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