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