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