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