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