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