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