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