xref: /illumos-gate/usr/src/uts/common/fs/zfs/dsl_dataset.c (revision 68038c2cd7751a1fc2b5c55e38609e137fa80807)
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 	rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
982 	err = dsl_dir_open_obj(dd->dd_pool, dd->dd_object, NULL, FTAG, &dd);
983 	rw_exit(&dd->dd_pool->dp_config_rwlock);
984 
985 	if (err)
986 		goto out;
987 
988 	if (ds->ds_user_ptr) {
989 		/*
990 		 * We need to sync out all in-flight IO before we try
991 		 * to evict (the dataset evict func is trying to clear
992 		 * the cached entries for this dataset in the ARC).
993 		 */
994 		txg_wait_synced(dd->dd_pool, 0);
995 	}
996 
997 	/*
998 	 * Blow away the dsl_dir + head dataset.
999 	 */
1000 	dsl_dataset_make_exclusive(ds, tag);
1001 	if (ds->ds_user_ptr) {
1002 		ds->ds_user_evict_func(ds, ds->ds_user_ptr);
1003 		ds->ds_user_ptr = NULL;
1004 	}
1005 	dstg = dsl_sync_task_group_create(ds->ds_dir->dd_pool);
1006 	dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
1007 	    dsl_dataset_destroy_sync, ds, tag, 0);
1008 	dsl_sync_task_create(dstg, dsl_dir_destroy_check,
1009 	    dsl_dir_destroy_sync, dd, FTAG, 0);
1010 	err = dsl_sync_task_group_wait(dstg);
1011 	dsl_sync_task_group_destroy(dstg);
1012 	/* if it is successful, dsl_dir_destroy_sync will close the dd */
1013 	if (err)
1014 		dsl_dir_close(dd, FTAG);
1015 out:
1016 	dsl_dataset_disown(ds, tag);
1017 	return (err);
1018 }
1019 
1020 int
1021 dsl_dataset_rollback(dsl_dataset_t *ds, dmu_objset_type_t ost)
1022 {
1023 	ASSERT(ds->ds_owner);
1024 
1025 	return (dsl_sync_task_do(ds->ds_dir->dd_pool,
1026 	    dsl_dataset_rollback_check, dsl_dataset_rollback_sync,
1027 	    ds, &ost, 0));
1028 }
1029 
1030 void *
1031 dsl_dataset_set_user_ptr(dsl_dataset_t *ds,
1032     void *p, dsl_dataset_evict_func_t func)
1033 {
1034 	void *old;
1035 
1036 	mutex_enter(&ds->ds_lock);
1037 	old = ds->ds_user_ptr;
1038 	if (old == NULL) {
1039 		ds->ds_user_ptr = p;
1040 		ds->ds_user_evict_func = func;
1041 	}
1042 	mutex_exit(&ds->ds_lock);
1043 	return (old);
1044 }
1045 
1046 void *
1047 dsl_dataset_get_user_ptr(dsl_dataset_t *ds)
1048 {
1049 	return (ds->ds_user_ptr);
1050 }
1051 
1052 
1053 blkptr_t *
1054 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1055 {
1056 	return (&ds->ds_phys->ds_bp);
1057 }
1058 
1059 void
1060 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
1061 {
1062 	ASSERT(dmu_tx_is_syncing(tx));
1063 	/* If it's the meta-objset, set dp_meta_rootbp */
1064 	if (ds == NULL) {
1065 		tx->tx_pool->dp_meta_rootbp = *bp;
1066 	} else {
1067 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1068 		ds->ds_phys->ds_bp = *bp;
1069 	}
1070 }
1071 
1072 spa_t *
1073 dsl_dataset_get_spa(dsl_dataset_t *ds)
1074 {
1075 	return (ds->ds_dir->dd_pool->dp_spa);
1076 }
1077 
1078 void
1079 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1080 {
1081 	dsl_pool_t *dp;
1082 
1083 	if (ds == NULL) /* this is the meta-objset */
1084 		return;
1085 
1086 	ASSERT(ds->ds_user_ptr != NULL);
1087 
1088 	if (ds->ds_phys->ds_next_snap_obj != 0)
1089 		panic("dirtying snapshot!");
1090 
1091 	dp = ds->ds_dir->dd_pool;
1092 
1093 	if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg) == 0) {
1094 		/* up the hold count until we can be written out */
1095 		dmu_buf_add_ref(ds->ds_dbuf, ds);
1096 	}
1097 }
1098 
1099 /*
1100  * The unique space in the head dataset can be calculated by subtracting
1101  * the space used in the most recent snapshot, that is still being used
1102  * in this file system, from the space currently in use.  To figure out
1103  * the space in the most recent snapshot still in use, we need to take
1104  * the total space used in the snapshot and subtract out the space that
1105  * has been freed up since the snapshot was taken.
1106  */
1107 static void
1108 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1109 {
1110 	uint64_t mrs_used;
1111 	uint64_t dlused, dlcomp, dluncomp;
1112 
1113 	ASSERT(ds->ds_object == ds->ds_dir->dd_phys->dd_head_dataset_obj);
1114 
1115 	if (ds->ds_phys->ds_prev_snap_obj != 0)
1116 		mrs_used = ds->ds_prev->ds_phys->ds_used_bytes;
1117 	else
1118 		mrs_used = 0;
1119 
1120 	VERIFY(0 == bplist_space(&ds->ds_deadlist, &dlused, &dlcomp,
1121 	    &dluncomp));
1122 
1123 	ASSERT3U(dlused, <=, mrs_used);
1124 	ds->ds_phys->ds_unique_bytes =
1125 	    ds->ds_phys->ds_used_bytes - (mrs_used - dlused);
1126 
1127 	if (!DS_UNIQUE_IS_ACCURATE(ds) &&
1128 	    spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1129 	    SPA_VERSION_UNIQUE_ACCURATE)
1130 		ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1131 }
1132 
1133 static uint64_t
1134 dsl_dataset_unique(dsl_dataset_t *ds)
1135 {
1136 	if (!DS_UNIQUE_IS_ACCURATE(ds) && !dsl_dataset_is_snapshot(ds))
1137 		dsl_dataset_recalc_head_uniq(ds);
1138 
1139 	return (ds->ds_phys->ds_unique_bytes);
1140 }
1141 
1142 struct killarg {
1143 	int64_t *usedp;
1144 	int64_t *compressedp;
1145 	int64_t *uncompressedp;
1146 	zio_t *zio;
1147 	dmu_tx_t *tx;
1148 };
1149 
1150 static int
1151 kill_blkptr(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1152 {
1153 	struct killarg *ka = arg;
1154 	blkptr_t *bp = &bc->bc_blkptr;
1155 
1156 	ASSERT3U(bc->bc_errno, ==, 0);
1157 
1158 	/*
1159 	 * Since this callback is not called concurrently, no lock is
1160 	 * needed on the accounting values.
1161 	 */
1162 	*ka->usedp += bp_get_dasize(spa, bp);
1163 	*ka->compressedp += BP_GET_PSIZE(bp);
1164 	*ka->uncompressedp += BP_GET_UCSIZE(bp);
1165 	/* XXX check for EIO? */
1166 	(void) arc_free(ka->zio, spa, ka->tx->tx_txg, bp, NULL, NULL,
1167 	    ARC_NOWAIT);
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 	/* Zero out the deadlist. */
1231 	bplist_close(&ds->ds_deadlist);
1232 	bplist_destroy(mos, ds->ds_phys->ds_deadlist_obj, tx);
1233 	ds->ds_phys->ds_deadlist_obj =
1234 	    bplist_create(mos, DSL_DEADLIST_BLOCKSIZE, tx);
1235 	VERIFY(0 == bplist_open(&ds->ds_deadlist, mos,
1236 	    ds->ds_phys->ds_deadlist_obj));
1237 
1238 	{
1239 		/* Free blkptrs that we gave birth to */
1240 		zio_t *zio;
1241 		int64_t used = 0, compressed = 0, uncompressed = 0;
1242 		struct killarg ka;
1243 		int64_t delta;
1244 
1245 		zio = zio_root(tx->tx_pool->dp_spa, NULL, NULL,
1246 		    ZIO_FLAG_MUSTSUCCEED);
1247 		ka.usedp = &used;
1248 		ka.compressedp = &compressed;
1249 		ka.uncompressedp = &uncompressed;
1250 		ka.zio = zio;
1251 		ka.tx = tx;
1252 		(void) traverse_dsl_dataset(ds, ds->ds_phys->ds_prev_snap_txg,
1253 		    ADVANCE_POST, kill_blkptr, &ka);
1254 		(void) zio_wait(zio);
1255 
1256 		/* only deduct space beyond any refreservation */
1257 		delta = parent_delta(ds, -used);
1258 		dsl_dir_diduse_space(ds->ds_dir,
1259 		    delta, -compressed, -uncompressed, tx);
1260 	}
1261 
1262 	if (ds->ds_prev) {
1263 		/* Change our contents to that of the prev snapshot */
1264 		ASSERT3U(ds->ds_prev->ds_object, ==,
1265 		    ds->ds_phys->ds_prev_snap_obj);
1266 		ds->ds_phys->ds_bp = ds->ds_prev->ds_phys->ds_bp;
1267 		ds->ds_phys->ds_used_bytes =
1268 		    ds->ds_prev->ds_phys->ds_used_bytes;
1269 		ds->ds_phys->ds_compressed_bytes =
1270 		    ds->ds_prev->ds_phys->ds_compressed_bytes;
1271 		ds->ds_phys->ds_uncompressed_bytes =
1272 		    ds->ds_prev->ds_phys->ds_uncompressed_bytes;
1273 		ds->ds_phys->ds_flags = ds->ds_prev->ds_phys->ds_flags;
1274 		ds->ds_phys->ds_unique_bytes = 0;
1275 
1276 		if (ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object) {
1277 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1278 			ds->ds_prev->ds_phys->ds_unique_bytes = 0;
1279 		}
1280 	} else {
1281 		/* Zero out our contents, recreate objset */
1282 		bzero(&ds->ds_phys->ds_bp, sizeof (blkptr_t));
1283 		ds->ds_phys->ds_used_bytes = 0;
1284 		ds->ds_phys->ds_compressed_bytes = 0;
1285 		ds->ds_phys->ds_uncompressed_bytes = 0;
1286 		ds->ds_phys->ds_flags = 0;
1287 		ds->ds_phys->ds_unique_bytes = 0;
1288 		(void) dmu_objset_create_impl(ds->ds_dir->dd_pool->dp_spa, ds,
1289 		    &ds->ds_phys->ds_bp, *ost, tx);
1290 	}
1291 
1292 	spa_history_internal_log(LOG_DS_ROLLBACK, ds->ds_dir->dd_pool->dp_spa,
1293 	    tx, cr, "dataset = %llu", ds->ds_object);
1294 }
1295 
1296 /* ARGSUSED */
1297 static int
1298 dsl_dataset_destroy_begin_check(void *arg1, void *arg2, dmu_tx_t *tx)
1299 {
1300 	dsl_dataset_t *ds = arg1;
1301 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1302 	uint64_t count;
1303 	int err;
1304 
1305 	/*
1306 	 * Can't delete a head dataset if there are snapshots of it.
1307 	 * (Except if the only snapshots are from the branch we cloned
1308 	 * from.)
1309 	 */
1310 	if (ds->ds_prev != NULL &&
1311 	    ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1312 		return (EINVAL);
1313 
1314 	/*
1315 	 * This is really a dsl_dir thing, but check it here so that
1316 	 * we'll be less likely to leave this dataset inconsistent &
1317 	 * nearly destroyed.
1318 	 */
1319 	err = zap_count(mos, ds->ds_dir->dd_phys->dd_child_dir_zapobj, &count);
1320 	if (err)
1321 		return (err);
1322 	if (count != 0)
1323 		return (EEXIST);
1324 
1325 	return (0);
1326 }
1327 
1328 /* ARGSUSED */
1329 static void
1330 dsl_dataset_destroy_begin_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1331 {
1332 	dsl_dataset_t *ds = arg1;
1333 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1334 
1335 	/* Mark it as inconsistent on-disk, in case we crash */
1336 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1337 	ds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;
1338 
1339 	spa_history_internal_log(LOG_DS_DESTROY_BEGIN, dp->dp_spa, tx,
1340 	    cr, "dataset = %llu", ds->ds_object);
1341 }
1342 
1343 /* ARGSUSED */
1344 int
1345 dsl_dataset_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
1346 {
1347 	dsl_dataset_t *ds = arg1;
1348 
1349 	/* we have an owner hold, so noone else can destroy us */
1350 	ASSERT(!DSL_DATASET_IS_DESTROYED(ds));
1351 
1352 	/* Can't delete a branch point. */
1353 	if (ds->ds_phys->ds_num_children > 1)
1354 		return (EEXIST);
1355 
1356 	/*
1357 	 * Can't delete a head dataset if there are snapshots of it.
1358 	 * (Except if the only snapshots are from the branch we cloned
1359 	 * from.)
1360 	 */
1361 	if (ds->ds_prev != NULL &&
1362 	    ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1363 		return (EINVAL);
1364 
1365 	/*
1366 	 * If we made changes this txg, traverse_dsl_dataset won't find
1367 	 * them.  Try again.
1368 	 */
1369 	if (ds->ds_phys->ds_bp.blk_birth >= tx->tx_txg)
1370 		return (EAGAIN);
1371 
1372 	/* XXX we should do some i/o error checking... */
1373 	return (0);
1374 }
1375 
1376 struct refsarg {
1377 	kmutex_t lock;
1378 	boolean_t gone;
1379 	kcondvar_t cv;
1380 };
1381 
1382 /* ARGSUSED */
1383 static void
1384 dsl_dataset_refs_gone(dmu_buf_t *db, void *argv)
1385 {
1386 	struct refsarg *arg = argv;
1387 
1388 	mutex_enter(&arg->lock);
1389 	arg->gone = TRUE;
1390 	cv_signal(&arg->cv);
1391 	mutex_exit(&arg->lock);
1392 }
1393 
1394 static void
1395 dsl_dataset_drain_refs(dsl_dataset_t *ds, void *tag)
1396 {
1397 	struct refsarg arg;
1398 
1399 	mutex_init(&arg.lock, NULL, MUTEX_DEFAULT, NULL);
1400 	cv_init(&arg.cv, NULL, CV_DEFAULT, NULL);
1401 	arg.gone = FALSE;
1402 	(void) dmu_buf_update_user(ds->ds_dbuf, ds, &arg, &ds->ds_phys,
1403 	    dsl_dataset_refs_gone);
1404 	dmu_buf_rele(ds->ds_dbuf, tag);
1405 	mutex_enter(&arg.lock);
1406 	while (!arg.gone)
1407 		cv_wait(&arg.cv, &arg.lock);
1408 	ASSERT(arg.gone);
1409 	mutex_exit(&arg.lock);
1410 	ds->ds_dbuf = NULL;
1411 	ds->ds_phys = NULL;
1412 	mutex_destroy(&arg.lock);
1413 	cv_destroy(&arg.cv);
1414 }
1415 
1416 void
1417 dsl_dataset_destroy_sync(void *arg1, void *tag, cred_t *cr, dmu_tx_t *tx)
1418 {
1419 	dsl_dataset_t *ds = arg1;
1420 	int64_t used = 0, compressed = 0, uncompressed = 0;
1421 	zio_t *zio;
1422 	int err;
1423 	int after_branch_point = FALSE;
1424 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1425 	objset_t *mos = dp->dp_meta_objset;
1426 	dsl_dataset_t *ds_prev = NULL;
1427 	uint64_t obj;
1428 
1429 	ASSERT(ds->ds_owner);
1430 	ASSERT3U(ds->ds_phys->ds_num_children, <=, 1);
1431 	ASSERT(ds->ds_prev == NULL ||
1432 	    ds->ds_prev->ds_phys->ds_next_snap_obj != ds->ds_object);
1433 	ASSERT3U(ds->ds_phys->ds_bp.blk_birth, <=, tx->tx_txg);
1434 
1435 	/* signal any waiters that this dataset is going away */
1436 	mutex_enter(&ds->ds_lock);
1437 	ds->ds_owner = dsl_reaper;
1438 	cv_broadcast(&ds->ds_exclusive_cv);
1439 	mutex_exit(&ds->ds_lock);
1440 
1441 	/* Remove our reservation */
1442 	if (ds->ds_reserved != 0) {
1443 		uint64_t val = 0;
1444 		dsl_dataset_set_reservation_sync(ds, &val, cr, tx);
1445 		ASSERT3U(ds->ds_reserved, ==, 0);
1446 	}
1447 
1448 	ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
1449 
1450 	obj = ds->ds_object;
1451 
1452 	if (ds->ds_phys->ds_prev_snap_obj != 0) {
1453 		if (ds->ds_prev) {
1454 			ds_prev = ds->ds_prev;
1455 		} else {
1456 			VERIFY(0 == dsl_dataset_hold_obj(dp,
1457 			    ds->ds_phys->ds_prev_snap_obj, FTAG, &ds_prev));
1458 		}
1459 		after_branch_point =
1460 		    (ds_prev->ds_phys->ds_next_snap_obj != obj);
1461 
1462 		dmu_buf_will_dirty(ds_prev->ds_dbuf, tx);
1463 		if (after_branch_point &&
1464 		    ds->ds_phys->ds_next_snap_obj == 0) {
1465 			/* This clone is toast. */
1466 			ASSERT(ds_prev->ds_phys->ds_num_children > 1);
1467 			ds_prev->ds_phys->ds_num_children--;
1468 		} else if (!after_branch_point) {
1469 			ds_prev->ds_phys->ds_next_snap_obj =
1470 			    ds->ds_phys->ds_next_snap_obj;
1471 		}
1472 	}
1473 
1474 	zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1475 
1476 	if (ds->ds_phys->ds_next_snap_obj != 0) {
1477 		blkptr_t bp;
1478 		dsl_dataset_t *ds_next;
1479 		uint64_t itor = 0;
1480 		uint64_t old_unique;
1481 
1482 		spa_scrub_restart(dp->dp_spa, tx->tx_txg);
1483 
1484 		VERIFY(0 == dsl_dataset_hold_obj(dp,
1485 		    ds->ds_phys->ds_next_snap_obj, FTAG, &ds_next));
1486 		ASSERT3U(ds_next->ds_phys->ds_prev_snap_obj, ==, obj);
1487 
1488 		old_unique = dsl_dataset_unique(ds_next);
1489 
1490 		dmu_buf_will_dirty(ds_next->ds_dbuf, tx);
1491 		ds_next->ds_phys->ds_prev_snap_obj =
1492 		    ds->ds_phys->ds_prev_snap_obj;
1493 		ds_next->ds_phys->ds_prev_snap_txg =
1494 		    ds->ds_phys->ds_prev_snap_txg;
1495 		ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
1496 		    ds_prev ? ds_prev->ds_phys->ds_creation_txg : 0);
1497 
1498 		/*
1499 		 * Transfer to our deadlist (which will become next's
1500 		 * new deadlist) any entries from next's current
1501 		 * deadlist which were born before prev, and free the
1502 		 * other entries.
1503 		 *
1504 		 * XXX we're doing this long task with the config lock held
1505 		 */
1506 		while (bplist_iterate(&ds_next->ds_deadlist, &itor, &bp) == 0) {
1507 			if (bp.blk_birth <= ds->ds_phys->ds_prev_snap_txg) {
1508 				VERIFY(0 == bplist_enqueue(&ds->ds_deadlist,
1509 				    &bp, tx));
1510 				if (ds_prev && !after_branch_point &&
1511 				    bp.blk_birth >
1512 				    ds_prev->ds_phys->ds_prev_snap_txg) {
1513 					ds_prev->ds_phys->ds_unique_bytes +=
1514 					    bp_get_dasize(dp->dp_spa, &bp);
1515 				}
1516 			} else {
1517 				used += bp_get_dasize(dp->dp_spa, &bp);
1518 				compressed += BP_GET_PSIZE(&bp);
1519 				uncompressed += BP_GET_UCSIZE(&bp);
1520 				/* XXX check return value? */
1521 				(void) arc_free(zio, dp->dp_spa, tx->tx_txg,
1522 				    &bp, NULL, NULL, ARC_NOWAIT);
1523 			}
1524 		}
1525 
1526 		/* free next's deadlist */
1527 		bplist_close(&ds_next->ds_deadlist);
1528 		bplist_destroy(mos, ds_next->ds_phys->ds_deadlist_obj, tx);
1529 
1530 		/* set next's deadlist to our deadlist */
1531 		bplist_close(&ds->ds_deadlist);
1532 		ds_next->ds_phys->ds_deadlist_obj =
1533 		    ds->ds_phys->ds_deadlist_obj;
1534 		VERIFY(0 == bplist_open(&ds_next->ds_deadlist, mos,
1535 		    ds_next->ds_phys->ds_deadlist_obj));
1536 		ds->ds_phys->ds_deadlist_obj = 0;
1537 
1538 		if (ds_next->ds_phys->ds_next_snap_obj != 0) {
1539 			/*
1540 			 * Update next's unique to include blocks which
1541 			 * were previously shared by only this snapshot
1542 			 * and it.  Those blocks will be born after the
1543 			 * prev snap and before this snap, and will have
1544 			 * died after the next snap and before the one
1545 			 * after that (ie. be on the snap after next's
1546 			 * deadlist).
1547 			 *
1548 			 * XXX we're doing this long task with the
1549 			 * config lock held
1550 			 */
1551 			dsl_dataset_t *ds_after_next;
1552 
1553 			VERIFY(0 == dsl_dataset_hold_obj(dp,
1554 			    ds_next->ds_phys->ds_next_snap_obj,
1555 			    FTAG, &ds_after_next));
1556 			itor = 0;
1557 			while (bplist_iterate(&ds_after_next->ds_deadlist,
1558 			    &itor, &bp) == 0) {
1559 				if (bp.blk_birth >
1560 				    ds->ds_phys->ds_prev_snap_txg &&
1561 				    bp.blk_birth <=
1562 				    ds->ds_phys->ds_creation_txg) {
1563 					ds_next->ds_phys->ds_unique_bytes +=
1564 					    bp_get_dasize(dp->dp_spa, &bp);
1565 				}
1566 			}
1567 
1568 			dsl_dataset_rele(ds_after_next, FTAG);
1569 			ASSERT3P(ds_next->ds_prev, ==, NULL);
1570 		} else {
1571 			ASSERT3P(ds_next->ds_prev, ==, ds);
1572 			dsl_dataset_drop_ref(ds_next->ds_prev, ds_next);
1573 			ds_next->ds_prev = NULL;
1574 			if (ds_prev) {
1575 				VERIFY(0 == dsl_dataset_get_ref(dp,
1576 				    ds->ds_phys->ds_prev_snap_obj,
1577 				    ds_next, &ds_next->ds_prev));
1578 			}
1579 
1580 			dsl_dataset_recalc_head_uniq(ds_next);
1581 
1582 			/*
1583 			 * Reduce the amount of our unconsmed refreservation
1584 			 * being charged to our parent by the amount of
1585 			 * new unique data we have gained.
1586 			 */
1587 			if (old_unique < ds_next->ds_reserved) {
1588 				int64_t mrsdelta;
1589 				uint64_t new_unique =
1590 				    ds_next->ds_phys->ds_unique_bytes;
1591 
1592 				ASSERT(old_unique <= new_unique);
1593 				mrsdelta = MIN(new_unique - old_unique,
1594 				    ds_next->ds_reserved - old_unique);
1595 				dsl_dir_diduse_space(ds->ds_dir, -mrsdelta,
1596 				    0, 0, tx);
1597 			}
1598 		}
1599 		dsl_dataset_rele(ds_next, FTAG);
1600 
1601 		/*
1602 		 * NB: unique_bytes might not be accurate for the head objset.
1603 		 * Before SPA_VERSION 9, we didn't update its value when we
1604 		 * deleted the most recent snapshot.
1605 		 */
1606 		ASSERT3U(used, ==, ds->ds_phys->ds_unique_bytes);
1607 	} else {
1608 		/*
1609 		 * There's no next snapshot, so this is a head dataset.
1610 		 * Destroy the deadlist.  Unless it's a clone, the
1611 		 * deadlist should be empty.  (If it's a clone, it's
1612 		 * safe to ignore the deadlist contents.)
1613 		 */
1614 		struct killarg ka;
1615 
1616 		ASSERT(after_branch_point || bplist_empty(&ds->ds_deadlist));
1617 		bplist_close(&ds->ds_deadlist);
1618 		bplist_destroy(mos, ds->ds_phys->ds_deadlist_obj, tx);
1619 		ds->ds_phys->ds_deadlist_obj = 0;
1620 
1621 		/*
1622 		 * Free everything that we point to (that's born after
1623 		 * the previous snapshot, if we are a clone)
1624 		 *
1625 		 * XXX we're doing this long task with the config lock held
1626 		 */
1627 		ka.usedp = &used;
1628 		ka.compressedp = &compressed;
1629 		ka.uncompressedp = &uncompressed;
1630 		ka.zio = zio;
1631 		ka.tx = tx;
1632 		err = traverse_dsl_dataset(ds, ds->ds_phys->ds_prev_snap_txg,
1633 		    ADVANCE_POST, kill_blkptr, &ka);
1634 		ASSERT3U(err, ==, 0);
1635 		ASSERT(spa_version(dp->dp_spa) <
1636 		    SPA_VERSION_UNIQUE_ACCURATE ||
1637 		    used == ds->ds_phys->ds_unique_bytes);
1638 	}
1639 
1640 	err = zio_wait(zio);
1641 	ASSERT3U(err, ==, 0);
1642 
1643 	dsl_dir_diduse_space(ds->ds_dir, -used, -compressed, -uncompressed, tx);
1644 
1645 	if (ds->ds_dir->dd_phys->dd_head_dataset_obj == ds->ds_object) {
1646 		/* Erase the link in the dir */
1647 		dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1648 		ds->ds_dir->dd_phys->dd_head_dataset_obj = 0;
1649 		ASSERT(ds->ds_phys->ds_snapnames_zapobj != 0);
1650 		err = zap_destroy(mos, ds->ds_phys->ds_snapnames_zapobj, tx);
1651 		ASSERT(err == 0);
1652 	} else {
1653 		/* remove from snapshot namespace */
1654 		dsl_dataset_t *ds_head;
1655 		ASSERT(ds->ds_phys->ds_snapnames_zapobj == 0);
1656 		VERIFY(0 == dsl_dataset_hold_obj(dp,
1657 		    ds->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ds_head));
1658 		VERIFY(0 == dsl_dataset_get_snapname(ds));
1659 #ifdef ZFS_DEBUG
1660 		{
1661 			uint64_t val;
1662 
1663 			err = dsl_dataset_snap_lookup(ds_head,
1664 			    ds->ds_snapname, &val);
1665 			ASSERT3U(err, ==, 0);
1666 			ASSERT3U(val, ==, obj);
1667 		}
1668 #endif
1669 		err = dsl_dataset_snap_remove(ds_head, ds->ds_snapname, tx);
1670 		ASSERT(err == 0);
1671 		dsl_dataset_rele(ds_head, FTAG);
1672 	}
1673 
1674 	if (ds_prev && ds->ds_prev != ds_prev)
1675 		dsl_dataset_rele(ds_prev, FTAG);
1676 
1677 	spa_prop_clear_bootfs(dp->dp_spa, ds->ds_object, tx);
1678 	spa_history_internal_log(LOG_DS_DESTROY, dp->dp_spa, tx,
1679 	    cr, "dataset = %llu", ds->ds_object);
1680 
1681 	dsl_dir_close(ds->ds_dir, ds);
1682 	ds->ds_dir = NULL;
1683 	dsl_dataset_drain_refs(ds, tag);
1684 	VERIFY(0 == dmu_object_free(mos, obj, tx));
1685 }
1686 
1687 static int
1688 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1689 {
1690 	uint64_t asize;
1691 
1692 	if (!dmu_tx_is_syncing(tx))
1693 		return (0);
1694 
1695 	/*
1696 	 * If there's an fs-only reservation, any blocks that might become
1697 	 * owned by the snapshot dataset must be accommodated by space
1698 	 * outside of the reservation.
1699 	 */
1700 	asize = MIN(dsl_dataset_unique(ds), ds->ds_reserved);
1701 	if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, FALSE))
1702 		return (ENOSPC);
1703 
1704 	/*
1705 	 * Propogate any reserved space for this snapshot to other
1706 	 * snapshot checks in this sync group.
1707 	 */
1708 	if (asize > 0)
1709 		dsl_dir_willuse_space(ds->ds_dir, asize, tx);
1710 
1711 	return (0);
1712 }
1713 
1714 /* ARGSUSED */
1715 int
1716 dsl_dataset_snapshot_check(void *arg1, void *arg2, dmu_tx_t *tx)
1717 {
1718 	dsl_dataset_t *ds = arg1;
1719 	const char *snapname = arg2;
1720 	int err;
1721 	uint64_t value;
1722 
1723 	/*
1724 	 * We don't allow multiple snapshots of the same txg.  If there
1725 	 * is already one, try again.
1726 	 */
1727 	if (ds->ds_phys->ds_prev_snap_txg >= tx->tx_txg)
1728 		return (EAGAIN);
1729 
1730 	/*
1731 	 * Check for conflicting name snapshot name.
1732 	 */
1733 	err = dsl_dataset_snap_lookup(ds, snapname, &value);
1734 	if (err == 0)
1735 		return (EEXIST);
1736 	if (err != ENOENT)
1737 		return (err);
1738 
1739 	/*
1740 	 * Check that the dataset's name is not too long.  Name consists
1741 	 * of the dataset's length + 1 for the @-sign + snapshot name's length
1742 	 */
1743 	if (dsl_dataset_namelen(ds) + 1 + strlen(snapname) >= MAXNAMELEN)
1744 		return (ENAMETOOLONG);
1745 
1746 	err = dsl_dataset_snapshot_reserve_space(ds, tx);
1747 	if (err)
1748 		return (err);
1749 
1750 	ds->ds_trysnap_txg = tx->tx_txg;
1751 	return (0);
1752 }
1753 
1754 void
1755 dsl_dataset_snapshot_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1756 {
1757 	dsl_dataset_t *ds = arg1;
1758 	const char *snapname = arg2;
1759 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1760 	dmu_buf_t *dbuf;
1761 	dsl_dataset_phys_t *dsphys;
1762 	uint64_t dsobj;
1763 	objset_t *mos = dp->dp_meta_objset;
1764 	int err;
1765 
1766 	spa_scrub_restart(dp->dp_spa, tx->tx_txg);
1767 	ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
1768 
1769 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1770 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1771 	VERIFY(0 == dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1772 	dmu_buf_will_dirty(dbuf, tx);
1773 	dsphys = dbuf->db_data;
1774 	bzero(dsphys, sizeof (dsl_dataset_phys_t));
1775 	dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1776 	dsphys->ds_fsid_guid = unique_create();
1777 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1778 	    sizeof (dsphys->ds_guid));
1779 	dsphys->ds_prev_snap_obj = ds->ds_phys->ds_prev_snap_obj;
1780 	dsphys->ds_prev_snap_txg = ds->ds_phys->ds_prev_snap_txg;
1781 	dsphys->ds_next_snap_obj = ds->ds_object;
1782 	dsphys->ds_num_children = 1;
1783 	dsphys->ds_creation_time = gethrestime_sec();
1784 	dsphys->ds_creation_txg = tx->tx_txg;
1785 	dsphys->ds_deadlist_obj = ds->ds_phys->ds_deadlist_obj;
1786 	dsphys->ds_used_bytes = ds->ds_phys->ds_used_bytes;
1787 	dsphys->ds_compressed_bytes = ds->ds_phys->ds_compressed_bytes;
1788 	dsphys->ds_uncompressed_bytes = ds->ds_phys->ds_uncompressed_bytes;
1789 	dsphys->ds_flags = ds->ds_phys->ds_flags;
1790 	dsphys->ds_bp = ds->ds_phys->ds_bp;
1791 	dmu_buf_rele(dbuf, FTAG);
1792 
1793 	ASSERT3U(ds->ds_prev != 0, ==, ds->ds_phys->ds_prev_snap_obj != 0);
1794 	if (ds->ds_prev) {
1795 		ASSERT(ds->ds_prev->ds_phys->ds_next_snap_obj ==
1796 		    ds->ds_object ||
1797 		    ds->ds_prev->ds_phys->ds_num_children > 1);
1798 		if (ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object) {
1799 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1800 			ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
1801 			    ds->ds_prev->ds_phys->ds_creation_txg);
1802 			ds->ds_prev->ds_phys->ds_next_snap_obj = dsobj;
1803 		}
1804 	}
1805 
1806 	/*
1807 	 * If we have a reference-reservation on this dataset, we will
1808 	 * need to increase the amount of refreservation being charged
1809 	 * since our unique space is going to zero.
1810 	 */
1811 	if (ds->ds_reserved) {
1812 		int64_t add = MIN(dsl_dataset_unique(ds), ds->ds_reserved);
1813 		dsl_dir_diduse_space(ds->ds_dir, add, 0, 0, tx);
1814 	}
1815 
1816 	bplist_close(&ds->ds_deadlist);
1817 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1818 	ASSERT3U(ds->ds_phys->ds_prev_snap_txg, <, tx->tx_txg);
1819 	ds->ds_phys->ds_prev_snap_obj = dsobj;
1820 	ds->ds_phys->ds_prev_snap_txg = tx->tx_txg;
1821 	ds->ds_phys->ds_unique_bytes = 0;
1822 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1823 		ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1824 	ds->ds_phys->ds_deadlist_obj =
1825 	    bplist_create(mos, DSL_DEADLIST_BLOCKSIZE, tx);
1826 	VERIFY(0 == bplist_open(&ds->ds_deadlist, mos,
1827 	    ds->ds_phys->ds_deadlist_obj));
1828 
1829 	dprintf("snap '%s' -> obj %llu\n", snapname, dsobj);
1830 	err = zap_add(mos, ds->ds_phys->ds_snapnames_zapobj,
1831 	    snapname, 8, 1, &dsobj, tx);
1832 	ASSERT(err == 0);
1833 
1834 	if (ds->ds_prev)
1835 		dsl_dataset_drop_ref(ds->ds_prev, ds);
1836 	VERIFY(0 == dsl_dataset_get_ref(dp,
1837 	    ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
1838 
1839 	spa_history_internal_log(LOG_DS_SNAPSHOT, dp->dp_spa, tx, cr,
1840 	    "dataset = %llu", dsobj);
1841 }
1842 
1843 void
1844 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
1845 {
1846 	ASSERT(dmu_tx_is_syncing(tx));
1847 	ASSERT(ds->ds_user_ptr != NULL);
1848 	ASSERT(ds->ds_phys->ds_next_snap_obj == 0);
1849 
1850 	/*
1851 	 * in case we had to change ds_fsid_guid when we opened it,
1852 	 * sync it out now.
1853 	 */
1854 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1855 	ds->ds_phys->ds_fsid_guid = ds->ds_fsid_guid;
1856 
1857 	dsl_dir_dirty(ds->ds_dir, tx);
1858 	dmu_objset_sync(ds->ds_user_ptr, zio, tx);
1859 }
1860 
1861 void
1862 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
1863 {
1864 	uint64_t refd, avail, uobjs, aobjs;
1865 
1866 	dsl_dir_stats(ds->ds_dir, nv);
1867 
1868 	dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
1869 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
1870 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
1871 
1872 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
1873 	    ds->ds_phys->ds_creation_time);
1874 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
1875 	    ds->ds_phys->ds_creation_txg);
1876 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
1877 	    ds->ds_quota);
1878 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
1879 	    ds->ds_reserved);
1880 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
1881 	    ds->ds_phys->ds_guid);
1882 
1883 	if (ds->ds_phys->ds_next_snap_obj) {
1884 		/*
1885 		 * This is a snapshot; override the dd's space used with
1886 		 * our unique space and compression ratio.
1887 		 */
1888 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
1889 		    ds->ds_phys->ds_unique_bytes);
1890 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
1891 		    ds->ds_phys->ds_compressed_bytes == 0 ? 100 :
1892 		    (ds->ds_phys->ds_uncompressed_bytes * 100 /
1893 		    ds->ds_phys->ds_compressed_bytes));
1894 	}
1895 }
1896 
1897 void
1898 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
1899 {
1900 	stat->dds_creation_txg = ds->ds_phys->ds_creation_txg;
1901 	stat->dds_inconsistent = ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT;
1902 	stat->dds_guid = ds->ds_phys->ds_guid;
1903 	if (ds->ds_phys->ds_next_snap_obj) {
1904 		stat->dds_is_snapshot = B_TRUE;
1905 		stat->dds_num_clones = ds->ds_phys->ds_num_children - 1;
1906 	}
1907 
1908 	/* clone origin is really a dsl_dir thing... */
1909 	rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
1910 	if (ds->ds_dir->dd_phys->dd_origin_obj) {
1911 		dsl_dataset_t *ods;
1912 
1913 		VERIFY(0 == dsl_dataset_get_ref(ds->ds_dir->dd_pool,
1914 		    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &ods));
1915 		dsl_dataset_name(ods, stat->dds_origin);
1916 		dsl_dataset_drop_ref(ods, FTAG);
1917 	}
1918 	rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
1919 }
1920 
1921 uint64_t
1922 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
1923 {
1924 	return (ds->ds_fsid_guid);
1925 }
1926 
1927 void
1928 dsl_dataset_space(dsl_dataset_t *ds,
1929     uint64_t *refdbytesp, uint64_t *availbytesp,
1930     uint64_t *usedobjsp, uint64_t *availobjsp)
1931 {
1932 	*refdbytesp = ds->ds_phys->ds_used_bytes;
1933 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
1934 	if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes)
1935 		*availbytesp += ds->ds_reserved - ds->ds_phys->ds_unique_bytes;
1936 	if (ds->ds_quota != 0) {
1937 		/*
1938 		 * Adjust available bytes according to refquota
1939 		 */
1940 		if (*refdbytesp < ds->ds_quota)
1941 			*availbytesp = MIN(*availbytesp,
1942 			    ds->ds_quota - *refdbytesp);
1943 		else
1944 			*availbytesp = 0;
1945 	}
1946 	*usedobjsp = ds->ds_phys->ds_bp.blk_fill;
1947 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
1948 }
1949 
1950 boolean_t
1951 dsl_dataset_modified_since_lastsnap(dsl_dataset_t *ds)
1952 {
1953 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1954 
1955 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
1956 	    dsl_pool_sync_context(dp));
1957 	if (ds->ds_prev == NULL)
1958 		return (B_FALSE);
1959 	if (ds->ds_phys->ds_bp.blk_birth >
1960 	    ds->ds_prev->ds_phys->ds_creation_txg)
1961 		return (B_TRUE);
1962 	return (B_FALSE);
1963 }
1964 
1965 /* ARGSUSED */
1966 static int
1967 dsl_dataset_snapshot_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
1968 {
1969 	dsl_dataset_t *ds = arg1;
1970 	char *newsnapname = arg2;
1971 	dsl_dir_t *dd = ds->ds_dir;
1972 	dsl_dataset_t *hds;
1973 	uint64_t val;
1974 	int err;
1975 
1976 	err = dsl_dataset_hold_obj(dd->dd_pool,
1977 	    dd->dd_phys->dd_head_dataset_obj, FTAG, &hds);
1978 	if (err)
1979 		return (err);
1980 
1981 	/* new name better not be in use */
1982 	err = dsl_dataset_snap_lookup(hds, newsnapname, &val);
1983 	dsl_dataset_rele(hds, FTAG);
1984 
1985 	if (err == 0)
1986 		err = EEXIST;
1987 	else if (err == ENOENT)
1988 		err = 0;
1989 
1990 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
1991 	if (dsl_dir_namelen(ds->ds_dir) + 1 + strlen(newsnapname) >= MAXNAMELEN)
1992 		err = ENAMETOOLONG;
1993 
1994 	return (err);
1995 }
1996 
1997 static void
1998 dsl_dataset_snapshot_rename_sync(void *arg1, void *arg2,
1999     cred_t *cr, dmu_tx_t *tx)
2000 {
2001 	dsl_dataset_t *ds = arg1;
2002 	const char *newsnapname = arg2;
2003 	dsl_dir_t *dd = ds->ds_dir;
2004 	objset_t *mos = dd->dd_pool->dp_meta_objset;
2005 	dsl_dataset_t *hds;
2006 	int err;
2007 
2008 	ASSERT(ds->ds_phys->ds_next_snap_obj != 0);
2009 
2010 	VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
2011 	    dd->dd_phys->dd_head_dataset_obj, FTAG, &hds));
2012 
2013 	VERIFY(0 == dsl_dataset_get_snapname(ds));
2014 	err = dsl_dataset_snap_remove(hds, ds->ds_snapname, tx);
2015 	ASSERT3U(err, ==, 0);
2016 	mutex_enter(&ds->ds_lock);
2017 	(void) strcpy(ds->ds_snapname, newsnapname);
2018 	mutex_exit(&ds->ds_lock);
2019 	err = zap_add(mos, hds->ds_phys->ds_snapnames_zapobj,
2020 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx);
2021 	ASSERT3U(err, ==, 0);
2022 
2023 	spa_history_internal_log(LOG_DS_RENAME, dd->dd_pool->dp_spa, tx,
2024 	    cr, "dataset = %llu", ds->ds_object);
2025 	dsl_dataset_rele(hds, FTAG);
2026 }
2027 
2028 struct renamesnaparg {
2029 	dsl_sync_task_group_t *dstg;
2030 	char failed[MAXPATHLEN];
2031 	char *oldsnap;
2032 	char *newsnap;
2033 };
2034 
2035 static int
2036 dsl_snapshot_rename_one(char *name, void *arg)
2037 {
2038 	struct renamesnaparg *ra = arg;
2039 	dsl_dataset_t *ds = NULL;
2040 	char *cp;
2041 	int err;
2042 
2043 	cp = name + strlen(name);
2044 	*cp = '@';
2045 	(void) strcpy(cp + 1, ra->oldsnap);
2046 
2047 	/*
2048 	 * For recursive snapshot renames the parent won't be changing
2049 	 * so we just pass name for both the to/from argument.
2050 	 */
2051 	if (err = zfs_secpolicy_rename_perms(name, name, CRED())) {
2052 		(void) strcpy(ra->failed, name);
2053 		return (err);
2054 	}
2055 
2056 #ifdef _KERNEL
2057 	/*
2058 	 * For all filesystems undergoing rename, we'll need to unmount it.
2059 	 */
2060 	(void) zfs_unmount_snap(name, NULL);
2061 #endif
2062 	err = dsl_dataset_hold(name, ra->dstg, &ds);
2063 	*cp = '\0';
2064 	if (err == ENOENT) {
2065 		return (0);
2066 	} else if (err) {
2067 		(void) strcpy(ra->failed, name);
2068 		return (err);
2069 	}
2070 
2071 	dsl_sync_task_create(ra->dstg, dsl_dataset_snapshot_rename_check,
2072 	    dsl_dataset_snapshot_rename_sync, ds, ra->newsnap, 0);
2073 
2074 	return (0);
2075 }
2076 
2077 static int
2078 dsl_recursive_rename(char *oldname, const char *newname)
2079 {
2080 	int err;
2081 	struct renamesnaparg *ra;
2082 	dsl_sync_task_t *dst;
2083 	spa_t *spa;
2084 	char *cp, *fsname = spa_strdup(oldname);
2085 	int len = strlen(oldname);
2086 
2087 	/* truncate the snapshot name to get the fsname */
2088 	cp = strchr(fsname, '@');
2089 	*cp = '\0';
2090 
2091 	err = spa_open(fsname, &spa, FTAG);
2092 	if (err) {
2093 		kmem_free(fsname, len + 1);
2094 		return (err);
2095 	}
2096 	ra = kmem_alloc(sizeof (struct renamesnaparg), KM_SLEEP);
2097 	ra->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
2098 
2099 	ra->oldsnap = strchr(oldname, '@') + 1;
2100 	ra->newsnap = strchr(newname, '@') + 1;
2101 	*ra->failed = '\0';
2102 
2103 	err = dmu_objset_find(fsname, dsl_snapshot_rename_one, ra,
2104 	    DS_FIND_CHILDREN);
2105 	kmem_free(fsname, len + 1);
2106 
2107 	if (err == 0) {
2108 		err = dsl_sync_task_group_wait(ra->dstg);
2109 	}
2110 
2111 	for (dst = list_head(&ra->dstg->dstg_tasks); dst;
2112 	    dst = list_next(&ra->dstg->dstg_tasks, dst)) {
2113 		dsl_dataset_t *ds = dst->dst_arg1;
2114 		if (dst->dst_err) {
2115 			dsl_dir_name(ds->ds_dir, ra->failed);
2116 			(void) strcat(ra->failed, "@");
2117 			(void) strcat(ra->failed, ra->newsnap);
2118 		}
2119 		dsl_dataset_rele(ds, ra->dstg);
2120 	}
2121 
2122 	if (err)
2123 		(void) strcpy(oldname, ra->failed);
2124 
2125 	dsl_sync_task_group_destroy(ra->dstg);
2126 	kmem_free(ra, sizeof (struct renamesnaparg));
2127 	spa_close(spa, FTAG);
2128 	return (err);
2129 }
2130 
2131 static int
2132 dsl_valid_rename(char *oldname, void *arg)
2133 {
2134 	int delta = *(int *)arg;
2135 
2136 	if (strlen(oldname) + delta >= MAXNAMELEN)
2137 		return (ENAMETOOLONG);
2138 
2139 	return (0);
2140 }
2141 
2142 #pragma weak dmu_objset_rename = dsl_dataset_rename
2143 int
2144 dsl_dataset_rename(char *oldname, const char *newname, boolean_t recursive)
2145 {
2146 	dsl_dir_t *dd;
2147 	dsl_dataset_t *ds;
2148 	const char *tail;
2149 	int err;
2150 
2151 	err = dsl_dir_open(oldname, FTAG, &dd, &tail);
2152 	if (err)
2153 		return (err);
2154 	if (tail == NULL) {
2155 		int delta = strlen(newname) - strlen(oldname);
2156 
2157 		/* if we're growing, validate child size lengths */
2158 		if (delta > 0)
2159 			err = dmu_objset_find(oldname, dsl_valid_rename,
2160 			    &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
2161 
2162 		if (!err)
2163 			err = dsl_dir_rename(dd, newname);
2164 		dsl_dir_close(dd, FTAG);
2165 		return (err);
2166 	}
2167 	if (tail[0] != '@') {
2168 		/* the name ended in a nonexistant component */
2169 		dsl_dir_close(dd, FTAG);
2170 		return (ENOENT);
2171 	}
2172 
2173 	dsl_dir_close(dd, FTAG);
2174 
2175 	/* new name must be snapshot in same filesystem */
2176 	tail = strchr(newname, '@');
2177 	if (tail == NULL)
2178 		return (EINVAL);
2179 	tail++;
2180 	if (strncmp(oldname, newname, tail - newname) != 0)
2181 		return (EXDEV);
2182 
2183 	if (recursive) {
2184 		err = dsl_recursive_rename(oldname, newname);
2185 	} else {
2186 		err = dsl_dataset_hold(oldname, FTAG, &ds);
2187 		if (err)
2188 			return (err);
2189 
2190 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
2191 		    dsl_dataset_snapshot_rename_check,
2192 		    dsl_dataset_snapshot_rename_sync, ds, (char *)tail, 1);
2193 
2194 		dsl_dataset_rele(ds, FTAG);
2195 	}
2196 
2197 	return (err);
2198 }
2199 
2200 struct promotedsarg {
2201 	list_node_t link;
2202 	dsl_dataset_t *ds;
2203 };
2204 
2205 struct promotearg {
2206 	list_t snap_list;
2207 	dsl_dataset_t *clone_origin, *old_head;
2208 	uint64_t used, comp, uncomp, unique;
2209 	uint64_t newnext_obj;
2210 };
2211 
2212 /* ARGSUSED */
2213 static int
2214 dsl_dataset_promote_check(void *arg1, void *arg2, dmu_tx_t *tx)
2215 {
2216 	dsl_dataset_t *hds = arg1;
2217 	struct promotearg *pa = arg2;
2218 	struct promotedsarg *snap = list_head(&pa->snap_list);
2219 	dsl_pool_t *dp = hds->ds_dir->dd_pool;
2220 	dsl_dataset_t *origin_ds = snap->ds;
2221 	dsl_dataset_t *newnext_ds;
2222 	char *name;
2223 	uint64_t itor = 0;
2224 	blkptr_t bp;
2225 	int err;
2226 
2227 	/* Check that it is a clone */
2228 	if (hds->ds_dir->dd_phys->dd_origin_obj == 0)
2229 		return (EINVAL);
2230 
2231 	/* Since this is so expensive, don't do the preliminary check */
2232 	if (!dmu_tx_is_syncing(tx))
2233 		return (0);
2234 
2235 	if (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE)
2236 		return (EXDEV);
2237 
2238 	/* find origin's new next ds */
2239 	newnext_ds = hds;
2240 	while (newnext_ds->ds_phys->ds_prev_snap_obj != origin_ds->ds_object) {
2241 		dsl_dataset_t *prev;
2242 
2243 		err = dsl_dataset_hold_obj(dp,
2244 		    newnext_ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
2245 		if (newnext_ds != hds)
2246 			dsl_dataset_rele(newnext_ds, FTAG);
2247 		if (err)
2248 			return (err);
2249 		newnext_ds = prev;
2250 	}
2251 	pa->newnext_obj = newnext_ds->ds_object;
2252 
2253 	/* compute origin's new unique space */
2254 	pa->unique = 0;
2255 	while ((err = bplist_iterate(&newnext_ds->ds_deadlist,
2256 	    &itor, &bp)) == 0) {
2257 		if (bp.blk_birth > origin_ds->ds_phys->ds_prev_snap_txg)
2258 			pa->unique += bp_get_dasize(dp->dp_spa, &bp);
2259 	}
2260 	if (newnext_ds != hds)
2261 		dsl_dataset_rele(newnext_ds, FTAG);
2262 	if (err != ENOENT)
2263 		return (err);
2264 
2265 	name = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2266 
2267 	/*
2268 	 * Walk the snapshots that we are moving
2269 	 *
2270 	 * Compute space to transfer.  Each snapshot gave birth to:
2271 	 * (my used) - (prev's used) + (deadlist's used)
2272 	 * So a sequence would look like:
2273 	 * uN - u(N-1) + dN + ... + u1 - u0 + d1 + u0 - 0 + d0
2274 	 * Which simplifies to:
2275 	 * uN + dN + ... + d1 + d0
2276 	 * Note however, if we stop before we reach the ORIGIN we get:
2277 	 * uN + dN + ... + dM - uM-1
2278 	 */
2279 	pa->used = origin_ds->ds_phys->ds_used_bytes;
2280 	pa->comp = origin_ds->ds_phys->ds_compressed_bytes;
2281 	pa->uncomp = origin_ds->ds_phys->ds_uncompressed_bytes;
2282 	do {
2283 		uint64_t val, dlused, dlcomp, dluncomp;
2284 		dsl_dataset_t *ds = snap->ds;
2285 
2286 		/* Check that the snapshot name does not conflict */
2287 		dsl_dataset_name(ds, name);
2288 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2289 		if (err == 0)
2290 			err = EEXIST;
2291 		if (err != ENOENT)
2292 			break;
2293 		err = 0;
2294 
2295 		/* The very first snapshot does not have a deadlist */
2296 		if (ds->ds_phys->ds_prev_snap_obj != 0) {
2297 			if (err = bplist_space(&ds->ds_deadlist,
2298 			    &dlused, &dlcomp, &dluncomp))
2299 				break;
2300 			pa->used += dlused;
2301 			pa->comp += dlcomp;
2302 			pa->uncomp += dluncomp;
2303 		}
2304 	} while (snap = list_next(&pa->snap_list, snap));
2305 
2306 	/*
2307 	 * If we are a clone of a clone then we never reached ORIGIN,
2308 	 * so we need to subtract out the clone origin's used space.
2309 	 */
2310 	if (pa->clone_origin) {
2311 		pa->used -= pa->clone_origin->ds_phys->ds_used_bytes;
2312 		pa->comp -= pa->clone_origin->ds_phys->ds_compressed_bytes;
2313 		pa->uncomp -= pa->clone_origin->ds_phys->ds_uncompressed_bytes;
2314 	}
2315 
2316 	kmem_free(name, MAXPATHLEN);
2317 
2318 	/* Check that there is enough space here */
2319 	if (err == 0) {
2320 		dsl_dir_t *odd = origin_ds->ds_dir;
2321 		err = dsl_dir_transfer_possible(odd, hds->ds_dir, pa->used);
2322 	}
2323 
2324 	return (err);
2325 }
2326 
2327 static void
2328 dsl_dataset_promote_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
2329 {
2330 	dsl_dataset_t *hds = arg1;
2331 	struct promotearg *pa = arg2;
2332 	struct promotedsarg *snap = list_head(&pa->snap_list);
2333 	dsl_dataset_t *origin_ds = snap->ds;
2334 	dsl_dir_t *dd = hds->ds_dir;
2335 	dsl_pool_t *dp = hds->ds_dir->dd_pool;
2336 	dsl_dir_t *odd = NULL;
2337 	char *name;
2338 
2339 	ASSERT(0 == (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE));
2340 
2341 	/*
2342 	 * We need to explicitly open odd, since origin_ds's dd will be
2343 	 * changing.
2344 	 */
2345 	VERIFY(0 == dsl_dir_open_obj(dp, origin_ds->ds_dir->dd_object,
2346 	    NULL, FTAG, &odd));
2347 
2348 	/* change origin's next snap */
2349 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2350 	origin_ds->ds_phys->ds_next_snap_obj = pa->newnext_obj;
2351 
2352 	/* change origin */
2353 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
2354 	ASSERT3U(dd->dd_phys->dd_origin_obj, ==, origin_ds->ds_object);
2355 	dd->dd_phys->dd_origin_obj = odd->dd_phys->dd_origin_obj;
2356 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
2357 	odd->dd_phys->dd_origin_obj = origin_ds->ds_object;
2358 
2359 	/* move snapshots to this dir */
2360 	name = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2361 	do {
2362 		dsl_dataset_t *ds = snap->ds;
2363 
2364 		/* move snap name entry */
2365 		dsl_dataset_name(ds, name);
2366 		VERIFY(0 == dsl_dataset_snap_remove(pa->old_head,
2367 		    ds->ds_snapname, tx));
2368 		VERIFY(0 == zap_add(dp->dp_meta_objset,
2369 		    hds->ds_phys->ds_snapnames_zapobj, ds->ds_snapname,
2370 		    8, 1, &ds->ds_object, tx));
2371 
2372 		/* change containing dsl_dir */
2373 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2374 		ASSERT3U(ds->ds_phys->ds_dir_obj, ==, odd->dd_object);
2375 		ds->ds_phys->ds_dir_obj = dd->dd_object;
2376 		ASSERT3P(ds->ds_dir, ==, odd);
2377 		dsl_dir_close(ds->ds_dir, ds);
2378 		VERIFY(0 == dsl_dir_open_obj(dp, dd->dd_object,
2379 		    NULL, ds, &ds->ds_dir));
2380 
2381 		ASSERT3U(dsl_prop_numcb(ds), ==, 0);
2382 	} while (snap = list_next(&pa->snap_list, snap));
2383 
2384 	/* change space accounting */
2385 	dsl_dir_diduse_space(odd, -pa->used, -pa->comp, -pa->uncomp, tx);
2386 	dsl_dir_diduse_space(dd, pa->used, pa->comp, pa->uncomp, tx);
2387 	origin_ds->ds_phys->ds_unique_bytes = pa->unique;
2388 
2389 	/* log history record */
2390 	spa_history_internal_log(LOG_DS_PROMOTE, dd->dd_pool->dp_spa, tx,
2391 	    cr, "dataset = %llu", hds->ds_object);
2392 
2393 	dsl_dir_close(odd, FTAG);
2394 	kmem_free(name, MAXPATHLEN);
2395 }
2396 
2397 int
2398 dsl_dataset_promote(const char *name)
2399 {
2400 	dsl_dataset_t *ds;
2401 	dsl_dir_t *dd;
2402 	dsl_pool_t *dp;
2403 	dmu_object_info_t doi;
2404 	struct promotearg pa;
2405 	struct promotedsarg *snap;
2406 	uint64_t snap_obj;
2407 	uint64_t last_snap = 0;
2408 	int err;
2409 
2410 	err = dsl_dataset_hold(name, FTAG, &ds);
2411 	if (err)
2412 		return (err);
2413 	dd = ds->ds_dir;
2414 	dp = dd->dd_pool;
2415 
2416 	err = dmu_object_info(dp->dp_meta_objset,
2417 	    ds->ds_phys->ds_snapnames_zapobj, &doi);
2418 	if (err) {
2419 		dsl_dataset_rele(ds, FTAG);
2420 		return (err);
2421 	}
2422 
2423 	/*
2424 	 * We are going to inherit all the snapshots taken before our
2425 	 * origin (i.e., our new origin will be our parent's origin).
2426 	 * Take ownership of them so that we can rename them into our
2427 	 * namespace.
2428 	 */
2429 	pa.clone_origin = NULL;
2430 	list_create(&pa.snap_list,
2431 	    sizeof (struct promotedsarg), offsetof(struct promotedsarg, link));
2432 	rw_enter(&dp->dp_config_rwlock, RW_READER);
2433 	ASSERT(dd->dd_phys->dd_origin_obj != 0);
2434 	snap_obj = dd->dd_phys->dd_origin_obj;
2435 	while (snap_obj) {
2436 		snap = kmem_alloc(sizeof (struct promotedsarg), KM_SLEEP);
2437 		err = dsl_dataset_own_obj(dp, snap_obj, 0, FTAG, &snap->ds);
2438 		if (err == ENOENT) {
2439 			/* lost race with snapshot destroy */
2440 			struct promotedsarg *last = list_tail(&pa.snap_list);
2441 			ASSERT(snap_obj != last->ds->ds_phys->ds_prev_snap_obj);
2442 			snap_obj = last->ds->ds_phys->ds_prev_snap_obj;
2443 			kmem_free(snap, sizeof (struct promotedsarg));
2444 			continue;
2445 		} else if (err) {
2446 			kmem_free(snap, sizeof (struct promotedsarg));
2447 			rw_exit(&dp->dp_config_rwlock);
2448 			goto out;
2449 		}
2450 		/*
2451 		 * We could be a clone of a clone.  If we reach our
2452 		 * parent's branch point, we're done.
2453 		 */
2454 		if (last_snap &&
2455 		    snap->ds->ds_phys->ds_next_snap_obj != last_snap) {
2456 			pa.clone_origin = snap->ds;
2457 			kmem_free(snap, sizeof (struct promotedsarg));
2458 			snap_obj = 0;
2459 		} else {
2460 			list_insert_tail(&pa.snap_list, snap);
2461 			last_snap = snap_obj;
2462 			snap_obj = snap->ds->ds_phys->ds_prev_snap_obj;
2463 		}
2464 	}
2465 	snap = list_head(&pa.snap_list);
2466 	ASSERT(snap != NULL);
2467 	err = dsl_dataset_hold_obj(dp,
2468 	    snap->ds->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &pa.old_head);
2469 	rw_exit(&dp->dp_config_rwlock);
2470 
2471 	if (err)
2472 		goto out;
2473 
2474 	/*
2475 	 * Add in 128x the snapnames zapobj size, since we will be moving
2476 	 * a bunch of snapnames to the promoted ds, and dirtying their
2477 	 * bonus buffers.
2478 	 */
2479 	err = dsl_sync_task_do(dp, dsl_dataset_promote_check,
2480 	    dsl_dataset_promote_sync, ds, &pa, 2 + 2 * doi.doi_physical_blks);
2481 
2482 	dsl_dataset_rele(pa.old_head, FTAG);
2483 out:
2484 	while ((snap = list_tail(&pa.snap_list)) != NULL) {
2485 		list_remove(&pa.snap_list, snap);
2486 		dsl_dataset_disown(snap->ds, FTAG);
2487 		kmem_free(snap, sizeof (struct promotedsarg));
2488 	}
2489 	list_destroy(&pa.snap_list);
2490 	if (pa.clone_origin)
2491 		dsl_dataset_disown(pa.clone_origin, FTAG);
2492 	dsl_dataset_rele(ds, FTAG);
2493 	return (err);
2494 }
2495 
2496 struct cloneswaparg {
2497 	dsl_dataset_t *cds; /* clone dataset */
2498 	dsl_dataset_t *ohds; /* origin's head dataset */
2499 	boolean_t force;
2500 	int64_t unused_refres_delta; /* change in unconsumed refreservation */
2501 };
2502 
2503 /* ARGSUSED */
2504 static int
2505 dsl_dataset_clone_swap_check(void *arg1, void *arg2, dmu_tx_t *tx)
2506 {
2507 	struct cloneswaparg *csa = arg1;
2508 
2509 	/* they should both be heads */
2510 	if (dsl_dataset_is_snapshot(csa->cds) ||
2511 	    dsl_dataset_is_snapshot(csa->ohds))
2512 		return (EINVAL);
2513 
2514 	/* the branch point should be just before them */
2515 	if (csa->cds->ds_prev != csa->ohds->ds_prev)
2516 		return (EINVAL);
2517 
2518 	/* cds should be the clone */
2519 	if (csa->cds->ds_prev->ds_phys->ds_next_snap_obj !=
2520 	    csa->ohds->ds_object)
2521 		return (EINVAL);
2522 
2523 	/* the clone should be a child of the origin */
2524 	if (csa->cds->ds_dir->dd_parent != csa->ohds->ds_dir)
2525 		return (EINVAL);
2526 
2527 	/* ohds shouldn't be modified unless 'force' */
2528 	if (!csa->force && dsl_dataset_modified_since_lastsnap(csa->ohds))
2529 		return (ETXTBSY);
2530 
2531 	/* adjust amount of any unconsumed refreservation */
2532 	csa->unused_refres_delta =
2533 	    (int64_t)MIN(csa->ohds->ds_reserved,
2534 	    csa->ohds->ds_phys->ds_unique_bytes) -
2535 	    (int64_t)MIN(csa->ohds->ds_reserved,
2536 	    csa->cds->ds_phys->ds_unique_bytes);
2537 
2538 	if (csa->unused_refres_delta > 0 &&
2539 	    csa->unused_refres_delta >
2540 	    dsl_dir_space_available(csa->ohds->ds_dir, NULL, 0, TRUE))
2541 		return (ENOSPC);
2542 
2543 	return (0);
2544 }
2545 
2546 /* ARGSUSED */
2547 static void
2548 dsl_dataset_clone_swap_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
2549 {
2550 	struct cloneswaparg *csa = arg1;
2551 	dsl_pool_t *dp = csa->cds->ds_dir->dd_pool;
2552 	uint64_t itor = 0;
2553 	blkptr_t bp;
2554 	uint64_t unique = 0;
2555 	int err;
2556 
2557 	ASSERT(csa->cds->ds_reserved == 0);
2558 	ASSERT(csa->cds->ds_quota == csa->ohds->ds_quota);
2559 
2560 	dmu_buf_will_dirty(csa->cds->ds_dbuf, tx);
2561 	dmu_buf_will_dirty(csa->ohds->ds_dbuf, tx);
2562 	dmu_buf_will_dirty(csa->cds->ds_prev->ds_dbuf, tx);
2563 
2564 	if (csa->cds->ds_user_ptr != NULL) {
2565 		csa->cds->ds_user_evict_func(csa->cds, csa->cds->ds_user_ptr);
2566 		csa->cds->ds_user_ptr = NULL;
2567 	}
2568 
2569 	if (csa->ohds->ds_user_ptr != NULL) {
2570 		csa->ohds->ds_user_evict_func(csa->ohds,
2571 		    csa->ohds->ds_user_ptr);
2572 		csa->ohds->ds_user_ptr = NULL;
2573 	}
2574 
2575 	/* compute unique space */
2576 	while ((err = bplist_iterate(&csa->cds->ds_deadlist,
2577 	    &itor, &bp)) == 0) {
2578 		if (bp.blk_birth > csa->cds->ds_prev->ds_phys->ds_prev_snap_txg)
2579 			unique += bp_get_dasize(dp->dp_spa, &bp);
2580 	}
2581 	VERIFY(err == ENOENT);
2582 
2583 	/* reset origin's unique bytes */
2584 	csa->cds->ds_prev->ds_phys->ds_unique_bytes = unique;
2585 
2586 	/* swap blkptrs */
2587 	{
2588 		blkptr_t tmp;
2589 		tmp = csa->ohds->ds_phys->ds_bp;
2590 		csa->ohds->ds_phys->ds_bp = csa->cds->ds_phys->ds_bp;
2591 		csa->cds->ds_phys->ds_bp = tmp;
2592 	}
2593 
2594 	/* set dd_*_bytes */
2595 	{
2596 		int64_t dused, dcomp, duncomp;
2597 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
2598 		uint64_t odl_used, odl_comp, odl_uncomp;
2599 
2600 		VERIFY(0 == bplist_space(&csa->cds->ds_deadlist, &cdl_used,
2601 		    &cdl_comp, &cdl_uncomp));
2602 		VERIFY(0 == bplist_space(&csa->ohds->ds_deadlist, &odl_used,
2603 		    &odl_comp, &odl_uncomp));
2604 		dused = csa->cds->ds_phys->ds_used_bytes + cdl_used -
2605 		    (csa->ohds->ds_phys->ds_used_bytes + odl_used);
2606 		dcomp = csa->cds->ds_phys->ds_compressed_bytes + cdl_comp -
2607 		    (csa->ohds->ds_phys->ds_compressed_bytes + odl_comp);
2608 		duncomp = csa->cds->ds_phys->ds_uncompressed_bytes +
2609 		    cdl_uncomp -
2610 		    (csa->ohds->ds_phys->ds_uncompressed_bytes + odl_uncomp);
2611 
2612 		dsl_dir_diduse_space(csa->ohds->ds_dir,
2613 		    dused, dcomp, duncomp, tx);
2614 		dsl_dir_diduse_space(csa->cds->ds_dir,
2615 		    -dused, -dcomp, -duncomp, tx);
2616 	}
2617 
2618 #define	SWITCH64(x, y) \
2619 	{ \
2620 		uint64_t __tmp = (x); \
2621 		(x) = (y); \
2622 		(y) = __tmp; \
2623 	}
2624 
2625 	/* swap ds_*_bytes */
2626 	SWITCH64(csa->ohds->ds_phys->ds_used_bytes,
2627 	    csa->cds->ds_phys->ds_used_bytes);
2628 	SWITCH64(csa->ohds->ds_phys->ds_compressed_bytes,
2629 	    csa->cds->ds_phys->ds_compressed_bytes);
2630 	SWITCH64(csa->ohds->ds_phys->ds_uncompressed_bytes,
2631 	    csa->cds->ds_phys->ds_uncompressed_bytes);
2632 	SWITCH64(csa->ohds->ds_phys->ds_unique_bytes,
2633 	    csa->cds->ds_phys->ds_unique_bytes);
2634 
2635 	/* apply any parent delta for change in unconsumed refreservation */
2636 	dsl_dir_diduse_space(csa->ohds->ds_dir, csa->unused_refres_delta,
2637 	    0, 0, tx);
2638 
2639 	/* swap deadlists */
2640 	bplist_close(&csa->cds->ds_deadlist);
2641 	bplist_close(&csa->ohds->ds_deadlist);
2642 	SWITCH64(csa->ohds->ds_phys->ds_deadlist_obj,
2643 	    csa->cds->ds_phys->ds_deadlist_obj);
2644 	VERIFY(0 == bplist_open(&csa->cds->ds_deadlist, dp->dp_meta_objset,
2645 	    csa->cds->ds_phys->ds_deadlist_obj));
2646 	VERIFY(0 == bplist_open(&csa->ohds->ds_deadlist, dp->dp_meta_objset,
2647 	    csa->ohds->ds_phys->ds_deadlist_obj));
2648 }
2649 
2650 /*
2651  * Swap 'clone' with its origin head file system.  Used at the end
2652  * of "online recv" to swizzle the file system to the new version.
2653  */
2654 int
2655 dsl_dataset_clone_swap(dsl_dataset_t *clone, dsl_dataset_t *origin_head,
2656     boolean_t force)
2657 {
2658 	struct cloneswaparg csa;
2659 	int error;
2660 
2661 	ASSERT(clone->ds_owner);
2662 	ASSERT(origin_head->ds_owner);
2663 retry:
2664 	/* Need exclusive access for the swap */
2665 	rw_enter(&clone->ds_rwlock, RW_WRITER);
2666 	if (!rw_tryenter(&origin_head->ds_rwlock, RW_WRITER)) {
2667 		rw_exit(&clone->ds_rwlock);
2668 		rw_enter(&origin_head->ds_rwlock, RW_WRITER);
2669 		if (!rw_tryenter(&clone->ds_rwlock, RW_WRITER)) {
2670 			rw_exit(&origin_head->ds_rwlock);
2671 			goto retry;
2672 		}
2673 	}
2674 	csa.cds = clone;
2675 	csa.ohds = origin_head;
2676 	csa.force = force;
2677 	error = dsl_sync_task_do(clone->ds_dir->dd_pool,
2678 	    dsl_dataset_clone_swap_check,
2679 	    dsl_dataset_clone_swap_sync, &csa, NULL, 9);
2680 	return (error);
2681 }
2682 
2683 /*
2684  * Given a pool name and a dataset object number in that pool,
2685  * return the name of that dataset.
2686  */
2687 int
2688 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
2689 {
2690 	spa_t *spa;
2691 	dsl_pool_t *dp;
2692 	dsl_dataset_t *ds;
2693 	int error;
2694 
2695 	if ((error = spa_open(pname, &spa, FTAG)) != 0)
2696 		return (error);
2697 	dp = spa_get_dsl(spa);
2698 	rw_enter(&dp->dp_config_rwlock, RW_READER);
2699 	if ((error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds)) == 0) {
2700 		dsl_dataset_name(ds, buf);
2701 		dsl_dataset_rele(ds, FTAG);
2702 	}
2703 	rw_exit(&dp->dp_config_rwlock);
2704 	spa_close(spa, FTAG);
2705 
2706 	return (error);
2707 }
2708 
2709 int
2710 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
2711     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
2712 {
2713 	int error = 0;
2714 
2715 	ASSERT3S(asize, >, 0);
2716 
2717 	/*
2718 	 * *ref_rsrv is the portion of asize that will come from any
2719 	 * unconsumed refreservation space.
2720 	 */
2721 	*ref_rsrv = 0;
2722 
2723 	mutex_enter(&ds->ds_lock);
2724 	/*
2725 	 * Make a space adjustment for reserved bytes.
2726 	 */
2727 	if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes) {
2728 		ASSERT3U(*used, >=,
2729 		    ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
2730 		*used -= (ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
2731 		*ref_rsrv =
2732 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
2733 	}
2734 
2735 	if (!check_quota || ds->ds_quota == 0) {
2736 		mutex_exit(&ds->ds_lock);
2737 		return (0);
2738 	}
2739 	/*
2740 	 * If they are requesting more space, and our current estimate
2741 	 * is over quota, they get to try again unless the actual
2742 	 * on-disk is over quota and there are no pending changes (which
2743 	 * may free up space for us).
2744 	 */
2745 	if (ds->ds_phys->ds_used_bytes + inflight >= ds->ds_quota) {
2746 		if (inflight > 0 || ds->ds_phys->ds_used_bytes < ds->ds_quota)
2747 			error = ERESTART;
2748 		else
2749 			error = EDQUOT;
2750 	}
2751 	mutex_exit(&ds->ds_lock);
2752 
2753 	return (error);
2754 }
2755 
2756 /* ARGSUSED */
2757 static int
2758 dsl_dataset_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
2759 {
2760 	dsl_dataset_t *ds = arg1;
2761 	uint64_t *quotap = arg2;
2762 	uint64_t new_quota = *quotap;
2763 
2764 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_REFQUOTA)
2765 		return (ENOTSUP);
2766 
2767 	if (new_quota == 0)
2768 		return (0);
2769 
2770 	if (new_quota < ds->ds_phys->ds_used_bytes ||
2771 	    new_quota < ds->ds_reserved)
2772 		return (ENOSPC);
2773 
2774 	return (0);
2775 }
2776 
2777 /* ARGSUSED */
2778 void
2779 dsl_dataset_set_quota_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
2780 {
2781 	dsl_dataset_t *ds = arg1;
2782 	uint64_t *quotap = arg2;
2783 	uint64_t new_quota = *quotap;
2784 
2785 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2786 
2787 	ds->ds_quota = new_quota;
2788 
2789 	dsl_prop_set_uint64_sync(ds->ds_dir, "refquota", new_quota, cr, tx);
2790 
2791 	spa_history_internal_log(LOG_DS_REFQUOTA, ds->ds_dir->dd_pool->dp_spa,
2792 	    tx, cr, "%lld dataset = %llu ",
2793 	    (longlong_t)new_quota, ds->ds_object);
2794 }
2795 
2796 int
2797 dsl_dataset_set_quota(const char *dsname, uint64_t quota)
2798 {
2799 	dsl_dataset_t *ds;
2800 	int err;
2801 
2802 	err = dsl_dataset_hold(dsname, FTAG, &ds);
2803 	if (err)
2804 		return (err);
2805 
2806 	if (quota != ds->ds_quota) {
2807 		/*
2808 		 * If someone removes a file, then tries to set the quota, we
2809 		 * want to make sure the file freeing takes effect.
2810 		 */
2811 		txg_wait_open(ds->ds_dir->dd_pool, 0);
2812 
2813 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
2814 		    dsl_dataset_set_quota_check, dsl_dataset_set_quota_sync,
2815 		    ds, &quota, 0);
2816 	}
2817 	dsl_dataset_rele(ds, FTAG);
2818 	return (err);
2819 }
2820 
2821 static int
2822 dsl_dataset_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
2823 {
2824 	dsl_dataset_t *ds = arg1;
2825 	uint64_t *reservationp = arg2;
2826 	uint64_t new_reservation = *reservationp;
2827 	int64_t delta;
2828 	uint64_t unique;
2829 
2830 	if (new_reservation > INT64_MAX)
2831 		return (EOVERFLOW);
2832 
2833 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) <
2834 	    SPA_VERSION_REFRESERVATION)
2835 		return (ENOTSUP);
2836 
2837 	if (dsl_dataset_is_snapshot(ds))
2838 		return (EINVAL);
2839 
2840 	/*
2841 	 * If we are doing the preliminary check in open context, the
2842 	 * space estimates may be inaccurate.
2843 	 */
2844 	if (!dmu_tx_is_syncing(tx))
2845 		return (0);
2846 
2847 	mutex_enter(&ds->ds_lock);
2848 	unique = dsl_dataset_unique(ds);
2849 	delta = MAX(unique, new_reservation) - MAX(unique, ds->ds_reserved);
2850 	mutex_exit(&ds->ds_lock);
2851 
2852 	if (delta > 0 &&
2853 	    delta > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
2854 		return (ENOSPC);
2855 	if (delta > 0 && ds->ds_quota > 0 &&
2856 	    new_reservation > ds->ds_quota)
2857 		return (ENOSPC);
2858 
2859 	return (0);
2860 }
2861 
2862 /* ARGSUSED */
2863 static void
2864 dsl_dataset_set_reservation_sync(void *arg1, void *arg2, cred_t *cr,
2865     dmu_tx_t *tx)
2866 {
2867 	dsl_dataset_t *ds = arg1;
2868 	uint64_t *reservationp = arg2;
2869 	uint64_t new_reservation = *reservationp;
2870 	uint64_t unique;
2871 	int64_t delta;
2872 
2873 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2874 
2875 	mutex_enter(&ds->ds_lock);
2876 	unique = dsl_dataset_unique(ds);
2877 	delta = MAX(0, (int64_t)(new_reservation - unique)) -
2878 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
2879 	ds->ds_reserved = new_reservation;
2880 	mutex_exit(&ds->ds_lock);
2881 
2882 	dsl_prop_set_uint64_sync(ds->ds_dir, "refreservation",
2883 	    new_reservation, cr, tx);
2884 
2885 	dsl_dir_diduse_space(ds->ds_dir, delta, 0, 0, tx);
2886 
2887 	spa_history_internal_log(LOG_DS_REFRESERV,
2888 	    ds->ds_dir->dd_pool->dp_spa, tx, cr, "%lld dataset = %llu",
2889 	    (longlong_t)new_reservation,
2890 	    ds->ds_dir->dd_phys->dd_head_dataset_obj);
2891 }
2892 
2893 int
2894 dsl_dataset_set_reservation(const char *dsname, uint64_t reservation)
2895 {
2896 	dsl_dataset_t *ds;
2897 	int err;
2898 
2899 	err = dsl_dataset_hold(dsname, FTAG, &ds);
2900 	if (err)
2901 		return (err);
2902 
2903 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
2904 	    dsl_dataset_set_reservation_check,
2905 	    dsl_dataset_set_reservation_sync, ds, &reservation, 0);
2906 	dsl_dataset_rele(ds, FTAG);
2907 	return (err);
2908 }
2909