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