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