xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_dir.c (revision 1d386b48)
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 https://opensource.org/licenses/CDDL-1.0.
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, 2018 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 (c) 2016 Actifio, Inc. All rights reserved.
28  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
29  */
30 
31 #include <sys/dmu.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/dsl_dataset.h>
35 #include <sys/dsl_dir.h>
36 #include <sys/dsl_prop.h>
37 #include <sys/dsl_synctask.h>
38 #include <sys/dsl_deleg.h>
39 #include <sys/dmu_impl.h>
40 #include <sys/spa.h>
41 #include <sys/spa_impl.h>
42 #include <sys/metaslab.h>
43 #include <sys/zap.h>
44 #include <sys/zio.h>
45 #include <sys/arc.h>
46 #include <sys/sunddi.h>
47 #include <sys/zfeature.h>
48 #include <sys/policy.h>
49 #include <sys/zfs_vfsops.h>
50 #include <sys/zfs_znode.h>
51 #include <sys/zvol.h>
52 #include <sys/zthr.h>
53 #include "zfs_namecheck.h"
54 #include "zfs_prop.h"
55 
56 /*
57  * This controls if we verify the ZVOL quota or not.
58  * Currently, quotas are not implemented for ZVOLs.
59  * The quota size is the size of the ZVOL.
60  * The size of the volume already implies the ZVOL size quota.
61  * The quota mechanism can introduce a significant performance drop.
62  */
63 static int zvol_enforce_quotas = B_TRUE;
64 
65 /*
66  * Filesystem and Snapshot Limits
67  * ------------------------------
68  *
69  * These limits are used to restrict the number of filesystems and/or snapshots
70  * that can be created at a given level in the tree or below. A typical
71  * use-case is with a delegated dataset where the administrator wants to ensure
72  * that a user within the zone is not creating too many additional filesystems
73  * or snapshots, even though they're not exceeding their space quota.
74  *
75  * The filesystem and snapshot counts are stored as extensible properties. This
76  * capability is controlled by a feature flag and must be enabled to be used.
77  * Once enabled, the feature is not active until the first limit is set. At
78  * that point, future operations to create/destroy filesystems or snapshots
79  * will validate and update the counts.
80  *
81  * Because the count properties will not exist before the feature is active,
82  * the counts are updated when a limit is first set on an uninitialized
83  * dsl_dir node in the tree (The filesystem/snapshot count on a node includes
84  * all of the nested filesystems/snapshots. Thus, a new leaf node has a
85  * filesystem count of 0 and a snapshot count of 0. Non-existent filesystem and
86  * snapshot count properties on a node indicate uninitialized counts on that
87  * node.) When first setting a limit on an uninitialized node, the code starts
88  * at the filesystem with the new limit and descends into all sub-filesystems
89  * to add the count properties.
90  *
91  * In practice this is lightweight since a limit is typically set when the
92  * filesystem is created and thus has no children. Once valid, changing the
93  * limit value won't require a re-traversal since the counts are already valid.
94  * When recursively fixing the counts, if a node with a limit is encountered
95  * during the descent, the counts are known to be valid and there is no need to
96  * descend into that filesystem's children. The counts on filesystems above the
97  * one with the new limit will still be uninitialized, unless a limit is
98  * eventually set on one of those filesystems. The counts are always recursively
99  * updated when a limit is set on a dataset, unless there is already a limit.
100  * When a new limit value is set on a filesystem with an existing limit, it is
101  * possible for the new limit to be less than the current count at that level
102  * since a user who can change the limit is also allowed to exceed the limit.
103  *
104  * Once the feature is active, then whenever a filesystem or snapshot is
105  * created, the code recurses up the tree, validating the new count against the
106  * limit at each initialized level. In practice, most levels will not have a
107  * limit set. If there is a limit at any initialized level up the tree, the
108  * check must pass or the creation will fail. Likewise, when a filesystem or
109  * snapshot is destroyed, the counts are recursively adjusted all the way up
110  * the initialized nodes in the tree. Renaming a filesystem into different point
111  * in the tree will first validate, then update the counts on each branch up to
112  * the common ancestor. A receive will also validate the counts and then update
113  * them.
114  *
115  * An exception to the above behavior is that the limit is not enforced if the
116  * user has permission to modify the limit. This is primarily so that
117  * recursive snapshots in the global zone always work. We want to prevent a
118  * denial-of-service in which a lower level delegated dataset could max out its
119  * limit and thus block recursive snapshots from being taken in the global zone.
120  * Because of this, it is possible for the snapshot count to be over the limit
121  * and snapshots taken in the global zone could cause a lower level dataset to
122  * hit or exceed its limit. The administrator taking the global zone recursive
123  * snapshot should be aware of this side-effect and behave accordingly.
124  * For consistency, the filesystem limit is also not enforced if the user can
125  * modify the limit.
126  *
127  * The filesystem and snapshot limits are validated by dsl_fs_ss_limit_check()
128  * and updated by dsl_fs_ss_count_adjust(). A new limit value is setup in
129  * dsl_dir_activate_fs_ss_limit() and the counts are adjusted, if necessary, by
130  * dsl_dir_init_fs_ss_count().
131  */
132 
133 static uint64_t dsl_dir_space_towrite(dsl_dir_t *dd);
134 
135 typedef struct ddulrt_arg {
136 	dsl_dir_t	*ddulrta_dd;
137 	uint64_t	ddlrta_txg;
138 } ddulrt_arg_t;
139 
140 static void
141 dsl_dir_evict_async(void *dbu)
142 {
143 	dsl_dir_t *dd = dbu;
144 	int t;
145 	dsl_pool_t *dp __maybe_unused = dd->dd_pool;
146 
147 	dd->dd_dbuf = NULL;
148 
149 	for (t = 0; t < TXG_SIZE; t++) {
150 		ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
151 		ASSERT(dd->dd_tempreserved[t] == 0);
152 		ASSERT(dd->dd_space_towrite[t] == 0);
153 	}
154 
155 	if (dd->dd_parent)
156 		dsl_dir_async_rele(dd->dd_parent, dd);
157 
158 	spa_async_close(dd->dd_pool->dp_spa, dd);
159 
160 	if (dsl_deadlist_is_open(&dd->dd_livelist))
161 		dsl_dir_livelist_close(dd);
162 
163 	dsl_prop_fini(dd);
164 	cv_destroy(&dd->dd_activity_cv);
165 	mutex_destroy(&dd->dd_activity_lock);
166 	mutex_destroy(&dd->dd_lock);
167 	kmem_free(dd, sizeof (dsl_dir_t));
168 }
169 
170 int
171 dsl_dir_hold_obj(dsl_pool_t *dp, uint64_t ddobj,
172     const char *tail, const void *tag, dsl_dir_t **ddp)
173 {
174 	dmu_buf_t *dbuf;
175 	dsl_dir_t *dd;
176 	dmu_object_info_t doi;
177 	int err;
178 
179 	ASSERT(dsl_pool_config_held(dp));
180 
181 	err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
182 	if (err != 0)
183 		return (err);
184 	dd = dmu_buf_get_user(dbuf);
185 
186 	dmu_object_info_from_db(dbuf, &doi);
187 	ASSERT3U(doi.doi_bonus_type, ==, DMU_OT_DSL_DIR);
188 	ASSERT3U(doi.doi_bonus_size, >=, sizeof (dsl_dir_phys_t));
189 
190 	if (dd == NULL) {
191 		dsl_dir_t *winner;
192 
193 		dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
194 		dd->dd_object = ddobj;
195 		dd->dd_dbuf = dbuf;
196 		dd->dd_pool = dp;
197 
198 		mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
199 		mutex_init(&dd->dd_activity_lock, NULL, MUTEX_DEFAULT, NULL);
200 		cv_init(&dd->dd_activity_cv, NULL, CV_DEFAULT, NULL);
201 		dsl_prop_init(dd);
202 
203 		if (dsl_dir_is_zapified(dd)) {
204 			err = zap_lookup(dp->dp_meta_objset,
205 			    ddobj, DD_FIELD_CRYPTO_KEY_OBJ,
206 			    sizeof (uint64_t), 1, &dd->dd_crypto_obj);
207 			if (err == 0) {
208 				/* check for on-disk format errata */
209 				if (dsl_dir_incompatible_encryption_version(
210 				    dd)) {
211 					dp->dp_spa->spa_errata =
212 					    ZPOOL_ERRATA_ZOL_6845_ENCRYPTION;
213 				}
214 			} else if (err != ENOENT) {
215 				goto errout;
216 			}
217 		}
218 
219 		if (dsl_dir_phys(dd)->dd_parent_obj) {
220 			err = dsl_dir_hold_obj(dp,
221 			    dsl_dir_phys(dd)->dd_parent_obj, NULL, dd,
222 			    &dd->dd_parent);
223 			if (err != 0)
224 				goto errout;
225 			if (tail) {
226 #ifdef ZFS_DEBUG
227 				uint64_t foundobj;
228 
229 				err = zap_lookup(dp->dp_meta_objset,
230 				    dsl_dir_phys(dd->dd_parent)->
231 				    dd_child_dir_zapobj, tail,
232 				    sizeof (foundobj), 1, &foundobj);
233 				ASSERT(err || foundobj == ddobj);
234 #endif
235 				(void) strlcpy(dd->dd_myname, tail,
236 				    sizeof (dd->dd_myname));
237 			} else {
238 				err = zap_value_search(dp->dp_meta_objset,
239 				    dsl_dir_phys(dd->dd_parent)->
240 				    dd_child_dir_zapobj,
241 				    ddobj, 0, dd->dd_myname);
242 			}
243 			if (err != 0)
244 				goto errout;
245 		} else {
246 			(void) strlcpy(dd->dd_myname, spa_name(dp->dp_spa),
247 			    sizeof (dd->dd_myname));
248 		}
249 
250 		if (dsl_dir_is_clone(dd)) {
251 			dmu_buf_t *origin_bonus;
252 			dsl_dataset_phys_t *origin_phys;
253 
254 			/*
255 			 * We can't open the origin dataset, because
256 			 * that would require opening this dsl_dir.
257 			 * Just look at its phys directly instead.
258 			 */
259 			err = dmu_bonus_hold(dp->dp_meta_objset,
260 			    dsl_dir_phys(dd)->dd_origin_obj, FTAG,
261 			    &origin_bonus);
262 			if (err != 0)
263 				goto errout;
264 			origin_phys = origin_bonus->db_data;
265 			dd->dd_origin_txg =
266 			    origin_phys->ds_creation_txg;
267 			dmu_buf_rele(origin_bonus, FTAG);
268 			if (dsl_dir_is_zapified(dd)) {
269 				uint64_t obj;
270 				err = zap_lookup(dp->dp_meta_objset,
271 				    dd->dd_object, DD_FIELD_LIVELIST,
272 				    sizeof (uint64_t), 1, &obj);
273 				if (err == 0)
274 					dsl_dir_livelist_open(dd, obj);
275 				else if (err != ENOENT)
276 					goto errout;
277 			}
278 		}
279 
280 		if (dsl_dir_is_zapified(dd)) {
281 			inode_timespec_t t = {0};
282 			(void) zap_lookup(dp->dp_meta_objset, ddobj,
283 			    DD_FIELD_SNAPSHOTS_CHANGED,
284 			    sizeof (uint64_t),
285 			    sizeof (inode_timespec_t) / sizeof (uint64_t),
286 			    &t);
287 			dd->dd_snap_cmtime = t;
288 		}
289 
290 		dmu_buf_init_user(&dd->dd_dbu, NULL, dsl_dir_evict_async,
291 		    &dd->dd_dbuf);
292 		winner = dmu_buf_set_user_ie(dbuf, &dd->dd_dbu);
293 		if (winner != NULL) {
294 			if (dd->dd_parent)
295 				dsl_dir_rele(dd->dd_parent, dd);
296 			if (dsl_deadlist_is_open(&dd->dd_livelist))
297 				dsl_dir_livelist_close(dd);
298 			dsl_prop_fini(dd);
299 			cv_destroy(&dd->dd_activity_cv);
300 			mutex_destroy(&dd->dd_activity_lock);
301 			mutex_destroy(&dd->dd_lock);
302 			kmem_free(dd, sizeof (dsl_dir_t));
303 			dd = winner;
304 		} else {
305 			spa_open_ref(dp->dp_spa, dd);
306 		}
307 	}
308 
309 	/*
310 	 * The dsl_dir_t has both open-to-close and instantiate-to-evict
311 	 * holds on the spa.  We need the open-to-close holds because
312 	 * otherwise the spa_refcnt wouldn't change when we open a
313 	 * dir which the spa also has open, so we could incorrectly
314 	 * think it was OK to unload/export/destroy the pool.  We need
315 	 * the instantiate-to-evict hold because the dsl_dir_t has a
316 	 * pointer to the dd_pool, which has a pointer to the spa_t.
317 	 */
318 	spa_open_ref(dp->dp_spa, tag);
319 	ASSERT3P(dd->dd_pool, ==, dp);
320 	ASSERT3U(dd->dd_object, ==, ddobj);
321 	ASSERT3P(dd->dd_dbuf, ==, dbuf);
322 	*ddp = dd;
323 	return (0);
324 
325 errout:
326 	if (dd->dd_parent)
327 		dsl_dir_rele(dd->dd_parent, dd);
328 	if (dsl_deadlist_is_open(&dd->dd_livelist))
329 		dsl_dir_livelist_close(dd);
330 	dsl_prop_fini(dd);
331 	cv_destroy(&dd->dd_activity_cv);
332 	mutex_destroy(&dd->dd_activity_lock);
333 	mutex_destroy(&dd->dd_lock);
334 	kmem_free(dd, sizeof (dsl_dir_t));
335 	dmu_buf_rele(dbuf, tag);
336 	return (err);
337 }
338 
339 void
340 dsl_dir_rele(dsl_dir_t *dd, const void *tag)
341 {
342 	dprintf_dd(dd, "%s\n", "");
343 	spa_close(dd->dd_pool->dp_spa, tag);
344 	dmu_buf_rele(dd->dd_dbuf, tag);
345 }
346 
347 /*
348  * Remove a reference to the given dsl dir that is being asynchronously
349  * released.  Async releases occur from a taskq performing eviction of
350  * dsl datasets and dirs.  This process is identical to a normal release
351  * with the exception of using the async API for releasing the reference on
352  * the spa.
353  */
354 void
355 dsl_dir_async_rele(dsl_dir_t *dd, const void *tag)
356 {
357 	dprintf_dd(dd, "%s\n", "");
358 	spa_async_close(dd->dd_pool->dp_spa, tag);
359 	dmu_buf_rele(dd->dd_dbuf, tag);
360 }
361 
362 /* buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes */
363 void
364 dsl_dir_name(dsl_dir_t *dd, char *buf)
365 {
366 	if (dd->dd_parent) {
367 		dsl_dir_name(dd->dd_parent, buf);
368 		VERIFY3U(strlcat(buf, "/", ZFS_MAX_DATASET_NAME_LEN), <,
369 		    ZFS_MAX_DATASET_NAME_LEN);
370 	} else {
371 		buf[0] = '\0';
372 	}
373 	if (!MUTEX_HELD(&dd->dd_lock)) {
374 		/*
375 		 * recursive mutex so that we can use
376 		 * dprintf_dd() with dd_lock held
377 		 */
378 		mutex_enter(&dd->dd_lock);
379 		VERIFY3U(strlcat(buf, dd->dd_myname, ZFS_MAX_DATASET_NAME_LEN),
380 		    <, ZFS_MAX_DATASET_NAME_LEN);
381 		mutex_exit(&dd->dd_lock);
382 	} else {
383 		VERIFY3U(strlcat(buf, dd->dd_myname, ZFS_MAX_DATASET_NAME_LEN),
384 		    <, ZFS_MAX_DATASET_NAME_LEN);
385 	}
386 }
387 
388 /* Calculate name length, avoiding all the strcat calls of dsl_dir_name */
389 int
390 dsl_dir_namelen(dsl_dir_t *dd)
391 {
392 	int result = 0;
393 
394 	if (dd->dd_parent) {
395 		/* parent's name + 1 for the "/" */
396 		result = dsl_dir_namelen(dd->dd_parent) + 1;
397 	}
398 
399 	if (!MUTEX_HELD(&dd->dd_lock)) {
400 		/* see dsl_dir_name */
401 		mutex_enter(&dd->dd_lock);
402 		result += strlen(dd->dd_myname);
403 		mutex_exit(&dd->dd_lock);
404 	} else {
405 		result += strlen(dd->dd_myname);
406 	}
407 
408 	return (result);
409 }
410 
411 static int
412 getcomponent(const char *path, char *component, const char **nextp)
413 {
414 	char *p;
415 
416 	if ((path == NULL) || (path[0] == '\0'))
417 		return (SET_ERROR(ENOENT));
418 	/* This would be a good place to reserve some namespace... */
419 	p = strpbrk(path, "/@");
420 	if (p && (p[1] == '/' || p[1] == '@')) {
421 		/* two separators in a row */
422 		return (SET_ERROR(EINVAL));
423 	}
424 	if (p == NULL || p == path) {
425 		/*
426 		 * if the first thing is an @ or /, it had better be an
427 		 * @ and it had better not have any more ats or slashes,
428 		 * and it had better have something after the @.
429 		 */
430 		if (p != NULL &&
431 		    (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
432 			return (SET_ERROR(EINVAL));
433 		if (strlen(path) >= ZFS_MAX_DATASET_NAME_LEN)
434 			return (SET_ERROR(ENAMETOOLONG));
435 		(void) strlcpy(component, path, ZFS_MAX_DATASET_NAME_LEN);
436 		p = NULL;
437 	} else if (p[0] == '/') {
438 		if (p - path >= ZFS_MAX_DATASET_NAME_LEN)
439 			return (SET_ERROR(ENAMETOOLONG));
440 		(void) strlcpy(component, path, p - path + 1);
441 		p++;
442 	} else if (p[0] == '@') {
443 		/*
444 		 * if the next separator is an @, there better not be
445 		 * any more slashes.
446 		 */
447 		if (strchr(path, '/'))
448 			return (SET_ERROR(EINVAL));
449 		if (p - path >= ZFS_MAX_DATASET_NAME_LEN)
450 			return (SET_ERROR(ENAMETOOLONG));
451 		(void) strlcpy(component, path, p - path + 1);
452 	} else {
453 		panic("invalid p=%p", (void *)p);
454 	}
455 	*nextp = p;
456 	return (0);
457 }
458 
459 /*
460  * Return the dsl_dir_t, and possibly the last component which couldn't
461  * be found in *tail.  The name must be in the specified dsl_pool_t.  This
462  * thread must hold the dp_config_rwlock for the pool.  Returns NULL if the
463  * path is bogus, or if tail==NULL and we couldn't parse the whole name.
464  * (*tail)[0] == '@' means that the last component is a snapshot.
465  */
466 int
467 dsl_dir_hold(dsl_pool_t *dp, const char *name, const void *tag,
468     dsl_dir_t **ddp, const char **tailp)
469 {
470 	char *buf;
471 	const char *spaname, *next, *nextnext = NULL;
472 	int err;
473 	dsl_dir_t *dd;
474 	uint64_t ddobj;
475 
476 	buf = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
477 	err = getcomponent(name, buf, &next);
478 	if (err != 0)
479 		goto error;
480 
481 	/* Make sure the name is in the specified pool. */
482 	spaname = spa_name(dp->dp_spa);
483 	if (strcmp(buf, spaname) != 0) {
484 		err = SET_ERROR(EXDEV);
485 		goto error;
486 	}
487 
488 	ASSERT(dsl_pool_config_held(dp));
489 
490 	err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
491 	if (err != 0) {
492 		goto error;
493 	}
494 
495 	while (next != NULL) {
496 		dsl_dir_t *child_dd;
497 		err = getcomponent(next, buf, &nextnext);
498 		if (err != 0)
499 			break;
500 		ASSERT(next[0] != '\0');
501 		if (next[0] == '@')
502 			break;
503 		dprintf("looking up %s in obj%lld\n",
504 		    buf, (longlong_t)dsl_dir_phys(dd)->dd_child_dir_zapobj);
505 
506 		err = zap_lookup(dp->dp_meta_objset,
507 		    dsl_dir_phys(dd)->dd_child_dir_zapobj,
508 		    buf, sizeof (ddobj), 1, &ddobj);
509 		if (err != 0) {
510 			if (err == ENOENT)
511 				err = 0;
512 			break;
513 		}
514 
515 		err = dsl_dir_hold_obj(dp, ddobj, buf, tag, &child_dd);
516 		if (err != 0)
517 			break;
518 		dsl_dir_rele(dd, tag);
519 		dd = child_dd;
520 		next = nextnext;
521 	}
522 
523 	if (err != 0) {
524 		dsl_dir_rele(dd, tag);
525 		goto error;
526 	}
527 
528 	/*
529 	 * It's an error if there's more than one component left, or
530 	 * tailp==NULL and there's any component left.
531 	 */
532 	if (next != NULL &&
533 	    (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
534 		/* bad path name */
535 		dsl_dir_rele(dd, tag);
536 		dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
537 		err = SET_ERROR(ENOENT);
538 	}
539 	if (tailp != NULL)
540 		*tailp = next;
541 	if (err == 0)
542 		*ddp = dd;
543 error:
544 	kmem_free(buf, ZFS_MAX_DATASET_NAME_LEN);
545 	return (err);
546 }
547 
548 /*
549  * If the counts are already initialized for this filesystem and its
550  * descendants then do nothing, otherwise initialize the counts.
551  *
552  * The counts on this filesystem, and those below, may be uninitialized due to
553  * either the use of a pre-existing pool which did not support the
554  * filesystem/snapshot limit feature, or one in which the feature had not yet
555  * been enabled.
556  *
557  * Recursively descend the filesystem tree and update the filesystem/snapshot
558  * counts on each filesystem below, then update the cumulative count on the
559  * current filesystem. If the filesystem already has a count set on it,
560  * then we know that its counts, and the counts on the filesystems below it,
561  * are already correct, so we don't have to update this filesystem.
562  */
563 static void
564 dsl_dir_init_fs_ss_count(dsl_dir_t *dd, dmu_tx_t *tx)
565 {
566 	uint64_t my_fs_cnt = 0;
567 	uint64_t my_ss_cnt = 0;
568 	dsl_pool_t *dp = dd->dd_pool;
569 	objset_t *os = dp->dp_meta_objset;
570 	zap_cursor_t *zc;
571 	zap_attribute_t *za;
572 	dsl_dataset_t *ds;
573 
574 	ASSERT(spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT));
575 	ASSERT(dsl_pool_config_held(dp));
576 	ASSERT(dmu_tx_is_syncing(tx));
577 
578 	dsl_dir_zapify(dd, tx);
579 
580 	/*
581 	 * If the filesystem count has already been initialized then we
582 	 * don't need to recurse down any further.
583 	 */
584 	if (zap_contains(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT) == 0)
585 		return;
586 
587 	zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
588 	za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
589 
590 	/* Iterate my child dirs */
591 	for (zap_cursor_init(zc, os, dsl_dir_phys(dd)->dd_child_dir_zapobj);
592 	    zap_cursor_retrieve(zc, za) == 0; zap_cursor_advance(zc)) {
593 		dsl_dir_t *chld_dd;
594 		uint64_t count;
595 
596 		VERIFY0(dsl_dir_hold_obj(dp, za->za_first_integer, NULL, FTAG,
597 		    &chld_dd));
598 
599 		/*
600 		 * Ignore hidden ($FREE, $MOS & $ORIGIN) objsets.
601 		 */
602 		if (chld_dd->dd_myname[0] == '$') {
603 			dsl_dir_rele(chld_dd, FTAG);
604 			continue;
605 		}
606 
607 		my_fs_cnt++;	/* count this child */
608 
609 		dsl_dir_init_fs_ss_count(chld_dd, tx);
610 
611 		VERIFY0(zap_lookup(os, chld_dd->dd_object,
612 		    DD_FIELD_FILESYSTEM_COUNT, sizeof (count), 1, &count));
613 		my_fs_cnt += count;
614 		VERIFY0(zap_lookup(os, chld_dd->dd_object,
615 		    DD_FIELD_SNAPSHOT_COUNT, sizeof (count), 1, &count));
616 		my_ss_cnt += count;
617 
618 		dsl_dir_rele(chld_dd, FTAG);
619 	}
620 	zap_cursor_fini(zc);
621 	/* Count my snapshots (we counted children's snapshots above) */
622 	VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
623 	    dsl_dir_phys(dd)->dd_head_dataset_obj, FTAG, &ds));
624 
625 	for (zap_cursor_init(zc, os, dsl_dataset_phys(ds)->ds_snapnames_zapobj);
626 	    zap_cursor_retrieve(zc, za) == 0;
627 	    zap_cursor_advance(zc)) {
628 		/* Don't count temporary snapshots */
629 		if (za->za_name[0] != '%')
630 			my_ss_cnt++;
631 	}
632 	zap_cursor_fini(zc);
633 
634 	dsl_dataset_rele(ds, FTAG);
635 
636 	kmem_free(zc, sizeof (zap_cursor_t));
637 	kmem_free(za, sizeof (zap_attribute_t));
638 
639 	/* we're in a sync task, update counts */
640 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
641 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
642 	    sizeof (my_fs_cnt), 1, &my_fs_cnt, tx));
643 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
644 	    sizeof (my_ss_cnt), 1, &my_ss_cnt, tx));
645 }
646 
647 static int
648 dsl_dir_actv_fs_ss_limit_check(void *arg, dmu_tx_t *tx)
649 {
650 	char *ddname = (char *)arg;
651 	dsl_pool_t *dp = dmu_tx_pool(tx);
652 	dsl_dataset_t *ds;
653 	dsl_dir_t *dd;
654 	int error;
655 
656 	error = dsl_dataset_hold(dp, ddname, FTAG, &ds);
657 	if (error != 0)
658 		return (error);
659 
660 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
661 		dsl_dataset_rele(ds, FTAG);
662 		return (SET_ERROR(ENOTSUP));
663 	}
664 
665 	dd = ds->ds_dir;
666 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT) &&
667 	    dsl_dir_is_zapified(dd) &&
668 	    zap_contains(dp->dp_meta_objset, dd->dd_object,
669 	    DD_FIELD_FILESYSTEM_COUNT) == 0) {
670 		dsl_dataset_rele(ds, FTAG);
671 		return (SET_ERROR(EALREADY));
672 	}
673 
674 	dsl_dataset_rele(ds, FTAG);
675 	return (0);
676 }
677 
678 static void
679 dsl_dir_actv_fs_ss_limit_sync(void *arg, dmu_tx_t *tx)
680 {
681 	char *ddname = (char *)arg;
682 	dsl_pool_t *dp = dmu_tx_pool(tx);
683 	dsl_dataset_t *ds;
684 	spa_t *spa;
685 
686 	VERIFY0(dsl_dataset_hold(dp, ddname, FTAG, &ds));
687 
688 	spa = dsl_dataset_get_spa(ds);
689 
690 	if (!spa_feature_is_active(spa, SPA_FEATURE_FS_SS_LIMIT)) {
691 		/*
692 		 * Since the feature was not active and we're now setting a
693 		 * limit, increment the feature-active counter so that the
694 		 * feature becomes active for the first time.
695 		 *
696 		 * We are already in a sync task so we can update the MOS.
697 		 */
698 		spa_feature_incr(spa, SPA_FEATURE_FS_SS_LIMIT, tx);
699 	}
700 
701 	/*
702 	 * Since we are now setting a non-UINT64_MAX limit on the filesystem,
703 	 * we need to ensure the counts are correct. Descend down the tree from
704 	 * this point and update all of the counts to be accurate.
705 	 */
706 	dsl_dir_init_fs_ss_count(ds->ds_dir, tx);
707 
708 	dsl_dataset_rele(ds, FTAG);
709 }
710 
711 /*
712  * Make sure the feature is enabled and activate it if necessary.
713  * Since we're setting a limit, ensure the on-disk counts are valid.
714  * This is only called by the ioctl path when setting a limit value.
715  *
716  * We do not need to validate the new limit, since users who can change the
717  * limit are also allowed to exceed the limit.
718  */
719 int
720 dsl_dir_activate_fs_ss_limit(const char *ddname)
721 {
722 	int error;
723 
724 	error = dsl_sync_task(ddname, dsl_dir_actv_fs_ss_limit_check,
725 	    dsl_dir_actv_fs_ss_limit_sync, (void *)ddname, 0,
726 	    ZFS_SPACE_CHECK_RESERVED);
727 
728 	if (error == EALREADY)
729 		error = 0;
730 
731 	return (error);
732 }
733 
734 /*
735  * Used to determine if the filesystem_limit or snapshot_limit should be
736  * enforced. We allow the limit to be exceeded if the user has permission to
737  * write the property value. We pass in the creds that we got in the open
738  * context since we will always be the GZ root in syncing context. We also have
739  * to handle the case where we are allowed to change the limit on the current
740  * dataset, but there may be another limit in the tree above.
741  *
742  * We can never modify these two properties within a non-global zone. In
743  * addition, the other checks are modeled on zfs_secpolicy_write_perms. We
744  * can't use that function since we are already holding the dp_config_rwlock.
745  * In addition, we already have the dd and dealing with snapshots is simplified
746  * in this code.
747  */
748 
749 typedef enum {
750 	ENFORCE_ALWAYS,
751 	ENFORCE_NEVER,
752 	ENFORCE_ABOVE
753 } enforce_res_t;
754 
755 static enforce_res_t
756 dsl_enforce_ds_ss_limits(dsl_dir_t *dd, zfs_prop_t prop,
757     cred_t *cr, proc_t *proc)
758 {
759 	enforce_res_t enforce = ENFORCE_ALWAYS;
760 	uint64_t obj;
761 	dsl_dataset_t *ds;
762 	uint64_t zoned;
763 	const char *zonedstr;
764 
765 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
766 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
767 
768 #ifdef _KERNEL
769 	if (crgetzoneid(cr) != GLOBAL_ZONEID)
770 		return (ENFORCE_ALWAYS);
771 
772 	/*
773 	 * We are checking the saved credentials of the user process, which is
774 	 * not the current process.  Note that we can't use secpolicy_zfs(),
775 	 * because it only works if the cred is that of the current process (on
776 	 * Linux).
777 	 */
778 	if (secpolicy_zfs_proc(cr, proc) == 0)
779 		return (ENFORCE_NEVER);
780 #else
781 	(void) proc;
782 #endif
783 
784 	if ((obj = dsl_dir_phys(dd)->dd_head_dataset_obj) == 0)
785 		return (ENFORCE_ALWAYS);
786 
787 	ASSERT(dsl_pool_config_held(dd->dd_pool));
788 
789 	if (dsl_dataset_hold_obj(dd->dd_pool, obj, FTAG, &ds) != 0)
790 		return (ENFORCE_ALWAYS);
791 
792 	zonedstr = zfs_prop_to_name(ZFS_PROP_ZONED);
793 	if (dsl_prop_get_ds(ds, zonedstr, 8, 1, &zoned, NULL) || zoned) {
794 		/* Only root can access zoned fs's from the GZ */
795 		enforce = ENFORCE_ALWAYS;
796 	} else {
797 		if (dsl_deleg_access_impl(ds, zfs_prop_to_name(prop), cr) == 0)
798 			enforce = ENFORCE_ABOVE;
799 	}
800 
801 	dsl_dataset_rele(ds, FTAG);
802 	return (enforce);
803 }
804 
805 /*
806  * Check if adding additional child filesystem(s) would exceed any filesystem
807  * limits or adding additional snapshot(s) would exceed any snapshot limits.
808  * The prop argument indicates which limit to check.
809  *
810  * Note that all filesystem limits up to the root (or the highest
811  * initialized) filesystem or the given ancestor must be satisfied.
812  */
813 int
814 dsl_fs_ss_limit_check(dsl_dir_t *dd, uint64_t delta, zfs_prop_t prop,
815     dsl_dir_t *ancestor, cred_t *cr, proc_t *proc)
816 {
817 	objset_t *os = dd->dd_pool->dp_meta_objset;
818 	uint64_t limit, count;
819 	const char *count_prop;
820 	enforce_res_t enforce;
821 	int err = 0;
822 
823 	ASSERT(dsl_pool_config_held(dd->dd_pool));
824 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
825 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
826 
827 	if (prop == ZFS_PROP_SNAPSHOT_LIMIT) {
828 		/*
829 		 * We don't enforce the limit for temporary snapshots. This is
830 		 * indicated by a NULL cred_t argument.
831 		 */
832 		if (cr == NULL)
833 			return (0);
834 
835 		count_prop = DD_FIELD_SNAPSHOT_COUNT;
836 	} else {
837 		count_prop = DD_FIELD_FILESYSTEM_COUNT;
838 	}
839 	/*
840 	 * If we're allowed to change the limit, don't enforce the limit
841 	 * e.g. this can happen if a snapshot is taken by an administrative
842 	 * user in the global zone (i.e. a recursive snapshot by root).
843 	 * However, we must handle the case of delegated permissions where we
844 	 * are allowed to change the limit on the current dataset, but there
845 	 * is another limit in the tree above.
846 	 */
847 	enforce = dsl_enforce_ds_ss_limits(dd, prop, cr, proc);
848 	if (enforce == ENFORCE_NEVER)
849 		return (0);
850 
851 	/*
852 	 * e.g. if renaming a dataset with no snapshots, count adjustment
853 	 * is 0.
854 	 */
855 	if (delta == 0)
856 		return (0);
857 
858 	/*
859 	 * If an ancestor has been provided, stop checking the limit once we
860 	 * hit that dir. We need this during rename so that we don't overcount
861 	 * the check once we recurse up to the common ancestor.
862 	 */
863 	if (ancestor == dd)
864 		return (0);
865 
866 	/*
867 	 * If we hit an uninitialized node while recursing up the tree, we can
868 	 * stop since we know there is no limit here (or above). The counts are
869 	 * not valid on this node and we know we won't touch this node's counts.
870 	 */
871 	if (!dsl_dir_is_zapified(dd))
872 		return (0);
873 	err = zap_lookup(os, dd->dd_object,
874 	    count_prop, sizeof (count), 1, &count);
875 	if (err == ENOENT)
876 		return (0);
877 	if (err != 0)
878 		return (err);
879 
880 	err = dsl_prop_get_dd(dd, zfs_prop_to_name(prop), 8, 1, &limit, NULL,
881 	    B_FALSE);
882 	if (err != 0)
883 		return (err);
884 
885 	/* Is there a limit which we've hit? */
886 	if (enforce == ENFORCE_ALWAYS && (count + delta) > limit)
887 		return (SET_ERROR(EDQUOT));
888 
889 	if (dd->dd_parent != NULL)
890 		err = dsl_fs_ss_limit_check(dd->dd_parent, delta, prop,
891 		    ancestor, cr, proc);
892 
893 	return (err);
894 }
895 
896 /*
897  * Adjust the filesystem or snapshot count for the specified dsl_dir_t and all
898  * parents. When a new filesystem/snapshot is created, increment the count on
899  * all parents, and when a filesystem/snapshot is destroyed, decrement the
900  * count.
901  */
902 void
903 dsl_fs_ss_count_adjust(dsl_dir_t *dd, int64_t delta, const char *prop,
904     dmu_tx_t *tx)
905 {
906 	int err;
907 	objset_t *os = dd->dd_pool->dp_meta_objset;
908 	uint64_t count;
909 
910 	ASSERT(dsl_pool_config_held(dd->dd_pool));
911 	ASSERT(dmu_tx_is_syncing(tx));
912 	ASSERT(strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0 ||
913 	    strcmp(prop, DD_FIELD_SNAPSHOT_COUNT) == 0);
914 
915 	/*
916 	 * We don't do accounting for hidden ($FREE, $MOS & $ORIGIN) objsets.
917 	 */
918 	if (dd->dd_myname[0] == '$' && strcmp(prop,
919 	    DD_FIELD_FILESYSTEM_COUNT) == 0) {
920 		return;
921 	}
922 
923 	/*
924 	 * e.g. if renaming a dataset with no snapshots, count adjustment is 0
925 	 */
926 	if (delta == 0)
927 		return;
928 
929 	/*
930 	 * If we hit an uninitialized node while recursing up the tree, we can
931 	 * stop since we know the counts are not valid on this node and we
932 	 * know we shouldn't touch this node's counts. An uninitialized count
933 	 * on the node indicates that either the feature has not yet been
934 	 * activated or there are no limits on this part of the tree.
935 	 */
936 	if (!dsl_dir_is_zapified(dd) || (err = zap_lookup(os, dd->dd_object,
937 	    prop, sizeof (count), 1, &count)) == ENOENT)
938 		return;
939 	VERIFY0(err);
940 
941 	count += delta;
942 	/* Use a signed verify to make sure we're not neg. */
943 	VERIFY3S(count, >=, 0);
944 
945 	VERIFY0(zap_update(os, dd->dd_object, prop, sizeof (count), 1, &count,
946 	    tx));
947 
948 	/* Roll up this additional count into our ancestors */
949 	if (dd->dd_parent != NULL)
950 		dsl_fs_ss_count_adjust(dd->dd_parent, delta, prop, tx);
951 }
952 
953 uint64_t
954 dsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
955     dmu_tx_t *tx)
956 {
957 	objset_t *mos = dp->dp_meta_objset;
958 	uint64_t ddobj;
959 	dsl_dir_phys_t *ddphys;
960 	dmu_buf_t *dbuf;
961 
962 	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
963 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
964 	if (pds) {
965 		VERIFY0(zap_add(mos, dsl_dir_phys(pds)->dd_child_dir_zapobj,
966 		    name, sizeof (uint64_t), 1, &ddobj, tx));
967 	} else {
968 		/* it's the root dir */
969 		VERIFY0(zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
970 		    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
971 	}
972 	VERIFY0(dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
973 	dmu_buf_will_dirty(dbuf, tx);
974 	ddphys = dbuf->db_data;
975 
976 	ddphys->dd_creation_time = gethrestime_sec();
977 	if (pds) {
978 		ddphys->dd_parent_obj = pds->dd_object;
979 
980 		/* update the filesystem counts */
981 		dsl_fs_ss_count_adjust(pds, 1, DD_FIELD_FILESYSTEM_COUNT, tx);
982 	}
983 	ddphys->dd_props_zapobj = zap_create(mos,
984 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
985 	ddphys->dd_child_dir_zapobj = zap_create(mos,
986 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
987 	if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
988 		ddphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
989 
990 	dmu_buf_rele(dbuf, FTAG);
991 
992 	return (ddobj);
993 }
994 
995 boolean_t
996 dsl_dir_is_clone(dsl_dir_t *dd)
997 {
998 	return (dsl_dir_phys(dd)->dd_origin_obj &&
999 	    (dd->dd_pool->dp_origin_snap == NULL ||
1000 	    dsl_dir_phys(dd)->dd_origin_obj !=
1001 	    dd->dd_pool->dp_origin_snap->ds_object));
1002 }
1003 
1004 uint64_t
1005 dsl_dir_get_used(dsl_dir_t *dd)
1006 {
1007 	return (dsl_dir_phys(dd)->dd_used_bytes);
1008 }
1009 
1010 uint64_t
1011 dsl_dir_get_compressed(dsl_dir_t *dd)
1012 {
1013 	return (dsl_dir_phys(dd)->dd_compressed_bytes);
1014 }
1015 
1016 uint64_t
1017 dsl_dir_get_quota(dsl_dir_t *dd)
1018 {
1019 	return (dsl_dir_phys(dd)->dd_quota);
1020 }
1021 
1022 uint64_t
1023 dsl_dir_get_reservation(dsl_dir_t *dd)
1024 {
1025 	return (dsl_dir_phys(dd)->dd_reserved);
1026 }
1027 
1028 uint64_t
1029 dsl_dir_get_compressratio(dsl_dir_t *dd)
1030 {
1031 	/* a fixed point number, 100x the ratio */
1032 	return (dsl_dir_phys(dd)->dd_compressed_bytes == 0 ? 100 :
1033 	    (dsl_dir_phys(dd)->dd_uncompressed_bytes * 100 /
1034 	    dsl_dir_phys(dd)->dd_compressed_bytes));
1035 }
1036 
1037 uint64_t
1038 dsl_dir_get_logicalused(dsl_dir_t *dd)
1039 {
1040 	return (dsl_dir_phys(dd)->dd_uncompressed_bytes);
1041 }
1042 
1043 uint64_t
1044 dsl_dir_get_usedsnap(dsl_dir_t *dd)
1045 {
1046 	return (dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP]);
1047 }
1048 
1049 uint64_t
1050 dsl_dir_get_usedds(dsl_dir_t *dd)
1051 {
1052 	return (dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_HEAD]);
1053 }
1054 
1055 uint64_t
1056 dsl_dir_get_usedrefreserv(dsl_dir_t *dd)
1057 {
1058 	return (dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_REFRSRV]);
1059 }
1060 
1061 uint64_t
1062 dsl_dir_get_usedchild(dsl_dir_t *dd)
1063 {
1064 	return (dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_CHILD] +
1065 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_CHILD_RSRV]);
1066 }
1067 
1068 void
1069 dsl_dir_get_origin(dsl_dir_t *dd, char *buf)
1070 {
1071 	dsl_dataset_t *ds;
1072 	VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
1073 	    dsl_dir_phys(dd)->dd_origin_obj, FTAG, &ds));
1074 
1075 	dsl_dataset_name(ds, buf);
1076 
1077 	dsl_dataset_rele(ds, FTAG);
1078 }
1079 
1080 int
1081 dsl_dir_get_filesystem_count(dsl_dir_t *dd, uint64_t *count)
1082 {
1083 	if (dsl_dir_is_zapified(dd)) {
1084 		objset_t *os = dd->dd_pool->dp_meta_objset;
1085 		return (zap_lookup(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
1086 		    sizeof (*count), 1, count));
1087 	} else {
1088 		return (SET_ERROR(ENOENT));
1089 	}
1090 }
1091 
1092 int
1093 dsl_dir_get_snapshot_count(dsl_dir_t *dd, uint64_t *count)
1094 {
1095 	if (dsl_dir_is_zapified(dd)) {
1096 		objset_t *os = dd->dd_pool->dp_meta_objset;
1097 		return (zap_lookup(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
1098 		    sizeof (*count), 1, count));
1099 	} else {
1100 		return (SET_ERROR(ENOENT));
1101 	}
1102 }
1103 
1104 void
1105 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
1106 {
1107 	mutex_enter(&dd->dd_lock);
1108 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA,
1109 	    dsl_dir_get_quota(dd));
1110 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
1111 	    dsl_dir_get_reservation(dd));
1112 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALUSED,
1113 	    dsl_dir_get_logicalused(dd));
1114 	if (dsl_dir_phys(dd)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1115 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
1116 		    dsl_dir_get_usedsnap(dd));
1117 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
1118 		    dsl_dir_get_usedds(dd));
1119 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
1120 		    dsl_dir_get_usedrefreserv(dd));
1121 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
1122 		    dsl_dir_get_usedchild(dd));
1123 	}
1124 	mutex_exit(&dd->dd_lock);
1125 
1126 	uint64_t count;
1127 	if (dsl_dir_get_filesystem_count(dd, &count) == 0) {
1128 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_FILESYSTEM_COUNT,
1129 		    count);
1130 	}
1131 	if (dsl_dir_get_snapshot_count(dd, &count) == 0) {
1132 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_SNAPSHOT_COUNT,
1133 		    count);
1134 	}
1135 
1136 	if (dsl_dir_is_clone(dd)) {
1137 		char buf[ZFS_MAX_DATASET_NAME_LEN];
1138 		dsl_dir_get_origin(dd, buf);
1139 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
1140 	}
1141 
1142 }
1143 
1144 void
1145 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
1146 {
1147 	dsl_pool_t *dp = dd->dd_pool;
1148 
1149 	ASSERT(dsl_dir_phys(dd));
1150 
1151 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg)) {
1152 		/* up the hold count until we can be written out */
1153 		dmu_buf_add_ref(dd->dd_dbuf, dd);
1154 	}
1155 }
1156 
1157 static int64_t
1158 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
1159 {
1160 	uint64_t old_accounted = MAX(used, dsl_dir_phys(dd)->dd_reserved);
1161 	uint64_t new_accounted =
1162 	    MAX(used + delta, dsl_dir_phys(dd)->dd_reserved);
1163 	return (new_accounted - old_accounted);
1164 }
1165 
1166 void
1167 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
1168 {
1169 	ASSERT(dmu_tx_is_syncing(tx));
1170 
1171 	mutex_enter(&dd->dd_lock);
1172 	ASSERT0(dd->dd_tempreserved[tx->tx_txg & TXG_MASK]);
1173 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", (u_longlong_t)tx->tx_txg,
1174 	    (u_longlong_t)dd->dd_space_towrite[tx->tx_txg & TXG_MASK] / 1024);
1175 	dd->dd_space_towrite[tx->tx_txg & TXG_MASK] = 0;
1176 	mutex_exit(&dd->dd_lock);
1177 
1178 	/* release the hold from dsl_dir_dirty */
1179 	dmu_buf_rele(dd->dd_dbuf, dd);
1180 }
1181 
1182 static uint64_t
1183 dsl_dir_space_towrite(dsl_dir_t *dd)
1184 {
1185 	uint64_t space = 0;
1186 
1187 	ASSERT(MUTEX_HELD(&dd->dd_lock));
1188 
1189 	for (int i = 0; i < TXG_SIZE; i++)
1190 		space += dd->dd_space_towrite[i & TXG_MASK];
1191 
1192 	return (space);
1193 }
1194 
1195 /*
1196  * How much space would dd have available if ancestor had delta applied
1197  * to it?  If ondiskonly is set, we're only interested in what's
1198  * on-disk, not estimated pending changes.
1199  */
1200 uint64_t
1201 dsl_dir_space_available(dsl_dir_t *dd,
1202     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
1203 {
1204 	uint64_t parentspace, myspace, quota, used;
1205 
1206 	/*
1207 	 * If there are no restrictions otherwise, assume we have
1208 	 * unlimited space available.
1209 	 */
1210 	quota = UINT64_MAX;
1211 	parentspace = UINT64_MAX;
1212 
1213 	if (dd->dd_parent != NULL) {
1214 		parentspace = dsl_dir_space_available(dd->dd_parent,
1215 		    ancestor, delta, ondiskonly);
1216 	}
1217 
1218 	mutex_enter(&dd->dd_lock);
1219 	if (dsl_dir_phys(dd)->dd_quota != 0)
1220 		quota = dsl_dir_phys(dd)->dd_quota;
1221 	used = dsl_dir_phys(dd)->dd_used_bytes;
1222 	if (!ondiskonly)
1223 		used += dsl_dir_space_towrite(dd);
1224 
1225 	if (dd->dd_parent == NULL) {
1226 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool,
1227 		    ZFS_SPACE_CHECK_NORMAL);
1228 		quota = MIN(quota, poolsize);
1229 	}
1230 
1231 	if (dsl_dir_phys(dd)->dd_reserved > used && parentspace != UINT64_MAX) {
1232 		/*
1233 		 * We have some space reserved, in addition to what our
1234 		 * parent gave us.
1235 		 */
1236 		parentspace += dsl_dir_phys(dd)->dd_reserved - used;
1237 	}
1238 
1239 	if (dd == ancestor) {
1240 		ASSERT(delta <= 0);
1241 		ASSERT(used >= -delta);
1242 		used += delta;
1243 		if (parentspace != UINT64_MAX)
1244 			parentspace -= delta;
1245 	}
1246 
1247 	if (used > quota) {
1248 		/* over quota */
1249 		myspace = 0;
1250 	} else {
1251 		/*
1252 		 * the lesser of the space provided by our parent and
1253 		 * the space left in our quota
1254 		 */
1255 		myspace = MIN(parentspace, quota - used);
1256 	}
1257 
1258 	mutex_exit(&dd->dd_lock);
1259 
1260 	return (myspace);
1261 }
1262 
1263 struct tempreserve {
1264 	list_node_t tr_node;
1265 	dsl_dir_t *tr_ds;
1266 	uint64_t tr_size;
1267 };
1268 
1269 static int
1270 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
1271     boolean_t ignorequota, list_t *tr_list,
1272     dmu_tx_t *tx, boolean_t first)
1273 {
1274 	uint64_t txg;
1275 	uint64_t quota;
1276 	struct tempreserve *tr;
1277 	int retval;
1278 	uint64_t ext_quota;
1279 	uint64_t ref_rsrv;
1280 
1281 top_of_function:
1282 	txg = tx->tx_txg;
1283 	retval = EDQUOT;
1284 	ref_rsrv = 0;
1285 
1286 	ASSERT3U(txg, !=, 0);
1287 	ASSERT3S(asize, >, 0);
1288 
1289 	mutex_enter(&dd->dd_lock);
1290 
1291 	/*
1292 	 * Check against the dsl_dir's quota.  We don't add in the delta
1293 	 * when checking for over-quota because they get one free hit.
1294 	 */
1295 	uint64_t est_inflight = dsl_dir_space_towrite(dd);
1296 	for (int i = 0; i < TXG_SIZE; i++)
1297 		est_inflight += dd->dd_tempreserved[i];
1298 	uint64_t used_on_disk = dsl_dir_phys(dd)->dd_used_bytes;
1299 
1300 	/*
1301 	 * On the first iteration, fetch the dataset's used-on-disk and
1302 	 * refreservation values. Also, if checkrefquota is set, test if
1303 	 * allocating this space would exceed the dataset's refquota.
1304 	 */
1305 	if (first && tx->tx_objset) {
1306 		int error;
1307 		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
1308 
1309 		error = dsl_dataset_check_quota(ds, !netfree,
1310 		    asize, est_inflight, &used_on_disk, &ref_rsrv);
1311 		if (error != 0) {
1312 			mutex_exit(&dd->dd_lock);
1313 			DMU_TX_STAT_BUMP(dmu_tx_quota);
1314 			return (error);
1315 		}
1316 	}
1317 
1318 	/*
1319 	 * If this transaction will result in a net free of space,
1320 	 * we want to let it through.
1321 	 */
1322 	if (ignorequota || netfree || dsl_dir_phys(dd)->dd_quota == 0 ||
1323 	    (tx->tx_objset && dmu_objset_type(tx->tx_objset) == DMU_OST_ZVOL &&
1324 	    zvol_enforce_quotas == B_FALSE))
1325 		quota = UINT64_MAX;
1326 	else
1327 		quota = dsl_dir_phys(dd)->dd_quota;
1328 
1329 	/*
1330 	 * Adjust the quota against the actual pool size at the root
1331 	 * minus any outstanding deferred frees.
1332 	 * To ensure that it's possible to remove files from a full
1333 	 * pool without inducing transient overcommits, we throttle
1334 	 * netfree transactions against a quota that is slightly larger,
1335 	 * but still within the pool's allocation slop.  In cases where
1336 	 * we're very close to full, this will allow a steady trickle of
1337 	 * removes to get through.
1338 	 */
1339 	if (dd->dd_parent == NULL) {
1340 		uint64_t avail = dsl_pool_unreserved_space(dd->dd_pool,
1341 		    (netfree) ?
1342 		    ZFS_SPACE_CHECK_RESERVED : ZFS_SPACE_CHECK_NORMAL);
1343 
1344 		if (avail < quota) {
1345 			quota = avail;
1346 			retval = SET_ERROR(ENOSPC);
1347 		}
1348 	}
1349 
1350 	/*
1351 	 * If they are requesting more space, and our current estimate
1352 	 * is over quota, they get to try again unless the actual
1353 	 * on-disk is over quota and there are no pending changes
1354 	 * or deferred frees (which may free up space for us).
1355 	 */
1356 	ext_quota = quota >> 5;
1357 	if (quota == UINT64_MAX)
1358 		ext_quota = 0;
1359 
1360 	if (used_on_disk >= quota) {
1361 		/* Quota exceeded */
1362 		mutex_exit(&dd->dd_lock);
1363 		DMU_TX_STAT_BUMP(dmu_tx_quota);
1364 		return (retval);
1365 	} else if (used_on_disk + est_inflight >= quota + ext_quota) {
1366 		if (est_inflight > 0 || used_on_disk < quota) {
1367 			retval = SET_ERROR(ERESTART);
1368 		} else {
1369 			ASSERT3U(used_on_disk, >=, quota);
1370 
1371 			if (retval == ENOSPC && (used_on_disk - quota) <
1372 			    dsl_pool_deferred_space(dd->dd_pool)) {
1373 				retval = SET_ERROR(ERESTART);
1374 			}
1375 		}
1376 
1377 		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
1378 		    "quota=%lluK tr=%lluK err=%d\n",
1379 		    (u_longlong_t)used_on_disk>>10,
1380 		    (u_longlong_t)est_inflight>>10,
1381 		    (u_longlong_t)quota>>10, (u_longlong_t)asize>>10, retval);
1382 		mutex_exit(&dd->dd_lock);
1383 		DMU_TX_STAT_BUMP(dmu_tx_quota);
1384 		return (retval);
1385 	}
1386 
1387 	/* We need to up our estimated delta before dropping dd_lock */
1388 	dd->dd_tempreserved[txg & TXG_MASK] += asize;
1389 
1390 	uint64_t parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
1391 	    asize - ref_rsrv);
1392 	mutex_exit(&dd->dd_lock);
1393 
1394 	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1395 	tr->tr_ds = dd;
1396 	tr->tr_size = asize;
1397 	list_insert_tail(tr_list, tr);
1398 
1399 	/* see if it's OK with our parent */
1400 	if (dd->dd_parent != NULL && parent_rsrv != 0) {
1401 		/*
1402 		 * Recurse on our parent without recursion. This has been
1403 		 * observed to be potentially large stack usage even within
1404 		 * the test suite. Largest seen stack was 7632 bytes on linux.
1405 		 */
1406 
1407 		dd = dd->dd_parent;
1408 		asize = parent_rsrv;
1409 		ignorequota = (dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
1410 		first = B_FALSE;
1411 		goto top_of_function;
1412 	}
1413 
1414 	return (0);
1415 }
1416 
1417 /*
1418  * Reserve space in this dsl_dir, to be used in this tx's txg.
1419  * After the space has been dirtied (and dsl_dir_willuse_space()
1420  * has been called), the reservation should be canceled, using
1421  * dsl_dir_tempreserve_clear().
1422  */
1423 int
1424 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
1425     boolean_t netfree, void **tr_cookiep, dmu_tx_t *tx)
1426 {
1427 	int err;
1428 	list_t *tr_list;
1429 
1430 	if (asize == 0) {
1431 		*tr_cookiep = NULL;
1432 		return (0);
1433 	}
1434 
1435 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
1436 	list_create(tr_list, sizeof (struct tempreserve),
1437 	    offsetof(struct tempreserve, tr_node));
1438 	ASSERT3S(asize, >, 0);
1439 
1440 	err = arc_tempreserve_space(dd->dd_pool->dp_spa, lsize, tx->tx_txg);
1441 	if (err == 0) {
1442 		struct tempreserve *tr;
1443 
1444 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1445 		tr->tr_size = lsize;
1446 		list_insert_tail(tr_list, tr);
1447 	} else {
1448 		if (err == EAGAIN) {
1449 			/*
1450 			 * If arc_memory_throttle() detected that pageout
1451 			 * is running and we are low on memory, we delay new
1452 			 * non-pageout transactions to give pageout an
1453 			 * advantage.
1454 			 *
1455 			 * It is unfortunate to be delaying while the caller's
1456 			 * locks are held.
1457 			 */
1458 			txg_delay(dd->dd_pool, tx->tx_txg,
1459 			    MSEC2NSEC(10), MSEC2NSEC(10));
1460 			err = SET_ERROR(ERESTART);
1461 		}
1462 	}
1463 
1464 	if (err == 0) {
1465 		err = dsl_dir_tempreserve_impl(dd, asize, netfree,
1466 		    B_FALSE, tr_list, tx, B_TRUE);
1467 	}
1468 
1469 	if (err != 0)
1470 		dsl_dir_tempreserve_clear(tr_list, tx);
1471 	else
1472 		*tr_cookiep = tr_list;
1473 
1474 	return (err);
1475 }
1476 
1477 /*
1478  * Clear a temporary reservation that we previously made with
1479  * dsl_dir_tempreserve_space().
1480  */
1481 void
1482 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
1483 {
1484 	int txgidx = tx->tx_txg & TXG_MASK;
1485 	list_t *tr_list = tr_cookie;
1486 	struct tempreserve *tr;
1487 
1488 	ASSERT3U(tx->tx_txg, !=, 0);
1489 
1490 	if (tr_cookie == NULL)
1491 		return;
1492 
1493 	while ((tr = list_remove_head(tr_list)) != NULL) {
1494 		if (tr->tr_ds) {
1495 			mutex_enter(&tr->tr_ds->dd_lock);
1496 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
1497 			    tr->tr_size);
1498 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
1499 			mutex_exit(&tr->tr_ds->dd_lock);
1500 		} else {
1501 			arc_tempreserve_clear(tr->tr_size);
1502 		}
1503 		kmem_free(tr, sizeof (struct tempreserve));
1504 	}
1505 
1506 	kmem_free(tr_list, sizeof (list_t));
1507 }
1508 
1509 /*
1510  * This should be called from open context when we think we're going to write
1511  * or free space, for example when dirtying data. Be conservative; it's okay
1512  * to write less space or free more, but we don't want to write more or free
1513  * less than the amount specified.
1514  *
1515  * NOTE: The behavior of this function is identical to the Illumos / FreeBSD
1516  * version however it has been adjusted to use an iterative rather than
1517  * recursive algorithm to minimize stack usage.
1518  */
1519 void
1520 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
1521 {
1522 	int64_t parent_space;
1523 	uint64_t est_used;
1524 
1525 	do {
1526 		mutex_enter(&dd->dd_lock);
1527 		if (space > 0)
1528 			dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
1529 
1530 		est_used = dsl_dir_space_towrite(dd) +
1531 		    dsl_dir_phys(dd)->dd_used_bytes;
1532 		parent_space = parent_delta(dd, est_used, space);
1533 		mutex_exit(&dd->dd_lock);
1534 
1535 		/* Make sure that we clean up dd_space_to* */
1536 		dsl_dir_dirty(dd, tx);
1537 
1538 		dd = dd->dd_parent;
1539 		space = parent_space;
1540 	} while (space && dd);
1541 }
1542 
1543 /* call from syncing context when we actually write/free space for this dd */
1544 void
1545 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
1546     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
1547 {
1548 	int64_t accounted_delta;
1549 
1550 	ASSERT(dmu_tx_is_syncing(tx));
1551 	ASSERT(type < DD_USED_NUM);
1552 
1553 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1554 
1555 	/*
1556 	 * dsl_dataset_set_refreservation_sync_impl() calls this with
1557 	 * dd_lock held, so that it can atomically update
1558 	 * ds->ds_reserved and the dsl_dir accounting, so that
1559 	 * dsl_dataset_check_quota() can see dataset and dir accounting
1560 	 * consistently.
1561 	 */
1562 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
1563 	if (needlock)
1564 		mutex_enter(&dd->dd_lock);
1565 	dsl_dir_phys_t *ddp = dsl_dir_phys(dd);
1566 	accounted_delta = parent_delta(dd, ddp->dd_used_bytes, used);
1567 	ASSERT(used >= 0 || ddp->dd_used_bytes >= -used);
1568 	ASSERT(compressed >= 0 || ddp->dd_compressed_bytes >= -compressed);
1569 	ASSERT(uncompressed >= 0 ||
1570 	    ddp->dd_uncompressed_bytes >= -uncompressed);
1571 	ddp->dd_used_bytes += used;
1572 	ddp->dd_uncompressed_bytes += uncompressed;
1573 	ddp->dd_compressed_bytes += compressed;
1574 
1575 	if (ddp->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1576 		ASSERT(used >= 0 || ddp->dd_used_breakdown[type] >= -used);
1577 		ddp->dd_used_breakdown[type] += used;
1578 #ifdef ZFS_DEBUG
1579 		{
1580 			dd_used_t t;
1581 			uint64_t u = 0;
1582 			for (t = 0; t < DD_USED_NUM; t++)
1583 				u += ddp->dd_used_breakdown[t];
1584 			ASSERT3U(u, ==, ddp->dd_used_bytes);
1585 		}
1586 #endif
1587 	}
1588 	if (needlock)
1589 		mutex_exit(&dd->dd_lock);
1590 
1591 	if (dd->dd_parent != NULL) {
1592 		dsl_dir_diduse_transfer_space(dd->dd_parent,
1593 		    accounted_delta, compressed, uncompressed,
1594 		    used, DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
1595 	}
1596 }
1597 
1598 void
1599 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
1600     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
1601 {
1602 	ASSERT(dmu_tx_is_syncing(tx));
1603 	ASSERT(oldtype < DD_USED_NUM);
1604 	ASSERT(newtype < DD_USED_NUM);
1605 
1606 	dsl_dir_phys_t *ddp = dsl_dir_phys(dd);
1607 	if (delta == 0 ||
1608 	    !(ddp->dd_flags & DD_FLAG_USED_BREAKDOWN))
1609 		return;
1610 
1611 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1612 	mutex_enter(&dd->dd_lock);
1613 	ASSERT(delta > 0 ?
1614 	    ddp->dd_used_breakdown[oldtype] >= delta :
1615 	    ddp->dd_used_breakdown[newtype] >= -delta);
1616 	ASSERT(ddp->dd_used_bytes >= ABS(delta));
1617 	ddp->dd_used_breakdown[oldtype] -= delta;
1618 	ddp->dd_used_breakdown[newtype] += delta;
1619 	mutex_exit(&dd->dd_lock);
1620 }
1621 
1622 void
1623 dsl_dir_diduse_transfer_space(dsl_dir_t *dd, int64_t used,
1624     int64_t compressed, int64_t uncompressed, int64_t tonew,
1625     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
1626 {
1627 	int64_t accounted_delta;
1628 
1629 	ASSERT(dmu_tx_is_syncing(tx));
1630 	ASSERT(oldtype < DD_USED_NUM);
1631 	ASSERT(newtype < DD_USED_NUM);
1632 
1633 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1634 
1635 	mutex_enter(&dd->dd_lock);
1636 	dsl_dir_phys_t *ddp = dsl_dir_phys(dd);
1637 	accounted_delta = parent_delta(dd, ddp->dd_used_bytes, used);
1638 	ASSERT(used >= 0 || ddp->dd_used_bytes >= -used);
1639 	ASSERT(compressed >= 0 || ddp->dd_compressed_bytes >= -compressed);
1640 	ASSERT(uncompressed >= 0 ||
1641 	    ddp->dd_uncompressed_bytes >= -uncompressed);
1642 	ddp->dd_used_bytes += used;
1643 	ddp->dd_uncompressed_bytes += uncompressed;
1644 	ddp->dd_compressed_bytes += compressed;
1645 
1646 	if (ddp->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1647 		ASSERT(tonew - used <= 0 ||
1648 		    ddp->dd_used_breakdown[oldtype] >= tonew - used);
1649 		ASSERT(tonew >= 0 ||
1650 		    ddp->dd_used_breakdown[newtype] >= -tonew);
1651 		ddp->dd_used_breakdown[oldtype] -= tonew - used;
1652 		ddp->dd_used_breakdown[newtype] += tonew;
1653 #ifdef ZFS_DEBUG
1654 		{
1655 			dd_used_t t;
1656 			uint64_t u = 0;
1657 			for (t = 0; t < DD_USED_NUM; t++)
1658 				u += ddp->dd_used_breakdown[t];
1659 			ASSERT3U(u, ==, ddp->dd_used_bytes);
1660 		}
1661 #endif
1662 	}
1663 	mutex_exit(&dd->dd_lock);
1664 
1665 	if (dd->dd_parent != NULL) {
1666 		dsl_dir_diduse_transfer_space(dd->dd_parent,
1667 		    accounted_delta, compressed, uncompressed,
1668 		    used, DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
1669 	}
1670 }
1671 
1672 typedef struct dsl_dir_set_qr_arg {
1673 	const char *ddsqra_name;
1674 	zprop_source_t ddsqra_source;
1675 	uint64_t ddsqra_value;
1676 } dsl_dir_set_qr_arg_t;
1677 
1678 static int
1679 dsl_dir_set_quota_check(void *arg, dmu_tx_t *tx)
1680 {
1681 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1682 	dsl_pool_t *dp = dmu_tx_pool(tx);
1683 	dsl_dataset_t *ds;
1684 	int error;
1685 	uint64_t towrite, newval;
1686 
1687 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1688 	if (error != 0)
1689 		return (error);
1690 
1691 	error = dsl_prop_predict(ds->ds_dir, "quota",
1692 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1693 	if (error != 0) {
1694 		dsl_dataset_rele(ds, FTAG);
1695 		return (error);
1696 	}
1697 
1698 	if (newval == 0) {
1699 		dsl_dataset_rele(ds, FTAG);
1700 		return (0);
1701 	}
1702 
1703 	mutex_enter(&ds->ds_dir->dd_lock);
1704 	/*
1705 	 * If we are doing the preliminary check in open context, and
1706 	 * there are pending changes, then don't fail it, since the
1707 	 * pending changes could under-estimate the amount of space to be
1708 	 * freed up.
1709 	 */
1710 	towrite = dsl_dir_space_towrite(ds->ds_dir);
1711 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1712 	    (newval < dsl_dir_phys(ds->ds_dir)->dd_reserved ||
1713 	    newval < dsl_dir_phys(ds->ds_dir)->dd_used_bytes + towrite)) {
1714 		error = SET_ERROR(ENOSPC);
1715 	}
1716 	mutex_exit(&ds->ds_dir->dd_lock);
1717 	dsl_dataset_rele(ds, FTAG);
1718 	return (error);
1719 }
1720 
1721 static void
1722 dsl_dir_set_quota_sync(void *arg, dmu_tx_t *tx)
1723 {
1724 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1725 	dsl_pool_t *dp = dmu_tx_pool(tx);
1726 	dsl_dataset_t *ds;
1727 	uint64_t newval;
1728 
1729 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1730 
1731 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1732 		dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_QUOTA),
1733 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1734 		    &ddsqra->ddsqra_value, tx);
1735 
1736 		VERIFY0(dsl_prop_get_int_ds(ds,
1737 		    zfs_prop_to_name(ZFS_PROP_QUOTA), &newval));
1738 	} else {
1739 		newval = ddsqra->ddsqra_value;
1740 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1741 		    zfs_prop_to_name(ZFS_PROP_QUOTA), (longlong_t)newval);
1742 	}
1743 
1744 	dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1745 	mutex_enter(&ds->ds_dir->dd_lock);
1746 	dsl_dir_phys(ds->ds_dir)->dd_quota = newval;
1747 	mutex_exit(&ds->ds_dir->dd_lock);
1748 	dsl_dataset_rele(ds, FTAG);
1749 }
1750 
1751 int
1752 dsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1753 {
1754 	dsl_dir_set_qr_arg_t ddsqra;
1755 
1756 	ddsqra.ddsqra_name = ddname;
1757 	ddsqra.ddsqra_source = source;
1758 	ddsqra.ddsqra_value = quota;
1759 
1760 	return (dsl_sync_task(ddname, dsl_dir_set_quota_check,
1761 	    dsl_dir_set_quota_sync, &ddsqra, 0,
1762 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
1763 }
1764 
1765 static int
1766 dsl_dir_set_reservation_check(void *arg, dmu_tx_t *tx)
1767 {
1768 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1769 	dsl_pool_t *dp = dmu_tx_pool(tx);
1770 	dsl_dataset_t *ds;
1771 	dsl_dir_t *dd;
1772 	uint64_t newval, used, avail;
1773 	int error;
1774 
1775 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1776 	if (error != 0)
1777 		return (error);
1778 	dd = ds->ds_dir;
1779 
1780 	/*
1781 	 * If we are doing the preliminary check in open context, the
1782 	 * space estimates may be inaccurate.
1783 	 */
1784 	if (!dmu_tx_is_syncing(tx)) {
1785 		dsl_dataset_rele(ds, FTAG);
1786 		return (0);
1787 	}
1788 
1789 	error = dsl_prop_predict(ds->ds_dir,
1790 	    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1791 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1792 	if (error != 0) {
1793 		dsl_dataset_rele(ds, FTAG);
1794 		return (error);
1795 	}
1796 
1797 	mutex_enter(&dd->dd_lock);
1798 	used = dsl_dir_phys(dd)->dd_used_bytes;
1799 	mutex_exit(&dd->dd_lock);
1800 
1801 	if (dd->dd_parent) {
1802 		avail = dsl_dir_space_available(dd->dd_parent,
1803 		    NULL, 0, FALSE);
1804 	} else {
1805 		avail = dsl_pool_adjustedsize(dd->dd_pool,
1806 		    ZFS_SPACE_CHECK_NORMAL) - used;
1807 	}
1808 
1809 	if (MAX(used, newval) > MAX(used, dsl_dir_phys(dd)->dd_reserved)) {
1810 		uint64_t delta = MAX(used, newval) -
1811 		    MAX(used, dsl_dir_phys(dd)->dd_reserved);
1812 
1813 		if (delta > avail ||
1814 		    (dsl_dir_phys(dd)->dd_quota > 0 &&
1815 		    newval > dsl_dir_phys(dd)->dd_quota))
1816 			error = SET_ERROR(ENOSPC);
1817 	}
1818 
1819 	dsl_dataset_rele(ds, FTAG);
1820 	return (error);
1821 }
1822 
1823 void
1824 dsl_dir_set_reservation_sync_impl(dsl_dir_t *dd, uint64_t value, dmu_tx_t *tx)
1825 {
1826 	uint64_t used;
1827 	int64_t delta;
1828 
1829 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1830 
1831 	mutex_enter(&dd->dd_lock);
1832 	used = dsl_dir_phys(dd)->dd_used_bytes;
1833 	delta = MAX(used, value) - MAX(used, dsl_dir_phys(dd)->dd_reserved);
1834 	dsl_dir_phys(dd)->dd_reserved = value;
1835 
1836 	if (dd->dd_parent != NULL) {
1837 		/* Roll up this additional usage into our ancestors */
1838 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1839 		    delta, 0, 0, tx);
1840 	}
1841 	mutex_exit(&dd->dd_lock);
1842 }
1843 
1844 static void
1845 dsl_dir_set_reservation_sync(void *arg, dmu_tx_t *tx)
1846 {
1847 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1848 	dsl_pool_t *dp = dmu_tx_pool(tx);
1849 	dsl_dataset_t *ds;
1850 	uint64_t newval;
1851 
1852 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1853 
1854 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1855 		dsl_prop_set_sync_impl(ds,
1856 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1857 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1858 		    &ddsqra->ddsqra_value, tx);
1859 
1860 		VERIFY0(dsl_prop_get_int_ds(ds,
1861 		    zfs_prop_to_name(ZFS_PROP_RESERVATION), &newval));
1862 	} else {
1863 		newval = ddsqra->ddsqra_value;
1864 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1865 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1866 		    (longlong_t)newval);
1867 	}
1868 
1869 	dsl_dir_set_reservation_sync_impl(ds->ds_dir, newval, tx);
1870 	dsl_dataset_rele(ds, FTAG);
1871 }
1872 
1873 int
1874 dsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1875     uint64_t reservation)
1876 {
1877 	dsl_dir_set_qr_arg_t ddsqra;
1878 
1879 	ddsqra.ddsqra_name = ddname;
1880 	ddsqra.ddsqra_source = source;
1881 	ddsqra.ddsqra_value = reservation;
1882 
1883 	return (dsl_sync_task(ddname, dsl_dir_set_reservation_check,
1884 	    dsl_dir_set_reservation_sync, &ddsqra, 0,
1885 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
1886 }
1887 
1888 static dsl_dir_t *
1889 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1890 {
1891 	for (; ds1; ds1 = ds1->dd_parent) {
1892 		dsl_dir_t *dd;
1893 		for (dd = ds2; dd; dd = dd->dd_parent) {
1894 			if (ds1 == dd)
1895 				return (dd);
1896 		}
1897 	}
1898 	return (NULL);
1899 }
1900 
1901 /*
1902  * If delta is applied to dd, how much of that delta would be applied to
1903  * ancestor?  Syncing context only.
1904  */
1905 static int64_t
1906 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1907 {
1908 	if (dd == ancestor)
1909 		return (delta);
1910 
1911 	mutex_enter(&dd->dd_lock);
1912 	delta = parent_delta(dd, dsl_dir_phys(dd)->dd_used_bytes, delta);
1913 	mutex_exit(&dd->dd_lock);
1914 	return (would_change(dd->dd_parent, delta, ancestor));
1915 }
1916 
1917 typedef struct dsl_dir_rename_arg {
1918 	const char *ddra_oldname;
1919 	const char *ddra_newname;
1920 	cred_t *ddra_cred;
1921 	proc_t *ddra_proc;
1922 } dsl_dir_rename_arg_t;
1923 
1924 typedef struct dsl_valid_rename_arg {
1925 	int char_delta;
1926 	int nest_delta;
1927 } dsl_valid_rename_arg_t;
1928 
1929 static int
1930 dsl_valid_rename(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1931 {
1932 	(void) dp;
1933 	dsl_valid_rename_arg_t *dvra = arg;
1934 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
1935 
1936 	dsl_dataset_name(ds, namebuf);
1937 
1938 	ASSERT3U(strnlen(namebuf, ZFS_MAX_DATASET_NAME_LEN),
1939 	    <, ZFS_MAX_DATASET_NAME_LEN);
1940 	int namelen = strlen(namebuf) + dvra->char_delta;
1941 	int depth = get_dataset_depth(namebuf) + dvra->nest_delta;
1942 
1943 	if (namelen >= ZFS_MAX_DATASET_NAME_LEN)
1944 		return (SET_ERROR(ENAMETOOLONG));
1945 	if (dvra->nest_delta > 0 && depth >= zfs_max_dataset_nesting)
1946 		return (SET_ERROR(ENAMETOOLONG));
1947 	return (0);
1948 }
1949 
1950 static int
1951 dsl_dir_rename_check(void *arg, dmu_tx_t *tx)
1952 {
1953 	dsl_dir_rename_arg_t *ddra = arg;
1954 	dsl_pool_t *dp = dmu_tx_pool(tx);
1955 	dsl_dir_t *dd, *newparent;
1956 	dsl_valid_rename_arg_t dvra;
1957 	dsl_dataset_t *parentds;
1958 	objset_t *parentos;
1959 	const char *mynewname;
1960 	int error;
1961 
1962 	/* target dir should exist */
1963 	error = dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL);
1964 	if (error != 0)
1965 		return (error);
1966 
1967 	/* new parent should exist */
1968 	error = dsl_dir_hold(dp, ddra->ddra_newname, FTAG,
1969 	    &newparent, &mynewname);
1970 	if (error != 0) {
1971 		dsl_dir_rele(dd, FTAG);
1972 		return (error);
1973 	}
1974 
1975 	/* can't rename to different pool */
1976 	if (dd->dd_pool != newparent->dd_pool) {
1977 		dsl_dir_rele(newparent, FTAG);
1978 		dsl_dir_rele(dd, FTAG);
1979 		return (SET_ERROR(EXDEV));
1980 	}
1981 
1982 	/* new name should not already exist */
1983 	if (mynewname == NULL) {
1984 		dsl_dir_rele(newparent, FTAG);
1985 		dsl_dir_rele(dd, FTAG);
1986 		return (SET_ERROR(EEXIST));
1987 	}
1988 
1989 	/* can't rename below anything but filesystems (eg. no ZVOLs) */
1990 	error = dsl_dataset_hold_obj(newparent->dd_pool,
1991 	    dsl_dir_phys(newparent)->dd_head_dataset_obj, FTAG, &parentds);
1992 	if (error != 0) {
1993 		dsl_dir_rele(newparent, FTAG);
1994 		dsl_dir_rele(dd, FTAG);
1995 		return (error);
1996 	}
1997 	error = dmu_objset_from_ds(parentds, &parentos);
1998 	if (error != 0) {
1999 		dsl_dataset_rele(parentds, FTAG);
2000 		dsl_dir_rele(newparent, FTAG);
2001 		dsl_dir_rele(dd, FTAG);
2002 		return (error);
2003 	}
2004 	if (dmu_objset_type(parentos) != DMU_OST_ZFS) {
2005 		dsl_dataset_rele(parentds, FTAG);
2006 		dsl_dir_rele(newparent, FTAG);
2007 		dsl_dir_rele(dd, FTAG);
2008 		return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
2009 	}
2010 	dsl_dataset_rele(parentds, FTAG);
2011 
2012 	ASSERT3U(strnlen(ddra->ddra_newname, ZFS_MAX_DATASET_NAME_LEN),
2013 	    <, ZFS_MAX_DATASET_NAME_LEN);
2014 	ASSERT3U(strnlen(ddra->ddra_oldname, ZFS_MAX_DATASET_NAME_LEN),
2015 	    <, ZFS_MAX_DATASET_NAME_LEN);
2016 	dvra.char_delta = strlen(ddra->ddra_newname)
2017 	    - strlen(ddra->ddra_oldname);
2018 	dvra.nest_delta = get_dataset_depth(ddra->ddra_newname)
2019 	    - get_dataset_depth(ddra->ddra_oldname);
2020 
2021 	/* if the name length is growing, validate child name lengths */
2022 	if (dvra.char_delta > 0 || dvra.nest_delta > 0) {
2023 		error = dmu_objset_find_dp(dp, dd->dd_object, dsl_valid_rename,
2024 		    &dvra, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
2025 		if (error != 0) {
2026 			dsl_dir_rele(newparent, FTAG);
2027 			dsl_dir_rele(dd, FTAG);
2028 			return (error);
2029 		}
2030 	}
2031 
2032 	if (dmu_tx_is_syncing(tx)) {
2033 		if (spa_feature_is_active(dp->dp_spa,
2034 		    SPA_FEATURE_FS_SS_LIMIT)) {
2035 			/*
2036 			 * Although this is the check function and we don't
2037 			 * normally make on-disk changes in check functions,
2038 			 * we need to do that here.
2039 			 *
2040 			 * Ensure this portion of the tree's counts have been
2041 			 * initialized in case the new parent has limits set.
2042 			 */
2043 			dsl_dir_init_fs_ss_count(dd, tx);
2044 		}
2045 	}
2046 
2047 	if (newparent != dd->dd_parent) {
2048 		/* is there enough space? */
2049 		uint64_t myspace =
2050 		    MAX(dsl_dir_phys(dd)->dd_used_bytes,
2051 		    dsl_dir_phys(dd)->dd_reserved);
2052 		objset_t *os = dd->dd_pool->dp_meta_objset;
2053 		uint64_t fs_cnt = 0;
2054 		uint64_t ss_cnt = 0;
2055 
2056 		if (dsl_dir_is_zapified(dd)) {
2057 			int err;
2058 
2059 			err = zap_lookup(os, dd->dd_object,
2060 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
2061 			    &fs_cnt);
2062 			if (err != ENOENT && err != 0) {
2063 				dsl_dir_rele(newparent, FTAG);
2064 				dsl_dir_rele(dd, FTAG);
2065 				return (err);
2066 			}
2067 
2068 			/*
2069 			 * have to add 1 for the filesystem itself that we're
2070 			 * moving
2071 			 */
2072 			fs_cnt++;
2073 
2074 			err = zap_lookup(os, dd->dd_object,
2075 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
2076 			    &ss_cnt);
2077 			if (err != ENOENT && err != 0) {
2078 				dsl_dir_rele(newparent, FTAG);
2079 				dsl_dir_rele(dd, FTAG);
2080 				return (err);
2081 			}
2082 		}
2083 
2084 		/* check for encryption errors */
2085 		error = dsl_dir_rename_crypt_check(dd, newparent);
2086 		if (error != 0) {
2087 			dsl_dir_rele(newparent, FTAG);
2088 			dsl_dir_rele(dd, FTAG);
2089 			return (SET_ERROR(EACCES));
2090 		}
2091 
2092 		/* no rename into our descendant */
2093 		if (closest_common_ancestor(dd, newparent) == dd) {
2094 			dsl_dir_rele(newparent, FTAG);
2095 			dsl_dir_rele(dd, FTAG);
2096 			return (SET_ERROR(EINVAL));
2097 		}
2098 
2099 		error = dsl_dir_transfer_possible(dd->dd_parent,
2100 		    newparent, fs_cnt, ss_cnt, myspace,
2101 		    ddra->ddra_cred, ddra->ddra_proc);
2102 		if (error != 0) {
2103 			dsl_dir_rele(newparent, FTAG);
2104 			dsl_dir_rele(dd, FTAG);
2105 			return (error);
2106 		}
2107 	}
2108 
2109 	dsl_dir_rele(newparent, FTAG);
2110 	dsl_dir_rele(dd, FTAG);
2111 	return (0);
2112 }
2113 
2114 static void
2115 dsl_dir_rename_sync(void *arg, dmu_tx_t *tx)
2116 {
2117 	dsl_dir_rename_arg_t *ddra = arg;
2118 	dsl_pool_t *dp = dmu_tx_pool(tx);
2119 	dsl_dir_t *dd, *newparent;
2120 	const char *mynewname;
2121 	objset_t *mos = dp->dp_meta_objset;
2122 
2123 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL));
2124 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_newname, FTAG, &newparent,
2125 	    &mynewname));
2126 
2127 	ASSERT3P(mynewname, !=, NULL);
2128 
2129 	/* Log this before we change the name. */
2130 	spa_history_log_internal_dd(dd, "rename", tx,
2131 	    "-> %s", ddra->ddra_newname);
2132 
2133 	if (newparent != dd->dd_parent) {
2134 		objset_t *os = dd->dd_pool->dp_meta_objset;
2135 		uint64_t fs_cnt = 0;
2136 		uint64_t ss_cnt = 0;
2137 
2138 		/*
2139 		 * We already made sure the dd counts were initialized in the
2140 		 * check function.
2141 		 */
2142 		if (spa_feature_is_active(dp->dp_spa,
2143 		    SPA_FEATURE_FS_SS_LIMIT)) {
2144 			VERIFY0(zap_lookup(os, dd->dd_object,
2145 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
2146 			    &fs_cnt));
2147 			/* add 1 for the filesystem itself that we're moving */
2148 			fs_cnt++;
2149 
2150 			VERIFY0(zap_lookup(os, dd->dd_object,
2151 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
2152 			    &ss_cnt));
2153 		}
2154 
2155 		dsl_fs_ss_count_adjust(dd->dd_parent, -fs_cnt,
2156 		    DD_FIELD_FILESYSTEM_COUNT, tx);
2157 		dsl_fs_ss_count_adjust(newparent, fs_cnt,
2158 		    DD_FIELD_FILESYSTEM_COUNT, tx);
2159 
2160 		dsl_fs_ss_count_adjust(dd->dd_parent, -ss_cnt,
2161 		    DD_FIELD_SNAPSHOT_COUNT, tx);
2162 		dsl_fs_ss_count_adjust(newparent, ss_cnt,
2163 		    DD_FIELD_SNAPSHOT_COUNT, tx);
2164 
2165 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
2166 		    -dsl_dir_phys(dd)->dd_used_bytes,
2167 		    -dsl_dir_phys(dd)->dd_compressed_bytes,
2168 		    -dsl_dir_phys(dd)->dd_uncompressed_bytes, tx);
2169 		dsl_dir_diduse_space(newparent, DD_USED_CHILD,
2170 		    dsl_dir_phys(dd)->dd_used_bytes,
2171 		    dsl_dir_phys(dd)->dd_compressed_bytes,
2172 		    dsl_dir_phys(dd)->dd_uncompressed_bytes, tx);
2173 
2174 		if (dsl_dir_phys(dd)->dd_reserved >
2175 		    dsl_dir_phys(dd)->dd_used_bytes) {
2176 			uint64_t unused_rsrv = dsl_dir_phys(dd)->dd_reserved -
2177 			    dsl_dir_phys(dd)->dd_used_bytes;
2178 
2179 			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
2180 			    -unused_rsrv, 0, 0, tx);
2181 			dsl_dir_diduse_space(newparent, DD_USED_CHILD_RSRV,
2182 			    unused_rsrv, 0, 0, tx);
2183 		}
2184 	}
2185 
2186 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
2187 
2188 	/* remove from old parent zapobj */
2189 	VERIFY0(zap_remove(mos,
2190 	    dsl_dir_phys(dd->dd_parent)->dd_child_dir_zapobj,
2191 	    dd->dd_myname, tx));
2192 
2193 	(void) strlcpy(dd->dd_myname, mynewname,
2194 	    sizeof (dd->dd_myname));
2195 	dsl_dir_rele(dd->dd_parent, dd);
2196 	dsl_dir_phys(dd)->dd_parent_obj = newparent->dd_object;
2197 	VERIFY0(dsl_dir_hold_obj(dp,
2198 	    newparent->dd_object, NULL, dd, &dd->dd_parent));
2199 
2200 	/* add to new parent zapobj */
2201 	VERIFY0(zap_add(mos, dsl_dir_phys(newparent)->dd_child_dir_zapobj,
2202 	    dd->dd_myname, 8, 1, &dd->dd_object, tx));
2203 
2204 	/* TODO: A rename callback to avoid these layering violations. */
2205 	zfsvfs_update_fromname(ddra->ddra_oldname, ddra->ddra_newname);
2206 	zvol_rename_minors(dp->dp_spa, ddra->ddra_oldname,
2207 	    ddra->ddra_newname, B_TRUE);
2208 
2209 	dsl_prop_notify_all(dd);
2210 
2211 	dsl_dir_rele(newparent, FTAG);
2212 	dsl_dir_rele(dd, FTAG);
2213 }
2214 
2215 int
2216 dsl_dir_rename(const char *oldname, const char *newname)
2217 {
2218 	dsl_dir_rename_arg_t ddra;
2219 
2220 	ddra.ddra_oldname = oldname;
2221 	ddra.ddra_newname = newname;
2222 	ddra.ddra_cred = CRED();
2223 	ddra.ddra_proc = curproc;
2224 
2225 	return (dsl_sync_task(oldname,
2226 	    dsl_dir_rename_check, dsl_dir_rename_sync, &ddra,
2227 	    3, ZFS_SPACE_CHECK_RESERVED));
2228 }
2229 
2230 int
2231 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd,
2232     uint64_t fs_cnt, uint64_t ss_cnt, uint64_t space,
2233     cred_t *cr, proc_t *proc)
2234 {
2235 	dsl_dir_t *ancestor;
2236 	int64_t adelta;
2237 	uint64_t avail;
2238 	int err;
2239 
2240 	ancestor = closest_common_ancestor(sdd, tdd);
2241 	adelta = would_change(sdd, -space, ancestor);
2242 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
2243 	if (avail < space)
2244 		return (SET_ERROR(ENOSPC));
2245 
2246 	err = dsl_fs_ss_limit_check(tdd, fs_cnt, ZFS_PROP_FILESYSTEM_LIMIT,
2247 	    ancestor, cr, proc);
2248 	if (err != 0)
2249 		return (err);
2250 	err = dsl_fs_ss_limit_check(tdd, ss_cnt, ZFS_PROP_SNAPSHOT_LIMIT,
2251 	    ancestor, cr, proc);
2252 	if (err != 0)
2253 		return (err);
2254 
2255 	return (0);
2256 }
2257 
2258 inode_timespec_t
2259 dsl_dir_snap_cmtime(dsl_dir_t *dd)
2260 {
2261 	inode_timespec_t t;
2262 
2263 	mutex_enter(&dd->dd_lock);
2264 	t = dd->dd_snap_cmtime;
2265 	mutex_exit(&dd->dd_lock);
2266 
2267 	return (t);
2268 }
2269 
2270 void
2271 dsl_dir_snap_cmtime_update(dsl_dir_t *dd, dmu_tx_t *tx)
2272 {
2273 	dsl_pool_t *dp = dmu_tx_pool(tx);
2274 	inode_timespec_t t;
2275 	gethrestime(&t);
2276 
2277 	mutex_enter(&dd->dd_lock);
2278 	dd->dd_snap_cmtime = t;
2279 	if (spa_feature_is_enabled(dp->dp_spa,
2280 	    SPA_FEATURE_EXTENSIBLE_DATASET)) {
2281 		objset_t *mos = dd->dd_pool->dp_meta_objset;
2282 		uint64_t ddobj = dd->dd_object;
2283 		dsl_dir_zapify(dd, tx);
2284 		VERIFY0(zap_update(mos, ddobj,
2285 		    DD_FIELD_SNAPSHOTS_CHANGED,
2286 		    sizeof (uint64_t),
2287 		    sizeof (inode_timespec_t) / sizeof (uint64_t),
2288 		    &t, tx));
2289 	}
2290 	mutex_exit(&dd->dd_lock);
2291 }
2292 
2293 void
2294 dsl_dir_zapify(dsl_dir_t *dd, dmu_tx_t *tx)
2295 {
2296 	objset_t *mos = dd->dd_pool->dp_meta_objset;
2297 	dmu_object_zapify(mos, dd->dd_object, DMU_OT_DSL_DIR, tx);
2298 }
2299 
2300 boolean_t
2301 dsl_dir_is_zapified(dsl_dir_t *dd)
2302 {
2303 	dmu_object_info_t doi;
2304 
2305 	dmu_object_info_from_db(dd->dd_dbuf, &doi);
2306 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
2307 }
2308 
2309 void
2310 dsl_dir_livelist_open(dsl_dir_t *dd, uint64_t obj)
2311 {
2312 	objset_t *mos = dd->dd_pool->dp_meta_objset;
2313 	ASSERT(spa_feature_is_active(dd->dd_pool->dp_spa,
2314 	    SPA_FEATURE_LIVELIST));
2315 	dsl_deadlist_open(&dd->dd_livelist, mos, obj);
2316 	bplist_create(&dd->dd_pending_allocs);
2317 	bplist_create(&dd->dd_pending_frees);
2318 }
2319 
2320 void
2321 dsl_dir_livelist_close(dsl_dir_t *dd)
2322 {
2323 	dsl_deadlist_close(&dd->dd_livelist);
2324 	bplist_destroy(&dd->dd_pending_allocs);
2325 	bplist_destroy(&dd->dd_pending_frees);
2326 }
2327 
2328 void
2329 dsl_dir_remove_livelist(dsl_dir_t *dd, dmu_tx_t *tx, boolean_t total)
2330 {
2331 	uint64_t obj;
2332 	dsl_pool_t *dp = dmu_tx_pool(tx);
2333 	spa_t *spa = dp->dp_spa;
2334 	livelist_condense_entry_t to_condense = spa->spa_to_condense;
2335 
2336 	if (!dsl_deadlist_is_open(&dd->dd_livelist))
2337 		return;
2338 
2339 	/*
2340 	 * If the livelist being removed is set to be condensed, stop the
2341 	 * condense zthr and indicate the cancellation in the spa_to_condense
2342 	 * struct in case the condense no-wait synctask has already started
2343 	 */
2344 	zthr_t *ll_condense_thread = spa->spa_livelist_condense_zthr;
2345 	if (ll_condense_thread != NULL &&
2346 	    (to_condense.ds != NULL) && (to_condense.ds->ds_dir == dd)) {
2347 		/*
2348 		 * We use zthr_wait_cycle_done instead of zthr_cancel
2349 		 * because we don't want to destroy the zthr, just have
2350 		 * it skip its current task.
2351 		 */
2352 		spa->spa_to_condense.cancelled = B_TRUE;
2353 		zthr_wait_cycle_done(ll_condense_thread);
2354 		/*
2355 		 * If we've returned from zthr_wait_cycle_done without
2356 		 * clearing the to_condense data structure it's either
2357 		 * because the no-wait synctask has started (which is
2358 		 * indicated by 'syncing' field of to_condense) and we
2359 		 * can expect it to clear to_condense on its own.
2360 		 * Otherwise, we returned before the zthr ran. The
2361 		 * checkfunc will now fail as cancelled == B_TRUE so we
2362 		 * can safely NULL out ds, allowing a different dir's
2363 		 * livelist to be condensed.
2364 		 *
2365 		 * We can be sure that the to_condense struct will not
2366 		 * be repopulated at this stage because both this
2367 		 * function and dsl_livelist_try_condense execute in
2368 		 * syncing context.
2369 		 */
2370 		if ((spa->spa_to_condense.ds != NULL) &&
2371 		    !spa->spa_to_condense.syncing) {
2372 			dmu_buf_rele(spa->spa_to_condense.ds->ds_dbuf,
2373 			    spa);
2374 			spa->spa_to_condense.ds = NULL;
2375 		}
2376 	}
2377 
2378 	dsl_dir_livelist_close(dd);
2379 	VERIFY0(zap_lookup(dp->dp_meta_objset, dd->dd_object,
2380 	    DD_FIELD_LIVELIST, sizeof (uint64_t), 1, &obj));
2381 	VERIFY0(zap_remove(dp->dp_meta_objset, dd->dd_object,
2382 	    DD_FIELD_LIVELIST, tx));
2383 	if (total) {
2384 		dsl_deadlist_free(dp->dp_meta_objset, obj, tx);
2385 		spa_feature_decr(spa, SPA_FEATURE_LIVELIST, tx);
2386 	}
2387 }
2388 
2389 static int
2390 dsl_dir_activity_in_progress(dsl_dir_t *dd, dsl_dataset_t *ds,
2391     zfs_wait_activity_t activity, boolean_t *in_progress)
2392 {
2393 	int error = 0;
2394 
2395 	ASSERT(MUTEX_HELD(&dd->dd_activity_lock));
2396 
2397 	switch (activity) {
2398 	case ZFS_WAIT_DELETEQ: {
2399 #ifdef _KERNEL
2400 		objset_t *os;
2401 		error = dmu_objset_from_ds(ds, &os);
2402 		if (error != 0)
2403 			break;
2404 
2405 		mutex_enter(&os->os_user_ptr_lock);
2406 		void *user = dmu_objset_get_user(os);
2407 		mutex_exit(&os->os_user_ptr_lock);
2408 		if (dmu_objset_type(os) != DMU_OST_ZFS ||
2409 		    user == NULL || zfs_get_vfs_flag_unmounted(os)) {
2410 			*in_progress = B_FALSE;
2411 			return (0);
2412 		}
2413 
2414 		uint64_t readonly = B_FALSE;
2415 		error = zfs_get_temporary_prop(ds, ZFS_PROP_READONLY, &readonly,
2416 		    NULL);
2417 
2418 		if (error != 0)
2419 			break;
2420 
2421 		if (readonly || !spa_writeable(dd->dd_pool->dp_spa)) {
2422 			*in_progress = B_FALSE;
2423 			return (0);
2424 		}
2425 
2426 		uint64_t count, unlinked_obj;
2427 		error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
2428 		    &unlinked_obj);
2429 		if (error != 0) {
2430 			dsl_dataset_rele(ds, FTAG);
2431 			break;
2432 		}
2433 		error = zap_count(os, unlinked_obj, &count);
2434 
2435 		if (error == 0)
2436 			*in_progress = (count != 0);
2437 		break;
2438 #else
2439 		/*
2440 		 * The delete queue is ZPL specific, and libzpool doesn't have
2441 		 * it. It doesn't make sense to wait for it.
2442 		 */
2443 		(void) ds;
2444 		*in_progress = B_FALSE;
2445 		break;
2446 #endif
2447 	}
2448 	default:
2449 		panic("unrecognized value for activity %d", activity);
2450 	}
2451 
2452 	return (error);
2453 }
2454 
2455 int
2456 dsl_dir_wait(dsl_dir_t *dd, dsl_dataset_t *ds, zfs_wait_activity_t activity,
2457     boolean_t *waited)
2458 {
2459 	int error = 0;
2460 	boolean_t in_progress;
2461 	dsl_pool_t *dp = dd->dd_pool;
2462 	for (;;) {
2463 		dsl_pool_config_enter(dp, FTAG);
2464 		error = dsl_dir_activity_in_progress(dd, ds, activity,
2465 		    &in_progress);
2466 		dsl_pool_config_exit(dp, FTAG);
2467 		if (error != 0 || !in_progress)
2468 			break;
2469 
2470 		*waited = B_TRUE;
2471 
2472 		if (cv_wait_sig(&dd->dd_activity_cv, &dd->dd_activity_lock) ==
2473 		    0 || dd->dd_activity_cancelled) {
2474 			error = SET_ERROR(EINTR);
2475 			break;
2476 		}
2477 	}
2478 	return (error);
2479 }
2480 
2481 void
2482 dsl_dir_cancel_waiters(dsl_dir_t *dd)
2483 {
2484 	mutex_enter(&dd->dd_activity_lock);
2485 	dd->dd_activity_cancelled = B_TRUE;
2486 	cv_broadcast(&dd->dd_activity_cv);
2487 	while (dd->dd_activity_waiters > 0)
2488 		cv_wait(&dd->dd_activity_cv, &dd->dd_activity_lock);
2489 	mutex_exit(&dd->dd_activity_lock);
2490 }
2491 
2492 #if defined(_KERNEL)
2493 EXPORT_SYMBOL(dsl_dir_set_quota);
2494 EXPORT_SYMBOL(dsl_dir_set_reservation);
2495 #endif
2496 
2497 /* CSTYLED */
2498 ZFS_MODULE_PARAM(zfs, , zvol_enforce_quotas, INT, ZMOD_RW,
2499 	"Enable strict ZVOL quota enforcment");
2500