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