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