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