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