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