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