xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_dataset.c (revision 546d3d08e5993cbe2d6141b256e8c2ebad5aa102)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 RackTop Systems.
28  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
29  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
30  * Copyright 2016, OmniTI Computer Consulting, Inc. All rights reserved.
31  * Copyright 2017 Nexenta Systems, Inc.
32  * Copyright (c) 2019, Klara Inc.
33  * Copyright (c) 2019, Allan Jude
34  * Copyright (c) 2020 The FreeBSD Foundation [1]
35  * Copyright (c) 2025, Rob Norris <robn@despairlabs.com>
36  *
37  * [1] Portions of this software were developed by Allan Jude
38  *     under sponsorship from the FreeBSD Foundation.
39  */
40 
41 #include <sys/dmu_objset.h>
42 #include <sys/dsl_dataset.h>
43 #include <sys/dsl_dir.h>
44 #include <sys/dsl_prop.h>
45 #include <sys/dsl_synctask.h>
46 #include <sys/dmu_traverse.h>
47 #include <sys/dmu_impl.h>
48 #include <sys/dmu_tx.h>
49 #include <sys/arc.h>
50 #include <sys/zio.h>
51 #include <sys/zap.h>
52 #include <sys/zfeature.h>
53 #include <sys/unique.h>
54 #include <sys/zfs_context.h>
55 #include <sys/zfs_ioctl.h>
56 #include <sys/spa.h>
57 #include <sys/spa_impl.h>
58 #include <sys/vdev.h>
59 #include <sys/zfs_znode.h>
60 #include <sys/zfs_onexit.h>
61 #include <sys/zvol.h>
62 #include <sys/dsl_scan.h>
63 #include <sys/dsl_deadlist.h>
64 #include <sys/dsl_destroy.h>
65 #include <sys/dsl_userhold.h>
66 #include <sys/dsl_bookmark.h>
67 #include <sys/policy.h>
68 #include <sys/dmu_send.h>
69 #include <sys/dmu_recv.h>
70 #include <sys/zio_compress.h>
71 #include <zfs_fletcher.h>
72 #include <sys/zio_checksum.h>
73 #include <sys/brt.h>
74 
75 /*
76  * The SPA supports block sizes up to 16MB.  However, very large blocks
77  * can have an impact on i/o latency (e.g. tying up a spinning disk for
78  * ~300ms), and also potentially on the memory allocator.  Therefore,
79  * we did not allow the recordsize to be set larger than zfs_max_recordsize
80  * (former default: 1MB).  Larger blocks could be created by changing this
81  * tunable, and pools with larger blocks could always be imported and used,
82  * regardless of this setting.
83  *
84  * We do, however, still limit it by default to 1M on x86_32, because Linux's
85  * 3/1 memory split doesn't leave much room for 16M chunks.
86  */
87 #ifdef _ILP32
88 uint_t zfs_max_recordsize =  1 * 1024 * 1024;
89 #else
90 uint_t zfs_max_recordsize = 16 * 1024 * 1024;
91 #endif
92 static int zfs_allow_redacted_dataset_mount = 0;
93 
94 int zfs_snapshot_history_enabled = 1;
95 
96 #define	SWITCH64(x, y) \
97 	{ \
98 		uint64_t __tmp = (x); \
99 		(x) = (y); \
100 		(y) = __tmp; \
101 	}
102 
103 #define	DS_REF_MAX	(1ULL << 62)
104 
105 static void dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds,
106     uint64_t obj, dmu_tx_t *tx);
107 static void dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds,
108     dmu_tx_t *tx);
109 
110 static void unload_zfeature(dsl_dataset_t *ds, spa_feature_t f);
111 
112 extern uint_t spa_asize_inflation;
113 
114 static zil_header_t zero_zil;
115 
116 /*
117  * Figure out how much of this delta should be propagated to the dsl_dir
118  * layer.  If there's a refreservation, that space has already been
119  * partially accounted for in our ancestors.
120  */
121 static int64_t
parent_delta(dsl_dataset_t * ds,int64_t delta)122 parent_delta(dsl_dataset_t *ds, int64_t delta)
123 {
124 	dsl_dataset_phys_t *ds_phys;
125 	uint64_t old_bytes, new_bytes;
126 
127 	if (ds->ds_reserved == 0)
128 		return (delta);
129 
130 	ds_phys = dsl_dataset_phys(ds);
131 	old_bytes = MAX(ds_phys->ds_unique_bytes, ds->ds_reserved);
132 	new_bytes = MAX(ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
133 
134 	ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
135 	return (new_bytes - old_bytes);
136 }
137 
138 void
dsl_dataset_block_born(dsl_dataset_t * ds,const blkptr_t * bp,dmu_tx_t * tx)139 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
140 {
141 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
142 	int used = bp_get_dsize_sync(spa, bp);
143 	int compressed = BP_GET_PSIZE(bp);
144 	int uncompressed = BP_GET_UCSIZE(bp);
145 	int64_t delta;
146 	spa_feature_t f;
147 
148 	dprintf_bp(bp, "ds=%p", ds);
149 
150 	ASSERT(dmu_tx_is_syncing(tx));
151 	/* It could have been compressed away to nothing */
152 	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
153 		return;
154 	ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
155 	ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
156 	if (ds == NULL) {
157 		dsl_pool_mos_diduse_space(tx->tx_pool,
158 		    used, compressed, uncompressed);
159 		return;
160 	}
161 
162 	ASSERT3U(BP_GET_BIRTH(bp), >,
163 	    dsl_dataset_phys(ds)->ds_prev_snap_txg);
164 	/* ds_dbuf is pre-dirtied in dsl_dataset_sync(). */
165 	ASSERT(dmu_buf_is_dirty(ds->ds_dbuf, tx));
166 	mutex_enter(&ds->ds_lock);
167 	delta = parent_delta(ds, used);
168 	dsl_dataset_phys(ds)->ds_referenced_bytes += used;
169 	dsl_dataset_phys(ds)->ds_compressed_bytes += compressed;
170 	dsl_dataset_phys(ds)->ds_uncompressed_bytes += uncompressed;
171 	dsl_dataset_phys(ds)->ds_unique_bytes += used;
172 
173 	if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE) {
174 		ds->ds_feature_activation[SPA_FEATURE_LARGE_BLOCKS] =
175 		    (void *)B_TRUE;
176 	}
177 
178 
179 	f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
180 	if (f != SPA_FEATURE_NONE) {
181 		ASSERT3S(spa_feature_table[f].fi_type, ==,
182 		    ZFEATURE_TYPE_BOOLEAN);
183 		ds->ds_feature_activation[f] = (void *)B_TRUE;
184 	}
185 
186 	f = zio_compress_to_feature(BP_GET_COMPRESS(bp));
187 	if (f != SPA_FEATURE_NONE) {
188 		ASSERT3S(spa_feature_table[f].fi_type, ==,
189 		    ZFEATURE_TYPE_BOOLEAN);
190 		ds->ds_feature_activation[f] = (void *)B_TRUE;
191 	}
192 
193 	/*
194 	 * Track block for livelist, but ignore embedded blocks because
195 	 * they do not need to be freed.
196 	 */
197 	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
198 	    BP_GET_BIRTH(bp) > ds->ds_dir->dd_origin_txg &&
199 	    !(BP_IS_EMBEDDED(bp))) {
200 		ASSERT(dsl_dir_is_clone(ds->ds_dir));
201 		ASSERT(spa_feature_is_enabled(spa,
202 		    SPA_FEATURE_LIVELIST));
203 		bplist_append(&ds->ds_dir->dd_pending_allocs, bp);
204 	}
205 
206 	mutex_exit(&ds->ds_lock);
207 	dsl_dir_diduse_transfer_space(ds->ds_dir, delta,
208 	    compressed, uncompressed, used,
209 	    DD_USED_REFRSRV, DD_USED_HEAD, tx);
210 }
211 
212 /*
213  * Called when the specified segment has been remapped, and is thus no
214  * longer referenced in the head dataset.  The vdev must be indirect.
215  *
216  * If the segment is referenced by a snapshot, put it on the remap deadlist.
217  * Otherwise, add this segment to the obsolete spacemap.
218  */
219 void
dsl_dataset_block_remapped(dsl_dataset_t * ds,uint64_t vdev,uint64_t offset,uint64_t size,uint64_t birth,dmu_tx_t * tx)220 dsl_dataset_block_remapped(dsl_dataset_t *ds, uint64_t vdev, uint64_t offset,
221     uint64_t size, uint64_t birth, dmu_tx_t *tx)
222 {
223 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
224 
225 	ASSERT(dmu_tx_is_syncing(tx));
226 	ASSERT(birth <= tx->tx_txg);
227 	ASSERT(!ds->ds_is_snapshot);
228 
229 	if (birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
230 		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
231 	} else {
232 		blkptr_t fakebp;
233 		dva_t *dva = &fakebp.blk_dva[0];
234 
235 		ASSERT(ds != NULL);
236 
237 		mutex_enter(&ds->ds_remap_deadlist_lock);
238 		if (!dsl_dataset_remap_deadlist_exists(ds)) {
239 			dsl_dataset_create_remap_deadlist(ds, tx);
240 		}
241 		mutex_exit(&ds->ds_remap_deadlist_lock);
242 
243 		BP_ZERO(&fakebp);
244 		BP_SET_LOGICAL_BIRTH(&fakebp, birth);
245 		DVA_SET_VDEV(dva, vdev);
246 		DVA_SET_OFFSET(dva, offset);
247 		DVA_SET_ASIZE(dva, size);
248 		dsl_deadlist_insert(&ds->ds_remap_deadlist, &fakebp, B_FALSE,
249 		    tx);
250 	}
251 }
252 
253 int
dsl_dataset_block_kill(dsl_dataset_t * ds,const blkptr_t * bp,dmu_tx_t * tx,boolean_t async)254 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
255     boolean_t async)
256 {
257 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
258 
259 	int used = bp_get_dsize_sync(spa, bp);
260 	int compressed = BP_GET_PSIZE(bp);
261 	int uncompressed = BP_GET_UCSIZE(bp);
262 
263 	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
264 		return (0);
265 
266 	ASSERT(dmu_tx_is_syncing(tx));
267 	ASSERT(BP_GET_BIRTH(bp) <= tx->tx_txg);
268 
269 	if (ds == NULL) {
270 		dsl_free(tx->tx_pool, tx->tx_txg, bp);
271 		dsl_pool_mos_diduse_space(tx->tx_pool,
272 		    -used, -compressed, -uncompressed);
273 		return (used);
274 	}
275 	ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
276 
277 	ASSERT(!ds->ds_is_snapshot);
278 	/* ds_dbuf is pre-dirtied in dsl_dataset_sync(). */
279 	ASSERT(dmu_buf_is_dirty(ds->ds_dbuf, tx));
280 
281 	/*
282 	 * Track block for livelist, but ignore embedded blocks because
283 	 * they do not need to be freed.
284 	 */
285 	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
286 	    BP_GET_BIRTH(bp) > ds->ds_dir->dd_origin_txg &&
287 	    !(BP_IS_EMBEDDED(bp))) {
288 		ASSERT(dsl_dir_is_clone(ds->ds_dir));
289 		ASSERT(spa_feature_is_enabled(spa,
290 		    SPA_FEATURE_LIVELIST));
291 		bplist_append(&ds->ds_dir->dd_pending_frees, bp);
292 	}
293 
294 	if (BP_GET_BIRTH(bp) > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
295 		int64_t delta;
296 
297 		/*
298 		 * Put blocks that would create IO on the pool's deadlist for
299 		 * dsl_process_async_destroys() to find. This is to prevent
300 		 * zio_free() from creating a ZIO_TYPE_FREE IO for them, which
301 		 * are very heavy and can lead to out-of-memory conditions if
302 		 * something tries to free millions of blocks on the same txg.
303 		 */
304 		boolean_t defer = spa_version(spa) >= SPA_VERSION_DEADLISTS &&
305 		    (BP_IS_GANG(bp) || BP_GET_DEDUP(bp) ||
306 		    brt_maybe_exists(spa, bp));
307 
308 		if (defer) {
309 			dprintf_bp(bp, "putting on free list: %s", "");
310 			bpobj_enqueue(&ds->ds_dir->dd_pool->dp_free_bpobj,
311 			    bp, B_FALSE, tx);
312 		} else {
313 			dprintf_bp(bp, "freeing ds=%llu",
314 			    (u_longlong_t)ds->ds_object);
315 			dsl_free(tx->tx_pool, tx->tx_txg, bp);
316 		}
317 
318 		mutex_enter(&ds->ds_lock);
319 		ASSERT(dsl_dataset_phys(ds)->ds_unique_bytes >= used ||
320 		    !DS_UNIQUE_IS_ACCURATE(ds));
321 		delta = parent_delta(ds, -used);
322 		dsl_dataset_phys(ds)->ds_unique_bytes -= used;
323 		mutex_exit(&ds->ds_lock);
324 
325 		dsl_dir_diduse_transfer_space(ds->ds_dir,
326 		    delta, -compressed, -uncompressed, -used,
327 		    DD_USED_REFRSRV, DD_USED_HEAD, tx);
328 
329 		if (defer)
330 			dsl_dir_diduse_space(tx->tx_pool->dp_free_dir,
331 			    DD_USED_HEAD, used, compressed, uncompressed, tx);
332 	} else {
333 		dprintf_bp(bp, "putting on dead list: %s", "");
334 		if (async) {
335 			/*
336 			 * We are here as part of zio's write done callback,
337 			 * which means we're a zio interrupt thread.  We can't
338 			 * call dsl_deadlist_insert() now because it may block
339 			 * waiting for I/O.  Instead, put bp on the deferred
340 			 * queue and let dsl_pool_sync() finish the job.
341 			 */
342 			bplist_append(&ds->ds_pending_deadlist, bp);
343 		} else {
344 			dsl_deadlist_insert(&ds->ds_deadlist, bp, B_FALSE, tx);
345 		}
346 		ASSERT3U(ds->ds_prev->ds_object, ==,
347 		    dsl_dataset_phys(ds)->ds_prev_snap_obj);
348 		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_num_children > 0);
349 		/* if (logical birth > prev prev snap txg) prev unique += bs */
350 		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
351 		    ds->ds_object && BP_GET_BIRTH(bp) >
352 		    dsl_dataset_phys(ds->ds_prev)->ds_prev_snap_txg) {
353 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
354 			mutex_enter(&ds->ds_prev->ds_lock);
355 			dsl_dataset_phys(ds->ds_prev)->ds_unique_bytes += used;
356 			mutex_exit(&ds->ds_prev->ds_lock);
357 		}
358 		if (BP_GET_BIRTH(bp) > ds->ds_dir->dd_origin_txg) {
359 			dsl_dir_transfer_space(ds->ds_dir, used,
360 			    DD_USED_HEAD, DD_USED_SNAP, tx);
361 		}
362 	}
363 
364 	dsl_bookmark_block_killed(ds, bp, tx);
365 
366 	mutex_enter(&ds->ds_lock);
367 	ASSERT3U(dsl_dataset_phys(ds)->ds_referenced_bytes, >=, used);
368 	dsl_dataset_phys(ds)->ds_referenced_bytes -= used;
369 	ASSERT3U(dsl_dataset_phys(ds)->ds_compressed_bytes, >=, compressed);
370 	dsl_dataset_phys(ds)->ds_compressed_bytes -= compressed;
371 	ASSERT3U(dsl_dataset_phys(ds)->ds_uncompressed_bytes, >=, uncompressed);
372 	dsl_dataset_phys(ds)->ds_uncompressed_bytes -= uncompressed;
373 	mutex_exit(&ds->ds_lock);
374 
375 	return (used);
376 }
377 
378 struct feature_type_uint64_array_arg {
379 	uint64_t length;
380 	uint64_t *array;
381 };
382 
383 static void
unload_zfeature(dsl_dataset_t * ds,spa_feature_t f)384 unload_zfeature(dsl_dataset_t *ds, spa_feature_t f)
385 {
386 	switch (spa_feature_table[f].fi_type) {
387 	case ZFEATURE_TYPE_BOOLEAN:
388 		break;
389 	case ZFEATURE_TYPE_UINT64_ARRAY:
390 	{
391 		struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
392 		kmem_free(ftuaa->array, ftuaa->length * sizeof (uint64_t));
393 		kmem_free(ftuaa, sizeof (*ftuaa));
394 		break;
395 	}
396 	default:
397 		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
398 	}
399 }
400 
401 static int
load_zfeature(objset_t * mos,dsl_dataset_t * ds,spa_feature_t f)402 load_zfeature(objset_t *mos, dsl_dataset_t *ds, spa_feature_t f)
403 {
404 	int err = 0;
405 	switch (spa_feature_table[f].fi_type) {
406 	case ZFEATURE_TYPE_BOOLEAN:
407 		err = zap_contains(mos, ds->ds_object,
408 		    spa_feature_table[f].fi_guid);
409 		if (err == 0) {
410 			ds->ds_feature[f] = (void *)B_TRUE;
411 		} else {
412 			ASSERT3U(err, ==, ENOENT);
413 			err = 0;
414 		}
415 		break;
416 	case ZFEATURE_TYPE_UINT64_ARRAY:
417 	{
418 		uint64_t int_size, num_int;
419 		uint64_t *data;
420 		err = zap_length(mos, ds->ds_object,
421 		    spa_feature_table[f].fi_guid, &int_size, &num_int);
422 		if (err != 0) {
423 			ASSERT3U(err, ==, ENOENT);
424 			err = 0;
425 			break;
426 		}
427 		ASSERT3U(int_size, ==, sizeof (uint64_t));
428 		data = kmem_alloc(int_size * num_int, KM_SLEEP);
429 		VERIFY0(zap_lookup(mos, ds->ds_object,
430 		    spa_feature_table[f].fi_guid, int_size, num_int, data));
431 		struct feature_type_uint64_array_arg *ftuaa =
432 		    kmem_alloc(sizeof (*ftuaa), KM_SLEEP);
433 		ftuaa->length = num_int;
434 		ftuaa->array = data;
435 		ds->ds_feature[f] = ftuaa;
436 		break;
437 	}
438 	default:
439 		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
440 	}
441 	return (err);
442 }
443 
444 /*
445  * We have to release the fsid synchronously or we risk that a subsequent
446  * mount of the same dataset will fail to unique_insert the fsid.  This
447  * failure would manifest itself as the fsid of this dataset changing
448  * between mounts which makes NFS clients quite unhappy.
449  */
450 static void
dsl_dataset_evict_sync(void * dbu)451 dsl_dataset_evict_sync(void *dbu)
452 {
453 	dsl_dataset_t *ds = dbu;
454 
455 	ASSERT0P(ds->ds_owner);
456 
457 	unique_remove(ds->ds_fsid_guid);
458 }
459 
460 static void
dsl_dataset_evict_async(void * dbu)461 dsl_dataset_evict_async(void *dbu)
462 {
463 	dsl_dataset_t *ds = dbu;
464 
465 	ASSERT0P(ds->ds_owner);
466 
467 	ds->ds_dbuf = NULL;
468 
469 	if (ds->ds_objset != NULL)
470 		dmu_objset_evict(ds->ds_objset);
471 
472 	if (ds->ds_prev) {
473 		dsl_dataset_rele(ds->ds_prev, ds);
474 		ds->ds_prev = NULL;
475 	}
476 
477 	dsl_bookmark_fini_ds(ds);
478 
479 	bplist_destroy(&ds->ds_pending_deadlist);
480 	if (dsl_deadlist_is_open(&ds->ds_deadlist))
481 		dsl_deadlist_close(&ds->ds_deadlist);
482 	if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
483 		dsl_deadlist_close(&ds->ds_remap_deadlist);
484 	if (ds->ds_dir)
485 		dsl_dir_async_rele(ds->ds_dir, ds);
486 
487 	ASSERT(!list_link_active(&ds->ds_synced_link));
488 
489 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
490 		if (dsl_dataset_feature_is_active(ds, f))
491 			unload_zfeature(ds, f);
492 	}
493 
494 	list_destroy(&ds->ds_prop_cbs);
495 	mutex_destroy(&ds->ds_lock);
496 	mutex_destroy(&ds->ds_opening_lock);
497 	mutex_destroy(&ds->ds_sendstream_lock);
498 	mutex_destroy(&ds->ds_remap_deadlist_lock);
499 	zfs_refcount_destroy(&ds->ds_longholds);
500 	rrw_destroy(&ds->ds_bp_rwlock);
501 
502 	kmem_free(ds, sizeof (dsl_dataset_t));
503 }
504 
505 int
dsl_dataset_get_snapname(dsl_dataset_t * ds)506 dsl_dataset_get_snapname(dsl_dataset_t *ds)
507 {
508 	dsl_dataset_phys_t *headphys;
509 	int err;
510 	dmu_buf_t *headdbuf;
511 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
512 	objset_t *mos = dp->dp_meta_objset;
513 
514 	if (ds->ds_snapname[0])
515 		return (0);
516 	if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0)
517 		return (0);
518 
519 	err = dmu_bonus_hold(mos, dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj,
520 	    FTAG, &headdbuf);
521 	if (err != 0)
522 		return (err);
523 	headphys = headdbuf->db_data;
524 	err = zap_value_search(dp->dp_meta_objset,
525 	    headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname,
526 	    sizeof (ds->ds_snapname));
527 	if (err != 0 && zfs_recover == B_TRUE) {
528 		err = 0;
529 		(void) snprintf(ds->ds_snapname, sizeof (ds->ds_snapname),
530 		    "SNAPOBJ=%llu-ERR=%d",
531 		    (unsigned long long)ds->ds_object, err);
532 	}
533 	dmu_buf_rele(headdbuf, FTAG);
534 	return (err);
535 }
536 
537 int
dsl_dataset_snap_lookup(dsl_dataset_t * ds,const char * name,uint64_t * value)538 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
539 {
540 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
541 	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
542 	matchtype_t mt = 0;
543 	int err;
544 
545 	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
546 		mt = MT_NORMALIZE;
547 
548 	err = zap_lookup_norm(mos, snapobj, name, 8, 1,
549 	    value, mt, NULL, 0, NULL);
550 	if (err == ENOTSUP && (mt & MT_NORMALIZE))
551 		err = zap_lookup(mos, snapobj, name, 8, 1, value);
552 	return (err);
553 }
554 
555 int
dsl_dataset_snap_remove(dsl_dataset_t * ds,const char * name,dmu_tx_t * tx,boolean_t adj_cnt)556 dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
557     boolean_t adj_cnt)
558 {
559 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
560 	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
561 	matchtype_t mt = 0;
562 	int err;
563 
564 	dsl_dir_snap_cmtime_update(ds->ds_dir, tx);
565 
566 	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
567 		mt = MT_NORMALIZE;
568 
569 	err = zap_remove_norm(mos, snapobj, name, mt, tx);
570 	if (err == ENOTSUP && (mt & MT_NORMALIZE))
571 		err = zap_remove(mos, snapobj, name, tx);
572 
573 	if (err == 0 && adj_cnt)
574 		dsl_fs_ss_count_adjust(ds->ds_dir, -1,
575 		    DD_FIELD_SNAPSHOT_COUNT, tx);
576 
577 	return (err);
578 }
579 
580 boolean_t
dsl_dataset_try_add_ref(dsl_pool_t * dp,dsl_dataset_t * ds,const void * tag)581 dsl_dataset_try_add_ref(dsl_pool_t *dp, dsl_dataset_t *ds, const void *tag)
582 {
583 	dmu_buf_t *dbuf = ds->ds_dbuf;
584 	boolean_t result = B_FALSE;
585 
586 	if (dbuf != NULL && dmu_buf_try_add_ref(dbuf, dp->dp_meta_objset,
587 	    ds->ds_object, DMU_BONUS_BLKID, tag)) {
588 
589 		if (ds == dmu_buf_get_user(dbuf))
590 			result = B_TRUE;
591 		else
592 			dmu_buf_rele(dbuf, tag);
593 	}
594 
595 	return (result);
596 }
597 
598 int
dsl_dataset_hold_obj(dsl_pool_t * dp,uint64_t dsobj,const void * tag,dsl_dataset_t ** dsp)599 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, const void *tag,
600     dsl_dataset_t **dsp)
601 {
602 	objset_t *mos = dp->dp_meta_objset;
603 	dmu_buf_t *dbuf;
604 	dsl_dataset_t *ds;
605 	int err;
606 	dmu_object_info_t doi;
607 
608 	ASSERT(dsl_pool_config_held(dp));
609 
610 	err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
611 	if (err != 0)
612 		return (err);
613 
614 	/* Make sure dsobj has the correct object type. */
615 	dmu_object_info_from_db(dbuf, &doi);
616 	if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
617 		dmu_buf_rele(dbuf, tag);
618 		return (SET_ERROR(EINVAL));
619 	}
620 
621 	ds = dmu_buf_get_user(dbuf);
622 	if (ds == NULL) {
623 		dsl_dataset_t *winner = NULL;
624 
625 		ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
626 		ds->ds_dbuf = dbuf;
627 		ds->ds_object = dsobj;
628 		ds->ds_is_snapshot = dsl_dataset_phys(ds)->ds_num_children != 0;
629 		list_link_init(&ds->ds_synced_link);
630 
631 		err = dsl_dir_hold_obj(dp, dsl_dataset_phys(ds)->ds_dir_obj,
632 		    NULL, ds, &ds->ds_dir);
633 		if (err != 0) {
634 			kmem_free(ds, sizeof (dsl_dataset_t));
635 			dmu_buf_rele(dbuf, tag);
636 			return (err);
637 		}
638 
639 		mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
640 		mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
641 		mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
642 		mutex_init(&ds->ds_remap_deadlist_lock,
643 		    NULL, MUTEX_DEFAULT, NULL);
644 		rrw_init(&ds->ds_bp_rwlock, B_FALSE);
645 		zfs_refcount_create(&ds->ds_longholds);
646 
647 		bplist_create(&ds->ds_pending_deadlist);
648 
649 		list_create(&ds->ds_sendstreams, sizeof (dmu_sendstatus_t),
650 		    offsetof(dmu_sendstatus_t, dss_link));
651 
652 		list_create(&ds->ds_prop_cbs, sizeof (dsl_prop_cb_record_t),
653 		    offsetof(dsl_prop_cb_record_t, cbr_ds_node));
654 
655 		if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
656 			spa_feature_t f;
657 
658 			for (f = 0; f < SPA_FEATURES; f++) {
659 				if (!(spa_feature_table[f].fi_flags &
660 				    ZFEATURE_FLAG_PER_DATASET))
661 					continue;
662 				err = load_zfeature(mos, ds, f);
663 			}
664 		}
665 
666 		if (!ds->ds_is_snapshot) {
667 			ds->ds_snapname[0] = '\0';
668 			if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
669 				err = dsl_dataset_hold_obj(dp,
670 				    dsl_dataset_phys(ds)->ds_prev_snap_obj,
671 				    ds, &ds->ds_prev);
672 			}
673 			if (err != 0)
674 				goto after_dsl_bookmark_fini;
675 			err = dsl_bookmark_init_ds(ds);
676 		} else {
677 			if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
678 				err = dsl_dataset_get_snapname(ds);
679 			if (err == 0 &&
680 			    dsl_dataset_phys(ds)->ds_userrefs_obj != 0) {
681 				err = zap_count(
682 				    ds->ds_dir->dd_pool->dp_meta_objset,
683 				    dsl_dataset_phys(ds)->ds_userrefs_obj,
684 				    &ds->ds_userrefs);
685 			}
686 		}
687 
688 		if (err == 0 && !ds->ds_is_snapshot) {
689 			err = dsl_prop_get_int_ds(ds,
690 			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
691 			    &ds->ds_reserved);
692 			if (err == 0) {
693 				err = dsl_prop_get_int_ds(ds,
694 				    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
695 				    &ds->ds_quota);
696 			}
697 		} else {
698 			ds->ds_reserved = ds->ds_quota = 0;
699 		}
700 
701 		if (err == 0 && ds->ds_dir->dd_crypto_obj != 0 &&
702 		    ds->ds_is_snapshot &&
703 		    zap_contains(mos, dsobj, DS_FIELD_IVSET_GUID) != 0) {
704 			dp->dp_spa->spa_errata =
705 			    ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
706 		}
707 
708 		if (err == 0) {
709 			err = dsl_deadlist_open(&ds->ds_deadlist,
710 			    mos, dsl_dataset_phys(ds)->ds_deadlist_obj);
711 		}
712 		if (err == 0) {
713 			uint64_t remap_deadlist_obj =
714 			    dsl_dataset_get_remap_deadlist_object(ds);
715 			if (remap_deadlist_obj != 0) {
716 				err = dsl_deadlist_open(&ds->ds_remap_deadlist,
717 				    mos, remap_deadlist_obj);
718 			}
719 		}
720 
721 		dmu_buf_init_user(&ds->ds_dbu, dsl_dataset_evict_sync,
722 		    dsl_dataset_evict_async, &ds->ds_dbuf);
723 		if (err == 0)
724 			winner = dmu_buf_set_user_ie(dbuf, &ds->ds_dbu);
725 
726 		if (err != 0 || winner != NULL) {
727 			if (dsl_deadlist_is_open(&ds->ds_deadlist))
728 				dsl_deadlist_close(&ds->ds_deadlist);
729 			if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
730 				dsl_deadlist_close(&ds->ds_remap_deadlist);
731 			dsl_bookmark_fini_ds(ds);
732 after_dsl_bookmark_fini:
733 			if (ds->ds_prev)
734 				dsl_dataset_rele(ds->ds_prev, ds);
735 			dsl_dir_rele(ds->ds_dir, ds);
736 			for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
737 				if (dsl_dataset_feature_is_active(ds, f))
738 					unload_zfeature(ds, f);
739 			}
740 
741 			list_destroy(&ds->ds_prop_cbs);
742 			list_destroy(&ds->ds_sendstreams);
743 			bplist_destroy(&ds->ds_pending_deadlist);
744 			mutex_destroy(&ds->ds_lock);
745 			mutex_destroy(&ds->ds_opening_lock);
746 			mutex_destroy(&ds->ds_sendstream_lock);
747 			mutex_destroy(&ds->ds_remap_deadlist_lock);
748 			zfs_refcount_destroy(&ds->ds_longholds);
749 			rrw_destroy(&ds->ds_bp_rwlock);
750 			kmem_free(ds, sizeof (dsl_dataset_t));
751 			if (err != 0) {
752 				dmu_buf_rele(dbuf, tag);
753 				return (err);
754 			}
755 			ds = winner;
756 		} else {
757 			ds->ds_fsid_guid =
758 			    unique_insert(dsl_dataset_phys(ds)->ds_fsid_guid);
759 			if (ds->ds_fsid_guid !=
760 			    dsl_dataset_phys(ds)->ds_fsid_guid) {
761 				zfs_dbgmsg("ds_fsid_guid changed from "
762 				    "%llx to %llx for pool %s dataset id %llu",
763 				    (long long)
764 				    dsl_dataset_phys(ds)->ds_fsid_guid,
765 				    (long long)ds->ds_fsid_guid,
766 				    spa_name(dp->dp_spa),
767 				    (u_longlong_t)dsobj);
768 			}
769 		}
770 	}
771 
772 	ASSERT3P(ds->ds_dbuf, ==, dbuf);
773 	ASSERT3P(dsl_dataset_phys(ds), ==, dbuf->db_data);
774 	ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0 ||
775 	    spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
776 	    dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
777 	*dsp = ds;
778 
779 	return (0);
780 }
781 
782 int
dsl_dataset_create_key_mapping(dsl_dataset_t * ds)783 dsl_dataset_create_key_mapping(dsl_dataset_t *ds)
784 {
785 	dsl_dir_t *dd = ds->ds_dir;
786 
787 	if (dd->dd_crypto_obj == 0)
788 		return (0);
789 
790 	return (spa_keystore_create_mapping(dd->dd_pool->dp_spa,
791 	    ds, ds, &ds->ds_key_mapping));
792 }
793 
794 int
dsl_dataset_hold_obj_flags(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)795 dsl_dataset_hold_obj_flags(dsl_pool_t *dp, uint64_t dsobj,
796     ds_hold_flags_t flags, const void *tag, dsl_dataset_t **dsp)
797 {
798 	int err;
799 
800 	err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
801 	if (err != 0)
802 		return (err);
803 
804 	ASSERT3P(*dsp, !=, NULL);
805 
806 	if (flags & DS_HOLD_FLAG_DECRYPT) {
807 		err = dsl_dataset_create_key_mapping(*dsp);
808 		if (err != 0)
809 			dsl_dataset_rele(*dsp, tag);
810 	}
811 
812 	return (err);
813 }
814 
815 int
dsl_dataset_hold_flags(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)816 dsl_dataset_hold_flags(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
817     const void *tag, dsl_dataset_t **dsp)
818 {
819 	dsl_dir_t *dd;
820 	const char *snapname;
821 	uint64_t obj;
822 	int err = 0;
823 	dsl_dataset_t *ds;
824 
825 	err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
826 	if (err != 0)
827 		return (err);
828 
829 	ASSERT(dsl_pool_config_held(dp));
830 	obj = dsl_dir_phys(dd)->dd_head_dataset_obj;
831 	if (obj != 0)
832 		err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag, &ds);
833 	else
834 		err = SET_ERROR(ENOENT);
835 
836 	/* we may be looking for a snapshot */
837 	if (err == 0 && snapname != NULL) {
838 		dsl_dataset_t *snap_ds;
839 
840 		if (*snapname++ != '@') {
841 			dsl_dataset_rele_flags(ds, flags, tag);
842 			dsl_dir_rele(dd, FTAG);
843 			return (SET_ERROR(ENOENT));
844 		}
845 
846 		dprintf("looking for snapshot '%s'\n", snapname);
847 		err = dsl_dataset_snap_lookup(ds, snapname, &obj);
848 		if (err == 0) {
849 			err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag,
850 			    &snap_ds);
851 		}
852 		dsl_dataset_rele_flags(ds, flags, tag);
853 
854 		if (err == 0) {
855 			mutex_enter(&snap_ds->ds_lock);
856 			if (snap_ds->ds_snapname[0] == 0)
857 				(void) strlcpy(snap_ds->ds_snapname, snapname,
858 				    sizeof (snap_ds->ds_snapname));
859 			mutex_exit(&snap_ds->ds_lock);
860 			ds = snap_ds;
861 		}
862 	}
863 	if (err == 0)
864 		*dsp = ds;
865 	dsl_dir_rele(dd, FTAG);
866 	return (err);
867 }
868 
869 int
dsl_dataset_hold(dsl_pool_t * dp,const char * name,const void * tag,dsl_dataset_t ** dsp)870 dsl_dataset_hold(dsl_pool_t *dp, const char *name, const void *tag,
871     dsl_dataset_t **dsp)
872 {
873 	return (dsl_dataset_hold_flags(dp, name, 0, tag, dsp));
874 }
875 
876 static int
dsl_dataset_own_obj_impl(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,boolean_t override,dsl_dataset_t ** dsp)877 dsl_dataset_own_obj_impl(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
878     const void *tag, boolean_t override, dsl_dataset_t **dsp)
879 {
880 	int err = dsl_dataset_hold_obj_flags(dp, dsobj, flags, tag, dsp);
881 	if (err != 0)
882 		return (err);
883 	if (!dsl_dataset_tryown(*dsp, tag, override)) {
884 		dsl_dataset_rele_flags(*dsp, flags, tag);
885 		*dsp = NULL;
886 		return (SET_ERROR(EBUSY));
887 	}
888 	return (0);
889 }
890 
891 
892 int
dsl_dataset_own_obj(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)893 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
894     const void *tag, dsl_dataset_t **dsp)
895 {
896 	return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_FALSE, dsp));
897 }
898 
899 int
dsl_dataset_own_obj_force(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)900 dsl_dataset_own_obj_force(dsl_pool_t *dp, uint64_t dsobj,
901     ds_hold_flags_t flags, const void *tag, dsl_dataset_t **dsp)
902 {
903 	return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_TRUE, dsp));
904 }
905 
906 static int
dsl_dataset_own_impl(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,boolean_t override,dsl_dataset_t ** dsp)907 dsl_dataset_own_impl(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
908     const void *tag, boolean_t override, dsl_dataset_t **dsp)
909 {
910 	int err = dsl_dataset_hold_flags(dp, name, flags, tag, dsp);
911 	if (err != 0)
912 		return (err);
913 	if (!dsl_dataset_tryown(*dsp, tag, override)) {
914 		dsl_dataset_rele_flags(*dsp, flags, tag);
915 		return (SET_ERROR(EBUSY));
916 	}
917 	return (0);
918 }
919 
920 int
dsl_dataset_own_force(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)921 dsl_dataset_own_force(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
922     const void *tag, dsl_dataset_t **dsp)
923 {
924 	return (dsl_dataset_own_impl(dp, name, flags, tag, B_TRUE, dsp));
925 }
926 
927 int
dsl_dataset_own(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)928 dsl_dataset_own(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
929     const void *tag, dsl_dataset_t **dsp)
930 {
931 	return (dsl_dataset_own_impl(dp, name, flags, tag, B_FALSE, dsp));
932 }
933 
934 /*
935  * See the comment above dsl_pool_hold() for details.  In summary, a long
936  * hold is used to prevent destruction of a dataset while the pool hold
937  * is dropped, allowing other concurrent operations (e.g. spa_sync()).
938  *
939  * The dataset and pool must be held when this function is called.  After it
940  * is called, the pool hold may be released while the dataset is still held
941  * and accessed.
942  */
943 void
dsl_dataset_long_hold(dsl_dataset_t * ds,const void * tag)944 dsl_dataset_long_hold(dsl_dataset_t *ds, const void *tag)
945 {
946 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
947 	(void) zfs_refcount_add(&ds->ds_longholds, tag);
948 }
949 
950 void
dsl_dataset_long_rele(dsl_dataset_t * ds,const void * tag)951 dsl_dataset_long_rele(dsl_dataset_t *ds, const void *tag)
952 {
953 	(void) zfs_refcount_remove(&ds->ds_longholds, tag);
954 }
955 
956 /* Return B_TRUE if there are any long holds on this dataset. */
957 boolean_t
dsl_dataset_long_held(dsl_dataset_t * ds)958 dsl_dataset_long_held(dsl_dataset_t *ds)
959 {
960 	return (!zfs_refcount_is_zero(&ds->ds_longholds));
961 }
962 
963 void
dsl_dataset_name(dsl_dataset_t * ds,char * name)964 dsl_dataset_name(dsl_dataset_t *ds, char *name)
965 {
966 	if (ds == NULL) {
967 		(void) strlcpy(name, "mos", ZFS_MAX_DATASET_NAME_LEN);
968 	} else {
969 		dsl_dir_name(ds->ds_dir, name);
970 		VERIFY0(dsl_dataset_get_snapname(ds));
971 		if (ds->ds_snapname[0]) {
972 			VERIFY3U(strlcat(name, "@", ZFS_MAX_DATASET_NAME_LEN),
973 			    <, ZFS_MAX_DATASET_NAME_LEN);
974 			/*
975 			 * We use a "recursive" mutex so that we
976 			 * can call dprintf_ds() with ds_lock held.
977 			 */
978 			if (!MUTEX_HELD(&ds->ds_lock)) {
979 				mutex_enter(&ds->ds_lock);
980 				VERIFY3U(strlcat(name, ds->ds_snapname,
981 				    ZFS_MAX_DATASET_NAME_LEN), <,
982 				    ZFS_MAX_DATASET_NAME_LEN);
983 				mutex_exit(&ds->ds_lock);
984 			} else {
985 				VERIFY3U(strlcat(name, ds->ds_snapname,
986 				    ZFS_MAX_DATASET_NAME_LEN), <,
987 				    ZFS_MAX_DATASET_NAME_LEN);
988 			}
989 		}
990 	}
991 }
992 
993 int
dsl_dataset_namelen(dsl_dataset_t * ds)994 dsl_dataset_namelen(dsl_dataset_t *ds)
995 {
996 	VERIFY0(dsl_dataset_get_snapname(ds));
997 	mutex_enter(&ds->ds_lock);
998 	int len = strlen(ds->ds_snapname);
999 	mutex_exit(&ds->ds_lock);
1000 	/* add '@' if ds is a snap */
1001 	if (len > 0)
1002 		len++;
1003 	len += dsl_dir_namelen(ds->ds_dir);
1004 	return (len);
1005 }
1006 
1007 void
dsl_dataset_rele(dsl_dataset_t * ds,const void * tag)1008 dsl_dataset_rele(dsl_dataset_t *ds, const void *tag)
1009 {
1010 	dmu_buf_rele(ds->ds_dbuf, tag);
1011 }
1012 
1013 void
dsl_dataset_remove_key_mapping(dsl_dataset_t * ds)1014 dsl_dataset_remove_key_mapping(dsl_dataset_t *ds)
1015 {
1016 	dsl_dir_t *dd = ds->ds_dir;
1017 
1018 	if (dd == NULL || dd->dd_crypto_obj == 0)
1019 		return;
1020 
1021 	(void) spa_keystore_remove_mapping(dd->dd_pool->dp_spa,
1022 	    ds->ds_object, ds);
1023 }
1024 
1025 void
dsl_dataset_rele_flags(dsl_dataset_t * ds,ds_hold_flags_t flags,const void * tag)1026 dsl_dataset_rele_flags(dsl_dataset_t *ds, ds_hold_flags_t flags,
1027     const void *tag)
1028 {
1029 	if (flags & DS_HOLD_FLAG_DECRYPT)
1030 		dsl_dataset_remove_key_mapping(ds);
1031 
1032 	dsl_dataset_rele(ds, tag);
1033 }
1034 
1035 void
dsl_dataset_disown(dsl_dataset_t * ds,ds_hold_flags_t flags,const void * tag)1036 dsl_dataset_disown(dsl_dataset_t *ds, ds_hold_flags_t flags, const void *tag)
1037 {
1038 	ASSERT3P(ds->ds_owner, ==, tag);
1039 	ASSERT(ds->ds_dbuf != NULL);
1040 
1041 	mutex_enter(&ds->ds_lock);
1042 	ds->ds_owner = NULL;
1043 	mutex_exit(&ds->ds_lock);
1044 	dsl_dataset_long_rele(ds, tag);
1045 	dsl_dataset_rele_flags(ds, flags, tag);
1046 }
1047 
1048 boolean_t
dsl_dataset_tryown(dsl_dataset_t * ds,const void * tag,boolean_t override)1049 dsl_dataset_tryown(dsl_dataset_t *ds, const void *tag, boolean_t override)
1050 {
1051 	boolean_t gotit = FALSE;
1052 
1053 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
1054 	mutex_enter(&ds->ds_lock);
1055 	if (ds->ds_owner == NULL && (override || !(DS_IS_INCONSISTENT(ds) ||
1056 	    (dsl_dataset_feature_is_active(ds,
1057 	    SPA_FEATURE_REDACTED_DATASETS) &&
1058 	    !zfs_allow_redacted_dataset_mount)))) {
1059 		ds->ds_owner = tag;
1060 		dsl_dataset_long_hold(ds, tag);
1061 		gotit = TRUE;
1062 	}
1063 	mutex_exit(&ds->ds_lock);
1064 	return (gotit);
1065 }
1066 
1067 boolean_t
dsl_dataset_has_owner(dsl_dataset_t * ds)1068 dsl_dataset_has_owner(dsl_dataset_t *ds)
1069 {
1070 	boolean_t rv;
1071 	mutex_enter(&ds->ds_lock);
1072 	rv = (ds->ds_owner != NULL);
1073 	mutex_exit(&ds->ds_lock);
1074 	return (rv);
1075 }
1076 
1077 static boolean_t
zfeature_active(spa_feature_t f,void * arg)1078 zfeature_active(spa_feature_t f, void *arg)
1079 {
1080 	switch (spa_feature_table[f].fi_type) {
1081 	case ZFEATURE_TYPE_BOOLEAN: {
1082 		boolean_t val = (boolean_t)(uintptr_t)arg;
1083 		ASSERT(val == B_FALSE || val == B_TRUE);
1084 		return (val);
1085 	}
1086 	case ZFEATURE_TYPE_UINT64_ARRAY:
1087 		/*
1088 		 * In this case, arg is a uint64_t array.  The feature is active
1089 		 * if the array is non-null.
1090 		 */
1091 		return (arg != NULL);
1092 	default:
1093 		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1094 		return (B_FALSE);
1095 	}
1096 }
1097 
1098 boolean_t
dsl_dataset_feature_is_active(dsl_dataset_t * ds,spa_feature_t f)1099 dsl_dataset_feature_is_active(dsl_dataset_t *ds, spa_feature_t f)
1100 {
1101 	return (zfeature_active(f, ds->ds_feature[f]));
1102 }
1103 
1104 /*
1105  * The buffers passed out by this function are references to internal buffers;
1106  * they should not be freed by callers of this function, and they should not be
1107  * used after the dataset has been released.
1108  */
1109 boolean_t
dsl_dataset_get_uint64_array_feature(dsl_dataset_t * ds,spa_feature_t f,uint64_t * outlength,uint64_t ** outp)1110 dsl_dataset_get_uint64_array_feature(dsl_dataset_t *ds, spa_feature_t f,
1111     uint64_t *outlength, uint64_t **outp)
1112 {
1113 	VERIFY(spa_feature_table[f].fi_type & ZFEATURE_TYPE_UINT64_ARRAY);
1114 	if (!dsl_dataset_feature_is_active(ds, f)) {
1115 		return (B_FALSE);
1116 	}
1117 	struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
1118 	*outp = ftuaa->array;
1119 	*outlength = ftuaa->length;
1120 	return (B_TRUE);
1121 }
1122 
1123 void
dsl_dataset_activate_feature(uint64_t dsobj,spa_feature_t f,void * arg,dmu_tx_t * tx)1124 dsl_dataset_activate_feature(uint64_t dsobj, spa_feature_t f, void *arg,
1125     dmu_tx_t *tx)
1126 {
1127 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1128 	objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1129 	uint64_t zero = 0;
1130 
1131 	VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1132 
1133 	spa_feature_incr(spa, f, tx);
1134 	dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1135 
1136 	switch (spa_feature_table[f].fi_type) {
1137 	case ZFEATURE_TYPE_BOOLEAN:
1138 		ASSERT3S((boolean_t)(uintptr_t)arg, ==, B_TRUE);
1139 		VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1140 		    sizeof (zero), 1, &zero, tx));
1141 		break;
1142 	case ZFEATURE_TYPE_UINT64_ARRAY:
1143 	{
1144 		struct feature_type_uint64_array_arg *ftuaa = arg;
1145 		VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1146 		    sizeof (uint64_t), ftuaa->length, ftuaa->array, tx));
1147 		break;
1148 	}
1149 	default:
1150 		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1151 	}
1152 }
1153 
1154 static void
dsl_dataset_deactivate_feature_impl(dsl_dataset_t * ds,spa_feature_t f,dmu_tx_t * tx)1155 dsl_dataset_deactivate_feature_impl(dsl_dataset_t *ds, spa_feature_t f,
1156     dmu_tx_t *tx)
1157 {
1158 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1159 	objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1160 	uint64_t dsobj = ds->ds_object;
1161 
1162 	VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1163 
1164 	VERIFY0(zap_remove(mos, dsobj, spa_feature_table[f].fi_guid, tx));
1165 	spa_feature_decr(spa, f, tx);
1166 	ds->ds_feature[f] = NULL;
1167 }
1168 
1169 void
dsl_dataset_deactivate_feature(dsl_dataset_t * ds,spa_feature_t f,dmu_tx_t * tx)1170 dsl_dataset_deactivate_feature(dsl_dataset_t *ds, spa_feature_t f, dmu_tx_t *tx)
1171 {
1172 	unload_zfeature(ds, f);
1173 	dsl_dataset_deactivate_feature_impl(ds, f, tx);
1174 }
1175 
1176 uint64_t
dsl_dataset_create_sync_dd(dsl_dir_t * dd,dsl_dataset_t * origin,dsl_crypto_params_t * dcp,uint64_t flags,dmu_tx_t * tx)1177 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
1178     dsl_crypto_params_t *dcp, uint64_t flags, dmu_tx_t *tx)
1179 {
1180 	dsl_pool_t *dp = dd->dd_pool;
1181 	dmu_buf_t *dbuf;
1182 	dsl_dataset_phys_t *dsphys;
1183 	uint64_t dsobj;
1184 	objset_t *mos = dp->dp_meta_objset;
1185 
1186 	if (origin == NULL)
1187 		origin = dp->dp_origin_snap;
1188 
1189 	ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
1190 	ASSERT(origin == NULL || dsl_dataset_phys(origin)->ds_num_children > 0);
1191 	ASSERT(dmu_tx_is_syncing(tx));
1192 	ASSERT0(dsl_dir_phys(dd)->dd_head_dataset_obj);
1193 
1194 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1195 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1196 	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1197 	dmu_buf_will_dirty(dbuf, tx);
1198 	dsphys = dbuf->db_data;
1199 	memset(dsphys, 0, sizeof (dsl_dataset_phys_t));
1200 	dsphys->ds_dir_obj = dd->dd_object;
1201 	dsphys->ds_flags = flags;
1202 	dsphys->ds_fsid_guid = unique_create();
1203 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1204 	    sizeof (dsphys->ds_guid));
1205 	dsphys->ds_snapnames_zapobj =
1206 	    zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
1207 	    DMU_OT_NONE, 0, tx);
1208 	dsphys->ds_creation_time = gethrestime_sec();
1209 	dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
1210 
1211 	if (origin == NULL) {
1212 		dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
1213 	} else {
1214 		dsl_dataset_t *ohds; /* head of the origin snapshot */
1215 
1216 		dsphys->ds_prev_snap_obj = origin->ds_object;
1217 		dsphys->ds_prev_snap_txg =
1218 		    dsl_dataset_phys(origin)->ds_creation_txg;
1219 		dsphys->ds_referenced_bytes =
1220 		    dsl_dataset_phys(origin)->ds_referenced_bytes;
1221 		dsphys->ds_compressed_bytes =
1222 		    dsl_dataset_phys(origin)->ds_compressed_bytes;
1223 		dsphys->ds_uncompressed_bytes =
1224 		    dsl_dataset_phys(origin)->ds_uncompressed_bytes;
1225 		rrw_enter(&origin->ds_bp_rwlock, RW_READER, FTAG);
1226 		dsphys->ds_bp = dsl_dataset_phys(origin)->ds_bp;
1227 		rrw_exit(&origin->ds_bp_rwlock, FTAG);
1228 
1229 		/*
1230 		 * Inherit flags that describe the dataset's contents
1231 		 * (INCONSISTENT) or properties (Case Insensitive).
1232 		 */
1233 		dsphys->ds_flags |= dsl_dataset_phys(origin)->ds_flags &
1234 		    (DS_FLAG_INCONSISTENT | DS_FLAG_CI_DATASET);
1235 
1236 		for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1237 			if (zfeature_active(f, origin->ds_feature[f])) {
1238 				dsl_dataset_activate_feature(dsobj, f,
1239 				    origin->ds_feature[f], tx);
1240 			}
1241 		}
1242 
1243 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
1244 		dsl_dataset_phys(origin)->ds_num_children++;
1245 
1246 		VERIFY0(dsl_dataset_hold_obj(dp,
1247 		    dsl_dir_phys(origin->ds_dir)->dd_head_dataset_obj,
1248 		    FTAG, &ohds));
1249 		dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
1250 		    dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
1251 		dsl_dataset_rele(ohds, FTAG);
1252 
1253 		if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
1254 			if (dsl_dataset_phys(origin)->ds_next_clones_obj == 0) {
1255 				dsl_dataset_phys(origin)->ds_next_clones_obj =
1256 				    zap_create(mos,
1257 				    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
1258 			}
1259 			VERIFY0(zap_add_int(mos,
1260 			    dsl_dataset_phys(origin)->ds_next_clones_obj,
1261 			    dsobj, tx));
1262 		}
1263 
1264 		dmu_buf_will_dirty(dd->dd_dbuf, tx);
1265 		dsl_dir_phys(dd)->dd_origin_obj = origin->ds_object;
1266 		if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
1267 			if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1268 				dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1269 				dsl_dir_phys(origin->ds_dir)->dd_clones =
1270 				    zap_create(mos,
1271 				    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
1272 			}
1273 			VERIFY0(zap_add_int(mos,
1274 			    dsl_dir_phys(origin->ds_dir)->dd_clones,
1275 			    dsobj, tx));
1276 		}
1277 	}
1278 
1279 	/* handle encryption */
1280 	dsl_dataset_create_crypt_sync(dsobj, dd, origin, dcp, tx);
1281 
1282 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1283 		dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1284 
1285 	dmu_buf_rele(dbuf, FTAG);
1286 
1287 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1288 	dsl_dir_phys(dd)->dd_head_dataset_obj = dsobj;
1289 
1290 	return (dsobj);
1291 }
1292 
1293 static void
dsl_dataset_zero_zil(dsl_dataset_t * ds,dmu_tx_t * tx)1294 dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
1295 {
1296 	objset_t *os;
1297 
1298 	VERIFY0(dmu_objset_from_ds(ds, &os));
1299 	if (memcmp(&os->os_zil_header, &zero_zil, sizeof (zero_zil)) != 0) {
1300 		dsl_pool_t *dp = ds->ds_dir->dd_pool;
1301 		zio_t *zio;
1302 
1303 		memset(&os->os_zil_header, 0, sizeof (os->os_zil_header));
1304 		if (os->os_encrypted)
1305 			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1306 
1307 		zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1308 		dsl_dataset_sync(ds, zio, tx);
1309 		VERIFY0(zio_wait(zio));
1310 		dsl_dataset_sync_done(ds, tx);
1311 	}
1312 }
1313 
1314 uint64_t
dsl_dataset_create_sync(dsl_dir_t * pdd,const char * lastname,dsl_dataset_t * origin,uint64_t flags,cred_t * cr,dsl_crypto_params_t * dcp,dmu_tx_t * tx)1315 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
1316     dsl_dataset_t *origin, uint64_t flags, cred_t *cr,
1317     dsl_crypto_params_t *dcp, dmu_tx_t *tx)
1318 {
1319 	dsl_pool_t *dp = pdd->dd_pool;
1320 	uint64_t dsobj, ddobj;
1321 	dsl_dir_t *dd;
1322 
1323 	ASSERT(dmu_tx_is_syncing(tx));
1324 	ASSERT(lastname[0] != '@');
1325 	/*
1326 	 * Filesystems will eventually have their origin set to dp_origin_snap,
1327 	 * but that's taken care of in dsl_dataset_create_sync_dd. When
1328 	 * creating a filesystem, this function is called with origin equal to
1329 	 * NULL.
1330 	 */
1331 	if (origin != NULL)
1332 		ASSERT3P(origin, !=, dp->dp_origin_snap);
1333 
1334 	ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
1335 	VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
1336 
1337 	dsobj = dsl_dataset_create_sync_dd(dd, origin, dcp,
1338 	    flags & ~DS_CREATE_FLAG_NODIRTY, tx);
1339 
1340 	dsl_deleg_set_create_perms(dd, tx, cr);
1341 
1342 	/*
1343 	 * If we are creating a clone and the livelist feature is enabled,
1344 	 * add the entry DD_FIELD_LIVELIST to ZAP.
1345 	 */
1346 	if (origin != NULL &&
1347 	    spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LIVELIST)) {
1348 		objset_t *mos = dd->dd_pool->dp_meta_objset;
1349 		dsl_dir_zapify(dd, tx);
1350 		uint64_t obj = dsl_deadlist_alloc(mos, tx);
1351 		VERIFY0(zap_add(mos, dd->dd_object, DD_FIELD_LIVELIST,
1352 		    sizeof (uint64_t), 1, &obj, tx));
1353 		spa_feature_incr(dp->dp_spa, SPA_FEATURE_LIVELIST, tx);
1354 	}
1355 
1356 	/*
1357 	 * Since we're creating a new node we know it's a leaf, so we can
1358 	 * initialize the counts if the limit feature is active.
1359 	 */
1360 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
1361 		uint64_t cnt = 0;
1362 		objset_t *os = dd->dd_pool->dp_meta_objset;
1363 
1364 		dsl_dir_zapify(dd, tx);
1365 		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
1366 		    sizeof (cnt), 1, &cnt, tx));
1367 		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
1368 		    sizeof (cnt), 1, &cnt, tx));
1369 	}
1370 
1371 	dsl_dir_rele(dd, FTAG);
1372 
1373 	/*
1374 	 * If we are creating a clone, make sure we zero out any stale
1375 	 * data from the origin snapshots zil header.
1376 	 */
1377 	if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
1378 		dsl_dataset_t *ds;
1379 
1380 		VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1381 		dsl_dataset_zero_zil(ds, tx);
1382 		dsl_dataset_rele(ds, FTAG);
1383 	}
1384 
1385 	return (dsobj);
1386 }
1387 
1388 /*
1389  * The unique space in the head dataset can be calculated by subtracting
1390  * the space used in the most recent snapshot, that is still being used
1391  * in this file system, from the space currently in use.  To figure out
1392  * the space in the most recent snapshot still in use, we need to take
1393  * the total space used in the snapshot and subtract out the space that
1394  * has been freed up since the snapshot was taken.
1395  */
1396 void
dsl_dataset_recalc_head_uniq(dsl_dataset_t * ds)1397 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1398 {
1399 	uint64_t mrs_used;
1400 	uint64_t dlused, dlcomp, dluncomp;
1401 
1402 	ASSERT(!ds->ds_is_snapshot);
1403 
1404 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0)
1405 		mrs_used = dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes;
1406 	else
1407 		mrs_used = 0;
1408 
1409 	dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
1410 
1411 	ASSERT3U(dlused, <=, mrs_used);
1412 	dsl_dataset_phys(ds)->ds_unique_bytes =
1413 	    dsl_dataset_phys(ds)->ds_referenced_bytes - (mrs_used - dlused);
1414 
1415 	if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1416 	    SPA_VERSION_UNIQUE_ACCURATE)
1417 		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1418 }
1419 
1420 void
dsl_dataset_remove_from_next_clones(dsl_dataset_t * ds,uint64_t obj,dmu_tx_t * tx)1421 dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
1422     dmu_tx_t *tx)
1423 {
1424 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1425 	uint64_t count __maybe_unused;
1426 	int err;
1427 
1428 	ASSERT(dsl_dataset_phys(ds)->ds_num_children >= 2);
1429 	err = zap_remove_int(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1430 	    obj, tx);
1431 	/*
1432 	 * The err should not be ENOENT, but a bug in a previous version
1433 	 * of the code could cause upgrade_clones_cb() to not set
1434 	 * ds_next_snap_obj when it should, leading to a missing entry.
1435 	 * If we knew that the pool was created after
1436 	 * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
1437 	 * ENOENT.  However, at least we can check that we don't have
1438 	 * too many entries in the next_clones_obj even after failing to
1439 	 * remove this one.
1440 	 */
1441 	if (err != ENOENT)
1442 		VERIFY0(err);
1443 	ASSERT0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1444 	    &count));
1445 	ASSERT3U(count, <=, dsl_dataset_phys(ds)->ds_num_children - 2);
1446 }
1447 
1448 
1449 blkptr_t *
dsl_dataset_get_blkptr(dsl_dataset_t * ds)1450 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1451 {
1452 	return (&dsl_dataset_phys(ds)->ds_bp);
1453 }
1454 
1455 spa_t *
dsl_dataset_get_spa(dsl_dataset_t * ds)1456 dsl_dataset_get_spa(dsl_dataset_t *ds)
1457 {
1458 	return (ds->ds_dir->dd_pool->dp_spa);
1459 }
1460 
1461 void
dsl_dataset_dirty(dsl_dataset_t * ds,dmu_tx_t * tx)1462 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1463 {
1464 	dsl_pool_t *dp;
1465 
1466 	if (ds == NULL) /* this is the meta-objset */
1467 		return;
1468 
1469 	ASSERT(ds->ds_objset != NULL);
1470 
1471 	if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0)
1472 		panic("dirtying snapshot!");
1473 
1474 	/* Must not dirty a dataset in the same txg where it got snapshotted. */
1475 	ASSERT3U(tx->tx_txg, >, dsl_dataset_phys(ds)->ds_prev_snap_txg);
1476 
1477 	dp = ds->ds_dir->dd_pool;
1478 	if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
1479 		objset_t *os = ds->ds_objset;
1480 
1481 		/* up the hold count until we can be written out */
1482 		dmu_buf_add_ref(ds->ds_dbuf, ds);
1483 
1484 		/* if this dataset is encrypted, grab a reference to the DCK */
1485 		if (ds->ds_dir->dd_crypto_obj != 0 &&
1486 		    !os->os_raw_receive &&
1487 		    !os->os_next_write_raw[tx->tx_txg & TXG_MASK]) {
1488 			ASSERT3P(ds->ds_key_mapping, !=, NULL);
1489 			key_mapping_add_ref(ds->ds_key_mapping, ds);
1490 		}
1491 	}
1492 }
1493 
1494 static int
dsl_dataset_snapshot_reserve_space(dsl_dataset_t * ds,dmu_tx_t * tx)1495 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1496 {
1497 	uint64_t asize;
1498 
1499 	if (!dmu_tx_is_syncing(tx))
1500 		return (0);
1501 
1502 	/*
1503 	 * If there's an fs-only reservation, any blocks that might become
1504 	 * owned by the snapshot dataset must be accommodated by space
1505 	 * outside of the reservation.
1506 	 */
1507 	ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
1508 	asize = MIN(dsl_dataset_phys(ds)->ds_unique_bytes, ds->ds_reserved);
1509 	if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
1510 		return (SET_ERROR(ENOSPC));
1511 
1512 	/*
1513 	 * Propagate any reserved space for this snapshot to other
1514 	 * snapshot checks in this sync group.
1515 	 */
1516 	if (asize > 0)
1517 		dsl_dir_willuse_space(ds->ds_dir, asize, tx);
1518 
1519 	return (0);
1520 }
1521 
1522 int
dsl_dataset_snapshot_check_impl(dsl_dataset_t * ds,const char * snapname,dmu_tx_t * tx,boolean_t recv,uint64_t cnt,cred_t * cr)1523 dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1524     dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr)
1525 {
1526 	int error;
1527 	uint64_t value;
1528 
1529 	ds->ds_trysnap_txg = tx->tx_txg;
1530 
1531 	if (!dmu_tx_is_syncing(tx))
1532 		return (0);
1533 
1534 	/*
1535 	 * We don't allow multiple snapshots of the same txg.  If there
1536 	 * is already one, try again.
1537 	 */
1538 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg)
1539 		return (SET_ERROR(EAGAIN));
1540 
1541 	/*
1542 	 * Check for conflicting snapshot name.
1543 	 */
1544 	error = dsl_dataset_snap_lookup(ds, snapname, &value);
1545 	if (error == 0)
1546 		return (SET_ERROR(EEXIST));
1547 	if (error != ENOENT)
1548 		return (error);
1549 
1550 	/*
1551 	 * We don't allow taking snapshots of inconsistent datasets, such as
1552 	 * those into which we are currently receiving.  However, if we are
1553 	 * creating this snapshot as part of a receive, this check will be
1554 	 * executed atomically with respect to the completion of the receive
1555 	 * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1556 	 * case we ignore this, knowing it will be fixed up for us shortly in
1557 	 * dmu_recv_end_sync().
1558 	 */
1559 	if (!recv && DS_IS_INCONSISTENT(ds))
1560 		return (SET_ERROR(EBUSY));
1561 
1562 	/*
1563 	 * Skip the check for temporary snapshots or if we have already checked
1564 	 * the counts in dsl_dataset_snapshot_check. This means we really only
1565 	 * check the count here when we're receiving a stream.
1566 	 */
1567 	if (cnt != 0 && cr != NULL) {
1568 		error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1569 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr);
1570 		if (error != 0)
1571 			return (error);
1572 	}
1573 
1574 	error = dsl_dataset_snapshot_reserve_space(ds, tx);
1575 	if (error != 0)
1576 		return (error);
1577 
1578 	return (0);
1579 }
1580 
1581 int
dsl_dataset_snapshot_check(void * arg,dmu_tx_t * tx)1582 dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1583 {
1584 	dsl_dataset_snapshot_arg_t *ddsa = arg;
1585 	dsl_pool_t *dp = dmu_tx_pool(tx);
1586 	nvpair_t *pair;
1587 	int rv = 0;
1588 
1589 	/*
1590 	 * Pre-compute how many total new snapshots will be created for each
1591 	 * level in the tree and below. This is needed for validating the
1592 	 * snapshot limit when either taking a recursive snapshot or when
1593 	 * taking multiple snapshots.
1594 	 *
1595 	 * The problem is that the counts are not actually adjusted when
1596 	 * we are checking, only when we finally sync. For a single snapshot,
1597 	 * this is easy, the count will increase by 1 at each node up the tree,
1598 	 * but its more complicated for the recursive/multiple snapshot case.
1599 	 *
1600 	 * The dsl_fs_ss_limit_check function does recursively check the count
1601 	 * at each level up the tree but since it is validating each snapshot
1602 	 * independently we need to be sure that we are validating the complete
1603 	 * count for the entire set of snapshots. We do this by rolling up the
1604 	 * counts for each component of the name into an nvlist and then
1605 	 * checking each of those cases with the aggregated count.
1606 	 *
1607 	 * This approach properly handles not only the recursive snapshot
1608 	 * case (where we get all of those on the ddsa_snaps list) but also
1609 	 * the sibling case (e.g. snapshot a/b and a/c so that we will also
1610 	 * validate the limit on 'a' using a count of 2).
1611 	 *
1612 	 * We validate the snapshot names in the third loop and only report
1613 	 * name errors once.
1614 	 */
1615 	if (dmu_tx_is_syncing(tx)) {
1616 		char *nm;
1617 		nvlist_t *cnt_track = NULL;
1618 		cnt_track = fnvlist_alloc();
1619 
1620 		nm = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1621 
1622 		/* Rollup aggregated counts into the cnt_track list */
1623 		for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1624 		    pair != NULL;
1625 		    pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1626 			char *pdelim;
1627 			uint64_t val;
1628 
1629 			(void) strlcpy(nm, nvpair_name(pair), MAXPATHLEN);
1630 			pdelim = strchr(nm, '@');
1631 			if (pdelim == NULL)
1632 				continue;
1633 			*pdelim = '\0';
1634 
1635 			do {
1636 				if (nvlist_lookup_uint64(cnt_track, nm,
1637 				    &val) == 0) {
1638 					/* update existing entry */
1639 					fnvlist_add_uint64(cnt_track, nm,
1640 					    val + 1);
1641 				} else {
1642 					/* add to list */
1643 					fnvlist_add_uint64(cnt_track, nm, 1);
1644 				}
1645 
1646 				pdelim = strrchr(nm, '/');
1647 				if (pdelim != NULL)
1648 					*pdelim = '\0';
1649 			} while (pdelim != NULL);
1650 		}
1651 
1652 		kmem_free(nm, MAXPATHLEN);
1653 
1654 		/* Check aggregated counts at each level */
1655 		for (pair = nvlist_next_nvpair(cnt_track, NULL);
1656 		    pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1657 			int error = 0;
1658 			const char *name;
1659 			uint64_t cnt = 0;
1660 			dsl_dataset_t *ds;
1661 
1662 			name = nvpair_name(pair);
1663 			cnt = fnvpair_value_uint64(pair);
1664 			ASSERT(cnt > 0);
1665 
1666 			error = dsl_dataset_hold(dp, name, FTAG, &ds);
1667 			if (error == 0) {
1668 				error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1669 				    ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1670 				    ddsa->ddsa_cr);
1671 				dsl_dataset_rele(ds, FTAG);
1672 			}
1673 
1674 			if (error != 0) {
1675 				if (ddsa->ddsa_errors != NULL)
1676 					fnvlist_add_int32(ddsa->ddsa_errors,
1677 					    name, error);
1678 				rv = error;
1679 				/* only report one error for this check */
1680 				break;
1681 			}
1682 		}
1683 		nvlist_free(cnt_track);
1684 	}
1685 
1686 	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1687 	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1688 		int error = 0;
1689 		dsl_dataset_t *ds;
1690 		const char *name, *atp = NULL;
1691 		char dsname[ZFS_MAX_DATASET_NAME_LEN];
1692 
1693 		name = nvpair_name(pair);
1694 		if (strlen(name) >= ZFS_MAX_DATASET_NAME_LEN)
1695 			error = SET_ERROR(ENAMETOOLONG);
1696 		if (error == 0) {
1697 			atp = strchr(name, '@');
1698 			if (atp == NULL)
1699 				error = SET_ERROR(EINVAL);
1700 			if (error == 0)
1701 				(void) strlcpy(dsname, name, atp - name + 1);
1702 		}
1703 		if (error == 0)
1704 			error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1705 		if (error == 0) {
1706 			/* passing 0/NULL skips dsl_fs_ss_limit_check */
1707 			error = dsl_dataset_snapshot_check_impl(ds,
1708 			    atp + 1, tx, B_FALSE, 0, NULL);
1709 			dsl_dataset_rele(ds, FTAG);
1710 		}
1711 
1712 		if (error != 0) {
1713 			if (ddsa->ddsa_errors != NULL) {
1714 				fnvlist_add_int32(ddsa->ddsa_errors,
1715 				    name, error);
1716 			}
1717 			rv = error;
1718 		}
1719 	}
1720 
1721 	return (rv);
1722 }
1723 
1724 void
dsl_dataset_snapshot_sync_impl(dsl_dataset_t * ds,const char * snapname,dmu_tx_t * tx)1725 dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1726     dmu_tx_t *tx)
1727 {
1728 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1729 	dmu_buf_t *dbuf;
1730 	dsl_dataset_phys_t *dsphys;
1731 	uint64_t dsobj, crtxg;
1732 	objset_t *mos = dp->dp_meta_objset;
1733 	objset_t *os __maybe_unused;
1734 
1735 	ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1736 
1737 	/*
1738 	 * If we are on an old pool, the zil must not be active, in which
1739 	 * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1740 	 */
1741 	ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1742 	    dmu_objset_from_ds(ds, &os) != 0 ||
1743 	    memcmp(&os->os_phys->os_zil_header, &zero_zil,
1744 	    sizeof (zero_zil)) == 0);
1745 
1746 	/* Should not snapshot a dirty dataset. */
1747 	ASSERT(!txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
1748 	    ds, tx->tx_txg));
1749 
1750 	dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1751 
1752 	/*
1753 	 * The origin's ds_creation_txg has to be < TXG_INITIAL
1754 	 */
1755 	if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1756 		crtxg = 1;
1757 	else
1758 		crtxg = tx->tx_txg;
1759 
1760 	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1761 	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1762 	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1763 	dmu_buf_will_dirty(dbuf, tx);
1764 	dsphys = dbuf->db_data;
1765 	memset(dsphys, 0, sizeof (dsl_dataset_phys_t));
1766 	dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1767 	dsphys->ds_fsid_guid = unique_create();
1768 	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1769 	    sizeof (dsphys->ds_guid));
1770 	dsphys->ds_prev_snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1771 	dsphys->ds_prev_snap_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1772 	dsphys->ds_next_snap_obj = ds->ds_object;
1773 	dsphys->ds_num_children = 1;
1774 	dsphys->ds_creation_time = gethrestime_sec();
1775 	dsphys->ds_creation_txg = crtxg;
1776 	dsphys->ds_deadlist_obj = dsl_dataset_phys(ds)->ds_deadlist_obj;
1777 	dsphys->ds_referenced_bytes = dsl_dataset_phys(ds)->ds_referenced_bytes;
1778 	dsphys->ds_compressed_bytes = dsl_dataset_phys(ds)->ds_compressed_bytes;
1779 	dsphys->ds_uncompressed_bytes =
1780 	    dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1781 	dsphys->ds_flags = dsl_dataset_phys(ds)->ds_flags;
1782 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1783 	dsphys->ds_bp = dsl_dataset_phys(ds)->ds_bp;
1784 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1785 	dmu_buf_rele(dbuf, FTAG);
1786 
1787 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1788 		if (zfeature_active(f, ds->ds_feature[f])) {
1789 			dsl_dataset_activate_feature(dsobj, f,
1790 			    ds->ds_feature[f], tx);
1791 		}
1792 	}
1793 
1794 	ASSERT3U(ds->ds_prev != 0, ==,
1795 	    dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1796 	if (ds->ds_prev) {
1797 		uint64_t next_clones_obj =
1798 		    dsl_dataset_phys(ds->ds_prev)->ds_next_clones_obj;
1799 		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1800 		    ds->ds_object ||
1801 		    dsl_dataset_phys(ds->ds_prev)->ds_num_children > 1);
1802 		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1803 		    ds->ds_object) {
1804 			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1805 			ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, ==,
1806 			    dsl_dataset_phys(ds->ds_prev)->ds_creation_txg);
1807 			dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj = dsobj;
1808 		} else if (next_clones_obj != 0) {
1809 			dsl_dataset_remove_from_next_clones(ds->ds_prev,
1810 			    dsphys->ds_next_snap_obj, tx);
1811 			VERIFY0(zap_add_int(mos,
1812 			    next_clones_obj, dsobj, tx));
1813 		}
1814 	}
1815 
1816 	/*
1817 	 * If we have a reference-reservation on this dataset, we will
1818 	 * need to increase the amount of refreservation being charged
1819 	 * since our unique space is going to zero.
1820 	 */
1821 	if (ds->ds_reserved) {
1822 		int64_t delta;
1823 		ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1824 		delta = MIN(dsl_dataset_phys(ds)->ds_unique_bytes,
1825 		    ds->ds_reserved);
1826 		dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1827 		    delta, 0, 0, tx);
1828 	}
1829 
1830 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1831 	dsl_dataset_phys(ds)->ds_deadlist_obj =
1832 	    dsl_deadlist_clone(&ds->ds_deadlist, UINT64_MAX,
1833 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
1834 	dsl_deadlist_close(&ds->ds_deadlist);
1835 	VERIFY0(dsl_deadlist_open(&ds->ds_deadlist, mos,
1836 	    dsl_dataset_phys(ds)->ds_deadlist_obj));
1837 	dsl_deadlist_add_key(&ds->ds_deadlist,
1838 	    dsl_dataset_phys(ds)->ds_prev_snap_txg, tx);
1839 	dsl_bookmark_snapshotted(ds, tx);
1840 
1841 	if (dsl_dataset_remap_deadlist_exists(ds)) {
1842 		uint64_t remap_deadlist_obj =
1843 		    dsl_dataset_get_remap_deadlist_object(ds);
1844 		/*
1845 		 * Move the remap_deadlist to the snapshot.  The head
1846 		 * will create a new remap deadlist on demand, from
1847 		 * dsl_dataset_block_remapped().
1848 		 */
1849 		dsl_dataset_unset_remap_deadlist_object(ds, tx);
1850 		dsl_deadlist_close(&ds->ds_remap_deadlist);
1851 
1852 		dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1853 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_REMAP_DEADLIST,
1854 		    sizeof (remap_deadlist_obj), 1, &remap_deadlist_obj, tx));
1855 	}
1856 
1857 	/*
1858 	 * Create a ivset guid for this snapshot if the dataset is
1859 	 * encrypted. This may be overridden by a raw receive. A
1860 	 * previous implementation of this code did not have this
1861 	 * field as part of the on-disk format for ZFS encryption
1862 	 * (see errata #4). As part of the remediation for this
1863 	 * issue, we ask the user to enable the bookmark_v2 feature
1864 	 * which is now a dependency of the encryption feature. We
1865 	 * use this as a heuristic to determine when the user has
1866 	 * elected to correct any datasets created with the old code.
1867 	 * As a result, we only do this step if the bookmark_v2
1868 	 * feature is enabled, which limits the number of states a
1869 	 * given pool / dataset can be in with regards to terms of
1870 	 * correcting the issue.
1871 	 */
1872 	if (ds->ds_dir->dd_crypto_obj != 0 &&
1873 	    spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_BOOKMARK_V2)) {
1874 		uint64_t ivset_guid = unique_create();
1875 
1876 		dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1877 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_IVSET_GUID,
1878 		    sizeof (ivset_guid), 1, &ivset_guid, tx));
1879 	}
1880 
1881 	ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, <, tx->tx_txg);
1882 	dsl_dataset_phys(ds)->ds_prev_snap_obj = dsobj;
1883 	dsl_dataset_phys(ds)->ds_prev_snap_txg = crtxg;
1884 	dsl_dataset_phys(ds)->ds_unique_bytes = 0;
1885 
1886 	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1887 		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1888 
1889 	VERIFY0(zap_add(mos, dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1890 	    snapname, 8, 1, &dsobj, tx));
1891 
1892 	if (ds->ds_prev)
1893 		dsl_dataset_rele(ds->ds_prev, ds);
1894 	VERIFY0(dsl_dataset_hold_obj(dp,
1895 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, ds, &ds->ds_prev));
1896 
1897 	dsl_scan_ds_snapshotted(ds, tx);
1898 
1899 	dsl_dir_snap_cmtime_update(ds->ds_dir, tx);
1900 
1901 	if (zfs_snapshot_history_enabled)
1902 		spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, " ");
1903 }
1904 
1905 void
dsl_dataset_snapshot_sync(void * arg,dmu_tx_t * tx)1906 dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1907 {
1908 	dsl_dataset_snapshot_arg_t *ddsa = arg;
1909 	dsl_pool_t *dp = dmu_tx_pool(tx);
1910 	nvpair_t *pair;
1911 
1912 	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1913 	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1914 		dsl_dataset_t *ds;
1915 		const char *name, *atp;
1916 		char dsname[ZFS_MAX_DATASET_NAME_LEN];
1917 
1918 		name = nvpair_name(pair);
1919 		atp = strchr(name, '@');
1920 		(void) strlcpy(dsname, name, atp - name + 1);
1921 		VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1922 
1923 		dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1924 		if (ddsa->ddsa_props != NULL) {
1925 			dsl_props_set_sync_impl(ds->ds_prev,
1926 			    ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1927 		}
1928 		dsl_dataset_rele(ds, FTAG);
1929 	}
1930 }
1931 
1932 /*
1933  * The snapshots must all be in the same pool.
1934  * All-or-nothing: if there are any failures, nothing will be modified.
1935  */
1936 int
dsl_dataset_snapshot(nvlist_t * snaps,nvlist_t * props,nvlist_t * errors)1937 dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1938 {
1939 	dsl_dataset_snapshot_arg_t ddsa;
1940 	nvpair_t *pair;
1941 	boolean_t needsuspend;
1942 	int error;
1943 	spa_t *spa;
1944 	const char *firstname;
1945 	nvlist_t *suspended = NULL;
1946 
1947 	pair = nvlist_next_nvpair(snaps, NULL);
1948 	if (pair == NULL)
1949 		return (0);
1950 	firstname = nvpair_name(pair);
1951 
1952 	error = spa_open(firstname, &spa, FTAG);
1953 	if (error != 0)
1954 		return (error);
1955 	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1956 	spa_close(spa, FTAG);
1957 
1958 	if (needsuspend) {
1959 		suspended = fnvlist_alloc();
1960 		for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1961 		    pair = nvlist_next_nvpair(snaps, pair)) {
1962 			char fsname[ZFS_MAX_DATASET_NAME_LEN];
1963 			const char *snapname = nvpair_name(pair);
1964 			const char *atp;
1965 			void *cookie;
1966 
1967 			atp = strchr(snapname, '@');
1968 			if (atp == NULL) {
1969 				error = SET_ERROR(EINVAL);
1970 				break;
1971 			}
1972 			(void) strlcpy(fsname, snapname, atp - snapname + 1);
1973 
1974 			error = zil_suspend(fsname, &cookie);
1975 			if (error != 0)
1976 				break;
1977 			fnvlist_add_uint64(suspended, fsname,
1978 			    (uintptr_t)cookie);
1979 		}
1980 	}
1981 
1982 	cred_t *cr = CRED();
1983 	crhold(cr);
1984 
1985 	ddsa.ddsa_snaps = snaps;
1986 	ddsa.ddsa_props = props;
1987 	ddsa.ddsa_errors = errors;
1988 	ddsa.ddsa_cr = cr;
1989 
1990 	if (error == 0) {
1991 		error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1992 		    dsl_dataset_snapshot_sync, &ddsa,
1993 		    fnvlist_num_pairs(snaps) * 3, ZFS_SPACE_CHECK_NORMAL);
1994 	}
1995 
1996 	crfree(cr);
1997 
1998 	if (suspended != NULL) {
1999 		for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
2000 		    pair = nvlist_next_nvpair(suspended, pair)) {
2001 			zil_resume((void *)(uintptr_t)
2002 			    fnvpair_value_uint64(pair));
2003 		}
2004 		fnvlist_free(suspended);
2005 	}
2006 
2007 	if (error == 0) {
2008 		for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
2009 		    pair = nvlist_next_nvpair(snaps, pair)) {
2010 			zvol_create_minors(nvpair_name(pair));
2011 		}
2012 	}
2013 
2014 	return (error);
2015 }
2016 
2017 typedef struct dsl_dataset_snapshot_tmp_arg {
2018 	const char *ddsta_fsname;
2019 	const char *ddsta_snapname;
2020 	minor_t ddsta_cleanup_minor;
2021 	const char *ddsta_htag;
2022 } dsl_dataset_snapshot_tmp_arg_t;
2023 
2024 static int
dsl_dataset_snapshot_tmp_check(void * arg,dmu_tx_t * tx)2025 dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
2026 {
2027 	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
2028 	dsl_pool_t *dp = dmu_tx_pool(tx);
2029 	dsl_dataset_t *ds;
2030 	int error;
2031 
2032 	error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
2033 	if (error != 0)
2034 		return (error);
2035 
2036 	/* NULL cred means no limit check for tmp snapshot */
2037 	error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
2038 	    tx, B_FALSE, 0, NULL);
2039 	if (error != 0) {
2040 		dsl_dataset_rele(ds, FTAG);
2041 		return (error);
2042 	}
2043 
2044 	if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
2045 		dsl_dataset_rele(ds, FTAG);
2046 		return (SET_ERROR(ENOTSUP));
2047 	}
2048 	error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
2049 	    B_TRUE, tx);
2050 	if (error != 0) {
2051 		dsl_dataset_rele(ds, FTAG);
2052 		return (error);
2053 	}
2054 
2055 	dsl_dataset_rele(ds, FTAG);
2056 	return (0);
2057 }
2058 
2059 static void
dsl_dataset_snapshot_tmp_sync(void * arg,dmu_tx_t * tx)2060 dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
2061 {
2062 	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
2063 	dsl_pool_t *dp = dmu_tx_pool(tx);
2064 	dsl_dataset_t *ds = NULL;
2065 
2066 	VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
2067 
2068 	dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
2069 	dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
2070 	    ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
2071 	dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
2072 
2073 	dsl_dataset_rele(ds, FTAG);
2074 }
2075 
2076 int
dsl_dataset_snapshot_tmp(const char * fsname,const char * snapname,minor_t cleanup_minor,const char * htag)2077 dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
2078     minor_t cleanup_minor, const char *htag)
2079 {
2080 	dsl_dataset_snapshot_tmp_arg_t ddsta;
2081 	int error;
2082 	spa_t *spa;
2083 	boolean_t needsuspend;
2084 	void *cookie;
2085 
2086 	ddsta.ddsta_fsname = fsname;
2087 	ddsta.ddsta_snapname = snapname;
2088 	ddsta.ddsta_cleanup_minor = cleanup_minor;
2089 	ddsta.ddsta_htag = htag;
2090 
2091 	error = spa_open(fsname, &spa, FTAG);
2092 	if (error != 0)
2093 		return (error);
2094 	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
2095 	spa_close(spa, FTAG);
2096 
2097 	if (needsuspend) {
2098 		error = zil_suspend(fsname, &cookie);
2099 		if (error != 0)
2100 			return (error);
2101 	}
2102 
2103 	error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
2104 	    dsl_dataset_snapshot_tmp_sync, &ddsta, 3, ZFS_SPACE_CHECK_RESERVED);
2105 
2106 	if (needsuspend)
2107 		zil_resume(cookie);
2108 	return (error);
2109 }
2110 
2111 /* Nonblocking dataset sync. Assumes dataset:objset is always 1:1 */
2112 void
dsl_dataset_sync(dsl_dataset_t * ds,zio_t * rio,dmu_tx_t * tx)2113 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *rio, dmu_tx_t *tx)
2114 {
2115 	ASSERT(dmu_tx_is_syncing(tx));
2116 	ASSERT(ds->ds_objset != NULL);
2117 	ASSERT0(dsl_dataset_phys(ds)->ds_next_snap_obj);
2118 
2119 	/*
2120 	 * in case we had to change ds_fsid_guid when we opened it,
2121 	 * sync it out now.
2122 	 */
2123 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2124 	dsl_dataset_phys(ds)->ds_fsid_guid = ds->ds_fsid_guid;
2125 
2126 	if (ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] != 0) {
2127 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2128 		    ds->ds_object, DS_FIELD_RESUME_OBJECT, 8, 1,
2129 		    &ds->ds_resume_object[tx->tx_txg & TXG_MASK], tx));
2130 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2131 		    ds->ds_object, DS_FIELD_RESUME_OFFSET, 8, 1,
2132 		    &ds->ds_resume_offset[tx->tx_txg & TXG_MASK], tx));
2133 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2134 		    ds->ds_object, DS_FIELD_RESUME_BYTES, 8, 1,
2135 		    &ds->ds_resume_bytes[tx->tx_txg & TXG_MASK], tx));
2136 		ds->ds_resume_object[tx->tx_txg & TXG_MASK] = 0;
2137 		ds->ds_resume_offset[tx->tx_txg & TXG_MASK] = 0;
2138 		ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] = 0;
2139 	}
2140 
2141 	dmu_objset_sync(ds->ds_objset, rio, tx);
2142 }
2143 
2144 /*
2145  * Check if the percentage of blocks shared between the clone and the
2146  * snapshot (as opposed to those that are clone only) is below a certain
2147  * threshold
2148  */
2149 static boolean_t
dsl_livelist_should_disable(dsl_dataset_t * ds)2150 dsl_livelist_should_disable(dsl_dataset_t *ds)
2151 {
2152 	uint64_t used, referenced;
2153 	int percent_shared;
2154 
2155 	used = dsl_dir_get_usedds(ds->ds_dir);
2156 	referenced = dsl_get_referenced(ds);
2157 	if (referenced == 0)
2158 		return (B_FALSE);
2159 	percent_shared = (100 * (referenced - used)) / referenced;
2160 	if (percent_shared <= zfs_livelist_min_percent_shared)
2161 		return (B_TRUE);
2162 	return (B_FALSE);
2163 }
2164 
2165 /*
2166  *  Check if it is possible to combine two livelist entries into one.
2167  *  This is the case if the combined number of 'live' blkptrs (ALLOCs that
2168  *  don't have a matching FREE) is under the maximum sublist size.
2169  *  We check this by subtracting twice the total number of frees from the total
2170  *  number of blkptrs. FREEs are counted twice because each FREE blkptr
2171  *  will cancel out an ALLOC blkptr when the livelist is processed.
2172  */
2173 static boolean_t
dsl_livelist_should_condense(dsl_deadlist_entry_t * first,dsl_deadlist_entry_t * next)2174 dsl_livelist_should_condense(dsl_deadlist_entry_t *first,
2175     dsl_deadlist_entry_t *next)
2176 {
2177 	uint64_t total_free = first->dle_bpobj.bpo_phys->bpo_num_freed +
2178 	    next->dle_bpobj.bpo_phys->bpo_num_freed;
2179 	uint64_t total_entries = first->dle_bpobj.bpo_phys->bpo_num_blkptrs +
2180 	    next->dle_bpobj.bpo_phys->bpo_num_blkptrs;
2181 	if ((total_entries - (2 * total_free)) < zfs_livelist_max_entries)
2182 		return (B_TRUE);
2183 	return (B_FALSE);
2184 }
2185 
2186 typedef struct try_condense_arg {
2187 	spa_t *spa;
2188 	dsl_dataset_t *ds;
2189 } try_condense_arg_t;
2190 
2191 /*
2192  * Iterate over the livelist entries, searching for a pair to condense.
2193  * A nonzero return value means stop, 0 means keep looking.
2194  */
2195 static int
dsl_livelist_try_condense(void * arg,dsl_deadlist_entry_t * first)2196 dsl_livelist_try_condense(void *arg, dsl_deadlist_entry_t *first)
2197 {
2198 	try_condense_arg_t *tca = arg;
2199 	spa_t *spa = tca->spa;
2200 	dsl_dataset_t *ds = tca->ds;
2201 	dsl_deadlist_t *ll = &ds->ds_dir->dd_livelist;
2202 	dsl_deadlist_entry_t *next;
2203 
2204 	/* The condense thread has not yet been created at import */
2205 	if (spa->spa_livelist_condense_zthr == NULL)
2206 		return (1);
2207 
2208 	/* A condense is already in progress */
2209 	if (spa->spa_to_condense.ds != NULL)
2210 		return (1);
2211 
2212 	next = AVL_NEXT(&ll->dl_tree, &first->dle_node);
2213 	/* The livelist has only one entry - don't condense it */
2214 	if (next == NULL)
2215 		return (1);
2216 
2217 	/* Next is the newest entry - don't condense it */
2218 	if (AVL_NEXT(&ll->dl_tree, &next->dle_node) == NULL)
2219 		return (1);
2220 
2221 	/* This pair is not ready to condense but keep looking */
2222 	if (!dsl_livelist_should_condense(first, next))
2223 		return (0);
2224 
2225 	/*
2226 	 * Add a ref to prevent the dataset from being evicted while
2227 	 * the condense zthr or synctask are running. Ref will be
2228 	 * released at the end of the condense synctask
2229 	 */
2230 	dmu_buf_add_ref(ds->ds_dbuf, spa);
2231 
2232 	spa->spa_to_condense.ds = ds;
2233 	spa->spa_to_condense.first = first;
2234 	spa->spa_to_condense.next = next;
2235 	spa->spa_to_condense.syncing = B_FALSE;
2236 	spa->spa_to_condense.cancelled = B_FALSE;
2237 
2238 	zthr_wakeup(spa->spa_livelist_condense_zthr);
2239 	return (1);
2240 }
2241 
2242 static void
dsl_flush_pending_livelist(dsl_dataset_t * ds,dmu_tx_t * tx)2243 dsl_flush_pending_livelist(dsl_dataset_t *ds, dmu_tx_t *tx)
2244 {
2245 	dsl_dir_t *dd = ds->ds_dir;
2246 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
2247 	dsl_deadlist_entry_t *last = dsl_deadlist_last(&dd->dd_livelist);
2248 
2249 	/* Check if we need to add a new sub-livelist */
2250 	if (last == NULL) {
2251 		/* The livelist is empty */
2252 		dsl_deadlist_add_key(&dd->dd_livelist,
2253 		    tx->tx_txg - 1, tx);
2254 	} else if (spa_sync_pass(spa) == 1) {
2255 		/*
2256 		 * Check if the newest entry is full. If it is, make a new one.
2257 		 * We only do this once per sync because we could overfill a
2258 		 * sublist in one sync pass and don't want to add another entry
2259 		 * for a txg that is already represented. This ensures that
2260 		 * blkptrs born in the same txg are stored in the same sublist.
2261 		 */
2262 		bpobj_t bpobj = last->dle_bpobj;
2263 		uint64_t all = bpobj.bpo_phys->bpo_num_blkptrs;
2264 		uint64_t free = bpobj.bpo_phys->bpo_num_freed;
2265 		uint64_t alloc = all - free;
2266 		if (alloc > zfs_livelist_max_entries) {
2267 			dsl_deadlist_add_key(&dd->dd_livelist,
2268 			    tx->tx_txg - 1, tx);
2269 		}
2270 	}
2271 
2272 	/* Insert each entry into the on-disk livelist */
2273 	bplist_iterate(&dd->dd_pending_allocs,
2274 	    dsl_deadlist_insert_alloc_cb, &dd->dd_livelist, tx);
2275 	bplist_iterate(&dd->dd_pending_frees,
2276 	    dsl_deadlist_insert_free_cb, &dd->dd_livelist, tx);
2277 
2278 	/* Attempt to condense every pair of adjacent entries */
2279 	try_condense_arg_t arg = {
2280 	    .spa = spa,
2281 	    .ds = ds
2282 	};
2283 	dsl_deadlist_iterate(&dd->dd_livelist, dsl_livelist_try_condense,
2284 	    &arg);
2285 }
2286 
2287 void
dsl_dataset_sync_done(dsl_dataset_t * ds,dmu_tx_t * tx)2288 dsl_dataset_sync_done(dsl_dataset_t *ds, dmu_tx_t *tx)
2289 {
2290 	objset_t *os = ds->ds_objset;
2291 
2292 	bplist_iterate(&ds->ds_pending_deadlist,
2293 	    dsl_deadlist_insert_alloc_cb, &ds->ds_deadlist, tx);
2294 
2295 	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist)) {
2296 		dsl_flush_pending_livelist(ds, tx);
2297 		if (dsl_livelist_should_disable(ds)) {
2298 			dsl_dir_remove_livelist(ds->ds_dir, tx, B_TRUE);
2299 		}
2300 	}
2301 
2302 	dsl_bookmark_sync_done(ds, tx);
2303 
2304 	multilist_destroy(&os->os_synced_dnodes);
2305 
2306 	if (os->os_encrypted)
2307 		os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_FALSE;
2308 	else
2309 		ASSERT0(os->os_next_write_raw[tx->tx_txg & TXG_MASK]);
2310 
2311 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2312 		if (zfeature_active(f,
2313 		    ds->ds_feature_activation[f])) {
2314 			if (zfeature_active(f, ds->ds_feature[f]))
2315 				continue;
2316 			dsl_dataset_activate_feature(ds->ds_object, f,
2317 			    ds->ds_feature_activation[f], tx);
2318 			ds->ds_feature[f] = ds->ds_feature_activation[f];
2319 		}
2320 	}
2321 
2322 	ASSERT(!dmu_objset_is_dirty(os, dmu_tx_get_txg(tx)));
2323 }
2324 
2325 int
get_clones_stat_impl(dsl_dataset_t * ds,nvlist_t * val)2326 get_clones_stat_impl(dsl_dataset_t *ds, nvlist_t *val)
2327 {
2328 	uint64_t count = 0;
2329 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
2330 	zap_cursor_t zc;
2331 	zap_attribute_t *za;
2332 
2333 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
2334 
2335 	/*
2336 	 * There may be missing entries in ds_next_clones_obj
2337 	 * due to a bug in a previous version of the code.
2338 	 * Only trust it if it has the right number of entries.
2339 	 */
2340 	if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2341 		VERIFY0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
2342 		    &count));
2343 	}
2344 	if (count != dsl_dataset_phys(ds)->ds_num_children - 1) {
2345 		return (SET_ERROR(ENOENT));
2346 	}
2347 
2348 	za = zap_attribute_alloc();
2349 	for (zap_cursor_init(&zc, mos,
2350 	    dsl_dataset_phys(ds)->ds_next_clones_obj);
2351 	    zap_cursor_retrieve(&zc, za) == 0;
2352 	    zap_cursor_advance(&zc)) {
2353 		dsl_dataset_t *clone;
2354 		char buf[ZFS_MAX_DATASET_NAME_LEN];
2355 		VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
2356 		    za->za_first_integer, FTAG, &clone));
2357 		dsl_dir_name(clone->ds_dir, buf);
2358 		fnvlist_add_boolean(val, buf);
2359 		dsl_dataset_rele(clone, FTAG);
2360 	}
2361 	zap_cursor_fini(&zc);
2362 	zap_attribute_free(za);
2363 	return (0);
2364 }
2365 
2366 void
get_clones_stat(dsl_dataset_t * ds,nvlist_t * nv)2367 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
2368 {
2369 	nvlist_t *propval = fnvlist_alloc();
2370 	nvlist_t *val = fnvlist_alloc();
2371 
2372 	if (get_clones_stat_impl(ds, val) == 0) {
2373 		fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
2374 		fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2375 		    propval);
2376 	}
2377 
2378 	nvlist_free(val);
2379 	nvlist_free(propval);
2380 }
2381 
2382 static char *
get_receive_resume_token_impl(dsl_dataset_t * ds)2383 get_receive_resume_token_impl(dsl_dataset_t *ds)
2384 {
2385 	if (!dsl_dataset_has_resume_receive_state(ds))
2386 		return (NULL);
2387 
2388 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2389 	char *str;
2390 	void *packed;
2391 	uint8_t *compressed;
2392 	uint64_t val;
2393 	nvlist_t *token_nv = fnvlist_alloc();
2394 	size_t packed_size, compressed_size;
2395 
2396 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2397 	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val) == 0) {
2398 		fnvlist_add_uint64(token_nv, "fromguid", val);
2399 	}
2400 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2401 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val) == 0) {
2402 		fnvlist_add_uint64(token_nv, "object", val);
2403 	}
2404 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2405 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val) == 0) {
2406 		fnvlist_add_uint64(token_nv, "offset", val);
2407 	}
2408 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2409 	    DS_FIELD_RESUME_BYTES, sizeof (val), 1, &val) == 0) {
2410 		fnvlist_add_uint64(token_nv, "bytes", val);
2411 	}
2412 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2413 	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val) == 0) {
2414 		fnvlist_add_uint64(token_nv, "toguid", val);
2415 	}
2416 	char buf[MAXNAMELEN];
2417 	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2418 	    DS_FIELD_RESUME_TONAME, 1, sizeof (buf), buf) == 0) {
2419 		fnvlist_add_string(token_nv, "toname", buf);
2420 	}
2421 	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2422 	    DS_FIELD_RESUME_LARGEBLOCK) == 0) {
2423 		fnvlist_add_boolean(token_nv, "largeblockok");
2424 	}
2425 	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2426 	    DS_FIELD_RESUME_EMBEDOK) == 0) {
2427 		fnvlist_add_boolean(token_nv, "embedok");
2428 	}
2429 	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2430 	    DS_FIELD_RESUME_COMPRESSOK) == 0) {
2431 		fnvlist_add_boolean(token_nv, "compressok");
2432 	}
2433 	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2434 	    DS_FIELD_RESUME_RAWOK) == 0) {
2435 		fnvlist_add_boolean(token_nv, "rawok");
2436 	}
2437 	if (dsl_dataset_feature_is_active(ds,
2438 	    SPA_FEATURE_REDACTED_DATASETS)) {
2439 		uint64_t num_redact_snaps = 0;
2440 		uint64_t *redact_snaps = NULL;
2441 		VERIFY3B(dsl_dataset_get_uint64_array_feature(ds,
2442 		    SPA_FEATURE_REDACTED_DATASETS, &num_redact_snaps,
2443 		    &redact_snaps), ==, B_TRUE);
2444 		fnvlist_add_uint64_array(token_nv, "redact_snaps",
2445 		    redact_snaps, num_redact_snaps);
2446 	}
2447 	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2448 	    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS) == 0) {
2449 		uint64_t num_redact_snaps = 0, int_size = 0;
2450 		uint64_t *redact_snaps = NULL;
2451 		VERIFY0(zap_length(dp->dp_meta_objset, ds->ds_object,
2452 		    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, &int_size,
2453 		    &num_redact_snaps));
2454 		ASSERT3U(int_size, ==, sizeof (uint64_t));
2455 
2456 		redact_snaps = kmem_alloc(int_size * num_redact_snaps,
2457 		    KM_SLEEP);
2458 		VERIFY0(zap_lookup(dp->dp_meta_objset, ds->ds_object,
2459 		    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, int_size,
2460 		    num_redact_snaps, redact_snaps));
2461 		fnvlist_add_uint64_array(token_nv, "book_redact_snaps",
2462 		    redact_snaps, num_redact_snaps);
2463 		kmem_free(redact_snaps, int_size * num_redact_snaps);
2464 	}
2465 	packed = fnvlist_pack(token_nv, &packed_size);
2466 	fnvlist_free(token_nv);
2467 	compressed = kmem_alloc(packed_size, KM_SLEEP);
2468 
2469 	/* Call compress function directly to avoid hole detection. */
2470 	abd_t pabd, cabd;
2471 	abd_get_from_buf_struct(&pabd, packed, packed_size);
2472 	abd_get_from_buf_struct(&cabd, compressed, packed_size);
2473 	compressed_size = zfs_gzip_compress(&pabd, &cabd,
2474 	    packed_size, packed_size, 6);
2475 	abd_free(&cabd);
2476 	abd_free(&pabd);
2477 
2478 	zio_cksum_t cksum;
2479 	fletcher_4_native_varsize(compressed, compressed_size, &cksum);
2480 
2481 	size_t alloc_size = compressed_size * 2 + 1;
2482 	str = kmem_alloc(alloc_size, KM_SLEEP);
2483 	for (int i = 0; i < compressed_size; i++) {
2484 		size_t offset = i * 2;
2485 		(void) snprintf(str + offset, alloc_size - offset,
2486 	    "%02x", compressed[i]);
2487 	}
2488 	str[compressed_size * 2] = '\0';
2489 	char *propval = kmem_asprintf("%u-%llx-%llx-%s",
2490 	    ZFS_SEND_RESUME_TOKEN_VERSION,
2491 	    (longlong_t)cksum.zc_word[0],
2492 	    (longlong_t)packed_size, str);
2493 	kmem_free(packed, packed_size);
2494 	kmem_free(str, alloc_size);
2495 	kmem_free(compressed, packed_size);
2496 	return (propval);
2497 }
2498 
2499 /*
2500  * Returns a string that represents the receive resume state token. It should
2501  * be freed with strfree(). NULL is returned if no resume state is present.
2502  */
2503 char *
get_receive_resume_token(dsl_dataset_t * ds)2504 get_receive_resume_token(dsl_dataset_t *ds)
2505 {
2506 	/*
2507 	 * A failed "newfs" (e.g. full) resumable receive leaves
2508 	 * the stats set on this dataset.  Check here for the prop.
2509 	 */
2510 	char *token = get_receive_resume_token_impl(ds);
2511 	if (token != NULL)
2512 		return (token);
2513 	/*
2514 	 * A failed incremental resumable receive leaves the
2515 	 * stats set on our child named "%recv".  Check the child
2516 	 * for the prop.
2517 	 */
2518 	/* 6 extra bytes for /%recv */
2519 	char name[ZFS_MAX_DATASET_NAME_LEN + 6];
2520 	dsl_dataset_t *recv_ds;
2521 	dsl_dataset_name(ds, name);
2522 	if (strlcat(name, "/", sizeof (name)) < sizeof (name) &&
2523 	    strlcat(name, recv_clone_name, sizeof (name)) < sizeof (name) &&
2524 	    dsl_dataset_hold(ds->ds_dir->dd_pool, name, FTAG, &recv_ds) == 0) {
2525 		token = get_receive_resume_token_impl(recv_ds);
2526 		dsl_dataset_rele(recv_ds, FTAG);
2527 	}
2528 	return (token);
2529 }
2530 
2531 uint64_t
dsl_get_refratio(dsl_dataset_t * ds)2532 dsl_get_refratio(dsl_dataset_t *ds)
2533 {
2534 	uint64_t ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
2535 	    (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
2536 	    dsl_dataset_phys(ds)->ds_compressed_bytes);
2537 	return (ratio);
2538 }
2539 
2540 uint64_t
dsl_get_logicalreferenced(dsl_dataset_t * ds)2541 dsl_get_logicalreferenced(dsl_dataset_t *ds)
2542 {
2543 	return (dsl_dataset_phys(ds)->ds_uncompressed_bytes);
2544 }
2545 
2546 uint64_t
dsl_get_compressratio(dsl_dataset_t * ds)2547 dsl_get_compressratio(dsl_dataset_t *ds)
2548 {
2549 	if (ds->ds_is_snapshot) {
2550 		return (dsl_get_refratio(ds));
2551 	} else {
2552 		dsl_dir_t *dd = ds->ds_dir;
2553 		mutex_enter(&dd->dd_lock);
2554 		uint64_t val = dsl_dir_get_compressratio(dd);
2555 		mutex_exit(&dd->dd_lock);
2556 		return (val);
2557 	}
2558 }
2559 
2560 uint64_t
dsl_get_used(dsl_dataset_t * ds)2561 dsl_get_used(dsl_dataset_t *ds)
2562 {
2563 	if (ds->ds_is_snapshot) {
2564 		return (dsl_dataset_phys(ds)->ds_unique_bytes);
2565 	} else {
2566 		dsl_dir_t *dd = ds->ds_dir;
2567 		mutex_enter(&dd->dd_lock);
2568 		uint64_t val = dsl_dir_get_used(dd);
2569 		mutex_exit(&dd->dd_lock);
2570 		return (val);
2571 	}
2572 }
2573 
2574 uint64_t
dsl_get_creation(dsl_dataset_t * ds)2575 dsl_get_creation(dsl_dataset_t *ds)
2576 {
2577 	return (dsl_dataset_phys(ds)->ds_creation_time);
2578 }
2579 
2580 uint64_t
dsl_get_creationtxg(dsl_dataset_t * ds)2581 dsl_get_creationtxg(dsl_dataset_t *ds)
2582 {
2583 	return (dsl_dataset_phys(ds)->ds_creation_txg);
2584 }
2585 
2586 uint64_t
dsl_get_refquota(dsl_dataset_t * ds)2587 dsl_get_refquota(dsl_dataset_t *ds)
2588 {
2589 	return (ds->ds_quota);
2590 }
2591 
2592 uint64_t
dsl_get_refreservation(dsl_dataset_t * ds)2593 dsl_get_refreservation(dsl_dataset_t *ds)
2594 {
2595 	return (ds->ds_reserved);
2596 }
2597 
2598 uint64_t
dsl_get_guid(dsl_dataset_t * ds)2599 dsl_get_guid(dsl_dataset_t *ds)
2600 {
2601 	return (dsl_dataset_phys(ds)->ds_guid);
2602 }
2603 
2604 uint64_t
dsl_get_unique(dsl_dataset_t * ds)2605 dsl_get_unique(dsl_dataset_t *ds)
2606 {
2607 	return (dsl_dataset_phys(ds)->ds_unique_bytes);
2608 }
2609 
2610 uint64_t
dsl_get_objsetid(dsl_dataset_t * ds)2611 dsl_get_objsetid(dsl_dataset_t *ds)
2612 {
2613 	return (ds->ds_object);
2614 }
2615 
2616 uint64_t
dsl_get_userrefs(dsl_dataset_t * ds)2617 dsl_get_userrefs(dsl_dataset_t *ds)
2618 {
2619 	return (ds->ds_userrefs);
2620 }
2621 
2622 uint64_t
dsl_get_defer_destroy(dsl_dataset_t * ds)2623 dsl_get_defer_destroy(dsl_dataset_t *ds)
2624 {
2625 	return (DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2626 }
2627 
2628 uint64_t
dsl_get_referenced(dsl_dataset_t * ds)2629 dsl_get_referenced(dsl_dataset_t *ds)
2630 {
2631 	return (dsl_dataset_phys(ds)->ds_referenced_bytes);
2632 }
2633 
2634 uint64_t
dsl_get_numclones(dsl_dataset_t * ds)2635 dsl_get_numclones(dsl_dataset_t *ds)
2636 {
2637 	ASSERT(ds->ds_is_snapshot);
2638 	return (dsl_dataset_phys(ds)->ds_num_children - 1);
2639 }
2640 
2641 uint64_t
dsl_get_inconsistent(dsl_dataset_t * ds)2642 dsl_get_inconsistent(dsl_dataset_t *ds)
2643 {
2644 	return ((dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT) ?
2645 	    1 : 0);
2646 }
2647 
2648 uint64_t
dsl_get_redacted(dsl_dataset_t * ds)2649 dsl_get_redacted(dsl_dataset_t *ds)
2650 {
2651 	return (dsl_dataset_feature_is_active(ds,
2652 	    SPA_FEATURE_REDACTED_DATASETS));
2653 }
2654 
2655 uint64_t
dsl_get_available(dsl_dataset_t * ds)2656 dsl_get_available(dsl_dataset_t *ds)
2657 {
2658 	uint64_t refdbytes = dsl_get_referenced(ds);
2659 	uint64_t availbytes = dsl_dir_space_available(ds->ds_dir,
2660 	    NULL, 0, TRUE);
2661 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
2662 		availbytes +=
2663 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2664 	}
2665 	if (ds->ds_quota != 0) {
2666 		/*
2667 		 * Adjust available bytes according to refquota
2668 		 */
2669 		if (refdbytes < ds->ds_quota) {
2670 			availbytes = MIN(availbytes,
2671 			    ds->ds_quota - refdbytes);
2672 		} else {
2673 			availbytes = 0;
2674 		}
2675 	}
2676 	return (availbytes);
2677 }
2678 
2679 int
dsl_get_written(dsl_dataset_t * ds,uint64_t * written)2680 dsl_get_written(dsl_dataset_t *ds, uint64_t *written)
2681 {
2682 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2683 	dsl_dataset_t *prev;
2684 	int err = dsl_dataset_hold_obj(dp,
2685 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2686 	if (err == 0) {
2687 		uint64_t comp, uncomp;
2688 		err = dsl_dataset_space_written(prev, ds, written,
2689 		    &comp, &uncomp);
2690 		dsl_dataset_rele(prev, FTAG);
2691 	}
2692 	return (err);
2693 }
2694 
2695 /*
2696  * 'snap' should be a buffer of size ZFS_MAX_DATASET_NAME_LEN.
2697  */
2698 int
dsl_get_prev_snap(dsl_dataset_t * ds,char * snap)2699 dsl_get_prev_snap(dsl_dataset_t *ds, char *snap)
2700 {
2701 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2702 	if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
2703 		dsl_dataset_name(ds->ds_prev, snap);
2704 		return (0);
2705 	} else {
2706 		return (SET_ERROR(ENOENT));
2707 	}
2708 }
2709 
2710 void
dsl_get_redact_snaps(dsl_dataset_t * ds,nvlist_t * propval)2711 dsl_get_redact_snaps(dsl_dataset_t *ds, nvlist_t *propval)
2712 {
2713 	uint64_t nsnaps;
2714 	uint64_t *snaps;
2715 	if (dsl_dataset_get_uint64_array_feature(ds,
2716 	    SPA_FEATURE_REDACTED_DATASETS, &nsnaps, &snaps)) {
2717 		fnvlist_add_uint64_array(propval, ZPROP_VALUE, snaps,
2718 		    nsnaps);
2719 	}
2720 }
2721 
2722 /*
2723  * Returns the mountpoint property and source for the given dataset in the value
2724  * and source buffers. The value buffer must be at least as large as MAXPATHLEN
2725  * and the source buffer as least as large a ZFS_MAX_DATASET_NAME_LEN.
2726  * Returns 0 on success and an error on failure.
2727  */
2728 int
dsl_get_mountpoint(dsl_dataset_t * ds,const char * dsname,char * value,char * source)2729 dsl_get_mountpoint(dsl_dataset_t *ds, const char *dsname, char *value,
2730     char *source)
2731 {
2732 	int error;
2733 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2734 
2735 	/* Retrieve the mountpoint value stored in the zap object */
2736 	error = dsl_prop_get_ds(ds, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT), 1,
2737 	    ZAP_MAXVALUELEN, value, source);
2738 	if (error != 0) {
2739 		return (error);
2740 	}
2741 
2742 	/*
2743 	 * Process the dsname and source to find the full mountpoint string.
2744 	 * Can be skipped for 'legacy' or 'none'.
2745 	 */
2746 	if (value[0] == '/') {
2747 		char *buf = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
2748 		char *root = buf;
2749 		const char *relpath;
2750 
2751 		/*
2752 		 * If we inherit the mountpoint, even from a dataset
2753 		 * with a received value, the source will be the path of
2754 		 * the dataset we inherit from. If source is
2755 		 * ZPROP_SOURCE_VAL_RECVD, the received value is not
2756 		 * inherited.
2757 		 */
2758 		if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2759 			relpath = "";
2760 		} else {
2761 			ASSERT0(strncmp(dsname, source, strlen(source)));
2762 			relpath = dsname + strlen(source);
2763 			if (relpath[0] == '/')
2764 				relpath++;
2765 		}
2766 
2767 		spa_altroot(dp->dp_spa, root, ZAP_MAXVALUELEN);
2768 
2769 		/*
2770 		 * Special case an alternate root of '/'. This will
2771 		 * avoid having multiple leading slashes in the
2772 		 * mountpoint path.
2773 		 */
2774 		if (strcmp(root, "/") == 0)
2775 			root++;
2776 
2777 		/*
2778 		 * If the mountpoint is '/' then skip over this
2779 		 * if we are obtaining either an alternate root or
2780 		 * an inherited mountpoint.
2781 		 */
2782 		char *mnt = value;
2783 		if (value[1] == '\0' && (root[0] != '\0' ||
2784 		    relpath[0] != '\0'))
2785 			mnt = value + 1;
2786 
2787 		mnt = kmem_strdup(mnt);
2788 
2789 		if (relpath[0] == '\0') {
2790 			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s",
2791 			    root, mnt);
2792 		} else {
2793 			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s%s%s",
2794 			    root, mnt, relpath[0] == '@' ? "" : "/",
2795 			    relpath);
2796 		}
2797 		kmem_free(buf, ZAP_MAXVALUELEN);
2798 		kmem_strfree(mnt);
2799 	}
2800 
2801 	return (0);
2802 }
2803 
2804 void
dsl_dataset_stats(dsl_dataset_t * ds,nvlist_t * nv)2805 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2806 {
2807 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2808 
2809 	ASSERT(dsl_pool_config_held(dp));
2810 
2811 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO,
2812 	    dsl_get_refratio(ds));
2813 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
2814 	    dsl_get_logicalreferenced(ds));
2815 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
2816 	    dsl_get_compressratio(ds));
2817 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2818 	    dsl_get_used(ds));
2819 
2820 	if (ds->ds_is_snapshot) {
2821 		get_clones_stat(ds, nv);
2822 	} else {
2823 		char buf[ZFS_MAX_DATASET_NAME_LEN];
2824 		if (dsl_get_prev_snap(ds, buf) == 0)
2825 			dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP,
2826 			    buf);
2827 		dsl_dir_stats(ds->ds_dir, nv);
2828 	}
2829 
2830 	nvlist_t *propval = fnvlist_alloc();
2831 	dsl_get_redact_snaps(ds, propval);
2832 	fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS),
2833 	    propval);
2834 	nvlist_free(propval);
2835 
2836 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE,
2837 	    dsl_get_available(ds));
2838 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED,
2839 	    dsl_get_referenced(ds));
2840 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2841 	    dsl_get_creation(ds));
2842 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2843 	    dsl_get_creationtxg(ds));
2844 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2845 	    dsl_get_refquota(ds));
2846 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2847 	    dsl_get_refreservation(ds));
2848 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2849 	    dsl_get_guid(ds));
2850 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2851 	    dsl_get_unique(ds));
2852 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2853 	    dsl_get_objsetid(ds));
2854 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2855 	    dsl_get_userrefs(ds));
2856 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2857 	    dsl_get_defer_destroy(ds));
2858 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_SNAPSHOTS_CHANGED,
2859 	    dsl_dir_snap_cmtime(ds->ds_dir).tv_sec);
2860 	dsl_dataset_crypt_stats(ds, nv);
2861 
2862 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2863 		uint64_t written;
2864 		if (dsl_get_written(ds, &written) == 0) {
2865 			dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2866 			    written);
2867 		}
2868 	}
2869 
2870 	if (!dsl_dataset_is_snapshot(ds)) {
2871 		char *token = get_receive_resume_token(ds);
2872 		if (token != NULL) {
2873 			dsl_prop_nvlist_add_string(nv,
2874 			    ZFS_PROP_RECEIVE_RESUME_TOKEN, token);
2875 			kmem_strfree(token);
2876 		}
2877 	}
2878 }
2879 
2880 void
dsl_dataset_fast_stat(dsl_dataset_t * ds,dmu_objset_stats_t * stat)2881 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2882 {
2883 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2884 	ASSERT(dsl_pool_config_held(dp));
2885 
2886 	stat->dds_creation_txg = dsl_get_creationtxg(ds);
2887 	stat->dds_inconsistent = dsl_get_inconsistent(ds);
2888 	stat->dds_guid = dsl_get_guid(ds);
2889 	stat->dds_redacted = dsl_get_redacted(ds);
2890 	stat->dds_origin[0] = '\0';
2891 	stat->dds_flags = DDS_FLAG_HAS_ENCRYPTED;
2892 	if (ds->ds_dir->dd_crypto_obj != 0)
2893 		stat->dds_flags |= DDS_FLAG_ENCRYPTED;
2894 	if (ds->ds_is_snapshot) {
2895 		stat->dds_is_snapshot = B_TRUE;
2896 		stat->dds_num_clones = dsl_get_numclones(ds);
2897 	} else {
2898 		stat->dds_is_snapshot = B_FALSE;
2899 		stat->dds_num_clones = 0;
2900 
2901 		if (dsl_dir_is_clone(ds->ds_dir)) {
2902 			dsl_dir_get_origin(ds->ds_dir, stat->dds_origin);
2903 		}
2904 	}
2905 }
2906 
2907 uint64_t
dsl_dataset_fsid_guid(dsl_dataset_t * ds)2908 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2909 {
2910 	return (ds->ds_fsid_guid);
2911 }
2912 
2913 void
dsl_dataset_space(dsl_dataset_t * ds,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)2914 dsl_dataset_space(dsl_dataset_t *ds,
2915     uint64_t *refdbytesp, uint64_t *availbytesp,
2916     uint64_t *usedobjsp, uint64_t *availobjsp)
2917 {
2918 	*refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
2919 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2920 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
2921 		*availbytesp +=
2922 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2923 	if (ds->ds_quota != 0) {
2924 		/*
2925 		 * Adjust available bytes according to refquota
2926 		 */
2927 		if (*refdbytesp < ds->ds_quota)
2928 			*availbytesp = MIN(*availbytesp,
2929 			    ds->ds_quota - *refdbytesp);
2930 		else
2931 			*availbytesp = 0;
2932 	}
2933 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2934 	*usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
2935 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2936 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
2937 }
2938 
2939 boolean_t
dsl_dataset_modified_since_snap(dsl_dataset_t * ds,dsl_dataset_t * snap)2940 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
2941 {
2942 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2943 	uint64_t birth;
2944 
2945 	ASSERT(dsl_pool_config_held(dp));
2946 	if (snap == NULL)
2947 		return (B_FALSE);
2948 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2949 	birth = BP_GET_BIRTH(dsl_dataset_get_blkptr(ds));
2950 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2951 	if (birth > dsl_dataset_phys(snap)->ds_creation_txg) {
2952 		objset_t *os, *os_snap;
2953 		/*
2954 		 * It may be that only the ZIL differs, because it was
2955 		 * reset in the head.  Don't count that as being
2956 		 * modified.
2957 		 */
2958 		if (dmu_objset_from_ds(ds, &os) != 0)
2959 			return (B_TRUE);
2960 		if (dmu_objset_from_ds(snap, &os_snap) != 0)
2961 			return (B_TRUE);
2962 		return (memcmp(&os->os_phys->os_meta_dnode,
2963 		    &os_snap->os_phys->os_meta_dnode,
2964 		    sizeof (os->os_phys->os_meta_dnode)) != 0);
2965 	}
2966 	return (B_FALSE);
2967 }
2968 
2969 static int
dsl_dataset_rename_snapshot_check_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)2970 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
2971     dsl_dataset_t *hds, void *arg)
2972 {
2973 	(void) dp;
2974 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2975 	int error;
2976 	uint64_t val;
2977 
2978 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2979 	if (error != 0) {
2980 		/* ignore nonexistent snapshots */
2981 		return (error == ENOENT ? 0 : error);
2982 	}
2983 
2984 	/* new name should not exist */
2985 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
2986 	if (error == 0)
2987 		error = SET_ERROR(EEXIST);
2988 	else if (error == ENOENT)
2989 		error = 0;
2990 
2991 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
2992 	if (dsl_dir_namelen(hds->ds_dir) + 1 +
2993 	    strlen(ddrsa->ddrsa_newsnapname) >= ZFS_MAX_DATASET_NAME_LEN)
2994 		error = SET_ERROR(ENAMETOOLONG);
2995 
2996 	return (error);
2997 }
2998 
2999 int
dsl_dataset_rename_snapshot_check(void * arg,dmu_tx_t * tx)3000 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
3001 {
3002 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3003 	dsl_pool_t *dp = dmu_tx_pool(tx);
3004 	dsl_dataset_t *hds;
3005 	int error;
3006 
3007 	error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
3008 	if (error != 0)
3009 		return (error);
3010 
3011 	if (ddrsa->ddrsa_recursive) {
3012 		error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3013 		    dsl_dataset_rename_snapshot_check_impl, ddrsa,
3014 		    DS_FIND_CHILDREN);
3015 	} else {
3016 		error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
3017 	}
3018 	dsl_dataset_rele(hds, FTAG);
3019 	return (error);
3020 }
3021 
3022 static int
dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)3023 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
3024     dsl_dataset_t *hds, void *arg)
3025 {
3026 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3027 	dsl_dataset_t *ds;
3028 	uint64_t val;
3029 	dmu_tx_t *tx = ddrsa->ddrsa_tx;
3030 	char *oldname, *newname;
3031 	int error;
3032 
3033 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
3034 	ASSERT(error == 0 || error == ENOENT);
3035 	if (error == ENOENT) {
3036 		/* ignore nonexistent snapshots */
3037 		return (0);
3038 	}
3039 
3040 	VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
3041 
3042 	/* log before we change the name */
3043 	spa_history_log_internal_ds(ds, "rename", tx,
3044 	    "-> @%s", ddrsa->ddrsa_newsnapname);
3045 
3046 	VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
3047 	    B_FALSE));
3048 	mutex_enter(&ds->ds_lock);
3049 	(void) strlcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname,
3050 	    sizeof (ds->ds_snapname));
3051 	mutex_exit(&ds->ds_lock);
3052 	VERIFY0(zap_add(dp->dp_meta_objset,
3053 	    dsl_dataset_phys(hds)->ds_snapnames_zapobj,
3054 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx));
3055 
3056 	oldname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3057 	    ddrsa->ddrsa_oldsnapname);
3058 	newname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3059 	    ddrsa->ddrsa_newsnapname);
3060 	zvol_rename_minors(dp->dp_spa, oldname, newname, B_TRUE);
3061 	kmem_strfree(oldname);
3062 	kmem_strfree(newname);
3063 
3064 	dsl_dataset_rele(ds, FTAG);
3065 	return (0);
3066 }
3067 
3068 void
dsl_dataset_rename_snapshot_sync(void * arg,dmu_tx_t * tx)3069 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
3070 {
3071 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3072 	dsl_pool_t *dp = dmu_tx_pool(tx);
3073 	dsl_dataset_t *hds = NULL;
3074 
3075 	VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
3076 	ddrsa->ddrsa_tx = tx;
3077 	if (ddrsa->ddrsa_recursive) {
3078 		VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3079 		    dsl_dataset_rename_snapshot_sync_impl, ddrsa,
3080 		    DS_FIND_CHILDREN));
3081 	} else {
3082 		VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
3083 	}
3084 	dsl_dataset_rele(hds, FTAG);
3085 }
3086 
3087 int
dsl_dataset_rename_snapshot(const char * fsname,const char * oldsnapname,const char * newsnapname,boolean_t recursive)3088 dsl_dataset_rename_snapshot(const char *fsname,
3089     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
3090 {
3091 	dsl_dataset_rename_snapshot_arg_t ddrsa;
3092 
3093 	ddrsa.ddrsa_fsname = fsname;
3094 	ddrsa.ddrsa_oldsnapname = oldsnapname;
3095 	ddrsa.ddrsa_newsnapname = newsnapname;
3096 	ddrsa.ddrsa_recursive = recursive;
3097 
3098 	return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
3099 	    dsl_dataset_rename_snapshot_sync, &ddrsa,
3100 	    1, ZFS_SPACE_CHECK_RESERVED));
3101 }
3102 
3103 /*
3104  * If we're doing an ownership handoff, we need to make sure that there is
3105  * only one long hold on the dataset.  We're not allowed to change anything here
3106  * so we don't permanently release the long hold or regular hold here.  We want
3107  * to do this only when syncing to avoid the dataset unexpectedly going away
3108  * when we release the long hold.
3109  */
3110 static int
dsl_dataset_handoff_check(dsl_dataset_t * ds,void * owner,dmu_tx_t * tx)3111 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
3112 {
3113 	boolean_t held = B_FALSE;
3114 
3115 	if (!dmu_tx_is_syncing(tx))
3116 		return (0);
3117 
3118 	dsl_dir_t *dd = ds->ds_dir;
3119 	mutex_enter(&dd->dd_activity_lock);
3120 	uint64_t holds = zfs_refcount_count(&ds->ds_longholds) -
3121 	    (owner != NULL ? 1 : 0);
3122 	/*
3123 	 * The value of dd_activity_waiters can chance as soon as we drop the
3124 	 * lock, but we're fine with that; new waiters coming in or old
3125 	 * waiters leaving doesn't cause problems, since we're going to cancel
3126 	 * waiters later anyway. The goal of this check is to verify that no
3127 	 * non-waiters have long-holds, and all new long-holds will be
3128 	 * prevented because we're holding the pool config as writer.
3129 	 */
3130 	if (holds != dd->dd_activity_waiters)
3131 		held = B_TRUE;
3132 	mutex_exit(&dd->dd_activity_lock);
3133 
3134 	if (held)
3135 		return (SET_ERROR(EBUSY));
3136 
3137 	return (0);
3138 }
3139 
3140 int
dsl_dataset_rollback_check(void * arg,dmu_tx_t * tx)3141 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
3142 {
3143 	dsl_dataset_rollback_arg_t *ddra = arg;
3144 	dsl_pool_t *dp = dmu_tx_pool(tx);
3145 	dsl_dataset_t *ds;
3146 	int64_t unused_refres_delta;
3147 	int error;
3148 
3149 	error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
3150 	if (error != 0)
3151 		return (error);
3152 
3153 	/* must not be a snapshot */
3154 	if (ds->ds_is_snapshot) {
3155 		dsl_dataset_rele(ds, FTAG);
3156 		return (SET_ERROR(EINVAL));
3157 	}
3158 
3159 	/* must have a most recent snapshot */
3160 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
3161 		dsl_dataset_rele(ds, FTAG);
3162 		return (SET_ERROR(ESRCH));
3163 	}
3164 
3165 	/*
3166 	 * No rollback to a snapshot created in the current txg, because
3167 	 * the rollback may dirty the dataset and create blocks that are
3168 	 * not reachable from the rootbp while having a birth txg that
3169 	 * falls into the snapshot's range.
3170 	 */
3171 	if (dmu_tx_is_syncing(tx) &&
3172 	    dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg) {
3173 		dsl_dataset_rele(ds, FTAG);
3174 		return (SET_ERROR(EAGAIN));
3175 	}
3176 
3177 	/*
3178 	 * If the expected target snapshot is specified, then check that
3179 	 * the latest snapshot is it.
3180 	 */
3181 	if (ddra->ddra_tosnap != NULL) {
3182 		dsl_dataset_t *snapds;
3183 
3184 		/* Check if the target snapshot exists at all. */
3185 		error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
3186 		if (error != 0) {
3187 			/*
3188 			 * ESRCH is used to signal that the target snapshot does
3189 			 * not exist, while ENOENT is used to report that
3190 			 * the rolled back dataset does not exist.
3191 			 * ESRCH is also used to cover other cases where the
3192 			 * target snapshot is not related to the dataset being
3193 			 * rolled back such as being in a different pool.
3194 			 */
3195 			if (error == ENOENT || error == EXDEV)
3196 				error = SET_ERROR(ESRCH);
3197 			dsl_dataset_rele(ds, FTAG);
3198 			return (error);
3199 		}
3200 		ASSERT(snapds->ds_is_snapshot);
3201 
3202 		/* Check if the snapshot is the latest snapshot indeed. */
3203 		if (snapds != ds->ds_prev) {
3204 			/*
3205 			 * Distinguish between the case where the only problem
3206 			 * is intervening snapshots (EEXIST) vs the snapshot
3207 			 * not being a valid target for rollback (ESRCH).
3208 			 */
3209 			if (snapds->ds_dir == ds->ds_dir ||
3210 			    (dsl_dir_is_clone(ds->ds_dir) &&
3211 			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
3212 			    snapds->ds_object)) {
3213 				error = SET_ERROR(EEXIST);
3214 			} else {
3215 				error = SET_ERROR(ESRCH);
3216 			}
3217 			dsl_dataset_rele(snapds, FTAG);
3218 			dsl_dataset_rele(ds, FTAG);
3219 			return (error);
3220 		}
3221 		dsl_dataset_rele(snapds, FTAG);
3222 	}
3223 
3224 	/* must not have any bookmarks after the most recent snapshot */
3225 	if (dsl_bookmark_latest_txg(ds) >
3226 	    dsl_dataset_phys(ds)->ds_prev_snap_txg) {
3227 		dsl_dataset_rele(ds, FTAG);
3228 		return (SET_ERROR(EEXIST));
3229 	}
3230 
3231 	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
3232 	if (error != 0) {
3233 		dsl_dataset_rele(ds, FTAG);
3234 		return (error);
3235 	}
3236 
3237 	/*
3238 	 * Check if the snap we are rolling back to uses more than
3239 	 * the refquota.
3240 	 */
3241 	if (ds->ds_quota != 0 &&
3242 	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
3243 		dsl_dataset_rele(ds, FTAG);
3244 		return (SET_ERROR(EDQUOT));
3245 	}
3246 
3247 	/*
3248 	 * When we do the clone swap, we will temporarily use more space
3249 	 * due to the refreservation (the head will no longer have any
3250 	 * unique space, so the entire amount of the refreservation will need
3251 	 * to be free).  We will immediately destroy the clone, freeing
3252 	 * this space, but the freeing happens over many txg's.
3253 	 */
3254 	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
3255 	    dsl_dataset_phys(ds)->ds_unique_bytes);
3256 
3257 	if (unused_refres_delta > 0 &&
3258 	    unused_refres_delta >
3259 	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
3260 		dsl_dataset_rele(ds, FTAG);
3261 		return (SET_ERROR(ENOSPC));
3262 	}
3263 
3264 	dsl_dataset_rele(ds, FTAG);
3265 	return (0);
3266 }
3267 
3268 void
dsl_dataset_rollback_sync(void * arg,dmu_tx_t * tx)3269 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
3270 {
3271 	dsl_dataset_rollback_arg_t *ddra = arg;
3272 	dsl_pool_t *dp = dmu_tx_pool(tx);
3273 	dsl_dataset_t *ds, *clone;
3274 	uint64_t cloneobj;
3275 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3276 
3277 	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
3278 
3279 	dsl_dataset_name(ds->ds_prev, namebuf);
3280 	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
3281 
3282 	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
3283 	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, NULL, tx);
3284 
3285 	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
3286 
3287 	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
3288 	dsl_dataset_zero_zil(ds, tx);
3289 
3290 	dsl_destroy_head_sync_impl(clone, tx);
3291 
3292 	dsl_dataset_rele(clone, FTAG);
3293 	dsl_dataset_rele(ds, FTAG);
3294 }
3295 
3296 /*
3297  * Rolls back the given filesystem or volume to the most recent snapshot.
3298  * The name of the most recent snapshot will be returned under key "target"
3299  * in the result nvlist.
3300  *
3301  * If owner != NULL:
3302  * - The existing dataset MUST be owned by the specified owner at entry
3303  * - Upon return, dataset will still be held by the same owner, whether we
3304  *   succeed or not.
3305  *
3306  * This mode is required any time the existing filesystem is mounted.  See
3307  * notes above zfs_suspend_fs() for further details.
3308  */
3309 int
dsl_dataset_rollback(const char * fsname,const char * tosnap,void * owner,nvlist_t * result)3310 dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
3311     nvlist_t *result)
3312 {
3313 	dsl_dataset_rollback_arg_t ddra;
3314 
3315 	ddra.ddra_fsname = fsname;
3316 	ddra.ddra_tosnap = tosnap;
3317 	ddra.ddra_owner = owner;
3318 	ddra.ddra_result = result;
3319 
3320 	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
3321 	    dsl_dataset_rollback_sync, &ddra,
3322 	    1, ZFS_SPACE_CHECK_RESERVED));
3323 }
3324 
3325 int
dsl_dataset_clone_check(void * arg,dmu_tx_t * tx)3326 dsl_dataset_clone_check(void *arg, dmu_tx_t *tx)
3327 {
3328 	dsl_dataset_clone_arg_t *ddca = arg;
3329 	dsl_dir_t *pdd;
3330 	const char *tail;
3331 	int error;
3332 	dsl_dataset_t *origin;
3333 	dsl_pool_t *dp = dmu_tx_pool(tx);
3334 
3335 	if (strchr(ddca->ddca_clone, '@') != NULL)
3336 		return (SET_ERROR(EINVAL));
3337 
3338 	if (strlen(ddca->ddca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
3339 		return (SET_ERROR(ENAMETOOLONG));
3340 
3341 	error = dsl_dir_hold(dp, ddca->ddca_clone, FTAG, &pdd, &tail);
3342 	if (error != 0)
3343 		return (error);
3344 	if (tail == NULL) {
3345 		dsl_dir_rele(pdd, FTAG);
3346 		return (SET_ERROR(EEXIST));
3347 	}
3348 
3349 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
3350 	    ddca->ddca_cred);
3351 	if (error != 0) {
3352 		dsl_dir_rele(pdd, FTAG);
3353 		return (SET_ERROR(EDQUOT));
3354 	}
3355 
3356 	error = dsl_dataset_hold(dp, ddca->ddca_origin, FTAG, &origin);
3357 	if (error != 0) {
3358 		dsl_dir_rele(pdd, FTAG);
3359 		return (error);
3360 	}
3361 
3362 	/* You can only clone snapshots, not the head datasets. */
3363 	if (!origin->ds_is_snapshot) {
3364 		dsl_dataset_rele(origin, FTAG);
3365 		dsl_dir_rele(pdd, FTAG);
3366 		return (SET_ERROR(EINVAL));
3367 	}
3368 
3369 	dsl_dataset_rele(origin, FTAG);
3370 	dsl_dir_rele(pdd, FTAG);
3371 
3372 	return (0);
3373 }
3374 
3375 void
dsl_dataset_clone_sync(void * arg,dmu_tx_t * tx)3376 dsl_dataset_clone_sync(void *arg, dmu_tx_t *tx)
3377 {
3378 	dsl_dataset_clone_arg_t *ddca = arg;
3379 	dsl_pool_t *dp = dmu_tx_pool(tx);
3380 	dsl_dir_t *pdd;
3381 	const char *tail;
3382 	dsl_dataset_t *origin, *ds;
3383 	uint64_t obj;
3384 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3385 
3386 	VERIFY0(dsl_dir_hold(dp, ddca->ddca_clone, FTAG, &pdd, &tail));
3387 	VERIFY0(dsl_dataset_hold(dp, ddca->ddca_origin, FTAG, &origin));
3388 
3389 	obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
3390 	    ddca->ddca_cred, NULL, tx);
3391 
3392 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
3393 	dsl_dataset_name(origin, namebuf);
3394 	spa_history_log_internal_ds(ds, "clone", tx,
3395 	    "origin=%s (%llu)", namebuf, (u_longlong_t)origin->ds_object);
3396 	dsl_dataset_rele(ds, FTAG);
3397 	dsl_dataset_rele(origin, FTAG);
3398 	dsl_dir_rele(pdd, FTAG);
3399 }
3400 
3401 int
dsl_dataset_clone(const char * clone,const char * origin)3402 dsl_dataset_clone(const char *clone, const char *origin)
3403 {
3404 	dsl_dataset_clone_arg_t ddca;
3405 
3406 	cred_t *cr = CRED();
3407 	crhold(cr);
3408 
3409 	ddca.ddca_clone = clone;
3410 	ddca.ddca_origin = origin;
3411 	ddca.ddca_cred = cr;
3412 
3413 	int rv = dsl_sync_task(clone,
3414 	    dsl_dataset_clone_check, dsl_dataset_clone_sync, &ddca,
3415 	    6, ZFS_SPACE_CHECK_NORMAL);
3416 
3417 	if (rv == 0)
3418 		zvol_create_minors(clone);
3419 
3420 	crfree(cr);
3421 
3422 	return (rv);
3423 }
3424 
3425 struct promotenode {
3426 	list_node_t link;
3427 	dsl_dataset_t *ds;
3428 };
3429 
3430 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
3431 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
3432     const void *tag);
3433 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag);
3434 
3435 int
dsl_dataset_promote_check(void * arg,dmu_tx_t * tx)3436 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
3437 {
3438 	dsl_dataset_promote_arg_t *ddpa = arg;
3439 	dsl_pool_t *dp = dmu_tx_pool(tx);
3440 	dsl_dataset_t *hds;
3441 	struct promotenode *snap;
3442 	int err;
3443 	uint64_t unused;
3444 	uint64_t ss_mv_cnt;
3445 	size_t max_snap_len;
3446 	boolean_t conflicting_snaps;
3447 
3448 	err = promote_hold(ddpa, dp, FTAG);
3449 	if (err != 0)
3450 		return (err);
3451 
3452 	hds = ddpa->ddpa_clone;
3453 	max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
3454 
3455 	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
3456 		promote_rele(ddpa, FTAG);
3457 		return (SET_ERROR(EXDEV));
3458 	}
3459 
3460 	snap = list_head(&ddpa->shared_snaps);
3461 	if (snap == NULL) {
3462 		err = SET_ERROR(ENOENT);
3463 		goto out;
3464 	}
3465 	dsl_dataset_t *const origin_ds = snap->ds;
3466 
3467 	/*
3468 	 * Encrypted clones share a DSL Crypto Key with their origin's dsl dir.
3469 	 * When doing a promote we must make sure the encryption root for
3470 	 * both the target and the target's origin does not change to avoid
3471 	 * needing to rewrap encryption keys
3472 	 */
3473 	err = dsl_dataset_promote_crypt_check(hds->ds_dir, origin_ds->ds_dir);
3474 	if (err != 0)
3475 		goto out;
3476 
3477 	/*
3478 	 * Compute and check the amount of space to transfer.  Since this is
3479 	 * so expensive, don't do the preliminary check.
3480 	 */
3481 	if (!dmu_tx_is_syncing(tx)) {
3482 		promote_rele(ddpa, FTAG);
3483 		return (0);
3484 	}
3485 
3486 	/* compute origin's new unique space */
3487 	snap = list_tail(&ddpa->clone_snaps);
3488 	ASSERT(snap != NULL);
3489 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3490 	    origin_ds->ds_object);
3491 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3492 	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
3493 	    &ddpa->unique, &unused, &unused);
3494 
3495 	/*
3496 	 * Walk the snapshots that we are moving
3497 	 *
3498 	 * Compute space to transfer.  Consider the incremental changes
3499 	 * to used by each snapshot:
3500 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
3501 	 * So each snapshot gave birth to:
3502 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
3503 	 * So a sequence would look like:
3504 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
3505 	 * Which simplifies to:
3506 	 * uN + kN + kN-1 + ... + k1 + k0
3507 	 * Note however, if we stop before we reach the ORIGIN we get:
3508 	 * uN + kN + kN-1 + ... + kM - uM-1
3509 	 */
3510 	conflicting_snaps = B_FALSE;
3511 	ss_mv_cnt = 0;
3512 	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
3513 	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
3514 	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
3515 	for (snap = list_head(&ddpa->shared_snaps); snap;
3516 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3517 		uint64_t val, dlused, dlcomp, dluncomp;
3518 		dsl_dataset_t *ds = snap->ds;
3519 
3520 		ss_mv_cnt++;
3521 
3522 		/*
3523 		 * If there are long holds, we won't be able to evict
3524 		 * the objset.
3525 		 */
3526 		if (dsl_dataset_long_held(ds)) {
3527 			err = SET_ERROR(EBUSY);
3528 			goto out;
3529 		}
3530 
3531 		/* Check that the snapshot name does not conflict */
3532 		VERIFY0(dsl_dataset_get_snapname(ds));
3533 		if (strlen(ds->ds_snapname) >= max_snap_len) {
3534 			err = SET_ERROR(ENAMETOOLONG);
3535 			goto out;
3536 		}
3537 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
3538 		if (err == 0) {
3539 			fnvlist_add_boolean(ddpa->err_ds,
3540 			    snap->ds->ds_snapname);
3541 			conflicting_snaps = B_TRUE;
3542 		} else if (err != ENOENT) {
3543 			goto out;
3544 		}
3545 
3546 		/* The very first snapshot does not have a deadlist */
3547 		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
3548 			continue;
3549 
3550 		dsl_deadlist_space(&ds->ds_deadlist,
3551 		    &dlused, &dlcomp, &dluncomp);
3552 		ddpa->used += dlused;
3553 		ddpa->comp += dlcomp;
3554 		ddpa->uncomp += dluncomp;
3555 	}
3556 
3557 	/*
3558 	 * Check that bookmarks that are being transferred don't have
3559 	 * name conflicts.
3560 	 */
3561 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_ds->ds_bookmarks);
3562 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3563 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3564 	    dbn = AVL_NEXT(&origin_ds->ds_bookmarks, dbn)) {
3565 		if (strlen(dbn->dbn_name) >= max_snap_len) {
3566 			err = SET_ERROR(ENAMETOOLONG);
3567 			goto out;
3568 		}
3569 		zfs_bookmark_phys_t bm;
3570 		err = dsl_bookmark_lookup_impl(ddpa->ddpa_clone,
3571 		    dbn->dbn_name, &bm);
3572 
3573 		if (err == 0) {
3574 			fnvlist_add_boolean(ddpa->err_ds, dbn->dbn_name);
3575 			conflicting_snaps = B_TRUE;
3576 		} else if (err == ESRCH) {
3577 			err = 0;
3578 		}
3579 		if (err != 0) {
3580 			goto out;
3581 		}
3582 	}
3583 
3584 	/*
3585 	 * In order to return the full list of conflicting snapshots, we check
3586 	 * whether there was a conflict after traversing all of them.
3587 	 */
3588 	if (conflicting_snaps) {
3589 		err = SET_ERROR(EEXIST);
3590 		goto out;
3591 	}
3592 
3593 	/*
3594 	 * If we are a clone of a clone then we never reached ORIGIN,
3595 	 * so we need to subtract out the clone origin's used space.
3596 	 */
3597 	if (ddpa->origin_origin) {
3598 		ddpa->used -=
3599 		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
3600 		ddpa->comp -=
3601 		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
3602 		ddpa->uncomp -=
3603 		    dsl_dataset_phys(ddpa->origin_origin)->
3604 		    ds_uncompressed_bytes;
3605 	}
3606 
3607 	/* Check that there is enough space and limit headroom here */
3608 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
3609 	    0, ss_mv_cnt, ddpa->used, ddpa->cr);
3610 	if (err != 0)
3611 		goto out;
3612 
3613 	/*
3614 	 * Compute the amounts of space that will be used by snapshots
3615 	 * after the promotion (for both origin and clone).  For each,
3616 	 * it is the amount of space that will be on all of their
3617 	 * deadlists (that was not born before their new origin).
3618 	 */
3619 	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
3620 		uint64_t space;
3621 
3622 		/*
3623 		 * Note, typically this will not be a clone of a clone,
3624 		 * so dd_origin_txg will be < TXG_INITIAL, so
3625 		 * these snaplist_space() -> dsl_deadlist_space_range()
3626 		 * calls will be fast because they do not have to
3627 		 * iterate over all bps.
3628 		 */
3629 		snap = list_head(&ddpa->origin_snaps);
3630 		if (snap == NULL) {
3631 			err = SET_ERROR(ENOENT);
3632 			goto out;
3633 		}
3634 		err = snaplist_space(&ddpa->shared_snaps,
3635 		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
3636 		if (err != 0)
3637 			goto out;
3638 
3639 		err = snaplist_space(&ddpa->clone_snaps,
3640 		    snap->ds->ds_dir->dd_origin_txg, &space);
3641 		if (err != 0)
3642 			goto out;
3643 		ddpa->cloneusedsnap += space;
3644 	}
3645 	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
3646 	    DD_FLAG_USED_BREAKDOWN) {
3647 		err = snaplist_space(&ddpa->origin_snaps,
3648 		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
3649 		    &ddpa->originusedsnap);
3650 		if (err != 0)
3651 			goto out;
3652 	}
3653 
3654 out:
3655 	promote_rele(ddpa, FTAG);
3656 	return (err);
3657 }
3658 
3659 void
dsl_dataset_promote_sync(void * arg,dmu_tx_t * tx)3660 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
3661 {
3662 	dsl_dataset_promote_arg_t *ddpa = arg;
3663 	dsl_pool_t *dp = dmu_tx_pool(tx);
3664 	dsl_dataset_t *hds;
3665 	struct promotenode *snap;
3666 	dsl_dataset_t *origin_ds;
3667 	dsl_dataset_t *origin_head;
3668 	dsl_dir_t *dd;
3669 	dsl_dir_t *odd = NULL;
3670 	uint64_t oldnext_obj;
3671 	int64_t delta;
3672 
3673 	ASSERT(nvlist_empty(ddpa->err_ds));
3674 
3675 	VERIFY0(promote_hold(ddpa, dp, FTAG));
3676 	hds = ddpa->ddpa_clone;
3677 
3678 	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
3679 
3680 	snap = list_head(&ddpa->shared_snaps);
3681 	origin_ds = snap->ds;
3682 	dd = hds->ds_dir;
3683 
3684 	snap = list_head(&ddpa->origin_snaps);
3685 	origin_head = snap->ds;
3686 
3687 	/*
3688 	 * We need to explicitly open odd, since origin_ds's dd will be
3689 	 * changing.
3690 	 */
3691 	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
3692 	    NULL, FTAG, &odd));
3693 
3694 	dsl_dataset_promote_crypt_sync(hds->ds_dir, odd, tx);
3695 
3696 	/* change origin's next snap */
3697 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
3698 	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
3699 	snap = list_tail(&ddpa->clone_snaps);
3700 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3701 	    origin_ds->ds_object);
3702 	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
3703 
3704 	/* change the origin's next clone */
3705 	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
3706 		dsl_dataset_remove_from_next_clones(origin_ds,
3707 		    snap->ds->ds_object, tx);
3708 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3709 		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
3710 		    oldnext_obj, tx));
3711 	}
3712 
3713 	/* change origin */
3714 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
3715 	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
3716 	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
3717 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
3718 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
3719 	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
3720 	origin_head->ds_dir->dd_origin_txg =
3721 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3722 
3723 	/* change dd_clone entries */
3724 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3725 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3726 		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
3727 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3728 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3729 		    hds->ds_object, tx));
3730 
3731 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3732 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3733 		    origin_head->ds_object, tx));
3734 		if (dsl_dir_phys(dd)->dd_clones == 0) {
3735 			dsl_dir_phys(dd)->dd_clones =
3736 			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
3737 			    DMU_OT_NONE, 0, tx);
3738 		}
3739 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3740 		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
3741 	}
3742 
3743 	/*
3744 	 * Move bookmarks to this dir.
3745 	 */
3746 	dsl_bookmark_node_t *dbn_next;
3747 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3748 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3749 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3750 	    dbn = dbn_next) {
3751 		dbn_next = AVL_NEXT(&origin_head->ds_bookmarks, dbn);
3752 
3753 		avl_remove(&origin_head->ds_bookmarks, dbn);
3754 		VERIFY0(zap_remove(dp->dp_meta_objset,
3755 		    origin_head->ds_bookmarks_obj, dbn->dbn_name, tx));
3756 
3757 		dsl_bookmark_node_add(hds, dbn, tx);
3758 	}
3759 
3760 	dsl_bookmark_next_changed(hds, origin_ds, tx);
3761 
3762 	/* move snapshots to this dir */
3763 	for (snap = list_head(&ddpa->shared_snaps); snap;
3764 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3765 		dsl_dataset_t *ds = snap->ds;
3766 
3767 		/*
3768 		 * Property callbacks are registered to a particular
3769 		 * dsl_dir.  Since ours is changing, evict the objset
3770 		 * so that they will be unregistered from the old dsl_dir.
3771 		 */
3772 		if (ds->ds_objset) {
3773 			dmu_objset_evict(ds->ds_objset);
3774 			ds->ds_objset = NULL;
3775 		}
3776 
3777 		/* move snap name entry */
3778 		VERIFY0(dsl_dataset_get_snapname(ds));
3779 		VERIFY0(dsl_dataset_snap_remove(origin_head,
3780 		    ds->ds_snapname, tx, B_TRUE));
3781 		VERIFY0(zap_add(dp->dp_meta_objset,
3782 		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3783 		    8, 1, &ds->ds_object, tx));
3784 		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3785 		    DD_FIELD_SNAPSHOT_COUNT, tx);
3786 
3787 		/* change containing dsl_dir */
3788 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3789 		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3790 		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3791 		ASSERT3P(ds->ds_dir, ==, odd);
3792 		dsl_dir_rele(ds->ds_dir, ds);
3793 		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3794 		    NULL, ds, &ds->ds_dir));
3795 
3796 		/* move any clone references */
3797 		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3798 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3799 			zap_cursor_t zc;
3800 			zap_attribute_t *za = zap_attribute_alloc();
3801 
3802 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3803 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3804 			    zap_cursor_retrieve(&zc, za) == 0;
3805 			    zap_cursor_advance(&zc)) {
3806 				dsl_dataset_t *cnds;
3807 				uint64_t o;
3808 
3809 				if (za->za_first_integer == oldnext_obj) {
3810 					/*
3811 					 * We've already moved the
3812 					 * origin's reference.
3813 					 */
3814 					continue;
3815 				}
3816 
3817 				VERIFY0(dsl_dataset_hold_obj(dp,
3818 				    za->za_first_integer, FTAG, &cnds));
3819 				o = dsl_dir_phys(cnds->ds_dir)->
3820 				    dd_head_dataset_obj;
3821 
3822 				VERIFY0(zap_remove_int(dp->dp_meta_objset,
3823 				    dsl_dir_phys(odd)->dd_clones, o, tx));
3824 				VERIFY0(zap_add_int(dp->dp_meta_objset,
3825 				    dsl_dir_phys(dd)->dd_clones, o, tx));
3826 				dsl_dataset_rele(cnds, FTAG);
3827 			}
3828 			zap_cursor_fini(&zc);
3829 			zap_attribute_free(za);
3830 		}
3831 
3832 		ASSERT(!dsl_prop_hascb(ds));
3833 	}
3834 
3835 	/*
3836 	 * Change space accounting.
3837 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3838 	 * both be valid, or both be 0 (resulting in delta == 0).  This
3839 	 * is true for each of {clone,origin} independently.
3840 	 */
3841 
3842 	delta = ddpa->cloneusedsnap -
3843 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3844 	ASSERT3S(delta, >=, 0);
3845 	ASSERT3U(ddpa->used, >=, delta);
3846 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3847 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
3848 	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3849 
3850 	delta = ddpa->originusedsnap -
3851 	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3852 	ASSERT3S(delta, <=, 0);
3853 	ASSERT3U(ddpa->used, >=, -delta);
3854 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3855 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
3856 	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3857 
3858 	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3859 
3860 	/*
3861 	 * Since livelists are specific to a clone's origin txg, they
3862 	 * are no longer accurate. Destroy the livelist from the clone being
3863 	 * promoted. If the origin dataset is a clone, destroy its livelist
3864 	 * as well.
3865 	 */
3866 	dsl_dir_remove_livelist(dd, tx, B_TRUE);
3867 	dsl_dir_remove_livelist(odd, tx, B_TRUE);
3868 
3869 	/* log history record */
3870 	spa_history_log_internal_ds(hds, "promote", tx, " ");
3871 
3872 	dsl_dir_rele(odd, FTAG);
3873 
3874 	/*
3875 	 * Transfer common error blocks from old head to new head, before
3876 	 * calling promote_rele() on ddpa since we need to dereference
3877 	 * origin_head and hds.
3878 	 */
3879 	if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_HEAD_ERRLOG)) {
3880 		uint64_t old_head = origin_head->ds_object;
3881 		uint64_t new_head = hds->ds_object;
3882 		spa_swap_errlog(dp->dp_spa, new_head, old_head, tx);
3883 	}
3884 
3885 	promote_rele(ddpa, FTAG);
3886 }
3887 
3888 /*
3889  * Make a list of dsl_dataset_t's for the snapshots between first_obj
3890  * (exclusive) and last_obj (inclusive).  The list will be in reverse
3891  * order (last_obj will be the list_head()).  If first_obj == 0, do all
3892  * snapshots back to this dataset's origin.
3893  */
3894 static int
snaplist_make(dsl_pool_t * dp,uint64_t first_obj,uint64_t last_obj,list_t * l,const void * tag)3895 snaplist_make(dsl_pool_t *dp,
3896     uint64_t first_obj, uint64_t last_obj, list_t *l, const void *tag)
3897 {
3898 	uint64_t obj = last_obj;
3899 
3900 	list_create(l, sizeof (struct promotenode),
3901 	    offsetof(struct promotenode, link));
3902 
3903 	while (obj != first_obj) {
3904 		dsl_dataset_t *ds;
3905 		struct promotenode *snap;
3906 		int err;
3907 
3908 		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3909 		ASSERT(err != ENOENT);
3910 		if (err != 0)
3911 			return (err);
3912 
3913 		if (first_obj == 0)
3914 			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3915 
3916 		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3917 		snap->ds = ds;
3918 		list_insert_tail(l, snap);
3919 		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3920 	}
3921 
3922 	return (0);
3923 }
3924 
3925 static int
snaplist_space(list_t * l,uint64_t mintxg,uint64_t * spacep)3926 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3927 {
3928 	struct promotenode *snap;
3929 
3930 	*spacep = 0;
3931 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3932 		uint64_t used, comp, uncomp;
3933 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3934 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
3935 		*spacep += used;
3936 	}
3937 	return (0);
3938 }
3939 
3940 static void
snaplist_destroy(list_t * l,const void * tag)3941 snaplist_destroy(list_t *l, const void *tag)
3942 {
3943 	struct promotenode *snap;
3944 
3945 	if (l == NULL || !list_link_active(&l->list_head))
3946 		return;
3947 
3948 	while ((snap = list_remove_tail(l)) != NULL) {
3949 		dsl_dataset_rele(snap->ds, tag);
3950 		kmem_free(snap, sizeof (*snap));
3951 	}
3952 	list_destroy(l);
3953 }
3954 
3955 static int
promote_hold(dsl_dataset_promote_arg_t * ddpa,dsl_pool_t * dp,const void * tag)3956 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, const void *tag)
3957 {
3958 	int error;
3959 	dsl_dir_t *dd;
3960 	struct promotenode *snap;
3961 
3962 	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3963 	    &ddpa->ddpa_clone);
3964 	if (error != 0)
3965 		return (error);
3966 	dd = ddpa->ddpa_clone->ds_dir;
3967 
3968 	if (ddpa->ddpa_clone->ds_is_snapshot ||
3969 	    !dsl_dir_is_clone(dd)) {
3970 		dsl_dataset_rele(ddpa->ddpa_clone, tag);
3971 		return (SET_ERROR(EINVAL));
3972 	}
3973 
3974 	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3975 	    &ddpa->shared_snaps, tag);
3976 	if (error != 0)
3977 		goto out;
3978 
3979 	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3980 	    &ddpa->clone_snaps, tag);
3981 	if (error != 0)
3982 		goto out;
3983 
3984 	snap = list_head(&ddpa->shared_snaps);
3985 	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3986 	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3987 	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3988 	    &ddpa->origin_snaps, tag);
3989 	if (error != 0)
3990 		goto out;
3991 
3992 	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3993 		error = dsl_dataset_hold_obj(dp,
3994 		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
3995 		    tag, &ddpa->origin_origin);
3996 		if (error != 0)
3997 			goto out;
3998 	}
3999 out:
4000 	if (error != 0)
4001 		promote_rele(ddpa, tag);
4002 	return (error);
4003 }
4004 
4005 static void
promote_rele(dsl_dataset_promote_arg_t * ddpa,const void * tag)4006 promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag)
4007 {
4008 	snaplist_destroy(&ddpa->shared_snaps, tag);
4009 	snaplist_destroy(&ddpa->clone_snaps, tag);
4010 	snaplist_destroy(&ddpa->origin_snaps, tag);
4011 	if (ddpa->origin_origin != NULL)
4012 		dsl_dataset_rele(ddpa->origin_origin, tag);
4013 	dsl_dataset_rele(ddpa->ddpa_clone, tag);
4014 }
4015 
4016 /*
4017  * Promote a clone.
4018  *
4019  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
4020  * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
4021  */
4022 int
dsl_dataset_promote(const char * name,char * conflsnap)4023 dsl_dataset_promote(const char *name, char *conflsnap)
4024 {
4025 	dsl_dataset_promote_arg_t ddpa = { 0 };
4026 	uint64_t numsnaps;
4027 	int error;
4028 	nvpair_t *snap_pair;
4029 	objset_t *os;
4030 
4031 	/*
4032 	 * We will modify space proportional to the number of
4033 	 * snapshots.  Compute numsnaps.
4034 	 */
4035 	error = dmu_objset_hold(name, FTAG, &os);
4036 	if (error != 0)
4037 		return (error);
4038 	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
4039 	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
4040 	    &numsnaps);
4041 	dmu_objset_rele(os, FTAG);
4042 	if (error != 0)
4043 		return (error);
4044 
4045 	cred_t *cr = CRED();
4046 	crhold(cr);
4047 
4048 	ddpa.ddpa_clonename = name;
4049 	ddpa.err_ds = fnvlist_alloc();
4050 	ddpa.cr = cr;
4051 
4052 	error = dsl_sync_task(name, dsl_dataset_promote_check,
4053 	    dsl_dataset_promote_sync, &ddpa,
4054 	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
4055 
4056 	crfree(cr);
4057 
4058 	/*
4059 	 * Return the first conflicting snapshot found.
4060 	 */
4061 	snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
4062 	if (snap_pair != NULL && conflsnap != NULL)
4063 		(void) strlcpy(conflsnap, nvpair_name(snap_pair),
4064 		    ZFS_MAX_DATASET_NAME_LEN);
4065 
4066 	fnvlist_free(ddpa.err_ds);
4067 	return (error);
4068 }
4069 
4070 int
dsl_dataset_clone_swap_check_impl(dsl_dataset_t * clone,dsl_dataset_t * origin_head,boolean_t force,void * owner,dmu_tx_t * tx)4071 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
4072     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
4073 {
4074 	/*
4075 	 * "slack" factor for received datasets with refquota set on them.
4076 	 * See the bottom of this function for details on its use.
4077 	 */
4078 	uint64_t refquota_slack = (uint64_t)DMU_MAX_ACCESS *
4079 	    spa_asize_inflation;
4080 	int64_t unused_refres_delta;
4081 
4082 	/* they should both be heads */
4083 	if (clone->ds_is_snapshot ||
4084 	    origin_head->ds_is_snapshot)
4085 		return (SET_ERROR(EINVAL));
4086 
4087 	/* if we are not forcing, the branch point should be just before them */
4088 	if (!force && clone->ds_prev != origin_head->ds_prev)
4089 		return (SET_ERROR(EINVAL));
4090 
4091 	/* clone should be the clone (unless they are unrelated) */
4092 	if (clone->ds_prev != NULL &&
4093 	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
4094 	    origin_head->ds_dir != clone->ds_prev->ds_dir)
4095 		return (SET_ERROR(EINVAL));
4096 
4097 	/* the clone should be a child of the origin */
4098 	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
4099 		return (SET_ERROR(EINVAL));
4100 
4101 	/* origin_head shouldn't be modified unless 'force' */
4102 	if (!force &&
4103 	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
4104 		return (SET_ERROR(ETXTBSY));
4105 
4106 	/* origin_head should have no long holds (e.g. is not mounted) */
4107 	if (dsl_dataset_handoff_check(origin_head, owner, tx))
4108 		return (SET_ERROR(EBUSY));
4109 
4110 	/* check amount of any unconsumed refreservation */
4111 	unused_refres_delta =
4112 	    (int64_t)MIN(origin_head->ds_reserved,
4113 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4114 	    (int64_t)MIN(origin_head->ds_reserved,
4115 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4116 
4117 	if (unused_refres_delta > 0 &&
4118 	    unused_refres_delta >
4119 	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
4120 		return (SET_ERROR(ENOSPC));
4121 
4122 	/*
4123 	 * The clone can't be too much over the head's refquota.
4124 	 *
4125 	 * To ensure that the entire refquota can be used, we allow one
4126 	 * transaction to exceed the refquota.  Therefore, this check
4127 	 * needs to also allow for the space referenced to be more than the
4128 	 * refquota.  The maximum amount of space that one transaction can use
4129 	 * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
4130 	 * overage ensures that we are able to receive a filesystem that
4131 	 * exceeds the refquota on the source system.
4132 	 *
4133 	 * So that overage is the refquota_slack we use below.
4134 	 */
4135 	if (origin_head->ds_quota != 0 &&
4136 	    dsl_dataset_phys(clone)->ds_referenced_bytes >
4137 	    origin_head->ds_quota + refquota_slack)
4138 		return (SET_ERROR(EDQUOT));
4139 
4140 	return (0);
4141 }
4142 
4143 static void
dsl_dataset_swap_remap_deadlists(dsl_dataset_t * clone,dsl_dataset_t * origin,dmu_tx_t * tx)4144 dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
4145     dsl_dataset_t *origin, dmu_tx_t *tx)
4146 {
4147 	uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
4148 	dsl_pool_t *dp = dmu_tx_pool(tx);
4149 
4150 	ASSERT(dsl_pool_sync_context(dp));
4151 
4152 	clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
4153 	origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
4154 
4155 	if (clone_remap_dl_obj != 0) {
4156 		dsl_deadlist_close(&clone->ds_remap_deadlist);
4157 		dsl_dataset_unset_remap_deadlist_object(clone, tx);
4158 	}
4159 	if (origin_remap_dl_obj != 0) {
4160 		dsl_deadlist_close(&origin->ds_remap_deadlist);
4161 		dsl_dataset_unset_remap_deadlist_object(origin, tx);
4162 	}
4163 
4164 	if (clone_remap_dl_obj != 0) {
4165 		dsl_dataset_set_remap_deadlist_object(origin,
4166 		    clone_remap_dl_obj, tx);
4167 		VERIFY0(dsl_deadlist_open(&origin->ds_remap_deadlist,
4168 		    dp->dp_meta_objset, clone_remap_dl_obj));
4169 	}
4170 	if (origin_remap_dl_obj != 0) {
4171 		dsl_dataset_set_remap_deadlist_object(clone,
4172 		    origin_remap_dl_obj, tx);
4173 		VERIFY0(dsl_deadlist_open(&clone->ds_remap_deadlist,
4174 		    dp->dp_meta_objset, origin_remap_dl_obj));
4175 	}
4176 }
4177 
4178 void
dsl_dataset_clone_swap_sync_impl(dsl_dataset_t * clone,dsl_dataset_t * origin_head,dmu_tx_t * tx)4179 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
4180     dsl_dataset_t *origin_head, dmu_tx_t *tx)
4181 {
4182 	dsl_pool_t *dp = dmu_tx_pool(tx);
4183 	int64_t unused_refres_delta;
4184 
4185 	ASSERT0(clone->ds_reserved);
4186 	/*
4187 	 * NOTE: On DEBUG kernels there could be a race between this and
4188 	 * the check function if spa_asize_inflation is adjusted...
4189 	 */
4190 	ASSERT(origin_head->ds_quota == 0 ||
4191 	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
4192 	    DMU_MAX_ACCESS * spa_asize_inflation);
4193 	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
4194 
4195 	dsl_dir_cancel_waiters(origin_head->ds_dir);
4196 
4197 	/*
4198 	 * Swap per-dataset feature flags.
4199 	 */
4200 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4201 		if (!(spa_feature_table[f].fi_flags &
4202 		    ZFEATURE_FLAG_PER_DATASET)) {
4203 			ASSERT(!dsl_dataset_feature_is_active(clone, f));
4204 			ASSERT(!dsl_dataset_feature_is_active(origin_head, f));
4205 			continue;
4206 		}
4207 
4208 		boolean_t clone_inuse = dsl_dataset_feature_is_active(clone, f);
4209 		void *clone_feature = clone->ds_feature[f];
4210 		boolean_t origin_head_inuse =
4211 		    dsl_dataset_feature_is_active(origin_head, f);
4212 		void *origin_head_feature = origin_head->ds_feature[f];
4213 
4214 		if (clone_inuse)
4215 			dsl_dataset_deactivate_feature_impl(clone, f, tx);
4216 		if (origin_head_inuse)
4217 			dsl_dataset_deactivate_feature_impl(origin_head, f, tx);
4218 
4219 		if (clone_inuse) {
4220 			dsl_dataset_activate_feature(origin_head->ds_object, f,
4221 			    clone_feature, tx);
4222 			origin_head->ds_feature[f] = clone_feature;
4223 		}
4224 		if (origin_head_inuse) {
4225 			dsl_dataset_activate_feature(clone->ds_object, f,
4226 			    origin_head_feature, tx);
4227 			clone->ds_feature[f] = origin_head_feature;
4228 		}
4229 	}
4230 
4231 	dmu_buf_will_dirty(clone->ds_dbuf, tx);
4232 	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
4233 
4234 	if (clone->ds_objset != NULL) {
4235 		dmu_objset_evict(clone->ds_objset);
4236 		clone->ds_objset = NULL;
4237 	}
4238 
4239 	if (origin_head->ds_objset != NULL) {
4240 		dmu_objset_evict(origin_head->ds_objset);
4241 		origin_head->ds_objset = NULL;
4242 	}
4243 
4244 	unused_refres_delta =
4245 	    (int64_t)MIN(origin_head->ds_reserved,
4246 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4247 	    (int64_t)MIN(origin_head->ds_reserved,
4248 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4249 
4250 	/*
4251 	 * Reset origin's unique bytes.
4252 	 */
4253 	{
4254 		dsl_dataset_t *origin = clone->ds_prev;
4255 		uint64_t comp, uncomp;
4256 
4257 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
4258 		dsl_deadlist_space_range(&clone->ds_deadlist,
4259 		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
4260 		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
4261 	}
4262 
4263 	/* swap blkptrs */
4264 	{
4265 		rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
4266 		rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
4267 		blkptr_t tmp;
4268 		tmp = dsl_dataset_phys(origin_head)->ds_bp;
4269 		dsl_dataset_phys(origin_head)->ds_bp =
4270 		    dsl_dataset_phys(clone)->ds_bp;
4271 		dsl_dataset_phys(clone)->ds_bp = tmp;
4272 		rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
4273 		rrw_exit(&clone->ds_bp_rwlock, FTAG);
4274 	}
4275 
4276 	/* set dd_*_bytes */
4277 	{
4278 		int64_t dused, dcomp, duncomp;
4279 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
4280 		uint64_t odl_used, odl_comp, odl_uncomp;
4281 
4282 		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
4283 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
4284 
4285 		dsl_deadlist_space(&clone->ds_deadlist,
4286 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4287 		dsl_deadlist_space(&origin_head->ds_deadlist,
4288 		    &odl_used, &odl_comp, &odl_uncomp);
4289 
4290 		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
4291 		    cdl_used -
4292 		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
4293 		    odl_used);
4294 		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
4295 		    cdl_comp -
4296 		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
4297 		    odl_comp);
4298 		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
4299 		    cdl_uncomp -
4300 		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
4301 		    odl_uncomp);
4302 
4303 		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
4304 		    dused, dcomp, duncomp, tx);
4305 		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
4306 		    -dused, -dcomp, -duncomp, tx);
4307 
4308 		/*
4309 		 * The difference in the space used by snapshots is the
4310 		 * difference in snapshot space due to the head's
4311 		 * deadlist (since that's the only thing that's
4312 		 * changing that affects the snapused).
4313 		 */
4314 		dsl_deadlist_space_range(&clone->ds_deadlist,
4315 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4316 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4317 		dsl_deadlist_space_range(&origin_head->ds_deadlist,
4318 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4319 		    &odl_used, &odl_comp, &odl_uncomp);
4320 		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
4321 		    DD_USED_HEAD, DD_USED_SNAP, tx);
4322 	}
4323 
4324 	/* swap ds_*_bytes */
4325 	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
4326 	    dsl_dataset_phys(clone)->ds_referenced_bytes);
4327 	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
4328 	    dsl_dataset_phys(clone)->ds_compressed_bytes);
4329 	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
4330 	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
4331 	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
4332 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4333 
4334 	/* apply any parent delta for change in unconsumed refreservation */
4335 	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
4336 	    unused_refres_delta, 0, 0, tx);
4337 
4338 	/*
4339 	 * Swap deadlists.
4340 	 */
4341 	dsl_deadlist_close(&clone->ds_deadlist);
4342 	dsl_deadlist_close(&origin_head->ds_deadlist);
4343 	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
4344 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
4345 	VERIFY0(dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
4346 	    dsl_dataset_phys(clone)->ds_deadlist_obj));
4347 	VERIFY0(dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
4348 	    dsl_dataset_phys(origin_head)->ds_deadlist_obj));
4349 	dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
4350 
4351 	/*
4352 	 * If there is a bookmark at the origin, its "next dataset" is
4353 	 * changing, so we need to reset its FBN.
4354 	 */
4355 	dsl_bookmark_next_changed(origin_head, origin_head->ds_prev, tx);
4356 
4357 	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
4358 
4359 	/*
4360 	 * Destroy any livelists associated with the clone or the origin,
4361 	 * since after the swap the corresponding livelists are no longer
4362 	 * valid.
4363 	 */
4364 	dsl_dir_remove_livelist(clone->ds_dir, tx, B_TRUE);
4365 	dsl_dir_remove_livelist(origin_head->ds_dir, tx, B_TRUE);
4366 
4367 	spa_history_log_internal_ds(clone, "clone swap", tx,
4368 	    "parent=%s", origin_head->ds_dir->dd_myname);
4369 }
4370 
4371 /*
4372  * Given a pool name and a dataset object number in that pool,
4373  * return the name of that dataset.
4374  */
4375 int
dsl_dsobj_to_dsname(char * pname,uint64_t obj,char * buf)4376 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
4377 {
4378 	dsl_pool_t *dp;
4379 	dsl_dataset_t *ds;
4380 	int error;
4381 
4382 	error = dsl_pool_hold(pname, FTAG, &dp);
4383 	if (error != 0)
4384 		return (error);
4385 
4386 	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
4387 	if (error == 0) {
4388 		dsl_dataset_name(ds, buf);
4389 		dsl_dataset_rele(ds, FTAG);
4390 	}
4391 	dsl_pool_rele(dp, FTAG);
4392 
4393 	return (error);
4394 }
4395 
4396 int
dsl_dataset_check_quota(dsl_dataset_t * ds,boolean_t check_quota,uint64_t asize,uint64_t inflight,uint64_t * used,uint64_t * ref_rsrv)4397 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
4398     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
4399 {
4400 	int error = 0;
4401 
4402 	ASSERT3S(asize, >, 0);
4403 
4404 	/*
4405 	 * *ref_rsrv is the portion of asize that will come from any
4406 	 * unconsumed refreservation space.
4407 	 */
4408 	*ref_rsrv = 0;
4409 
4410 	mutex_enter(&ds->ds_lock);
4411 	/*
4412 	 * Make a space adjustment for reserved bytes.
4413 	 */
4414 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
4415 		ASSERT3U(*used, >=,
4416 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4417 		*used -=
4418 		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4419 		*ref_rsrv =
4420 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
4421 	}
4422 
4423 	if (!check_quota || ds->ds_quota == 0) {
4424 		mutex_exit(&ds->ds_lock);
4425 		return (0);
4426 	}
4427 	/*
4428 	 * If they are requesting more space, and our current estimate
4429 	 * is over quota, they get to try again unless the actual
4430 	 * on-disk is over quota and there are no pending changes (which
4431 	 * may free up space for us).
4432 	 */
4433 	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
4434 	    ds->ds_quota) {
4435 		if (inflight > 0 ||
4436 		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
4437 			error = SET_ERROR(ERESTART);
4438 		else
4439 			error = SET_ERROR(EDQUOT);
4440 	}
4441 	mutex_exit(&ds->ds_lock);
4442 
4443 	return (error);
4444 }
4445 
4446 typedef struct dsl_dataset_set_qr_arg {
4447 	const char *ddsqra_name;
4448 	zprop_source_t ddsqra_source;
4449 	uint64_t ddsqra_value;
4450 } dsl_dataset_set_qr_arg_t;
4451 
4452 
4453 static int
dsl_dataset_set_refquota_check(void * arg,dmu_tx_t * tx)4454 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
4455 {
4456 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4457 	dsl_pool_t *dp = dmu_tx_pool(tx);
4458 	dsl_dataset_t *ds;
4459 	int error;
4460 	uint64_t newval;
4461 
4462 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
4463 		return (SET_ERROR(ENOTSUP));
4464 
4465 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4466 	if (error != 0)
4467 		return (error);
4468 
4469 	if (ds->ds_is_snapshot) {
4470 		dsl_dataset_rele(ds, FTAG);
4471 		return (SET_ERROR(EINVAL));
4472 	}
4473 
4474 	error = dsl_prop_predict(ds->ds_dir,
4475 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4476 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4477 	if (error != 0) {
4478 		dsl_dataset_rele(ds, FTAG);
4479 		return (error);
4480 	}
4481 
4482 	if (newval == 0) {
4483 		dsl_dataset_rele(ds, FTAG);
4484 		return (0);
4485 	}
4486 
4487 	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
4488 	    newval < ds->ds_reserved) {
4489 		dsl_dataset_rele(ds, FTAG);
4490 		return (SET_ERROR(ENOSPC));
4491 	}
4492 
4493 	dsl_dataset_rele(ds, FTAG);
4494 	return (0);
4495 }
4496 
4497 static void
dsl_dataset_set_refquota_sync(void * arg,dmu_tx_t * tx)4498 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
4499 {
4500 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4501 	dsl_pool_t *dp = dmu_tx_pool(tx);
4502 	dsl_dataset_t *ds = NULL;
4503 	uint64_t newval;
4504 
4505 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4506 
4507 	dsl_prop_set_sync_impl(ds,
4508 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4509 	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
4510 	    &ddsqra->ddsqra_value, tx);
4511 
4512 	VERIFY0(dsl_prop_get_int_ds(ds,
4513 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
4514 
4515 	if (ds->ds_quota != newval) {
4516 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
4517 		ds->ds_quota = newval;
4518 	}
4519 	dsl_dataset_rele(ds, FTAG);
4520 }
4521 
4522 int
dsl_dataset_set_refquota(const char * dsname,zprop_source_t source,uint64_t refquota)4523 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
4524     uint64_t refquota)
4525 {
4526 	dsl_dataset_set_qr_arg_t ddsqra;
4527 
4528 	ddsqra.ddsqra_name = dsname;
4529 	ddsqra.ddsqra_source = source;
4530 	ddsqra.ddsqra_value = refquota;
4531 
4532 	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
4533 	    dsl_dataset_set_refquota_sync, &ddsqra, 0,
4534 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4535 }
4536 
4537 static int
dsl_dataset_set_refreservation_check(void * arg,dmu_tx_t * tx)4538 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
4539 {
4540 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4541 	dsl_pool_t *dp = dmu_tx_pool(tx);
4542 	dsl_dataset_t *ds;
4543 	int error;
4544 	uint64_t newval, unique;
4545 
4546 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
4547 		return (SET_ERROR(ENOTSUP));
4548 
4549 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4550 	if (error != 0)
4551 		return (error);
4552 
4553 	if (ds->ds_is_snapshot) {
4554 		dsl_dataset_rele(ds, FTAG);
4555 		return (SET_ERROR(EINVAL));
4556 	}
4557 
4558 	error = dsl_prop_predict(ds->ds_dir,
4559 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4560 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4561 	if (error != 0) {
4562 		dsl_dataset_rele(ds, FTAG);
4563 		return (error);
4564 	}
4565 
4566 	/*
4567 	 * If we are doing the preliminary check in open context, the
4568 	 * space estimates may be inaccurate.
4569 	 */
4570 	if (!dmu_tx_is_syncing(tx)) {
4571 		dsl_dataset_rele(ds, FTAG);
4572 		return (0);
4573 	}
4574 
4575 	mutex_enter(&ds->ds_lock);
4576 	if (!DS_UNIQUE_IS_ACCURATE(ds))
4577 		dsl_dataset_recalc_head_uniq(ds);
4578 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4579 	mutex_exit(&ds->ds_lock);
4580 
4581 	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
4582 		uint64_t delta = MAX(unique, newval) -
4583 		    MAX(unique, ds->ds_reserved);
4584 
4585 		if (delta >
4586 		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
4587 		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
4588 			dsl_dataset_rele(ds, FTAG);
4589 			return (SET_ERROR(ENOSPC));
4590 		}
4591 	}
4592 
4593 	dsl_dataset_rele(ds, FTAG);
4594 	return (0);
4595 }
4596 
4597 void
dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t * ds,zprop_source_t source,uint64_t value,dmu_tx_t * tx)4598 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
4599     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
4600 {
4601 	uint64_t newval;
4602 	uint64_t unique;
4603 	int64_t delta;
4604 
4605 	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4606 	    source, sizeof (value), 1, &value, tx);
4607 
4608 	VERIFY0(dsl_prop_get_int_ds(ds,
4609 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
4610 
4611 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
4612 	mutex_enter(&ds->ds_dir->dd_lock);
4613 	mutex_enter(&ds->ds_lock);
4614 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
4615 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4616 	delta = MAX(0, (int64_t)(newval - unique)) -
4617 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
4618 	ds->ds_reserved = newval;
4619 	mutex_exit(&ds->ds_lock);
4620 
4621 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
4622 	mutex_exit(&ds->ds_dir->dd_lock);
4623 }
4624 
4625 static void
dsl_dataset_set_refreservation_sync(void * arg,dmu_tx_t * tx)4626 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
4627 {
4628 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4629 	dsl_pool_t *dp = dmu_tx_pool(tx);
4630 	dsl_dataset_t *ds = NULL;
4631 
4632 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4633 	dsl_dataset_set_refreservation_sync_impl(ds,
4634 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
4635 	dsl_dataset_rele(ds, FTAG);
4636 }
4637 
4638 int
dsl_dataset_set_refreservation(const char * dsname,zprop_source_t source,uint64_t refreservation)4639 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
4640     uint64_t refreservation)
4641 {
4642 	dsl_dataset_set_qr_arg_t ddsqra;
4643 
4644 	ddsqra.ddsqra_name = dsname;
4645 	ddsqra.ddsqra_source = source;
4646 	ddsqra.ddsqra_value = refreservation;
4647 
4648 	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
4649 	    dsl_dataset_set_refreservation_sync, &ddsqra, 0,
4650 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4651 }
4652 
4653 typedef struct dsl_dataset_set_compression_arg {
4654 	const char *ddsca_name;
4655 	zprop_source_t ddsca_source;
4656 	uint64_t ddsca_value;
4657 } dsl_dataset_set_compression_arg_t;
4658 
4659 static int
dsl_dataset_set_compression_check(void * arg,dmu_tx_t * tx)4660 dsl_dataset_set_compression_check(void *arg, dmu_tx_t *tx)
4661 {
4662 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4663 	dsl_pool_t *dp = dmu_tx_pool(tx);
4664 
4665 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4666 	spa_feature_t f = zio_compress_to_feature(compval);
4667 
4668 	if (f == SPA_FEATURE_NONE)
4669 		return (SET_ERROR(EINVAL));
4670 
4671 	if (!spa_feature_is_enabled(dp->dp_spa, f))
4672 		return (SET_ERROR(ENOTSUP));
4673 
4674 	return (0);
4675 }
4676 
4677 static void
dsl_dataset_set_compression_sync(void * arg,dmu_tx_t * tx)4678 dsl_dataset_set_compression_sync(void *arg, dmu_tx_t *tx)
4679 {
4680 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4681 	dsl_pool_t *dp = dmu_tx_pool(tx);
4682 	dsl_dataset_t *ds = NULL;
4683 
4684 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4685 	spa_feature_t f = zio_compress_to_feature(compval);
4686 	ASSERT3S(f, !=, SPA_FEATURE_NONE);
4687 	ASSERT3S(spa_feature_table[f].fi_type, ==, ZFEATURE_TYPE_BOOLEAN);
4688 
4689 	VERIFY0(dsl_dataset_hold(dp, ddsca->ddsca_name, FTAG, &ds));
4690 	if (zfeature_active(f, ds->ds_feature[f]) != B_TRUE) {
4691 		ds->ds_feature_activation[f] = (void *)B_TRUE;
4692 		dsl_dataset_activate_feature(ds->ds_object, f,
4693 		    ds->ds_feature_activation[f], tx);
4694 		ds->ds_feature[f] = ds->ds_feature_activation[f];
4695 	}
4696 	dsl_dataset_rele(ds, FTAG);
4697 }
4698 
4699 int
dsl_dataset_set_compression(const char * dsname,zprop_source_t source,uint64_t compression)4700 dsl_dataset_set_compression(const char *dsname, zprop_source_t source,
4701     uint64_t compression)
4702 {
4703 	dsl_dataset_set_compression_arg_t ddsca;
4704 
4705 	/*
4706 	 * The sync task is only required for zstd in order to activate
4707 	 * the feature flag when the property is first set.
4708 	 */
4709 	if (ZIO_COMPRESS_ALGO(compression) != ZIO_COMPRESS_ZSTD)
4710 		return (0);
4711 
4712 	ddsca.ddsca_name = dsname;
4713 	ddsca.ddsca_source = source;
4714 	ddsca.ddsca_value = compression;
4715 
4716 	return (dsl_sync_task(dsname, dsl_dataset_set_compression_check,
4717 	    dsl_dataset_set_compression_sync, &ddsca, 0,
4718 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4719 }
4720 
4721 /*
4722  * Return (in *usedp) the amount of space referenced by "new" that was not
4723  * referenced at the time the bookmark corresponds to.  "New" may be a
4724  * snapshot or a head.  The bookmark must be before new, in
4725  * new's filesystem (or its origin) -- caller verifies this.
4726  *
4727  * The written space is calculated by considering two components:  First, we
4728  * ignore any freed space, and calculate the written as new's used space
4729  * minus old's used space.  Next, we add in the amount of space that was freed
4730  * between the two time points, thus reducing new's used space relative to
4731  * old's. Specifically, this is the space that was born before
4732  * zbm_creation_txg, and freed before new (ie. on new's deadlist or a
4733  * previous deadlist).
4734  *
4735  * space freed                         [---------------------]
4736  * snapshots                       ---O-------O--------O-------O------
4737  *                                         bookmark           new
4738  *
4739  * Note, the bookmark's zbm_*_bytes_refd must be valid, but if the HAS_FBN
4740  * flag is not set, we will calculate the freed_before_next based on the
4741  * next snapshot's deadlist, rather than using zbm_*_freed_before_next_snap.
4742  */
4743 static int
dsl_dataset_space_written_impl(zfs_bookmark_phys_t * bmp,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4744 dsl_dataset_space_written_impl(zfs_bookmark_phys_t *bmp,
4745     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4746 {
4747 	int err = 0;
4748 	dsl_pool_t *dp = new->ds_dir->dd_pool;
4749 
4750 	ASSERT(dsl_pool_config_held(dp));
4751 	if (dsl_dataset_is_snapshot(new)) {
4752 		ASSERT3U(bmp->zbm_creation_txg, <,
4753 		    dsl_dataset_phys(new)->ds_creation_txg);
4754 	}
4755 
4756 	*usedp = 0;
4757 	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
4758 	*usedp -= bmp->zbm_referenced_bytes_refd;
4759 
4760 	*compp = 0;
4761 	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
4762 	*compp -= bmp->zbm_compressed_bytes_refd;
4763 
4764 	*uncompp = 0;
4765 	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
4766 	*uncompp -= bmp->zbm_uncompressed_bytes_refd;
4767 
4768 	dsl_dataset_t *snap = new;
4769 
4770 	while (dsl_dataset_phys(snap)->ds_prev_snap_txg >
4771 	    bmp->zbm_creation_txg) {
4772 		uint64_t used, comp, uncomp;
4773 
4774 		dsl_deadlist_space_range(&snap->ds_deadlist,
4775 		    0, bmp->zbm_creation_txg,
4776 		    &used, &comp, &uncomp);
4777 		*usedp += used;
4778 		*compp += comp;
4779 		*uncompp += uncomp;
4780 
4781 		uint64_t snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
4782 		if (snap != new)
4783 			dsl_dataset_rele(snap, FTAG);
4784 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4785 		if (err != 0)
4786 			break;
4787 	}
4788 
4789 	/*
4790 	 * We might not have the FBN if we are calculating written from
4791 	 * a snapshot (because we didn't know the correct "next" snapshot
4792 	 * until now).
4793 	 */
4794 	if (bmp->zbm_flags & ZBM_FLAG_HAS_FBN) {
4795 		*usedp += bmp->zbm_referenced_freed_before_next_snap;
4796 		*compp += bmp->zbm_compressed_freed_before_next_snap;
4797 		*uncompp += bmp->zbm_uncompressed_freed_before_next_snap;
4798 	} else {
4799 		ASSERT3U(dsl_dataset_phys(snap)->ds_prev_snap_txg, ==,
4800 		    bmp->zbm_creation_txg);
4801 		uint64_t used, comp, uncomp;
4802 		dsl_deadlist_space(&snap->ds_deadlist, &used, &comp, &uncomp);
4803 		*usedp += used;
4804 		*compp += comp;
4805 		*uncompp += uncomp;
4806 	}
4807 	if (snap != new)
4808 		dsl_dataset_rele(snap, FTAG);
4809 	return (err);
4810 }
4811 
4812 /*
4813  * Return (in *usedp) the amount of space written in new that was not
4814  * present at the time the bookmark corresponds to.  New may be a
4815  * snapshot or the head.  Old must be a bookmark before new, in
4816  * new's filesystem (or its origin) -- caller verifies this.
4817  */
4818 int
dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t * bmp,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4819 dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t *bmp,
4820     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4821 {
4822 	if (!(bmp->zbm_flags & ZBM_FLAG_HAS_FBN))
4823 		return (SET_ERROR(ENOTSUP));
4824 	return (dsl_dataset_space_written_impl(bmp, new,
4825 	    usedp, compp, uncompp));
4826 }
4827 
4828 /*
4829  * Return (in *usedp) the amount of space written in new that is not
4830  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4831  * a snapshot before new, in new's filesystem (or its origin).  If not then
4832  * fail and return EINVAL.
4833  */
4834 int
dsl_dataset_space_written(dsl_dataset_t * oldsnap,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4835 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4836     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4837 {
4838 	if (!dsl_dataset_is_before(new, oldsnap, 0))
4839 		return (SET_ERROR(EINVAL));
4840 
4841 	zfs_bookmark_phys_t zbm = { 0 };
4842 	dsl_dataset_phys_t *dsp = dsl_dataset_phys(oldsnap);
4843 	zbm.zbm_guid = dsp->ds_guid;
4844 	zbm.zbm_creation_txg = dsp->ds_creation_txg;
4845 	zbm.zbm_creation_time = dsp->ds_creation_time;
4846 	zbm.zbm_referenced_bytes_refd = dsp->ds_referenced_bytes;
4847 	zbm.zbm_compressed_bytes_refd = dsp->ds_compressed_bytes;
4848 	zbm.zbm_uncompressed_bytes_refd = dsp->ds_uncompressed_bytes;
4849 
4850 	/*
4851 	 * If oldsnap is the origin (or origin's origin, ...) of new,
4852 	 * we can't easily calculate the effective FBN.  Therefore,
4853 	 * we do not set ZBM_FLAG_HAS_FBN, so that the _impl will calculate
4854 	 * it relative to the correct "next": the next snapshot towards "new",
4855 	 * rather than the next snapshot in oldsnap's dsl_dir.
4856 	 */
4857 	return (dsl_dataset_space_written_impl(&zbm, new,
4858 	    usedp, compp, uncompp));
4859 }
4860 
4861 /*
4862  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4863  * lastsnap, and all snapshots in between are deleted.
4864  *
4865  * blocks that would be freed            [---------------------------]
4866  * snapshots                       ---O-------O--------O-------O--------O
4867  *                                        firstsnap        lastsnap
4868  *
4869  * This is the set of blocks that were born after the snap before firstsnap,
4870  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4871  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4872  * We calculate this by iterating over the relevant deadlists (from the snap
4873  * after lastsnap, backward to the snap after firstsnap), summing up the
4874  * space on the deadlist that was born after the snap before firstsnap.
4875  */
4876 int
dsl_dataset_space_wouldfree(dsl_dataset_t * firstsnap,dsl_dataset_t * lastsnap,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4877 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4878     dsl_dataset_t *lastsnap,
4879     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4880 {
4881 	int err = 0;
4882 	uint64_t snapobj;
4883 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4884 
4885 	ASSERT(firstsnap->ds_is_snapshot);
4886 	ASSERT(lastsnap->ds_is_snapshot);
4887 
4888 	/*
4889 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
4890 	 * is before lastsnap.
4891 	 */
4892 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
4893 	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
4894 	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
4895 		return (SET_ERROR(EINVAL));
4896 
4897 	*usedp = *compp = *uncompp = 0;
4898 
4899 	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
4900 	while (snapobj != firstsnap->ds_object) {
4901 		dsl_dataset_t *ds;
4902 		uint64_t used, comp, uncomp;
4903 
4904 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4905 		if (err != 0)
4906 			break;
4907 
4908 		dsl_deadlist_space_range(&ds->ds_deadlist,
4909 		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
4910 		    &used, &comp, &uncomp);
4911 		*usedp += used;
4912 		*compp += comp;
4913 		*uncompp += uncomp;
4914 
4915 		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4916 		ASSERT3U(snapobj, !=, 0);
4917 		dsl_dataset_rele(ds, FTAG);
4918 	}
4919 	return (err);
4920 }
4921 
4922 /*
4923  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
4924  * For example, they could both be snapshots of the same filesystem, and
4925  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
4926  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
4927  * filesystem.  Or 'earlier' could be the origin's origin.
4928  *
4929  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
4930  */
4931 boolean_t
dsl_dataset_is_before(dsl_dataset_t * later,dsl_dataset_t * earlier,uint64_t earlier_txg)4932 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4933     uint64_t earlier_txg)
4934 {
4935 	dsl_pool_t *dp = later->ds_dir->dd_pool;
4936 	int error;
4937 	boolean_t ret;
4938 
4939 	ASSERT(dsl_pool_config_held(dp));
4940 	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4941 
4942 	if (earlier_txg == 0)
4943 		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4944 
4945 	if (later->ds_is_snapshot &&
4946 	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4947 		return (B_FALSE);
4948 
4949 	if (later->ds_dir == earlier->ds_dir)
4950 		return (B_TRUE);
4951 
4952 	/*
4953 	 * We check dd_origin_obj explicitly here rather than using
4954 	 * dsl_dir_is_clone() so that we will return TRUE if "earlier"
4955 	 * is $ORIGIN@$ORIGIN.  dsl_dataset_space_written() depends on
4956 	 * this behavior.
4957 	 */
4958 	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == 0)
4959 		return (B_FALSE);
4960 
4961 	dsl_dataset_t *origin;
4962 	error = dsl_dataset_hold_obj(dp,
4963 	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4964 	if (error != 0)
4965 		return (B_FALSE);
4966 	if (dsl_dataset_phys(origin)->ds_creation_txg == earlier_txg &&
4967 	    origin->ds_dir == earlier->ds_dir) {
4968 		dsl_dataset_rele(origin, FTAG);
4969 		return (B_TRUE);
4970 	}
4971 	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4972 	dsl_dataset_rele(origin, FTAG);
4973 	return (ret);
4974 }
4975 
4976 void
dsl_dataset_zapify(dsl_dataset_t * ds,dmu_tx_t * tx)4977 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4978 {
4979 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4980 	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4981 }
4982 
4983 boolean_t
dsl_dataset_is_zapified(dsl_dataset_t * ds)4984 dsl_dataset_is_zapified(dsl_dataset_t *ds)
4985 {
4986 	dmu_object_info_t doi;
4987 
4988 	dmu_object_info_from_db(ds->ds_dbuf, &doi);
4989 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4990 }
4991 
4992 boolean_t
dsl_dataset_has_resume_receive_state(dsl_dataset_t * ds)4993 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
4994 {
4995 	return (dsl_dataset_is_zapified(ds) &&
4996 	    zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
4997 	    ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
4998 }
4999 
5000 uint64_t
dsl_dataset_get_remap_deadlist_object(dsl_dataset_t * ds)5001 dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
5002 {
5003 	uint64_t remap_deadlist_obj;
5004 	int err;
5005 
5006 	if (!dsl_dataset_is_zapified(ds))
5007 		return (0);
5008 
5009 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
5010 	    DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
5011 	    &remap_deadlist_obj);
5012 
5013 	if (err != 0) {
5014 		VERIFY3S(err, ==, ENOENT);
5015 		return (0);
5016 	}
5017 
5018 	ASSERT(remap_deadlist_obj != 0);
5019 	return (remap_deadlist_obj);
5020 }
5021 
5022 boolean_t
dsl_dataset_remap_deadlist_exists(dsl_dataset_t * ds)5023 dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
5024 {
5025 	EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
5026 	    dsl_dataset_get_remap_deadlist_object(ds) != 0);
5027 	return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
5028 }
5029 
5030 static void
dsl_dataset_set_remap_deadlist_object(dsl_dataset_t * ds,uint64_t obj,dmu_tx_t * tx)5031 dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
5032     dmu_tx_t *tx)
5033 {
5034 	ASSERT(obj != 0);
5035 	dsl_dataset_zapify(ds, tx);
5036 	VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
5037 	    DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
5038 }
5039 
5040 static void
dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t * ds,dmu_tx_t * tx)5041 dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
5042 {
5043 	VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
5044 	    ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
5045 }
5046 
5047 void
dsl_dataset_destroy_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)5048 dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
5049 {
5050 	uint64_t remap_deadlist_object;
5051 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
5052 
5053 	ASSERT(dmu_tx_is_syncing(tx));
5054 	ASSERT(dsl_dataset_remap_deadlist_exists(ds));
5055 
5056 	remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
5057 	dsl_deadlist_close(&ds->ds_remap_deadlist);
5058 	dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
5059 	dsl_dataset_unset_remap_deadlist_object(ds, tx);
5060 	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
5061 }
5062 
5063 void
dsl_dataset_create_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)5064 dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
5065 {
5066 	uint64_t remap_deadlist_obj;
5067 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
5068 
5069 	ASSERT(dmu_tx_is_syncing(tx));
5070 	ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
5071 	/*
5072 	 * Currently we only create remap deadlists when there are indirect
5073 	 * vdevs with referenced mappings.
5074 	 */
5075 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
5076 
5077 	remap_deadlist_obj = dsl_deadlist_clone(
5078 	    &ds->ds_deadlist, UINT64_MAX,
5079 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
5080 	dsl_dataset_set_remap_deadlist_object(ds,
5081 	    remap_deadlist_obj, tx);
5082 	VERIFY0(dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
5083 	    remap_deadlist_obj));
5084 	spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
5085 }
5086 
5087 void
dsl_dataset_activate_redaction(dsl_dataset_t * ds,uint64_t * redact_snaps,uint64_t num_redact_snaps,dmu_tx_t * tx)5088 dsl_dataset_activate_redaction(dsl_dataset_t *ds, uint64_t *redact_snaps,
5089     uint64_t num_redact_snaps, dmu_tx_t *tx)
5090 {
5091 	uint64_t dsobj = ds->ds_object;
5092 	struct feature_type_uint64_array_arg *ftuaa =
5093 	    kmem_zalloc(sizeof (*ftuaa), KM_SLEEP);
5094 	ftuaa->length = (int64_t)num_redact_snaps;
5095 	if (num_redact_snaps > 0) {
5096 		ftuaa->array = kmem_alloc(num_redact_snaps * sizeof (uint64_t),
5097 		    KM_SLEEP);
5098 		memcpy(ftuaa->array, redact_snaps, num_redact_snaps *
5099 		    sizeof (uint64_t));
5100 	}
5101 	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_REDACTED_DATASETS,
5102 	    ftuaa, tx);
5103 	ds->ds_feature[SPA_FEATURE_REDACTED_DATASETS] = ftuaa;
5104 }
5105 
5106 /*
5107  * Find and return (in *oldest_dsobj) the oldest snapshot of the dsobj
5108  * dataset whose birth time is >= min_txg.
5109  */
5110 int
dsl_dataset_oldest_snapshot(spa_t * spa,uint64_t head_ds,uint64_t min_txg,uint64_t * oldest_dsobj)5111 dsl_dataset_oldest_snapshot(spa_t *spa, uint64_t head_ds, uint64_t min_txg,
5112     uint64_t *oldest_dsobj)
5113 {
5114 	dsl_dataset_t *ds;
5115 	dsl_pool_t *dp = spa->spa_dsl_pool;
5116 
5117 	int error = dsl_dataset_hold_obj(dp, head_ds, FTAG, &ds);
5118 	if (error != 0)
5119 		return (error);
5120 
5121 	uint64_t prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5122 	uint64_t prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5123 
5124 	while (prev_obj != 0 && min_txg < prev_obj_txg) {
5125 		dsl_dataset_rele(ds, FTAG);
5126 		if ((error = dsl_dataset_hold_obj(dp, prev_obj,
5127 		    FTAG, &ds)) != 0)
5128 			return (error);
5129 		prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5130 		prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5131 	}
5132 	*oldest_dsobj = ds->ds_object;
5133 	dsl_dataset_rele(ds, FTAG);
5134 	return (0);
5135 }
5136 
5137 ZFS_MODULE_PARAM(zfs, zfs_, max_recordsize, UINT, ZMOD_RW,
5138 	"Max allowed record size");
5139 
5140 ZFS_MODULE_PARAM(zfs, zfs_, allow_redacted_dataset_mount, INT, ZMOD_RW,
5141 	"Allow mounting of redacted datasets");
5142 
5143 ZFS_MODULE_PARAM(zfs, zfs_, snapshot_history_enabled, INT, ZMOD_RW,
5144 	"Include snapshot events in pool history/events");
5145 
5146 EXPORT_SYMBOL(dsl_dataset_hold);
5147 EXPORT_SYMBOL(dsl_dataset_hold_flags);
5148 EXPORT_SYMBOL(dsl_dataset_hold_obj);
5149 EXPORT_SYMBOL(dsl_dataset_hold_obj_flags);
5150 EXPORT_SYMBOL(dsl_dataset_own);
5151 EXPORT_SYMBOL(dsl_dataset_own_obj);
5152 EXPORT_SYMBOL(dsl_dataset_name);
5153 EXPORT_SYMBOL(dsl_dataset_rele);
5154 EXPORT_SYMBOL(dsl_dataset_rele_flags);
5155 EXPORT_SYMBOL(dsl_dataset_disown);
5156 EXPORT_SYMBOL(dsl_dataset_tryown);
5157 EXPORT_SYMBOL(dsl_dataset_create_sync);
5158 EXPORT_SYMBOL(dsl_dataset_create_sync_dd);
5159 EXPORT_SYMBOL(dsl_dataset_snapshot_check);
5160 EXPORT_SYMBOL(dsl_dataset_snapshot_sync);
5161 EXPORT_SYMBOL(dsl_dataset_promote);
5162 EXPORT_SYMBOL(dsl_dataset_user_hold);
5163 EXPORT_SYMBOL(dsl_dataset_user_release);
5164 EXPORT_SYMBOL(dsl_dataset_get_holds);
5165 EXPORT_SYMBOL(dsl_dataset_get_blkptr);
5166 EXPORT_SYMBOL(dsl_dataset_get_spa);
5167 EXPORT_SYMBOL(dsl_dataset_modified_since_snap);
5168 EXPORT_SYMBOL(dsl_dataset_space_written);
5169 EXPORT_SYMBOL(dsl_dataset_space_wouldfree);
5170 EXPORT_SYMBOL(dsl_dataset_sync);
5171 EXPORT_SYMBOL(dsl_dataset_block_born);
5172 EXPORT_SYMBOL(dsl_dataset_block_kill);
5173 EXPORT_SYMBOL(dsl_dataset_dirty);
5174 EXPORT_SYMBOL(dsl_dataset_stats);
5175 EXPORT_SYMBOL(dsl_dataset_fast_stat);
5176 EXPORT_SYMBOL(dsl_dataset_space);
5177 EXPORT_SYMBOL(dsl_dataset_fsid_guid);
5178 EXPORT_SYMBOL(dsl_dsobj_to_dsname);
5179 EXPORT_SYMBOL(dsl_dataset_check_quota);
5180 EXPORT_SYMBOL(dsl_dataset_clone_swap_check_impl);
5181 EXPORT_SYMBOL(dsl_dataset_clone_swap_sync_impl);
5182