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