xref: /titanic_51/usr/src/uts/common/fs/zfs/dsl_dataset.c (revision e57a022b8f718889ffa92adbde47a8f08abcdb25)
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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
24  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
25  * Copyright (c) 2014 RackTop Systems.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  */
28 
29 #include <sys/dmu_objset.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_dir.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_synctask.h>
34 #include <sys/dmu_traverse.h>
35 #include <sys/dmu_impl.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/arc.h>
38 #include <sys/zio.h>
39 #include <sys/zap.h>
40 #include <sys/zfeature.h>
41 #include <sys/unique.h>
42 #include <sys/zfs_context.h>
43 #include <sys/zfs_ioctl.h>
44 #include <sys/spa.h>
45 #include <sys/zfs_znode.h>
46 #include <sys/zfs_onexit.h>
47 #include <sys/zvol.h>
48 #include <sys/dsl_scan.h>
49 #include <sys/dsl_deadlist.h>
50 #include <sys/dsl_destroy.h>
51 #include <sys/dsl_userhold.h>
52 #include <sys/dsl_bookmark.h>
53 
54 /*
55  * The SPA supports block sizes up to 16MB.  However, very large blocks
56  * can have an impact on i/o latency (e.g. tying up a spinning disk for
57  * ~300ms), and also potentially on the memory allocator.  Therefore,
58  * we do not allow the recordsize to be set larger than zfs_max_recordsize
59  * (default 1MB).  Larger blocks can be created by changing this tunable,
60  * and pools with larger blocks can always be imported and used, regardless
61  * of this setting.
62  */
63 int zfs_max_recordsize = 1 * 1024 * 1024;
64 
65 #define	SWITCH64(x, y) \
66 	{ \
67 		uint64_t __tmp = (x); \
68 		(x) = (y); \
69 		(y) = __tmp; \
70 	}
71 
72 #define	DS_REF_MAX	(1ULL << 62)
73 
74 extern inline dsl_dataset_phys_t *dsl_dataset_phys(dsl_dataset_t *ds);
75 
76 /*
77  * Figure out how much of this delta should be propogated to the dsl_dir
78  * layer.  If there's a refreservation, that space has already been
79  * partially accounted for in our ancestors.
80  */
81 static int64_t
82 parent_delta(dsl_dataset_t *ds, int64_t delta)
83 {
84 	dsl_dataset_phys_t *ds_phys;
85 	uint64_t old_bytes, new_bytes;
86 
87 	if (ds->ds_reserved == 0)
88 		return (delta);
89 
90 	ds_phys = dsl_dataset_phys(ds);
91 	old_bytes = MAX(ds_phys->ds_unique_bytes, ds->ds_reserved);
92 	new_bytes = MAX(ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
93 
94 	ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
95 	return (new_bytes - old_bytes);
96 }
97 
98 void
99 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
100 {
101 	int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
102 	int compressed = BP_GET_PSIZE(bp);
103 	int uncompressed = BP_GET_UCSIZE(bp);
104 	int64_t delta;
105 
106 	dprintf_bp(bp, "ds=%p", ds);
107 
108 	ASSERT(dmu_tx_is_syncing(tx));
109 	/* It could have been compressed away to nothing */
110 	if (BP_IS_HOLE(bp))
111 		return;
112 	ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
113 	ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
114 	if (ds == NULL) {
115 		dsl_pool_mos_diduse_space(tx->tx_pool,
116 		    used, compressed, uncompressed);
117 		return;
118 	}
119 
120 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
121 	mutex_enter(&ds->ds_lock);
122 	delta = parent_delta(ds, used);
123 	dsl_dataset_phys(ds)->ds_referenced_bytes += used;
124 	dsl_dataset_phys(ds)->ds_compressed_bytes += compressed;
125 	dsl_dataset_phys(ds)->ds_uncompressed_bytes += uncompressed;
126 	dsl_dataset_phys(ds)->ds_unique_bytes += used;
127 	if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE)
128 		ds->ds_need_large_blocks = B_TRUE;
129 	mutex_exit(&ds->ds_lock);
130 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
131 	    compressed, uncompressed, tx);
132 	dsl_dir_transfer_space(ds->ds_dir, used - delta,
133 	    DD_USED_REFRSRV, DD_USED_HEAD, tx);
134 }
135 
136 int
137 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
138     boolean_t async)
139 {
140 	int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
141 	int compressed = BP_GET_PSIZE(bp);
142 	int uncompressed = BP_GET_UCSIZE(bp);
143 
144 	if (BP_IS_HOLE(bp))
145 		return (0);
146 
147 	ASSERT(dmu_tx_is_syncing(tx));
148 	ASSERT(bp->blk_birth <= tx->tx_txg);
149 
150 	if (ds == NULL) {
151 		dsl_free(tx->tx_pool, tx->tx_txg, bp);
152 		dsl_pool_mos_diduse_space(tx->tx_pool,
153 		    -used, -compressed, -uncompressed);
154 		return (used);
155 	}
156 	ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
157 
158 	ASSERT(!ds->ds_is_snapshot);
159 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
160 
161 	if (bp->blk_birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
162 		int64_t delta;
163 
164 		dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
165 		dsl_free(tx->tx_pool, tx->tx_txg, bp);
166 
167 		mutex_enter(&ds->ds_lock);
168 		ASSERT(dsl_dataset_phys(ds)->ds_unique_bytes >= used ||
169 		    !DS_UNIQUE_IS_ACCURATE(ds));
170 		delta = parent_delta(ds, -used);
171 		dsl_dataset_phys(ds)->ds_unique_bytes -= used;
172 		mutex_exit(&ds->ds_lock);
173 		dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
174 		    delta, -compressed, -uncompressed, tx);
175 		dsl_dir_transfer_space(ds->ds_dir, -used - delta,
176 		    DD_USED_REFRSRV, DD_USED_HEAD, tx);
177 	} else {
178 		dprintf_bp(bp, "putting on dead list: %s", "");
179 		if (async) {
180 			/*
181 			 * We are here as part of zio's write done callback,
182 			 * which means we're a zio interrupt thread.  We can't
183 			 * call dsl_deadlist_insert() now because it may block
184 			 * waiting for I/O.  Instead, put bp on the deferred
185 			 * queue and let dsl_pool_sync() finish the job.
186 			 */
187 			bplist_append(&ds->ds_pending_deadlist, bp);
188 		} else {
189 			dsl_deadlist_insert(&ds->ds_deadlist, bp, tx);
190 		}
191 		ASSERT3U(ds->ds_prev->ds_object, ==,
192 		    dsl_dataset_phys(ds)->ds_prev_snap_obj);
193 		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_num_children > 0);
194 		/* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
195 		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
196 		    ds->ds_object && bp->blk_birth >
197 		    dsl_dataset_phys(ds->ds_prev)->ds_prev_snap_txg) {
198 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
199 			mutex_enter(&ds->ds_prev->ds_lock);
200 			dsl_dataset_phys(ds->ds_prev)->ds_unique_bytes += used;
201 			mutex_exit(&ds->ds_prev->ds_lock);
202 		}
203 		if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
204 			dsl_dir_transfer_space(ds->ds_dir, used,
205 			    DD_USED_HEAD, DD_USED_SNAP, tx);
206 		}
207 	}
208 	mutex_enter(&ds->ds_lock);
209 	ASSERT3U(dsl_dataset_phys(ds)->ds_referenced_bytes, >=, used);
210 	dsl_dataset_phys(ds)->ds_referenced_bytes -= used;
211 	ASSERT3U(dsl_dataset_phys(ds)->ds_compressed_bytes, >=, compressed);
212 	dsl_dataset_phys(ds)->ds_compressed_bytes -= compressed;
213 	ASSERT3U(dsl_dataset_phys(ds)->ds_uncompressed_bytes, >=, uncompressed);
214 	dsl_dataset_phys(ds)->ds_uncompressed_bytes -= uncompressed;
215 	mutex_exit(&ds->ds_lock);
216 
217 	return (used);
218 }
219 
220 uint64_t
221 dsl_dataset_prev_snap_txg(dsl_dataset_t *ds)
222 {
223 	uint64_t trysnap = 0;
224 
225 	if (ds == NULL)
226 		return (0);
227 	/*
228 	 * The snapshot creation could fail, but that would cause an
229 	 * incorrect FALSE return, which would only result in an
230 	 * overestimation of the amount of space that an operation would
231 	 * consume, which is OK.
232 	 *
233 	 * There's also a small window where we could miss a pending
234 	 * snapshot, because we could set the sync task in the quiescing
235 	 * phase.  So this should only be used as a guess.
236 	 */
237 	if (ds->ds_trysnap_txg >
238 	    spa_last_synced_txg(ds->ds_dir->dd_pool->dp_spa))
239 		trysnap = ds->ds_trysnap_txg;
240 	return (MAX(dsl_dataset_phys(ds)->ds_prev_snap_txg, trysnap));
241 }
242 
243 boolean_t
244 dsl_dataset_block_freeable(dsl_dataset_t *ds, const blkptr_t *bp,
245     uint64_t blk_birth)
246 {
247 	if (blk_birth <= dsl_dataset_prev_snap_txg(ds) ||
248 	    (bp != NULL && BP_IS_HOLE(bp)))
249 		return (B_FALSE);
250 
251 	ddt_prefetch(dsl_dataset_get_spa(ds), bp);
252 
253 	return (B_TRUE);
254 }
255 
256 static void
257 dsl_dataset_evict(void *dbu)
258 {
259 	dsl_dataset_t *ds = dbu;
260 
261 	ASSERT(ds->ds_owner == NULL);
262 
263 	ds->ds_dbuf = NULL;
264 
265 	unique_remove(ds->ds_fsid_guid);
266 
267 	if (ds->ds_objset != NULL)
268 		dmu_objset_evict(ds->ds_objset);
269 
270 	if (ds->ds_prev) {
271 		dsl_dataset_rele(ds->ds_prev, ds);
272 		ds->ds_prev = NULL;
273 	}
274 
275 	bplist_destroy(&ds->ds_pending_deadlist);
276 	if (ds->ds_deadlist.dl_os != NULL)
277 		dsl_deadlist_close(&ds->ds_deadlist);
278 	if (ds->ds_dir)
279 		dsl_dir_async_rele(ds->ds_dir, ds);
280 
281 	ASSERT(!list_link_active(&ds->ds_synced_link));
282 
283 	mutex_destroy(&ds->ds_lock);
284 	mutex_destroy(&ds->ds_opening_lock);
285 	mutex_destroy(&ds->ds_sendstream_lock);
286 	refcount_destroy(&ds->ds_longholds);
287 
288 	kmem_free(ds, sizeof (dsl_dataset_t));
289 }
290 
291 int
292 dsl_dataset_get_snapname(dsl_dataset_t *ds)
293 {
294 	dsl_dataset_phys_t *headphys;
295 	int err;
296 	dmu_buf_t *headdbuf;
297 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
298 	objset_t *mos = dp->dp_meta_objset;
299 
300 	if (ds->ds_snapname[0])
301 		return (0);
302 	if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0)
303 		return (0);
304 
305 	err = dmu_bonus_hold(mos, dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj,
306 	    FTAG, &headdbuf);
307 	if (err != 0)
308 		return (err);
309 	headphys = headdbuf->db_data;
310 	err = zap_value_search(dp->dp_meta_objset,
311 	    headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
312 	dmu_buf_rele(headdbuf, FTAG);
313 	return (err);
314 }
315 
316 int
317 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
318 {
319 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
320 	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
321 	matchtype_t mt;
322 	int err;
323 
324 	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
325 		mt = MT_FIRST;
326 	else
327 		mt = MT_EXACT;
328 
329 	err = zap_lookup_norm(mos, snapobj, name, 8, 1,
330 	    value, mt, NULL, 0, NULL);
331 	if (err == ENOTSUP && mt == MT_FIRST)
332 		err = zap_lookup(mos, snapobj, name, 8, 1, value);
333 	return (err);
334 }
335 
336 int
337 dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
338     boolean_t adj_cnt)
339 {
340 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
341 	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
342 	matchtype_t mt;
343 	int err;
344 
345 	dsl_dir_snap_cmtime_update(ds->ds_dir);
346 
347 	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
348 		mt = MT_FIRST;
349 	else
350 		mt = MT_EXACT;
351 
352 	err = zap_remove_norm(mos, snapobj, name, mt, tx);
353 	if (err == ENOTSUP && mt == MT_FIRST)
354 		err = zap_remove(mos, snapobj, name, tx);
355 
356 	if (err == 0 && adj_cnt)
357 		dsl_fs_ss_count_adjust(ds->ds_dir, -1,
358 		    DD_FIELD_SNAPSHOT_COUNT, tx);
359 
360 	return (err);
361 }
362 
363 boolean_t
364 dsl_dataset_try_add_ref(dsl_pool_t *dp, dsl_dataset_t *ds, void *tag)
365 {
366 	return (dmu_buf_try_add_ref(ds->ds_dbuf, dp->dp_meta_objset,
367 	    ds->ds_object, DMU_BONUS_BLKID, tag));
368 }
369 
370 int
371 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
372     dsl_dataset_t **dsp)
373 {
374 	objset_t *mos = dp->dp_meta_objset;
375 	dmu_buf_t *dbuf;
376 	dsl_dataset_t *ds;
377 	int err;
378 	dmu_object_info_t doi;
379 
380 	ASSERT(dsl_pool_config_held(dp));
381 
382 	err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
383 	if (err != 0)
384 		return (err);
385 
386 	/* Make sure dsobj has the correct object type. */
387 	dmu_object_info_from_db(dbuf, &doi);
388 	if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
389 		dmu_buf_rele(dbuf, tag);
390 		return (SET_ERROR(EINVAL));
391 	}
392 
393 	ds = dmu_buf_get_user(dbuf);
394 	if (ds == NULL) {
395 		dsl_dataset_t *winner = NULL;
396 
397 		ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
398 		ds->ds_dbuf = dbuf;
399 		ds->ds_object = dsobj;
400 		ds->ds_is_snapshot = dsl_dataset_phys(ds)->ds_num_children != 0;
401 
402 		mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
403 		mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
404 		mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
405 		refcount_create(&ds->ds_longholds);
406 
407 		bplist_create(&ds->ds_pending_deadlist);
408 		dsl_deadlist_open(&ds->ds_deadlist,
409 		    mos, dsl_dataset_phys(ds)->ds_deadlist_obj);
410 
411 		list_create(&ds->ds_sendstreams, sizeof (dmu_sendarg_t),
412 		    offsetof(dmu_sendarg_t, dsa_link));
413 
414 		if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
415 			err = zap_contains(mos, dsobj, DS_FIELD_LARGE_BLOCKS);
416 			if (err == 0)
417 				ds->ds_large_blocks = B_TRUE;
418 			else
419 				ASSERT3U(err, ==, ENOENT);
420 		}
421 
422 		if (err == 0) {
423 			err = dsl_dir_hold_obj(dp,
424 			    dsl_dataset_phys(ds)->ds_dir_obj, NULL, ds,
425 			    &ds->ds_dir);
426 		}
427 		if (err != 0) {
428 			mutex_destroy(&ds->ds_lock);
429 			mutex_destroy(&ds->ds_opening_lock);
430 			mutex_destroy(&ds->ds_sendstream_lock);
431 			refcount_destroy(&ds->ds_longholds);
432 			bplist_destroy(&ds->ds_pending_deadlist);
433 			dsl_deadlist_close(&ds->ds_deadlist);
434 			kmem_free(ds, sizeof (dsl_dataset_t));
435 			dmu_buf_rele(dbuf, tag);
436 			return (err);
437 		}
438 
439 		if (!ds->ds_is_snapshot) {
440 			ds->ds_snapname[0] = '\0';
441 			if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
442 				err = dsl_dataset_hold_obj(dp,
443 				    dsl_dataset_phys(ds)->ds_prev_snap_obj,
444 				    ds, &ds->ds_prev);
445 			}
446 			if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
447 				int zaperr = zap_lookup(mos, ds->ds_object,
448 				    DS_FIELD_BOOKMARK_NAMES,
449 				    sizeof (ds->ds_bookmarks), 1,
450 				    &ds->ds_bookmarks);
451 				if (zaperr != ENOENT)
452 					VERIFY0(zaperr);
453 			}
454 		} else {
455 			if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
456 				err = dsl_dataset_get_snapname(ds);
457 			if (err == 0 &&
458 			    dsl_dataset_phys(ds)->ds_userrefs_obj != 0) {
459 				err = zap_count(
460 				    ds->ds_dir->dd_pool->dp_meta_objset,
461 				    dsl_dataset_phys(ds)->ds_userrefs_obj,
462 				    &ds->ds_userrefs);
463 			}
464 		}
465 
466 		if (err == 0 && !ds->ds_is_snapshot) {
467 			err = dsl_prop_get_int_ds(ds,
468 			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
469 			    &ds->ds_reserved);
470 			if (err == 0) {
471 				err = dsl_prop_get_int_ds(ds,
472 				    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
473 				    &ds->ds_quota);
474 			}
475 		} else {
476 			ds->ds_reserved = ds->ds_quota = 0;
477 		}
478 
479 		dmu_buf_init_user(&ds->ds_dbu, dsl_dataset_evict, &ds->ds_dbuf);
480 		if (err == 0)
481 			winner = dmu_buf_set_user_ie(dbuf, &ds->ds_dbu);
482 
483 		if (err != 0 || winner != NULL) {
484 			bplist_destroy(&ds->ds_pending_deadlist);
485 			dsl_deadlist_close(&ds->ds_deadlist);
486 			if (ds->ds_prev)
487 				dsl_dataset_rele(ds->ds_prev, ds);
488 			dsl_dir_rele(ds->ds_dir, ds);
489 			mutex_destroy(&ds->ds_lock);
490 			mutex_destroy(&ds->ds_opening_lock);
491 			mutex_destroy(&ds->ds_sendstream_lock);
492 			refcount_destroy(&ds->ds_longholds);
493 			kmem_free(ds, sizeof (dsl_dataset_t));
494 			if (err != 0) {
495 				dmu_buf_rele(dbuf, tag);
496 				return (err);
497 			}
498 			ds = winner;
499 		} else {
500 			ds->ds_fsid_guid =
501 			    unique_insert(dsl_dataset_phys(ds)->ds_fsid_guid);
502 		}
503 	}
504 	ASSERT3P(ds->ds_dbuf, ==, dbuf);
505 	ASSERT3P(dsl_dataset_phys(ds), ==, dbuf->db_data);
506 	ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0 ||
507 	    spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
508 	    dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
509 	*dsp = ds;
510 	return (0);
511 }
512 
513 int
514 dsl_dataset_hold(dsl_pool_t *dp, const char *name,
515     void *tag, dsl_dataset_t **dsp)
516 {
517 	dsl_dir_t *dd;
518 	const char *snapname;
519 	uint64_t obj;
520 	int err = 0;
521 
522 	err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
523 	if (err != 0)
524 		return (err);
525 
526 	ASSERT(dsl_pool_config_held(dp));
527 	obj = dsl_dir_phys(dd)->dd_head_dataset_obj;
528 	if (obj != 0)
529 		err = dsl_dataset_hold_obj(dp, obj, tag, dsp);
530 	else
531 		err = SET_ERROR(ENOENT);
532 
533 	/* we may be looking for a snapshot */
534 	if (err == 0 && snapname != NULL) {
535 		dsl_dataset_t *ds;
536 
537 		if (*snapname++ != '@') {
538 			dsl_dataset_rele(*dsp, tag);
539 			dsl_dir_rele(dd, FTAG);
540 			return (SET_ERROR(ENOENT));
541 		}
542 
543 		dprintf("looking for snapshot '%s'\n", snapname);
544 		err = dsl_dataset_snap_lookup(*dsp, snapname, &obj);
545 		if (err == 0)
546 			err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
547 		dsl_dataset_rele(*dsp, tag);
548 
549 		if (err == 0) {
550 			mutex_enter(&ds->ds_lock);
551 			if (ds->ds_snapname[0] == 0)
552 				(void) strlcpy(ds->ds_snapname, snapname,
553 				    sizeof (ds->ds_snapname));
554 			mutex_exit(&ds->ds_lock);
555 			*dsp = ds;
556 		}
557 	}
558 
559 	dsl_dir_rele(dd, FTAG);
560 	return (err);
561 }
562 
563 int
564 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj,
565     void *tag, dsl_dataset_t **dsp)
566 {
567 	int err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
568 	if (err != 0)
569 		return (err);
570 	if (!dsl_dataset_tryown(*dsp, tag)) {
571 		dsl_dataset_rele(*dsp, tag);
572 		*dsp = NULL;
573 		return (SET_ERROR(EBUSY));
574 	}
575 	return (0);
576 }
577 
578 int
579 dsl_dataset_own(dsl_pool_t *dp, const char *name,
580     void *tag, dsl_dataset_t **dsp)
581 {
582 	int err = dsl_dataset_hold(dp, name, tag, dsp);
583 	if (err != 0)
584 		return (err);
585 	if (!dsl_dataset_tryown(*dsp, tag)) {
586 		dsl_dataset_rele(*dsp, tag);
587 		return (SET_ERROR(EBUSY));
588 	}
589 	return (0);
590 }
591 
592 /*
593  * See the comment above dsl_pool_hold() for details.  In summary, a long
594  * hold is used to prevent destruction of a dataset while the pool hold
595  * is dropped, allowing other concurrent operations (e.g. spa_sync()).
596  *
597  * The dataset and pool must be held when this function is called.  After it
598  * is called, the pool hold may be released while the dataset is still held
599  * and accessed.
600  */
601 void
602 dsl_dataset_long_hold(dsl_dataset_t *ds, void *tag)
603 {
604 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
605 	(void) refcount_add(&ds->ds_longholds, tag);
606 }
607 
608 void
609 dsl_dataset_long_rele(dsl_dataset_t *ds, void *tag)
610 {
611 	(void) refcount_remove(&ds->ds_longholds, tag);
612 }
613 
614 /* Return B_TRUE if there are any long holds on this dataset. */
615 boolean_t
616 dsl_dataset_long_held(dsl_dataset_t *ds)
617 {
618 	return (!refcount_is_zero(&ds->ds_longholds));
619 }
620 
621 void
622 dsl_dataset_name(dsl_dataset_t *ds, char *name)
623 {
624 	if (ds == NULL) {
625 		(void) strcpy(name, "mos");
626 	} else {
627 		dsl_dir_name(ds->ds_dir, name);
628 		VERIFY0(dsl_dataset_get_snapname(ds));
629 		if (ds->ds_snapname[0]) {
630 			(void) strcat(name, "@");
631 			/*
632 			 * We use a "recursive" mutex so that we
633 			 * can call dprintf_ds() with ds_lock held.
634 			 */
635 			if (!MUTEX_HELD(&ds->ds_lock)) {
636 				mutex_enter(&ds->ds_lock);
637 				(void) strcat(name, ds->ds_snapname);
638 				mutex_exit(&ds->ds_lock);
639 			} else {
640 				(void) strcat(name, ds->ds_snapname);
641 			}
642 		}
643 	}
644 }
645 
646 void
647 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
648 {
649 	dmu_buf_rele(ds->ds_dbuf, tag);
650 }
651 
652 void
653 dsl_dataset_disown(dsl_dataset_t *ds, void *tag)
654 {
655 	ASSERT3P(ds->ds_owner, ==, tag);
656 	ASSERT(ds->ds_dbuf != NULL);
657 
658 	mutex_enter(&ds->ds_lock);
659 	ds->ds_owner = NULL;
660 	mutex_exit(&ds->ds_lock);
661 	dsl_dataset_long_rele(ds, tag);
662 	dsl_dataset_rele(ds, tag);
663 }
664 
665 boolean_t
666 dsl_dataset_tryown(dsl_dataset_t *ds, void *tag)
667 {
668 	boolean_t gotit = FALSE;
669 
670 	mutex_enter(&ds->ds_lock);
671 	if (ds->ds_owner == NULL && !DS_IS_INCONSISTENT(ds)) {
672 		ds->ds_owner = tag;
673 		dsl_dataset_long_hold(ds, tag);
674 		gotit = TRUE;
675 	}
676 	mutex_exit(&ds->ds_lock);
677 	return (gotit);
678 }
679 
680 uint64_t
681 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
682     uint64_t flags, dmu_tx_t *tx)
683 {
684 	dsl_pool_t *dp = dd->dd_pool;
685 	dmu_buf_t *dbuf;
686 	dsl_dataset_phys_t *dsphys;
687 	uint64_t dsobj;
688 	objset_t *mos = dp->dp_meta_objset;
689 
690 	if (origin == NULL)
691 		origin = dp->dp_origin_snap;
692 
693 	ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
694 	ASSERT(origin == NULL || dsl_dataset_phys(origin)->ds_num_children > 0);
695 	ASSERT(dmu_tx_is_syncing(tx));
696 	ASSERT(dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
697 
698 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
699 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
700 	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
701 	dmu_buf_will_dirty(dbuf, tx);
702 	dsphys = dbuf->db_data;
703 	bzero(dsphys, sizeof (dsl_dataset_phys_t));
704 	dsphys->ds_dir_obj = dd->dd_object;
705 	dsphys->ds_flags = flags;
706 	dsphys->ds_fsid_guid = unique_create();
707 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
708 	    sizeof (dsphys->ds_guid));
709 	dsphys->ds_snapnames_zapobj =
710 	    zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
711 	    DMU_OT_NONE, 0, tx);
712 	dsphys->ds_creation_time = gethrestime_sec();
713 	dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
714 
715 	if (origin == NULL) {
716 		dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
717 	} else {
718 		dsl_dataset_t *ohds; /* head of the origin snapshot */
719 
720 		dsphys->ds_prev_snap_obj = origin->ds_object;
721 		dsphys->ds_prev_snap_txg =
722 		    dsl_dataset_phys(origin)->ds_creation_txg;
723 		dsphys->ds_referenced_bytes =
724 		    dsl_dataset_phys(origin)->ds_referenced_bytes;
725 		dsphys->ds_compressed_bytes =
726 		    dsl_dataset_phys(origin)->ds_compressed_bytes;
727 		dsphys->ds_uncompressed_bytes =
728 		    dsl_dataset_phys(origin)->ds_uncompressed_bytes;
729 		dsphys->ds_bp = dsl_dataset_phys(origin)->ds_bp;
730 
731 		/*
732 		 * Inherit flags that describe the dataset's contents
733 		 * (INCONSISTENT) or properties (Case Insensitive).
734 		 */
735 		dsphys->ds_flags |= dsl_dataset_phys(origin)->ds_flags &
736 		    (DS_FLAG_INCONSISTENT | DS_FLAG_CI_DATASET);
737 
738 		if (origin->ds_large_blocks)
739 			dsl_dataset_activate_large_blocks_sync_impl(dsobj, tx);
740 
741 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
742 		dsl_dataset_phys(origin)->ds_num_children++;
743 
744 		VERIFY0(dsl_dataset_hold_obj(dp,
745 		    dsl_dir_phys(origin->ds_dir)->dd_head_dataset_obj,
746 		    FTAG, &ohds));
747 		dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
748 		    dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
749 		dsl_dataset_rele(ohds, FTAG);
750 
751 		if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
752 			if (dsl_dataset_phys(origin)->ds_next_clones_obj == 0) {
753 				dsl_dataset_phys(origin)->ds_next_clones_obj =
754 				    zap_create(mos,
755 				    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
756 			}
757 			VERIFY0(zap_add_int(mos,
758 			    dsl_dataset_phys(origin)->ds_next_clones_obj,
759 			    dsobj, tx));
760 		}
761 
762 		dmu_buf_will_dirty(dd->dd_dbuf, tx);
763 		dsl_dir_phys(dd)->dd_origin_obj = origin->ds_object;
764 		if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
765 			if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
766 				dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
767 				dsl_dir_phys(origin->ds_dir)->dd_clones =
768 				    zap_create(mos,
769 				    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
770 			}
771 			VERIFY0(zap_add_int(mos,
772 			    dsl_dir_phys(origin->ds_dir)->dd_clones,
773 			    dsobj, tx));
774 		}
775 	}
776 
777 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
778 		dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
779 
780 	dmu_buf_rele(dbuf, FTAG);
781 
782 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
783 	dsl_dir_phys(dd)->dd_head_dataset_obj = dsobj;
784 
785 	return (dsobj);
786 }
787 
788 static void
789 dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
790 {
791 	objset_t *os;
792 
793 	VERIFY0(dmu_objset_from_ds(ds, &os));
794 	bzero(&os->os_zil_header, sizeof (os->os_zil_header));
795 	dsl_dataset_dirty(ds, tx);
796 }
797 
798 uint64_t
799 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
800     dsl_dataset_t *origin, uint64_t flags, cred_t *cr, dmu_tx_t *tx)
801 {
802 	dsl_pool_t *dp = pdd->dd_pool;
803 	uint64_t dsobj, ddobj;
804 	dsl_dir_t *dd;
805 
806 	ASSERT(dmu_tx_is_syncing(tx));
807 	ASSERT(lastname[0] != '@');
808 
809 	ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
810 	VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
811 
812 	dsobj = dsl_dataset_create_sync_dd(dd, origin,
813 	    flags & ~DS_CREATE_FLAG_NODIRTY, tx);
814 
815 	dsl_deleg_set_create_perms(dd, tx, cr);
816 
817 	/*
818 	 * Since we're creating a new node we know it's a leaf, so we can
819 	 * initialize the counts if the limit feature is active.
820 	 */
821 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
822 		uint64_t cnt = 0;
823 		objset_t *os = dd->dd_pool->dp_meta_objset;
824 
825 		dsl_dir_zapify(dd, tx);
826 		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
827 		    sizeof (cnt), 1, &cnt, tx));
828 		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
829 		    sizeof (cnt), 1, &cnt, tx));
830 	}
831 
832 	dsl_dir_rele(dd, FTAG);
833 
834 	/*
835 	 * If we are creating a clone, make sure we zero out any stale
836 	 * data from the origin snapshots zil header.
837 	 */
838 	if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
839 		dsl_dataset_t *ds;
840 
841 		VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
842 		dsl_dataset_zero_zil(ds, tx);
843 		dsl_dataset_rele(ds, FTAG);
844 	}
845 
846 	return (dsobj);
847 }
848 
849 /*
850  * The unique space in the head dataset can be calculated by subtracting
851  * the space used in the most recent snapshot, that is still being used
852  * in this file system, from the space currently in use.  To figure out
853  * the space in the most recent snapshot still in use, we need to take
854  * the total space used in the snapshot and subtract out the space that
855  * has been freed up since the snapshot was taken.
856  */
857 void
858 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
859 {
860 	uint64_t mrs_used;
861 	uint64_t dlused, dlcomp, dluncomp;
862 
863 	ASSERT(!ds->ds_is_snapshot);
864 
865 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0)
866 		mrs_used = dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes;
867 	else
868 		mrs_used = 0;
869 
870 	dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
871 
872 	ASSERT3U(dlused, <=, mrs_used);
873 	dsl_dataset_phys(ds)->ds_unique_bytes =
874 	    dsl_dataset_phys(ds)->ds_referenced_bytes - (mrs_used - dlused);
875 
876 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
877 	    SPA_VERSION_UNIQUE_ACCURATE)
878 		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
879 }
880 
881 void
882 dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
883     dmu_tx_t *tx)
884 {
885 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
886 	uint64_t count;
887 	int err;
888 
889 	ASSERT(dsl_dataset_phys(ds)->ds_num_children >= 2);
890 	err = zap_remove_int(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
891 	    obj, tx);
892 	/*
893 	 * The err should not be ENOENT, but a bug in a previous version
894 	 * of the code could cause upgrade_clones_cb() to not set
895 	 * ds_next_snap_obj when it should, leading to a missing entry.
896 	 * If we knew that the pool was created after
897 	 * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
898 	 * ENOENT.  However, at least we can check that we don't have
899 	 * too many entries in the next_clones_obj even after failing to
900 	 * remove this one.
901 	 */
902 	if (err != ENOENT)
903 		VERIFY0(err);
904 	ASSERT0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
905 	    &count));
906 	ASSERT3U(count, <=, dsl_dataset_phys(ds)->ds_num_children - 2);
907 }
908 
909 
910 blkptr_t *
911 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
912 {
913 	return (&dsl_dataset_phys(ds)->ds_bp);
914 }
915 
916 void
917 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
918 {
919 	ASSERT(dmu_tx_is_syncing(tx));
920 	/* If it's the meta-objset, set dp_meta_rootbp */
921 	if (ds == NULL) {
922 		tx->tx_pool->dp_meta_rootbp = *bp;
923 	} else {
924 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
925 		dsl_dataset_phys(ds)->ds_bp = *bp;
926 	}
927 }
928 
929 spa_t *
930 dsl_dataset_get_spa(dsl_dataset_t *ds)
931 {
932 	return (ds->ds_dir->dd_pool->dp_spa);
933 }
934 
935 void
936 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
937 {
938 	dsl_pool_t *dp;
939 
940 	if (ds == NULL) /* this is the meta-objset */
941 		return;
942 
943 	ASSERT(ds->ds_objset != NULL);
944 
945 	if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0)
946 		panic("dirtying snapshot!");
947 
948 	dp = ds->ds_dir->dd_pool;
949 
950 	if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
951 		/* up the hold count until we can be written out */
952 		dmu_buf_add_ref(ds->ds_dbuf, ds);
953 	}
954 }
955 
956 boolean_t
957 dsl_dataset_is_dirty(dsl_dataset_t *ds)
958 {
959 	for (int t = 0; t < TXG_SIZE; t++) {
960 		if (txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
961 		    ds, t))
962 			return (B_TRUE);
963 	}
964 	return (B_FALSE);
965 }
966 
967 static int
968 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
969 {
970 	uint64_t asize;
971 
972 	if (!dmu_tx_is_syncing(tx))
973 		return (0);
974 
975 	/*
976 	 * If there's an fs-only reservation, any blocks that might become
977 	 * owned by the snapshot dataset must be accommodated by space
978 	 * outside of the reservation.
979 	 */
980 	ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
981 	asize = MIN(dsl_dataset_phys(ds)->ds_unique_bytes, ds->ds_reserved);
982 	if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
983 		return (SET_ERROR(ENOSPC));
984 
985 	/*
986 	 * Propagate any reserved space for this snapshot to other
987 	 * snapshot checks in this sync group.
988 	 */
989 	if (asize > 0)
990 		dsl_dir_willuse_space(ds->ds_dir, asize, tx);
991 
992 	return (0);
993 }
994 
995 typedef struct dsl_dataset_snapshot_arg {
996 	nvlist_t *ddsa_snaps;
997 	nvlist_t *ddsa_props;
998 	nvlist_t *ddsa_errors;
999 	cred_t *ddsa_cr;
1000 } dsl_dataset_snapshot_arg_t;
1001 
1002 int
1003 dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1004     dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr)
1005 {
1006 	int error;
1007 	uint64_t value;
1008 
1009 	ds->ds_trysnap_txg = tx->tx_txg;
1010 
1011 	if (!dmu_tx_is_syncing(tx))
1012 		return (0);
1013 
1014 	/*
1015 	 * We don't allow multiple snapshots of the same txg.  If there
1016 	 * is already one, try again.
1017 	 */
1018 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg)
1019 		return (SET_ERROR(EAGAIN));
1020 
1021 	/*
1022 	 * Check for conflicting snapshot name.
1023 	 */
1024 	error = dsl_dataset_snap_lookup(ds, snapname, &value);
1025 	if (error == 0)
1026 		return (SET_ERROR(EEXIST));
1027 	if (error != ENOENT)
1028 		return (error);
1029 
1030 	/*
1031 	 * We don't allow taking snapshots of inconsistent datasets, such as
1032 	 * those into which we are currently receiving.  However, if we are
1033 	 * creating this snapshot as part of a receive, this check will be
1034 	 * executed atomically with respect to the completion of the receive
1035 	 * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1036 	 * case we ignore this, knowing it will be fixed up for us shortly in
1037 	 * dmu_recv_end_sync().
1038 	 */
1039 	if (!recv && DS_IS_INCONSISTENT(ds))
1040 		return (SET_ERROR(EBUSY));
1041 
1042 	/*
1043 	 * Skip the check for temporary snapshots or if we have already checked
1044 	 * the counts in dsl_dataset_snapshot_check. This means we really only
1045 	 * check the count here when we're receiving a stream.
1046 	 */
1047 	if (cnt != 0 && cr != NULL) {
1048 		error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1049 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr);
1050 		if (error != 0)
1051 			return (error);
1052 	}
1053 
1054 	error = dsl_dataset_snapshot_reserve_space(ds, tx);
1055 	if (error != 0)
1056 		return (error);
1057 
1058 	return (0);
1059 }
1060 
1061 static int
1062 dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1063 {
1064 	dsl_dataset_snapshot_arg_t *ddsa = arg;
1065 	dsl_pool_t *dp = dmu_tx_pool(tx);
1066 	nvpair_t *pair;
1067 	int rv = 0;
1068 
1069 	/*
1070 	 * Pre-compute how many total new snapshots will be created for each
1071 	 * level in the tree and below. This is needed for validating the
1072 	 * snapshot limit when either taking a recursive snapshot or when
1073 	 * taking multiple snapshots.
1074 	 *
1075 	 * The problem is that the counts are not actually adjusted when
1076 	 * we are checking, only when we finally sync. For a single snapshot,
1077 	 * this is easy, the count will increase by 1 at each node up the tree,
1078 	 * but its more complicated for the recursive/multiple snapshot case.
1079 	 *
1080 	 * The dsl_fs_ss_limit_check function does recursively check the count
1081 	 * at each level up the tree but since it is validating each snapshot
1082 	 * independently we need to be sure that we are validating the complete
1083 	 * count for the entire set of snapshots. We do this by rolling up the
1084 	 * counts for each component of the name into an nvlist and then
1085 	 * checking each of those cases with the aggregated count.
1086 	 *
1087 	 * This approach properly handles not only the recursive snapshot
1088 	 * case (where we get all of those on the ddsa_snaps list) but also
1089 	 * the sibling case (e.g. snapshot a/b and a/c so that we will also
1090 	 * validate the limit on 'a' using a count of 2).
1091 	 *
1092 	 * We validate the snapshot names in the third loop and only report
1093 	 * name errors once.
1094 	 */
1095 	if (dmu_tx_is_syncing(tx)) {
1096 		nvlist_t *cnt_track = NULL;
1097 		cnt_track = fnvlist_alloc();
1098 
1099 		/* Rollup aggregated counts into the cnt_track list */
1100 		for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1101 		    pair != NULL;
1102 		    pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1103 			char *pdelim;
1104 			uint64_t val;
1105 			char nm[MAXPATHLEN];
1106 
1107 			(void) strlcpy(nm, nvpair_name(pair), sizeof (nm));
1108 			pdelim = strchr(nm, '@');
1109 			if (pdelim == NULL)
1110 				continue;
1111 			*pdelim = '\0';
1112 
1113 			do {
1114 				if (nvlist_lookup_uint64(cnt_track, nm,
1115 				    &val) == 0) {
1116 					/* update existing entry */
1117 					fnvlist_add_uint64(cnt_track, nm,
1118 					    val + 1);
1119 				} else {
1120 					/* add to list */
1121 					fnvlist_add_uint64(cnt_track, nm, 1);
1122 				}
1123 
1124 				pdelim = strrchr(nm, '/');
1125 				if (pdelim != NULL)
1126 					*pdelim = '\0';
1127 			} while (pdelim != NULL);
1128 		}
1129 
1130 		/* Check aggregated counts at each level */
1131 		for (pair = nvlist_next_nvpair(cnt_track, NULL);
1132 		    pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1133 			int error = 0;
1134 			char *name;
1135 			uint64_t cnt = 0;
1136 			dsl_dataset_t *ds;
1137 
1138 			name = nvpair_name(pair);
1139 			cnt = fnvpair_value_uint64(pair);
1140 			ASSERT(cnt > 0);
1141 
1142 			error = dsl_dataset_hold(dp, name, FTAG, &ds);
1143 			if (error == 0) {
1144 				error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1145 				    ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1146 				    ddsa->ddsa_cr);
1147 				dsl_dataset_rele(ds, FTAG);
1148 			}
1149 
1150 			if (error != 0) {
1151 				if (ddsa->ddsa_errors != NULL)
1152 					fnvlist_add_int32(ddsa->ddsa_errors,
1153 					    name, error);
1154 				rv = error;
1155 				/* only report one error for this check */
1156 				break;
1157 			}
1158 		}
1159 		nvlist_free(cnt_track);
1160 	}
1161 
1162 	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1163 	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1164 		int error = 0;
1165 		dsl_dataset_t *ds;
1166 		char *name, *atp;
1167 		char dsname[MAXNAMELEN];
1168 
1169 		name = nvpair_name(pair);
1170 		if (strlen(name) >= MAXNAMELEN)
1171 			error = SET_ERROR(ENAMETOOLONG);
1172 		if (error == 0) {
1173 			atp = strchr(name, '@');
1174 			if (atp == NULL)
1175 				error = SET_ERROR(EINVAL);
1176 			if (error == 0)
1177 				(void) strlcpy(dsname, name, atp - name + 1);
1178 		}
1179 		if (error == 0)
1180 			error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1181 		if (error == 0) {
1182 			/* passing 0/NULL skips dsl_fs_ss_limit_check */
1183 			error = dsl_dataset_snapshot_check_impl(ds,
1184 			    atp + 1, tx, B_FALSE, 0, NULL);
1185 			dsl_dataset_rele(ds, FTAG);
1186 		}
1187 
1188 		if (error != 0) {
1189 			if (ddsa->ddsa_errors != NULL) {
1190 				fnvlist_add_int32(ddsa->ddsa_errors,
1191 				    name, error);
1192 			}
1193 			rv = error;
1194 		}
1195 	}
1196 
1197 	return (rv);
1198 }
1199 
1200 void
1201 dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1202     dmu_tx_t *tx)
1203 {
1204 	static zil_header_t zero_zil;
1205 
1206 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1207 	dmu_buf_t *dbuf;
1208 	dsl_dataset_phys_t *dsphys;
1209 	uint64_t dsobj, crtxg;
1210 	objset_t *mos = dp->dp_meta_objset;
1211 	objset_t *os;
1212 
1213 	ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1214 
1215 	/*
1216 	 * If we are on an old pool, the zil must not be active, in which
1217 	 * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1218 	 */
1219 	ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1220 	    dmu_objset_from_ds(ds, &os) != 0 ||
1221 	    bcmp(&os->os_phys->os_zil_header, &zero_zil,
1222 	    sizeof (zero_zil)) == 0);
1223 
1224 	dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1225 
1226 	/*
1227 	 * The origin's ds_creation_txg has to be < TXG_INITIAL
1228 	 */
1229 	if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1230 		crtxg = 1;
1231 	else
1232 		crtxg = tx->tx_txg;
1233 
1234 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1235 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1236 	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1237 	dmu_buf_will_dirty(dbuf, tx);
1238 	dsphys = dbuf->db_data;
1239 	bzero(dsphys, sizeof (dsl_dataset_phys_t));
1240 	dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1241 	dsphys->ds_fsid_guid = unique_create();
1242 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1243 	    sizeof (dsphys->ds_guid));
1244 	dsphys->ds_prev_snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1245 	dsphys->ds_prev_snap_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1246 	dsphys->ds_next_snap_obj = ds->ds_object;
1247 	dsphys->ds_num_children = 1;
1248 	dsphys->ds_creation_time = gethrestime_sec();
1249 	dsphys->ds_creation_txg = crtxg;
1250 	dsphys->ds_deadlist_obj = dsl_dataset_phys(ds)->ds_deadlist_obj;
1251 	dsphys->ds_referenced_bytes = dsl_dataset_phys(ds)->ds_referenced_bytes;
1252 	dsphys->ds_compressed_bytes = dsl_dataset_phys(ds)->ds_compressed_bytes;
1253 	dsphys->ds_uncompressed_bytes =
1254 	    dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1255 	dsphys->ds_flags = dsl_dataset_phys(ds)->ds_flags;
1256 	dsphys->ds_bp = dsl_dataset_phys(ds)->ds_bp;
1257 	dmu_buf_rele(dbuf, FTAG);
1258 
1259 	if (ds->ds_large_blocks)
1260 		dsl_dataset_activate_large_blocks_sync_impl(dsobj, tx);
1261 
1262 	ASSERT3U(ds->ds_prev != 0, ==,
1263 	    dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1264 	if (ds->ds_prev) {
1265 		uint64_t next_clones_obj =
1266 		    dsl_dataset_phys(ds->ds_prev)->ds_next_clones_obj;
1267 		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1268 		    ds->ds_object ||
1269 		    dsl_dataset_phys(ds->ds_prev)->ds_num_children > 1);
1270 		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1271 		    ds->ds_object) {
1272 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1273 			ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, ==,
1274 			    dsl_dataset_phys(ds->ds_prev)->ds_creation_txg);
1275 			dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj = dsobj;
1276 		} else if (next_clones_obj != 0) {
1277 			dsl_dataset_remove_from_next_clones(ds->ds_prev,
1278 			    dsphys->ds_next_snap_obj, tx);
1279 			VERIFY0(zap_add_int(mos,
1280 			    next_clones_obj, dsobj, tx));
1281 		}
1282 	}
1283 
1284 	/*
1285 	 * If we have a reference-reservation on this dataset, we will
1286 	 * need to increase the amount of refreservation being charged
1287 	 * since our unique space is going to zero.
1288 	 */
1289 	if (ds->ds_reserved) {
1290 		int64_t delta;
1291 		ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1292 		delta = MIN(dsl_dataset_phys(ds)->ds_unique_bytes,
1293 		    ds->ds_reserved);
1294 		dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1295 		    delta, 0, 0, tx);
1296 	}
1297 
1298 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1299 	dsl_dataset_phys(ds)->ds_deadlist_obj =
1300 	    dsl_deadlist_clone(&ds->ds_deadlist, UINT64_MAX,
1301 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
1302 	dsl_deadlist_close(&ds->ds_deadlist);
1303 	dsl_deadlist_open(&ds->ds_deadlist, mos,
1304 	    dsl_dataset_phys(ds)->ds_deadlist_obj);
1305 	dsl_deadlist_add_key(&ds->ds_deadlist,
1306 	    dsl_dataset_phys(ds)->ds_prev_snap_txg, tx);
1307 
1308 	ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, <, tx->tx_txg);
1309 	dsl_dataset_phys(ds)->ds_prev_snap_obj = dsobj;
1310 	dsl_dataset_phys(ds)->ds_prev_snap_txg = crtxg;
1311 	dsl_dataset_phys(ds)->ds_unique_bytes = 0;
1312 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1313 		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1314 
1315 	VERIFY0(zap_add(mos, dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1316 	    snapname, 8, 1, &dsobj, tx));
1317 
1318 	if (ds->ds_prev)
1319 		dsl_dataset_rele(ds->ds_prev, ds);
1320 	VERIFY0(dsl_dataset_hold_obj(dp,
1321 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, ds, &ds->ds_prev));
1322 
1323 	dsl_scan_ds_snapshotted(ds, tx);
1324 
1325 	dsl_dir_snap_cmtime_update(ds->ds_dir);
1326 
1327 	spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, "");
1328 }
1329 
1330 static void
1331 dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1332 {
1333 	dsl_dataset_snapshot_arg_t *ddsa = arg;
1334 	dsl_pool_t *dp = dmu_tx_pool(tx);
1335 	nvpair_t *pair;
1336 
1337 	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1338 	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1339 		dsl_dataset_t *ds;
1340 		char *name, *atp;
1341 		char dsname[MAXNAMELEN];
1342 
1343 		name = nvpair_name(pair);
1344 		atp = strchr(name, '@');
1345 		(void) strlcpy(dsname, name, atp - name + 1);
1346 		VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1347 
1348 		dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1349 		if (ddsa->ddsa_props != NULL) {
1350 			dsl_props_set_sync_impl(ds->ds_prev,
1351 			    ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1352 		}
1353 		dsl_dataset_rele(ds, FTAG);
1354 	}
1355 }
1356 
1357 /*
1358  * The snapshots must all be in the same pool.
1359  * All-or-nothing: if there are any failures, nothing will be modified.
1360  */
1361 int
1362 dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1363 {
1364 	dsl_dataset_snapshot_arg_t ddsa;
1365 	nvpair_t *pair;
1366 	boolean_t needsuspend;
1367 	int error;
1368 	spa_t *spa;
1369 	char *firstname;
1370 	nvlist_t *suspended = NULL;
1371 
1372 	pair = nvlist_next_nvpair(snaps, NULL);
1373 	if (pair == NULL)
1374 		return (0);
1375 	firstname = nvpair_name(pair);
1376 
1377 	error = spa_open(firstname, &spa, FTAG);
1378 	if (error != 0)
1379 		return (error);
1380 	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1381 	spa_close(spa, FTAG);
1382 
1383 	if (needsuspend) {
1384 		suspended = fnvlist_alloc();
1385 		for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1386 		    pair = nvlist_next_nvpair(snaps, pair)) {
1387 			char fsname[MAXNAMELEN];
1388 			char *snapname = nvpair_name(pair);
1389 			char *atp;
1390 			void *cookie;
1391 
1392 			atp = strchr(snapname, '@');
1393 			if (atp == NULL) {
1394 				error = SET_ERROR(EINVAL);
1395 				break;
1396 			}
1397 			(void) strlcpy(fsname, snapname, atp - snapname + 1);
1398 
1399 			error = zil_suspend(fsname, &cookie);
1400 			if (error != 0)
1401 				break;
1402 			fnvlist_add_uint64(suspended, fsname,
1403 			    (uintptr_t)cookie);
1404 		}
1405 	}
1406 
1407 	ddsa.ddsa_snaps = snaps;
1408 	ddsa.ddsa_props = props;
1409 	ddsa.ddsa_errors = errors;
1410 	ddsa.ddsa_cr = CRED();
1411 
1412 	if (error == 0) {
1413 		error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1414 		    dsl_dataset_snapshot_sync, &ddsa,
1415 		    fnvlist_num_pairs(snaps) * 3, ZFS_SPACE_CHECK_NORMAL);
1416 	}
1417 
1418 	if (suspended != NULL) {
1419 		for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
1420 		    pair = nvlist_next_nvpair(suspended, pair)) {
1421 			zil_resume((void *)(uintptr_t)
1422 			    fnvpair_value_uint64(pair));
1423 		}
1424 		fnvlist_free(suspended);
1425 	}
1426 
1427 	return (error);
1428 }
1429 
1430 typedef struct dsl_dataset_snapshot_tmp_arg {
1431 	const char *ddsta_fsname;
1432 	const char *ddsta_snapname;
1433 	minor_t ddsta_cleanup_minor;
1434 	const char *ddsta_htag;
1435 } dsl_dataset_snapshot_tmp_arg_t;
1436 
1437 static int
1438 dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
1439 {
1440 	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1441 	dsl_pool_t *dp = dmu_tx_pool(tx);
1442 	dsl_dataset_t *ds;
1443 	int error;
1444 
1445 	error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
1446 	if (error != 0)
1447 		return (error);
1448 
1449 	/* NULL cred means no limit check for tmp snapshot */
1450 	error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
1451 	    tx, B_FALSE, 0, NULL);
1452 	if (error != 0) {
1453 		dsl_dataset_rele(ds, FTAG);
1454 		return (error);
1455 	}
1456 
1457 	if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
1458 		dsl_dataset_rele(ds, FTAG);
1459 		return (SET_ERROR(ENOTSUP));
1460 	}
1461 	error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
1462 	    B_TRUE, tx);
1463 	if (error != 0) {
1464 		dsl_dataset_rele(ds, FTAG);
1465 		return (error);
1466 	}
1467 
1468 	dsl_dataset_rele(ds, FTAG);
1469 	return (0);
1470 }
1471 
1472 static void
1473 dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
1474 {
1475 	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1476 	dsl_pool_t *dp = dmu_tx_pool(tx);
1477 	dsl_dataset_t *ds;
1478 
1479 	VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
1480 
1481 	dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
1482 	dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
1483 	    ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
1484 	dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
1485 
1486 	dsl_dataset_rele(ds, FTAG);
1487 }
1488 
1489 int
1490 dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
1491     minor_t cleanup_minor, const char *htag)
1492 {
1493 	dsl_dataset_snapshot_tmp_arg_t ddsta;
1494 	int error;
1495 	spa_t *spa;
1496 	boolean_t needsuspend;
1497 	void *cookie;
1498 
1499 	ddsta.ddsta_fsname = fsname;
1500 	ddsta.ddsta_snapname = snapname;
1501 	ddsta.ddsta_cleanup_minor = cleanup_minor;
1502 	ddsta.ddsta_htag = htag;
1503 
1504 	error = spa_open(fsname, &spa, FTAG);
1505 	if (error != 0)
1506 		return (error);
1507 	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1508 	spa_close(spa, FTAG);
1509 
1510 	if (needsuspend) {
1511 		error = zil_suspend(fsname, &cookie);
1512 		if (error != 0)
1513 			return (error);
1514 	}
1515 
1516 	error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
1517 	    dsl_dataset_snapshot_tmp_sync, &ddsta, 3, ZFS_SPACE_CHECK_RESERVED);
1518 
1519 	if (needsuspend)
1520 		zil_resume(cookie);
1521 	return (error);
1522 }
1523 
1524 
1525 void
1526 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
1527 {
1528 	ASSERT(dmu_tx_is_syncing(tx));
1529 	ASSERT(ds->ds_objset != NULL);
1530 	ASSERT(dsl_dataset_phys(ds)->ds_next_snap_obj == 0);
1531 
1532 	/*
1533 	 * in case we had to change ds_fsid_guid when we opened it,
1534 	 * sync it out now.
1535 	 */
1536 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1537 	dsl_dataset_phys(ds)->ds_fsid_guid = ds->ds_fsid_guid;
1538 
1539 	dmu_objset_sync(ds->ds_objset, zio, tx);
1540 
1541 	if (ds->ds_need_large_blocks && !ds->ds_large_blocks) {
1542 		dsl_dataset_activate_large_blocks_sync_impl(ds->ds_object, tx);
1543 		ds->ds_large_blocks = B_TRUE;
1544 	}
1545 }
1546 
1547 static void
1548 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
1549 {
1550 	uint64_t count = 0;
1551 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1552 	zap_cursor_t zc;
1553 	zap_attribute_t za;
1554 	nvlist_t *propval = fnvlist_alloc();
1555 	nvlist_t *val = fnvlist_alloc();
1556 
1557 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
1558 
1559 	/*
1560 	 * There may be missing entries in ds_next_clones_obj
1561 	 * due to a bug in a previous version of the code.
1562 	 * Only trust it if it has the right number of entries.
1563 	 */
1564 	if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
1565 		VERIFY0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1566 		    &count));
1567 	}
1568 	if (count != dsl_dataset_phys(ds)->ds_num_children - 1)
1569 		goto fail;
1570 	for (zap_cursor_init(&zc, mos,
1571 	    dsl_dataset_phys(ds)->ds_next_clones_obj);
1572 	    zap_cursor_retrieve(&zc, &za) == 0;
1573 	    zap_cursor_advance(&zc)) {
1574 		dsl_dataset_t *clone;
1575 		char buf[ZFS_MAXNAMELEN];
1576 		VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
1577 		    za.za_first_integer, FTAG, &clone));
1578 		dsl_dir_name(clone->ds_dir, buf);
1579 		fnvlist_add_boolean(val, buf);
1580 		dsl_dataset_rele(clone, FTAG);
1581 	}
1582 	zap_cursor_fini(&zc);
1583 	fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
1584 	fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES), propval);
1585 fail:
1586 	nvlist_free(val);
1587 	nvlist_free(propval);
1588 }
1589 
1590 void
1591 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
1592 {
1593 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1594 	uint64_t refd, avail, uobjs, aobjs, ratio;
1595 
1596 	ASSERT(dsl_pool_config_held(dp));
1597 
1598 	ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
1599 	    (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
1600 	    dsl_dataset_phys(ds)->ds_compressed_bytes);
1601 
1602 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO, ratio);
1603 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
1604 	    dsl_dataset_phys(ds)->ds_uncompressed_bytes);
1605 
1606 	if (ds->ds_is_snapshot) {
1607 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
1608 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
1609 		    dsl_dataset_phys(ds)->ds_unique_bytes);
1610 		get_clones_stat(ds, nv);
1611 	} else {
1612 		if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
1613 			char buf[MAXNAMELEN];
1614 			dsl_dataset_name(ds->ds_prev, buf);
1615 			dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP, buf);
1616 		}
1617 
1618 		dsl_dir_stats(ds->ds_dir, nv);
1619 	}
1620 
1621 	dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
1622 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
1623 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
1624 
1625 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
1626 	    dsl_dataset_phys(ds)->ds_creation_time);
1627 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
1628 	    dsl_dataset_phys(ds)->ds_creation_txg);
1629 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
1630 	    ds->ds_quota);
1631 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
1632 	    ds->ds_reserved);
1633 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
1634 	    dsl_dataset_phys(ds)->ds_guid);
1635 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
1636 	    dsl_dataset_phys(ds)->ds_unique_bytes);
1637 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
1638 	    ds->ds_object);
1639 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
1640 	    ds->ds_userrefs);
1641 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
1642 	    DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
1643 
1644 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
1645 		uint64_t written, comp, uncomp;
1646 		dsl_pool_t *dp = ds->ds_dir->dd_pool;
1647 		dsl_dataset_t *prev;
1648 
1649 		int err = dsl_dataset_hold_obj(dp,
1650 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
1651 		if (err == 0) {
1652 			err = dsl_dataset_space_written(prev, ds, &written,
1653 			    &comp, &uncomp);
1654 			dsl_dataset_rele(prev, FTAG);
1655 			if (err == 0) {
1656 				dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
1657 				    written);
1658 			}
1659 		}
1660 	}
1661 }
1662 
1663 void
1664 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
1665 {
1666 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1667 	ASSERT(dsl_pool_config_held(dp));
1668 
1669 	stat->dds_creation_txg = dsl_dataset_phys(ds)->ds_creation_txg;
1670 	stat->dds_inconsistent =
1671 	    dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT;
1672 	stat->dds_guid = dsl_dataset_phys(ds)->ds_guid;
1673 	stat->dds_origin[0] = '\0';
1674 	if (ds->ds_is_snapshot) {
1675 		stat->dds_is_snapshot = B_TRUE;
1676 		stat->dds_num_clones =
1677 		    dsl_dataset_phys(ds)->ds_num_children - 1;
1678 	} else {
1679 		stat->dds_is_snapshot = B_FALSE;
1680 		stat->dds_num_clones = 0;
1681 
1682 		if (dsl_dir_is_clone(ds->ds_dir)) {
1683 			dsl_dataset_t *ods;
1684 
1685 			VERIFY0(dsl_dataset_hold_obj(dp,
1686 			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj,
1687 			    FTAG, &ods));
1688 			dsl_dataset_name(ods, stat->dds_origin);
1689 			dsl_dataset_rele(ods, FTAG);
1690 		}
1691 	}
1692 }
1693 
1694 uint64_t
1695 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
1696 {
1697 	return (ds->ds_fsid_guid);
1698 }
1699 
1700 void
1701 dsl_dataset_space(dsl_dataset_t *ds,
1702     uint64_t *refdbytesp, uint64_t *availbytesp,
1703     uint64_t *usedobjsp, uint64_t *availobjsp)
1704 {
1705 	*refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
1706 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
1707 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
1708 		*availbytesp +=
1709 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
1710 	if (ds->ds_quota != 0) {
1711 		/*
1712 		 * Adjust available bytes according to refquota
1713 		 */
1714 		if (*refdbytesp < ds->ds_quota)
1715 			*availbytesp = MIN(*availbytesp,
1716 			    ds->ds_quota - *refdbytesp);
1717 		else
1718 			*availbytesp = 0;
1719 	}
1720 	*usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
1721 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
1722 }
1723 
1724 boolean_t
1725 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
1726 {
1727 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1728 
1729 	ASSERT(dsl_pool_config_held(dp));
1730 	if (snap == NULL)
1731 		return (B_FALSE);
1732 	if (dsl_dataset_phys(ds)->ds_bp.blk_birth >
1733 	    dsl_dataset_phys(snap)->ds_creation_txg) {
1734 		objset_t *os, *os_snap;
1735 		/*
1736 		 * It may be that only the ZIL differs, because it was
1737 		 * reset in the head.  Don't count that as being
1738 		 * modified.
1739 		 */
1740 		if (dmu_objset_from_ds(ds, &os) != 0)
1741 			return (B_TRUE);
1742 		if (dmu_objset_from_ds(snap, &os_snap) != 0)
1743 			return (B_TRUE);
1744 		return (bcmp(&os->os_phys->os_meta_dnode,
1745 		    &os_snap->os_phys->os_meta_dnode,
1746 		    sizeof (os->os_phys->os_meta_dnode)) != 0);
1747 	}
1748 	return (B_FALSE);
1749 }
1750 
1751 typedef struct dsl_dataset_rename_snapshot_arg {
1752 	const char *ddrsa_fsname;
1753 	const char *ddrsa_oldsnapname;
1754 	const char *ddrsa_newsnapname;
1755 	boolean_t ddrsa_recursive;
1756 	dmu_tx_t *ddrsa_tx;
1757 } dsl_dataset_rename_snapshot_arg_t;
1758 
1759 /* ARGSUSED */
1760 static int
1761 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
1762     dsl_dataset_t *hds, void *arg)
1763 {
1764 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1765 	int error;
1766 	uint64_t val;
1767 
1768 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
1769 	if (error != 0) {
1770 		/* ignore nonexistent snapshots */
1771 		return (error == ENOENT ? 0 : error);
1772 	}
1773 
1774 	/* new name should not exist */
1775 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
1776 	if (error == 0)
1777 		error = SET_ERROR(EEXIST);
1778 	else if (error == ENOENT)
1779 		error = 0;
1780 
1781 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
1782 	if (dsl_dir_namelen(hds->ds_dir) + 1 +
1783 	    strlen(ddrsa->ddrsa_newsnapname) >= MAXNAMELEN)
1784 		error = SET_ERROR(ENAMETOOLONG);
1785 
1786 	return (error);
1787 }
1788 
1789 static int
1790 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
1791 {
1792 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1793 	dsl_pool_t *dp = dmu_tx_pool(tx);
1794 	dsl_dataset_t *hds;
1795 	int error;
1796 
1797 	error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
1798 	if (error != 0)
1799 		return (error);
1800 
1801 	if (ddrsa->ddrsa_recursive) {
1802 		error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
1803 		    dsl_dataset_rename_snapshot_check_impl, ddrsa,
1804 		    DS_FIND_CHILDREN);
1805 	} else {
1806 		error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
1807 	}
1808 	dsl_dataset_rele(hds, FTAG);
1809 	return (error);
1810 }
1811 
1812 static int
1813 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
1814     dsl_dataset_t *hds, void *arg)
1815 {
1816 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1817 	dsl_dataset_t *ds;
1818 	uint64_t val;
1819 	dmu_tx_t *tx = ddrsa->ddrsa_tx;
1820 	int error;
1821 
1822 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
1823 	ASSERT(error == 0 || error == ENOENT);
1824 	if (error == ENOENT) {
1825 		/* ignore nonexistent snapshots */
1826 		return (0);
1827 	}
1828 
1829 	VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
1830 
1831 	/* log before we change the name */
1832 	spa_history_log_internal_ds(ds, "rename", tx,
1833 	    "-> @%s", ddrsa->ddrsa_newsnapname);
1834 
1835 	VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
1836 	    B_FALSE));
1837 	mutex_enter(&ds->ds_lock);
1838 	(void) strcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname);
1839 	mutex_exit(&ds->ds_lock);
1840 	VERIFY0(zap_add(dp->dp_meta_objset,
1841 	    dsl_dataset_phys(hds)->ds_snapnames_zapobj,
1842 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx));
1843 
1844 	dsl_dataset_rele(ds, FTAG);
1845 	return (0);
1846 }
1847 
1848 static void
1849 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
1850 {
1851 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1852 	dsl_pool_t *dp = dmu_tx_pool(tx);
1853 	dsl_dataset_t *hds;
1854 
1855 	VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
1856 	ddrsa->ddrsa_tx = tx;
1857 	if (ddrsa->ddrsa_recursive) {
1858 		VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
1859 		    dsl_dataset_rename_snapshot_sync_impl, ddrsa,
1860 		    DS_FIND_CHILDREN));
1861 	} else {
1862 		VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
1863 	}
1864 	dsl_dataset_rele(hds, FTAG);
1865 }
1866 
1867 int
1868 dsl_dataset_rename_snapshot(const char *fsname,
1869     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
1870 {
1871 	dsl_dataset_rename_snapshot_arg_t ddrsa;
1872 
1873 	ddrsa.ddrsa_fsname = fsname;
1874 	ddrsa.ddrsa_oldsnapname = oldsnapname;
1875 	ddrsa.ddrsa_newsnapname = newsnapname;
1876 	ddrsa.ddrsa_recursive = recursive;
1877 
1878 	return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
1879 	    dsl_dataset_rename_snapshot_sync, &ddrsa,
1880 	    1, ZFS_SPACE_CHECK_RESERVED));
1881 }
1882 
1883 /*
1884  * If we're doing an ownership handoff, we need to make sure that there is
1885  * only one long hold on the dataset.  We're not allowed to change anything here
1886  * so we don't permanently release the long hold or regular hold here.  We want
1887  * to do this only when syncing to avoid the dataset unexpectedly going away
1888  * when we release the long hold.
1889  */
1890 static int
1891 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
1892 {
1893 	boolean_t held;
1894 
1895 	if (!dmu_tx_is_syncing(tx))
1896 		return (0);
1897 
1898 	if (owner != NULL) {
1899 		VERIFY3P(ds->ds_owner, ==, owner);
1900 		dsl_dataset_long_rele(ds, owner);
1901 	}
1902 
1903 	held = dsl_dataset_long_held(ds);
1904 
1905 	if (owner != NULL)
1906 		dsl_dataset_long_hold(ds, owner);
1907 
1908 	if (held)
1909 		return (SET_ERROR(EBUSY));
1910 
1911 	return (0);
1912 }
1913 
1914 typedef struct dsl_dataset_rollback_arg {
1915 	const char *ddra_fsname;
1916 	void *ddra_owner;
1917 	nvlist_t *ddra_result;
1918 } dsl_dataset_rollback_arg_t;
1919 
1920 static int
1921 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
1922 {
1923 	dsl_dataset_rollback_arg_t *ddra = arg;
1924 	dsl_pool_t *dp = dmu_tx_pool(tx);
1925 	dsl_dataset_t *ds;
1926 	int64_t unused_refres_delta;
1927 	int error;
1928 
1929 	error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
1930 	if (error != 0)
1931 		return (error);
1932 
1933 	/* must not be a snapshot */
1934 	if (ds->ds_is_snapshot) {
1935 		dsl_dataset_rele(ds, FTAG);
1936 		return (SET_ERROR(EINVAL));
1937 	}
1938 
1939 	/* must have a most recent snapshot */
1940 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
1941 		dsl_dataset_rele(ds, FTAG);
1942 		return (SET_ERROR(EINVAL));
1943 	}
1944 
1945 	/* must not have any bookmarks after the most recent snapshot */
1946 	nvlist_t *proprequest = fnvlist_alloc();
1947 	fnvlist_add_boolean(proprequest, zfs_prop_to_name(ZFS_PROP_CREATETXG));
1948 	nvlist_t *bookmarks = fnvlist_alloc();
1949 	error = dsl_get_bookmarks_impl(ds, proprequest, bookmarks);
1950 	fnvlist_free(proprequest);
1951 	if (error != 0)
1952 		return (error);
1953 	for (nvpair_t *pair = nvlist_next_nvpair(bookmarks, NULL);
1954 	    pair != NULL; pair = nvlist_next_nvpair(bookmarks, pair)) {
1955 		nvlist_t *valuenv =
1956 		    fnvlist_lookup_nvlist(fnvpair_value_nvlist(pair),
1957 		    zfs_prop_to_name(ZFS_PROP_CREATETXG));
1958 		uint64_t createtxg = fnvlist_lookup_uint64(valuenv, "value");
1959 		if (createtxg > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
1960 			fnvlist_free(bookmarks);
1961 			dsl_dataset_rele(ds, FTAG);
1962 			return (SET_ERROR(EEXIST));
1963 		}
1964 	}
1965 	fnvlist_free(bookmarks);
1966 
1967 	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
1968 	if (error != 0) {
1969 		dsl_dataset_rele(ds, FTAG);
1970 		return (error);
1971 	}
1972 
1973 	/*
1974 	 * Check if the snap we are rolling back to uses more than
1975 	 * the refquota.
1976 	 */
1977 	if (ds->ds_quota != 0 &&
1978 	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
1979 		dsl_dataset_rele(ds, FTAG);
1980 		return (SET_ERROR(EDQUOT));
1981 	}
1982 
1983 	/*
1984 	 * When we do the clone swap, we will temporarily use more space
1985 	 * due to the refreservation (the head will no longer have any
1986 	 * unique space, so the entire amount of the refreservation will need
1987 	 * to be free).  We will immediately destroy the clone, freeing
1988 	 * this space, but the freeing happens over many txg's.
1989 	 */
1990 	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
1991 	    dsl_dataset_phys(ds)->ds_unique_bytes);
1992 
1993 	if (unused_refres_delta > 0 &&
1994 	    unused_refres_delta >
1995 	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
1996 		dsl_dataset_rele(ds, FTAG);
1997 		return (SET_ERROR(ENOSPC));
1998 	}
1999 
2000 	dsl_dataset_rele(ds, FTAG);
2001 	return (0);
2002 }
2003 
2004 static void
2005 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
2006 {
2007 	dsl_dataset_rollback_arg_t *ddra = arg;
2008 	dsl_pool_t *dp = dmu_tx_pool(tx);
2009 	dsl_dataset_t *ds, *clone;
2010 	uint64_t cloneobj;
2011 	char namebuf[ZFS_MAXNAMELEN];
2012 
2013 	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
2014 
2015 	dsl_dataset_name(ds->ds_prev, namebuf);
2016 	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
2017 
2018 	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
2019 	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, tx);
2020 
2021 	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
2022 
2023 	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
2024 	dsl_dataset_zero_zil(ds, tx);
2025 
2026 	dsl_destroy_head_sync_impl(clone, tx);
2027 
2028 	dsl_dataset_rele(clone, FTAG);
2029 	dsl_dataset_rele(ds, FTAG);
2030 }
2031 
2032 /*
2033  * Rolls back the given filesystem or volume to the most recent snapshot.
2034  * The name of the most recent snapshot will be returned under key "target"
2035  * in the result nvlist.
2036  *
2037  * If owner != NULL:
2038  * - The existing dataset MUST be owned by the specified owner at entry
2039  * - Upon return, dataset will still be held by the same owner, whether we
2040  *   succeed or not.
2041  *
2042  * This mode is required any time the existing filesystem is mounted.  See
2043  * notes above zfs_suspend_fs() for further details.
2044  */
2045 int
2046 dsl_dataset_rollback(const char *fsname, void *owner, nvlist_t *result)
2047 {
2048 	dsl_dataset_rollback_arg_t ddra;
2049 
2050 	ddra.ddra_fsname = fsname;
2051 	ddra.ddra_owner = owner;
2052 	ddra.ddra_result = result;
2053 
2054 	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
2055 	    dsl_dataset_rollback_sync, &ddra,
2056 	    1, ZFS_SPACE_CHECK_RESERVED));
2057 }
2058 
2059 struct promotenode {
2060 	list_node_t link;
2061 	dsl_dataset_t *ds;
2062 };
2063 
2064 typedef struct dsl_dataset_promote_arg {
2065 	const char *ddpa_clonename;
2066 	dsl_dataset_t *ddpa_clone;
2067 	list_t shared_snaps, origin_snaps, clone_snaps;
2068 	dsl_dataset_t *origin_origin; /* origin of the origin */
2069 	uint64_t used, comp, uncomp, unique, cloneusedsnap, originusedsnap;
2070 	char *err_ds;
2071 	cred_t *cr;
2072 } dsl_dataset_promote_arg_t;
2073 
2074 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2075 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
2076     void *tag);
2077 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
2078 
2079 static int
2080 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
2081 {
2082 	dsl_dataset_promote_arg_t *ddpa = arg;
2083 	dsl_pool_t *dp = dmu_tx_pool(tx);
2084 	dsl_dataset_t *hds;
2085 	struct promotenode *snap;
2086 	dsl_dataset_t *origin_ds;
2087 	int err;
2088 	uint64_t unused;
2089 	uint64_t ss_mv_cnt;
2090 
2091 	err = promote_hold(ddpa, dp, FTAG);
2092 	if (err != 0)
2093 		return (err);
2094 
2095 	hds = ddpa->ddpa_clone;
2096 
2097 	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
2098 		promote_rele(ddpa, FTAG);
2099 		return (SET_ERROR(EXDEV));
2100 	}
2101 
2102 	/*
2103 	 * Compute and check the amount of space to transfer.  Since this is
2104 	 * so expensive, don't do the preliminary check.
2105 	 */
2106 	if (!dmu_tx_is_syncing(tx)) {
2107 		promote_rele(ddpa, FTAG);
2108 		return (0);
2109 	}
2110 
2111 	snap = list_head(&ddpa->shared_snaps);
2112 	origin_ds = snap->ds;
2113 
2114 	/* compute origin's new unique space */
2115 	snap = list_tail(&ddpa->clone_snaps);
2116 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2117 	    origin_ds->ds_object);
2118 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2119 	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
2120 	    &ddpa->unique, &unused, &unused);
2121 
2122 	/*
2123 	 * Walk the snapshots that we are moving
2124 	 *
2125 	 * Compute space to transfer.  Consider the incremental changes
2126 	 * to used by each snapshot:
2127 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
2128 	 * So each snapshot gave birth to:
2129 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
2130 	 * So a sequence would look like:
2131 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2132 	 * Which simplifies to:
2133 	 * uN + kN + kN-1 + ... + k1 + k0
2134 	 * Note however, if we stop before we reach the ORIGIN we get:
2135 	 * uN + kN + kN-1 + ... + kM - uM-1
2136 	 */
2137 	ss_mv_cnt = 0;
2138 	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
2139 	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
2140 	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
2141 	for (snap = list_head(&ddpa->shared_snaps); snap;
2142 	    snap = list_next(&ddpa->shared_snaps, snap)) {
2143 		uint64_t val, dlused, dlcomp, dluncomp;
2144 		dsl_dataset_t *ds = snap->ds;
2145 
2146 		ss_mv_cnt++;
2147 
2148 		/*
2149 		 * If there are long holds, we won't be able to evict
2150 		 * the objset.
2151 		 */
2152 		if (dsl_dataset_long_held(ds)) {
2153 			err = SET_ERROR(EBUSY);
2154 			goto out;
2155 		}
2156 
2157 		/* Check that the snapshot name does not conflict */
2158 		VERIFY0(dsl_dataset_get_snapname(ds));
2159 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2160 		if (err == 0) {
2161 			(void) strcpy(ddpa->err_ds, snap->ds->ds_snapname);
2162 			err = SET_ERROR(EEXIST);
2163 			goto out;
2164 		}
2165 		if (err != ENOENT)
2166 			goto out;
2167 
2168 		/* The very first snapshot does not have a deadlist */
2169 		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
2170 			continue;
2171 
2172 		dsl_deadlist_space(&ds->ds_deadlist,
2173 		    &dlused, &dlcomp, &dluncomp);
2174 		ddpa->used += dlused;
2175 		ddpa->comp += dlcomp;
2176 		ddpa->uncomp += dluncomp;
2177 	}
2178 
2179 	/*
2180 	 * If we are a clone of a clone then we never reached ORIGIN,
2181 	 * so we need to subtract out the clone origin's used space.
2182 	 */
2183 	if (ddpa->origin_origin) {
2184 		ddpa->used -=
2185 		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
2186 		ddpa->comp -=
2187 		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
2188 		ddpa->uncomp -=
2189 		    dsl_dataset_phys(ddpa->origin_origin)->
2190 		    ds_uncompressed_bytes;
2191 	}
2192 
2193 	/* Check that there is enough space and limit headroom here */
2194 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2195 	    0, ss_mv_cnt, ddpa->used, ddpa->cr);
2196 	if (err != 0)
2197 		goto out;
2198 
2199 	/*
2200 	 * Compute the amounts of space that will be used by snapshots
2201 	 * after the promotion (for both origin and clone).  For each,
2202 	 * it is the amount of space that will be on all of their
2203 	 * deadlists (that was not born before their new origin).
2204 	 */
2205 	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2206 		uint64_t space;
2207 
2208 		/*
2209 		 * Note, typically this will not be a clone of a clone,
2210 		 * so dd_origin_txg will be < TXG_INITIAL, so
2211 		 * these snaplist_space() -> dsl_deadlist_space_range()
2212 		 * calls will be fast because they do not have to
2213 		 * iterate over all bps.
2214 		 */
2215 		snap = list_head(&ddpa->origin_snaps);
2216 		err = snaplist_space(&ddpa->shared_snaps,
2217 		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
2218 		if (err != 0)
2219 			goto out;
2220 
2221 		err = snaplist_space(&ddpa->clone_snaps,
2222 		    snap->ds->ds_dir->dd_origin_txg, &space);
2223 		if (err != 0)
2224 			goto out;
2225 		ddpa->cloneusedsnap += space;
2226 	}
2227 	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
2228 	    DD_FLAG_USED_BREAKDOWN) {
2229 		err = snaplist_space(&ddpa->origin_snaps,
2230 		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
2231 		    &ddpa->originusedsnap);
2232 		if (err != 0)
2233 			goto out;
2234 	}
2235 
2236 out:
2237 	promote_rele(ddpa, FTAG);
2238 	return (err);
2239 }
2240 
2241 static void
2242 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
2243 {
2244 	dsl_dataset_promote_arg_t *ddpa = arg;
2245 	dsl_pool_t *dp = dmu_tx_pool(tx);
2246 	dsl_dataset_t *hds;
2247 	struct promotenode *snap;
2248 	dsl_dataset_t *origin_ds;
2249 	dsl_dataset_t *origin_head;
2250 	dsl_dir_t *dd;
2251 	dsl_dir_t *odd = NULL;
2252 	uint64_t oldnext_obj;
2253 	int64_t delta;
2254 
2255 	VERIFY0(promote_hold(ddpa, dp, FTAG));
2256 	hds = ddpa->ddpa_clone;
2257 
2258 	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
2259 
2260 	snap = list_head(&ddpa->shared_snaps);
2261 	origin_ds = snap->ds;
2262 	dd = hds->ds_dir;
2263 
2264 	snap = list_head(&ddpa->origin_snaps);
2265 	origin_head = snap->ds;
2266 
2267 	/*
2268 	 * We need to explicitly open odd, since origin_ds's dd will be
2269 	 * changing.
2270 	 */
2271 	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
2272 	    NULL, FTAG, &odd));
2273 
2274 	/* change origin's next snap */
2275 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2276 	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
2277 	snap = list_tail(&ddpa->clone_snaps);
2278 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2279 	    origin_ds->ds_object);
2280 	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
2281 
2282 	/* change the origin's next clone */
2283 	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
2284 		dsl_dataset_remove_from_next_clones(origin_ds,
2285 		    snap->ds->ds_object, tx);
2286 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2287 		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
2288 		    oldnext_obj, tx));
2289 	}
2290 
2291 	/* change origin */
2292 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
2293 	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
2294 	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
2295 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2296 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
2297 	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
2298 	origin_head->ds_dir->dd_origin_txg =
2299 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
2300 
2301 	/* change dd_clone entries */
2302 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2303 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
2304 		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
2305 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2306 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2307 		    hds->ds_object, tx));
2308 
2309 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
2310 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2311 		    origin_head->ds_object, tx));
2312 		if (dsl_dir_phys(dd)->dd_clones == 0) {
2313 			dsl_dir_phys(dd)->dd_clones =
2314 			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
2315 			    DMU_OT_NONE, 0, tx);
2316 		}
2317 		VERIFY0(zap_add_int(dp->dp_meta_objset,
2318 		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
2319 	}
2320 
2321 	/* move snapshots to this dir */
2322 	for (snap = list_head(&ddpa->shared_snaps); snap;
2323 	    snap = list_next(&ddpa->shared_snaps, snap)) {
2324 		dsl_dataset_t *ds = snap->ds;
2325 
2326 		/*
2327 		 * Property callbacks are registered to a particular
2328 		 * dsl_dir.  Since ours is changing, evict the objset
2329 		 * so that they will be unregistered from the old dsl_dir.
2330 		 */
2331 		if (ds->ds_objset) {
2332 			dmu_objset_evict(ds->ds_objset);
2333 			ds->ds_objset = NULL;
2334 		}
2335 
2336 		/* move snap name entry */
2337 		VERIFY0(dsl_dataset_get_snapname(ds));
2338 		VERIFY0(dsl_dataset_snap_remove(origin_head,
2339 		    ds->ds_snapname, tx, B_TRUE));
2340 		VERIFY0(zap_add(dp->dp_meta_objset,
2341 		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
2342 		    8, 1, &ds->ds_object, tx));
2343 		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
2344 		    DD_FIELD_SNAPSHOT_COUNT, tx);
2345 
2346 		/* change containing dsl_dir */
2347 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2348 		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
2349 		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
2350 		ASSERT3P(ds->ds_dir, ==, odd);
2351 		dsl_dir_rele(ds->ds_dir, ds);
2352 		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
2353 		    NULL, ds, &ds->ds_dir));
2354 
2355 		/* move any clone references */
2356 		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
2357 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2358 			zap_cursor_t zc;
2359 			zap_attribute_t za;
2360 
2361 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
2362 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
2363 			    zap_cursor_retrieve(&zc, &za) == 0;
2364 			    zap_cursor_advance(&zc)) {
2365 				dsl_dataset_t *cnds;
2366 				uint64_t o;
2367 
2368 				if (za.za_first_integer == oldnext_obj) {
2369 					/*
2370 					 * We've already moved the
2371 					 * origin's reference.
2372 					 */
2373 					continue;
2374 				}
2375 
2376 				VERIFY0(dsl_dataset_hold_obj(dp,
2377 				    za.za_first_integer, FTAG, &cnds));
2378 				o = dsl_dir_phys(cnds->ds_dir)->
2379 				    dd_head_dataset_obj;
2380 
2381 				VERIFY0(zap_remove_int(dp->dp_meta_objset,
2382 				    dsl_dir_phys(odd)->dd_clones, o, tx));
2383 				VERIFY0(zap_add_int(dp->dp_meta_objset,
2384 				    dsl_dir_phys(dd)->dd_clones, o, tx));
2385 				dsl_dataset_rele(cnds, FTAG);
2386 			}
2387 			zap_cursor_fini(&zc);
2388 		}
2389 
2390 		ASSERT(!dsl_prop_hascb(ds));
2391 	}
2392 
2393 	/*
2394 	 * Change space accounting.
2395 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
2396 	 * both be valid, or both be 0 (resulting in delta == 0).  This
2397 	 * is true for each of {clone,origin} independently.
2398 	 */
2399 
2400 	delta = ddpa->cloneusedsnap -
2401 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
2402 	ASSERT3S(delta, >=, 0);
2403 	ASSERT3U(ddpa->used, >=, delta);
2404 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
2405 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
2406 	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
2407 
2408 	delta = ddpa->originusedsnap -
2409 	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
2410 	ASSERT3S(delta, <=, 0);
2411 	ASSERT3U(ddpa->used, >=, -delta);
2412 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
2413 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
2414 	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
2415 
2416 	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
2417 
2418 	/* log history record */
2419 	spa_history_log_internal_ds(hds, "promote", tx, "");
2420 
2421 	dsl_dir_rele(odd, FTAG);
2422 	promote_rele(ddpa, FTAG);
2423 }
2424 
2425 /*
2426  * Make a list of dsl_dataset_t's for the snapshots between first_obj
2427  * (exclusive) and last_obj (inclusive).  The list will be in reverse
2428  * order (last_obj will be the list_head()).  If first_obj == 0, do all
2429  * snapshots back to this dataset's origin.
2430  */
2431 static int
2432 snaplist_make(dsl_pool_t *dp,
2433     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
2434 {
2435 	uint64_t obj = last_obj;
2436 
2437 	list_create(l, sizeof (struct promotenode),
2438 	    offsetof(struct promotenode, link));
2439 
2440 	while (obj != first_obj) {
2441 		dsl_dataset_t *ds;
2442 		struct promotenode *snap;
2443 		int err;
2444 
2445 		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
2446 		ASSERT(err != ENOENT);
2447 		if (err != 0)
2448 			return (err);
2449 
2450 		if (first_obj == 0)
2451 			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
2452 
2453 		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
2454 		snap->ds = ds;
2455 		list_insert_tail(l, snap);
2456 		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
2457 	}
2458 
2459 	return (0);
2460 }
2461 
2462 static int
2463 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
2464 {
2465 	struct promotenode *snap;
2466 
2467 	*spacep = 0;
2468 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
2469 		uint64_t used, comp, uncomp;
2470 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2471 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
2472 		*spacep += used;
2473 	}
2474 	return (0);
2475 }
2476 
2477 static void
2478 snaplist_destroy(list_t *l, void *tag)
2479 {
2480 	struct promotenode *snap;
2481 
2482 	if (l == NULL || !list_link_active(&l->list_head))
2483 		return;
2484 
2485 	while ((snap = list_tail(l)) != NULL) {
2486 		list_remove(l, snap);
2487 		dsl_dataset_rele(snap->ds, tag);
2488 		kmem_free(snap, sizeof (*snap));
2489 	}
2490 	list_destroy(l);
2491 }
2492 
2493 static int
2494 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
2495 {
2496 	int error;
2497 	dsl_dir_t *dd;
2498 	struct promotenode *snap;
2499 
2500 	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
2501 	    &ddpa->ddpa_clone);
2502 	if (error != 0)
2503 		return (error);
2504 	dd = ddpa->ddpa_clone->ds_dir;
2505 
2506 	if (ddpa->ddpa_clone->ds_is_snapshot ||
2507 	    !dsl_dir_is_clone(dd)) {
2508 		dsl_dataset_rele(ddpa->ddpa_clone, tag);
2509 		return (SET_ERROR(EINVAL));
2510 	}
2511 
2512 	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
2513 	    &ddpa->shared_snaps, tag);
2514 	if (error != 0)
2515 		goto out;
2516 
2517 	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
2518 	    &ddpa->clone_snaps, tag);
2519 	if (error != 0)
2520 		goto out;
2521 
2522 	snap = list_head(&ddpa->shared_snaps);
2523 	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
2524 	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
2525 	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
2526 	    &ddpa->origin_snaps, tag);
2527 	if (error != 0)
2528 		goto out;
2529 
2530 	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
2531 		error = dsl_dataset_hold_obj(dp,
2532 		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
2533 		    tag, &ddpa->origin_origin);
2534 		if (error != 0)
2535 			goto out;
2536 	}
2537 out:
2538 	if (error != 0)
2539 		promote_rele(ddpa, tag);
2540 	return (error);
2541 }
2542 
2543 static void
2544 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
2545 {
2546 	snaplist_destroy(&ddpa->shared_snaps, tag);
2547 	snaplist_destroy(&ddpa->clone_snaps, tag);
2548 	snaplist_destroy(&ddpa->origin_snaps, tag);
2549 	if (ddpa->origin_origin != NULL)
2550 		dsl_dataset_rele(ddpa->origin_origin, tag);
2551 	dsl_dataset_rele(ddpa->ddpa_clone, tag);
2552 }
2553 
2554 /*
2555  * Promote a clone.
2556  *
2557  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
2558  * in with the name.  (It must be at least MAXNAMELEN bytes long.)
2559  */
2560 int
2561 dsl_dataset_promote(const char *name, char *conflsnap)
2562 {
2563 	dsl_dataset_promote_arg_t ddpa = { 0 };
2564 	uint64_t numsnaps;
2565 	int error;
2566 	objset_t *os;
2567 
2568 	/*
2569 	 * We will modify space proportional to the number of
2570 	 * snapshots.  Compute numsnaps.
2571 	 */
2572 	error = dmu_objset_hold(name, FTAG, &os);
2573 	if (error != 0)
2574 		return (error);
2575 	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
2576 	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
2577 	    &numsnaps);
2578 	dmu_objset_rele(os, FTAG);
2579 	if (error != 0)
2580 		return (error);
2581 
2582 	ddpa.ddpa_clonename = name;
2583 	ddpa.err_ds = conflsnap;
2584 	ddpa.cr = CRED();
2585 
2586 	return (dsl_sync_task(name, dsl_dataset_promote_check,
2587 	    dsl_dataset_promote_sync, &ddpa,
2588 	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED));
2589 }
2590 
2591 int
2592 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
2593     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
2594 {
2595 	int64_t unused_refres_delta;
2596 
2597 	/* they should both be heads */
2598 	if (clone->ds_is_snapshot ||
2599 	    origin_head->ds_is_snapshot)
2600 		return (SET_ERROR(EINVAL));
2601 
2602 	/* if we are not forcing, the branch point should be just before them */
2603 	if (!force && clone->ds_prev != origin_head->ds_prev)
2604 		return (SET_ERROR(EINVAL));
2605 
2606 	/* clone should be the clone (unless they are unrelated) */
2607 	if (clone->ds_prev != NULL &&
2608 	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
2609 	    origin_head->ds_dir != clone->ds_prev->ds_dir)
2610 		return (SET_ERROR(EINVAL));
2611 
2612 	/* the clone should be a child of the origin */
2613 	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
2614 		return (SET_ERROR(EINVAL));
2615 
2616 	/* origin_head shouldn't be modified unless 'force' */
2617 	if (!force &&
2618 	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
2619 		return (SET_ERROR(ETXTBSY));
2620 
2621 	/* origin_head should have no long holds (e.g. is not mounted) */
2622 	if (dsl_dataset_handoff_check(origin_head, owner, tx))
2623 		return (SET_ERROR(EBUSY));
2624 
2625 	/* check amount of any unconsumed refreservation */
2626 	unused_refres_delta =
2627 	    (int64_t)MIN(origin_head->ds_reserved,
2628 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
2629 	    (int64_t)MIN(origin_head->ds_reserved,
2630 	    dsl_dataset_phys(clone)->ds_unique_bytes);
2631 
2632 	if (unused_refres_delta > 0 &&
2633 	    unused_refres_delta >
2634 	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
2635 		return (SET_ERROR(ENOSPC));
2636 
2637 	/* clone can't be over the head's refquota */
2638 	if (origin_head->ds_quota != 0 &&
2639 	    dsl_dataset_phys(clone)->ds_referenced_bytes >
2640 	    origin_head->ds_quota)
2641 		return (SET_ERROR(EDQUOT));
2642 
2643 	return (0);
2644 }
2645 
2646 void
2647 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
2648     dsl_dataset_t *origin_head, dmu_tx_t *tx)
2649 {
2650 	dsl_pool_t *dp = dmu_tx_pool(tx);
2651 	int64_t unused_refres_delta;
2652 
2653 	ASSERT(clone->ds_reserved == 0);
2654 	ASSERT(origin_head->ds_quota == 0 ||
2655 	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota);
2656 	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
2657 
2658 	dmu_buf_will_dirty(clone->ds_dbuf, tx);
2659 	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
2660 
2661 	if (clone->ds_objset != NULL) {
2662 		dmu_objset_evict(clone->ds_objset);
2663 		clone->ds_objset = NULL;
2664 	}
2665 
2666 	if (origin_head->ds_objset != NULL) {
2667 		dmu_objset_evict(origin_head->ds_objset);
2668 		origin_head->ds_objset = NULL;
2669 	}
2670 
2671 	unused_refres_delta =
2672 	    (int64_t)MIN(origin_head->ds_reserved,
2673 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
2674 	    (int64_t)MIN(origin_head->ds_reserved,
2675 	    dsl_dataset_phys(clone)->ds_unique_bytes);
2676 
2677 	/*
2678 	 * Reset origin's unique bytes, if it exists.
2679 	 */
2680 	if (clone->ds_prev) {
2681 		dsl_dataset_t *origin = clone->ds_prev;
2682 		uint64_t comp, uncomp;
2683 
2684 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
2685 		dsl_deadlist_space_range(&clone->ds_deadlist,
2686 		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
2687 		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
2688 	}
2689 
2690 	/* swap blkptrs */
2691 	{
2692 		blkptr_t tmp;
2693 		tmp = dsl_dataset_phys(origin_head)->ds_bp;
2694 		dsl_dataset_phys(origin_head)->ds_bp =
2695 		    dsl_dataset_phys(clone)->ds_bp;
2696 		dsl_dataset_phys(clone)->ds_bp = tmp;
2697 	}
2698 
2699 	/* set dd_*_bytes */
2700 	{
2701 		int64_t dused, dcomp, duncomp;
2702 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
2703 		uint64_t odl_used, odl_comp, odl_uncomp;
2704 
2705 		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
2706 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
2707 
2708 		dsl_deadlist_space(&clone->ds_deadlist,
2709 		    &cdl_used, &cdl_comp, &cdl_uncomp);
2710 		dsl_deadlist_space(&origin_head->ds_deadlist,
2711 		    &odl_used, &odl_comp, &odl_uncomp);
2712 
2713 		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
2714 		    cdl_used -
2715 		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
2716 		    odl_used);
2717 		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
2718 		    cdl_comp -
2719 		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
2720 		    odl_comp);
2721 		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
2722 		    cdl_uncomp -
2723 		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
2724 		    odl_uncomp);
2725 
2726 		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
2727 		    dused, dcomp, duncomp, tx);
2728 		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
2729 		    -dused, -dcomp, -duncomp, tx);
2730 
2731 		/*
2732 		 * The difference in the space used by snapshots is the
2733 		 * difference in snapshot space due to the head's
2734 		 * deadlist (since that's the only thing that's
2735 		 * changing that affects the snapused).
2736 		 */
2737 		dsl_deadlist_space_range(&clone->ds_deadlist,
2738 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2739 		    &cdl_used, &cdl_comp, &cdl_uncomp);
2740 		dsl_deadlist_space_range(&origin_head->ds_deadlist,
2741 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2742 		    &odl_used, &odl_comp, &odl_uncomp);
2743 		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
2744 		    DD_USED_HEAD, DD_USED_SNAP, tx);
2745 	}
2746 
2747 	/* swap ds_*_bytes */
2748 	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
2749 	    dsl_dataset_phys(clone)->ds_referenced_bytes);
2750 	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
2751 	    dsl_dataset_phys(clone)->ds_compressed_bytes);
2752 	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
2753 	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
2754 	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
2755 	    dsl_dataset_phys(clone)->ds_unique_bytes);
2756 
2757 	/* apply any parent delta for change in unconsumed refreservation */
2758 	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
2759 	    unused_refres_delta, 0, 0, tx);
2760 
2761 	/*
2762 	 * Swap deadlists.
2763 	 */
2764 	dsl_deadlist_close(&clone->ds_deadlist);
2765 	dsl_deadlist_close(&origin_head->ds_deadlist);
2766 	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
2767 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
2768 	dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
2769 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
2770 	dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
2771 	    dsl_dataset_phys(origin_head)->ds_deadlist_obj);
2772 
2773 	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
2774 
2775 	spa_history_log_internal_ds(clone, "clone swap", tx,
2776 	    "parent=%s", origin_head->ds_dir->dd_myname);
2777 }
2778 
2779 /*
2780  * Given a pool name and a dataset object number in that pool,
2781  * return the name of that dataset.
2782  */
2783 int
2784 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
2785 {
2786 	dsl_pool_t *dp;
2787 	dsl_dataset_t *ds;
2788 	int error;
2789 
2790 	error = dsl_pool_hold(pname, FTAG, &dp);
2791 	if (error != 0)
2792 		return (error);
2793 
2794 	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
2795 	if (error == 0) {
2796 		dsl_dataset_name(ds, buf);
2797 		dsl_dataset_rele(ds, FTAG);
2798 	}
2799 	dsl_pool_rele(dp, FTAG);
2800 
2801 	return (error);
2802 }
2803 
2804 int
2805 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
2806     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
2807 {
2808 	int error = 0;
2809 
2810 	ASSERT3S(asize, >, 0);
2811 
2812 	/*
2813 	 * *ref_rsrv is the portion of asize that will come from any
2814 	 * unconsumed refreservation space.
2815 	 */
2816 	*ref_rsrv = 0;
2817 
2818 	mutex_enter(&ds->ds_lock);
2819 	/*
2820 	 * Make a space adjustment for reserved bytes.
2821 	 */
2822 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
2823 		ASSERT3U(*used, >=,
2824 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
2825 		*used -=
2826 		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
2827 		*ref_rsrv =
2828 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
2829 	}
2830 
2831 	if (!check_quota || ds->ds_quota == 0) {
2832 		mutex_exit(&ds->ds_lock);
2833 		return (0);
2834 	}
2835 	/*
2836 	 * If they are requesting more space, and our current estimate
2837 	 * is over quota, they get to try again unless the actual
2838 	 * on-disk is over quota and there are no pending changes (which
2839 	 * may free up space for us).
2840 	 */
2841 	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
2842 	    ds->ds_quota) {
2843 		if (inflight > 0 ||
2844 		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
2845 			error = SET_ERROR(ERESTART);
2846 		else
2847 			error = SET_ERROR(EDQUOT);
2848 	}
2849 	mutex_exit(&ds->ds_lock);
2850 
2851 	return (error);
2852 }
2853 
2854 typedef struct dsl_dataset_set_qr_arg {
2855 	const char *ddsqra_name;
2856 	zprop_source_t ddsqra_source;
2857 	uint64_t ddsqra_value;
2858 } dsl_dataset_set_qr_arg_t;
2859 
2860 
2861 /* ARGSUSED */
2862 static int
2863 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
2864 {
2865 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
2866 	dsl_pool_t *dp = dmu_tx_pool(tx);
2867 	dsl_dataset_t *ds;
2868 	int error;
2869 	uint64_t newval;
2870 
2871 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
2872 		return (SET_ERROR(ENOTSUP));
2873 
2874 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
2875 	if (error != 0)
2876 		return (error);
2877 
2878 	if (ds->ds_is_snapshot) {
2879 		dsl_dataset_rele(ds, FTAG);
2880 		return (SET_ERROR(EINVAL));
2881 	}
2882 
2883 	error = dsl_prop_predict(ds->ds_dir,
2884 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
2885 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
2886 	if (error != 0) {
2887 		dsl_dataset_rele(ds, FTAG);
2888 		return (error);
2889 	}
2890 
2891 	if (newval == 0) {
2892 		dsl_dataset_rele(ds, FTAG);
2893 		return (0);
2894 	}
2895 
2896 	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
2897 	    newval < ds->ds_reserved) {
2898 		dsl_dataset_rele(ds, FTAG);
2899 		return (SET_ERROR(ENOSPC));
2900 	}
2901 
2902 	dsl_dataset_rele(ds, FTAG);
2903 	return (0);
2904 }
2905 
2906 static void
2907 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
2908 {
2909 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
2910 	dsl_pool_t *dp = dmu_tx_pool(tx);
2911 	dsl_dataset_t *ds;
2912 	uint64_t newval;
2913 
2914 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
2915 
2916 	dsl_prop_set_sync_impl(ds,
2917 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
2918 	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
2919 	    &ddsqra->ddsqra_value, tx);
2920 
2921 	VERIFY0(dsl_prop_get_int_ds(ds,
2922 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
2923 
2924 	if (ds->ds_quota != newval) {
2925 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2926 		ds->ds_quota = newval;
2927 	}
2928 	dsl_dataset_rele(ds, FTAG);
2929 }
2930 
2931 int
2932 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
2933     uint64_t refquota)
2934 {
2935 	dsl_dataset_set_qr_arg_t ddsqra;
2936 
2937 	ddsqra.ddsqra_name = dsname;
2938 	ddsqra.ddsqra_source = source;
2939 	ddsqra.ddsqra_value = refquota;
2940 
2941 	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
2942 	    dsl_dataset_set_refquota_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
2943 }
2944 
2945 static int
2946 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
2947 {
2948 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
2949 	dsl_pool_t *dp = dmu_tx_pool(tx);
2950 	dsl_dataset_t *ds;
2951 	int error;
2952 	uint64_t newval, unique;
2953 
2954 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
2955 		return (SET_ERROR(ENOTSUP));
2956 
2957 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
2958 	if (error != 0)
2959 		return (error);
2960 
2961 	if (ds->ds_is_snapshot) {
2962 		dsl_dataset_rele(ds, FTAG);
2963 		return (SET_ERROR(EINVAL));
2964 	}
2965 
2966 	error = dsl_prop_predict(ds->ds_dir,
2967 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2968 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
2969 	if (error != 0) {
2970 		dsl_dataset_rele(ds, FTAG);
2971 		return (error);
2972 	}
2973 
2974 	/*
2975 	 * If we are doing the preliminary check in open context, the
2976 	 * space estimates may be inaccurate.
2977 	 */
2978 	if (!dmu_tx_is_syncing(tx)) {
2979 		dsl_dataset_rele(ds, FTAG);
2980 		return (0);
2981 	}
2982 
2983 	mutex_enter(&ds->ds_lock);
2984 	if (!DS_UNIQUE_IS_ACCURATE(ds))
2985 		dsl_dataset_recalc_head_uniq(ds);
2986 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
2987 	mutex_exit(&ds->ds_lock);
2988 
2989 	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
2990 		uint64_t delta = MAX(unique, newval) -
2991 		    MAX(unique, ds->ds_reserved);
2992 
2993 		if (delta >
2994 		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
2995 		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
2996 			dsl_dataset_rele(ds, FTAG);
2997 			return (SET_ERROR(ENOSPC));
2998 		}
2999 	}
3000 
3001 	dsl_dataset_rele(ds, FTAG);
3002 	return (0);
3003 }
3004 
3005 void
3006 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
3007     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
3008 {
3009 	uint64_t newval;
3010 	uint64_t unique;
3011 	int64_t delta;
3012 
3013 	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
3014 	    source, sizeof (value), 1, &value, tx);
3015 
3016 	VERIFY0(dsl_prop_get_int_ds(ds,
3017 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
3018 
3019 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
3020 	mutex_enter(&ds->ds_dir->dd_lock);
3021 	mutex_enter(&ds->ds_lock);
3022 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3023 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
3024 	delta = MAX(0, (int64_t)(newval - unique)) -
3025 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
3026 	ds->ds_reserved = newval;
3027 	mutex_exit(&ds->ds_lock);
3028 
3029 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3030 	mutex_exit(&ds->ds_dir->dd_lock);
3031 }
3032 
3033 static void
3034 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
3035 {
3036 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
3037 	dsl_pool_t *dp = dmu_tx_pool(tx);
3038 	dsl_dataset_t *ds;
3039 
3040 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3041 	dsl_dataset_set_refreservation_sync_impl(ds,
3042 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
3043 	dsl_dataset_rele(ds, FTAG);
3044 }
3045 
3046 int
3047 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
3048     uint64_t refreservation)
3049 {
3050 	dsl_dataset_set_qr_arg_t ddsqra;
3051 
3052 	ddsqra.ddsqra_name = dsname;
3053 	ddsqra.ddsqra_source = source;
3054 	ddsqra.ddsqra_value = refreservation;
3055 
3056 	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
3057 	    dsl_dataset_set_refreservation_sync, &ddsqra,
3058 	    0, ZFS_SPACE_CHECK_NONE));
3059 }
3060 
3061 /*
3062  * Return (in *usedp) the amount of space written in new that is not
3063  * present in oldsnap.  New may be a snapshot or the head.  Old must be
3064  * a snapshot before new, in new's filesystem (or its origin).  If not then
3065  * fail and return EINVAL.
3066  *
3067  * The written space is calculated by considering two components:  First, we
3068  * ignore any freed space, and calculate the written as new's used space
3069  * minus old's used space.  Next, we add in the amount of space that was freed
3070  * between the two snapshots, thus reducing new's used space relative to old's.
3071  * Specifically, this is the space that was born before old->ds_creation_txg,
3072  * and freed before new (ie. on new's deadlist or a previous deadlist).
3073  *
3074  * space freed                         [---------------------]
3075  * snapshots                       ---O-------O--------O-------O------
3076  *                                         oldsnap            new
3077  */
3078 int
3079 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
3080     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3081 {
3082 	int err = 0;
3083 	uint64_t snapobj;
3084 	dsl_pool_t *dp = new->ds_dir->dd_pool;
3085 
3086 	ASSERT(dsl_pool_config_held(dp));
3087 
3088 	*usedp = 0;
3089 	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
3090 	*usedp -= dsl_dataset_phys(oldsnap)->ds_referenced_bytes;
3091 
3092 	*compp = 0;
3093 	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
3094 	*compp -= dsl_dataset_phys(oldsnap)->ds_compressed_bytes;
3095 
3096 	*uncompp = 0;
3097 	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
3098 	*uncompp -= dsl_dataset_phys(oldsnap)->ds_uncompressed_bytes;
3099 
3100 	snapobj = new->ds_object;
3101 	while (snapobj != oldsnap->ds_object) {
3102 		dsl_dataset_t *snap;
3103 		uint64_t used, comp, uncomp;
3104 
3105 		if (snapobj == new->ds_object) {
3106 			snap = new;
3107 		} else {
3108 			err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
3109 			if (err != 0)
3110 				break;
3111 		}
3112 
3113 		if (dsl_dataset_phys(snap)->ds_prev_snap_txg ==
3114 		    dsl_dataset_phys(oldsnap)->ds_creation_txg) {
3115 			/*
3116 			 * The blocks in the deadlist can not be born after
3117 			 * ds_prev_snap_txg, so get the whole deadlist space,
3118 			 * which is more efficient (especially for old-format
3119 			 * deadlists).  Unfortunately the deadlist code
3120 			 * doesn't have enough information to make this
3121 			 * optimization itself.
3122 			 */
3123 			dsl_deadlist_space(&snap->ds_deadlist,
3124 			    &used, &comp, &uncomp);
3125 		} else {
3126 			dsl_deadlist_space_range(&snap->ds_deadlist,
3127 			    0, dsl_dataset_phys(oldsnap)->ds_creation_txg,
3128 			    &used, &comp, &uncomp);
3129 		}
3130 		*usedp += used;
3131 		*compp += comp;
3132 		*uncompp += uncomp;
3133 
3134 		/*
3135 		 * If we get to the beginning of the chain of snapshots
3136 		 * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
3137 		 * was not a snapshot of/before new.
3138 		 */
3139 		snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3140 		if (snap != new)
3141 			dsl_dataset_rele(snap, FTAG);
3142 		if (snapobj == 0) {
3143 			err = SET_ERROR(EINVAL);
3144 			break;
3145 		}
3146 
3147 	}
3148 	return (err);
3149 }
3150 
3151 /*
3152  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
3153  * lastsnap, and all snapshots in between are deleted.
3154  *
3155  * blocks that would be freed            [---------------------------]
3156  * snapshots                       ---O-------O--------O-------O--------O
3157  *                                        firstsnap        lastsnap
3158  *
3159  * This is the set of blocks that were born after the snap before firstsnap,
3160  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
3161  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
3162  * We calculate this by iterating over the relevant deadlists (from the snap
3163  * after lastsnap, backward to the snap after firstsnap), summing up the
3164  * space on the deadlist that was born after the snap before firstsnap.
3165  */
3166 int
3167 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
3168     dsl_dataset_t *lastsnap,
3169     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3170 {
3171 	int err = 0;
3172 	uint64_t snapobj;
3173 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
3174 
3175 	ASSERT(firstsnap->ds_is_snapshot);
3176 	ASSERT(lastsnap->ds_is_snapshot);
3177 
3178 	/*
3179 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
3180 	 * is before lastsnap.
3181 	 */
3182 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
3183 	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
3184 	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
3185 		return (SET_ERROR(EINVAL));
3186 
3187 	*usedp = *compp = *uncompp = 0;
3188 
3189 	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
3190 	while (snapobj != firstsnap->ds_object) {
3191 		dsl_dataset_t *ds;
3192 		uint64_t used, comp, uncomp;
3193 
3194 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
3195 		if (err != 0)
3196 			break;
3197 
3198 		dsl_deadlist_space_range(&ds->ds_deadlist,
3199 		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
3200 		    &used, &comp, &uncomp);
3201 		*usedp += used;
3202 		*compp += comp;
3203 		*uncompp += uncomp;
3204 
3205 		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3206 		ASSERT3U(snapobj, !=, 0);
3207 		dsl_dataset_rele(ds, FTAG);
3208 	}
3209 	return (err);
3210 }
3211 
3212 static int
3213 dsl_dataset_activate_large_blocks_check(void *arg, dmu_tx_t *tx)
3214 {
3215 	const char *dsname = arg;
3216 	dsl_dataset_t *ds;
3217 	dsl_pool_t *dp = dmu_tx_pool(tx);
3218 	int error = 0;
3219 
3220 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
3221 		return (SET_ERROR(ENOTSUP));
3222 
3223 	ASSERT(spa_feature_is_enabled(dp->dp_spa,
3224 	    SPA_FEATURE_EXTENSIBLE_DATASET));
3225 
3226 	error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
3227 	if (error != 0)
3228 		return (error);
3229 
3230 	if (ds->ds_large_blocks)
3231 		error = EALREADY;
3232 	dsl_dataset_rele(ds, FTAG);
3233 
3234 	return (error);
3235 }
3236 
3237 void
3238 dsl_dataset_activate_large_blocks_sync_impl(uint64_t dsobj, dmu_tx_t *tx)
3239 {
3240 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
3241 	objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
3242 	uint64_t zero = 0;
3243 
3244 	spa_feature_incr(spa, SPA_FEATURE_LARGE_BLOCKS, tx);
3245 	dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
3246 
3247 	VERIFY0(zap_add(mos, dsobj, DS_FIELD_LARGE_BLOCKS,
3248 	    sizeof (zero), 1, &zero, tx));
3249 }
3250 
3251 static void
3252 dsl_dataset_activate_large_blocks_sync(void *arg, dmu_tx_t *tx)
3253 {
3254 	const char *dsname = arg;
3255 	dsl_dataset_t *ds;
3256 
3257 	VERIFY0(dsl_dataset_hold(dmu_tx_pool(tx), dsname, FTAG, &ds));
3258 
3259 	dsl_dataset_activate_large_blocks_sync_impl(ds->ds_object, tx);
3260 	ASSERT(!ds->ds_large_blocks);
3261 	ds->ds_large_blocks = B_TRUE;
3262 	dsl_dataset_rele(ds, FTAG);
3263 }
3264 
3265 int
3266 dsl_dataset_activate_large_blocks(const char *dsname)
3267 {
3268 	int error;
3269 
3270 	error = dsl_sync_task(dsname,
3271 	    dsl_dataset_activate_large_blocks_check,
3272 	    dsl_dataset_activate_large_blocks_sync, (void *)dsname,
3273 	    1, ZFS_SPACE_CHECK_RESERVED);
3274 
3275 	/*
3276 	 * EALREADY indicates that this dataset already supports large blocks.
3277 	 */
3278 	if (error == EALREADY)
3279 		error = 0;
3280 	return (error);
3281 }
3282 
3283 /*
3284  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
3285  * For example, they could both be snapshots of the same filesystem, and
3286  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
3287  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
3288  * filesystem.  Or 'earlier' could be the origin's origin.
3289  *
3290  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
3291  */
3292 boolean_t
3293 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
3294 	uint64_t earlier_txg)
3295 {
3296 	dsl_pool_t *dp = later->ds_dir->dd_pool;
3297 	int error;
3298 	boolean_t ret;
3299 
3300 	ASSERT(dsl_pool_config_held(dp));
3301 	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
3302 
3303 	if (earlier_txg == 0)
3304 		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
3305 
3306 	if (later->ds_is_snapshot &&
3307 	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
3308 		return (B_FALSE);
3309 
3310 	if (later->ds_dir == earlier->ds_dir)
3311 		return (B_TRUE);
3312 	if (!dsl_dir_is_clone(later->ds_dir))
3313 		return (B_FALSE);
3314 
3315 	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == earlier->ds_object)
3316 		return (B_TRUE);
3317 	dsl_dataset_t *origin;
3318 	error = dsl_dataset_hold_obj(dp,
3319 	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
3320 	if (error != 0)
3321 		return (B_FALSE);
3322 	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
3323 	dsl_dataset_rele(origin, FTAG);
3324 	return (ret);
3325 }
3326 
3327 
3328 void
3329 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
3330 {
3331 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3332 	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
3333 }
3334