]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c
MFC r264835: MFV r264829:
[FreeBSD/stable/9.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / dsl_dataset.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  * Portions Copyright (c) 2011 Martin Matuska <mm@FreeBSD.org>
24  * Copyright (c) 2013 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2014 RackTop Systems.
27  */
28
29 #include <sys/dmu_objset.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/dmu_traverse.h>
35 #include <sys/dmu_impl.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/arc.h>
38 #include <sys/zio.h>
39 #include <sys/zap.h>
40 #include <sys/zfeature.h>
41 #include <sys/unique.h>
42 #include <sys/zfs_context.h>
43 #include <sys/zfs_ioctl.h>
44 #include <sys/spa.h>
45 #include <sys/zfs_znode.h>
46 #include <sys/zfs_onexit.h>
47 #include <sys/zvol.h>
48 #include <sys/dsl_scan.h>
49 #include <sys/dsl_deadlist.h>
50 #include <sys/dsl_destroy.h>
51 #include <sys/dsl_userhold.h>
52 #include <sys/dsl_bookmark.h>
53
54 #define SWITCH64(x, y) \
55         { \
56                 uint64_t __tmp = (x); \
57                 (x) = (y); \
58                 (y) = __tmp; \
59         }
60
61 #define DS_REF_MAX      (1ULL << 62)
62
63 #define DSL_DEADLIST_BLOCKSIZE  SPA_MAXBLOCKSIZE
64
65 /*
66  * Figure out how much of this delta should be propogated to the dsl_dir
67  * layer.  If there's a refreservation, that space has already been
68  * partially accounted for in our ancestors.
69  */
70 static int64_t
71 parent_delta(dsl_dataset_t *ds, int64_t delta)
72 {
73         uint64_t old_bytes, new_bytes;
74
75         if (ds->ds_reserved == 0)
76                 return (delta);
77
78         old_bytes = MAX(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
79         new_bytes = MAX(ds->ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
80
81         ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
82         return (new_bytes - old_bytes);
83 }
84
85 void
86 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
87 {
88         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
89         int compressed = BP_GET_PSIZE(bp);
90         int uncompressed = BP_GET_UCSIZE(bp);
91         int64_t delta;
92
93         dprintf_bp(bp, "ds=%p", ds);
94
95         ASSERT(dmu_tx_is_syncing(tx));
96         /* It could have been compressed away to nothing */
97         if (BP_IS_HOLE(bp))
98                 return;
99         ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
100         ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
101         if (ds == NULL) {
102                 dsl_pool_mos_diduse_space(tx->tx_pool,
103                     used, compressed, uncompressed);
104                 return;
105         }
106
107         dmu_buf_will_dirty(ds->ds_dbuf, tx);
108         mutex_enter(&ds->ds_lock);
109         delta = parent_delta(ds, used);
110         ds->ds_phys->ds_referenced_bytes += used;
111         ds->ds_phys->ds_compressed_bytes += compressed;
112         ds->ds_phys->ds_uncompressed_bytes += uncompressed;
113         ds->ds_phys->ds_unique_bytes += used;
114         mutex_exit(&ds->ds_lock);
115         dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
116             compressed, uncompressed, tx);
117         dsl_dir_transfer_space(ds->ds_dir, used - delta,
118             DD_USED_REFRSRV, DD_USED_HEAD, tx);
119 }
120
121 int
122 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
123     boolean_t async)
124 {
125         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
126         int compressed = BP_GET_PSIZE(bp);
127         int uncompressed = BP_GET_UCSIZE(bp);
128
129         if (BP_IS_HOLE(bp))
130                 return (0);
131
132         ASSERT(dmu_tx_is_syncing(tx));
133         ASSERT(bp->blk_birth <= tx->tx_txg);
134
135         if (ds == NULL) {
136                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
137                 dsl_pool_mos_diduse_space(tx->tx_pool,
138                     -used, -compressed, -uncompressed);
139                 return (used);
140         }
141         ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
142
143         ASSERT(!dsl_dataset_is_snapshot(ds));
144         dmu_buf_will_dirty(ds->ds_dbuf, tx);
145
146         if (bp->blk_birth > ds->ds_phys->ds_prev_snap_txg) {
147                 int64_t delta;
148
149                 dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
150                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
151
152                 mutex_enter(&ds->ds_lock);
153                 ASSERT(ds->ds_phys->ds_unique_bytes >= used ||
154                     !DS_UNIQUE_IS_ACCURATE(ds));
155                 delta = parent_delta(ds, -used);
156                 ds->ds_phys->ds_unique_bytes -= used;
157                 mutex_exit(&ds->ds_lock);
158                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
159                     delta, -compressed, -uncompressed, tx);
160                 dsl_dir_transfer_space(ds->ds_dir, -used - delta,
161                     DD_USED_REFRSRV, DD_USED_HEAD, tx);
162         } else {
163                 dprintf_bp(bp, "putting on dead list: %s", "");
164                 if (async) {
165                         /*
166                          * We are here as part of zio's write done callback,
167                          * which means we're a zio interrupt thread.  We can't
168                          * call dsl_deadlist_insert() now because it may block
169                          * waiting for I/O.  Instead, put bp on the deferred
170                          * queue and let dsl_pool_sync() finish the job.
171                          */
172                         bplist_append(&ds->ds_pending_deadlist, bp);
173                 } else {
174                         dsl_deadlist_insert(&ds->ds_deadlist, bp, tx);
175                 }
176                 ASSERT3U(ds->ds_prev->ds_object, ==,
177                     ds->ds_phys->ds_prev_snap_obj);
178                 ASSERT(ds->ds_prev->ds_phys->ds_num_children > 0);
179                 /* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
180                 if (ds->ds_prev->ds_phys->ds_next_snap_obj ==
181                     ds->ds_object && bp->blk_birth >
182                     ds->ds_prev->ds_phys->ds_prev_snap_txg) {
183                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
184                         mutex_enter(&ds->ds_prev->ds_lock);
185                         ds->ds_prev->ds_phys->ds_unique_bytes += used;
186                         mutex_exit(&ds->ds_prev->ds_lock);
187                 }
188                 if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
189                         dsl_dir_transfer_space(ds->ds_dir, used,
190                             DD_USED_HEAD, DD_USED_SNAP, tx);
191                 }
192         }
193         mutex_enter(&ds->ds_lock);
194         ASSERT3U(ds->ds_phys->ds_referenced_bytes, >=, used);
195         ds->ds_phys->ds_referenced_bytes -= used;
196         ASSERT3U(ds->ds_phys->ds_compressed_bytes, >=, compressed);
197         ds->ds_phys->ds_compressed_bytes -= compressed;
198         ASSERT3U(ds->ds_phys->ds_uncompressed_bytes, >=, uncompressed);
199         ds->ds_phys->ds_uncompressed_bytes -= uncompressed;
200         mutex_exit(&ds->ds_lock);
201
202         return (used);
203 }
204
205 uint64_t
206 dsl_dataset_prev_snap_txg(dsl_dataset_t *ds)
207 {
208         uint64_t trysnap = 0;
209
210         if (ds == NULL)
211                 return (0);
212         /*
213          * The snapshot creation could fail, but that would cause an
214          * incorrect FALSE return, which would only result in an
215          * overestimation of the amount of space that an operation would
216          * consume, which is OK.
217          *
218          * There's also a small window where we could miss a pending
219          * snapshot, because we could set the sync task in the quiescing
220          * phase.  So this should only be used as a guess.
221          */
222         if (ds->ds_trysnap_txg >
223             spa_last_synced_txg(ds->ds_dir->dd_pool->dp_spa))
224                 trysnap = ds->ds_trysnap_txg;
225         return (MAX(ds->ds_phys->ds_prev_snap_txg, trysnap));
226 }
227
228 boolean_t
229 dsl_dataset_block_freeable(dsl_dataset_t *ds, const blkptr_t *bp,
230     uint64_t blk_birth)
231 {
232         if (blk_birth <= dsl_dataset_prev_snap_txg(ds) ||
233             (bp != NULL && BP_IS_HOLE(bp)))
234                 return (B_FALSE);
235
236         ddt_prefetch(dsl_dataset_get_spa(ds), bp);
237
238         return (B_TRUE);
239 }
240
241 /* ARGSUSED */
242 static void
243 dsl_dataset_evict(dmu_buf_t *db, void *dsv)
244 {
245         dsl_dataset_t *ds = dsv;
246
247         ASSERT(ds->ds_owner == NULL);
248
249         unique_remove(ds->ds_fsid_guid);
250
251         if (ds->ds_objset != NULL)
252                 dmu_objset_evict(ds->ds_objset);
253
254         if (ds->ds_prev) {
255                 dsl_dataset_rele(ds->ds_prev, ds);
256                 ds->ds_prev = NULL;
257         }
258
259         bplist_destroy(&ds->ds_pending_deadlist);
260         if (ds->ds_phys->ds_deadlist_obj != 0)
261                 dsl_deadlist_close(&ds->ds_deadlist);
262         if (ds->ds_dir)
263                 dsl_dir_rele(ds->ds_dir, ds);
264
265         ASSERT(!list_link_active(&ds->ds_synced_link));
266
267         if (mutex_owned(&ds->ds_lock))
268                 mutex_exit(&ds->ds_lock);
269         mutex_destroy(&ds->ds_lock);
270         if (mutex_owned(&ds->ds_opening_lock))
271                 mutex_exit(&ds->ds_opening_lock);
272         mutex_destroy(&ds->ds_opening_lock);
273         refcount_destroy(&ds->ds_longholds);
274
275         kmem_free(ds, sizeof (dsl_dataset_t));
276 }
277
278 int
279 dsl_dataset_get_snapname(dsl_dataset_t *ds)
280 {
281         dsl_dataset_phys_t *headphys;
282         int err;
283         dmu_buf_t *headdbuf;
284         dsl_pool_t *dp = ds->ds_dir->dd_pool;
285         objset_t *mos = dp->dp_meta_objset;
286
287         if (ds->ds_snapname[0])
288                 return (0);
289         if (ds->ds_phys->ds_next_snap_obj == 0)
290                 return (0);
291
292         err = dmu_bonus_hold(mos, ds->ds_dir->dd_phys->dd_head_dataset_obj,
293             FTAG, &headdbuf);
294         if (err != 0)
295                 return (err);
296         headphys = headdbuf->db_data;
297         err = zap_value_search(dp->dp_meta_objset,
298             headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
299         dmu_buf_rele(headdbuf, FTAG);
300         return (err);
301 }
302
303 int
304 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
305 {
306         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
307         uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
308         matchtype_t mt;
309         int err;
310
311         if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
312                 mt = MT_FIRST;
313         else
314                 mt = MT_EXACT;
315
316         err = zap_lookup_norm(mos, snapobj, name, 8, 1,
317             value, mt, NULL, 0, NULL);
318         if (err == ENOTSUP && mt == MT_FIRST)
319                 err = zap_lookup(mos, snapobj, name, 8, 1, value);
320         return (err);
321 }
322
323 int
324 dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
325     boolean_t adj_cnt)
326 {
327         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
328         uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
329         matchtype_t mt;
330         int err;
331
332         dsl_dir_snap_cmtime_update(ds->ds_dir);
333
334         if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
335                 mt = MT_FIRST;
336         else
337                 mt = MT_EXACT;
338
339         err = zap_remove_norm(mos, snapobj, name, mt, tx);
340         if (err == ENOTSUP && mt == MT_FIRST)
341                 err = zap_remove(mos, snapobj, name, tx);
342
343         if (err == 0 && adj_cnt)
344                 dsl_fs_ss_count_adjust(ds->ds_dir, -1,
345                     DD_FIELD_SNAPSHOT_COUNT, tx);
346
347         return (err);
348 }
349
350 int
351 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
352     dsl_dataset_t **dsp)
353 {
354         objset_t *mos = dp->dp_meta_objset;
355         dmu_buf_t *dbuf;
356         dsl_dataset_t *ds;
357         int err;
358         dmu_object_info_t doi;
359
360         ASSERT(dsl_pool_config_held(dp));
361
362         err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
363         if (err != 0)
364                 return (err);
365
366         /* Make sure dsobj has the correct object type. */
367         dmu_object_info_from_db(dbuf, &doi);
368         if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
369                 dmu_buf_rele(dbuf, tag);
370                 return (SET_ERROR(EINVAL));
371         }
372
373         ds = dmu_buf_get_user(dbuf);
374         if (ds == NULL) {
375                 dsl_dataset_t *winner = NULL;
376
377                 ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
378                 ds->ds_dbuf = dbuf;
379                 ds->ds_object = dsobj;
380                 ds->ds_phys = dbuf->db_data;
381
382                 mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
383                 mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
384                 mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
385                 refcount_create(&ds->ds_longholds);
386
387                 bplist_create(&ds->ds_pending_deadlist);
388                 dsl_deadlist_open(&ds->ds_deadlist,
389                     mos, ds->ds_phys->ds_deadlist_obj);
390
391                 list_create(&ds->ds_sendstreams, sizeof (dmu_sendarg_t),
392                     offsetof(dmu_sendarg_t, dsa_link));
393
394                 if (err == 0) {
395                         err = dsl_dir_hold_obj(dp,
396                             ds->ds_phys->ds_dir_obj, NULL, ds, &ds->ds_dir);
397                 }
398                 if (err != 0) {
399                         mutex_destroy(&ds->ds_lock);
400                         mutex_destroy(&ds->ds_opening_lock);
401                         refcount_destroy(&ds->ds_longholds);
402                         bplist_destroy(&ds->ds_pending_deadlist);
403                         dsl_deadlist_close(&ds->ds_deadlist);
404                         kmem_free(ds, sizeof (dsl_dataset_t));
405                         dmu_buf_rele(dbuf, tag);
406                         return (err);
407                 }
408
409                 if (!dsl_dataset_is_snapshot(ds)) {
410                         ds->ds_snapname[0] = '\0';
411                         if (ds->ds_phys->ds_prev_snap_obj != 0) {
412                                 err = dsl_dataset_hold_obj(dp,
413                                     ds->ds_phys->ds_prev_snap_obj,
414                                     ds, &ds->ds_prev);
415                         }
416                         if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
417                                 int zaperr = zap_lookup(mos, ds->ds_object,
418                                     DS_FIELD_BOOKMARK_NAMES,
419                                     sizeof (ds->ds_bookmarks), 1,
420                                     &ds->ds_bookmarks);
421                                 if (zaperr != ENOENT)
422                                         VERIFY0(zaperr);
423                         }
424                 } else {
425                         if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
426                                 err = dsl_dataset_get_snapname(ds);
427                         if (err == 0 && ds->ds_phys->ds_userrefs_obj != 0) {
428                                 err = zap_count(
429                                     ds->ds_dir->dd_pool->dp_meta_objset,
430                                     ds->ds_phys->ds_userrefs_obj,
431                                     &ds->ds_userrefs);
432                         }
433                 }
434
435                 if (err == 0 && !dsl_dataset_is_snapshot(ds)) {
436                         err = dsl_prop_get_int_ds(ds,
437                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
438                             &ds->ds_reserved);
439                         if (err == 0) {
440                                 err = dsl_prop_get_int_ds(ds,
441                                     zfs_prop_to_name(ZFS_PROP_REFQUOTA),
442                                     &ds->ds_quota);
443                         }
444                 } else {
445                         ds->ds_reserved = ds->ds_quota = 0;
446                 }
447
448                 if (err != 0 || (winner = dmu_buf_set_user_ie(dbuf, ds,
449                     &ds->ds_phys, dsl_dataset_evict)) != NULL) {
450                         bplist_destroy(&ds->ds_pending_deadlist);
451                         dsl_deadlist_close(&ds->ds_deadlist);
452                         if (ds->ds_prev)
453                                 dsl_dataset_rele(ds->ds_prev, ds);
454                         dsl_dir_rele(ds->ds_dir, ds);
455                         mutex_destroy(&ds->ds_lock);
456                         mutex_destroy(&ds->ds_opening_lock);
457                         refcount_destroy(&ds->ds_longholds);
458                         kmem_free(ds, sizeof (dsl_dataset_t));
459                         if (err != 0) {
460                                 dmu_buf_rele(dbuf, tag);
461                                 return (err);
462                         }
463                         ds = winner;
464                 } else {
465                         ds->ds_fsid_guid =
466                             unique_insert(ds->ds_phys->ds_fsid_guid);
467                 }
468         }
469         ASSERT3P(ds->ds_dbuf, ==, dbuf);
470         ASSERT3P(ds->ds_phys, ==, dbuf->db_data);
471         ASSERT(ds->ds_phys->ds_prev_snap_obj != 0 ||
472             spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
473             dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
474         *dsp = ds;
475         return (0);
476 }
477
478 int
479 dsl_dataset_hold(dsl_pool_t *dp, const char *name,
480     void *tag, dsl_dataset_t **dsp)
481 {
482         dsl_dir_t *dd;
483         const char *snapname;
484         uint64_t obj;
485         int err = 0;
486
487         err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
488         if (err != 0)
489                 return (err);
490
491         ASSERT(dsl_pool_config_held(dp));
492         obj = dd->dd_phys->dd_head_dataset_obj;
493         if (obj != 0)
494                 err = dsl_dataset_hold_obj(dp, obj, tag, dsp);
495         else
496                 err = SET_ERROR(ENOENT);
497
498         /* we may be looking for a snapshot */
499         if (err == 0 && snapname != NULL) {
500                 dsl_dataset_t *ds;
501
502                 if (*snapname++ != '@') {
503                         dsl_dataset_rele(*dsp, tag);
504                         dsl_dir_rele(dd, FTAG);
505                         return (SET_ERROR(ENOENT));
506                 }
507
508                 dprintf("looking for snapshot '%s'\n", snapname);
509                 err = dsl_dataset_snap_lookup(*dsp, snapname, &obj);
510                 if (err == 0)
511                         err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
512                 dsl_dataset_rele(*dsp, tag);
513
514                 if (err == 0) {
515                         mutex_enter(&ds->ds_lock);
516                         if (ds->ds_snapname[0] == 0)
517                                 (void) strlcpy(ds->ds_snapname, snapname,
518                                     sizeof (ds->ds_snapname));
519                         mutex_exit(&ds->ds_lock);
520                         *dsp = ds;
521                 }
522         }
523
524         dsl_dir_rele(dd, FTAG);
525         return (err);
526 }
527
528 int
529 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj,
530     void *tag, dsl_dataset_t **dsp)
531 {
532         int err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
533         if (err != 0)
534                 return (err);
535         if (!dsl_dataset_tryown(*dsp, tag)) {
536                 dsl_dataset_rele(*dsp, tag);
537                 *dsp = NULL;
538                 return (SET_ERROR(EBUSY));
539         }
540         return (0);
541 }
542
543 int
544 dsl_dataset_own(dsl_pool_t *dp, const char *name,
545     void *tag, dsl_dataset_t **dsp)
546 {
547         int err = dsl_dataset_hold(dp, name, tag, dsp);
548         if (err != 0)
549                 return (err);
550         if (!dsl_dataset_tryown(*dsp, tag)) {
551                 dsl_dataset_rele(*dsp, tag);
552                 return (SET_ERROR(EBUSY));
553         }
554         return (0);
555 }
556
557 /*
558  * See the comment above dsl_pool_hold() for details.  In summary, a long
559  * hold is used to prevent destruction of a dataset while the pool hold
560  * is dropped, allowing other concurrent operations (e.g. spa_sync()).
561  *
562  * The dataset and pool must be held when this function is called.  After it
563  * is called, the pool hold may be released while the dataset is still held
564  * and accessed.
565  */
566 void
567 dsl_dataset_long_hold(dsl_dataset_t *ds, void *tag)
568 {
569         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
570         (void) refcount_add(&ds->ds_longholds, tag);
571 }
572
573 void
574 dsl_dataset_long_rele(dsl_dataset_t *ds, void *tag)
575 {
576         (void) refcount_remove(&ds->ds_longholds, tag);
577 }
578
579 /* Return B_TRUE if there are any long holds on this dataset. */
580 boolean_t
581 dsl_dataset_long_held(dsl_dataset_t *ds)
582 {
583         return (!refcount_is_zero(&ds->ds_longholds));
584 }
585
586 void
587 dsl_dataset_name(dsl_dataset_t *ds, char *name)
588 {
589         if (ds == NULL) {
590                 (void) strcpy(name, "mos");
591         } else {
592                 dsl_dir_name(ds->ds_dir, name);
593                 VERIFY0(dsl_dataset_get_snapname(ds));
594                 if (ds->ds_snapname[0]) {
595                         (void) strcat(name, "@");
596                         /*
597                          * We use a "recursive" mutex so that we
598                          * can call dprintf_ds() with ds_lock held.
599                          */
600                         if (!MUTEX_HELD(&ds->ds_lock)) {
601                                 mutex_enter(&ds->ds_lock);
602                                 (void) strcat(name, ds->ds_snapname);
603                                 mutex_exit(&ds->ds_lock);
604                         } else {
605                                 (void) strcat(name, ds->ds_snapname);
606                         }
607                 }
608         }
609 }
610
611 void
612 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
613 {
614         dmu_buf_rele(ds->ds_dbuf, tag);
615 }
616
617 void
618 dsl_dataset_disown(dsl_dataset_t *ds, void *tag)
619 {
620         ASSERT(ds->ds_owner == tag && ds->ds_dbuf != NULL);
621
622         mutex_enter(&ds->ds_lock);
623         ds->ds_owner = NULL;
624         mutex_exit(&ds->ds_lock);
625         dsl_dataset_long_rele(ds, tag);
626         if (ds->ds_dbuf != NULL)
627                 dsl_dataset_rele(ds, tag);
628         else
629                 dsl_dataset_evict(NULL, ds);
630 }
631
632 boolean_t
633 dsl_dataset_tryown(dsl_dataset_t *ds, void *tag)
634 {
635         boolean_t gotit = FALSE;
636
637         mutex_enter(&ds->ds_lock);
638         if (ds->ds_owner == NULL && !DS_IS_INCONSISTENT(ds)) {
639                 ds->ds_owner = tag;
640                 dsl_dataset_long_hold(ds, tag);
641                 gotit = TRUE;
642         }
643         mutex_exit(&ds->ds_lock);
644         return (gotit);
645 }
646
647 uint64_t
648 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
649     uint64_t flags, dmu_tx_t *tx)
650 {
651         dsl_pool_t *dp = dd->dd_pool;
652         dmu_buf_t *dbuf;
653         dsl_dataset_phys_t *dsphys;
654         uint64_t dsobj;
655         objset_t *mos = dp->dp_meta_objset;
656
657         if (origin == NULL)
658                 origin = dp->dp_origin_snap;
659
660         ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
661         ASSERT(origin == NULL || origin->ds_phys->ds_num_children > 0);
662         ASSERT(dmu_tx_is_syncing(tx));
663         ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
664
665         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
666             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
667         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
668         dmu_buf_will_dirty(dbuf, tx);
669         dsphys = dbuf->db_data;
670         bzero(dsphys, sizeof (dsl_dataset_phys_t));
671         dsphys->ds_dir_obj = dd->dd_object;
672         dsphys->ds_flags = flags;
673         dsphys->ds_fsid_guid = unique_create();
674         do {
675                 (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
676                     sizeof (dsphys->ds_guid));
677         } while (dsphys->ds_guid == 0);
678         dsphys->ds_snapnames_zapobj =
679             zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
680             DMU_OT_NONE, 0, tx);
681         dsphys->ds_creation_time = gethrestime_sec();
682         dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
683
684         if (origin == NULL) {
685                 dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
686         } else {
687                 dsl_dataset_t *ohds; /* head of the origin snapshot */
688
689                 dsphys->ds_prev_snap_obj = origin->ds_object;
690                 dsphys->ds_prev_snap_txg =
691                     origin->ds_phys->ds_creation_txg;
692                 dsphys->ds_referenced_bytes =
693                     origin->ds_phys->ds_referenced_bytes;
694                 dsphys->ds_compressed_bytes =
695                     origin->ds_phys->ds_compressed_bytes;
696                 dsphys->ds_uncompressed_bytes =
697                     origin->ds_phys->ds_uncompressed_bytes;
698                 dsphys->ds_bp = origin->ds_phys->ds_bp;
699                 dsphys->ds_flags |= origin->ds_phys->ds_flags;
700
701                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
702                 origin->ds_phys->ds_num_children++;
703
704                 VERIFY0(dsl_dataset_hold_obj(dp,
705                     origin->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ohds));
706                 dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
707                     dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
708                 dsl_dataset_rele(ohds, FTAG);
709
710                 if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
711                         if (origin->ds_phys->ds_next_clones_obj == 0) {
712                                 origin->ds_phys->ds_next_clones_obj =
713                                     zap_create(mos,
714                                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
715                         }
716                         VERIFY0(zap_add_int(mos,
717                             origin->ds_phys->ds_next_clones_obj, dsobj, tx));
718                 }
719
720                 dmu_buf_will_dirty(dd->dd_dbuf, tx);
721                 dd->dd_phys->dd_origin_obj = origin->ds_object;
722                 if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
723                         if (origin->ds_dir->dd_phys->dd_clones == 0) {
724                                 dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
725                                 origin->ds_dir->dd_phys->dd_clones =
726                                     zap_create(mos,
727                                     DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
728                         }
729                         VERIFY0(zap_add_int(mos,
730                             origin->ds_dir->dd_phys->dd_clones, dsobj, tx));
731                 }
732         }
733
734         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
735                 dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
736
737         dmu_buf_rele(dbuf, FTAG);
738
739         dmu_buf_will_dirty(dd->dd_dbuf, tx);
740         dd->dd_phys->dd_head_dataset_obj = dsobj;
741
742         return (dsobj);
743 }
744
745 static void
746 dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
747 {
748         objset_t *os;
749
750         VERIFY0(dmu_objset_from_ds(ds, &os));
751         bzero(&os->os_zil_header, sizeof (os->os_zil_header));
752         dsl_dataset_dirty(ds, tx);
753 }
754
755 uint64_t
756 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
757     dsl_dataset_t *origin, uint64_t flags, cred_t *cr, dmu_tx_t *tx)
758 {
759         dsl_pool_t *dp = pdd->dd_pool;
760         uint64_t dsobj, ddobj;
761         dsl_dir_t *dd;
762
763         ASSERT(dmu_tx_is_syncing(tx));
764         ASSERT(lastname[0] != '@');
765
766         ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
767         VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
768
769         dsobj = dsl_dataset_create_sync_dd(dd, origin,
770             flags & ~DS_CREATE_FLAG_NODIRTY, tx);
771
772         dsl_deleg_set_create_perms(dd, tx, cr);
773
774         /*
775          * Since we're creating a new node we know it's a leaf, so we can
776          * initialize the counts if the limit feature is active.
777          */
778         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
779                 uint64_t cnt = 0;
780                 objset_t *os = dd->dd_pool->dp_meta_objset;
781
782                 dsl_dir_zapify(dd, tx);
783                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
784                     sizeof (cnt), 1, &cnt, tx));
785                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
786                     sizeof (cnt), 1, &cnt, tx));
787         }
788
789         dsl_dir_rele(dd, FTAG);
790
791         /*
792          * If we are creating a clone, make sure we zero out any stale
793          * data from the origin snapshots zil header.
794          */
795         if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
796                 dsl_dataset_t *ds;
797
798                 VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
799                 dsl_dataset_zero_zil(ds, tx);
800                 dsl_dataset_rele(ds, FTAG);
801         }
802
803         return (dsobj);
804 }
805
806 #ifdef __FreeBSD__
807 /* FreeBSD ioctl compat begin */
808 struct destroyarg {
809         nvlist_t *nvl;
810         const char *snapname;
811 };
812
813 static int
814 dsl_check_snap_cb(const char *name, void *arg)
815 {
816         struct destroyarg *da = arg;
817         dsl_dataset_t *ds;
818         char *dsname;
819
820         dsname = kmem_asprintf("%s@%s", name, da->snapname);
821         fnvlist_add_boolean(da->nvl, dsname);
822         kmem_free(dsname, strlen(dsname) + 1);
823
824         return (0);
825 }
826
827 int
828 dmu_get_recursive_snaps_nvl(char *fsname, const char *snapname,
829     nvlist_t *snaps)
830 {
831         struct destroyarg *da;
832         int err;
833
834         da = kmem_zalloc(sizeof (struct destroyarg), KM_SLEEP);
835         da->nvl = snaps;
836         da->snapname = snapname;
837         err = dmu_objset_find(fsname, dsl_check_snap_cb, da,
838             DS_FIND_CHILDREN);
839         kmem_free(da, sizeof (struct destroyarg));
840
841         return (err);
842 }
843 /* FreeBSD ioctl compat end */
844 #endif /* __FreeBSD__ */
845
846 /*
847  * The unique space in the head dataset can be calculated by subtracting
848  * the space used in the most recent snapshot, that is still being used
849  * in this file system, from the space currently in use.  To figure out
850  * the space in the most recent snapshot still in use, we need to take
851  * the total space used in the snapshot and subtract out the space that
852  * has been freed up since the snapshot was taken.
853  */
854 void
855 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
856 {
857         uint64_t mrs_used;
858         uint64_t dlused, dlcomp, dluncomp;
859
860         ASSERT(!dsl_dataset_is_snapshot(ds));
861
862         if (ds->ds_phys->ds_prev_snap_obj != 0)
863                 mrs_used = ds->ds_prev->ds_phys->ds_referenced_bytes;
864         else
865                 mrs_used = 0;
866
867         dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
868
869         ASSERT3U(dlused, <=, mrs_used);
870         ds->ds_phys->ds_unique_bytes =
871             ds->ds_phys->ds_referenced_bytes - (mrs_used - dlused);
872
873         if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
874             SPA_VERSION_UNIQUE_ACCURATE)
875                 ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
876 }
877
878 void
879 dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
880     dmu_tx_t *tx)
881 {
882         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
883         uint64_t count;
884         int err;
885
886         ASSERT(ds->ds_phys->ds_num_children >= 2);
887         err = zap_remove_int(mos, ds->ds_phys->ds_next_clones_obj, obj, tx);
888         /*
889          * The err should not be ENOENT, but a bug in a previous version
890          * of the code could cause upgrade_clones_cb() to not set
891          * ds_next_snap_obj when it should, leading to a missing entry.
892          * If we knew that the pool was created after
893          * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
894          * ENOENT.  However, at least we can check that we don't have
895          * too many entries in the next_clones_obj even after failing to
896          * remove this one.
897          */
898         if (err != ENOENT)
899                 VERIFY0(err);
900         ASSERT0(zap_count(mos, ds->ds_phys->ds_next_clones_obj,
901             &count));
902         ASSERT3U(count, <=, ds->ds_phys->ds_num_children - 2);
903 }
904
905
906 blkptr_t *
907 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
908 {
909         return (&ds->ds_phys->ds_bp);
910 }
911
912 void
913 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
914 {
915         ASSERT(dmu_tx_is_syncing(tx));
916         /* If it's the meta-objset, set dp_meta_rootbp */
917         if (ds == NULL) {
918                 tx->tx_pool->dp_meta_rootbp = *bp;
919         } else {
920                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
921                 ds->ds_phys->ds_bp = *bp;
922         }
923 }
924
925 spa_t *
926 dsl_dataset_get_spa(dsl_dataset_t *ds)
927 {
928         return (ds->ds_dir->dd_pool->dp_spa);
929 }
930
931 void
932 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
933 {
934         dsl_pool_t *dp;
935
936         if (ds == NULL) /* this is the meta-objset */
937                 return;
938
939         ASSERT(ds->ds_objset != NULL);
940
941         if (ds->ds_phys->ds_next_snap_obj != 0)
942                 panic("dirtying snapshot!");
943
944         dp = ds->ds_dir->dd_pool;
945
946         if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
947                 /* up the hold count until we can be written out */
948                 dmu_buf_add_ref(ds->ds_dbuf, ds);
949         }
950 }
951
952 boolean_t
953 dsl_dataset_is_dirty(dsl_dataset_t *ds)
954 {
955         for (int t = 0; t < TXG_SIZE; t++) {
956                 if (txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
957                     ds, t))
958                         return (B_TRUE);
959         }
960         return (B_FALSE);
961 }
962
963 static int
964 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
965 {
966         uint64_t asize;
967
968         if (!dmu_tx_is_syncing(tx))
969                 return (0);
970
971         /*
972          * If there's an fs-only reservation, any blocks that might become
973          * owned by the snapshot dataset must be accommodated by space
974          * outside of the reservation.
975          */
976         ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
977         asize = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
978         if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
979                 return (SET_ERROR(ENOSPC));
980
981         /*
982          * Propagate any reserved space for this snapshot to other
983          * snapshot checks in this sync group.
984          */
985         if (asize > 0)
986                 dsl_dir_willuse_space(ds->ds_dir, asize, tx);
987
988         return (0);
989 }
990
991 typedef struct dsl_dataset_snapshot_arg {
992         nvlist_t *ddsa_snaps;
993         nvlist_t *ddsa_props;
994         nvlist_t *ddsa_errors;
995         cred_t *ddsa_cr;
996 } dsl_dataset_snapshot_arg_t;
997
998 int
999 dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1000     dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr)
1001 {
1002         int error;
1003         uint64_t value;
1004
1005         ds->ds_trysnap_txg = tx->tx_txg;
1006
1007         if (!dmu_tx_is_syncing(tx))
1008                 return (0);
1009
1010         /*
1011          * We don't allow multiple snapshots of the same txg.  If there
1012          * is already one, try again.
1013          */
1014         if (ds->ds_phys->ds_prev_snap_txg >= tx->tx_txg)
1015                 return (SET_ERROR(EAGAIN));
1016
1017         /*
1018          * Check for conflicting snapshot name.
1019          */
1020         error = dsl_dataset_snap_lookup(ds, snapname, &value);
1021         if (error == 0)
1022                 return (SET_ERROR(EEXIST));
1023         if (error != ENOENT)
1024                 return (error);
1025
1026         /*
1027          * We don't allow taking snapshots of inconsistent datasets, such as
1028          * those into which we are currently receiving.  However, if we are
1029          * creating this snapshot as part of a receive, this check will be
1030          * executed atomically with respect to the completion of the receive
1031          * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1032          * case we ignore this, knowing it will be fixed up for us shortly in
1033          * dmu_recv_end_sync().
1034          */
1035         if (!recv && DS_IS_INCONSISTENT(ds))
1036                 return (SET_ERROR(EBUSY));
1037
1038         /*
1039          * Skip the check for temporary snapshots or if we have already checked
1040          * the counts in dsl_dataset_snapshot_check. This means we really only
1041          * check the count here when we're receiving a stream.
1042          */
1043         if (cnt != 0 && cr != NULL) {
1044                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1045                     ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr);
1046                 if (error != 0)
1047                         return (error);
1048         }
1049
1050         error = dsl_dataset_snapshot_reserve_space(ds, tx);
1051         if (error != 0)
1052                 return (error);
1053
1054         return (0);
1055 }
1056
1057 static int
1058 dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1059 {
1060         dsl_dataset_snapshot_arg_t *ddsa = arg;
1061         dsl_pool_t *dp = dmu_tx_pool(tx);
1062         nvpair_t *pair;
1063         int rv = 0;
1064
1065         /*
1066          * Pre-compute how many total new snapshots will be created for each
1067          * level in the tree and below. This is needed for validating the
1068          * snapshot limit when either taking a recursive snapshot or when
1069          * taking multiple snapshots.
1070          *
1071          * The problem is that the counts are not actually adjusted when
1072          * we are checking, only when we finally sync. For a single snapshot,
1073          * this is easy, the count will increase by 1 at each node up the tree,
1074          * but its more complicated for the recursive/multiple snapshot case.
1075          *
1076          * The dsl_fs_ss_limit_check function does recursively check the count
1077          * at each level up the tree but since it is validating each snapshot
1078          * independently we need to be sure that we are validating the complete
1079          * count for the entire set of snapshots. We do this by rolling up the
1080          * counts for each component of the name into an nvlist and then
1081          * checking each of those cases with the aggregated count.
1082          *
1083          * This approach properly handles not only the recursive snapshot
1084          * case (where we get all of those on the ddsa_snaps list) but also
1085          * the sibling case (e.g. snapshot a/b and a/c so that we will also
1086          * validate the limit on 'a' using a count of 2).
1087          *
1088          * We validate the snapshot names in the third loop and only report
1089          * name errors once.
1090          */
1091         if (dmu_tx_is_syncing(tx)) {
1092                 nvlist_t *cnt_track = NULL;
1093                 cnt_track = fnvlist_alloc();
1094
1095                 /* Rollup aggregated counts into the cnt_track list */
1096                 for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1097                     pair != NULL;
1098                     pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1099                         char *pdelim;
1100                         uint64_t val;
1101                         char nm[MAXPATHLEN];
1102
1103                         (void) strlcpy(nm, nvpair_name(pair), sizeof (nm));
1104                         pdelim = strchr(nm, '@');
1105                         if (pdelim == NULL)
1106                                 continue;
1107                         *pdelim = '\0';
1108
1109                         do {
1110                                 if (nvlist_lookup_uint64(cnt_track, nm,
1111                                     &val) == 0) {
1112                                         /* update existing entry */
1113                                         fnvlist_add_uint64(cnt_track, nm,
1114                                             val + 1);
1115                                 } else {
1116                                         /* add to list */
1117                                         fnvlist_add_uint64(cnt_track, nm, 1);
1118                                 }
1119
1120                                 pdelim = strrchr(nm, '/');
1121                                 if (pdelim != NULL)
1122                                         *pdelim = '\0';
1123                         } while (pdelim != NULL);
1124                 }
1125
1126                 /* Check aggregated counts at each level */
1127                 for (pair = nvlist_next_nvpair(cnt_track, NULL);
1128                     pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1129                         int error = 0;
1130                         char *name;
1131                         uint64_t cnt = 0;
1132                         dsl_dataset_t *ds;
1133
1134                         name = nvpair_name(pair);
1135                         cnt = fnvpair_value_uint64(pair);
1136                         ASSERT(cnt > 0);
1137
1138                         error = dsl_dataset_hold(dp, name, FTAG, &ds);
1139                         if (error == 0) {
1140                                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1141                                     ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1142                                     ddsa->ddsa_cr);
1143                                 dsl_dataset_rele(ds, FTAG);
1144                         }
1145
1146                         if (error != 0) {
1147                                 if (ddsa->ddsa_errors != NULL)
1148                                         fnvlist_add_int32(ddsa->ddsa_errors,
1149                                             name, error);
1150                                 rv = error;
1151                                 /* only report one error for this check */
1152                                 break;
1153                         }
1154                 }
1155                 nvlist_free(cnt_track);
1156         }
1157
1158         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1159             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1160                 int error = 0;
1161                 dsl_dataset_t *ds;
1162                 char *name, *atp;
1163                 char dsname[MAXNAMELEN];
1164
1165                 name = nvpair_name(pair);
1166                 if (strlen(name) >= MAXNAMELEN)
1167                         error = SET_ERROR(ENAMETOOLONG);
1168                 if (error == 0) {
1169                         atp = strchr(name, '@');
1170                         if (atp == NULL)
1171                                 error = SET_ERROR(EINVAL);
1172                         if (error == 0)
1173                                 (void) strlcpy(dsname, name, atp - name + 1);
1174                 }
1175                 if (error == 0)
1176                         error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1177                 if (error == 0) {
1178                         /* passing 0/NULL skips dsl_fs_ss_limit_check */
1179                         error = dsl_dataset_snapshot_check_impl(ds,
1180                             atp + 1, tx, B_FALSE, 0, NULL);
1181                         dsl_dataset_rele(ds, FTAG);
1182                 }
1183
1184                 if (error != 0) {
1185                         if (ddsa->ddsa_errors != NULL) {
1186                                 fnvlist_add_int32(ddsa->ddsa_errors,
1187                                     name, error);
1188                         }
1189                         rv = error;
1190                 }
1191         }
1192
1193         return (rv);
1194 }
1195
1196 void
1197 dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1198     dmu_tx_t *tx)
1199 {
1200         static zil_header_t zero_zil;
1201
1202         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1203         dmu_buf_t *dbuf;
1204         dsl_dataset_phys_t *dsphys;
1205         uint64_t dsobj, crtxg;
1206         objset_t *mos = dp->dp_meta_objset;
1207         objset_t *os;
1208
1209         ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1210
1211         /*
1212          * If we are on an old pool, the zil must not be active, in which
1213          * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1214          */
1215         ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1216             dmu_objset_from_ds(ds, &os) != 0 ||
1217             bcmp(&os->os_phys->os_zil_header, &zero_zil,
1218             sizeof (zero_zil)) == 0);
1219
1220         dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1221
1222         /*
1223          * The origin's ds_creation_txg has to be < TXG_INITIAL
1224          */
1225         if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1226                 crtxg = 1;
1227         else
1228                 crtxg = tx->tx_txg;
1229
1230         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1231             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1232         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1233         dmu_buf_will_dirty(dbuf, tx);
1234         dsphys = dbuf->db_data;
1235         bzero(dsphys, sizeof (dsl_dataset_phys_t));
1236         dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1237         dsphys->ds_fsid_guid = unique_create();
1238         do {
1239                 (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1240                     sizeof (dsphys->ds_guid));
1241         } while (dsphys->ds_guid == 0);
1242         dsphys->ds_prev_snap_obj = ds->ds_phys->ds_prev_snap_obj;
1243         dsphys->ds_prev_snap_txg = ds->ds_phys->ds_prev_snap_txg;
1244         dsphys->ds_next_snap_obj = ds->ds_object;
1245         dsphys->ds_num_children = 1;
1246         dsphys->ds_creation_time = gethrestime_sec();
1247         dsphys->ds_creation_txg = crtxg;
1248         dsphys->ds_deadlist_obj = ds->ds_phys->ds_deadlist_obj;
1249         dsphys->ds_referenced_bytes = ds->ds_phys->ds_referenced_bytes;
1250         dsphys->ds_compressed_bytes = ds->ds_phys->ds_compressed_bytes;
1251         dsphys->ds_uncompressed_bytes = ds->ds_phys->ds_uncompressed_bytes;
1252         dsphys->ds_flags = ds->ds_phys->ds_flags;
1253         dsphys->ds_bp = ds->ds_phys->ds_bp;
1254         dmu_buf_rele(dbuf, FTAG);
1255
1256         ASSERT3U(ds->ds_prev != 0, ==, ds->ds_phys->ds_prev_snap_obj != 0);
1257         if (ds->ds_prev) {
1258                 uint64_t next_clones_obj =
1259                     ds->ds_prev->ds_phys->ds_next_clones_obj;
1260                 ASSERT(ds->ds_prev->ds_phys->ds_next_snap_obj ==
1261                     ds->ds_object ||
1262                     ds->ds_prev->ds_phys->ds_num_children > 1);
1263                 if (ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object) {
1264                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1265                         ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
1266                             ds->ds_prev->ds_phys->ds_creation_txg);
1267                         ds->ds_prev->ds_phys->ds_next_snap_obj = dsobj;
1268                 } else if (next_clones_obj != 0) {
1269                         dsl_dataset_remove_from_next_clones(ds->ds_prev,
1270                             dsphys->ds_next_snap_obj, tx);
1271                         VERIFY0(zap_add_int(mos,
1272                             next_clones_obj, dsobj, tx));
1273                 }
1274         }
1275
1276         /*
1277          * If we have a reference-reservation on this dataset, we will
1278          * need to increase the amount of refreservation being charged
1279          * since our unique space is going to zero.
1280          */
1281         if (ds->ds_reserved) {
1282                 int64_t delta;
1283                 ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1284                 delta = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
1285                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1286                     delta, 0, 0, tx);
1287         }
1288
1289         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1290         ds->ds_phys->ds_deadlist_obj = dsl_deadlist_clone(&ds->ds_deadlist,
1291             UINT64_MAX, ds->ds_phys->ds_prev_snap_obj, tx);
1292         dsl_deadlist_close(&ds->ds_deadlist);
1293         dsl_deadlist_open(&ds->ds_deadlist, mos, ds->ds_phys->ds_deadlist_obj);
1294         dsl_deadlist_add_key(&ds->ds_deadlist,
1295             ds->ds_phys->ds_prev_snap_txg, tx);
1296
1297         ASSERT3U(ds->ds_phys->ds_prev_snap_txg, <, tx->tx_txg);
1298         ds->ds_phys->ds_prev_snap_obj = dsobj;
1299         ds->ds_phys->ds_prev_snap_txg = crtxg;
1300         ds->ds_phys->ds_unique_bytes = 0;
1301         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1302                 ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1303
1304         VERIFY0(zap_add(mos, ds->ds_phys->ds_snapnames_zapobj,
1305             snapname, 8, 1, &dsobj, tx));
1306
1307         if (ds->ds_prev)
1308                 dsl_dataset_rele(ds->ds_prev, ds);
1309         VERIFY0(dsl_dataset_hold_obj(dp,
1310             ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
1311
1312         dsl_scan_ds_snapshotted(ds, tx);
1313
1314         dsl_dir_snap_cmtime_update(ds->ds_dir);
1315
1316         spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, "");
1317 }
1318
1319 static void
1320 dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1321 {
1322         dsl_dataset_snapshot_arg_t *ddsa = arg;
1323         dsl_pool_t *dp = dmu_tx_pool(tx);
1324         nvpair_t *pair;
1325
1326         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1327             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1328                 dsl_dataset_t *ds;
1329                 char *name, *atp;
1330                 char dsname[MAXNAMELEN];
1331
1332                 name = nvpair_name(pair);
1333                 atp = strchr(name, '@');
1334                 (void) strlcpy(dsname, name, atp - name + 1);
1335                 VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1336
1337                 dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1338                 if (ddsa->ddsa_props != NULL) {
1339                         dsl_props_set_sync_impl(ds->ds_prev,
1340                             ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1341                 }
1342                 dsl_dataset_rele(ds, FTAG);
1343         }
1344 }
1345
1346 /*
1347  * The snapshots must all be in the same pool.
1348  * All-or-nothing: if there are any failures, nothing will be modified.
1349  */
1350 int
1351 dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1352 {
1353         dsl_dataset_snapshot_arg_t ddsa;
1354         nvpair_t *pair;
1355         boolean_t needsuspend;
1356         int error;
1357         spa_t *spa;
1358         char *firstname;
1359         nvlist_t *suspended = NULL;
1360
1361         pair = nvlist_next_nvpair(snaps, NULL);
1362         if (pair == NULL)
1363                 return (0);
1364         firstname = nvpair_name(pair);
1365
1366         error = spa_open(firstname, &spa, FTAG);
1367         if (error != 0)
1368                 return (error);
1369         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1370         spa_close(spa, FTAG);
1371
1372         if (needsuspend) {
1373                 suspended = fnvlist_alloc();
1374                 for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1375                     pair = nvlist_next_nvpair(snaps, pair)) {
1376                         char fsname[MAXNAMELEN];
1377                         char *snapname = nvpair_name(pair);
1378                         char *atp;
1379                         void *cookie;
1380
1381                         atp = strchr(snapname, '@');
1382                         if (atp == NULL) {
1383                                 error = SET_ERROR(EINVAL);
1384                                 break;
1385                         }
1386                         (void) strlcpy(fsname, snapname, atp - snapname + 1);
1387
1388                         error = zil_suspend(fsname, &cookie);
1389                         if (error != 0)
1390                                 break;
1391                         fnvlist_add_uint64(suspended, fsname,
1392                             (uintptr_t)cookie);
1393                 }
1394         }
1395
1396         ddsa.ddsa_snaps = snaps;
1397         ddsa.ddsa_props = props;
1398         ddsa.ddsa_errors = errors;
1399         ddsa.ddsa_cr = CRED();
1400
1401         if (error == 0) {
1402                 error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1403                     dsl_dataset_snapshot_sync, &ddsa,
1404                     fnvlist_num_pairs(snaps) * 3);
1405         }
1406
1407         if (suspended != NULL) {
1408                 for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
1409                     pair = nvlist_next_nvpair(suspended, pair)) {
1410                         zil_resume((void *)(uintptr_t)
1411                             fnvpair_value_uint64(pair));
1412                 }
1413                 fnvlist_free(suspended);
1414         }
1415
1416 #ifdef __FreeBSD__
1417 #ifdef _KERNEL
1418         if (error == 0) {
1419                 for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1420                     pair = nvlist_next_nvpair(snaps, pair)) {
1421                         char *snapname = nvpair_name(pair);
1422                         zvol_create_minors(snapname);
1423                 }
1424         }
1425 #endif
1426 #endif
1427         return (error);
1428 }
1429
1430 typedef struct dsl_dataset_snapshot_tmp_arg {
1431         const char *ddsta_fsname;
1432         const char *ddsta_snapname;
1433         minor_t ddsta_cleanup_minor;
1434         const char *ddsta_htag;
1435 } dsl_dataset_snapshot_tmp_arg_t;
1436
1437 static int
1438 dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
1439 {
1440         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1441         dsl_pool_t *dp = dmu_tx_pool(tx);
1442         dsl_dataset_t *ds;
1443         int error;
1444
1445         error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
1446         if (error != 0)
1447                 return (error);
1448
1449         /* NULL cred means no limit check for tmp snapshot */
1450         error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
1451             tx, B_FALSE, 0, NULL);
1452         if (error != 0) {
1453                 dsl_dataset_rele(ds, FTAG);
1454                 return (error);
1455         }
1456
1457         if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
1458                 dsl_dataset_rele(ds, FTAG);
1459                 return (SET_ERROR(ENOTSUP));
1460         }
1461         error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
1462             B_TRUE, tx);
1463         if (error != 0) {
1464                 dsl_dataset_rele(ds, FTAG);
1465                 return (error);
1466         }
1467
1468         dsl_dataset_rele(ds, FTAG);
1469         return (0);
1470 }
1471
1472 static void
1473 dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
1474 {
1475         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1476         dsl_pool_t *dp = dmu_tx_pool(tx);
1477         dsl_dataset_t *ds;
1478
1479         VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
1480
1481         dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
1482         dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
1483             ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
1484         dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
1485
1486         dsl_dataset_rele(ds, FTAG);
1487 }
1488
1489 int
1490 dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
1491     minor_t cleanup_minor, const char *htag)
1492 {
1493         dsl_dataset_snapshot_tmp_arg_t ddsta;
1494         int error;
1495         spa_t *spa;
1496         boolean_t needsuspend;
1497         void *cookie;
1498
1499         ddsta.ddsta_fsname = fsname;
1500         ddsta.ddsta_snapname = snapname;
1501         ddsta.ddsta_cleanup_minor = cleanup_minor;
1502         ddsta.ddsta_htag = htag;
1503
1504         error = spa_open(fsname, &spa, FTAG);
1505         if (error != 0)
1506                 return (error);
1507         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1508         spa_close(spa, FTAG);
1509
1510         if (needsuspend) {
1511                 error = zil_suspend(fsname, &cookie);
1512                 if (error != 0)
1513                         return (error);
1514         }
1515
1516         error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
1517             dsl_dataset_snapshot_tmp_sync, &ddsta, 3);
1518
1519         if (needsuspend)
1520                 zil_resume(cookie);
1521         return (error);
1522 }
1523
1524
1525 void
1526 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
1527 {
1528         ASSERT(dmu_tx_is_syncing(tx));
1529         ASSERT(ds->ds_objset != NULL);
1530         ASSERT(ds->ds_phys->ds_next_snap_obj == 0);
1531
1532         /*
1533          * in case we had to change ds_fsid_guid when we opened it,
1534          * sync it out now.
1535          */
1536         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1537         ds->ds_phys->ds_fsid_guid = ds->ds_fsid_guid;
1538
1539         dmu_objset_sync(ds->ds_objset, zio, tx);
1540 }
1541
1542 static void
1543 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
1544 {
1545         uint64_t count = 0;
1546         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1547         zap_cursor_t zc;
1548         zap_attribute_t za;
1549         nvlist_t *propval = fnvlist_alloc();
1550         nvlist_t *val = fnvlist_alloc();
1551
1552         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
1553
1554         /*
1555          * There may be missing entries in ds_next_clones_obj
1556          * due to a bug in a previous version of the code.
1557          * Only trust it if it has the right number of entries.
1558          */
1559         if (ds->ds_phys->ds_next_clones_obj != 0) {
1560                 VERIFY0(zap_count(mos, ds->ds_phys->ds_next_clones_obj,
1561                     &count));
1562         }
1563         if (count != ds->ds_phys->ds_num_children - 1)
1564                 goto fail;
1565         for (zap_cursor_init(&zc, mos, ds->ds_phys->ds_next_clones_obj);
1566             zap_cursor_retrieve(&zc, &za) == 0;
1567             zap_cursor_advance(&zc)) {
1568                 dsl_dataset_t *clone;
1569                 char buf[ZFS_MAXNAMELEN];
1570                 VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
1571                     za.za_first_integer, FTAG, &clone));
1572                 dsl_dir_name(clone->ds_dir, buf);
1573                 fnvlist_add_boolean(val, buf);
1574                 dsl_dataset_rele(clone, FTAG);
1575         }
1576         zap_cursor_fini(&zc);
1577         fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
1578         fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES), propval);
1579 fail:
1580         nvlist_free(val);
1581         nvlist_free(propval);
1582 }
1583
1584 void
1585 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
1586 {
1587         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1588         uint64_t refd, avail, uobjs, aobjs, ratio;
1589
1590         ASSERT(dsl_pool_config_held(dp));
1591
1592         ratio = ds->ds_phys->ds_compressed_bytes == 0 ? 100 :
1593             (ds->ds_phys->ds_uncompressed_bytes * 100 /
1594             ds->ds_phys->ds_compressed_bytes);
1595
1596         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO, ratio);
1597         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
1598             ds->ds_phys->ds_uncompressed_bytes);
1599
1600         if (dsl_dataset_is_snapshot(ds)) {
1601                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
1602                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
1603                     ds->ds_phys->ds_unique_bytes);
1604                 get_clones_stat(ds, nv);
1605         } else {
1606                 dsl_dir_stats(ds->ds_dir, nv);
1607         }
1608
1609         dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
1610         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
1611         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
1612
1613         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
1614             ds->ds_phys->ds_creation_time);
1615         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
1616             ds->ds_phys->ds_creation_txg);
1617         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
1618             ds->ds_quota);
1619         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
1620             ds->ds_reserved);
1621         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
1622             ds->ds_phys->ds_guid);
1623         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
1624             ds->ds_phys->ds_unique_bytes);
1625         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
1626             ds->ds_object);
1627         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
1628             ds->ds_userrefs);
1629         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
1630             DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
1631
1632         if (ds->ds_phys->ds_prev_snap_obj != 0) {
1633                 uint64_t written, comp, uncomp;
1634                 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1635                 dsl_dataset_t *prev;
1636
1637                 int err = dsl_dataset_hold_obj(dp,
1638                     ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
1639                 if (err == 0) {
1640                         err = dsl_dataset_space_written(prev, ds, &written,
1641                             &comp, &uncomp);
1642                         dsl_dataset_rele(prev, FTAG);
1643                         if (err == 0) {
1644                                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
1645                                     written);
1646                         }
1647                 }
1648         }
1649 }
1650
1651 void
1652 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
1653 {
1654         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1655         ASSERT(dsl_pool_config_held(dp));
1656
1657         stat->dds_creation_txg = ds->ds_phys->ds_creation_txg;
1658         stat->dds_inconsistent = ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT;
1659         stat->dds_guid = ds->ds_phys->ds_guid;
1660         stat->dds_origin[0] = '\0';
1661         if (dsl_dataset_is_snapshot(ds)) {
1662                 stat->dds_is_snapshot = B_TRUE;
1663                 stat->dds_num_clones = ds->ds_phys->ds_num_children - 1;
1664         } else {
1665                 stat->dds_is_snapshot = B_FALSE;
1666                 stat->dds_num_clones = 0;
1667
1668                 if (dsl_dir_is_clone(ds->ds_dir)) {
1669                         dsl_dataset_t *ods;
1670
1671                         VERIFY0(dsl_dataset_hold_obj(dp,
1672                             ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &ods));
1673                         dsl_dataset_name(ods, stat->dds_origin);
1674                         dsl_dataset_rele(ods, FTAG);
1675                 }
1676         }
1677 }
1678
1679 uint64_t
1680 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
1681 {
1682         return (ds->ds_fsid_guid);
1683 }
1684
1685 void
1686 dsl_dataset_space(dsl_dataset_t *ds,
1687     uint64_t *refdbytesp, uint64_t *availbytesp,
1688     uint64_t *usedobjsp, uint64_t *availobjsp)
1689 {
1690         *refdbytesp = ds->ds_phys->ds_referenced_bytes;
1691         *availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
1692         if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes)
1693                 *availbytesp += ds->ds_reserved - ds->ds_phys->ds_unique_bytes;
1694         if (ds->ds_quota != 0) {
1695                 /*
1696                  * Adjust available bytes according to refquota
1697                  */
1698                 if (*refdbytesp < ds->ds_quota)
1699                         *availbytesp = MIN(*availbytesp,
1700                             ds->ds_quota - *refdbytesp);
1701                 else
1702                         *availbytesp = 0;
1703         }
1704         *usedobjsp = ds->ds_phys->ds_bp.blk_fill;
1705         *availobjsp = DN_MAX_OBJECT - *usedobjsp;
1706 }
1707
1708 boolean_t
1709 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
1710 {
1711         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1712
1713         ASSERT(dsl_pool_config_held(dp));
1714         if (snap == NULL)
1715                 return (B_FALSE);
1716         if (ds->ds_phys->ds_bp.blk_birth >
1717             snap->ds_phys->ds_creation_txg) {
1718                 objset_t *os, *os_snap;
1719                 /*
1720                  * It may be that only the ZIL differs, because it was
1721                  * reset in the head.  Don't count that as being
1722                  * modified.
1723                  */
1724                 if (dmu_objset_from_ds(ds, &os) != 0)
1725                         return (B_TRUE);
1726                 if (dmu_objset_from_ds(snap, &os_snap) != 0)
1727                         return (B_TRUE);
1728                 return (bcmp(&os->os_phys->os_meta_dnode,
1729                     &os_snap->os_phys->os_meta_dnode,
1730                     sizeof (os->os_phys->os_meta_dnode)) != 0);
1731         }
1732         return (B_FALSE);
1733 }
1734
1735 typedef struct dsl_dataset_rename_snapshot_arg {
1736         const char *ddrsa_fsname;
1737         const char *ddrsa_oldsnapname;
1738         const char *ddrsa_newsnapname;
1739         boolean_t ddrsa_recursive;
1740         dmu_tx_t *ddrsa_tx;
1741 } dsl_dataset_rename_snapshot_arg_t;
1742
1743 /* ARGSUSED */
1744 static int
1745 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
1746     dsl_dataset_t *hds, void *arg)
1747 {
1748         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1749         int error;
1750         uint64_t val;
1751
1752         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
1753         if (error != 0) {
1754                 /* ignore nonexistent snapshots */
1755                 return (error == ENOENT ? 0 : error);
1756         }
1757
1758         /* new name should not exist */
1759         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
1760         if (error == 0)
1761                 error = SET_ERROR(EEXIST);
1762         else if (error == ENOENT)
1763                 error = 0;
1764
1765         /* dataset name + 1 for the "@" + the new snapshot name must fit */
1766         if (dsl_dir_namelen(hds->ds_dir) + 1 +
1767             strlen(ddrsa->ddrsa_newsnapname) >= MAXNAMELEN)
1768                 error = SET_ERROR(ENAMETOOLONG);
1769
1770         return (error);
1771 }
1772
1773 static int
1774 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
1775 {
1776         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1777         dsl_pool_t *dp = dmu_tx_pool(tx);
1778         dsl_dataset_t *hds;
1779         int error;
1780
1781         error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
1782         if (error != 0)
1783                 return (error);
1784
1785         if (ddrsa->ddrsa_recursive) {
1786                 error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
1787                     dsl_dataset_rename_snapshot_check_impl, ddrsa,
1788                     DS_FIND_CHILDREN);
1789         } else {
1790                 error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
1791         }
1792         dsl_dataset_rele(hds, FTAG);
1793         return (error);
1794 }
1795
1796 static int
1797 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
1798     dsl_dataset_t *hds, void *arg)
1799 {
1800 #ifdef __FreeBSD__
1801 #ifdef _KERNEL
1802         char *oldname, *newname;
1803 #endif
1804 #endif
1805         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1806         dsl_dataset_t *ds;
1807         uint64_t val;
1808         dmu_tx_t *tx = ddrsa->ddrsa_tx;
1809         int error;
1810
1811         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
1812         ASSERT(error == 0 || error == ENOENT);
1813         if (error == ENOENT) {
1814                 /* ignore nonexistent snapshots */
1815                 return (0);
1816         }
1817
1818         VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
1819
1820         /* log before we change the name */
1821         spa_history_log_internal_ds(ds, "rename", tx,
1822             "-> @%s", ddrsa->ddrsa_newsnapname);
1823
1824         VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
1825             B_FALSE));
1826         mutex_enter(&ds->ds_lock);
1827         (void) strcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname);
1828         mutex_exit(&ds->ds_lock);
1829         VERIFY0(zap_add(dp->dp_meta_objset, hds->ds_phys->ds_snapnames_zapobj,
1830             ds->ds_snapname, 8, 1, &ds->ds_object, tx));
1831
1832 #ifdef __FreeBSD__
1833 #ifdef _KERNEL
1834         oldname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1835         newname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1836         snprintf(oldname, MAXPATHLEN, "%s@%s", ddrsa->ddrsa_fsname,
1837             ddrsa->ddrsa_oldsnapname);
1838         snprintf(newname, MAXPATHLEN, "%s@%s", ddrsa->ddrsa_fsname,
1839             ddrsa->ddrsa_newsnapname);
1840         zfsvfs_update_fromname(oldname, newname);
1841         zvol_rename_minors(oldname, newname);
1842         kmem_free(newname, MAXPATHLEN);
1843         kmem_free(oldname, MAXPATHLEN);
1844 #endif
1845 #endif
1846         dsl_dataset_rele(ds, FTAG);
1847
1848         return (0);
1849 }
1850
1851 static void
1852 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
1853 {
1854         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1855         dsl_pool_t *dp = dmu_tx_pool(tx);
1856         dsl_dataset_t *hds;
1857
1858         VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
1859         ddrsa->ddrsa_tx = tx;
1860         if (ddrsa->ddrsa_recursive) {
1861                 VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
1862                     dsl_dataset_rename_snapshot_sync_impl, ddrsa,
1863                     DS_FIND_CHILDREN));
1864         } else {
1865                 VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
1866         }
1867         dsl_dataset_rele(hds, FTAG);
1868 }
1869
1870 int
1871 dsl_dataset_rename_snapshot(const char *fsname,
1872     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
1873 {
1874         dsl_dataset_rename_snapshot_arg_t ddrsa;
1875
1876         ddrsa.ddrsa_fsname = fsname;
1877         ddrsa.ddrsa_oldsnapname = oldsnapname;
1878         ddrsa.ddrsa_newsnapname = newsnapname;
1879         ddrsa.ddrsa_recursive = recursive;
1880
1881         return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
1882             dsl_dataset_rename_snapshot_sync, &ddrsa, 1));
1883 }
1884
1885 /*
1886  * If we're doing an ownership handoff, we need to make sure that there is
1887  * only one long hold on the dataset.  We're not allowed to change anything here
1888  * so we don't permanently release the long hold or regular hold here.  We want
1889  * to do this only when syncing to avoid the dataset unexpectedly going away
1890  * when we release the long hold.
1891  */
1892 static int
1893 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
1894 {
1895         boolean_t held;
1896
1897         if (!dmu_tx_is_syncing(tx))
1898                 return (0);
1899
1900         if (owner != NULL) {
1901                 VERIFY3P(ds->ds_owner, ==, owner);
1902                 dsl_dataset_long_rele(ds, owner);
1903         }
1904
1905         held = dsl_dataset_long_held(ds);
1906
1907         if (owner != NULL)
1908                 dsl_dataset_long_hold(ds, owner);
1909
1910         if (held)
1911                 return (SET_ERROR(EBUSY));
1912
1913         return (0);
1914 }
1915
1916 typedef struct dsl_dataset_rollback_arg {
1917         const char *ddra_fsname;
1918         void *ddra_owner;
1919         nvlist_t *ddra_result;
1920 } dsl_dataset_rollback_arg_t;
1921
1922 static int
1923 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
1924 {
1925         dsl_dataset_rollback_arg_t *ddra = arg;
1926         dsl_pool_t *dp = dmu_tx_pool(tx);
1927         dsl_dataset_t *ds;
1928         int64_t unused_refres_delta;
1929         int error;
1930
1931         error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
1932         if (error != 0)
1933                 return (error);
1934
1935         /* must not be a snapshot */
1936         if (dsl_dataset_is_snapshot(ds)) {
1937                 dsl_dataset_rele(ds, FTAG);
1938                 return (SET_ERROR(EINVAL));
1939         }
1940
1941         /* must have a most recent snapshot */
1942         if (ds->ds_phys->ds_prev_snap_txg < TXG_INITIAL) {
1943                 dsl_dataset_rele(ds, FTAG);
1944                 return (SET_ERROR(EINVAL));
1945         }
1946
1947         /* must not have any bookmarks after the most recent snapshot */
1948         nvlist_t *proprequest = fnvlist_alloc();
1949         fnvlist_add_boolean(proprequest, zfs_prop_to_name(ZFS_PROP_CREATETXG));
1950         nvlist_t *bookmarks = fnvlist_alloc();
1951         error = dsl_get_bookmarks_impl(ds, proprequest, bookmarks);
1952         fnvlist_free(proprequest);
1953         if (error != 0)
1954                 return (error);
1955         for (nvpair_t *pair = nvlist_next_nvpair(bookmarks, NULL);
1956             pair != NULL; pair = nvlist_next_nvpair(bookmarks, pair)) {
1957                 nvlist_t *valuenv =
1958                     fnvlist_lookup_nvlist(fnvpair_value_nvlist(pair),
1959                     zfs_prop_to_name(ZFS_PROP_CREATETXG));
1960                 uint64_t createtxg = fnvlist_lookup_uint64(valuenv, "value");
1961                 if (createtxg > ds->ds_phys->ds_prev_snap_txg) {
1962                         fnvlist_free(bookmarks);
1963                         dsl_dataset_rele(ds, FTAG);
1964                         return (SET_ERROR(EEXIST));
1965                 }
1966         }
1967         fnvlist_free(bookmarks);
1968
1969         error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
1970         if (error != 0) {
1971                 dsl_dataset_rele(ds, FTAG);
1972                 return (error);
1973         }
1974
1975         /*
1976          * Check if the snap we are rolling back to uses more than
1977          * the refquota.
1978          */
1979         if (ds->ds_quota != 0 &&
1980             ds->ds_prev->ds_phys->ds_referenced_bytes > ds->ds_quota) {
1981                 dsl_dataset_rele(ds, FTAG);
1982                 return (SET_ERROR(EDQUOT));
1983         }
1984
1985         /*
1986          * When we do the clone swap, we will temporarily use more space
1987          * due to the refreservation (the head will no longer have any
1988          * unique space, so the entire amount of the refreservation will need
1989          * to be free).  We will immediately destroy the clone, freeing
1990          * this space, but the freeing happens over many txg's.
1991          */
1992         unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
1993             ds->ds_phys->ds_unique_bytes);
1994
1995         if (unused_refres_delta > 0 &&
1996             unused_refres_delta >
1997             dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
1998                 dsl_dataset_rele(ds, FTAG);
1999                 return (SET_ERROR(ENOSPC));
2000         }
2001
2002         dsl_dataset_rele(ds, FTAG);
2003         return (0);
2004 }
2005
2006 static void
2007 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
2008 {
2009         dsl_dataset_rollback_arg_t *ddra = arg;
2010         dsl_pool_t *dp = dmu_tx_pool(tx);
2011         dsl_dataset_t *ds, *clone;
2012         uint64_t cloneobj;
2013         char namebuf[ZFS_MAXNAMELEN];
2014
2015         VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
2016
2017         dsl_dataset_name(ds->ds_prev, namebuf);
2018         fnvlist_add_string(ddra->ddra_result, "target", namebuf);
2019
2020         cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
2021             ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, tx);
2022
2023         VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
2024
2025         dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
2026         dsl_dataset_zero_zil(ds, tx);
2027
2028         dsl_destroy_head_sync_impl(clone, tx);
2029
2030         dsl_dataset_rele(clone, FTAG);
2031         dsl_dataset_rele(ds, FTAG);
2032 }
2033
2034 /*
2035  * Rolls back the given filesystem or volume to the most recent snapshot.
2036  * The name of the most recent snapshot will be returned under key "target"
2037  * in the result nvlist.
2038  *
2039  * If owner != NULL:
2040  * - The existing dataset MUST be owned by the specified owner at entry
2041  * - Upon return, dataset will still be held by the same owner, whether we
2042  *   succeed or not.
2043  *
2044  * This mode is required any time the existing filesystem is mounted.  See
2045  * notes above zfs_suspend_fs() for further details.
2046  */
2047 int
2048 dsl_dataset_rollback(const char *fsname, void *owner, nvlist_t *result)
2049 {
2050         dsl_dataset_rollback_arg_t ddra;
2051
2052         ddra.ddra_fsname = fsname;
2053         ddra.ddra_owner = owner;
2054         ddra.ddra_result = result;
2055
2056         return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
2057             dsl_dataset_rollback_sync, &ddra, 1));
2058 }
2059
2060 struct promotenode {
2061         list_node_t link;
2062         dsl_dataset_t *ds;
2063 };
2064
2065 typedef struct dsl_dataset_promote_arg {
2066         const char *ddpa_clonename;
2067         dsl_dataset_t *ddpa_clone;
2068         list_t shared_snaps, origin_snaps, clone_snaps;
2069         dsl_dataset_t *origin_origin; /* origin of the origin */
2070         uint64_t used, comp, uncomp, unique, cloneusedsnap, originusedsnap;
2071         char *err_ds;
2072         cred_t *cr;
2073 } dsl_dataset_promote_arg_t;
2074
2075 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2076 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
2077     void *tag);
2078 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
2079
2080 static int
2081 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
2082 {
2083         dsl_dataset_promote_arg_t *ddpa = arg;
2084         dsl_pool_t *dp = dmu_tx_pool(tx);
2085         dsl_dataset_t *hds;
2086         struct promotenode *snap;
2087         dsl_dataset_t *origin_ds;
2088         int err;
2089         uint64_t unused;
2090         uint64_t ss_mv_cnt;
2091
2092         err = promote_hold(ddpa, dp, FTAG);
2093         if (err != 0)
2094                 return (err);
2095
2096         hds = ddpa->ddpa_clone;
2097
2098         if (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE) {
2099                 promote_rele(ddpa, FTAG);
2100                 return (SET_ERROR(EXDEV));
2101         }
2102
2103         /*
2104          * Compute and check the amount of space to transfer.  Since this is
2105          * so expensive, don't do the preliminary check.
2106          */
2107         if (!dmu_tx_is_syncing(tx)) {
2108                 promote_rele(ddpa, FTAG);
2109                 return (0);
2110         }
2111
2112         snap = list_head(&ddpa->shared_snaps);
2113         origin_ds = snap->ds;
2114
2115         /* compute origin's new unique space */
2116         snap = list_tail(&ddpa->clone_snaps);
2117         ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2118         dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2119             origin_ds->ds_phys->ds_prev_snap_txg, UINT64_MAX,
2120             &ddpa->unique, &unused, &unused);
2121
2122         /*
2123          * Walk the snapshots that we are moving
2124          *
2125          * Compute space to transfer.  Consider the incremental changes
2126          * to used by each snapshot:
2127          * (my used) = (prev's used) + (blocks born) - (blocks killed)
2128          * So each snapshot gave birth to:
2129          * (blocks born) = (my used) - (prev's used) + (blocks killed)
2130          * So a sequence would look like:
2131          * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2132          * Which simplifies to:
2133          * uN + kN + kN-1 + ... + k1 + k0
2134          * Note however, if we stop before we reach the ORIGIN we get:
2135          * uN + kN + kN-1 + ... + kM - uM-1
2136          */
2137         ss_mv_cnt = 0;
2138         ddpa->used = origin_ds->ds_phys->ds_referenced_bytes;
2139         ddpa->comp = origin_ds->ds_phys->ds_compressed_bytes;
2140         ddpa->uncomp = origin_ds->ds_phys->ds_uncompressed_bytes;
2141         for (snap = list_head(&ddpa->shared_snaps); snap;
2142             snap = list_next(&ddpa->shared_snaps, snap)) {
2143                 uint64_t val, dlused, dlcomp, dluncomp;
2144                 dsl_dataset_t *ds = snap->ds;
2145
2146                 ss_mv_cnt++;
2147
2148                 /*
2149                  * If there are long holds, we won't be able to evict
2150                  * the objset.
2151                  */
2152                 if (dsl_dataset_long_held(ds)) {
2153                         err = SET_ERROR(EBUSY);
2154                         goto out;
2155                 }
2156
2157                 /* Check that the snapshot name does not conflict */
2158                 VERIFY0(dsl_dataset_get_snapname(ds));
2159                 err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2160                 if (err == 0) {
2161                         (void) strcpy(ddpa->err_ds, snap->ds->ds_snapname);
2162                         err = SET_ERROR(EEXIST);
2163                         goto out;
2164                 }
2165                 if (err != ENOENT)
2166                         goto out;
2167
2168                 /* The very first snapshot does not have a deadlist */
2169                 if (ds->ds_phys->ds_prev_snap_obj == 0)
2170                         continue;
2171
2172                 dsl_deadlist_space(&ds->ds_deadlist,
2173                     &dlused, &dlcomp, &dluncomp);
2174                 ddpa->used += dlused;
2175                 ddpa->comp += dlcomp;
2176                 ddpa->uncomp += dluncomp;
2177         }
2178
2179         /*
2180          * If we are a clone of a clone then we never reached ORIGIN,
2181          * so we need to subtract out the clone origin's used space.
2182          */
2183         if (ddpa->origin_origin) {
2184                 ddpa->used -= ddpa->origin_origin->ds_phys->ds_referenced_bytes;
2185                 ddpa->comp -= ddpa->origin_origin->ds_phys->ds_compressed_bytes;
2186                 ddpa->uncomp -=
2187                     ddpa->origin_origin->ds_phys->ds_uncompressed_bytes;
2188         }
2189
2190         /* Check that there is enough space and limit headroom here */
2191         err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2192             0, ss_mv_cnt, ddpa->used, ddpa->cr);
2193         if (err != 0)
2194                 goto out;
2195
2196         /*
2197          * Compute the amounts of space that will be used by snapshots
2198          * after the promotion (for both origin and clone).  For each,
2199          * it is the amount of space that will be on all of their
2200          * deadlists (that was not born before their new origin).
2201          */
2202         if (hds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2203                 uint64_t space;
2204
2205                 /*
2206                  * Note, typically this will not be a clone of a clone,
2207                  * so dd_origin_txg will be < TXG_INITIAL, so
2208                  * these snaplist_space() -> dsl_deadlist_space_range()
2209                  * calls will be fast because they do not have to
2210                  * iterate over all bps.
2211                  */
2212                 snap = list_head(&ddpa->origin_snaps);
2213                 err = snaplist_space(&ddpa->shared_snaps,
2214                     snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
2215                 if (err != 0)
2216                         goto out;
2217
2218                 err = snaplist_space(&ddpa->clone_snaps,
2219                     snap->ds->ds_dir->dd_origin_txg, &space);
2220                 if (err != 0)
2221                         goto out;
2222                 ddpa->cloneusedsnap += space;
2223         }
2224         if (origin_ds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2225                 err = snaplist_space(&ddpa->origin_snaps,
2226                     origin_ds->ds_phys->ds_creation_txg, &ddpa->originusedsnap);
2227                 if (err != 0)
2228                         goto out;
2229         }
2230
2231 out:
2232         promote_rele(ddpa, FTAG);
2233         return (err);
2234 }
2235
2236 static void
2237 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
2238 {
2239         dsl_dataset_promote_arg_t *ddpa = arg;
2240         dsl_pool_t *dp = dmu_tx_pool(tx);
2241         dsl_dataset_t *hds;
2242         struct promotenode *snap;
2243         dsl_dataset_t *origin_ds;
2244         dsl_dataset_t *origin_head;
2245         dsl_dir_t *dd;
2246         dsl_dir_t *odd = NULL;
2247         uint64_t oldnext_obj;
2248         int64_t delta;
2249
2250         VERIFY0(promote_hold(ddpa, dp, FTAG));
2251         hds = ddpa->ddpa_clone;
2252
2253         ASSERT0(hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE);
2254
2255         snap = list_head(&ddpa->shared_snaps);
2256         origin_ds = snap->ds;
2257         dd = hds->ds_dir;
2258
2259         snap = list_head(&ddpa->origin_snaps);
2260         origin_head = snap->ds;
2261
2262         /*
2263          * We need to explicitly open odd, since origin_ds's dd will be
2264          * changing.
2265          */
2266         VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
2267             NULL, FTAG, &odd));
2268
2269         /* change origin's next snap */
2270         dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2271         oldnext_obj = origin_ds->ds_phys->ds_next_snap_obj;
2272         snap = list_tail(&ddpa->clone_snaps);
2273         ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2274         origin_ds->ds_phys->ds_next_snap_obj = snap->ds->ds_object;
2275
2276         /* change the origin's next clone */
2277         if (origin_ds->ds_phys->ds_next_clones_obj) {
2278                 dsl_dataset_remove_from_next_clones(origin_ds,
2279                     snap->ds->ds_object, tx);
2280                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2281                     origin_ds->ds_phys->ds_next_clones_obj,
2282                     oldnext_obj, tx));
2283         }
2284
2285         /* change origin */
2286         dmu_buf_will_dirty(dd->dd_dbuf, tx);
2287         ASSERT3U(dd->dd_phys->dd_origin_obj, ==, origin_ds->ds_object);
2288         dd->dd_phys->dd_origin_obj = odd->dd_phys->dd_origin_obj;
2289         dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2290         dmu_buf_will_dirty(odd->dd_dbuf, tx);
2291         odd->dd_phys->dd_origin_obj = origin_ds->ds_object;
2292         origin_head->ds_dir->dd_origin_txg =
2293             origin_ds->ds_phys->ds_creation_txg;
2294
2295         /* change dd_clone entries */
2296         if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2297                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2298                     odd->dd_phys->dd_clones, hds->ds_object, tx));
2299                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2300                     ddpa->origin_origin->ds_dir->dd_phys->dd_clones,
2301                     hds->ds_object, tx));
2302
2303                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2304                     ddpa->origin_origin->ds_dir->dd_phys->dd_clones,
2305                     origin_head->ds_object, tx));
2306                 if (dd->dd_phys->dd_clones == 0) {
2307                         dd->dd_phys->dd_clones = zap_create(dp->dp_meta_objset,
2308                             DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
2309                 }
2310                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2311                     dd->dd_phys->dd_clones, origin_head->ds_object, tx));
2312         }
2313
2314         /* move snapshots to this dir */
2315         for (snap = list_head(&ddpa->shared_snaps); snap;
2316             snap = list_next(&ddpa->shared_snaps, snap)) {
2317                 dsl_dataset_t *ds = snap->ds;
2318
2319                 /*
2320                  * Property callbacks are registered to a particular
2321                  * dsl_dir.  Since ours is changing, evict the objset
2322                  * so that they will be unregistered from the old dsl_dir.
2323                  */
2324                 if (ds->ds_objset) {
2325                         dmu_objset_evict(ds->ds_objset);
2326                         ds->ds_objset = NULL;
2327                 }
2328
2329                 /* move snap name entry */
2330                 VERIFY0(dsl_dataset_get_snapname(ds));
2331                 VERIFY0(dsl_dataset_snap_remove(origin_head,
2332                     ds->ds_snapname, tx, B_TRUE));
2333                 VERIFY0(zap_add(dp->dp_meta_objset,
2334                     hds->ds_phys->ds_snapnames_zapobj, ds->ds_snapname,
2335                     8, 1, &ds->ds_object, tx));
2336                 dsl_fs_ss_count_adjust(hds->ds_dir, 1,
2337                     DD_FIELD_SNAPSHOT_COUNT, tx);
2338
2339                 /* change containing dsl_dir */
2340                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2341                 ASSERT3U(ds->ds_phys->ds_dir_obj, ==, odd->dd_object);
2342                 ds->ds_phys->ds_dir_obj = dd->dd_object;
2343                 ASSERT3P(ds->ds_dir, ==, odd);
2344                 dsl_dir_rele(ds->ds_dir, ds);
2345                 VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
2346                     NULL, ds, &ds->ds_dir));
2347
2348                 /* move any clone references */
2349                 if (ds->ds_phys->ds_next_clones_obj &&
2350                     spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2351                         zap_cursor_t zc;
2352                         zap_attribute_t za;
2353
2354                         for (zap_cursor_init(&zc, dp->dp_meta_objset,
2355                             ds->ds_phys->ds_next_clones_obj);
2356                             zap_cursor_retrieve(&zc, &za) == 0;
2357                             zap_cursor_advance(&zc)) {
2358                                 dsl_dataset_t *cnds;
2359                                 uint64_t o;
2360
2361                                 if (za.za_first_integer == oldnext_obj) {
2362                                         /*
2363                                          * We've already moved the
2364                                          * origin's reference.
2365                                          */
2366                                         continue;
2367                                 }
2368
2369                                 VERIFY0(dsl_dataset_hold_obj(dp,
2370                                     za.za_first_integer, FTAG, &cnds));
2371                                 o = cnds->ds_dir->dd_phys->dd_head_dataset_obj;
2372
2373                                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2374                                     odd->dd_phys->dd_clones, o, tx));
2375                                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2376                                     dd->dd_phys->dd_clones, o, tx));
2377                                 dsl_dataset_rele(cnds, FTAG);
2378                         }
2379                         zap_cursor_fini(&zc);
2380                 }
2381
2382                 ASSERT(!dsl_prop_hascb(ds));
2383         }
2384
2385         /*
2386          * Change space accounting.
2387          * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
2388          * both be valid, or both be 0 (resulting in delta == 0).  This
2389          * is true for each of {clone,origin} independently.
2390          */
2391
2392         delta = ddpa->cloneusedsnap -
2393             dd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2394         ASSERT3S(delta, >=, 0);
2395         ASSERT3U(ddpa->used, >=, delta);
2396         dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
2397         dsl_dir_diduse_space(dd, DD_USED_HEAD,
2398             ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
2399
2400         delta = ddpa->originusedsnap -
2401             odd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2402         ASSERT3S(delta, <=, 0);
2403         ASSERT3U(ddpa->used, >=, -delta);
2404         dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
2405         dsl_dir_diduse_space(odd, DD_USED_HEAD,
2406             -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
2407
2408         origin_ds->ds_phys->ds_unique_bytes = ddpa->unique;
2409
2410         /* log history record */
2411         spa_history_log_internal_ds(hds, "promote", tx, "");
2412
2413         dsl_dir_rele(odd, FTAG);
2414         promote_rele(ddpa, FTAG);
2415 }
2416
2417 /*
2418  * Make a list of dsl_dataset_t's for the snapshots between first_obj
2419  * (exclusive) and last_obj (inclusive).  The list will be in reverse
2420  * order (last_obj will be the list_head()).  If first_obj == 0, do all
2421  * snapshots back to this dataset's origin.
2422  */
2423 static int
2424 snaplist_make(dsl_pool_t *dp,
2425     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
2426 {
2427         uint64_t obj = last_obj;
2428
2429         list_create(l, sizeof (struct promotenode),
2430             offsetof(struct promotenode, link));
2431
2432         while (obj != first_obj) {
2433                 dsl_dataset_t *ds;
2434                 struct promotenode *snap;
2435                 int err;
2436
2437                 err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
2438                 ASSERT(err != ENOENT);
2439                 if (err != 0)
2440                         return (err);
2441
2442                 if (first_obj == 0)
2443                         first_obj = ds->ds_dir->dd_phys->dd_origin_obj;
2444
2445                 snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
2446                 snap->ds = ds;
2447                 list_insert_tail(l, snap);
2448                 obj = ds->ds_phys->ds_prev_snap_obj;
2449         }
2450
2451         return (0);
2452 }
2453
2454 static int
2455 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
2456 {
2457         struct promotenode *snap;
2458
2459         *spacep = 0;
2460         for (snap = list_head(l); snap; snap = list_next(l, snap)) {
2461                 uint64_t used, comp, uncomp;
2462                 dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2463                     mintxg, UINT64_MAX, &used, &comp, &uncomp);
2464                 *spacep += used;
2465         }
2466         return (0);
2467 }
2468
2469 static void
2470 snaplist_destroy(list_t *l, void *tag)
2471 {
2472         struct promotenode *snap;
2473
2474         if (l == NULL || !list_link_active(&l->list_head))
2475                 return;
2476
2477         while ((snap = list_tail(l)) != NULL) {
2478                 list_remove(l, snap);
2479                 dsl_dataset_rele(snap->ds, tag);
2480                 kmem_free(snap, sizeof (*snap));
2481         }
2482         list_destroy(l);
2483 }
2484
2485 static int
2486 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
2487 {
2488         int error;
2489         dsl_dir_t *dd;
2490         struct promotenode *snap;
2491
2492         error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
2493             &ddpa->ddpa_clone);
2494         if (error != 0)
2495                 return (error);
2496         dd = ddpa->ddpa_clone->ds_dir;
2497
2498         if (dsl_dataset_is_snapshot(ddpa->ddpa_clone) ||
2499             !dsl_dir_is_clone(dd)) {
2500                 dsl_dataset_rele(ddpa->ddpa_clone, tag);
2501                 return (SET_ERROR(EINVAL));
2502         }
2503
2504         error = snaplist_make(dp, 0, dd->dd_phys->dd_origin_obj,
2505             &ddpa->shared_snaps, tag);
2506         if (error != 0)
2507                 goto out;
2508
2509         error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
2510             &ddpa->clone_snaps, tag);
2511         if (error != 0)
2512                 goto out;
2513
2514         snap = list_head(&ddpa->shared_snaps);
2515         ASSERT3U(snap->ds->ds_object, ==, dd->dd_phys->dd_origin_obj);
2516         error = snaplist_make(dp, dd->dd_phys->dd_origin_obj,
2517             snap->ds->ds_dir->dd_phys->dd_head_dataset_obj,
2518             &ddpa->origin_snaps, tag);
2519         if (error != 0)
2520                 goto out;
2521
2522         if (snap->ds->ds_dir->dd_phys->dd_origin_obj != 0) {
2523                 error = dsl_dataset_hold_obj(dp,
2524                     snap->ds->ds_dir->dd_phys->dd_origin_obj,
2525                     tag, &ddpa->origin_origin);
2526                 if (error != 0)
2527                         goto out;
2528         }
2529 out:
2530         if (error != 0)
2531                 promote_rele(ddpa, tag);
2532         return (error);
2533 }
2534
2535 static void
2536 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
2537 {
2538         snaplist_destroy(&ddpa->shared_snaps, tag);
2539         snaplist_destroy(&ddpa->clone_snaps, tag);
2540         snaplist_destroy(&ddpa->origin_snaps, tag);
2541         if (ddpa->origin_origin != NULL)
2542                 dsl_dataset_rele(ddpa->origin_origin, tag);
2543         dsl_dataset_rele(ddpa->ddpa_clone, tag);
2544 }
2545
2546 /*
2547  * Promote a clone.
2548  *
2549  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
2550  * in with the name.  (It must be at least MAXNAMELEN bytes long.)
2551  */
2552 int
2553 dsl_dataset_promote(const char *name, char *conflsnap)
2554 {
2555         dsl_dataset_promote_arg_t ddpa = { 0 };
2556         uint64_t numsnaps;
2557         int error;
2558         objset_t *os;
2559
2560         /*
2561          * We will modify space proportional to the number of
2562          * snapshots.  Compute numsnaps.
2563          */
2564         error = dmu_objset_hold(name, FTAG, &os);
2565         if (error != 0)
2566                 return (error);
2567         error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
2568             dmu_objset_ds(os)->ds_phys->ds_snapnames_zapobj, &numsnaps);
2569         dmu_objset_rele(os, FTAG);
2570         if (error != 0)
2571                 return (error);
2572
2573         ddpa.ddpa_clonename = name;
2574         ddpa.err_ds = conflsnap;
2575         ddpa.cr = CRED();
2576
2577         return (dsl_sync_task(name, dsl_dataset_promote_check,
2578             dsl_dataset_promote_sync, &ddpa, 2 + numsnaps));
2579 }
2580
2581 int
2582 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
2583     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
2584 {
2585         int64_t unused_refres_delta;
2586
2587         /* they should both be heads */
2588         if (dsl_dataset_is_snapshot(clone) ||
2589             dsl_dataset_is_snapshot(origin_head))
2590                 return (SET_ERROR(EINVAL));
2591
2592         /* if we are not forcing, the branch point should be just before them */
2593         if (!force && clone->ds_prev != origin_head->ds_prev)
2594                 return (SET_ERROR(EINVAL));
2595
2596         /* clone should be the clone (unless they are unrelated) */
2597         if (clone->ds_prev != NULL &&
2598             clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
2599             origin_head->ds_dir != clone->ds_prev->ds_dir)
2600                 return (SET_ERROR(EINVAL));
2601
2602         /* the clone should be a child of the origin */
2603         if (clone->ds_dir->dd_parent != origin_head->ds_dir)
2604                 return (SET_ERROR(EINVAL));
2605
2606         /* origin_head shouldn't be modified unless 'force' */
2607         if (!force &&
2608             dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
2609                 return (SET_ERROR(ETXTBSY));
2610
2611         /* origin_head should have no long holds (e.g. is not mounted) */
2612         if (dsl_dataset_handoff_check(origin_head, owner, tx))
2613                 return (SET_ERROR(EBUSY));
2614
2615         /* check amount of any unconsumed refreservation */
2616         unused_refres_delta =
2617             (int64_t)MIN(origin_head->ds_reserved,
2618             origin_head->ds_phys->ds_unique_bytes) -
2619             (int64_t)MIN(origin_head->ds_reserved,
2620             clone->ds_phys->ds_unique_bytes);
2621
2622         if (unused_refres_delta > 0 &&
2623             unused_refres_delta >
2624             dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
2625                 return (SET_ERROR(ENOSPC));
2626
2627         /* clone can't be over the head's refquota */
2628         if (origin_head->ds_quota != 0 &&
2629             clone->ds_phys->ds_referenced_bytes > origin_head->ds_quota)
2630                 return (SET_ERROR(EDQUOT));
2631
2632         return (0);
2633 }
2634
2635 void
2636 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
2637     dsl_dataset_t *origin_head, dmu_tx_t *tx)
2638 {
2639         dsl_pool_t *dp = dmu_tx_pool(tx);
2640         int64_t unused_refres_delta;
2641
2642         ASSERT(clone->ds_reserved == 0);
2643         ASSERT(origin_head->ds_quota == 0 ||
2644             clone->ds_phys->ds_unique_bytes <= origin_head->ds_quota);
2645         ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
2646
2647         dmu_buf_will_dirty(clone->ds_dbuf, tx);
2648         dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
2649
2650         if (clone->ds_objset != NULL) {
2651                 dmu_objset_evict(clone->ds_objset);
2652                 clone->ds_objset = NULL;
2653         }
2654
2655         if (origin_head->ds_objset != NULL) {
2656                 dmu_objset_evict(origin_head->ds_objset);
2657                 origin_head->ds_objset = NULL;
2658         }
2659
2660         unused_refres_delta =
2661             (int64_t)MIN(origin_head->ds_reserved,
2662             origin_head->ds_phys->ds_unique_bytes) -
2663             (int64_t)MIN(origin_head->ds_reserved,
2664             clone->ds_phys->ds_unique_bytes);
2665
2666         /*
2667          * Reset origin's unique bytes, if it exists.
2668          */
2669         if (clone->ds_prev) {
2670                 dsl_dataset_t *origin = clone->ds_prev;
2671                 uint64_t comp, uncomp;
2672
2673                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
2674                 dsl_deadlist_space_range(&clone->ds_deadlist,
2675                     origin->ds_phys->ds_prev_snap_txg, UINT64_MAX,
2676                     &origin->ds_phys->ds_unique_bytes, &comp, &uncomp);
2677         }
2678
2679         /* swap blkptrs */
2680         {
2681                 blkptr_t tmp;
2682                 tmp = origin_head->ds_phys->ds_bp;
2683                 origin_head->ds_phys->ds_bp = clone->ds_phys->ds_bp;
2684                 clone->ds_phys->ds_bp = tmp;
2685         }
2686
2687         /* set dd_*_bytes */
2688         {
2689                 int64_t dused, dcomp, duncomp;
2690                 uint64_t cdl_used, cdl_comp, cdl_uncomp;
2691                 uint64_t odl_used, odl_comp, odl_uncomp;
2692
2693                 ASSERT3U(clone->ds_dir->dd_phys->
2694                     dd_used_breakdown[DD_USED_SNAP], ==, 0);
2695
2696                 dsl_deadlist_space(&clone->ds_deadlist,
2697                     &cdl_used, &cdl_comp, &cdl_uncomp);
2698                 dsl_deadlist_space(&origin_head->ds_deadlist,
2699                     &odl_used, &odl_comp, &odl_uncomp);
2700
2701                 dused = clone->ds_phys->ds_referenced_bytes + cdl_used -
2702                     (origin_head->ds_phys->ds_referenced_bytes + odl_used);
2703                 dcomp = clone->ds_phys->ds_compressed_bytes + cdl_comp -
2704                     (origin_head->ds_phys->ds_compressed_bytes + odl_comp);
2705                 duncomp = clone->ds_phys->ds_uncompressed_bytes +
2706                     cdl_uncomp -
2707                     (origin_head->ds_phys->ds_uncompressed_bytes + odl_uncomp);
2708
2709                 dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
2710                     dused, dcomp, duncomp, tx);
2711                 dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
2712                     -dused, -dcomp, -duncomp, tx);
2713
2714                 /*
2715                  * The difference in the space used by snapshots is the
2716                  * difference in snapshot space due to the head's
2717                  * deadlist (since that's the only thing that's
2718                  * changing that affects the snapused).
2719                  */
2720                 dsl_deadlist_space_range(&clone->ds_deadlist,
2721                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2722                     &cdl_used, &cdl_comp, &cdl_uncomp);
2723                 dsl_deadlist_space_range(&origin_head->ds_deadlist,
2724                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2725                     &odl_used, &odl_comp, &odl_uncomp);
2726                 dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
2727                     DD_USED_HEAD, DD_USED_SNAP, tx);
2728         }
2729
2730         /* swap ds_*_bytes */
2731         SWITCH64(origin_head->ds_phys->ds_referenced_bytes,
2732             clone->ds_phys->ds_referenced_bytes);
2733         SWITCH64(origin_head->ds_phys->ds_compressed_bytes,
2734             clone->ds_phys->ds_compressed_bytes);
2735         SWITCH64(origin_head->ds_phys->ds_uncompressed_bytes,
2736             clone->ds_phys->ds_uncompressed_bytes);
2737         SWITCH64(origin_head->ds_phys->ds_unique_bytes,
2738             clone->ds_phys->ds_unique_bytes);
2739
2740         /* apply any parent delta for change in unconsumed refreservation */
2741         dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
2742             unused_refres_delta, 0, 0, tx);
2743
2744         /*
2745          * Swap deadlists.
2746          */
2747         dsl_deadlist_close(&clone->ds_deadlist);
2748         dsl_deadlist_close(&origin_head->ds_deadlist);
2749         SWITCH64(origin_head->ds_phys->ds_deadlist_obj,
2750             clone->ds_phys->ds_deadlist_obj);
2751         dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
2752             clone->ds_phys->ds_deadlist_obj);
2753         dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
2754             origin_head->ds_phys->ds_deadlist_obj);
2755
2756         dsl_scan_ds_clone_swapped(origin_head, clone, tx);
2757
2758         spa_history_log_internal_ds(clone, "clone swap", tx,
2759             "parent=%s", origin_head->ds_dir->dd_myname);
2760 }
2761
2762 /*
2763  * Given a pool name and a dataset object number in that pool,
2764  * return the name of that dataset.
2765  */
2766 int
2767 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
2768 {
2769         dsl_pool_t *dp;
2770         dsl_dataset_t *ds;
2771         int error;
2772
2773         error = dsl_pool_hold(pname, FTAG, &dp);
2774         if (error != 0)
2775                 return (error);
2776
2777         error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
2778         if (error == 0) {
2779                 dsl_dataset_name(ds, buf);
2780                 dsl_dataset_rele(ds, FTAG);
2781         }
2782         dsl_pool_rele(dp, FTAG);
2783
2784         return (error);
2785 }
2786
2787 int
2788 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
2789     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
2790 {
2791         int error = 0;
2792
2793         ASSERT3S(asize, >, 0);
2794
2795         /*
2796          * *ref_rsrv is the portion of asize that will come from any
2797          * unconsumed refreservation space.
2798          */
2799         *ref_rsrv = 0;
2800
2801         mutex_enter(&ds->ds_lock);
2802         /*
2803          * Make a space adjustment for reserved bytes.
2804          */
2805         if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes) {
2806                 ASSERT3U(*used, >=,
2807                     ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
2808                 *used -= (ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
2809                 *ref_rsrv =
2810                     asize - MIN(asize, parent_delta(ds, asize + inflight));
2811         }
2812
2813         if (!check_quota || ds->ds_quota == 0) {
2814                 mutex_exit(&ds->ds_lock);
2815                 return (0);
2816         }
2817         /*
2818          * If they are requesting more space, and our current estimate
2819          * is over quota, they get to try again unless the actual
2820          * on-disk is over quota and there are no pending changes (which
2821          * may free up space for us).
2822          */
2823         if (ds->ds_phys->ds_referenced_bytes + inflight >= ds->ds_quota) {
2824                 if (inflight > 0 ||
2825                     ds->ds_phys->ds_referenced_bytes < ds->ds_quota)
2826                         error = SET_ERROR(ERESTART);
2827                 else
2828                         error = SET_ERROR(EDQUOT);
2829         }
2830         mutex_exit(&ds->ds_lock);
2831
2832         return (error);
2833 }
2834
2835 typedef struct dsl_dataset_set_qr_arg {
2836         const char *ddsqra_name;
2837         zprop_source_t ddsqra_source;
2838         uint64_t ddsqra_value;
2839 } dsl_dataset_set_qr_arg_t;
2840
2841
2842 /* ARGSUSED */
2843 static int
2844 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
2845 {
2846         dsl_dataset_set_qr_arg_t *ddsqra = arg;
2847         dsl_pool_t *dp = dmu_tx_pool(tx);
2848         dsl_dataset_t *ds;
2849         int error;
2850         uint64_t newval;
2851
2852         if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
2853                 return (SET_ERROR(ENOTSUP));
2854
2855         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
2856         if (error != 0)
2857                 return (error);
2858
2859         if (dsl_dataset_is_snapshot(ds)) {
2860                 dsl_dataset_rele(ds, FTAG);
2861                 return (SET_ERROR(EINVAL));
2862         }
2863
2864         error = dsl_prop_predict(ds->ds_dir,
2865             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
2866             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
2867         if (error != 0) {
2868                 dsl_dataset_rele(ds, FTAG);
2869                 return (error);
2870         }
2871
2872         if (newval == 0) {
2873                 dsl_dataset_rele(ds, FTAG);
2874                 return (0);
2875         }
2876
2877         if (newval < ds->ds_phys->ds_referenced_bytes ||
2878             newval < ds->ds_reserved) {
2879                 dsl_dataset_rele(ds, FTAG);
2880                 return (SET_ERROR(ENOSPC));
2881         }
2882
2883         dsl_dataset_rele(ds, FTAG);
2884         return (0);
2885 }
2886
2887 static void
2888 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
2889 {
2890         dsl_dataset_set_qr_arg_t *ddsqra = arg;
2891         dsl_pool_t *dp = dmu_tx_pool(tx);
2892         dsl_dataset_t *ds;
2893         uint64_t newval;
2894
2895         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
2896
2897         dsl_prop_set_sync_impl(ds,
2898             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
2899             ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
2900             &ddsqra->ddsqra_value, tx);
2901
2902         VERIFY0(dsl_prop_get_int_ds(ds,
2903             zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
2904
2905         if (ds->ds_quota != newval) {
2906                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2907                 ds->ds_quota = newval;
2908         }
2909         dsl_dataset_rele(ds, FTAG);
2910 }
2911
2912 int
2913 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
2914     uint64_t refquota)
2915 {
2916         dsl_dataset_set_qr_arg_t ddsqra;
2917
2918         ddsqra.ddsqra_name = dsname;
2919         ddsqra.ddsqra_source = source;
2920         ddsqra.ddsqra_value = refquota;
2921
2922         return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
2923             dsl_dataset_set_refquota_sync, &ddsqra, 0));
2924 }
2925
2926 static int
2927 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
2928 {
2929         dsl_dataset_set_qr_arg_t *ddsqra = arg;
2930         dsl_pool_t *dp = dmu_tx_pool(tx);
2931         dsl_dataset_t *ds;
2932         int error;
2933         uint64_t newval, unique;
2934
2935         if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
2936                 return (SET_ERROR(ENOTSUP));
2937
2938         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
2939         if (error != 0)
2940                 return (error);
2941
2942         if (dsl_dataset_is_snapshot(ds)) {
2943                 dsl_dataset_rele(ds, FTAG);
2944                 return (SET_ERROR(EINVAL));
2945         }
2946
2947         error = dsl_prop_predict(ds->ds_dir,
2948             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2949             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
2950         if (error != 0) {
2951                 dsl_dataset_rele(ds, FTAG);
2952                 return (error);
2953         }
2954
2955         /*
2956          * If we are doing the preliminary check in open context, the
2957          * space estimates may be inaccurate.
2958          */
2959         if (!dmu_tx_is_syncing(tx)) {
2960                 dsl_dataset_rele(ds, FTAG);
2961                 return (0);
2962         }
2963
2964         mutex_enter(&ds->ds_lock);
2965         if (!DS_UNIQUE_IS_ACCURATE(ds))
2966                 dsl_dataset_recalc_head_uniq(ds);
2967         unique = ds->ds_phys->ds_unique_bytes;
2968         mutex_exit(&ds->ds_lock);
2969
2970         if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
2971                 uint64_t delta = MAX(unique, newval) -
2972                     MAX(unique, ds->ds_reserved);
2973
2974                 if (delta >
2975                     dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
2976                     (ds->ds_quota > 0 && newval > ds->ds_quota)) {
2977                         dsl_dataset_rele(ds, FTAG);
2978                         return (SET_ERROR(ENOSPC));
2979                 }
2980         }
2981
2982         dsl_dataset_rele(ds, FTAG);
2983         return (0);
2984 }
2985
2986 void
2987 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
2988     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
2989 {
2990         uint64_t newval;
2991         uint64_t unique;
2992         int64_t delta;
2993
2994         dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2995             source, sizeof (value), 1, &value, tx);
2996
2997         VERIFY0(dsl_prop_get_int_ds(ds,
2998             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
2999
3000         dmu_buf_will_dirty(ds->ds_dbuf, tx);
3001         mutex_enter(&ds->ds_dir->dd_lock);
3002         mutex_enter(&ds->ds_lock);
3003         ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3004         unique = ds->ds_phys->ds_unique_bytes;
3005         delta = MAX(0, (int64_t)(newval - unique)) -
3006             MAX(0, (int64_t)(ds->ds_reserved - unique));
3007         ds->ds_reserved = newval;
3008         mutex_exit(&ds->ds_lock);
3009
3010         dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3011         mutex_exit(&ds->ds_dir->dd_lock);
3012 }
3013
3014 static void
3015 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
3016 {
3017         dsl_dataset_set_qr_arg_t *ddsqra = arg;
3018         dsl_pool_t *dp = dmu_tx_pool(tx);
3019         dsl_dataset_t *ds;
3020
3021         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3022         dsl_dataset_set_refreservation_sync_impl(ds,
3023             ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
3024         dsl_dataset_rele(ds, FTAG);
3025 }
3026
3027 int
3028 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
3029     uint64_t refreservation)
3030 {
3031         dsl_dataset_set_qr_arg_t ddsqra;
3032
3033         ddsqra.ddsqra_name = dsname;
3034         ddsqra.ddsqra_source = source;
3035         ddsqra.ddsqra_value = refreservation;
3036
3037         return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
3038             dsl_dataset_set_refreservation_sync, &ddsqra, 0));
3039 }
3040
3041 /*
3042  * Return (in *usedp) the amount of space written in new that is not
3043  * present in oldsnap.  New may be a snapshot or the head.  Old must be
3044  * a snapshot before new, in new's filesystem (or its origin).  If not then
3045  * fail and return EINVAL.
3046  *
3047  * The written space is calculated by considering two components:  First, we
3048  * ignore any freed space, and calculate the written as new's used space
3049  * minus old's used space.  Next, we add in the amount of space that was freed
3050  * between the two snapshots, thus reducing new's used space relative to old's.
3051  * Specifically, this is the space that was born before old->ds_creation_txg,
3052  * and freed before new (ie. on new's deadlist or a previous deadlist).
3053  *
3054  * space freed                         [---------------------]
3055  * snapshots                       ---O-------O--------O-------O------
3056  *                                         oldsnap            new
3057  */
3058 int
3059 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
3060     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3061 {
3062         int err = 0;
3063         uint64_t snapobj;
3064         dsl_pool_t *dp = new->ds_dir->dd_pool;
3065
3066         ASSERT(dsl_pool_config_held(dp));
3067
3068         *usedp = 0;
3069         *usedp += new->ds_phys->ds_referenced_bytes;
3070         *usedp -= oldsnap->ds_phys->ds_referenced_bytes;
3071
3072         *compp = 0;
3073         *compp += new->ds_phys->ds_compressed_bytes;
3074         *compp -= oldsnap->ds_phys->ds_compressed_bytes;
3075
3076         *uncompp = 0;
3077         *uncompp += new->ds_phys->ds_uncompressed_bytes;
3078         *uncompp -= oldsnap->ds_phys->ds_uncompressed_bytes;
3079
3080         snapobj = new->ds_object;
3081         while (snapobj != oldsnap->ds_object) {
3082                 dsl_dataset_t *snap;
3083                 uint64_t used, comp, uncomp;
3084
3085                 if (snapobj == new->ds_object) {
3086                         snap = new;
3087                 } else {
3088                         err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
3089                         if (err != 0)
3090                                 break;
3091                 }
3092
3093                 if (snap->ds_phys->ds_prev_snap_txg ==
3094                     oldsnap->ds_phys->ds_creation_txg) {
3095                         /*
3096                          * The blocks in the deadlist can not be born after
3097                          * ds_prev_snap_txg, so get the whole deadlist space,
3098                          * which is more efficient (especially for old-format
3099                          * deadlists).  Unfortunately the deadlist code
3100                          * doesn't have enough information to make this
3101                          * optimization itself.
3102                          */
3103                         dsl_deadlist_space(&snap->ds_deadlist,
3104                             &used, &comp, &uncomp);
3105                 } else {
3106                         dsl_deadlist_space_range(&snap->ds_deadlist,
3107                             0, oldsnap->ds_phys->ds_creation_txg,
3108                             &used, &comp, &uncomp);
3109                 }
3110                 *usedp += used;
3111                 *compp += comp;
3112                 *uncompp += uncomp;
3113
3114                 /*
3115                  * If we get to the beginning of the chain of snapshots
3116                  * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
3117                  * was not a snapshot of/before new.
3118                  */
3119                 snapobj = snap->ds_phys->ds_prev_snap_obj;
3120                 if (snap != new)
3121                         dsl_dataset_rele(snap, FTAG);
3122                 if (snapobj == 0) {
3123                         err = SET_ERROR(EINVAL);
3124                         break;
3125                 }
3126
3127         }
3128         return (err);
3129 }
3130
3131 /*
3132  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
3133  * lastsnap, and all snapshots in between are deleted.
3134  *
3135  * blocks that would be freed            [---------------------------]
3136  * snapshots                       ---O-------O--------O-------O--------O
3137  *                                        firstsnap        lastsnap
3138  *
3139  * This is the set of blocks that were born after the snap before firstsnap,
3140  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
3141  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
3142  * We calculate this by iterating over the relevant deadlists (from the snap
3143  * after lastsnap, backward to the snap after firstsnap), summing up the
3144  * space on the deadlist that was born after the snap before firstsnap.
3145  */
3146 int
3147 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
3148     dsl_dataset_t *lastsnap,
3149     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3150 {
3151         int err = 0;
3152         uint64_t snapobj;
3153         dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
3154
3155         ASSERT(dsl_dataset_is_snapshot(firstsnap));
3156         ASSERT(dsl_dataset_is_snapshot(lastsnap));
3157
3158         /*
3159          * Check that the snapshots are in the same dsl_dir, and firstsnap
3160          * is before lastsnap.
3161          */
3162         if (firstsnap->ds_dir != lastsnap->ds_dir ||
3163             firstsnap->ds_phys->ds_creation_txg >
3164             lastsnap->ds_phys->ds_creation_txg)
3165                 return (SET_ERROR(EINVAL));
3166
3167         *usedp = *compp = *uncompp = 0;
3168
3169         snapobj = lastsnap->ds_phys->ds_next_snap_obj;
3170         while (snapobj != firstsnap->ds_object) {
3171                 dsl_dataset_t *ds;
3172                 uint64_t used, comp, uncomp;
3173
3174                 err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
3175                 if (err != 0)
3176                         break;
3177
3178                 dsl_deadlist_space_range(&ds->ds_deadlist,
3179                     firstsnap->ds_phys->ds_prev_snap_txg, UINT64_MAX,
3180                     &used, &comp, &uncomp);
3181                 *usedp += used;
3182                 *compp += comp;
3183                 *uncompp += uncomp;
3184
3185                 snapobj = ds->ds_phys->ds_prev_snap_obj;
3186                 ASSERT3U(snapobj, !=, 0);
3187                 dsl_dataset_rele(ds, FTAG);
3188         }
3189         return (err);
3190 }
3191
3192 /*
3193  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
3194  * For example, they could both be snapshots of the same filesystem, and
3195  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
3196  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
3197  * filesystem.  Or 'earlier' could be the origin's origin.
3198  *
3199  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
3200  */
3201 boolean_t
3202 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
3203         uint64_t earlier_txg)
3204 {
3205         dsl_pool_t *dp = later->ds_dir->dd_pool;
3206         int error;
3207         boolean_t ret;
3208
3209         ASSERT(dsl_pool_config_held(dp));
3210         ASSERT(dsl_dataset_is_snapshot(earlier) || earlier_txg != 0);
3211
3212         if (earlier_txg == 0)
3213                 earlier_txg = earlier->ds_phys->ds_creation_txg;
3214
3215         if (dsl_dataset_is_snapshot(later) &&
3216             earlier_txg >= later->ds_phys->ds_creation_txg)
3217                 return (B_FALSE);
3218
3219         if (later->ds_dir == earlier->ds_dir)
3220                 return (B_TRUE);
3221         if (!dsl_dir_is_clone(later->ds_dir))
3222                 return (B_FALSE);
3223
3224         if (later->ds_dir->dd_phys->dd_origin_obj == earlier->ds_object)
3225                 return (B_TRUE);
3226         dsl_dataset_t *origin;
3227         error = dsl_dataset_hold_obj(dp,
3228             later->ds_dir->dd_phys->dd_origin_obj, FTAG, &origin);
3229         if (error != 0)
3230                 return (B_FALSE);
3231         ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
3232         dsl_dataset_rele(origin, FTAG);
3233         return (ret);
3234 }
3235
3236
3237 void
3238 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
3239 {
3240         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3241         dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
3242 }