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