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