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