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