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