xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_dataset.c (revision 90b5fc95832da64a5f56295e687379732c33718f)
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;
2326 
2327 	/*
2328 	 * We use nvlist_alloc() instead of fnvlist_alloc() because the
2329 	 * latter would allocate the list with NV_UNIQUE_NAME flag.
2330 	 * As a result, every time a clone name is appended to the list
2331 	 * it would be (linearly) searched for a duplicate name.
2332 	 * We already know that all clone names must be unique and we
2333 	 * want avoid the quadratic complexity of double-checking that
2334 	 * because we can have a large number of clones.
2335 	 */
2336 	VERIFY0(nvlist_alloc(&val, 0, KM_SLEEP));
2337 
2338 	if (get_clones_stat_impl(ds, val) == 0) {
2339 		fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
2340 		fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2341 		    propval);
2342 	}
2343 
2344 	nvlist_free(val);
2345 	nvlist_free(propval);
2346 }
2347 
2348 /*
2349  * Returns a string that represents the receive resume stats token. It should
2350  * be freed with strfree().
2351  */
2352 char *
2353 get_receive_resume_stats_impl(dsl_dataset_t *ds)
2354 {
2355 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2356 
2357 	if (dsl_dataset_has_resume_receive_state(ds)) {
2358 		char *str;
2359 		void *packed;
2360 		uint8_t *compressed;
2361 		uint64_t val;
2362 		nvlist_t *token_nv = fnvlist_alloc();
2363 		size_t packed_size, compressed_size;
2364 
2365 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2366 		    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val) == 0) {
2367 			fnvlist_add_uint64(token_nv, "fromguid", val);
2368 		}
2369 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2370 		    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val) == 0) {
2371 			fnvlist_add_uint64(token_nv, "object", val);
2372 		}
2373 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2374 		    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val) == 0) {
2375 			fnvlist_add_uint64(token_nv, "offset", val);
2376 		}
2377 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2378 		    DS_FIELD_RESUME_BYTES, sizeof (val), 1, &val) == 0) {
2379 			fnvlist_add_uint64(token_nv, "bytes", val);
2380 		}
2381 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2382 		    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val) == 0) {
2383 			fnvlist_add_uint64(token_nv, "toguid", val);
2384 		}
2385 		char buf[MAXNAMELEN];
2386 		if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2387 		    DS_FIELD_RESUME_TONAME, 1, sizeof (buf), buf) == 0) {
2388 			fnvlist_add_string(token_nv, "toname", buf);
2389 		}
2390 		if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2391 		    DS_FIELD_RESUME_LARGEBLOCK) == 0) {
2392 			fnvlist_add_boolean(token_nv, "largeblockok");
2393 		}
2394 		if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2395 		    DS_FIELD_RESUME_EMBEDOK) == 0) {
2396 			fnvlist_add_boolean(token_nv, "embedok");
2397 		}
2398 		if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2399 		    DS_FIELD_RESUME_COMPRESSOK) == 0) {
2400 			fnvlist_add_boolean(token_nv, "compressok");
2401 		}
2402 		if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2403 		    DS_FIELD_RESUME_RAWOK) == 0) {
2404 			fnvlist_add_boolean(token_nv, "rawok");
2405 		}
2406 		if (dsl_dataset_feature_is_active(ds,
2407 		    SPA_FEATURE_REDACTED_DATASETS)) {
2408 			uint64_t num_redact_snaps;
2409 			uint64_t *redact_snaps;
2410 			VERIFY(dsl_dataset_get_uint64_array_feature(ds,
2411 			    SPA_FEATURE_REDACTED_DATASETS, &num_redact_snaps,
2412 			    &redact_snaps));
2413 			fnvlist_add_uint64_array(token_nv, "redact_snaps",
2414 			    redact_snaps, num_redact_snaps);
2415 		}
2416 		if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2417 		    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS) == 0) {
2418 			uint64_t num_redact_snaps, int_size;
2419 			uint64_t *redact_snaps;
2420 			VERIFY0(zap_length(dp->dp_meta_objset, ds->ds_object,
2421 			    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, &int_size,
2422 			    &num_redact_snaps));
2423 			ASSERT3U(int_size, ==, sizeof (uint64_t));
2424 
2425 			redact_snaps = kmem_alloc(int_size * num_redact_snaps,
2426 			    KM_SLEEP);
2427 			VERIFY0(zap_lookup(dp->dp_meta_objset, ds->ds_object,
2428 			    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, int_size,
2429 			    num_redact_snaps, redact_snaps));
2430 			fnvlist_add_uint64_array(token_nv, "book_redact_snaps",
2431 			    redact_snaps, num_redact_snaps);
2432 			kmem_free(redact_snaps, int_size * num_redact_snaps);
2433 		}
2434 		packed = fnvlist_pack(token_nv, &packed_size);
2435 		fnvlist_free(token_nv);
2436 		compressed = kmem_alloc(packed_size, KM_SLEEP);
2437 
2438 		compressed_size = gzip_compress(packed, compressed,
2439 		    packed_size, packed_size, 6);
2440 
2441 		zio_cksum_t cksum;
2442 		fletcher_4_native_varsize(compressed, compressed_size, &cksum);
2443 
2444 		size_t alloc_size = compressed_size * 2 + 1;
2445 		str = kmem_alloc(alloc_size, KM_SLEEP);
2446 		for (int i = 0; i < compressed_size; i++) {
2447 			size_t offset = i * 2;
2448 			(void) snprintf(str + offset, alloc_size - offset,
2449 		    "%02x", compressed[i]);
2450 		}
2451 		str[compressed_size * 2] = '\0';
2452 		char *propval = kmem_asprintf("%u-%llx-%llx-%s",
2453 		    ZFS_SEND_RESUME_TOKEN_VERSION,
2454 		    (longlong_t)cksum.zc_word[0],
2455 		    (longlong_t)packed_size, str);
2456 		kmem_free(packed, packed_size);
2457 		kmem_free(str, alloc_size);
2458 		kmem_free(compressed, packed_size);
2459 		return (propval);
2460 	}
2461 	return (kmem_strdup(""));
2462 }
2463 
2464 /*
2465  * Returns a string that represents the receive resume stats token of the
2466  * dataset's child. It should be freed with strfree().
2467  */
2468 char *
2469 get_child_receive_stats(dsl_dataset_t *ds)
2470 {
2471 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
2472 	dsl_dataset_t *recv_ds;
2473 	dsl_dataset_name(ds, recvname);
2474 	if (strlcat(recvname, "/", sizeof (recvname)) <
2475 	    sizeof (recvname) &&
2476 	    strlcat(recvname, recv_clone_name, sizeof (recvname)) <
2477 	    sizeof (recvname) &&
2478 	    dsl_dataset_hold(ds->ds_dir->dd_pool, recvname, FTAG,
2479 	    &recv_ds)  == 0) {
2480 		char *propval = get_receive_resume_stats_impl(recv_ds);
2481 		dsl_dataset_rele(recv_ds, FTAG);
2482 		return (propval);
2483 	}
2484 	return (kmem_strdup(""));
2485 }
2486 
2487 static void
2488 get_receive_resume_stats(dsl_dataset_t *ds, nvlist_t *nv)
2489 {
2490 	char *propval = get_receive_resume_stats_impl(ds);
2491 	if (strcmp(propval, "") != 0) {
2492 		dsl_prop_nvlist_add_string(nv,
2493 		    ZFS_PROP_RECEIVE_RESUME_TOKEN, propval);
2494 	} else {
2495 		char *childval = get_child_receive_stats(ds);
2496 		if (strcmp(childval, "") != 0) {
2497 			dsl_prop_nvlist_add_string(nv,
2498 			    ZFS_PROP_RECEIVE_RESUME_TOKEN, childval);
2499 		}
2500 		kmem_strfree(childval);
2501 	}
2502 	kmem_strfree(propval);
2503 }
2504 
2505 uint64_t
2506 dsl_get_refratio(dsl_dataset_t *ds)
2507 {
2508 	uint64_t ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
2509 	    (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
2510 	    dsl_dataset_phys(ds)->ds_compressed_bytes);
2511 	return (ratio);
2512 }
2513 
2514 uint64_t
2515 dsl_get_logicalreferenced(dsl_dataset_t *ds)
2516 {
2517 	return (dsl_dataset_phys(ds)->ds_uncompressed_bytes);
2518 }
2519 
2520 uint64_t
2521 dsl_get_compressratio(dsl_dataset_t *ds)
2522 {
2523 	if (ds->ds_is_snapshot) {
2524 		return (dsl_get_refratio(ds));
2525 	} else {
2526 		dsl_dir_t *dd = ds->ds_dir;
2527 		mutex_enter(&dd->dd_lock);
2528 		uint64_t val = dsl_dir_get_compressratio(dd);
2529 		mutex_exit(&dd->dd_lock);
2530 		return (val);
2531 	}
2532 }
2533 
2534 uint64_t
2535 dsl_get_used(dsl_dataset_t *ds)
2536 {
2537 	if (ds->ds_is_snapshot) {
2538 		return (dsl_dataset_phys(ds)->ds_unique_bytes);
2539 	} else {
2540 		dsl_dir_t *dd = ds->ds_dir;
2541 		mutex_enter(&dd->dd_lock);
2542 		uint64_t val = dsl_dir_get_used(dd);
2543 		mutex_exit(&dd->dd_lock);
2544 		return (val);
2545 	}
2546 }
2547 
2548 uint64_t
2549 dsl_get_creation(dsl_dataset_t *ds)
2550 {
2551 	return (dsl_dataset_phys(ds)->ds_creation_time);
2552 }
2553 
2554 uint64_t
2555 dsl_get_creationtxg(dsl_dataset_t *ds)
2556 {
2557 	return (dsl_dataset_phys(ds)->ds_creation_txg);
2558 }
2559 
2560 uint64_t
2561 dsl_get_refquota(dsl_dataset_t *ds)
2562 {
2563 	return (ds->ds_quota);
2564 }
2565 
2566 uint64_t
2567 dsl_get_refreservation(dsl_dataset_t *ds)
2568 {
2569 	return (ds->ds_reserved);
2570 }
2571 
2572 uint64_t
2573 dsl_get_guid(dsl_dataset_t *ds)
2574 {
2575 	return (dsl_dataset_phys(ds)->ds_guid);
2576 }
2577 
2578 uint64_t
2579 dsl_get_unique(dsl_dataset_t *ds)
2580 {
2581 	return (dsl_dataset_phys(ds)->ds_unique_bytes);
2582 }
2583 
2584 uint64_t
2585 dsl_get_objsetid(dsl_dataset_t *ds)
2586 {
2587 	return (ds->ds_object);
2588 }
2589 
2590 uint64_t
2591 dsl_get_userrefs(dsl_dataset_t *ds)
2592 {
2593 	return (ds->ds_userrefs);
2594 }
2595 
2596 uint64_t
2597 dsl_get_defer_destroy(dsl_dataset_t *ds)
2598 {
2599 	return (DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2600 }
2601 
2602 uint64_t
2603 dsl_get_referenced(dsl_dataset_t *ds)
2604 {
2605 	return (dsl_dataset_phys(ds)->ds_referenced_bytes);
2606 }
2607 
2608 uint64_t
2609 dsl_get_numclones(dsl_dataset_t *ds)
2610 {
2611 	ASSERT(ds->ds_is_snapshot);
2612 	return (dsl_dataset_phys(ds)->ds_num_children - 1);
2613 }
2614 
2615 uint64_t
2616 dsl_get_inconsistent(dsl_dataset_t *ds)
2617 {
2618 	return ((dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT) ?
2619 	    1 : 0);
2620 }
2621 
2622 uint64_t
2623 dsl_get_redacted(dsl_dataset_t *ds)
2624 {
2625 	return (dsl_dataset_feature_is_active(ds,
2626 	    SPA_FEATURE_REDACTED_DATASETS));
2627 }
2628 
2629 uint64_t
2630 dsl_get_available(dsl_dataset_t *ds)
2631 {
2632 	uint64_t refdbytes = dsl_get_referenced(ds);
2633 	uint64_t availbytes = dsl_dir_space_available(ds->ds_dir,
2634 	    NULL, 0, TRUE);
2635 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
2636 		availbytes +=
2637 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2638 	}
2639 	if (ds->ds_quota != 0) {
2640 		/*
2641 		 * Adjust available bytes according to refquota
2642 		 */
2643 		if (refdbytes < ds->ds_quota) {
2644 			availbytes = MIN(availbytes,
2645 			    ds->ds_quota - refdbytes);
2646 		} else {
2647 			availbytes = 0;
2648 		}
2649 	}
2650 	return (availbytes);
2651 }
2652 
2653 int
2654 dsl_get_written(dsl_dataset_t *ds, uint64_t *written)
2655 {
2656 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2657 	dsl_dataset_t *prev;
2658 	int err = dsl_dataset_hold_obj(dp,
2659 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2660 	if (err == 0) {
2661 		uint64_t comp, uncomp;
2662 		err = dsl_dataset_space_written(prev, ds, written,
2663 		    &comp, &uncomp);
2664 		dsl_dataset_rele(prev, FTAG);
2665 	}
2666 	return (err);
2667 }
2668 
2669 /*
2670  * 'snap' should be a buffer of size ZFS_MAX_DATASET_NAME_LEN.
2671  */
2672 int
2673 dsl_get_prev_snap(dsl_dataset_t *ds, char *snap)
2674 {
2675 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2676 	if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
2677 		dsl_dataset_name(ds->ds_prev, snap);
2678 		return (0);
2679 	} else {
2680 		return (SET_ERROR(ENOENT));
2681 	}
2682 }
2683 
2684 void
2685 dsl_get_redact_snaps(dsl_dataset_t *ds, nvlist_t *propval)
2686 {
2687 	uint64_t nsnaps;
2688 	uint64_t *snaps;
2689 	if (dsl_dataset_get_uint64_array_feature(ds,
2690 	    SPA_FEATURE_REDACTED_DATASETS, &nsnaps, &snaps)) {
2691 		fnvlist_add_uint64_array(propval, ZPROP_VALUE, snaps,
2692 		    nsnaps);
2693 	}
2694 }
2695 
2696 /*
2697  * Returns the mountpoint property and source for the given dataset in the value
2698  * and source buffers. The value buffer must be at least as large as MAXPATHLEN
2699  * and the source buffer as least as large a ZFS_MAX_DATASET_NAME_LEN.
2700  * Returns 0 on success and an error on failure.
2701  */
2702 int
2703 dsl_get_mountpoint(dsl_dataset_t *ds, const char *dsname, char *value,
2704     char *source)
2705 {
2706 	int error;
2707 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2708 
2709 	/* Retrieve the mountpoint value stored in the zap object */
2710 	error = dsl_prop_get_ds(ds, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT), 1,
2711 	    ZAP_MAXVALUELEN, value, source);
2712 	if (error != 0) {
2713 		return (error);
2714 	}
2715 
2716 	/*
2717 	 * Process the dsname and source to find the full mountpoint string.
2718 	 * Can be skipped for 'legacy' or 'none'.
2719 	 */
2720 	if (value[0] == '/') {
2721 		char *buf = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
2722 		char *root = buf;
2723 		const char *relpath;
2724 
2725 		/*
2726 		 * If we inherit the mountpoint, even from a dataset
2727 		 * with a received value, the source will be the path of
2728 		 * the dataset we inherit from. If source is
2729 		 * ZPROP_SOURCE_VAL_RECVD, the received value is not
2730 		 * inherited.
2731 		 */
2732 		if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2733 			relpath = "";
2734 		} else {
2735 			ASSERT0(strncmp(dsname, source, strlen(source)));
2736 			relpath = dsname + strlen(source);
2737 			if (relpath[0] == '/')
2738 				relpath++;
2739 		}
2740 
2741 		spa_altroot(dp->dp_spa, root, ZAP_MAXVALUELEN);
2742 
2743 		/*
2744 		 * Special case an alternate root of '/'. This will
2745 		 * avoid having multiple leading slashes in the
2746 		 * mountpoint path.
2747 		 */
2748 		if (strcmp(root, "/") == 0)
2749 			root++;
2750 
2751 		/*
2752 		 * If the mountpoint is '/' then skip over this
2753 		 * if we are obtaining either an alternate root or
2754 		 * an inherited mountpoint.
2755 		 */
2756 		char *mnt = value;
2757 		if (value[1] == '\0' && (root[0] != '\0' ||
2758 		    relpath[0] != '\0'))
2759 			mnt = value + 1;
2760 
2761 		if (relpath[0] == '\0') {
2762 			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s",
2763 			    root, mnt);
2764 		} else {
2765 			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s%s%s",
2766 			    root, mnt, relpath[0] == '@' ? "" : "/",
2767 			    relpath);
2768 		}
2769 		kmem_free(buf, ZAP_MAXVALUELEN);
2770 	}
2771 
2772 	return (0);
2773 }
2774 
2775 void
2776 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2777 {
2778 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2779 
2780 	ASSERT(dsl_pool_config_held(dp));
2781 
2782 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO,
2783 	    dsl_get_refratio(ds));
2784 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
2785 	    dsl_get_logicalreferenced(ds));
2786 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
2787 	    dsl_get_compressratio(ds));
2788 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2789 	    dsl_get_used(ds));
2790 
2791 	if (ds->ds_is_snapshot) {
2792 		get_clones_stat(ds, nv);
2793 	} else {
2794 		char buf[ZFS_MAX_DATASET_NAME_LEN];
2795 		if (dsl_get_prev_snap(ds, buf) == 0)
2796 			dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP,
2797 			    buf);
2798 		dsl_dir_stats(ds->ds_dir, nv);
2799 	}
2800 
2801 	nvlist_t *propval = fnvlist_alloc();
2802 	dsl_get_redact_snaps(ds, propval);
2803 	fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS),
2804 	    propval);
2805 	nvlist_free(propval);
2806 
2807 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE,
2808 	    dsl_get_available(ds));
2809 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED,
2810 	    dsl_get_referenced(ds));
2811 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2812 	    dsl_get_creation(ds));
2813 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2814 	    dsl_get_creationtxg(ds));
2815 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2816 	    dsl_get_refquota(ds));
2817 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2818 	    dsl_get_refreservation(ds));
2819 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2820 	    dsl_get_guid(ds));
2821 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2822 	    dsl_get_unique(ds));
2823 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2824 	    dsl_get_objsetid(ds));
2825 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2826 	    dsl_get_userrefs(ds));
2827 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2828 	    dsl_get_defer_destroy(ds));
2829 	dsl_dataset_crypt_stats(ds, nv);
2830 
2831 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2832 		uint64_t written;
2833 		if (dsl_get_written(ds, &written) == 0) {
2834 			dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2835 			    written);
2836 		}
2837 	}
2838 
2839 	if (!dsl_dataset_is_snapshot(ds)) {
2840 		/*
2841 		 * A failed "newfs" (e.g. full) resumable receive leaves
2842 		 * the stats set on this dataset.  Check here for the prop.
2843 		 */
2844 		get_receive_resume_stats(ds, nv);
2845 
2846 		/*
2847 		 * A failed incremental resumable receive leaves the
2848 		 * stats set on our child named "%recv".  Check the child
2849 		 * for the prop.
2850 		 */
2851 		/* 6 extra bytes for /%recv */
2852 		char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
2853 		dsl_dataset_t *recv_ds;
2854 		dsl_dataset_name(ds, recvname);
2855 		if (strlcat(recvname, "/", sizeof (recvname)) <
2856 		    sizeof (recvname) &&
2857 		    strlcat(recvname, recv_clone_name, sizeof (recvname)) <
2858 		    sizeof (recvname) &&
2859 		    dsl_dataset_hold(dp, recvname, FTAG, &recv_ds) == 0) {
2860 			get_receive_resume_stats(recv_ds, nv);
2861 			dsl_dataset_rele(recv_ds, FTAG);
2862 		}
2863 	}
2864 }
2865 
2866 void
2867 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2868 {
2869 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2870 	ASSERT(dsl_pool_config_held(dp));
2871 
2872 	stat->dds_creation_txg = dsl_get_creationtxg(ds);
2873 	stat->dds_inconsistent = dsl_get_inconsistent(ds);
2874 	stat->dds_guid = dsl_get_guid(ds);
2875 	stat->dds_redacted = dsl_get_redacted(ds);
2876 	stat->dds_origin[0] = '\0';
2877 	if (ds->ds_is_snapshot) {
2878 		stat->dds_is_snapshot = B_TRUE;
2879 		stat->dds_num_clones = dsl_get_numclones(ds);
2880 	} else {
2881 		stat->dds_is_snapshot = B_FALSE;
2882 		stat->dds_num_clones = 0;
2883 
2884 		if (dsl_dir_is_clone(ds->ds_dir)) {
2885 			dsl_dir_get_origin(ds->ds_dir, stat->dds_origin);
2886 		}
2887 	}
2888 }
2889 
2890 uint64_t
2891 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2892 {
2893 	return (ds->ds_fsid_guid);
2894 }
2895 
2896 void
2897 dsl_dataset_space(dsl_dataset_t *ds,
2898     uint64_t *refdbytesp, uint64_t *availbytesp,
2899     uint64_t *usedobjsp, uint64_t *availobjsp)
2900 {
2901 	*refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
2902 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2903 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
2904 		*availbytesp +=
2905 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2906 	if (ds->ds_quota != 0) {
2907 		/*
2908 		 * Adjust available bytes according to refquota
2909 		 */
2910 		if (*refdbytesp < ds->ds_quota)
2911 			*availbytesp = MIN(*availbytesp,
2912 			    ds->ds_quota - *refdbytesp);
2913 		else
2914 			*availbytesp = 0;
2915 	}
2916 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2917 	*usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
2918 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2919 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
2920 }
2921 
2922 boolean_t
2923 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
2924 {
2925 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2926 	uint64_t birth;
2927 
2928 	ASSERT(dsl_pool_config_held(dp));
2929 	if (snap == NULL)
2930 		return (B_FALSE);
2931 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2932 	birth = dsl_dataset_get_blkptr(ds)->blk_birth;
2933 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2934 	if (birth > dsl_dataset_phys(snap)->ds_creation_txg) {
2935 		objset_t *os, *os_snap;
2936 		/*
2937 		 * It may be that only the ZIL differs, because it was
2938 		 * reset in the head.  Don't count that as being
2939 		 * modified.
2940 		 */
2941 		if (dmu_objset_from_ds(ds, &os) != 0)
2942 			return (B_TRUE);
2943 		if (dmu_objset_from_ds(snap, &os_snap) != 0)
2944 			return (B_TRUE);
2945 		return (bcmp(&os->os_phys->os_meta_dnode,
2946 		    &os_snap->os_phys->os_meta_dnode,
2947 		    sizeof (os->os_phys->os_meta_dnode)) != 0);
2948 	}
2949 	return (B_FALSE);
2950 }
2951 
2952 typedef struct dsl_dataset_rename_snapshot_arg {
2953 	const char *ddrsa_fsname;
2954 	const char *ddrsa_oldsnapname;
2955 	const char *ddrsa_newsnapname;
2956 	boolean_t ddrsa_recursive;
2957 	dmu_tx_t *ddrsa_tx;
2958 } dsl_dataset_rename_snapshot_arg_t;
2959 
2960 /* ARGSUSED */
2961 static int
2962 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
2963     dsl_dataset_t *hds, void *arg)
2964 {
2965 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2966 	int error;
2967 	uint64_t val;
2968 
2969 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2970 	if (error != 0) {
2971 		/* ignore nonexistent snapshots */
2972 		return (error == ENOENT ? 0 : error);
2973 	}
2974 
2975 	/* new name should not exist */
2976 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
2977 	if (error == 0)
2978 		error = SET_ERROR(EEXIST);
2979 	else if (error == ENOENT)
2980 		error = 0;
2981 
2982 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
2983 	if (dsl_dir_namelen(hds->ds_dir) + 1 +
2984 	    strlen(ddrsa->ddrsa_newsnapname) >= ZFS_MAX_DATASET_NAME_LEN)
2985 		error = SET_ERROR(ENAMETOOLONG);
2986 
2987 	return (error);
2988 }
2989 
2990 static int
2991 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
2992 {
2993 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2994 	dsl_pool_t *dp = dmu_tx_pool(tx);
2995 	dsl_dataset_t *hds;
2996 	int error;
2997 
2998 	error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
2999 	if (error != 0)
3000 		return (error);
3001 
3002 	if (ddrsa->ddrsa_recursive) {
3003 		error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3004 		    dsl_dataset_rename_snapshot_check_impl, ddrsa,
3005 		    DS_FIND_CHILDREN);
3006 	} else {
3007 		error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
3008 	}
3009 	dsl_dataset_rele(hds, FTAG);
3010 	return (error);
3011 }
3012 
3013 static int
3014 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
3015     dsl_dataset_t *hds, void *arg)
3016 {
3017 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3018 	dsl_dataset_t *ds;
3019 	uint64_t val;
3020 	dmu_tx_t *tx = ddrsa->ddrsa_tx;
3021 	int error;
3022 
3023 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
3024 	ASSERT(error == 0 || error == ENOENT);
3025 	if (error == ENOENT) {
3026 		/* ignore nonexistent snapshots */
3027 		return (0);
3028 	}
3029 
3030 	VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
3031 
3032 	/* log before we change the name */
3033 	spa_history_log_internal_ds(ds, "rename", tx,
3034 	    "-> @%s", ddrsa->ddrsa_newsnapname);
3035 
3036 	VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
3037 	    B_FALSE));
3038 	mutex_enter(&ds->ds_lock);
3039 	(void) strlcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname,
3040 	    sizeof (ds->ds_snapname));
3041 	mutex_exit(&ds->ds_lock);
3042 	VERIFY0(zap_add(dp->dp_meta_objset,
3043 	    dsl_dataset_phys(hds)->ds_snapnames_zapobj,
3044 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx));
3045 	zvol_rename_minors(dp->dp_spa, ddrsa->ddrsa_oldsnapname,
3046 	    ddrsa->ddrsa_newsnapname, B_TRUE);
3047 
3048 	dsl_dataset_rele(ds, FTAG);
3049 	return (0);
3050 }
3051 
3052 static void
3053 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
3054 {
3055 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3056 	dsl_pool_t *dp = dmu_tx_pool(tx);
3057 	dsl_dataset_t *hds = NULL;
3058 
3059 	VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
3060 	ddrsa->ddrsa_tx = tx;
3061 	if (ddrsa->ddrsa_recursive) {
3062 		VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3063 		    dsl_dataset_rename_snapshot_sync_impl, ddrsa,
3064 		    DS_FIND_CHILDREN));
3065 	} else {
3066 		VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
3067 	}
3068 	dsl_dataset_rele(hds, FTAG);
3069 }
3070 
3071 int
3072 dsl_dataset_rename_snapshot(const char *fsname,
3073     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
3074 {
3075 	dsl_dataset_rename_snapshot_arg_t ddrsa;
3076 
3077 	ddrsa.ddrsa_fsname = fsname;
3078 	ddrsa.ddrsa_oldsnapname = oldsnapname;
3079 	ddrsa.ddrsa_newsnapname = newsnapname;
3080 	ddrsa.ddrsa_recursive = recursive;
3081 
3082 	return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
3083 	    dsl_dataset_rename_snapshot_sync, &ddrsa,
3084 	    1, ZFS_SPACE_CHECK_RESERVED));
3085 }
3086 
3087 /*
3088  * If we're doing an ownership handoff, we need to make sure that there is
3089  * only one long hold on the dataset.  We're not allowed to change anything here
3090  * so we don't permanently release the long hold or regular hold here.  We want
3091  * to do this only when syncing to avoid the dataset unexpectedly going away
3092  * when we release the long hold.
3093  */
3094 static int
3095 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
3096 {
3097 	boolean_t held = B_FALSE;
3098 
3099 	if (!dmu_tx_is_syncing(tx))
3100 		return (0);
3101 
3102 	dsl_dir_t *dd = ds->ds_dir;
3103 	mutex_enter(&dd->dd_activity_lock);
3104 	uint64_t holds = zfs_refcount_count(&ds->ds_longholds) -
3105 	    (owner != NULL ? 1 : 0);
3106 	/*
3107 	 * The value of dd_activity_waiters can chance as soon as we drop the
3108 	 * lock, but we're fine with that; new waiters coming in or old
3109 	 * waiters leaving doesn't cause problems, since we're going to cancel
3110 	 * waiters later anyway. The goal of this check is to verify that no
3111 	 * non-waiters have long-holds, and all new long-holds will be
3112 	 * prevented because we're holding the pool config as writer.
3113 	 */
3114 	if (holds != dd->dd_activity_waiters)
3115 		held = B_TRUE;
3116 	mutex_exit(&dd->dd_activity_lock);
3117 
3118 	if (held)
3119 		return (SET_ERROR(EBUSY));
3120 
3121 	return (0);
3122 }
3123 
3124 int
3125 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
3126 {
3127 	dsl_dataset_rollback_arg_t *ddra = arg;
3128 	dsl_pool_t *dp = dmu_tx_pool(tx);
3129 	dsl_dataset_t *ds;
3130 	int64_t unused_refres_delta;
3131 	int error;
3132 
3133 	error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
3134 	if (error != 0)
3135 		return (error);
3136 
3137 	/* must not be a snapshot */
3138 	if (ds->ds_is_snapshot) {
3139 		dsl_dataset_rele(ds, FTAG);
3140 		return (SET_ERROR(EINVAL));
3141 	}
3142 
3143 	/* must have a most recent snapshot */
3144 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
3145 		dsl_dataset_rele(ds, FTAG);
3146 		return (SET_ERROR(ESRCH));
3147 	}
3148 
3149 	/*
3150 	 * No rollback to a snapshot created in the current txg, because
3151 	 * the rollback may dirty the dataset and create blocks that are
3152 	 * not reachable from the rootbp while having a birth txg that
3153 	 * falls into the snapshot's range.
3154 	 */
3155 	if (dmu_tx_is_syncing(tx) &&
3156 	    dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg) {
3157 		dsl_dataset_rele(ds, FTAG);
3158 		return (SET_ERROR(EAGAIN));
3159 	}
3160 
3161 	/*
3162 	 * If the expected target snapshot is specified, then check that
3163 	 * the latest snapshot is it.
3164 	 */
3165 	if (ddra->ddra_tosnap != NULL) {
3166 		dsl_dataset_t *snapds;
3167 
3168 		/* Check if the target snapshot exists at all. */
3169 		error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
3170 		if (error != 0) {
3171 			/*
3172 			 * ESRCH is used to signal that the target snapshot does
3173 			 * not exist, while ENOENT is used to report that
3174 			 * the rolled back dataset does not exist.
3175 			 * ESRCH is also used to cover other cases where the
3176 			 * target snapshot is not related to the dataset being
3177 			 * rolled back such as being in a different pool.
3178 			 */
3179 			if (error == ENOENT || error == EXDEV)
3180 				error = SET_ERROR(ESRCH);
3181 			dsl_dataset_rele(ds, FTAG);
3182 			return (error);
3183 		}
3184 		ASSERT(snapds->ds_is_snapshot);
3185 
3186 		/* Check if the snapshot is the latest snapshot indeed. */
3187 		if (snapds != ds->ds_prev) {
3188 			/*
3189 			 * Distinguish between the case where the only problem
3190 			 * is intervening snapshots (EEXIST) vs the snapshot
3191 			 * not being a valid target for rollback (ESRCH).
3192 			 */
3193 			if (snapds->ds_dir == ds->ds_dir ||
3194 			    (dsl_dir_is_clone(ds->ds_dir) &&
3195 			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
3196 			    snapds->ds_object)) {
3197 				error = SET_ERROR(EEXIST);
3198 			} else {
3199 				error = SET_ERROR(ESRCH);
3200 			}
3201 			dsl_dataset_rele(snapds, FTAG);
3202 			dsl_dataset_rele(ds, FTAG);
3203 			return (error);
3204 		}
3205 		dsl_dataset_rele(snapds, FTAG);
3206 	}
3207 
3208 	/* must not have any bookmarks after the most recent snapshot */
3209 	if (dsl_bookmark_latest_txg(ds) >
3210 	    dsl_dataset_phys(ds)->ds_prev_snap_txg) {
3211 		dsl_dataset_rele(ds, FTAG);
3212 		return (SET_ERROR(EEXIST));
3213 	}
3214 
3215 	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
3216 	if (error != 0) {
3217 		dsl_dataset_rele(ds, FTAG);
3218 		return (error);
3219 	}
3220 
3221 	/*
3222 	 * Check if the snap we are rolling back to uses more than
3223 	 * the refquota.
3224 	 */
3225 	if (ds->ds_quota != 0 &&
3226 	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
3227 		dsl_dataset_rele(ds, FTAG);
3228 		return (SET_ERROR(EDQUOT));
3229 	}
3230 
3231 	/*
3232 	 * When we do the clone swap, we will temporarily use more space
3233 	 * due to the refreservation (the head will no longer have any
3234 	 * unique space, so the entire amount of the refreservation will need
3235 	 * to be free).  We will immediately destroy the clone, freeing
3236 	 * this space, but the freeing happens over many txg's.
3237 	 */
3238 	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
3239 	    dsl_dataset_phys(ds)->ds_unique_bytes);
3240 
3241 	if (unused_refres_delta > 0 &&
3242 	    unused_refres_delta >
3243 	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
3244 		dsl_dataset_rele(ds, FTAG);
3245 		return (SET_ERROR(ENOSPC));
3246 	}
3247 
3248 	dsl_dataset_rele(ds, FTAG);
3249 	return (0);
3250 }
3251 
3252 void
3253 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
3254 {
3255 	dsl_dataset_rollback_arg_t *ddra = arg;
3256 	dsl_pool_t *dp = dmu_tx_pool(tx);
3257 	dsl_dataset_t *ds, *clone;
3258 	uint64_t cloneobj;
3259 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3260 
3261 	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
3262 
3263 	dsl_dataset_name(ds->ds_prev, namebuf);
3264 	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
3265 
3266 	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
3267 	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, NULL, tx);
3268 
3269 	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
3270 
3271 	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
3272 	dsl_dataset_zero_zil(ds, tx);
3273 
3274 	dsl_destroy_head_sync_impl(clone, tx);
3275 
3276 	dsl_dataset_rele(clone, FTAG);
3277 	dsl_dataset_rele(ds, FTAG);
3278 }
3279 
3280 /*
3281  * Rolls back the given filesystem or volume to the most recent snapshot.
3282  * The name of the most recent snapshot will be returned under key "target"
3283  * in the result nvlist.
3284  *
3285  * If owner != NULL:
3286  * - The existing dataset MUST be owned by the specified owner at entry
3287  * - Upon return, dataset will still be held by the same owner, whether we
3288  *   succeed or not.
3289  *
3290  * This mode is required any time the existing filesystem is mounted.  See
3291  * notes above zfs_suspend_fs() for further details.
3292  */
3293 int
3294 dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
3295     nvlist_t *result)
3296 {
3297 	dsl_dataset_rollback_arg_t ddra;
3298 
3299 	ddra.ddra_fsname = fsname;
3300 	ddra.ddra_tosnap = tosnap;
3301 	ddra.ddra_owner = owner;
3302 	ddra.ddra_result = result;
3303 
3304 	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
3305 	    dsl_dataset_rollback_sync, &ddra,
3306 	    1, ZFS_SPACE_CHECK_RESERVED));
3307 }
3308 
3309 struct promotenode {
3310 	list_node_t link;
3311 	dsl_dataset_t *ds;
3312 };
3313 
3314 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
3315 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
3316     void *tag);
3317 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
3318 
3319 int
3320 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
3321 {
3322 	dsl_dataset_promote_arg_t *ddpa = arg;
3323 	dsl_pool_t *dp = dmu_tx_pool(tx);
3324 	dsl_dataset_t *hds;
3325 	struct promotenode *snap;
3326 	dsl_dataset_t *origin_ds, *origin_head;
3327 	int err;
3328 	uint64_t unused;
3329 	uint64_t ss_mv_cnt;
3330 	size_t max_snap_len;
3331 	boolean_t conflicting_snaps;
3332 
3333 	err = promote_hold(ddpa, dp, FTAG);
3334 	if (err != 0)
3335 		return (err);
3336 
3337 	hds = ddpa->ddpa_clone;
3338 	max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
3339 
3340 	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
3341 		promote_rele(ddpa, FTAG);
3342 		return (SET_ERROR(EXDEV));
3343 	}
3344 
3345 	snap = list_head(&ddpa->shared_snaps);
3346 	origin_head = snap->ds;
3347 	if (snap == NULL) {
3348 		err = SET_ERROR(ENOENT);
3349 		goto out;
3350 	}
3351 	origin_ds = snap->ds;
3352 
3353 	/*
3354 	 * Encrypted clones share a DSL Crypto Key with their origin's dsl dir.
3355 	 * When doing a promote we must make sure the encryption root for
3356 	 * both the target and the target's origin does not change to avoid
3357 	 * needing to rewrap encryption keys
3358 	 */
3359 	err = dsl_dataset_promote_crypt_check(hds->ds_dir, origin_ds->ds_dir);
3360 	if (err != 0)
3361 		goto out;
3362 
3363 	/*
3364 	 * Compute and check the amount of space to transfer.  Since this is
3365 	 * so expensive, don't do the preliminary check.
3366 	 */
3367 	if (!dmu_tx_is_syncing(tx)) {
3368 		promote_rele(ddpa, FTAG);
3369 		return (0);
3370 	}
3371 
3372 	/* compute origin's new unique space */
3373 	snap = list_tail(&ddpa->clone_snaps);
3374 	ASSERT(snap != NULL);
3375 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3376 	    origin_ds->ds_object);
3377 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3378 	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
3379 	    &ddpa->unique, &unused, &unused);
3380 
3381 	/*
3382 	 * Walk the snapshots that we are moving
3383 	 *
3384 	 * Compute space to transfer.  Consider the incremental changes
3385 	 * to used by each snapshot:
3386 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
3387 	 * So each snapshot gave birth to:
3388 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
3389 	 * So a sequence would look like:
3390 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
3391 	 * Which simplifies to:
3392 	 * uN + kN + kN-1 + ... + k1 + k0
3393 	 * Note however, if we stop before we reach the ORIGIN we get:
3394 	 * uN + kN + kN-1 + ... + kM - uM-1
3395 	 */
3396 	conflicting_snaps = B_FALSE;
3397 	ss_mv_cnt = 0;
3398 	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
3399 	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
3400 	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
3401 	for (snap = list_head(&ddpa->shared_snaps); snap;
3402 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3403 		uint64_t val, dlused, dlcomp, dluncomp;
3404 		dsl_dataset_t *ds = snap->ds;
3405 
3406 		ss_mv_cnt++;
3407 
3408 		/*
3409 		 * If there are long holds, we won't be able to evict
3410 		 * the objset.
3411 		 */
3412 		if (dsl_dataset_long_held(ds)) {
3413 			err = SET_ERROR(EBUSY);
3414 			goto out;
3415 		}
3416 
3417 		/* Check that the snapshot name does not conflict */
3418 		VERIFY0(dsl_dataset_get_snapname(ds));
3419 		if (strlen(ds->ds_snapname) >= max_snap_len) {
3420 			err = SET_ERROR(ENAMETOOLONG);
3421 			goto out;
3422 		}
3423 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
3424 		if (err == 0) {
3425 			fnvlist_add_boolean(ddpa->err_ds,
3426 			    snap->ds->ds_snapname);
3427 			conflicting_snaps = B_TRUE;
3428 		} else if (err != ENOENT) {
3429 			goto out;
3430 		}
3431 
3432 		/* The very first snapshot does not have a deadlist */
3433 		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
3434 			continue;
3435 
3436 		dsl_deadlist_space(&ds->ds_deadlist,
3437 		    &dlused, &dlcomp, &dluncomp);
3438 		ddpa->used += dlused;
3439 		ddpa->comp += dlcomp;
3440 		ddpa->uncomp += dluncomp;
3441 	}
3442 
3443 	/*
3444 	 * Check that bookmarks that are being transferred don't have
3445 	 * name conflicts.
3446 	 */
3447 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3448 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3449 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3450 	    dbn = AVL_NEXT(&origin_head->ds_bookmarks, dbn)) {
3451 		if (strlen(dbn->dbn_name) >= max_snap_len) {
3452 			err = SET_ERROR(ENAMETOOLONG);
3453 			goto out;
3454 		}
3455 		zfs_bookmark_phys_t bm;
3456 		err = dsl_bookmark_lookup_impl(ddpa->ddpa_clone,
3457 		    dbn->dbn_name, &bm);
3458 
3459 		if (err == 0) {
3460 			fnvlist_add_boolean(ddpa->err_ds, dbn->dbn_name);
3461 			conflicting_snaps = B_TRUE;
3462 		} else if (err == ESRCH) {
3463 			err = 0;
3464 		} else if (err != 0) {
3465 			goto out;
3466 		}
3467 	}
3468 
3469 	/*
3470 	 * In order to return the full list of conflicting snapshots, we check
3471 	 * whether there was a conflict after traversing all of them.
3472 	 */
3473 	if (conflicting_snaps) {
3474 		err = SET_ERROR(EEXIST);
3475 		goto out;
3476 	}
3477 
3478 	/*
3479 	 * If we are a clone of a clone then we never reached ORIGIN,
3480 	 * so we need to subtract out the clone origin's used space.
3481 	 */
3482 	if (ddpa->origin_origin) {
3483 		ddpa->used -=
3484 		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
3485 		ddpa->comp -=
3486 		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
3487 		ddpa->uncomp -=
3488 		    dsl_dataset_phys(ddpa->origin_origin)->
3489 		    ds_uncompressed_bytes;
3490 	}
3491 
3492 	/* Check that there is enough space and limit headroom here */
3493 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
3494 	    0, ss_mv_cnt, ddpa->used, ddpa->cr, ddpa->proc);
3495 	if (err != 0)
3496 		goto out;
3497 
3498 	/*
3499 	 * Compute the amounts of space that will be used by snapshots
3500 	 * after the promotion (for both origin and clone).  For each,
3501 	 * it is the amount of space that will be on all of their
3502 	 * deadlists (that was not born before their new origin).
3503 	 */
3504 	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
3505 		uint64_t space;
3506 
3507 		/*
3508 		 * Note, typically this will not be a clone of a clone,
3509 		 * so dd_origin_txg will be < TXG_INITIAL, so
3510 		 * these snaplist_space() -> dsl_deadlist_space_range()
3511 		 * calls will be fast because they do not have to
3512 		 * iterate over all bps.
3513 		 */
3514 		snap = list_head(&ddpa->origin_snaps);
3515 		if (snap == NULL) {
3516 			err = SET_ERROR(ENOENT);
3517 			goto out;
3518 		}
3519 		err = snaplist_space(&ddpa->shared_snaps,
3520 		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
3521 		if (err != 0)
3522 			goto out;
3523 
3524 		err = snaplist_space(&ddpa->clone_snaps,
3525 		    snap->ds->ds_dir->dd_origin_txg, &space);
3526 		if (err != 0)
3527 			goto out;
3528 		ddpa->cloneusedsnap += space;
3529 	}
3530 	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
3531 	    DD_FLAG_USED_BREAKDOWN) {
3532 		err = snaplist_space(&ddpa->origin_snaps,
3533 		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
3534 		    &ddpa->originusedsnap);
3535 		if (err != 0)
3536 			goto out;
3537 	}
3538 
3539 out:
3540 	promote_rele(ddpa, FTAG);
3541 	return (err);
3542 }
3543 
3544 void
3545 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
3546 {
3547 	dsl_dataset_promote_arg_t *ddpa = arg;
3548 	dsl_pool_t *dp = dmu_tx_pool(tx);
3549 	dsl_dataset_t *hds;
3550 	struct promotenode *snap;
3551 	dsl_dataset_t *origin_ds;
3552 	dsl_dataset_t *origin_head;
3553 	dsl_dir_t *dd;
3554 	dsl_dir_t *odd = NULL;
3555 	uint64_t oldnext_obj;
3556 	int64_t delta;
3557 
3558 	ASSERT(nvlist_empty(ddpa->err_ds));
3559 
3560 	VERIFY0(promote_hold(ddpa, dp, FTAG));
3561 	hds = ddpa->ddpa_clone;
3562 
3563 	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
3564 
3565 	snap = list_head(&ddpa->shared_snaps);
3566 	origin_ds = snap->ds;
3567 	dd = hds->ds_dir;
3568 
3569 	snap = list_head(&ddpa->origin_snaps);
3570 	origin_head = snap->ds;
3571 
3572 	/*
3573 	 * We need to explicitly open odd, since origin_ds's dd will be
3574 	 * changing.
3575 	 */
3576 	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
3577 	    NULL, FTAG, &odd));
3578 
3579 	dsl_dataset_promote_crypt_sync(hds->ds_dir, odd, tx);
3580 
3581 	/* change origin's next snap */
3582 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
3583 	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
3584 	snap = list_tail(&ddpa->clone_snaps);
3585 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3586 	    origin_ds->ds_object);
3587 	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
3588 
3589 	/* change the origin's next clone */
3590 	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
3591 		dsl_dataset_remove_from_next_clones(origin_ds,
3592 		    snap->ds->ds_object, tx);
3593 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3594 		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
3595 		    oldnext_obj, tx));
3596 	}
3597 
3598 	/* change origin */
3599 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
3600 	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
3601 	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
3602 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
3603 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
3604 	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
3605 	origin_head->ds_dir->dd_origin_txg =
3606 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3607 
3608 	/* change dd_clone entries */
3609 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3610 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3611 		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
3612 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3613 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3614 		    hds->ds_object, tx));
3615 
3616 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3617 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3618 		    origin_head->ds_object, tx));
3619 		if (dsl_dir_phys(dd)->dd_clones == 0) {
3620 			dsl_dir_phys(dd)->dd_clones =
3621 			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
3622 			    DMU_OT_NONE, 0, tx);
3623 		}
3624 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3625 		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
3626 	}
3627 
3628 	/*
3629 	 * Move bookmarks to this dir.
3630 	 */
3631 	dsl_bookmark_node_t *dbn_next;
3632 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3633 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3634 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3635 	    dbn = dbn_next) {
3636 		dbn_next = AVL_NEXT(&origin_head->ds_bookmarks, dbn);
3637 
3638 		avl_remove(&origin_head->ds_bookmarks, dbn);
3639 		VERIFY0(zap_remove(dp->dp_meta_objset,
3640 		    origin_head->ds_bookmarks_obj, dbn->dbn_name, tx));
3641 
3642 		dsl_bookmark_node_add(hds, dbn, tx);
3643 	}
3644 
3645 	dsl_bookmark_next_changed(hds, origin_ds, tx);
3646 
3647 	/* move snapshots to this dir */
3648 	for (snap = list_head(&ddpa->shared_snaps); snap;
3649 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3650 		dsl_dataset_t *ds = snap->ds;
3651 
3652 		/*
3653 		 * Property callbacks are registered to a particular
3654 		 * dsl_dir.  Since ours is changing, evict the objset
3655 		 * so that they will be unregistered from the old dsl_dir.
3656 		 */
3657 		if (ds->ds_objset) {
3658 			dmu_objset_evict(ds->ds_objset);
3659 			ds->ds_objset = NULL;
3660 		}
3661 
3662 		/* move snap name entry */
3663 		VERIFY0(dsl_dataset_get_snapname(ds));
3664 		VERIFY0(dsl_dataset_snap_remove(origin_head,
3665 		    ds->ds_snapname, tx, B_TRUE));
3666 		VERIFY0(zap_add(dp->dp_meta_objset,
3667 		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3668 		    8, 1, &ds->ds_object, tx));
3669 		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3670 		    DD_FIELD_SNAPSHOT_COUNT, tx);
3671 
3672 		/* change containing dsl_dir */
3673 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3674 		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3675 		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3676 		ASSERT3P(ds->ds_dir, ==, odd);
3677 		dsl_dir_rele(ds->ds_dir, ds);
3678 		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3679 		    NULL, ds, &ds->ds_dir));
3680 
3681 		/* move any clone references */
3682 		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3683 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3684 			zap_cursor_t zc;
3685 			zap_attribute_t za;
3686 
3687 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3688 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3689 			    zap_cursor_retrieve(&zc, &za) == 0;
3690 			    zap_cursor_advance(&zc)) {
3691 				dsl_dataset_t *cnds;
3692 				uint64_t o;
3693 
3694 				if (za.za_first_integer == oldnext_obj) {
3695 					/*
3696 					 * We've already moved the
3697 					 * origin's reference.
3698 					 */
3699 					continue;
3700 				}
3701 
3702 				VERIFY0(dsl_dataset_hold_obj(dp,
3703 				    za.za_first_integer, FTAG, &cnds));
3704 				o = dsl_dir_phys(cnds->ds_dir)->
3705 				    dd_head_dataset_obj;
3706 
3707 				VERIFY0(zap_remove_int(dp->dp_meta_objset,
3708 				    dsl_dir_phys(odd)->dd_clones, o, tx));
3709 				VERIFY0(zap_add_int(dp->dp_meta_objset,
3710 				    dsl_dir_phys(dd)->dd_clones, o, tx));
3711 				dsl_dataset_rele(cnds, FTAG);
3712 			}
3713 			zap_cursor_fini(&zc);
3714 		}
3715 
3716 		ASSERT(!dsl_prop_hascb(ds));
3717 	}
3718 
3719 	/*
3720 	 * Change space accounting.
3721 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3722 	 * both be valid, or both be 0 (resulting in delta == 0).  This
3723 	 * is true for each of {clone,origin} independently.
3724 	 */
3725 
3726 	delta = ddpa->cloneusedsnap -
3727 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3728 	ASSERT3S(delta, >=, 0);
3729 	ASSERT3U(ddpa->used, >=, delta);
3730 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3731 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
3732 	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3733 
3734 	delta = ddpa->originusedsnap -
3735 	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3736 	ASSERT3S(delta, <=, 0);
3737 	ASSERT3U(ddpa->used, >=, -delta);
3738 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3739 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
3740 	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3741 
3742 	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3743 
3744 	/*
3745 	 * Since livelists are specific to a clone's origin txg, they
3746 	 * are no longer accurate. Destroy the livelist from the clone being
3747 	 * promoted. If the origin dataset is a clone, destroy its livelist
3748 	 * as well.
3749 	 */
3750 	dsl_dir_remove_livelist(dd, tx, B_TRUE);
3751 	dsl_dir_remove_livelist(odd, tx, B_TRUE);
3752 
3753 	/* log history record */
3754 	spa_history_log_internal_ds(hds, "promote", tx, " ");
3755 
3756 	dsl_dir_rele(odd, FTAG);
3757 	promote_rele(ddpa, FTAG);
3758 }
3759 
3760 /*
3761  * Make a list of dsl_dataset_t's for the snapshots between first_obj
3762  * (exclusive) and last_obj (inclusive).  The list will be in reverse
3763  * order (last_obj will be the list_head()).  If first_obj == 0, do all
3764  * snapshots back to this dataset's origin.
3765  */
3766 static int
3767 snaplist_make(dsl_pool_t *dp,
3768     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
3769 {
3770 	uint64_t obj = last_obj;
3771 
3772 	list_create(l, sizeof (struct promotenode),
3773 	    offsetof(struct promotenode, link));
3774 
3775 	while (obj != first_obj) {
3776 		dsl_dataset_t *ds;
3777 		struct promotenode *snap;
3778 		int err;
3779 
3780 		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3781 		ASSERT(err != ENOENT);
3782 		if (err != 0)
3783 			return (err);
3784 
3785 		if (first_obj == 0)
3786 			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3787 
3788 		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3789 		snap->ds = ds;
3790 		list_insert_tail(l, snap);
3791 		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3792 	}
3793 
3794 	return (0);
3795 }
3796 
3797 static int
3798 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3799 {
3800 	struct promotenode *snap;
3801 
3802 	*spacep = 0;
3803 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3804 		uint64_t used, comp, uncomp;
3805 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3806 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
3807 		*spacep += used;
3808 	}
3809 	return (0);
3810 }
3811 
3812 static void
3813 snaplist_destroy(list_t *l, void *tag)
3814 {
3815 	struct promotenode *snap;
3816 
3817 	if (l == NULL || !list_link_active(&l->list_head))
3818 		return;
3819 
3820 	while ((snap = list_tail(l)) != NULL) {
3821 		list_remove(l, snap);
3822 		dsl_dataset_rele(snap->ds, tag);
3823 		kmem_free(snap, sizeof (*snap));
3824 	}
3825 	list_destroy(l);
3826 }
3827 
3828 static int
3829 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
3830 {
3831 	int error;
3832 	dsl_dir_t *dd;
3833 	struct promotenode *snap;
3834 
3835 	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3836 	    &ddpa->ddpa_clone);
3837 	if (error != 0)
3838 		return (error);
3839 	dd = ddpa->ddpa_clone->ds_dir;
3840 
3841 	if (ddpa->ddpa_clone->ds_is_snapshot ||
3842 	    !dsl_dir_is_clone(dd)) {
3843 		dsl_dataset_rele(ddpa->ddpa_clone, tag);
3844 		return (SET_ERROR(EINVAL));
3845 	}
3846 
3847 	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3848 	    &ddpa->shared_snaps, tag);
3849 	if (error != 0)
3850 		goto out;
3851 
3852 	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3853 	    &ddpa->clone_snaps, tag);
3854 	if (error != 0)
3855 		goto out;
3856 
3857 	snap = list_head(&ddpa->shared_snaps);
3858 	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3859 	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3860 	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3861 	    &ddpa->origin_snaps, tag);
3862 	if (error != 0)
3863 		goto out;
3864 
3865 	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3866 		error = dsl_dataset_hold_obj(dp,
3867 		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
3868 		    tag, &ddpa->origin_origin);
3869 		if (error != 0)
3870 			goto out;
3871 	}
3872 out:
3873 	if (error != 0)
3874 		promote_rele(ddpa, tag);
3875 	return (error);
3876 }
3877 
3878 static void
3879 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
3880 {
3881 	snaplist_destroy(&ddpa->shared_snaps, tag);
3882 	snaplist_destroy(&ddpa->clone_snaps, tag);
3883 	snaplist_destroy(&ddpa->origin_snaps, tag);
3884 	if (ddpa->origin_origin != NULL)
3885 		dsl_dataset_rele(ddpa->origin_origin, tag);
3886 	dsl_dataset_rele(ddpa->ddpa_clone, tag);
3887 }
3888 
3889 /*
3890  * Promote a clone.
3891  *
3892  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
3893  * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
3894  */
3895 int
3896 dsl_dataset_promote(const char *name, char *conflsnap)
3897 {
3898 	dsl_dataset_promote_arg_t ddpa = { 0 };
3899 	uint64_t numsnaps;
3900 	int error;
3901 	nvpair_t *snap_pair;
3902 	objset_t *os;
3903 
3904 	/*
3905 	 * We will modify space proportional to the number of
3906 	 * snapshots.  Compute numsnaps.
3907 	 */
3908 	error = dmu_objset_hold(name, FTAG, &os);
3909 	if (error != 0)
3910 		return (error);
3911 	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
3912 	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
3913 	    &numsnaps);
3914 	dmu_objset_rele(os, FTAG);
3915 	if (error != 0)
3916 		return (error);
3917 
3918 	ddpa.ddpa_clonename = name;
3919 	ddpa.err_ds = fnvlist_alloc();
3920 	ddpa.cr = CRED();
3921 	ddpa.proc = curproc;
3922 
3923 	error = dsl_sync_task(name, dsl_dataset_promote_check,
3924 	    dsl_dataset_promote_sync, &ddpa,
3925 	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
3926 
3927 	/*
3928 	 * Return the first conflicting snapshot found.
3929 	 */
3930 	snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
3931 	if (snap_pair != NULL && conflsnap != NULL)
3932 		(void) strlcpy(conflsnap, nvpair_name(snap_pair),
3933 		    ZFS_MAX_DATASET_NAME_LEN);
3934 
3935 	fnvlist_free(ddpa.err_ds);
3936 	return (error);
3937 }
3938 
3939 int
3940 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
3941     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
3942 {
3943 	/*
3944 	 * "slack" factor for received datasets with refquota set on them.
3945 	 * See the bottom of this function for details on its use.
3946 	 */
3947 	uint64_t refquota_slack = (uint64_t)DMU_MAX_ACCESS *
3948 	    spa_asize_inflation;
3949 	int64_t unused_refres_delta;
3950 
3951 	/* they should both be heads */
3952 	if (clone->ds_is_snapshot ||
3953 	    origin_head->ds_is_snapshot)
3954 		return (SET_ERROR(EINVAL));
3955 
3956 	/* if we are not forcing, the branch point should be just before them */
3957 	if (!force && clone->ds_prev != origin_head->ds_prev)
3958 		return (SET_ERROR(EINVAL));
3959 
3960 	/* clone should be the clone (unless they are unrelated) */
3961 	if (clone->ds_prev != NULL &&
3962 	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
3963 	    origin_head->ds_dir != clone->ds_prev->ds_dir)
3964 		return (SET_ERROR(EINVAL));
3965 
3966 	/* the clone should be a child of the origin */
3967 	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
3968 		return (SET_ERROR(EINVAL));
3969 
3970 	/* origin_head shouldn't be modified unless 'force' */
3971 	if (!force &&
3972 	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
3973 		return (SET_ERROR(ETXTBSY));
3974 
3975 	/* origin_head should have no long holds (e.g. is not mounted) */
3976 	if (dsl_dataset_handoff_check(origin_head, owner, tx))
3977 		return (SET_ERROR(EBUSY));
3978 
3979 	/* check amount of any unconsumed refreservation */
3980 	unused_refres_delta =
3981 	    (int64_t)MIN(origin_head->ds_reserved,
3982 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
3983 	    (int64_t)MIN(origin_head->ds_reserved,
3984 	    dsl_dataset_phys(clone)->ds_unique_bytes);
3985 
3986 	if (unused_refres_delta > 0 &&
3987 	    unused_refres_delta >
3988 	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
3989 		return (SET_ERROR(ENOSPC));
3990 
3991 	/*
3992 	 * The clone can't be too much over the head's refquota.
3993 	 *
3994 	 * To ensure that the entire refquota can be used, we allow one
3995 	 * transaction to exceed the refquota.  Therefore, this check
3996 	 * needs to also allow for the space referenced to be more than the
3997 	 * refquota.  The maximum amount of space that one transaction can use
3998 	 * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
3999 	 * overage ensures that we are able to receive a filesystem that
4000 	 * exceeds the refquota on the source system.
4001 	 *
4002 	 * So that overage is the refquota_slack we use below.
4003 	 */
4004 	if (origin_head->ds_quota != 0 &&
4005 	    dsl_dataset_phys(clone)->ds_referenced_bytes >
4006 	    origin_head->ds_quota + refquota_slack)
4007 		return (SET_ERROR(EDQUOT));
4008 
4009 	return (0);
4010 }
4011 
4012 static void
4013 dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
4014     dsl_dataset_t *origin, dmu_tx_t *tx)
4015 {
4016 	uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
4017 	dsl_pool_t *dp = dmu_tx_pool(tx);
4018 
4019 	ASSERT(dsl_pool_sync_context(dp));
4020 
4021 	clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
4022 	origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
4023 
4024 	if (clone_remap_dl_obj != 0) {
4025 		dsl_deadlist_close(&clone->ds_remap_deadlist);
4026 		dsl_dataset_unset_remap_deadlist_object(clone, tx);
4027 	}
4028 	if (origin_remap_dl_obj != 0) {
4029 		dsl_deadlist_close(&origin->ds_remap_deadlist);
4030 		dsl_dataset_unset_remap_deadlist_object(origin, tx);
4031 	}
4032 
4033 	if (clone_remap_dl_obj != 0) {
4034 		dsl_dataset_set_remap_deadlist_object(origin,
4035 		    clone_remap_dl_obj, tx);
4036 		dsl_deadlist_open(&origin->ds_remap_deadlist,
4037 		    dp->dp_meta_objset, clone_remap_dl_obj);
4038 	}
4039 	if (origin_remap_dl_obj != 0) {
4040 		dsl_dataset_set_remap_deadlist_object(clone,
4041 		    origin_remap_dl_obj, tx);
4042 		dsl_deadlist_open(&clone->ds_remap_deadlist,
4043 		    dp->dp_meta_objset, origin_remap_dl_obj);
4044 	}
4045 }
4046 
4047 void
4048 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
4049     dsl_dataset_t *origin_head, dmu_tx_t *tx)
4050 {
4051 	dsl_pool_t *dp = dmu_tx_pool(tx);
4052 	int64_t unused_refres_delta;
4053 
4054 	ASSERT(clone->ds_reserved == 0);
4055 	/*
4056 	 * NOTE: On DEBUG kernels there could be a race between this and
4057 	 * the check function if spa_asize_inflation is adjusted...
4058 	 */
4059 	ASSERT(origin_head->ds_quota == 0 ||
4060 	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
4061 	    DMU_MAX_ACCESS * spa_asize_inflation);
4062 	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
4063 
4064 	dsl_dir_cancel_waiters(origin_head->ds_dir);
4065 
4066 	/*
4067 	 * Swap per-dataset feature flags.
4068 	 */
4069 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4070 		if (!(spa_feature_table[f].fi_flags &
4071 		    ZFEATURE_FLAG_PER_DATASET)) {
4072 			ASSERT(!dsl_dataset_feature_is_active(clone, f));
4073 			ASSERT(!dsl_dataset_feature_is_active(origin_head, f));
4074 			continue;
4075 		}
4076 
4077 		boolean_t clone_inuse = dsl_dataset_feature_is_active(clone, f);
4078 		void *clone_feature = clone->ds_feature[f];
4079 		boolean_t origin_head_inuse =
4080 		    dsl_dataset_feature_is_active(origin_head, f);
4081 		void *origin_head_feature = origin_head->ds_feature[f];
4082 
4083 		if (clone_inuse)
4084 			dsl_dataset_deactivate_feature_impl(clone, f, tx);
4085 		if (origin_head_inuse)
4086 			dsl_dataset_deactivate_feature_impl(origin_head, f, tx);
4087 
4088 		if (clone_inuse) {
4089 			dsl_dataset_activate_feature(origin_head->ds_object, f,
4090 			    clone_feature, tx);
4091 			origin_head->ds_feature[f] = clone_feature;
4092 		}
4093 		if (origin_head_inuse) {
4094 			dsl_dataset_activate_feature(clone->ds_object, f,
4095 			    origin_head_feature, tx);
4096 			clone->ds_feature[f] = origin_head_feature;
4097 		}
4098 	}
4099 
4100 	dmu_buf_will_dirty(clone->ds_dbuf, tx);
4101 	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
4102 
4103 	if (clone->ds_objset != NULL) {
4104 		dmu_objset_evict(clone->ds_objset);
4105 		clone->ds_objset = NULL;
4106 	}
4107 
4108 	if (origin_head->ds_objset != NULL) {
4109 		dmu_objset_evict(origin_head->ds_objset);
4110 		origin_head->ds_objset = NULL;
4111 	}
4112 
4113 	unused_refres_delta =
4114 	    (int64_t)MIN(origin_head->ds_reserved,
4115 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4116 	    (int64_t)MIN(origin_head->ds_reserved,
4117 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4118 
4119 	/*
4120 	 * Reset origin's unique bytes.
4121 	 */
4122 	{
4123 		dsl_dataset_t *origin = clone->ds_prev;
4124 		uint64_t comp, uncomp;
4125 
4126 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
4127 		dsl_deadlist_space_range(&clone->ds_deadlist,
4128 		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
4129 		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
4130 	}
4131 
4132 	/* swap blkptrs */
4133 	{
4134 		rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
4135 		rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
4136 		blkptr_t tmp;
4137 		tmp = dsl_dataset_phys(origin_head)->ds_bp;
4138 		dsl_dataset_phys(origin_head)->ds_bp =
4139 		    dsl_dataset_phys(clone)->ds_bp;
4140 		dsl_dataset_phys(clone)->ds_bp = tmp;
4141 		rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
4142 		rrw_exit(&clone->ds_bp_rwlock, FTAG);
4143 	}
4144 
4145 	/* set dd_*_bytes */
4146 	{
4147 		int64_t dused, dcomp, duncomp;
4148 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
4149 		uint64_t odl_used, odl_comp, odl_uncomp;
4150 
4151 		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
4152 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
4153 
4154 		dsl_deadlist_space(&clone->ds_deadlist,
4155 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4156 		dsl_deadlist_space(&origin_head->ds_deadlist,
4157 		    &odl_used, &odl_comp, &odl_uncomp);
4158 
4159 		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
4160 		    cdl_used -
4161 		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
4162 		    odl_used);
4163 		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
4164 		    cdl_comp -
4165 		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
4166 		    odl_comp);
4167 		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
4168 		    cdl_uncomp -
4169 		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
4170 		    odl_uncomp);
4171 
4172 		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
4173 		    dused, dcomp, duncomp, tx);
4174 		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
4175 		    -dused, -dcomp, -duncomp, tx);
4176 
4177 		/*
4178 		 * The difference in the space used by snapshots is the
4179 		 * difference in snapshot space due to the head's
4180 		 * deadlist (since that's the only thing that's
4181 		 * changing that affects the snapused).
4182 		 */
4183 		dsl_deadlist_space_range(&clone->ds_deadlist,
4184 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4185 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4186 		dsl_deadlist_space_range(&origin_head->ds_deadlist,
4187 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4188 		    &odl_used, &odl_comp, &odl_uncomp);
4189 		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
4190 		    DD_USED_HEAD, DD_USED_SNAP, tx);
4191 	}
4192 
4193 	/* swap ds_*_bytes */
4194 	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
4195 	    dsl_dataset_phys(clone)->ds_referenced_bytes);
4196 	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
4197 	    dsl_dataset_phys(clone)->ds_compressed_bytes);
4198 	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
4199 	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
4200 	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
4201 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4202 
4203 	/* apply any parent delta for change in unconsumed refreservation */
4204 	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
4205 	    unused_refres_delta, 0, 0, tx);
4206 
4207 	/*
4208 	 * Swap deadlists.
4209 	 */
4210 	dsl_deadlist_close(&clone->ds_deadlist);
4211 	dsl_deadlist_close(&origin_head->ds_deadlist);
4212 	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
4213 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
4214 	dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
4215 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
4216 	dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
4217 	    dsl_dataset_phys(origin_head)->ds_deadlist_obj);
4218 	dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
4219 
4220 	/*
4221 	 * If there is a bookmark at the origin, its "next dataset" is
4222 	 * changing, so we need to reset its FBN.
4223 	 */
4224 	dsl_bookmark_next_changed(origin_head, origin_head->ds_prev, tx);
4225 
4226 	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
4227 
4228 	/*
4229 	 * Destroy any livelists associated with the clone or the origin,
4230 	 * since after the swap the corresponding livelists are no longer
4231 	 * valid.
4232 	 */
4233 	dsl_dir_remove_livelist(clone->ds_dir, tx, B_TRUE);
4234 	dsl_dir_remove_livelist(origin_head->ds_dir, tx, B_TRUE);
4235 
4236 	spa_history_log_internal_ds(clone, "clone swap", tx,
4237 	    "parent=%s", origin_head->ds_dir->dd_myname);
4238 }
4239 
4240 /*
4241  * Given a pool name and a dataset object number in that pool,
4242  * return the name of that dataset.
4243  */
4244 int
4245 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
4246 {
4247 	dsl_pool_t *dp;
4248 	dsl_dataset_t *ds;
4249 	int error;
4250 
4251 	error = dsl_pool_hold(pname, FTAG, &dp);
4252 	if (error != 0)
4253 		return (error);
4254 
4255 	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
4256 	if (error == 0) {
4257 		dsl_dataset_name(ds, buf);
4258 		dsl_dataset_rele(ds, FTAG);
4259 	}
4260 	dsl_pool_rele(dp, FTAG);
4261 
4262 	return (error);
4263 }
4264 
4265 int
4266 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
4267     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
4268 {
4269 	int error = 0;
4270 
4271 	ASSERT3S(asize, >, 0);
4272 
4273 	/*
4274 	 * *ref_rsrv is the portion of asize that will come from any
4275 	 * unconsumed refreservation space.
4276 	 */
4277 	*ref_rsrv = 0;
4278 
4279 	mutex_enter(&ds->ds_lock);
4280 	/*
4281 	 * Make a space adjustment for reserved bytes.
4282 	 */
4283 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
4284 		ASSERT3U(*used, >=,
4285 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4286 		*used -=
4287 		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4288 		*ref_rsrv =
4289 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
4290 	}
4291 
4292 	if (!check_quota || ds->ds_quota == 0) {
4293 		mutex_exit(&ds->ds_lock);
4294 		return (0);
4295 	}
4296 	/*
4297 	 * If they are requesting more space, and our current estimate
4298 	 * is over quota, they get to try again unless the actual
4299 	 * on-disk is over quota and there are no pending changes (which
4300 	 * may free up space for us).
4301 	 */
4302 	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
4303 	    ds->ds_quota) {
4304 		if (inflight > 0 ||
4305 		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
4306 			error = SET_ERROR(ERESTART);
4307 		else
4308 			error = SET_ERROR(EDQUOT);
4309 	}
4310 	mutex_exit(&ds->ds_lock);
4311 
4312 	return (error);
4313 }
4314 
4315 typedef struct dsl_dataset_set_qr_arg {
4316 	const char *ddsqra_name;
4317 	zprop_source_t ddsqra_source;
4318 	uint64_t ddsqra_value;
4319 } dsl_dataset_set_qr_arg_t;
4320 
4321 
4322 /* ARGSUSED */
4323 static int
4324 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
4325 {
4326 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4327 	dsl_pool_t *dp = dmu_tx_pool(tx);
4328 	dsl_dataset_t *ds;
4329 	int error;
4330 	uint64_t newval;
4331 
4332 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
4333 		return (SET_ERROR(ENOTSUP));
4334 
4335 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4336 	if (error != 0)
4337 		return (error);
4338 
4339 	if (ds->ds_is_snapshot) {
4340 		dsl_dataset_rele(ds, FTAG);
4341 		return (SET_ERROR(EINVAL));
4342 	}
4343 
4344 	error = dsl_prop_predict(ds->ds_dir,
4345 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4346 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4347 	if (error != 0) {
4348 		dsl_dataset_rele(ds, FTAG);
4349 		return (error);
4350 	}
4351 
4352 	if (newval == 0) {
4353 		dsl_dataset_rele(ds, FTAG);
4354 		return (0);
4355 	}
4356 
4357 	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
4358 	    newval < ds->ds_reserved) {
4359 		dsl_dataset_rele(ds, FTAG);
4360 		return (SET_ERROR(ENOSPC));
4361 	}
4362 
4363 	dsl_dataset_rele(ds, FTAG);
4364 	return (0);
4365 }
4366 
4367 static void
4368 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
4369 {
4370 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4371 	dsl_pool_t *dp = dmu_tx_pool(tx);
4372 	dsl_dataset_t *ds = NULL;
4373 	uint64_t newval;
4374 
4375 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4376 
4377 	dsl_prop_set_sync_impl(ds,
4378 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4379 	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
4380 	    &ddsqra->ddsqra_value, tx);
4381 
4382 	VERIFY0(dsl_prop_get_int_ds(ds,
4383 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
4384 
4385 	if (ds->ds_quota != newval) {
4386 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
4387 		ds->ds_quota = newval;
4388 	}
4389 	dsl_dataset_rele(ds, FTAG);
4390 }
4391 
4392 int
4393 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
4394     uint64_t refquota)
4395 {
4396 	dsl_dataset_set_qr_arg_t ddsqra;
4397 
4398 	ddsqra.ddsqra_name = dsname;
4399 	ddsqra.ddsqra_source = source;
4400 	ddsqra.ddsqra_value = refquota;
4401 
4402 	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
4403 	    dsl_dataset_set_refquota_sync, &ddsqra, 0,
4404 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4405 }
4406 
4407 static int
4408 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
4409 {
4410 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4411 	dsl_pool_t *dp = dmu_tx_pool(tx);
4412 	dsl_dataset_t *ds;
4413 	int error;
4414 	uint64_t newval, unique;
4415 
4416 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
4417 		return (SET_ERROR(ENOTSUP));
4418 
4419 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4420 	if (error != 0)
4421 		return (error);
4422 
4423 	if (ds->ds_is_snapshot) {
4424 		dsl_dataset_rele(ds, FTAG);
4425 		return (SET_ERROR(EINVAL));
4426 	}
4427 
4428 	error = dsl_prop_predict(ds->ds_dir,
4429 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4430 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4431 	if (error != 0) {
4432 		dsl_dataset_rele(ds, FTAG);
4433 		return (error);
4434 	}
4435 
4436 	/*
4437 	 * If we are doing the preliminary check in open context, the
4438 	 * space estimates may be inaccurate.
4439 	 */
4440 	if (!dmu_tx_is_syncing(tx)) {
4441 		dsl_dataset_rele(ds, FTAG);
4442 		return (0);
4443 	}
4444 
4445 	mutex_enter(&ds->ds_lock);
4446 	if (!DS_UNIQUE_IS_ACCURATE(ds))
4447 		dsl_dataset_recalc_head_uniq(ds);
4448 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4449 	mutex_exit(&ds->ds_lock);
4450 
4451 	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
4452 		uint64_t delta = MAX(unique, newval) -
4453 		    MAX(unique, ds->ds_reserved);
4454 
4455 		if (delta >
4456 		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
4457 		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
4458 			dsl_dataset_rele(ds, FTAG);
4459 			return (SET_ERROR(ENOSPC));
4460 		}
4461 	}
4462 
4463 	dsl_dataset_rele(ds, FTAG);
4464 	return (0);
4465 }
4466 
4467 void
4468 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
4469     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
4470 {
4471 	uint64_t newval;
4472 	uint64_t unique;
4473 	int64_t delta;
4474 
4475 	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4476 	    source, sizeof (value), 1, &value, tx);
4477 
4478 	VERIFY0(dsl_prop_get_int_ds(ds,
4479 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
4480 
4481 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
4482 	mutex_enter(&ds->ds_dir->dd_lock);
4483 	mutex_enter(&ds->ds_lock);
4484 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
4485 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4486 	delta = MAX(0, (int64_t)(newval - unique)) -
4487 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
4488 	ds->ds_reserved = newval;
4489 	mutex_exit(&ds->ds_lock);
4490 
4491 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
4492 	mutex_exit(&ds->ds_dir->dd_lock);
4493 }
4494 
4495 static void
4496 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
4497 {
4498 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4499 	dsl_pool_t *dp = dmu_tx_pool(tx);
4500 	dsl_dataset_t *ds = NULL;
4501 
4502 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4503 	dsl_dataset_set_refreservation_sync_impl(ds,
4504 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
4505 	dsl_dataset_rele(ds, FTAG);
4506 }
4507 
4508 int
4509 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
4510     uint64_t refreservation)
4511 {
4512 	dsl_dataset_set_qr_arg_t ddsqra;
4513 
4514 	ddsqra.ddsqra_name = dsname;
4515 	ddsqra.ddsqra_source = source;
4516 	ddsqra.ddsqra_value = refreservation;
4517 
4518 	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
4519 	    dsl_dataset_set_refreservation_sync, &ddsqra, 0,
4520 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4521 }
4522 
4523 typedef struct dsl_dataset_set_compression_arg {
4524 	const char *ddsca_name;
4525 	zprop_source_t ddsca_source;
4526 	uint64_t ddsca_value;
4527 } dsl_dataset_set_compression_arg_t;
4528 
4529 /* ARGSUSED */
4530 static int
4531 dsl_dataset_set_compression_check(void *arg, dmu_tx_t *tx)
4532 {
4533 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4534 	dsl_pool_t *dp = dmu_tx_pool(tx);
4535 
4536 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4537 	spa_feature_t f = zio_compress_to_feature(compval);
4538 
4539 	if (f == SPA_FEATURE_NONE)
4540 		return (SET_ERROR(EINVAL));
4541 
4542 	if (!spa_feature_is_enabled(dp->dp_spa, f))
4543 		return (SET_ERROR(ENOTSUP));
4544 
4545 	return (0);
4546 }
4547 
4548 static void
4549 dsl_dataset_set_compression_sync(void *arg, dmu_tx_t *tx)
4550 {
4551 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4552 	dsl_pool_t *dp = dmu_tx_pool(tx);
4553 	dsl_dataset_t *ds = NULL;
4554 
4555 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4556 	spa_feature_t f = zio_compress_to_feature(compval);
4557 	ASSERT3S(spa_feature_table[f].fi_type, ==, ZFEATURE_TYPE_BOOLEAN);
4558 
4559 	VERIFY0(dsl_dataset_hold(dp, ddsca->ddsca_name, FTAG, &ds));
4560 	if (zfeature_active(f, ds->ds_feature[f]) != B_TRUE) {
4561 		ds->ds_feature_activation[f] = (void *)B_TRUE;
4562 		dsl_dataset_activate_feature(ds->ds_object, f,
4563 		    ds->ds_feature_activation[f], tx);
4564 		ds->ds_feature[f] = ds->ds_feature_activation[f];
4565 	}
4566 	dsl_dataset_rele(ds, FTAG);
4567 }
4568 
4569 int
4570 dsl_dataset_set_compression(const char *dsname, zprop_source_t source,
4571     uint64_t compression)
4572 {
4573 	dsl_dataset_set_compression_arg_t ddsca;
4574 
4575 	/*
4576 	 * The sync task is only required for zstd in order to activate
4577 	 * the feature flag when the property is first set.
4578 	 */
4579 	if (ZIO_COMPRESS_ALGO(compression) != ZIO_COMPRESS_ZSTD)
4580 		return (0);
4581 
4582 	ddsca.ddsca_name = dsname;
4583 	ddsca.ddsca_source = source;
4584 	ddsca.ddsca_value = compression;
4585 
4586 	return (dsl_sync_task(dsname, dsl_dataset_set_compression_check,
4587 	    dsl_dataset_set_compression_sync, &ddsca, 0,
4588 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4589 }
4590 
4591 /*
4592  * Return (in *usedp) the amount of space referenced by "new" that was not
4593  * referenced at the time the bookmark corresponds to.  "New" may be a
4594  * snapshot or a head.  The bookmark must be before new, in
4595  * new's filesystem (or its origin) -- caller verifies this.
4596  *
4597  * The written space is calculated by considering two components:  First, we
4598  * ignore any freed space, and calculate the written as new's used space
4599  * minus old's used space.  Next, we add in the amount of space that was freed
4600  * between the two time points, thus reducing new's used space relative to
4601  * old's. Specifically, this is the space that was born before
4602  * zbm_creation_txg, and freed before new (ie. on new's deadlist or a
4603  * previous deadlist).
4604  *
4605  * space freed                         [---------------------]
4606  * snapshots                       ---O-------O--------O-------O------
4607  *                                         bookmark           new
4608  *
4609  * Note, the bookmark's zbm_*_bytes_refd must be valid, but if the HAS_FBN
4610  * flag is not set, we will calculate the freed_before_next based on the
4611  * next snapshot's deadlist, rather than using zbm_*_freed_before_next_snap.
4612  */
4613 static int
4614 dsl_dataset_space_written_impl(zfs_bookmark_phys_t *bmp,
4615     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4616 {
4617 	int err = 0;
4618 	dsl_pool_t *dp = new->ds_dir->dd_pool;
4619 
4620 	ASSERT(dsl_pool_config_held(dp));
4621 	if (dsl_dataset_is_snapshot(new)) {
4622 		ASSERT3U(bmp->zbm_creation_txg, <,
4623 		    dsl_dataset_phys(new)->ds_creation_txg);
4624 	}
4625 
4626 	*usedp = 0;
4627 	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
4628 	*usedp -= bmp->zbm_referenced_bytes_refd;
4629 
4630 	*compp = 0;
4631 	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
4632 	*compp -= bmp->zbm_compressed_bytes_refd;
4633 
4634 	*uncompp = 0;
4635 	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
4636 	*uncompp -= bmp->zbm_uncompressed_bytes_refd;
4637 
4638 	dsl_dataset_t *snap = new;
4639 
4640 	while (dsl_dataset_phys(snap)->ds_prev_snap_txg >
4641 	    bmp->zbm_creation_txg) {
4642 		uint64_t used, comp, uncomp;
4643 
4644 		dsl_deadlist_space_range(&snap->ds_deadlist,
4645 		    0, bmp->zbm_creation_txg,
4646 		    &used, &comp, &uncomp);
4647 		*usedp += used;
4648 		*compp += comp;
4649 		*uncompp += uncomp;
4650 
4651 		uint64_t snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
4652 		if (snap != new)
4653 			dsl_dataset_rele(snap, FTAG);
4654 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4655 		if (err != 0)
4656 			break;
4657 	}
4658 
4659 	/*
4660 	 * We might not have the FBN if we are calculating written from
4661 	 * a snapshot (because we didn't know the correct "next" snapshot
4662 	 * until now).
4663 	 */
4664 	if (bmp->zbm_flags & ZBM_FLAG_HAS_FBN) {
4665 		*usedp += bmp->zbm_referenced_freed_before_next_snap;
4666 		*compp += bmp->zbm_compressed_freed_before_next_snap;
4667 		*uncompp += bmp->zbm_uncompressed_freed_before_next_snap;
4668 	} else {
4669 		ASSERT3U(dsl_dataset_phys(snap)->ds_prev_snap_txg, ==,
4670 		    bmp->zbm_creation_txg);
4671 		uint64_t used, comp, uncomp;
4672 		dsl_deadlist_space(&snap->ds_deadlist, &used, &comp, &uncomp);
4673 		*usedp += used;
4674 		*compp += comp;
4675 		*uncompp += uncomp;
4676 	}
4677 	if (snap != new)
4678 		dsl_dataset_rele(snap, FTAG);
4679 	return (err);
4680 }
4681 
4682 /*
4683  * Return (in *usedp) the amount of space written in new that was not
4684  * present at the time the bookmark corresponds to.  New may be a
4685  * snapshot or the head.  Old must be a bookmark before new, in
4686  * new's filesystem (or its origin) -- caller verifies this.
4687  */
4688 int
4689 dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t *bmp,
4690     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4691 {
4692 	if (!(bmp->zbm_flags & ZBM_FLAG_HAS_FBN))
4693 		return (SET_ERROR(ENOTSUP));
4694 	return (dsl_dataset_space_written_impl(bmp, new,
4695 	    usedp, compp, uncompp));
4696 }
4697 
4698 /*
4699  * Return (in *usedp) the amount of space written in new that is not
4700  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4701  * a snapshot before new, in new's filesystem (or its origin).  If not then
4702  * fail and return EINVAL.
4703  */
4704 int
4705 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4706     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4707 {
4708 	if (!dsl_dataset_is_before(new, oldsnap, 0))
4709 		return (SET_ERROR(EINVAL));
4710 
4711 	zfs_bookmark_phys_t zbm = { 0 };
4712 	dsl_dataset_phys_t *dsp = dsl_dataset_phys(oldsnap);
4713 	zbm.zbm_guid = dsp->ds_guid;
4714 	zbm.zbm_creation_txg = dsp->ds_creation_txg;
4715 	zbm.zbm_creation_time = dsp->ds_creation_time;
4716 	zbm.zbm_referenced_bytes_refd = dsp->ds_referenced_bytes;
4717 	zbm.zbm_compressed_bytes_refd = dsp->ds_compressed_bytes;
4718 	zbm.zbm_uncompressed_bytes_refd = dsp->ds_uncompressed_bytes;
4719 
4720 	/*
4721 	 * If oldsnap is the origin (or origin's origin, ...) of new,
4722 	 * we can't easily calculate the effective FBN.  Therefore,
4723 	 * we do not set ZBM_FLAG_HAS_FBN, so that the _impl will calculate
4724 	 * it relative to the correct "next": the next snapshot towards "new",
4725 	 * rather than the next snapshot in oldsnap's dsl_dir.
4726 	 */
4727 	return (dsl_dataset_space_written_impl(&zbm, new,
4728 	    usedp, compp, uncompp));
4729 }
4730 
4731 /*
4732  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4733  * lastsnap, and all snapshots in between are deleted.
4734  *
4735  * blocks that would be freed            [---------------------------]
4736  * snapshots                       ---O-------O--------O-------O--------O
4737  *                                        firstsnap        lastsnap
4738  *
4739  * This is the set of blocks that were born after the snap before firstsnap,
4740  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4741  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4742  * We calculate this by iterating over the relevant deadlists (from the snap
4743  * after lastsnap, backward to the snap after firstsnap), summing up the
4744  * space on the deadlist that was born after the snap before firstsnap.
4745  */
4746 int
4747 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4748     dsl_dataset_t *lastsnap,
4749     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4750 {
4751 	int err = 0;
4752 	uint64_t snapobj;
4753 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4754 
4755 	ASSERT(firstsnap->ds_is_snapshot);
4756 	ASSERT(lastsnap->ds_is_snapshot);
4757 
4758 	/*
4759 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
4760 	 * is before lastsnap.
4761 	 */
4762 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
4763 	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
4764 	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
4765 		return (SET_ERROR(EINVAL));
4766 
4767 	*usedp = *compp = *uncompp = 0;
4768 
4769 	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
4770 	while (snapobj != firstsnap->ds_object) {
4771 		dsl_dataset_t *ds;
4772 		uint64_t used, comp, uncomp;
4773 
4774 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4775 		if (err != 0)
4776 			break;
4777 
4778 		dsl_deadlist_space_range(&ds->ds_deadlist,
4779 		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
4780 		    &used, &comp, &uncomp);
4781 		*usedp += used;
4782 		*compp += comp;
4783 		*uncompp += uncomp;
4784 
4785 		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4786 		ASSERT3U(snapobj, !=, 0);
4787 		dsl_dataset_rele(ds, FTAG);
4788 	}
4789 	return (err);
4790 }
4791 
4792 /*
4793  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
4794  * For example, they could both be snapshots of the same filesystem, and
4795  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
4796  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
4797  * filesystem.  Or 'earlier' could be the origin's origin.
4798  *
4799  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
4800  */
4801 boolean_t
4802 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4803     uint64_t earlier_txg)
4804 {
4805 	dsl_pool_t *dp = later->ds_dir->dd_pool;
4806 	int error;
4807 	boolean_t ret;
4808 
4809 	ASSERT(dsl_pool_config_held(dp));
4810 	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4811 
4812 	if (earlier_txg == 0)
4813 		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4814 
4815 	if (later->ds_is_snapshot &&
4816 	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4817 		return (B_FALSE);
4818 
4819 	if (later->ds_dir == earlier->ds_dir)
4820 		return (B_TRUE);
4821 
4822 	/*
4823 	 * We check dd_origin_obj explicitly here rather than using
4824 	 * dsl_dir_is_clone() so that we will return TRUE if "earlier"
4825 	 * is $ORIGIN@$ORIGIN.  dsl_dataset_space_written() depends on
4826 	 * this behavior.
4827 	 */
4828 	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == 0)
4829 		return (B_FALSE);
4830 
4831 	dsl_dataset_t *origin;
4832 	error = dsl_dataset_hold_obj(dp,
4833 	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4834 	if (error != 0)
4835 		return (B_FALSE);
4836 	if (dsl_dataset_phys(origin)->ds_creation_txg == earlier_txg &&
4837 	    origin->ds_dir == earlier->ds_dir) {
4838 		dsl_dataset_rele(origin, FTAG);
4839 		return (B_TRUE);
4840 	}
4841 	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4842 	dsl_dataset_rele(origin, FTAG);
4843 	return (ret);
4844 }
4845 
4846 void
4847 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4848 {
4849 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4850 	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4851 }
4852 
4853 boolean_t
4854 dsl_dataset_is_zapified(dsl_dataset_t *ds)
4855 {
4856 	dmu_object_info_t doi;
4857 
4858 	dmu_object_info_from_db(ds->ds_dbuf, &doi);
4859 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4860 }
4861 
4862 boolean_t
4863 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
4864 {
4865 	return (dsl_dataset_is_zapified(ds) &&
4866 	    zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
4867 	    ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
4868 }
4869 
4870 uint64_t
4871 dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
4872 {
4873 	uint64_t remap_deadlist_obj;
4874 	int err;
4875 
4876 	if (!dsl_dataset_is_zapified(ds))
4877 		return (0);
4878 
4879 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4880 	    DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
4881 	    &remap_deadlist_obj);
4882 
4883 	if (err != 0) {
4884 		VERIFY3S(err, ==, ENOENT);
4885 		return (0);
4886 	}
4887 
4888 	ASSERT(remap_deadlist_obj != 0);
4889 	return (remap_deadlist_obj);
4890 }
4891 
4892 boolean_t
4893 dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
4894 {
4895 	EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
4896 	    dsl_dataset_get_remap_deadlist_object(ds) != 0);
4897 	return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
4898 }
4899 
4900 static void
4901 dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
4902     dmu_tx_t *tx)
4903 {
4904 	ASSERT(obj != 0);
4905 	dsl_dataset_zapify(ds, tx);
4906 	VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4907 	    DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
4908 }
4909 
4910 static void
4911 dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
4912 {
4913 	VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
4914 	    ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
4915 }
4916 
4917 void
4918 dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4919 {
4920 	uint64_t remap_deadlist_object;
4921 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4922 
4923 	ASSERT(dmu_tx_is_syncing(tx));
4924 	ASSERT(dsl_dataset_remap_deadlist_exists(ds));
4925 
4926 	remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
4927 	dsl_deadlist_close(&ds->ds_remap_deadlist);
4928 	dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
4929 	dsl_dataset_unset_remap_deadlist_object(ds, tx);
4930 	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4931 }
4932 
4933 void
4934 dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4935 {
4936 	uint64_t remap_deadlist_obj;
4937 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4938 
4939 	ASSERT(dmu_tx_is_syncing(tx));
4940 	ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
4941 	/*
4942 	 * Currently we only create remap deadlists when there are indirect
4943 	 * vdevs with referenced mappings.
4944 	 */
4945 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
4946 
4947 	remap_deadlist_obj = dsl_deadlist_clone(
4948 	    &ds->ds_deadlist, UINT64_MAX,
4949 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
4950 	dsl_dataset_set_remap_deadlist_object(ds,
4951 	    remap_deadlist_obj, tx);
4952 	dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
4953 	    remap_deadlist_obj);
4954 	spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4955 }
4956 
4957 void
4958 dsl_dataset_activate_redaction(dsl_dataset_t *ds, uint64_t *redact_snaps,
4959     uint64_t num_redact_snaps, dmu_tx_t *tx)
4960 {
4961 	uint64_t dsobj = ds->ds_object;
4962 	struct feature_type_uint64_array_arg *ftuaa =
4963 	    kmem_zalloc(sizeof (*ftuaa), KM_SLEEP);
4964 	ftuaa->length = (int64_t)num_redact_snaps;
4965 	if (num_redact_snaps > 0) {
4966 		ftuaa->array = kmem_alloc(num_redact_snaps * sizeof (uint64_t),
4967 		    KM_SLEEP);
4968 		bcopy(redact_snaps, ftuaa->array, num_redact_snaps *
4969 		    sizeof (uint64_t));
4970 	}
4971 	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_REDACTED_DATASETS,
4972 	    ftuaa, tx);
4973 	ds->ds_feature[SPA_FEATURE_REDACTED_DATASETS] = ftuaa;
4974 }
4975 
4976 /* BEGIN CSTYLED */
4977 #if defined(_LP64)
4978 #define	RECORDSIZE_PERM ZMOD_RW
4979 #else
4980 /* Limited to 1M on 32-bit platforms due to lack of virtual address space */
4981 #define	RECORDSIZE_PERM ZMOD_RD
4982 #endif
4983 ZFS_MODULE_PARAM(zfs, zfs_, max_recordsize, INT, RECORDSIZE_PERM,
4984 	"Max allowed record size");
4985 
4986 ZFS_MODULE_PARAM(zfs, zfs_, allow_redacted_dataset_mount, INT, ZMOD_RW,
4987 	"Allow mounting of redacted datasets");
4988 /* END CSTYLED */
4989 
4990 EXPORT_SYMBOL(dsl_dataset_hold);
4991 EXPORT_SYMBOL(dsl_dataset_hold_flags);
4992 EXPORT_SYMBOL(dsl_dataset_hold_obj);
4993 EXPORT_SYMBOL(dsl_dataset_hold_obj_flags);
4994 EXPORT_SYMBOL(dsl_dataset_own);
4995 EXPORT_SYMBOL(dsl_dataset_own_obj);
4996 EXPORT_SYMBOL(dsl_dataset_name);
4997 EXPORT_SYMBOL(dsl_dataset_rele);
4998 EXPORT_SYMBOL(dsl_dataset_rele_flags);
4999 EXPORT_SYMBOL(dsl_dataset_disown);
5000 EXPORT_SYMBOL(dsl_dataset_tryown);
5001 EXPORT_SYMBOL(dsl_dataset_create_sync);
5002 EXPORT_SYMBOL(dsl_dataset_create_sync_dd);
5003 EXPORT_SYMBOL(dsl_dataset_snapshot_check);
5004 EXPORT_SYMBOL(dsl_dataset_snapshot_sync);
5005 EXPORT_SYMBOL(dsl_dataset_promote);
5006 EXPORT_SYMBOL(dsl_dataset_user_hold);
5007 EXPORT_SYMBOL(dsl_dataset_user_release);
5008 EXPORT_SYMBOL(dsl_dataset_get_holds);
5009 EXPORT_SYMBOL(dsl_dataset_get_blkptr);
5010 EXPORT_SYMBOL(dsl_dataset_get_spa);
5011 EXPORT_SYMBOL(dsl_dataset_modified_since_snap);
5012 EXPORT_SYMBOL(dsl_dataset_space_written);
5013 EXPORT_SYMBOL(dsl_dataset_space_wouldfree);
5014 EXPORT_SYMBOL(dsl_dataset_sync);
5015 EXPORT_SYMBOL(dsl_dataset_block_born);
5016 EXPORT_SYMBOL(dsl_dataset_block_kill);
5017 EXPORT_SYMBOL(dsl_dataset_dirty);
5018 EXPORT_SYMBOL(dsl_dataset_stats);
5019 EXPORT_SYMBOL(dsl_dataset_fast_stat);
5020 EXPORT_SYMBOL(dsl_dataset_space);
5021 EXPORT_SYMBOL(dsl_dataset_fsid_guid);
5022 EXPORT_SYMBOL(dsl_dsobj_to_dsname);
5023 EXPORT_SYMBOL(dsl_dataset_check_quota);
5024 EXPORT_SYMBOL(dsl_dataset_clone_swap_check_impl);
5025 EXPORT_SYMBOL(dsl_dataset_clone_swap_sync_impl);
5026