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