xref: /titanic_41/usr/src/uts/common/fs/zfs/dsl_dir.c (revision 7801e5e8b5bc4af34929c54a02cfb78398da08dd)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/dmu.h>
27 #include <sys/dmu_objset.h>
28 #include <sys/dmu_tx.h>
29 #include <sys/dsl_dataset.h>
30 #include <sys/dsl_dir.h>
31 #include <sys/dsl_prop.h>
32 #include <sys/dsl_synctask.h>
33 #include <sys/dsl_deleg.h>
34 #include <sys/spa.h>
35 #include <sys/metaslab.h>
36 #include <sys/zap.h>
37 #include <sys/zio.h>
38 #include <sys/arc.h>
39 #include <sys/sunddi.h>
40 #include "zfs_namecheck.h"
41 
42 static uint64_t dsl_dir_space_towrite(dsl_dir_t *dd);
43 static void dsl_dir_set_reservation_sync(void *arg1, void *arg2,
44     cred_t *cr, dmu_tx_t *tx);
45 
46 
47 /* ARGSUSED */
48 static void
49 dsl_dir_evict(dmu_buf_t *db, void *arg)
50 {
51 	dsl_dir_t *dd = arg;
52 	dsl_pool_t *dp = dd->dd_pool;
53 	int t;
54 
55 	for (t = 0; t < TXG_SIZE; t++) {
56 		ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
57 		ASSERT(dd->dd_tempreserved[t] == 0);
58 		ASSERT(dd->dd_space_towrite[t] == 0);
59 	}
60 
61 	if (dd->dd_parent)
62 		dsl_dir_close(dd->dd_parent, dd);
63 
64 	spa_close(dd->dd_pool->dp_spa, dd);
65 
66 	/*
67 	 * The props callback list should be empty since they hold the
68 	 * dir open.
69 	 */
70 	list_destroy(&dd->dd_prop_cbs);
71 	mutex_destroy(&dd->dd_lock);
72 	kmem_free(dd, sizeof (dsl_dir_t));
73 }
74 
75 int
76 dsl_dir_open_obj(dsl_pool_t *dp, uint64_t ddobj,
77     const char *tail, void *tag, dsl_dir_t **ddp)
78 {
79 	dmu_buf_t *dbuf;
80 	dsl_dir_t *dd;
81 	int err;
82 
83 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
84 	    dsl_pool_sync_context(dp));
85 
86 	err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
87 	if (err)
88 		return (err);
89 	dd = dmu_buf_get_user(dbuf);
90 #ifdef ZFS_DEBUG
91 	{
92 		dmu_object_info_t doi;
93 		dmu_object_info_from_db(dbuf, &doi);
94 		ASSERT3U(doi.doi_type, ==, DMU_OT_DSL_DIR);
95 		ASSERT3U(doi.doi_bonus_size, >=, sizeof (dsl_dir_phys_t));
96 	}
97 #endif
98 	if (dd == NULL) {
99 		dsl_dir_t *winner;
100 
101 		dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
102 		dd->dd_object = ddobj;
103 		dd->dd_dbuf = dbuf;
104 		dd->dd_pool = dp;
105 		dd->dd_phys = dbuf->db_data;
106 		mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
107 
108 		list_create(&dd->dd_prop_cbs, sizeof (dsl_prop_cb_record_t),
109 		    offsetof(dsl_prop_cb_record_t, cbr_node));
110 
111 		dsl_dir_snap_cmtime_update(dd);
112 
113 		if (dd->dd_phys->dd_parent_obj) {
114 			err = dsl_dir_open_obj(dp, dd->dd_phys->dd_parent_obj,
115 			    NULL, dd, &dd->dd_parent);
116 			if (err)
117 				goto errout;
118 			if (tail) {
119 #ifdef ZFS_DEBUG
120 				uint64_t foundobj;
121 
122 				err = zap_lookup(dp->dp_meta_objset,
123 				    dd->dd_parent->dd_phys->dd_child_dir_zapobj,
124 				    tail, sizeof (foundobj), 1, &foundobj);
125 				ASSERT(err || foundobj == ddobj);
126 #endif
127 				(void) strcpy(dd->dd_myname, tail);
128 			} else {
129 				err = zap_value_search(dp->dp_meta_objset,
130 				    dd->dd_parent->dd_phys->dd_child_dir_zapobj,
131 				    ddobj, 0, dd->dd_myname);
132 			}
133 			if (err)
134 				goto errout;
135 		} else {
136 			(void) strcpy(dd->dd_myname, spa_name(dp->dp_spa));
137 		}
138 
139 		winner = dmu_buf_set_user_ie(dbuf, dd, &dd->dd_phys,
140 		    dsl_dir_evict);
141 		if (winner) {
142 			if (dd->dd_parent)
143 				dsl_dir_close(dd->dd_parent, dd);
144 			mutex_destroy(&dd->dd_lock);
145 			kmem_free(dd, sizeof (dsl_dir_t));
146 			dd = winner;
147 		} else {
148 			spa_open_ref(dp->dp_spa, dd);
149 		}
150 	}
151 
152 	/*
153 	 * The dsl_dir_t has both open-to-close and instantiate-to-evict
154 	 * holds on the spa.  We need the open-to-close holds because
155 	 * otherwise the spa_refcnt wouldn't change when we open a
156 	 * dir which the spa also has open, so we could incorrectly
157 	 * think it was OK to unload/export/destroy the pool.  We need
158 	 * the instantiate-to-evict hold because the dsl_dir_t has a
159 	 * pointer to the dd_pool, which has a pointer to the spa_t.
160 	 */
161 	spa_open_ref(dp->dp_spa, tag);
162 	ASSERT3P(dd->dd_pool, ==, dp);
163 	ASSERT3U(dd->dd_object, ==, ddobj);
164 	ASSERT3P(dd->dd_dbuf, ==, dbuf);
165 	*ddp = dd;
166 	return (0);
167 
168 errout:
169 	if (dd->dd_parent)
170 		dsl_dir_close(dd->dd_parent, dd);
171 	mutex_destroy(&dd->dd_lock);
172 	kmem_free(dd, sizeof (dsl_dir_t));
173 	dmu_buf_rele(dbuf, tag);
174 	return (err);
175 
176 }
177 
178 void
179 dsl_dir_close(dsl_dir_t *dd, void *tag)
180 {
181 	dprintf_dd(dd, "%s\n", "");
182 	spa_close(dd->dd_pool->dp_spa, tag);
183 	dmu_buf_rele(dd->dd_dbuf, tag);
184 }
185 
186 /* buf must be long enough (MAXNAMELEN + strlen(MOS_DIR_NAME) + 1 should do) */
187 void
188 dsl_dir_name(dsl_dir_t *dd, char *buf)
189 {
190 	if (dd->dd_parent) {
191 		dsl_dir_name(dd->dd_parent, buf);
192 		(void) strcat(buf, "/");
193 	} else {
194 		buf[0] = '\0';
195 	}
196 	if (!MUTEX_HELD(&dd->dd_lock)) {
197 		/*
198 		 * recursive mutex so that we can use
199 		 * dprintf_dd() with dd_lock held
200 		 */
201 		mutex_enter(&dd->dd_lock);
202 		(void) strcat(buf, dd->dd_myname);
203 		mutex_exit(&dd->dd_lock);
204 	} else {
205 		(void) strcat(buf, dd->dd_myname);
206 	}
207 }
208 
209 /* Calculate name legnth, avoiding all the strcat calls of dsl_dir_name */
210 int
211 dsl_dir_namelen(dsl_dir_t *dd)
212 {
213 	int result = 0;
214 
215 	if (dd->dd_parent) {
216 		/* parent's name + 1 for the "/" */
217 		result = dsl_dir_namelen(dd->dd_parent) + 1;
218 	}
219 
220 	if (!MUTEX_HELD(&dd->dd_lock)) {
221 		/* see dsl_dir_name */
222 		mutex_enter(&dd->dd_lock);
223 		result += strlen(dd->dd_myname);
224 		mutex_exit(&dd->dd_lock);
225 	} else {
226 		result += strlen(dd->dd_myname);
227 	}
228 
229 	return (result);
230 }
231 
232 static int
233 getcomponent(const char *path, char *component, const char **nextp)
234 {
235 	char *p;
236 	if ((path == NULL) || (path[0] == '\0'))
237 		return (ENOENT);
238 	/* This would be a good place to reserve some namespace... */
239 	p = strpbrk(path, "/@");
240 	if (p && (p[1] == '/' || p[1] == '@')) {
241 		/* two separators in a row */
242 		return (EINVAL);
243 	}
244 	if (p == NULL || p == path) {
245 		/*
246 		 * if the first thing is an @ or /, it had better be an
247 		 * @ and it had better not have any more ats or slashes,
248 		 * and it had better have something after the @.
249 		 */
250 		if (p != NULL &&
251 		    (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
252 			return (EINVAL);
253 		if (strlen(path) >= MAXNAMELEN)
254 			return (ENAMETOOLONG);
255 		(void) strcpy(component, path);
256 		p = NULL;
257 	} else if (p[0] == '/') {
258 		if (p-path >= MAXNAMELEN)
259 			return (ENAMETOOLONG);
260 		(void) strncpy(component, path, p - path);
261 		component[p-path] = '\0';
262 		p++;
263 	} else if (p[0] == '@') {
264 		/*
265 		 * if the next separator is an @, there better not be
266 		 * any more slashes.
267 		 */
268 		if (strchr(path, '/'))
269 			return (EINVAL);
270 		if (p-path >= MAXNAMELEN)
271 			return (ENAMETOOLONG);
272 		(void) strncpy(component, path, p - path);
273 		component[p-path] = '\0';
274 	} else {
275 		ASSERT(!"invalid p");
276 	}
277 	*nextp = p;
278 	return (0);
279 }
280 
281 /*
282  * same as dsl_open_dir, ignore the first component of name and use the
283  * spa instead
284  */
285 int
286 dsl_dir_open_spa(spa_t *spa, const char *name, void *tag,
287     dsl_dir_t **ddp, const char **tailp)
288 {
289 	char buf[MAXNAMELEN];
290 	const char *next, *nextnext = NULL;
291 	int err;
292 	dsl_dir_t *dd;
293 	dsl_pool_t *dp;
294 	uint64_t ddobj;
295 	int openedspa = FALSE;
296 
297 	dprintf("%s\n", name);
298 
299 	err = getcomponent(name, buf, &next);
300 	if (err)
301 		return (err);
302 	if (spa == NULL) {
303 		err = spa_open(buf, &spa, FTAG);
304 		if (err) {
305 			dprintf("spa_open(%s) failed\n", buf);
306 			return (err);
307 		}
308 		openedspa = TRUE;
309 
310 		/* XXX this assertion belongs in spa_open */
311 		ASSERT(!dsl_pool_sync_context(spa_get_dsl(spa)));
312 	}
313 
314 	dp = spa_get_dsl(spa);
315 
316 	rw_enter(&dp->dp_config_rwlock, RW_READER);
317 	err = dsl_dir_open_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
318 	if (err) {
319 		rw_exit(&dp->dp_config_rwlock);
320 		if (openedspa)
321 			spa_close(spa, FTAG);
322 		return (err);
323 	}
324 
325 	while (next != NULL) {
326 		dsl_dir_t *child_ds;
327 		err = getcomponent(next, buf, &nextnext);
328 		if (err)
329 			break;
330 		ASSERT(next[0] != '\0');
331 		if (next[0] == '@')
332 			break;
333 		dprintf("looking up %s in obj%lld\n",
334 		    buf, dd->dd_phys->dd_child_dir_zapobj);
335 
336 		err = zap_lookup(dp->dp_meta_objset,
337 		    dd->dd_phys->dd_child_dir_zapobj,
338 		    buf, sizeof (ddobj), 1, &ddobj);
339 		if (err) {
340 			if (err == ENOENT)
341 				err = 0;
342 			break;
343 		}
344 
345 		err = dsl_dir_open_obj(dp, ddobj, buf, tag, &child_ds);
346 		if (err)
347 			break;
348 		dsl_dir_close(dd, tag);
349 		dd = child_ds;
350 		next = nextnext;
351 	}
352 	rw_exit(&dp->dp_config_rwlock);
353 
354 	if (err) {
355 		dsl_dir_close(dd, tag);
356 		if (openedspa)
357 			spa_close(spa, FTAG);
358 		return (err);
359 	}
360 
361 	/*
362 	 * It's an error if there's more than one component left, or
363 	 * tailp==NULL and there's any component left.
364 	 */
365 	if (next != NULL &&
366 	    (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
367 		/* bad path name */
368 		dsl_dir_close(dd, tag);
369 		dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
370 		err = ENOENT;
371 	}
372 	if (tailp)
373 		*tailp = next;
374 	if (openedspa)
375 		spa_close(spa, FTAG);
376 	*ddp = dd;
377 	return (err);
378 }
379 
380 /*
381  * Return the dsl_dir_t, and possibly the last component which couldn't
382  * be found in *tail.  Return NULL if the path is bogus, or if
383  * tail==NULL and we couldn't parse the whole name.  (*tail)[0] == '@'
384  * means that the last component is a snapshot.
385  */
386 int
387 dsl_dir_open(const char *name, void *tag, dsl_dir_t **ddp, const char **tailp)
388 {
389 	return (dsl_dir_open_spa(NULL, name, tag, ddp, tailp));
390 }
391 
392 uint64_t
393 dsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
394     dmu_tx_t *tx)
395 {
396 	objset_t *mos = dp->dp_meta_objset;
397 	uint64_t ddobj;
398 	dsl_dir_phys_t *dsphys;
399 	dmu_buf_t *dbuf;
400 
401 	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
402 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
403 	if (pds) {
404 		VERIFY(0 == zap_add(mos, pds->dd_phys->dd_child_dir_zapobj,
405 		    name, sizeof (uint64_t), 1, &ddobj, tx));
406 	} else {
407 		/* it's the root dir */
408 		VERIFY(0 == zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
409 		    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
410 	}
411 	VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
412 	dmu_buf_will_dirty(dbuf, tx);
413 	dsphys = dbuf->db_data;
414 
415 	dsphys->dd_creation_time = gethrestime_sec();
416 	if (pds)
417 		dsphys->dd_parent_obj = pds->dd_object;
418 	dsphys->dd_props_zapobj = zap_create(mos,
419 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
420 	dsphys->dd_child_dir_zapobj = zap_create(mos,
421 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
422 	if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
423 		dsphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
424 	dmu_buf_rele(dbuf, FTAG);
425 
426 	return (ddobj);
427 }
428 
429 /* ARGSUSED */
430 int
431 dsl_dir_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
432 {
433 	dsl_dataset_t *ds = arg1;
434 	dsl_dir_t *dd = ds->ds_dir;
435 	dsl_pool_t *dp = dd->dd_pool;
436 	objset_t *mos = dp->dp_meta_objset;
437 	int err;
438 	uint64_t count;
439 
440 	/*
441 	 * There should be exactly two holds, both from
442 	 * dsl_dataset_destroy: one on the dd directory, and one on its
443 	 * head ds.  Otherwise, someone is trying to lookup something
444 	 * inside this dir while we want to destroy it.  The
445 	 * config_rwlock ensures that nobody else opens it after we
446 	 * check.
447 	 */
448 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
449 		return (EBUSY);
450 
451 	err = zap_count(mos, dd->dd_phys->dd_child_dir_zapobj, &count);
452 	if (err)
453 		return (err);
454 	if (count != 0)
455 		return (EEXIST);
456 
457 	return (0);
458 }
459 
460 void
461 dsl_dir_destroy_sync(void *arg1, void *tag, cred_t *cr, dmu_tx_t *tx)
462 {
463 	dsl_dataset_t *ds = arg1;
464 	dsl_dir_t *dd = ds->ds_dir;
465 	objset_t *mos = dd->dd_pool->dp_meta_objset;
466 	dsl_prop_setarg_t psa;
467 	uint64_t value = 0;
468 	uint64_t obj;
469 	dd_used_t t;
470 
471 	ASSERT(RW_WRITE_HELD(&dd->dd_pool->dp_config_rwlock));
472 	ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
473 
474 	/* Remove our reservation. */
475 	dsl_prop_setarg_init_uint64(&psa, "reservation",
476 	    (ZPROP_SRC_NONE | ZPROP_SRC_LOCAL | ZPROP_SRC_RECEIVED),
477 	    &value);
478 	psa.psa_effective_value = 0;	/* predict default value */
479 
480 	dsl_dir_set_reservation_sync(ds, &psa, cr, tx);
481 
482 	ASSERT3U(dd->dd_phys->dd_used_bytes, ==, 0);
483 	ASSERT3U(dd->dd_phys->dd_reserved, ==, 0);
484 	for (t = 0; t < DD_USED_NUM; t++)
485 		ASSERT3U(dd->dd_phys->dd_used_breakdown[t], ==, 0);
486 
487 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_child_dir_zapobj, tx));
488 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_props_zapobj, tx));
489 	VERIFY(0 == dsl_deleg_destroy(mos, dd->dd_phys->dd_deleg_zapobj, tx));
490 	VERIFY(0 == zap_remove(mos,
491 	    dd->dd_parent->dd_phys->dd_child_dir_zapobj, dd->dd_myname, tx));
492 
493 	obj = dd->dd_object;
494 	dsl_dir_close(dd, tag);
495 	VERIFY(0 == dmu_object_free(mos, obj, tx));
496 }
497 
498 boolean_t
499 dsl_dir_is_clone(dsl_dir_t *dd)
500 {
501 	return (dd->dd_phys->dd_origin_obj &&
502 	    (dd->dd_pool->dp_origin_snap == NULL ||
503 	    dd->dd_phys->dd_origin_obj !=
504 	    dd->dd_pool->dp_origin_snap->ds_object));
505 }
506 
507 void
508 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
509 {
510 	mutex_enter(&dd->dd_lock);
511 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
512 	    dd->dd_phys->dd_used_bytes);
513 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA, dd->dd_phys->dd_quota);
514 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
515 	    dd->dd_phys->dd_reserved);
516 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
517 	    dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
518 	    (dd->dd_phys->dd_uncompressed_bytes * 100 /
519 	    dd->dd_phys->dd_compressed_bytes));
520 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
521 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
522 		    dd->dd_phys->dd_used_breakdown[DD_USED_SNAP]);
523 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
524 		    dd->dd_phys->dd_used_breakdown[DD_USED_HEAD]);
525 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
526 		    dd->dd_phys->dd_used_breakdown[DD_USED_REFRSRV]);
527 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
528 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD] +
529 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD_RSRV]);
530 	}
531 	mutex_exit(&dd->dd_lock);
532 
533 	rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
534 	if (dsl_dir_is_clone(dd)) {
535 		dsl_dataset_t *ds;
536 		char buf[MAXNAMELEN];
537 
538 		VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
539 		    dd->dd_phys->dd_origin_obj, FTAG, &ds));
540 		dsl_dataset_name(ds, buf);
541 		dsl_dataset_rele(ds, FTAG);
542 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
543 	}
544 	rw_exit(&dd->dd_pool->dp_config_rwlock);
545 }
546 
547 void
548 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
549 {
550 	dsl_pool_t *dp = dd->dd_pool;
551 
552 	ASSERT(dd->dd_phys);
553 
554 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg) == 0) {
555 		/* up the hold count until we can be written out */
556 		dmu_buf_add_ref(dd->dd_dbuf, dd);
557 	}
558 }
559 
560 static int64_t
561 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
562 {
563 	uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
564 	uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
565 	return (new_accounted - old_accounted);
566 }
567 
568 void
569 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
570 {
571 	ASSERT(dmu_tx_is_syncing(tx));
572 
573 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
574 
575 	mutex_enter(&dd->dd_lock);
576 	ASSERT3U(dd->dd_tempreserved[tx->tx_txg&TXG_MASK], ==, 0);
577 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
578 	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
579 	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
580 	mutex_exit(&dd->dd_lock);
581 
582 	/* release the hold from dsl_dir_dirty */
583 	dmu_buf_rele(dd->dd_dbuf, dd);
584 }
585 
586 static uint64_t
587 dsl_dir_space_towrite(dsl_dir_t *dd)
588 {
589 	uint64_t space = 0;
590 	int i;
591 
592 	ASSERT(MUTEX_HELD(&dd->dd_lock));
593 
594 	for (i = 0; i < TXG_SIZE; i++) {
595 		space += dd->dd_space_towrite[i&TXG_MASK];
596 		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
597 	}
598 	return (space);
599 }
600 
601 /*
602  * How much space would dd have available if ancestor had delta applied
603  * to it?  If ondiskonly is set, we're only interested in what's
604  * on-disk, not estimated pending changes.
605  */
606 uint64_t
607 dsl_dir_space_available(dsl_dir_t *dd,
608     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
609 {
610 	uint64_t parentspace, myspace, quota, used;
611 
612 	/*
613 	 * If there are no restrictions otherwise, assume we have
614 	 * unlimited space available.
615 	 */
616 	quota = UINT64_MAX;
617 	parentspace = UINT64_MAX;
618 
619 	if (dd->dd_parent != NULL) {
620 		parentspace = dsl_dir_space_available(dd->dd_parent,
621 		    ancestor, delta, ondiskonly);
622 	}
623 
624 	mutex_enter(&dd->dd_lock);
625 	if (dd->dd_phys->dd_quota != 0)
626 		quota = dd->dd_phys->dd_quota;
627 	used = dd->dd_phys->dd_used_bytes;
628 	if (!ondiskonly)
629 		used += dsl_dir_space_towrite(dd);
630 
631 	if (dd->dd_parent == NULL) {
632 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
633 		quota = MIN(quota, poolsize);
634 	}
635 
636 	if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
637 		/*
638 		 * We have some space reserved, in addition to what our
639 		 * parent gave us.
640 		 */
641 		parentspace += dd->dd_phys->dd_reserved - used;
642 	}
643 
644 	if (dd == ancestor) {
645 		ASSERT(delta <= 0);
646 		ASSERT(used >= -delta);
647 		used += delta;
648 		if (parentspace != UINT64_MAX)
649 			parentspace -= delta;
650 	}
651 
652 	if (used > quota) {
653 		/* over quota */
654 		myspace = 0;
655 
656 		/*
657 		 * While it's OK to be a little over quota, if
658 		 * we think we are using more space than there
659 		 * is in the pool (which is already 1.6% more than
660 		 * dsl_pool_adjustedsize()), something is very
661 		 * wrong.
662 		 */
663 		ASSERT3U(used, <=, spa_get_dspace(dd->dd_pool->dp_spa));
664 	} else {
665 		/*
666 		 * the lesser of the space provided by our parent and
667 		 * the space left in our quota
668 		 */
669 		myspace = MIN(parentspace, quota - used);
670 	}
671 
672 	mutex_exit(&dd->dd_lock);
673 
674 	return (myspace);
675 }
676 
677 struct tempreserve {
678 	list_node_t tr_node;
679 	dsl_pool_t *tr_dp;
680 	dsl_dir_t *tr_ds;
681 	uint64_t tr_size;
682 };
683 
684 static int
685 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
686     boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
687     dmu_tx_t *tx, boolean_t first)
688 {
689 	uint64_t txg = tx->tx_txg;
690 	uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
691 	uint64_t deferred = 0;
692 	struct tempreserve *tr;
693 	int retval = EDQUOT;
694 	int txgidx = txg & TXG_MASK;
695 	int i;
696 	uint64_t ref_rsrv = 0;
697 
698 	ASSERT3U(txg, !=, 0);
699 	ASSERT3S(asize, >, 0);
700 
701 	mutex_enter(&dd->dd_lock);
702 
703 	/*
704 	 * Check against the dsl_dir's quota.  We don't add in the delta
705 	 * when checking for over-quota because they get one free hit.
706 	 */
707 	est_inflight = dsl_dir_space_towrite(dd);
708 	for (i = 0; i < TXG_SIZE; i++)
709 		est_inflight += dd->dd_tempreserved[i];
710 	used_on_disk = dd->dd_phys->dd_used_bytes;
711 
712 	/*
713 	 * On the first iteration, fetch the dataset's used-on-disk and
714 	 * refreservation values. Also, if checkrefquota is set, test if
715 	 * allocating this space would exceed the dataset's refquota.
716 	 */
717 	if (first && tx->tx_objset) {
718 		int error;
719 		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
720 
721 		error = dsl_dataset_check_quota(ds, checkrefquota,
722 		    asize, est_inflight, &used_on_disk, &ref_rsrv);
723 		if (error) {
724 			mutex_exit(&dd->dd_lock);
725 			return (error);
726 		}
727 	}
728 
729 	/*
730 	 * If this transaction will result in a net free of space,
731 	 * we want to let it through.
732 	 */
733 	if (ignorequota || netfree || dd->dd_phys->dd_quota == 0)
734 		quota = UINT64_MAX;
735 	else
736 		quota = dd->dd_phys->dd_quota;
737 
738 	/*
739 	 * Adjust the quota against the actual pool size at the root
740 	 * minus any outstanding deferred frees.
741 	 * To ensure that it's possible to remove files from a full
742 	 * pool without inducing transient overcommits, we throttle
743 	 * netfree transactions against a quota that is slightly larger,
744 	 * but still within the pool's allocation slop.  In cases where
745 	 * we're very close to full, this will allow a steady trickle of
746 	 * removes to get through.
747 	 */
748 	if (dd->dd_parent == NULL) {
749 		spa_t *spa = dd->dd_pool->dp_spa;
750 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
751 		deferred = metaslab_class_get_deferred(spa_normal_class(spa));
752 		if (poolsize - deferred < quota) {
753 			quota = poolsize - deferred;
754 			retval = ENOSPC;
755 		}
756 	}
757 
758 	/*
759 	 * If they are requesting more space, and our current estimate
760 	 * is over quota, they get to try again unless the actual
761 	 * on-disk is over quota and there are no pending changes (which
762 	 * may free up space for us).
763 	 */
764 	if (used_on_disk + est_inflight >= quota) {
765 		if (est_inflight > 0 || used_on_disk < quota ||
766 		    (retval == ENOSPC && used_on_disk < quota + deferred))
767 			retval = ERESTART;
768 		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
769 		    "quota=%lluK tr=%lluK err=%d\n",
770 		    used_on_disk>>10, est_inflight>>10,
771 		    quota>>10, asize>>10, retval);
772 		mutex_exit(&dd->dd_lock);
773 		return (retval);
774 	}
775 
776 	/* We need to up our estimated delta before dropping dd_lock */
777 	dd->dd_tempreserved[txgidx] += asize;
778 
779 	parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
780 	    asize - ref_rsrv);
781 	mutex_exit(&dd->dd_lock);
782 
783 	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
784 	tr->tr_ds = dd;
785 	tr->tr_size = asize;
786 	list_insert_tail(tr_list, tr);
787 
788 	/* see if it's OK with our parent */
789 	if (dd->dd_parent && parent_rsrv) {
790 		boolean_t ismos = (dd->dd_phys->dd_head_dataset_obj == 0);
791 
792 		return (dsl_dir_tempreserve_impl(dd->dd_parent,
793 		    parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
794 	} else {
795 		return (0);
796 	}
797 }
798 
799 /*
800  * Reserve space in this dsl_dir, to be used in this tx's txg.
801  * After the space has been dirtied (and dsl_dir_willuse_space()
802  * has been called), the reservation should be canceled, using
803  * dsl_dir_tempreserve_clear().
804  */
805 int
806 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
807     uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
808 {
809 	int err;
810 	list_t *tr_list;
811 
812 	if (asize == 0) {
813 		*tr_cookiep = NULL;
814 		return (0);
815 	}
816 
817 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
818 	list_create(tr_list, sizeof (struct tempreserve),
819 	    offsetof(struct tempreserve, tr_node));
820 	ASSERT3S(asize, >, 0);
821 	ASSERT3S(fsize, >=, 0);
822 
823 	err = arc_tempreserve_space(lsize, tx->tx_txg);
824 	if (err == 0) {
825 		struct tempreserve *tr;
826 
827 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
828 		tr->tr_size = lsize;
829 		list_insert_tail(tr_list, tr);
830 
831 		err = dsl_pool_tempreserve_space(dd->dd_pool, asize, tx);
832 	} else {
833 		if (err == EAGAIN) {
834 			txg_delay(dd->dd_pool, tx->tx_txg, 1);
835 			err = ERESTART;
836 		}
837 		dsl_pool_memory_pressure(dd->dd_pool);
838 	}
839 
840 	if (err == 0) {
841 		struct tempreserve *tr;
842 
843 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
844 		tr->tr_dp = dd->dd_pool;
845 		tr->tr_size = asize;
846 		list_insert_tail(tr_list, tr);
847 
848 		err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
849 		    FALSE, asize > usize, tr_list, tx, TRUE);
850 	}
851 
852 	if (err)
853 		dsl_dir_tempreserve_clear(tr_list, tx);
854 	else
855 		*tr_cookiep = tr_list;
856 
857 	return (err);
858 }
859 
860 /*
861  * Clear a temporary reservation that we previously made with
862  * dsl_dir_tempreserve_space().
863  */
864 void
865 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
866 {
867 	int txgidx = tx->tx_txg & TXG_MASK;
868 	list_t *tr_list = tr_cookie;
869 	struct tempreserve *tr;
870 
871 	ASSERT3U(tx->tx_txg, !=, 0);
872 
873 	if (tr_cookie == NULL)
874 		return;
875 
876 	while (tr = list_head(tr_list)) {
877 		if (tr->tr_dp) {
878 			dsl_pool_tempreserve_clear(tr->tr_dp, tr->tr_size, tx);
879 		} else if (tr->tr_ds) {
880 			mutex_enter(&tr->tr_ds->dd_lock);
881 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
882 			    tr->tr_size);
883 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
884 			mutex_exit(&tr->tr_ds->dd_lock);
885 		} else {
886 			arc_tempreserve_clear(tr->tr_size);
887 		}
888 		list_remove(tr_list, tr);
889 		kmem_free(tr, sizeof (struct tempreserve));
890 	}
891 
892 	kmem_free(tr_list, sizeof (list_t));
893 }
894 
895 static void
896 dsl_dir_willuse_space_impl(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
897 {
898 	int64_t parent_space;
899 	uint64_t est_used;
900 
901 	mutex_enter(&dd->dd_lock);
902 	if (space > 0)
903 		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
904 
905 	est_used = dsl_dir_space_towrite(dd) + dd->dd_phys->dd_used_bytes;
906 	parent_space = parent_delta(dd, est_used, space);
907 	mutex_exit(&dd->dd_lock);
908 
909 	/* Make sure that we clean up dd_space_to* */
910 	dsl_dir_dirty(dd, tx);
911 
912 	/* XXX this is potentially expensive and unnecessary... */
913 	if (parent_space && dd->dd_parent)
914 		dsl_dir_willuse_space_impl(dd->dd_parent, parent_space, tx);
915 }
916 
917 /*
918  * Call in open context when we think we're going to write/free space,
919  * eg. when dirtying data.  Be conservative (ie. OK to write less than
920  * this or free more than this, but don't write more or free less).
921  */
922 void
923 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
924 {
925 	dsl_pool_willuse_space(dd->dd_pool, space, tx);
926 	dsl_dir_willuse_space_impl(dd, space, tx);
927 }
928 
929 /* call from syncing context when we actually write/free space for this dd */
930 void
931 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
932     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
933 {
934 	int64_t accounted_delta;
935 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
936 
937 	ASSERT(dmu_tx_is_syncing(tx));
938 	ASSERT(type < DD_USED_NUM);
939 
940 	dsl_dir_dirty(dd, tx);
941 
942 	if (needlock)
943 		mutex_enter(&dd->dd_lock);
944 	accounted_delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, used);
945 	ASSERT(used >= 0 || dd->dd_phys->dd_used_bytes >= -used);
946 	ASSERT(compressed >= 0 ||
947 	    dd->dd_phys->dd_compressed_bytes >= -compressed);
948 	ASSERT(uncompressed >= 0 ||
949 	    dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
950 	dd->dd_phys->dd_used_bytes += used;
951 	dd->dd_phys->dd_uncompressed_bytes += uncompressed;
952 	dd->dd_phys->dd_compressed_bytes += compressed;
953 
954 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
955 		ASSERT(used > 0 ||
956 		    dd->dd_phys->dd_used_breakdown[type] >= -used);
957 		dd->dd_phys->dd_used_breakdown[type] += used;
958 #ifdef DEBUG
959 		dd_used_t t;
960 		uint64_t u = 0;
961 		for (t = 0; t < DD_USED_NUM; t++)
962 			u += dd->dd_phys->dd_used_breakdown[t];
963 		ASSERT3U(u, ==, dd->dd_phys->dd_used_bytes);
964 #endif
965 	}
966 	if (needlock)
967 		mutex_exit(&dd->dd_lock);
968 
969 	if (dd->dd_parent != NULL) {
970 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
971 		    accounted_delta, compressed, uncompressed, tx);
972 		dsl_dir_transfer_space(dd->dd_parent,
973 		    used - accounted_delta,
974 		    DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
975 	}
976 }
977 
978 void
979 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
980     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
981 {
982 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
983 
984 	ASSERT(dmu_tx_is_syncing(tx));
985 	ASSERT(oldtype < DD_USED_NUM);
986 	ASSERT(newtype < DD_USED_NUM);
987 
988 	if (delta == 0 || !(dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN))
989 		return;
990 
991 	dsl_dir_dirty(dd, tx);
992 	if (needlock)
993 		mutex_enter(&dd->dd_lock);
994 	ASSERT(delta > 0 ?
995 	    dd->dd_phys->dd_used_breakdown[oldtype] >= delta :
996 	    dd->dd_phys->dd_used_breakdown[newtype] >= -delta);
997 	ASSERT(dd->dd_phys->dd_used_bytes >= ABS(delta));
998 	dd->dd_phys->dd_used_breakdown[oldtype] -= delta;
999 	dd->dd_phys->dd_used_breakdown[newtype] += delta;
1000 	if (needlock)
1001 		mutex_exit(&dd->dd_lock);
1002 }
1003 
1004 static int
1005 dsl_dir_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
1006 {
1007 	dsl_dataset_t *ds = arg1;
1008 	dsl_dir_t *dd = ds->ds_dir;
1009 	dsl_prop_setarg_t *psa = arg2;
1010 	int err;
1011 	uint64_t towrite;
1012 
1013 	if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
1014 		return (err);
1015 
1016 	if (psa->psa_effective_value == 0)
1017 		return (0);
1018 
1019 	mutex_enter(&dd->dd_lock);
1020 	/*
1021 	 * If we are doing the preliminary check in open context, and
1022 	 * there are pending changes, then don't fail it, since the
1023 	 * pending changes could under-estimate the amount of space to be
1024 	 * freed up.
1025 	 */
1026 	towrite = dsl_dir_space_towrite(dd);
1027 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1028 	    (psa->psa_effective_value < dd->dd_phys->dd_reserved ||
1029 	    psa->psa_effective_value < dd->dd_phys->dd_used_bytes + towrite)) {
1030 		err = ENOSPC;
1031 	}
1032 	mutex_exit(&dd->dd_lock);
1033 	return (err);
1034 }
1035 
1036 extern void dsl_prop_set_sync(void *, void *, cred_t *, dmu_tx_t *);
1037 
1038 /* ARGSUSED */
1039 static void
1040 dsl_dir_set_quota_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1041 {
1042 	dsl_dataset_t *ds = arg1;
1043 	dsl_dir_t *dd = ds->ds_dir;
1044 	dsl_prop_setarg_t *psa = arg2;
1045 	uint64_t effective_value = psa->psa_effective_value;
1046 
1047 	dsl_prop_set_sync(ds, psa, cr, tx);
1048 	DSL_PROP_CHECK_PREDICTION(dd, psa);
1049 
1050 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1051 
1052 	mutex_enter(&dd->dd_lock);
1053 	dd->dd_phys->dd_quota = effective_value;
1054 	mutex_exit(&dd->dd_lock);
1055 
1056 	spa_history_internal_log(LOG_DS_QUOTA, dd->dd_pool->dp_spa,
1057 	    tx, cr, "%lld dataset = %llu ",
1058 	    (longlong_t)effective_value, dd->dd_phys->dd_head_dataset_obj);
1059 }
1060 
1061 int
1062 dsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1063 {
1064 	dsl_dir_t *dd;
1065 	dsl_dataset_t *ds;
1066 	dsl_prop_setarg_t psa;
1067 	int err;
1068 
1069 	dsl_prop_setarg_init_uint64(&psa, "quota", source, &quota);
1070 
1071 	err = dsl_dataset_hold(ddname, FTAG, &ds);
1072 	if (err)
1073 		return (err);
1074 
1075 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1076 	if (err) {
1077 		dsl_dataset_rele(ds, FTAG);
1078 		return (err);
1079 	}
1080 
1081 	ASSERT(ds->ds_dir == dd);
1082 
1083 	/*
1084 	 * If someone removes a file, then tries to set the quota, we want to
1085 	 * make sure the file freeing takes effect.
1086 	 */
1087 	txg_wait_open(dd->dd_pool, 0);
1088 
1089 	err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_quota_check,
1090 	    dsl_dir_set_quota_sync, ds, &psa, 0);
1091 
1092 	dsl_dir_close(dd, FTAG);
1093 	dsl_dataset_rele(ds, FTAG);
1094 	return (err);
1095 }
1096 
1097 int
1098 dsl_dir_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
1099 {
1100 	dsl_dataset_t *ds = arg1;
1101 	dsl_dir_t *dd = ds->ds_dir;
1102 	dsl_prop_setarg_t *psa = arg2;
1103 	uint64_t effective_value;
1104 	uint64_t used, avail;
1105 	int err;
1106 
1107 	if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
1108 		return (err);
1109 
1110 	effective_value = psa->psa_effective_value;
1111 
1112 	/*
1113 	 * If we are doing the preliminary check in open context, the
1114 	 * space estimates may be inaccurate.
1115 	 */
1116 	if (!dmu_tx_is_syncing(tx))
1117 		return (0);
1118 
1119 	mutex_enter(&dd->dd_lock);
1120 	used = dd->dd_phys->dd_used_bytes;
1121 	mutex_exit(&dd->dd_lock);
1122 
1123 	if (dd->dd_parent) {
1124 		avail = dsl_dir_space_available(dd->dd_parent,
1125 		    NULL, 0, FALSE);
1126 	} else {
1127 		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1128 	}
1129 
1130 	if (MAX(used, effective_value) > MAX(used, dd->dd_phys->dd_reserved)) {
1131 		uint64_t delta = MAX(used, effective_value) -
1132 		    MAX(used, dd->dd_phys->dd_reserved);
1133 
1134 		if (delta > avail)
1135 			return (ENOSPC);
1136 		if (dd->dd_phys->dd_quota > 0 &&
1137 		    effective_value > dd->dd_phys->dd_quota)
1138 			return (ENOSPC);
1139 	}
1140 
1141 	return (0);
1142 }
1143 
1144 /* ARGSUSED */
1145 static void
1146 dsl_dir_set_reservation_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1147 {
1148 	dsl_dataset_t *ds = arg1;
1149 	dsl_dir_t *dd = ds->ds_dir;
1150 	dsl_prop_setarg_t *psa = arg2;
1151 	uint64_t effective_value = psa->psa_effective_value;
1152 	uint64_t used;
1153 	int64_t delta;
1154 
1155 	dsl_prop_set_sync(ds, psa, cr, tx);
1156 	DSL_PROP_CHECK_PREDICTION(dd, psa);
1157 
1158 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1159 
1160 	mutex_enter(&dd->dd_lock);
1161 	used = dd->dd_phys->dd_used_bytes;
1162 	delta = MAX(used, effective_value) -
1163 	    MAX(used, dd->dd_phys->dd_reserved);
1164 	dd->dd_phys->dd_reserved = effective_value;
1165 
1166 	if (dd->dd_parent != NULL) {
1167 		/* Roll up this additional usage into our ancestors */
1168 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1169 		    delta, 0, 0, tx);
1170 	}
1171 	mutex_exit(&dd->dd_lock);
1172 
1173 	spa_history_internal_log(LOG_DS_RESERVATION, dd->dd_pool->dp_spa,
1174 	    tx, cr, "%lld dataset = %llu",
1175 	    (longlong_t)effective_value, dd->dd_phys->dd_head_dataset_obj);
1176 }
1177 
1178 int
1179 dsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1180     uint64_t reservation)
1181 {
1182 	dsl_dir_t *dd;
1183 	dsl_dataset_t *ds;
1184 	dsl_prop_setarg_t psa;
1185 	int err;
1186 
1187 	dsl_prop_setarg_init_uint64(&psa, "reservation", source, &reservation);
1188 
1189 	err = dsl_dataset_hold(ddname, FTAG, &ds);
1190 	if (err)
1191 		return (err);
1192 
1193 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1194 	if (err) {
1195 		dsl_dataset_rele(ds, FTAG);
1196 		return (err);
1197 	}
1198 
1199 	ASSERT(ds->ds_dir == dd);
1200 
1201 	err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_reservation_check,
1202 	    dsl_dir_set_reservation_sync, ds, &psa, 0);
1203 
1204 	dsl_dir_close(dd, FTAG);
1205 	dsl_dataset_rele(ds, FTAG);
1206 	return (err);
1207 }
1208 
1209 static dsl_dir_t *
1210 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1211 {
1212 	for (; ds1; ds1 = ds1->dd_parent) {
1213 		dsl_dir_t *dd;
1214 		for (dd = ds2; dd; dd = dd->dd_parent) {
1215 			if (ds1 == dd)
1216 				return (dd);
1217 		}
1218 	}
1219 	return (NULL);
1220 }
1221 
1222 /*
1223  * If delta is applied to dd, how much of that delta would be applied to
1224  * ancestor?  Syncing context only.
1225  */
1226 static int64_t
1227 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1228 {
1229 	if (dd == ancestor)
1230 		return (delta);
1231 
1232 	mutex_enter(&dd->dd_lock);
1233 	delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, delta);
1234 	mutex_exit(&dd->dd_lock);
1235 	return (would_change(dd->dd_parent, delta, ancestor));
1236 }
1237 
1238 struct renamearg {
1239 	dsl_dir_t *newparent;
1240 	const char *mynewname;
1241 };
1242 
1243 /*ARGSUSED*/
1244 static int
1245 dsl_dir_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
1246 {
1247 	dsl_dir_t *dd = arg1;
1248 	struct renamearg *ra = arg2;
1249 	dsl_pool_t *dp = dd->dd_pool;
1250 	objset_t *mos = dp->dp_meta_objset;
1251 	int err;
1252 	uint64_t val;
1253 
1254 	/* There should be 2 references: the open and the dirty */
1255 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
1256 		return (EBUSY);
1257 
1258 	/* check for existing name */
1259 	err = zap_lookup(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1260 	    ra->mynewname, 8, 1, &val);
1261 	if (err == 0)
1262 		return (EEXIST);
1263 	if (err != ENOENT)
1264 		return (err);
1265 
1266 	if (ra->newparent != dd->dd_parent) {
1267 		/* is there enough space? */
1268 		uint64_t myspace =
1269 		    MAX(dd->dd_phys->dd_used_bytes, dd->dd_phys->dd_reserved);
1270 
1271 		/* no rename into our descendant */
1272 		if (closest_common_ancestor(dd, ra->newparent) == dd)
1273 			return (EINVAL);
1274 
1275 		if (err = dsl_dir_transfer_possible(dd->dd_parent,
1276 		    ra->newparent, myspace))
1277 			return (err);
1278 	}
1279 
1280 	return (0);
1281 }
1282 
1283 static void
1284 dsl_dir_rename_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1285 {
1286 	dsl_dir_t *dd = arg1;
1287 	struct renamearg *ra = arg2;
1288 	dsl_pool_t *dp = dd->dd_pool;
1289 	objset_t *mos = dp->dp_meta_objset;
1290 	int err;
1291 
1292 	ASSERT(dmu_buf_refcount(dd->dd_dbuf) <= 2);
1293 
1294 	if (ra->newparent != dd->dd_parent) {
1295 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1296 		    -dd->dd_phys->dd_used_bytes,
1297 		    -dd->dd_phys->dd_compressed_bytes,
1298 		    -dd->dd_phys->dd_uncompressed_bytes, tx);
1299 		dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD,
1300 		    dd->dd_phys->dd_used_bytes,
1301 		    dd->dd_phys->dd_compressed_bytes,
1302 		    dd->dd_phys->dd_uncompressed_bytes, tx);
1303 
1304 		if (dd->dd_phys->dd_reserved > dd->dd_phys->dd_used_bytes) {
1305 			uint64_t unused_rsrv = dd->dd_phys->dd_reserved -
1306 			    dd->dd_phys->dd_used_bytes;
1307 
1308 			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1309 			    -unused_rsrv, 0, 0, tx);
1310 			dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD_RSRV,
1311 			    unused_rsrv, 0, 0, tx);
1312 		}
1313 	}
1314 
1315 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1316 
1317 	/* remove from old parent zapobj */
1318 	err = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1319 	    dd->dd_myname, tx);
1320 	ASSERT3U(err, ==, 0);
1321 
1322 	(void) strcpy(dd->dd_myname, ra->mynewname);
1323 	dsl_dir_close(dd->dd_parent, dd);
1324 	dd->dd_phys->dd_parent_obj = ra->newparent->dd_object;
1325 	VERIFY(0 == dsl_dir_open_obj(dd->dd_pool,
1326 	    ra->newparent->dd_object, NULL, dd, &dd->dd_parent));
1327 
1328 	/* add to new parent zapobj */
1329 	err = zap_add(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1330 	    dd->dd_myname, 8, 1, &dd->dd_object, tx);
1331 	ASSERT3U(err, ==, 0);
1332 
1333 	spa_history_internal_log(LOG_DS_RENAME, dd->dd_pool->dp_spa,
1334 	    tx, cr, "dataset = %llu", dd->dd_phys->dd_head_dataset_obj);
1335 }
1336 
1337 int
1338 dsl_dir_rename(dsl_dir_t *dd, const char *newname)
1339 {
1340 	struct renamearg ra;
1341 	int err;
1342 
1343 	/* new parent should exist */
1344 	err = dsl_dir_open(newname, FTAG, &ra.newparent, &ra.mynewname);
1345 	if (err)
1346 		return (err);
1347 
1348 	/* can't rename to different pool */
1349 	if (dd->dd_pool != ra.newparent->dd_pool) {
1350 		err = ENXIO;
1351 		goto out;
1352 	}
1353 
1354 	/* new name should not already exist */
1355 	if (ra.mynewname == NULL) {
1356 		err = EEXIST;
1357 		goto out;
1358 	}
1359 
1360 	err = dsl_sync_task_do(dd->dd_pool,
1361 	    dsl_dir_rename_check, dsl_dir_rename_sync, dd, &ra, 3);
1362 
1363 out:
1364 	dsl_dir_close(ra.newparent, FTAG);
1365 	return (err);
1366 }
1367 
1368 int
1369 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd, uint64_t space)
1370 {
1371 	dsl_dir_t *ancestor;
1372 	int64_t adelta;
1373 	uint64_t avail;
1374 
1375 	ancestor = closest_common_ancestor(sdd, tdd);
1376 	adelta = would_change(sdd, -space, ancestor);
1377 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1378 	if (avail < space)
1379 		return (ENOSPC);
1380 
1381 	return (0);
1382 }
1383 
1384 timestruc_t
1385 dsl_dir_snap_cmtime(dsl_dir_t *dd)
1386 {
1387 	timestruc_t t;
1388 
1389 	mutex_enter(&dd->dd_lock);
1390 	t = dd->dd_snap_cmtime;
1391 	mutex_exit(&dd->dd_lock);
1392 
1393 	return (t);
1394 }
1395 
1396 void
1397 dsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1398 {
1399 	timestruc_t t;
1400 
1401 	gethrestime(&t);
1402 	mutex_enter(&dd->dd_lock);
1403 	dd->dd_snap_cmtime = t;
1404 	mutex_exit(&dd->dd_lock);
1405 }
1406