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(ESRCH));
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 		dsl_dataset_t *snapds;
2563 
2564 		/* Check if the target snapshot exists at all. */
2565 		error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
2566 		if (error != 0) {
2567 			/*
2568 			 * ESRCH is used to signal that the target snapshot does
2569 			 * not exist, while ENOENT is used to report that
2570 			 * the rolled back dataset does not exist.
2571 			 * ESRCH is also used to cover other cases where the
2572 			 * target snapshot is not related to the dataset being
2573 			 * rolled back such as being in a different pool.
2574 			 */
2575 			if (error == ENOENT || error == EXDEV)
2576 				error = SET_ERROR(ESRCH);
2577 			dsl_dataset_rele(ds, FTAG);
2578 			return (error);
2579 		}
2580 		ASSERT(snapds->ds_is_snapshot);
2581 
2582 		/* Check if the snapshot is the latest snapshot indeed. */
2583 		if (snapds != ds->ds_prev) {
2584 			/*
2585 			 * Distinguish between the case where the only problem
2586 			 * is intervening snapshots (EEXIST) vs the snapshot
2587 			 * not being a valid target for rollback (ESRCH).
2588 			 */
2589 			if (snapds->ds_dir == ds->ds_dir ||
2590 			    (dsl_dir_is_clone(ds->ds_dir) &&
2591 			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
2592 			    snapds->ds_object)) {
2593 				error = SET_ERROR(EEXIST);
2594 			} else {
2595 				error = SET_ERROR(ESRCH);
2596 			}
2597 			dsl_dataset_rele(snapds, FTAG);
2598 			dsl_dataset_rele(ds, FTAG);
2599 			return (error);
2600 		}
2601 		dsl_dataset_rele(snapds, FTAG);
2602 	}
2603 
2604 	/* must not have any bookmarks after the most recent snapshot */
2605 	nvlist_t *proprequest = fnvlist_alloc();
2606 	fnvlist_add_boolean(proprequest, zfs_prop_to_name(ZFS_PROP_CREATETXG));
2607 	nvlist_t *bookmarks = fnvlist_alloc();
2608 	error = dsl_get_bookmarks_impl(ds, proprequest, bookmarks);
2609 	fnvlist_free(proprequest);
2610 	if (error != 0) {
2611 		dsl_dataset_rele(ds, FTAG);
2612 		return (error);
2613 	}
2614 	for (nvpair_t *pair = nvlist_next_nvpair(bookmarks, NULL);
2615 	    pair != NULL; pair = nvlist_next_nvpair(bookmarks, pair)) {
2616 		nvlist_t *valuenv =
2617 		    fnvlist_lookup_nvlist(fnvpair_value_nvlist(pair),
2618 		    zfs_prop_to_name(ZFS_PROP_CREATETXG));
2619 		uint64_t createtxg = fnvlist_lookup_uint64(valuenv, "value");
2620 		if (createtxg > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
2621 			fnvlist_free(bookmarks);
2622 			dsl_dataset_rele(ds, FTAG);
2623 			return (SET_ERROR(EEXIST));
2624 		}
2625 	}
2626 	fnvlist_free(bookmarks);
2627 
2628 	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
2629 	if (error != 0) {
2630 		dsl_dataset_rele(ds, FTAG);
2631 		return (error);
2632 	}
2633 
2634 	/*
2635 	 * Check if the snap we are rolling back to uses more than
2636 	 * the refquota.
2637 	 */
2638 	if (ds->ds_quota != 0 &&
2639 	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
2640 		dsl_dataset_rele(ds, FTAG);
2641 		return (SET_ERROR(EDQUOT));
2642 	}
2643 
2644 	/*
2645 	 * When we do the clone swap, we will temporarily use more space
2646 	 * due to the refreservation (the head will no longer have any
2647 	 * unique space, so the entire amount of the refreservation will need
2648 	 * to be free).  We will immediately destroy the clone, freeing
2649 	 * this space, but the freeing happens over many txg's.
2650 	 */
2651 	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
2652 	    dsl_dataset_phys(ds)->ds_unique_bytes);
2653 
2654 	if (unused_refres_delta > 0 &&
2655 	    unused_refres_delta >
2656 	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
2657 		dsl_dataset_rele(ds, FTAG);
2658 		return (SET_ERROR(ENOSPC));
2659 	}
2660 
2661 	dsl_dataset_rele(ds, FTAG);
2662 	return (0);
2663 }
2664 
2665 void
2666 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
2667 {
2668 	dsl_dataset_rollback_arg_t *ddra = arg;
2669 	dsl_pool_t *dp = dmu_tx_pool(tx);
2670 	dsl_dataset_t *ds, *clone;
2671 	uint64_t cloneobj;
2672 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
2673 
2674 	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
2675 
2676 	dsl_dataset_name(ds->ds_prev, namebuf);
2677 	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
2678 
2679 	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
2680 	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, tx);
2681 
2682 	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
2683 
2684 	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
2685 	dsl_dataset_zero_zil(ds, tx);
2686 
2687 	dsl_destroy_head_sync_impl(clone, tx);
2688 
2689 	dsl_dataset_rele(clone, FTAG);
2690 	dsl_dataset_rele(ds, FTAG);
2691 }
2692 
2693 /*
2694  * Rolls back the given filesystem or volume to the most recent snapshot.
2695  * The name of the most recent snapshot will be returned under key "target"
2696  * in the result nvlist.
2697  *
2698  * If owner != NULL:
2699  * - The existing dataset MUST be owned by the specified owner at entry
2700  * - Upon return, dataset will still be held by the same owner, whether we
2701  *   succeed or not.
2702  *
2703  * This mode is required any time the existing filesystem is mounted.  See
2704  * notes above zfs_suspend_fs() for further details.
2705  */
2706 int
2707 dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
2708     nvlist_t *result)
2709 {
2710 	dsl_dataset_rollback_arg_t ddra;
2711 
2712 	ddra.ddra_fsname = fsname;
2713 	ddra.ddra_tosnap = tosnap;
2714 	ddra.ddra_owner = owner;
2715 	ddra.ddra_result = result;
2716 
2717 	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
2718 	    dsl_dataset_rollback_sync, &ddra,
2719 	    1, ZFS_SPACE_CHECK_RESERVED));
2720 }
2721 
2722 struct promotenode {
2723 	list_node_t link;
2724 	dsl_dataset_t *ds;
2725 };
2726 
2727 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2728 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
2729     void *tag);
2730 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
2731 
2732 int
2733 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
2734 {
2735 	dsl_dataset_promote_arg_t *ddpa = arg;
2736 	dsl_pool_t *dp = dmu_tx_pool(tx);
2737 	dsl_dataset_t *hds;
2738 	struct promotenode *snap;
2739 	dsl_dataset_t *origin_ds;
2740 	int err;
2741 	uint64_t unused;
2742 	uint64_t ss_mv_cnt;
2743 	size_t max_snap_len;
2744 	boolean_t conflicting_snaps;
2745 
2746 	err = promote_hold(ddpa, dp, FTAG);
2747 	if (err != 0)
2748 		return (err);
2749 
2750 	hds = ddpa->ddpa_clone;
2751 	snap = list_head(&ddpa->shared_snaps);
2752 	origin_ds = snap->ds;
2753 	max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
2754 
2755 	snap = list_head(&ddpa->origin_snaps);
2756 
2757 	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
2758 		promote_rele(ddpa, FTAG);
2759 		return (SET_ERROR(EXDEV));
2760 	}
2761 
2762 	/*
2763 	 * Compute and check the amount of space to transfer.  Since this is
2764 	 * so expensive, don't do the preliminary check.
2765 	 */
2766 	if (!dmu_tx_is_syncing(tx)) {
2767 		promote_rele(ddpa, FTAG);
2768 		return (0);
2769 	}
2770 
2771 	/* compute origin's new unique space */
2772 	snap = list_tail(&ddpa->clone_snaps);
2773 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2774 	    origin_ds->ds_object);
2775 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2776 	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
2777 	    &ddpa->unique, &unused, &unused);
2778 
2779 	/*
2780 	 * Walk the snapshots that we are moving
2781 	 *
2782 	 * Compute space to transfer.  Consider the incremental changes
2783 	 * to used by each snapshot:
2784 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
2785 	 * So each snapshot gave birth to:
2786 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
2787 	 * So a sequence would look like:
2788 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2789 	 * Which simplifies to:
2790 	 * uN + kN + kN-1 + ... + k1 + k0
2791 	 * Note however, if we stop before we reach the ORIGIN we get:
2792 	 * uN + kN + kN-1 + ... + kM - uM-1
2793 	 */
2794 	conflicting_snaps = B_FALSE;
2795 	ss_mv_cnt = 0;
2796 	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
2797 	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
2798 	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
2799 	for (snap = list_head(&ddpa->shared_snaps); snap;
2800 	    snap = list_next(&ddpa->shared_snaps, snap)) {
2801 		uint64_t val, dlused, dlcomp, dluncomp;
2802 		dsl_dataset_t *ds = snap->ds;
2803 
2804 		ss_mv_cnt++;
2805 
2806 		/*
2807 		 * If there are long holds, we won't be able to evict
2808 		 * the objset.
2809 		 */
2810 		if (dsl_dataset_long_held(ds)) {
2811 			err = SET_ERROR(EBUSY);
2812 			goto out;
2813 		}
2814 
2815 		/* Check that the snapshot name does not conflict */
2816 		VERIFY0(dsl_dataset_get_snapname(ds));
2817 		if (strlen(ds->ds_snapname) >= max_snap_len) {
2818 			err = SET_ERROR(ENAMETOOLONG);
2819 			goto out;
2820 		}
2821 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2822 		if (err == 0) {
2823 			fnvlist_add_boolean(ddpa->err_ds,
2824 			    snap->ds->ds_snapname);
2825 			conflicting_snaps = B_TRUE;
2826 		} else if (err != ENOENT) {
2827 			goto out;
2828 		}
2829 
2830 		/* The very first snapshot does not have a deadlist */
2831 		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
2832 			continue;
2833 
2834 		dsl_deadlist_space(&ds->ds_deadlist,
2835 		    &dlused, &dlcomp, &dluncomp);
2836 		ddpa->used += dlused;
2837 		ddpa->comp += dlcomp;
2838 		ddpa->uncomp += dluncomp;
2839 	}
2840 
2841 	/*
2842 	 * In order to return the full list of conflicting snapshots, we check
2843 	 * whether there was a conflict after traversing all of them.
2844 	 */
2845 	if (conflicting_snaps) {
2846 		err = SET_ERROR(EEXIST);
2847 		goto out;
2848 	}
2849 
2850 	/*
2851 	 * If we are a clone of a clone then we never reached ORIGIN,
2852 	 * so we need to subtract out the clone origin's used space.
2853 	 */
2854 	if (ddpa->origin_origin) {
2855 		ddpa->used -=
2856 		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
2857 		ddpa->comp -=
2858 		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
2859 		ddpa->uncomp -=
2860 		    dsl_dataset_phys(ddpa->origin_origin)->
2861 		    ds_uncompressed_bytes;
2862 	}
2863 
2864 	/* Check that there is enough space and limit headroom here */
2865 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2866 	    0, ss_mv_cnt, ddpa->used, ddpa->cr);
2867 	if (err != 0)
2868 		goto out;
2869 
2870 	/*
2871 	 * Compute the amounts of space that will be used by snapshots
2872 	 * after the promotion (for both origin and clone).  For each,
2873 	 * it is the amount of space that will be on all of their
2874 	 * deadlists (that was not born before their new origin).
2875 	 */
2876 	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2877 		uint64_t space;
2878 
2879 		/*
2880 		 * Note, typically this will not be a clone of a clone,
2881 		 * so dd_origin_txg will be < TXG_INITIAL, so
2882 		 * these snaplist_space() -> dsl_deadlist_space_range()
2883 		 * calls will be fast because they do not have to
2884 		 * iterate over all bps.
2885 		 */
2886 		snap = list_head(&ddpa->origin_snaps);
2887 		err = snaplist_space(&ddpa->shared_snaps,
2888 		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
2889 		if (err != 0)
2890 			goto out;
2891 
2892 		err = snaplist_space(&ddpa->clone_snaps,
2893 		    snap->ds->ds_dir->dd_origin_txg, &space);
2894 		if (err != 0)
2895 			goto out;
2896 		ddpa->cloneusedsnap += space;
2897 	}
2898 	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
2899 	    DD_FLAG_USED_BREAKDOWN) {
2900 		err = snaplist_space(&ddpa->origin_snaps,
2901 		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
2902 		    &ddpa->originusedsnap);
2903 		if (err != 0)
2904 			goto out;
2905 	}
2906 
2907 out:
2908 	promote_rele(ddpa, FTAG);
2909 	return (err);
2910 }
2911 
2912 void
2913 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
2914 {
2915 	dsl_dataset_promote_arg_t *ddpa = arg;
2916 	dsl_pool_t *dp = dmu_tx_pool(tx);
2917 	dsl_dataset_t *hds;
2918 	struct promotenode *snap;
2919 	dsl_dataset_t *origin_ds;
2920 	dsl_dataset_t *origin_head;
2921 	dsl_dir_t *dd;
2922 	dsl_dir_t *odd = NULL;
2923 	uint64_t oldnext_obj;
2924 	int64_t delta;
2925 
2926 	VERIFY0(promote_hold(ddpa, dp, FTAG));
2927 	hds = ddpa->ddpa_clone;
2928 
2929 	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
2930 
2931 	snap = list_head(&ddpa->shared_snaps);
2932 	origin_ds = snap->ds;
2933 	dd = hds->ds_dir;
2934 
2935 	snap = list_head(&ddpa->origin_snaps);
2936 	origin_head = snap->ds;
2937 
2938 	/*
2939 	 * We need to explicitly open odd, since origin_ds's dd will be
2940 	 * changing.
2941 	 */
2942 	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
2943 	    NULL, FTAG, &odd));
2944 
2945 	/* change origin's next snap */
2946 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2947 	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
2948 	snap = list_tail(&ddpa->clone_snaps);
2949 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2950 	    origin_ds->ds_object);
2951 	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
2952 
2953 	/* change the origin's next clone */
2954 	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
2955 		dsl_dataset_remove_from_next_clones(origin_ds,
2956 		    snap->ds->ds_object, tx);
2957 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2958 		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
2959 		    oldnext_obj, tx));
2960 	}
2961 
2962 	/* change origin */
2963 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
2964 	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
2965 	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
2966 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2967 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
2968 	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
2969 	origin_head->ds_dir->dd_origin_txg =
2970 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
2971 
2972 	/* change dd_clone entries */
2973 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2974 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
2975 		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
2976 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2977 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2978 		    hds->ds_object, tx));
2979 
2980 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
2981 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2982 		    origin_head->ds_object, tx));
2983 		if (dsl_dir_phys(dd)->dd_clones == 0) {
2984 			dsl_dir_phys(dd)->dd_clones =
2985 			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
2986 			    DMU_OT_NONE, 0, tx);
2987 		}
2988 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2989 		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
2990 	}
2991 
2992 	/* move snapshots to this dir */
2993 	for (snap = list_head(&ddpa->shared_snaps); snap;
2994 	    snap = list_next(&ddpa->shared_snaps, snap)) {
2995 		dsl_dataset_t *ds = snap->ds;
2996 
2997 		/*
2998 		 * Property callbacks are registered to a particular
2999 		 * dsl_dir.  Since ours is changing, evict the objset
3000 		 * so that they will be unregistered from the old dsl_dir.
3001 		 */
3002 		if (ds->ds_objset) {
3003 			dmu_objset_evict(ds->ds_objset);
3004 			ds->ds_objset = NULL;
3005 		}
3006 
3007 		/* move snap name entry */
3008 		VERIFY0(dsl_dataset_get_snapname(ds));
3009 		VERIFY0(dsl_dataset_snap_remove(origin_head,
3010 		    ds->ds_snapname, tx, B_TRUE));
3011 		VERIFY0(zap_add(dp->dp_meta_objset,
3012 		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3013 		    8, 1, &ds->ds_object, tx));
3014 		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3015 		    DD_FIELD_SNAPSHOT_COUNT, tx);
3016 
3017 		/* change containing dsl_dir */
3018 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3019 		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3020 		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3021 		ASSERT3P(ds->ds_dir, ==, odd);
3022 		dsl_dir_rele(ds->ds_dir, ds);
3023 		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3024 		    NULL, ds, &ds->ds_dir));
3025 
3026 		/* move any clone references */
3027 		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3028 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3029 			zap_cursor_t zc;
3030 			zap_attribute_t za;
3031 
3032 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3033 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3034 			    zap_cursor_retrieve(&zc, &za) == 0;
3035 			    zap_cursor_advance(&zc)) {
3036 				dsl_dataset_t *cnds;
3037 				uint64_t o;
3038 
3039 				if (za.za_first_integer == oldnext_obj) {
3040 					/*
3041 					 * We've already moved the
3042 					 * origin's reference.
3043 					 */
3044 					continue;
3045 				}
3046 
3047 				VERIFY0(dsl_dataset_hold_obj(dp,
3048 				    za.za_first_integer, FTAG, &cnds));
3049 				o = dsl_dir_phys(cnds->ds_dir)->
3050 				    dd_head_dataset_obj;
3051 
3052 				VERIFY0(zap_remove_int(dp->dp_meta_objset,
3053 				    dsl_dir_phys(odd)->dd_clones, o, tx));
3054 				VERIFY0(zap_add_int(dp->dp_meta_objset,
3055 				    dsl_dir_phys(dd)->dd_clones, o, tx));
3056 				dsl_dataset_rele(cnds, FTAG);
3057 			}
3058 			zap_cursor_fini(&zc);
3059 		}
3060 
3061 		ASSERT(!dsl_prop_hascb(ds));
3062 	}
3063 
3064 	/*
3065 	 * Change space accounting.
3066 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3067 	 * both be valid, or both be 0 (resulting in delta == 0).  This
3068 	 * is true for each of {clone,origin} independently.
3069 	 */
3070 
3071 	delta = ddpa->cloneusedsnap -
3072 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3073 	ASSERT3S(delta, >=, 0);
3074 	ASSERT3U(ddpa->used, >=, delta);
3075 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3076 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
3077 	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3078 
3079 	delta = ddpa->originusedsnap -
3080 	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3081 	ASSERT3S(delta, <=, 0);
3082 	ASSERT3U(ddpa->used, >=, -delta);
3083 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3084 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
3085 	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3086 
3087 	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3088 
3089 	/* log history record */
3090 	spa_history_log_internal_ds(hds, "promote", tx, "");
3091 
3092 	dsl_dir_rele(odd, FTAG);
3093 	promote_rele(ddpa, FTAG);
3094 }
3095 
3096 /*
3097  * Make a list of dsl_dataset_t's for the snapshots between first_obj
3098  * (exclusive) and last_obj (inclusive).  The list will be in reverse
3099  * order (last_obj will be the list_head()).  If first_obj == 0, do all
3100  * snapshots back to this dataset's origin.
3101  */
3102 static int
3103 snaplist_make(dsl_pool_t *dp,
3104     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
3105 {
3106 	uint64_t obj = last_obj;
3107 
3108 	list_create(l, sizeof (struct promotenode),
3109 	    offsetof(struct promotenode, link));
3110 
3111 	while (obj != first_obj) {
3112 		dsl_dataset_t *ds;
3113 		struct promotenode *snap;
3114 		int err;
3115 
3116 		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3117 		ASSERT(err != ENOENT);
3118 		if (err != 0)
3119 			return (err);
3120 
3121 		if (first_obj == 0)
3122 			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3123 
3124 		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3125 		snap->ds = ds;
3126 		list_insert_tail(l, snap);
3127 		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3128 	}
3129 
3130 	return (0);
3131 }
3132 
3133 static int
3134 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3135 {
3136 	struct promotenode *snap;
3137 
3138 	*spacep = 0;
3139 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3140 		uint64_t used, comp, uncomp;
3141 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3142 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
3143 		*spacep += used;
3144 	}
3145 	return (0);
3146 }
3147 
3148 static void
3149 snaplist_destroy(list_t *l, void *tag)
3150 {
3151 	struct promotenode *snap;
3152 
3153 	if (l == NULL || !list_link_active(&l->list_head))
3154 		return;
3155 
3156 	while ((snap = list_tail(l)) != NULL) {
3157 		list_remove(l, snap);
3158 		dsl_dataset_rele(snap->ds, tag);
3159 		kmem_free(snap, sizeof (*snap));
3160 	}
3161 	list_destroy(l);
3162 }
3163 
3164 static int
3165 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
3166 {
3167 	int error;
3168 	dsl_dir_t *dd;
3169 	struct promotenode *snap;
3170 
3171 	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3172 	    &ddpa->ddpa_clone);
3173 	if (error != 0)
3174 		return (error);
3175 	dd = ddpa->ddpa_clone->ds_dir;
3176 
3177 	if (ddpa->ddpa_clone->ds_is_snapshot ||
3178 	    !dsl_dir_is_clone(dd)) {
3179 		dsl_dataset_rele(ddpa->ddpa_clone, tag);
3180 		return (SET_ERROR(EINVAL));
3181 	}
3182 
3183 	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3184 	    &ddpa->shared_snaps, tag);
3185 	if (error != 0)
3186 		goto out;
3187 
3188 	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3189 	    &ddpa->clone_snaps, tag);
3190 	if (error != 0)
3191 		goto out;
3192 
3193 	snap = list_head(&ddpa->shared_snaps);
3194 	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3195 	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3196 	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3197 	    &ddpa->origin_snaps, tag);
3198 	if (error != 0)
3199 		goto out;
3200 
3201 	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3202 		error = dsl_dataset_hold_obj(dp,
3203 		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
3204 		    tag, &ddpa->origin_origin);
3205 		if (error != 0)
3206 			goto out;
3207 	}
3208 out:
3209 	if (error != 0)
3210 		promote_rele(ddpa, tag);
3211 	return (error);
3212 }
3213 
3214 static void
3215 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
3216 {
3217 	snaplist_destroy(&ddpa->shared_snaps, tag);
3218 	snaplist_destroy(&ddpa->clone_snaps, tag);
3219 	snaplist_destroy(&ddpa->origin_snaps, tag);
3220 	if (ddpa->origin_origin != NULL)
3221 		dsl_dataset_rele(ddpa->origin_origin, tag);
3222 	dsl_dataset_rele(ddpa->ddpa_clone, tag);
3223 }
3224 
3225 /*
3226  * Promote a clone.
3227  *
3228  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
3229  * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
3230  */
3231 int
3232 dsl_dataset_promote(const char *name, char *conflsnap)
3233 {
3234 	dsl_dataset_promote_arg_t ddpa = { 0 };
3235 	uint64_t numsnaps;
3236 	int error;
3237 	nvpair_t *snap_pair;
3238 	objset_t *os;
3239 
3240 	/*
3241 	 * We will modify space proportional to the number of
3242 	 * snapshots.  Compute numsnaps.
3243 	 */
3244 	error = dmu_objset_hold(name, FTAG, &os);
3245 	if (error != 0)
3246 		return (error);
3247 	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
3248 	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
3249 	    &numsnaps);
3250 	dmu_objset_rele(os, FTAG);
3251 	if (error != 0)
3252 		return (error);
3253 
3254 	ddpa.ddpa_clonename = name;
3255 	ddpa.err_ds = fnvlist_alloc();
3256 	ddpa.cr = CRED();
3257 
3258 	error = dsl_sync_task(name, dsl_dataset_promote_check,
3259 	    dsl_dataset_promote_sync, &ddpa,
3260 	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
3261 
3262 	/*
3263 	 * Return the first conflicting snapshot found.
3264 	 */
3265 	snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
3266 	if (snap_pair != NULL && conflsnap != NULL)
3267 		(void) strcpy(conflsnap, nvpair_name(snap_pair));
3268 
3269 	fnvlist_free(ddpa.err_ds);
3270 	return (error);
3271 }
3272 
3273 int
3274 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
3275     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
3276 {
3277 	/*
3278 	 * "slack" factor for received datasets with refquota set on them.
3279 	 * See the bottom of this function for details on its use.
3280 	 */
3281 	uint64_t refquota_slack = DMU_MAX_ACCESS * spa_asize_inflation;
3282 	int64_t unused_refres_delta;
3283 
3284 	/* they should both be heads */
3285 	if (clone->ds_is_snapshot ||
3286 	    origin_head->ds_is_snapshot)
3287 		return (SET_ERROR(EINVAL));
3288 
3289 	/* if we are not forcing, the branch point should be just before them */
3290 	if (!force && clone->ds_prev != origin_head->ds_prev)
3291 		return (SET_ERROR(EINVAL));
3292 
3293 	/* clone should be the clone (unless they are unrelated) */
3294 	if (clone->ds_prev != NULL &&
3295 	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
3296 	    origin_head->ds_dir != clone->ds_prev->ds_dir)
3297 		return (SET_ERROR(EINVAL));
3298 
3299 	/* the clone should be a child of the origin */
3300 	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
3301 		return (SET_ERROR(EINVAL));
3302 
3303 	/* origin_head shouldn't be modified unless 'force' */
3304 	if (!force &&
3305 	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
3306 		return (SET_ERROR(ETXTBSY));
3307 
3308 	/* origin_head should have no long holds (e.g. is not mounted) */
3309 	if (dsl_dataset_handoff_check(origin_head, owner, tx))
3310 		return (SET_ERROR(EBUSY));
3311 
3312 	/* check amount of any unconsumed refreservation */
3313 	unused_refres_delta =
3314 	    (int64_t)MIN(origin_head->ds_reserved,
3315 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
3316 	    (int64_t)MIN(origin_head->ds_reserved,
3317 	    dsl_dataset_phys(clone)->ds_unique_bytes);
3318 
3319 	if (unused_refres_delta > 0 &&
3320 	    unused_refres_delta >
3321 	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
3322 		return (SET_ERROR(ENOSPC));
3323 
3324 	/*
3325 	 * The clone can't be too much over the head's refquota.
3326 	 *
3327 	 * To ensure that the entire refquota can be used, we allow one
3328 	 * transaction to exceed the the refquota.  Therefore, this check
3329 	 * needs to also allow for the space referenced to be more than the
3330 	 * refquota.  The maximum amount of space that one transaction can use
3331 	 * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
3332 	 * overage ensures that we are able to receive a filesystem that
3333 	 * exceeds the refquota on the source system.
3334 	 *
3335 	 * So that overage is the refquota_slack we use below.
3336 	 */
3337 	if (origin_head->ds_quota != 0 &&
3338 	    dsl_dataset_phys(clone)->ds_referenced_bytes >
3339 	    origin_head->ds_quota + refquota_slack)
3340 		return (SET_ERROR(EDQUOT));
3341 
3342 	return (0);
3343 }
3344 
3345 static void
3346 dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
3347     dsl_dataset_t *origin, dmu_tx_t *tx)
3348 {
3349 	uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
3350 	dsl_pool_t *dp = dmu_tx_pool(tx);
3351 
3352 	ASSERT(dsl_pool_sync_context(dp));
3353 
3354 	clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
3355 	origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
3356 
3357 	if (clone_remap_dl_obj != 0) {
3358 		dsl_deadlist_close(&clone->ds_remap_deadlist);
3359 		dsl_dataset_unset_remap_deadlist_object(clone, tx);
3360 	}
3361 	if (origin_remap_dl_obj != 0) {
3362 		dsl_deadlist_close(&origin->ds_remap_deadlist);
3363 		dsl_dataset_unset_remap_deadlist_object(origin, tx);
3364 	}
3365 
3366 	if (clone_remap_dl_obj != 0) {
3367 		dsl_dataset_set_remap_deadlist_object(origin,
3368 		    clone_remap_dl_obj, tx);
3369 		dsl_deadlist_open(&origin->ds_remap_deadlist,
3370 		    dp->dp_meta_objset, clone_remap_dl_obj);
3371 	}
3372 	if (origin_remap_dl_obj != 0) {
3373 		dsl_dataset_set_remap_deadlist_object(clone,
3374 		    origin_remap_dl_obj, tx);
3375 		dsl_deadlist_open(&clone->ds_remap_deadlist,
3376 		    dp->dp_meta_objset, origin_remap_dl_obj);
3377 	}
3378 }
3379 
3380 void
3381 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
3382     dsl_dataset_t *origin_head, dmu_tx_t *tx)
3383 {
3384 	dsl_pool_t *dp = dmu_tx_pool(tx);
3385 	int64_t unused_refres_delta;
3386 
3387 	ASSERT(clone->ds_reserved == 0);
3388 	/*
3389 	 * NOTE: On DEBUG kernels there could be a race between this and
3390 	 * the check function if spa_asize_inflation is adjusted...
3391 	 */
3392 	ASSERT(origin_head->ds_quota == 0 ||
3393 	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
3394 	    DMU_MAX_ACCESS * spa_asize_inflation);
3395 	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
3396 
3397 	/*
3398 	 * Swap per-dataset feature flags.
3399 	 */
3400 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
3401 		if (!(spa_feature_table[f].fi_flags &
3402 		    ZFEATURE_FLAG_PER_DATASET)) {
3403 			ASSERT(!clone->ds_feature_inuse[f]);
3404 			ASSERT(!origin_head->ds_feature_inuse[f]);
3405 			continue;
3406 		}
3407 
3408 		boolean_t clone_inuse = clone->ds_feature_inuse[f];
3409 		boolean_t origin_head_inuse = origin_head->ds_feature_inuse[f];
3410 
3411 		if (clone_inuse) {
3412 			dsl_dataset_deactivate_feature(clone->ds_object, f, tx);
3413 			clone->ds_feature_inuse[f] = B_FALSE;
3414 		}
3415 		if (origin_head_inuse) {
3416 			dsl_dataset_deactivate_feature(origin_head->ds_object,
3417 			    f, tx);
3418 			origin_head->ds_feature_inuse[f] = B_FALSE;
3419 		}
3420 		if (clone_inuse) {
3421 			dsl_dataset_activate_feature(origin_head->ds_object,
3422 			    f, tx);
3423 			origin_head->ds_feature_inuse[f] = B_TRUE;
3424 		}
3425 		if (origin_head_inuse) {
3426 			dsl_dataset_activate_feature(clone->ds_object, f, tx);
3427 			clone->ds_feature_inuse[f] = B_TRUE;
3428 		}
3429 	}
3430 
3431 	dmu_buf_will_dirty(clone->ds_dbuf, tx);
3432 	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3433 
3434 	if (clone->ds_objset != NULL) {
3435 		dmu_objset_evict(clone->ds_objset);
3436 		clone->ds_objset = NULL;
3437 	}
3438 
3439 	if (origin_head->ds_objset != NULL) {
3440 		dmu_objset_evict(origin_head->ds_objset);
3441 		origin_head->ds_objset = NULL;
3442 	}
3443 
3444 	unused_refres_delta =
3445 	    (int64_t)MIN(origin_head->ds_reserved,
3446 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
3447 	    (int64_t)MIN(origin_head->ds_reserved,
3448 	    dsl_dataset_phys(clone)->ds_unique_bytes);
3449 
3450 	/*
3451 	 * Reset origin's unique bytes, if it exists.
3452 	 */
3453 	if (clone->ds_prev) {
3454 		dsl_dataset_t *origin = clone->ds_prev;
3455 		uint64_t comp, uncomp;
3456 
3457 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
3458 		dsl_deadlist_space_range(&clone->ds_deadlist,
3459 		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
3460 		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
3461 	}
3462 
3463 	/* swap blkptrs */
3464 	{
3465 		rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
3466 		rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
3467 		blkptr_t tmp;
3468 		tmp = dsl_dataset_phys(origin_head)->ds_bp;
3469 		dsl_dataset_phys(origin_head)->ds_bp =
3470 		    dsl_dataset_phys(clone)->ds_bp;
3471 		dsl_dataset_phys(clone)->ds_bp = tmp;
3472 		rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
3473 		rrw_exit(&clone->ds_bp_rwlock, FTAG);
3474 	}
3475 
3476 	/* set dd_*_bytes */
3477 	{
3478 		int64_t dused, dcomp, duncomp;
3479 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
3480 		uint64_t odl_used, odl_comp, odl_uncomp;
3481 
3482 		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
3483 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
3484 
3485 		dsl_deadlist_space(&clone->ds_deadlist,
3486 		    &cdl_used, &cdl_comp, &cdl_uncomp);
3487 		dsl_deadlist_space(&origin_head->ds_deadlist,
3488 		    &odl_used, &odl_comp, &odl_uncomp);
3489 
3490 		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
3491 		    cdl_used -
3492 		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
3493 		    odl_used);
3494 		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
3495 		    cdl_comp -
3496 		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
3497 		    odl_comp);
3498 		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
3499 		    cdl_uncomp -
3500 		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
3501 		    odl_uncomp);
3502 
3503 		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
3504 		    dused, dcomp, duncomp, tx);
3505 		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
3506 		    -dused, -dcomp, -duncomp, tx);
3507 
3508 		/*
3509 		 * The difference in the space used by snapshots is the
3510 		 * difference in snapshot space due to the head's
3511 		 * deadlist (since that's the only thing that's
3512 		 * changing that affects the snapused).
3513 		 */
3514 		dsl_deadlist_space_range(&clone->ds_deadlist,
3515 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
3516 		    &cdl_used, &cdl_comp, &cdl_uncomp);
3517 		dsl_deadlist_space_range(&origin_head->ds_deadlist,
3518 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
3519 		    &odl_used, &odl_comp, &odl_uncomp);
3520 		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
3521 		    DD_USED_HEAD, DD_USED_SNAP, tx);
3522 	}
3523 
3524 	/* swap ds_*_bytes */
3525 	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
3526 	    dsl_dataset_phys(clone)->ds_referenced_bytes);
3527 	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
3528 	    dsl_dataset_phys(clone)->ds_compressed_bytes);
3529 	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
3530 	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
3531 	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
3532 	    dsl_dataset_phys(clone)->ds_unique_bytes);
3533 
3534 	/* apply any parent delta for change in unconsumed refreservation */
3535 	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
3536 	    unused_refres_delta, 0, 0, tx);
3537 
3538 	/*
3539 	 * Swap deadlists.
3540 	 */
3541 	dsl_deadlist_close(&clone->ds_deadlist);
3542 	dsl_deadlist_close(&origin_head->ds_deadlist);
3543 	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
3544 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
3545 	dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
3546 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
3547 	dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
3548 	    dsl_dataset_phys(origin_head)->ds_deadlist_obj);
3549 	dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
3550 
3551 	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
3552 
3553 	spa_history_log_internal_ds(clone, "clone swap", tx,
3554 	    "parent=%s", origin_head->ds_dir->dd_myname);
3555 }
3556 
3557 /*
3558  * Given a pool name and a dataset object number in that pool,
3559  * return the name of that dataset.
3560  */
3561 int
3562 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
3563 {
3564 	dsl_pool_t *dp;
3565 	dsl_dataset_t *ds;
3566 	int error;
3567 
3568 	error = dsl_pool_hold(pname, FTAG, &dp);
3569 	if (error != 0)
3570 		return (error);
3571 
3572 	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
3573 	if (error == 0) {
3574 		dsl_dataset_name(ds, buf);
3575 		dsl_dataset_rele(ds, FTAG);
3576 	}
3577 	dsl_pool_rele(dp, FTAG);
3578 
3579 	return (error);
3580 }
3581 
3582 int
3583 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
3584     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
3585 {
3586 	int error = 0;
3587 
3588 	ASSERT3S(asize, >, 0);
3589 
3590 	/*
3591 	 * *ref_rsrv is the portion of asize that will come from any
3592 	 * unconsumed refreservation space.
3593 	 */
3594 	*ref_rsrv = 0;
3595 
3596 	mutex_enter(&ds->ds_lock);
3597 	/*
3598 	 * Make a space adjustment for reserved bytes.
3599 	 */
3600 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
3601 		ASSERT3U(*used, >=,
3602 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
3603 		*used -=
3604 		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
3605 		*ref_rsrv =
3606 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
3607 	}
3608 
3609 	if (!check_quota || ds->ds_quota == 0) {
3610 		mutex_exit(&ds->ds_lock);
3611 		return (0);
3612 	}
3613 	/*
3614 	 * If they are requesting more space, and our current estimate
3615 	 * is over quota, they get to try again unless the actual
3616 	 * on-disk is over quota and there are no pending changes (which
3617 	 * may free up space for us).
3618 	 */
3619 	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
3620 	    ds->ds_quota) {
3621 		if (inflight > 0 ||
3622 		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
3623 			error = SET_ERROR(ERESTART);
3624 		else
3625 			error = SET_ERROR(EDQUOT);
3626 	}
3627 	mutex_exit(&ds->ds_lock);
3628 
3629 	return (error);
3630 }
3631 
3632 typedef struct dsl_dataset_set_qr_arg {
3633 	const char *ddsqra_name;
3634 	zprop_source_t ddsqra_source;
3635 	uint64_t ddsqra_value;
3636 } dsl_dataset_set_qr_arg_t;
3637 
3638 
3639 /* ARGSUSED */
3640 static int
3641 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
3642 {
3643 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
3644 	dsl_pool_t *dp = dmu_tx_pool(tx);
3645 	dsl_dataset_t *ds;
3646 	int error;
3647 	uint64_t newval;
3648 
3649 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
3650 		return (SET_ERROR(ENOTSUP));
3651 
3652 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
3653 	if (error != 0)
3654 		return (error);
3655 
3656 	if (ds->ds_is_snapshot) {
3657 		dsl_dataset_rele(ds, FTAG);
3658 		return (SET_ERROR(EINVAL));
3659 	}
3660 
3661 	error = dsl_prop_predict(ds->ds_dir,
3662 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
3663 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
3664 	if (error != 0) {
3665 		dsl_dataset_rele(ds, FTAG);
3666 		return (error);
3667 	}
3668 
3669 	if (newval == 0) {
3670 		dsl_dataset_rele(ds, FTAG);
3671 		return (0);
3672 	}
3673 
3674 	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
3675 	    newval < ds->ds_reserved) {
3676 		dsl_dataset_rele(ds, FTAG);
3677 		return (SET_ERROR(ENOSPC));
3678 	}
3679 
3680 	dsl_dataset_rele(ds, FTAG);
3681 	return (0);
3682 }
3683 
3684 static void
3685 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
3686 {
3687 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
3688 	dsl_pool_t *dp = dmu_tx_pool(tx);
3689 	dsl_dataset_t *ds;
3690 	uint64_t newval;
3691 
3692 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3693 
3694 	dsl_prop_set_sync_impl(ds,
3695 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
3696 	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
3697 	    &ddsqra->ddsqra_value, tx);
3698 
3699 	VERIFY0(dsl_prop_get_int_ds(ds,
3700 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
3701 
3702 	if (ds->ds_quota != newval) {
3703 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3704 		ds->ds_quota = newval;
3705 	}
3706 	dsl_dataset_rele(ds, FTAG);
3707 }
3708 
3709 int
3710 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
3711     uint64_t refquota)
3712 {
3713 	dsl_dataset_set_qr_arg_t ddsqra;
3714 
3715 	ddsqra.ddsqra_name = dsname;
3716 	ddsqra.ddsqra_source = source;
3717 	ddsqra.ddsqra_value = refquota;
3718 
3719 	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
3720 	    dsl_dataset_set_refquota_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
3721 }
3722 
3723 static int
3724 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
3725 {
3726 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
3727 	dsl_pool_t *dp = dmu_tx_pool(tx);
3728 	dsl_dataset_t *ds;
3729 	int error;
3730 	uint64_t newval, unique;
3731 
3732 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
3733 		return (SET_ERROR(ENOTSUP));
3734 
3735 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
3736 	if (error != 0)
3737 		return (error);
3738 
3739 	if (ds->ds_is_snapshot) {
3740 		dsl_dataset_rele(ds, FTAG);
3741 		return (SET_ERROR(EINVAL));
3742 	}
3743 
3744 	error = dsl_prop_predict(ds->ds_dir,
3745 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
3746 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
3747 	if (error != 0) {
3748 		dsl_dataset_rele(ds, FTAG);
3749 		return (error);
3750 	}
3751 
3752 	/*
3753 	 * If we are doing the preliminary check in open context, the
3754 	 * space estimates may be inaccurate.
3755 	 */
3756 	if (!dmu_tx_is_syncing(tx)) {
3757 		dsl_dataset_rele(ds, FTAG);
3758 		return (0);
3759 	}
3760 
3761 	mutex_enter(&ds->ds_lock);
3762 	if (!DS_UNIQUE_IS_ACCURATE(ds))
3763 		dsl_dataset_recalc_head_uniq(ds);
3764 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
3765 	mutex_exit(&ds->ds_lock);
3766 
3767 	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
3768 		uint64_t delta = MAX(unique, newval) -
3769 		    MAX(unique, ds->ds_reserved);
3770 
3771 		if (delta >
3772 		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
3773 		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
3774 			dsl_dataset_rele(ds, FTAG);
3775 			return (SET_ERROR(ENOSPC));
3776 		}
3777 	}
3778 
3779 	dsl_dataset_rele(ds, FTAG);
3780 	return (0);
3781 }
3782 
3783 void
3784 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
3785     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
3786 {
3787 	uint64_t newval;
3788 	uint64_t unique;
3789 	int64_t delta;
3790 
3791 	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
3792 	    source, sizeof (value), 1, &value, tx);
3793 
3794 	VERIFY0(dsl_prop_get_int_ds(ds,
3795 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
3796 
3797 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
3798 	mutex_enter(&ds->ds_dir->dd_lock);
3799 	mutex_enter(&ds->ds_lock);
3800 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3801 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
3802 	delta = MAX(0, (int64_t)(newval - unique)) -
3803 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
3804 	ds->ds_reserved = newval;
3805 	mutex_exit(&ds->ds_lock);
3806 
3807 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3808 	mutex_exit(&ds->ds_dir->dd_lock);
3809 }
3810 
3811 static void
3812 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
3813 {
3814 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
3815 	dsl_pool_t *dp = dmu_tx_pool(tx);
3816 	dsl_dataset_t *ds;
3817 
3818 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3819 	dsl_dataset_set_refreservation_sync_impl(ds,
3820 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
3821 	dsl_dataset_rele(ds, FTAG);
3822 }
3823 
3824 int
3825 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
3826     uint64_t refreservation)
3827 {
3828 	dsl_dataset_set_qr_arg_t ddsqra;
3829 
3830 	ddsqra.ddsqra_name = dsname;
3831 	ddsqra.ddsqra_source = source;
3832 	ddsqra.ddsqra_value = refreservation;
3833 
3834 	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
3835 	    dsl_dataset_set_refreservation_sync, &ddsqra,
3836 	    0, ZFS_SPACE_CHECK_NONE));
3837 }
3838 
3839 /*
3840  * Return (in *usedp) the amount of space written in new that is not
3841  * present in oldsnap.  New may be a snapshot or the head.  Old must be
3842  * a snapshot before new, in new's filesystem (or its origin).  If not then
3843  * fail and return EINVAL.
3844  *
3845  * The written space is calculated by considering two components:  First, we
3846  * ignore any freed space, and calculate the written as new's used space
3847  * minus old's used space.  Next, we add in the amount of space that was freed
3848  * between the two snapshots, thus reducing new's used space relative to old's.
3849  * Specifically, this is the space that was born before old->ds_creation_txg,
3850  * and freed before new (ie. on new's deadlist or a previous deadlist).
3851  *
3852  * space freed                         [---------------------]
3853  * snapshots                       ---O-------O--------O-------O------
3854  *                                         oldsnap            new
3855  */
3856 int
3857 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
3858     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3859 {
3860 	int err = 0;
3861 	uint64_t snapobj;
3862 	dsl_pool_t *dp = new->ds_dir->dd_pool;
3863 
3864 	ASSERT(dsl_pool_config_held(dp));
3865 
3866 	*usedp = 0;
3867 	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
3868 	*usedp -= dsl_dataset_phys(oldsnap)->ds_referenced_bytes;
3869 
3870 	*compp = 0;
3871 	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
3872 	*compp -= dsl_dataset_phys(oldsnap)->ds_compressed_bytes;
3873 
3874 	*uncompp = 0;
3875 	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
3876 	*uncompp -= dsl_dataset_phys(oldsnap)->ds_uncompressed_bytes;
3877 
3878 	snapobj = new->ds_object;
3879 	while (snapobj != oldsnap->ds_object) {
3880 		dsl_dataset_t *snap;
3881 		uint64_t used, comp, uncomp;
3882 
3883 		if (snapobj == new->ds_object) {
3884 			snap = new;
3885 		} else {
3886 			err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
3887 			if (err != 0)
3888 				break;
3889 		}
3890 
3891 		if (dsl_dataset_phys(snap)->ds_prev_snap_txg ==
3892 		    dsl_dataset_phys(oldsnap)->ds_creation_txg) {
3893 			/*
3894 			 * The blocks in the deadlist can not be born after
3895 			 * ds_prev_snap_txg, so get the whole deadlist space,
3896 			 * which is more efficient (especially for old-format
3897 			 * deadlists).  Unfortunately the deadlist code
3898 			 * doesn't have enough information to make this
3899 			 * optimization itself.
3900 			 */
3901 			dsl_deadlist_space(&snap->ds_deadlist,
3902 			    &used, &comp, &uncomp);
3903 		} else {
3904 			dsl_deadlist_space_range(&snap->ds_deadlist,
3905 			    0, dsl_dataset_phys(oldsnap)->ds_creation_txg,
3906 			    &used, &comp, &uncomp);
3907 		}
3908 		*usedp += used;
3909 		*compp += comp;
3910 		*uncompp += uncomp;
3911 
3912 		/*
3913 		 * If we get to the beginning of the chain of snapshots
3914 		 * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
3915 		 * was not a snapshot of/before new.
3916 		 */
3917 		snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3918 		if (snap != new)
3919 			dsl_dataset_rele(snap, FTAG);
3920 		if (snapobj == 0) {
3921 			err = SET_ERROR(EINVAL);
3922 			break;
3923 		}
3924 
3925 	}
3926 	return (err);
3927 }
3928 
3929 /*
3930  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
3931  * lastsnap, and all snapshots in between are deleted.
3932  *
3933  * blocks that would be freed            [---------------------------]
3934  * snapshots                       ---O-------O--------O-------O--------O
3935  *                                        firstsnap        lastsnap
3936  *
3937  * This is the set of blocks that were born after the snap before firstsnap,
3938  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
3939  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
3940  * We calculate this by iterating over the relevant deadlists (from the snap
3941  * after lastsnap, backward to the snap after firstsnap), summing up the
3942  * space on the deadlist that was born after the snap before firstsnap.
3943  */
3944 int
3945 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
3946     dsl_dataset_t *lastsnap,
3947     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3948 {
3949 	int err = 0;
3950 	uint64_t snapobj;
3951 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
3952 
3953 	ASSERT(firstsnap->ds_is_snapshot);
3954 	ASSERT(lastsnap->ds_is_snapshot);
3955 
3956 	/*
3957 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
3958 	 * is before lastsnap.
3959 	 */
3960 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
3961 	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
3962 	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
3963 		return (SET_ERROR(EINVAL));
3964 
3965 	*usedp = *compp = *uncompp = 0;
3966 
3967 	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
3968 	while (snapobj != firstsnap->ds_object) {
3969 		dsl_dataset_t *ds;
3970 		uint64_t used, comp, uncomp;
3971 
3972 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
3973 		if (err != 0)
3974 			break;
3975 
3976 		dsl_deadlist_space_range(&ds->ds_deadlist,
3977 		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
3978 		    &used, &comp, &uncomp);
3979 		*usedp += used;
3980 		*compp += comp;
3981 		*uncompp += uncomp;
3982 
3983 		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3984 		ASSERT3U(snapobj, !=, 0);
3985 		dsl_dataset_rele(ds, FTAG);
3986 	}
3987 	return (err);
3988 }
3989 
3990 /*
3991  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
3992  * For example, they could both be snapshots of the same filesystem, and
3993  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
3994  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
3995  * filesystem.  Or 'earlier' could be the origin's origin.
3996  *
3997  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
3998  */
3999 boolean_t
4000 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4001     uint64_t earlier_txg)
4002 {
4003 	dsl_pool_t *dp = later->ds_dir->dd_pool;
4004 	int error;
4005 	boolean_t ret;
4006 
4007 	ASSERT(dsl_pool_config_held(dp));
4008 	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4009 
4010 	if (earlier_txg == 0)
4011 		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4012 
4013 	if (later->ds_is_snapshot &&
4014 	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4015 		return (B_FALSE);
4016 
4017 	if (later->ds_dir == earlier->ds_dir)
4018 		return (B_TRUE);
4019 	if (!dsl_dir_is_clone(later->ds_dir))
4020 		return (B_FALSE);
4021 
4022 	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == earlier->ds_object)
4023 		return (B_TRUE);
4024 	dsl_dataset_t *origin;
4025 	error = dsl_dataset_hold_obj(dp,
4026 	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4027 	if (error != 0)
4028 		return (B_FALSE);
4029 	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4030 	dsl_dataset_rele(origin, FTAG);
4031 	return (ret);
4032 }
4033 
4034 void
4035 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4036 {
4037 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4038 	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4039 }
4040 
4041 boolean_t
4042 dsl_dataset_is_zapified(dsl_dataset_t *ds)
4043 {
4044 	dmu_object_info_t doi;
4045 
4046 	dmu_object_info_from_db(ds->ds_dbuf, &doi);
4047 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4048 }
4049 
4050 boolean_t
4051 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
4052 {
4053 	return (dsl_dataset_is_zapified(ds) &&
4054 	    zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
4055 	    ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
4056 }
4057 
4058 uint64_t
4059 dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
4060 {
4061 	uint64_t remap_deadlist_obj;
4062 	int err;
4063 
4064 	if (!dsl_dataset_is_zapified(ds))
4065 		return (0);
4066 
4067 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4068 	    DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
4069 	    &remap_deadlist_obj);
4070 
4071 	if (err != 0) {
4072 		VERIFY3S(err, ==, ENOENT);
4073 		return (0);
4074 	}
4075 
4076 	ASSERT(remap_deadlist_obj != 0);
4077 	return (remap_deadlist_obj);
4078 }
4079 
4080 boolean_t
4081 dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
4082 {
4083 	EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
4084 	    dsl_dataset_get_remap_deadlist_object(ds) != 0);
4085 	return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
4086 }
4087 
4088 static void
4089 dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
4090     dmu_tx_t *tx)
4091 {
4092 	ASSERT(obj != 0);
4093 	dsl_dataset_zapify(ds, tx);
4094 	VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4095 	    DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
4096 }
4097 
4098 static void
4099 dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
4100 {
4101 	VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
4102 	    ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
4103 }
4104 
4105 void
4106 dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4107 {
4108 	uint64_t remap_deadlist_object;
4109 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4110 
4111 	ASSERT(dmu_tx_is_syncing(tx));
4112 	ASSERT(dsl_dataset_remap_deadlist_exists(ds));
4113 
4114 	remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
4115 	dsl_deadlist_close(&ds->ds_remap_deadlist);
4116 	dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
4117 	dsl_dataset_unset_remap_deadlist_object(ds, tx);
4118 	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4119 }
4120 
4121 void
4122 dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4123 {
4124 	uint64_t remap_deadlist_obj;
4125 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4126 
4127 	ASSERT(dmu_tx_is_syncing(tx));
4128 	ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
4129 	/*
4130 	 * Currently we only create remap deadlists when there are indirect
4131 	 * vdevs with referenced mappings.
4132 	 */
4133 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
4134 
4135 	remap_deadlist_obj = dsl_deadlist_clone(
4136 	    &ds->ds_deadlist, UINT64_MAX,
4137 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
4138 	dsl_dataset_set_remap_deadlist_object(ds,
4139 	    remap_deadlist_obj, tx);
4140 	dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
4141 	    remap_deadlist_obj);
4142 	spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4143 }
4144