]> granicus.if.org Git - zfs/blob - module/zfs/dsl_dataset.c
Fix for ARC sysctls ignored at runtime
[zfs] / module / 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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2014 RackTop Systems.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
29  * Copyright 2016, OmniTI Computer Consulting, Inc. All rights reserved.
30  * Copyright 2017 Nexenta Systems, Inc.
31  */
32
33 #include <sys/dmu_objset.h>
34 #include <sys/dsl_dataset.h>
35 #include <sys/dsl_dir.h>
36 #include <sys/dsl_prop.h>
37 #include <sys/dsl_synctask.h>
38 #include <sys/dmu_traverse.h>
39 #include <sys/dmu_impl.h>
40 #include <sys/dmu_tx.h>
41 #include <sys/arc.h>
42 #include <sys/zio.h>
43 #include <sys/zap.h>
44 #include <sys/zfeature.h>
45 #include <sys/unique.h>
46 #include <sys/zfs_context.h>
47 #include <sys/zfs_ioctl.h>
48 #include <sys/spa.h>
49 #include <sys/spa_impl.h>
50 #include <sys/vdev.h>
51 #include <sys/zfs_znode.h>
52 #include <sys/zfs_onexit.h>
53 #include <sys/zvol.h>
54 #include <sys/dsl_scan.h>
55 #include <sys/dsl_deadlist.h>
56 #include <sys/dsl_destroy.h>
57 #include <sys/dsl_userhold.h>
58 #include <sys/dsl_bookmark.h>
59 #include <sys/policy.h>
60 #include <sys/dmu_send.h>
61 #include <sys/dmu_recv.h>
62 #include <sys/zio_compress.h>
63 #include <zfs_fletcher.h>
64 #include <sys/zio_checksum.h>
65
66 /*
67  * The SPA supports block sizes up to 16MB.  However, very large blocks
68  * can have an impact on i/o latency (e.g. tying up a spinning disk for
69  * ~300ms), and also potentially on the memory allocator.  Therefore,
70  * we do not allow the recordsize to be set larger than zfs_max_recordsize
71  * (default 1MB).  Larger blocks can be created by changing this tunable,
72  * and pools with larger blocks can always be imported and used, regardless
73  * of this setting.
74  */
75 int zfs_max_recordsize = 1 * 1024 * 1024;
76 int zfs_allow_redacted_dataset_mount = 0;
77
78 #define SWITCH64(x, y) \
79         { \
80                 uint64_t __tmp = (x); \
81                 (x) = (y); \
82                 (y) = __tmp; \
83         }
84
85 #define DS_REF_MAX      (1ULL << 62)
86
87 extern inline dsl_dataset_phys_t *dsl_dataset_phys(dsl_dataset_t *ds);
88
89 static void dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds,
90     uint64_t obj, dmu_tx_t *tx);
91 static void dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds,
92     dmu_tx_t *tx);
93
94 static void unload_zfeature(dsl_dataset_t *ds, spa_feature_t f);
95
96 extern int spa_asize_inflation;
97
98 static zil_header_t zero_zil;
99
100 /*
101  * Figure out how much of this delta should be propagated to the dsl_dir
102  * layer.  If there's a refreservation, that space has already been
103  * partially accounted for in our ancestors.
104  */
105 static int64_t
106 parent_delta(dsl_dataset_t *ds, int64_t delta)
107 {
108         dsl_dataset_phys_t *ds_phys;
109         uint64_t old_bytes, new_bytes;
110
111         if (ds->ds_reserved == 0)
112                 return (delta);
113
114         ds_phys = dsl_dataset_phys(ds);
115         old_bytes = MAX(ds_phys->ds_unique_bytes, ds->ds_reserved);
116         new_bytes = MAX(ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
117
118         ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
119         return (new_bytes - old_bytes);
120 }
121
122 void
123 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
124 {
125         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
126         int used = bp_get_dsize_sync(spa, bp);
127         int compressed = BP_GET_PSIZE(bp);
128         int uncompressed = BP_GET_UCSIZE(bp);
129         int64_t delta;
130
131         dprintf_bp(bp, "ds=%p", ds);
132
133         ASSERT(dmu_tx_is_syncing(tx));
134         /* It could have been compressed away to nothing */
135         if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
136                 return;
137         ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
138         ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
139         if (ds == NULL) {
140                 dsl_pool_mos_diduse_space(tx->tx_pool,
141                     used, compressed, uncompressed);
142                 return;
143         }
144
145         ASSERT3U(bp->blk_birth, >, dsl_dataset_phys(ds)->ds_prev_snap_txg);
146         dmu_buf_will_dirty(ds->ds_dbuf, tx);
147         mutex_enter(&ds->ds_lock);
148         delta = parent_delta(ds, used);
149         dsl_dataset_phys(ds)->ds_referenced_bytes += used;
150         dsl_dataset_phys(ds)->ds_compressed_bytes += compressed;
151         dsl_dataset_phys(ds)->ds_uncompressed_bytes += uncompressed;
152         dsl_dataset_phys(ds)->ds_unique_bytes += used;
153
154         if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE) {
155                 ds->ds_feature_activation[SPA_FEATURE_LARGE_BLOCKS] =
156                     (void *)B_TRUE;
157         }
158
159         spa_feature_t f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
160         if (f != SPA_FEATURE_NONE) {
161                 ASSERT3S(spa_feature_table[f].fi_type, ==,
162                     ZFEATURE_TYPE_BOOLEAN);
163                 ds->ds_feature_activation[f] = (void *)B_TRUE;
164         }
165
166         /*
167          * Track block for livelist, but ignore embedded blocks because
168          * they do not need to be freed.
169          */
170         if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
171             bp->blk_birth > ds->ds_dir->dd_origin_txg &&
172             !(BP_IS_EMBEDDED(bp))) {
173                 ASSERT(dsl_dir_is_clone(ds->ds_dir));
174                 ASSERT(spa_feature_is_enabled(spa,
175                     SPA_FEATURE_LIVELIST));
176                 bplist_append(&ds->ds_dir->dd_pending_allocs, bp);
177         }
178
179         mutex_exit(&ds->ds_lock);
180         dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
181             compressed, uncompressed, tx);
182         dsl_dir_transfer_space(ds->ds_dir, used - delta,
183             DD_USED_REFRSRV, DD_USED_HEAD, tx);
184 }
185
186 /*
187  * Called when the specified segment has been remapped, and is thus no
188  * longer referenced in the head dataset.  The vdev must be indirect.
189  *
190  * If the segment is referenced by a snapshot, put it on the remap deadlist.
191  * Otherwise, add this segment to the obsolete spacemap.
192  */
193 void
194 dsl_dataset_block_remapped(dsl_dataset_t *ds, uint64_t vdev, uint64_t offset,
195     uint64_t size, uint64_t birth, dmu_tx_t *tx)
196 {
197         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
198
199         ASSERT(dmu_tx_is_syncing(tx));
200         ASSERT(birth <= tx->tx_txg);
201         ASSERT(!ds->ds_is_snapshot);
202
203         if (birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
204                 spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
205         } else {
206                 blkptr_t fakebp;
207                 dva_t *dva = &fakebp.blk_dva[0];
208
209                 ASSERT(ds != NULL);
210
211                 mutex_enter(&ds->ds_remap_deadlist_lock);
212                 if (!dsl_dataset_remap_deadlist_exists(ds)) {
213                         dsl_dataset_create_remap_deadlist(ds, tx);
214                 }
215                 mutex_exit(&ds->ds_remap_deadlist_lock);
216
217                 BP_ZERO(&fakebp);
218                 fakebp.blk_birth = birth;
219                 DVA_SET_VDEV(dva, vdev);
220                 DVA_SET_OFFSET(dva, offset);
221                 DVA_SET_ASIZE(dva, size);
222                 dsl_deadlist_insert(&ds->ds_remap_deadlist, &fakebp, B_FALSE,
223                     tx);
224         }
225 }
226
227 int
228 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
229     boolean_t async)
230 {
231         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
232
233         int used = bp_get_dsize_sync(spa, bp);
234         int compressed = BP_GET_PSIZE(bp);
235         int uncompressed = BP_GET_UCSIZE(bp);
236
237         if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
238                 return (0);
239
240         ASSERT(dmu_tx_is_syncing(tx));
241         ASSERT(bp->blk_birth <= tx->tx_txg);
242
243         if (ds == NULL) {
244                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
245                 dsl_pool_mos_diduse_space(tx->tx_pool,
246                     -used, -compressed, -uncompressed);
247                 return (used);
248         }
249         ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
250
251         ASSERT(!ds->ds_is_snapshot);
252         dmu_buf_will_dirty(ds->ds_dbuf, tx);
253
254         /*
255          * Track block for livelist, but ignore embedded blocks because
256          * they do not need to be freed.
257          */
258         if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
259             bp->blk_birth > ds->ds_dir->dd_origin_txg &&
260             !(BP_IS_EMBEDDED(bp))) {
261                 ASSERT(dsl_dir_is_clone(ds->ds_dir));
262                 ASSERT(spa_feature_is_enabled(spa,
263                     SPA_FEATURE_LIVELIST));
264                 bplist_append(&ds->ds_dir->dd_pending_frees, bp);
265         }
266
267         if (bp->blk_birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
268                 int64_t delta;
269
270                 dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
271                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
272
273                 mutex_enter(&ds->ds_lock);
274                 ASSERT(dsl_dataset_phys(ds)->ds_unique_bytes >= used ||
275                     !DS_UNIQUE_IS_ACCURATE(ds));
276                 delta = parent_delta(ds, -used);
277                 dsl_dataset_phys(ds)->ds_unique_bytes -= used;
278                 mutex_exit(&ds->ds_lock);
279                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
280                     delta, -compressed, -uncompressed, tx);
281                 dsl_dir_transfer_space(ds->ds_dir, -used - delta,
282                     DD_USED_REFRSRV, DD_USED_HEAD, tx);
283         } else {
284                 dprintf_bp(bp, "putting on dead list: %s", "");
285                 if (async) {
286                         /*
287                          * We are here as part of zio's write done callback,
288                          * which means we're a zio interrupt thread.  We can't
289                          * call dsl_deadlist_insert() now because it may block
290                          * waiting for I/O.  Instead, put bp on the deferred
291                          * queue and let dsl_pool_sync() finish the job.
292                          */
293                         bplist_append(&ds->ds_pending_deadlist, bp);
294                 } else {
295                         dsl_deadlist_insert(&ds->ds_deadlist, bp, B_FALSE, tx);
296                 }
297                 ASSERT3U(ds->ds_prev->ds_object, ==,
298                     dsl_dataset_phys(ds)->ds_prev_snap_obj);
299                 ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_num_children > 0);
300                 /* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
301                 if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
302                     ds->ds_object && bp->blk_birth >
303                     dsl_dataset_phys(ds->ds_prev)->ds_prev_snap_txg) {
304                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
305                         mutex_enter(&ds->ds_prev->ds_lock);
306                         dsl_dataset_phys(ds->ds_prev)->ds_unique_bytes += used;
307                         mutex_exit(&ds->ds_prev->ds_lock);
308                 }
309                 if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
310                         dsl_dir_transfer_space(ds->ds_dir, used,
311                             DD_USED_HEAD, DD_USED_SNAP, tx);
312                 }
313         }
314
315         dsl_bookmark_block_killed(ds, bp, tx);
316
317         mutex_enter(&ds->ds_lock);
318         ASSERT3U(dsl_dataset_phys(ds)->ds_referenced_bytes, >=, used);
319         dsl_dataset_phys(ds)->ds_referenced_bytes -= used;
320         ASSERT3U(dsl_dataset_phys(ds)->ds_compressed_bytes, >=, compressed);
321         dsl_dataset_phys(ds)->ds_compressed_bytes -= compressed;
322         ASSERT3U(dsl_dataset_phys(ds)->ds_uncompressed_bytes, >=, uncompressed);
323         dsl_dataset_phys(ds)->ds_uncompressed_bytes -= uncompressed;
324         mutex_exit(&ds->ds_lock);
325
326         return (used);
327 }
328
329 struct feature_type_uint64_array_arg {
330         uint64_t length;
331         uint64_t *array;
332 };
333
334 static void
335 unload_zfeature(dsl_dataset_t *ds, spa_feature_t f)
336 {
337         switch (spa_feature_table[f].fi_type) {
338         case ZFEATURE_TYPE_BOOLEAN:
339                 break;
340         case ZFEATURE_TYPE_UINT64_ARRAY:
341         {
342                 struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
343                 kmem_free(ftuaa->array, ftuaa->length * sizeof (uint64_t));
344                 kmem_free(ftuaa, sizeof (*ftuaa));
345                 break;
346         }
347         default:
348                 panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
349         }
350 }
351
352 static int
353 load_zfeature(objset_t *mos, dsl_dataset_t *ds, spa_feature_t f)
354 {
355         int err = 0;
356         switch (spa_feature_table[f].fi_type) {
357         case ZFEATURE_TYPE_BOOLEAN:
358                 err = zap_contains(mos, ds->ds_object,
359                     spa_feature_table[f].fi_guid);
360                 if (err == 0) {
361                         ds->ds_feature[f] = (void *)B_TRUE;
362                 } else {
363                         ASSERT3U(err, ==, ENOENT);
364                         err = 0;
365                 }
366                 break;
367         case ZFEATURE_TYPE_UINT64_ARRAY:
368         {
369                 uint64_t int_size, num_int;
370                 uint64_t *data;
371                 err = zap_length(mos, ds->ds_object,
372                     spa_feature_table[f].fi_guid, &int_size, &num_int);
373                 if (err != 0) {
374                         ASSERT3U(err, ==, ENOENT);
375                         err = 0;
376                         break;
377                 }
378                 ASSERT3U(int_size, ==, sizeof (uint64_t));
379                 data = kmem_alloc(int_size * num_int, KM_SLEEP);
380                 VERIFY0(zap_lookup(mos, ds->ds_object,
381                     spa_feature_table[f].fi_guid, int_size, num_int, data));
382                 struct feature_type_uint64_array_arg *ftuaa =
383                     kmem_alloc(sizeof (*ftuaa), KM_SLEEP);
384                 ftuaa->length = num_int;
385                 ftuaa->array = data;
386                 ds->ds_feature[f] = ftuaa;
387                 break;
388         }
389         default:
390                 panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
391         }
392         return (err);
393 }
394
395 /*
396  * We have to release the fsid synchronously or we risk that a subsequent
397  * mount of the same dataset will fail to unique_insert the fsid.  This
398  * failure would manifest itself as the fsid of this dataset changing
399  * between mounts which makes NFS clients quite unhappy.
400  */
401 static void
402 dsl_dataset_evict_sync(void *dbu)
403 {
404         dsl_dataset_t *ds = dbu;
405
406         ASSERT(ds->ds_owner == NULL);
407
408         unique_remove(ds->ds_fsid_guid);
409 }
410
411 static void
412 dsl_dataset_evict_async(void *dbu)
413 {
414         dsl_dataset_t *ds = dbu;
415
416         ASSERT(ds->ds_owner == NULL);
417
418         ds->ds_dbuf = NULL;
419
420         if (ds->ds_objset != NULL)
421                 dmu_objset_evict(ds->ds_objset);
422
423         if (ds->ds_prev) {
424                 dsl_dataset_rele(ds->ds_prev, ds);
425                 ds->ds_prev = NULL;
426         }
427
428         dsl_bookmark_fini_ds(ds);
429
430         bplist_destroy(&ds->ds_pending_deadlist);
431         if (dsl_deadlist_is_open(&ds->ds_deadlist))
432                 dsl_deadlist_close(&ds->ds_deadlist);
433         if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
434                 dsl_deadlist_close(&ds->ds_remap_deadlist);
435         if (ds->ds_dir)
436                 dsl_dir_async_rele(ds->ds_dir, ds);
437
438         ASSERT(!list_link_active(&ds->ds_synced_link));
439
440         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
441                 if (dsl_dataset_feature_is_active(ds, f))
442                         unload_zfeature(ds, f);
443         }
444
445         list_destroy(&ds->ds_prop_cbs);
446         mutex_destroy(&ds->ds_lock);
447         mutex_destroy(&ds->ds_opening_lock);
448         mutex_destroy(&ds->ds_sendstream_lock);
449         mutex_destroy(&ds->ds_remap_deadlist_lock);
450         zfs_refcount_destroy(&ds->ds_longholds);
451         rrw_destroy(&ds->ds_bp_rwlock);
452
453         kmem_free(ds, sizeof (dsl_dataset_t));
454 }
455
456 int
457 dsl_dataset_get_snapname(dsl_dataset_t *ds)
458 {
459         dsl_dataset_phys_t *headphys;
460         int err;
461         dmu_buf_t *headdbuf;
462         dsl_pool_t *dp = ds->ds_dir->dd_pool;
463         objset_t *mos = dp->dp_meta_objset;
464
465         if (ds->ds_snapname[0])
466                 return (0);
467         if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0)
468                 return (0);
469
470         err = dmu_bonus_hold(mos, dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj,
471             FTAG, &headdbuf);
472         if (err != 0)
473                 return (err);
474         headphys = headdbuf->db_data;
475         err = zap_value_search(dp->dp_meta_objset,
476             headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
477         if (err != 0 && zfs_recover == B_TRUE) {
478                 err = 0;
479                 (void) snprintf(ds->ds_snapname, sizeof (ds->ds_snapname),
480                     "SNAPOBJ=%llu-ERR=%d",
481                     (unsigned long long)ds->ds_object, err);
482         }
483         dmu_buf_rele(headdbuf, FTAG);
484         return (err);
485 }
486
487 int
488 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
489 {
490         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
491         uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
492         matchtype_t mt = 0;
493         int err;
494
495         if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
496                 mt = MT_NORMALIZE;
497
498         err = zap_lookup_norm(mos, snapobj, name, 8, 1,
499             value, mt, NULL, 0, NULL);
500         if (err == ENOTSUP && (mt & MT_NORMALIZE))
501                 err = zap_lookup(mos, snapobj, name, 8, 1, value);
502         return (err);
503 }
504
505 int
506 dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
507     boolean_t adj_cnt)
508 {
509         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
510         uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
511         matchtype_t mt = 0;
512         int err;
513
514         dsl_dir_snap_cmtime_update(ds->ds_dir);
515
516         if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
517                 mt = MT_NORMALIZE;
518
519         err = zap_remove_norm(mos, snapobj, name, mt, tx);
520         if (err == ENOTSUP && (mt & MT_NORMALIZE))
521                 err = zap_remove(mos, snapobj, name, tx);
522
523         if (err == 0 && adj_cnt)
524                 dsl_fs_ss_count_adjust(ds->ds_dir, -1,
525                     DD_FIELD_SNAPSHOT_COUNT, tx);
526
527         return (err);
528 }
529
530 boolean_t
531 dsl_dataset_try_add_ref(dsl_pool_t *dp, dsl_dataset_t *ds, void *tag)
532 {
533         dmu_buf_t *dbuf = ds->ds_dbuf;
534         boolean_t result = B_FALSE;
535
536         if (dbuf != NULL && dmu_buf_try_add_ref(dbuf, dp->dp_meta_objset,
537             ds->ds_object, DMU_BONUS_BLKID, tag)) {
538
539                 if (ds == dmu_buf_get_user(dbuf))
540                         result = B_TRUE;
541                 else
542                         dmu_buf_rele(dbuf, tag);
543         }
544
545         return (result);
546 }
547
548 int
549 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
550     dsl_dataset_t **dsp)
551 {
552         objset_t *mos = dp->dp_meta_objset;
553         dmu_buf_t *dbuf;
554         dsl_dataset_t *ds;
555         int err;
556         dmu_object_info_t doi;
557
558         ASSERT(dsl_pool_config_held(dp));
559
560         err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
561         if (err != 0)
562                 return (err);
563
564         /* Make sure dsobj has the correct object type. */
565         dmu_object_info_from_db(dbuf, &doi);
566         if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
567                 dmu_buf_rele(dbuf, tag);
568                 return (SET_ERROR(EINVAL));
569         }
570
571         ds = dmu_buf_get_user(dbuf);
572         if (ds == NULL) {
573                 dsl_dataset_t *winner = NULL;
574
575                 ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
576                 ds->ds_dbuf = dbuf;
577                 ds->ds_object = dsobj;
578                 ds->ds_is_snapshot = dsl_dataset_phys(ds)->ds_num_children != 0;
579                 list_link_init(&ds->ds_synced_link);
580
581                 err = dsl_dir_hold_obj(dp, dsl_dataset_phys(ds)->ds_dir_obj,
582                     NULL, ds, &ds->ds_dir);
583                 if (err != 0) {
584                         kmem_free(ds, sizeof (dsl_dataset_t));
585                         dmu_buf_rele(dbuf, tag);
586                         return (err);
587                 }
588
589                 mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
590                 mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
591                 mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
592                 mutex_init(&ds->ds_remap_deadlist_lock,
593                     NULL, MUTEX_DEFAULT, NULL);
594                 rrw_init(&ds->ds_bp_rwlock, B_FALSE);
595                 zfs_refcount_create(&ds->ds_longholds);
596
597                 bplist_create(&ds->ds_pending_deadlist);
598
599                 list_create(&ds->ds_sendstreams, sizeof (dmu_sendstatus_t),
600                     offsetof(dmu_sendstatus_t, dss_link));
601
602                 list_create(&ds->ds_prop_cbs, sizeof (dsl_prop_cb_record_t),
603                     offsetof(dsl_prop_cb_record_t, cbr_ds_node));
604
605                 if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
606                         spa_feature_t f;
607
608                         for (f = 0; f < SPA_FEATURES; f++) {
609                                 if (!(spa_feature_table[f].fi_flags &
610                                     ZFEATURE_FLAG_PER_DATASET))
611                                         continue;
612                                 err = load_zfeature(mos, ds, f);
613                         }
614                 }
615
616                 if (!ds->ds_is_snapshot) {
617                         ds->ds_snapname[0] = '\0';
618                         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
619                                 err = dsl_dataset_hold_obj(dp,
620                                     dsl_dataset_phys(ds)->ds_prev_snap_obj,
621                                     ds, &ds->ds_prev);
622                         }
623                         err = dsl_bookmark_init_ds(ds);
624                 } else {
625                         if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
626                                 err = dsl_dataset_get_snapname(ds);
627                         if (err == 0 &&
628                             dsl_dataset_phys(ds)->ds_userrefs_obj != 0) {
629                                 err = zap_count(
630                                     ds->ds_dir->dd_pool->dp_meta_objset,
631                                     dsl_dataset_phys(ds)->ds_userrefs_obj,
632                                     &ds->ds_userrefs);
633                         }
634                 }
635
636                 if (err == 0 && !ds->ds_is_snapshot) {
637                         err = dsl_prop_get_int_ds(ds,
638                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
639                             &ds->ds_reserved);
640                         if (err == 0) {
641                                 err = dsl_prop_get_int_ds(ds,
642                                     zfs_prop_to_name(ZFS_PROP_REFQUOTA),
643                                     &ds->ds_quota);
644                         }
645                 } else {
646                         ds->ds_reserved = ds->ds_quota = 0;
647                 }
648
649                 if (err == 0 && ds->ds_dir->dd_crypto_obj != 0 &&
650                     ds->ds_is_snapshot &&
651                     zap_contains(mos, dsobj, DS_FIELD_IVSET_GUID) != 0) {
652                         dp->dp_spa->spa_errata =
653                             ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
654                 }
655
656                 dsl_deadlist_open(&ds->ds_deadlist,
657                     mos, dsl_dataset_phys(ds)->ds_deadlist_obj);
658                 uint64_t remap_deadlist_obj =
659                     dsl_dataset_get_remap_deadlist_object(ds);
660                 if (remap_deadlist_obj != 0) {
661                         dsl_deadlist_open(&ds->ds_remap_deadlist, mos,
662                             remap_deadlist_obj);
663                 }
664
665                 dmu_buf_init_user(&ds->ds_dbu, dsl_dataset_evict_sync,
666                     dsl_dataset_evict_async, &ds->ds_dbuf);
667                 if (err == 0)
668                         winner = dmu_buf_set_user_ie(dbuf, &ds->ds_dbu);
669
670                 if (err != 0 || winner != NULL) {
671                         bplist_destroy(&ds->ds_pending_deadlist);
672                         dsl_deadlist_close(&ds->ds_deadlist);
673                         if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
674                                 dsl_deadlist_close(&ds->ds_remap_deadlist);
675                         dsl_bookmark_fini_ds(ds);
676                         if (ds->ds_prev)
677                                 dsl_dataset_rele(ds->ds_prev, ds);
678                         dsl_dir_rele(ds->ds_dir, ds);
679                         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
680                                 if (dsl_dataset_feature_is_active(ds, f))
681                                         unload_zfeature(ds, f);
682                         }
683
684                         list_destroy(&ds->ds_prop_cbs);
685                         list_destroy(&ds->ds_sendstreams);
686                         mutex_destroy(&ds->ds_lock);
687                         mutex_destroy(&ds->ds_opening_lock);
688                         mutex_destroy(&ds->ds_sendstream_lock);
689                         mutex_destroy(&ds->ds_remap_deadlist_lock);
690                         zfs_refcount_destroy(&ds->ds_longholds);
691                         rrw_destroy(&ds->ds_bp_rwlock);
692                         kmem_free(ds, sizeof (dsl_dataset_t));
693                         if (err != 0) {
694                                 dmu_buf_rele(dbuf, tag);
695                                 return (err);
696                         }
697                         ds = winner;
698                 } else {
699                         ds->ds_fsid_guid =
700                             unique_insert(dsl_dataset_phys(ds)->ds_fsid_guid);
701                         if (ds->ds_fsid_guid !=
702                             dsl_dataset_phys(ds)->ds_fsid_guid) {
703                                 zfs_dbgmsg("ds_fsid_guid changed from "
704                                     "%llx to %llx for pool %s dataset id %llu",
705                                     (long long)
706                                     dsl_dataset_phys(ds)->ds_fsid_guid,
707                                     (long long)ds->ds_fsid_guid,
708                                     spa_name(dp->dp_spa),
709                                     dsobj);
710                         }
711                 }
712         }
713
714         ASSERT3P(ds->ds_dbuf, ==, dbuf);
715         ASSERT3P(dsl_dataset_phys(ds), ==, dbuf->db_data);
716         ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0 ||
717             spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
718             dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
719         *dsp = ds;
720
721         return (0);
722 }
723
724 int
725 dsl_dataset_create_key_mapping(dsl_dataset_t *ds)
726 {
727         dsl_dir_t *dd = ds->ds_dir;
728
729         if (dd->dd_crypto_obj == 0)
730                 return (0);
731
732         return (spa_keystore_create_mapping(dd->dd_pool->dp_spa,
733             ds, ds, &ds->ds_key_mapping));
734 }
735
736 int
737 dsl_dataset_hold_obj_flags(dsl_pool_t *dp, uint64_t dsobj,
738     ds_hold_flags_t flags, void *tag, dsl_dataset_t **dsp)
739 {
740         int err;
741
742         err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
743         if (err != 0)
744                 return (err);
745
746         ASSERT3P(*dsp, !=, NULL);
747
748         if (flags & DS_HOLD_FLAG_DECRYPT) {
749                 err = dsl_dataset_create_key_mapping(*dsp);
750                 if (err != 0)
751                         dsl_dataset_rele(*dsp, tag);
752         }
753
754         return (err);
755 }
756
757 int
758 dsl_dataset_hold_flags(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
759     void *tag, dsl_dataset_t **dsp)
760 {
761         dsl_dir_t *dd;
762         const char *snapname;
763         uint64_t obj;
764         int err = 0;
765         dsl_dataset_t *ds;
766
767         err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
768         if (err != 0)
769                 return (err);
770
771         ASSERT(dsl_pool_config_held(dp));
772         obj = dsl_dir_phys(dd)->dd_head_dataset_obj;
773         if (obj != 0)
774                 err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag, &ds);
775         else
776                 err = SET_ERROR(ENOENT);
777
778         /* we may be looking for a snapshot */
779         if (err == 0 && snapname != NULL) {
780                 dsl_dataset_t *snap_ds;
781
782                 if (*snapname++ != '@') {
783                         dsl_dataset_rele_flags(ds, flags, tag);
784                         dsl_dir_rele(dd, FTAG);
785                         return (SET_ERROR(ENOENT));
786                 }
787
788                 dprintf("looking for snapshot '%s'\n", snapname);
789                 err = dsl_dataset_snap_lookup(ds, snapname, &obj);
790                 if (err == 0) {
791                         err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag,
792                             &snap_ds);
793                 }
794                 dsl_dataset_rele_flags(ds, flags, tag);
795
796                 if (err == 0) {
797                         mutex_enter(&snap_ds->ds_lock);
798                         if (snap_ds->ds_snapname[0] == 0)
799                                 (void) strlcpy(snap_ds->ds_snapname, snapname,
800                                     sizeof (snap_ds->ds_snapname));
801                         mutex_exit(&snap_ds->ds_lock);
802                         ds = snap_ds;
803                 }
804         }
805         if (err == 0)
806                 *dsp = ds;
807         dsl_dir_rele(dd, FTAG);
808         return (err);
809 }
810
811 int
812 dsl_dataset_hold(dsl_pool_t *dp, const char *name, void *tag,
813     dsl_dataset_t **dsp)
814 {
815         return (dsl_dataset_hold_flags(dp, name, 0, tag, dsp));
816 }
817
818 static int
819 dsl_dataset_own_obj_impl(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
820     void *tag, boolean_t override, dsl_dataset_t **dsp)
821 {
822         int err = dsl_dataset_hold_obj_flags(dp, dsobj, flags, tag, dsp);
823         if (err != 0)
824                 return (err);
825         if (!dsl_dataset_tryown(*dsp, tag, override)) {
826                 dsl_dataset_rele_flags(*dsp, flags, tag);
827                 *dsp = NULL;
828                 return (SET_ERROR(EBUSY));
829         }
830         return (0);
831 }
832
833
834 int
835 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
836     void *tag, dsl_dataset_t **dsp)
837 {
838         return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_FALSE, dsp));
839 }
840
841 int
842 dsl_dataset_own_obj_force(dsl_pool_t *dp, uint64_t dsobj,
843     ds_hold_flags_t flags, void *tag, dsl_dataset_t **dsp)
844 {
845         return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_TRUE, dsp));
846 }
847
848 static int
849 dsl_dataset_own_impl(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
850     void *tag, boolean_t override, dsl_dataset_t **dsp)
851 {
852         int err = dsl_dataset_hold_flags(dp, name, flags, tag, dsp);
853         if (err != 0)
854                 return (err);
855         if (!dsl_dataset_tryown(*dsp, tag, override)) {
856                 dsl_dataset_rele_flags(*dsp, flags, tag);
857                 return (SET_ERROR(EBUSY));
858         }
859         return (0);
860 }
861
862 int
863 dsl_dataset_own_force(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
864     void *tag, dsl_dataset_t **dsp)
865 {
866         return (dsl_dataset_own_impl(dp, name, flags, tag, B_TRUE, dsp));
867 }
868
869 int
870 dsl_dataset_own(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
871     void *tag, dsl_dataset_t **dsp)
872 {
873         return (dsl_dataset_own_impl(dp, name, flags, tag, B_FALSE, dsp));
874 }
875
876 /*
877  * See the comment above dsl_pool_hold() for details.  In summary, a long
878  * hold is used to prevent destruction of a dataset while the pool hold
879  * is dropped, allowing other concurrent operations (e.g. spa_sync()).
880  *
881  * The dataset and pool must be held when this function is called.  After it
882  * is called, the pool hold may be released while the dataset is still held
883  * and accessed.
884  */
885 void
886 dsl_dataset_long_hold(dsl_dataset_t *ds, void *tag)
887 {
888         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
889         (void) zfs_refcount_add(&ds->ds_longholds, tag);
890 }
891
892 void
893 dsl_dataset_long_rele(dsl_dataset_t *ds, void *tag)
894 {
895         (void) zfs_refcount_remove(&ds->ds_longholds, tag);
896 }
897
898 /* Return B_TRUE if there are any long holds on this dataset. */
899 boolean_t
900 dsl_dataset_long_held(dsl_dataset_t *ds)
901 {
902         return (!zfs_refcount_is_zero(&ds->ds_longholds));
903 }
904
905 void
906 dsl_dataset_name(dsl_dataset_t *ds, char *name)
907 {
908         if (ds == NULL) {
909                 (void) strcpy(name, "mos");
910         } else {
911                 dsl_dir_name(ds->ds_dir, name);
912                 VERIFY0(dsl_dataset_get_snapname(ds));
913                 if (ds->ds_snapname[0]) {
914                         VERIFY3U(strlcat(name, "@", ZFS_MAX_DATASET_NAME_LEN),
915                             <, ZFS_MAX_DATASET_NAME_LEN);
916                         /*
917                          * We use a "recursive" mutex so that we
918                          * can call dprintf_ds() with ds_lock held.
919                          */
920                         if (!MUTEX_HELD(&ds->ds_lock)) {
921                                 mutex_enter(&ds->ds_lock);
922                                 VERIFY3U(strlcat(name, ds->ds_snapname,
923                                     ZFS_MAX_DATASET_NAME_LEN), <,
924                                     ZFS_MAX_DATASET_NAME_LEN);
925                                 mutex_exit(&ds->ds_lock);
926                         } else {
927                                 VERIFY3U(strlcat(name, ds->ds_snapname,
928                                     ZFS_MAX_DATASET_NAME_LEN), <,
929                                     ZFS_MAX_DATASET_NAME_LEN);
930                         }
931                 }
932         }
933 }
934
935 int
936 dsl_dataset_namelen(dsl_dataset_t *ds)
937 {
938         VERIFY0(dsl_dataset_get_snapname(ds));
939         mutex_enter(&ds->ds_lock);
940         int len = strlen(ds->ds_snapname);
941         mutex_exit(&ds->ds_lock);
942         /* add '@' if ds is a snap */
943         if (len > 0)
944                 len++;
945         len += dsl_dir_namelen(ds->ds_dir);
946         return (len);
947 }
948
949 void
950 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
951 {
952         dmu_buf_rele(ds->ds_dbuf, tag);
953 }
954
955 void
956 dsl_dataset_remove_key_mapping(dsl_dataset_t *ds)
957 {
958         dsl_dir_t *dd = ds->ds_dir;
959
960         if (dd == NULL || dd->dd_crypto_obj == 0)
961                 return;
962
963         (void) spa_keystore_remove_mapping(dd->dd_pool->dp_spa,
964             ds->ds_object, ds);
965 }
966
967 void
968 dsl_dataset_rele_flags(dsl_dataset_t *ds, ds_hold_flags_t flags, void *tag)
969 {
970         if (flags & DS_HOLD_FLAG_DECRYPT)
971                 dsl_dataset_remove_key_mapping(ds);
972
973         dsl_dataset_rele(ds, tag);
974 }
975
976 void
977 dsl_dataset_disown(dsl_dataset_t *ds, ds_hold_flags_t flags, void *tag)
978 {
979         ASSERT3P(ds->ds_owner, ==, tag);
980         ASSERT(ds->ds_dbuf != NULL);
981
982         mutex_enter(&ds->ds_lock);
983         ds->ds_owner = NULL;
984         mutex_exit(&ds->ds_lock);
985         dsl_dataset_long_rele(ds, tag);
986         dsl_dataset_rele_flags(ds, flags, tag);
987 }
988
989 boolean_t
990 dsl_dataset_tryown(dsl_dataset_t *ds, void *tag, boolean_t override)
991 {
992         boolean_t gotit = FALSE;
993
994         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
995         mutex_enter(&ds->ds_lock);
996         if (ds->ds_owner == NULL && (override || !(DS_IS_INCONSISTENT(ds) ||
997             (dsl_dataset_feature_is_active(ds,
998             SPA_FEATURE_REDACTED_DATASETS) &&
999             !zfs_allow_redacted_dataset_mount)))) {
1000                 ds->ds_owner = tag;
1001                 dsl_dataset_long_hold(ds, tag);
1002                 gotit = TRUE;
1003         }
1004         mutex_exit(&ds->ds_lock);
1005         return (gotit);
1006 }
1007
1008 boolean_t
1009 dsl_dataset_has_owner(dsl_dataset_t *ds)
1010 {
1011         boolean_t rv;
1012         mutex_enter(&ds->ds_lock);
1013         rv = (ds->ds_owner != NULL);
1014         mutex_exit(&ds->ds_lock);
1015         return (rv);
1016 }
1017
1018 static boolean_t
1019 zfeature_active(spa_feature_t f, void *arg)
1020 {
1021         switch (spa_feature_table[f].fi_type) {
1022         case ZFEATURE_TYPE_BOOLEAN: {
1023                 boolean_t val = (boolean_t)arg;
1024                 ASSERT(val == B_FALSE || val == B_TRUE);
1025                 return (val);
1026         }
1027         case ZFEATURE_TYPE_UINT64_ARRAY:
1028                 /*
1029                  * In this case, arg is a uint64_t array.  The feature is active
1030                  * if the array is non-null.
1031                  */
1032                 return (arg != NULL);
1033         default:
1034                 panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1035                 return (B_FALSE);
1036         }
1037 }
1038
1039 boolean_t
1040 dsl_dataset_feature_is_active(dsl_dataset_t *ds, spa_feature_t f)
1041 {
1042         return (zfeature_active(f, ds->ds_feature[f]));
1043 }
1044
1045 /*
1046  * The buffers passed out by this function are references to internal buffers;
1047  * they should not be freed by callers of this function, and they should not be
1048  * used after the dataset has been released.
1049  */
1050 boolean_t
1051 dsl_dataset_get_uint64_array_feature(dsl_dataset_t *ds, spa_feature_t f,
1052     uint64_t *outlength, uint64_t **outp)
1053 {
1054         VERIFY(spa_feature_table[f].fi_type & ZFEATURE_TYPE_UINT64_ARRAY);
1055         if (!dsl_dataset_feature_is_active(ds, f)) {
1056                 return (B_FALSE);
1057         }
1058         struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
1059         *outp = ftuaa->array;
1060         *outlength = ftuaa->length;
1061         return (B_TRUE);
1062 }
1063
1064 void
1065 dsl_dataset_activate_feature(uint64_t dsobj, spa_feature_t f, void *arg,
1066     dmu_tx_t *tx)
1067 {
1068         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1069         objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1070         uint64_t zero = 0;
1071
1072         VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1073
1074         spa_feature_incr(spa, f, tx);
1075         dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1076
1077         switch (spa_feature_table[f].fi_type) {
1078         case ZFEATURE_TYPE_BOOLEAN:
1079                 ASSERT3S((boolean_t)arg, ==, B_TRUE);
1080                 VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1081                     sizeof (zero), 1, &zero, tx));
1082                 break;
1083         case ZFEATURE_TYPE_UINT64_ARRAY:
1084         {
1085                 struct feature_type_uint64_array_arg *ftuaa = arg;
1086                 VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1087                     sizeof (uint64_t), ftuaa->length, ftuaa->array, tx));
1088                 break;
1089         }
1090         default:
1091                 panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1092         }
1093 }
1094
1095 void
1096 dsl_dataset_deactivate_feature_impl(dsl_dataset_t *ds, spa_feature_t f,
1097     dmu_tx_t *tx)
1098 {
1099         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1100         objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1101         uint64_t dsobj = ds->ds_object;
1102
1103         VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1104
1105         VERIFY0(zap_remove(mos, dsobj, spa_feature_table[f].fi_guid, tx));
1106         spa_feature_decr(spa, f, tx);
1107         ds->ds_feature[f] = NULL;
1108 }
1109
1110 void
1111 dsl_dataset_deactivate_feature(dsl_dataset_t *ds, spa_feature_t f, dmu_tx_t *tx)
1112 {
1113         unload_zfeature(ds, f);
1114         dsl_dataset_deactivate_feature_impl(ds, f, tx);
1115 }
1116
1117 uint64_t
1118 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
1119     dsl_crypto_params_t *dcp, uint64_t flags, dmu_tx_t *tx)
1120 {
1121         dsl_pool_t *dp = dd->dd_pool;
1122         dmu_buf_t *dbuf;
1123         dsl_dataset_phys_t *dsphys;
1124         uint64_t dsobj;
1125         objset_t *mos = dp->dp_meta_objset;
1126
1127         if (origin == NULL)
1128                 origin = dp->dp_origin_snap;
1129
1130         ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
1131         ASSERT(origin == NULL || dsl_dataset_phys(origin)->ds_num_children > 0);
1132         ASSERT(dmu_tx_is_syncing(tx));
1133         ASSERT(dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
1134
1135         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1136             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1137         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1138         dmu_buf_will_dirty(dbuf, tx);
1139         dsphys = dbuf->db_data;
1140         bzero(dsphys, sizeof (dsl_dataset_phys_t));
1141         dsphys->ds_dir_obj = dd->dd_object;
1142         dsphys->ds_flags = flags;
1143         dsphys->ds_fsid_guid = unique_create();
1144         (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1145             sizeof (dsphys->ds_guid));
1146         dsphys->ds_snapnames_zapobj =
1147             zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
1148             DMU_OT_NONE, 0, tx);
1149         dsphys->ds_creation_time = gethrestime_sec();
1150         dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
1151
1152         if (origin == NULL) {
1153                 dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
1154         } else {
1155                 dsl_dataset_t *ohds; /* head of the origin snapshot */
1156
1157                 dsphys->ds_prev_snap_obj = origin->ds_object;
1158                 dsphys->ds_prev_snap_txg =
1159                     dsl_dataset_phys(origin)->ds_creation_txg;
1160                 dsphys->ds_referenced_bytes =
1161                     dsl_dataset_phys(origin)->ds_referenced_bytes;
1162                 dsphys->ds_compressed_bytes =
1163                     dsl_dataset_phys(origin)->ds_compressed_bytes;
1164                 dsphys->ds_uncompressed_bytes =
1165                     dsl_dataset_phys(origin)->ds_uncompressed_bytes;
1166                 rrw_enter(&origin->ds_bp_rwlock, RW_READER, FTAG);
1167                 dsphys->ds_bp = dsl_dataset_phys(origin)->ds_bp;
1168                 rrw_exit(&origin->ds_bp_rwlock, FTAG);
1169
1170                 /*
1171                  * Inherit flags that describe the dataset's contents
1172                  * (INCONSISTENT) or properties (Case Insensitive).
1173                  */
1174                 dsphys->ds_flags |= dsl_dataset_phys(origin)->ds_flags &
1175                     (DS_FLAG_INCONSISTENT | DS_FLAG_CI_DATASET);
1176
1177                 for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1178                         if (zfeature_active(f, origin->ds_feature[f])) {
1179                                 dsl_dataset_activate_feature(dsobj, f,
1180                                     origin->ds_feature[f], tx);
1181                         }
1182                 }
1183
1184                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
1185                 dsl_dataset_phys(origin)->ds_num_children++;
1186
1187                 VERIFY0(dsl_dataset_hold_obj(dp,
1188                     dsl_dir_phys(origin->ds_dir)->dd_head_dataset_obj,
1189                     FTAG, &ohds));
1190                 dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
1191                     dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
1192                 dsl_dataset_rele(ohds, FTAG);
1193
1194                 if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
1195                         if (dsl_dataset_phys(origin)->ds_next_clones_obj == 0) {
1196                                 dsl_dataset_phys(origin)->ds_next_clones_obj =
1197                                     zap_create(mos,
1198                                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
1199                         }
1200                         VERIFY0(zap_add_int(mos,
1201                             dsl_dataset_phys(origin)->ds_next_clones_obj,
1202                             dsobj, tx));
1203                 }
1204
1205                 dmu_buf_will_dirty(dd->dd_dbuf, tx);
1206                 dsl_dir_phys(dd)->dd_origin_obj = origin->ds_object;
1207                 if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
1208                         if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1209                                 dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1210                                 dsl_dir_phys(origin->ds_dir)->dd_clones =
1211                                     zap_create(mos,
1212                                     DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
1213                         }
1214                         VERIFY0(zap_add_int(mos,
1215                             dsl_dir_phys(origin->ds_dir)->dd_clones,
1216                             dsobj, tx));
1217                 }
1218         }
1219
1220         /* handle encryption */
1221         dsl_dataset_create_crypt_sync(dsobj, dd, origin, dcp, tx);
1222
1223         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1224                 dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1225
1226         dmu_buf_rele(dbuf, FTAG);
1227
1228         dmu_buf_will_dirty(dd->dd_dbuf, tx);
1229         dsl_dir_phys(dd)->dd_head_dataset_obj = dsobj;
1230
1231         return (dsobj);
1232 }
1233
1234 static void
1235 dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
1236 {
1237         objset_t *os;
1238
1239         VERIFY0(dmu_objset_from_ds(ds, &os));
1240         if (bcmp(&os->os_zil_header, &zero_zil, sizeof (zero_zil)) != 0) {
1241                 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1242                 zio_t *zio;
1243
1244                 bzero(&os->os_zil_header, sizeof (os->os_zil_header));
1245                 if (os->os_encrypted)
1246                         os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1247
1248                 zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1249                 dsl_dataset_sync(ds, zio, tx);
1250                 VERIFY0(zio_wait(zio));
1251
1252                 /* dsl_dataset_sync_done will drop this reference. */
1253                 dmu_buf_add_ref(ds->ds_dbuf, ds);
1254                 dsl_dataset_sync_done(ds, tx);
1255         }
1256 }
1257
1258 uint64_t
1259 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
1260     dsl_dataset_t *origin, uint64_t flags, cred_t *cr,
1261     dsl_crypto_params_t *dcp, dmu_tx_t *tx)
1262 {
1263         dsl_pool_t *dp = pdd->dd_pool;
1264         uint64_t dsobj, ddobj;
1265         dsl_dir_t *dd;
1266
1267         ASSERT(dmu_tx_is_syncing(tx));
1268         ASSERT(lastname[0] != '@');
1269         /*
1270          * Filesystems will eventually have their origin set to dp_origin_snap,
1271          * but that's taken care of in dsl_dataset_create_sync_dd. When
1272          * creating a filesystem, this function is called with origin equal to
1273          * NULL.
1274          */
1275         if (origin != NULL)
1276                 ASSERT3P(origin, !=, dp->dp_origin_snap);
1277
1278         ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
1279         VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
1280
1281         dsobj = dsl_dataset_create_sync_dd(dd, origin, dcp,
1282             flags & ~DS_CREATE_FLAG_NODIRTY, tx);
1283
1284         dsl_deleg_set_create_perms(dd, tx, cr);
1285
1286         /*
1287          * If we are creating a clone and the livelist feature is enabled,
1288          * add the entry DD_FIELD_LIVELIST to ZAP.
1289          */
1290         if (origin != NULL &&
1291             spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LIVELIST)) {
1292                 objset_t *mos = dd->dd_pool->dp_meta_objset;
1293                 dsl_dir_zapify(dd, tx);
1294                 uint64_t obj = dsl_deadlist_alloc(mos, tx);
1295                 VERIFY0(zap_add(mos, dd->dd_object, DD_FIELD_LIVELIST,
1296                     sizeof (uint64_t), 1, &obj, tx));
1297                 spa_feature_incr(dp->dp_spa, SPA_FEATURE_LIVELIST, tx);
1298         }
1299
1300         /*
1301          * Since we're creating a new node we know it's a leaf, so we can
1302          * initialize the counts if the limit feature is active.
1303          */
1304         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
1305                 uint64_t cnt = 0;
1306                 objset_t *os = dd->dd_pool->dp_meta_objset;
1307
1308                 dsl_dir_zapify(dd, tx);
1309                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
1310                     sizeof (cnt), 1, &cnt, tx));
1311                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
1312                     sizeof (cnt), 1, &cnt, tx));
1313         }
1314
1315         dsl_dir_rele(dd, FTAG);
1316
1317         /*
1318          * If we are creating a clone, make sure we zero out any stale
1319          * data from the origin snapshots zil header.
1320          */
1321         if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
1322                 dsl_dataset_t *ds;
1323
1324                 VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1325                 dsl_dataset_zero_zil(ds, tx);
1326                 dsl_dataset_rele(ds, FTAG);
1327         }
1328
1329         return (dsobj);
1330 }
1331
1332 /*
1333  * The unique space in the head dataset can be calculated by subtracting
1334  * the space used in the most recent snapshot, that is still being used
1335  * in this file system, from the space currently in use.  To figure out
1336  * the space in the most recent snapshot still in use, we need to take
1337  * the total space used in the snapshot and subtract out the space that
1338  * has been freed up since the snapshot was taken.
1339  */
1340 void
1341 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1342 {
1343         uint64_t mrs_used;
1344         uint64_t dlused, dlcomp, dluncomp;
1345
1346         ASSERT(!ds->ds_is_snapshot);
1347
1348         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0)
1349                 mrs_used = dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes;
1350         else
1351                 mrs_used = 0;
1352
1353         dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
1354
1355         ASSERT3U(dlused, <=, mrs_used);
1356         dsl_dataset_phys(ds)->ds_unique_bytes =
1357             dsl_dataset_phys(ds)->ds_referenced_bytes - (mrs_used - dlused);
1358
1359         if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1360             SPA_VERSION_UNIQUE_ACCURATE)
1361                 dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1362 }
1363
1364 void
1365 dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
1366     dmu_tx_t *tx)
1367 {
1368         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1369         ASSERTV(uint64_t count);
1370         int err;
1371
1372         ASSERT(dsl_dataset_phys(ds)->ds_num_children >= 2);
1373         err = zap_remove_int(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1374             obj, tx);
1375         /*
1376          * The err should not be ENOENT, but a bug in a previous version
1377          * of the code could cause upgrade_clones_cb() to not set
1378          * ds_next_snap_obj when it should, leading to a missing entry.
1379          * If we knew that the pool was created after
1380          * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
1381          * ENOENT.  However, at least we can check that we don't have
1382          * too many entries in the next_clones_obj even after failing to
1383          * remove this one.
1384          */
1385         if (err != ENOENT)
1386                 VERIFY0(err);
1387         ASSERT0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1388             &count));
1389         ASSERT3U(count, <=, dsl_dataset_phys(ds)->ds_num_children - 2);
1390 }
1391
1392
1393 blkptr_t *
1394 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1395 {
1396         return (&dsl_dataset_phys(ds)->ds_bp);
1397 }
1398
1399 spa_t *
1400 dsl_dataset_get_spa(dsl_dataset_t *ds)
1401 {
1402         return (ds->ds_dir->dd_pool->dp_spa);
1403 }
1404
1405 void
1406 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1407 {
1408         dsl_pool_t *dp;
1409
1410         if (ds == NULL) /* this is the meta-objset */
1411                 return;
1412
1413         ASSERT(ds->ds_objset != NULL);
1414
1415         if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0)
1416                 panic("dirtying snapshot!");
1417
1418         /* Must not dirty a dataset in the same txg where it got snapshotted. */
1419         ASSERT3U(tx->tx_txg, >, dsl_dataset_phys(ds)->ds_prev_snap_txg);
1420
1421         dp = ds->ds_dir->dd_pool;
1422         if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
1423                 objset_t *os = ds->ds_objset;
1424
1425                 /* up the hold count until we can be written out */
1426                 dmu_buf_add_ref(ds->ds_dbuf, ds);
1427
1428                 /* if this dataset is encrypted, grab a reference to the DCK */
1429                 if (ds->ds_dir->dd_crypto_obj != 0 &&
1430                     !os->os_raw_receive &&
1431                     !os->os_next_write_raw[tx->tx_txg & TXG_MASK]) {
1432                         ASSERT3P(ds->ds_key_mapping, !=, NULL);
1433                         key_mapping_add_ref(ds->ds_key_mapping, ds);
1434                 }
1435         }
1436 }
1437
1438 static int
1439 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1440 {
1441         uint64_t asize;
1442
1443         if (!dmu_tx_is_syncing(tx))
1444                 return (0);
1445
1446         /*
1447          * If there's an fs-only reservation, any blocks that might become
1448          * owned by the snapshot dataset must be accommodated by space
1449          * outside of the reservation.
1450          */
1451         ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
1452         asize = MIN(dsl_dataset_phys(ds)->ds_unique_bytes, ds->ds_reserved);
1453         if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
1454                 return (SET_ERROR(ENOSPC));
1455
1456         /*
1457          * Propagate any reserved space for this snapshot to other
1458          * snapshot checks in this sync group.
1459          */
1460         if (asize > 0)
1461                 dsl_dir_willuse_space(ds->ds_dir, asize, tx);
1462
1463         return (0);
1464 }
1465
1466 int
1467 dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1468     dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr)
1469 {
1470         int error;
1471         uint64_t value;
1472
1473         ds->ds_trysnap_txg = tx->tx_txg;
1474
1475         if (!dmu_tx_is_syncing(tx))
1476                 return (0);
1477
1478         /*
1479          * We don't allow multiple snapshots of the same txg.  If there
1480          * is already one, try again.
1481          */
1482         if (dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg)
1483                 return (SET_ERROR(EAGAIN));
1484
1485         /*
1486          * Check for conflicting snapshot name.
1487          */
1488         error = dsl_dataset_snap_lookup(ds, snapname, &value);
1489         if (error == 0)
1490                 return (SET_ERROR(EEXIST));
1491         if (error != ENOENT)
1492                 return (error);
1493
1494         /*
1495          * We don't allow taking snapshots of inconsistent datasets, such as
1496          * those into which we are currently receiving.  However, if we are
1497          * creating this snapshot as part of a receive, this check will be
1498          * executed atomically with respect to the completion of the receive
1499          * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1500          * case we ignore this, knowing it will be fixed up for us shortly in
1501          * dmu_recv_end_sync().
1502          */
1503         if (!recv && DS_IS_INCONSISTENT(ds))
1504                 return (SET_ERROR(EBUSY));
1505
1506         /*
1507          * Skip the check for temporary snapshots or if we have already checked
1508          * the counts in dsl_dataset_snapshot_check. This means we really only
1509          * check the count here when we're receiving a stream.
1510          */
1511         if (cnt != 0 && cr != NULL) {
1512                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1513                     ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr);
1514                 if (error != 0)
1515                         return (error);
1516         }
1517
1518         error = dsl_dataset_snapshot_reserve_space(ds, tx);
1519         if (error != 0)
1520                 return (error);
1521
1522         return (0);
1523 }
1524
1525 int
1526 dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1527 {
1528         dsl_dataset_snapshot_arg_t *ddsa = arg;
1529         dsl_pool_t *dp = dmu_tx_pool(tx);
1530         nvpair_t *pair;
1531         int rv = 0;
1532
1533         /*
1534          * Pre-compute how many total new snapshots will be created for each
1535          * level in the tree and below. This is needed for validating the
1536          * snapshot limit when either taking a recursive snapshot or when
1537          * taking multiple snapshots.
1538          *
1539          * The problem is that the counts are not actually adjusted when
1540          * we are checking, only when we finally sync. For a single snapshot,
1541          * this is easy, the count will increase by 1 at each node up the tree,
1542          * but its more complicated for the recursive/multiple snapshot case.
1543          *
1544          * The dsl_fs_ss_limit_check function does recursively check the count
1545          * at each level up the tree but since it is validating each snapshot
1546          * independently we need to be sure that we are validating the complete
1547          * count for the entire set of snapshots. We do this by rolling up the
1548          * counts for each component of the name into an nvlist and then
1549          * checking each of those cases with the aggregated count.
1550          *
1551          * This approach properly handles not only the recursive snapshot
1552          * case (where we get all of those on the ddsa_snaps list) but also
1553          * the sibling case (e.g. snapshot a/b and a/c so that we will also
1554          * validate the limit on 'a' using a count of 2).
1555          *
1556          * We validate the snapshot names in the third loop and only report
1557          * name errors once.
1558          */
1559         if (dmu_tx_is_syncing(tx)) {
1560                 char *nm;
1561                 nvlist_t *cnt_track = NULL;
1562                 cnt_track = fnvlist_alloc();
1563
1564                 nm = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1565
1566                 /* Rollup aggregated counts into the cnt_track list */
1567                 for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1568                     pair != NULL;
1569                     pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1570                         char *pdelim;
1571                         uint64_t val;
1572
1573                         (void) strlcpy(nm, nvpair_name(pair), MAXPATHLEN);
1574                         pdelim = strchr(nm, '@');
1575                         if (pdelim == NULL)
1576                                 continue;
1577                         *pdelim = '\0';
1578
1579                         do {
1580                                 if (nvlist_lookup_uint64(cnt_track, nm,
1581                                     &val) == 0) {
1582                                         /* update existing entry */
1583                                         fnvlist_add_uint64(cnt_track, nm,
1584                                             val + 1);
1585                                 } else {
1586                                         /* add to list */
1587                                         fnvlist_add_uint64(cnt_track, nm, 1);
1588                                 }
1589
1590                                 pdelim = strrchr(nm, '/');
1591                                 if (pdelim != NULL)
1592                                         *pdelim = '\0';
1593                         } while (pdelim != NULL);
1594                 }
1595
1596                 kmem_free(nm, MAXPATHLEN);
1597
1598                 /* Check aggregated counts at each level */
1599                 for (pair = nvlist_next_nvpair(cnt_track, NULL);
1600                     pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1601                         int error = 0;
1602                         char *name;
1603                         uint64_t cnt = 0;
1604                         dsl_dataset_t *ds;
1605
1606                         name = nvpair_name(pair);
1607                         cnt = fnvpair_value_uint64(pair);
1608                         ASSERT(cnt > 0);
1609
1610                         error = dsl_dataset_hold(dp, name, FTAG, &ds);
1611                         if (error == 0) {
1612                                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1613                                     ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1614                                     ddsa->ddsa_cr);
1615                                 dsl_dataset_rele(ds, FTAG);
1616                         }
1617
1618                         if (error != 0) {
1619                                 if (ddsa->ddsa_errors != NULL)
1620                                         fnvlist_add_int32(ddsa->ddsa_errors,
1621                                             name, error);
1622                                 rv = error;
1623                                 /* only report one error for this check */
1624                                 break;
1625                         }
1626                 }
1627                 nvlist_free(cnt_track);
1628         }
1629
1630         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1631             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1632                 int error = 0;
1633                 dsl_dataset_t *ds;
1634                 char *name, *atp = NULL;
1635                 char dsname[ZFS_MAX_DATASET_NAME_LEN];
1636
1637                 name = nvpair_name(pair);
1638                 if (strlen(name) >= ZFS_MAX_DATASET_NAME_LEN)
1639                         error = SET_ERROR(ENAMETOOLONG);
1640                 if (error == 0) {
1641                         atp = strchr(name, '@');
1642                         if (atp == NULL)
1643                                 error = SET_ERROR(EINVAL);
1644                         if (error == 0)
1645                                 (void) strlcpy(dsname, name, atp - name + 1);
1646                 }
1647                 if (error == 0)
1648                         error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1649                 if (error == 0) {
1650                         /* passing 0/NULL skips dsl_fs_ss_limit_check */
1651                         error = dsl_dataset_snapshot_check_impl(ds,
1652                             atp + 1, tx, B_FALSE, 0, NULL);
1653                         dsl_dataset_rele(ds, FTAG);
1654                 }
1655
1656                 if (error != 0) {
1657                         if (ddsa->ddsa_errors != NULL) {
1658                                 fnvlist_add_int32(ddsa->ddsa_errors,
1659                                     name, error);
1660                         }
1661                         rv = error;
1662                 }
1663         }
1664
1665         return (rv);
1666 }
1667
1668 void
1669 dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1670     dmu_tx_t *tx)
1671 {
1672         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1673         dmu_buf_t *dbuf;
1674         dsl_dataset_phys_t *dsphys;
1675         uint64_t dsobj, crtxg;
1676         objset_t *mos = dp->dp_meta_objset;
1677         ASSERTV(static zil_header_t zero_zil);
1678         ASSERTV(objset_t *os);
1679
1680         ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1681
1682         /*
1683          * If we are on an old pool, the zil must not be active, in which
1684          * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1685          */
1686         ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1687             dmu_objset_from_ds(ds, &os) != 0 ||
1688             bcmp(&os->os_phys->os_zil_header, &zero_zil,
1689             sizeof (zero_zil)) == 0);
1690
1691         /* Should not snapshot a dirty dataset. */
1692         ASSERT(!txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
1693             ds, tx->tx_txg));
1694
1695         dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1696
1697         /*
1698          * The origin's ds_creation_txg has to be < TXG_INITIAL
1699          */
1700         if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1701                 crtxg = 1;
1702         else
1703                 crtxg = tx->tx_txg;
1704
1705         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1706             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1707         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1708         dmu_buf_will_dirty(dbuf, tx);
1709         dsphys = dbuf->db_data;
1710         bzero(dsphys, sizeof (dsl_dataset_phys_t));
1711         dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1712         dsphys->ds_fsid_guid = unique_create();
1713         (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1714             sizeof (dsphys->ds_guid));
1715         dsphys->ds_prev_snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1716         dsphys->ds_prev_snap_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1717         dsphys->ds_next_snap_obj = ds->ds_object;
1718         dsphys->ds_num_children = 1;
1719         dsphys->ds_creation_time = gethrestime_sec();
1720         dsphys->ds_creation_txg = crtxg;
1721         dsphys->ds_deadlist_obj = dsl_dataset_phys(ds)->ds_deadlist_obj;
1722         dsphys->ds_referenced_bytes = dsl_dataset_phys(ds)->ds_referenced_bytes;
1723         dsphys->ds_compressed_bytes = dsl_dataset_phys(ds)->ds_compressed_bytes;
1724         dsphys->ds_uncompressed_bytes =
1725             dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1726         dsphys->ds_flags = dsl_dataset_phys(ds)->ds_flags;
1727         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1728         dsphys->ds_bp = dsl_dataset_phys(ds)->ds_bp;
1729         rrw_exit(&ds->ds_bp_rwlock, FTAG);
1730         dmu_buf_rele(dbuf, FTAG);
1731
1732         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1733                 if (zfeature_active(f, ds->ds_feature[f])) {
1734                         dsl_dataset_activate_feature(dsobj, f,
1735                             ds->ds_feature[f], tx);
1736                 }
1737         }
1738
1739         ASSERT3U(ds->ds_prev != 0, ==,
1740             dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1741         if (ds->ds_prev) {
1742                 uint64_t next_clones_obj =
1743                     dsl_dataset_phys(ds->ds_prev)->ds_next_clones_obj;
1744                 ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1745                     ds->ds_object ||
1746                     dsl_dataset_phys(ds->ds_prev)->ds_num_children > 1);
1747                 if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1748                     ds->ds_object) {
1749                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1750                         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, ==,
1751                             dsl_dataset_phys(ds->ds_prev)->ds_creation_txg);
1752                         dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj = dsobj;
1753                 } else if (next_clones_obj != 0) {
1754                         dsl_dataset_remove_from_next_clones(ds->ds_prev,
1755                             dsphys->ds_next_snap_obj, tx);
1756                         VERIFY0(zap_add_int(mos,
1757                             next_clones_obj, dsobj, tx));
1758                 }
1759         }
1760
1761         /*
1762          * If we have a reference-reservation on this dataset, we will
1763          * need to increase the amount of refreservation being charged
1764          * since our unique space is going to zero.
1765          */
1766         if (ds->ds_reserved) {
1767                 int64_t delta;
1768                 ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1769                 delta = MIN(dsl_dataset_phys(ds)->ds_unique_bytes,
1770                     ds->ds_reserved);
1771                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1772                     delta, 0, 0, tx);
1773         }
1774
1775         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1776         dsl_dataset_phys(ds)->ds_deadlist_obj =
1777             dsl_deadlist_clone(&ds->ds_deadlist, UINT64_MAX,
1778             dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
1779         dsl_deadlist_close(&ds->ds_deadlist);
1780         dsl_deadlist_open(&ds->ds_deadlist, mos,
1781             dsl_dataset_phys(ds)->ds_deadlist_obj);
1782         dsl_deadlist_add_key(&ds->ds_deadlist,
1783             dsl_dataset_phys(ds)->ds_prev_snap_txg, tx);
1784         dsl_bookmark_snapshotted(ds, tx);
1785
1786         if (dsl_dataset_remap_deadlist_exists(ds)) {
1787                 uint64_t remap_deadlist_obj =
1788                     dsl_dataset_get_remap_deadlist_object(ds);
1789                 /*
1790                  * Move the remap_deadlist to the snapshot.  The head
1791                  * will create a new remap deadlist on demand, from
1792                  * dsl_dataset_block_remapped().
1793                  */
1794                 dsl_dataset_unset_remap_deadlist_object(ds, tx);
1795                 dsl_deadlist_close(&ds->ds_remap_deadlist);
1796
1797                 dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1798                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_REMAP_DEADLIST,
1799                     sizeof (remap_deadlist_obj), 1, &remap_deadlist_obj, tx));
1800         }
1801
1802         /*
1803          * Create a ivset guid for this snapshot if the dataset is
1804          * encrypted. This may be overridden by a raw receive. A
1805          * previous implementation of this code did not have this
1806          * field as part of the on-disk format for ZFS encryption
1807          * (see errata #4). As part of the remediation for this
1808          * issue, we ask the user to enable the bookmark_v2 feature
1809          * which is now a dependency of the encryption feature. We
1810          * use this as a heuristic to determine when the user has
1811          * elected to correct any datasets created with the old code.
1812          * As a result, we only do this step if the bookmark_v2
1813          * feature is enabled, which limits the number of states a
1814          * given pool / dataset can be in with regards to terms of
1815          * correcting the issue.
1816          */
1817         if (ds->ds_dir->dd_crypto_obj != 0 &&
1818             spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_BOOKMARK_V2)) {
1819                 uint64_t ivset_guid = unique_create();
1820
1821                 dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1822                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_IVSET_GUID,
1823                     sizeof (ivset_guid), 1, &ivset_guid, tx));
1824         }
1825
1826         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, <, tx->tx_txg);
1827         dsl_dataset_phys(ds)->ds_prev_snap_obj = dsobj;
1828         dsl_dataset_phys(ds)->ds_prev_snap_txg = crtxg;
1829         dsl_dataset_phys(ds)->ds_unique_bytes = 0;
1830
1831         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1832                 dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1833
1834         VERIFY0(zap_add(mos, dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1835             snapname, 8, 1, &dsobj, tx));
1836
1837         if (ds->ds_prev)
1838                 dsl_dataset_rele(ds->ds_prev, ds);
1839         VERIFY0(dsl_dataset_hold_obj(dp,
1840             dsl_dataset_phys(ds)->ds_prev_snap_obj, ds, &ds->ds_prev));
1841
1842         dsl_scan_ds_snapshotted(ds, tx);
1843
1844         dsl_dir_snap_cmtime_update(ds->ds_dir);
1845
1846         spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, " ");
1847 }
1848
1849 void
1850 dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1851 {
1852         dsl_dataset_snapshot_arg_t *ddsa = arg;
1853         dsl_pool_t *dp = dmu_tx_pool(tx);
1854         nvpair_t *pair;
1855
1856         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1857             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1858                 dsl_dataset_t *ds;
1859                 char *name, *atp;
1860                 char dsname[ZFS_MAX_DATASET_NAME_LEN];
1861
1862                 name = nvpair_name(pair);
1863                 atp = strchr(name, '@');
1864                 (void) strlcpy(dsname, name, atp - name + 1);
1865                 VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1866
1867                 dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1868                 if (ddsa->ddsa_props != NULL) {
1869                         dsl_props_set_sync_impl(ds->ds_prev,
1870                             ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1871                 }
1872                 zvol_create_minors(dp->dp_spa, nvpair_name(pair), B_TRUE);
1873                 dsl_dataset_rele(ds, FTAG);
1874         }
1875 }
1876
1877 /*
1878  * The snapshots must all be in the same pool.
1879  * All-or-nothing: if there are any failures, nothing will be modified.
1880  */
1881 int
1882 dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1883 {
1884         dsl_dataset_snapshot_arg_t ddsa;
1885         nvpair_t *pair;
1886         boolean_t needsuspend;
1887         int error;
1888         spa_t *spa;
1889         char *firstname;
1890         nvlist_t *suspended = NULL;
1891
1892         pair = nvlist_next_nvpair(snaps, NULL);
1893         if (pair == NULL)
1894                 return (0);
1895         firstname = nvpair_name(pair);
1896
1897         error = spa_open(firstname, &spa, FTAG);
1898         if (error != 0)
1899                 return (error);
1900         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1901         spa_close(spa, FTAG);
1902
1903         if (needsuspend) {
1904                 suspended = fnvlist_alloc();
1905                 for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1906                     pair = nvlist_next_nvpair(snaps, pair)) {
1907                         char fsname[ZFS_MAX_DATASET_NAME_LEN];
1908                         char *snapname = nvpair_name(pair);
1909                         char *atp;
1910                         void *cookie;
1911
1912                         atp = strchr(snapname, '@');
1913                         if (atp == NULL) {
1914                                 error = SET_ERROR(EINVAL);
1915                                 break;
1916                         }
1917                         (void) strlcpy(fsname, snapname, atp - snapname + 1);
1918
1919                         error = zil_suspend(fsname, &cookie);
1920                         if (error != 0)
1921                                 break;
1922                         fnvlist_add_uint64(suspended, fsname,
1923                             (uintptr_t)cookie);
1924                 }
1925         }
1926
1927         ddsa.ddsa_snaps = snaps;
1928         ddsa.ddsa_props = props;
1929         ddsa.ddsa_errors = errors;
1930         ddsa.ddsa_cr = CRED();
1931
1932         if (error == 0) {
1933                 error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1934                     dsl_dataset_snapshot_sync, &ddsa,
1935                     fnvlist_num_pairs(snaps) * 3, ZFS_SPACE_CHECK_NORMAL);
1936         }
1937
1938         if (suspended != NULL) {
1939                 for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
1940                     pair = nvlist_next_nvpair(suspended, pair)) {
1941                         zil_resume((void *)(uintptr_t)
1942                             fnvpair_value_uint64(pair));
1943                 }
1944                 fnvlist_free(suspended);
1945         }
1946
1947         return (error);
1948 }
1949
1950 typedef struct dsl_dataset_snapshot_tmp_arg {
1951         const char *ddsta_fsname;
1952         const char *ddsta_snapname;
1953         minor_t ddsta_cleanup_minor;
1954         const char *ddsta_htag;
1955 } dsl_dataset_snapshot_tmp_arg_t;
1956
1957 static int
1958 dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
1959 {
1960         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1961         dsl_pool_t *dp = dmu_tx_pool(tx);
1962         dsl_dataset_t *ds;
1963         int error;
1964
1965         error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
1966         if (error != 0)
1967                 return (error);
1968
1969         /* NULL cred means no limit check for tmp snapshot */
1970         error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
1971             tx, B_FALSE, 0, NULL);
1972         if (error != 0) {
1973                 dsl_dataset_rele(ds, FTAG);
1974                 return (error);
1975         }
1976
1977         if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
1978                 dsl_dataset_rele(ds, FTAG);
1979                 return (SET_ERROR(ENOTSUP));
1980         }
1981         error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
1982             B_TRUE, tx);
1983         if (error != 0) {
1984                 dsl_dataset_rele(ds, FTAG);
1985                 return (error);
1986         }
1987
1988         dsl_dataset_rele(ds, FTAG);
1989         return (0);
1990 }
1991
1992 static void
1993 dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
1994 {
1995         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1996         dsl_pool_t *dp = dmu_tx_pool(tx);
1997         dsl_dataset_t *ds = NULL;
1998
1999         VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
2000
2001         dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
2002         dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
2003             ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
2004         dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
2005
2006         dsl_dataset_rele(ds, FTAG);
2007 }
2008
2009 int
2010 dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
2011     minor_t cleanup_minor, const char *htag)
2012 {
2013         dsl_dataset_snapshot_tmp_arg_t ddsta;
2014         int error;
2015         spa_t *spa;
2016         boolean_t needsuspend;
2017         void *cookie;
2018
2019         ddsta.ddsta_fsname = fsname;
2020         ddsta.ddsta_snapname = snapname;
2021         ddsta.ddsta_cleanup_minor = cleanup_minor;
2022         ddsta.ddsta_htag = htag;
2023
2024         error = spa_open(fsname, &spa, FTAG);
2025         if (error != 0)
2026                 return (error);
2027         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
2028         spa_close(spa, FTAG);
2029
2030         if (needsuspend) {
2031                 error = zil_suspend(fsname, &cookie);
2032                 if (error != 0)
2033                         return (error);
2034         }
2035
2036         error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
2037             dsl_dataset_snapshot_tmp_sync, &ddsta, 3, ZFS_SPACE_CHECK_RESERVED);
2038
2039         if (needsuspend)
2040                 zil_resume(cookie);
2041         return (error);
2042 }
2043
2044 void
2045 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
2046 {
2047         ASSERT(dmu_tx_is_syncing(tx));
2048         ASSERT(ds->ds_objset != NULL);
2049         ASSERT(dsl_dataset_phys(ds)->ds_next_snap_obj == 0);
2050
2051         /*
2052          * in case we had to change ds_fsid_guid when we opened it,
2053          * sync it out now.
2054          */
2055         dmu_buf_will_dirty(ds->ds_dbuf, tx);
2056         dsl_dataset_phys(ds)->ds_fsid_guid = ds->ds_fsid_guid;
2057
2058         if (ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] != 0) {
2059                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2060                     ds->ds_object, DS_FIELD_RESUME_OBJECT, 8, 1,
2061                     &ds->ds_resume_object[tx->tx_txg & TXG_MASK], tx));
2062                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2063                     ds->ds_object, DS_FIELD_RESUME_OFFSET, 8, 1,
2064                     &ds->ds_resume_offset[tx->tx_txg & TXG_MASK], tx));
2065                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2066                     ds->ds_object, DS_FIELD_RESUME_BYTES, 8, 1,
2067                     &ds->ds_resume_bytes[tx->tx_txg & TXG_MASK], tx));
2068                 ds->ds_resume_object[tx->tx_txg & TXG_MASK] = 0;
2069                 ds->ds_resume_offset[tx->tx_txg & TXG_MASK] = 0;
2070                 ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] = 0;
2071         }
2072
2073         dmu_objset_sync(ds->ds_objset, zio, tx);
2074
2075         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2076                 if (zfeature_active(f, ds->ds_feature_activation[f])) {
2077                         if (zfeature_active(f, ds->ds_feature[f]))
2078                                 continue;
2079                         dsl_dataset_activate_feature(ds->ds_object, f,
2080                             ds->ds_feature_activation[f], tx);
2081                         ds->ds_feature[f] = ds->ds_feature_activation[f];
2082                 }
2083         }
2084 }
2085
2086 /*
2087  * Check if the percentage of blocks shared between the clone and the
2088  * snapshot (as opposed to those that are clone only) is below a certain
2089  * threshold
2090  */
2091 static boolean_t
2092 dsl_livelist_should_disable(dsl_dataset_t *ds)
2093 {
2094         uint64_t used, referenced;
2095         int percent_shared;
2096
2097         used = dsl_dir_get_usedds(ds->ds_dir);
2098         referenced = dsl_get_referenced(ds);
2099         ASSERT3U(referenced, >=, 0);
2100         ASSERT3U(used, >=, 0);
2101         if (referenced == 0)
2102                 return (B_FALSE);
2103         percent_shared = (100 * (referenced - used)) / referenced;
2104         if (percent_shared <= zfs_livelist_min_percent_shared)
2105                 return (B_TRUE);
2106         return (B_FALSE);
2107 }
2108
2109 /*
2110  *  Check if it is possible to combine two livelist entries into one.
2111  *  This is the case if the combined number of 'live' blkptrs (ALLOCs that
2112  *  don't have a matching FREE) is under the maximum sublist size.
2113  *  We check this by subtracting twice the total number of frees from the total
2114  *  number of blkptrs. FREEs are counted twice because each FREE blkptr
2115  *  will cancel out an ALLOC blkptr when the livelist is processed.
2116  */
2117 static boolean_t
2118 dsl_livelist_should_condense(dsl_deadlist_entry_t *first,
2119     dsl_deadlist_entry_t *next)
2120 {
2121         uint64_t total_free = first->dle_bpobj.bpo_phys->bpo_num_freed +
2122             next->dle_bpobj.bpo_phys->bpo_num_freed;
2123         uint64_t total_entries = first->dle_bpobj.bpo_phys->bpo_num_blkptrs +
2124             next->dle_bpobj.bpo_phys->bpo_num_blkptrs;
2125         if ((total_entries - (2 * total_free)) < zfs_livelist_max_entries)
2126                 return (B_TRUE);
2127         return (B_FALSE);
2128 }
2129
2130 typedef struct try_condense_arg {
2131         spa_t *spa;
2132         dsl_dataset_t *ds;
2133 } try_condense_arg_t;
2134
2135 /*
2136  * Iterate over the livelist entries, searching for a pair to condense.
2137  * A nonzero return value means stop, 0 means keep looking.
2138  */
2139 static int
2140 dsl_livelist_try_condense(void *arg, dsl_deadlist_entry_t *first)
2141 {
2142         try_condense_arg_t *tca = arg;
2143         spa_t *spa = tca->spa;
2144         dsl_dataset_t *ds = tca->ds;
2145         dsl_deadlist_t *ll = &ds->ds_dir->dd_livelist;
2146         dsl_deadlist_entry_t *next;
2147
2148         /* The condense thread has not yet been created at import */
2149         if (spa->spa_livelist_condense_zthr == NULL)
2150                 return (1);
2151
2152         /* A condense is already in progress */
2153         if (spa->spa_to_condense.ds != NULL)
2154                 return (1);
2155
2156         next = AVL_NEXT(&ll->dl_tree, &first->dle_node);
2157         /* The livelist has only one entry - don't condense it */
2158         if (next == NULL)
2159                 return (1);
2160
2161         /* Next is the newest entry - don't condense it */
2162         if (AVL_NEXT(&ll->dl_tree, &next->dle_node) == NULL)
2163                 return (1);
2164
2165         /* This pair is not ready to condense but keep looking */
2166         if (!dsl_livelist_should_condense(first, next))
2167                 return (0);
2168
2169         /*
2170          * Add a ref to prevent the dataset from being evicted while
2171          * the condense zthr or synctask are running. Ref will be
2172          * released at the end of the condense synctask
2173          */
2174         dmu_buf_add_ref(ds->ds_dbuf, spa);
2175
2176         spa->spa_to_condense.ds = ds;
2177         spa->spa_to_condense.first = first;
2178         spa->spa_to_condense.next = next;
2179         spa->spa_to_condense.syncing = B_FALSE;
2180         spa->spa_to_condense.cancelled = B_FALSE;
2181
2182         zthr_wakeup(spa->spa_livelist_condense_zthr);
2183         return (1);
2184 }
2185
2186 static void
2187 dsl_flush_pending_livelist(dsl_dataset_t *ds, dmu_tx_t *tx)
2188 {
2189         dsl_dir_t *dd = ds->ds_dir;
2190         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
2191         dsl_deadlist_entry_t *last = dsl_deadlist_last(&dd->dd_livelist);
2192
2193         /* Check if we need to add a new sub-livelist */
2194         if (last == NULL) {
2195                 /* The livelist is empty */
2196                 dsl_deadlist_add_key(&dd->dd_livelist,
2197                     tx->tx_txg - 1, tx);
2198         } else if (spa_sync_pass(spa) == 1) {
2199                 /*
2200                  * Check if the newest entry is full. If it is, make a new one.
2201                  * We only do this once per sync because we could overfill a
2202                  * sublist in one sync pass and don't want to add another entry
2203                  * for a txg that is already represented. This ensures that
2204                  * blkptrs born in the same txg are stored in the same sublist.
2205                  */
2206                 bpobj_t bpobj = last->dle_bpobj;
2207                 uint64_t all = bpobj.bpo_phys->bpo_num_blkptrs;
2208                 uint64_t free = bpobj.bpo_phys->bpo_num_freed;
2209                 uint64_t alloc = all - free;
2210                 if (alloc > zfs_livelist_max_entries) {
2211                         dsl_deadlist_add_key(&dd->dd_livelist,
2212                             tx->tx_txg - 1, tx);
2213                 }
2214         }
2215
2216         /* Insert each entry into the on-disk livelist */
2217         bplist_iterate(&dd->dd_pending_allocs,
2218             dsl_deadlist_insert_alloc_cb, &dd->dd_livelist, tx);
2219         bplist_iterate(&dd->dd_pending_frees,
2220             dsl_deadlist_insert_free_cb, &dd->dd_livelist, tx);
2221
2222         /* Attempt to condense every pair of adjacent entries */
2223         try_condense_arg_t arg = {
2224             .spa = spa,
2225             .ds = ds
2226         };
2227         dsl_deadlist_iterate(&dd->dd_livelist, dsl_livelist_try_condense,
2228             &arg);
2229 }
2230
2231 void
2232 dsl_dataset_sync_done(dsl_dataset_t *ds, dmu_tx_t *tx)
2233 {
2234         objset_t *os = ds->ds_objset;
2235
2236         bplist_iterate(&ds->ds_pending_deadlist,
2237             dsl_deadlist_insert_alloc_cb, &ds->ds_deadlist, tx);
2238
2239         if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist)) {
2240                 dsl_flush_pending_livelist(ds, tx);
2241                 if (dsl_livelist_should_disable(ds)) {
2242                         dsl_dir_remove_livelist(ds->ds_dir, tx, B_TRUE);
2243                 }
2244         }
2245
2246         dsl_bookmark_sync_done(ds, tx);
2247
2248         if (os->os_synced_dnodes != NULL) {
2249                 multilist_destroy(os->os_synced_dnodes);
2250                 os->os_synced_dnodes = NULL;
2251         }
2252
2253         if (os->os_encrypted)
2254                 os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_FALSE;
2255         else
2256                 ASSERT0(os->os_next_write_raw[tx->tx_txg & TXG_MASK]);
2257
2258         ASSERT(!dmu_objset_is_dirty(os, dmu_tx_get_txg(tx)));
2259
2260         dmu_buf_rele(ds->ds_dbuf, ds);
2261 }
2262
2263 int
2264 get_clones_stat_impl(dsl_dataset_t *ds, nvlist_t *val)
2265 {
2266         uint64_t count = 0;
2267         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
2268         zap_cursor_t zc;
2269         zap_attribute_t za;
2270
2271         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
2272
2273         /*
2274          * There may be missing entries in ds_next_clones_obj
2275          * due to a bug in a previous version of the code.
2276          * Only trust it if it has the right number of entries.
2277          */
2278         if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2279                 VERIFY0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
2280                     &count));
2281         }
2282         if (count != dsl_dataset_phys(ds)->ds_num_children - 1) {
2283                 return (ENOENT);
2284         }
2285         for (zap_cursor_init(&zc, mos,
2286             dsl_dataset_phys(ds)->ds_next_clones_obj);
2287             zap_cursor_retrieve(&zc, &za) == 0;
2288             zap_cursor_advance(&zc)) {
2289                 dsl_dataset_t *clone;
2290                 char buf[ZFS_MAX_DATASET_NAME_LEN];
2291                 VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
2292                     za.za_first_integer, FTAG, &clone));
2293                 dsl_dir_name(clone->ds_dir, buf);
2294                 fnvlist_add_boolean(val, buf);
2295                 dsl_dataset_rele(clone, FTAG);
2296         }
2297         zap_cursor_fini(&zc);
2298         return (0);
2299 }
2300
2301 void
2302 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
2303 {
2304         nvlist_t *propval = fnvlist_alloc();
2305         nvlist_t *val;
2306
2307         /*
2308          * We use nvlist_alloc() instead of fnvlist_alloc() because the
2309          * latter would allocate the list with NV_UNIQUE_NAME flag.
2310          * As a result, every time a clone name is appended to the list
2311          * it would be (linearly) searched for a duplicate name.
2312          * We already know that all clone names must be unique and we
2313          * want avoid the quadratic complexity of double-checking that
2314          * because we can have a large number of clones.
2315          */
2316         VERIFY0(nvlist_alloc(&val, 0, KM_SLEEP));
2317
2318         if (get_clones_stat_impl(ds, val) == 0) {
2319                 fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
2320                 fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2321                     propval);
2322         }
2323
2324         nvlist_free(val);
2325         nvlist_free(propval);
2326 }
2327
2328 /*
2329  * Returns a string that represents the receive resume stats token. It should
2330  * be freed with strfree().
2331  */
2332 char *
2333 get_receive_resume_stats_impl(dsl_dataset_t *ds)
2334 {
2335         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2336
2337         if (dsl_dataset_has_resume_receive_state(ds)) {
2338                 char *str;
2339                 void *packed;
2340                 uint8_t *compressed;
2341                 uint64_t val;
2342                 nvlist_t *token_nv = fnvlist_alloc();
2343                 size_t packed_size, compressed_size;
2344
2345                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2346                     DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val) == 0) {
2347                         fnvlist_add_uint64(token_nv, "fromguid", val);
2348                 }
2349                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2350                     DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val) == 0) {
2351                         fnvlist_add_uint64(token_nv, "object", val);
2352                 }
2353                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2354                     DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val) == 0) {
2355                         fnvlist_add_uint64(token_nv, "offset", val);
2356                 }
2357                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2358                     DS_FIELD_RESUME_BYTES, sizeof (val), 1, &val) == 0) {
2359                         fnvlist_add_uint64(token_nv, "bytes", val);
2360                 }
2361                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2362                     DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val) == 0) {
2363                         fnvlist_add_uint64(token_nv, "toguid", val);
2364                 }
2365                 char buf[MAXNAMELEN];
2366                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2367                     DS_FIELD_RESUME_TONAME, 1, sizeof (buf), buf) == 0) {
2368                         fnvlist_add_string(token_nv, "toname", buf);
2369                 }
2370                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2371                     DS_FIELD_RESUME_LARGEBLOCK) == 0) {
2372                         fnvlist_add_boolean(token_nv, "largeblockok");
2373                 }
2374                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2375                     DS_FIELD_RESUME_EMBEDOK) == 0) {
2376                         fnvlist_add_boolean(token_nv, "embedok");
2377                 }
2378                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2379                     DS_FIELD_RESUME_COMPRESSOK) == 0) {
2380                         fnvlist_add_boolean(token_nv, "compressok");
2381                 }
2382                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2383                     DS_FIELD_RESUME_RAWOK) == 0) {
2384                         fnvlist_add_boolean(token_nv, "rawok");
2385                 }
2386                 if (dsl_dataset_feature_is_active(ds,
2387                     SPA_FEATURE_REDACTED_DATASETS)) {
2388                         uint64_t num_redact_snaps;
2389                         uint64_t *redact_snaps;
2390                         VERIFY(dsl_dataset_get_uint64_array_feature(ds,
2391                             SPA_FEATURE_REDACTED_DATASETS, &num_redact_snaps,
2392                             &redact_snaps));
2393                         fnvlist_add_uint64_array(token_nv, "redact_snaps",
2394                             redact_snaps, num_redact_snaps);
2395                 }
2396                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2397                     DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS) == 0) {
2398                         uint64_t num_redact_snaps, int_size;
2399                         uint64_t *redact_snaps;
2400                         VERIFY0(zap_length(dp->dp_meta_objset, ds->ds_object,
2401                             DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, &int_size,
2402                             &num_redact_snaps));
2403                         ASSERT3U(int_size, ==, sizeof (uint64_t));
2404
2405                         redact_snaps = kmem_alloc(int_size * num_redact_snaps,
2406                             KM_SLEEP);
2407                         VERIFY0(zap_lookup(dp->dp_meta_objset, ds->ds_object,
2408                             DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, int_size,
2409                             num_redact_snaps, redact_snaps));
2410                         fnvlist_add_uint64_array(token_nv, "book_redact_snaps",
2411                             redact_snaps, num_redact_snaps);
2412                         kmem_free(redact_snaps, int_size * num_redact_snaps);
2413                 }
2414                 packed = fnvlist_pack(token_nv, &packed_size);
2415                 fnvlist_free(token_nv);
2416                 compressed = kmem_alloc(packed_size, KM_SLEEP);
2417
2418                 compressed_size = gzip_compress(packed, compressed,
2419                     packed_size, packed_size, 6);
2420
2421                 zio_cksum_t cksum;
2422                 fletcher_4_native_varsize(compressed, compressed_size, &cksum);
2423
2424                 str = kmem_alloc(compressed_size * 2 + 1, KM_SLEEP);
2425                 for (int i = 0; i < compressed_size; i++) {
2426                         (void) sprintf(str + i * 2, "%02x", compressed[i]);
2427                 }
2428                 str[compressed_size * 2] = '\0';
2429                 char *propval = kmem_asprintf("%u-%llx-%llx-%s",
2430                     ZFS_SEND_RESUME_TOKEN_VERSION,
2431                     (longlong_t)cksum.zc_word[0],
2432                     (longlong_t)packed_size, str);
2433                 kmem_free(packed, packed_size);
2434                 kmem_free(str, compressed_size * 2 + 1);
2435                 kmem_free(compressed, packed_size);
2436                 return (propval);
2437         }
2438         return (kmem_strdup(""));
2439 }
2440
2441 /*
2442  * Returns a string that represents the receive resume stats token of the
2443  * dataset's child. It should be freed with strfree().
2444  */
2445 char *
2446 get_child_receive_stats(dsl_dataset_t *ds)
2447 {
2448         char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
2449         dsl_dataset_t *recv_ds;
2450         dsl_dataset_name(ds, recvname);
2451         if (strlcat(recvname, "/", sizeof (recvname)) <
2452             sizeof (recvname) &&
2453             strlcat(recvname, recv_clone_name, sizeof (recvname)) <
2454             sizeof (recvname) &&
2455             dsl_dataset_hold(ds->ds_dir->dd_pool, recvname, FTAG,
2456             &recv_ds)  == 0) {
2457                 char *propval = get_receive_resume_stats_impl(recv_ds);
2458                 dsl_dataset_rele(recv_ds, FTAG);
2459                 return (propval);
2460         }
2461         return (kmem_strdup(""));
2462 }
2463
2464 static void
2465 get_receive_resume_stats(dsl_dataset_t *ds, nvlist_t *nv)
2466 {
2467         char *propval = get_receive_resume_stats_impl(ds);
2468         if (strcmp(propval, "") != 0) {
2469                 dsl_prop_nvlist_add_string(nv,
2470                     ZFS_PROP_RECEIVE_RESUME_TOKEN, propval);
2471         } else {
2472                 char *childval = get_child_receive_stats(ds);
2473                 if (strcmp(childval, "") != 0) {
2474                         dsl_prop_nvlist_add_string(nv,
2475                             ZFS_PROP_RECEIVE_RESUME_TOKEN, childval);
2476                 }
2477                 kmem_strfree(childval);
2478         }
2479         kmem_strfree(propval);
2480 }
2481
2482 uint64_t
2483 dsl_get_refratio(dsl_dataset_t *ds)
2484 {
2485         uint64_t ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
2486             (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
2487             dsl_dataset_phys(ds)->ds_compressed_bytes);
2488         return (ratio);
2489 }
2490
2491 uint64_t
2492 dsl_get_logicalreferenced(dsl_dataset_t *ds)
2493 {
2494         return (dsl_dataset_phys(ds)->ds_uncompressed_bytes);
2495 }
2496
2497 uint64_t
2498 dsl_get_compressratio(dsl_dataset_t *ds)
2499 {
2500         if (ds->ds_is_snapshot) {
2501                 return (dsl_get_refratio(ds));
2502         } else {
2503                 dsl_dir_t *dd = ds->ds_dir;
2504                 mutex_enter(&dd->dd_lock);
2505                 uint64_t val = dsl_dir_get_compressratio(dd);
2506                 mutex_exit(&dd->dd_lock);
2507                 return (val);
2508         }
2509 }
2510
2511 uint64_t
2512 dsl_get_used(dsl_dataset_t *ds)
2513 {
2514         if (ds->ds_is_snapshot) {
2515                 return (dsl_dataset_phys(ds)->ds_unique_bytes);
2516         } else {
2517                 dsl_dir_t *dd = ds->ds_dir;
2518                 mutex_enter(&dd->dd_lock);
2519                 uint64_t val = dsl_dir_get_used(dd);
2520                 mutex_exit(&dd->dd_lock);
2521                 return (val);
2522         }
2523 }
2524
2525 uint64_t
2526 dsl_get_creation(dsl_dataset_t *ds)
2527 {
2528         return (dsl_dataset_phys(ds)->ds_creation_time);
2529 }
2530
2531 uint64_t
2532 dsl_get_creationtxg(dsl_dataset_t *ds)
2533 {
2534         return (dsl_dataset_phys(ds)->ds_creation_txg);
2535 }
2536
2537 uint64_t
2538 dsl_get_refquota(dsl_dataset_t *ds)
2539 {
2540         return (ds->ds_quota);
2541 }
2542
2543 uint64_t
2544 dsl_get_refreservation(dsl_dataset_t *ds)
2545 {
2546         return (ds->ds_reserved);
2547 }
2548
2549 uint64_t
2550 dsl_get_guid(dsl_dataset_t *ds)
2551 {
2552         return (dsl_dataset_phys(ds)->ds_guid);
2553 }
2554
2555 uint64_t
2556 dsl_get_unique(dsl_dataset_t *ds)
2557 {
2558         return (dsl_dataset_phys(ds)->ds_unique_bytes);
2559 }
2560
2561 uint64_t
2562 dsl_get_objsetid(dsl_dataset_t *ds)
2563 {
2564         return (ds->ds_object);
2565 }
2566
2567 uint64_t
2568 dsl_get_userrefs(dsl_dataset_t *ds)
2569 {
2570         return (ds->ds_userrefs);
2571 }
2572
2573 uint64_t
2574 dsl_get_defer_destroy(dsl_dataset_t *ds)
2575 {
2576         return (DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2577 }
2578
2579 uint64_t
2580 dsl_get_referenced(dsl_dataset_t *ds)
2581 {
2582         return (dsl_dataset_phys(ds)->ds_referenced_bytes);
2583 }
2584
2585 uint64_t
2586 dsl_get_numclones(dsl_dataset_t *ds)
2587 {
2588         ASSERT(ds->ds_is_snapshot);
2589         return (dsl_dataset_phys(ds)->ds_num_children - 1);
2590 }
2591
2592 uint64_t
2593 dsl_get_inconsistent(dsl_dataset_t *ds)
2594 {
2595         return ((dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT) ?
2596             1 : 0);
2597 }
2598
2599 uint64_t
2600 dsl_get_redacted(dsl_dataset_t *ds)
2601 {
2602         return (dsl_dataset_feature_is_active(ds,
2603             SPA_FEATURE_REDACTED_DATASETS));
2604 }
2605
2606 uint64_t
2607 dsl_get_available(dsl_dataset_t *ds)
2608 {
2609         uint64_t refdbytes = dsl_get_referenced(ds);
2610         uint64_t availbytes = dsl_dir_space_available(ds->ds_dir,
2611             NULL, 0, TRUE);
2612         if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
2613                 availbytes +=
2614                     ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2615         }
2616         if (ds->ds_quota != 0) {
2617                 /*
2618                  * Adjust available bytes according to refquota
2619                  */
2620                 if (refdbytes < ds->ds_quota) {
2621                         availbytes = MIN(availbytes,
2622                             ds->ds_quota - refdbytes);
2623                 } else {
2624                         availbytes = 0;
2625                 }
2626         }
2627         return (availbytes);
2628 }
2629
2630 int
2631 dsl_get_written(dsl_dataset_t *ds, uint64_t *written)
2632 {
2633         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2634         dsl_dataset_t *prev;
2635         int err = dsl_dataset_hold_obj(dp,
2636             dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2637         if (err == 0) {
2638                 uint64_t comp, uncomp;
2639                 err = dsl_dataset_space_written(prev, ds, written,
2640                     &comp, &uncomp);
2641                 dsl_dataset_rele(prev, FTAG);
2642         }
2643         return (err);
2644 }
2645
2646 /*
2647  * 'snap' should be a buffer of size ZFS_MAX_DATASET_NAME_LEN.
2648  */
2649 int
2650 dsl_get_prev_snap(dsl_dataset_t *ds, char *snap)
2651 {
2652         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2653         if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
2654                 dsl_dataset_name(ds->ds_prev, snap);
2655                 return (0);
2656         } else {
2657                 return (ENOENT);
2658         }
2659 }
2660
2661 void
2662 dsl_get_redact_snaps(dsl_dataset_t *ds, nvlist_t *propval)
2663 {
2664         uint64_t nsnaps;
2665         uint64_t *snaps;
2666         if (dsl_dataset_get_uint64_array_feature(ds,
2667             SPA_FEATURE_REDACTED_DATASETS, &nsnaps, &snaps)) {
2668                 fnvlist_add_uint64_array(propval, ZPROP_VALUE, snaps,
2669                     nsnaps);
2670         }
2671 }
2672
2673 /*
2674  * Returns the mountpoint property and source for the given dataset in the value
2675  * and source buffers. The value buffer must be at least as large as MAXPATHLEN
2676  * and the source buffer as least as large a ZFS_MAX_DATASET_NAME_LEN.
2677  * Returns 0 on success and an error on failure.
2678  */
2679 int
2680 dsl_get_mountpoint(dsl_dataset_t *ds, const char *dsname, char *value,
2681     char *source)
2682 {
2683         int error;
2684         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2685
2686         /* Retrieve the mountpoint value stored in the zap object */
2687         error = dsl_prop_get_ds(ds, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT), 1,
2688             ZAP_MAXVALUELEN, value, source);
2689         if (error != 0) {
2690                 return (error);
2691         }
2692
2693         /*
2694          * Process the dsname and source to find the full mountpoint string.
2695          * Can be skipped for 'legacy' or 'none'.
2696          */
2697         if (value[0] == '/') {
2698                 char *buf = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
2699                 char *root = buf;
2700                 const char *relpath;
2701
2702                 /*
2703                  * If we inherit the mountpoint, even from a dataset
2704                  * with a received value, the source will be the path of
2705                  * the dataset we inherit from. If source is
2706                  * ZPROP_SOURCE_VAL_RECVD, the received value is not
2707                  * inherited.
2708                  */
2709                 if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2710                         relpath = "";
2711                 } else {
2712                         ASSERT0(strncmp(dsname, source, strlen(source)));
2713                         relpath = dsname + strlen(source);
2714                         if (relpath[0] == '/')
2715                                 relpath++;
2716                 }
2717
2718                 spa_altroot(dp->dp_spa, root, ZAP_MAXVALUELEN);
2719
2720                 /*
2721                  * Special case an alternate root of '/'. This will
2722                  * avoid having multiple leading slashes in the
2723                  * mountpoint path.
2724                  */
2725                 if (strcmp(root, "/") == 0)
2726                         root++;
2727
2728                 /*
2729                  * If the mountpoint is '/' then skip over this
2730                  * if we are obtaining either an alternate root or
2731                  * an inherited mountpoint.
2732                  */
2733                 char *mnt = value;
2734                 if (value[1] == '\0' && (root[0] != '\0' ||
2735                     relpath[0] != '\0'))
2736                         mnt = value + 1;
2737
2738                 if (relpath[0] == '\0') {
2739                         (void) snprintf(value, ZAP_MAXVALUELEN, "%s%s",
2740                             root, mnt);
2741                 } else {
2742                         (void) snprintf(value, ZAP_MAXVALUELEN, "%s%s%s%s",
2743                             root, mnt, relpath[0] == '@' ? "" : "/",
2744                             relpath);
2745                 }
2746                 kmem_free(buf, ZAP_MAXVALUELEN);
2747         }
2748
2749         return (0);
2750 }
2751
2752 void
2753 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2754 {
2755         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2756
2757         ASSERT(dsl_pool_config_held(dp));
2758
2759         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO,
2760             dsl_get_refratio(ds));
2761         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
2762             dsl_get_logicalreferenced(ds));
2763         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
2764             dsl_get_compressratio(ds));
2765         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2766             dsl_get_used(ds));
2767
2768         if (ds->ds_is_snapshot) {
2769                 get_clones_stat(ds, nv);
2770         } else {
2771                 char buf[ZFS_MAX_DATASET_NAME_LEN];
2772                 if (dsl_get_prev_snap(ds, buf) == 0)
2773                         dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP,
2774                             buf);
2775                 dsl_dir_stats(ds->ds_dir, nv);
2776         }
2777
2778         nvlist_t *propval = fnvlist_alloc();
2779         dsl_get_redact_snaps(ds, propval);
2780         fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS),
2781             propval);
2782         nvlist_free(propval);
2783
2784         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE,
2785             dsl_get_available(ds));
2786         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED,
2787             dsl_get_referenced(ds));
2788         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2789             dsl_get_creation(ds));
2790         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2791             dsl_get_creationtxg(ds));
2792         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2793             dsl_get_refquota(ds));
2794         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2795             dsl_get_refreservation(ds));
2796         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2797             dsl_get_guid(ds));
2798         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2799             dsl_get_unique(ds));
2800         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2801             dsl_get_objsetid(ds));
2802         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2803             dsl_get_userrefs(ds));
2804         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2805             dsl_get_defer_destroy(ds));
2806         dsl_dataset_crypt_stats(ds, nv);
2807
2808         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2809                 uint64_t written;
2810                 if (dsl_get_written(ds, &written) == 0) {
2811                         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2812                             written);
2813                 }
2814         }
2815
2816         if (!dsl_dataset_is_snapshot(ds)) {
2817                 /*
2818                  * A failed "newfs" (e.g. full) resumable receive leaves
2819                  * the stats set on this dataset.  Check here for the prop.
2820                  */
2821                 get_receive_resume_stats(ds, nv);
2822
2823                 /*
2824                  * A failed incremental resumable receive leaves the
2825                  * stats set on our child named "%recv".  Check the child
2826                  * for the prop.
2827                  */
2828                 /* 6 extra bytes for /%recv */
2829                 char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
2830                 dsl_dataset_t *recv_ds;
2831                 dsl_dataset_name(ds, recvname);
2832                 if (strlcat(recvname, "/", sizeof (recvname)) <
2833                     sizeof (recvname) &&
2834                     strlcat(recvname, recv_clone_name, sizeof (recvname)) <
2835                     sizeof (recvname) &&
2836                     dsl_dataset_hold(dp, recvname, FTAG, &recv_ds) == 0) {
2837                         get_receive_resume_stats(recv_ds, nv);
2838                         dsl_dataset_rele(recv_ds, FTAG);
2839                 }
2840         }
2841 }
2842
2843 void
2844 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2845 {
2846         ASSERTV(dsl_pool_t *dp = ds->ds_dir->dd_pool);
2847         ASSERT(dsl_pool_config_held(dp));
2848
2849         stat->dds_creation_txg = dsl_get_creationtxg(ds);
2850         stat->dds_inconsistent = dsl_get_inconsistent(ds);
2851         stat->dds_guid = dsl_get_guid(ds);
2852         stat->dds_redacted = dsl_get_redacted(ds);
2853         stat->dds_origin[0] = '\0';
2854         if (ds->ds_is_snapshot) {
2855                 stat->dds_is_snapshot = B_TRUE;
2856                 stat->dds_num_clones = dsl_get_numclones(ds);
2857         } else {
2858                 stat->dds_is_snapshot = B_FALSE;
2859                 stat->dds_num_clones = 0;
2860
2861                 if (dsl_dir_is_clone(ds->ds_dir)) {
2862                         dsl_dir_get_origin(ds->ds_dir, stat->dds_origin);
2863                 }
2864         }
2865 }
2866
2867 uint64_t
2868 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2869 {
2870         return (ds->ds_fsid_guid);
2871 }
2872
2873 void
2874 dsl_dataset_space(dsl_dataset_t *ds,
2875     uint64_t *refdbytesp, uint64_t *availbytesp,
2876     uint64_t *usedobjsp, uint64_t *availobjsp)
2877 {
2878         *refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
2879         *availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2880         if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
2881                 *availbytesp +=
2882                     ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2883         if (ds->ds_quota != 0) {
2884                 /*
2885                  * Adjust available bytes according to refquota
2886                  */
2887                 if (*refdbytesp < ds->ds_quota)
2888                         *availbytesp = MIN(*availbytesp,
2889                             ds->ds_quota - *refdbytesp);
2890                 else
2891                         *availbytesp = 0;
2892         }
2893         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2894         *usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
2895         rrw_exit(&ds->ds_bp_rwlock, FTAG);
2896         *availobjsp = DN_MAX_OBJECT - *usedobjsp;
2897 }
2898
2899 boolean_t
2900 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
2901 {
2902         ASSERTV(dsl_pool_t *dp = ds->ds_dir->dd_pool);
2903         uint64_t birth;
2904
2905         ASSERT(dsl_pool_config_held(dp));
2906         if (snap == NULL)
2907                 return (B_FALSE);
2908         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2909         birth = dsl_dataset_get_blkptr(ds)->blk_birth;
2910         rrw_exit(&ds->ds_bp_rwlock, FTAG);
2911         if (birth > dsl_dataset_phys(snap)->ds_creation_txg) {
2912                 objset_t *os, *os_snap;
2913                 /*
2914                  * It may be that only the ZIL differs, because it was
2915                  * reset in the head.  Don't count that as being
2916                  * modified.
2917                  */
2918                 if (dmu_objset_from_ds(ds, &os) != 0)
2919                         return (B_TRUE);
2920                 if (dmu_objset_from_ds(snap, &os_snap) != 0)
2921                         return (B_TRUE);
2922                 return (bcmp(&os->os_phys->os_meta_dnode,
2923                     &os_snap->os_phys->os_meta_dnode,
2924                     sizeof (os->os_phys->os_meta_dnode)) != 0);
2925         }
2926         return (B_FALSE);
2927 }
2928
2929 typedef struct dsl_dataset_rename_snapshot_arg {
2930         const char *ddrsa_fsname;
2931         const char *ddrsa_oldsnapname;
2932         const char *ddrsa_newsnapname;
2933         boolean_t ddrsa_recursive;
2934         dmu_tx_t *ddrsa_tx;
2935 } dsl_dataset_rename_snapshot_arg_t;
2936
2937 /* ARGSUSED */
2938 static int
2939 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
2940     dsl_dataset_t *hds, void *arg)
2941 {
2942         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2943         int error;
2944         uint64_t val;
2945
2946         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2947         if (error != 0) {
2948                 /* ignore nonexistent snapshots */
2949                 return (error == ENOENT ? 0 : error);
2950         }
2951
2952         /* new name should not exist */
2953         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
2954         if (error == 0)
2955                 error = SET_ERROR(EEXIST);
2956         else if (error == ENOENT)
2957                 error = 0;
2958
2959         /* dataset name + 1 for the "@" + the new snapshot name must fit */
2960         if (dsl_dir_namelen(hds->ds_dir) + 1 +
2961             strlen(ddrsa->ddrsa_newsnapname) >= ZFS_MAX_DATASET_NAME_LEN)
2962                 error = SET_ERROR(ENAMETOOLONG);
2963
2964         return (error);
2965 }
2966
2967 static int
2968 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
2969 {
2970         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2971         dsl_pool_t *dp = dmu_tx_pool(tx);
2972         dsl_dataset_t *hds;
2973         int error;
2974
2975         error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
2976         if (error != 0)
2977                 return (error);
2978
2979         if (ddrsa->ddrsa_recursive) {
2980                 error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
2981                     dsl_dataset_rename_snapshot_check_impl, ddrsa,
2982                     DS_FIND_CHILDREN);
2983         } else {
2984                 error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
2985         }
2986         dsl_dataset_rele(hds, FTAG);
2987         return (error);
2988 }
2989
2990 static int
2991 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
2992     dsl_dataset_t *hds, void *arg)
2993 {
2994         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2995         dsl_dataset_t *ds;
2996         uint64_t val;
2997         dmu_tx_t *tx = ddrsa->ddrsa_tx;
2998         int error;
2999
3000         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
3001         ASSERT(error == 0 || error == ENOENT);
3002         if (error == ENOENT) {
3003                 /* ignore nonexistent snapshots */
3004                 return (0);
3005         }
3006
3007         VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
3008
3009         /* log before we change the name */
3010         spa_history_log_internal_ds(ds, "rename", tx,
3011             "-> @%s", ddrsa->ddrsa_newsnapname);
3012
3013         VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
3014             B_FALSE));
3015         mutex_enter(&ds->ds_lock);
3016         (void) strlcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname,
3017             sizeof (ds->ds_snapname));
3018         mutex_exit(&ds->ds_lock);
3019         VERIFY0(zap_add(dp->dp_meta_objset,
3020             dsl_dataset_phys(hds)->ds_snapnames_zapobj,
3021             ds->ds_snapname, 8, 1, &ds->ds_object, tx));
3022         zvol_rename_minors(dp->dp_spa, ddrsa->ddrsa_oldsnapname,
3023             ddrsa->ddrsa_newsnapname, B_TRUE);
3024
3025         dsl_dataset_rele(ds, FTAG);
3026         return (0);
3027 }
3028
3029 static void
3030 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
3031 {
3032         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3033         dsl_pool_t *dp = dmu_tx_pool(tx);
3034         dsl_dataset_t *hds = NULL;
3035
3036         VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
3037         ddrsa->ddrsa_tx = tx;
3038         if (ddrsa->ddrsa_recursive) {
3039                 VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3040                     dsl_dataset_rename_snapshot_sync_impl, ddrsa,
3041                     DS_FIND_CHILDREN));
3042         } else {
3043                 VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
3044         }
3045         dsl_dataset_rele(hds, FTAG);
3046 }
3047
3048 int
3049 dsl_dataset_rename_snapshot(const char *fsname,
3050     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
3051 {
3052         dsl_dataset_rename_snapshot_arg_t ddrsa;
3053
3054         ddrsa.ddrsa_fsname = fsname;
3055         ddrsa.ddrsa_oldsnapname = oldsnapname;
3056         ddrsa.ddrsa_newsnapname = newsnapname;
3057         ddrsa.ddrsa_recursive = recursive;
3058
3059         return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
3060             dsl_dataset_rename_snapshot_sync, &ddrsa,
3061             1, ZFS_SPACE_CHECK_RESERVED));
3062 }
3063
3064 /*
3065  * If we're doing an ownership handoff, we need to make sure that there is
3066  * only one long hold on the dataset.  We're not allowed to change anything here
3067  * so we don't permanently release the long hold or regular hold here.  We want
3068  * to do this only when syncing to avoid the dataset unexpectedly going away
3069  * when we release the long hold.
3070  */
3071 static int
3072 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
3073 {
3074         boolean_t held;
3075
3076         if (!dmu_tx_is_syncing(tx))
3077                 return (0);
3078
3079         if (owner != NULL) {
3080                 VERIFY3P(ds->ds_owner, ==, owner);
3081                 dsl_dataset_long_rele(ds, owner);
3082         }
3083
3084         held = dsl_dataset_long_held(ds);
3085
3086         if (owner != NULL)
3087                 dsl_dataset_long_hold(ds, owner);
3088
3089         if (held)
3090                 return (SET_ERROR(EBUSY));
3091
3092         return (0);
3093 }
3094
3095 int
3096 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
3097 {
3098         dsl_dataset_rollback_arg_t *ddra = arg;
3099         dsl_pool_t *dp = dmu_tx_pool(tx);
3100         dsl_dataset_t *ds;
3101         int64_t unused_refres_delta;
3102         int error;
3103
3104         error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
3105         if (error != 0)
3106                 return (error);
3107
3108         /* must not be a snapshot */
3109         if (ds->ds_is_snapshot) {
3110                 dsl_dataset_rele(ds, FTAG);
3111                 return (SET_ERROR(EINVAL));
3112         }
3113
3114         /* must have a most recent snapshot */
3115         if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
3116                 dsl_dataset_rele(ds, FTAG);
3117                 return (SET_ERROR(ESRCH));
3118         }
3119
3120         /*
3121          * No rollback to a snapshot created in the current txg, because
3122          * the rollback may dirty the dataset and create blocks that are
3123          * not reachable from the rootbp while having a birth txg that
3124          * falls into the snapshot's range.
3125          */
3126         if (dmu_tx_is_syncing(tx) &&
3127             dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg) {
3128                 dsl_dataset_rele(ds, FTAG);
3129                 return (SET_ERROR(EAGAIN));
3130         }
3131
3132         /*
3133          * If the expected target snapshot is specified, then check that
3134          * the latest snapshot is it.
3135          */
3136         if (ddra->ddra_tosnap != NULL) {
3137                 dsl_dataset_t *snapds;
3138
3139                 /* Check if the target snapshot exists at all. */
3140                 error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
3141                 if (error != 0) {
3142                         /*
3143                          * ESRCH is used to signal that the target snapshot does
3144                          * not exist, while ENOENT is used to report that
3145                          * the rolled back dataset does not exist.
3146                          * ESRCH is also used to cover other cases where the
3147                          * target snapshot is not related to the dataset being
3148                          * rolled back such as being in a different pool.
3149                          */
3150                         if (error == ENOENT || error == EXDEV)
3151                                 error = SET_ERROR(ESRCH);
3152                         dsl_dataset_rele(ds, FTAG);
3153                         return (error);
3154                 }
3155                 ASSERT(snapds->ds_is_snapshot);
3156
3157                 /* Check if the snapshot is the latest snapshot indeed. */
3158                 if (snapds != ds->ds_prev) {
3159                         /*
3160                          * Distinguish between the case where the only problem
3161                          * is intervening snapshots (EEXIST) vs the snapshot
3162                          * not being a valid target for rollback (ESRCH).
3163                          */
3164                         if (snapds->ds_dir == ds->ds_dir ||
3165                             (dsl_dir_is_clone(ds->ds_dir) &&
3166                             dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
3167                             snapds->ds_object)) {
3168                                 error = SET_ERROR(EEXIST);
3169                         } else {
3170                                 error = SET_ERROR(ESRCH);
3171                         }
3172                         dsl_dataset_rele(snapds, FTAG);
3173                         dsl_dataset_rele(ds, FTAG);
3174                         return (error);
3175                 }
3176                 dsl_dataset_rele(snapds, FTAG);
3177         }
3178
3179         /* must not have any bookmarks after the most recent snapshot */
3180         if (dsl_bookmark_latest_txg(ds) >
3181             dsl_dataset_phys(ds)->ds_prev_snap_txg) {
3182                 dsl_dataset_rele(ds, FTAG);
3183                 return (SET_ERROR(EEXIST));
3184         }
3185
3186         error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
3187         if (error != 0) {
3188                 dsl_dataset_rele(ds, FTAG);
3189                 return (error);
3190         }
3191
3192         /*
3193          * Check if the snap we are rolling back to uses more than
3194          * the refquota.
3195          */
3196         if (ds->ds_quota != 0 &&
3197             dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
3198                 dsl_dataset_rele(ds, FTAG);
3199                 return (SET_ERROR(EDQUOT));
3200         }
3201
3202         /*
3203          * When we do the clone swap, we will temporarily use more space
3204          * due to the refreservation (the head will no longer have any
3205          * unique space, so the entire amount of the refreservation will need
3206          * to be free).  We will immediately destroy the clone, freeing
3207          * this space, but the freeing happens over many txg's.
3208          */
3209         unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
3210             dsl_dataset_phys(ds)->ds_unique_bytes);
3211
3212         if (unused_refres_delta > 0 &&
3213             unused_refres_delta >
3214             dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
3215                 dsl_dataset_rele(ds, FTAG);
3216                 return (SET_ERROR(ENOSPC));
3217         }
3218
3219         dsl_dataset_rele(ds, FTAG);
3220         return (0);
3221 }
3222
3223 void
3224 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
3225 {
3226         dsl_dataset_rollback_arg_t *ddra = arg;
3227         dsl_pool_t *dp = dmu_tx_pool(tx);
3228         dsl_dataset_t *ds, *clone;
3229         uint64_t cloneobj;
3230         char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3231
3232         VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
3233
3234         dsl_dataset_name(ds->ds_prev, namebuf);
3235         fnvlist_add_string(ddra->ddra_result, "target", namebuf);
3236
3237         cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
3238             ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, NULL, tx);
3239
3240         VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
3241
3242         dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
3243         dsl_dataset_zero_zil(ds, tx);
3244
3245         dsl_destroy_head_sync_impl(clone, tx);
3246
3247         dsl_dataset_rele(clone, FTAG);
3248         dsl_dataset_rele(ds, FTAG);
3249 }
3250
3251 /*
3252  * Rolls back the given filesystem or volume to the most recent snapshot.
3253  * The name of the most recent snapshot will be returned under key "target"
3254  * in the result nvlist.
3255  *
3256  * If owner != NULL:
3257  * - The existing dataset MUST be owned by the specified owner at entry
3258  * - Upon return, dataset will still be held by the same owner, whether we
3259  *   succeed or not.
3260  *
3261  * This mode is required any time the existing filesystem is mounted.  See
3262  * notes above zfs_suspend_fs() for further details.
3263  */
3264 int
3265 dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
3266     nvlist_t *result)
3267 {
3268         dsl_dataset_rollback_arg_t ddra;
3269
3270         ddra.ddra_fsname = fsname;
3271         ddra.ddra_tosnap = tosnap;
3272         ddra.ddra_owner = owner;
3273         ddra.ddra_result = result;
3274
3275         return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
3276             dsl_dataset_rollback_sync, &ddra,
3277             1, ZFS_SPACE_CHECK_RESERVED));
3278 }
3279
3280 struct promotenode {
3281         list_node_t link;
3282         dsl_dataset_t *ds;
3283 };
3284
3285 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
3286 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
3287     void *tag);
3288 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
3289
3290 int
3291 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
3292 {
3293         dsl_dataset_promote_arg_t *ddpa = arg;
3294         dsl_pool_t *dp = dmu_tx_pool(tx);
3295         dsl_dataset_t *hds;
3296         struct promotenode *snap;
3297         dsl_dataset_t *origin_ds, *origin_head;
3298         int err;
3299         uint64_t unused;
3300         uint64_t ss_mv_cnt;
3301         size_t max_snap_len;
3302         boolean_t conflicting_snaps;
3303
3304         err = promote_hold(ddpa, dp, FTAG);
3305         if (err != 0)
3306                 return (err);
3307
3308         hds = ddpa->ddpa_clone;
3309         max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
3310
3311         if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
3312                 promote_rele(ddpa, FTAG);
3313                 return (SET_ERROR(EXDEV));
3314         }
3315
3316         snap = list_head(&ddpa->shared_snaps);
3317         origin_head = snap->ds;
3318         if (snap == NULL) {
3319                 err = SET_ERROR(ENOENT);
3320                 goto out;
3321         }
3322         origin_ds = snap->ds;
3323
3324         /*
3325          * Encrypted clones share a DSL Crypto Key with their origin's dsl dir.
3326          * When doing a promote we must make sure the encryption root for
3327          * both the target and the target's origin does not change to avoid
3328          * needing to rewrap encryption keys
3329          */
3330         err = dsl_dataset_promote_crypt_check(hds->ds_dir, origin_ds->ds_dir);
3331         if (err != 0)
3332                 goto out;
3333
3334         /*
3335          * Compute and check the amount of space to transfer.  Since this is
3336          * so expensive, don't do the preliminary check.
3337          */
3338         if (!dmu_tx_is_syncing(tx)) {
3339                 promote_rele(ddpa, FTAG);
3340                 return (0);
3341         }
3342
3343         /* compute origin's new unique space */
3344         snap = list_tail(&ddpa->clone_snaps);
3345         ASSERT(snap != NULL);
3346         ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3347             origin_ds->ds_object);
3348         dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3349             dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
3350             &ddpa->unique, &unused, &unused);
3351
3352         /*
3353          * Walk the snapshots that we are moving
3354          *
3355          * Compute space to transfer.  Consider the incremental changes
3356          * to used by each snapshot:
3357          * (my used) = (prev's used) + (blocks born) - (blocks killed)
3358          * So each snapshot gave birth to:
3359          * (blocks born) = (my used) - (prev's used) + (blocks killed)
3360          * So a sequence would look like:
3361          * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
3362          * Which simplifies to:
3363          * uN + kN + kN-1 + ... + k1 + k0
3364          * Note however, if we stop before we reach the ORIGIN we get:
3365          * uN + kN + kN-1 + ... + kM - uM-1
3366          */
3367         conflicting_snaps = B_FALSE;
3368         ss_mv_cnt = 0;
3369         ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
3370         ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
3371         ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
3372         for (snap = list_head(&ddpa->shared_snaps); snap;
3373             snap = list_next(&ddpa->shared_snaps, snap)) {
3374                 uint64_t val, dlused, dlcomp, dluncomp;
3375                 dsl_dataset_t *ds = snap->ds;
3376
3377                 ss_mv_cnt++;
3378
3379                 /*
3380                  * If there are long holds, we won't be able to evict
3381                  * the objset.
3382                  */
3383                 if (dsl_dataset_long_held(ds)) {
3384                         err = SET_ERROR(EBUSY);
3385                         goto out;
3386                 }
3387
3388                 /* Check that the snapshot name does not conflict */
3389                 VERIFY0(dsl_dataset_get_snapname(ds));
3390                 if (strlen(ds->ds_snapname) >= max_snap_len) {
3391                         err = SET_ERROR(ENAMETOOLONG);
3392                         goto out;
3393                 }
3394                 err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
3395                 if (err == 0) {
3396                         fnvlist_add_boolean(ddpa->err_ds,
3397                             snap->ds->ds_snapname);
3398                         conflicting_snaps = B_TRUE;
3399                 } else if (err != ENOENT) {
3400                         goto out;
3401                 }
3402
3403                 /* The very first snapshot does not have a deadlist */
3404                 if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
3405                         continue;
3406
3407                 dsl_deadlist_space(&ds->ds_deadlist,
3408                     &dlused, &dlcomp, &dluncomp);
3409                 ddpa->used += dlused;
3410                 ddpa->comp += dlcomp;
3411                 ddpa->uncomp += dluncomp;
3412         }
3413
3414         /*
3415          * Check that bookmarks that are being transferred don't have
3416          * name conflicts.
3417          */
3418         for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3419             dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3420             dsl_dataset_phys(origin_ds)->ds_creation_txg;
3421             dbn = AVL_NEXT(&origin_head->ds_bookmarks, dbn)) {
3422                 if (strlen(dbn->dbn_name) >= max_snap_len) {
3423                         err = SET_ERROR(ENAMETOOLONG);
3424                         goto out;
3425                 }
3426                 zfs_bookmark_phys_t bm;
3427                 err = dsl_bookmark_lookup_impl(ddpa->ddpa_clone,
3428                     dbn->dbn_name, &bm);
3429
3430                 if (err == 0) {
3431                         fnvlist_add_boolean(ddpa->err_ds, dbn->dbn_name);
3432                         conflicting_snaps = B_TRUE;
3433                 } else if (err == ESRCH) {
3434                         err = 0;
3435                 } else if (err != 0) {
3436                         goto out;
3437                 }
3438         }
3439
3440         /*
3441          * In order to return the full list of conflicting snapshots, we check
3442          * whether there was a conflict after traversing all of them.
3443          */
3444         if (conflicting_snaps) {
3445                 err = SET_ERROR(EEXIST);
3446                 goto out;
3447         }
3448
3449         /*
3450          * If we are a clone of a clone then we never reached ORIGIN,
3451          * so we need to subtract out the clone origin's used space.
3452          */
3453         if (ddpa->origin_origin) {
3454                 ddpa->used -=
3455                     dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
3456                 ddpa->comp -=
3457                     dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
3458                 ddpa->uncomp -=
3459                     dsl_dataset_phys(ddpa->origin_origin)->
3460                     ds_uncompressed_bytes;
3461         }
3462
3463         /* Check that there is enough space and limit headroom here */
3464         err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
3465             0, ss_mv_cnt, ddpa->used, ddpa->cr);
3466         if (err != 0)
3467                 goto out;
3468
3469         /*
3470          * Compute the amounts of space that will be used by snapshots
3471          * after the promotion (for both origin and clone).  For each,
3472          * it is the amount of space that will be on all of their
3473          * deadlists (that was not born before their new origin).
3474          */
3475         if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
3476                 uint64_t space;
3477
3478                 /*
3479                  * Note, typically this will not be a clone of a clone,
3480                  * so dd_origin_txg will be < TXG_INITIAL, so
3481                  * these snaplist_space() -> dsl_deadlist_space_range()
3482                  * calls will be fast because they do not have to
3483                  * iterate over all bps.
3484                  */
3485                 snap = list_head(&ddpa->origin_snaps);
3486                 if (snap == NULL) {
3487                         err = SET_ERROR(ENOENT);
3488                         goto out;
3489                 }
3490                 err = snaplist_space(&ddpa->shared_snaps,
3491                     snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
3492                 if (err != 0)
3493                         goto out;
3494
3495                 err = snaplist_space(&ddpa->clone_snaps,
3496                     snap->ds->ds_dir->dd_origin_txg, &space);
3497                 if (err != 0)
3498                         goto out;
3499                 ddpa->cloneusedsnap += space;
3500         }
3501         if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
3502             DD_FLAG_USED_BREAKDOWN) {
3503                 err = snaplist_space(&ddpa->origin_snaps,
3504                     dsl_dataset_phys(origin_ds)->ds_creation_txg,
3505                     &ddpa->originusedsnap);
3506                 if (err != 0)
3507                         goto out;
3508         }
3509
3510 out:
3511         promote_rele(ddpa, FTAG);
3512         return (err);
3513 }
3514
3515 void
3516 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
3517 {
3518         dsl_dataset_promote_arg_t *ddpa = arg;
3519         dsl_pool_t *dp = dmu_tx_pool(tx);
3520         dsl_dataset_t *hds;
3521         struct promotenode *snap;
3522         dsl_dataset_t *origin_ds;
3523         dsl_dataset_t *origin_head;
3524         dsl_dir_t *dd;
3525         dsl_dir_t *odd = NULL;
3526         uint64_t oldnext_obj;
3527         int64_t delta;
3528
3529         ASSERT(nvlist_empty(ddpa->err_ds));
3530
3531         VERIFY0(promote_hold(ddpa, dp, FTAG));
3532         hds = ddpa->ddpa_clone;
3533
3534         ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
3535
3536         snap = list_head(&ddpa->shared_snaps);
3537         origin_ds = snap->ds;
3538         dd = hds->ds_dir;
3539
3540         snap = list_head(&ddpa->origin_snaps);
3541         origin_head = snap->ds;
3542
3543         /*
3544          * We need to explicitly open odd, since origin_ds's dd will be
3545          * changing.
3546          */
3547         VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
3548             NULL, FTAG, &odd));
3549
3550         dsl_dataset_promote_crypt_sync(hds->ds_dir, odd, tx);
3551
3552         /* change origin's next snap */
3553         dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
3554         oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
3555         snap = list_tail(&ddpa->clone_snaps);
3556         ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3557             origin_ds->ds_object);
3558         dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
3559
3560         /* change the origin's next clone */
3561         if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
3562                 dsl_dataset_remove_from_next_clones(origin_ds,
3563                     snap->ds->ds_object, tx);
3564                 VERIFY0(zap_add_int(dp->dp_meta_objset,
3565                     dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
3566                     oldnext_obj, tx));
3567         }
3568
3569         /* change origin */
3570         dmu_buf_will_dirty(dd->dd_dbuf, tx);
3571         ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
3572         dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
3573         dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
3574         dmu_buf_will_dirty(odd->dd_dbuf, tx);
3575         dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
3576         origin_head->ds_dir->dd_origin_txg =
3577             dsl_dataset_phys(origin_ds)->ds_creation_txg;
3578
3579         /* change dd_clone entries */
3580         if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3581                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
3582                     dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
3583                 VERIFY0(zap_add_int(dp->dp_meta_objset,
3584                     dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3585                     hds->ds_object, tx));
3586
3587                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
3588                     dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3589                     origin_head->ds_object, tx));
3590                 if (dsl_dir_phys(dd)->dd_clones == 0) {
3591                         dsl_dir_phys(dd)->dd_clones =
3592                             zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
3593                             DMU_OT_NONE, 0, tx);
3594                 }
3595                 VERIFY0(zap_add_int(dp->dp_meta_objset,
3596                     dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
3597         }
3598
3599         /*
3600          * Move bookmarks to this dir.
3601          */
3602         dsl_bookmark_node_t *dbn_next;
3603         for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3604             dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3605             dsl_dataset_phys(origin_ds)->ds_creation_txg;
3606             dbn = dbn_next) {
3607                 dbn_next = AVL_NEXT(&origin_head->ds_bookmarks, dbn);
3608
3609                 avl_remove(&origin_head->ds_bookmarks, dbn);
3610                 VERIFY0(zap_remove(dp->dp_meta_objset,
3611                     origin_head->ds_bookmarks_obj, dbn->dbn_name, tx));
3612
3613                 dsl_bookmark_node_add(hds, dbn, tx);
3614         }
3615
3616         dsl_bookmark_next_changed(hds, origin_ds, tx);
3617
3618         /* move snapshots to this dir */
3619         for (snap = list_head(&ddpa->shared_snaps); snap;
3620             snap = list_next(&ddpa->shared_snaps, snap)) {
3621                 dsl_dataset_t *ds = snap->ds;
3622
3623                 /*
3624                  * Property callbacks are registered to a particular
3625                  * dsl_dir.  Since ours is changing, evict the objset
3626                  * so that they will be unregistered from the old dsl_dir.
3627                  */
3628                 if (ds->ds_objset) {
3629                         dmu_objset_evict(ds->ds_objset);
3630                         ds->ds_objset = NULL;
3631                 }
3632
3633                 /* move snap name entry */
3634                 VERIFY0(dsl_dataset_get_snapname(ds));
3635                 VERIFY0(dsl_dataset_snap_remove(origin_head,
3636                     ds->ds_snapname, tx, B_TRUE));
3637                 VERIFY0(zap_add(dp->dp_meta_objset,
3638                     dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3639                     8, 1, &ds->ds_object, tx));
3640                 dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3641                     DD_FIELD_SNAPSHOT_COUNT, tx);
3642
3643                 /* change containing dsl_dir */
3644                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3645                 ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3646                 dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3647                 ASSERT3P(ds->ds_dir, ==, odd);
3648                 dsl_dir_rele(ds->ds_dir, ds);
3649                 VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3650                     NULL, ds, &ds->ds_dir));
3651
3652                 /* move any clone references */
3653                 if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3654                     spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3655                         zap_cursor_t zc;
3656                         zap_attribute_t za;
3657
3658                         for (zap_cursor_init(&zc, dp->dp_meta_objset,
3659                             dsl_dataset_phys(ds)->ds_next_clones_obj);
3660                             zap_cursor_retrieve(&zc, &za) == 0;
3661                             zap_cursor_advance(&zc)) {
3662                                 dsl_dataset_t *cnds;
3663                                 uint64_t o;
3664
3665                                 if (za.za_first_integer == oldnext_obj) {
3666                                         /*
3667                                          * We've already moved the
3668                                          * origin's reference.
3669                                          */
3670                                         continue;
3671                                 }
3672
3673                                 VERIFY0(dsl_dataset_hold_obj(dp,
3674                                     za.za_first_integer, FTAG, &cnds));
3675                                 o = dsl_dir_phys(cnds->ds_dir)->
3676                                     dd_head_dataset_obj;
3677
3678                                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
3679                                     dsl_dir_phys(odd)->dd_clones, o, tx));
3680                                 VERIFY0(zap_add_int(dp->dp_meta_objset,
3681                                     dsl_dir_phys(dd)->dd_clones, o, tx));
3682                                 dsl_dataset_rele(cnds, FTAG);
3683                         }
3684                         zap_cursor_fini(&zc);
3685                 }
3686
3687                 ASSERT(!dsl_prop_hascb(ds));
3688         }
3689
3690         /*
3691          * Change space accounting.
3692          * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3693          * both be valid, or both be 0 (resulting in delta == 0).  This
3694          * is true for each of {clone,origin} independently.
3695          */
3696
3697         delta = ddpa->cloneusedsnap -
3698             dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3699         ASSERT3S(delta, >=, 0);
3700         ASSERT3U(ddpa->used, >=, delta);
3701         dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3702         dsl_dir_diduse_space(dd, DD_USED_HEAD,
3703             ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3704
3705         delta = ddpa->originusedsnap -
3706             dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3707         ASSERT3S(delta, <=, 0);
3708         ASSERT3U(ddpa->used, >=, -delta);
3709         dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3710         dsl_dir_diduse_space(odd, DD_USED_HEAD,
3711             -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3712
3713         dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3714
3715         /*
3716          * Since livelists are specific to a clone's origin txg, they
3717          * are no longer accurate. Destroy the livelist from the clone being
3718          * promoted. If the origin dataset is a clone, destroy its livelist
3719          * as well.
3720          */
3721         dsl_dir_remove_livelist(dd, tx, B_TRUE);
3722         dsl_dir_remove_livelist(origin_ds->ds_dir, tx, B_TRUE);
3723
3724         /* log history record */
3725         spa_history_log_internal_ds(hds, "promote", tx, " ");
3726
3727         dsl_dir_rele(odd, FTAG);
3728         promote_rele(ddpa, FTAG);
3729 }
3730
3731 /*
3732  * Make a list of dsl_dataset_t's for the snapshots between first_obj
3733  * (exclusive) and last_obj (inclusive).  The list will be in reverse
3734  * order (last_obj will be the list_head()).  If first_obj == 0, do all
3735  * snapshots back to this dataset's origin.
3736  */
3737 static int
3738 snaplist_make(dsl_pool_t *dp,
3739     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
3740 {
3741         uint64_t obj = last_obj;
3742
3743         list_create(l, sizeof (struct promotenode),
3744             offsetof(struct promotenode, link));
3745
3746         while (obj != first_obj) {
3747                 dsl_dataset_t *ds;
3748                 struct promotenode *snap;
3749                 int err;
3750
3751                 err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3752                 ASSERT(err != ENOENT);
3753                 if (err != 0)
3754                         return (err);
3755
3756                 if (first_obj == 0)
3757                         first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3758
3759                 snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3760                 snap->ds = ds;
3761                 list_insert_tail(l, snap);
3762                 obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3763         }
3764
3765         return (0);
3766 }
3767
3768 static int
3769 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3770 {
3771         struct promotenode *snap;
3772
3773         *spacep = 0;
3774         for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3775                 uint64_t used, comp, uncomp;
3776                 dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3777                     mintxg, UINT64_MAX, &used, &comp, &uncomp);
3778                 *spacep += used;
3779         }
3780         return (0);
3781 }
3782
3783 static void
3784 snaplist_destroy(list_t *l, void *tag)
3785 {
3786         struct promotenode *snap;
3787
3788         if (l == NULL || !list_link_active(&l->list_head))
3789                 return;
3790
3791         while ((snap = list_tail(l)) != NULL) {
3792                 list_remove(l, snap);
3793                 dsl_dataset_rele(snap->ds, tag);
3794                 kmem_free(snap, sizeof (*snap));
3795         }
3796         list_destroy(l);
3797 }
3798
3799 static int
3800 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
3801 {
3802         int error;
3803         dsl_dir_t *dd;
3804         struct promotenode *snap;
3805
3806         error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3807             &ddpa->ddpa_clone);
3808         if (error != 0)
3809                 return (error);
3810         dd = ddpa->ddpa_clone->ds_dir;
3811
3812         if (ddpa->ddpa_clone->ds_is_snapshot ||
3813             !dsl_dir_is_clone(dd)) {
3814                 dsl_dataset_rele(ddpa->ddpa_clone, tag);
3815                 return (SET_ERROR(EINVAL));
3816         }
3817
3818         error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3819             &ddpa->shared_snaps, tag);
3820         if (error != 0)
3821                 goto out;
3822
3823         error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3824             &ddpa->clone_snaps, tag);
3825         if (error != 0)
3826                 goto out;
3827
3828         snap = list_head(&ddpa->shared_snaps);
3829         ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3830         error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3831             dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3832             &ddpa->origin_snaps, tag);
3833         if (error != 0)
3834                 goto out;
3835
3836         if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3837                 error = dsl_dataset_hold_obj(dp,
3838                     dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
3839                     tag, &ddpa->origin_origin);
3840                 if (error != 0)
3841                         goto out;
3842         }
3843 out:
3844         if (error != 0)
3845                 promote_rele(ddpa, tag);
3846         return (error);
3847 }
3848
3849 static void
3850 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
3851 {
3852         snaplist_destroy(&ddpa->shared_snaps, tag);
3853         snaplist_destroy(&ddpa->clone_snaps, tag);
3854         snaplist_destroy(&ddpa->origin_snaps, tag);
3855         if (ddpa->origin_origin != NULL)
3856                 dsl_dataset_rele(ddpa->origin_origin, tag);
3857         dsl_dataset_rele(ddpa->ddpa_clone, tag);
3858 }
3859
3860 /*
3861  * Promote a clone.
3862  *
3863  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
3864  * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
3865  */
3866 int
3867 dsl_dataset_promote(const char *name, char *conflsnap)
3868 {
3869         dsl_dataset_promote_arg_t ddpa = { 0 };
3870         uint64_t numsnaps;
3871         int error;
3872         nvpair_t *snap_pair;
3873         objset_t *os;
3874
3875         /*
3876          * We will modify space proportional to the number of
3877          * snapshots.  Compute numsnaps.
3878          */
3879         error = dmu_objset_hold(name, FTAG, &os);
3880         if (error != 0)
3881                 return (error);
3882         error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
3883             dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
3884             &numsnaps);
3885         dmu_objset_rele(os, FTAG);
3886         if (error != 0)
3887                 return (error);
3888
3889         ddpa.ddpa_clonename = name;
3890         ddpa.err_ds = fnvlist_alloc();
3891         ddpa.cr = CRED();
3892
3893         error = dsl_sync_task(name, dsl_dataset_promote_check,
3894             dsl_dataset_promote_sync, &ddpa,
3895             2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
3896
3897         /*
3898          * Return the first conflicting snapshot found.
3899          */
3900         snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
3901         if (snap_pair != NULL && conflsnap != NULL)
3902                 (void) strcpy(conflsnap, nvpair_name(snap_pair));
3903
3904         fnvlist_free(ddpa.err_ds);
3905         return (error);
3906 }
3907
3908 int
3909 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
3910     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
3911 {
3912         /*
3913          * "slack" factor for received datasets with refquota set on them.
3914          * See the bottom of this function for details on its use.
3915          */
3916         uint64_t refquota_slack = (uint64_t)DMU_MAX_ACCESS *
3917             spa_asize_inflation;
3918         int64_t unused_refres_delta;
3919
3920         /* they should both be heads */
3921         if (clone->ds_is_snapshot ||
3922             origin_head->ds_is_snapshot)
3923                 return (SET_ERROR(EINVAL));
3924
3925         /* if we are not forcing, the branch point should be just before them */
3926         if (!force && clone->ds_prev != origin_head->ds_prev)
3927                 return (SET_ERROR(EINVAL));
3928
3929         /* clone should be the clone (unless they are unrelated) */
3930         if (clone->ds_prev != NULL &&
3931             clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
3932             origin_head->ds_dir != clone->ds_prev->ds_dir)
3933                 return (SET_ERROR(EINVAL));
3934
3935         /* the clone should be a child of the origin */
3936         if (clone->ds_dir->dd_parent != origin_head->ds_dir)
3937                 return (SET_ERROR(EINVAL));
3938
3939         /* origin_head shouldn't be modified unless 'force' */
3940         if (!force &&
3941             dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
3942                 return (SET_ERROR(ETXTBSY));
3943
3944         /* origin_head should have no long holds (e.g. is not mounted) */
3945         if (dsl_dataset_handoff_check(origin_head, owner, tx))
3946                 return (SET_ERROR(EBUSY));
3947
3948         /* check amount of any unconsumed refreservation */
3949         unused_refres_delta =
3950             (int64_t)MIN(origin_head->ds_reserved,
3951             dsl_dataset_phys(origin_head)->ds_unique_bytes) -
3952             (int64_t)MIN(origin_head->ds_reserved,
3953             dsl_dataset_phys(clone)->ds_unique_bytes);
3954
3955         if (unused_refres_delta > 0 &&
3956             unused_refres_delta >
3957             dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
3958                 return (SET_ERROR(ENOSPC));
3959
3960         /*
3961          * The clone can't be too much over the head's refquota.
3962          *
3963          * To ensure that the entire refquota can be used, we allow one
3964          * transaction to exceed the refquota.  Therefore, this check
3965          * needs to also allow for the space referenced to be more than the
3966          * refquota.  The maximum amount of space that one transaction can use
3967          * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
3968          * overage ensures that we are able to receive a filesystem that
3969          * exceeds the refquota on the source system.
3970          *
3971          * So that overage is the refquota_slack we use below.
3972          */
3973         if (origin_head->ds_quota != 0 &&
3974             dsl_dataset_phys(clone)->ds_referenced_bytes >
3975             origin_head->ds_quota + refquota_slack)
3976                 return (SET_ERROR(EDQUOT));
3977
3978         return (0);
3979 }
3980
3981 static void
3982 dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
3983     dsl_dataset_t *origin, dmu_tx_t *tx)
3984 {
3985         uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
3986         dsl_pool_t *dp = dmu_tx_pool(tx);
3987
3988         ASSERT(dsl_pool_sync_context(dp));
3989
3990         clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
3991         origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
3992
3993         if (clone_remap_dl_obj != 0) {
3994                 dsl_deadlist_close(&clone->ds_remap_deadlist);
3995                 dsl_dataset_unset_remap_deadlist_object(clone, tx);
3996         }
3997         if (origin_remap_dl_obj != 0) {
3998                 dsl_deadlist_close(&origin->ds_remap_deadlist);
3999                 dsl_dataset_unset_remap_deadlist_object(origin, tx);
4000         }
4001
4002         if (clone_remap_dl_obj != 0) {
4003                 dsl_dataset_set_remap_deadlist_object(origin,
4004                     clone_remap_dl_obj, tx);
4005                 dsl_deadlist_open(&origin->ds_remap_deadlist,
4006                     dp->dp_meta_objset, clone_remap_dl_obj);
4007         }
4008         if (origin_remap_dl_obj != 0) {
4009                 dsl_dataset_set_remap_deadlist_object(clone,
4010                     origin_remap_dl_obj, tx);
4011                 dsl_deadlist_open(&clone->ds_remap_deadlist,
4012                     dp->dp_meta_objset, origin_remap_dl_obj);
4013         }
4014 }
4015
4016 void
4017 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
4018     dsl_dataset_t *origin_head, dmu_tx_t *tx)
4019 {
4020         dsl_pool_t *dp = dmu_tx_pool(tx);
4021         int64_t unused_refres_delta;
4022
4023         ASSERT(clone->ds_reserved == 0);
4024         /*
4025          * NOTE: On DEBUG kernels there could be a race between this and
4026          * the check function if spa_asize_inflation is adjusted...
4027          */
4028         ASSERT(origin_head->ds_quota == 0 ||
4029             dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
4030             DMU_MAX_ACCESS * spa_asize_inflation);
4031         ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
4032
4033         /*
4034          * Swap per-dataset feature flags.
4035          */
4036         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4037                 if (!(spa_feature_table[f].fi_flags &
4038                     ZFEATURE_FLAG_PER_DATASET)) {
4039                         ASSERT(!dsl_dataset_feature_is_active(clone, f));
4040                         ASSERT(!dsl_dataset_feature_is_active(origin_head, f));
4041                         continue;
4042                 }
4043
4044                 boolean_t clone_inuse = dsl_dataset_feature_is_active(clone, f);
4045                 void *clone_feature = clone->ds_feature[f];
4046                 boolean_t origin_head_inuse =
4047                     dsl_dataset_feature_is_active(origin_head, f);
4048                 void *origin_head_feature = origin_head->ds_feature[f];
4049
4050                 if (clone_inuse)
4051                         dsl_dataset_deactivate_feature_impl(clone, f, tx);
4052                 if (origin_head_inuse)
4053                         dsl_dataset_deactivate_feature_impl(origin_head, f, tx);
4054
4055                 if (clone_inuse) {
4056                         dsl_dataset_activate_feature(origin_head->ds_object, f,
4057                             clone_feature, tx);
4058                         origin_head->ds_feature[f] = clone_feature;
4059                 }
4060                 if (origin_head_inuse) {
4061                         dsl_dataset_activate_feature(clone->ds_object, f,
4062                             origin_head_feature, tx);
4063                         clone->ds_feature[f] = origin_head_feature;
4064                 }
4065         }
4066
4067         dmu_buf_will_dirty(clone->ds_dbuf, tx);
4068         dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
4069
4070         if (clone->ds_objset != NULL) {
4071                 dmu_objset_evict(clone->ds_objset);
4072                 clone->ds_objset = NULL;
4073         }
4074
4075         if (origin_head->ds_objset != NULL) {
4076                 dmu_objset_evict(origin_head->ds_objset);
4077                 origin_head->ds_objset = NULL;
4078         }
4079
4080         unused_refres_delta =
4081             (int64_t)MIN(origin_head->ds_reserved,
4082             dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4083             (int64_t)MIN(origin_head->ds_reserved,
4084             dsl_dataset_phys(clone)->ds_unique_bytes);
4085
4086         /*
4087          * Reset origin's unique bytes.
4088          */
4089         {
4090                 dsl_dataset_t *origin = clone->ds_prev;
4091                 uint64_t comp, uncomp;
4092
4093                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
4094                 dsl_deadlist_space_range(&clone->ds_deadlist,
4095                     dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
4096                     &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
4097         }
4098
4099         /* swap blkptrs */
4100         {
4101                 rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
4102                 rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
4103                 blkptr_t tmp;
4104                 tmp = dsl_dataset_phys(origin_head)->ds_bp;
4105                 dsl_dataset_phys(origin_head)->ds_bp =
4106                     dsl_dataset_phys(clone)->ds_bp;
4107                 dsl_dataset_phys(clone)->ds_bp = tmp;
4108                 rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
4109                 rrw_exit(&clone->ds_bp_rwlock, FTAG);
4110         }
4111
4112         /* set dd_*_bytes */
4113         {
4114                 int64_t dused, dcomp, duncomp;
4115                 uint64_t cdl_used, cdl_comp, cdl_uncomp;
4116                 uint64_t odl_used, odl_comp, odl_uncomp;
4117
4118                 ASSERT3U(dsl_dir_phys(clone->ds_dir)->
4119                     dd_used_breakdown[DD_USED_SNAP], ==, 0);
4120
4121                 dsl_deadlist_space(&clone->ds_deadlist,
4122                     &cdl_used, &cdl_comp, &cdl_uncomp);
4123                 dsl_deadlist_space(&origin_head->ds_deadlist,
4124                     &odl_used, &odl_comp, &odl_uncomp);
4125
4126                 dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
4127                     cdl_used -
4128                     (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
4129                     odl_used);
4130                 dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
4131                     cdl_comp -
4132                     (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
4133                     odl_comp);
4134                 duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
4135                     cdl_uncomp -
4136                     (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
4137                     odl_uncomp);
4138
4139                 dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
4140                     dused, dcomp, duncomp, tx);
4141                 dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
4142                     -dused, -dcomp, -duncomp, tx);
4143
4144                 /*
4145                  * The difference in the space used by snapshots is the
4146                  * difference in snapshot space due to the head's
4147                  * deadlist (since that's the only thing that's
4148                  * changing that affects the snapused).
4149                  */
4150                 dsl_deadlist_space_range(&clone->ds_deadlist,
4151                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4152                     &cdl_used, &cdl_comp, &cdl_uncomp);
4153                 dsl_deadlist_space_range(&origin_head->ds_deadlist,
4154                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4155                     &odl_used, &odl_comp, &odl_uncomp);
4156                 dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
4157                     DD_USED_HEAD, DD_USED_SNAP, tx);
4158         }
4159
4160         /* swap ds_*_bytes */
4161         SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
4162             dsl_dataset_phys(clone)->ds_referenced_bytes);
4163         SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
4164             dsl_dataset_phys(clone)->ds_compressed_bytes);
4165         SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
4166             dsl_dataset_phys(clone)->ds_uncompressed_bytes);
4167         SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
4168             dsl_dataset_phys(clone)->ds_unique_bytes);
4169
4170         /* apply any parent delta for change in unconsumed refreservation */
4171         dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
4172             unused_refres_delta, 0, 0, tx);
4173
4174         /*
4175          * Swap deadlists.
4176          */
4177         dsl_deadlist_close(&clone->ds_deadlist);
4178         dsl_deadlist_close(&origin_head->ds_deadlist);
4179         SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
4180             dsl_dataset_phys(clone)->ds_deadlist_obj);
4181         dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
4182             dsl_dataset_phys(clone)->ds_deadlist_obj);
4183         dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
4184             dsl_dataset_phys(origin_head)->ds_deadlist_obj);
4185         dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
4186
4187         /*
4188          * If there is a bookmark at the origin, its "next dataset" is
4189          * changing, so we need to reset its FBN.
4190          */
4191         dsl_bookmark_next_changed(origin_head, origin_head->ds_prev, tx);
4192
4193         dsl_scan_ds_clone_swapped(origin_head, clone, tx);
4194
4195         /*
4196          * Destroy any livelists associated with the clone or the origin,
4197          * since after the swap the corresponding livelists are no longer
4198          * valid.
4199          */
4200         dsl_dir_remove_livelist(clone->ds_dir, tx, B_TRUE);
4201         dsl_dir_remove_livelist(origin_head->ds_dir, tx, B_TRUE);
4202
4203         spa_history_log_internal_ds(clone, "clone swap", tx,
4204             "parent=%s", origin_head->ds_dir->dd_myname);
4205 }
4206
4207 /*
4208  * Given a pool name and a dataset object number in that pool,
4209  * return the name of that dataset.
4210  */
4211 int
4212 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
4213 {
4214         dsl_pool_t *dp;
4215         dsl_dataset_t *ds;
4216         int error;
4217
4218         error = dsl_pool_hold(pname, FTAG, &dp);
4219         if (error != 0)
4220                 return (error);
4221
4222         error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
4223         if (error == 0) {
4224                 dsl_dataset_name(ds, buf);
4225                 dsl_dataset_rele(ds, FTAG);
4226         }
4227         dsl_pool_rele(dp, FTAG);
4228
4229         return (error);
4230 }
4231
4232 int
4233 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
4234     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
4235 {
4236         int error = 0;
4237
4238         ASSERT3S(asize, >, 0);
4239
4240         /*
4241          * *ref_rsrv is the portion of asize that will come from any
4242          * unconsumed refreservation space.
4243          */
4244         *ref_rsrv = 0;
4245
4246         mutex_enter(&ds->ds_lock);
4247         /*
4248          * Make a space adjustment for reserved bytes.
4249          */
4250         if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
4251                 ASSERT3U(*used, >=,
4252                     ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4253                 *used -=
4254                     (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4255                 *ref_rsrv =
4256                     asize - MIN(asize, parent_delta(ds, asize + inflight));
4257         }
4258
4259         if (!check_quota || ds->ds_quota == 0) {
4260                 mutex_exit(&ds->ds_lock);
4261                 return (0);
4262         }
4263         /*
4264          * If they are requesting more space, and our current estimate
4265          * is over quota, they get to try again unless the actual
4266          * on-disk is over quota and there are no pending changes (which
4267          * may free up space for us).
4268          */
4269         if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
4270             ds->ds_quota) {
4271                 if (inflight > 0 ||
4272                     dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
4273                         error = SET_ERROR(ERESTART);
4274                 else
4275                         error = SET_ERROR(EDQUOT);
4276         }
4277         mutex_exit(&ds->ds_lock);
4278
4279         return (error);
4280 }
4281
4282 typedef struct dsl_dataset_set_qr_arg {
4283         const char *ddsqra_name;
4284         zprop_source_t ddsqra_source;
4285         uint64_t ddsqra_value;
4286 } dsl_dataset_set_qr_arg_t;
4287
4288
4289 /* ARGSUSED */
4290 static int
4291 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
4292 {
4293         dsl_dataset_set_qr_arg_t *ddsqra = arg;
4294         dsl_pool_t *dp = dmu_tx_pool(tx);
4295         dsl_dataset_t *ds;
4296         int error;
4297         uint64_t newval;
4298
4299         if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
4300                 return (SET_ERROR(ENOTSUP));
4301
4302         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4303         if (error != 0)
4304                 return (error);
4305
4306         if (ds->ds_is_snapshot) {
4307                 dsl_dataset_rele(ds, FTAG);
4308                 return (SET_ERROR(EINVAL));
4309         }
4310
4311         error = dsl_prop_predict(ds->ds_dir,
4312             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4313             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4314         if (error != 0) {
4315                 dsl_dataset_rele(ds, FTAG);
4316                 return (error);
4317         }
4318
4319         if (newval == 0) {
4320                 dsl_dataset_rele(ds, FTAG);
4321                 return (0);
4322         }
4323
4324         if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
4325             newval < ds->ds_reserved) {
4326                 dsl_dataset_rele(ds, FTAG);
4327                 return (SET_ERROR(ENOSPC));
4328         }
4329
4330         dsl_dataset_rele(ds, FTAG);
4331         return (0);
4332 }
4333
4334 static void
4335 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
4336 {
4337         dsl_dataset_set_qr_arg_t *ddsqra = arg;
4338         dsl_pool_t *dp = dmu_tx_pool(tx);
4339         dsl_dataset_t *ds = NULL;
4340         uint64_t newval;
4341
4342         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4343
4344         dsl_prop_set_sync_impl(ds,
4345             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4346             ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
4347             &ddsqra->ddsqra_value, tx);
4348
4349         VERIFY0(dsl_prop_get_int_ds(ds,
4350             zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
4351
4352         if (ds->ds_quota != newval) {
4353                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
4354                 ds->ds_quota = newval;
4355         }
4356         dsl_dataset_rele(ds, FTAG);
4357 }
4358
4359 int
4360 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
4361     uint64_t refquota)
4362 {
4363         dsl_dataset_set_qr_arg_t ddsqra;
4364
4365         ddsqra.ddsqra_name = dsname;
4366         ddsqra.ddsqra_source = source;
4367         ddsqra.ddsqra_value = refquota;
4368
4369         return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
4370             dsl_dataset_set_refquota_sync, &ddsqra, 0,
4371             ZFS_SPACE_CHECK_EXTRA_RESERVED));
4372 }
4373
4374 static int
4375 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
4376 {
4377         dsl_dataset_set_qr_arg_t *ddsqra = arg;
4378         dsl_pool_t *dp = dmu_tx_pool(tx);
4379         dsl_dataset_t *ds;
4380         int error;
4381         uint64_t newval, unique;
4382
4383         if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
4384                 return (SET_ERROR(ENOTSUP));
4385
4386         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4387         if (error != 0)
4388                 return (error);
4389
4390         if (ds->ds_is_snapshot) {
4391                 dsl_dataset_rele(ds, FTAG);
4392                 return (SET_ERROR(EINVAL));
4393         }
4394
4395         error = dsl_prop_predict(ds->ds_dir,
4396             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4397             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4398         if (error != 0) {
4399                 dsl_dataset_rele(ds, FTAG);
4400                 return (error);
4401         }
4402
4403         /*
4404          * If we are doing the preliminary check in open context, the
4405          * space estimates may be inaccurate.
4406          */
4407         if (!dmu_tx_is_syncing(tx)) {
4408                 dsl_dataset_rele(ds, FTAG);
4409                 return (0);
4410         }
4411
4412         mutex_enter(&ds->ds_lock);
4413         if (!DS_UNIQUE_IS_ACCURATE(ds))
4414                 dsl_dataset_recalc_head_uniq(ds);
4415         unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4416         mutex_exit(&ds->ds_lock);
4417
4418         if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
4419                 uint64_t delta = MAX(unique, newval) -
4420                     MAX(unique, ds->ds_reserved);
4421
4422                 if (delta >
4423                     dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
4424                     (ds->ds_quota > 0 && newval > ds->ds_quota)) {
4425                         dsl_dataset_rele(ds, FTAG);
4426                         return (SET_ERROR(ENOSPC));
4427                 }
4428         }
4429
4430         dsl_dataset_rele(ds, FTAG);
4431         return (0);
4432 }
4433
4434 void
4435 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
4436     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
4437 {
4438         uint64_t newval;
4439         uint64_t unique;
4440         int64_t delta;
4441
4442         dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4443             source, sizeof (value), 1, &value, tx);
4444
4445         VERIFY0(dsl_prop_get_int_ds(ds,
4446             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
4447
4448         dmu_buf_will_dirty(ds->ds_dbuf, tx);
4449         mutex_enter(&ds->ds_dir->dd_lock);
4450         mutex_enter(&ds->ds_lock);
4451         ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
4452         unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4453         delta = MAX(0, (int64_t)(newval - unique)) -
4454             MAX(0, (int64_t)(ds->ds_reserved - unique));
4455         ds->ds_reserved = newval;
4456         mutex_exit(&ds->ds_lock);
4457
4458         dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
4459         mutex_exit(&ds->ds_dir->dd_lock);
4460 }
4461
4462 static void
4463 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
4464 {
4465         dsl_dataset_set_qr_arg_t *ddsqra = arg;
4466         dsl_pool_t *dp = dmu_tx_pool(tx);
4467         dsl_dataset_t *ds = NULL;
4468
4469         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4470         dsl_dataset_set_refreservation_sync_impl(ds,
4471             ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
4472         dsl_dataset_rele(ds, FTAG);
4473 }
4474
4475 int
4476 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
4477     uint64_t refreservation)
4478 {
4479         dsl_dataset_set_qr_arg_t ddsqra;
4480
4481         ddsqra.ddsqra_name = dsname;
4482         ddsqra.ddsqra_source = source;
4483         ddsqra.ddsqra_value = refreservation;
4484
4485         return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
4486             dsl_dataset_set_refreservation_sync, &ddsqra, 0,
4487             ZFS_SPACE_CHECK_EXTRA_RESERVED));
4488 }
4489
4490 /*
4491  * Return (in *usedp) the amount of space referenced by "new" that was not
4492  * referenced at the time the bookmark corresponds to.  "New" may be a
4493  * snapshot or a head.  The bookmark must be before new, in
4494  * new's filesystem (or its origin) -- caller verifies this.
4495  *
4496  * The written space is calculated by considering two components:  First, we
4497  * ignore any freed space, and calculate the written as new's used space
4498  * minus old's used space.  Next, we add in the amount of space that was freed
4499  * between the two time points, thus reducing new's used space relative to
4500  * old's. Specifically, this is the space that was born before
4501  * zbm_creation_txg, and freed before new (ie. on new's deadlist or a
4502  * previous deadlist).
4503  *
4504  * space freed                         [---------------------]
4505  * snapshots                       ---O-------O--------O-------O------
4506  *                                         bookmark           new
4507  *
4508  * Note, the bookmark's zbm_*_bytes_refd must be valid, but if the HAS_FBN
4509  * flag is not set, we will calculate the freed_before_next based on the
4510  * next snapshot's deadlist, rather than using zbm_*_freed_before_next_snap.
4511  */
4512 static int
4513 dsl_dataset_space_written_impl(zfs_bookmark_phys_t *bmp,
4514     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4515 {
4516         int err = 0;
4517         dsl_pool_t *dp = new->ds_dir->dd_pool;
4518
4519         ASSERT(dsl_pool_config_held(dp));
4520         if (dsl_dataset_is_snapshot(new)) {
4521                 ASSERT3U(bmp->zbm_creation_txg, <,
4522                     dsl_dataset_phys(new)->ds_creation_txg);
4523         }
4524
4525         *usedp = 0;
4526         *usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
4527         *usedp -= bmp->zbm_referenced_bytes_refd;
4528
4529         *compp = 0;
4530         *compp += dsl_dataset_phys(new)->ds_compressed_bytes;
4531         *compp -= bmp->zbm_compressed_bytes_refd;
4532
4533         *uncompp = 0;
4534         *uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
4535         *uncompp -= bmp->zbm_uncompressed_bytes_refd;
4536
4537         dsl_dataset_t *snap = new;
4538
4539         while (dsl_dataset_phys(snap)->ds_prev_snap_txg >
4540             bmp->zbm_creation_txg) {
4541                 uint64_t used, comp, uncomp;
4542
4543                 dsl_deadlist_space_range(&snap->ds_deadlist,
4544                     0, bmp->zbm_creation_txg,
4545                     &used, &comp, &uncomp);
4546                 *usedp += used;
4547                 *compp += comp;
4548                 *uncompp += uncomp;
4549
4550                 uint64_t snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
4551                 if (snap != new)
4552                         dsl_dataset_rele(snap, FTAG);
4553                 err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4554                 if (err != 0)
4555                         break;
4556         }
4557
4558         /*
4559          * We might not have the FBN if we are calculating written from
4560          * a snapshot (because we didn't know the correct "next" snapshot
4561          * until now).
4562          */
4563         if (bmp->zbm_flags & ZBM_FLAG_HAS_FBN) {
4564                 *usedp += bmp->zbm_referenced_freed_before_next_snap;
4565                 *compp += bmp->zbm_compressed_freed_before_next_snap;
4566                 *uncompp += bmp->zbm_uncompressed_freed_before_next_snap;
4567         } else {
4568                 ASSERT3U(dsl_dataset_phys(snap)->ds_prev_snap_txg, ==,
4569                     bmp->zbm_creation_txg);
4570                 uint64_t used, comp, uncomp;
4571                 dsl_deadlist_space(&snap->ds_deadlist, &used, &comp, &uncomp);
4572                 *usedp += used;
4573                 *compp += comp;
4574                 *uncompp += uncomp;
4575         }
4576         if (snap != new)
4577                 dsl_dataset_rele(snap, FTAG);
4578         return (err);
4579 }
4580
4581 /*
4582  * Return (in *usedp) the amount of space written in new that was not
4583  * present at the time the bookmark corresponds to.  New may be a
4584  * snapshot or the head.  Old must be a bookmark before new, in
4585  * new's filesystem (or its origin) -- caller verifies this.
4586  */
4587 int
4588 dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t *bmp,
4589     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4590 {
4591         if (!(bmp->zbm_flags & ZBM_FLAG_HAS_FBN))
4592                 return (SET_ERROR(ENOTSUP));
4593         return (dsl_dataset_space_written_impl(bmp, new,
4594             usedp, compp, uncompp));
4595 }
4596
4597 /*
4598  * Return (in *usedp) the amount of space written in new that is not
4599  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4600  * a snapshot before new, in new's filesystem (or its origin).  If not then
4601  * fail and return EINVAL.
4602  */
4603 int
4604 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4605     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4606 {
4607         if (!dsl_dataset_is_before(new, oldsnap, 0))
4608                 return (SET_ERROR(EINVAL));
4609
4610         zfs_bookmark_phys_t zbm = { 0 };
4611         dsl_dataset_phys_t *dsp = dsl_dataset_phys(oldsnap);
4612         zbm.zbm_guid = dsp->ds_guid;
4613         zbm.zbm_creation_txg = dsp->ds_creation_txg;
4614         zbm.zbm_creation_time = dsp->ds_creation_time;
4615         zbm.zbm_referenced_bytes_refd = dsp->ds_referenced_bytes;
4616         zbm.zbm_compressed_bytes_refd = dsp->ds_compressed_bytes;
4617         zbm.zbm_uncompressed_bytes_refd = dsp->ds_uncompressed_bytes;
4618
4619         /*
4620          * If oldsnap is the origin (or origin's origin, ...) of new,
4621          * we can't easily calculate the effective FBN.  Therefore,
4622          * we do not set ZBM_FLAG_HAS_FBN, so that the _impl will calculate
4623          * it relative to the correct "next": the next snapshot towards "new",
4624          * rather than the next snapshot in oldsnap's dsl_dir.
4625          */
4626         return (dsl_dataset_space_written_impl(&zbm, new,
4627             usedp, compp, uncompp));
4628 }
4629
4630 /*
4631  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4632  * lastsnap, and all snapshots in between are deleted.
4633  *
4634  * blocks that would be freed            [---------------------------]
4635  * snapshots                       ---O-------O--------O-------O--------O
4636  *                                        firstsnap        lastsnap
4637  *
4638  * This is the set of blocks that were born after the snap before firstsnap,
4639  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4640  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4641  * We calculate this by iterating over the relevant deadlists (from the snap
4642  * after lastsnap, backward to the snap after firstsnap), summing up the
4643  * space on the deadlist that was born after the snap before firstsnap.
4644  */
4645 int
4646 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4647     dsl_dataset_t *lastsnap,
4648     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4649 {
4650         int err = 0;
4651         uint64_t snapobj;
4652         dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4653
4654         ASSERT(firstsnap->ds_is_snapshot);
4655         ASSERT(lastsnap->ds_is_snapshot);
4656
4657         /*
4658          * Check that the snapshots are in the same dsl_dir, and firstsnap
4659          * is before lastsnap.
4660          */
4661         if (firstsnap->ds_dir != lastsnap->ds_dir ||
4662             dsl_dataset_phys(firstsnap)->ds_creation_txg >
4663             dsl_dataset_phys(lastsnap)->ds_creation_txg)
4664                 return (SET_ERROR(EINVAL));
4665
4666         *usedp = *compp = *uncompp = 0;
4667
4668         snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
4669         while (snapobj != firstsnap->ds_object) {
4670                 dsl_dataset_t *ds;
4671                 uint64_t used, comp, uncomp;
4672
4673                 err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4674                 if (err != 0)
4675                         break;
4676
4677                 dsl_deadlist_space_range(&ds->ds_deadlist,
4678                     dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
4679                     &used, &comp, &uncomp);
4680                 *usedp += used;
4681                 *compp += comp;
4682                 *uncompp += uncomp;
4683
4684                 snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4685                 ASSERT3U(snapobj, !=, 0);
4686                 dsl_dataset_rele(ds, FTAG);
4687         }
4688         return (err);
4689 }
4690
4691 /*
4692  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
4693  * For example, they could both be snapshots of the same filesystem, and
4694  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
4695  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
4696  * filesystem.  Or 'earlier' could be the origin's origin.
4697  *
4698  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
4699  */
4700 boolean_t
4701 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4702     uint64_t earlier_txg)
4703 {
4704         dsl_pool_t *dp = later->ds_dir->dd_pool;
4705         int error;
4706         boolean_t ret;
4707
4708         ASSERT(dsl_pool_config_held(dp));
4709         ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4710
4711         if (earlier_txg == 0)
4712                 earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4713
4714         if (later->ds_is_snapshot &&
4715             earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4716                 return (B_FALSE);
4717
4718         if (later->ds_dir == earlier->ds_dir)
4719                 return (B_TRUE);
4720
4721         /*
4722          * We check dd_origin_obj explicitly here rather than using
4723          * dsl_dir_is_clone() so that we will return TRUE if "earlier"
4724          * is $ORIGIN@$ORIGIN.  dsl_dataset_space_written() depends on
4725          * this behavior.
4726          */
4727         if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == 0)
4728                 return (B_FALSE);
4729
4730         dsl_dataset_t *origin;
4731         error = dsl_dataset_hold_obj(dp,
4732             dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4733         if (error != 0)
4734                 return (B_FALSE);
4735         if (dsl_dataset_phys(origin)->ds_creation_txg == earlier_txg &&
4736             origin->ds_dir == earlier->ds_dir) {
4737                 dsl_dataset_rele(origin, FTAG);
4738                 return (B_TRUE);
4739         }
4740         ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4741         dsl_dataset_rele(origin, FTAG);
4742         return (ret);
4743 }
4744
4745 void
4746 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4747 {
4748         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4749         dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4750 }
4751
4752 boolean_t
4753 dsl_dataset_is_zapified(dsl_dataset_t *ds)
4754 {
4755         dmu_object_info_t doi;
4756
4757         dmu_object_info_from_db(ds->ds_dbuf, &doi);
4758         return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4759 }
4760
4761 boolean_t
4762 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
4763 {
4764         return (dsl_dataset_is_zapified(ds) &&
4765             zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
4766             ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
4767 }
4768
4769 uint64_t
4770 dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
4771 {
4772         uint64_t remap_deadlist_obj;
4773         int err;
4774
4775         if (!dsl_dataset_is_zapified(ds))
4776                 return (0);
4777
4778         err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4779             DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
4780             &remap_deadlist_obj);
4781
4782         if (err != 0) {
4783                 VERIFY3S(err, ==, ENOENT);
4784                 return (0);
4785         }
4786
4787         ASSERT(remap_deadlist_obj != 0);
4788         return (remap_deadlist_obj);
4789 }
4790
4791 boolean_t
4792 dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
4793 {
4794         EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
4795             dsl_dataset_get_remap_deadlist_object(ds) != 0);
4796         return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
4797 }
4798
4799 static void
4800 dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
4801     dmu_tx_t *tx)
4802 {
4803         ASSERT(obj != 0);
4804         dsl_dataset_zapify(ds, tx);
4805         VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4806             DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
4807 }
4808
4809 static void
4810 dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
4811 {
4812         VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
4813             ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
4814 }
4815
4816 void
4817 dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4818 {
4819         uint64_t remap_deadlist_object;
4820         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4821
4822         ASSERT(dmu_tx_is_syncing(tx));
4823         ASSERT(dsl_dataset_remap_deadlist_exists(ds));
4824
4825         remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
4826         dsl_deadlist_close(&ds->ds_remap_deadlist);
4827         dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
4828         dsl_dataset_unset_remap_deadlist_object(ds, tx);
4829         spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4830 }
4831
4832 void
4833 dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4834 {
4835         uint64_t remap_deadlist_obj;
4836         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4837
4838         ASSERT(dmu_tx_is_syncing(tx));
4839         ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
4840         /*
4841          * Currently we only create remap deadlists when there are indirect
4842          * vdevs with referenced mappings.
4843          */
4844         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
4845
4846         remap_deadlist_obj = dsl_deadlist_clone(
4847             &ds->ds_deadlist, UINT64_MAX,
4848             dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
4849         dsl_dataset_set_remap_deadlist_object(ds,
4850             remap_deadlist_obj, tx);
4851         dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
4852             remap_deadlist_obj);
4853         spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4854 }
4855
4856 void
4857 dsl_dataset_activate_redaction(dsl_dataset_t *ds, uint64_t *redact_snaps,
4858     uint64_t num_redact_snaps, dmu_tx_t *tx)
4859 {
4860         uint64_t dsobj = ds->ds_object;
4861         struct feature_type_uint64_array_arg *ftuaa =
4862             kmem_zalloc(sizeof (*ftuaa), KM_SLEEP);
4863         ftuaa->length = (int64_t)num_redact_snaps;
4864         if (num_redact_snaps > 0) {
4865                 ftuaa->array = kmem_alloc(num_redact_snaps * sizeof (uint64_t),
4866                     KM_SLEEP);
4867                 bcopy(redact_snaps, ftuaa->array, num_redact_snaps *
4868                     sizeof (uint64_t));
4869         }
4870         dsl_dataset_activate_feature(dsobj, SPA_FEATURE_REDACTED_DATASETS,
4871             ftuaa, tx);
4872         ds->ds_feature[SPA_FEATURE_REDACTED_DATASETS] = ftuaa;
4873 }
4874
4875 /* BEGIN CSTYLED */
4876 #if defined(_LP64)
4877 #define RECORDSIZE_PERM ZMOD_RW
4878 #else
4879 /* Limited to 1M on 32-bit platforms due to lack of virtual address space */
4880 #define RECORDSIZE_PERM ZMOD_RD
4881 #endif
4882 ZFS_MODULE_PARAM(zfs, zfs_, max_recordsize, INT, RECORDSIZE_PERM,
4883         "Max allowed record size");
4884
4885 ZFS_MODULE_PARAM(zfs, zfs_, allow_redacted_dataset_mount, INT, ZMOD_RW,
4886         "Allow mounting of redacted datasets");
4887 /* END CSTYLED */
4888
4889 EXPORT_SYMBOL(dsl_dataset_hold);
4890 EXPORT_SYMBOL(dsl_dataset_hold_flags);
4891 EXPORT_SYMBOL(dsl_dataset_hold_obj);
4892 EXPORT_SYMBOL(dsl_dataset_hold_obj_flags);
4893 EXPORT_SYMBOL(dsl_dataset_own);
4894 EXPORT_SYMBOL(dsl_dataset_own_obj);
4895 EXPORT_SYMBOL(dsl_dataset_name);
4896 EXPORT_SYMBOL(dsl_dataset_rele);
4897 EXPORT_SYMBOL(dsl_dataset_rele_flags);
4898 EXPORT_SYMBOL(dsl_dataset_disown);
4899 EXPORT_SYMBOL(dsl_dataset_tryown);
4900 EXPORT_SYMBOL(dsl_dataset_create_sync);
4901 EXPORT_SYMBOL(dsl_dataset_create_sync_dd);
4902 EXPORT_SYMBOL(dsl_dataset_snapshot_check);
4903 EXPORT_SYMBOL(dsl_dataset_snapshot_sync);
4904 EXPORT_SYMBOL(dsl_dataset_promote);
4905 EXPORT_SYMBOL(dsl_dataset_user_hold);
4906 EXPORT_SYMBOL(dsl_dataset_user_release);
4907 EXPORT_SYMBOL(dsl_dataset_get_holds);
4908 EXPORT_SYMBOL(dsl_dataset_get_blkptr);
4909 EXPORT_SYMBOL(dsl_dataset_get_spa);
4910 EXPORT_SYMBOL(dsl_dataset_modified_since_snap);
4911 EXPORT_SYMBOL(dsl_dataset_space_written);
4912 EXPORT_SYMBOL(dsl_dataset_space_wouldfree);
4913 EXPORT_SYMBOL(dsl_dataset_sync);
4914 EXPORT_SYMBOL(dsl_dataset_block_born);
4915 EXPORT_SYMBOL(dsl_dataset_block_kill);
4916 EXPORT_SYMBOL(dsl_dataset_dirty);
4917 EXPORT_SYMBOL(dsl_dataset_stats);
4918 EXPORT_SYMBOL(dsl_dataset_fast_stat);
4919 EXPORT_SYMBOL(dsl_dataset_space);
4920 EXPORT_SYMBOL(dsl_dataset_fsid_guid);
4921 EXPORT_SYMBOL(dsl_dsobj_to_dsname);
4922 EXPORT_SYMBOL(dsl_dataset_check_quota);
4923 EXPORT_SYMBOL(dsl_dataset_clone_swap_check_impl);
4924 EXPORT_SYMBOL(dsl_dataset_clone_swap_sync_impl);