xref: /titanic_41/usr/src/uts/common/fs/zfs/dsl_dir.c (revision 4b0d01e9d944e10498c80bc88d80a2f5cdd9be22)
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_enabled(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 
548 	dsl_dataset_rele(ds, FTAG);
549 
550 	kmem_free(zc, sizeof (zap_cursor_t));
551 	kmem_free(za, sizeof (zap_attribute_t));
552 
553 	/* we're in a sync task, update counts */
554 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
555 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
556 	    sizeof (my_fs_cnt), 1, &my_fs_cnt, tx));
557 	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
558 	    sizeof (my_ss_cnt), 1, &my_ss_cnt, tx));
559 }
560 
561 static int
562 dsl_dir_actv_fs_ss_limit_check(void *arg, dmu_tx_t *tx)
563 {
564 	char *ddname = (char *)arg;
565 	dsl_pool_t *dp = dmu_tx_pool(tx);
566 	dsl_dataset_t *ds;
567 	dsl_dir_t *dd;
568 	int error;
569 
570 	error = dsl_dataset_hold(dp, ddname, FTAG, &ds);
571 	if (error != 0)
572 		return (error);
573 
574 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
575 		dsl_dataset_rele(ds, FTAG);
576 		return (SET_ERROR(ENOTSUP));
577 	}
578 
579 	dd = ds->ds_dir;
580 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT) &&
581 	    dsl_dir_is_zapified(dd) &&
582 	    zap_contains(dp->dp_meta_objset, dd->dd_object,
583 	    DD_FIELD_FILESYSTEM_COUNT) == 0) {
584 		dsl_dataset_rele(ds, FTAG);
585 		return (SET_ERROR(EALREADY));
586 	}
587 
588 	dsl_dataset_rele(ds, FTAG);
589 	return (0);
590 }
591 
592 static void
593 dsl_dir_actv_fs_ss_limit_sync(void *arg, dmu_tx_t *tx)
594 {
595 	char *ddname = (char *)arg;
596 	dsl_pool_t *dp = dmu_tx_pool(tx);
597 	dsl_dataset_t *ds;
598 	spa_t *spa;
599 
600 	VERIFY0(dsl_dataset_hold(dp, ddname, FTAG, &ds));
601 
602 	spa = dsl_dataset_get_spa(ds);
603 
604 	if (!spa_feature_is_active(spa, SPA_FEATURE_FS_SS_LIMIT)) {
605 		/*
606 		 * Since the feature was not active and we're now setting a
607 		 * limit, increment the feature-active counter so that the
608 		 * feature becomes active for the first time.
609 		 *
610 		 * We are already in a sync task so we can update the MOS.
611 		 */
612 		spa_feature_incr(spa, SPA_FEATURE_FS_SS_LIMIT, tx);
613 	}
614 
615 	/*
616 	 * Since we are now setting a non-UINT64_MAX limit on the filesystem,
617 	 * we need to ensure the counts are correct. Descend down the tree from
618 	 * this point and update all of the counts to be accurate.
619 	 */
620 	dsl_dir_init_fs_ss_count(ds->ds_dir, tx);
621 
622 	dsl_dataset_rele(ds, FTAG);
623 }
624 
625 /*
626  * Make sure the feature is enabled and activate it if necessary.
627  * Since we're setting a limit, ensure the on-disk counts are valid.
628  * This is only called by the ioctl path when setting a limit value.
629  *
630  * We do not need to validate the new limit, since users who can change the
631  * limit are also allowed to exceed the limit.
632  */
633 int
634 dsl_dir_activate_fs_ss_limit(const char *ddname)
635 {
636 	int error;
637 
638 	error = dsl_sync_task(ddname, dsl_dir_actv_fs_ss_limit_check,
639 	    dsl_dir_actv_fs_ss_limit_sync, (void *)ddname, 0);
640 
641 	if (error == EALREADY)
642 		error = 0;
643 
644 	return (error);
645 }
646 
647 /*
648  * Used to determine if the filesystem_limit or snapshot_limit should be
649  * enforced. We allow the limit to be exceeded if the user has permission to
650  * write the property value. We pass in the creds that we got in the open
651  * context since we will always be the GZ root in syncing context. We also have
652  * to handle the case where we are allowed to change the limit on the current
653  * dataset, but there may be another limit in the tree above.
654  *
655  * We can never modify these two properties within a non-global zone. In
656  * addition, the other checks are modeled on zfs_secpolicy_write_perms. We
657  * can't use that function since we are already holding the dp_config_rwlock.
658  * In addition, we already have the dd and dealing with snapshots is simplified
659  * in this code.
660  */
661 
662 typedef enum {
663 	ENFORCE_ALWAYS,
664 	ENFORCE_NEVER,
665 	ENFORCE_ABOVE
666 } enforce_res_t;
667 
668 static enforce_res_t
669 dsl_enforce_ds_ss_limits(dsl_dir_t *dd, zfs_prop_t prop, cred_t *cr)
670 {
671 	enforce_res_t enforce = ENFORCE_ALWAYS;
672 	uint64_t obj;
673 	dsl_dataset_t *ds;
674 	uint64_t zoned;
675 
676 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
677 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
678 
679 #ifdef _KERNEL
680 	if (crgetzoneid(cr) != GLOBAL_ZONEID)
681 		return (ENFORCE_ALWAYS);
682 
683 	if (secpolicy_zfs(cr) == 0)
684 		return (ENFORCE_NEVER);
685 #endif
686 
687 	if ((obj = dd->dd_phys->dd_head_dataset_obj) == 0)
688 		return (ENFORCE_ALWAYS);
689 
690 	ASSERT(dsl_pool_config_held(dd->dd_pool));
691 
692 	if (dsl_dataset_hold_obj(dd->dd_pool, obj, FTAG, &ds) != 0)
693 		return (ENFORCE_ALWAYS);
694 
695 	if (dsl_prop_get_ds(ds, "zoned", 8, 1, &zoned, NULL) || zoned) {
696 		/* Only root can access zoned fs's from the GZ */
697 		enforce = ENFORCE_ALWAYS;
698 	} else {
699 		if (dsl_deleg_access_impl(ds, zfs_prop_to_name(prop), cr) == 0)
700 			enforce = ENFORCE_ABOVE;
701 	}
702 
703 	dsl_dataset_rele(ds, FTAG);
704 	return (enforce);
705 }
706 
707 /*
708  * Check if adding additional child filesystem(s) would exceed any filesystem
709  * limits or adding additional snapshot(s) would exceed any snapshot limits.
710  * The prop argument indicates which limit to check.
711  *
712  * Note that all filesystem limits up to the root (or the highest
713  * initialized) filesystem or the given ancestor must be satisfied.
714  */
715 int
716 dsl_fs_ss_limit_check(dsl_dir_t *dd, uint64_t delta, zfs_prop_t prop,
717     dsl_dir_t *ancestor, cred_t *cr)
718 {
719 	objset_t *os = dd->dd_pool->dp_meta_objset;
720 	uint64_t limit, count;
721 	char *count_prop;
722 	enforce_res_t enforce;
723 	int err = 0;
724 
725 	ASSERT(dsl_pool_config_held(dd->dd_pool));
726 	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
727 	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
728 
729 	/*
730 	 * If we're allowed to change the limit, don't enforce the limit
731 	 * e.g. this can happen if a snapshot is taken by an administrative
732 	 * user in the global zone (i.e. a recursive snapshot by root).
733 	 * However, we must handle the case of delegated permissions where we
734 	 * are allowed to change the limit on the current dataset, but there
735 	 * is another limit in the tree above.
736 	 */
737 	enforce = dsl_enforce_ds_ss_limits(dd, prop, cr);
738 	if (enforce == ENFORCE_NEVER)
739 		return (0);
740 
741 	/*
742 	 * e.g. if renaming a dataset with no snapshots, count adjustment
743 	 * is 0.
744 	 */
745 	if (delta == 0)
746 		return (0);
747 
748 	if (prop == ZFS_PROP_SNAPSHOT_LIMIT) {
749 		/*
750 		 * We don't enforce the limit for temporary snapshots. This is
751 		 * indicated by a NULL cred_t argument.
752 		 */
753 		if (cr == NULL)
754 			return (0);
755 
756 		count_prop = DD_FIELD_SNAPSHOT_COUNT;
757 	} else {
758 		count_prop = DD_FIELD_FILESYSTEM_COUNT;
759 	}
760 
761 	/*
762 	 * If an ancestor has been provided, stop checking the limit once we
763 	 * hit that dir. We need this during rename so that we don't overcount
764 	 * the check once we recurse up to the common ancestor.
765 	 */
766 	if (ancestor == dd)
767 		return (0);
768 
769 	/*
770 	 * If we hit an uninitialized node while recursing up the tree, we can
771 	 * stop since we know there is no limit here (or above). The counts are
772 	 * not valid on this node and we know we won't touch this node's counts.
773 	 */
774 	if (!dsl_dir_is_zapified(dd) || zap_lookup(os, dd->dd_object,
775 	    count_prop, sizeof (count), 1, &count) == ENOENT)
776 		return (0);
777 
778 	err = dsl_prop_get_dd(dd, zfs_prop_to_name(prop), 8, 1, &limit, NULL,
779 	    B_FALSE);
780 	if (err != 0)
781 		return (err);
782 
783 	/* Is there a limit which we've hit? */
784 	if (enforce == ENFORCE_ALWAYS && (count + delta) > limit)
785 		return (SET_ERROR(EDQUOT));
786 
787 	if (dd->dd_parent != NULL)
788 		err = dsl_fs_ss_limit_check(dd->dd_parent, delta, prop,
789 		    ancestor, cr);
790 
791 	return (err);
792 }
793 
794 /*
795  * Adjust the filesystem or snapshot count for the specified dsl_dir_t and all
796  * parents. When a new filesystem/snapshot is created, increment the count on
797  * all parents, and when a filesystem/snapshot is destroyed, decrement the
798  * count.
799  */
800 void
801 dsl_fs_ss_count_adjust(dsl_dir_t *dd, int64_t delta, const char *prop,
802     dmu_tx_t *tx)
803 {
804 	int err;
805 	objset_t *os = dd->dd_pool->dp_meta_objset;
806 	uint64_t count;
807 
808 	ASSERT(dsl_pool_config_held(dd->dd_pool));
809 	ASSERT(dmu_tx_is_syncing(tx));
810 	ASSERT(strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0 ||
811 	    strcmp(prop, DD_FIELD_SNAPSHOT_COUNT) == 0);
812 
813 	/*
814 	 * When we receive an incremental stream into a filesystem that already
815 	 * exists, a temporary clone is created.  We don't count this temporary
816 	 * clone, whose name begins with a '%'. We also ignore hidden ($FREE,
817 	 * $MOS & $ORIGIN) objsets.
818 	 */
819 	if ((dd->dd_myname[0] == '%' || dd->dd_myname[0] == '$') &&
820 	    strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0)
821 		return;
822 
823 	/*
824 	 * e.g. if renaming a dataset with no snapshots, count adjustment is 0
825 	 */
826 	if (delta == 0)
827 		return;
828 
829 	/*
830 	 * If we hit an uninitialized node while recursing up the tree, we can
831 	 * stop since we know the counts are not valid on this node and we
832 	 * know we shouldn't touch this node's counts. An uninitialized count
833 	 * on the node indicates that either the feature has not yet been
834 	 * activated or there are no limits on this part of the tree.
835 	 */
836 	if (!dsl_dir_is_zapified(dd) || (err = zap_lookup(os, dd->dd_object,
837 	    prop, sizeof (count), 1, &count)) == ENOENT)
838 		return;
839 	VERIFY0(err);
840 
841 	count += delta;
842 	/* Use a signed verify to make sure we're not neg. */
843 	VERIFY3S(count, >=, 0);
844 
845 	VERIFY0(zap_update(os, dd->dd_object, prop, sizeof (count), 1, &count,
846 	    tx));
847 
848 	/* Roll up this additional count into our ancestors */
849 	if (dd->dd_parent != NULL)
850 		dsl_fs_ss_count_adjust(dd->dd_parent, delta, prop, tx);
851 }
852 
853 uint64_t
854 dsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
855     dmu_tx_t *tx)
856 {
857 	objset_t *mos = dp->dp_meta_objset;
858 	uint64_t ddobj;
859 	dsl_dir_phys_t *ddphys;
860 	dmu_buf_t *dbuf;
861 
862 	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
863 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
864 	if (pds) {
865 		VERIFY(0 == zap_add(mos, pds->dd_phys->dd_child_dir_zapobj,
866 		    name, sizeof (uint64_t), 1, &ddobj, tx));
867 	} else {
868 		/* it's the root dir */
869 		VERIFY(0 == zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
870 		    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
871 	}
872 	VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
873 	dmu_buf_will_dirty(dbuf, tx);
874 	ddphys = dbuf->db_data;
875 
876 	ddphys->dd_creation_time = gethrestime_sec();
877 	if (pds) {
878 		ddphys->dd_parent_obj = pds->dd_object;
879 
880 		/* update the filesystem counts */
881 		dsl_fs_ss_count_adjust(pds, 1, DD_FIELD_FILESYSTEM_COUNT, tx);
882 	}
883 	ddphys->dd_props_zapobj = zap_create(mos,
884 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
885 	ddphys->dd_child_dir_zapobj = zap_create(mos,
886 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
887 	if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
888 		ddphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
889 	dmu_buf_rele(dbuf, FTAG);
890 
891 	return (ddobj);
892 }
893 
894 boolean_t
895 dsl_dir_is_clone(dsl_dir_t *dd)
896 {
897 	return (dd->dd_phys->dd_origin_obj &&
898 	    (dd->dd_pool->dp_origin_snap == NULL ||
899 	    dd->dd_phys->dd_origin_obj !=
900 	    dd->dd_pool->dp_origin_snap->ds_object));
901 }
902 
903 void
904 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
905 {
906 	mutex_enter(&dd->dd_lock);
907 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
908 	    dd->dd_phys->dd_used_bytes);
909 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA, dd->dd_phys->dd_quota);
910 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
911 	    dd->dd_phys->dd_reserved);
912 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
913 	    dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
914 	    (dd->dd_phys->dd_uncompressed_bytes * 100 /
915 	    dd->dd_phys->dd_compressed_bytes));
916 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALUSED,
917 	    dd->dd_phys->dd_uncompressed_bytes);
918 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
919 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
920 		    dd->dd_phys->dd_used_breakdown[DD_USED_SNAP]);
921 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
922 		    dd->dd_phys->dd_used_breakdown[DD_USED_HEAD]);
923 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
924 		    dd->dd_phys->dd_used_breakdown[DD_USED_REFRSRV]);
925 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
926 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD] +
927 		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD_RSRV]);
928 	}
929 	mutex_exit(&dd->dd_lock);
930 
931 	if (dsl_dir_is_zapified(dd)) {
932 		uint64_t count;
933 		objset_t *os = dd->dd_pool->dp_meta_objset;
934 
935 		if (zap_lookup(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
936 		    sizeof (count), 1, &count) == 0) {
937 			dsl_prop_nvlist_add_uint64(nv,
938 			    ZFS_PROP_FILESYSTEM_COUNT, count);
939 		}
940 		if (zap_lookup(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
941 		    sizeof (count), 1, &count) == 0) {
942 			dsl_prop_nvlist_add_uint64(nv,
943 			    ZFS_PROP_SNAPSHOT_COUNT, count);
944 		}
945 	}
946 
947 	if (dsl_dir_is_clone(dd)) {
948 		dsl_dataset_t *ds;
949 		char buf[MAXNAMELEN];
950 
951 		VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
952 		    dd->dd_phys->dd_origin_obj, FTAG, &ds));
953 		dsl_dataset_name(ds, buf);
954 		dsl_dataset_rele(ds, FTAG);
955 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
956 	}
957 }
958 
959 void
960 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
961 {
962 	dsl_pool_t *dp = dd->dd_pool;
963 
964 	ASSERT(dd->dd_phys);
965 
966 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg)) {
967 		/* up the hold count until we can be written out */
968 		dmu_buf_add_ref(dd->dd_dbuf, dd);
969 	}
970 }
971 
972 static int64_t
973 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
974 {
975 	uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
976 	uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
977 	return (new_accounted - old_accounted);
978 }
979 
980 void
981 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
982 {
983 	ASSERT(dmu_tx_is_syncing(tx));
984 
985 	mutex_enter(&dd->dd_lock);
986 	ASSERT0(dd->dd_tempreserved[tx->tx_txg&TXG_MASK]);
987 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
988 	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
989 	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
990 	mutex_exit(&dd->dd_lock);
991 
992 	/* release the hold from dsl_dir_dirty */
993 	dmu_buf_rele(dd->dd_dbuf, dd);
994 }
995 
996 static uint64_t
997 dsl_dir_space_towrite(dsl_dir_t *dd)
998 {
999 	uint64_t space = 0;
1000 	int i;
1001 
1002 	ASSERT(MUTEX_HELD(&dd->dd_lock));
1003 
1004 	for (i = 0; i < TXG_SIZE; i++) {
1005 		space += dd->dd_space_towrite[i&TXG_MASK];
1006 		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
1007 	}
1008 	return (space);
1009 }
1010 
1011 /*
1012  * How much space would dd have available if ancestor had delta applied
1013  * to it?  If ondiskonly is set, we're only interested in what's
1014  * on-disk, not estimated pending changes.
1015  */
1016 uint64_t
1017 dsl_dir_space_available(dsl_dir_t *dd,
1018     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
1019 {
1020 	uint64_t parentspace, myspace, quota, used;
1021 
1022 	/*
1023 	 * If there are no restrictions otherwise, assume we have
1024 	 * unlimited space available.
1025 	 */
1026 	quota = UINT64_MAX;
1027 	parentspace = UINT64_MAX;
1028 
1029 	if (dd->dd_parent != NULL) {
1030 		parentspace = dsl_dir_space_available(dd->dd_parent,
1031 		    ancestor, delta, ondiskonly);
1032 	}
1033 
1034 	mutex_enter(&dd->dd_lock);
1035 	if (dd->dd_phys->dd_quota != 0)
1036 		quota = dd->dd_phys->dd_quota;
1037 	used = dd->dd_phys->dd_used_bytes;
1038 	if (!ondiskonly)
1039 		used += dsl_dir_space_towrite(dd);
1040 
1041 	if (dd->dd_parent == NULL) {
1042 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
1043 		quota = MIN(quota, poolsize);
1044 	}
1045 
1046 	if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
1047 		/*
1048 		 * We have some space reserved, in addition to what our
1049 		 * parent gave us.
1050 		 */
1051 		parentspace += dd->dd_phys->dd_reserved - used;
1052 	}
1053 
1054 	if (dd == ancestor) {
1055 		ASSERT(delta <= 0);
1056 		ASSERT(used >= -delta);
1057 		used += delta;
1058 		if (parentspace != UINT64_MAX)
1059 			parentspace -= delta;
1060 	}
1061 
1062 	if (used > quota) {
1063 		/* over quota */
1064 		myspace = 0;
1065 	} else {
1066 		/*
1067 		 * the lesser of the space provided by our parent and
1068 		 * the space left in our quota
1069 		 */
1070 		myspace = MIN(parentspace, quota - used);
1071 	}
1072 
1073 	mutex_exit(&dd->dd_lock);
1074 
1075 	return (myspace);
1076 }
1077 
1078 struct tempreserve {
1079 	list_node_t tr_node;
1080 	dsl_dir_t *tr_ds;
1081 	uint64_t tr_size;
1082 };
1083 
1084 static int
1085 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
1086     boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
1087     dmu_tx_t *tx, boolean_t first)
1088 {
1089 	uint64_t txg = tx->tx_txg;
1090 	uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
1091 	uint64_t deferred = 0;
1092 	struct tempreserve *tr;
1093 	int retval = EDQUOT;
1094 	int txgidx = txg & TXG_MASK;
1095 	int i;
1096 	uint64_t ref_rsrv = 0;
1097 
1098 	ASSERT3U(txg, !=, 0);
1099 	ASSERT3S(asize, >, 0);
1100 
1101 	mutex_enter(&dd->dd_lock);
1102 
1103 	/*
1104 	 * Check against the dsl_dir's quota.  We don't add in the delta
1105 	 * when checking for over-quota because they get one free hit.
1106 	 */
1107 	est_inflight = dsl_dir_space_towrite(dd);
1108 	for (i = 0; i < TXG_SIZE; i++)
1109 		est_inflight += dd->dd_tempreserved[i];
1110 	used_on_disk = dd->dd_phys->dd_used_bytes;
1111 
1112 	/*
1113 	 * On the first iteration, fetch the dataset's used-on-disk and
1114 	 * refreservation values. Also, if checkrefquota is set, test if
1115 	 * allocating this space would exceed the dataset's refquota.
1116 	 */
1117 	if (first && tx->tx_objset) {
1118 		int error;
1119 		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
1120 
1121 		error = dsl_dataset_check_quota(ds, checkrefquota,
1122 		    asize, est_inflight, &used_on_disk, &ref_rsrv);
1123 		if (error) {
1124 			mutex_exit(&dd->dd_lock);
1125 			return (error);
1126 		}
1127 	}
1128 
1129 	/*
1130 	 * If this transaction will result in a net free of space,
1131 	 * we want to let it through.
1132 	 */
1133 	if (ignorequota || netfree || dd->dd_phys->dd_quota == 0)
1134 		quota = UINT64_MAX;
1135 	else
1136 		quota = dd->dd_phys->dd_quota;
1137 
1138 	/*
1139 	 * Adjust the quota against the actual pool size at the root
1140 	 * minus any outstanding deferred frees.
1141 	 * To ensure that it's possible to remove files from a full
1142 	 * pool without inducing transient overcommits, we throttle
1143 	 * netfree transactions against a quota that is slightly larger,
1144 	 * but still within the pool's allocation slop.  In cases where
1145 	 * we're very close to full, this will allow a steady trickle of
1146 	 * removes to get through.
1147 	 */
1148 	if (dd->dd_parent == NULL) {
1149 		spa_t *spa = dd->dd_pool->dp_spa;
1150 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
1151 		deferred = metaslab_class_get_deferred(spa_normal_class(spa));
1152 		if (poolsize - deferred < quota) {
1153 			quota = poolsize - deferred;
1154 			retval = ENOSPC;
1155 		}
1156 	}
1157 
1158 	/*
1159 	 * If they are requesting more space, and our current estimate
1160 	 * is over quota, they get to try again unless the actual
1161 	 * on-disk is over quota and there are no pending changes (which
1162 	 * may free up space for us).
1163 	 */
1164 	if (used_on_disk + est_inflight >= quota) {
1165 		if (est_inflight > 0 || used_on_disk < quota ||
1166 		    (retval == ENOSPC && used_on_disk < quota + deferred))
1167 			retval = ERESTART;
1168 		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
1169 		    "quota=%lluK tr=%lluK err=%d\n",
1170 		    used_on_disk>>10, est_inflight>>10,
1171 		    quota>>10, asize>>10, retval);
1172 		mutex_exit(&dd->dd_lock);
1173 		return (SET_ERROR(retval));
1174 	}
1175 
1176 	/* We need to up our estimated delta before dropping dd_lock */
1177 	dd->dd_tempreserved[txgidx] += asize;
1178 
1179 	parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
1180 	    asize - ref_rsrv);
1181 	mutex_exit(&dd->dd_lock);
1182 
1183 	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1184 	tr->tr_ds = dd;
1185 	tr->tr_size = asize;
1186 	list_insert_tail(tr_list, tr);
1187 
1188 	/* see if it's OK with our parent */
1189 	if (dd->dd_parent && parent_rsrv) {
1190 		boolean_t ismos = (dd->dd_phys->dd_head_dataset_obj == 0);
1191 
1192 		return (dsl_dir_tempreserve_impl(dd->dd_parent,
1193 		    parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
1194 	} else {
1195 		return (0);
1196 	}
1197 }
1198 
1199 /*
1200  * Reserve space in this dsl_dir, to be used in this tx's txg.
1201  * After the space has been dirtied (and dsl_dir_willuse_space()
1202  * has been called), the reservation should be canceled, using
1203  * dsl_dir_tempreserve_clear().
1204  */
1205 int
1206 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
1207     uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
1208 {
1209 	int err;
1210 	list_t *tr_list;
1211 
1212 	if (asize == 0) {
1213 		*tr_cookiep = NULL;
1214 		return (0);
1215 	}
1216 
1217 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
1218 	list_create(tr_list, sizeof (struct tempreserve),
1219 	    offsetof(struct tempreserve, tr_node));
1220 	ASSERT3S(asize, >, 0);
1221 	ASSERT3S(fsize, >=, 0);
1222 
1223 	err = arc_tempreserve_space(lsize, tx->tx_txg);
1224 	if (err == 0) {
1225 		struct tempreserve *tr;
1226 
1227 		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1228 		tr->tr_size = lsize;
1229 		list_insert_tail(tr_list, tr);
1230 	} else {
1231 		if (err == EAGAIN) {
1232 			/*
1233 			 * If arc_memory_throttle() detected that pageout
1234 			 * is running and we are low on memory, we delay new
1235 			 * non-pageout transactions to give pageout an
1236 			 * advantage.
1237 			 *
1238 			 * It is unfortunate to be delaying while the caller's
1239 			 * locks are held.
1240 			 */
1241 			txg_delay(dd->dd_pool, tx->tx_txg,
1242 			    MSEC2NSEC(10), MSEC2NSEC(10));
1243 			err = SET_ERROR(ERESTART);
1244 		}
1245 	}
1246 
1247 	if (err == 0) {
1248 		err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
1249 		    FALSE, asize > usize, tr_list, tx, TRUE);
1250 	}
1251 
1252 	if (err != 0)
1253 		dsl_dir_tempreserve_clear(tr_list, tx);
1254 	else
1255 		*tr_cookiep = tr_list;
1256 
1257 	return (err);
1258 }
1259 
1260 /*
1261  * Clear a temporary reservation that we previously made with
1262  * dsl_dir_tempreserve_space().
1263  */
1264 void
1265 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
1266 {
1267 	int txgidx = tx->tx_txg & TXG_MASK;
1268 	list_t *tr_list = tr_cookie;
1269 	struct tempreserve *tr;
1270 
1271 	ASSERT3U(tx->tx_txg, !=, 0);
1272 
1273 	if (tr_cookie == NULL)
1274 		return;
1275 
1276 	while ((tr = list_head(tr_list)) != NULL) {
1277 		if (tr->tr_ds) {
1278 			mutex_enter(&tr->tr_ds->dd_lock);
1279 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
1280 			    tr->tr_size);
1281 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
1282 			mutex_exit(&tr->tr_ds->dd_lock);
1283 		} else {
1284 			arc_tempreserve_clear(tr->tr_size);
1285 		}
1286 		list_remove(tr_list, tr);
1287 		kmem_free(tr, sizeof (struct tempreserve));
1288 	}
1289 
1290 	kmem_free(tr_list, sizeof (list_t));
1291 }
1292 
1293 /*
1294  * This should be called from open context when we think we're going to write
1295  * or free space, for example when dirtying data. Be conservative; it's okay
1296  * to write less space or free more, but we don't want to write more or free
1297  * less than the amount specified.
1298  */
1299 void
1300 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
1301 {
1302 	int64_t parent_space;
1303 	uint64_t est_used;
1304 
1305 	mutex_enter(&dd->dd_lock);
1306 	if (space > 0)
1307 		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
1308 
1309 	est_used = dsl_dir_space_towrite(dd) + dd->dd_phys->dd_used_bytes;
1310 	parent_space = parent_delta(dd, est_used, space);
1311 	mutex_exit(&dd->dd_lock);
1312 
1313 	/* Make sure that we clean up dd_space_to* */
1314 	dsl_dir_dirty(dd, tx);
1315 
1316 	/* XXX this is potentially expensive and unnecessary... */
1317 	if (parent_space && dd->dd_parent)
1318 		dsl_dir_willuse_space(dd->dd_parent, parent_space, tx);
1319 }
1320 
1321 /* call from syncing context when we actually write/free space for this dd */
1322 void
1323 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
1324     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
1325 {
1326 	int64_t accounted_delta;
1327 
1328 	/*
1329 	 * dsl_dataset_set_refreservation_sync_impl() calls this with
1330 	 * dd_lock held, so that it can atomically update
1331 	 * ds->ds_reserved and the dsl_dir accounting, so that
1332 	 * dsl_dataset_check_quota() can see dataset and dir accounting
1333 	 * consistently.
1334 	 */
1335 	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
1336 
1337 	ASSERT(dmu_tx_is_syncing(tx));
1338 	ASSERT(type < DD_USED_NUM);
1339 
1340 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1341 
1342 	if (needlock)
1343 		mutex_enter(&dd->dd_lock);
1344 	accounted_delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, used);
1345 	ASSERT(used >= 0 || dd->dd_phys->dd_used_bytes >= -used);
1346 	ASSERT(compressed >= 0 ||
1347 	    dd->dd_phys->dd_compressed_bytes >= -compressed);
1348 	ASSERT(uncompressed >= 0 ||
1349 	    dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
1350 	dd->dd_phys->dd_used_bytes += used;
1351 	dd->dd_phys->dd_uncompressed_bytes += uncompressed;
1352 	dd->dd_phys->dd_compressed_bytes += compressed;
1353 
1354 	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1355 		ASSERT(used > 0 ||
1356 		    dd->dd_phys->dd_used_breakdown[type] >= -used);
1357 		dd->dd_phys->dd_used_breakdown[type] += used;
1358 #ifdef DEBUG
1359 		dd_used_t t;
1360 		uint64_t u = 0;
1361 		for (t = 0; t < DD_USED_NUM; t++)
1362 			u += dd->dd_phys->dd_used_breakdown[t];
1363 		ASSERT3U(u, ==, dd->dd_phys->dd_used_bytes);
1364 #endif
1365 	}
1366 	if (needlock)
1367 		mutex_exit(&dd->dd_lock);
1368 
1369 	if (dd->dd_parent != NULL) {
1370 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1371 		    accounted_delta, compressed, uncompressed, tx);
1372 		dsl_dir_transfer_space(dd->dd_parent,
1373 		    used - accounted_delta,
1374 		    DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
1375 	}
1376 }
1377 
1378 void
1379 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
1380     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
1381 {
1382 	ASSERT(dmu_tx_is_syncing(tx));
1383 	ASSERT(oldtype < DD_USED_NUM);
1384 	ASSERT(newtype < DD_USED_NUM);
1385 
1386 	if (delta == 0 || !(dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN))
1387 		return;
1388 
1389 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1390 	mutex_enter(&dd->dd_lock);
1391 	ASSERT(delta > 0 ?
1392 	    dd->dd_phys->dd_used_breakdown[oldtype] >= delta :
1393 	    dd->dd_phys->dd_used_breakdown[newtype] >= -delta);
1394 	ASSERT(dd->dd_phys->dd_used_bytes >= ABS(delta));
1395 	dd->dd_phys->dd_used_breakdown[oldtype] -= delta;
1396 	dd->dd_phys->dd_used_breakdown[newtype] += delta;
1397 	mutex_exit(&dd->dd_lock);
1398 }
1399 
1400 typedef struct dsl_dir_set_qr_arg {
1401 	const char *ddsqra_name;
1402 	zprop_source_t ddsqra_source;
1403 	uint64_t ddsqra_value;
1404 } dsl_dir_set_qr_arg_t;
1405 
1406 static int
1407 dsl_dir_set_quota_check(void *arg, dmu_tx_t *tx)
1408 {
1409 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1410 	dsl_pool_t *dp = dmu_tx_pool(tx);
1411 	dsl_dataset_t *ds;
1412 	int error;
1413 	uint64_t towrite, newval;
1414 
1415 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1416 	if (error != 0)
1417 		return (error);
1418 
1419 	error = dsl_prop_predict(ds->ds_dir, "quota",
1420 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1421 	if (error != 0) {
1422 		dsl_dataset_rele(ds, FTAG);
1423 		return (error);
1424 	}
1425 
1426 	if (newval == 0) {
1427 		dsl_dataset_rele(ds, FTAG);
1428 		return (0);
1429 	}
1430 
1431 	mutex_enter(&ds->ds_dir->dd_lock);
1432 	/*
1433 	 * If we are doing the preliminary check in open context, and
1434 	 * there are pending changes, then don't fail it, since the
1435 	 * pending changes could under-estimate the amount of space to be
1436 	 * freed up.
1437 	 */
1438 	towrite = dsl_dir_space_towrite(ds->ds_dir);
1439 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1440 	    (newval < ds->ds_dir->dd_phys->dd_reserved ||
1441 	    newval < ds->ds_dir->dd_phys->dd_used_bytes + towrite)) {
1442 		error = SET_ERROR(ENOSPC);
1443 	}
1444 	mutex_exit(&ds->ds_dir->dd_lock);
1445 	dsl_dataset_rele(ds, FTAG);
1446 	return (error);
1447 }
1448 
1449 static void
1450 dsl_dir_set_quota_sync(void *arg, dmu_tx_t *tx)
1451 {
1452 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1453 	dsl_pool_t *dp = dmu_tx_pool(tx);
1454 	dsl_dataset_t *ds;
1455 	uint64_t newval;
1456 
1457 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1458 
1459 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1460 		dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_QUOTA),
1461 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1462 		    &ddsqra->ddsqra_value, tx);
1463 
1464 		VERIFY0(dsl_prop_get_int_ds(ds,
1465 		    zfs_prop_to_name(ZFS_PROP_QUOTA), &newval));
1466 	} else {
1467 		newval = ddsqra->ddsqra_value;
1468 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1469 		    zfs_prop_to_name(ZFS_PROP_QUOTA), (longlong_t)newval);
1470 	}
1471 
1472 	dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1473 	mutex_enter(&ds->ds_dir->dd_lock);
1474 	ds->ds_dir->dd_phys->dd_quota = newval;
1475 	mutex_exit(&ds->ds_dir->dd_lock);
1476 	dsl_dataset_rele(ds, FTAG);
1477 }
1478 
1479 int
1480 dsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1481 {
1482 	dsl_dir_set_qr_arg_t ddsqra;
1483 
1484 	ddsqra.ddsqra_name = ddname;
1485 	ddsqra.ddsqra_source = source;
1486 	ddsqra.ddsqra_value = quota;
1487 
1488 	return (dsl_sync_task(ddname, dsl_dir_set_quota_check,
1489 	    dsl_dir_set_quota_sync, &ddsqra, 0));
1490 }
1491 
1492 int
1493 dsl_dir_set_reservation_check(void *arg, dmu_tx_t *tx)
1494 {
1495 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1496 	dsl_pool_t *dp = dmu_tx_pool(tx);
1497 	dsl_dataset_t *ds;
1498 	dsl_dir_t *dd;
1499 	uint64_t newval, used, avail;
1500 	int error;
1501 
1502 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1503 	if (error != 0)
1504 		return (error);
1505 	dd = ds->ds_dir;
1506 
1507 	/*
1508 	 * If we are doing the preliminary check in open context, the
1509 	 * space estimates may be inaccurate.
1510 	 */
1511 	if (!dmu_tx_is_syncing(tx)) {
1512 		dsl_dataset_rele(ds, FTAG);
1513 		return (0);
1514 	}
1515 
1516 	error = dsl_prop_predict(ds->ds_dir,
1517 	    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1518 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1519 	if (error != 0) {
1520 		dsl_dataset_rele(ds, FTAG);
1521 		return (error);
1522 	}
1523 
1524 	mutex_enter(&dd->dd_lock);
1525 	used = dd->dd_phys->dd_used_bytes;
1526 	mutex_exit(&dd->dd_lock);
1527 
1528 	if (dd->dd_parent) {
1529 		avail = dsl_dir_space_available(dd->dd_parent,
1530 		    NULL, 0, FALSE);
1531 	} else {
1532 		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1533 	}
1534 
1535 	if (MAX(used, newval) > MAX(used, dd->dd_phys->dd_reserved)) {
1536 		uint64_t delta = MAX(used, newval) -
1537 		    MAX(used, dd->dd_phys->dd_reserved);
1538 
1539 		if (delta > avail ||
1540 		    (dd->dd_phys->dd_quota > 0 &&
1541 		    newval > dd->dd_phys->dd_quota))
1542 			error = SET_ERROR(ENOSPC);
1543 	}
1544 
1545 	dsl_dataset_rele(ds, FTAG);
1546 	return (error);
1547 }
1548 
1549 void
1550 dsl_dir_set_reservation_sync_impl(dsl_dir_t *dd, uint64_t value, dmu_tx_t *tx)
1551 {
1552 	uint64_t used;
1553 	int64_t delta;
1554 
1555 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1556 
1557 	mutex_enter(&dd->dd_lock);
1558 	used = dd->dd_phys->dd_used_bytes;
1559 	delta = MAX(used, value) - MAX(used, dd->dd_phys->dd_reserved);
1560 	dd->dd_phys->dd_reserved = value;
1561 
1562 	if (dd->dd_parent != NULL) {
1563 		/* Roll up this additional usage into our ancestors */
1564 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1565 		    delta, 0, 0, tx);
1566 	}
1567 	mutex_exit(&dd->dd_lock);
1568 }
1569 
1570 
1571 static void
1572 dsl_dir_set_reservation_sync(void *arg, dmu_tx_t *tx)
1573 {
1574 	dsl_dir_set_qr_arg_t *ddsqra = arg;
1575 	dsl_pool_t *dp = dmu_tx_pool(tx);
1576 	dsl_dataset_t *ds;
1577 	uint64_t newval;
1578 
1579 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1580 
1581 	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1582 		dsl_prop_set_sync_impl(ds,
1583 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1584 		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1585 		    &ddsqra->ddsqra_value, tx);
1586 
1587 		VERIFY0(dsl_prop_get_int_ds(ds,
1588 		    zfs_prop_to_name(ZFS_PROP_RESERVATION), &newval));
1589 	} else {
1590 		newval = ddsqra->ddsqra_value;
1591 		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1592 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1593 		    (longlong_t)newval);
1594 	}
1595 
1596 	dsl_dir_set_reservation_sync_impl(ds->ds_dir, newval, tx);
1597 	dsl_dataset_rele(ds, FTAG);
1598 }
1599 
1600 int
1601 dsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1602     uint64_t reservation)
1603 {
1604 	dsl_dir_set_qr_arg_t ddsqra;
1605 
1606 	ddsqra.ddsqra_name = ddname;
1607 	ddsqra.ddsqra_source = source;
1608 	ddsqra.ddsqra_value = reservation;
1609 
1610 	return (dsl_sync_task(ddname, dsl_dir_set_reservation_check,
1611 	    dsl_dir_set_reservation_sync, &ddsqra, 0));
1612 }
1613 
1614 static dsl_dir_t *
1615 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1616 {
1617 	for (; ds1; ds1 = ds1->dd_parent) {
1618 		dsl_dir_t *dd;
1619 		for (dd = ds2; dd; dd = dd->dd_parent) {
1620 			if (ds1 == dd)
1621 				return (dd);
1622 		}
1623 	}
1624 	return (NULL);
1625 }
1626 
1627 /*
1628  * If delta is applied to dd, how much of that delta would be applied to
1629  * ancestor?  Syncing context only.
1630  */
1631 static int64_t
1632 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1633 {
1634 	if (dd == ancestor)
1635 		return (delta);
1636 
1637 	mutex_enter(&dd->dd_lock);
1638 	delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, delta);
1639 	mutex_exit(&dd->dd_lock);
1640 	return (would_change(dd->dd_parent, delta, ancestor));
1641 }
1642 
1643 typedef struct dsl_dir_rename_arg {
1644 	const char *ddra_oldname;
1645 	const char *ddra_newname;
1646 	cred_t *ddra_cred;
1647 } dsl_dir_rename_arg_t;
1648 
1649 /* ARGSUSED */
1650 static int
1651 dsl_valid_rename(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1652 {
1653 	int *deltap = arg;
1654 	char namebuf[MAXNAMELEN];
1655 
1656 	dsl_dataset_name(ds, namebuf);
1657 
1658 	if (strlen(namebuf) + *deltap >= MAXNAMELEN)
1659 		return (SET_ERROR(ENAMETOOLONG));
1660 	return (0);
1661 }
1662 
1663 static int
1664 dsl_dir_rename_check(void *arg, dmu_tx_t *tx)
1665 {
1666 	dsl_dir_rename_arg_t *ddra = arg;
1667 	dsl_pool_t *dp = dmu_tx_pool(tx);
1668 	dsl_dir_t *dd, *newparent;
1669 	const char *mynewname;
1670 	int error;
1671 	int delta = strlen(ddra->ddra_newname) - strlen(ddra->ddra_oldname);
1672 
1673 	/* target dir should exist */
1674 	error = dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL);
1675 	if (error != 0)
1676 		return (error);
1677 
1678 	/* new parent should exist */
1679 	error = dsl_dir_hold(dp, ddra->ddra_newname, FTAG,
1680 	    &newparent, &mynewname);
1681 	if (error != 0) {
1682 		dsl_dir_rele(dd, FTAG);
1683 		return (error);
1684 	}
1685 
1686 	/* can't rename to different pool */
1687 	if (dd->dd_pool != newparent->dd_pool) {
1688 		dsl_dir_rele(newparent, FTAG);
1689 		dsl_dir_rele(dd, FTAG);
1690 		return (SET_ERROR(ENXIO));
1691 	}
1692 
1693 	/* new name should not already exist */
1694 	if (mynewname == NULL) {
1695 		dsl_dir_rele(newparent, FTAG);
1696 		dsl_dir_rele(dd, FTAG);
1697 		return (SET_ERROR(EEXIST));
1698 	}
1699 
1700 	/* if the name length is growing, validate child name lengths */
1701 	if (delta > 0) {
1702 		error = dmu_objset_find_dp(dp, dd->dd_object, dsl_valid_rename,
1703 		    &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1704 		if (error != 0) {
1705 			dsl_dir_rele(newparent, FTAG);
1706 			dsl_dir_rele(dd, FTAG);
1707 			return (error);
1708 		}
1709 	}
1710 
1711 	if (dmu_tx_is_syncing(tx)) {
1712 		if (spa_feature_is_enabled(dp->dp_spa,
1713 		    SPA_FEATURE_FS_SS_LIMIT)) {
1714 			/*
1715 			 * Although this is the check function and we don't
1716 			 * normally make on-disk changes in check functions,
1717 			 * we need to do that here.
1718 			 *
1719 			 * Ensure this portion of the tree's counts have been
1720 			 * initialized in case the new parent has limits set.
1721 			 */
1722 			dsl_dir_init_fs_ss_count(dd, tx);
1723 		}
1724 	}
1725 
1726 	if (newparent != dd->dd_parent) {
1727 		/* is there enough space? */
1728 		uint64_t myspace =
1729 		    MAX(dd->dd_phys->dd_used_bytes, dd->dd_phys->dd_reserved);
1730 		objset_t *os = dd->dd_pool->dp_meta_objset;
1731 		uint64_t fs_cnt = 0;
1732 		uint64_t ss_cnt = 0;
1733 
1734 		if (dsl_dir_is_zapified(dd)) {
1735 			int err;
1736 
1737 			err = zap_lookup(os, dd->dd_object,
1738 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1739 			    &fs_cnt);
1740 			if (err != ENOENT && err != 0)
1741 				return (err);
1742 
1743 			/*
1744 			 * have to add 1 for the filesystem itself that we're
1745 			 * moving
1746 			 */
1747 			fs_cnt++;
1748 
1749 			err = zap_lookup(os, dd->dd_object,
1750 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1751 			    &ss_cnt);
1752 			if (err != ENOENT && err != 0)
1753 				return (err);
1754 		}
1755 
1756 		/* no rename into our descendant */
1757 		if (closest_common_ancestor(dd, newparent) == dd) {
1758 			dsl_dir_rele(newparent, FTAG);
1759 			dsl_dir_rele(dd, FTAG);
1760 			return (SET_ERROR(EINVAL));
1761 		}
1762 
1763 		error = dsl_dir_transfer_possible(dd->dd_parent,
1764 		    newparent, fs_cnt, ss_cnt, myspace, ddra->ddra_cred);
1765 		if (error != 0) {
1766 			dsl_dir_rele(newparent, FTAG);
1767 			dsl_dir_rele(dd, FTAG);
1768 			return (error);
1769 		}
1770 	}
1771 
1772 	dsl_dir_rele(newparent, FTAG);
1773 	dsl_dir_rele(dd, FTAG);
1774 	return (0);
1775 }
1776 
1777 static void
1778 dsl_dir_rename_sync(void *arg, dmu_tx_t *tx)
1779 {
1780 	dsl_dir_rename_arg_t *ddra = arg;
1781 	dsl_pool_t *dp = dmu_tx_pool(tx);
1782 	dsl_dir_t *dd, *newparent;
1783 	const char *mynewname;
1784 	int error;
1785 	objset_t *mos = dp->dp_meta_objset;
1786 
1787 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL));
1788 	VERIFY0(dsl_dir_hold(dp, ddra->ddra_newname, FTAG, &newparent,
1789 	    &mynewname));
1790 
1791 	/* Log this before we change the name. */
1792 	spa_history_log_internal_dd(dd, "rename", tx,
1793 	    "-> %s", ddra->ddra_newname);
1794 
1795 	if (newparent != dd->dd_parent) {
1796 		objset_t *os = dd->dd_pool->dp_meta_objset;
1797 		uint64_t fs_cnt = 0;
1798 		uint64_t ss_cnt = 0;
1799 
1800 		/*
1801 		 * We already made sure the dd counts were initialized in the
1802 		 * check function.
1803 		 */
1804 		if (spa_feature_is_enabled(dp->dp_spa,
1805 		    SPA_FEATURE_FS_SS_LIMIT)) {
1806 			VERIFY0(zap_lookup(os, dd->dd_object,
1807 			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1808 			    &fs_cnt));
1809 			/* add 1 for the filesystem itself that we're moving */
1810 			fs_cnt++;
1811 
1812 			VERIFY0(zap_lookup(os, dd->dd_object,
1813 			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1814 			    &ss_cnt));
1815 		}
1816 
1817 		dsl_fs_ss_count_adjust(dd->dd_parent, -fs_cnt,
1818 		    DD_FIELD_FILESYSTEM_COUNT, tx);
1819 		dsl_fs_ss_count_adjust(newparent, fs_cnt,
1820 		    DD_FIELD_FILESYSTEM_COUNT, tx);
1821 
1822 		dsl_fs_ss_count_adjust(dd->dd_parent, -ss_cnt,
1823 		    DD_FIELD_SNAPSHOT_COUNT, tx);
1824 		dsl_fs_ss_count_adjust(newparent, ss_cnt,
1825 		    DD_FIELD_SNAPSHOT_COUNT, tx);
1826 
1827 		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1828 		    -dd->dd_phys->dd_used_bytes,
1829 		    -dd->dd_phys->dd_compressed_bytes,
1830 		    -dd->dd_phys->dd_uncompressed_bytes, tx);
1831 		dsl_dir_diduse_space(newparent, DD_USED_CHILD,
1832 		    dd->dd_phys->dd_used_bytes,
1833 		    dd->dd_phys->dd_compressed_bytes,
1834 		    dd->dd_phys->dd_uncompressed_bytes, tx);
1835 
1836 		if (dd->dd_phys->dd_reserved > dd->dd_phys->dd_used_bytes) {
1837 			uint64_t unused_rsrv = dd->dd_phys->dd_reserved -
1838 			    dd->dd_phys->dd_used_bytes;
1839 
1840 			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1841 			    -unused_rsrv, 0, 0, tx);
1842 			dsl_dir_diduse_space(newparent, DD_USED_CHILD_RSRV,
1843 			    unused_rsrv, 0, 0, tx);
1844 		}
1845 	}
1846 
1847 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1848 
1849 	/* remove from old parent zapobj */
1850 	error = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1851 	    dd->dd_myname, tx);
1852 	ASSERT0(error);
1853 
1854 	(void) strcpy(dd->dd_myname, mynewname);
1855 	dsl_dir_rele(dd->dd_parent, dd);
1856 	dd->dd_phys->dd_parent_obj = newparent->dd_object;
1857 	VERIFY0(dsl_dir_hold_obj(dp,
1858 	    newparent->dd_object, NULL, dd, &dd->dd_parent));
1859 
1860 	/* add to new parent zapobj */
1861 	VERIFY0(zap_add(mos, newparent->dd_phys->dd_child_dir_zapobj,
1862 	    dd->dd_myname, 8, 1, &dd->dd_object, tx));
1863 
1864 	dsl_prop_notify_all(dd);
1865 
1866 	dsl_dir_rele(newparent, FTAG);
1867 	dsl_dir_rele(dd, FTAG);
1868 }
1869 
1870 int
1871 dsl_dir_rename(const char *oldname, const char *newname)
1872 {
1873 	dsl_dir_rename_arg_t ddra;
1874 
1875 	ddra.ddra_oldname = oldname;
1876 	ddra.ddra_newname = newname;
1877 	ddra.ddra_cred = CRED();
1878 
1879 	return (dsl_sync_task(oldname,
1880 	    dsl_dir_rename_check, dsl_dir_rename_sync, &ddra, 3));
1881 }
1882 
1883 int
1884 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd,
1885     uint64_t fs_cnt, uint64_t ss_cnt, uint64_t space, cred_t *cr)
1886 {
1887 	dsl_dir_t *ancestor;
1888 	int64_t adelta;
1889 	uint64_t avail;
1890 	int err;
1891 
1892 	ancestor = closest_common_ancestor(sdd, tdd);
1893 	adelta = would_change(sdd, -space, ancestor);
1894 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1895 	if (avail < space)
1896 		return (SET_ERROR(ENOSPC));
1897 
1898 	err = dsl_fs_ss_limit_check(tdd, fs_cnt, ZFS_PROP_FILESYSTEM_LIMIT,
1899 	    ancestor, cr);
1900 	if (err != 0)
1901 		return (err);
1902 	err = dsl_fs_ss_limit_check(tdd, ss_cnt, ZFS_PROP_SNAPSHOT_LIMIT,
1903 	    ancestor, cr);
1904 	if (err != 0)
1905 		return (err);
1906 
1907 	return (0);
1908 }
1909 
1910 timestruc_t
1911 dsl_dir_snap_cmtime(dsl_dir_t *dd)
1912 {
1913 	timestruc_t t;
1914 
1915 	mutex_enter(&dd->dd_lock);
1916 	t = dd->dd_snap_cmtime;
1917 	mutex_exit(&dd->dd_lock);
1918 
1919 	return (t);
1920 }
1921 
1922 void
1923 dsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1924 {
1925 	timestruc_t t;
1926 
1927 	gethrestime(&t);
1928 	mutex_enter(&dd->dd_lock);
1929 	dd->dd_snap_cmtime = t;
1930 	mutex_exit(&dd->dd_lock);
1931 }
1932 
1933 void
1934 dsl_dir_zapify(dsl_dir_t *dd, dmu_tx_t *tx)
1935 {
1936 	objset_t *mos = dd->dd_pool->dp_meta_objset;
1937 	dmu_object_zapify(mos, dd->dd_object, DMU_OT_DSL_DIR, tx);
1938 }
1939 
1940 boolean_t
1941 dsl_dir_is_zapified(dsl_dir_t *dd)
1942 {
1943 	dmu_object_info_t doi;
1944 
1945 	dmu_object_info_from_db(dd->dd_dbuf, &doi);
1946 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
1947 }
1948