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