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