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