]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dir.c
Merge ZFS feature flags support and related bugfixes:
[FreeBSD/stable/8.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  */
26
27 #include <sys/dmu.h>
28 #include <sys/dmu_objset.h>
29 #include <sys/dmu_tx.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_dir.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_synctask.h>
34 #include <sys/dsl_deleg.h>
35 #include <sys/spa.h>
36 #include <sys/metaslab.h>
37 #include <sys/zap.h>
38 #include <sys/zio.h>
39 #include <sys/arc.h>
40 #include <sys/sunddi.h>
41 #include <sys/zvol.h>
42 #ifdef _KERNEL
43 #include <sys/zfs_vfsops.h>
44 #endif
45 #include "zfs_namecheck.h"
46
47 static uint64_t dsl_dir_space_towrite(dsl_dir_t *dd);
48 static void dsl_dir_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx);
49
50
51 /* ARGSUSED */
52 static void
53 dsl_dir_evict(dmu_buf_t *db, void *arg)
54 {
55         dsl_dir_t *dd = arg;
56         dsl_pool_t *dp = dd->dd_pool;
57         int t;
58
59         for (t = 0; t < TXG_SIZE; t++) {
60                 ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
61                 ASSERT(dd->dd_tempreserved[t] == 0);
62                 ASSERT(dd->dd_space_towrite[t] == 0);
63         }
64
65         if (dd->dd_parent)
66                 dsl_dir_close(dd->dd_parent, dd);
67
68         spa_close(dd->dd_pool->dp_spa, dd);
69
70         /*
71          * The props callback list should have been cleaned up by
72          * objset_evict().
73          */
74         list_destroy(&dd->dd_prop_cbs);
75         mutex_destroy(&dd->dd_lock);
76         kmem_free(dd, sizeof (dsl_dir_t));
77 }
78
79 int
80 dsl_dir_open_obj(dsl_pool_t *dp, uint64_t ddobj,
81     const char *tail, void *tag, dsl_dir_t **ddp)
82 {
83         dmu_buf_t *dbuf;
84         dsl_dir_t *dd;
85         int err;
86
87         ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
88             dsl_pool_sync_context(dp));
89
90         err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
91         if (err)
92                 return (err);
93         dd = dmu_buf_get_user(dbuf);
94 #ifdef ZFS_DEBUG
95         {
96                 dmu_object_info_t doi;
97                 dmu_object_info_from_db(dbuf, &doi);
98                 ASSERT3U(doi.doi_type, ==, DMU_OT_DSL_DIR);
99                 ASSERT3U(doi.doi_bonus_size, >=, sizeof (dsl_dir_phys_t));
100         }
101 #endif
102         if (dd == NULL) {
103                 dsl_dir_t *winner;
104
105                 dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
106                 dd->dd_object = ddobj;
107                 dd->dd_dbuf = dbuf;
108                 dd->dd_pool = dp;
109                 dd->dd_phys = dbuf->db_data;
110                 mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
111
112                 list_create(&dd->dd_prop_cbs, sizeof (dsl_prop_cb_record_t),
113                     offsetof(dsl_prop_cb_record_t, cbr_node));
114
115                 dsl_dir_snap_cmtime_update(dd);
116
117                 if (dd->dd_phys->dd_parent_obj) {
118                         err = dsl_dir_open_obj(dp, dd->dd_phys->dd_parent_obj,
119                             NULL, dd, &dd->dd_parent);
120                         if (err)
121                                 goto errout;
122                         if (tail) {
123 #ifdef ZFS_DEBUG
124                                 uint64_t foundobj;
125
126                                 err = zap_lookup(dp->dp_meta_objset,
127                                     dd->dd_parent->dd_phys->dd_child_dir_zapobj,
128                                     tail, sizeof (foundobj), 1, &foundobj);
129                                 ASSERT(err || foundobj == ddobj);
130 #endif
131                                 (void) strcpy(dd->dd_myname, tail);
132                         } else {
133                                 err = zap_value_search(dp->dp_meta_objset,
134                                     dd->dd_parent->dd_phys->dd_child_dir_zapobj,
135                                     ddobj, 0, dd->dd_myname);
136                         }
137                         if (err)
138                                 goto errout;
139                 } else {
140                         (void) strcpy(dd->dd_myname, spa_name(dp->dp_spa));
141                 }
142
143                 if (dsl_dir_is_clone(dd)) {
144                         dmu_buf_t *origin_bonus;
145                         dsl_dataset_phys_t *origin_phys;
146
147                         /*
148                          * We can't open the origin dataset, because
149                          * that would require opening this dsl_dir.
150                          * Just look at its phys directly instead.
151                          */
152                         err = dmu_bonus_hold(dp->dp_meta_objset,
153                             dd->dd_phys->dd_origin_obj, FTAG, &origin_bonus);
154                         if (err)
155                                 goto errout;
156                         origin_phys = origin_bonus->db_data;
157                         dd->dd_origin_txg =
158                             origin_phys->ds_creation_txg;
159                         dmu_buf_rele(origin_bonus, FTAG);
160                 }
161
162                 winner = dmu_buf_set_user_ie(dbuf, dd, &dd->dd_phys,
163                     dsl_dir_evict);
164                 if (winner) {
165                         if (dd->dd_parent)
166                                 dsl_dir_close(dd->dd_parent, dd);
167                         mutex_destroy(&dd->dd_lock);
168                         kmem_free(dd, sizeof (dsl_dir_t));
169                         dd = winner;
170                 } else {
171                         spa_open_ref(dp->dp_spa, dd);
172                 }
173         }
174
175         /*
176          * The dsl_dir_t has both open-to-close and instantiate-to-evict
177          * holds on the spa.  We need the open-to-close holds because
178          * otherwise the spa_refcnt wouldn't change when we open a
179          * dir which the spa also has open, so we could incorrectly
180          * think it was OK to unload/export/destroy the pool.  We need
181          * the instantiate-to-evict hold because the dsl_dir_t has a
182          * pointer to the dd_pool, which has a pointer to the spa_t.
183          */
184         spa_open_ref(dp->dp_spa, tag);
185         ASSERT3P(dd->dd_pool, ==, dp);
186         ASSERT3U(dd->dd_object, ==, ddobj);
187         ASSERT3P(dd->dd_dbuf, ==, dbuf);
188         *ddp = dd;
189         return (0);
190
191 errout:
192         if (dd->dd_parent)
193                 dsl_dir_close(dd->dd_parent, dd);
194         mutex_destroy(&dd->dd_lock);
195         kmem_free(dd, sizeof (dsl_dir_t));
196         dmu_buf_rele(dbuf, tag);
197         return (err);
198 }
199
200 void
201 dsl_dir_close(dsl_dir_t *dd, void *tag)
202 {
203         dprintf_dd(dd, "%s\n", "");
204         spa_close(dd->dd_pool->dp_spa, tag);
205         dmu_buf_rele(dd->dd_dbuf, tag);
206 }
207
208 /* buf must be long enough (MAXNAMELEN + strlen(MOS_DIR_NAME) + 1 should do) */
209 void
210 dsl_dir_name(dsl_dir_t *dd, char *buf)
211 {
212         if (dd->dd_parent) {
213                 dsl_dir_name(dd->dd_parent, buf);
214                 (void) strcat(buf, "/");
215         } else {
216                 buf[0] = '\0';
217         }
218         if (!MUTEX_HELD(&dd->dd_lock)) {
219                 /*
220                  * recursive mutex so that we can use
221                  * dprintf_dd() with dd_lock held
222                  */
223                 mutex_enter(&dd->dd_lock);
224                 (void) strcat(buf, dd->dd_myname);
225                 mutex_exit(&dd->dd_lock);
226         } else {
227                 (void) strcat(buf, dd->dd_myname);
228         }
229 }
230
231 /* Calculate name length, avoiding all the strcat calls of dsl_dir_name */
232 int
233 dsl_dir_namelen(dsl_dir_t *dd)
234 {
235         int result = 0;
236
237         if (dd->dd_parent) {
238                 /* parent's name + 1 for the "/" */
239                 result = dsl_dir_namelen(dd->dd_parent) + 1;
240         }
241
242         if (!MUTEX_HELD(&dd->dd_lock)) {
243                 /* see dsl_dir_name */
244                 mutex_enter(&dd->dd_lock);
245                 result += strlen(dd->dd_myname);
246                 mutex_exit(&dd->dd_lock);
247         } else {
248                 result += strlen(dd->dd_myname);
249         }
250
251         return (result);
252 }
253
254 static int
255 getcomponent(const char *path, char *component, const char **nextp)
256 {
257         char *p;
258         if ((path == NULL) || (path[0] == '\0'))
259                 return (ENOENT);
260         /* This would be a good place to reserve some namespace... */
261         p = strpbrk(path, "/@");
262         if (p && (p[1] == '/' || p[1] == '@')) {
263                 /* two separators in a row */
264                 return (EINVAL);
265         }
266         if (p == NULL || p == path) {
267                 /*
268                  * if the first thing is an @ or /, it had better be an
269                  * @ and it had better not have any more ats or slashes,
270                  * and it had better have something after the @.
271                  */
272                 if (p != NULL &&
273                     (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
274                         return (EINVAL);
275                 if (strlen(path) >= MAXNAMELEN)
276                         return (ENAMETOOLONG);
277                 (void) strcpy(component, path);
278                 p = NULL;
279         } else if (p[0] == '/') {
280                 if (p-path >= MAXNAMELEN)
281                         return (ENAMETOOLONG);
282                 (void) strncpy(component, path, p - path);
283                 component[p-path] = '\0';
284                 p++;
285         } else if (p[0] == '@') {
286                 /*
287                  * if the next separator is an @, there better not be
288                  * any more slashes.
289                  */
290                 if (strchr(path, '/'))
291                         return (EINVAL);
292                 if (p-path >= MAXNAMELEN)
293                         return (ENAMETOOLONG);
294                 (void) strncpy(component, path, p - path);
295                 component[p-path] = '\0';
296         } else {
297                 ASSERT(!"invalid p");
298         }
299         *nextp = p;
300         return (0);
301 }
302
303 /*
304  * same as dsl_open_dir, ignore the first component of name and use the
305  * spa instead
306  */
307 int
308 dsl_dir_open_spa(spa_t *spa, const char *name, void *tag,
309     dsl_dir_t **ddp, const char **tailp)
310 {
311         char buf[MAXNAMELEN];
312         const char *next, *nextnext = NULL;
313         int err;
314         dsl_dir_t *dd;
315         dsl_pool_t *dp;
316         uint64_t ddobj;
317         int openedspa = FALSE;
318
319         dprintf("%s\n", name);
320
321         err = getcomponent(name, buf, &next);
322         if (err)
323                 return (err);
324         if (spa == NULL) {
325                 err = spa_open(buf, &spa, FTAG);
326                 if (err) {
327                         dprintf("spa_open(%s) failed\n", buf);
328                         return (err);
329                 }
330                 openedspa = TRUE;
331
332                 /* XXX this assertion belongs in spa_open */
333                 ASSERT(!dsl_pool_sync_context(spa_get_dsl(spa)));
334         }
335
336         dp = spa_get_dsl(spa);
337
338         rw_enter(&dp->dp_config_rwlock, RW_READER);
339         err = dsl_dir_open_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
340         if (err) {
341                 rw_exit(&dp->dp_config_rwlock);
342                 if (openedspa)
343                         spa_close(spa, FTAG);
344                 return (err);
345         }
346
347         while (next != NULL) {
348                 dsl_dir_t *child_ds;
349                 err = getcomponent(next, buf, &nextnext);
350                 if (err)
351                         break;
352                 ASSERT(next[0] != '\0');
353                 if (next[0] == '@')
354                         break;
355                 dprintf("looking up %s in obj%lld\n",
356                     buf, dd->dd_phys->dd_child_dir_zapobj);
357
358                 err = zap_lookup(dp->dp_meta_objset,
359                     dd->dd_phys->dd_child_dir_zapobj,
360                     buf, sizeof (ddobj), 1, &ddobj);
361                 if (err) {
362                         if (err == ENOENT)
363                                 err = 0;
364                         break;
365                 }
366
367                 err = dsl_dir_open_obj(dp, ddobj, buf, tag, &child_ds);
368                 if (err)
369                         break;
370                 dsl_dir_close(dd, tag);
371                 dd = child_ds;
372                 next = nextnext;
373         }
374         rw_exit(&dp->dp_config_rwlock);
375
376         if (err) {
377                 dsl_dir_close(dd, tag);
378                 if (openedspa)
379                         spa_close(spa, FTAG);
380                 return (err);
381         }
382
383         /*
384          * It's an error if there's more than one component left, or
385          * tailp==NULL and there's any component left.
386          */
387         if (next != NULL &&
388             (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
389                 /* bad path name */
390                 dsl_dir_close(dd, tag);
391                 dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
392                 err = ENOENT;
393         }
394         if (tailp)
395                 *tailp = next;
396         if (openedspa)
397                 spa_close(spa, FTAG);
398         *ddp = dd;
399         return (err);
400 }
401
402 /*
403  * Return the dsl_dir_t, and possibly the last component which couldn't
404  * be found in *tail.  Return NULL if the path is bogus, or if
405  * tail==NULL and we couldn't parse the whole name.  (*tail)[0] == '@'
406  * means that the last component is a snapshot.
407  */
408 int
409 dsl_dir_open(const char *name, void *tag, dsl_dir_t **ddp, const char **tailp)
410 {
411         return (dsl_dir_open_spa(NULL, name, tag, ddp, tailp));
412 }
413
414 uint64_t
415 dsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
416     dmu_tx_t *tx)
417 {
418         objset_t *mos = dp->dp_meta_objset;
419         uint64_t ddobj;
420         dsl_dir_phys_t *ddphys;
421         dmu_buf_t *dbuf;
422
423         ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
424             DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
425         if (pds) {
426                 VERIFY(0 == zap_add(mos, pds->dd_phys->dd_child_dir_zapobj,
427                     name, sizeof (uint64_t), 1, &ddobj, tx));
428         } else {
429                 /* it's the root dir */
430                 VERIFY(0 == zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
431                     DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
432         }
433         VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
434         dmu_buf_will_dirty(dbuf, tx);
435         ddphys = dbuf->db_data;
436
437         ddphys->dd_creation_time = gethrestime_sec();
438         if (pds)
439                 ddphys->dd_parent_obj = pds->dd_object;
440         ddphys->dd_props_zapobj = zap_create(mos,
441             DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
442         ddphys->dd_child_dir_zapobj = zap_create(mos,
443             DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
444         if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
445                 ddphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
446         dmu_buf_rele(dbuf, FTAG);
447
448         return (ddobj);
449 }
450
451 /* ARGSUSED */
452 int
453 dsl_dir_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
454 {
455         dsl_dataset_t *ds = arg1;
456         dsl_dir_t *dd = ds->ds_dir;
457         dsl_pool_t *dp = dd->dd_pool;
458         objset_t *mos = dp->dp_meta_objset;
459         int err;
460         uint64_t count;
461
462         /*
463          * There should be exactly two holds, both from
464          * dsl_dataset_destroy: one on the dd directory, and one on its
465          * head ds.  If there are more holds, then a concurrent thread is
466          * performing a lookup inside this dir while we're trying to destroy
467          * it.  To minimize this possibility, we perform this check only
468          * in syncing context and fail the operation if we encounter
469          * additional holds.  The dp_config_rwlock ensures that nobody else
470          * opens it after we check.
471          */
472         if (dmu_tx_is_syncing(tx) && dmu_buf_refcount(dd->dd_dbuf) > 2)
473                 return (EBUSY);
474
475         err = zap_count(mos, dd->dd_phys->dd_child_dir_zapobj, &count);
476         if (err)
477                 return (err);
478         if (count != 0)
479                 return (EEXIST);
480
481         return (0);
482 }
483
484 void
485 dsl_dir_destroy_sync(void *arg1, void *tag, dmu_tx_t *tx)
486 {
487         dsl_dataset_t *ds = arg1;
488         dsl_dir_t *dd = ds->ds_dir;
489         objset_t *mos = dd->dd_pool->dp_meta_objset;
490         dsl_prop_setarg_t psa;
491         uint64_t value = 0;
492         uint64_t obj;
493         dd_used_t t;
494
495         ASSERT(RW_WRITE_HELD(&dd->dd_pool->dp_config_rwlock));
496         ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
497
498         /* Remove our reservation. */
499         dsl_prop_setarg_init_uint64(&psa, "reservation",
500             (ZPROP_SRC_NONE | ZPROP_SRC_LOCAL | ZPROP_SRC_RECEIVED),
501             &value);
502         psa.psa_effective_value = 0;    /* predict default value */
503
504         dsl_dir_set_reservation_sync(ds, &psa, tx);
505
506         ASSERT0(dd->dd_phys->dd_used_bytes);
507         ASSERT0(dd->dd_phys->dd_reserved);
508         for (t = 0; t < DD_USED_NUM; t++)
509                 ASSERT0(dd->dd_phys->dd_used_breakdown[t]);
510
511         VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_child_dir_zapobj, tx));
512         VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_props_zapobj, tx));
513         VERIFY(0 == dsl_deleg_destroy(mos, dd->dd_phys->dd_deleg_zapobj, tx));
514         VERIFY(0 == zap_remove(mos,
515             dd->dd_parent->dd_phys->dd_child_dir_zapobj, dd->dd_myname, tx));
516
517         obj = dd->dd_object;
518         dsl_dir_close(dd, tag);
519         VERIFY(0 == dmu_object_free(mos, obj, tx));
520 }
521
522 boolean_t
523 dsl_dir_is_clone(dsl_dir_t *dd)
524 {
525         return (dd->dd_phys->dd_origin_obj &&
526             (dd->dd_pool->dp_origin_snap == NULL ||
527             dd->dd_phys->dd_origin_obj !=
528             dd->dd_pool->dp_origin_snap->ds_object));
529 }
530
531 void
532 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
533 {
534         mutex_enter(&dd->dd_lock);
535         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
536             dd->dd_phys->dd_used_bytes);
537         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA, dd->dd_phys->dd_quota);
538         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
539             dd->dd_phys->dd_reserved);
540         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
541             dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
542             (dd->dd_phys->dd_uncompressed_bytes * 100 /
543             dd->dd_phys->dd_compressed_bytes));
544         if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
545                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
546                     dd->dd_phys->dd_used_breakdown[DD_USED_SNAP]);
547                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
548                     dd->dd_phys->dd_used_breakdown[DD_USED_HEAD]);
549                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
550                     dd->dd_phys->dd_used_breakdown[DD_USED_REFRSRV]);
551                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
552                     dd->dd_phys->dd_used_breakdown[DD_USED_CHILD] +
553                     dd->dd_phys->dd_used_breakdown[DD_USED_CHILD_RSRV]);
554         }
555         mutex_exit(&dd->dd_lock);
556
557         rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
558         if (dsl_dir_is_clone(dd)) {
559                 dsl_dataset_t *ds;
560                 char buf[MAXNAMELEN];
561
562                 VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
563                     dd->dd_phys->dd_origin_obj, FTAG, &ds));
564                 dsl_dataset_name(ds, buf);
565                 dsl_dataset_rele(ds, FTAG);
566                 dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
567         }
568         rw_exit(&dd->dd_pool->dp_config_rwlock);
569 }
570
571 void
572 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
573 {
574         dsl_pool_t *dp = dd->dd_pool;
575
576         ASSERT(dd->dd_phys);
577
578         if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg) == 0) {
579                 /* up the hold count until we can be written out */
580                 dmu_buf_add_ref(dd->dd_dbuf, dd);
581         }
582 }
583
584 static int64_t
585 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
586 {
587         uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
588         uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
589         return (new_accounted - old_accounted);
590 }
591
592 void
593 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
594 {
595         ASSERT(dmu_tx_is_syncing(tx));
596
597         mutex_enter(&dd->dd_lock);
598         ASSERT0(dd->dd_tempreserved[tx->tx_txg&TXG_MASK]);
599         dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
600             dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
601         dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
602         mutex_exit(&dd->dd_lock);
603
604         /* release the hold from dsl_dir_dirty */
605         dmu_buf_rele(dd->dd_dbuf, dd);
606 }
607
608 static uint64_t
609 dsl_dir_space_towrite(dsl_dir_t *dd)
610 {
611         uint64_t space = 0;
612         int i;
613
614         ASSERT(MUTEX_HELD(&dd->dd_lock));
615
616         for (i = 0; i < TXG_SIZE; i++) {
617                 space += dd->dd_space_towrite[i&TXG_MASK];
618                 ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
619         }
620         return (space);
621 }
622
623 /*
624  * How much space would dd have available if ancestor had delta applied
625  * to it?  If ondiskonly is set, we're only interested in what's
626  * on-disk, not estimated pending changes.
627  */
628 uint64_t
629 dsl_dir_space_available(dsl_dir_t *dd,
630     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
631 {
632         uint64_t parentspace, myspace, quota, used;
633
634         /*
635          * If there are no restrictions otherwise, assume we have
636          * unlimited space available.
637          */
638         quota = UINT64_MAX;
639         parentspace = UINT64_MAX;
640
641         if (dd->dd_parent != NULL) {
642                 parentspace = dsl_dir_space_available(dd->dd_parent,
643                     ancestor, delta, ondiskonly);
644         }
645
646         mutex_enter(&dd->dd_lock);
647         if (dd->dd_phys->dd_quota != 0)
648                 quota = dd->dd_phys->dd_quota;
649         used = dd->dd_phys->dd_used_bytes;
650         if (!ondiskonly)
651                 used += dsl_dir_space_towrite(dd);
652
653         if (dd->dd_parent == NULL) {
654                 uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
655                 quota = MIN(quota, poolsize);
656         }
657
658         if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
659                 /*
660                  * We have some space reserved, in addition to what our
661                  * parent gave us.
662                  */
663                 parentspace += dd->dd_phys->dd_reserved - used;
664         }
665
666         if (dd == ancestor) {
667                 ASSERT(delta <= 0);
668                 ASSERT(used >= -delta);
669                 used += delta;
670                 if (parentspace != UINT64_MAX)
671                         parentspace -= delta;
672         }
673
674         if (used > quota) {
675                 /* over quota */
676                 myspace = 0;
677         } else {
678                 /*
679                  * the lesser of the space provided by our parent and
680                  * the space left in our quota
681                  */
682                 myspace = MIN(parentspace, quota - used);
683         }
684
685         mutex_exit(&dd->dd_lock);
686
687         return (myspace);
688 }
689
690 struct tempreserve {
691         list_node_t tr_node;
692         dsl_pool_t *tr_dp;
693         dsl_dir_t *tr_ds;
694         uint64_t tr_size;
695 };
696
697 static int
698 dsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
699     boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
700     dmu_tx_t *tx, boolean_t first)
701 {
702         uint64_t txg = tx->tx_txg;
703         uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
704         uint64_t deferred = 0;
705         struct tempreserve *tr;
706         int retval = EDQUOT;
707         int txgidx = txg & TXG_MASK;
708         int i;
709         uint64_t ref_rsrv = 0;
710
711         ASSERT3U(txg, !=, 0);
712         ASSERT3S(asize, >, 0);
713
714         mutex_enter(&dd->dd_lock);
715
716         /*
717          * Check against the dsl_dir's quota.  We don't add in the delta
718          * when checking for over-quota because they get one free hit.
719          */
720         est_inflight = dsl_dir_space_towrite(dd);
721         for (i = 0; i < TXG_SIZE; i++)
722                 est_inflight += dd->dd_tempreserved[i];
723         used_on_disk = dd->dd_phys->dd_used_bytes;
724
725         /*
726          * On the first iteration, fetch the dataset's used-on-disk and
727          * refreservation values. Also, if checkrefquota is set, test if
728          * allocating this space would exceed the dataset's refquota.
729          */
730         if (first && tx->tx_objset) {
731                 int error;
732                 dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
733
734                 error = dsl_dataset_check_quota(ds, checkrefquota,
735                     asize, est_inflight, &used_on_disk, &ref_rsrv);
736                 if (error) {
737                         mutex_exit(&dd->dd_lock);
738                         return (error);
739                 }
740         }
741
742         /*
743          * If this transaction will result in a net free of space,
744          * we want to let it through.
745          */
746         if (ignorequota || netfree || dd->dd_phys->dd_quota == 0)
747                 quota = UINT64_MAX;
748         else
749                 quota = dd->dd_phys->dd_quota;
750
751         /*
752          * Adjust the quota against the actual pool size at the root
753          * minus any outstanding deferred frees.
754          * To ensure that it's possible to remove files from a full
755          * pool without inducing transient overcommits, we throttle
756          * netfree transactions against a quota that is slightly larger,
757          * but still within the pool's allocation slop.  In cases where
758          * we're very close to full, this will allow a steady trickle of
759          * removes to get through.
760          */
761         if (dd->dd_parent == NULL) {
762                 spa_t *spa = dd->dd_pool->dp_spa;
763                 uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
764                 deferred = metaslab_class_get_deferred(spa_normal_class(spa));
765                 if (poolsize - deferred < quota) {
766                         quota = poolsize - deferred;
767                         retval = ENOSPC;
768                 }
769         }
770
771         /*
772          * If they are requesting more space, and our current estimate
773          * is over quota, they get to try again unless the actual
774          * on-disk is over quota and there are no pending changes (which
775          * may free up space for us).
776          */
777         if (used_on_disk + est_inflight >= quota) {
778                 if (est_inflight > 0 || used_on_disk < quota ||
779                     (retval == ENOSPC && used_on_disk < quota + deferred))
780                         retval = ERESTART;
781                 dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
782                     "quota=%lluK tr=%lluK err=%d\n",
783                     used_on_disk>>10, est_inflight>>10,
784                     quota>>10, asize>>10, retval);
785                 mutex_exit(&dd->dd_lock);
786                 return (retval);
787         }
788
789         /* We need to up our estimated delta before dropping dd_lock */
790         dd->dd_tempreserved[txgidx] += asize;
791
792         parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
793             asize - ref_rsrv);
794         mutex_exit(&dd->dd_lock);
795
796         tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
797         tr->tr_ds = dd;
798         tr->tr_size = asize;
799         list_insert_tail(tr_list, tr);
800
801         /* see if it's OK with our parent */
802         if (dd->dd_parent && parent_rsrv) {
803                 boolean_t ismos = (dd->dd_phys->dd_head_dataset_obj == 0);
804
805                 return (dsl_dir_tempreserve_impl(dd->dd_parent,
806                     parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
807         } else {
808                 return (0);
809         }
810 }
811
812 /*
813  * Reserve space in this dsl_dir, to be used in this tx's txg.
814  * After the space has been dirtied (and dsl_dir_willuse_space()
815  * has been called), the reservation should be canceled, using
816  * dsl_dir_tempreserve_clear().
817  */
818 int
819 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
820     uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
821 {
822         int err;
823         list_t *tr_list;
824
825         if (asize == 0) {
826                 *tr_cookiep = NULL;
827                 return (0);
828         }
829
830         tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
831         list_create(tr_list, sizeof (struct tempreserve),
832             offsetof(struct tempreserve, tr_node));
833         ASSERT3S(asize, >, 0);
834         ASSERT3S(fsize, >=, 0);
835
836         err = arc_tempreserve_space(lsize, tx->tx_txg);
837         if (err == 0) {
838                 struct tempreserve *tr;
839
840                 tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
841                 tr->tr_size = lsize;
842                 list_insert_tail(tr_list, tr);
843
844                 err = dsl_pool_tempreserve_space(dd->dd_pool, asize, tx);
845         } else {
846                 if (err == EAGAIN) {
847                         txg_delay(dd->dd_pool, tx->tx_txg, 1);
848                         err = ERESTART;
849                 }
850                 dsl_pool_memory_pressure(dd->dd_pool);
851         }
852
853         if (err == 0) {
854                 struct tempreserve *tr;
855
856                 tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
857                 tr->tr_dp = dd->dd_pool;
858                 tr->tr_size = asize;
859                 list_insert_tail(tr_list, tr);
860
861                 err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
862                     FALSE, asize > usize, tr_list, tx, TRUE);
863         }
864
865         if (err)
866                 dsl_dir_tempreserve_clear(tr_list, tx);
867         else
868                 *tr_cookiep = tr_list;
869
870         return (err);
871 }
872
873 /*
874  * Clear a temporary reservation that we previously made with
875  * dsl_dir_tempreserve_space().
876  */
877 void
878 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
879 {
880         int txgidx = tx->tx_txg & TXG_MASK;
881         list_t *tr_list = tr_cookie;
882         struct tempreserve *tr;
883
884         ASSERT3U(tx->tx_txg, !=, 0);
885
886         if (tr_cookie == NULL)
887                 return;
888
889         while (tr = list_head(tr_list)) {
890                 if (tr->tr_dp) {
891                         dsl_pool_tempreserve_clear(tr->tr_dp, tr->tr_size, tx);
892                 } else if (tr->tr_ds) {
893                         mutex_enter(&tr->tr_ds->dd_lock);
894                         ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
895                             tr->tr_size);
896                         tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
897                         mutex_exit(&tr->tr_ds->dd_lock);
898                 } else {
899                         arc_tempreserve_clear(tr->tr_size);
900                 }
901                 list_remove(tr_list, tr);
902                 kmem_free(tr, sizeof (struct tempreserve));
903         }
904
905         kmem_free(tr_list, sizeof (list_t));
906 }
907
908 static void
909 dsl_dir_willuse_space_impl(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
910 {
911         int64_t parent_space;
912         uint64_t est_used;
913
914         mutex_enter(&dd->dd_lock);
915         if (space > 0)
916                 dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
917
918         est_used = dsl_dir_space_towrite(dd) + dd->dd_phys->dd_used_bytes;
919         parent_space = parent_delta(dd, est_used, space);
920         mutex_exit(&dd->dd_lock);
921
922         /* Make sure that we clean up dd_space_to* */
923         dsl_dir_dirty(dd, tx);
924
925         /* XXX this is potentially expensive and unnecessary... */
926         if (parent_space && dd->dd_parent)
927                 dsl_dir_willuse_space_impl(dd->dd_parent, parent_space, tx);
928 }
929
930 /*
931  * Call in open context when we think we're going to write/free space,
932  * eg. when dirtying data.  Be conservative (ie. OK to write less than
933  * this or free more than this, but don't write more or free less).
934  */
935 void
936 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
937 {
938         dsl_pool_willuse_space(dd->dd_pool, space, tx);
939         dsl_dir_willuse_space_impl(dd, space, tx);
940 }
941
942 /* call from syncing context when we actually write/free space for this dd */
943 void
944 dsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
945     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
946 {
947         int64_t accounted_delta;
948         boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
949
950         ASSERT(dmu_tx_is_syncing(tx));
951         ASSERT(type < DD_USED_NUM);
952
953         if (needlock)
954                 mutex_enter(&dd->dd_lock);
955         accounted_delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, used);
956         ASSERT(used >= 0 || dd->dd_phys->dd_used_bytes >= -used);
957         ASSERT(compressed >= 0 ||
958             dd->dd_phys->dd_compressed_bytes >= -compressed);
959         ASSERT(uncompressed >= 0 ||
960             dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
961         dmu_buf_will_dirty(dd->dd_dbuf, tx);
962         dd->dd_phys->dd_used_bytes += used;
963         dd->dd_phys->dd_uncompressed_bytes += uncompressed;
964         dd->dd_phys->dd_compressed_bytes += compressed;
965
966         if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
967                 ASSERT(used > 0 ||
968                     dd->dd_phys->dd_used_breakdown[type] >= -used);
969                 dd->dd_phys->dd_used_breakdown[type] += used;
970 #ifdef DEBUG
971                 dd_used_t t;
972                 uint64_t u = 0;
973                 for (t = 0; t < DD_USED_NUM; t++)
974                         u += dd->dd_phys->dd_used_breakdown[t];
975                 ASSERT3U(u, ==, dd->dd_phys->dd_used_bytes);
976 #endif
977         }
978         if (needlock)
979                 mutex_exit(&dd->dd_lock);
980
981         if (dd->dd_parent != NULL) {
982                 dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
983                     accounted_delta, compressed, uncompressed, tx);
984                 dsl_dir_transfer_space(dd->dd_parent,
985                     used - accounted_delta,
986                     DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
987         }
988 }
989
990 void
991 dsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
992     dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
993 {
994         boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
995
996         ASSERT(dmu_tx_is_syncing(tx));
997         ASSERT(oldtype < DD_USED_NUM);
998         ASSERT(newtype < DD_USED_NUM);
999
1000         if (delta == 0 || !(dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN))
1001                 return;
1002
1003         if (needlock)
1004                 mutex_enter(&dd->dd_lock);
1005         ASSERT(delta > 0 ?
1006             dd->dd_phys->dd_used_breakdown[oldtype] >= delta :
1007             dd->dd_phys->dd_used_breakdown[newtype] >= -delta);
1008         ASSERT(dd->dd_phys->dd_used_bytes >= ABS(delta));
1009         dmu_buf_will_dirty(dd->dd_dbuf, tx);
1010         dd->dd_phys->dd_used_breakdown[oldtype] -= delta;
1011         dd->dd_phys->dd_used_breakdown[newtype] += delta;
1012         if (needlock)
1013                 mutex_exit(&dd->dd_lock);
1014 }
1015
1016 static int
1017 dsl_dir_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
1018 {
1019         dsl_dataset_t *ds = arg1;
1020         dsl_dir_t *dd = ds->ds_dir;
1021         dsl_prop_setarg_t *psa = arg2;
1022         int err;
1023         uint64_t towrite;
1024
1025         if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
1026                 return (err);
1027
1028         if (psa->psa_effective_value == 0)
1029                 return (0);
1030
1031         mutex_enter(&dd->dd_lock);
1032         /*
1033          * If we are doing the preliminary check in open context, and
1034          * there are pending changes, then don't fail it, since the
1035          * pending changes could under-estimate the amount of space to be
1036          * freed up.
1037          */
1038         towrite = dsl_dir_space_towrite(dd);
1039         if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1040             (psa->psa_effective_value < dd->dd_phys->dd_reserved ||
1041             psa->psa_effective_value < dd->dd_phys->dd_used_bytes + towrite)) {
1042                 err = ENOSPC;
1043         }
1044         mutex_exit(&dd->dd_lock);
1045         return (err);
1046 }
1047
1048 extern dsl_syncfunc_t dsl_prop_set_sync;
1049
1050 static void
1051 dsl_dir_set_quota_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1052 {
1053         dsl_dataset_t *ds = arg1;
1054         dsl_dir_t *dd = ds->ds_dir;
1055         dsl_prop_setarg_t *psa = arg2;
1056         uint64_t effective_value = psa->psa_effective_value;
1057
1058         dsl_prop_set_sync(ds, psa, tx);
1059         DSL_PROP_CHECK_PREDICTION(dd, psa);
1060
1061         dmu_buf_will_dirty(dd->dd_dbuf, tx);
1062
1063         mutex_enter(&dd->dd_lock);
1064         dd->dd_phys->dd_quota = effective_value;
1065         mutex_exit(&dd->dd_lock);
1066 }
1067
1068 int
1069 dsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1070 {
1071         dsl_dir_t *dd;
1072         dsl_dataset_t *ds;
1073         dsl_prop_setarg_t psa;
1074         int err;
1075
1076         dsl_prop_setarg_init_uint64(&psa, "quota", source, &quota);
1077
1078         err = dsl_dataset_hold(ddname, FTAG, &ds);
1079         if (err)
1080                 return (err);
1081
1082         err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1083         if (err) {
1084                 dsl_dataset_rele(ds, FTAG);
1085                 return (err);
1086         }
1087
1088         ASSERT(ds->ds_dir == dd);
1089
1090         /*
1091          * If someone removes a file, then tries to set the quota, we want to
1092          * make sure the file freeing takes effect.
1093          */
1094         txg_wait_open(dd->dd_pool, 0);
1095
1096         err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_quota_check,
1097             dsl_dir_set_quota_sync, ds, &psa, 0);
1098
1099         dsl_dir_close(dd, FTAG);
1100         dsl_dataset_rele(ds, FTAG);
1101         return (err);
1102 }
1103
1104 int
1105 dsl_dir_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
1106 {
1107         dsl_dataset_t *ds = arg1;
1108         dsl_dir_t *dd = ds->ds_dir;
1109         dsl_prop_setarg_t *psa = arg2;
1110         uint64_t effective_value;
1111         uint64_t used, avail;
1112         int err;
1113
1114         if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
1115                 return (err);
1116
1117         effective_value = psa->psa_effective_value;
1118
1119         /*
1120          * If we are doing the preliminary check in open context, the
1121          * space estimates may be inaccurate.
1122          */
1123         if (!dmu_tx_is_syncing(tx))
1124                 return (0);
1125
1126         mutex_enter(&dd->dd_lock);
1127         used = dd->dd_phys->dd_used_bytes;
1128         mutex_exit(&dd->dd_lock);
1129
1130         if (dd->dd_parent) {
1131                 avail = dsl_dir_space_available(dd->dd_parent,
1132                     NULL, 0, FALSE);
1133         } else {
1134                 avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1135         }
1136
1137         if (MAX(used, effective_value) > MAX(used, dd->dd_phys->dd_reserved)) {
1138                 uint64_t delta = MAX(used, effective_value) -
1139                     MAX(used, dd->dd_phys->dd_reserved);
1140
1141                 if (delta > avail)
1142                         return (ENOSPC);
1143                 if (dd->dd_phys->dd_quota > 0 &&
1144                     effective_value > dd->dd_phys->dd_quota)
1145                         return (ENOSPC);
1146         }
1147
1148         return (0);
1149 }
1150
1151 static void
1152 dsl_dir_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1153 {
1154         dsl_dataset_t *ds = arg1;
1155         dsl_dir_t *dd = ds->ds_dir;
1156         dsl_prop_setarg_t *psa = arg2;
1157         uint64_t effective_value = psa->psa_effective_value;
1158         uint64_t used;
1159         int64_t delta;
1160
1161         dsl_prop_set_sync(ds, psa, tx);
1162         DSL_PROP_CHECK_PREDICTION(dd, psa);
1163
1164         dmu_buf_will_dirty(dd->dd_dbuf, tx);
1165
1166         mutex_enter(&dd->dd_lock);
1167         used = dd->dd_phys->dd_used_bytes;
1168         delta = MAX(used, effective_value) -
1169             MAX(used, dd->dd_phys->dd_reserved);
1170         dd->dd_phys->dd_reserved = effective_value;
1171
1172         if (dd->dd_parent != NULL) {
1173                 /* Roll up this additional usage into our ancestors */
1174                 dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1175                     delta, 0, 0, tx);
1176         }
1177         mutex_exit(&dd->dd_lock);
1178 }
1179
1180 int
1181 dsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1182     uint64_t reservation)
1183 {
1184         dsl_dir_t *dd;
1185         dsl_dataset_t *ds;
1186         dsl_prop_setarg_t psa;
1187         int err;
1188
1189         dsl_prop_setarg_init_uint64(&psa, "reservation", source, &reservation);
1190
1191         err = dsl_dataset_hold(ddname, FTAG, &ds);
1192         if (err)
1193                 return (err);
1194
1195         err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1196         if (err) {
1197                 dsl_dataset_rele(ds, FTAG);
1198                 return (err);
1199         }
1200
1201         ASSERT(ds->ds_dir == dd);
1202
1203         err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_reservation_check,
1204             dsl_dir_set_reservation_sync, ds, &psa, 0);
1205
1206         dsl_dir_close(dd, FTAG);
1207         dsl_dataset_rele(ds, FTAG);
1208         return (err);
1209 }
1210
1211 static dsl_dir_t *
1212 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1213 {
1214         for (; ds1; ds1 = ds1->dd_parent) {
1215                 dsl_dir_t *dd;
1216                 for (dd = ds2; dd; dd = dd->dd_parent) {
1217                         if (ds1 == dd)
1218                                 return (dd);
1219                 }
1220         }
1221         return (NULL);
1222 }
1223
1224 /*
1225  * If delta is applied to dd, how much of that delta would be applied to
1226  * ancestor?  Syncing context only.
1227  */
1228 static int64_t
1229 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1230 {
1231         if (dd == ancestor)
1232                 return (delta);
1233
1234         mutex_enter(&dd->dd_lock);
1235         delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, delta);
1236         mutex_exit(&dd->dd_lock);
1237         return (would_change(dd->dd_parent, delta, ancestor));
1238 }
1239
1240 struct renamearg {
1241         dsl_dir_t *newparent;
1242         const char *mynewname;
1243         boolean_t allowmounted;
1244 };
1245
1246 static int
1247 dsl_dir_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
1248 {
1249         dsl_dir_t *dd = arg1;
1250         struct renamearg *ra = arg2;
1251         dsl_pool_t *dp = dd->dd_pool;
1252         objset_t *mos = dp->dp_meta_objset;
1253         int err;
1254         uint64_t val;
1255
1256         /*
1257          * There should only be one reference, from dmu_objset_rename().
1258          * Fleeting holds are also possible (eg, from "zfs list" getting
1259          * stats), but any that are present in open context will likely
1260          * be gone by syncing context, so only fail from syncing
1261          * context.
1262          * Don't check if we allow renaming of busy (mounted) dataset.
1263          */
1264         if (!ra->allowmounted && dmu_tx_is_syncing(tx) &&
1265             dmu_buf_refcount(dd->dd_dbuf) > 1) {
1266                 return (EBUSY);
1267         }
1268
1269         /* check for existing name */
1270         err = zap_lookup(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1271             ra->mynewname, 8, 1, &val);
1272         if (err == 0)
1273                 return (EEXIST);
1274         if (err != ENOENT)
1275                 return (err);
1276
1277         if (ra->newparent != dd->dd_parent) {
1278                 /* is there enough space? */
1279                 uint64_t myspace =
1280                     MAX(dd->dd_phys->dd_used_bytes, dd->dd_phys->dd_reserved);
1281
1282                 /* no rename into our descendant */
1283                 if (closest_common_ancestor(dd, ra->newparent) == dd)
1284                         return (EINVAL);
1285
1286                 if (err = dsl_dir_transfer_possible(dd->dd_parent,
1287                     ra->newparent, myspace))
1288                         return (err);
1289         }
1290
1291         return (0);
1292 }
1293
1294 static void
1295 dsl_dir_rename_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1296 {
1297         char oldname[MAXPATHLEN], newname[MAXPATHLEN];
1298         dsl_dir_t *dd = arg1;
1299         struct renamearg *ra = arg2;
1300         dsl_pool_t *dp = dd->dd_pool;
1301         objset_t *mos = dp->dp_meta_objset;
1302         int err;
1303
1304         ASSERT(ra->allowmounted || dmu_buf_refcount(dd->dd_dbuf) <= 2);
1305
1306         if (ra->newparent != dd->dd_parent) {
1307                 dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1308                     -dd->dd_phys->dd_used_bytes,
1309                     -dd->dd_phys->dd_compressed_bytes,
1310                     -dd->dd_phys->dd_uncompressed_bytes, tx);
1311                 dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD,
1312                     dd->dd_phys->dd_used_bytes,
1313                     dd->dd_phys->dd_compressed_bytes,
1314                     dd->dd_phys->dd_uncompressed_bytes, tx);
1315
1316                 if (dd->dd_phys->dd_reserved > dd->dd_phys->dd_used_bytes) {
1317                         uint64_t unused_rsrv = dd->dd_phys->dd_reserved -
1318                             dd->dd_phys->dd_used_bytes;
1319
1320                         dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1321                             -unused_rsrv, 0, 0, tx);
1322                         dsl_dir_diduse_space(ra->newparent, DD_USED_CHILD_RSRV,
1323                             unused_rsrv, 0, 0, tx);
1324                 }
1325         }
1326
1327         dmu_buf_will_dirty(dd->dd_dbuf, tx);
1328
1329         /* remove from old parent zapobj */
1330         dsl_dir_name(dd, oldname);
1331         err = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1332             dd->dd_myname, tx);
1333         ASSERT0(err);
1334
1335         (void) strcpy(dd->dd_myname, ra->mynewname);
1336         dsl_dir_close(dd->dd_parent, dd);
1337         dd->dd_phys->dd_parent_obj = ra->newparent->dd_object;
1338         VERIFY(0 == dsl_dir_open_obj(dd->dd_pool,
1339             ra->newparent->dd_object, NULL, dd, &dd->dd_parent));
1340
1341         /* add to new parent zapobj */
1342         err = zap_add(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1343             dd->dd_myname, 8, 1, &dd->dd_object, tx);
1344         ASSERT0(err);
1345         dsl_dir_name(dd, newname);
1346 #ifdef _KERNEL
1347         zfsvfs_update_fromname(oldname, newname);
1348         zvol_rename_minors(oldname, newname);
1349 #endif
1350
1351         spa_history_log_internal(LOG_DS_RENAME, dd->dd_pool->dp_spa,
1352             tx, "dataset = %llu", dd->dd_phys->dd_head_dataset_obj);
1353 }
1354
1355 int
1356 dsl_dir_rename(dsl_dir_t *dd, const char *newname, int flags)
1357 {
1358         struct renamearg ra;
1359         int err;
1360
1361         /* new parent should exist */
1362         err = dsl_dir_open(newname, FTAG, &ra.newparent, &ra.mynewname);
1363         if (err)
1364                 return (err);
1365
1366         /* can't rename to different pool */
1367         if (dd->dd_pool != ra.newparent->dd_pool) {
1368                 err = ENXIO;
1369                 goto out;
1370         }
1371
1372         /* new name should not already exist */
1373         if (ra.mynewname == NULL) {
1374                 err = EEXIST;
1375                 goto out;
1376         }
1377
1378         ra.allowmounted = !!(flags & ZFS_RENAME_ALLOW_MOUNTED);
1379
1380         err = dsl_sync_task_do(dd->dd_pool,
1381             dsl_dir_rename_check, dsl_dir_rename_sync, dd, &ra, 3);
1382
1383 out:
1384         dsl_dir_close(ra.newparent, FTAG);
1385         return (err);
1386 }
1387
1388 int
1389 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd, uint64_t space)
1390 {
1391         dsl_dir_t *ancestor;
1392         int64_t adelta;
1393         uint64_t avail;
1394
1395         ancestor = closest_common_ancestor(sdd, tdd);
1396         adelta = would_change(sdd, -space, ancestor);
1397         avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1398         if (avail < space)
1399                 return (ENOSPC);
1400
1401         return (0);
1402 }
1403
1404 timestruc_t
1405 dsl_dir_snap_cmtime(dsl_dir_t *dd)
1406 {
1407         timestruc_t t;
1408
1409         mutex_enter(&dd->dd_lock);
1410         t = dd->dd_snap_cmtime;
1411         mutex_exit(&dd->dd_lock);
1412
1413         return (t);
1414 }
1415
1416 void
1417 dsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1418 {
1419         timestruc_t t;
1420
1421         gethrestime(&t);
1422         mutex_enter(&dd->dd_lock);
1423         dd->dd_snap_cmtime = t;
1424         mutex_exit(&dd->dd_lock);
1425 }