xref: /titanic_41/usr/src/uts/common/fs/zfs/dsl_dataset.c (revision 2c2d21e98a95cba5687ec6574c974a5c6c4a6adb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012 by Delphix. All rights reserved.
24  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
25  */
26 
27 #include <sys/dmu_objset.h>
28 #include <sys/dsl_dataset.h>
29 #include <sys/dsl_dir.h>
30 #include <sys/dsl_prop.h>
31 #include <sys/dsl_synctask.h>
32 #include <sys/dmu_traverse.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/arc.h>
36 #include <sys/zio.h>
37 #include <sys/zap.h>
38 #include <sys/zfeature.h>
39 #include <sys/unique.h>
40 #include <sys/zfs_context.h>
41 #include <sys/zfs_ioctl.h>
42 #include <sys/spa.h>
43 #include <sys/zfs_znode.h>
44 #include <sys/zfs_onexit.h>
45 #include <sys/zvol.h>
46 #include <sys/dsl_scan.h>
47 #include <sys/dsl_deadlist.h>
48 
49 static char *dsl_reaper = "the grim reaper";
50 
51 static dsl_checkfunc_t dsl_dataset_destroy_begin_check;
52 static dsl_syncfunc_t dsl_dataset_destroy_begin_sync;
53 static dsl_syncfunc_t dsl_dataset_set_reservation_sync;
54 
55 #define	SWITCH64(x, y) \
56 	{ \
57 		uint64_t __tmp = (x); \
58 		(x) = (y); \
59 		(y) = __tmp; \
60 	}
61 
62 #define	DS_REF_MAX	(1ULL << 62)
63 
64 #define	DSL_DEADLIST_BLOCKSIZE	SPA_MAXBLOCKSIZE
65 
66 #define	DSL_DATASET_IS_DESTROYED(ds)	((ds)->ds_owner == dsl_reaper)
67 
68 
69 /*
70  * Figure out how much of this delta should be propogated to the dsl_dir
71  * layer.  If there's a refreservation, that space has already been
72  * partially accounted for in our ancestors.
73  */
74 static int64_t
75 parent_delta(dsl_dataset_t *ds, int64_t delta)
76 {
77 	uint64_t old_bytes, new_bytes;
78 
79 	if (ds->ds_reserved == 0)
80 		return (delta);
81 
82 	old_bytes = MAX(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
83 	new_bytes = MAX(ds->ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
84 
85 	ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
86 	return (new_bytes - old_bytes);
87 }
88 
89 void
90 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
91 {
92 	int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
93 	int compressed = BP_GET_PSIZE(bp);
94 	int uncompressed = BP_GET_UCSIZE(bp);
95 	int64_t delta;
96 
97 	dprintf_bp(bp, "ds=%p", ds);
98 
99 	ASSERT(dmu_tx_is_syncing(tx));
100 	/* It could have been compressed away to nothing */
101 	if (BP_IS_HOLE(bp))
102 		return;
103 	ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
104 	ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
105 	if (ds == NULL) {
106 		dsl_pool_mos_diduse_space(tx->tx_pool,
107 		    used, compressed, uncompressed);
108 		return;
109 	}
110 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
111 
112 	mutex_enter(&ds->ds_dir->dd_lock);
113 	mutex_enter(&ds->ds_lock);
114 	delta = parent_delta(ds, used);
115 	ds->ds_phys->ds_referenced_bytes += used;
116 	ds->ds_phys->ds_compressed_bytes += compressed;
117 	ds->ds_phys->ds_uncompressed_bytes += uncompressed;
118 	ds->ds_phys->ds_unique_bytes += used;
119 	mutex_exit(&ds->ds_lock);
120 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
121 	    compressed, uncompressed, tx);
122 	dsl_dir_transfer_space(ds->ds_dir, used - delta,
123 	    DD_USED_REFRSRV, DD_USED_HEAD, tx);
124 	mutex_exit(&ds->ds_dir->dd_lock);
125 }
126 
127 int
128 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
129     boolean_t async)
130 {
131 	if (BP_IS_HOLE(bp))
132 		return (0);
133 
134 	ASSERT(dmu_tx_is_syncing(tx));
135 	ASSERT(bp->blk_birth <= tx->tx_txg);
136 
137 	int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
138 	int compressed = BP_GET_PSIZE(bp);
139 	int uncompressed = BP_GET_UCSIZE(bp);
140 
141 	ASSERT(used > 0);
142 	if (ds == NULL) {
143 		dsl_free(tx->tx_pool, tx->tx_txg, bp);
144 		dsl_pool_mos_diduse_space(tx->tx_pool,
145 		    -used, -compressed, -uncompressed);
146 		return (used);
147 	}
148 	ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
149 
150 	ASSERT(!dsl_dataset_is_snapshot(ds));
151 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
152 
153 	if (bp->blk_birth > ds->ds_phys->ds_prev_snap_txg) {
154 		int64_t delta;
155 
156 		dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
157 		dsl_free(tx->tx_pool, tx->tx_txg, bp);
158 
159 		mutex_enter(&ds->ds_dir->dd_lock);
160 		mutex_enter(&ds->ds_lock);
161 		ASSERT(ds->ds_phys->ds_unique_bytes >= used ||
162 		    !DS_UNIQUE_IS_ACCURATE(ds));
163 		delta = parent_delta(ds, -used);
164 		ds->ds_phys->ds_unique_bytes -= used;
165 		mutex_exit(&ds->ds_lock);
166 		dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
167 		    delta, -compressed, -uncompressed, tx);
168 		dsl_dir_transfer_space(ds->ds_dir, -used - delta,
169 		    DD_USED_REFRSRV, DD_USED_HEAD, tx);
170 		mutex_exit(&ds->ds_dir->dd_lock);
171 	} else {
172 		dprintf_bp(bp, "putting on dead list: %s", "");
173 		if (async) {
174 			/*
175 			 * We are here as part of zio's write done callback,
176 			 * which means we're a zio interrupt thread.  We can't
177 			 * call dsl_deadlist_insert() now because it may block
178 			 * waiting for I/O.  Instead, put bp on the deferred
179 			 * queue and let dsl_pool_sync() finish the job.
180 			 */
181 			bplist_append(&ds->ds_pending_deadlist, bp);
182 		} else {
183 			dsl_deadlist_insert(&ds->ds_deadlist, bp, tx);
184 		}
185 		ASSERT3U(ds->ds_prev->ds_object, ==,
186 		    ds->ds_phys->ds_prev_snap_obj);
187 		ASSERT(ds->ds_prev->ds_phys->ds_num_children > 0);
188 		/* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
189 		if (ds->ds_prev->ds_phys->ds_next_snap_obj ==
190 		    ds->ds_object && bp->blk_birth >
191 		    ds->ds_prev->ds_phys->ds_prev_snap_txg) {
192 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
193 			mutex_enter(&ds->ds_prev->ds_lock);
194 			ds->ds_prev->ds_phys->ds_unique_bytes += used;
195 			mutex_exit(&ds->ds_prev->ds_lock);
196 		}
197 		if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
198 			dsl_dir_transfer_space(ds->ds_dir, used,
199 			    DD_USED_HEAD, DD_USED_SNAP, tx);
200 		}
201 	}
202 	mutex_enter(&ds->ds_lock);
203 	ASSERT3U(ds->ds_phys->ds_referenced_bytes, >=, used);
204 	ds->ds_phys->ds_referenced_bytes -= used;
205 	ASSERT3U(ds->ds_phys->ds_compressed_bytes, >=, compressed);
206 	ds->ds_phys->ds_compressed_bytes -= compressed;
207 	ASSERT3U(ds->ds_phys->ds_uncompressed_bytes, >=, uncompressed);
208 	ds->ds_phys->ds_uncompressed_bytes -= uncompressed;
209 	mutex_exit(&ds->ds_lock);
210 
211 	return (used);
212 }
213 
214 uint64_t
215 dsl_dataset_prev_snap_txg(dsl_dataset_t *ds)
216 {
217 	uint64_t trysnap = 0;
218 
219 	if (ds == NULL)
220 		return (0);
221 	/*
222 	 * The snapshot creation could fail, but that would cause an
223 	 * incorrect FALSE return, which would only result in an
224 	 * overestimation of the amount of space that an operation would
225 	 * consume, which is OK.
226 	 *
227 	 * There's also a small window where we could miss a pending
228 	 * snapshot, because we could set the sync task in the quiescing
229 	 * phase.  So this should only be used as a guess.
230 	 */
231 	if (ds->ds_trysnap_txg >
232 	    spa_last_synced_txg(ds->ds_dir->dd_pool->dp_spa))
233 		trysnap = ds->ds_trysnap_txg;
234 	return (MAX(ds->ds_phys->ds_prev_snap_txg, trysnap));
235 }
236 
237 boolean_t
238 dsl_dataset_block_freeable(dsl_dataset_t *ds, const blkptr_t *bp,
239     uint64_t blk_birth)
240 {
241 	if (blk_birth <= dsl_dataset_prev_snap_txg(ds))
242 		return (B_FALSE);
243 
244 	ddt_prefetch(dsl_dataset_get_spa(ds), bp);
245 
246 	return (B_TRUE);
247 }
248 
249 /* ARGSUSED */
250 static void
251 dsl_dataset_evict(dmu_buf_t *db, void *dsv)
252 {
253 	dsl_dataset_t *ds = dsv;
254 
255 	ASSERT(ds->ds_owner == NULL || DSL_DATASET_IS_DESTROYED(ds));
256 
257 	unique_remove(ds->ds_fsid_guid);
258 
259 	if (ds->ds_objset != NULL)
260 		dmu_objset_evict(ds->ds_objset);
261 
262 	if (ds->ds_prev) {
263 		dsl_dataset_drop_ref(ds->ds_prev, ds);
264 		ds->ds_prev = NULL;
265 	}
266 
267 	bplist_destroy(&ds->ds_pending_deadlist);
268 	if (db != NULL) {
269 		dsl_deadlist_close(&ds->ds_deadlist);
270 	} else {
271 		ASSERT(ds->ds_deadlist.dl_dbuf == NULL);
272 		ASSERT(!ds->ds_deadlist.dl_oldfmt);
273 	}
274 	if (ds->ds_dir)
275 		dsl_dir_close(ds->ds_dir, ds);
276 
277 	ASSERT(!list_link_active(&ds->ds_synced_link));
278 
279 	mutex_destroy(&ds->ds_lock);
280 	mutex_destroy(&ds->ds_recvlock);
281 	mutex_destroy(&ds->ds_opening_lock);
282 	rw_destroy(&ds->ds_rwlock);
283 	cv_destroy(&ds->ds_exclusive_cv);
284 
285 	kmem_free(ds, sizeof (dsl_dataset_t));
286 }
287 
288 static int
289 dsl_dataset_get_snapname(dsl_dataset_t *ds)
290 {
291 	dsl_dataset_phys_t *headphys;
292 	int err;
293 	dmu_buf_t *headdbuf;
294 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
295 	objset_t *mos = dp->dp_meta_objset;
296 
297 	if (ds->ds_snapname[0])
298 		return (0);
299 	if (ds->ds_phys->ds_next_snap_obj == 0)
300 		return (0);
301 
302 	err = dmu_bonus_hold(mos, ds->ds_dir->dd_phys->dd_head_dataset_obj,
303 	    FTAG, &headdbuf);
304 	if (err)
305 		return (err);
306 	headphys = headdbuf->db_data;
307 	err = zap_value_search(dp->dp_meta_objset,
308 	    headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
309 	dmu_buf_rele(headdbuf, FTAG);
310 	return (err);
311 }
312 
313 static int
314 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
315 {
316 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
317 	uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
318 	matchtype_t mt;
319 	int err;
320 
321 	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
322 		mt = MT_FIRST;
323 	else
324 		mt = MT_EXACT;
325 
326 	err = zap_lookup_norm(mos, snapobj, name, 8, 1,
327 	    value, mt, NULL, 0, NULL);
328 	if (err == ENOTSUP && mt == MT_FIRST)
329 		err = zap_lookup(mos, snapobj, name, 8, 1, value);
330 	return (err);
331 }
332 
333 static int
334 dsl_dataset_snap_remove(dsl_dataset_t *ds, char *name, dmu_tx_t *tx)
335 {
336 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
337 	uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
338 	matchtype_t mt;
339 	int err;
340 
341 	dsl_dir_snap_cmtime_update(ds->ds_dir);
342 
343 	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
344 		mt = MT_FIRST;
345 	else
346 		mt = MT_EXACT;
347 
348 	err = zap_remove_norm(mos, snapobj, name, mt, tx);
349 	if (err == ENOTSUP && mt == MT_FIRST)
350 		err = zap_remove(mos, snapobj, name, tx);
351 	return (err);
352 }
353 
354 static int
355 dsl_dataset_get_ref(dsl_pool_t *dp, uint64_t dsobj, void *tag,
356     dsl_dataset_t **dsp)
357 {
358 	objset_t *mos = dp->dp_meta_objset;
359 	dmu_buf_t *dbuf;
360 	dsl_dataset_t *ds;
361 	int err;
362 	dmu_object_info_t doi;
363 
364 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
365 	    dsl_pool_sync_context(dp));
366 
367 	err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
368 	if (err)
369 		return (err);
370 
371 	/* Make sure dsobj has the correct object type. */
372 	dmu_object_info_from_db(dbuf, &doi);
373 	if (doi.doi_type != DMU_OT_DSL_DATASET)
374 		return (EINVAL);
375 
376 	ds = dmu_buf_get_user(dbuf);
377 	if (ds == NULL) {
378 		dsl_dataset_t *winner;
379 
380 		ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
381 		ds->ds_dbuf = dbuf;
382 		ds->ds_object = dsobj;
383 		ds->ds_phys = dbuf->db_data;
384 
385 		mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
386 		mutex_init(&ds->ds_recvlock, NULL, MUTEX_DEFAULT, NULL);
387 		mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
388 		mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
389 
390 		rw_init(&ds->ds_rwlock, 0, 0, 0);
391 		cv_init(&ds->ds_exclusive_cv, NULL, CV_DEFAULT, NULL);
392 
393 		bplist_create(&ds->ds_pending_deadlist);
394 		dsl_deadlist_open(&ds->ds_deadlist,
395 		    mos, ds->ds_phys->ds_deadlist_obj);
396 
397 		list_create(&ds->ds_sendstreams, sizeof (dmu_sendarg_t),
398 		    offsetof(dmu_sendarg_t, dsa_link));
399 
400 		if (err == 0) {
401 			err = dsl_dir_open_obj(dp,
402 			    ds->ds_phys->ds_dir_obj, NULL, ds, &ds->ds_dir);
403 		}
404 		if (err) {
405 			mutex_destroy(&ds->ds_lock);
406 			mutex_destroy(&ds->ds_recvlock);
407 			mutex_destroy(&ds->ds_opening_lock);
408 			rw_destroy(&ds->ds_rwlock);
409 			cv_destroy(&ds->ds_exclusive_cv);
410 			bplist_destroy(&ds->ds_pending_deadlist);
411 			dsl_deadlist_close(&ds->ds_deadlist);
412 			kmem_free(ds, sizeof (dsl_dataset_t));
413 			dmu_buf_rele(dbuf, tag);
414 			return (err);
415 		}
416 
417 		if (!dsl_dataset_is_snapshot(ds)) {
418 			ds->ds_snapname[0] = '\0';
419 			if (ds->ds_phys->ds_prev_snap_obj) {
420 				err = dsl_dataset_get_ref(dp,
421 				    ds->ds_phys->ds_prev_snap_obj,
422 				    ds, &ds->ds_prev);
423 			}
424 		} else {
425 			if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
426 				err = dsl_dataset_get_snapname(ds);
427 			if (err == 0 && ds->ds_phys->ds_userrefs_obj != 0) {
428 				err = zap_count(
429 				    ds->ds_dir->dd_pool->dp_meta_objset,
430 				    ds->ds_phys->ds_userrefs_obj,
431 				    &ds->ds_userrefs);
432 			}
433 		}
434 
435 		if (err == 0 && !dsl_dataset_is_snapshot(ds)) {
436 			/*
437 			 * In sync context, we're called with either no lock
438 			 * or with the write lock.  If we're not syncing,
439 			 * we're always called with the read lock held.
440 			 */
441 			boolean_t need_lock =
442 			    !RW_WRITE_HELD(&dp->dp_config_rwlock) &&
443 			    dsl_pool_sync_context(dp);
444 
445 			if (need_lock)
446 				rw_enter(&dp->dp_config_rwlock, RW_READER);
447 
448 			err = dsl_prop_get_ds(ds,
449 			    "refreservation", sizeof (uint64_t), 1,
450 			    &ds->ds_reserved, NULL);
451 			if (err == 0) {
452 				err = dsl_prop_get_ds(ds,
453 				    "refquota", sizeof (uint64_t), 1,
454 				    &ds->ds_quota, NULL);
455 			}
456 
457 			if (need_lock)
458 				rw_exit(&dp->dp_config_rwlock);
459 		} else {
460 			ds->ds_reserved = ds->ds_quota = 0;
461 		}
462 
463 		if (err == 0) {
464 			winner = dmu_buf_set_user_ie(dbuf, ds, &ds->ds_phys,
465 			    dsl_dataset_evict);
466 		}
467 		if (err || winner) {
468 			bplist_destroy(&ds->ds_pending_deadlist);
469 			dsl_deadlist_close(&ds->ds_deadlist);
470 			if (ds->ds_prev)
471 				dsl_dataset_drop_ref(ds->ds_prev, ds);
472 			dsl_dir_close(ds->ds_dir, ds);
473 			mutex_destroy(&ds->ds_lock);
474 			mutex_destroy(&ds->ds_recvlock);
475 			mutex_destroy(&ds->ds_opening_lock);
476 			rw_destroy(&ds->ds_rwlock);
477 			cv_destroy(&ds->ds_exclusive_cv);
478 			kmem_free(ds, sizeof (dsl_dataset_t));
479 			if (err) {
480 				dmu_buf_rele(dbuf, tag);
481 				return (err);
482 			}
483 			ds = winner;
484 		} else {
485 			ds->ds_fsid_guid =
486 			    unique_insert(ds->ds_phys->ds_fsid_guid);
487 		}
488 	}
489 	ASSERT3P(ds->ds_dbuf, ==, dbuf);
490 	ASSERT3P(ds->ds_phys, ==, dbuf->db_data);
491 	ASSERT(ds->ds_phys->ds_prev_snap_obj != 0 ||
492 	    spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
493 	    dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
494 	mutex_enter(&ds->ds_lock);
495 	if (!dsl_pool_sync_context(dp) && DSL_DATASET_IS_DESTROYED(ds)) {
496 		mutex_exit(&ds->ds_lock);
497 		dmu_buf_rele(ds->ds_dbuf, tag);
498 		return (ENOENT);
499 	}
500 	mutex_exit(&ds->ds_lock);
501 	*dsp = ds;
502 	return (0);
503 }
504 
505 static int
506 dsl_dataset_hold_ref(dsl_dataset_t *ds, void *tag)
507 {
508 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
509 
510 	/*
511 	 * In syncing context we don't want the rwlock lock: there
512 	 * may be an existing writer waiting for sync phase to
513 	 * finish.  We don't need to worry about such writers, since
514 	 * sync phase is single-threaded, so the writer can't be
515 	 * doing anything while we are active.
516 	 */
517 	if (dsl_pool_sync_context(dp)) {
518 		ASSERT(!DSL_DATASET_IS_DESTROYED(ds));
519 		return (0);
520 	}
521 
522 	/*
523 	 * Normal users will hold the ds_rwlock as a READER until they
524 	 * are finished (i.e., call dsl_dataset_rele()).  "Owners" will
525 	 * drop their READER lock after they set the ds_owner field.
526 	 *
527 	 * If the dataset is being destroyed, the destroy thread will
528 	 * obtain a WRITER lock for exclusive access after it's done its
529 	 * open-context work and then change the ds_owner to
530 	 * dsl_reaper once destruction is assured.  So threads
531 	 * may block here temporarily, until the "destructability" of
532 	 * the dataset is determined.
533 	 */
534 	ASSERT(!RW_WRITE_HELD(&dp->dp_config_rwlock));
535 	mutex_enter(&ds->ds_lock);
536 	while (!rw_tryenter(&ds->ds_rwlock, RW_READER)) {
537 		rw_exit(&dp->dp_config_rwlock);
538 		cv_wait(&ds->ds_exclusive_cv, &ds->ds_lock);
539 		if (DSL_DATASET_IS_DESTROYED(ds)) {
540 			mutex_exit(&ds->ds_lock);
541 			dsl_dataset_drop_ref(ds, tag);
542 			rw_enter(&dp->dp_config_rwlock, RW_READER);
543 			return (ENOENT);
544 		}
545 		/*
546 		 * The dp_config_rwlock lives above the ds_lock. And
547 		 * we need to check DSL_DATASET_IS_DESTROYED() while
548 		 * holding the ds_lock, so we have to drop and reacquire
549 		 * the ds_lock here.
550 		 */
551 		mutex_exit(&ds->ds_lock);
552 		rw_enter(&dp->dp_config_rwlock, RW_READER);
553 		mutex_enter(&ds->ds_lock);
554 	}
555 	mutex_exit(&ds->ds_lock);
556 	return (0);
557 }
558 
559 int
560 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
561     dsl_dataset_t **dsp)
562 {
563 	int err = dsl_dataset_get_ref(dp, dsobj, tag, dsp);
564 
565 	if (err)
566 		return (err);
567 	return (dsl_dataset_hold_ref(*dsp, tag));
568 }
569 
570 int
571 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj, boolean_t inconsistentok,
572     void *tag, dsl_dataset_t **dsp)
573 {
574 	int err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
575 	if (err)
576 		return (err);
577 	if (!dsl_dataset_tryown(*dsp, inconsistentok, tag)) {
578 		dsl_dataset_rele(*dsp, tag);
579 		*dsp = NULL;
580 		return (EBUSY);
581 	}
582 	return (0);
583 }
584 
585 int
586 dsl_dataset_hold(const char *name, void *tag, dsl_dataset_t **dsp)
587 {
588 	dsl_dir_t *dd;
589 	dsl_pool_t *dp;
590 	const char *snapname;
591 	uint64_t obj;
592 	int err = 0;
593 
594 	err = dsl_dir_open_spa(NULL, name, FTAG, &dd, &snapname);
595 	if (err)
596 		return (err);
597 
598 	dp = dd->dd_pool;
599 	obj = dd->dd_phys->dd_head_dataset_obj;
600 	rw_enter(&dp->dp_config_rwlock, RW_READER);
601 	if (obj)
602 		err = dsl_dataset_get_ref(dp, obj, tag, dsp);
603 	else
604 		err = ENOENT;
605 	if (err)
606 		goto out;
607 
608 	err = dsl_dataset_hold_ref(*dsp, tag);
609 
610 	/* we may be looking for a snapshot */
611 	if (err == 0 && snapname != NULL) {
612 		dsl_dataset_t *ds = NULL;
613 
614 		if (*snapname++ != '@') {
615 			dsl_dataset_rele(*dsp, tag);
616 			err = ENOENT;
617 			goto out;
618 		}
619 
620 		dprintf("looking for snapshot '%s'\n", snapname);
621 		err = dsl_dataset_snap_lookup(*dsp, snapname, &obj);
622 		if (err == 0)
623 			err = dsl_dataset_get_ref(dp, obj, tag, &ds);
624 		dsl_dataset_rele(*dsp, tag);
625 
626 		ASSERT3U((err == 0), ==, (ds != NULL));
627 
628 		if (ds) {
629 			mutex_enter(&ds->ds_lock);
630 			if (ds->ds_snapname[0] == 0)
631 				(void) strlcpy(ds->ds_snapname, snapname,
632 				    sizeof (ds->ds_snapname));
633 			mutex_exit(&ds->ds_lock);
634 			err = dsl_dataset_hold_ref(ds, tag);
635 			*dsp = err ? NULL : ds;
636 		}
637 	}
638 out:
639 	rw_exit(&dp->dp_config_rwlock);
640 	dsl_dir_close(dd, FTAG);
641 	return (err);
642 }
643 
644 int
645 dsl_dataset_own(const char *name, boolean_t inconsistentok,
646     void *tag, dsl_dataset_t **dsp)
647 {
648 	int err = dsl_dataset_hold(name, tag, dsp);
649 	if (err)
650 		return (err);
651 	if (!dsl_dataset_tryown(*dsp, inconsistentok, tag)) {
652 		dsl_dataset_rele(*dsp, tag);
653 		return (EBUSY);
654 	}
655 	return (0);
656 }
657 
658 void
659 dsl_dataset_name(dsl_dataset_t *ds, char *name)
660 {
661 	if (ds == NULL) {
662 		(void) strcpy(name, "mos");
663 	} else {
664 		dsl_dir_name(ds->ds_dir, name);
665 		VERIFY(0 == dsl_dataset_get_snapname(ds));
666 		if (ds->ds_snapname[0]) {
667 			(void) strcat(name, "@");
668 			/*
669 			 * We use a "recursive" mutex so that we
670 			 * can call dprintf_ds() with ds_lock held.
671 			 */
672 			if (!MUTEX_HELD(&ds->ds_lock)) {
673 				mutex_enter(&ds->ds_lock);
674 				(void) strcat(name, ds->ds_snapname);
675 				mutex_exit(&ds->ds_lock);
676 			} else {
677 				(void) strcat(name, ds->ds_snapname);
678 			}
679 		}
680 	}
681 }
682 
683 static int
684 dsl_dataset_namelen(dsl_dataset_t *ds)
685 {
686 	int result;
687 
688 	if (ds == NULL) {
689 		result = 3;	/* "mos" */
690 	} else {
691 		result = dsl_dir_namelen(ds->ds_dir);
692 		VERIFY(0 == dsl_dataset_get_snapname(ds));
693 		if (ds->ds_snapname[0]) {
694 			++result;	/* adding one for the @-sign */
695 			if (!MUTEX_HELD(&ds->ds_lock)) {
696 				mutex_enter(&ds->ds_lock);
697 				result += strlen(ds->ds_snapname);
698 				mutex_exit(&ds->ds_lock);
699 			} else {
700 				result += strlen(ds->ds_snapname);
701 			}
702 		}
703 	}
704 
705 	return (result);
706 }
707 
708 void
709 dsl_dataset_drop_ref(dsl_dataset_t *ds, void *tag)
710 {
711 	dmu_buf_rele(ds->ds_dbuf, tag);
712 }
713 
714 void
715 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
716 {
717 	if (!dsl_pool_sync_context(ds->ds_dir->dd_pool)) {
718 		rw_exit(&ds->ds_rwlock);
719 	}
720 	dsl_dataset_drop_ref(ds, tag);
721 }
722 
723 void
724 dsl_dataset_disown(dsl_dataset_t *ds, void *tag)
725 {
726 	ASSERT((ds->ds_owner == tag && ds->ds_dbuf) ||
727 	    (DSL_DATASET_IS_DESTROYED(ds) && ds->ds_dbuf == NULL));
728 
729 	mutex_enter(&ds->ds_lock);
730 	ds->ds_owner = NULL;
731 	if (RW_WRITE_HELD(&ds->ds_rwlock)) {
732 		rw_exit(&ds->ds_rwlock);
733 		cv_broadcast(&ds->ds_exclusive_cv);
734 	}
735 	mutex_exit(&ds->ds_lock);
736 	if (ds->ds_dbuf)
737 		dsl_dataset_drop_ref(ds, tag);
738 	else
739 		dsl_dataset_evict(NULL, ds);
740 }
741 
742 boolean_t
743 dsl_dataset_tryown(dsl_dataset_t *ds, boolean_t inconsistentok, void *tag)
744 {
745 	boolean_t gotit = FALSE;
746 
747 	mutex_enter(&ds->ds_lock);
748 	if (ds->ds_owner == NULL &&
749 	    (!DS_IS_INCONSISTENT(ds) || inconsistentok)) {
750 		ds->ds_owner = tag;
751 		if (!dsl_pool_sync_context(ds->ds_dir->dd_pool))
752 			rw_exit(&ds->ds_rwlock);
753 		gotit = TRUE;
754 	}
755 	mutex_exit(&ds->ds_lock);
756 	return (gotit);
757 }
758 
759 void
760 dsl_dataset_make_exclusive(dsl_dataset_t *ds, void *owner)
761 {
762 	ASSERT3P(owner, ==, ds->ds_owner);
763 	if (!RW_WRITE_HELD(&ds->ds_rwlock))
764 		rw_enter(&ds->ds_rwlock, RW_WRITER);
765 }
766 
767 uint64_t
768 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
769     uint64_t flags, dmu_tx_t *tx)
770 {
771 	dsl_pool_t *dp = dd->dd_pool;
772 	dmu_buf_t *dbuf;
773 	dsl_dataset_phys_t *dsphys;
774 	uint64_t dsobj;
775 	objset_t *mos = dp->dp_meta_objset;
776 
777 	if (origin == NULL)
778 		origin = dp->dp_origin_snap;
779 
780 	ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
781 	ASSERT(origin == NULL || origin->ds_phys->ds_num_children > 0);
782 	ASSERT(dmu_tx_is_syncing(tx));
783 	ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
784 
785 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
786 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
787 	VERIFY(0 == dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
788 	dmu_buf_will_dirty(dbuf, tx);
789 	dsphys = dbuf->db_data;
790 	bzero(dsphys, sizeof (dsl_dataset_phys_t));
791 	dsphys->ds_dir_obj = dd->dd_object;
792 	dsphys->ds_flags = flags;
793 	dsphys->ds_fsid_guid = unique_create();
794 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
795 	    sizeof (dsphys->ds_guid));
796 	dsphys->ds_snapnames_zapobj =
797 	    zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
798 	    DMU_OT_NONE, 0, tx);
799 	dsphys->ds_creation_time = gethrestime_sec();
800 	dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
801 
802 	if (origin == NULL) {
803 		dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
804 	} else {
805 		dsl_dataset_t *ohds;
806 
807 		dsphys->ds_prev_snap_obj = origin->ds_object;
808 		dsphys->ds_prev_snap_txg =
809 		    origin->ds_phys->ds_creation_txg;
810 		dsphys->ds_referenced_bytes =
811 		    origin->ds_phys->ds_referenced_bytes;
812 		dsphys->ds_compressed_bytes =
813 		    origin->ds_phys->ds_compressed_bytes;
814 		dsphys->ds_uncompressed_bytes =
815 		    origin->ds_phys->ds_uncompressed_bytes;
816 		dsphys->ds_bp = origin->ds_phys->ds_bp;
817 		dsphys->ds_flags |= origin->ds_phys->ds_flags;
818 
819 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
820 		origin->ds_phys->ds_num_children++;
821 
822 		VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
823 		    origin->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ohds));
824 		dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
825 		    dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
826 		dsl_dataset_rele(ohds, FTAG);
827 
828 		if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
829 			if (origin->ds_phys->ds_next_clones_obj == 0) {
830 				origin->ds_phys->ds_next_clones_obj =
831 				    zap_create(mos,
832 				    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
833 			}
834 			VERIFY(0 == zap_add_int(mos,
835 			    origin->ds_phys->ds_next_clones_obj,
836 			    dsobj, tx));
837 		}
838 
839 		dmu_buf_will_dirty(dd->dd_dbuf, tx);
840 		dd->dd_phys->dd_origin_obj = origin->ds_object;
841 		if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
842 			if (origin->ds_dir->dd_phys->dd_clones == 0) {
843 				dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
844 				origin->ds_dir->dd_phys->dd_clones =
845 				    zap_create(mos,
846 				    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
847 			}
848 			VERIFY3U(0, ==, zap_add_int(mos,
849 			    origin->ds_dir->dd_phys->dd_clones, dsobj, tx));
850 		}
851 	}
852 
853 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
854 		dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
855 
856 	dmu_buf_rele(dbuf, FTAG);
857 
858 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
859 	dd->dd_phys->dd_head_dataset_obj = dsobj;
860 
861 	return (dsobj);
862 }
863 
864 uint64_t
865 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
866     dsl_dataset_t *origin, uint64_t flags, cred_t *cr, dmu_tx_t *tx)
867 {
868 	dsl_pool_t *dp = pdd->dd_pool;
869 	uint64_t dsobj, ddobj;
870 	dsl_dir_t *dd;
871 
872 	ASSERT(lastname[0] != '@');
873 
874 	ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
875 	VERIFY(0 == dsl_dir_open_obj(dp, ddobj, lastname, FTAG, &dd));
876 
877 	dsobj = dsl_dataset_create_sync_dd(dd, origin, flags, tx);
878 
879 	dsl_deleg_set_create_perms(dd, tx, cr);
880 
881 	dsl_dir_close(dd, FTAG);
882 
883 	/*
884 	 * If we are creating a clone, make sure we zero out any stale
885 	 * data from the origin snapshots zil header.
886 	 */
887 	if (origin != NULL) {
888 		dsl_dataset_t *ds;
889 		objset_t *os;
890 
891 		VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
892 		VERIFY3U(0, ==, dmu_objset_from_ds(ds, &os));
893 		bzero(&os->os_zil_header, sizeof (os->os_zil_header));
894 		dsl_dataset_dirty(ds, tx);
895 		dsl_dataset_rele(ds, FTAG);
896 	}
897 
898 	return (dsobj);
899 }
900 
901 /*
902  * The snapshots must all be in the same pool.
903  */
904 int
905 dmu_snapshots_destroy_nvl(nvlist_t *snaps, boolean_t defer,
906     nvlist_t *errlist)
907 {
908 	int err;
909 	dsl_sync_task_t *dst;
910 	spa_t *spa;
911 	nvpair_t *pair;
912 	dsl_sync_task_group_t *dstg;
913 
914 	pair = nvlist_next_nvpair(snaps, NULL);
915 	if (pair == NULL)
916 		return (0);
917 
918 	err = spa_open(nvpair_name(pair), &spa, FTAG);
919 	if (err)
920 		return (err);
921 	dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
922 
923 	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
924 	    pair = nvlist_next_nvpair(snaps, pair)) {
925 		dsl_dataset_t *ds;
926 
927 		err = dsl_dataset_own(nvpair_name(pair), B_TRUE, dstg, &ds);
928 		if (err == 0) {
929 			struct dsl_ds_destroyarg *dsda;
930 
931 			dsl_dataset_make_exclusive(ds, dstg);
932 			dsda = kmem_zalloc(sizeof (struct dsl_ds_destroyarg),
933 			    KM_SLEEP);
934 			dsda->ds = ds;
935 			dsda->defer = defer;
936 			dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
937 			    dsl_dataset_destroy_sync, dsda, dstg, 0);
938 		} else if (err == ENOENT) {
939 			err = 0;
940 		} else {
941 			fnvlist_add_int32(errlist, nvpair_name(pair), err);
942 			break;
943 		}
944 	}
945 
946 	if (err == 0)
947 		err = dsl_sync_task_group_wait(dstg);
948 
949 	for (dst = list_head(&dstg->dstg_tasks); dst;
950 	    dst = list_next(&dstg->dstg_tasks, dst)) {
951 		struct dsl_ds_destroyarg *dsda = dst->dst_arg1;
952 		dsl_dataset_t *ds = dsda->ds;
953 
954 		/*
955 		 * Return the snapshots that triggered the error.
956 		 */
957 		if (dst->dst_err != 0) {
958 			char name[ZFS_MAXNAMELEN];
959 			dsl_dataset_name(ds, name);
960 			fnvlist_add_int32(errlist, name, dst->dst_err);
961 		}
962 		ASSERT3P(dsda->rm_origin, ==, NULL);
963 		dsl_dataset_disown(ds, dstg);
964 		kmem_free(dsda, sizeof (struct dsl_ds_destroyarg));
965 	}
966 
967 	dsl_sync_task_group_destroy(dstg);
968 	spa_close(spa, FTAG);
969 	return (err);
970 
971 }
972 
973 static boolean_t
974 dsl_dataset_might_destroy_origin(dsl_dataset_t *ds)
975 {
976 	boolean_t might_destroy = B_FALSE;
977 
978 	mutex_enter(&ds->ds_lock);
979 	if (ds->ds_phys->ds_num_children == 2 && ds->ds_userrefs == 0 &&
980 	    DS_IS_DEFER_DESTROY(ds))
981 		might_destroy = B_TRUE;
982 	mutex_exit(&ds->ds_lock);
983 
984 	return (might_destroy);
985 }
986 
987 /*
988  * If we're removing a clone, and these three conditions are true:
989  *	1) the clone's origin has no other children
990  *	2) the clone's origin has no user references
991  *	3) the clone's origin has been marked for deferred destruction
992  * Then, prepare to remove the origin as part of this sync task group.
993  */
994 static int
995 dsl_dataset_origin_rm_prep(struct dsl_ds_destroyarg *dsda, void *tag)
996 {
997 	dsl_dataset_t *ds = dsda->ds;
998 	dsl_dataset_t *origin = ds->ds_prev;
999 
1000 	if (dsl_dataset_might_destroy_origin(origin)) {
1001 		char *name;
1002 		int namelen;
1003 		int error;
1004 
1005 		namelen = dsl_dataset_namelen(origin) + 1;
1006 		name = kmem_alloc(namelen, KM_SLEEP);
1007 		dsl_dataset_name(origin, name);
1008 #ifdef _KERNEL
1009 		error = zfs_unmount_snap(name, NULL);
1010 		if (error) {
1011 			kmem_free(name, namelen);
1012 			return (error);
1013 		}
1014 #endif
1015 		error = dsl_dataset_own(name, B_TRUE, tag, &origin);
1016 		kmem_free(name, namelen);
1017 		if (error)
1018 			return (error);
1019 		dsda->rm_origin = origin;
1020 		dsl_dataset_make_exclusive(origin, tag);
1021 	}
1022 
1023 	return (0);
1024 }
1025 
1026 /*
1027  * ds must be opened as OWNER.  On return (whether successful or not),
1028  * ds will be closed and caller can no longer dereference it.
1029  */
1030 int
1031 dsl_dataset_destroy(dsl_dataset_t *ds, void *tag, boolean_t defer)
1032 {
1033 	int err;
1034 	dsl_sync_task_group_t *dstg;
1035 	objset_t *os;
1036 	dsl_dir_t *dd;
1037 	uint64_t obj;
1038 	struct dsl_ds_destroyarg dsda = { 0 };
1039 
1040 	dsda.ds = ds;
1041 
1042 	if (dsl_dataset_is_snapshot(ds)) {
1043 		/* Destroying a snapshot is simpler */
1044 		dsl_dataset_make_exclusive(ds, tag);
1045 
1046 		dsda.defer = defer;
1047 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1048 		    dsl_dataset_destroy_check, dsl_dataset_destroy_sync,
1049 		    &dsda, tag, 0);
1050 		ASSERT3P(dsda.rm_origin, ==, NULL);
1051 		goto out;
1052 	} else if (defer) {
1053 		err = EINVAL;
1054 		goto out;
1055 	}
1056 
1057 	dd = ds->ds_dir;
1058 
1059 	if (!spa_feature_is_enabled(dsl_dataset_get_spa(ds),
1060 	    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
1061 		/*
1062 		 * Check for errors and mark this ds as inconsistent, in
1063 		 * case we crash while freeing the objects.
1064 		 */
1065 		err = dsl_sync_task_do(dd->dd_pool,
1066 		    dsl_dataset_destroy_begin_check,
1067 		    dsl_dataset_destroy_begin_sync, ds, NULL, 0);
1068 		if (err)
1069 			goto out;
1070 
1071 		err = dmu_objset_from_ds(ds, &os);
1072 		if (err)
1073 			goto out;
1074 
1075 		/*
1076 		 * Remove all objects while in the open context so that
1077 		 * there is less work to do in the syncing context.
1078 		 */
1079 		for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE,
1080 		    ds->ds_phys->ds_prev_snap_txg)) {
1081 			/*
1082 			 * Ignore errors, if there is not enough disk space
1083 			 * we will deal with it in dsl_dataset_destroy_sync().
1084 			 */
1085 			(void) dmu_free_object(os, obj);
1086 		}
1087 		if (err != ESRCH)
1088 			goto out;
1089 
1090 		/*
1091 		 * Sync out all in-flight IO.
1092 		 */
1093 		txg_wait_synced(dd->dd_pool, 0);
1094 
1095 		/*
1096 		 * If we managed to free all the objects in open
1097 		 * context, the user space accounting should be zero.
1098 		 */
1099 		if (ds->ds_phys->ds_bp.blk_fill == 0 &&
1100 		    dmu_objset_userused_enabled(os)) {
1101 			uint64_t count;
1102 
1103 			ASSERT(zap_count(os, DMU_USERUSED_OBJECT,
1104 			    &count) != 0 || count == 0);
1105 			ASSERT(zap_count(os, DMU_GROUPUSED_OBJECT,
1106 			    &count) != 0 || count == 0);
1107 		}
1108 	}
1109 
1110 	rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
1111 	err = dsl_dir_open_obj(dd->dd_pool, dd->dd_object, NULL, FTAG, &dd);
1112 	rw_exit(&dd->dd_pool->dp_config_rwlock);
1113 
1114 	if (err)
1115 		goto out;
1116 
1117 	/*
1118 	 * Blow away the dsl_dir + head dataset.
1119 	 */
1120 	dsl_dataset_make_exclusive(ds, tag);
1121 	/*
1122 	 * If we're removing a clone, we might also need to remove its
1123 	 * origin.
1124 	 */
1125 	do {
1126 		dsda.need_prep = B_FALSE;
1127 		if (dsl_dir_is_clone(dd)) {
1128 			err = dsl_dataset_origin_rm_prep(&dsda, tag);
1129 			if (err) {
1130 				dsl_dir_close(dd, FTAG);
1131 				goto out;
1132 			}
1133 		}
1134 
1135 		dstg = dsl_sync_task_group_create(ds->ds_dir->dd_pool);
1136 		dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
1137 		    dsl_dataset_destroy_sync, &dsda, tag, 0);
1138 		dsl_sync_task_create(dstg, dsl_dir_destroy_check,
1139 		    dsl_dir_destroy_sync, dd, FTAG, 0);
1140 		err = dsl_sync_task_group_wait(dstg);
1141 		dsl_sync_task_group_destroy(dstg);
1142 
1143 		/*
1144 		 * We could be racing against 'zfs release' or 'zfs destroy -d'
1145 		 * on the origin snap, in which case we can get EBUSY if we
1146 		 * needed to destroy the origin snap but were not ready to
1147 		 * do so.
1148 		 */
1149 		if (dsda.need_prep) {
1150 			ASSERT(err == EBUSY);
1151 			ASSERT(dsl_dir_is_clone(dd));
1152 			ASSERT(dsda.rm_origin == NULL);
1153 		}
1154 	} while (dsda.need_prep);
1155 
1156 	if (dsda.rm_origin != NULL)
1157 		dsl_dataset_disown(dsda.rm_origin, tag);
1158 
1159 	/* if it is successful, dsl_dir_destroy_sync will close the dd */
1160 	if (err)
1161 		dsl_dir_close(dd, FTAG);
1162 out:
1163 	dsl_dataset_disown(ds, tag);
1164 	return (err);
1165 }
1166 
1167 blkptr_t *
1168 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1169 {
1170 	return (&ds->ds_phys->ds_bp);
1171 }
1172 
1173 void
1174 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
1175 {
1176 	ASSERT(dmu_tx_is_syncing(tx));
1177 	/* If it's the meta-objset, set dp_meta_rootbp */
1178 	if (ds == NULL) {
1179 		tx->tx_pool->dp_meta_rootbp = *bp;
1180 	} else {
1181 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1182 		ds->ds_phys->ds_bp = *bp;
1183 	}
1184 }
1185 
1186 spa_t *
1187 dsl_dataset_get_spa(dsl_dataset_t *ds)
1188 {
1189 	return (ds->ds_dir->dd_pool->dp_spa);
1190 }
1191 
1192 void
1193 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1194 {
1195 	dsl_pool_t *dp;
1196 
1197 	if (ds == NULL) /* this is the meta-objset */
1198 		return;
1199 
1200 	ASSERT(ds->ds_objset != NULL);
1201 
1202 	if (ds->ds_phys->ds_next_snap_obj != 0)
1203 		panic("dirtying snapshot!");
1204 
1205 	dp = ds->ds_dir->dd_pool;
1206 
1207 	if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg) == 0) {
1208 		/* up the hold count until we can be written out */
1209 		dmu_buf_add_ref(ds->ds_dbuf, ds);
1210 	}
1211 }
1212 
1213 /*
1214  * The unique space in the head dataset can be calculated by subtracting
1215  * the space used in the most recent snapshot, that is still being used
1216  * in this file system, from the space currently in use.  To figure out
1217  * the space in the most recent snapshot still in use, we need to take
1218  * the total space used in the snapshot and subtract out the space that
1219  * has been freed up since the snapshot was taken.
1220  */
1221 static void
1222 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1223 {
1224 	uint64_t mrs_used;
1225 	uint64_t dlused, dlcomp, dluncomp;
1226 
1227 	ASSERT(!dsl_dataset_is_snapshot(ds));
1228 
1229 	if (ds->ds_phys->ds_prev_snap_obj != 0)
1230 		mrs_used = ds->ds_prev->ds_phys->ds_referenced_bytes;
1231 	else
1232 		mrs_used = 0;
1233 
1234 	dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
1235 
1236 	ASSERT3U(dlused, <=, mrs_used);
1237 	ds->ds_phys->ds_unique_bytes =
1238 	    ds->ds_phys->ds_referenced_bytes - (mrs_used - dlused);
1239 
1240 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1241 	    SPA_VERSION_UNIQUE_ACCURATE)
1242 		ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1243 }
1244 
1245 struct killarg {
1246 	dsl_dataset_t *ds;
1247 	dmu_tx_t *tx;
1248 };
1249 
1250 /* ARGSUSED */
1251 static int
1252 kill_blkptr(spa_t *spa, zilog_t *zilog, const blkptr_t *bp, arc_buf_t *pbuf,
1253     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1254 {
1255 	struct killarg *ka = arg;
1256 	dmu_tx_t *tx = ka->tx;
1257 
1258 	if (bp == NULL)
1259 		return (0);
1260 
1261 	if (zb->zb_level == ZB_ZIL_LEVEL) {
1262 		ASSERT(zilog != NULL);
1263 		/*
1264 		 * It's a block in the intent log.  It has no
1265 		 * accounting, so just free it.
1266 		 */
1267 		dsl_free(ka->tx->tx_pool, ka->tx->tx_txg, bp);
1268 	} else {
1269 		ASSERT(zilog == NULL);
1270 		ASSERT3U(bp->blk_birth, >, ka->ds->ds_phys->ds_prev_snap_txg);
1271 		(void) dsl_dataset_block_kill(ka->ds, bp, tx, B_FALSE);
1272 	}
1273 
1274 	return (0);
1275 }
1276 
1277 /* ARGSUSED */
1278 static int
1279 dsl_dataset_destroy_begin_check(void *arg1, void *arg2, dmu_tx_t *tx)
1280 {
1281 	dsl_dataset_t *ds = arg1;
1282 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1283 	uint64_t count;
1284 	int err;
1285 
1286 	/*
1287 	 * Can't delete a head dataset if there are snapshots of it.
1288 	 * (Except if the only snapshots are from the branch we cloned
1289 	 * from.)
1290 	 */
1291 	if (ds->ds_prev != NULL &&
1292 	    ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1293 		return (EBUSY);
1294 
1295 	/*
1296 	 * This is really a dsl_dir thing, but check it here so that
1297 	 * we'll be less likely to leave this dataset inconsistent &
1298 	 * nearly destroyed.
1299 	 */
1300 	err = zap_count(mos, ds->ds_dir->dd_phys->dd_child_dir_zapobj, &count);
1301 	if (err)
1302 		return (err);
1303 	if (count != 0)
1304 		return (EEXIST);
1305 
1306 	return (0);
1307 }
1308 
1309 /* ARGSUSED */
1310 static void
1311 dsl_dataset_destroy_begin_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1312 {
1313 	dsl_dataset_t *ds = arg1;
1314 
1315 	/* Mark it as inconsistent on-disk, in case we crash */
1316 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1317 	ds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;
1318 
1319 	spa_history_log_internal_ds(ds, "destroy begin", tx, "");
1320 }
1321 
1322 static int
1323 dsl_dataset_origin_check(struct dsl_ds_destroyarg *dsda, void *tag,
1324     dmu_tx_t *tx)
1325 {
1326 	dsl_dataset_t *ds = dsda->ds;
1327 	dsl_dataset_t *ds_prev = ds->ds_prev;
1328 
1329 	if (dsl_dataset_might_destroy_origin(ds_prev)) {
1330 		struct dsl_ds_destroyarg ndsda = {0};
1331 
1332 		/*
1333 		 * If we're not prepared to remove the origin, don't remove
1334 		 * the clone either.
1335 		 */
1336 		if (dsda->rm_origin == NULL) {
1337 			dsda->need_prep = B_TRUE;
1338 			return (EBUSY);
1339 		}
1340 
1341 		ndsda.ds = ds_prev;
1342 		ndsda.is_origin_rm = B_TRUE;
1343 		return (dsl_dataset_destroy_check(&ndsda, tag, tx));
1344 	}
1345 
1346 	/*
1347 	 * If we're not going to remove the origin after all,
1348 	 * undo the open context setup.
1349 	 */
1350 	if (dsda->rm_origin != NULL) {
1351 		dsl_dataset_disown(dsda->rm_origin, tag);
1352 		dsda->rm_origin = NULL;
1353 	}
1354 
1355 	return (0);
1356 }
1357 
1358 /*
1359  * If you add new checks here, you may need to add
1360  * additional checks to the "temporary" case in
1361  * snapshot_check() in dmu_objset.c.
1362  */
1363 /* ARGSUSED */
1364 int
1365 dsl_dataset_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
1366 {
1367 	struct dsl_ds_destroyarg *dsda = arg1;
1368 	dsl_dataset_t *ds = dsda->ds;
1369 
1370 	/* we have an owner hold, so noone else can destroy us */
1371 	ASSERT(!DSL_DATASET_IS_DESTROYED(ds));
1372 
1373 	/*
1374 	 * Only allow deferred destroy on pools that support it.
1375 	 * NOTE: deferred destroy is only supported on snapshots.
1376 	 */
1377 	if (dsda->defer) {
1378 		if (spa_version(ds->ds_dir->dd_pool->dp_spa) <
1379 		    SPA_VERSION_USERREFS)
1380 			return (ENOTSUP);
1381 		ASSERT(dsl_dataset_is_snapshot(ds));
1382 		return (0);
1383 	}
1384 
1385 	/*
1386 	 * Can't delete a head dataset if there are snapshots of it.
1387 	 * (Except if the only snapshots are from the branch we cloned
1388 	 * from.)
1389 	 */
1390 	if (ds->ds_prev != NULL &&
1391 	    ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1392 		return (EBUSY);
1393 
1394 	/*
1395 	 * If we made changes this txg, traverse_dsl_dataset won't find
1396 	 * them.  Try again.
1397 	 */
1398 	if (ds->ds_phys->ds_bp.blk_birth >= tx->tx_txg)
1399 		return (EAGAIN);
1400 
1401 	if (dsl_dataset_is_snapshot(ds)) {
1402 		/*
1403 		 * If this snapshot has an elevated user reference count,
1404 		 * we can't destroy it yet.
1405 		 */
1406 		if (ds->ds_userrefs > 0 && !dsda->releasing)
1407 			return (EBUSY);
1408 
1409 		mutex_enter(&ds->ds_lock);
1410 		/*
1411 		 * Can't delete a branch point. However, if we're destroying
1412 		 * a clone and removing its origin due to it having a user
1413 		 * hold count of 0 and having been marked for deferred destroy,
1414 		 * it's OK for the origin to have a single clone.
1415 		 */
1416 		if (ds->ds_phys->ds_num_children >
1417 		    (dsda->is_origin_rm ? 2 : 1)) {
1418 			mutex_exit(&ds->ds_lock);
1419 			return (EEXIST);
1420 		}
1421 		mutex_exit(&ds->ds_lock);
1422 	} else if (dsl_dir_is_clone(ds->ds_dir)) {
1423 		return (dsl_dataset_origin_check(dsda, arg2, tx));
1424 	}
1425 
1426 	/* XXX we should do some i/o error checking... */
1427 	return (0);
1428 }
1429 
1430 struct refsarg {
1431 	kmutex_t lock;
1432 	boolean_t gone;
1433 	kcondvar_t cv;
1434 };
1435 
1436 /* ARGSUSED */
1437 static void
1438 dsl_dataset_refs_gone(dmu_buf_t *db, void *argv)
1439 {
1440 	struct refsarg *arg = argv;
1441 
1442 	mutex_enter(&arg->lock);
1443 	arg->gone = TRUE;
1444 	cv_signal(&arg->cv);
1445 	mutex_exit(&arg->lock);
1446 }
1447 
1448 static void
1449 dsl_dataset_drain_refs(dsl_dataset_t *ds, void *tag)
1450 {
1451 	struct refsarg arg;
1452 
1453 	mutex_init(&arg.lock, NULL, MUTEX_DEFAULT, NULL);
1454 	cv_init(&arg.cv, NULL, CV_DEFAULT, NULL);
1455 	arg.gone = FALSE;
1456 	(void) dmu_buf_update_user(ds->ds_dbuf, ds, &arg, &ds->ds_phys,
1457 	    dsl_dataset_refs_gone);
1458 	dmu_buf_rele(ds->ds_dbuf, tag);
1459 	mutex_enter(&arg.lock);
1460 	while (!arg.gone)
1461 		cv_wait(&arg.cv, &arg.lock);
1462 	ASSERT(arg.gone);
1463 	mutex_exit(&arg.lock);
1464 	ds->ds_dbuf = NULL;
1465 	ds->ds_phys = NULL;
1466 	mutex_destroy(&arg.lock);
1467 	cv_destroy(&arg.cv);
1468 }
1469 
1470 static void
1471 remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj, dmu_tx_t *tx)
1472 {
1473 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1474 	uint64_t count;
1475 	int err;
1476 
1477 	ASSERT(ds->ds_phys->ds_num_children >= 2);
1478 	err = zap_remove_int(mos, ds->ds_phys->ds_next_clones_obj, obj, tx);
1479 	/*
1480 	 * The err should not be ENOENT, but a bug in a previous version
1481 	 * of the code could cause upgrade_clones_cb() to not set
1482 	 * ds_next_snap_obj when it should, leading to a missing entry.
1483 	 * If we knew that the pool was created after
1484 	 * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
1485 	 * ENOENT.  However, at least we can check that we don't have
1486 	 * too many entries in the next_clones_obj even after failing to
1487 	 * remove this one.
1488 	 */
1489 	if (err != ENOENT) {
1490 		VERIFY3U(err, ==, 0);
1491 	}
1492 	ASSERT3U(0, ==, zap_count(mos, ds->ds_phys->ds_next_clones_obj,
1493 	    &count));
1494 	ASSERT3U(count, <=, ds->ds_phys->ds_num_children - 2);
1495 }
1496 
1497 static void
1498 dsl_dataset_remove_clones_key(dsl_dataset_t *ds, uint64_t mintxg, dmu_tx_t *tx)
1499 {
1500 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1501 	zap_cursor_t zc;
1502 	zap_attribute_t za;
1503 
1504 	/*
1505 	 * If it is the old version, dd_clones doesn't exist so we can't
1506 	 * find the clones, but deadlist_remove_key() is a no-op so it
1507 	 * doesn't matter.
1508 	 */
1509 	if (ds->ds_dir->dd_phys->dd_clones == 0)
1510 		return;
1511 
1512 	for (zap_cursor_init(&zc, mos, ds->ds_dir->dd_phys->dd_clones);
1513 	    zap_cursor_retrieve(&zc, &za) == 0;
1514 	    zap_cursor_advance(&zc)) {
1515 		dsl_dataset_t *clone;
1516 
1517 		VERIFY3U(0, ==, dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
1518 		    za.za_first_integer, FTAG, &clone));
1519 		if (clone->ds_dir->dd_origin_txg > mintxg) {
1520 			dsl_deadlist_remove_key(&clone->ds_deadlist,
1521 			    mintxg, tx);
1522 			dsl_dataset_remove_clones_key(clone, mintxg, tx);
1523 		}
1524 		dsl_dataset_rele(clone, FTAG);
1525 	}
1526 	zap_cursor_fini(&zc);
1527 }
1528 
1529 struct process_old_arg {
1530 	dsl_dataset_t *ds;
1531 	dsl_dataset_t *ds_prev;
1532 	boolean_t after_branch_point;
1533 	zio_t *pio;
1534 	uint64_t used, comp, uncomp;
1535 };
1536 
1537 static int
1538 process_old_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1539 {
1540 	struct process_old_arg *poa = arg;
1541 	dsl_pool_t *dp = poa->ds->ds_dir->dd_pool;
1542 
1543 	if (bp->blk_birth <= poa->ds->ds_phys->ds_prev_snap_txg) {
1544 		dsl_deadlist_insert(&poa->ds->ds_deadlist, bp, tx);
1545 		if (poa->ds_prev && !poa->after_branch_point &&
1546 		    bp->blk_birth >
1547 		    poa->ds_prev->ds_phys->ds_prev_snap_txg) {
1548 			poa->ds_prev->ds_phys->ds_unique_bytes +=
1549 			    bp_get_dsize_sync(dp->dp_spa, bp);
1550 		}
1551 	} else {
1552 		poa->used += bp_get_dsize_sync(dp->dp_spa, bp);
1553 		poa->comp += BP_GET_PSIZE(bp);
1554 		poa->uncomp += BP_GET_UCSIZE(bp);
1555 		dsl_free_sync(poa->pio, dp, tx->tx_txg, bp);
1556 	}
1557 	return (0);
1558 }
1559 
1560 static void
1561 process_old_deadlist(dsl_dataset_t *ds, dsl_dataset_t *ds_prev,
1562     dsl_dataset_t *ds_next, boolean_t after_branch_point, dmu_tx_t *tx)
1563 {
1564 	struct process_old_arg poa = { 0 };
1565 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1566 	objset_t *mos = dp->dp_meta_objset;
1567 
1568 	ASSERT(ds->ds_deadlist.dl_oldfmt);
1569 	ASSERT(ds_next->ds_deadlist.dl_oldfmt);
1570 
1571 	poa.ds = ds;
1572 	poa.ds_prev = ds_prev;
1573 	poa.after_branch_point = after_branch_point;
1574 	poa.pio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1575 	VERIFY3U(0, ==, bpobj_iterate(&ds_next->ds_deadlist.dl_bpobj,
1576 	    process_old_cb, &poa, tx));
1577 	VERIFY3U(zio_wait(poa.pio), ==, 0);
1578 	ASSERT3U(poa.used, ==, ds->ds_phys->ds_unique_bytes);
1579 
1580 	/* change snapused */
1581 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_SNAP,
1582 	    -poa.used, -poa.comp, -poa.uncomp, tx);
1583 
1584 	/* swap next's deadlist to our deadlist */
1585 	dsl_deadlist_close(&ds->ds_deadlist);
1586 	dsl_deadlist_close(&ds_next->ds_deadlist);
1587 	SWITCH64(ds_next->ds_phys->ds_deadlist_obj,
1588 	    ds->ds_phys->ds_deadlist_obj);
1589 	dsl_deadlist_open(&ds->ds_deadlist, mos, ds->ds_phys->ds_deadlist_obj);
1590 	dsl_deadlist_open(&ds_next->ds_deadlist, mos,
1591 	    ds_next->ds_phys->ds_deadlist_obj);
1592 }
1593 
1594 static int
1595 old_synchronous_dataset_destroy(dsl_dataset_t *ds, dmu_tx_t *tx)
1596 {
1597 	int err;
1598 	struct killarg ka;
1599 
1600 	/*
1601 	 * Free everything that we point to (that's born after
1602 	 * the previous snapshot, if we are a clone)
1603 	 *
1604 	 * NB: this should be very quick, because we already
1605 	 * freed all the objects in open context.
1606 	 */
1607 	ka.ds = ds;
1608 	ka.tx = tx;
1609 	err = traverse_dataset(ds,
1610 	    ds->ds_phys->ds_prev_snap_txg, TRAVERSE_POST,
1611 	    kill_blkptr, &ka);
1612 	ASSERT3U(err, ==, 0);
1613 	ASSERT(!DS_UNIQUE_IS_ACCURATE(ds) || ds->ds_phys->ds_unique_bytes == 0);
1614 
1615 	return (err);
1616 }
1617 
1618 void
1619 dsl_dataset_destroy_sync(void *arg1, void *tag, dmu_tx_t *tx)
1620 {
1621 	struct dsl_ds_destroyarg *dsda = arg1;
1622 	dsl_dataset_t *ds = dsda->ds;
1623 	int err;
1624 	int after_branch_point = FALSE;
1625 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1626 	objset_t *mos = dp->dp_meta_objset;
1627 	dsl_dataset_t *ds_prev = NULL;
1628 	boolean_t wont_destroy;
1629 	uint64_t obj;
1630 
1631 	wont_destroy = (dsda->defer &&
1632 	    (ds->ds_userrefs > 0 || ds->ds_phys->ds_num_children > 1));
1633 
1634 	ASSERT(ds->ds_owner || wont_destroy);
1635 	ASSERT(dsda->defer || ds->ds_phys->ds_num_children <= 1);
1636 	ASSERT(ds->ds_prev == NULL ||
1637 	    ds->ds_prev->ds_phys->ds_next_snap_obj != ds->ds_object);
1638 	ASSERT3U(ds->ds_phys->ds_bp.blk_birth, <=, tx->tx_txg);
1639 
1640 	if (wont_destroy) {
1641 		ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1642 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1643 		ds->ds_phys->ds_flags |= DS_FLAG_DEFER_DESTROY;
1644 		spa_history_log_internal_ds(ds, "defer_destroy", tx, "");
1645 		return;
1646 	}
1647 
1648 	/* We need to log before removing it from the namespace. */
1649 	spa_history_log_internal_ds(ds, "destroy", tx, "");
1650 
1651 	/* signal any waiters that this dataset is going away */
1652 	mutex_enter(&ds->ds_lock);
1653 	ds->ds_owner = dsl_reaper;
1654 	cv_broadcast(&ds->ds_exclusive_cv);
1655 	mutex_exit(&ds->ds_lock);
1656 
1657 	/* Remove our reservation */
1658 	if (ds->ds_reserved != 0) {
1659 		dsl_prop_setarg_t psa;
1660 		uint64_t value = 0;
1661 
1662 		dsl_prop_setarg_init_uint64(&psa, "refreservation",
1663 		    (ZPROP_SRC_NONE | ZPROP_SRC_LOCAL | ZPROP_SRC_RECEIVED),
1664 		    &value);
1665 		psa.psa_effective_value = 0;	/* predict default value */
1666 
1667 		dsl_dataset_set_reservation_sync(ds, &psa, tx);
1668 		ASSERT3U(ds->ds_reserved, ==, 0);
1669 	}
1670 
1671 	ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
1672 
1673 	dsl_scan_ds_destroyed(ds, tx);
1674 
1675 	obj = ds->ds_object;
1676 
1677 	if (ds->ds_phys->ds_prev_snap_obj != 0) {
1678 		if (ds->ds_prev) {
1679 			ds_prev = ds->ds_prev;
1680 		} else {
1681 			VERIFY(0 == dsl_dataset_hold_obj(dp,
1682 			    ds->ds_phys->ds_prev_snap_obj, FTAG, &ds_prev));
1683 		}
1684 		after_branch_point =
1685 		    (ds_prev->ds_phys->ds_next_snap_obj != obj);
1686 
1687 		dmu_buf_will_dirty(ds_prev->ds_dbuf, tx);
1688 		if (after_branch_point &&
1689 		    ds_prev->ds_phys->ds_next_clones_obj != 0) {
1690 			remove_from_next_clones(ds_prev, obj, tx);
1691 			if (ds->ds_phys->ds_next_snap_obj != 0) {
1692 				VERIFY(0 == zap_add_int(mos,
1693 				    ds_prev->ds_phys->ds_next_clones_obj,
1694 				    ds->ds_phys->ds_next_snap_obj, tx));
1695 			}
1696 		}
1697 		if (after_branch_point &&
1698 		    ds->ds_phys->ds_next_snap_obj == 0) {
1699 			/* This clone is toast. */
1700 			ASSERT(ds_prev->ds_phys->ds_num_children > 1);
1701 			ds_prev->ds_phys->ds_num_children--;
1702 
1703 			/*
1704 			 * If the clone's origin has no other clones, no
1705 			 * user holds, and has been marked for deferred
1706 			 * deletion, then we should have done the necessary
1707 			 * destroy setup for it.
1708 			 */
1709 			if (ds_prev->ds_phys->ds_num_children == 1 &&
1710 			    ds_prev->ds_userrefs == 0 &&
1711 			    DS_IS_DEFER_DESTROY(ds_prev)) {
1712 				ASSERT3P(dsda->rm_origin, !=, NULL);
1713 			} else {
1714 				ASSERT3P(dsda->rm_origin, ==, NULL);
1715 			}
1716 		} else if (!after_branch_point) {
1717 			ds_prev->ds_phys->ds_next_snap_obj =
1718 			    ds->ds_phys->ds_next_snap_obj;
1719 		}
1720 	}
1721 
1722 	if (dsl_dataset_is_snapshot(ds)) {
1723 		dsl_dataset_t *ds_next;
1724 		uint64_t old_unique;
1725 		uint64_t used = 0, comp = 0, uncomp = 0;
1726 
1727 		VERIFY(0 == dsl_dataset_hold_obj(dp,
1728 		    ds->ds_phys->ds_next_snap_obj, FTAG, &ds_next));
1729 		ASSERT3U(ds_next->ds_phys->ds_prev_snap_obj, ==, obj);
1730 
1731 		old_unique = ds_next->ds_phys->ds_unique_bytes;
1732 
1733 		dmu_buf_will_dirty(ds_next->ds_dbuf, tx);
1734 		ds_next->ds_phys->ds_prev_snap_obj =
1735 		    ds->ds_phys->ds_prev_snap_obj;
1736 		ds_next->ds_phys->ds_prev_snap_txg =
1737 		    ds->ds_phys->ds_prev_snap_txg;
1738 		ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
1739 		    ds_prev ? ds_prev->ds_phys->ds_creation_txg : 0);
1740 
1741 
1742 		if (ds_next->ds_deadlist.dl_oldfmt) {
1743 			process_old_deadlist(ds, ds_prev, ds_next,
1744 			    after_branch_point, tx);
1745 		} else {
1746 			/* Adjust prev's unique space. */
1747 			if (ds_prev && !after_branch_point) {
1748 				dsl_deadlist_space_range(&ds_next->ds_deadlist,
1749 				    ds_prev->ds_phys->ds_prev_snap_txg,
1750 				    ds->ds_phys->ds_prev_snap_txg,
1751 				    &used, &comp, &uncomp);
1752 				ds_prev->ds_phys->ds_unique_bytes += used;
1753 			}
1754 
1755 			/* Adjust snapused. */
1756 			dsl_deadlist_space_range(&ds_next->ds_deadlist,
1757 			    ds->ds_phys->ds_prev_snap_txg, UINT64_MAX,
1758 			    &used, &comp, &uncomp);
1759 			dsl_dir_diduse_space(ds->ds_dir, DD_USED_SNAP,
1760 			    -used, -comp, -uncomp, tx);
1761 
1762 			/* Move blocks to be freed to pool's free list. */
1763 			dsl_deadlist_move_bpobj(&ds_next->ds_deadlist,
1764 			    &dp->dp_free_bpobj, ds->ds_phys->ds_prev_snap_txg,
1765 			    tx);
1766 			dsl_dir_diduse_space(tx->tx_pool->dp_free_dir,
1767 			    DD_USED_HEAD, used, comp, uncomp, tx);
1768 
1769 			/* Merge our deadlist into next's and free it. */
1770 			dsl_deadlist_merge(&ds_next->ds_deadlist,
1771 			    ds->ds_phys->ds_deadlist_obj, tx);
1772 		}
1773 		dsl_deadlist_close(&ds->ds_deadlist);
1774 		dsl_deadlist_free(mos, ds->ds_phys->ds_deadlist_obj, tx);
1775 
1776 		/* Collapse range in clone heads */
1777 		dsl_dataset_remove_clones_key(ds,
1778 		    ds->ds_phys->ds_creation_txg, tx);
1779 
1780 		if (dsl_dataset_is_snapshot(ds_next)) {
1781 			dsl_dataset_t *ds_nextnext;
1782 
1783 			/*
1784 			 * Update next's unique to include blocks which
1785 			 * were previously shared by only this snapshot
1786 			 * and it.  Those blocks will be born after the
1787 			 * prev snap and before this snap, and will have
1788 			 * died after the next snap and before the one
1789 			 * after that (ie. be on the snap after next's
1790 			 * deadlist).
1791 			 */
1792 			VERIFY(0 == dsl_dataset_hold_obj(dp,
1793 			    ds_next->ds_phys->ds_next_snap_obj,
1794 			    FTAG, &ds_nextnext));
1795 			dsl_deadlist_space_range(&ds_nextnext->ds_deadlist,
1796 			    ds->ds_phys->ds_prev_snap_txg,
1797 			    ds->ds_phys->ds_creation_txg,
1798 			    &used, &comp, &uncomp);
1799 			ds_next->ds_phys->ds_unique_bytes += used;
1800 			dsl_dataset_rele(ds_nextnext, FTAG);
1801 			ASSERT3P(ds_next->ds_prev, ==, NULL);
1802 
1803 			/* Collapse range in this head. */
1804 			dsl_dataset_t *hds;
1805 			VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
1806 			    ds->ds_dir->dd_phys->dd_head_dataset_obj,
1807 			    FTAG, &hds));
1808 			dsl_deadlist_remove_key(&hds->ds_deadlist,
1809 			    ds->ds_phys->ds_creation_txg, tx);
1810 			dsl_dataset_rele(hds, FTAG);
1811 
1812 		} else {
1813 			ASSERT3P(ds_next->ds_prev, ==, ds);
1814 			dsl_dataset_drop_ref(ds_next->ds_prev, ds_next);
1815 			ds_next->ds_prev = NULL;
1816 			if (ds_prev) {
1817 				VERIFY(0 == dsl_dataset_get_ref(dp,
1818 				    ds->ds_phys->ds_prev_snap_obj,
1819 				    ds_next, &ds_next->ds_prev));
1820 			}
1821 
1822 			dsl_dataset_recalc_head_uniq(ds_next);
1823 
1824 			/*
1825 			 * Reduce the amount of our unconsmed refreservation
1826 			 * being charged to our parent by the amount of
1827 			 * new unique data we have gained.
1828 			 */
1829 			if (old_unique < ds_next->ds_reserved) {
1830 				int64_t mrsdelta;
1831 				uint64_t new_unique =
1832 				    ds_next->ds_phys->ds_unique_bytes;
1833 
1834 				ASSERT(old_unique <= new_unique);
1835 				mrsdelta = MIN(new_unique - old_unique,
1836 				    ds_next->ds_reserved - old_unique);
1837 				dsl_dir_diduse_space(ds->ds_dir,
1838 				    DD_USED_REFRSRV, -mrsdelta, 0, 0, tx);
1839 			}
1840 		}
1841 		dsl_dataset_rele(ds_next, FTAG);
1842 	} else {
1843 		zfeature_info_t *async_destroy =
1844 		    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY];
1845 		objset_t *os;
1846 
1847 		/*
1848 		 * There's no next snapshot, so this is a head dataset.
1849 		 * Destroy the deadlist.  Unless it's a clone, the
1850 		 * deadlist should be empty.  (If it's a clone, it's
1851 		 * safe to ignore the deadlist contents.)
1852 		 */
1853 		dsl_deadlist_close(&ds->ds_deadlist);
1854 		dsl_deadlist_free(mos, ds->ds_phys->ds_deadlist_obj, tx);
1855 		ds->ds_phys->ds_deadlist_obj = 0;
1856 
1857 		VERIFY3U(0, ==, dmu_objset_from_ds(ds, &os));
1858 
1859 		if (!spa_feature_is_enabled(dp->dp_spa, async_destroy)) {
1860 			err = old_synchronous_dataset_destroy(ds, tx);
1861 		} else {
1862 			/*
1863 			 * Move the bptree into the pool's list of trees to
1864 			 * clean up and update space accounting information.
1865 			 */
1866 			uint64_t used, comp, uncomp;
1867 
1868 			zil_destroy_sync(dmu_objset_zil(os), tx);
1869 
1870 			if (!spa_feature_is_active(dp->dp_spa, async_destroy)) {
1871 				spa_feature_incr(dp->dp_spa, async_destroy, tx);
1872 				dp->dp_bptree_obj = bptree_alloc(mos, tx);
1873 				VERIFY(zap_add(mos,
1874 				    DMU_POOL_DIRECTORY_OBJECT,
1875 				    DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
1876 				    &dp->dp_bptree_obj, tx) == 0);
1877 			}
1878 
1879 			used = ds->ds_dir->dd_phys->dd_used_bytes;
1880 			comp = ds->ds_dir->dd_phys->dd_compressed_bytes;
1881 			uncomp = ds->ds_dir->dd_phys->dd_uncompressed_bytes;
1882 
1883 			ASSERT(!DS_UNIQUE_IS_ACCURATE(ds) ||
1884 			    ds->ds_phys->ds_unique_bytes == used);
1885 
1886 			bptree_add(mos, dp->dp_bptree_obj,
1887 			    &ds->ds_phys->ds_bp, ds->ds_phys->ds_prev_snap_txg,
1888 			    used, comp, uncomp, tx);
1889 			dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
1890 			    -used, -comp, -uncomp, tx);
1891 			dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
1892 			    used, comp, uncomp, tx);
1893 		}
1894 
1895 		if (ds->ds_prev != NULL) {
1896 			if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
1897 				VERIFY3U(0, ==, zap_remove_int(mos,
1898 				    ds->ds_prev->ds_dir->dd_phys->dd_clones,
1899 				    ds->ds_object, tx));
1900 			}
1901 			dsl_dataset_rele(ds->ds_prev, ds);
1902 			ds->ds_prev = ds_prev = NULL;
1903 		}
1904 	}
1905 
1906 	/*
1907 	 * This must be done after the dsl_traverse(), because it will
1908 	 * re-open the objset.
1909 	 */
1910 	if (ds->ds_objset) {
1911 		dmu_objset_evict(ds->ds_objset);
1912 		ds->ds_objset = NULL;
1913 	}
1914 
1915 	if (ds->ds_dir->dd_phys->dd_head_dataset_obj == ds->ds_object) {
1916 		/* Erase the link in the dir */
1917 		dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1918 		ds->ds_dir->dd_phys->dd_head_dataset_obj = 0;
1919 		ASSERT(ds->ds_phys->ds_snapnames_zapobj != 0);
1920 		err = zap_destroy(mos, ds->ds_phys->ds_snapnames_zapobj, tx);
1921 		ASSERT(err == 0);
1922 	} else {
1923 		/* remove from snapshot namespace */
1924 		dsl_dataset_t *ds_head;
1925 		ASSERT(ds->ds_phys->ds_snapnames_zapobj == 0);
1926 		VERIFY(0 == dsl_dataset_hold_obj(dp,
1927 		    ds->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ds_head));
1928 		VERIFY(0 == dsl_dataset_get_snapname(ds));
1929 #ifdef ZFS_DEBUG
1930 		{
1931 			uint64_t val;
1932 
1933 			err = dsl_dataset_snap_lookup(ds_head,
1934 			    ds->ds_snapname, &val);
1935 			ASSERT3U(err, ==, 0);
1936 			ASSERT3U(val, ==, obj);
1937 		}
1938 #endif
1939 		err = dsl_dataset_snap_remove(ds_head, ds->ds_snapname, tx);
1940 		ASSERT(err == 0);
1941 		dsl_dataset_rele(ds_head, FTAG);
1942 	}
1943 
1944 	if (ds_prev && ds->ds_prev != ds_prev)
1945 		dsl_dataset_rele(ds_prev, FTAG);
1946 
1947 	spa_prop_clear_bootfs(dp->dp_spa, ds->ds_object, tx);
1948 
1949 	if (ds->ds_phys->ds_next_clones_obj != 0) {
1950 		uint64_t count;
1951 		ASSERT(0 == zap_count(mos,
1952 		    ds->ds_phys->ds_next_clones_obj, &count) && count == 0);
1953 		VERIFY(0 == dmu_object_free(mos,
1954 		    ds->ds_phys->ds_next_clones_obj, tx));
1955 	}
1956 	if (ds->ds_phys->ds_props_obj != 0)
1957 		VERIFY(0 == zap_destroy(mos, ds->ds_phys->ds_props_obj, tx));
1958 	if (ds->ds_phys->ds_userrefs_obj != 0)
1959 		VERIFY(0 == zap_destroy(mos, ds->ds_phys->ds_userrefs_obj, tx));
1960 	dsl_dir_close(ds->ds_dir, ds);
1961 	ds->ds_dir = NULL;
1962 	dsl_dataset_drain_refs(ds, tag);
1963 	VERIFY(0 == dmu_object_free(mos, obj, tx));
1964 
1965 	if (dsda->rm_origin) {
1966 		/*
1967 		 * Remove the origin of the clone we just destroyed.
1968 		 */
1969 		struct dsl_ds_destroyarg ndsda = {0};
1970 
1971 		ndsda.ds = dsda->rm_origin;
1972 		dsl_dataset_destroy_sync(&ndsda, tag, tx);
1973 	}
1974 }
1975 
1976 static int
1977 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1978 {
1979 	uint64_t asize;
1980 
1981 	if (!dmu_tx_is_syncing(tx))
1982 		return (0);
1983 
1984 	/*
1985 	 * If there's an fs-only reservation, any blocks that might become
1986 	 * owned by the snapshot dataset must be accommodated by space
1987 	 * outside of the reservation.
1988 	 */
1989 	ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
1990 	asize = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
1991 	if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
1992 		return (ENOSPC);
1993 
1994 	/*
1995 	 * Propagate any reserved space for this snapshot to other
1996 	 * snapshot checks in this sync group.
1997 	 */
1998 	if (asize > 0)
1999 		dsl_dir_willuse_space(ds->ds_dir, asize, tx);
2000 
2001 	return (0);
2002 }
2003 
2004 int
2005 dsl_dataset_snapshot_check(dsl_dataset_t *ds, const char *snapname,
2006     dmu_tx_t *tx)
2007 {
2008 	int err;
2009 	uint64_t value;
2010 
2011 	/*
2012 	 * We don't allow multiple snapshots of the same txg.  If there
2013 	 * is already one, try again.
2014 	 */
2015 	if (ds->ds_phys->ds_prev_snap_txg >= tx->tx_txg)
2016 		return (EAGAIN);
2017 
2018 	/*
2019 	 * Check for conflicting snapshot name.
2020 	 */
2021 	err = dsl_dataset_snap_lookup(ds, snapname, &value);
2022 	if (err == 0)
2023 		return (EEXIST);
2024 	if (err != ENOENT)
2025 		return (err);
2026 
2027 	/*
2028 	 * Check that the dataset's name is not too long.  Name consists
2029 	 * of the dataset's length + 1 for the @-sign + snapshot name's length
2030 	 */
2031 	if (dsl_dataset_namelen(ds) + 1 + strlen(snapname) >= MAXNAMELEN)
2032 		return (ENAMETOOLONG);
2033 
2034 	err = dsl_dataset_snapshot_reserve_space(ds, tx);
2035 	if (err)
2036 		return (err);
2037 
2038 	ds->ds_trysnap_txg = tx->tx_txg;
2039 	return (0);
2040 }
2041 
2042 void
2043 dsl_dataset_snapshot_sync(dsl_dataset_t *ds, const char *snapname,
2044     dmu_tx_t *tx)
2045 {
2046 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2047 	dmu_buf_t *dbuf;
2048 	dsl_dataset_phys_t *dsphys;
2049 	uint64_t dsobj, crtxg;
2050 	objset_t *mos = dp->dp_meta_objset;
2051 	int err;
2052 
2053 	ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
2054 
2055 	/*
2056 	 * The origin's ds_creation_txg has to be < TXG_INITIAL
2057 	 */
2058 	if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
2059 		crtxg = 1;
2060 	else
2061 		crtxg = tx->tx_txg;
2062 
2063 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
2064 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
2065 	VERIFY(0 == dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
2066 	dmu_buf_will_dirty(dbuf, tx);
2067 	dsphys = dbuf->db_data;
2068 	bzero(dsphys, sizeof (dsl_dataset_phys_t));
2069 	dsphys->ds_dir_obj = ds->ds_dir->dd_object;
2070 	dsphys->ds_fsid_guid = unique_create();
2071 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
2072 	    sizeof (dsphys->ds_guid));
2073 	dsphys->ds_prev_snap_obj = ds->ds_phys->ds_prev_snap_obj;
2074 	dsphys->ds_prev_snap_txg = ds->ds_phys->ds_prev_snap_txg;
2075 	dsphys->ds_next_snap_obj = ds->ds_object;
2076 	dsphys->ds_num_children = 1;
2077 	dsphys->ds_creation_time = gethrestime_sec();
2078 	dsphys->ds_creation_txg = crtxg;
2079 	dsphys->ds_deadlist_obj = ds->ds_phys->ds_deadlist_obj;
2080 	dsphys->ds_referenced_bytes = ds->ds_phys->ds_referenced_bytes;
2081 	dsphys->ds_compressed_bytes = ds->ds_phys->ds_compressed_bytes;
2082 	dsphys->ds_uncompressed_bytes = ds->ds_phys->ds_uncompressed_bytes;
2083 	dsphys->ds_flags = ds->ds_phys->ds_flags;
2084 	dsphys->ds_bp = ds->ds_phys->ds_bp;
2085 	dmu_buf_rele(dbuf, FTAG);
2086 
2087 	ASSERT3U(ds->ds_prev != 0, ==, ds->ds_phys->ds_prev_snap_obj != 0);
2088 	if (ds->ds_prev) {
2089 		uint64_t next_clones_obj =
2090 		    ds->ds_prev->ds_phys->ds_next_clones_obj;
2091 		ASSERT(ds->ds_prev->ds_phys->ds_next_snap_obj ==
2092 		    ds->ds_object ||
2093 		    ds->ds_prev->ds_phys->ds_num_children > 1);
2094 		if (ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object) {
2095 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
2096 			ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
2097 			    ds->ds_prev->ds_phys->ds_creation_txg);
2098 			ds->ds_prev->ds_phys->ds_next_snap_obj = dsobj;
2099 		} else if (next_clones_obj != 0) {
2100 			remove_from_next_clones(ds->ds_prev,
2101 			    dsphys->ds_next_snap_obj, tx);
2102 			VERIFY3U(0, ==, zap_add_int(mos,
2103 			    next_clones_obj, dsobj, tx));
2104 		}
2105 	}
2106 
2107 	/*
2108 	 * If we have a reference-reservation on this dataset, we will
2109 	 * need to increase the amount of refreservation being charged
2110 	 * since our unique space is going to zero.
2111 	 */
2112 	if (ds->ds_reserved) {
2113 		int64_t delta;
2114 		ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
2115 		delta = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
2116 		dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
2117 		    delta, 0, 0, tx);
2118 	}
2119 
2120 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2121 	zfs_dbgmsg("taking snapshot %s@%s/%llu; newkey=%llu",
2122 	    ds->ds_dir->dd_myname, snapname, dsobj,
2123 	    ds->ds_phys->ds_prev_snap_txg);
2124 	ds->ds_phys->ds_deadlist_obj = dsl_deadlist_clone(&ds->ds_deadlist,
2125 	    UINT64_MAX, ds->ds_phys->ds_prev_snap_obj, tx);
2126 	dsl_deadlist_close(&ds->ds_deadlist);
2127 	dsl_deadlist_open(&ds->ds_deadlist, mos, ds->ds_phys->ds_deadlist_obj);
2128 	dsl_deadlist_add_key(&ds->ds_deadlist,
2129 	    ds->ds_phys->ds_prev_snap_txg, tx);
2130 
2131 	ASSERT3U(ds->ds_phys->ds_prev_snap_txg, <, tx->tx_txg);
2132 	ds->ds_phys->ds_prev_snap_obj = dsobj;
2133 	ds->ds_phys->ds_prev_snap_txg = crtxg;
2134 	ds->ds_phys->ds_unique_bytes = 0;
2135 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
2136 		ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
2137 
2138 	err = zap_add(mos, ds->ds_phys->ds_snapnames_zapobj,
2139 	    snapname, 8, 1, &dsobj, tx);
2140 	ASSERT(err == 0);
2141 
2142 	if (ds->ds_prev)
2143 		dsl_dataset_drop_ref(ds->ds_prev, ds);
2144 	VERIFY(0 == dsl_dataset_get_ref(dp,
2145 	    ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
2146 
2147 	dsl_scan_ds_snapshotted(ds, tx);
2148 
2149 	dsl_dir_snap_cmtime_update(ds->ds_dir);
2150 
2151 	spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, "");
2152 }
2153 
2154 void
2155 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
2156 {
2157 	ASSERT(dmu_tx_is_syncing(tx));
2158 	ASSERT(ds->ds_objset != NULL);
2159 	ASSERT(ds->ds_phys->ds_next_snap_obj == 0);
2160 
2161 	/*
2162 	 * in case we had to change ds_fsid_guid when we opened it,
2163 	 * sync it out now.
2164 	 */
2165 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2166 	ds->ds_phys->ds_fsid_guid = ds->ds_fsid_guid;
2167 
2168 	dmu_objset_sync(ds->ds_objset, zio, tx);
2169 }
2170 
2171 static void
2172 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
2173 {
2174 	uint64_t count = 0;
2175 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
2176 	zap_cursor_t zc;
2177 	zap_attribute_t za;
2178 	nvlist_t *propval;
2179 	nvlist_t *val;
2180 
2181 	rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
2182 	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2183 	VERIFY(nvlist_alloc(&val, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2184 
2185 	/*
2186 	 * There may me missing entries in ds_next_clones_obj
2187 	 * due to a bug in a previous version of the code.
2188 	 * Only trust it if it has the right number of entries.
2189 	 */
2190 	if (ds->ds_phys->ds_next_clones_obj != 0) {
2191 		ASSERT3U(0, ==, zap_count(mos, ds->ds_phys->ds_next_clones_obj,
2192 		    &count));
2193 	}
2194 	if (count != ds->ds_phys->ds_num_children - 1) {
2195 		goto fail;
2196 	}
2197 	for (zap_cursor_init(&zc, mos, ds->ds_phys->ds_next_clones_obj);
2198 	    zap_cursor_retrieve(&zc, &za) == 0;
2199 	    zap_cursor_advance(&zc)) {
2200 		dsl_dataset_t *clone;
2201 		char buf[ZFS_MAXNAMELEN];
2202 		/*
2203 		 * Even though we hold the dp_config_rwlock, the dataset
2204 		 * may fail to open, returning ENOENT.  If there is a
2205 		 * thread concurrently attempting to destroy this
2206 		 * dataset, it will have the ds_rwlock held for
2207 		 * RW_WRITER.  Our call to dsl_dataset_hold_obj() ->
2208 		 * dsl_dataset_hold_ref() will fail its
2209 		 * rw_tryenter(&ds->ds_rwlock, RW_READER), drop the
2210 		 * dp_config_rwlock, and wait for the destroy progress
2211 		 * and signal ds_exclusive_cv.  If the destroy was
2212 		 * successful, we will see that
2213 		 * DSL_DATASET_IS_DESTROYED(), and return ENOENT.
2214 		 */
2215 		if (dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
2216 		    za.za_first_integer, FTAG, &clone) != 0)
2217 			continue;
2218 		dsl_dir_name(clone->ds_dir, buf);
2219 		VERIFY(nvlist_add_boolean(val, buf) == 0);
2220 		dsl_dataset_rele(clone, FTAG);
2221 	}
2222 	zap_cursor_fini(&zc);
2223 	VERIFY(nvlist_add_nvlist(propval, ZPROP_VALUE, val) == 0);
2224 	VERIFY(nvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2225 	    propval) == 0);
2226 fail:
2227 	nvlist_free(val);
2228 	nvlist_free(propval);
2229 	rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
2230 }
2231 
2232 void
2233 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2234 {
2235 	uint64_t refd, avail, uobjs, aobjs, ratio;
2236 
2237 	ratio = ds->ds_phys->ds_compressed_bytes == 0 ? 100 :
2238 	    (ds->ds_phys->ds_uncompressed_bytes * 100 /
2239 	    ds->ds_phys->ds_compressed_bytes);
2240 
2241 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO, ratio);
2242 
2243 	if (dsl_dataset_is_snapshot(ds)) {
2244 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
2245 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2246 		    ds->ds_phys->ds_unique_bytes);
2247 		get_clones_stat(ds, nv);
2248 	} else {
2249 		dsl_dir_stats(ds->ds_dir, nv);
2250 	}
2251 
2252 	dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
2253 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
2254 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
2255 
2256 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2257 	    ds->ds_phys->ds_creation_time);
2258 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2259 	    ds->ds_phys->ds_creation_txg);
2260 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2261 	    ds->ds_quota);
2262 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2263 	    ds->ds_reserved);
2264 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2265 	    ds->ds_phys->ds_guid);
2266 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2267 	    ds->ds_phys->ds_unique_bytes);
2268 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2269 	    ds->ds_object);
2270 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2271 	    ds->ds_userrefs);
2272 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2273 	    DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2274 
2275 	if (ds->ds_phys->ds_prev_snap_obj != 0) {
2276 		uint64_t written, comp, uncomp;
2277 		dsl_pool_t *dp = ds->ds_dir->dd_pool;
2278 		dsl_dataset_t *prev;
2279 
2280 		rw_enter(&dp->dp_config_rwlock, RW_READER);
2281 		int err = dsl_dataset_hold_obj(dp,
2282 		    ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
2283 		rw_exit(&dp->dp_config_rwlock);
2284 		if (err == 0) {
2285 			err = dsl_dataset_space_written(prev, ds, &written,
2286 			    &comp, &uncomp);
2287 			dsl_dataset_rele(prev, FTAG);
2288 			if (err == 0) {
2289 				dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2290 				    written);
2291 			}
2292 		}
2293 	}
2294 
2295 }
2296 
2297 void
2298 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2299 {
2300 	stat->dds_creation_txg = ds->ds_phys->ds_creation_txg;
2301 	stat->dds_inconsistent = ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT;
2302 	stat->dds_guid = ds->ds_phys->ds_guid;
2303 	stat->dds_origin[0] = '\0';
2304 	if (dsl_dataset_is_snapshot(ds)) {
2305 		stat->dds_is_snapshot = B_TRUE;
2306 		stat->dds_num_clones = ds->ds_phys->ds_num_children - 1;
2307 	} else {
2308 		stat->dds_is_snapshot = B_FALSE;
2309 		stat->dds_num_clones = 0;
2310 
2311 		rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
2312 		if (dsl_dir_is_clone(ds->ds_dir)) {
2313 			dsl_dataset_t *ods;
2314 
2315 			VERIFY(0 == dsl_dataset_get_ref(ds->ds_dir->dd_pool,
2316 			    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &ods));
2317 			dsl_dataset_name(ods, stat->dds_origin);
2318 			dsl_dataset_drop_ref(ods, FTAG);
2319 		}
2320 		rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
2321 	}
2322 }
2323 
2324 uint64_t
2325 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2326 {
2327 	return (ds->ds_fsid_guid);
2328 }
2329 
2330 void
2331 dsl_dataset_space(dsl_dataset_t *ds,
2332     uint64_t *refdbytesp, uint64_t *availbytesp,
2333     uint64_t *usedobjsp, uint64_t *availobjsp)
2334 {
2335 	*refdbytesp = ds->ds_phys->ds_referenced_bytes;
2336 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2337 	if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes)
2338 		*availbytesp += ds->ds_reserved - ds->ds_phys->ds_unique_bytes;
2339 	if (ds->ds_quota != 0) {
2340 		/*
2341 		 * Adjust available bytes according to refquota
2342 		 */
2343 		if (*refdbytesp < ds->ds_quota)
2344 			*availbytesp = MIN(*availbytesp,
2345 			    ds->ds_quota - *refdbytesp);
2346 		else
2347 			*availbytesp = 0;
2348 	}
2349 	*usedobjsp = ds->ds_phys->ds_bp.blk_fill;
2350 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
2351 }
2352 
2353 boolean_t
2354 dsl_dataset_modified_since_lastsnap(dsl_dataset_t *ds)
2355 {
2356 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2357 
2358 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
2359 	    dsl_pool_sync_context(dp));
2360 	if (ds->ds_prev == NULL)
2361 		return (B_FALSE);
2362 	if (ds->ds_phys->ds_bp.blk_birth >
2363 	    ds->ds_prev->ds_phys->ds_creation_txg) {
2364 		objset_t *os, *os_prev;
2365 		/*
2366 		 * It may be that only the ZIL differs, because it was
2367 		 * reset in the head.  Don't count that as being
2368 		 * modified.
2369 		 */
2370 		if (dmu_objset_from_ds(ds, &os) != 0)
2371 			return (B_TRUE);
2372 		if (dmu_objset_from_ds(ds->ds_prev, &os_prev) != 0)
2373 			return (B_TRUE);
2374 		return (bcmp(&os->os_phys->os_meta_dnode,
2375 		    &os_prev->os_phys->os_meta_dnode,
2376 		    sizeof (os->os_phys->os_meta_dnode)) != 0);
2377 	}
2378 	return (B_FALSE);
2379 }
2380 
2381 /* ARGSUSED */
2382 static int
2383 dsl_dataset_snapshot_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
2384 {
2385 	dsl_dataset_t *ds = arg1;
2386 	char *newsnapname = arg2;
2387 	dsl_dir_t *dd = ds->ds_dir;
2388 	dsl_dataset_t *hds;
2389 	uint64_t val;
2390 	int err;
2391 
2392 	err = dsl_dataset_hold_obj(dd->dd_pool,
2393 	    dd->dd_phys->dd_head_dataset_obj, FTAG, &hds);
2394 	if (err)
2395 		return (err);
2396 
2397 	/* new name better not be in use */
2398 	err = dsl_dataset_snap_lookup(hds, newsnapname, &val);
2399 	dsl_dataset_rele(hds, FTAG);
2400 
2401 	if (err == 0)
2402 		err = EEXIST;
2403 	else if (err == ENOENT)
2404 		err = 0;
2405 
2406 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
2407 	if (dsl_dir_namelen(ds->ds_dir) + 1 + strlen(newsnapname) >= MAXNAMELEN)
2408 		err = ENAMETOOLONG;
2409 
2410 	return (err);
2411 }
2412 
2413 static void
2414 dsl_dataset_snapshot_rename_sync(void *arg1, void *arg2, dmu_tx_t *tx)
2415 {
2416 	dsl_dataset_t *ds = arg1;
2417 	const char *newsnapname = arg2;
2418 	dsl_dir_t *dd = ds->ds_dir;
2419 	objset_t *mos = dd->dd_pool->dp_meta_objset;
2420 	dsl_dataset_t *hds;
2421 	int err;
2422 
2423 	ASSERT(ds->ds_phys->ds_next_snap_obj != 0);
2424 
2425 	VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
2426 	    dd->dd_phys->dd_head_dataset_obj, FTAG, &hds));
2427 
2428 	VERIFY(0 == dsl_dataset_get_snapname(ds));
2429 	err = dsl_dataset_snap_remove(hds, ds->ds_snapname, tx);
2430 	ASSERT3U(err, ==, 0);
2431 	mutex_enter(&ds->ds_lock);
2432 	(void) strcpy(ds->ds_snapname, newsnapname);
2433 	mutex_exit(&ds->ds_lock);
2434 	err = zap_add(mos, hds->ds_phys->ds_snapnames_zapobj,
2435 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx);
2436 	ASSERT3U(err, ==, 0);
2437 
2438 	spa_history_log_internal_ds(ds, "rename", tx,
2439 	    "-> @%s", newsnapname);
2440 	dsl_dataset_rele(hds, FTAG);
2441 }
2442 
2443 struct renamesnaparg {
2444 	dsl_sync_task_group_t *dstg;
2445 	char failed[MAXPATHLEN];
2446 	char *oldsnap;
2447 	char *newsnap;
2448 };
2449 
2450 static int
2451 dsl_snapshot_rename_one(const char *name, void *arg)
2452 {
2453 	struct renamesnaparg *ra = arg;
2454 	dsl_dataset_t *ds = NULL;
2455 	char *snapname;
2456 	int err;
2457 
2458 	snapname = kmem_asprintf("%s@%s", name, ra->oldsnap);
2459 	(void) strlcpy(ra->failed, snapname, sizeof (ra->failed));
2460 
2461 	/*
2462 	 * For recursive snapshot renames the parent won't be changing
2463 	 * so we just pass name for both the to/from argument.
2464 	 */
2465 	err = zfs_secpolicy_rename_perms(snapname, snapname, CRED());
2466 	if (err != 0) {
2467 		strfree(snapname);
2468 		return (err == ENOENT ? 0 : err);
2469 	}
2470 
2471 #ifdef _KERNEL
2472 	/*
2473 	 * For all filesystems undergoing rename, we'll need to unmount it.
2474 	 */
2475 	(void) zfs_unmount_snap(snapname, NULL);
2476 #endif
2477 	err = dsl_dataset_hold(snapname, ra->dstg, &ds);
2478 	strfree(snapname);
2479 	if (err != 0)
2480 		return (err == ENOENT ? 0 : err);
2481 
2482 	dsl_sync_task_create(ra->dstg, dsl_dataset_snapshot_rename_check,
2483 	    dsl_dataset_snapshot_rename_sync, ds, ra->newsnap, 0);
2484 
2485 	return (0);
2486 }
2487 
2488 static int
2489 dsl_recursive_rename(char *oldname, const char *newname)
2490 {
2491 	int err;
2492 	struct renamesnaparg *ra;
2493 	dsl_sync_task_t *dst;
2494 	spa_t *spa;
2495 	char *cp, *fsname = spa_strdup(oldname);
2496 	int len = strlen(oldname) + 1;
2497 
2498 	/* truncate the snapshot name to get the fsname */
2499 	cp = strchr(fsname, '@');
2500 	*cp = '\0';
2501 
2502 	err = spa_open(fsname, &spa, FTAG);
2503 	if (err) {
2504 		kmem_free(fsname, len);
2505 		return (err);
2506 	}
2507 	ra = kmem_alloc(sizeof (struct renamesnaparg), KM_SLEEP);
2508 	ra->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
2509 
2510 	ra->oldsnap = strchr(oldname, '@') + 1;
2511 	ra->newsnap = strchr(newname, '@') + 1;
2512 	*ra->failed = '\0';
2513 
2514 	err = dmu_objset_find(fsname, dsl_snapshot_rename_one, ra,
2515 	    DS_FIND_CHILDREN);
2516 	kmem_free(fsname, len);
2517 
2518 	if (err == 0) {
2519 		err = dsl_sync_task_group_wait(ra->dstg);
2520 	}
2521 
2522 	for (dst = list_head(&ra->dstg->dstg_tasks); dst;
2523 	    dst = list_next(&ra->dstg->dstg_tasks, dst)) {
2524 		dsl_dataset_t *ds = dst->dst_arg1;
2525 		if (dst->dst_err) {
2526 			dsl_dir_name(ds->ds_dir, ra->failed);
2527 			(void) strlcat(ra->failed, "@", sizeof (ra->failed));
2528 			(void) strlcat(ra->failed, ra->newsnap,
2529 			    sizeof (ra->failed));
2530 		}
2531 		dsl_dataset_rele(ds, ra->dstg);
2532 	}
2533 
2534 	if (err)
2535 		(void) strlcpy(oldname, ra->failed, sizeof (ra->failed));
2536 
2537 	dsl_sync_task_group_destroy(ra->dstg);
2538 	kmem_free(ra, sizeof (struct renamesnaparg));
2539 	spa_close(spa, FTAG);
2540 	return (err);
2541 }
2542 
2543 static int
2544 dsl_valid_rename(const char *oldname, void *arg)
2545 {
2546 	int delta = *(int *)arg;
2547 
2548 	if (strlen(oldname) + delta >= MAXNAMELEN)
2549 		return (ENAMETOOLONG);
2550 
2551 	return (0);
2552 }
2553 
2554 #pragma weak dmu_objset_rename = dsl_dataset_rename
2555 int
2556 dsl_dataset_rename(char *oldname, const char *newname, boolean_t recursive)
2557 {
2558 	dsl_dir_t *dd;
2559 	dsl_dataset_t *ds;
2560 	const char *tail;
2561 	int err;
2562 
2563 	err = dsl_dir_open(oldname, FTAG, &dd, &tail);
2564 	if (err)
2565 		return (err);
2566 
2567 	if (tail == NULL) {
2568 		int delta = strlen(newname) - strlen(oldname);
2569 
2570 		/* if we're growing, validate child name lengths */
2571 		if (delta > 0)
2572 			err = dmu_objset_find(oldname, dsl_valid_rename,
2573 			    &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
2574 
2575 		if (err == 0)
2576 			err = dsl_dir_rename(dd, newname);
2577 		dsl_dir_close(dd, FTAG);
2578 		return (err);
2579 	}
2580 
2581 	if (tail[0] != '@') {
2582 		/* the name ended in a nonexistent component */
2583 		dsl_dir_close(dd, FTAG);
2584 		return (ENOENT);
2585 	}
2586 
2587 	dsl_dir_close(dd, FTAG);
2588 
2589 	/* new name must be snapshot in same filesystem */
2590 	tail = strchr(newname, '@');
2591 	if (tail == NULL)
2592 		return (EINVAL);
2593 	tail++;
2594 	if (strncmp(oldname, newname, tail - newname) != 0)
2595 		return (EXDEV);
2596 
2597 	if (recursive) {
2598 		err = dsl_recursive_rename(oldname, newname);
2599 	} else {
2600 		err = dsl_dataset_hold(oldname, FTAG, &ds);
2601 		if (err)
2602 			return (err);
2603 
2604 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
2605 		    dsl_dataset_snapshot_rename_check,
2606 		    dsl_dataset_snapshot_rename_sync, ds, (char *)tail, 1);
2607 
2608 		dsl_dataset_rele(ds, FTAG);
2609 	}
2610 
2611 	return (err);
2612 }
2613 
2614 struct promotenode {
2615 	list_node_t link;
2616 	dsl_dataset_t *ds;
2617 };
2618 
2619 struct promotearg {
2620 	list_t shared_snaps, origin_snaps, clone_snaps;
2621 	dsl_dataset_t *origin_origin;
2622 	uint64_t used, comp, uncomp, unique, cloneusedsnap, originusedsnap;
2623 	char *err_ds;
2624 };
2625 
2626 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2627 static boolean_t snaplist_unstable(list_t *l);
2628 
2629 static int
2630 dsl_dataset_promote_check(void *arg1, void *arg2, dmu_tx_t *tx)
2631 {
2632 	dsl_dataset_t *hds = arg1;
2633 	struct promotearg *pa = arg2;
2634 	struct promotenode *snap = list_head(&pa->shared_snaps);
2635 	dsl_dataset_t *origin_ds = snap->ds;
2636 	int err;
2637 	uint64_t unused;
2638 
2639 	/* Check that it is a real clone */
2640 	if (!dsl_dir_is_clone(hds->ds_dir))
2641 		return (EINVAL);
2642 
2643 	/* Since this is so expensive, don't do the preliminary check */
2644 	if (!dmu_tx_is_syncing(tx))
2645 		return (0);
2646 
2647 	if (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE)
2648 		return (EXDEV);
2649 
2650 	/* compute origin's new unique space */
2651 	snap = list_tail(&pa->clone_snaps);
2652 	ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2653 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2654 	    origin_ds->ds_phys->ds_prev_snap_txg, UINT64_MAX,
2655 	    &pa->unique, &unused, &unused);
2656 
2657 	/*
2658 	 * Walk the snapshots that we are moving
2659 	 *
2660 	 * Compute space to transfer.  Consider the incremental changes
2661 	 * to used for each snapshot:
2662 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
2663 	 * So each snapshot gave birth to:
2664 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
2665 	 * So a sequence would look like:
2666 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2667 	 * Which simplifies to:
2668 	 * uN + kN + kN-1 + ... + k1 + k0
2669 	 * Note however, if we stop before we reach the ORIGIN we get:
2670 	 * uN + kN + kN-1 + ... + kM - uM-1
2671 	 */
2672 	pa->used = origin_ds->ds_phys->ds_referenced_bytes;
2673 	pa->comp = origin_ds->ds_phys->ds_compressed_bytes;
2674 	pa->uncomp = origin_ds->ds_phys->ds_uncompressed_bytes;
2675 	for (snap = list_head(&pa->shared_snaps); snap;
2676 	    snap = list_next(&pa->shared_snaps, snap)) {
2677 		uint64_t val, dlused, dlcomp, dluncomp;
2678 		dsl_dataset_t *ds = snap->ds;
2679 
2680 		/* Check that the snapshot name does not conflict */
2681 		VERIFY(0 == dsl_dataset_get_snapname(ds));
2682 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2683 		if (err == 0) {
2684 			err = EEXIST;
2685 			goto out;
2686 		}
2687 		if (err != ENOENT)
2688 			goto out;
2689 
2690 		/* The very first snapshot does not have a deadlist */
2691 		if (ds->ds_phys->ds_prev_snap_obj == 0)
2692 			continue;
2693 
2694 		dsl_deadlist_space(&ds->ds_deadlist,
2695 		    &dlused, &dlcomp, &dluncomp);
2696 		pa->used += dlused;
2697 		pa->comp += dlcomp;
2698 		pa->uncomp += dluncomp;
2699 	}
2700 
2701 	/*
2702 	 * If we are a clone of a clone then we never reached ORIGIN,
2703 	 * so we need to subtract out the clone origin's used space.
2704 	 */
2705 	if (pa->origin_origin) {
2706 		pa->used -= pa->origin_origin->ds_phys->ds_referenced_bytes;
2707 		pa->comp -= pa->origin_origin->ds_phys->ds_compressed_bytes;
2708 		pa->uncomp -= pa->origin_origin->ds_phys->ds_uncompressed_bytes;
2709 	}
2710 
2711 	/* Check that there is enough space here */
2712 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2713 	    pa->used);
2714 	if (err)
2715 		return (err);
2716 
2717 	/*
2718 	 * Compute the amounts of space that will be used by snapshots
2719 	 * after the promotion (for both origin and clone).  For each,
2720 	 * it is the amount of space that will be on all of their
2721 	 * deadlists (that was not born before their new origin).
2722 	 */
2723 	if (hds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2724 		uint64_t space;
2725 
2726 		/*
2727 		 * Note, typically this will not be a clone of a clone,
2728 		 * so dd_origin_txg will be < TXG_INITIAL, so
2729 		 * these snaplist_space() -> dsl_deadlist_space_range()
2730 		 * calls will be fast because they do not have to
2731 		 * iterate over all bps.
2732 		 */
2733 		snap = list_head(&pa->origin_snaps);
2734 		err = snaplist_space(&pa->shared_snaps,
2735 		    snap->ds->ds_dir->dd_origin_txg, &pa->cloneusedsnap);
2736 		if (err)
2737 			return (err);
2738 
2739 		err = snaplist_space(&pa->clone_snaps,
2740 		    snap->ds->ds_dir->dd_origin_txg, &space);
2741 		if (err)
2742 			return (err);
2743 		pa->cloneusedsnap += space;
2744 	}
2745 	if (origin_ds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2746 		err = snaplist_space(&pa->origin_snaps,
2747 		    origin_ds->ds_phys->ds_creation_txg, &pa->originusedsnap);
2748 		if (err)
2749 			return (err);
2750 	}
2751 
2752 	return (0);
2753 out:
2754 	pa->err_ds =  snap->ds->ds_snapname;
2755 	return (err);
2756 }
2757 
2758 static void
2759 dsl_dataset_promote_sync(void *arg1, void *arg2, dmu_tx_t *tx)
2760 {
2761 	dsl_dataset_t *hds = arg1;
2762 	struct promotearg *pa = arg2;
2763 	struct promotenode *snap = list_head(&pa->shared_snaps);
2764 	dsl_dataset_t *origin_ds = snap->ds;
2765 	dsl_dataset_t *origin_head;
2766 	dsl_dir_t *dd = hds->ds_dir;
2767 	dsl_pool_t *dp = hds->ds_dir->dd_pool;
2768 	dsl_dir_t *odd = NULL;
2769 	uint64_t oldnext_obj;
2770 	int64_t delta;
2771 
2772 	ASSERT(0 == (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE));
2773 
2774 	snap = list_head(&pa->origin_snaps);
2775 	origin_head = snap->ds;
2776 
2777 	/*
2778 	 * We need to explicitly open odd, since origin_ds's dd will be
2779 	 * changing.
2780 	 */
2781 	VERIFY(0 == dsl_dir_open_obj(dp, origin_ds->ds_dir->dd_object,
2782 	    NULL, FTAG, &odd));
2783 
2784 	/* change origin's next snap */
2785 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2786 	oldnext_obj = origin_ds->ds_phys->ds_next_snap_obj;
2787 	snap = list_tail(&pa->clone_snaps);
2788 	ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2789 	origin_ds->ds_phys->ds_next_snap_obj = snap->ds->ds_object;
2790 
2791 	/* change the origin's next clone */
2792 	if (origin_ds->ds_phys->ds_next_clones_obj) {
2793 		remove_from_next_clones(origin_ds, snap->ds->ds_object, tx);
2794 		VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2795 		    origin_ds->ds_phys->ds_next_clones_obj,
2796 		    oldnext_obj, tx));
2797 	}
2798 
2799 	/* change origin */
2800 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
2801 	ASSERT3U(dd->dd_phys->dd_origin_obj, ==, origin_ds->ds_object);
2802 	dd->dd_phys->dd_origin_obj = odd->dd_phys->dd_origin_obj;
2803 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2804 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
2805 	odd->dd_phys->dd_origin_obj = origin_ds->ds_object;
2806 	origin_head->ds_dir->dd_origin_txg =
2807 	    origin_ds->ds_phys->ds_creation_txg;
2808 
2809 	/* change dd_clone entries */
2810 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2811 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2812 		    odd->dd_phys->dd_clones, hds->ds_object, tx));
2813 		VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2814 		    pa->origin_origin->ds_dir->dd_phys->dd_clones,
2815 		    hds->ds_object, tx));
2816 
2817 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2818 		    pa->origin_origin->ds_dir->dd_phys->dd_clones,
2819 		    origin_head->ds_object, tx));
2820 		if (dd->dd_phys->dd_clones == 0) {
2821 			dd->dd_phys->dd_clones = zap_create(dp->dp_meta_objset,
2822 			    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
2823 		}
2824 		VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2825 		    dd->dd_phys->dd_clones, origin_head->ds_object, tx));
2826 
2827 	}
2828 
2829 	/* move snapshots to this dir */
2830 	for (snap = list_head(&pa->shared_snaps); snap;
2831 	    snap = list_next(&pa->shared_snaps, snap)) {
2832 		dsl_dataset_t *ds = snap->ds;
2833 
2834 		/* unregister props as dsl_dir is changing */
2835 		if (ds->ds_objset) {
2836 			dmu_objset_evict(ds->ds_objset);
2837 			ds->ds_objset = NULL;
2838 		}
2839 		/* move snap name entry */
2840 		VERIFY(0 == dsl_dataset_get_snapname(ds));
2841 		VERIFY(0 == dsl_dataset_snap_remove(origin_head,
2842 		    ds->ds_snapname, tx));
2843 		VERIFY(0 == zap_add(dp->dp_meta_objset,
2844 		    hds->ds_phys->ds_snapnames_zapobj, ds->ds_snapname,
2845 		    8, 1, &ds->ds_object, tx));
2846 
2847 		/* change containing dsl_dir */
2848 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2849 		ASSERT3U(ds->ds_phys->ds_dir_obj, ==, odd->dd_object);
2850 		ds->ds_phys->ds_dir_obj = dd->dd_object;
2851 		ASSERT3P(ds->ds_dir, ==, odd);
2852 		dsl_dir_close(ds->ds_dir, ds);
2853 		VERIFY(0 == dsl_dir_open_obj(dp, dd->dd_object,
2854 		    NULL, ds, &ds->ds_dir));
2855 
2856 		/* move any clone references */
2857 		if (ds->ds_phys->ds_next_clones_obj &&
2858 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2859 			zap_cursor_t zc;
2860 			zap_attribute_t za;
2861 
2862 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
2863 			    ds->ds_phys->ds_next_clones_obj);
2864 			    zap_cursor_retrieve(&zc, &za) == 0;
2865 			    zap_cursor_advance(&zc)) {
2866 				dsl_dataset_t *cnds;
2867 				uint64_t o;
2868 
2869 				if (za.za_first_integer == oldnext_obj) {
2870 					/*
2871 					 * We've already moved the
2872 					 * origin's reference.
2873 					 */
2874 					continue;
2875 				}
2876 
2877 				VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
2878 				    za.za_first_integer, FTAG, &cnds));
2879 				o = cnds->ds_dir->dd_phys->dd_head_dataset_obj;
2880 
2881 				VERIFY3U(zap_remove_int(dp->dp_meta_objset,
2882 				    odd->dd_phys->dd_clones, o, tx), ==, 0);
2883 				VERIFY3U(zap_add_int(dp->dp_meta_objset,
2884 				    dd->dd_phys->dd_clones, o, tx), ==, 0);
2885 				dsl_dataset_rele(cnds, FTAG);
2886 			}
2887 			zap_cursor_fini(&zc);
2888 		}
2889 
2890 		ASSERT3U(dsl_prop_numcb(ds), ==, 0);
2891 	}
2892 
2893 	/*
2894 	 * Change space accounting.
2895 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
2896 	 * both be valid, or both be 0 (resulting in delta == 0).  This
2897 	 * is true for each of {clone,origin} independently.
2898 	 */
2899 
2900 	delta = pa->cloneusedsnap -
2901 	    dd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2902 	ASSERT3S(delta, >=, 0);
2903 	ASSERT3U(pa->used, >=, delta);
2904 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
2905 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
2906 	    pa->used - delta, pa->comp, pa->uncomp, tx);
2907 
2908 	delta = pa->originusedsnap -
2909 	    odd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2910 	ASSERT3S(delta, <=, 0);
2911 	ASSERT3U(pa->used, >=, -delta);
2912 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
2913 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
2914 	    -pa->used - delta, -pa->comp, -pa->uncomp, tx);
2915 
2916 	origin_ds->ds_phys->ds_unique_bytes = pa->unique;
2917 
2918 	/* log history record */
2919 	spa_history_log_internal_ds(hds, "promote", tx, "");
2920 
2921 	dsl_dir_close(odd, FTAG);
2922 }
2923 
2924 static char *snaplist_tag = "snaplist";
2925 /*
2926  * Make a list of dsl_dataset_t's for the snapshots between first_obj
2927  * (exclusive) and last_obj (inclusive).  The list will be in reverse
2928  * order (last_obj will be the list_head()).  If first_obj == 0, do all
2929  * snapshots back to this dataset's origin.
2930  */
2931 static int
2932 snaplist_make(dsl_pool_t *dp, boolean_t own,
2933     uint64_t first_obj, uint64_t last_obj, list_t *l)
2934 {
2935 	uint64_t obj = last_obj;
2936 
2937 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock));
2938 
2939 	list_create(l, sizeof (struct promotenode),
2940 	    offsetof(struct promotenode, link));
2941 
2942 	while (obj != first_obj) {
2943 		dsl_dataset_t *ds;
2944 		struct promotenode *snap;
2945 		int err;
2946 
2947 		if (own) {
2948 			err = dsl_dataset_own_obj(dp, obj,
2949 			    0, snaplist_tag, &ds);
2950 			if (err == 0)
2951 				dsl_dataset_make_exclusive(ds, snaplist_tag);
2952 		} else {
2953 			err = dsl_dataset_hold_obj(dp, obj, snaplist_tag, &ds);
2954 		}
2955 		if (err == ENOENT) {
2956 			/* lost race with snapshot destroy */
2957 			struct promotenode *last = list_tail(l);
2958 			ASSERT(obj != last->ds->ds_phys->ds_prev_snap_obj);
2959 			obj = last->ds->ds_phys->ds_prev_snap_obj;
2960 			continue;
2961 		} else if (err) {
2962 			return (err);
2963 		}
2964 
2965 		if (first_obj == 0)
2966 			first_obj = ds->ds_dir->dd_phys->dd_origin_obj;
2967 
2968 		snap = kmem_alloc(sizeof (struct promotenode), KM_SLEEP);
2969 		snap->ds = ds;
2970 		list_insert_tail(l, snap);
2971 		obj = ds->ds_phys->ds_prev_snap_obj;
2972 	}
2973 
2974 	return (0);
2975 }
2976 
2977 static int
2978 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
2979 {
2980 	struct promotenode *snap;
2981 
2982 	*spacep = 0;
2983 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
2984 		uint64_t used, comp, uncomp;
2985 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2986 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
2987 		*spacep += used;
2988 	}
2989 	return (0);
2990 }
2991 
2992 static void
2993 snaplist_destroy(list_t *l, boolean_t own)
2994 {
2995 	struct promotenode *snap;
2996 
2997 	if (!l || !list_link_active(&l->list_head))
2998 		return;
2999 
3000 	while ((snap = list_tail(l)) != NULL) {
3001 		list_remove(l, snap);
3002 		if (own)
3003 			dsl_dataset_disown(snap->ds, snaplist_tag);
3004 		else
3005 			dsl_dataset_rele(snap->ds, snaplist_tag);
3006 		kmem_free(snap, sizeof (struct promotenode));
3007 	}
3008 	list_destroy(l);
3009 }
3010 
3011 /*
3012  * Promote a clone.  Nomenclature note:
3013  * "clone" or "cds": the original clone which is being promoted
3014  * "origin" or "ods": the snapshot which is originally clone's origin
3015  * "origin head" or "ohds": the dataset which is the head
3016  * (filesystem/volume) for the origin
3017  * "origin origin": the origin of the origin's filesystem (typically
3018  * NULL, indicating that the clone is not a clone of a clone).
3019  */
3020 int
3021 dsl_dataset_promote(const char *name, char *conflsnap)
3022 {
3023 	dsl_dataset_t *ds;
3024 	dsl_dir_t *dd;
3025 	dsl_pool_t *dp;
3026 	dmu_object_info_t doi;
3027 	struct promotearg pa = { 0 };
3028 	struct promotenode *snap;
3029 	int err;
3030 
3031 	err = dsl_dataset_hold(name, FTAG, &ds);
3032 	if (err)
3033 		return (err);
3034 	dd = ds->ds_dir;
3035 	dp = dd->dd_pool;
3036 
3037 	err = dmu_object_info(dp->dp_meta_objset,
3038 	    ds->ds_phys->ds_snapnames_zapobj, &doi);
3039 	if (err) {
3040 		dsl_dataset_rele(ds, FTAG);
3041 		return (err);
3042 	}
3043 
3044 	if (dsl_dataset_is_snapshot(ds) || dd->dd_phys->dd_origin_obj == 0) {
3045 		dsl_dataset_rele(ds, FTAG);
3046 		return (EINVAL);
3047 	}
3048 
3049 	/*
3050 	 * We are going to inherit all the snapshots taken before our
3051 	 * origin (i.e., our new origin will be our parent's origin).
3052 	 * Take ownership of them so that we can rename them into our
3053 	 * namespace.
3054 	 */
3055 	rw_enter(&dp->dp_config_rwlock, RW_READER);
3056 
3057 	err = snaplist_make(dp, B_TRUE, 0, dd->dd_phys->dd_origin_obj,
3058 	    &pa.shared_snaps);
3059 	if (err != 0)
3060 		goto out;
3061 
3062 	err = snaplist_make(dp, B_FALSE, 0, ds->ds_object, &pa.clone_snaps);
3063 	if (err != 0)
3064 		goto out;
3065 
3066 	snap = list_head(&pa.shared_snaps);
3067 	ASSERT3U(snap->ds->ds_object, ==, dd->dd_phys->dd_origin_obj);
3068 	err = snaplist_make(dp, B_FALSE, dd->dd_phys->dd_origin_obj,
3069 	    snap->ds->ds_dir->dd_phys->dd_head_dataset_obj, &pa.origin_snaps);
3070 	if (err != 0)
3071 		goto out;
3072 
3073 	if (snap->ds->ds_dir->dd_phys->dd_origin_obj != 0) {
3074 		err = dsl_dataset_hold_obj(dp,
3075 		    snap->ds->ds_dir->dd_phys->dd_origin_obj,
3076 		    FTAG, &pa.origin_origin);
3077 		if (err != 0)
3078 			goto out;
3079 	}
3080 
3081 out:
3082 	rw_exit(&dp->dp_config_rwlock);
3083 
3084 	/*
3085 	 * Add in 128x the snapnames zapobj size, since we will be moving
3086 	 * a bunch of snapnames to the promoted ds, and dirtying their
3087 	 * bonus buffers.
3088 	 */
3089 	if (err == 0) {
3090 		err = dsl_sync_task_do(dp, dsl_dataset_promote_check,
3091 		    dsl_dataset_promote_sync, ds, &pa,
3092 		    2 + 2 * doi.doi_physical_blocks_512);
3093 		if (err && pa.err_ds && conflsnap)
3094 			(void) strncpy(conflsnap, pa.err_ds, MAXNAMELEN);
3095 	}
3096 
3097 	snaplist_destroy(&pa.shared_snaps, B_TRUE);
3098 	snaplist_destroy(&pa.clone_snaps, B_FALSE);
3099 	snaplist_destroy(&pa.origin_snaps, B_FALSE);
3100 	if (pa.origin_origin)
3101 		dsl_dataset_rele(pa.origin_origin, FTAG);
3102 	dsl_dataset_rele(ds, FTAG);
3103 	return (err);
3104 }
3105 
3106 struct cloneswaparg {
3107 	dsl_dataset_t *cds; /* clone dataset */
3108 	dsl_dataset_t *ohds; /* origin's head dataset */
3109 	boolean_t force;
3110 	int64_t unused_refres_delta; /* change in unconsumed refreservation */
3111 };
3112 
3113 /* ARGSUSED */
3114 static int
3115 dsl_dataset_clone_swap_check(void *arg1, void *arg2, dmu_tx_t *tx)
3116 {
3117 	struct cloneswaparg *csa = arg1;
3118 
3119 	/* they should both be heads */
3120 	if (dsl_dataset_is_snapshot(csa->cds) ||
3121 	    dsl_dataset_is_snapshot(csa->ohds))
3122 		return (EINVAL);
3123 
3124 	/* the branch point should be just before them */
3125 	if (csa->cds->ds_prev != csa->ohds->ds_prev)
3126 		return (EINVAL);
3127 
3128 	/* cds should be the clone (unless they are unrelated) */
3129 	if (csa->cds->ds_prev != NULL &&
3130 	    csa->cds->ds_prev != csa->cds->ds_dir->dd_pool->dp_origin_snap &&
3131 	    csa->ohds->ds_object !=
3132 	    csa->cds->ds_prev->ds_phys->ds_next_snap_obj)
3133 		return (EINVAL);
3134 
3135 	/* the clone should be a child of the origin */
3136 	if (csa->cds->ds_dir->dd_parent != csa->ohds->ds_dir)
3137 		return (EINVAL);
3138 
3139 	/* ohds shouldn't be modified unless 'force' */
3140 	if (!csa->force && dsl_dataset_modified_since_lastsnap(csa->ohds))
3141 		return (ETXTBSY);
3142 
3143 	/* adjust amount of any unconsumed refreservation */
3144 	csa->unused_refres_delta =
3145 	    (int64_t)MIN(csa->ohds->ds_reserved,
3146 	    csa->ohds->ds_phys->ds_unique_bytes) -
3147 	    (int64_t)MIN(csa->ohds->ds_reserved,
3148 	    csa->cds->ds_phys->ds_unique_bytes);
3149 
3150 	if (csa->unused_refres_delta > 0 &&
3151 	    csa->unused_refres_delta >
3152 	    dsl_dir_space_available(csa->ohds->ds_dir, NULL, 0, TRUE))
3153 		return (ENOSPC);
3154 
3155 	if (csa->ohds->ds_quota != 0 &&
3156 	    csa->cds->ds_phys->ds_unique_bytes > csa->ohds->ds_quota)
3157 		return (EDQUOT);
3158 
3159 	return (0);
3160 }
3161 
3162 /* ARGSUSED */
3163 static void
3164 dsl_dataset_clone_swap_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3165 {
3166 	struct cloneswaparg *csa = arg1;
3167 	dsl_pool_t *dp = csa->cds->ds_dir->dd_pool;
3168 
3169 	ASSERT(csa->cds->ds_reserved == 0);
3170 	ASSERT(csa->ohds->ds_quota == 0 ||
3171 	    csa->cds->ds_phys->ds_unique_bytes <= csa->ohds->ds_quota);
3172 
3173 	dmu_buf_will_dirty(csa->cds->ds_dbuf, tx);
3174 	dmu_buf_will_dirty(csa->ohds->ds_dbuf, tx);
3175 
3176 	if (csa->cds->ds_objset != NULL) {
3177 		dmu_objset_evict(csa->cds->ds_objset);
3178 		csa->cds->ds_objset = NULL;
3179 	}
3180 
3181 	if (csa->ohds->ds_objset != NULL) {
3182 		dmu_objset_evict(csa->ohds->ds_objset);
3183 		csa->ohds->ds_objset = NULL;
3184 	}
3185 
3186 	/*
3187 	 * Reset origin's unique bytes, if it exists.
3188 	 */
3189 	if (csa->cds->ds_prev) {
3190 		dsl_dataset_t *origin = csa->cds->ds_prev;
3191 		uint64_t comp, uncomp;
3192 
3193 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
3194 		dsl_deadlist_space_range(&csa->cds->ds_deadlist,
3195 		    origin->ds_phys->ds_prev_snap_txg, UINT64_MAX,
3196 		    &origin->ds_phys->ds_unique_bytes, &comp, &uncomp);
3197 	}
3198 
3199 	/* swap blkptrs */
3200 	{
3201 		blkptr_t tmp;
3202 		tmp = csa->ohds->ds_phys->ds_bp;
3203 		csa->ohds->ds_phys->ds_bp = csa->cds->ds_phys->ds_bp;
3204 		csa->cds->ds_phys->ds_bp = tmp;
3205 	}
3206 
3207 	/* set dd_*_bytes */
3208 	{
3209 		int64_t dused, dcomp, duncomp;
3210 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
3211 		uint64_t odl_used, odl_comp, odl_uncomp;
3212 
3213 		ASSERT3U(csa->cds->ds_dir->dd_phys->
3214 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
3215 
3216 		dsl_deadlist_space(&csa->cds->ds_deadlist,
3217 		    &cdl_used, &cdl_comp, &cdl_uncomp);
3218 		dsl_deadlist_space(&csa->ohds->ds_deadlist,
3219 		    &odl_used, &odl_comp, &odl_uncomp);
3220 
3221 		dused = csa->cds->ds_phys->ds_referenced_bytes + cdl_used -
3222 		    (csa->ohds->ds_phys->ds_referenced_bytes + odl_used);
3223 		dcomp = csa->cds->ds_phys->ds_compressed_bytes + cdl_comp -
3224 		    (csa->ohds->ds_phys->ds_compressed_bytes + odl_comp);
3225 		duncomp = csa->cds->ds_phys->ds_uncompressed_bytes +
3226 		    cdl_uncomp -
3227 		    (csa->ohds->ds_phys->ds_uncompressed_bytes + odl_uncomp);
3228 
3229 		dsl_dir_diduse_space(csa->ohds->ds_dir, DD_USED_HEAD,
3230 		    dused, dcomp, duncomp, tx);
3231 		dsl_dir_diduse_space(csa->cds->ds_dir, DD_USED_HEAD,
3232 		    -dused, -dcomp, -duncomp, tx);
3233 
3234 		/*
3235 		 * The difference in the space used by snapshots is the
3236 		 * difference in snapshot space due to the head's
3237 		 * deadlist (since that's the only thing that's
3238 		 * changing that affects the snapused).
3239 		 */
3240 		dsl_deadlist_space_range(&csa->cds->ds_deadlist,
3241 		    csa->ohds->ds_dir->dd_origin_txg, UINT64_MAX,
3242 		    &cdl_used, &cdl_comp, &cdl_uncomp);
3243 		dsl_deadlist_space_range(&csa->ohds->ds_deadlist,
3244 		    csa->ohds->ds_dir->dd_origin_txg, UINT64_MAX,
3245 		    &odl_used, &odl_comp, &odl_uncomp);
3246 		dsl_dir_transfer_space(csa->ohds->ds_dir, cdl_used - odl_used,
3247 		    DD_USED_HEAD, DD_USED_SNAP, tx);
3248 	}
3249 
3250 	/* swap ds_*_bytes */
3251 	SWITCH64(csa->ohds->ds_phys->ds_referenced_bytes,
3252 	    csa->cds->ds_phys->ds_referenced_bytes);
3253 	SWITCH64(csa->ohds->ds_phys->ds_compressed_bytes,
3254 	    csa->cds->ds_phys->ds_compressed_bytes);
3255 	SWITCH64(csa->ohds->ds_phys->ds_uncompressed_bytes,
3256 	    csa->cds->ds_phys->ds_uncompressed_bytes);
3257 	SWITCH64(csa->ohds->ds_phys->ds_unique_bytes,
3258 	    csa->cds->ds_phys->ds_unique_bytes);
3259 
3260 	/* apply any parent delta for change in unconsumed refreservation */
3261 	dsl_dir_diduse_space(csa->ohds->ds_dir, DD_USED_REFRSRV,
3262 	    csa->unused_refres_delta, 0, 0, tx);
3263 
3264 	/*
3265 	 * Swap deadlists.
3266 	 */
3267 	dsl_deadlist_close(&csa->cds->ds_deadlist);
3268 	dsl_deadlist_close(&csa->ohds->ds_deadlist);
3269 	SWITCH64(csa->ohds->ds_phys->ds_deadlist_obj,
3270 	    csa->cds->ds_phys->ds_deadlist_obj);
3271 	dsl_deadlist_open(&csa->cds->ds_deadlist, dp->dp_meta_objset,
3272 	    csa->cds->ds_phys->ds_deadlist_obj);
3273 	dsl_deadlist_open(&csa->ohds->ds_deadlist, dp->dp_meta_objset,
3274 	    csa->ohds->ds_phys->ds_deadlist_obj);
3275 
3276 	dsl_scan_ds_clone_swapped(csa->ohds, csa->cds, tx);
3277 
3278 	spa_history_log_internal_ds(csa->cds, "clone swap", tx,
3279 	    "parent=%s", csa->ohds->ds_dir->dd_myname);
3280 }
3281 
3282 /*
3283  * Swap 'clone' with its origin head datasets.  Used at the end of "zfs
3284  * recv" into an existing fs to swizzle the file system to the new
3285  * version, and by "zfs rollback".  Can also be used to swap two
3286  * independent head datasets if neither has any snapshots.
3287  */
3288 int
3289 dsl_dataset_clone_swap(dsl_dataset_t *clone, dsl_dataset_t *origin_head,
3290     boolean_t force)
3291 {
3292 	struct cloneswaparg csa;
3293 	int error;
3294 
3295 	ASSERT(clone->ds_owner);
3296 	ASSERT(origin_head->ds_owner);
3297 retry:
3298 	/*
3299 	 * Need exclusive access for the swap. If we're swapping these
3300 	 * datasets back after an error, we already hold the locks.
3301 	 */
3302 	if (!RW_WRITE_HELD(&clone->ds_rwlock))
3303 		rw_enter(&clone->ds_rwlock, RW_WRITER);
3304 	if (!RW_WRITE_HELD(&origin_head->ds_rwlock) &&
3305 	    !rw_tryenter(&origin_head->ds_rwlock, RW_WRITER)) {
3306 		rw_exit(&clone->ds_rwlock);
3307 		rw_enter(&origin_head->ds_rwlock, RW_WRITER);
3308 		if (!rw_tryenter(&clone->ds_rwlock, RW_WRITER)) {
3309 			rw_exit(&origin_head->ds_rwlock);
3310 			goto retry;
3311 		}
3312 	}
3313 	csa.cds = clone;
3314 	csa.ohds = origin_head;
3315 	csa.force = force;
3316 	error = dsl_sync_task_do(clone->ds_dir->dd_pool,
3317 	    dsl_dataset_clone_swap_check,
3318 	    dsl_dataset_clone_swap_sync, &csa, NULL, 9);
3319 	return (error);
3320 }
3321 
3322 /*
3323  * Given a pool name and a dataset object number in that pool,
3324  * return the name of that dataset.
3325  */
3326 int
3327 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
3328 {
3329 	spa_t *spa;
3330 	dsl_pool_t *dp;
3331 	dsl_dataset_t *ds;
3332 	int error;
3333 
3334 	if ((error = spa_open(pname, &spa, FTAG)) != 0)
3335 		return (error);
3336 	dp = spa_get_dsl(spa);
3337 	rw_enter(&dp->dp_config_rwlock, RW_READER);
3338 	if ((error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds)) == 0) {
3339 		dsl_dataset_name(ds, buf);
3340 		dsl_dataset_rele(ds, FTAG);
3341 	}
3342 	rw_exit(&dp->dp_config_rwlock);
3343 	spa_close(spa, FTAG);
3344 
3345 	return (error);
3346 }
3347 
3348 int
3349 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
3350     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
3351 {
3352 	int error = 0;
3353 
3354 	ASSERT3S(asize, >, 0);
3355 
3356 	/*
3357 	 * *ref_rsrv is the portion of asize that will come from any
3358 	 * unconsumed refreservation space.
3359 	 */
3360 	*ref_rsrv = 0;
3361 
3362 	mutex_enter(&ds->ds_lock);
3363 	/*
3364 	 * Make a space adjustment for reserved bytes.
3365 	 */
3366 	if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes) {
3367 		ASSERT3U(*used, >=,
3368 		    ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
3369 		*used -= (ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
3370 		*ref_rsrv =
3371 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
3372 	}
3373 
3374 	if (!check_quota || ds->ds_quota == 0) {
3375 		mutex_exit(&ds->ds_lock);
3376 		return (0);
3377 	}
3378 	/*
3379 	 * If they are requesting more space, and our current estimate
3380 	 * is over quota, they get to try again unless the actual
3381 	 * on-disk is over quota and there are no pending changes (which
3382 	 * may free up space for us).
3383 	 */
3384 	if (ds->ds_phys->ds_referenced_bytes + inflight >= ds->ds_quota) {
3385 		if (inflight > 0 ||
3386 		    ds->ds_phys->ds_referenced_bytes < ds->ds_quota)
3387 			error = ERESTART;
3388 		else
3389 			error = EDQUOT;
3390 	}
3391 	mutex_exit(&ds->ds_lock);
3392 
3393 	return (error);
3394 }
3395 
3396 /* ARGSUSED */
3397 static int
3398 dsl_dataset_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
3399 {
3400 	dsl_dataset_t *ds = arg1;
3401 	dsl_prop_setarg_t *psa = arg2;
3402 	int err;
3403 
3404 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_REFQUOTA)
3405 		return (ENOTSUP);
3406 
3407 	if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
3408 		return (err);
3409 
3410 	if (psa->psa_effective_value == 0)
3411 		return (0);
3412 
3413 	if (psa->psa_effective_value < ds->ds_phys->ds_referenced_bytes ||
3414 	    psa->psa_effective_value < ds->ds_reserved)
3415 		return (ENOSPC);
3416 
3417 	return (0);
3418 }
3419 
3420 extern void dsl_prop_set_sync(void *, void *, dmu_tx_t *);
3421 
3422 void
3423 dsl_dataset_set_quota_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3424 {
3425 	dsl_dataset_t *ds = arg1;
3426 	dsl_prop_setarg_t *psa = arg2;
3427 	uint64_t effective_value = psa->psa_effective_value;
3428 
3429 	dsl_prop_set_sync(ds, psa, tx);
3430 	DSL_PROP_CHECK_PREDICTION(ds->ds_dir, psa);
3431 
3432 	if (ds->ds_quota != effective_value) {
3433 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3434 		ds->ds_quota = effective_value;
3435 
3436 		spa_history_log_internal_ds(ds, "set refquota", tx,
3437 		    "refquota=%lld", (longlong_t)ds->ds_quota);
3438 	}
3439 }
3440 
3441 int
3442 dsl_dataset_set_quota(const char *dsname, zprop_source_t source, uint64_t quota)
3443 {
3444 	dsl_dataset_t *ds;
3445 	dsl_prop_setarg_t psa;
3446 	int err;
3447 
3448 	dsl_prop_setarg_init_uint64(&psa, "refquota", source, &quota);
3449 
3450 	err = dsl_dataset_hold(dsname, FTAG, &ds);
3451 	if (err)
3452 		return (err);
3453 
3454 	/*
3455 	 * If someone removes a file, then tries to set the quota, we
3456 	 * want to make sure the file freeing takes effect.
3457 	 */
3458 	txg_wait_open(ds->ds_dir->dd_pool, 0);
3459 
3460 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
3461 	    dsl_dataset_set_quota_check, dsl_dataset_set_quota_sync,
3462 	    ds, &psa, 0);
3463 
3464 	dsl_dataset_rele(ds, FTAG);
3465 	return (err);
3466 }
3467 
3468 static int
3469 dsl_dataset_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
3470 {
3471 	dsl_dataset_t *ds = arg1;
3472 	dsl_prop_setarg_t *psa = arg2;
3473 	uint64_t effective_value;
3474 	uint64_t unique;
3475 	int err;
3476 
3477 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) <
3478 	    SPA_VERSION_REFRESERVATION)
3479 		return (ENOTSUP);
3480 
3481 	if (dsl_dataset_is_snapshot(ds))
3482 		return (EINVAL);
3483 
3484 	if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
3485 		return (err);
3486 
3487 	effective_value = psa->psa_effective_value;
3488 
3489 	/*
3490 	 * If we are doing the preliminary check in open context, the
3491 	 * space estimates may be inaccurate.
3492 	 */
3493 	if (!dmu_tx_is_syncing(tx))
3494 		return (0);
3495 
3496 	mutex_enter(&ds->ds_lock);
3497 	if (!DS_UNIQUE_IS_ACCURATE(ds))
3498 		dsl_dataset_recalc_head_uniq(ds);
3499 	unique = ds->ds_phys->ds_unique_bytes;
3500 	mutex_exit(&ds->ds_lock);
3501 
3502 	if (MAX(unique, effective_value) > MAX(unique, ds->ds_reserved)) {
3503 		uint64_t delta = MAX(unique, effective_value) -
3504 		    MAX(unique, ds->ds_reserved);
3505 
3506 		if (delta > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
3507 			return (ENOSPC);
3508 		if (ds->ds_quota > 0 &&
3509 		    effective_value > ds->ds_quota)
3510 			return (ENOSPC);
3511 	}
3512 
3513 	return (0);
3514 }
3515 
3516 static void
3517 dsl_dataset_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3518 {
3519 	dsl_dataset_t *ds = arg1;
3520 	dsl_prop_setarg_t *psa = arg2;
3521 	uint64_t effective_value = psa->psa_effective_value;
3522 	uint64_t unique;
3523 	int64_t delta;
3524 
3525 	dsl_prop_set_sync(ds, psa, tx);
3526 	DSL_PROP_CHECK_PREDICTION(ds->ds_dir, psa);
3527 
3528 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
3529 
3530 	mutex_enter(&ds->ds_dir->dd_lock);
3531 	mutex_enter(&ds->ds_lock);
3532 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3533 	unique = ds->ds_phys->ds_unique_bytes;
3534 	delta = MAX(0, (int64_t)(effective_value - unique)) -
3535 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
3536 	ds->ds_reserved = effective_value;
3537 	mutex_exit(&ds->ds_lock);
3538 
3539 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3540 	mutex_exit(&ds->ds_dir->dd_lock);
3541 
3542 	spa_history_log_internal_ds(ds, "set refreservation", tx,
3543 	    "refreservation=%lld", (longlong_t)effective_value);
3544 }
3545 
3546 int
3547 dsl_dataset_set_reservation(const char *dsname, zprop_source_t source,
3548     uint64_t reservation)
3549 {
3550 	dsl_dataset_t *ds;
3551 	dsl_prop_setarg_t psa;
3552 	int err;
3553 
3554 	dsl_prop_setarg_init_uint64(&psa, "refreservation", source,
3555 	    &reservation);
3556 
3557 	err = dsl_dataset_hold(dsname, FTAG, &ds);
3558 	if (err)
3559 		return (err);
3560 
3561 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
3562 	    dsl_dataset_set_reservation_check,
3563 	    dsl_dataset_set_reservation_sync, ds, &psa, 0);
3564 
3565 	dsl_dataset_rele(ds, FTAG);
3566 	return (err);
3567 }
3568 
3569 typedef struct zfs_hold_cleanup_arg {
3570 	dsl_pool_t *dp;
3571 	uint64_t dsobj;
3572 	char htag[MAXNAMELEN];
3573 } zfs_hold_cleanup_arg_t;
3574 
3575 static void
3576 dsl_dataset_user_release_onexit(void *arg)
3577 {
3578 	zfs_hold_cleanup_arg_t *ca = arg;
3579 
3580 	(void) dsl_dataset_user_release_tmp(ca->dp, ca->dsobj, ca->htag,
3581 	    B_TRUE);
3582 	kmem_free(ca, sizeof (zfs_hold_cleanup_arg_t));
3583 }
3584 
3585 void
3586 dsl_register_onexit_hold_cleanup(dsl_dataset_t *ds, const char *htag,
3587     minor_t minor)
3588 {
3589 	zfs_hold_cleanup_arg_t *ca;
3590 
3591 	ca = kmem_alloc(sizeof (zfs_hold_cleanup_arg_t), KM_SLEEP);
3592 	ca->dp = ds->ds_dir->dd_pool;
3593 	ca->dsobj = ds->ds_object;
3594 	(void) strlcpy(ca->htag, htag, sizeof (ca->htag));
3595 	VERIFY3U(0, ==, zfs_onexit_add_cb(minor,
3596 	    dsl_dataset_user_release_onexit, ca, NULL));
3597 }
3598 
3599 /*
3600  * If you add new checks here, you may need to add
3601  * additional checks to the "temporary" case in
3602  * snapshot_check() in dmu_objset.c.
3603  */
3604 static int
3605 dsl_dataset_user_hold_check(void *arg1, void *arg2, dmu_tx_t *tx)
3606 {
3607 	dsl_dataset_t *ds = arg1;
3608 	struct dsl_ds_holdarg *ha = arg2;
3609 	const char *htag = ha->htag;
3610 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3611 	int error = 0;
3612 
3613 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_USERREFS)
3614 		return (ENOTSUP);
3615 
3616 	if (!dsl_dataset_is_snapshot(ds))
3617 		return (EINVAL);
3618 
3619 	/* tags must be unique */
3620 	mutex_enter(&ds->ds_lock);
3621 	if (ds->ds_phys->ds_userrefs_obj) {
3622 		error = zap_lookup(mos, ds->ds_phys->ds_userrefs_obj, htag,
3623 		    8, 1, tx);
3624 		if (error == 0)
3625 			error = EEXIST;
3626 		else if (error == ENOENT)
3627 			error = 0;
3628 	}
3629 	mutex_exit(&ds->ds_lock);
3630 
3631 	if (error == 0 && ha->temphold &&
3632 	    strlen(htag) + MAX_TAG_PREFIX_LEN >= MAXNAMELEN)
3633 		error = E2BIG;
3634 
3635 	return (error);
3636 }
3637 
3638 void
3639 dsl_dataset_user_hold_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3640 {
3641 	dsl_dataset_t *ds = arg1;
3642 	struct dsl_ds_holdarg *ha = arg2;
3643 	const char *htag = ha->htag;
3644 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
3645 	objset_t *mos = dp->dp_meta_objset;
3646 	uint64_t now = gethrestime_sec();
3647 	uint64_t zapobj;
3648 
3649 	mutex_enter(&ds->ds_lock);
3650 	if (ds->ds_phys->ds_userrefs_obj == 0) {
3651 		/*
3652 		 * This is the first user hold for this dataset.  Create
3653 		 * the userrefs zap object.
3654 		 */
3655 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3656 		zapobj = ds->ds_phys->ds_userrefs_obj =
3657 		    zap_create(mos, DMU_OT_USERREFS, DMU_OT_NONE, 0, tx);
3658 	} else {
3659 		zapobj = ds->ds_phys->ds_userrefs_obj;
3660 	}
3661 	ds->ds_userrefs++;
3662 	mutex_exit(&ds->ds_lock);
3663 
3664 	VERIFY(0 == zap_add(mos, zapobj, htag, 8, 1, &now, tx));
3665 
3666 	if (ha->temphold) {
3667 		VERIFY(0 == dsl_pool_user_hold(dp, ds->ds_object,
3668 		    htag, &now, tx));
3669 	}
3670 
3671 	spa_history_log_internal_ds(ds, "hold", tx,
3672 	    "tag = %s temp = %d holds now = %llu",
3673 	    htag, (int)ha->temphold, ds->ds_userrefs);
3674 }
3675 
3676 static int
3677 dsl_dataset_user_hold_one(const char *dsname, void *arg)
3678 {
3679 	struct dsl_ds_holdarg *ha = arg;
3680 	dsl_dataset_t *ds;
3681 	int error;
3682 	char *name;
3683 
3684 	/* alloc a buffer to hold dsname@snapname plus terminating NULL */
3685 	name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3686 	error = dsl_dataset_hold(name, ha->dstg, &ds);
3687 	strfree(name);
3688 	if (error == 0) {
3689 		ha->gotone = B_TRUE;
3690 		dsl_sync_task_create(ha->dstg, dsl_dataset_user_hold_check,
3691 		    dsl_dataset_user_hold_sync, ds, ha, 0);
3692 	} else if (error == ENOENT && ha->recursive) {
3693 		error = 0;
3694 	} else {
3695 		(void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3696 	}
3697 	return (error);
3698 }
3699 
3700 int
3701 dsl_dataset_user_hold_for_send(dsl_dataset_t *ds, char *htag,
3702     boolean_t temphold)
3703 {
3704 	struct dsl_ds_holdarg *ha;
3705 	int error;
3706 
3707 	ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
3708 	ha->htag = htag;
3709 	ha->temphold = temphold;
3710 	error = dsl_sync_task_do(ds->ds_dir->dd_pool,
3711 	    dsl_dataset_user_hold_check, dsl_dataset_user_hold_sync,
3712 	    ds, ha, 0);
3713 	kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3714 
3715 	return (error);
3716 }
3717 
3718 int
3719 dsl_dataset_user_hold(char *dsname, char *snapname, char *htag,
3720     boolean_t recursive, boolean_t temphold, int cleanup_fd)
3721 {
3722 	struct dsl_ds_holdarg *ha;
3723 	dsl_sync_task_t *dst;
3724 	spa_t *spa;
3725 	int error;
3726 	minor_t minor = 0;
3727 
3728 	if (cleanup_fd != -1) {
3729 		/* Currently we only support cleanup-on-exit of tempholds. */
3730 		if (!temphold)
3731 			return (EINVAL);
3732 		error = zfs_onexit_fd_hold(cleanup_fd, &minor);
3733 		if (error)
3734 			return (error);
3735 	}
3736 
3737 	ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
3738 
3739 	(void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3740 
3741 	error = spa_open(dsname, &spa, FTAG);
3742 	if (error) {
3743 		kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3744 		if (cleanup_fd != -1)
3745 			zfs_onexit_fd_rele(cleanup_fd);
3746 		return (error);
3747 	}
3748 
3749 	ha->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
3750 	ha->htag = htag;
3751 	ha->snapname = snapname;
3752 	ha->recursive = recursive;
3753 	ha->temphold = temphold;
3754 
3755 	if (recursive) {
3756 		error = dmu_objset_find(dsname, dsl_dataset_user_hold_one,
3757 		    ha, DS_FIND_CHILDREN);
3758 	} else {
3759 		error = dsl_dataset_user_hold_one(dsname, ha);
3760 	}
3761 	if (error == 0)
3762 		error = dsl_sync_task_group_wait(ha->dstg);
3763 
3764 	for (dst = list_head(&ha->dstg->dstg_tasks); dst;
3765 	    dst = list_next(&ha->dstg->dstg_tasks, dst)) {
3766 		dsl_dataset_t *ds = dst->dst_arg1;
3767 
3768 		if (dst->dst_err) {
3769 			dsl_dataset_name(ds, ha->failed);
3770 			*strchr(ha->failed, '@') = '\0';
3771 		} else if (error == 0 && minor != 0 && temphold) {
3772 			/*
3773 			 * If this hold is to be released upon process exit,
3774 			 * register that action now.
3775 			 */
3776 			dsl_register_onexit_hold_cleanup(ds, htag, minor);
3777 		}
3778 		dsl_dataset_rele(ds, ha->dstg);
3779 	}
3780 
3781 	if (error == 0 && recursive && !ha->gotone)
3782 		error = ENOENT;
3783 
3784 	if (error)
3785 		(void) strlcpy(dsname, ha->failed, sizeof (ha->failed));
3786 
3787 	dsl_sync_task_group_destroy(ha->dstg);
3788 
3789 	kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3790 	spa_close(spa, FTAG);
3791 	if (cleanup_fd != -1)
3792 		zfs_onexit_fd_rele(cleanup_fd);
3793 	return (error);
3794 }
3795 
3796 struct dsl_ds_releasearg {
3797 	dsl_dataset_t *ds;
3798 	const char *htag;
3799 	boolean_t own;		/* do we own or just hold ds? */
3800 };
3801 
3802 static int
3803 dsl_dataset_release_might_destroy(dsl_dataset_t *ds, const char *htag,
3804     boolean_t *might_destroy)
3805 {
3806 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3807 	uint64_t zapobj;
3808 	uint64_t tmp;
3809 	int error;
3810 
3811 	*might_destroy = B_FALSE;
3812 
3813 	mutex_enter(&ds->ds_lock);
3814 	zapobj = ds->ds_phys->ds_userrefs_obj;
3815 	if (zapobj == 0) {
3816 		/* The tag can't possibly exist */
3817 		mutex_exit(&ds->ds_lock);
3818 		return (ESRCH);
3819 	}
3820 
3821 	/* Make sure the tag exists */
3822 	error = zap_lookup(mos, zapobj, htag, 8, 1, &tmp);
3823 	if (error) {
3824 		mutex_exit(&ds->ds_lock);
3825 		if (error == ENOENT)
3826 			error = ESRCH;
3827 		return (error);
3828 	}
3829 
3830 	if (ds->ds_userrefs == 1 && ds->ds_phys->ds_num_children == 1 &&
3831 	    DS_IS_DEFER_DESTROY(ds))
3832 		*might_destroy = B_TRUE;
3833 
3834 	mutex_exit(&ds->ds_lock);
3835 	return (0);
3836 }
3837 
3838 static int
3839 dsl_dataset_user_release_check(void *arg1, void *tag, dmu_tx_t *tx)
3840 {
3841 	struct dsl_ds_releasearg *ra = arg1;
3842 	dsl_dataset_t *ds = ra->ds;
3843 	boolean_t might_destroy;
3844 	int error;
3845 
3846 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_USERREFS)
3847 		return (ENOTSUP);
3848 
3849 	error = dsl_dataset_release_might_destroy(ds, ra->htag, &might_destroy);
3850 	if (error)
3851 		return (error);
3852 
3853 	if (might_destroy) {
3854 		struct dsl_ds_destroyarg dsda = {0};
3855 
3856 		if (dmu_tx_is_syncing(tx)) {
3857 			/*
3858 			 * If we're not prepared to remove the snapshot,
3859 			 * we can't allow the release to happen right now.
3860 			 */
3861 			if (!ra->own)
3862 				return (EBUSY);
3863 		}
3864 		dsda.ds = ds;
3865 		dsda.releasing = B_TRUE;
3866 		return (dsl_dataset_destroy_check(&dsda, tag, tx));
3867 	}
3868 
3869 	return (0);
3870 }
3871 
3872 static void
3873 dsl_dataset_user_release_sync(void *arg1, void *tag, dmu_tx_t *tx)
3874 {
3875 	struct dsl_ds_releasearg *ra = arg1;
3876 	dsl_dataset_t *ds = ra->ds;
3877 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
3878 	objset_t *mos = dp->dp_meta_objset;
3879 	uint64_t zapobj;
3880 	uint64_t refs;
3881 	int error;
3882 
3883 	mutex_enter(&ds->ds_lock);
3884 	ds->ds_userrefs--;
3885 	refs = ds->ds_userrefs;
3886 	mutex_exit(&ds->ds_lock);
3887 	error = dsl_pool_user_release(dp, ds->ds_object, ra->htag, tx);
3888 	VERIFY(error == 0 || error == ENOENT);
3889 	zapobj = ds->ds_phys->ds_userrefs_obj;
3890 	VERIFY(0 == zap_remove(mos, zapobj, ra->htag, tx));
3891 
3892 	spa_history_log_internal_ds(ds, "release", tx,
3893 	    "tag = %s refs now = %lld", ra->htag, (longlong_t)refs);
3894 
3895 	if (ds->ds_userrefs == 0 && ds->ds_phys->ds_num_children == 1 &&
3896 	    DS_IS_DEFER_DESTROY(ds)) {
3897 		struct dsl_ds_destroyarg dsda = {0};
3898 
3899 		ASSERT(ra->own);
3900 		dsda.ds = ds;
3901 		dsda.releasing = B_TRUE;
3902 		/* We already did the destroy_check */
3903 		dsl_dataset_destroy_sync(&dsda, tag, tx);
3904 	}
3905 }
3906 
3907 static int
3908 dsl_dataset_user_release_one(const char *dsname, void *arg)
3909 {
3910 	struct dsl_ds_holdarg *ha = arg;
3911 	struct dsl_ds_releasearg *ra;
3912 	dsl_dataset_t *ds;
3913 	int error;
3914 	void *dtag = ha->dstg;
3915 	char *name;
3916 	boolean_t own = B_FALSE;
3917 	boolean_t might_destroy;
3918 
3919 	/* alloc a buffer to hold dsname@snapname, plus the terminating NULL */
3920 	name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3921 	error = dsl_dataset_hold(name, dtag, &ds);
3922 	strfree(name);
3923 	if (error == ENOENT && ha->recursive)
3924 		return (0);
3925 	(void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3926 	if (error)
3927 		return (error);
3928 
3929 	ha->gotone = B_TRUE;
3930 
3931 	ASSERT(dsl_dataset_is_snapshot(ds));
3932 
3933 	error = dsl_dataset_release_might_destroy(ds, ha->htag, &might_destroy);
3934 	if (error) {
3935 		dsl_dataset_rele(ds, dtag);
3936 		return (error);
3937 	}
3938 
3939 	if (might_destroy) {
3940 #ifdef _KERNEL
3941 		name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3942 		error = zfs_unmount_snap(name, NULL);
3943 		strfree(name);
3944 		if (error) {
3945 			dsl_dataset_rele(ds, dtag);
3946 			return (error);
3947 		}
3948 #endif
3949 		if (!dsl_dataset_tryown(ds, B_TRUE, dtag)) {
3950 			dsl_dataset_rele(ds, dtag);
3951 			return (EBUSY);
3952 		} else {
3953 			own = B_TRUE;
3954 			dsl_dataset_make_exclusive(ds, dtag);
3955 		}
3956 	}
3957 
3958 	ra = kmem_alloc(sizeof (struct dsl_ds_releasearg), KM_SLEEP);
3959 	ra->ds = ds;
3960 	ra->htag = ha->htag;
3961 	ra->own = own;
3962 	dsl_sync_task_create(ha->dstg, dsl_dataset_user_release_check,
3963 	    dsl_dataset_user_release_sync, ra, dtag, 0);
3964 
3965 	return (0);
3966 }
3967 
3968 int
3969 dsl_dataset_user_release(char *dsname, char *snapname, char *htag,
3970     boolean_t recursive)
3971 {
3972 	struct dsl_ds_holdarg *ha;
3973 	dsl_sync_task_t *dst;
3974 	spa_t *spa;
3975 	int error;
3976 
3977 top:
3978 	ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
3979 
3980 	(void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3981 
3982 	error = spa_open(dsname, &spa, FTAG);
3983 	if (error) {
3984 		kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3985 		return (error);
3986 	}
3987 
3988 	ha->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
3989 	ha->htag = htag;
3990 	ha->snapname = snapname;
3991 	ha->recursive = recursive;
3992 	if (recursive) {
3993 		error = dmu_objset_find(dsname, dsl_dataset_user_release_one,
3994 		    ha, DS_FIND_CHILDREN);
3995 	} else {
3996 		error = dsl_dataset_user_release_one(dsname, ha);
3997 	}
3998 	if (error == 0)
3999 		error = dsl_sync_task_group_wait(ha->dstg);
4000 
4001 	for (dst = list_head(&ha->dstg->dstg_tasks); dst;
4002 	    dst = list_next(&ha->dstg->dstg_tasks, dst)) {
4003 		struct dsl_ds_releasearg *ra = dst->dst_arg1;
4004 		dsl_dataset_t *ds = ra->ds;
4005 
4006 		if (dst->dst_err)
4007 			dsl_dataset_name(ds, ha->failed);
4008 
4009 		if (ra->own)
4010 			dsl_dataset_disown(ds, ha->dstg);
4011 		else
4012 			dsl_dataset_rele(ds, ha->dstg);
4013 
4014 		kmem_free(ra, sizeof (struct dsl_ds_releasearg));
4015 	}
4016 
4017 	if (error == 0 && recursive && !ha->gotone)
4018 		error = ENOENT;
4019 
4020 	if (error && error != EBUSY)
4021 		(void) strlcpy(dsname, ha->failed, sizeof (ha->failed));
4022 
4023 	dsl_sync_task_group_destroy(ha->dstg);
4024 	kmem_free(ha, sizeof (struct dsl_ds_holdarg));
4025 	spa_close(spa, FTAG);
4026 
4027 	/*
4028 	 * We can get EBUSY if we were racing with deferred destroy and
4029 	 * dsl_dataset_user_release_check() hadn't done the necessary
4030 	 * open context setup.  We can also get EBUSY if we're racing
4031 	 * with destroy and that thread is the ds_owner.  Either way
4032 	 * the busy condition should be transient, and we should retry
4033 	 * the release operation.
4034 	 */
4035 	if (error == EBUSY)
4036 		goto top;
4037 
4038 	return (error);
4039 }
4040 
4041 /*
4042  * Called at spa_load time (with retry == B_FALSE) to release a stale
4043  * temporary user hold. Also called by the onexit code (with retry == B_TRUE).
4044  */
4045 int
4046 dsl_dataset_user_release_tmp(dsl_pool_t *dp, uint64_t dsobj, char *htag,
4047     boolean_t retry)
4048 {
4049 	dsl_dataset_t *ds;
4050 	char *snap;
4051 	char *name;
4052 	int namelen;
4053 	int error;
4054 
4055 	do {
4056 		rw_enter(&dp->dp_config_rwlock, RW_READER);
4057 		error = dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds);
4058 		rw_exit(&dp->dp_config_rwlock);
4059 		if (error)
4060 			return (error);
4061 		namelen = dsl_dataset_namelen(ds)+1;
4062 		name = kmem_alloc(namelen, KM_SLEEP);
4063 		dsl_dataset_name(ds, name);
4064 		dsl_dataset_rele(ds, FTAG);
4065 
4066 		snap = strchr(name, '@');
4067 		*snap = '\0';
4068 		++snap;
4069 		error = dsl_dataset_user_release(name, snap, htag, B_FALSE);
4070 		kmem_free(name, namelen);
4071 
4072 		/*
4073 		 * The object can't have been destroyed because we have a hold,
4074 		 * but it might have been renamed, resulting in ENOENT.  Retry
4075 		 * if we've been requested to do so.
4076 		 *
4077 		 * It would be nice if we could use the dsobj all the way
4078 		 * through and avoid ENOENT entirely.  But we might need to
4079 		 * unmount the snapshot, and there's currently no way to lookup
4080 		 * a vfsp using a ZFS object id.
4081 		 */
4082 	} while ((error == ENOENT) && retry);
4083 
4084 	return (error);
4085 }
4086 
4087 int
4088 dsl_dataset_get_holds(const char *dsname, nvlist_t **nvp)
4089 {
4090 	dsl_dataset_t *ds;
4091 	int err;
4092 
4093 	err = dsl_dataset_hold(dsname, FTAG, &ds);
4094 	if (err)
4095 		return (err);
4096 
4097 	VERIFY(0 == nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP));
4098 	if (ds->ds_phys->ds_userrefs_obj != 0) {
4099 		zap_attribute_t *za;
4100 		zap_cursor_t zc;
4101 
4102 		za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
4103 		for (zap_cursor_init(&zc, ds->ds_dir->dd_pool->dp_meta_objset,
4104 		    ds->ds_phys->ds_userrefs_obj);
4105 		    zap_cursor_retrieve(&zc, za) == 0;
4106 		    zap_cursor_advance(&zc)) {
4107 			VERIFY(0 == nvlist_add_uint64(*nvp, za->za_name,
4108 			    za->za_first_integer));
4109 		}
4110 		zap_cursor_fini(&zc);
4111 		kmem_free(za, sizeof (zap_attribute_t));
4112 	}
4113 	dsl_dataset_rele(ds, FTAG);
4114 	return (0);
4115 }
4116 
4117 /*
4118  * Note, this function is used as the callback for dmu_objset_find().  We
4119  * always return 0 so that we will continue to find and process
4120  * inconsistent datasets, even if we encounter an error trying to
4121  * process one of them.
4122  */
4123 /* ARGSUSED */
4124 int
4125 dsl_destroy_inconsistent(const char *dsname, void *arg)
4126 {
4127 	dsl_dataset_t *ds;
4128 
4129 	if (dsl_dataset_own(dsname, B_TRUE, FTAG, &ds) == 0) {
4130 		if (DS_IS_INCONSISTENT(ds))
4131 			(void) dsl_dataset_destroy(ds, FTAG, B_FALSE);
4132 		else
4133 			dsl_dataset_disown(ds, FTAG);
4134 	}
4135 	return (0);
4136 }
4137 
4138 /*
4139  * Return (in *usedp) the amount of space written in new that is not
4140  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4141  * a snapshot before new, in new's filesystem (or its origin).  If not then
4142  * fail and return EINVAL.
4143  *
4144  * The written space is calculated by considering two components:  First, we
4145  * ignore any freed space, and calculate the written as new's used space
4146  * minus old's used space.  Next, we add in the amount of space that was freed
4147  * between the two snapshots, thus reducing new's used space relative to old's.
4148  * Specifically, this is the space that was born before old->ds_creation_txg,
4149  * and freed before new (ie. on new's deadlist or a previous deadlist).
4150  *
4151  * space freed                         [---------------------]
4152  * snapshots                       ---O-------O--------O-------O------
4153  *                                         oldsnap            new
4154  */
4155 int
4156 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4157     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4158 {
4159 	int err = 0;
4160 	uint64_t snapobj;
4161 	dsl_pool_t *dp = new->ds_dir->dd_pool;
4162 
4163 	*usedp = 0;
4164 	*usedp += new->ds_phys->ds_referenced_bytes;
4165 	*usedp -= oldsnap->ds_phys->ds_referenced_bytes;
4166 
4167 	*compp = 0;
4168 	*compp += new->ds_phys->ds_compressed_bytes;
4169 	*compp -= oldsnap->ds_phys->ds_compressed_bytes;
4170 
4171 	*uncompp = 0;
4172 	*uncompp += new->ds_phys->ds_uncompressed_bytes;
4173 	*uncompp -= oldsnap->ds_phys->ds_uncompressed_bytes;
4174 
4175 	rw_enter(&dp->dp_config_rwlock, RW_READER);
4176 	snapobj = new->ds_object;
4177 	while (snapobj != oldsnap->ds_object) {
4178 		dsl_dataset_t *snap;
4179 		uint64_t used, comp, uncomp;
4180 
4181 		if (snapobj == new->ds_object) {
4182 			snap = new;
4183 		} else {
4184 			err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4185 			if (err != 0)
4186 				break;
4187 		}
4188 
4189 		if (snap->ds_phys->ds_prev_snap_txg ==
4190 		    oldsnap->ds_phys->ds_creation_txg) {
4191 			/*
4192 			 * The blocks in the deadlist can not be born after
4193 			 * ds_prev_snap_txg, so get the whole deadlist space,
4194 			 * which is more efficient (especially for old-format
4195 			 * deadlists).  Unfortunately the deadlist code
4196 			 * doesn't have enough information to make this
4197 			 * optimization itself.
4198 			 */
4199 			dsl_deadlist_space(&snap->ds_deadlist,
4200 			    &used, &comp, &uncomp);
4201 		} else {
4202 			dsl_deadlist_space_range(&snap->ds_deadlist,
4203 			    0, oldsnap->ds_phys->ds_creation_txg,
4204 			    &used, &comp, &uncomp);
4205 		}
4206 		*usedp += used;
4207 		*compp += comp;
4208 		*uncompp += uncomp;
4209 
4210 		/*
4211 		 * If we get to the beginning of the chain of snapshots
4212 		 * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
4213 		 * was not a snapshot of/before new.
4214 		 */
4215 		snapobj = snap->ds_phys->ds_prev_snap_obj;
4216 		if (snap != new)
4217 			dsl_dataset_rele(snap, FTAG);
4218 		if (snapobj == 0) {
4219 			err = EINVAL;
4220 			break;
4221 		}
4222 
4223 	}
4224 	rw_exit(&dp->dp_config_rwlock);
4225 	return (err);
4226 }
4227 
4228 /*
4229  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4230  * lastsnap, and all snapshots in between are deleted.
4231  *
4232  * blocks that would be freed            [---------------------------]
4233  * snapshots                       ---O-------O--------O-------O--------O
4234  *                                        firstsnap        lastsnap
4235  *
4236  * This is the set of blocks that were born after the snap before firstsnap,
4237  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4238  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4239  * We calculate this by iterating over the relevant deadlists (from the snap
4240  * after lastsnap, backward to the snap after firstsnap), summing up the
4241  * space on the deadlist that was born after the snap before firstsnap.
4242  */
4243 int
4244 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4245     dsl_dataset_t *lastsnap,
4246     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4247 {
4248 	int err = 0;
4249 	uint64_t snapobj;
4250 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4251 
4252 	ASSERT(dsl_dataset_is_snapshot(firstsnap));
4253 	ASSERT(dsl_dataset_is_snapshot(lastsnap));
4254 
4255 	/*
4256 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
4257 	 * is before lastsnap.
4258 	 */
4259 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
4260 	    firstsnap->ds_phys->ds_creation_txg >
4261 	    lastsnap->ds_phys->ds_creation_txg)
4262 		return (EINVAL);
4263 
4264 	*usedp = *compp = *uncompp = 0;
4265 
4266 	rw_enter(&dp->dp_config_rwlock, RW_READER);
4267 	snapobj = lastsnap->ds_phys->ds_next_snap_obj;
4268 	while (snapobj != firstsnap->ds_object) {
4269 		dsl_dataset_t *ds;
4270 		uint64_t used, comp, uncomp;
4271 
4272 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4273 		if (err != 0)
4274 			break;
4275 
4276 		dsl_deadlist_space_range(&ds->ds_deadlist,
4277 		    firstsnap->ds_phys->ds_prev_snap_txg, UINT64_MAX,
4278 		    &used, &comp, &uncomp);
4279 		*usedp += used;
4280 		*compp += comp;
4281 		*uncompp += uncomp;
4282 
4283 		snapobj = ds->ds_phys->ds_prev_snap_obj;
4284 		ASSERT3U(snapobj, !=, 0);
4285 		dsl_dataset_rele(ds, FTAG);
4286 	}
4287 	rw_exit(&dp->dp_config_rwlock);
4288 	return (err);
4289 }
4290