xref: /titanic_51/usr/src/uts/common/fs/zfs/dsl_dir.c (revision 42cc51e07cdbcad3b9aca8d9d991fc09b251feb7)
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Martin Matuska. All rights reserved.
25  * Copyright (c) 2014 Joyent, Inc. All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
28  */
29 
30 #include <sys/dmu.h>
31 #include <sys/dmu_objset.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/dsl_dataset.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dsl_prop.h>
36 #include <sys/dsl_synctask.h>
37 #include <sys/dsl_deleg.h>
38 #include <sys/dmu_impl.h>
39 #include <sys/spa.h>
40 #include <sys/metaslab.h>
41 #include <sys/zap.h>
42 #include <sys/zio.h>
43 #include <sys/arc.h>
44 #include <sys/sunddi.h>
45 #include <sys/zfeature.h>
46 #include <sys/policy.h>
47 #include <sys/zfs_znode.h>
48 #include "zfs_namecheck.h"
49 #include "zfs_prop.h"
50 
51 /*
52  * Filesystem and Snapshot Limits
53  * ------------------------------
54  *
55  * These limits are used to restrict the number of filesystems and/or snapshots
56  * that can be created at a given level in the tree or below. A typical
57  * use-case is with a delegated dataset where the administrator wants to ensure
58  * that a user within the zone is not creating too many additional filesystems
59  * or snapshots, even though they're not exceeding their space quota.
60  *
61  * The filesystem and snapshot counts are stored as extensible properties. This
62  * capability is controlled by a feature flag and must be enabled to be used.
63  * Once enabled, the feature is not active until the first limit is set. At
64  * that point, future operations to create/destroy filesystems or snapshots
65  * will validate and update the counts.
66  *
67  * Because the count properties will not exist before the feature is active,
68  * the counts are updated when a limit is first set on an uninitialized
69  * dsl_dir node in the tree (The filesystem/snapshot count on a node includes
70  * all of the nested filesystems/snapshots. Thus, a new leaf node has a
71  * filesystem count of 0 and a snapshot count of 0. Non-existent filesystem and
72  * snapshot count properties on a node indicate uninitialized counts on that
73  * node.) When first setting a limit on an uninitialized node, the code starts
74  * at the filesystem with the new limit and descends into all sub-filesystems
75  * to add the count properties.
76  *
77  * In practice this is lightweight since a limit is typically set when the
78  * filesystem is created and thus has no children. Once valid, changing the
79  * limit value won't require a re-traversal since the counts are already valid.
80  * When recursively fixing the counts, if a node with a limit is encountered
81  * during the descent, the counts are known to be valid and there is no need to
82  * descend into that filesystem's children. The counts on filesystems above the
83  * one with the new limit will still be uninitialized, unless a limit is
84  * eventually set on one of those filesystems. The counts are always recursively
85  * updated when a limit is set on a dataset, unless there is already a limit.
86  * When a new limit value is set on a filesystem with an existing limit, it is
87  * possible for the new limit to be less than the current count at that level
88  * since a user who can change the limit is also allowed to exceed the limit.
89  *
90  * Once the feature is active, then whenever a filesystem or snapshot is
91  * created, the code recurses up the tree, validating the new count against the
92  * limit at each initialized level. In practice, most levels will not have a
93  * limit set. If there is a limit at any initialized level up the tree, the
94  * check must pass or the creation will fail. Likewise, when a filesystem or
95  * snapshot is destroyed, the counts are recursively adjusted all the way up
96  * the initizized nodes in the tree. Renaming a filesystem into different point
97  * in the tree will first validate, then update the counts on each branch up to
98  * the common ancestor. A receive will also validate the counts and then update
99  * them.
100  *
101  * An exception to the above behavior is that the limit is not enforced if the
102  * user has permission to modify the limit. This is primarily so that
103  * recursive snapshots in the global zone always work. We want to prevent a
104  * denial-of-service in which a lower level delegated dataset could max out its
105  * limit and thus block recursive snapshots from being taken in the global zone.
106  * Because of this, it is possible for the snapshot count to be over the limit
107  * and snapshots taken in the global zone could cause a lower level dataset to
108  * hit or exceed its limit. The administrator taking the global zone recursive
109  * snapshot should be aware of this side-effect and behave accordingly.
110  * For consistency, the filesystem limit is also not enforced if the user can
111  * modify the limit.
112  *
113  * The filesystem and snapshot limits are validated by dsl_fs_ss_limit_check()
114  * and updated by dsl_fs_ss_count_adjust(). A new limit value is setup in
115  * dsl_dir_activate_fs_ss_limit() and the counts are adjusted, if necessary, by
116  * dsl_dir_init_fs_ss_count().
117  *
118  * There is a special case when we receive a filesystem that already exists. In
119  * this case a temporary clone name of %X is created (see dmu_recv_begin). We
120  * never update the filesystem counts for temporary clones.
121  *
122  * Likewise, we do not update the snapshot counts for temporary snapshots,
123  * such as those created by zfs diff.
124  */
125 
126 /*
127  * Tunable to control EDQUOT behaviour. With this set to a value != 0, zfs
128  * doesn't always wait for a dirty txg to complete when an operation can't
129  * get through due to space exhaustion. Instead it fails early in a range
130  * of the tunable around the quota.
131  * This vastly helps to reduce the number of threads waiting for the txg
132  * to commit when a busy filesystem is near quota, especially in combination
133  * with NFS, where each waiter takes up a server thread.
134  */
135 uint64_t early_edquot_threshold = 32 * 1048576; /* tunable */
136 
137 extern inline dsl_dir_phys_t *dsl_dir_phys(dsl_dir_t *dd);
138 
139 static uint64_t dsl_dir_space_towrite(dsl_dir_t *dd);
140 
141 static void
142 dsl_dir_evict_async(void *dbu)
143 {
144 	dsl_dir_t *dd = dbu;
145 	dsl_pool_t *dp = dd->dd_pool;
146 	int t;
147 
148 	dd->dd_dbuf = NULL;
149 
150 	for (t = 0; t < TXG_SIZE; t++) {
151 		ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
152 		ASSERT(dd->dd_tempreserved[t] == 0);
153 		ASSERT(dd->dd_space_towrite[t] == 0);
154 	}
155 
156 	if (dd->dd_parent)
157 		dsl_dir_async_rele(dd->dd_parent, dd);
158 
159 	spa_async_close(dd->dd_pool->dp_spa, dd);
160 
161 	dsl_prop_fini(dd);
162 	mutex_destroy(&dd->dd_lock);
163 	kmem_free(dd, sizeof (dsl_dir_t));
164 }
165 
166 int
167 dsl_dir_hold_obj(dsl_pool_t *dp, uint64_t ddobj,
168     const char *tail, void *tag, dsl_dir_t **ddp)
169 {
170 	dmu_buf_t *dbuf;
171 	dsl_dir_t *dd;
172 	int err;
173 
174 	ASSERT(dsl_pool_config_held(dp));
175 
176 	err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
177 	if (err != 0)
178 		return (err);
179 	dd = dmu_buf_get_user(dbuf);
180 #ifdef ZFS_DEBUG
181 	{
182 		dmu_object_info_t doi;
183 		dmu_object_info_from_db(dbuf, &doi);
184 		ASSERT3U(doi.doi_bonus_type, ==, DMU_OT_DSL_DIR);
185 		ASSERT3U(doi.doi_bonus_size, >=, sizeof (dsl_dir_phys_t));
186 	}
187 #endif
188 	if (dd == NULL) {
189 		dsl_dir_t *winner;
190 
191 		dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
192 		dd->dd_object = ddobj;
193 		dd->dd_dbuf = dbuf;
194 		dd->dd_pool = dp;
195 		mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
196 		dsl_prop_init(dd);
197 
198 		dsl_dir_snap_cmtime_update(dd);
199 
200 		if (dsl_dir_phys(dd)->dd_parent_obj) {
201 			err = dsl_dir_hold_obj(dp,
202 			    dsl_dir_phys(dd)->dd_parent_obj, NULL, dd,
203 			    &dd->dd_parent);
204 			if (err != 0)
205 				goto errout;
206 			if (tail) {
207 #ifdef ZFS_DEBUG
208 				uint64_t foundobj;
209 
210 				err = zap_lookup(dp->dp_meta_objset,
211 				    dsl_dir_phys(dd->dd_parent)->
212 				    dd_child_dir_zapobj, tail,
213 				    sizeof (foundobj), 1, &foundobj);
214 				ASSERT(err || foundobj == ddobj);
215 #endif
216 				(void) strcpy(dd->dd_myname, tail);
217 			} else {
218 				err = zap_value_search(dp->dp_meta_objset,
219 				    dsl_dir_phys(dd->dd_parent)->
220 				    dd_child_dir_zapobj,
221 				    ddobj, 0, dd->dd_myname);
222 			}
223 			if (err != 0)
224 				goto errout;
225 		} else {
226 			(void) strcpy(dd->dd_myname, spa_name(dp->dp_spa));
227 		}
228 
229 		if (dsl_dir_is_clone(dd)) {
230 			dmu_buf_t *origin_bonus;
231 			dsl_dataset_phys_t *origin_phys;
232 
233 			/*
234 			 * We can't open the origin dataset, because
235 			 * that would require opening this dsl_dir.
236 			 * Just look at its phys directly instead.
237 			 */
238 			err = dmu_bonus_hold(dp->dp_meta_objset,
239 			    dsl_dir_phys(dd)->dd_origin_obj, FTAG,
240 			    &origin_bonus);
241 			if (err != 0)
242 				goto errout;
243 			origin_phys = origin_bonus->db_data;
244 			dd->dd_origin_txg =
245 			    origin_phys->ds_creation_txg;
246 			dmu_buf_rele(origin_bonus, FTAG);
247 		}
248 
249 		dmu_buf_init_user(&dd->dd_dbu, NULL, dsl_dir_evict_async,
250 		    &dd->dd_dbuf);
251 		winner = dmu_buf_set_user_ie(dbuf, &dd->dd_dbu);
252 		if (winner != NULL) {
253 			if (dd->dd_parent)
254 				dsl_dir_rele(dd->dd_parent, dd);
255 			dsl_prop_fini(dd);
256 			mutex_destroy(&dd->dd_lock);
257 			kmem_free(dd, sizeof (dsl_dir_t));
258 			dd = winner;
259 		} else {
260 			spa_open_ref(dp->dp_spa, dd);
261 		}
262 	}
263 
264 	/*
265 	 * The dsl_dir_t has both open-to-close and instantiate-to-evict
266 	 * holds on the spa.  We need the open-to-close holds because
267 	 * otherwise the spa_refcnt wouldn't change when we open a
268 	 * dir which the spa also has open, so we could incorrectly
269 	 * think it was OK to unload/export/destroy the pool.  We need
270 	 * the instantiate-to-evict hold because the dsl_dir_t has a
271 	 * pointer to the dd_pool, which has a pointer to the spa_t.
272 	 */
273 	spa_open_ref(dp->dp_spa, tag);
274 	ASSERT3P(dd->dd_pool, ==, dp);
275 	ASSERT3U(dd->dd_object, ==, ddobj);
276 	ASSERT3P(dd->dd_dbuf, ==, dbuf);
277 	*ddp = dd;
278 	return (0);
279 
280 errout:
281 	if (dd->dd_parent)
282 		dsl_dir_rele(dd->dd_parent, dd);
283 	dsl_prop_fini(dd);
284 	mutex_destroy(&dd->dd_lock);
285 	kmem_free(dd, sizeof (dsl_dir_t));
286 	dmu_buf_rele(dbuf, tag);
287 	return (err);
288 }
289 
290 void
291 dsl_dir_rele(dsl_dir_t *dd, void *tag)
292 {
293 	dprintf_dd(dd, "%s\n", "");
294 	spa_close(dd->dd_pool->dp_spa, tag);
295 	dmu_buf_rele(dd->dd_dbuf, tag);
296 }
297 
298 /*
299  * Remove a reference to the given dsl dir that is being asynchronously
300  * released.  Async releases occur from a taskq performing eviction of
301  * dsl datasets and dirs.  This process is identical to a normal release
302  * with the exception of using the async API for releasing the reference on
303  * the spa.
304  */
305 void
306 dsl_dir_async_rele(dsl_dir_t *dd, void *tag)
307 {
308 	dprintf_dd(dd, "%s\n", "");
309 	spa_async_close(dd->dd_pool->dp_spa, tag);
310 	dmu_buf_rele(dd->dd_dbuf, tag);
311 }
312 
313 /* buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes */
314 void
315 dsl_dir_name(dsl_dir_t *dd, char *buf)
316 {
317 	if (dd->dd_parent) {
318 		dsl_dir_name(dd->dd_parent, buf);
319 		VERIFY3U(strlcat(buf, "/", ZFS_MAX_DATASET_NAME_LEN), <,
320 		    ZFS_MAX_DATASET_NAME_LEN);
321 	} else {
322 		buf[0] = '\0';
323 	}
324 	if (!MUTEX_HELD(&dd->dd_lock)) {
325 		/*
326 		 * recursive mutex so that we can use
327 		 * dprintf_dd() with dd_lock held
328 		 */
329 		mutex_enter(&dd->dd_lock);
330 		VERIFY3U(strlcat(buf, dd->dd_myname, ZFS_MAX_DATASET_NAME_LEN),
331 		    <, ZFS_MAX_DATASET_NAME_LEN);
332 		mutex_exit(&dd->dd_lock);
333 	} else {
334 		VERIFY3U(strlcat(buf, dd->dd_myname, ZFS_MAX_DATASET_NAME_LEN),
335 		    <, ZFS_MAX_DATASET_NAME_LEN);
336 	}
337 }
338 
339 /* Calculate name length, avoiding all the strcat calls of dsl_dir_name */
340 int
341 dsl_dir_namelen(dsl_dir_t *dd)
342 {
343 	int result = 0;
344 
345 	if (dd->dd_parent) {
346 		/* parent's name + 1 for the "/" */
347 		result = dsl_dir_namelen(dd->dd_parent) + 1;
348 	}
349 
350 	if (!MUTEX_HELD(&dd->dd_lock)) {
351 		/* see dsl_dir_name */
352 		mutex_enter(&dd->dd_lock);
353 		result += strlen(dd->dd_myname);
354 		mutex_exit(&dd->dd_lock);
355 	} else {
356 		result += strlen(dd->dd_myname);
357 	}
358 
359 	return (result);
360 }
361 
362 static int
363 getcomponent(const char *path, char *component, const char **nextp)
364 {
365 	char *p;
366 
367 	if ((path == NULL) || (path[0] == '\0'))
368 		return (SET_ERROR(ENOENT));
369 	/* This would be a good place to reserve some namespace... */
370 	p = strpbrk(path, "/@");
371 	if (p && (p[1] == '/' || p[1] == '@')) {
372 		/* two separators in a row */
373 		return (SET_ERROR(EINVAL));
374 	}
375 	if (p == NULL || p == path) {
376 		/*
377 		 * if the first thing is an @ or /, it had better be an
378 		 * @ and it had better not have any more ats or slashes,
379 		 * and it had better have something after the @.
380 		 */
381 		if (p != NULL &&
382 		    (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
383 			return (SET_ERROR(EINVAL));
384 		if (strlen(path) >= ZFS_MAX_DATASET_NAME_LEN)
385 			return (SET_ERROR(ENAMETOOLONG));
386 		(void) strcpy(component, path);
387 		p = NULL;
388 	} else if (p[0] == '/') {
389 		if (p - path >= ZFS_MAX_DATASET_NAME_LEN)
390 			return (SET_ERROR(ENAMETOOLONG));
391 		(void) strncpy(component, path, p - path);
392 		component[p - path] = '\0';
393 		p++;
394 	} else if (p[0] == '@') {
395 		/*
396 		 * if the next separator is an @, there better not be
397 		 * any more slashes.
398 		 */
399 		if (strchr(path, '/'))
400 			return (SET_ERROR(EINVAL));
401 		if (p - path >= ZFS_MAX_DATASET_NAME_LEN)
402 			return (SET_ERROR(ENAMETOOLONG));
403 		(void) strncpy(component, path, p - path);
404 		component[p - path] = '\0';
405 	} else {
406 		panic("invalid p=%p", (void *)p);
407 	}
408 	*nextp = p;
409 	return (0);
410 }
411 
412 /*
413  * Return the dsl_dir_t, and possibly the last component which couldn't
414  * be found in *tail.  The name must be in the specified dsl_pool_t.  This
415  * thread must hold the dp_config_rwlock for the pool.  Returns NULL if the
416  * path is bogus, or if tail==NULL and we couldn't parse the whole name.
417  * (*tail)[0] == '@' means that the last component is a snapshot.
418  */
419 int
420 dsl_dir_hold(dsl_pool_t *dp, const char *name, void *tag,
421     dsl_dir_t **ddp, const char **tailp)
422 {
423 	char buf[ZFS_MAX_DATASET_NAME_LEN];
424 	const char *spaname, *next, *nextnext = NULL;
425 	int err;
426 	dsl_dir_t *dd;
427 	uint64_t ddobj;
428 
429 	err = getcomponent(name, buf, &next);
430 	if (err != 0)
431 		return (err);
432 
433 	/* Make sure the name is in the specified pool. */
434 	spaname = spa_name(dp->dp_spa);
435 	if (strcmp(buf, spaname) != 0)
436 		return (SET_ERROR(EXDEV));
437 
438 	ASSERT(dsl_pool_config_held(dp));
439 
440 	err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
441 	if (err != 0) {
442 		return (err);
443 	}
444 
445 	while (next != NULL) {
446 		dsl_dir_t *child_dd;
447 		err = getcomponent(next, buf, &nextnext);
448 		if (err != 0)
449 			break;
450 		ASSERT(next[0] != '\0');
451 		if (next[0] == '@')
452 			break;
453 		dprintf("looking up %s in obj%lld\n",
454 		    buf, dsl_dir_phys(dd)->dd_child_dir_zapobj);
455 
456 		err = zap_lookup(dp->dp_meta_objset,
457 		    dsl_dir_phys(dd)->dd_child_dir_zapobj,
458 		    buf, sizeof (ddobj), 1, &ddobj);
459 		if (err != 0) {
460 			if (err == ENOENT)
461 				err = 0;
462 			break;
463 		}
464 
465 		err = dsl_dir_hold_obj(dp, ddobj, buf, tag, &child_dd);
466 		if (err != 0)
467 			break;
468 		dsl_dir_rele(dd, tag);
469 		dd = child_dd;
470 		next = nextnext;
471 	}
472 
473 	if (err != 0) {
474 		dsl_dir_rele(dd, tag);
475 		return (err);
476 	}
477 
478 	/*
479 	 * It's an error if there's more than one component left, or
480 	 * tailp==NULL and there's any component left.
481 	 */
482 	if (next != NULL &&
483 	    (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
484 		/* bad path name */
485 		dsl_dir_rele(dd, tag);
486 		dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
487 		err = SET_ERROR(ENOENT);
488 	}
489 	if (tailp != NULL)
490 		*tailp = next;
491 	*ddp = dd;
492 	return (err);
493 }
494 
495 /*
496  * If the counts are already initialized for this filesystem and its
497  * descendants then do nothing, otherwise initialize the counts.
498  *
499  * The counts on this filesystem, and those below, may be uninitialized due to
500  * either the use of a pre-existing pool which did not support the
501  * filesystem/snapshot limit feature, or one in which the feature had not yet
502  * been enabled.
503  *
504  * Recursively descend the filesystem tree and update the filesystem/snapshot
505  * counts on each filesystem below, then update the cumulative count on the
506  * current filesystem. If the filesystem already has a count set on it,
507  * then we know that its counts, and the counts on the filesystems below it,
508  * are already correct, so we don't have to update this filesystem.
509  */
510 static void
511 dsl_dir_init_fs_ss_count(dsl_dir_t *dd, dmu_tx_t *tx)
512 {
513 	uint64_t my_fs_cnt = 0;
514 	uint64_t my_ss_cnt = 0;
515 	dsl_pool_t *dp = dd->dd_pool;
516 	objset_t *os = dp->dp_meta_objset;
517 	zap_cursor_t *zc;
518 	zap_attribute_t *za;
519 	dsl_dataset_t *ds;
520 
521 	ASSERT(spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT));
522 	ASSERT(dsl_pool_config_held(dp));
523 	ASSERT(dmu_tx_is_syncing(tx));
524 
525 	dsl_dir_zapify(dd, tx);
526 
527 	/*
528 	 * If the filesystem count has already been initialized then we
529 	 * don't need to recurse down any further.
530 	 */
531 	if (zap_contains(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT) == 0)
532 		return;
533 
534 	zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
535 	za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
536 
537 	/* Iterate my child dirs */
538 	for (zap_cursor_init(zc, os, dsl_dir_phys(dd)->dd_child_dir_zapobj);
539 	    zap_cursor_retrieve(zc, za) == 0; zap_cursor_advance(zc)) {
540 		dsl_dir_t *chld_dd;
541 		uint64_t count;
542 
543 		VERIFY0(dsl_dir_hold_obj(dp, za->za_first_integer, NULL, FTAG,
544 		    &chld_dd));
545 
546 		/*
547 		 * Ignore hidden ($FREE, $MOS & $ORIGIN) objsets and
548 		 * temporary datasets.
549 		 */
550 		if (chld_dd->dd_myname[0] == '$' ||
551 		    chld_dd->dd_myname[0] == '%') {
552 			dsl_dir_rele(chld_dd, FTAG);
553 			continue;
554 		}
555 
556 		my_fs_cnt++;	/* count this child */
557 
558 		dsl_dir_init_fs_ss_count(chld_dd, tx);
559 
560 		VERIFY0(zap_lookup(os, chld_dd->dd_object,
561 		    DD_FIELD_FILESYSTEM_COUNT, sizeof (count), 1, &count));
562 		my_fs_cnt += count;
563 		VERIFY0(zap_lookup(os, chld_dd->dd_object,
564 		    DD_FIELD_SNAPSHOT_COUNT, sizeof (count), 1, &count));
565 		my_ss_cnt += count;
566 
567 		dsl_dir_rele(chld_dd, FTAG);
568 	}
569 	zap_cursor_fini(zc);
570 	/* Count my snapshots (we counted children's snapshots above) */
571 	VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
572 	    dsl_dir_phys(dd)->dd_head_dataset_obj, FTAG, &ds));
573 
574 	for (zap_cursor_init(zc, os, dsl_dataset_phys(ds)->ds_snapnames_zapobj);
575 	    zap_cursor_retrieve(zc, za) == 0;
576 	    zap_cursor_advance(zc)) {
577 		/* Don't count temporary snapshots */
578 		if (za->za_name[0] != '%')
579 			my_ss_cnt++;
580 	}
581 	zap_cursor_fini(zc);
582 
583 	dsl_dataset_rele(ds, FTAG);
584 
585 	kmem_free(zc, sizeof (zap_cursor_t));
586 	kmem_free(za, sizeof (zap_attribute_t));
587 
588 	/* we're in a sync task, update counts */
589 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
590 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
591 	    sizeof (my_fs_cnt), 1, &my_fs_cnt, tx));
592 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
593 	    sizeof (my_ss_cnt), 1, &my_ss_cnt, tx));
594 }
595 
596 static int
597 dsl_dir_actv_fs_ss_limit_check(void *arg, dmu_tx_t *tx)
598 {
599 	char *ddname = (char *)arg;
600 	dsl_pool_t *dp = dmu_tx_pool(tx);
601 	dsl_dataset_t *ds;
602 	dsl_dir_t *dd;
603 	int error;
604 
605 	error = dsl_dataset_hold(dp, ddname, FTAG, &ds);
606 	if (error != 0)
607 		return (error);
608 
609 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
610 		dsl_dataset_rele(ds, FTAG);
611 		return (SET_ERROR(ENOTSUP));
612 	}
613 
614 	dd = ds->ds_dir;
615 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT) &&
616 	    dsl_dir_is_zapified(dd) &&
617 	    zap_contains(dp->dp_meta_objset, dd->dd_object,
618 	    DD_FIELD_FILESYSTEM_COUNT) == 0) {
619 		dsl_dataset_rele(ds, FTAG);
620 		return (SET_ERROR(EALREADY));
621 	}
622 
623 	dsl_dataset_rele(ds, FTAG);
624 	return (0);
625 }
626 
627 static void
628 dsl_dir_actv_fs_ss_limit_sync(void *arg, dmu_tx_t *tx)
629 {
630 	char *ddname = (char *)arg;
631 	dsl_pool_t *dp = dmu_tx_pool(tx);
632 	dsl_dataset_t *ds;
633 	spa_t *spa;
634 
635 	VERIFY0(dsl_dataset_hold(dp, ddname, FTAG, &ds));
636 
637 	spa = dsl_dataset_get_spa(ds);
638 
639 	if (!spa_feature_is_active(spa, SPA_FEATURE_FS_SS_LIMIT)) {
640 		/*
641 		 * Since the feature was not active and we're now setting a
642 		 * limit, increment the feature-active counter so that the
643 		 * feature becomes active for the first time.
644 		 *
645 		 * We are already in a sync task so we can update the MOS.
646 		 */
647 		spa_feature_incr(spa, SPA_FEATURE_FS_SS_LIMIT, tx);
648 	}
649 
650 	/*
651 	 * Since we are now setting a non-UINT64_MAX limit on the filesystem,
652 	 * we need to ensure the counts are correct. Descend down the tree from
653 	 * this point and update all of the counts to be accurate.
654 	 */
655 	dsl_dir_init_fs_ss_count(ds->ds_dir, tx);
656 
657 	dsl_dataset_rele(ds, FTAG);
658 }
659 
660 /*
661  * Make sure the feature is enabled and activate it if necessary.
662  * Since we're setting a limit, ensure the on-disk counts are valid.
663  * This is only called by the ioctl path when setting a limit value.
664  *
665  * We do not need to validate the new limit, since users who can change the
666  * limit are also allowed to exceed the limit.
667  */
668 int
669 dsl_dir_activate_fs_ss_limit(const char *ddname)
670 {
671 	int error;
672 
673 	error = dsl_sync_task(ddname, dsl_dir_actv_fs_ss_limit_check,
674 	    dsl_dir_actv_fs_ss_limit_sync, (void *)ddname, 0,
675 	    ZFS_SPACE_CHECK_RESERVED);
676 
677 	if (error == EALREADY)
678 		error = 0;
679 
680 	return (error);
681 }
682 
683 /*
684  * Used to determine if the filesystem_limit or snapshot_limit should be
685  * enforced. We allow the limit to be exceeded if the user has permission to
686  * write the property value. We pass in the creds that we got in the open
687  * context since we will always be the GZ root in syncing context. We also have
688  * to handle the case where we are allowed to change the limit on the current
689  * dataset, but there may be another limit in the tree above.
690  *
691  * We can never modify these two properties within a non-global zone. In
692  * addition, the other checks are modeled on zfs_secpolicy_write_perms. We
693  * can't use that function since we are already holding the dp_config_rwlock.
694  * In addition, we already have the dd and dealing with snapshots is simplified
695  * in this code.
696  */
697 
698 typedef enum {
699 	ENFORCE_ALWAYS,
700 	ENFORCE_NEVER,
701 	ENFORCE_ABOVE
702 } enforce_res_t;
703 
704 static enforce_res_t
705 dsl_enforce_ds_ss_limits(dsl_dir_t *dd, zfs_prop_t prop, cred_t *cr)
706 {
707 	enforce_res_t enforce = ENFORCE_ALWAYS;
708 	uint64_t obj;
709 	dsl_dataset_t *ds;
710 	uint64_t zoned;
711 
712 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
713 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
714 
715 #ifdef _KERNEL
716 	if (crgetzoneid(cr) != GLOBAL_ZONEID)
717 		return (ENFORCE_ALWAYS);
718 
719 	if (secpolicy_zfs(cr) == 0)
720 		return (ENFORCE_NEVER);
721 #endif
722 
723 	if ((obj = dsl_dir_phys(dd)->dd_head_dataset_obj) == 0)
724 		return (ENFORCE_ALWAYS);
725 
726 	ASSERT(dsl_pool_config_held(dd->dd_pool));
727 
728 	if (dsl_dataset_hold_obj(dd->dd_pool, obj, FTAG, &ds) != 0)
729 		return (ENFORCE_ALWAYS);
730 
731 	if (dsl_prop_get_ds(ds, "zoned", 8, 1, &zoned, NULL) || zoned) {
732 		/* Only root can access zoned fs's from the GZ */
733 		enforce = ENFORCE_ALWAYS;
734 	} else {
735 		if (dsl_deleg_access_impl(ds, zfs_prop_to_name(prop), cr) == 0)
736 			enforce = ENFORCE_ABOVE;
737 	}
738 
739 	dsl_dataset_rele(ds, FTAG);
740 	return (enforce);
741 }
742 
743 /*
744  * Check if adding additional child filesystem(s) would exceed any filesystem
745  * limits or adding additional snapshot(s) would exceed any snapshot limits.
746  * The prop argument indicates which limit to check.
747  *
748  * Note that all filesystem limits up to the root (or the highest
749  * initialized) filesystem or the given ancestor must be satisfied.
750  */
751 int
752 dsl_fs_ss_limit_check(dsl_dir_t *dd, uint64_t delta, zfs_prop_t prop,
753     dsl_dir_t *ancestor, cred_t *cr)
754 {
755 	objset_t *os = dd->dd_pool->dp_meta_objset;
756 	uint64_t limit, count;
757 	char *count_prop;
758 	enforce_res_t enforce;
759 	int err = 0;
760 
761 	ASSERT(dsl_pool_config_held(dd->dd_pool));
762 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
763 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
764 
765 	/*
766 	 * If we're allowed to change the limit, don't enforce the limit
767 	 * e.g. this can happen if a snapshot is taken by an administrative
768 	 * user in the global zone (i.e. a recursive snapshot by root).
769 	 * However, we must handle the case of delegated permissions where we
770 	 * are allowed to change the limit on the current dataset, but there
771 	 * is another limit in the tree above.
772 	 */
773 	enforce = dsl_enforce_ds_ss_limits(dd, prop, cr);
774 	if (enforce == ENFORCE_NEVER)
775 		return (0);
776 
777 	/*
778 	 * e.g. if renaming a dataset with no snapshots, count adjustment
779 	 * is 0.
780 	 */
781 	if (delta == 0)
782 		return (0);
783 
784 	if (prop == ZFS_PROP_SNAPSHOT_LIMIT) {
785 		/*
786 		 * We don't enforce the limit for temporary snapshots. This is
787 		 * indicated by a NULL cred_t argument.
788 		 */
789 		if (cr == NULL)
790 			return (0);
791 
792 		count_prop = DD_FIELD_SNAPSHOT_COUNT;
793 	} else {
794 		count_prop = DD_FIELD_FILESYSTEM_COUNT;
795 	}
796 
797 	/*
798 	 * If an ancestor has been provided, stop checking the limit once we
799 	 * hit that dir. We need this during rename so that we don't overcount
800 	 * the check once we recurse up to the common ancestor.
801 	 */
802 	if (ancestor == dd)
803 		return (0);
804 
805 	/*
806 	 * If we hit an uninitialized node while recursing up the tree, we can
807 	 * stop since we know there is no limit here (or above). The counts are
808 	 * not valid on this node and we know we won't touch this node's counts.
809 	 */
810 	if (!dsl_dir_is_zapified(dd) || zap_lookup(os, dd->dd_object,
811 	    count_prop, sizeof (count), 1, &count) == ENOENT)
812 		return (0);
813 
814 	err = dsl_prop_get_dd(dd, zfs_prop_to_name(prop), 8, 1, &limit, NULL,
815 	    B_FALSE);
816 	if (err != 0)
817 		return (err);
818 
819 	/* Is there a limit which we've hit? */
820 	if (enforce == ENFORCE_ALWAYS && (count + delta) > limit)
821 		return (SET_ERROR(EDQUOT));
822 
823 	if (dd->dd_parent != NULL)
824 		err = dsl_fs_ss_limit_check(dd->dd_parent, delta, prop,
825 		    ancestor, cr);
826 
827 	return (err);
828 }
829 
830 /*
831  * Adjust the filesystem or snapshot count for the specified dsl_dir_t and all
832  * parents. When a new filesystem/snapshot is created, increment the count on
833  * all parents, and when a filesystem/snapshot is destroyed, decrement the
834  * count.
835  */
836 void
837 dsl_fs_ss_count_adjust(dsl_dir_t *dd, int64_t delta, const char *prop,
838     dmu_tx_t *tx)
839 {
840 	int err;
841 	objset_t *os = dd->dd_pool->dp_meta_objset;
842 	uint64_t count;
843 
844 	ASSERT(dsl_pool_config_held(dd->dd_pool));
845 	ASSERT(dmu_tx_is_syncing(tx));
846 	ASSERT(strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0 ||
847 	    strcmp(prop, DD_FIELD_SNAPSHOT_COUNT) == 0);
848 
849 	/*
850 	 * When we receive an incremental stream into a filesystem that already
851 	 * exists, a temporary clone is created.  We don't count this temporary
852 	 * clone, whose name begins with a '%'. We also ignore hidden ($FREE,
853 	 * $MOS & $ORIGIN) objsets.
854 	 */
855 	if ((dd->dd_myname[0] == '%' || dd->dd_myname[0] == '$') &&
856 	    strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0)
857 		return;
858 
859 	/*
860 	 * e.g. if renaming a dataset with no snapshots, count adjustment is 0
861 	 */
862 	if (delta == 0)
863 		return;
864 
865 	/*
866 	 * If we hit an uninitialized node while recursing up the tree, we can
867 	 * stop since we know the counts are not valid on this node and we
868 	 * know we shouldn't touch this node's counts. An uninitialized count
869 	 * on the node indicates that either the feature has not yet been
870 	 * activated or there are no limits on this part of the tree.
871 	 */
872 	if (!dsl_dir_is_zapified(dd) || (err = zap_lookup(os, dd->dd_object,
873 	    prop, sizeof (count), 1, &count)) == ENOENT)
874 		return;
875 	VERIFY0(err);
876 
877 	count += delta;
878 	/* Use a signed verify to make sure we're not neg. */
879 	VERIFY3S(count, >=, 0);
880 
881 	VERIFY0(zap_update(os, dd->dd_object, prop, sizeof (count), 1, &count,
882 	    tx));
883 
884 	/* Roll up this additional count into our ancestors */
885 	if (dd->dd_parent != NULL)
886 		dsl_fs_ss_count_adjust(dd->dd_parent, delta, prop, tx);
887 }
888 
889 uint64_t
890 dsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
891     dmu_tx_t *tx)
892 {
893 	objset_t *mos = dp->dp_meta_objset;
894 	uint64_t ddobj;
895 	dsl_dir_phys_t *ddphys;
896 	dmu_buf_t *dbuf;
897 
898 	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
899 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
900 	if (pds) {
901 		VERIFY(0 == zap_add(mos, dsl_dir_phys(pds)->dd_child_dir_zapobj,
902 		    name, sizeof (uint64_t), 1, &ddobj, tx));
903 	} else {
904 		/* it's the root dir */
905 		VERIFY(0 == zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
906 		    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
907 	}
908 	VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
909 	dmu_buf_will_dirty(dbuf, tx);
910 	ddphys = dbuf->db_data;
911 
912 	ddphys->dd_creation_time = gethrestime_sec();
913 	if (pds) {
914 		ddphys->dd_parent_obj = pds->dd_object;
915 
916 		/* update the filesystem counts */
917 		dsl_fs_ss_count_adjust(pds, 1, DD_FIELD_FILESYSTEM_COUNT, tx);
918 	}
919 	ddphys->dd_props_zapobj = zap_create(mos,
920 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
921 	ddphys->dd_child_dir_zapobj = zap_create(mos,
922 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
923 	if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
924 		ddphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
925 	dmu_buf_rele(dbuf, FTAG);
926 
927 	return (ddobj);
928 }
929 
930 boolean_t
931 dsl_dir_is_clone(dsl_dir_t *dd)
932 {
933 	return (dsl_dir_phys(dd)->dd_origin_obj &&
934 	    (dd->dd_pool->dp_origin_snap == NULL ||
935 	    dsl_dir_phys(dd)->dd_origin_obj !=
936 	    dd->dd_pool->dp_origin_snap->ds_object));
937 }
938 
939 void
940 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
941 {
942 	mutex_enter(&dd->dd_lock);
943 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
944 	    dsl_dir_phys(dd)->dd_used_bytes);
945 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA,
946 	    dsl_dir_phys(dd)->dd_quota);
947 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
948 	    dsl_dir_phys(dd)->dd_reserved);
949 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
950 	    dsl_dir_phys(dd)->dd_compressed_bytes == 0 ? 100 :
951 	    (dsl_dir_phys(dd)->dd_uncompressed_bytes * 100 /
952 	    dsl_dir_phys(dd)->dd_compressed_bytes));
953 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALUSED,
954 	    dsl_dir_phys(dd)->dd_uncompressed_bytes);
955 	if (dsl_dir_phys(dd)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
956 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
957 		    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP]);
958 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
959 		    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_HEAD]);
960 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
961 		    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_REFRSRV]);
962 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
963 		    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_CHILD] +
964 		    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_CHILD_RSRV]);
965 	}
966 	mutex_exit(&dd->dd_lock);
967 
968 	if (dsl_dir_is_zapified(dd)) {
969 		uint64_t count;
970 		objset_t *os = dd->dd_pool->dp_meta_objset;
971 
972 		if (zap_lookup(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
973 		    sizeof (count), 1, &count) == 0) {
974 			dsl_prop_nvlist_add_uint64(nv,
975 			    ZFS_PROP_FILESYSTEM_COUNT, count);
976 		}
977 		if (zap_lookup(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
978 		    sizeof (count), 1, &count) == 0) {
979 			dsl_prop_nvlist_add_uint64(nv,
980 			    ZFS_PROP_SNAPSHOT_COUNT, count);
981 		}
982 	}
983 
984 	if (dsl_dir_is_clone(dd)) {
985 		dsl_dataset_t *ds;
986 		char buf[ZFS_MAX_DATASET_NAME_LEN];
987 
988 		VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
989 		    dsl_dir_phys(dd)->dd_origin_obj, FTAG, &ds));
990 		dsl_dataset_name(ds, buf);
991 		dsl_dataset_rele(ds, FTAG);
992 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
993 	}
994 }
995 
996 void
997 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
998 {
999 	dsl_pool_t *dp = dd->dd_pool;
1000 
1001 	ASSERT(dsl_dir_phys(dd));
1002 
1003 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg)) {
1004 		/* up the hold count until we can be written out */
1005 		dmu_buf_add_ref(dd->dd_dbuf, dd);
1006 	}
1007 }
1008 
1009 static int64_t
1010 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
1011 {
1012 	uint64_t old_accounted = MAX(used, dsl_dir_phys(dd)->dd_reserved);
1013 	uint64_t new_accounted =
1014 	    MAX(used + delta, dsl_dir_phys(dd)->dd_reserved);
1015 	return (new_accounted - old_accounted);
1016 }
1017 
1018 void
1019 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
1020 {
1021 	ASSERT(dmu_tx_is_syncing(tx));
1022 
1023 	mutex_enter(&dd->dd_lock);
1024 	ASSERT0(dd->dd_tempreserved[tx->tx_txg&TXG_MASK]);
1025 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
1026 	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
1027 	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
1028 	mutex_exit(&dd->dd_lock);
1029 
1030 	/* release the hold from dsl_dir_dirty */
1031 	dmu_buf_rele(dd->dd_dbuf, dd);
1032 }
1033 
1034 static uint64_t
1035 dsl_dir_space_towrite(dsl_dir_t *dd)
1036 {
1037 	uint64_t space = 0;
1038 	int i;
1039 
1040 	ASSERT(MUTEX_HELD(&dd->dd_lock));
1041 
1042 	for (i = 0; i < TXG_SIZE; i++) {
1043 		space += dd->dd_space_towrite[i&TXG_MASK];
1044 		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
1045 	}
1046 	return (space);
1047 }
1048 
1049 /*
1050  * How much space would dd have available if ancestor had delta applied
1051  * to it?  If ondiskonly is set, we're only interested in what's
1052  * on-disk, not estimated pending changes.
1053  */
1054 uint64_t
1055 dsl_dir_space_available(dsl_dir_t *dd,
1056     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
1057 {
1058 	uint64_t parentspace, myspace, quota, used;
1059 
1060 	/*
1061 	 * If there are no restrictions otherwise, assume we have
1062 	 * unlimited space available.
1063 	 */
1064 	quota = UINT64_MAX;
1065 	parentspace = UINT64_MAX;
1066 
1067 	if (dd->dd_parent != NULL) {
1068 		parentspace = dsl_dir_space_available(dd->dd_parent,
1069 		    ancestor, delta, ondiskonly);
1070 	}
1071 
1072 	mutex_enter(&dd->dd_lock);
1073 	if (dsl_dir_phys(dd)->dd_quota != 0)
1074 		quota = dsl_dir_phys(dd)->dd_quota;
1075 	used = dsl_dir_phys(dd)->dd_used_bytes;
1076 	if (!ondiskonly)
1077 		used += dsl_dir_space_towrite(dd);
1078 
1079 	if (dd->dd_parent == NULL) {
1080 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
1081 		quota = MIN(quota, poolsize);
1082 	}
1083 
1084 	if (dsl_dir_phys(dd)->dd_reserved > used && parentspace != UINT64_MAX) {
1085 		/*
1086 		 * We have some space reserved, in addition to what our
1087 		 * parent gave us.
1088 		 */
1089 		parentspace += dsl_dir_phys(dd)->dd_reserved - used;
1090 	}
1091 
1092 	if (dd == ancestor) {
1093 		ASSERT(delta <= 0);
1094 		ASSERT(used >= -delta);
1095 		used += delta;
1096 		if (parentspace != UINT64_MAX)
1097 			parentspace -= delta;
1098 	}
1099 
1100 	if (used > quota) {
1101 		/* over quota */
1102 		myspace = 0;
1103 	} else {
1104 		/*
1105 		 * the lesser of the space provided by our parent and
1106 		 * the space left in our quota
1107 		 */
1108 		myspace = MIN(parentspace, quota - used);
1109 	}
1110 
1111 	mutex_exit(&dd->dd_lock);
1112 
1113 	return (myspace);
1114 }
1115 
1116 struct tempreserve {
1117 	list_node_t tr_node;
1118 	dsl_dir_t *tr_ds;
1119 	uint64_t tr_size;
1120 };
1121 
1122 static int
1123 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
1124     boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
1125     dmu_tx_t *tx, boolean_t first)
1126 {
1127 	uint64_t txg = tx->tx_txg;
1128 	uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
1129 	uint64_t deferred = 0;
1130 	struct tempreserve *tr;
1131 	int retval = EDQUOT;
1132 	int txgidx = txg & TXG_MASK;
1133 	int i;
1134 	uint64_t ref_rsrv = 0;
1135 
1136 	ASSERT3U(txg, !=, 0);
1137 	ASSERT3S(asize, >, 0);
1138 
1139 	mutex_enter(&dd->dd_lock);
1140 
1141 	/*
1142 	 * Check against the dsl_dir's quota.  We don't add in the delta
1143 	 * when checking for over-quota because they get one free hit.
1144 	 */
1145 	est_inflight = dsl_dir_space_towrite(dd);
1146 	for (i = 0; i < TXG_SIZE; i++)
1147 		est_inflight += dd->dd_tempreserved[i];
1148 	used_on_disk = dsl_dir_phys(dd)->dd_used_bytes;
1149 
1150 	/*
1151 	 * On the first iteration, fetch the dataset's used-on-disk and
1152 	 * refreservation values. Also, if checkrefquota is set, test if
1153 	 * allocating this space would exceed the dataset's refquota.
1154 	 */
1155 	if (first && tx->tx_objset) {
1156 		int error;
1157 		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
1158 
1159 		error = dsl_dataset_check_quota(ds, checkrefquota,
1160 		    asize, est_inflight, &used_on_disk, &ref_rsrv);
1161 		if (error) {
1162 			mutex_exit(&dd->dd_lock);
1163 			return (error);
1164 		}
1165 	}
1166 
1167 	/*
1168 	 * If this transaction will result in a net free of space,
1169 	 * we want to let it through.
1170 	 */
1171 	if (ignorequota || netfree || dsl_dir_phys(dd)->dd_quota == 0)
1172 		quota = UINT64_MAX;
1173 	else
1174 		quota = dsl_dir_phys(dd)->dd_quota;
1175 
1176 	/*
1177 	 * Adjust the quota against the actual pool size at the root
1178 	 * minus any outstanding deferred frees.
1179 	 * To ensure that it's possible to remove files from a full
1180 	 * pool without inducing transient overcommits, we throttle
1181 	 * netfree transactions against a quota that is slightly larger,
1182 	 * but still within the pool's allocation slop.  In cases where
1183 	 * we're very close to full, this will allow a steady trickle of
1184 	 * removes to get through.
1185 	 */
1186 	if (dd->dd_parent == NULL) {
1187 		spa_t *spa = dd->dd_pool->dp_spa;
1188 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
1189 		deferred = metaslab_class_get_deferred(spa_normal_class(spa));
1190 		if (poolsize - deferred < quota) {
1191 			quota = poolsize - deferred;
1192 			retval = ENOSPC;
1193 		}
1194 	}
1195 
1196 	/*
1197 	 * If they are requesting more space, and our current estimate
1198 	 * is over quota, they get to try again unless the actual
1199 	 * on-disk is over quota and there are no pending changes (which
1200 	 * may free up space for us).
1201 	 */
1202 	if (used_on_disk + est_inflight >= quota) {
1203 		if (est_inflight > early_edquot_threshold ||
1204 		    used_on_disk + early_edquot_threshold < quota ||
1205 		    (retval == ENOSPC && used_on_disk < quota + deferred))
1206 			retval = ERESTART;
1207 		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
1208 		    "quota=%lluK tr=%lluK err=%d\n",
1209 		    used_on_disk>>10, est_inflight>>10,
1210 		    quota>>10, asize>>10, retval);
1211 		mutex_exit(&dd->dd_lock);
1212 		return (SET_ERROR(retval));
1213 	}
1214 
1215 	/* We need to up our estimated delta before dropping dd_lock */
1216 	dd->dd_tempreserved[txgidx] += asize;
1217 
1218 	parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
1219 	    asize - ref_rsrv);
1220 	mutex_exit(&dd->dd_lock);
1221 
1222 	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1223 	tr->tr_ds = dd;
1224 	tr->tr_size = asize;
1225 	list_insert_tail(tr_list, tr);
1226 
1227 	/* see if it's OK with our parent */
1228 	if (dd->dd_parent && parent_rsrv) {
1229 		boolean_t ismos = (dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
1230 
1231 		return (dsl_dir_tempreserve_impl(dd->dd_parent,
1232 		    parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
1233 	} else {
1234 		return (0);
1235 	}
1236 }
1237 
1238 /*
1239  * Reserve space in this dsl_dir, to be used in this tx's txg.
1240  * After the space has been dirtied (and dsl_dir_willuse_space()
1241  * has been called), the reservation should be canceled, using
1242  * dsl_dir_tempreserve_clear().
1243  */
1244 int
1245 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
1246     uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
1247 {
1248 	int err;
1249 	list_t *tr_list;
1250 
1251 	if (asize == 0) {
1252 		*tr_cookiep = NULL;
1253 		return (0);
1254 	}
1255 
1256 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
1257 	list_create(tr_list, sizeof (struct tempreserve),
1258 	    offsetof(struct tempreserve, tr_node));
1259 	ASSERT3S(asize, >, 0);
1260 	ASSERT3S(fsize, >=, 0);
1261 
1262 	err = arc_tempreserve_space(lsize, tx->tx_txg);
1263 	if (err == 0) {
1264 		struct tempreserve *tr;
1265 
1266 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1267 		tr->tr_size = lsize;
1268 		list_insert_tail(tr_list, tr);
1269 	} else {
1270 		if (err == EAGAIN) {
1271 			/*
1272 			 * If arc_memory_throttle() detected that pageout
1273 			 * is running and we are low on memory, we delay new
1274 			 * non-pageout transactions to give pageout an
1275 			 * advantage.
1276 			 *
1277 			 * It is unfortunate to be delaying while the caller's
1278 			 * locks are held.
1279 			 */
1280 			txg_delay(dd->dd_pool, tx->tx_txg,
1281 			    MSEC2NSEC(10), MSEC2NSEC(10));
1282 			err = SET_ERROR(ERESTART);
1283 		}
1284 	}
1285 
1286 	if (err == 0) {
1287 		err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
1288 		    FALSE, asize > usize, tr_list, tx, TRUE);
1289 	}
1290 
1291 	if (err != 0)
1292 		dsl_dir_tempreserve_clear(tr_list, tx);
1293 	else
1294 		*tr_cookiep = tr_list;
1295 
1296 	return (err);
1297 }
1298 
1299 /*
1300  * Clear a temporary reservation that we previously made with
1301  * dsl_dir_tempreserve_space().
1302  */
1303 void
1304 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
1305 {
1306 	int txgidx = tx->tx_txg & TXG_MASK;
1307 	list_t *tr_list = tr_cookie;
1308 	struct tempreserve *tr;
1309 
1310 	ASSERT3U(tx->tx_txg, !=, 0);
1311 
1312 	if (tr_cookie == NULL)
1313 		return;
1314 
1315 	while ((tr = list_head(tr_list)) != NULL) {
1316 		if (tr->tr_ds) {
1317 			mutex_enter(&tr->tr_ds->dd_lock);
1318 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
1319 			    tr->tr_size);
1320 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
1321 			mutex_exit(&tr->tr_ds->dd_lock);
1322 		} else {
1323 			arc_tempreserve_clear(tr->tr_size);
1324 		}
1325 		list_remove(tr_list, tr);
1326 		kmem_free(tr, sizeof (struct tempreserve));
1327 	}
1328 
1329 	kmem_free(tr_list, sizeof (list_t));
1330 }
1331 
1332 /*
1333  * This should be called from open context when we think we're going to write
1334  * or free space, for example when dirtying data. Be conservative; it's okay
1335  * to write less space or free more, but we don't want to write more or free
1336  * less than the amount specified.
1337  */
1338 void
1339 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
1340 {
1341 	int64_t parent_space;
1342 	uint64_t est_used;
1343 
1344 	mutex_enter(&dd->dd_lock);
1345 	if (space > 0)
1346 		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
1347 
1348 	est_used = dsl_dir_space_towrite(dd) + dsl_dir_phys(dd)->dd_used_bytes;
1349 	parent_space = parent_delta(dd, est_used, space);
1350 	mutex_exit(&dd->dd_lock);
1351 
1352 	/* Make sure that we clean up dd_space_to* */
1353 	dsl_dir_dirty(dd, tx);
1354 
1355 	/* XXX this is potentially expensive and unnecessary... */
1356 	if (parent_space && dd->dd_parent)
1357 		dsl_dir_willuse_space(dd->dd_parent, parent_space, tx);
1358 }
1359 
1360 /* call from syncing context when we actually write/free space for this dd */
1361 void
1362 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
1363     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
1364 {
1365 	int64_t accounted_delta;
1366 
1367 	/*
1368 	 * dsl_dataset_set_refreservation_sync_impl() calls this with
1369 	 * dd_lock held, so that it can atomically update
1370 	 * ds->ds_reserved and the dsl_dir accounting, so that
1371 	 * dsl_dataset_check_quota() can see dataset and dir accounting
1372 	 * consistently.
1373 	 */
1374 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
1375 
1376 	ASSERT(dmu_tx_is_syncing(tx));
1377 	ASSERT(type < DD_USED_NUM);
1378 
1379 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1380 
1381 	if (needlock)
1382 		mutex_enter(&dd->dd_lock);
1383 	accounted_delta =
1384 	    parent_delta(dd, dsl_dir_phys(dd)->dd_used_bytes, used);
1385 	ASSERT(used >= 0 || dsl_dir_phys(dd)->dd_used_bytes >= -used);
1386 	ASSERT(compressed >= 0 ||
1387 	    dsl_dir_phys(dd)->dd_compressed_bytes >= -compressed);
1388 	ASSERT(uncompressed >= 0 ||
1389 	    dsl_dir_phys(dd)->dd_uncompressed_bytes >= -uncompressed);
1390 	dsl_dir_phys(dd)->dd_used_bytes += used;
1391 	dsl_dir_phys(dd)->dd_uncompressed_bytes += uncompressed;
1392 	dsl_dir_phys(dd)->dd_compressed_bytes += compressed;
1393 
1394 	if (dsl_dir_phys(dd)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1395 		ASSERT(used > 0 ||
1396 		    dsl_dir_phys(dd)->dd_used_breakdown[type] >= -used);
1397 		dsl_dir_phys(dd)->dd_used_breakdown[type] += used;
1398 #ifdef DEBUG
1399 		dd_used_t t;
1400 		uint64_t u = 0;
1401 		for (t = 0; t < DD_USED_NUM; t++)
1402 			u += dsl_dir_phys(dd)->dd_used_breakdown[t];
1403 		ASSERT3U(u, ==, dsl_dir_phys(dd)->dd_used_bytes);
1404 #endif
1405 	}
1406 	if (needlock)
1407 		mutex_exit(&dd->dd_lock);
1408 
1409 	if (dd->dd_parent != NULL) {
1410 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1411 		    accounted_delta, compressed, uncompressed, tx);
1412 		dsl_dir_transfer_space(dd->dd_parent,
1413 		    used - accounted_delta,
1414 		    DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
1415 	}
1416 }
1417 
1418 void
1419 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
1420     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
1421 {
1422 	ASSERT(dmu_tx_is_syncing(tx));
1423 	ASSERT(oldtype < DD_USED_NUM);
1424 	ASSERT(newtype < DD_USED_NUM);
1425 
1426 	if (delta == 0 ||
1427 	    !(dsl_dir_phys(dd)->dd_flags & DD_FLAG_USED_BREAKDOWN))
1428 		return;
1429 
1430 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1431 	mutex_enter(&dd->dd_lock);
1432 	ASSERT(delta > 0 ?
1433 	    dsl_dir_phys(dd)->dd_used_breakdown[oldtype] >= delta :
1434 	    dsl_dir_phys(dd)->dd_used_breakdown[newtype] >= -delta);
1435 	ASSERT(dsl_dir_phys(dd)->dd_used_bytes >= ABS(delta));
1436 	dsl_dir_phys(dd)->dd_used_breakdown[oldtype] -= delta;
1437 	dsl_dir_phys(dd)->dd_used_breakdown[newtype] += delta;
1438 	mutex_exit(&dd->dd_lock);
1439 }
1440 
1441 typedef struct dsl_dir_set_qr_arg {
1442 	const char *ddsqra_name;
1443 	zprop_source_t ddsqra_source;
1444 	uint64_t ddsqra_value;
1445 } dsl_dir_set_qr_arg_t;
1446 
1447 static int
1448 dsl_dir_set_quota_check(void *arg, dmu_tx_t *tx)
1449 {
1450 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1451 	dsl_pool_t *dp = dmu_tx_pool(tx);
1452 	dsl_dataset_t *ds;
1453 	int error;
1454 	uint64_t towrite, newval;
1455 
1456 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1457 	if (error != 0)
1458 		return (error);
1459 
1460 	error = dsl_prop_predict(ds->ds_dir, "quota",
1461 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1462 	if (error != 0) {
1463 		dsl_dataset_rele(ds, FTAG);
1464 		return (error);
1465 	}
1466 
1467 	if (newval == 0) {
1468 		dsl_dataset_rele(ds, FTAG);
1469 		return (0);
1470 	}
1471 
1472 	mutex_enter(&ds->ds_dir->dd_lock);
1473 	/*
1474 	 * If we are doing the preliminary check in open context, and
1475 	 * there are pending changes, then don't fail it, since the
1476 	 * pending changes could under-estimate the amount of space to be
1477 	 * freed up.
1478 	 */
1479 	towrite = dsl_dir_space_towrite(ds->ds_dir);
1480 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1481 	    (newval < dsl_dir_phys(ds->ds_dir)->dd_reserved ||
1482 	    newval < dsl_dir_phys(ds->ds_dir)->dd_used_bytes + towrite)) {
1483 		error = SET_ERROR(ENOSPC);
1484 	}
1485 	mutex_exit(&ds->ds_dir->dd_lock);
1486 	dsl_dataset_rele(ds, FTAG);
1487 	return (error);
1488 }
1489 
1490 static void
1491 dsl_dir_set_quota_sync(void *arg, dmu_tx_t *tx)
1492 {
1493 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1494 	dsl_pool_t *dp = dmu_tx_pool(tx);
1495 	dsl_dataset_t *ds;
1496 	uint64_t newval;
1497 
1498 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1499 
1500 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1501 		dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_QUOTA),
1502 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1503 		    &ddsqra->ddsqra_value, tx);
1504 
1505 		VERIFY0(dsl_prop_get_int_ds(ds,
1506 		    zfs_prop_to_name(ZFS_PROP_QUOTA), &newval));
1507 	} else {
1508 		newval = ddsqra->ddsqra_value;
1509 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1510 		    zfs_prop_to_name(ZFS_PROP_QUOTA), (longlong_t)newval);
1511 	}
1512 
1513 	dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1514 	mutex_enter(&ds->ds_dir->dd_lock);
1515 	dsl_dir_phys(ds->ds_dir)->dd_quota = newval;
1516 	mutex_exit(&ds->ds_dir->dd_lock);
1517 	dsl_dataset_rele(ds, FTAG);
1518 }
1519 
1520 int
1521 dsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1522 {
1523 	dsl_dir_set_qr_arg_t ddsqra;
1524 
1525 	ddsqra.ddsqra_name = ddname;
1526 	ddsqra.ddsqra_source = source;
1527 	ddsqra.ddsqra_value = quota;
1528 
1529 	return (dsl_sync_task(ddname, dsl_dir_set_quota_check,
1530 	    dsl_dir_set_quota_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
1531 }
1532 
1533 int
1534 dsl_dir_set_reservation_check(void *arg, dmu_tx_t *tx)
1535 {
1536 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1537 	dsl_pool_t *dp = dmu_tx_pool(tx);
1538 	dsl_dataset_t *ds;
1539 	dsl_dir_t *dd;
1540 	uint64_t newval, used, avail;
1541 	int error;
1542 
1543 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1544 	if (error != 0)
1545 		return (error);
1546 	dd = ds->ds_dir;
1547 
1548 	/*
1549 	 * If we are doing the preliminary check in open context, the
1550 	 * space estimates may be inaccurate.
1551 	 */
1552 	if (!dmu_tx_is_syncing(tx)) {
1553 		dsl_dataset_rele(ds, FTAG);
1554 		return (0);
1555 	}
1556 
1557 	error = dsl_prop_predict(ds->ds_dir,
1558 	    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1559 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1560 	if (error != 0) {
1561 		dsl_dataset_rele(ds, FTAG);
1562 		return (error);
1563 	}
1564 
1565 	mutex_enter(&dd->dd_lock);
1566 	used = dsl_dir_phys(dd)->dd_used_bytes;
1567 	mutex_exit(&dd->dd_lock);
1568 
1569 	if (dd->dd_parent) {
1570 		avail = dsl_dir_space_available(dd->dd_parent,
1571 		    NULL, 0, FALSE);
1572 	} else {
1573 		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1574 	}
1575 
1576 	if (MAX(used, newval) > MAX(used, dsl_dir_phys(dd)->dd_reserved)) {
1577 		uint64_t delta = MAX(used, newval) -
1578 		    MAX(used, dsl_dir_phys(dd)->dd_reserved);
1579 
1580 		if (delta > avail ||
1581 		    (dsl_dir_phys(dd)->dd_quota > 0 &&
1582 		    newval > dsl_dir_phys(dd)->dd_quota))
1583 			error = SET_ERROR(ENOSPC);
1584 	}
1585 
1586 	dsl_dataset_rele(ds, FTAG);
1587 	return (error);
1588 }
1589 
1590 void
1591 dsl_dir_set_reservation_sync_impl(dsl_dir_t *dd, uint64_t value, dmu_tx_t *tx)
1592 {
1593 	uint64_t used;
1594 	int64_t delta;
1595 
1596 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1597 
1598 	mutex_enter(&dd->dd_lock);
1599 	used = dsl_dir_phys(dd)->dd_used_bytes;
1600 	delta = MAX(used, value) - MAX(used, dsl_dir_phys(dd)->dd_reserved);
1601 	dsl_dir_phys(dd)->dd_reserved = value;
1602 
1603 	if (dd->dd_parent != NULL) {
1604 		/* Roll up this additional usage into our ancestors */
1605 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1606 		    delta, 0, 0, tx);
1607 	}
1608 	mutex_exit(&dd->dd_lock);
1609 }
1610 
1611 
1612 static void
1613 dsl_dir_set_reservation_sync(void *arg, dmu_tx_t *tx)
1614 {
1615 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1616 	dsl_pool_t *dp = dmu_tx_pool(tx);
1617 	dsl_dataset_t *ds;
1618 	uint64_t newval;
1619 
1620 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1621 
1622 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1623 		dsl_prop_set_sync_impl(ds,
1624 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1625 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1626 		    &ddsqra->ddsqra_value, tx);
1627 
1628 		VERIFY0(dsl_prop_get_int_ds(ds,
1629 		    zfs_prop_to_name(ZFS_PROP_RESERVATION), &newval));
1630 	} else {
1631 		newval = ddsqra->ddsqra_value;
1632 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1633 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1634 		    (longlong_t)newval);
1635 	}
1636 
1637 	dsl_dir_set_reservation_sync_impl(ds->ds_dir, newval, tx);
1638 	dsl_dataset_rele(ds, FTAG);
1639 }
1640 
1641 int
1642 dsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1643     uint64_t reservation)
1644 {
1645 	dsl_dir_set_qr_arg_t ddsqra;
1646 
1647 	ddsqra.ddsqra_name = ddname;
1648 	ddsqra.ddsqra_source = source;
1649 	ddsqra.ddsqra_value = reservation;
1650 
1651 	return (dsl_sync_task(ddname, dsl_dir_set_reservation_check,
1652 	    dsl_dir_set_reservation_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
1653 }
1654 
1655 static dsl_dir_t *
1656 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1657 {
1658 	for (; ds1; ds1 = ds1->dd_parent) {
1659 		dsl_dir_t *dd;
1660 		for (dd = ds2; dd; dd = dd->dd_parent) {
1661 			if (ds1 == dd)
1662 				return (dd);
1663 		}
1664 	}
1665 	return (NULL);
1666 }
1667 
1668 /*
1669  * If delta is applied to dd, how much of that delta would be applied to
1670  * ancestor?  Syncing context only.
1671  */
1672 static int64_t
1673 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1674 {
1675 	if (dd == ancestor)
1676 		return (delta);
1677 
1678 	mutex_enter(&dd->dd_lock);
1679 	delta = parent_delta(dd, dsl_dir_phys(dd)->dd_used_bytes, delta);
1680 	mutex_exit(&dd->dd_lock);
1681 	return (would_change(dd->dd_parent, delta, ancestor));
1682 }
1683 
1684 typedef struct dsl_dir_rename_arg {
1685 	const char *ddra_oldname;
1686 	const char *ddra_newname;
1687 	cred_t *ddra_cred;
1688 } dsl_dir_rename_arg_t;
1689 
1690 /* ARGSUSED */
1691 static int
1692 dsl_valid_rename(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1693 {
1694 	int *deltap = arg;
1695 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
1696 
1697 	dsl_dataset_name(ds, namebuf);
1698 
1699 	if (strlen(namebuf) + *deltap >= ZFS_MAX_DATASET_NAME_LEN)
1700 		return (SET_ERROR(ENAMETOOLONG));
1701 	return (0);
1702 }
1703 
1704 static int
1705 dsl_dir_rename_check(void *arg, dmu_tx_t *tx)
1706 {
1707 	dsl_dir_rename_arg_t *ddra = arg;
1708 	dsl_pool_t *dp = dmu_tx_pool(tx);
1709 	dsl_dir_t *dd, *newparent;
1710 	const char *mynewname;
1711 	int error;
1712 	int delta = strlen(ddra->ddra_newname) - strlen(ddra->ddra_oldname);
1713 
1714 	/* target dir should exist */
1715 	error = dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL);
1716 	if (error != 0)
1717 		return (error);
1718 
1719 	/* new parent should exist */
1720 	error = dsl_dir_hold(dp, ddra->ddra_newname, FTAG,
1721 	    &newparent, &mynewname);
1722 	if (error != 0) {
1723 		dsl_dir_rele(dd, FTAG);
1724 		return (error);
1725 	}
1726 
1727 	/* can't rename to different pool */
1728 	if (dd->dd_pool != newparent->dd_pool) {
1729 		dsl_dir_rele(newparent, FTAG);
1730 		dsl_dir_rele(dd, FTAG);
1731 		return (SET_ERROR(ENXIO));
1732 	}
1733 
1734 	/* new name should not already exist */
1735 	if (mynewname == NULL) {
1736 		dsl_dir_rele(newparent, FTAG);
1737 		dsl_dir_rele(dd, FTAG);
1738 		return (SET_ERROR(EEXIST));
1739 	}
1740 
1741 	/* if the name length is growing, validate child name lengths */
1742 	if (delta > 0) {
1743 		error = dmu_objset_find_dp(dp, dd->dd_object, dsl_valid_rename,
1744 		    &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1745 		if (error != 0) {
1746 			dsl_dir_rele(newparent, FTAG);
1747 			dsl_dir_rele(dd, FTAG);
1748 			return (error);
1749 		}
1750 	}
1751 
1752 	if (dmu_tx_is_syncing(tx)) {
1753 		if (spa_feature_is_active(dp->dp_spa,
1754 		    SPA_FEATURE_FS_SS_LIMIT)) {
1755 			/*
1756 			 * Although this is the check function and we don't
1757 			 * normally make on-disk changes in check functions,
1758 			 * we need to do that here.
1759 			 *
1760 			 * Ensure this portion of the tree's counts have been
1761 			 * initialized in case the new parent has limits set.
1762 			 */
1763 			dsl_dir_init_fs_ss_count(dd, tx);
1764 		}
1765 	}
1766 
1767 	if (newparent != dd->dd_parent) {
1768 		/* is there enough space? */
1769 		uint64_t myspace =
1770 		    MAX(dsl_dir_phys(dd)->dd_used_bytes,
1771 		    dsl_dir_phys(dd)->dd_reserved);
1772 		objset_t *os = dd->dd_pool->dp_meta_objset;
1773 		uint64_t fs_cnt = 0;
1774 		uint64_t ss_cnt = 0;
1775 
1776 		if (dsl_dir_is_zapified(dd)) {
1777 			int err;
1778 
1779 			err = zap_lookup(os, dd->dd_object,
1780 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1781 			    &fs_cnt);
1782 			if (err != ENOENT && err != 0) {
1783 				dsl_dir_rele(newparent, FTAG);
1784 				dsl_dir_rele(dd, FTAG);
1785 				return (err);
1786 			}
1787 
1788 			/*
1789 			 * have to add 1 for the filesystem itself that we're
1790 			 * moving
1791 			 */
1792 			fs_cnt++;
1793 
1794 			err = zap_lookup(os, dd->dd_object,
1795 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1796 			    &ss_cnt);
1797 			if (err != ENOENT && err != 0) {
1798 				dsl_dir_rele(newparent, FTAG);
1799 				dsl_dir_rele(dd, FTAG);
1800 				return (err);
1801 			}
1802 		}
1803 
1804 		/* no rename into our descendant */
1805 		if (closest_common_ancestor(dd, newparent) == dd) {
1806 			dsl_dir_rele(newparent, FTAG);
1807 			dsl_dir_rele(dd, FTAG);
1808 			return (SET_ERROR(EINVAL));
1809 		}
1810 
1811 		error = dsl_dir_transfer_possible(dd->dd_parent,
1812 		    newparent, fs_cnt, ss_cnt, myspace, ddra->ddra_cred);
1813 		if (error != 0) {
1814 			dsl_dir_rele(newparent, FTAG);
1815 			dsl_dir_rele(dd, FTAG);
1816 			return (error);
1817 		}
1818 	}
1819 
1820 	dsl_dir_rele(newparent, FTAG);
1821 	dsl_dir_rele(dd, FTAG);
1822 	return (0);
1823 }
1824 
1825 static void
1826 dsl_dir_rename_sync(void *arg, dmu_tx_t *tx)
1827 {
1828 	dsl_dir_rename_arg_t *ddra = arg;
1829 	dsl_pool_t *dp = dmu_tx_pool(tx);
1830 	dsl_dir_t *dd, *newparent;
1831 	const char *mynewname;
1832 	int error;
1833 	objset_t *mos = dp->dp_meta_objset;
1834 
1835 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL));
1836 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_newname, FTAG, &newparent,
1837 	    &mynewname));
1838 
1839 	/* Log this before we change the name. */
1840 	spa_history_log_internal_dd(dd, "rename", tx,
1841 	    "-> %s", ddra->ddra_newname);
1842 
1843 	if (newparent != dd->dd_parent) {
1844 		objset_t *os = dd->dd_pool->dp_meta_objset;
1845 		uint64_t fs_cnt = 0;
1846 		uint64_t ss_cnt = 0;
1847 
1848 		/*
1849 		 * We already made sure the dd counts were initialized in the
1850 		 * check function.
1851 		 */
1852 		if (spa_feature_is_active(dp->dp_spa,
1853 		    SPA_FEATURE_FS_SS_LIMIT)) {
1854 			VERIFY0(zap_lookup(os, dd->dd_object,
1855 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1856 			    &fs_cnt));
1857 			/* add 1 for the filesystem itself that we're moving */
1858 			fs_cnt++;
1859 
1860 			VERIFY0(zap_lookup(os, dd->dd_object,
1861 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1862 			    &ss_cnt));
1863 		}
1864 
1865 		dsl_fs_ss_count_adjust(dd->dd_parent, -fs_cnt,
1866 		    DD_FIELD_FILESYSTEM_COUNT, tx);
1867 		dsl_fs_ss_count_adjust(newparent, fs_cnt,
1868 		    DD_FIELD_FILESYSTEM_COUNT, tx);
1869 
1870 		dsl_fs_ss_count_adjust(dd->dd_parent, -ss_cnt,
1871 		    DD_FIELD_SNAPSHOT_COUNT, tx);
1872 		dsl_fs_ss_count_adjust(newparent, ss_cnt,
1873 		    DD_FIELD_SNAPSHOT_COUNT, tx);
1874 
1875 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1876 		    -dsl_dir_phys(dd)->dd_used_bytes,
1877 		    -dsl_dir_phys(dd)->dd_compressed_bytes,
1878 		    -dsl_dir_phys(dd)->dd_uncompressed_bytes, tx);
1879 		dsl_dir_diduse_space(newparent, DD_USED_CHILD,
1880 		    dsl_dir_phys(dd)->dd_used_bytes,
1881 		    dsl_dir_phys(dd)->dd_compressed_bytes,
1882 		    dsl_dir_phys(dd)->dd_uncompressed_bytes, tx);
1883 
1884 		if (dsl_dir_phys(dd)->dd_reserved >
1885 		    dsl_dir_phys(dd)->dd_used_bytes) {
1886 			uint64_t unused_rsrv = dsl_dir_phys(dd)->dd_reserved -
1887 			    dsl_dir_phys(dd)->dd_used_bytes;
1888 
1889 			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1890 			    -unused_rsrv, 0, 0, tx);
1891 			dsl_dir_diduse_space(newparent, DD_USED_CHILD_RSRV,
1892 			    unused_rsrv, 0, 0, tx);
1893 		}
1894 	}
1895 
1896 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1897 
1898 	/* remove from old parent zapobj */
1899 	error = zap_remove(mos,
1900 	    dsl_dir_phys(dd->dd_parent)->dd_child_dir_zapobj,
1901 	    dd->dd_myname, tx);
1902 	ASSERT0(error);
1903 
1904 	(void) strcpy(dd->dd_myname, mynewname);
1905 	dsl_dir_rele(dd->dd_parent, dd);
1906 	dsl_dir_phys(dd)->dd_parent_obj = newparent->dd_object;
1907 	VERIFY0(dsl_dir_hold_obj(dp,
1908 	    newparent->dd_object, NULL, dd, &dd->dd_parent));
1909 
1910 	/* add to new parent zapobj */
1911 	VERIFY0(zap_add(mos, dsl_dir_phys(newparent)->dd_child_dir_zapobj,
1912 	    dd->dd_myname, 8, 1, &dd->dd_object, tx));
1913 
1914 	dsl_prop_notify_all(dd);
1915 
1916 	dsl_dir_rele(newparent, FTAG);
1917 	dsl_dir_rele(dd, FTAG);
1918 }
1919 
1920 int
1921 dsl_dir_rename(const char *oldname, const char *newname)
1922 {
1923 	dsl_dir_rename_arg_t ddra;
1924 
1925 	ddra.ddra_oldname = oldname;
1926 	ddra.ddra_newname = newname;
1927 	ddra.ddra_cred = CRED();
1928 
1929 	return (dsl_sync_task(oldname,
1930 	    dsl_dir_rename_check, dsl_dir_rename_sync, &ddra,
1931 	    3, ZFS_SPACE_CHECK_RESERVED));
1932 }
1933 
1934 int
1935 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd,
1936     uint64_t fs_cnt, uint64_t ss_cnt, uint64_t space, cred_t *cr)
1937 {
1938 	dsl_dir_t *ancestor;
1939 	int64_t adelta;
1940 	uint64_t avail;
1941 	int err;
1942 
1943 	ancestor = closest_common_ancestor(sdd, tdd);
1944 	adelta = would_change(sdd, -space, ancestor);
1945 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1946 	if (avail < space)
1947 		return (SET_ERROR(ENOSPC));
1948 
1949 	err = dsl_fs_ss_limit_check(tdd, fs_cnt, ZFS_PROP_FILESYSTEM_LIMIT,
1950 	    ancestor, cr);
1951 	if (err != 0)
1952 		return (err);
1953 	err = dsl_fs_ss_limit_check(tdd, ss_cnt, ZFS_PROP_SNAPSHOT_LIMIT,
1954 	    ancestor, cr);
1955 	if (err != 0)
1956 		return (err);
1957 
1958 	return (0);
1959 }
1960 
1961 timestruc_t
1962 dsl_dir_snap_cmtime(dsl_dir_t *dd)
1963 {
1964 	timestruc_t t;
1965 
1966 	mutex_enter(&dd->dd_lock);
1967 	t = dd->dd_snap_cmtime;
1968 	mutex_exit(&dd->dd_lock);
1969 
1970 	return (t);
1971 }
1972 
1973 void
1974 dsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1975 {
1976 	timestruc_t t;
1977 
1978 	gethrestime(&t);
1979 	mutex_enter(&dd->dd_lock);
1980 	dd->dd_snap_cmtime = t;
1981 	mutex_exit(&dd->dd_lock);
1982 }
1983 
1984 void
1985 dsl_dir_zapify(dsl_dir_t *dd, dmu_tx_t *tx)
1986 {
1987 	objset_t *mos = dd->dd_pool->dp_meta_objset;
1988 	dmu_object_zapify(mos, dd->dd_object, DMU_OT_DSL_DIR, tx);
1989 }
1990 
1991 boolean_t
1992 dsl_dir_is_zapified(dsl_dir_t *dd)
1993 {
1994 	dmu_object_info_t doi;
1995 
1996 	dmu_object_info_from_db(dd->dd_dbuf, &doi);
1997 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
1998 }
1999