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