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