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