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