xref: /titanic_50/usr/src/uts/common/fs/zfs/dsl_dir.c (revision 540db9a98e48e044a5fb290242f3ebb8cc3afc36)
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_dir_t *dd = arg1;
434 	dsl_pool_t *dp = dd->dd_pool;
435 	objset_t *mos = dp->dp_meta_objset;
436 	int err;
437 	uint64_t count;
438 
439 	/*
440 	 * There should be exactly two holds, both from
441 	 * dsl_dataset_destroy: one on the dd directory, and one on its
442 	 * head ds.  Otherwise, someone is trying to lookup something
443 	 * inside this dir while we want to destroy it.  The
444 	 * config_rwlock ensures that nobody else opens it after we
445 	 * check.
446 	 */
447 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
448 		return (EBUSY);
449 
450 	err = zap_count(mos, dd->dd_phys->dd_child_dir_zapobj, &count);
451 	if (err)
452 		return (err);
453 	if (count != 0)
454 		return (EEXIST);
455 
456 	return (0);
457 }
458 
459 void
460 dsl_dir_destroy_sync(void *arg1, void *tag, cred_t *cr, dmu_tx_t *tx)
461 {
462 	dsl_dir_t *dd = arg1;
463 	objset_t *mos = dd->dd_pool->dp_meta_objset;
464 	uint64_t val, obj;
465 	dd_used_t t;
466 
467 	ASSERT(RW_WRITE_HELD(&dd->dd_pool->dp_config_rwlock));
468 	ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
469 
470 	/* Remove our reservation. */
471 	val = 0;
472 	dsl_dir_set_reservation_sync(dd, &val, cr, tx);
473 	ASSERT3U(dd->dd_phys->dd_used_bytes, ==, 0);
474 	ASSERT3U(dd->dd_phys->dd_reserved, ==, 0);
475 	for (t = 0; t < DD_USED_NUM; t++)
476 		ASSERT3U(dd->dd_phys->dd_used_breakdown[t], ==, 0);
477 
478 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_child_dir_zapobj, tx));
479 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_props_zapobj, tx));
480 	VERIFY(0 == dsl_deleg_destroy(mos, dd->dd_phys->dd_deleg_zapobj, tx));
481 	VERIFY(0 == zap_remove(mos,
482 	    dd->dd_parent->dd_phys->dd_child_dir_zapobj, dd->dd_myname, tx));
483 
484 	obj = dd->dd_object;
485 	dsl_dir_close(dd, tag);
486 	VERIFY(0 == dmu_object_free(mos, obj, tx));
487 }
488 
489 boolean_t
490 dsl_dir_is_clone(dsl_dir_t *dd)
491 {
492 	return (dd->dd_phys->dd_origin_obj &&
493 	    (dd->dd_pool->dp_origin_snap == NULL ||
494 	    dd->dd_phys->dd_origin_obj !=
495 	    dd->dd_pool->dp_origin_snap->ds_object));
496 }
497 
498 void
499 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
500 {
501 	mutex_enter(&dd->dd_lock);
502 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
503 	    dd->dd_phys->dd_used_bytes);
504 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA, dd->dd_phys->dd_quota);
505 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
506 	    dd->dd_phys->dd_reserved);
507 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
508 	    dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
509 	    (dd->dd_phys->dd_uncompressed_bytes * 100 /
510 	    dd->dd_phys->dd_compressed_bytes));
511 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
512 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
513 		    dd->dd_phys->dd_used_breakdown[DD_USED_SNAP]);
514 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
515 		    dd->dd_phys->dd_used_breakdown[DD_USED_HEAD]);
516 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
517 		    dd->dd_phys->dd_used_breakdown[DD_USED_REFRSRV]);
518 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
519 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD] +
520 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD_RSRV]);
521 	}
522 	mutex_exit(&dd->dd_lock);
523 
524 	rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
525 	if (dsl_dir_is_clone(dd)) {
526 		dsl_dataset_t *ds;
527 		char buf[MAXNAMELEN];
528 
529 		VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
530 		    dd->dd_phys->dd_origin_obj, FTAG, &ds));
531 		dsl_dataset_name(ds, buf);
532 		dsl_dataset_rele(ds, FTAG);
533 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
534 	}
535 	rw_exit(&dd->dd_pool->dp_config_rwlock);
536 }
537 
538 void
539 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
540 {
541 	dsl_pool_t *dp = dd->dd_pool;
542 
543 	ASSERT(dd->dd_phys);
544 
545 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg) == 0) {
546 		/* up the hold count until we can be written out */
547 		dmu_buf_add_ref(dd->dd_dbuf, dd);
548 	}
549 }
550 
551 static int64_t
552 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
553 {
554 	uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
555 	uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
556 	return (new_accounted - old_accounted);
557 }
558 
559 void
560 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
561 {
562 	ASSERT(dmu_tx_is_syncing(tx));
563 
564 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
565 
566 	mutex_enter(&dd->dd_lock);
567 	ASSERT3U(dd->dd_tempreserved[tx->tx_txg&TXG_MASK], ==, 0);
568 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
569 	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
570 	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
571 	mutex_exit(&dd->dd_lock);
572 
573 	/* release the hold from dsl_dir_dirty */
574 	dmu_buf_rele(dd->dd_dbuf, dd);
575 }
576 
577 static uint64_t
578 dsl_dir_space_towrite(dsl_dir_t *dd)
579 {
580 	uint64_t space = 0;
581 	int i;
582 
583 	ASSERT(MUTEX_HELD(&dd->dd_lock));
584 
585 	for (i = 0; i < TXG_SIZE; i++) {
586 		space += dd->dd_space_towrite[i&TXG_MASK];
587 		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
588 	}
589 	return (space);
590 }
591 
592 /*
593  * How much space would dd have available if ancestor had delta applied
594  * to it?  If ondiskonly is set, we're only interested in what's
595  * on-disk, not estimated pending changes.
596  */
597 uint64_t
598 dsl_dir_space_available(dsl_dir_t *dd,
599     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
600 {
601 	uint64_t parentspace, myspace, quota, used;
602 
603 	/*
604 	 * If there are no restrictions otherwise, assume we have
605 	 * unlimited space available.
606 	 */
607 	quota = UINT64_MAX;
608 	parentspace = UINT64_MAX;
609 
610 	if (dd->dd_parent != NULL) {
611 		parentspace = dsl_dir_space_available(dd->dd_parent,
612 		    ancestor, delta, ondiskonly);
613 	}
614 
615 	mutex_enter(&dd->dd_lock);
616 	if (dd->dd_phys->dd_quota != 0)
617 		quota = dd->dd_phys->dd_quota;
618 	used = dd->dd_phys->dd_used_bytes;
619 	if (!ondiskonly)
620 		used += dsl_dir_space_towrite(dd);
621 
622 	if (dd->dd_parent == NULL) {
623 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
624 		quota = MIN(quota, poolsize);
625 	}
626 
627 	if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
628 		/*
629 		 * We have some space reserved, in addition to what our
630 		 * parent gave us.
631 		 */
632 		parentspace += dd->dd_phys->dd_reserved - used;
633 	}
634 
635 	if (dd == ancestor) {
636 		ASSERT(delta <= 0);
637 		ASSERT(used >= -delta);
638 		used += delta;
639 		if (parentspace != UINT64_MAX)
640 			parentspace -= delta;
641 	}
642 
643 	if (used > quota) {
644 		/* over quota */
645 		myspace = 0;
646 
647 		/*
648 		 * While it's OK to be a little over quota, if
649 		 * we think we are using more space than there
650 		 * is in the pool (which is already 1.6% more than
651 		 * dsl_pool_adjustedsize()), something is very
652 		 * wrong.
653 		 */
654 		ASSERT3U(used, <=, metaslab_class_get_space(
655 		    spa_normal_class(dd->dd_pool->dp_spa)));
656 	} else {
657 		/*
658 		 * the lesser of the space provided by our parent and
659 		 * the space left in our quota
660 		 */
661 		myspace = MIN(parentspace, quota - used);
662 	}
663 
664 	mutex_exit(&dd->dd_lock);
665 
666 	return (myspace);
667 }
668 
669 struct tempreserve {
670 	list_node_t tr_node;
671 	dsl_pool_t *tr_dp;
672 	dsl_dir_t *tr_ds;
673 	uint64_t tr_size;
674 };
675 
676 static int
677 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
678     boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
679     dmu_tx_t *tx, boolean_t first)
680 {
681 	uint64_t txg = tx->tx_txg;
682 	uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
683 	uint64_t deferred = 0;
684 	struct tempreserve *tr;
685 	int retval = EDQUOT;
686 	int txgidx = txg & TXG_MASK;
687 	int i;
688 	uint64_t ref_rsrv = 0;
689 
690 	ASSERT3U(txg, !=, 0);
691 	ASSERT3S(asize, >, 0);
692 
693 	mutex_enter(&dd->dd_lock);
694 
695 	/*
696 	 * Check against the dsl_dir's quota.  We don't add in the delta
697 	 * when checking for over-quota because they get one free hit.
698 	 */
699 	est_inflight = dsl_dir_space_towrite(dd);
700 	for (i = 0; i < TXG_SIZE; i++)
701 		est_inflight += dd->dd_tempreserved[i];
702 	used_on_disk = dd->dd_phys->dd_used_bytes;
703 
704 	/*
705 	 * On the first iteration, fetch the dataset's used-on-disk and
706 	 * refreservation values. Also, if checkrefquota is set, test if
707 	 * allocating this space would exceed the dataset's refquota.
708 	 */
709 	if (first && tx->tx_objset) {
710 		int error;
711 		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
712 
713 		error = dsl_dataset_check_quota(ds, checkrefquota,
714 		    asize, est_inflight, &used_on_disk, &ref_rsrv);
715 		if (error) {
716 			mutex_exit(&dd->dd_lock);
717 			return (error);
718 		}
719 	}
720 
721 	/*
722 	 * If this transaction will result in a net free of space,
723 	 * we want to let it through.
724 	 */
725 	if (ignorequota || netfree || dd->dd_phys->dd_quota == 0)
726 		quota = UINT64_MAX;
727 	else
728 		quota = dd->dd_phys->dd_quota;
729 
730 	/*
731 	 * Adjust the quota against the actual pool size at the root
732 	 * minus any outstanding deferred frees.
733 	 * To ensure that it's possible to remove files from a full
734 	 * pool without inducing transient overcommits, we throttle
735 	 * netfree transactions against a quota that is slightly larger,
736 	 * but still within the pool's allocation slop.  In cases where
737 	 * we're very close to full, this will allow a steady trickle of
738 	 * removes to get through.
739 	 */
740 	if (dd->dd_parent == NULL) {
741 		spa_t *spa = dd->dd_pool->dp_spa;
742 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
743 		deferred = metaslab_class_get_deferred(spa_normal_class(spa));
744 		if (poolsize - deferred < quota) {
745 			quota = poolsize - deferred;
746 			retval = ENOSPC;
747 		}
748 	}
749 
750 	/*
751 	 * If they are requesting more space, and our current estimate
752 	 * is over quota, they get to try again unless the actual
753 	 * on-disk is over quota and there are no pending changes (which
754 	 * may free up space for us).
755 	 */
756 	if (used_on_disk + est_inflight >= quota) {
757 		if (est_inflight > 0 || used_on_disk < quota ||
758 		    (retval == ENOSPC && used_on_disk < quota + deferred))
759 			retval = ERESTART;
760 		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
761 		    "quota=%lluK tr=%lluK err=%d\n",
762 		    used_on_disk>>10, est_inflight>>10,
763 		    quota>>10, asize>>10, retval);
764 		mutex_exit(&dd->dd_lock);
765 		return (retval);
766 	}
767 
768 	/* We need to up our estimated delta before dropping dd_lock */
769 	dd->dd_tempreserved[txgidx] += asize;
770 
771 	parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
772 	    asize - ref_rsrv);
773 	mutex_exit(&dd->dd_lock);
774 
775 	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
776 	tr->tr_ds = dd;
777 	tr->tr_size = asize;
778 	list_insert_tail(tr_list, tr);
779 
780 	/* see if it's OK with our parent */
781 	if (dd->dd_parent && parent_rsrv) {
782 		boolean_t ismos = (dd->dd_phys->dd_head_dataset_obj == 0);
783 
784 		return (dsl_dir_tempreserve_impl(dd->dd_parent,
785 		    parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
786 	} else {
787 		return (0);
788 	}
789 }
790 
791 /*
792  * Reserve space in this dsl_dir, to be used in this tx's txg.
793  * After the space has been dirtied (and dsl_dir_willuse_space()
794  * has been called), the reservation should be canceled, using
795  * dsl_dir_tempreserve_clear().
796  */
797 int
798 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
799     uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
800 {
801 	int err;
802 	list_t *tr_list;
803 
804 	if (asize == 0) {
805 		*tr_cookiep = NULL;
806 		return (0);
807 	}
808 
809 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
810 	list_create(tr_list, sizeof (struct tempreserve),
811 	    offsetof(struct tempreserve, tr_node));
812 	ASSERT3S(asize, >, 0);
813 	ASSERT3S(fsize, >=, 0);
814 
815 	err = arc_tempreserve_space(lsize, tx->tx_txg);
816 	if (err == 0) {
817 		struct tempreserve *tr;
818 
819 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
820 		tr->tr_size = lsize;
821 		list_insert_tail(tr_list, tr);
822 
823 		err = dsl_pool_tempreserve_space(dd->dd_pool, asize, tx);
824 	} else {
825 		if (err == EAGAIN) {
826 			txg_delay(dd->dd_pool, tx->tx_txg, 1);
827 			err = ERESTART;
828 		}
829 		dsl_pool_memory_pressure(dd->dd_pool);
830 	}
831 
832 	if (err == 0) {
833 		struct tempreserve *tr;
834 
835 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
836 		tr->tr_dp = dd->dd_pool;
837 		tr->tr_size = asize;
838 		list_insert_tail(tr_list, tr);
839 
840 		err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
841 		    FALSE, asize > usize, tr_list, tx, TRUE);
842 	}
843 
844 	if (err)
845 		dsl_dir_tempreserve_clear(tr_list, tx);
846 	else
847 		*tr_cookiep = tr_list;
848 
849 	return (err);
850 }
851 
852 /*
853  * Clear a temporary reservation that we previously made with
854  * dsl_dir_tempreserve_space().
855  */
856 void
857 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
858 {
859 	int txgidx = tx->tx_txg & TXG_MASK;
860 	list_t *tr_list = tr_cookie;
861 	struct tempreserve *tr;
862 
863 	ASSERT3U(tx->tx_txg, !=, 0);
864 
865 	if (tr_cookie == NULL)
866 		return;
867 
868 	while (tr = list_head(tr_list)) {
869 		if (tr->tr_dp) {
870 			dsl_pool_tempreserve_clear(tr->tr_dp, tr->tr_size, tx);
871 		} else if (tr->tr_ds) {
872 			mutex_enter(&tr->tr_ds->dd_lock);
873 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
874 			    tr->tr_size);
875 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
876 			mutex_exit(&tr->tr_ds->dd_lock);
877 		} else {
878 			arc_tempreserve_clear(tr->tr_size);
879 		}
880 		list_remove(tr_list, tr);
881 		kmem_free(tr, sizeof (struct tempreserve));
882 	}
883 
884 	kmem_free(tr_list, sizeof (list_t));
885 }
886 
887 static void
888 dsl_dir_willuse_space_impl(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
889 {
890 	int64_t parent_space;
891 	uint64_t est_used;
892 
893 	mutex_enter(&dd->dd_lock);
894 	if (space > 0)
895 		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
896 
897 	est_used = dsl_dir_space_towrite(dd) + dd->dd_phys->dd_used_bytes;
898 	parent_space = parent_delta(dd, est_used, space);
899 	mutex_exit(&dd->dd_lock);
900 
901 	/* Make sure that we clean up dd_space_to* */
902 	dsl_dir_dirty(dd, tx);
903 
904 	/* XXX this is potentially expensive and unnecessary... */
905 	if (parent_space && dd->dd_parent)
906 		dsl_dir_willuse_space_impl(dd->dd_parent, parent_space, tx);
907 }
908 
909 /*
910  * Call in open context when we think we're going to write/free space,
911  * eg. when dirtying data.  Be conservative (ie. OK to write less than
912  * this or free more than this, but don't write more or free less).
913  */
914 void
915 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
916 {
917 	dsl_pool_willuse_space(dd->dd_pool, space, tx);
918 	dsl_dir_willuse_space_impl(dd, space, tx);
919 }
920 
921 /* call from syncing context when we actually write/free space for this dd */
922 void
923 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
924     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
925 {
926 	int64_t accounted_delta;
927 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
928 
929 	ASSERT(dmu_tx_is_syncing(tx));
930 	ASSERT(type < DD_USED_NUM);
931 
932 	dsl_dir_dirty(dd, tx);
933 
934 	if (needlock)
935 		mutex_enter(&dd->dd_lock);
936 	accounted_delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, used);
937 	ASSERT(used >= 0 || dd->dd_phys->dd_used_bytes >= -used);
938 	ASSERT(compressed >= 0 ||
939 	    dd->dd_phys->dd_compressed_bytes >= -compressed);
940 	ASSERT(uncompressed >= 0 ||
941 	    dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
942 	dd->dd_phys->dd_used_bytes += used;
943 	dd->dd_phys->dd_uncompressed_bytes += uncompressed;
944 	dd->dd_phys->dd_compressed_bytes += compressed;
945 
946 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
947 		ASSERT(used > 0 ||
948 		    dd->dd_phys->dd_used_breakdown[type] >= -used);
949 		dd->dd_phys->dd_used_breakdown[type] += used;
950 #ifdef DEBUG
951 		dd_used_t t;
952 		uint64_t u = 0;
953 		for (t = 0; t < DD_USED_NUM; t++)
954 			u += dd->dd_phys->dd_used_breakdown[t];
955 		ASSERT3U(u, ==, dd->dd_phys->dd_used_bytes);
956 #endif
957 	}
958 	if (needlock)
959 		mutex_exit(&dd->dd_lock);
960 
961 	if (dd->dd_parent != NULL) {
962 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
963 		    accounted_delta, compressed, uncompressed, tx);
964 		dsl_dir_transfer_space(dd->dd_parent,
965 		    used - accounted_delta,
966 		    DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
967 	}
968 }
969 
970 void
971 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
972     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
973 {
974 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
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 	if (needlock)
985 		mutex_enter(&dd->dd_lock);
986 	ASSERT(delta > 0 ?
987 	    dd->dd_phys->dd_used_breakdown[oldtype] >= delta :
988 	    dd->dd_phys->dd_used_breakdown[newtype] >= -delta);
989 	ASSERT(dd->dd_phys->dd_used_bytes >= ABS(delta));
990 	dd->dd_phys->dd_used_breakdown[oldtype] -= delta;
991 	dd->dd_phys->dd_used_breakdown[newtype] += delta;
992 	if (needlock)
993 		mutex_exit(&dd->dd_lock);
994 }
995 
996 static int
997 dsl_dir_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
998 {
999 	dsl_dir_t *dd = arg1;
1000 	uint64_t *quotap = arg2;
1001 	uint64_t new_quota = *quotap;
1002 	int err = 0;
1003 	uint64_t towrite;
1004 
1005 	if (new_quota == 0)
1006 		return (0);
1007 
1008 	mutex_enter(&dd->dd_lock);
1009 	/*
1010 	 * If we are doing the preliminary check in open context, and
1011 	 * there are pending changes, then don't fail it, since the
1012 	 * pending changes could under-estimate the amount of space to be
1013 	 * freed up.
1014 	 */
1015 	towrite = dsl_dir_space_towrite(dd);
1016 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1017 	    (new_quota < dd->dd_phys->dd_reserved ||
1018 	    new_quota < dd->dd_phys->dd_used_bytes + towrite)) {
1019 		err = ENOSPC;
1020 	}
1021 	mutex_exit(&dd->dd_lock);
1022 	return (err);
1023 }
1024 
1025 /* ARGSUSED */
1026 static void
1027 dsl_dir_set_quota_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1028 {
1029 	dsl_dir_t *dd = arg1;
1030 	uint64_t *quotap = arg2;
1031 	uint64_t new_quota = *quotap;
1032 
1033 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1034 
1035 	mutex_enter(&dd->dd_lock);
1036 	dd->dd_phys->dd_quota = new_quota;
1037 	mutex_exit(&dd->dd_lock);
1038 
1039 	spa_history_internal_log(LOG_DS_QUOTA, dd->dd_pool->dp_spa,
1040 	    tx, cr, "%lld dataset = %llu ",
1041 	    (longlong_t)new_quota, dd->dd_phys->dd_head_dataset_obj);
1042 }
1043 
1044 int
1045 dsl_dir_set_quota(const char *ddname, uint64_t quota)
1046 {
1047 	dsl_dir_t *dd;
1048 	int err;
1049 
1050 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1051 	if (err)
1052 		return (err);
1053 
1054 	if (quota != dd->dd_phys->dd_quota) {
1055 		/*
1056 		 * If someone removes a file, then tries to set the quota, we
1057 		 * want to make sure the file freeing takes effect.
1058 		 */
1059 		txg_wait_open(dd->dd_pool, 0);
1060 
1061 		err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_quota_check,
1062 		    dsl_dir_set_quota_sync, dd, &quota, 0);
1063 	}
1064 	dsl_dir_close(dd, FTAG);
1065 	return (err);
1066 }
1067 
1068 int
1069 dsl_dir_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
1070 {
1071 	dsl_dir_t *dd = arg1;
1072 	uint64_t *reservationp = arg2;
1073 	uint64_t new_reservation = *reservationp;
1074 	uint64_t used, avail;
1075 
1076 	/*
1077 	 * If we are doing the preliminary check in open context, the
1078 	 * space estimates may be inaccurate.
1079 	 */
1080 	if (!dmu_tx_is_syncing(tx))
1081 		return (0);
1082 
1083 	mutex_enter(&dd->dd_lock);
1084 	used = dd->dd_phys->dd_used_bytes;
1085 	mutex_exit(&dd->dd_lock);
1086 
1087 	if (dd->dd_parent) {
1088 		avail = dsl_dir_space_available(dd->dd_parent,
1089 		    NULL, 0, FALSE);
1090 	} else {
1091 		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1092 	}
1093 
1094 	if (MAX(used, new_reservation) > MAX(used, dd->dd_phys->dd_reserved)) {
1095 		uint64_t delta = MAX(used, new_reservation) -
1096 		    MAX(used, dd->dd_phys->dd_reserved);
1097 
1098 		if (delta > avail)
1099 			return (ENOSPC);
1100 		if (dd->dd_phys->dd_quota > 0 &&
1101 		    new_reservation > dd->dd_phys->dd_quota)
1102 			return (ENOSPC);
1103 	}
1104 
1105 	return (0);
1106 }
1107 
1108 /* ARGSUSED */
1109 static void
1110 dsl_dir_set_reservation_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1111 {
1112 	dsl_dir_t *dd = arg1;
1113 	uint64_t *reservationp = arg2;
1114 	uint64_t new_reservation = *reservationp;
1115 	uint64_t used;
1116 	int64_t delta;
1117 
1118 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1119 
1120 	mutex_enter(&dd->dd_lock);
1121 	used = dd->dd_phys->dd_used_bytes;
1122 	delta = MAX(used, new_reservation) -
1123 	    MAX(used, dd->dd_phys->dd_reserved);
1124 	dd->dd_phys->dd_reserved = new_reservation;
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 	mutex_exit(&dd->dd_lock);
1132 
1133 	spa_history_internal_log(LOG_DS_RESERVATION, dd->dd_pool->dp_spa,
1134 	    tx, cr, "%lld dataset = %llu",
1135 	    (longlong_t)new_reservation, dd->dd_phys->dd_head_dataset_obj);
1136 }
1137 
1138 int
1139 dsl_dir_set_reservation(const char *ddname, uint64_t reservation)
1140 {
1141 	dsl_dir_t *dd;
1142 	int err;
1143 
1144 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1145 	if (err)
1146 		return (err);
1147 	err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_reservation_check,
1148 	    dsl_dir_set_reservation_sync, dd, &reservation, 0);
1149 	dsl_dir_close(dd, FTAG);
1150 	return (err);
1151 }
1152 
1153 static dsl_dir_t *
1154 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1155 {
1156 	for (; ds1; ds1 = ds1->dd_parent) {
1157 		dsl_dir_t *dd;
1158 		for (dd = ds2; dd; dd = dd->dd_parent) {
1159 			if (ds1 == dd)
1160 				return (dd);
1161 		}
1162 	}
1163 	return (NULL);
1164 }
1165 
1166 /*
1167  * If delta is applied to dd, how much of that delta would be applied to
1168  * ancestor?  Syncing context only.
1169  */
1170 static int64_t
1171 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1172 {
1173 	if (dd == ancestor)
1174 		return (delta);
1175 
1176 	mutex_enter(&dd->dd_lock);
1177 	delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, delta);
1178 	mutex_exit(&dd->dd_lock);
1179 	return (would_change(dd->dd_parent, delta, ancestor));
1180 }
1181 
1182 struct renamearg {
1183 	dsl_dir_t *newparent;
1184 	const char *mynewname;
1185 };
1186 
1187 /*ARGSUSED*/
1188 static int
1189 dsl_dir_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
1190 {
1191 	dsl_dir_t *dd = arg1;
1192 	struct renamearg *ra = arg2;
1193 	dsl_pool_t *dp = dd->dd_pool;
1194 	objset_t *mos = dp->dp_meta_objset;
1195 	int err;
1196 	uint64_t val;
1197 
1198 	/* There should be 2 references: the open and the dirty */
1199 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
1200 		return (EBUSY);
1201 
1202 	/* check for existing name */
1203 	err = zap_lookup(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1204 	    ra->mynewname, 8, 1, &val);
1205 	if (err == 0)
1206 		return (EEXIST);
1207 	if (err != ENOENT)
1208 		return (err);
1209 
1210 	if (ra->newparent != dd->dd_parent) {
1211 		/* is there enough space? */
1212 		uint64_t myspace =
1213 		    MAX(dd->dd_phys->dd_used_bytes, dd->dd_phys->dd_reserved);
1214 
1215 		/* no rename into our descendant */
1216 		if (closest_common_ancestor(dd, ra->newparent) == dd)
1217 			return (EINVAL);
1218 
1219 		if (err = dsl_dir_transfer_possible(dd->dd_parent,
1220 		    ra->newparent, myspace))
1221 			return (err);
1222 	}
1223 
1224 	return (0);
1225 }
1226 
1227 static void
1228 dsl_dir_rename_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1229 {
1230 	dsl_dir_t *dd = arg1;
1231 	struct renamearg *ra = arg2;
1232 	dsl_pool_t *dp = dd->dd_pool;
1233 	objset_t *mos = dp->dp_meta_objset;
1234 	int err;
1235 
1236 	ASSERT(dmu_buf_refcount(dd->dd_dbuf) <= 2);
1237 
1238 	if (ra->newparent != dd->dd_parent) {
1239 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1240 		    -dd->dd_phys->dd_used_bytes,
1241 		    -dd->dd_phys->dd_compressed_bytes,
1242 		    -dd->dd_phys->dd_uncompressed_bytes, tx);
1243 		dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD,
1244 		    dd->dd_phys->dd_used_bytes,
1245 		    dd->dd_phys->dd_compressed_bytes,
1246 		    dd->dd_phys->dd_uncompressed_bytes, tx);
1247 
1248 		if (dd->dd_phys->dd_reserved > dd->dd_phys->dd_used_bytes) {
1249 			uint64_t unused_rsrv = dd->dd_phys->dd_reserved -
1250 			    dd->dd_phys->dd_used_bytes;
1251 
1252 			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1253 			    -unused_rsrv, 0, 0, tx);
1254 			dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD_RSRV,
1255 			    unused_rsrv, 0, 0, tx);
1256 		}
1257 	}
1258 
1259 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1260 
1261 	/* remove from old parent zapobj */
1262 	err = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1263 	    dd->dd_myname, tx);
1264 	ASSERT3U(err, ==, 0);
1265 
1266 	(void) strcpy(dd->dd_myname, ra->mynewname);
1267 	dsl_dir_close(dd->dd_parent, dd);
1268 	dd->dd_phys->dd_parent_obj = ra->newparent->dd_object;
1269 	VERIFY(0 == dsl_dir_open_obj(dd->dd_pool,
1270 	    ra->newparent->dd_object, NULL, dd, &dd->dd_parent));
1271 
1272 	/* add to new parent zapobj */
1273 	err = zap_add(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1274 	    dd->dd_myname, 8, 1, &dd->dd_object, tx);
1275 	ASSERT3U(err, ==, 0);
1276 
1277 	spa_history_internal_log(LOG_DS_RENAME, dd->dd_pool->dp_spa,
1278 	    tx, cr, "dataset = %llu", dd->dd_phys->dd_head_dataset_obj);
1279 }
1280 
1281 int
1282 dsl_dir_rename(dsl_dir_t *dd, const char *newname)
1283 {
1284 	struct renamearg ra;
1285 	int err;
1286 
1287 	/* new parent should exist */
1288 	err = dsl_dir_open(newname, FTAG, &ra.newparent, &ra.mynewname);
1289 	if (err)
1290 		return (err);
1291 
1292 	/* can't rename to different pool */
1293 	if (dd->dd_pool != ra.newparent->dd_pool) {
1294 		err = ENXIO;
1295 		goto out;
1296 	}
1297 
1298 	/* new name should not already exist */
1299 	if (ra.mynewname == NULL) {
1300 		err = EEXIST;
1301 		goto out;
1302 	}
1303 
1304 	err = dsl_sync_task_do(dd->dd_pool,
1305 	    dsl_dir_rename_check, dsl_dir_rename_sync, dd, &ra, 3);
1306 
1307 out:
1308 	dsl_dir_close(ra.newparent, FTAG);
1309 	return (err);
1310 }
1311 
1312 int
1313 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd, uint64_t space)
1314 {
1315 	dsl_dir_t *ancestor;
1316 	int64_t adelta;
1317 	uint64_t avail;
1318 
1319 	ancestor = closest_common_ancestor(sdd, tdd);
1320 	adelta = would_change(sdd, -space, ancestor);
1321 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1322 	if (avail < space)
1323 		return (ENOSPC);
1324 
1325 	return (0);
1326 }
1327 
1328 timestruc_t
1329 dsl_dir_snap_cmtime(dsl_dir_t *dd)
1330 {
1331 	timestruc_t t;
1332 
1333 	mutex_enter(&dd->dd_lock);
1334 	t = dd->dd_snap_cmtime;
1335 	mutex_exit(&dd->dd_lock);
1336 
1337 	return (t);
1338 }
1339 
1340 void
1341 dsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1342 {
1343 	timestruc_t t;
1344 
1345 	gethrestime(&t);
1346 	mutex_enter(&dd->dd_lock);
1347 	dd->dd_snap_cmtime = t;
1348 	mutex_exit(&dd->dd_lock);
1349 }
1350