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