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