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