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