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