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