xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_dataset.c (revision 8a62a2a5659d1839d8799b4274c04469d7f17c78)
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 	inode_timespec_t snap_cmtime = dsl_dir_snap_cmtime(ds->ds_dir);
2859 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_SNAPSHOTS_CHANGED,
2860 	    snap_cmtime.tv_sec);
2861 	uint64_t snap_cmtime_ns =
2862 	    ((uint64_t)snap_cmtime.tv_sec * NANOSEC) +
2863 	    snap_cmtime.tv_nsec;
2864 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_SNAPSHOTS_CHANGED_NSECS,
2865 	    snap_cmtime_ns);
2866 	dsl_dataset_crypt_stats(ds, nv);
2867 
2868 	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2869 		uint64_t written;
2870 		if (dsl_get_written(ds, &written) == 0) {
2871 			dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2872 			    written);
2873 		}
2874 	}
2875 
2876 	if (!dsl_dataset_is_snapshot(ds)) {
2877 		char *token = get_receive_resume_token(ds);
2878 		if (token != NULL) {
2879 			dsl_prop_nvlist_add_string(nv,
2880 			    ZFS_PROP_RECEIVE_RESUME_TOKEN, token);
2881 			kmem_strfree(token);
2882 		}
2883 	}
2884 }
2885 
2886 void
dsl_dataset_fast_stat(dsl_dataset_t * ds,dmu_objset_stats_t * stat)2887 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2888 {
2889 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2890 	ASSERT(dsl_pool_config_held(dp));
2891 
2892 	stat->dds_creation_txg = dsl_get_creationtxg(ds);
2893 	stat->dds_inconsistent = dsl_get_inconsistent(ds);
2894 	stat->dds_guid = dsl_get_guid(ds);
2895 	stat->dds_redacted = dsl_get_redacted(ds);
2896 	stat->dds_origin[0] = '\0';
2897 	stat->dds_flags = DDS_FLAG_HAS_ENCRYPTED;
2898 	if (ds->ds_dir->dd_crypto_obj != 0)
2899 		stat->dds_flags |= DDS_FLAG_ENCRYPTED;
2900 	if (ds->ds_is_snapshot) {
2901 		stat->dds_is_snapshot = B_TRUE;
2902 		stat->dds_num_clones = dsl_get_numclones(ds);
2903 	} else {
2904 		stat->dds_is_snapshot = B_FALSE;
2905 		stat->dds_num_clones = 0;
2906 
2907 		if (dsl_dir_is_clone(ds->ds_dir)) {
2908 			dsl_dir_get_origin(ds->ds_dir, stat->dds_origin);
2909 		}
2910 	}
2911 }
2912 
2913 uint64_t
dsl_dataset_fsid_guid(dsl_dataset_t * ds)2914 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2915 {
2916 	return (ds->ds_fsid_guid);
2917 }
2918 
2919 void
dsl_dataset_space(dsl_dataset_t * ds,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)2920 dsl_dataset_space(dsl_dataset_t *ds,
2921     uint64_t *refdbytesp, uint64_t *availbytesp,
2922     uint64_t *usedobjsp, uint64_t *availobjsp)
2923 {
2924 	*refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
2925 	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2926 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
2927 		*availbytesp +=
2928 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2929 	if (ds->ds_quota != 0) {
2930 		/*
2931 		 * Adjust available bytes according to refquota
2932 		 */
2933 		if (*refdbytesp < ds->ds_quota)
2934 			*availbytesp = MIN(*availbytesp,
2935 			    ds->ds_quota - *refdbytesp);
2936 		else
2937 			*availbytesp = 0;
2938 	}
2939 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2940 	*usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
2941 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2942 	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
2943 }
2944 
2945 boolean_t
dsl_dataset_modified_since_snap(dsl_dataset_t * ds,dsl_dataset_t * snap)2946 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
2947 {
2948 	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2949 	uint64_t birth;
2950 
2951 	ASSERT(dsl_pool_config_held(dp));
2952 	if (snap == NULL)
2953 		return (B_FALSE);
2954 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2955 	birth = BP_GET_BIRTH(dsl_dataset_get_blkptr(ds));
2956 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2957 	if (birth > dsl_dataset_phys(snap)->ds_creation_txg) {
2958 		objset_t *os, *os_snap;
2959 		/*
2960 		 * It may be that only the ZIL differs, because it was
2961 		 * reset in the head.  Don't count that as being
2962 		 * modified.
2963 		 */
2964 		if (dmu_objset_from_ds(ds, &os) != 0)
2965 			return (B_TRUE);
2966 		if (dmu_objset_from_ds(snap, &os_snap) != 0)
2967 			return (B_TRUE);
2968 		return (memcmp(&os->os_phys->os_meta_dnode,
2969 		    &os_snap->os_phys->os_meta_dnode,
2970 		    sizeof (os->os_phys->os_meta_dnode)) != 0);
2971 	}
2972 	return (B_FALSE);
2973 }
2974 
2975 static int
dsl_dataset_rename_snapshot_check_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)2976 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
2977     dsl_dataset_t *hds, void *arg)
2978 {
2979 	(void) dp;
2980 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2981 	int error;
2982 	uint64_t val;
2983 
2984 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2985 	if (error != 0) {
2986 		/* ignore nonexistent snapshots */
2987 		return (error == ENOENT ? 0 : error);
2988 	}
2989 
2990 	/* new name should not exist */
2991 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
2992 	if (error == 0)
2993 		error = SET_ERROR(EEXIST);
2994 	else if (error == ENOENT)
2995 		error = 0;
2996 
2997 	/* dataset name + 1 for the "@" + the new snapshot name must fit */
2998 	if (dsl_dir_namelen(hds->ds_dir) + 1 +
2999 	    strlen(ddrsa->ddrsa_newsnapname) >= ZFS_MAX_DATASET_NAME_LEN)
3000 		error = SET_ERROR(ENAMETOOLONG);
3001 
3002 	return (error);
3003 }
3004 
3005 int
dsl_dataset_rename_snapshot_check(void * arg,dmu_tx_t * tx)3006 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
3007 {
3008 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3009 	dsl_pool_t *dp = dmu_tx_pool(tx);
3010 	dsl_dataset_t *hds;
3011 	int error;
3012 
3013 	error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
3014 	if (error != 0)
3015 		return (error);
3016 
3017 	if (ddrsa->ddrsa_recursive) {
3018 		error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3019 		    dsl_dataset_rename_snapshot_check_impl, ddrsa,
3020 		    DS_FIND_CHILDREN);
3021 	} else {
3022 		error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
3023 	}
3024 	dsl_dataset_rele(hds, FTAG);
3025 	return (error);
3026 }
3027 
3028 static int
dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)3029 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
3030     dsl_dataset_t *hds, void *arg)
3031 {
3032 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3033 	dsl_dataset_t *ds;
3034 	uint64_t val;
3035 	dmu_tx_t *tx = ddrsa->ddrsa_tx;
3036 	char *oldname, *newname;
3037 	int error;
3038 
3039 	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
3040 	ASSERT(error == 0 || error == ENOENT);
3041 	if (error == ENOENT) {
3042 		/* ignore nonexistent snapshots */
3043 		return (0);
3044 	}
3045 
3046 	VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
3047 
3048 	/* log before we change the name */
3049 	spa_history_log_internal_ds(ds, "rename", tx,
3050 	    "-> @%s", ddrsa->ddrsa_newsnapname);
3051 
3052 	VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
3053 	    B_FALSE));
3054 	mutex_enter(&ds->ds_lock);
3055 	(void) strlcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname,
3056 	    sizeof (ds->ds_snapname));
3057 	mutex_exit(&ds->ds_lock);
3058 	VERIFY0(zap_add(dp->dp_meta_objset,
3059 	    dsl_dataset_phys(hds)->ds_snapnames_zapobj,
3060 	    ds->ds_snapname, 8, 1, &ds->ds_object, tx));
3061 
3062 	oldname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3063 	    ddrsa->ddrsa_oldsnapname);
3064 	newname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3065 	    ddrsa->ddrsa_newsnapname);
3066 	zvol_rename_minors(dp->dp_spa, oldname, newname, B_TRUE);
3067 	kmem_strfree(oldname);
3068 	kmem_strfree(newname);
3069 
3070 	dsl_dataset_rele(ds, FTAG);
3071 	return (0);
3072 }
3073 
3074 void
dsl_dataset_rename_snapshot_sync(void * arg,dmu_tx_t * tx)3075 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
3076 {
3077 	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3078 	dsl_pool_t *dp = dmu_tx_pool(tx);
3079 	dsl_dataset_t *hds = NULL;
3080 
3081 	VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
3082 	ddrsa->ddrsa_tx = tx;
3083 	if (ddrsa->ddrsa_recursive) {
3084 		VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3085 		    dsl_dataset_rename_snapshot_sync_impl, ddrsa,
3086 		    DS_FIND_CHILDREN));
3087 	} else {
3088 		VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
3089 	}
3090 	dsl_dataset_rele(hds, FTAG);
3091 }
3092 
3093 int
dsl_dataset_rename_snapshot(const char * fsname,const char * oldsnapname,const char * newsnapname,boolean_t recursive)3094 dsl_dataset_rename_snapshot(const char *fsname,
3095     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
3096 {
3097 	dsl_dataset_rename_snapshot_arg_t ddrsa;
3098 
3099 	ddrsa.ddrsa_fsname = fsname;
3100 	ddrsa.ddrsa_oldsnapname = oldsnapname;
3101 	ddrsa.ddrsa_newsnapname = newsnapname;
3102 	ddrsa.ddrsa_recursive = recursive;
3103 
3104 	return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
3105 	    dsl_dataset_rename_snapshot_sync, &ddrsa,
3106 	    1, ZFS_SPACE_CHECK_RESERVED));
3107 }
3108 
3109 /*
3110  * If we're doing an ownership handoff, we need to make sure that there is
3111  * only one long hold on the dataset.  We're not allowed to change anything here
3112  * so we don't permanently release the long hold or regular hold here.  We want
3113  * to do this only when syncing to avoid the dataset unexpectedly going away
3114  * when we release the long hold.
3115  */
3116 static int
dsl_dataset_handoff_check(dsl_dataset_t * ds,void * owner,dmu_tx_t * tx)3117 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
3118 {
3119 	boolean_t held = B_FALSE;
3120 
3121 	if (!dmu_tx_is_syncing(tx))
3122 		return (0);
3123 
3124 	dsl_dir_t *dd = ds->ds_dir;
3125 	mutex_enter(&dd->dd_activity_lock);
3126 	uint64_t holds = zfs_refcount_count(&ds->ds_longholds) -
3127 	    (owner != NULL ? 1 : 0);
3128 	/*
3129 	 * The value of dd_activity_waiters can chance as soon as we drop the
3130 	 * lock, but we're fine with that; new waiters coming in or old
3131 	 * waiters leaving doesn't cause problems, since we're going to cancel
3132 	 * waiters later anyway. The goal of this check is to verify that no
3133 	 * non-waiters have long-holds, and all new long-holds will be
3134 	 * prevented because we're holding the pool config as writer.
3135 	 */
3136 	if (holds != dd->dd_activity_waiters)
3137 		held = B_TRUE;
3138 	mutex_exit(&dd->dd_activity_lock);
3139 
3140 	if (held)
3141 		return (SET_ERROR(EBUSY));
3142 
3143 	return (0);
3144 }
3145 
3146 int
dsl_dataset_rollback_check(void * arg,dmu_tx_t * tx)3147 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
3148 {
3149 	dsl_dataset_rollback_arg_t *ddra = arg;
3150 	dsl_pool_t *dp = dmu_tx_pool(tx);
3151 	dsl_dataset_t *ds;
3152 	int64_t unused_refres_delta;
3153 	int error;
3154 
3155 	error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
3156 	if (error != 0)
3157 		return (error);
3158 
3159 	/* must not be a snapshot */
3160 	if (ds->ds_is_snapshot) {
3161 		dsl_dataset_rele(ds, FTAG);
3162 		return (SET_ERROR(EINVAL));
3163 	}
3164 
3165 	/* must have a most recent snapshot */
3166 	if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
3167 		dsl_dataset_rele(ds, FTAG);
3168 		return (SET_ERROR(ESRCH));
3169 	}
3170 
3171 	/*
3172 	 * No rollback to a snapshot created in the current txg, because
3173 	 * the rollback may dirty the dataset and create blocks that are
3174 	 * not reachable from the rootbp while having a birth txg that
3175 	 * falls into the snapshot's range.
3176 	 */
3177 	if (dmu_tx_is_syncing(tx) &&
3178 	    dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg) {
3179 		dsl_dataset_rele(ds, FTAG);
3180 		return (SET_ERROR(EAGAIN));
3181 	}
3182 
3183 	/*
3184 	 * If the expected target snapshot is specified, then check that
3185 	 * the latest snapshot is it.
3186 	 */
3187 	if (ddra->ddra_tosnap != NULL) {
3188 		dsl_dataset_t *snapds;
3189 
3190 		/* Check if the target snapshot exists at all. */
3191 		error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
3192 		if (error != 0) {
3193 			/*
3194 			 * ESRCH is used to signal that the target snapshot does
3195 			 * not exist, while ENOENT is used to report that
3196 			 * the rolled back dataset does not exist.
3197 			 * ESRCH is also used to cover other cases where the
3198 			 * target snapshot is not related to the dataset being
3199 			 * rolled back such as being in a different pool.
3200 			 */
3201 			if (error == ENOENT || error == EXDEV)
3202 				error = SET_ERROR(ESRCH);
3203 			dsl_dataset_rele(ds, FTAG);
3204 			return (error);
3205 		}
3206 		ASSERT(snapds->ds_is_snapshot);
3207 
3208 		/* Check if the snapshot is the latest snapshot indeed. */
3209 		if (snapds != ds->ds_prev) {
3210 			/*
3211 			 * Distinguish between the case where the only problem
3212 			 * is intervening snapshots (EEXIST) vs the snapshot
3213 			 * not being a valid target for rollback (ESRCH).
3214 			 */
3215 			if (snapds->ds_dir == ds->ds_dir ||
3216 			    (dsl_dir_is_clone(ds->ds_dir) &&
3217 			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
3218 			    snapds->ds_object)) {
3219 				error = SET_ERROR(EEXIST);
3220 			} else {
3221 				error = SET_ERROR(ESRCH);
3222 			}
3223 			dsl_dataset_rele(snapds, FTAG);
3224 			dsl_dataset_rele(ds, FTAG);
3225 			return (error);
3226 		}
3227 		dsl_dataset_rele(snapds, FTAG);
3228 	}
3229 
3230 	/* must not have any bookmarks after the most recent snapshot */
3231 	if (dsl_bookmark_latest_txg(ds) >
3232 	    dsl_dataset_phys(ds)->ds_prev_snap_txg) {
3233 		dsl_dataset_rele(ds, FTAG);
3234 		return (SET_ERROR(EEXIST));
3235 	}
3236 
3237 	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
3238 	if (error != 0) {
3239 		dsl_dataset_rele(ds, FTAG);
3240 		return (error);
3241 	}
3242 
3243 	/*
3244 	 * Check if the snap we are rolling back to uses more than
3245 	 * the refquota.
3246 	 */
3247 	if (ds->ds_quota != 0 &&
3248 	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
3249 		dsl_dataset_rele(ds, FTAG);
3250 		return (SET_ERROR(EDQUOT));
3251 	}
3252 
3253 	/*
3254 	 * When we do the clone swap, we will temporarily use more space
3255 	 * due to the refreservation (the head will no longer have any
3256 	 * unique space, so the entire amount of the refreservation will need
3257 	 * to be free).  We will immediately destroy the clone, freeing
3258 	 * this space, but the freeing happens over many txg's.
3259 	 */
3260 	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
3261 	    dsl_dataset_phys(ds)->ds_unique_bytes);
3262 
3263 	if (unused_refres_delta > 0 &&
3264 	    unused_refres_delta >
3265 	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
3266 		dsl_dataset_rele(ds, FTAG);
3267 		return (SET_ERROR(ENOSPC));
3268 	}
3269 
3270 	dsl_dataset_rele(ds, FTAG);
3271 	return (0);
3272 }
3273 
3274 void
dsl_dataset_rollback_sync(void * arg,dmu_tx_t * tx)3275 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
3276 {
3277 	dsl_dataset_rollback_arg_t *ddra = arg;
3278 	dsl_pool_t *dp = dmu_tx_pool(tx);
3279 	dsl_dataset_t *ds, *clone;
3280 	uint64_t cloneobj;
3281 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3282 
3283 	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
3284 
3285 	dsl_dataset_name(ds->ds_prev, namebuf);
3286 	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
3287 
3288 	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
3289 	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, NULL, tx);
3290 
3291 	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
3292 
3293 	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
3294 	dsl_dataset_zero_zil(ds, tx);
3295 
3296 	dsl_destroy_head_sync_impl(clone, tx);
3297 
3298 	dsl_dataset_rele(clone, FTAG);
3299 	dsl_dataset_rele(ds, FTAG);
3300 }
3301 
3302 /*
3303  * Rolls back the given filesystem or volume to the most recent snapshot.
3304  * The name of the most recent snapshot will be returned under key "target"
3305  * in the result nvlist.
3306  *
3307  * If owner != NULL:
3308  * - The existing dataset MUST be owned by the specified owner at entry
3309  * - Upon return, dataset will still be held by the same owner, whether we
3310  *   succeed or not.
3311  *
3312  * This mode is required any time the existing filesystem is mounted.  See
3313  * notes above zfs_suspend_fs() for further details.
3314  */
3315 int
dsl_dataset_rollback(const char * fsname,const char * tosnap,void * owner,nvlist_t * result)3316 dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
3317     nvlist_t *result)
3318 {
3319 	dsl_dataset_rollback_arg_t ddra;
3320 
3321 	ddra.ddra_fsname = fsname;
3322 	ddra.ddra_tosnap = tosnap;
3323 	ddra.ddra_owner = owner;
3324 	ddra.ddra_result = result;
3325 
3326 	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
3327 	    dsl_dataset_rollback_sync, &ddra,
3328 	    1, ZFS_SPACE_CHECK_RESERVED));
3329 }
3330 
3331 int
dsl_dataset_clone_check(void * arg,dmu_tx_t * tx)3332 dsl_dataset_clone_check(void *arg, dmu_tx_t *tx)
3333 {
3334 	dsl_dataset_clone_arg_t *ddca = arg;
3335 	dsl_dir_t *pdd;
3336 	const char *tail;
3337 	int error;
3338 	dsl_dataset_t *origin;
3339 	dsl_pool_t *dp = dmu_tx_pool(tx);
3340 
3341 	if (strchr(ddca->ddca_clone, '@') != NULL)
3342 		return (SET_ERROR(EINVAL));
3343 
3344 	if (strlen(ddca->ddca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
3345 		return (SET_ERROR(ENAMETOOLONG));
3346 
3347 	error = dsl_dir_hold(dp, ddca->ddca_clone, FTAG, &pdd, &tail);
3348 	if (error != 0)
3349 		return (error);
3350 	if (tail == NULL) {
3351 		dsl_dir_rele(pdd, FTAG);
3352 		return (SET_ERROR(EEXIST));
3353 	}
3354 
3355 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
3356 	    ddca->ddca_cred);
3357 	if (error != 0) {
3358 		dsl_dir_rele(pdd, FTAG);
3359 		return (SET_ERROR(EDQUOT));
3360 	}
3361 
3362 	error = dsl_dataset_hold(dp, ddca->ddca_origin, FTAG, &origin);
3363 	if (error != 0) {
3364 		dsl_dir_rele(pdd, FTAG);
3365 		return (error);
3366 	}
3367 
3368 	/* You can only clone snapshots, not the head datasets. */
3369 	if (!origin->ds_is_snapshot) {
3370 		dsl_dataset_rele(origin, FTAG);
3371 		dsl_dir_rele(pdd, FTAG);
3372 		return (SET_ERROR(EINVAL));
3373 	}
3374 
3375 	dsl_dataset_rele(origin, FTAG);
3376 	dsl_dir_rele(pdd, FTAG);
3377 
3378 	return (0);
3379 }
3380 
3381 void
dsl_dataset_clone_sync(void * arg,dmu_tx_t * tx)3382 dsl_dataset_clone_sync(void *arg, dmu_tx_t *tx)
3383 {
3384 	dsl_dataset_clone_arg_t *ddca = arg;
3385 	dsl_pool_t *dp = dmu_tx_pool(tx);
3386 	dsl_dir_t *pdd;
3387 	const char *tail;
3388 	dsl_dataset_t *origin, *ds;
3389 	uint64_t obj;
3390 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3391 
3392 	VERIFY0(dsl_dir_hold(dp, ddca->ddca_clone, FTAG, &pdd, &tail));
3393 	VERIFY0(dsl_dataset_hold(dp, ddca->ddca_origin, FTAG, &origin));
3394 
3395 	obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
3396 	    ddca->ddca_cred, NULL, tx);
3397 
3398 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
3399 	dsl_dataset_name(origin, namebuf);
3400 	spa_history_log_internal_ds(ds, "clone", tx,
3401 	    "origin=%s (%llu)", namebuf, (u_longlong_t)origin->ds_object);
3402 	dsl_dataset_rele(ds, FTAG);
3403 	dsl_dataset_rele(origin, FTAG);
3404 	dsl_dir_rele(pdd, FTAG);
3405 }
3406 
3407 int
dsl_dataset_clone(const char * clone,const char * origin)3408 dsl_dataset_clone(const char *clone, const char *origin)
3409 {
3410 	dsl_dataset_clone_arg_t ddca;
3411 
3412 	cred_t *cr = CRED();
3413 	crhold(cr);
3414 
3415 	ddca.ddca_clone = clone;
3416 	ddca.ddca_origin = origin;
3417 	ddca.ddca_cred = cr;
3418 
3419 	int rv = dsl_sync_task(clone,
3420 	    dsl_dataset_clone_check, dsl_dataset_clone_sync, &ddca,
3421 	    6, ZFS_SPACE_CHECK_NORMAL);
3422 
3423 	if (rv == 0)
3424 		zvol_create_minors(clone);
3425 
3426 	crfree(cr);
3427 
3428 	return (rv);
3429 }
3430 
3431 struct promotenode {
3432 	list_node_t link;
3433 	dsl_dataset_t *ds;
3434 };
3435 
3436 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
3437 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
3438     const void *tag);
3439 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag);
3440 
3441 int
dsl_dataset_promote_check(void * arg,dmu_tx_t * tx)3442 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
3443 {
3444 	dsl_dataset_promote_arg_t *ddpa = arg;
3445 	dsl_pool_t *dp = dmu_tx_pool(tx);
3446 	dsl_dataset_t *hds;
3447 	struct promotenode *snap;
3448 	int err;
3449 	uint64_t unused;
3450 	uint64_t ss_mv_cnt;
3451 	size_t max_snap_len;
3452 	boolean_t conflicting_snaps;
3453 
3454 	err = promote_hold(ddpa, dp, FTAG);
3455 	if (err != 0)
3456 		return (err);
3457 
3458 	hds = ddpa->ddpa_clone;
3459 	max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
3460 
3461 	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
3462 		promote_rele(ddpa, FTAG);
3463 		return (SET_ERROR(EXDEV));
3464 	}
3465 
3466 	snap = list_head(&ddpa->shared_snaps);
3467 	if (snap == NULL) {
3468 		err = SET_ERROR(ENOENT);
3469 		goto out;
3470 	}
3471 	dsl_dataset_t *const origin_ds = snap->ds;
3472 
3473 	/*
3474 	 * Encrypted clones share a DSL Crypto Key with their origin's dsl dir.
3475 	 * When doing a promote we must make sure the encryption root for
3476 	 * both the target and the target's origin does not change to avoid
3477 	 * needing to rewrap encryption keys
3478 	 */
3479 	err = dsl_dataset_promote_crypt_check(hds->ds_dir, origin_ds->ds_dir);
3480 	if (err != 0)
3481 		goto out;
3482 
3483 	/*
3484 	 * Compute and check the amount of space to transfer.  Since this is
3485 	 * so expensive, don't do the preliminary check.
3486 	 */
3487 	if (!dmu_tx_is_syncing(tx)) {
3488 		promote_rele(ddpa, FTAG);
3489 		return (0);
3490 	}
3491 
3492 	/* compute origin's new unique space */
3493 	snap = list_tail(&ddpa->clone_snaps);
3494 	ASSERT(snap != NULL);
3495 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3496 	    origin_ds->ds_object);
3497 	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3498 	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
3499 	    &ddpa->unique, &unused, &unused);
3500 
3501 	/*
3502 	 * Walk the snapshots that we are moving
3503 	 *
3504 	 * Compute space to transfer.  Consider the incremental changes
3505 	 * to used by each snapshot:
3506 	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
3507 	 * So each snapshot gave birth to:
3508 	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
3509 	 * So a sequence would look like:
3510 	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
3511 	 * Which simplifies to:
3512 	 * uN + kN + kN-1 + ... + k1 + k0
3513 	 * Note however, if we stop before we reach the ORIGIN we get:
3514 	 * uN + kN + kN-1 + ... + kM - uM-1
3515 	 */
3516 	conflicting_snaps = B_FALSE;
3517 	ss_mv_cnt = 0;
3518 	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
3519 	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
3520 	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
3521 	for (snap = list_head(&ddpa->shared_snaps); snap;
3522 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3523 		uint64_t val, dlused, dlcomp, dluncomp;
3524 		dsl_dataset_t *ds = snap->ds;
3525 
3526 		ss_mv_cnt++;
3527 
3528 		/*
3529 		 * If there are long holds, we won't be able to evict
3530 		 * the objset.
3531 		 */
3532 		if (dsl_dataset_long_held(ds)) {
3533 			err = SET_ERROR(EBUSY);
3534 			goto out;
3535 		}
3536 
3537 		/* Check that the snapshot name does not conflict */
3538 		VERIFY0(dsl_dataset_get_snapname(ds));
3539 		if (strlen(ds->ds_snapname) >= max_snap_len) {
3540 			err = SET_ERROR(ENAMETOOLONG);
3541 			goto out;
3542 		}
3543 		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
3544 		if (err == 0) {
3545 			fnvlist_add_boolean(ddpa->err_ds,
3546 			    snap->ds->ds_snapname);
3547 			conflicting_snaps = B_TRUE;
3548 		} else if (err != ENOENT) {
3549 			goto out;
3550 		}
3551 
3552 		/* The very first snapshot does not have a deadlist */
3553 		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
3554 			continue;
3555 
3556 		dsl_deadlist_space(&ds->ds_deadlist,
3557 		    &dlused, &dlcomp, &dluncomp);
3558 		ddpa->used += dlused;
3559 		ddpa->comp += dlcomp;
3560 		ddpa->uncomp += dluncomp;
3561 	}
3562 
3563 	/*
3564 	 * Check that bookmarks that are being transferred don't have
3565 	 * name conflicts.
3566 	 */
3567 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_ds->ds_bookmarks);
3568 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3569 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3570 	    dbn = AVL_NEXT(&origin_ds->ds_bookmarks, dbn)) {
3571 		if (strlen(dbn->dbn_name) >= max_snap_len) {
3572 			err = SET_ERROR(ENAMETOOLONG);
3573 			goto out;
3574 		}
3575 		zfs_bookmark_phys_t bm;
3576 		err = dsl_bookmark_lookup_impl(ddpa->ddpa_clone,
3577 		    dbn->dbn_name, &bm);
3578 
3579 		if (err == 0) {
3580 			fnvlist_add_boolean(ddpa->err_ds, dbn->dbn_name);
3581 			conflicting_snaps = B_TRUE;
3582 		} else if (err == ESRCH) {
3583 			err = 0;
3584 		}
3585 		if (err != 0) {
3586 			goto out;
3587 		}
3588 	}
3589 
3590 	/*
3591 	 * In order to return the full list of conflicting snapshots, we check
3592 	 * whether there was a conflict after traversing all of them.
3593 	 */
3594 	if (conflicting_snaps) {
3595 		err = SET_ERROR(EEXIST);
3596 		goto out;
3597 	}
3598 
3599 	/*
3600 	 * If we are a clone of a clone then we never reached ORIGIN,
3601 	 * so we need to subtract out the clone origin's used space.
3602 	 */
3603 	if (ddpa->origin_origin) {
3604 		ddpa->used -=
3605 		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
3606 		ddpa->comp -=
3607 		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
3608 		ddpa->uncomp -=
3609 		    dsl_dataset_phys(ddpa->origin_origin)->
3610 		    ds_uncompressed_bytes;
3611 	}
3612 
3613 	/* Check that there is enough space and limit headroom here */
3614 	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
3615 	    0, ss_mv_cnt, ddpa->used, ddpa->cr);
3616 	if (err != 0)
3617 		goto out;
3618 
3619 	/*
3620 	 * Compute the amounts of space that will be used by snapshots
3621 	 * after the promotion (for both origin and clone).  For each,
3622 	 * it is the amount of space that will be on all of their
3623 	 * deadlists (that was not born before their new origin).
3624 	 */
3625 	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
3626 		uint64_t space;
3627 
3628 		/*
3629 		 * Note, typically this will not be a clone of a clone,
3630 		 * so dd_origin_txg will be < TXG_INITIAL, so
3631 		 * these snaplist_space() -> dsl_deadlist_space_range()
3632 		 * calls will be fast because they do not have to
3633 		 * iterate over all bps.
3634 		 */
3635 		snap = list_head(&ddpa->origin_snaps);
3636 		if (snap == NULL) {
3637 			err = SET_ERROR(ENOENT);
3638 			goto out;
3639 		}
3640 		err = snaplist_space(&ddpa->shared_snaps,
3641 		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
3642 		if (err != 0)
3643 			goto out;
3644 
3645 		err = snaplist_space(&ddpa->clone_snaps,
3646 		    snap->ds->ds_dir->dd_origin_txg, &space);
3647 		if (err != 0)
3648 			goto out;
3649 		ddpa->cloneusedsnap += space;
3650 	}
3651 	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
3652 	    DD_FLAG_USED_BREAKDOWN) {
3653 		err = snaplist_space(&ddpa->origin_snaps,
3654 		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
3655 		    &ddpa->originusedsnap);
3656 		if (err != 0)
3657 			goto out;
3658 	}
3659 
3660 out:
3661 	promote_rele(ddpa, FTAG);
3662 	return (err);
3663 }
3664 
3665 void
dsl_dataset_promote_sync(void * arg,dmu_tx_t * tx)3666 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
3667 {
3668 	dsl_dataset_promote_arg_t *ddpa = arg;
3669 	dsl_pool_t *dp = dmu_tx_pool(tx);
3670 	dsl_dataset_t *hds;
3671 	struct promotenode *snap;
3672 	dsl_dataset_t *origin_ds;
3673 	dsl_dataset_t *origin_head;
3674 	dsl_dir_t *dd;
3675 	dsl_dir_t *odd = NULL;
3676 	uint64_t oldnext_obj;
3677 	int64_t delta;
3678 
3679 	ASSERT(nvlist_empty(ddpa->err_ds));
3680 
3681 	VERIFY0(promote_hold(ddpa, dp, FTAG));
3682 	hds = ddpa->ddpa_clone;
3683 
3684 	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
3685 
3686 	snap = list_head(&ddpa->shared_snaps);
3687 	origin_ds = snap->ds;
3688 	dd = hds->ds_dir;
3689 
3690 	snap = list_head(&ddpa->origin_snaps);
3691 	origin_head = snap->ds;
3692 
3693 	/*
3694 	 * We need to explicitly open odd, since origin_ds's dd will be
3695 	 * changing.
3696 	 */
3697 	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
3698 	    NULL, FTAG, &odd));
3699 
3700 	dsl_dataset_promote_crypt_sync(hds->ds_dir, odd, tx);
3701 
3702 	/* change origin's next snap */
3703 	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
3704 	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
3705 	snap = list_tail(&ddpa->clone_snaps);
3706 	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3707 	    origin_ds->ds_object);
3708 	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
3709 
3710 	/* change the origin's next clone */
3711 	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
3712 		dsl_dataset_remove_from_next_clones(origin_ds,
3713 		    snap->ds->ds_object, tx);
3714 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3715 		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
3716 		    oldnext_obj, tx));
3717 	}
3718 
3719 	/* change origin */
3720 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
3721 	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
3722 	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
3723 	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
3724 	dmu_buf_will_dirty(odd->dd_dbuf, tx);
3725 	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
3726 	origin_head->ds_dir->dd_origin_txg =
3727 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3728 
3729 	/* change dd_clone entries */
3730 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3731 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3732 		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
3733 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3734 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3735 		    hds->ds_object, tx));
3736 
3737 		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3738 		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3739 		    origin_head->ds_object, tx));
3740 		if (dsl_dir_phys(dd)->dd_clones == 0) {
3741 			dsl_dir_phys(dd)->dd_clones =
3742 			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
3743 			    DMU_OT_NONE, 0, tx);
3744 		}
3745 		VERIFY0(zap_add_int(dp->dp_meta_objset,
3746 		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
3747 	}
3748 
3749 	/*
3750 	 * Move bookmarks to this dir.
3751 	 */
3752 	dsl_bookmark_node_t *dbn_next;
3753 	for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3754 	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3755 	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3756 	    dbn = dbn_next) {
3757 		dbn_next = AVL_NEXT(&origin_head->ds_bookmarks, dbn);
3758 
3759 		avl_remove(&origin_head->ds_bookmarks, dbn);
3760 		VERIFY0(zap_remove(dp->dp_meta_objset,
3761 		    origin_head->ds_bookmarks_obj, dbn->dbn_name, tx));
3762 
3763 		dsl_bookmark_node_add(hds, dbn, tx);
3764 	}
3765 
3766 	dsl_bookmark_next_changed(hds, origin_ds, tx);
3767 
3768 	/* move snapshots to this dir */
3769 	for (snap = list_head(&ddpa->shared_snaps); snap;
3770 	    snap = list_next(&ddpa->shared_snaps, snap)) {
3771 		dsl_dataset_t *ds = snap->ds;
3772 
3773 		/*
3774 		 * Property callbacks are registered to a particular
3775 		 * dsl_dir.  Since ours is changing, evict the objset
3776 		 * so that they will be unregistered from the old dsl_dir.
3777 		 */
3778 		if (ds->ds_objset) {
3779 			dmu_objset_evict(ds->ds_objset);
3780 			ds->ds_objset = NULL;
3781 		}
3782 
3783 		/* move snap name entry */
3784 		VERIFY0(dsl_dataset_get_snapname(ds));
3785 		VERIFY0(dsl_dataset_snap_remove(origin_head,
3786 		    ds->ds_snapname, tx, B_TRUE));
3787 		VERIFY0(zap_add(dp->dp_meta_objset,
3788 		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3789 		    8, 1, &ds->ds_object, tx));
3790 		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3791 		    DD_FIELD_SNAPSHOT_COUNT, tx);
3792 
3793 		/* change containing dsl_dir */
3794 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3795 		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3796 		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3797 		ASSERT3P(ds->ds_dir, ==, odd);
3798 		dsl_dir_rele(ds->ds_dir, ds);
3799 		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3800 		    NULL, ds, &ds->ds_dir));
3801 
3802 		/* move any clone references */
3803 		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3804 		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3805 			zap_cursor_t zc;
3806 			zap_attribute_t *za = zap_attribute_alloc();
3807 
3808 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3809 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3810 			    zap_cursor_retrieve(&zc, za) == 0;
3811 			    zap_cursor_advance(&zc)) {
3812 				dsl_dataset_t *cnds;
3813 				uint64_t o;
3814 
3815 				if (za->za_first_integer == oldnext_obj) {
3816 					/*
3817 					 * We've already moved the
3818 					 * origin's reference.
3819 					 */
3820 					continue;
3821 				}
3822 
3823 				VERIFY0(dsl_dataset_hold_obj(dp,
3824 				    za->za_first_integer, FTAG, &cnds));
3825 				o = dsl_dir_phys(cnds->ds_dir)->
3826 				    dd_head_dataset_obj;
3827 
3828 				VERIFY0(zap_remove_int(dp->dp_meta_objset,
3829 				    dsl_dir_phys(odd)->dd_clones, o, tx));
3830 				VERIFY0(zap_add_int(dp->dp_meta_objset,
3831 				    dsl_dir_phys(dd)->dd_clones, o, tx));
3832 				dsl_dataset_rele(cnds, FTAG);
3833 			}
3834 			zap_cursor_fini(&zc);
3835 			zap_attribute_free(za);
3836 		}
3837 
3838 		ASSERT(!dsl_prop_hascb(ds));
3839 	}
3840 
3841 	/*
3842 	 * Change space accounting.
3843 	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3844 	 * both be valid, or both be 0 (resulting in delta == 0).  This
3845 	 * is true for each of {clone,origin} independently.
3846 	 */
3847 
3848 	delta = ddpa->cloneusedsnap -
3849 	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3850 	ASSERT3S(delta, >=, 0);
3851 	ASSERT3U(ddpa->used, >=, delta);
3852 	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3853 	dsl_dir_diduse_space(dd, DD_USED_HEAD,
3854 	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3855 
3856 	delta = ddpa->originusedsnap -
3857 	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3858 	ASSERT3S(delta, <=, 0);
3859 	ASSERT3U(ddpa->used, >=, -delta);
3860 	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3861 	dsl_dir_diduse_space(odd, DD_USED_HEAD,
3862 	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3863 
3864 	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3865 
3866 	/*
3867 	 * Since livelists are specific to a clone's origin txg, they
3868 	 * are no longer accurate. Destroy the livelist from the clone being
3869 	 * promoted. If the origin dataset is a clone, destroy its livelist
3870 	 * as well.
3871 	 */
3872 	dsl_dir_remove_livelist(dd, tx, B_TRUE);
3873 	dsl_dir_remove_livelist(odd, tx, B_TRUE);
3874 
3875 	/* log history record */
3876 	spa_history_log_internal_ds(hds, "promote", tx, " ");
3877 
3878 	dsl_dir_rele(odd, FTAG);
3879 
3880 	/*
3881 	 * Transfer common error blocks from old head to new head, before
3882 	 * calling promote_rele() on ddpa since we need to dereference
3883 	 * origin_head and hds.
3884 	 */
3885 	if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_HEAD_ERRLOG)) {
3886 		uint64_t old_head = origin_head->ds_object;
3887 		uint64_t new_head = hds->ds_object;
3888 		spa_swap_errlog(dp->dp_spa, new_head, old_head, tx);
3889 	}
3890 
3891 	promote_rele(ddpa, FTAG);
3892 }
3893 
3894 /*
3895  * Make a list of dsl_dataset_t's for the snapshots between first_obj
3896  * (exclusive) and last_obj (inclusive).  The list will be in reverse
3897  * order (last_obj will be the list_head()).  If first_obj == 0, do all
3898  * snapshots back to this dataset's origin.
3899  */
3900 static int
snaplist_make(dsl_pool_t * dp,uint64_t first_obj,uint64_t last_obj,list_t * l,const void * tag)3901 snaplist_make(dsl_pool_t *dp,
3902     uint64_t first_obj, uint64_t last_obj, list_t *l, const void *tag)
3903 {
3904 	uint64_t obj = last_obj;
3905 
3906 	list_create(l, sizeof (struct promotenode),
3907 	    offsetof(struct promotenode, link));
3908 
3909 	while (obj != first_obj) {
3910 		dsl_dataset_t *ds;
3911 		struct promotenode *snap;
3912 		int err;
3913 
3914 		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3915 		ASSERT(err != ENOENT);
3916 		if (err != 0)
3917 			return (err);
3918 
3919 		if (first_obj == 0)
3920 			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3921 
3922 		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3923 		snap->ds = ds;
3924 		list_insert_tail(l, snap);
3925 		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3926 	}
3927 
3928 	return (0);
3929 }
3930 
3931 static int
snaplist_space(list_t * l,uint64_t mintxg,uint64_t * spacep)3932 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3933 {
3934 	struct promotenode *snap;
3935 
3936 	*spacep = 0;
3937 	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3938 		uint64_t used, comp, uncomp;
3939 		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3940 		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
3941 		*spacep += used;
3942 	}
3943 	return (0);
3944 }
3945 
3946 static void
snaplist_destroy(list_t * l,const void * tag)3947 snaplist_destroy(list_t *l, const void *tag)
3948 {
3949 	struct promotenode *snap;
3950 
3951 	if (l == NULL || !list_link_active(&l->list_head))
3952 		return;
3953 
3954 	while ((snap = list_remove_tail(l)) != NULL) {
3955 		dsl_dataset_rele(snap->ds, tag);
3956 		kmem_free(snap, sizeof (*snap));
3957 	}
3958 	list_destroy(l);
3959 }
3960 
3961 static int
promote_hold(dsl_dataset_promote_arg_t * ddpa,dsl_pool_t * dp,const void * tag)3962 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, const void *tag)
3963 {
3964 	int error;
3965 	dsl_dir_t *dd;
3966 	struct promotenode *snap;
3967 
3968 	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3969 	    &ddpa->ddpa_clone);
3970 	if (error != 0)
3971 		return (error);
3972 	dd = ddpa->ddpa_clone->ds_dir;
3973 
3974 	if (ddpa->ddpa_clone->ds_is_snapshot ||
3975 	    !dsl_dir_is_clone(dd)) {
3976 		dsl_dataset_rele(ddpa->ddpa_clone, tag);
3977 		return (SET_ERROR(EINVAL));
3978 	}
3979 
3980 	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3981 	    &ddpa->shared_snaps, tag);
3982 	if (error != 0)
3983 		goto out;
3984 
3985 	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3986 	    &ddpa->clone_snaps, tag);
3987 	if (error != 0)
3988 		goto out;
3989 
3990 	snap = list_head(&ddpa->shared_snaps);
3991 	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3992 	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3993 	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3994 	    &ddpa->origin_snaps, tag);
3995 	if (error != 0)
3996 		goto out;
3997 
3998 	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3999 		error = dsl_dataset_hold_obj(dp,
4000 		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
4001 		    tag, &ddpa->origin_origin);
4002 		if (error != 0)
4003 			goto out;
4004 	}
4005 out:
4006 	if (error != 0)
4007 		promote_rele(ddpa, tag);
4008 	return (error);
4009 }
4010 
4011 static void
promote_rele(dsl_dataset_promote_arg_t * ddpa,const void * tag)4012 promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag)
4013 {
4014 	snaplist_destroy(&ddpa->shared_snaps, tag);
4015 	snaplist_destroy(&ddpa->clone_snaps, tag);
4016 	snaplist_destroy(&ddpa->origin_snaps, tag);
4017 	if (ddpa->origin_origin != NULL)
4018 		dsl_dataset_rele(ddpa->origin_origin, tag);
4019 	dsl_dataset_rele(ddpa->ddpa_clone, tag);
4020 }
4021 
4022 /*
4023  * Promote a clone.
4024  *
4025  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
4026  * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
4027  */
4028 int
dsl_dataset_promote(const char * name,char * conflsnap)4029 dsl_dataset_promote(const char *name, char *conflsnap)
4030 {
4031 	dsl_dataset_promote_arg_t ddpa = { 0 };
4032 	uint64_t numsnaps;
4033 	int error;
4034 	nvpair_t *snap_pair;
4035 	objset_t *os;
4036 
4037 	/*
4038 	 * We will modify space proportional to the number of
4039 	 * snapshots.  Compute numsnaps.
4040 	 */
4041 	error = dmu_objset_hold(name, FTAG, &os);
4042 	if (error != 0)
4043 		return (error);
4044 	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
4045 	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
4046 	    &numsnaps);
4047 	dmu_objset_rele(os, FTAG);
4048 	if (error != 0)
4049 		return (error);
4050 
4051 	cred_t *cr = CRED();
4052 	crhold(cr);
4053 
4054 	ddpa.ddpa_clonename = name;
4055 	ddpa.err_ds = fnvlist_alloc();
4056 	ddpa.cr = cr;
4057 
4058 	error = dsl_sync_task(name, dsl_dataset_promote_check,
4059 	    dsl_dataset_promote_sync, &ddpa,
4060 	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
4061 
4062 	crfree(cr);
4063 
4064 	/*
4065 	 * Return the first conflicting snapshot found.
4066 	 */
4067 	snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
4068 	if (snap_pair != NULL && conflsnap != NULL)
4069 		(void) strlcpy(conflsnap, nvpair_name(snap_pair),
4070 		    ZFS_MAX_DATASET_NAME_LEN);
4071 
4072 	fnvlist_free(ddpa.err_ds);
4073 	return (error);
4074 }
4075 
4076 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)4077 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
4078     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
4079 {
4080 	/*
4081 	 * "slack" factor for received datasets with refquota set on them.
4082 	 * See the bottom of this function for details on its use.
4083 	 */
4084 	uint64_t refquota_slack = (uint64_t)DMU_MAX_ACCESS *
4085 	    spa_asize_inflation;
4086 	int64_t unused_refres_delta;
4087 
4088 	/* they should both be heads */
4089 	if (clone->ds_is_snapshot ||
4090 	    origin_head->ds_is_snapshot)
4091 		return (SET_ERROR(EINVAL));
4092 
4093 	/* if we are not forcing, the branch point should be just before them */
4094 	if (!force && clone->ds_prev != origin_head->ds_prev)
4095 		return (SET_ERROR(EINVAL));
4096 
4097 	/* clone should be the clone (unless they are unrelated) */
4098 	if (clone->ds_prev != NULL &&
4099 	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
4100 	    origin_head->ds_dir != clone->ds_prev->ds_dir)
4101 		return (SET_ERROR(EINVAL));
4102 
4103 	/* the clone should be a child of the origin */
4104 	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
4105 		return (SET_ERROR(EINVAL));
4106 
4107 	/* origin_head shouldn't be modified unless 'force' */
4108 	if (!force &&
4109 	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
4110 		return (SET_ERROR(ETXTBSY));
4111 
4112 	/* origin_head should have no long holds (e.g. is not mounted) */
4113 	if (dsl_dataset_handoff_check(origin_head, owner, tx))
4114 		return (SET_ERROR(EBUSY));
4115 
4116 	/* check amount of any unconsumed refreservation */
4117 	unused_refres_delta =
4118 	    (int64_t)MIN(origin_head->ds_reserved,
4119 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4120 	    (int64_t)MIN(origin_head->ds_reserved,
4121 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4122 
4123 	if (unused_refres_delta > 0 &&
4124 	    unused_refres_delta >
4125 	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
4126 		return (SET_ERROR(ENOSPC));
4127 
4128 	/*
4129 	 * The clone can't be too much over the head's refquota.
4130 	 *
4131 	 * To ensure that the entire refquota can be used, we allow one
4132 	 * transaction to exceed the refquota.  Therefore, this check
4133 	 * needs to also allow for the space referenced to be more than the
4134 	 * refquota.  The maximum amount of space that one transaction can use
4135 	 * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
4136 	 * overage ensures that we are able to receive a filesystem that
4137 	 * exceeds the refquota on the source system.
4138 	 *
4139 	 * So that overage is the refquota_slack we use below.
4140 	 */
4141 	if (origin_head->ds_quota != 0 &&
4142 	    dsl_dataset_phys(clone)->ds_referenced_bytes >
4143 	    origin_head->ds_quota + refquota_slack)
4144 		return (SET_ERROR(EDQUOT));
4145 
4146 	return (0);
4147 }
4148 
4149 static void
dsl_dataset_swap_remap_deadlists(dsl_dataset_t * clone,dsl_dataset_t * origin,dmu_tx_t * tx)4150 dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
4151     dsl_dataset_t *origin, dmu_tx_t *tx)
4152 {
4153 	uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
4154 	dsl_pool_t *dp = dmu_tx_pool(tx);
4155 
4156 	ASSERT(dsl_pool_sync_context(dp));
4157 
4158 	clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
4159 	origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
4160 
4161 	if (clone_remap_dl_obj != 0) {
4162 		dsl_deadlist_close(&clone->ds_remap_deadlist);
4163 		dsl_dataset_unset_remap_deadlist_object(clone, tx);
4164 	}
4165 	if (origin_remap_dl_obj != 0) {
4166 		dsl_deadlist_close(&origin->ds_remap_deadlist);
4167 		dsl_dataset_unset_remap_deadlist_object(origin, tx);
4168 	}
4169 
4170 	if (clone_remap_dl_obj != 0) {
4171 		dsl_dataset_set_remap_deadlist_object(origin,
4172 		    clone_remap_dl_obj, tx);
4173 		VERIFY0(dsl_deadlist_open(&origin->ds_remap_deadlist,
4174 		    dp->dp_meta_objset, clone_remap_dl_obj));
4175 	}
4176 	if (origin_remap_dl_obj != 0) {
4177 		dsl_dataset_set_remap_deadlist_object(clone,
4178 		    origin_remap_dl_obj, tx);
4179 		VERIFY0(dsl_deadlist_open(&clone->ds_remap_deadlist,
4180 		    dp->dp_meta_objset, origin_remap_dl_obj));
4181 	}
4182 }
4183 
4184 void
dsl_dataset_clone_swap_sync_impl(dsl_dataset_t * clone,dsl_dataset_t * origin_head,dmu_tx_t * tx)4185 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
4186     dsl_dataset_t *origin_head, dmu_tx_t *tx)
4187 {
4188 	dsl_pool_t *dp = dmu_tx_pool(tx);
4189 	int64_t unused_refres_delta;
4190 
4191 	ASSERT0(clone->ds_reserved);
4192 	/*
4193 	 * NOTE: On DEBUG kernels there could be a race between this and
4194 	 * the check function if spa_asize_inflation is adjusted...
4195 	 */
4196 	ASSERT(origin_head->ds_quota == 0 ||
4197 	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
4198 	    DMU_MAX_ACCESS * spa_asize_inflation);
4199 	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
4200 
4201 	dsl_dir_cancel_waiters(origin_head->ds_dir);
4202 
4203 	/*
4204 	 * Swap per-dataset feature flags.
4205 	 */
4206 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4207 		if (!(spa_feature_table[f].fi_flags &
4208 		    ZFEATURE_FLAG_PER_DATASET)) {
4209 			ASSERT(!dsl_dataset_feature_is_active(clone, f));
4210 			ASSERT(!dsl_dataset_feature_is_active(origin_head, f));
4211 			continue;
4212 		}
4213 
4214 		boolean_t clone_inuse = dsl_dataset_feature_is_active(clone, f);
4215 		void *clone_feature = clone->ds_feature[f];
4216 		boolean_t origin_head_inuse =
4217 		    dsl_dataset_feature_is_active(origin_head, f);
4218 		void *origin_head_feature = origin_head->ds_feature[f];
4219 
4220 		if (clone_inuse)
4221 			dsl_dataset_deactivate_feature_impl(clone, f, tx);
4222 		if (origin_head_inuse)
4223 			dsl_dataset_deactivate_feature_impl(origin_head, f, tx);
4224 
4225 		if (clone_inuse) {
4226 			dsl_dataset_activate_feature(origin_head->ds_object, f,
4227 			    clone_feature, tx);
4228 			origin_head->ds_feature[f] = clone_feature;
4229 		}
4230 		if (origin_head_inuse) {
4231 			dsl_dataset_activate_feature(clone->ds_object, f,
4232 			    origin_head_feature, tx);
4233 			clone->ds_feature[f] = origin_head_feature;
4234 		}
4235 	}
4236 
4237 	dmu_buf_will_dirty(clone->ds_dbuf, tx);
4238 	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
4239 
4240 	if (clone->ds_objset != NULL) {
4241 		dmu_objset_evict(clone->ds_objset);
4242 		clone->ds_objset = NULL;
4243 	}
4244 
4245 	if (origin_head->ds_objset != NULL) {
4246 		dmu_objset_evict(origin_head->ds_objset);
4247 		origin_head->ds_objset = NULL;
4248 	}
4249 
4250 	unused_refres_delta =
4251 	    (int64_t)MIN(origin_head->ds_reserved,
4252 	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4253 	    (int64_t)MIN(origin_head->ds_reserved,
4254 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4255 
4256 	/*
4257 	 * Reset origin's unique bytes.
4258 	 */
4259 	{
4260 		dsl_dataset_t *origin = clone->ds_prev;
4261 		uint64_t comp, uncomp;
4262 
4263 		dmu_buf_will_dirty(origin->ds_dbuf, tx);
4264 		dsl_deadlist_space_range(&clone->ds_deadlist,
4265 		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
4266 		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
4267 	}
4268 
4269 	/* swap blkptrs */
4270 	{
4271 		rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
4272 		rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
4273 		blkptr_t tmp;
4274 		tmp = dsl_dataset_phys(origin_head)->ds_bp;
4275 		dsl_dataset_phys(origin_head)->ds_bp =
4276 		    dsl_dataset_phys(clone)->ds_bp;
4277 		dsl_dataset_phys(clone)->ds_bp = tmp;
4278 		rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
4279 		rrw_exit(&clone->ds_bp_rwlock, FTAG);
4280 	}
4281 
4282 	/* set dd_*_bytes */
4283 	{
4284 		int64_t dused, dcomp, duncomp;
4285 		uint64_t cdl_used, cdl_comp, cdl_uncomp;
4286 		uint64_t odl_used, odl_comp, odl_uncomp;
4287 
4288 		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
4289 		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
4290 
4291 		dsl_deadlist_space(&clone->ds_deadlist,
4292 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4293 		dsl_deadlist_space(&origin_head->ds_deadlist,
4294 		    &odl_used, &odl_comp, &odl_uncomp);
4295 
4296 		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
4297 		    cdl_used -
4298 		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
4299 		    odl_used);
4300 		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
4301 		    cdl_comp -
4302 		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
4303 		    odl_comp);
4304 		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
4305 		    cdl_uncomp -
4306 		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
4307 		    odl_uncomp);
4308 
4309 		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
4310 		    dused, dcomp, duncomp, tx);
4311 		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
4312 		    -dused, -dcomp, -duncomp, tx);
4313 
4314 		/*
4315 		 * The difference in the space used by snapshots is the
4316 		 * difference in snapshot space due to the head's
4317 		 * deadlist (since that's the only thing that's
4318 		 * changing that affects the snapused).
4319 		 */
4320 		dsl_deadlist_space_range(&clone->ds_deadlist,
4321 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4322 		    &cdl_used, &cdl_comp, &cdl_uncomp);
4323 		dsl_deadlist_space_range(&origin_head->ds_deadlist,
4324 		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4325 		    &odl_used, &odl_comp, &odl_uncomp);
4326 		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
4327 		    DD_USED_HEAD, DD_USED_SNAP, tx);
4328 	}
4329 
4330 	/* swap ds_*_bytes */
4331 	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
4332 	    dsl_dataset_phys(clone)->ds_referenced_bytes);
4333 	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
4334 	    dsl_dataset_phys(clone)->ds_compressed_bytes);
4335 	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
4336 	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
4337 	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
4338 	    dsl_dataset_phys(clone)->ds_unique_bytes);
4339 
4340 	/* apply any parent delta for change in unconsumed refreservation */
4341 	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
4342 	    unused_refres_delta, 0, 0, tx);
4343 
4344 	/*
4345 	 * Swap deadlists.
4346 	 */
4347 	dsl_deadlist_close(&clone->ds_deadlist);
4348 	dsl_deadlist_close(&origin_head->ds_deadlist);
4349 	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
4350 	    dsl_dataset_phys(clone)->ds_deadlist_obj);
4351 	VERIFY0(dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
4352 	    dsl_dataset_phys(clone)->ds_deadlist_obj));
4353 	VERIFY0(dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
4354 	    dsl_dataset_phys(origin_head)->ds_deadlist_obj));
4355 	dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
4356 
4357 	/*
4358 	 * If there is a bookmark at the origin, its "next dataset" is
4359 	 * changing, so we need to reset its FBN.
4360 	 */
4361 	dsl_bookmark_next_changed(origin_head, origin_head->ds_prev, tx);
4362 
4363 	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
4364 
4365 	/*
4366 	 * Destroy any livelists associated with the clone or the origin,
4367 	 * since after the swap the corresponding livelists are no longer
4368 	 * valid.
4369 	 */
4370 	dsl_dir_remove_livelist(clone->ds_dir, tx, B_TRUE);
4371 	dsl_dir_remove_livelist(origin_head->ds_dir, tx, B_TRUE);
4372 
4373 	spa_history_log_internal_ds(clone, "clone swap", tx,
4374 	    "parent=%s", origin_head->ds_dir->dd_myname);
4375 }
4376 
4377 /*
4378  * Given a pool name and a dataset object number in that pool,
4379  * return the name of that dataset.
4380  */
4381 int
dsl_dsobj_to_dsname(char * pname,uint64_t obj,char * buf)4382 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
4383 {
4384 	dsl_pool_t *dp;
4385 	dsl_dataset_t *ds;
4386 	int error;
4387 
4388 	error = dsl_pool_hold(pname, FTAG, &dp);
4389 	if (error != 0)
4390 		return (error);
4391 
4392 	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
4393 	if (error == 0) {
4394 		dsl_dataset_name(ds, buf);
4395 		dsl_dataset_rele(ds, FTAG);
4396 	}
4397 	dsl_pool_rele(dp, FTAG);
4398 
4399 	return (error);
4400 }
4401 
4402 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)4403 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
4404     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
4405 {
4406 	int error = 0;
4407 
4408 	ASSERT3S(asize, >, 0);
4409 
4410 	/*
4411 	 * *ref_rsrv is the portion of asize that will come from any
4412 	 * unconsumed refreservation space.
4413 	 */
4414 	*ref_rsrv = 0;
4415 
4416 	mutex_enter(&ds->ds_lock);
4417 	/*
4418 	 * Make a space adjustment for reserved bytes.
4419 	 */
4420 	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
4421 		ASSERT3U(*used, >=,
4422 		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4423 		*used -=
4424 		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4425 		*ref_rsrv =
4426 		    asize - MIN(asize, parent_delta(ds, asize + inflight));
4427 	}
4428 
4429 	if (!check_quota || ds->ds_quota == 0) {
4430 		mutex_exit(&ds->ds_lock);
4431 		return (0);
4432 	}
4433 	/*
4434 	 * If they are requesting more space, and our current estimate
4435 	 * is over quota, they get to try again unless the actual
4436 	 * on-disk is over quota and there are no pending changes (which
4437 	 * may free up space for us).
4438 	 */
4439 	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
4440 	    ds->ds_quota) {
4441 		if (inflight > 0 ||
4442 		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
4443 			error = SET_ERROR(ERESTART);
4444 		else
4445 			error = SET_ERROR(EDQUOT);
4446 	}
4447 	mutex_exit(&ds->ds_lock);
4448 
4449 	return (error);
4450 }
4451 
4452 typedef struct dsl_dataset_set_qr_arg {
4453 	const char *ddsqra_name;
4454 	zprop_source_t ddsqra_source;
4455 	uint64_t ddsqra_value;
4456 } dsl_dataset_set_qr_arg_t;
4457 
4458 
4459 static int
dsl_dataset_set_refquota_check(void * arg,dmu_tx_t * tx)4460 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
4461 {
4462 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4463 	dsl_pool_t *dp = dmu_tx_pool(tx);
4464 	dsl_dataset_t *ds;
4465 	int error;
4466 	uint64_t newval;
4467 
4468 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
4469 		return (SET_ERROR(ENOTSUP));
4470 
4471 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4472 	if (error != 0)
4473 		return (error);
4474 
4475 	if (ds->ds_is_snapshot) {
4476 		dsl_dataset_rele(ds, FTAG);
4477 		return (SET_ERROR(EINVAL));
4478 	}
4479 
4480 	error = dsl_prop_predict(ds->ds_dir,
4481 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4482 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4483 	if (error != 0) {
4484 		dsl_dataset_rele(ds, FTAG);
4485 		return (error);
4486 	}
4487 
4488 	if (newval == 0) {
4489 		dsl_dataset_rele(ds, FTAG);
4490 		return (0);
4491 	}
4492 
4493 	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
4494 	    newval < ds->ds_reserved) {
4495 		dsl_dataset_rele(ds, FTAG);
4496 		return (SET_ERROR(ENOSPC));
4497 	}
4498 
4499 	dsl_dataset_rele(ds, FTAG);
4500 	return (0);
4501 }
4502 
4503 static void
dsl_dataset_set_refquota_sync(void * arg,dmu_tx_t * tx)4504 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
4505 {
4506 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4507 	dsl_pool_t *dp = dmu_tx_pool(tx);
4508 	dsl_dataset_t *ds = NULL;
4509 	uint64_t newval;
4510 
4511 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4512 
4513 	dsl_prop_set_sync_impl(ds,
4514 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4515 	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
4516 	    &ddsqra->ddsqra_value, tx);
4517 
4518 	VERIFY0(dsl_prop_get_int_ds(ds,
4519 	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
4520 
4521 	if (ds->ds_quota != newval) {
4522 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
4523 		ds->ds_quota = newval;
4524 	}
4525 	dsl_dataset_rele(ds, FTAG);
4526 }
4527 
4528 int
dsl_dataset_set_refquota(const char * dsname,zprop_source_t source,uint64_t refquota)4529 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
4530     uint64_t refquota)
4531 {
4532 	dsl_dataset_set_qr_arg_t ddsqra;
4533 
4534 	ddsqra.ddsqra_name = dsname;
4535 	ddsqra.ddsqra_source = source;
4536 	ddsqra.ddsqra_value = refquota;
4537 
4538 	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
4539 	    dsl_dataset_set_refquota_sync, &ddsqra, 0,
4540 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4541 }
4542 
4543 static int
dsl_dataset_set_refreservation_check(void * arg,dmu_tx_t * tx)4544 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
4545 {
4546 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4547 	dsl_pool_t *dp = dmu_tx_pool(tx);
4548 	dsl_dataset_t *ds;
4549 	int error;
4550 	uint64_t newval, unique;
4551 
4552 	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
4553 		return (SET_ERROR(ENOTSUP));
4554 
4555 	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4556 	if (error != 0)
4557 		return (error);
4558 
4559 	if (ds->ds_is_snapshot) {
4560 		dsl_dataset_rele(ds, FTAG);
4561 		return (SET_ERROR(EINVAL));
4562 	}
4563 
4564 	error = dsl_prop_predict(ds->ds_dir,
4565 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4566 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4567 	if (error != 0) {
4568 		dsl_dataset_rele(ds, FTAG);
4569 		return (error);
4570 	}
4571 
4572 	/*
4573 	 * If we are doing the preliminary check in open context, the
4574 	 * space estimates may be inaccurate.
4575 	 */
4576 	if (!dmu_tx_is_syncing(tx)) {
4577 		dsl_dataset_rele(ds, FTAG);
4578 		return (0);
4579 	}
4580 
4581 	mutex_enter(&ds->ds_lock);
4582 	if (!DS_UNIQUE_IS_ACCURATE(ds))
4583 		dsl_dataset_recalc_head_uniq(ds);
4584 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4585 	mutex_exit(&ds->ds_lock);
4586 
4587 	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
4588 		uint64_t delta = MAX(unique, newval) -
4589 		    MAX(unique, ds->ds_reserved);
4590 
4591 		if (delta >
4592 		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
4593 		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
4594 			dsl_dataset_rele(ds, FTAG);
4595 			return (SET_ERROR(ENOSPC));
4596 		}
4597 	}
4598 
4599 	dsl_dataset_rele(ds, FTAG);
4600 	return (0);
4601 }
4602 
4603 void
dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t * ds,zprop_source_t source,uint64_t value,dmu_tx_t * tx)4604 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
4605     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
4606 {
4607 	uint64_t newval;
4608 	uint64_t unique;
4609 	int64_t delta;
4610 
4611 	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4612 	    source, sizeof (value), 1, &value, tx);
4613 
4614 	VERIFY0(dsl_prop_get_int_ds(ds,
4615 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
4616 
4617 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
4618 	mutex_enter(&ds->ds_dir->dd_lock);
4619 	mutex_enter(&ds->ds_lock);
4620 	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
4621 	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4622 	delta = MAX(0, (int64_t)(newval - unique)) -
4623 	    MAX(0, (int64_t)(ds->ds_reserved - unique));
4624 	ds->ds_reserved = newval;
4625 	mutex_exit(&ds->ds_lock);
4626 
4627 	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
4628 	mutex_exit(&ds->ds_dir->dd_lock);
4629 }
4630 
4631 static void
dsl_dataset_set_refreservation_sync(void * arg,dmu_tx_t * tx)4632 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
4633 {
4634 	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4635 	dsl_pool_t *dp = dmu_tx_pool(tx);
4636 	dsl_dataset_t *ds = NULL;
4637 
4638 	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4639 	dsl_dataset_set_refreservation_sync_impl(ds,
4640 	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
4641 	dsl_dataset_rele(ds, FTAG);
4642 }
4643 
4644 int
dsl_dataset_set_refreservation(const char * dsname,zprop_source_t source,uint64_t refreservation)4645 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
4646     uint64_t refreservation)
4647 {
4648 	dsl_dataset_set_qr_arg_t ddsqra;
4649 
4650 	ddsqra.ddsqra_name = dsname;
4651 	ddsqra.ddsqra_source = source;
4652 	ddsqra.ddsqra_value = refreservation;
4653 
4654 	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
4655 	    dsl_dataset_set_refreservation_sync, &ddsqra, 0,
4656 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4657 }
4658 
4659 typedef struct dsl_dataset_set_compression_arg {
4660 	const char *ddsca_name;
4661 	zprop_source_t ddsca_source;
4662 	uint64_t ddsca_value;
4663 } dsl_dataset_set_compression_arg_t;
4664 
4665 static int
dsl_dataset_set_compression_check(void * arg,dmu_tx_t * tx)4666 dsl_dataset_set_compression_check(void *arg, dmu_tx_t *tx)
4667 {
4668 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4669 	dsl_pool_t *dp = dmu_tx_pool(tx);
4670 
4671 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4672 	spa_feature_t f = zio_compress_to_feature(compval);
4673 
4674 	if (f == SPA_FEATURE_NONE)
4675 		return (SET_ERROR(EINVAL));
4676 
4677 	if (!spa_feature_is_enabled(dp->dp_spa, f))
4678 		return (SET_ERROR(ENOTSUP));
4679 
4680 	return (0);
4681 }
4682 
4683 static void
dsl_dataset_set_compression_sync(void * arg,dmu_tx_t * tx)4684 dsl_dataset_set_compression_sync(void *arg, dmu_tx_t *tx)
4685 {
4686 	dsl_dataset_set_compression_arg_t *ddsca = arg;
4687 	dsl_pool_t *dp = dmu_tx_pool(tx);
4688 	dsl_dataset_t *ds = NULL;
4689 
4690 	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4691 	spa_feature_t f = zio_compress_to_feature(compval);
4692 	ASSERT3S(f, !=, SPA_FEATURE_NONE);
4693 	ASSERT3S(spa_feature_table[f].fi_type, ==, ZFEATURE_TYPE_BOOLEAN);
4694 
4695 	VERIFY0(dsl_dataset_hold(dp, ddsca->ddsca_name, FTAG, &ds));
4696 	if (zfeature_active(f, ds->ds_feature[f]) != B_TRUE) {
4697 		ds->ds_feature_activation[f] = (void *)B_TRUE;
4698 		dsl_dataset_activate_feature(ds->ds_object, f,
4699 		    ds->ds_feature_activation[f], tx);
4700 		ds->ds_feature[f] = ds->ds_feature_activation[f];
4701 	}
4702 	dsl_dataset_rele(ds, FTAG);
4703 }
4704 
4705 int
dsl_dataset_set_compression(const char * dsname,zprop_source_t source,uint64_t compression)4706 dsl_dataset_set_compression(const char *dsname, zprop_source_t source,
4707     uint64_t compression)
4708 {
4709 	dsl_dataset_set_compression_arg_t ddsca;
4710 
4711 	/*
4712 	 * The sync task is only required for zstd in order to activate
4713 	 * the feature flag when the property is first set.
4714 	 */
4715 	if (ZIO_COMPRESS_ALGO(compression) != ZIO_COMPRESS_ZSTD)
4716 		return (0);
4717 
4718 	ddsca.ddsca_name = dsname;
4719 	ddsca.ddsca_source = source;
4720 	ddsca.ddsca_value = compression;
4721 
4722 	return (dsl_sync_task(dsname, dsl_dataset_set_compression_check,
4723 	    dsl_dataset_set_compression_sync, &ddsca, 0,
4724 	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4725 }
4726 
4727 /*
4728  * Return (in *usedp) the amount of space referenced by "new" that was not
4729  * referenced at the time the bookmark corresponds to.  "New" may be a
4730  * snapshot or a head.  The bookmark must be before new, in
4731  * new's filesystem (or its origin) -- caller verifies this.
4732  *
4733  * The written space is calculated by considering two components:  First, we
4734  * ignore any freed space, and calculate the written as new's used space
4735  * minus old's used space.  Next, we add in the amount of space that was freed
4736  * between the two time points, thus reducing new's used space relative to
4737  * old's. Specifically, this is the space that was born before
4738  * zbm_creation_txg, and freed before new (ie. on new's deadlist or a
4739  * previous deadlist).
4740  *
4741  * space freed                         [---------------------]
4742  * snapshots                       ---O-------O--------O-------O------
4743  *                                         bookmark           new
4744  *
4745  * Note, the bookmark's zbm_*_bytes_refd must be valid, but if the HAS_FBN
4746  * flag is not set, we will calculate the freed_before_next based on the
4747  * next snapshot's deadlist, rather than using zbm_*_freed_before_next_snap.
4748  */
4749 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)4750 dsl_dataset_space_written_impl(zfs_bookmark_phys_t *bmp,
4751     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4752 {
4753 	int err = 0;
4754 	dsl_pool_t *dp = new->ds_dir->dd_pool;
4755 
4756 	ASSERT(dsl_pool_config_held(dp));
4757 	if (dsl_dataset_is_snapshot(new)) {
4758 		ASSERT3U(bmp->zbm_creation_txg, <,
4759 		    dsl_dataset_phys(new)->ds_creation_txg);
4760 	}
4761 
4762 	*usedp = 0;
4763 	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
4764 	*usedp -= bmp->zbm_referenced_bytes_refd;
4765 
4766 	*compp = 0;
4767 	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
4768 	*compp -= bmp->zbm_compressed_bytes_refd;
4769 
4770 	*uncompp = 0;
4771 	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
4772 	*uncompp -= bmp->zbm_uncompressed_bytes_refd;
4773 
4774 	dsl_dataset_t *snap = new;
4775 
4776 	while (dsl_dataset_phys(snap)->ds_prev_snap_txg >
4777 	    bmp->zbm_creation_txg) {
4778 		uint64_t used, comp, uncomp;
4779 
4780 		dsl_deadlist_space_range(&snap->ds_deadlist,
4781 		    0, bmp->zbm_creation_txg,
4782 		    &used, &comp, &uncomp);
4783 		*usedp += used;
4784 		*compp += comp;
4785 		*uncompp += uncomp;
4786 
4787 		uint64_t snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
4788 		if (snap != new)
4789 			dsl_dataset_rele(snap, FTAG);
4790 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4791 		if (err != 0)
4792 			break;
4793 	}
4794 
4795 	/*
4796 	 * We might not have the FBN if we are calculating written from
4797 	 * a snapshot (because we didn't know the correct "next" snapshot
4798 	 * until now).
4799 	 */
4800 	if (bmp->zbm_flags & ZBM_FLAG_HAS_FBN) {
4801 		*usedp += bmp->zbm_referenced_freed_before_next_snap;
4802 		*compp += bmp->zbm_compressed_freed_before_next_snap;
4803 		*uncompp += bmp->zbm_uncompressed_freed_before_next_snap;
4804 	} else {
4805 		ASSERT3U(dsl_dataset_phys(snap)->ds_prev_snap_txg, ==,
4806 		    bmp->zbm_creation_txg);
4807 		uint64_t used, comp, uncomp;
4808 		dsl_deadlist_space(&snap->ds_deadlist, &used, &comp, &uncomp);
4809 		*usedp += used;
4810 		*compp += comp;
4811 		*uncompp += uncomp;
4812 	}
4813 	if (snap != new)
4814 		dsl_dataset_rele(snap, FTAG);
4815 	return (err);
4816 }
4817 
4818 /*
4819  * Return (in *usedp) the amount of space written in new that was not
4820  * present at the time the bookmark corresponds to.  New may be a
4821  * snapshot or the head.  Old must be a bookmark before new, in
4822  * new's filesystem (or its origin) -- caller verifies this.
4823  */
4824 int
dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t * bmp,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4825 dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t *bmp,
4826     dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4827 {
4828 	if (!(bmp->zbm_flags & ZBM_FLAG_HAS_FBN))
4829 		return (SET_ERROR(ENOTSUP));
4830 	return (dsl_dataset_space_written_impl(bmp, new,
4831 	    usedp, compp, uncompp));
4832 }
4833 
4834 /*
4835  * Return (in *usedp) the amount of space written in new that is not
4836  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4837  * a snapshot before new, in new's filesystem (or its origin).  If not then
4838  * fail and return EINVAL.
4839  */
4840 int
dsl_dataset_space_written(dsl_dataset_t * oldsnap,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4841 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4842     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4843 {
4844 	if (!dsl_dataset_is_before(new, oldsnap, 0))
4845 		return (SET_ERROR(EINVAL));
4846 
4847 	zfs_bookmark_phys_t zbm = { 0 };
4848 	dsl_dataset_phys_t *dsp = dsl_dataset_phys(oldsnap);
4849 	zbm.zbm_guid = dsp->ds_guid;
4850 	zbm.zbm_creation_txg = dsp->ds_creation_txg;
4851 	zbm.zbm_creation_time = dsp->ds_creation_time;
4852 	zbm.zbm_referenced_bytes_refd = dsp->ds_referenced_bytes;
4853 	zbm.zbm_compressed_bytes_refd = dsp->ds_compressed_bytes;
4854 	zbm.zbm_uncompressed_bytes_refd = dsp->ds_uncompressed_bytes;
4855 
4856 	/*
4857 	 * If oldsnap is the origin (or origin's origin, ...) of new,
4858 	 * we can't easily calculate the effective FBN.  Therefore,
4859 	 * we do not set ZBM_FLAG_HAS_FBN, so that the _impl will calculate
4860 	 * it relative to the correct "next": the next snapshot towards "new",
4861 	 * rather than the next snapshot in oldsnap's dsl_dir.
4862 	 */
4863 	return (dsl_dataset_space_written_impl(&zbm, new,
4864 	    usedp, compp, uncompp));
4865 }
4866 
4867 /*
4868  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4869  * lastsnap, and all snapshots in between are deleted.
4870  *
4871  * blocks that would be freed            [---------------------------]
4872  * snapshots                       ---O-------O--------O-------O--------O
4873  *                                        firstsnap        lastsnap
4874  *
4875  * This is the set of blocks that were born after the snap before firstsnap,
4876  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4877  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4878  * We calculate this by iterating over the relevant deadlists (from the snap
4879  * after lastsnap, backward to the snap after firstsnap), summing up the
4880  * space on the deadlist that was born after the snap before firstsnap.
4881  */
4882 int
dsl_dataset_space_wouldfree(dsl_dataset_t * firstsnap,dsl_dataset_t * lastsnap,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4883 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4884     dsl_dataset_t *lastsnap,
4885     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4886 {
4887 	int err = 0;
4888 	uint64_t snapobj;
4889 	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4890 
4891 	ASSERT(firstsnap->ds_is_snapshot);
4892 	ASSERT(lastsnap->ds_is_snapshot);
4893 
4894 	/*
4895 	 * Check that the snapshots are in the same dsl_dir, and firstsnap
4896 	 * is before lastsnap.
4897 	 */
4898 	if (firstsnap->ds_dir != lastsnap->ds_dir ||
4899 	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
4900 	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
4901 		return (SET_ERROR(EINVAL));
4902 
4903 	*usedp = *compp = *uncompp = 0;
4904 
4905 	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
4906 	while (snapobj != firstsnap->ds_object) {
4907 		dsl_dataset_t *ds;
4908 		uint64_t used, comp, uncomp;
4909 
4910 		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4911 		if (err != 0)
4912 			break;
4913 
4914 		dsl_deadlist_space_range(&ds->ds_deadlist,
4915 		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
4916 		    &used, &comp, &uncomp);
4917 		*usedp += used;
4918 		*compp += comp;
4919 		*uncompp += uncomp;
4920 
4921 		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4922 		ASSERT3U(snapobj, !=, 0);
4923 		dsl_dataset_rele(ds, FTAG);
4924 	}
4925 	return (err);
4926 }
4927 
4928 /*
4929  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
4930  * For example, they could both be snapshots of the same filesystem, and
4931  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
4932  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
4933  * filesystem.  Or 'earlier' could be the origin's origin.
4934  *
4935  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
4936  */
4937 boolean_t
dsl_dataset_is_before(dsl_dataset_t * later,dsl_dataset_t * earlier,uint64_t earlier_txg)4938 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4939     uint64_t earlier_txg)
4940 {
4941 	dsl_pool_t *dp = later->ds_dir->dd_pool;
4942 	int error;
4943 	boolean_t ret;
4944 
4945 	ASSERT(dsl_pool_config_held(dp));
4946 	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4947 
4948 	if (earlier_txg == 0)
4949 		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4950 
4951 	if (later->ds_is_snapshot &&
4952 	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4953 		return (B_FALSE);
4954 
4955 	if (later->ds_dir == earlier->ds_dir)
4956 		return (B_TRUE);
4957 
4958 	/*
4959 	 * We check dd_origin_obj explicitly here rather than using
4960 	 * dsl_dir_is_clone() so that we will return TRUE if "earlier"
4961 	 * is $ORIGIN@$ORIGIN.  dsl_dataset_space_written() depends on
4962 	 * this behavior.
4963 	 */
4964 	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == 0)
4965 		return (B_FALSE);
4966 
4967 	dsl_dataset_t *origin;
4968 	error = dsl_dataset_hold_obj(dp,
4969 	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4970 	if (error != 0)
4971 		return (B_FALSE);
4972 	if (dsl_dataset_phys(origin)->ds_creation_txg == earlier_txg &&
4973 	    origin->ds_dir == earlier->ds_dir) {
4974 		dsl_dataset_rele(origin, FTAG);
4975 		return (B_TRUE);
4976 	}
4977 	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4978 	dsl_dataset_rele(origin, FTAG);
4979 	return (ret);
4980 }
4981 
4982 void
dsl_dataset_zapify(dsl_dataset_t * ds,dmu_tx_t * tx)4983 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4984 {
4985 	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4986 	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4987 }
4988 
4989 boolean_t
dsl_dataset_is_zapified(dsl_dataset_t * ds)4990 dsl_dataset_is_zapified(dsl_dataset_t *ds)
4991 {
4992 	dmu_object_info_t doi;
4993 
4994 	dmu_object_info_from_db(ds->ds_dbuf, &doi);
4995 	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4996 }
4997 
4998 boolean_t
dsl_dataset_has_resume_receive_state(dsl_dataset_t * ds)4999 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
5000 {
5001 	return (dsl_dataset_is_zapified(ds) &&
5002 	    zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
5003 	    ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
5004 }
5005 
5006 uint64_t
dsl_dataset_get_remap_deadlist_object(dsl_dataset_t * ds)5007 dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
5008 {
5009 	uint64_t remap_deadlist_obj;
5010 	int err;
5011 
5012 	if (!dsl_dataset_is_zapified(ds))
5013 		return (0);
5014 
5015 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
5016 	    DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
5017 	    &remap_deadlist_obj);
5018 
5019 	if (err != 0) {
5020 		VERIFY3S(err, ==, ENOENT);
5021 		return (0);
5022 	}
5023 
5024 	ASSERT(remap_deadlist_obj != 0);
5025 	return (remap_deadlist_obj);
5026 }
5027 
5028 boolean_t
dsl_dataset_remap_deadlist_exists(dsl_dataset_t * ds)5029 dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
5030 {
5031 	EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
5032 	    dsl_dataset_get_remap_deadlist_object(ds) != 0);
5033 	return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
5034 }
5035 
5036 static void
dsl_dataset_set_remap_deadlist_object(dsl_dataset_t * ds,uint64_t obj,dmu_tx_t * tx)5037 dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
5038     dmu_tx_t *tx)
5039 {
5040 	ASSERT(obj != 0);
5041 	dsl_dataset_zapify(ds, tx);
5042 	VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
5043 	    DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
5044 }
5045 
5046 static void
dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t * ds,dmu_tx_t * tx)5047 dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
5048 {
5049 	VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
5050 	    ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
5051 }
5052 
5053 void
dsl_dataset_destroy_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)5054 dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
5055 {
5056 	uint64_t remap_deadlist_object;
5057 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
5058 
5059 	ASSERT(dmu_tx_is_syncing(tx));
5060 	ASSERT(dsl_dataset_remap_deadlist_exists(ds));
5061 
5062 	remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
5063 	dsl_deadlist_close(&ds->ds_remap_deadlist);
5064 	dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
5065 	dsl_dataset_unset_remap_deadlist_object(ds, tx);
5066 	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
5067 }
5068 
5069 void
dsl_dataset_create_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)5070 dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
5071 {
5072 	uint64_t remap_deadlist_obj;
5073 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
5074 
5075 	ASSERT(dmu_tx_is_syncing(tx));
5076 	ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
5077 	/*
5078 	 * Currently we only create remap deadlists when there are indirect
5079 	 * vdevs with referenced mappings.
5080 	 */
5081 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
5082 
5083 	remap_deadlist_obj = dsl_deadlist_clone(
5084 	    &ds->ds_deadlist, UINT64_MAX,
5085 	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
5086 	dsl_dataset_set_remap_deadlist_object(ds,
5087 	    remap_deadlist_obj, tx);
5088 	VERIFY0(dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
5089 	    remap_deadlist_obj));
5090 	spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
5091 }
5092 
5093 void
dsl_dataset_activate_redaction(dsl_dataset_t * ds,uint64_t * redact_snaps,uint64_t num_redact_snaps,dmu_tx_t * tx)5094 dsl_dataset_activate_redaction(dsl_dataset_t *ds, uint64_t *redact_snaps,
5095     uint64_t num_redact_snaps, dmu_tx_t *tx)
5096 {
5097 	uint64_t dsobj = ds->ds_object;
5098 	struct feature_type_uint64_array_arg *ftuaa =
5099 	    kmem_zalloc(sizeof (*ftuaa), KM_SLEEP);
5100 	ftuaa->length = (int64_t)num_redact_snaps;
5101 	if (num_redact_snaps > 0) {
5102 		ftuaa->array = kmem_alloc(num_redact_snaps * sizeof (uint64_t),
5103 		    KM_SLEEP);
5104 		memcpy(ftuaa->array, redact_snaps, num_redact_snaps *
5105 		    sizeof (uint64_t));
5106 	}
5107 	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_REDACTED_DATASETS,
5108 	    ftuaa, tx);
5109 	ds->ds_feature[SPA_FEATURE_REDACTED_DATASETS] = ftuaa;
5110 }
5111 
5112 /*
5113  * Find and return (in *oldest_dsobj) the oldest snapshot of the dsobj
5114  * dataset whose birth time is >= min_txg.
5115  */
5116 int
dsl_dataset_oldest_snapshot(spa_t * spa,uint64_t head_ds,uint64_t min_txg,uint64_t * oldest_dsobj)5117 dsl_dataset_oldest_snapshot(spa_t *spa, uint64_t head_ds, uint64_t min_txg,
5118     uint64_t *oldest_dsobj)
5119 {
5120 	dsl_dataset_t *ds;
5121 	dsl_pool_t *dp = spa->spa_dsl_pool;
5122 
5123 	int error = dsl_dataset_hold_obj(dp, head_ds, FTAG, &ds);
5124 	if (error != 0)
5125 		return (error);
5126 
5127 	uint64_t prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5128 	uint64_t prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5129 
5130 	while (prev_obj != 0 && min_txg < prev_obj_txg) {
5131 		dsl_dataset_rele(ds, FTAG);
5132 		if ((error = dsl_dataset_hold_obj(dp, prev_obj,
5133 		    FTAG, &ds)) != 0)
5134 			return (error);
5135 		prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5136 		prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5137 	}
5138 	*oldest_dsobj = ds->ds_object;
5139 	dsl_dataset_rele(ds, FTAG);
5140 	return (0);
5141 }
5142 
5143 ZFS_MODULE_PARAM(zfs, zfs_, max_recordsize, UINT, ZMOD_RW,
5144 	"Max allowed record size");
5145 
5146 ZFS_MODULE_PARAM(zfs, zfs_, allow_redacted_dataset_mount, INT, ZMOD_RW,
5147 	"Allow mounting of redacted datasets");
5148 
5149 ZFS_MODULE_PARAM(zfs, zfs_, snapshot_history_enabled, INT, ZMOD_RW,
5150 	"Include snapshot events in pool history/events");
5151 
5152 EXPORT_SYMBOL(dsl_dataset_hold);
5153 EXPORT_SYMBOL(dsl_dataset_hold_flags);
5154 EXPORT_SYMBOL(dsl_dataset_hold_obj);
5155 EXPORT_SYMBOL(dsl_dataset_hold_obj_flags);
5156 EXPORT_SYMBOL(dsl_dataset_own);
5157 EXPORT_SYMBOL(dsl_dataset_own_obj);
5158 EXPORT_SYMBOL(dsl_dataset_name);
5159 EXPORT_SYMBOL(dsl_dataset_rele);
5160 EXPORT_SYMBOL(dsl_dataset_rele_flags);
5161 EXPORT_SYMBOL(dsl_dataset_disown);
5162 EXPORT_SYMBOL(dsl_dataset_tryown);
5163 EXPORT_SYMBOL(dsl_dataset_create_sync);
5164 EXPORT_SYMBOL(dsl_dataset_create_sync_dd);
5165 EXPORT_SYMBOL(dsl_dataset_snapshot_check);
5166 EXPORT_SYMBOL(dsl_dataset_snapshot_sync);
5167 EXPORT_SYMBOL(dsl_dataset_promote);
5168 EXPORT_SYMBOL(dsl_dataset_user_hold);
5169 EXPORT_SYMBOL(dsl_dataset_user_release);
5170 EXPORT_SYMBOL(dsl_dataset_get_holds);
5171 EXPORT_SYMBOL(dsl_dataset_get_blkptr);
5172 EXPORT_SYMBOL(dsl_dataset_get_spa);
5173 EXPORT_SYMBOL(dsl_dataset_modified_since_snap);
5174 EXPORT_SYMBOL(dsl_dataset_space_written);
5175 EXPORT_SYMBOL(dsl_dataset_space_wouldfree);
5176 EXPORT_SYMBOL(dsl_dataset_sync);
5177 EXPORT_SYMBOL(dsl_dataset_block_born);
5178 EXPORT_SYMBOL(dsl_dataset_block_kill);
5179 EXPORT_SYMBOL(dsl_dataset_dirty);
5180 EXPORT_SYMBOL(dsl_dataset_stats);
5181 EXPORT_SYMBOL(dsl_dataset_fast_stat);
5182 EXPORT_SYMBOL(dsl_dataset_space);
5183 EXPORT_SYMBOL(dsl_dataset_fsid_guid);
5184 EXPORT_SYMBOL(dsl_dsobj_to_dsname);
5185 EXPORT_SYMBOL(dsl_dataset_check_quota);
5186 EXPORT_SYMBOL(dsl_dataset_clone_swap_check_impl);
5187 EXPORT_SYMBOL(dsl_dataset_clone_swap_sync_impl);
5188