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