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