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