xref: /freebsd/sys/contrib/openzfs/module/zfs/brt.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2020, 2021, 2022 by Pawel Jakub Dawidek
15  */
16 
17 #include <sys/zfs_context.h>
18 #include <sys/spa.h>
19 #include <sys/spa_impl.h>
20 #include <sys/zio.h>
21 #include <sys/brt.h>
22 #include <sys/brt_impl.h>
23 #include <sys/ddt.h>
24 #include <sys/bitmap.h>
25 #include <sys/zap.h>
26 #include <sys/dmu_tx.h>
27 #include <sys/arc.h>
28 #include <sys/dsl_pool.h>
29 #include <sys/dsl_scan.h>
30 #include <sys/vdev_impl.h>
31 #include <sys/kstat.h>
32 #include <sys/wmsum.h>
33 
34 /*
35  * Block Cloning design.
36  *
37  * Block Cloning allows to manually clone a file (or a subset of its blocks)
38  * into another (or the same) file by just creating additional references to
39  * the data blocks without copying the data itself. Those references are kept
40  * in the Block Reference Tables (BRTs).
41  *
42  * In many ways this is similar to the existing deduplication, but there are
43  * some important differences:
44  *
45  * - Deduplication is automatic and Block Cloning is not - one has to use a
46  *   dedicated system call(s) to clone the given file/blocks.
47  * - Deduplication keeps all data blocks in its table, even those referenced
48  *   just once. Block Cloning creates an entry in its tables only when there
49  *   are at least two references to the given data block. If the block was
50  *   never explicitly cloned or the second to last reference was dropped,
51  *   there will be neither space nor performance overhead.
52  * - Deduplication needs data to work - one needs to pass real data to the
53  *   write(2) syscall, so hash can be calculated. Block Cloning doesn't require
54  *   data, just block pointers to the data, so it is extremely fast, as we pay
55  *   neither the cost of reading the data, nor the cost of writing the data -
56  *   we operate exclusively on metadata.
57  * - If the D (dedup) bit is not set in the block pointer, it means that
58  *   the block is not in the dedup table (DDT) and we won't consult the DDT
59  *   when we need to free the block. Block Cloning must be consulted on every
60  *   free, because we cannot modify the source BP (eg. by setting something
61  *   similar to the D bit), thus we have no hint if the block is in the
62  *   Block Reference Table (BRT), so we need to look into the BRT. There is
63  *   an optimization in place that allows us to eliminate the majority of BRT
64  *   lookups which is described below in the "Minimizing free penalty" section.
65  * - The BRT entry is much smaller than the DDT entry - for BRT we only store
66  *   64bit offset and 64bit reference counter.
67  * - Dedup keys are cryptographic hashes, so two blocks that are close to each
68  *   other on disk are most likely in totally different parts of the DDT.
69  *   The BRT entry keys are offsets into a single top-level VDEV, so data blocks
70  *   from one file should have BRT entries close to each other.
71  * - Scrub will only do a single pass over a block that is referenced multiple
72  *   times in the DDT. Unfortunately it is not currently (if at all) possible
73  *   with Block Cloning and block referenced multiple times will be scrubbed
74  *   multiple times. The new, sorted scrub should be able to eliminate
75  *   duplicated reads given enough memory.
76  * - Deduplication requires cryptographically strong hash as a checksum or
77  *   additional data verification. Block Cloning works with any checksum
78  *   algorithm or even with checksumming disabled.
79  *
80  * As mentioned above, the BRT entries are much smaller than the DDT entries.
81  * To uniquely identify a block we just need its vdev id and offset. We also
82  * need to maintain a reference counter. The vdev id will often repeat, as there
83  * is a small number of top-level VDEVs and a large number of blocks stored in
84  * each VDEV. We take advantage of that to reduce the BRT entry size further by
85  * maintaining one BRT for each top-level VDEV, so we can then have only offset
86  * and counter as the BRT entry.
87  *
88  * Minimizing free penalty.
89  *
90  * Block Cloning allows creating additional references to any existing block.
91  * When we free a block there is no hint in the block pointer whether the block
92  * was cloned or not, so on each free we have to check if there is a
93  * corresponding entry in the BRT or not. If there is, we need to decrease
94  * the reference counter. Doing BRT lookup on every free can potentially be
95  * expensive by requiring additional I/Os if the BRT doesn't fit into memory.
96  * This is the main problem with deduplication, so we've learned our lesson and
97  * try not to repeat the same mistake here. How do we do that? We divide each
98  * top-level VDEV into 16MB regions. For each region we maintain a counter that
99  * is a sum of all the BRT entries that have offsets within the region. This
100  * creates the entries count array of 16bit numbers for each top-level VDEV.
101  * The entries count array is always kept in memory and updated on disk in the
102  * same transaction group as the BRT updates to keep everything in-sync. We can
103  * keep the array in memory, because it is very small. With 16MB regions and
104  * 1TB VDEV the array requires only 128kB of memory (we may decide to decrease
105  * the region size even further in the future). Now, when we want to free
106  * a block, we first consult the array. If the counter for the whole region is
107  * zero, there is no need to look for the BRT entry, as there isn't one for
108  * sure. If the counter for the region is greater than zero, only then we will
109  * do a BRT lookup and if an entry is found we will decrease the reference
110  * counter in the BRT entry and in the entry counters array.
111  *
112  * The entry counters array is small, but can potentially be larger for very
113  * large VDEVs or smaller regions. In this case we don't want to rewrite entire
114  * array on every change. We then divide the array into 32kB block and keep
115  * a bitmap of dirty blocks within a transaction group. When we sync the
116  * transaction group we can only update the parts of the entry counters array
117  * that were modified. Note: Keeping track of the dirty parts of the entry
118  * counters array is implemented, but updating only parts of the array on disk
119  * is not yet implemented - for now we will update entire array if there was
120  * any change.
121  *
122  * The implementation tries to be economic: if BRT is not used, or no longer
123  * used, there will be no entries in the MOS and no additional memory used (eg.
124  * the entry counters array is only allocated if needed).
125  *
126  * Interaction between Deduplication and Block Cloning.
127  *
128  * If both functionalities are in use, we could end up with a block that is
129  * referenced multiple times in both DDT and BRT. When we free one of the
130  * references we couldn't tell where it belongs, so we would have to decide
131  * what table takes the precedence: do we first clear DDT references or BRT
132  * references? To avoid this dilemma BRT cooperates with DDT - if a given block
133  * is being cloned using BRT and the BP has the D (dedup) bit set, BRT will
134  * lookup DDT entry instead and increase the counter there. No BRT entry
135  * will be created for a block which has the D (dedup) bit set.
136  * BRT may be more efficient for manual deduplication, but if the block is
137  * already in the DDT, then creating additional BRT entry would be less
138  * efficient. This clever idea was proposed by Allan Jude.
139  *
140  * Block Cloning across datasets.
141  *
142  * Block Cloning is not limited to cloning blocks within the same dataset.
143  * It is possible (and very useful) to clone blocks between different datasets.
144  * One use case is recovering files from snapshots. By cloning the files into
145  * dataset we need no additional storage. Without Block Cloning we would need
146  * additional space for those files.
147  * Another interesting use case is moving the files between datasets
148  * (copying the file content to the new dataset and removing the source file).
149  * In that case Block Cloning will only be used briefly, because the BRT entries
150  * will be removed when the source is removed.
151  * Block Cloning across encrypted datasets is supported as long as both
152  * datasets share the same master key (e.g. snapshots and clones)
153  *
154  * Block Cloning flow through ZFS layers.
155  *
156  * Note: Block Cloning can be used both for cloning file system blocks and ZVOL
157  * blocks. As of this writing no interface is implemented that allows for block
158  * cloning within a ZVOL.
159  * FreeBSD and Linux provides copy_file_range(2) system call and we will use it
160  * for blocking cloning.
161  *
162  *	ssize_t
163  *	copy_file_range(int infd, off_t *inoffp, int outfd, off_t *outoffp,
164  *	                size_t len, unsigned int flags);
165  *
166  * Even though offsets and length represent bytes, they have to be
167  * block-aligned or we will return an error so the upper layer can
168  * fallback to the generic mechanism that will just copy the data.
169  * Using copy_file_range(2) will call OS-independent zfs_clone_range() function.
170  * This function was implemented based on zfs_write(), but instead of writing
171  * the given data we first read block pointers using the new dmu_read_l0_bps()
172  * function from the source file. Once we have BPs from the source file we call
173  * the dmu_brt_clone() function on the destination file. This function
174  * allocates BPs for us. We iterate over all source BPs. If the given BP is
175  * a hole or an embedded block, we just copy BP as-is. If it points to a real
176  * data we place this BP on a BRT pending list using the brt_pending_add()
177  * function.
178  *
179  * We use this pending list to keep track of all BPs that got new references
180  * within this transaction group.
181  *
182  * Some special cases to consider and how we address them:
183  * - The block we want to clone may have been created within the same
184  *   transaction group that we are trying to clone. Such block has no BP
185  *   allocated yet, so cannot be immediately cloned. We return EAGAIN.
186  * - The block we want to clone may have been modified within the same
187  *   transaction group. We return EAGAIN.
188  * - A block may be cloned multiple times during one transaction group (that's
189  *   why pending list is actually a tree and not an append-only list - this
190  *   way we can figure out faster if this block is cloned for the first time
191  *   in this txg or consecutive time).
192  * - A block may be cloned and freed within the same transaction group
193  *   (see dbuf_undirty()).
194  * - A block may be cloned and within the same transaction group the clone
195  *   can be cloned again (see dmu_read_l0_bps()).
196  * - A file might have been deleted, but the caller still has a file descriptor
197  *   open to this file and clones it.
198  *
199  * When we free a block we have an additional step in the ZIO pipeline where we
200  * call the zio_brt_free() function. We then call the brt_entry_decref()
201  * that loads the corresponding BRT entry (if one exists) and decreases
202  * reference counter. If this is not the last reference we will stop ZIO
203  * pipeline here. If this is the last reference or the block is not in the
204  * BRT, we continue the pipeline and free the block as usual.
205  *
206  * At the beginning of spa_sync() where there can be no more block cloning,
207  * but before issuing frees we call brt_pending_apply(). This function applies
208  * all the new clones to the BRT table - we load BRT entries and update
209  * reference counters. Blocks with the DEDUP bit set are referenced in the
210  * DDT instead and are kept on separate pending trees, sorted and sharded by
211  * the DDT ZAP hash, so that syncing context can process them in parallel
212  * with sequential access to the DDT ZAP leaves. To sync new BRT entries to
213  * disk, we use brt_sync() function. This function will sync all dirty
214  * per-top-level-vdev BRTs, the entry counters arrays, etc.
215  *
216  * Block Cloning and ZIL.
217  *
218  * Every clone operation is divided into chunks (similar to write) and each
219  * chunk is cloned in a separate transaction. The chunk size is determined by
220  * how many BPs we can fit into a single ZIL entry.
221  * Replaying clone operation is different from the regular clone operation,
222  * as when we log clone operations we cannot use the source object - it may
223  * reside on a different dataset, so we log BPs we want to clone.
224  * The ZIL is replayed when we mount the given dataset, not when the pool is
225  * imported. Taking this into account it is possible that the pool is imported
226  * without mounting datasets and the source dataset is destroyed before the
227  * destination dataset is mounted and its ZIL replayed.
228  * To address this situation we leverage zil_claim() mechanism where ZFS will
229  * parse all the ZILs on pool import. When we come across TX_CLONE_RANGE
230  * entries, we will bump reference counters for their BPs in the BRT.  Then
231  * on mount and ZIL replay we bump the reference counters once more, while the
232  * first references are dropped during ZIL destroy by zil_free_clone_range().
233  * It is possible that after zil_claim() we never mount the destination, so
234  * we never replay its ZIL and just destroy it.  In this case the only taken
235  * references will be dropped by zil_free_clone_range(), since the cloning is
236  * not going to ever take place.
237  */
238 
239 static kmem_cache_t *brt_entry_cache;
240 
241 /*
242  * Enable/disable prefetching of BRT entries that we are going to modify.
243  */
244 static int brt_zap_prefetch = 1;
245 
246 #ifdef ZFS_DEBUG
247 #define	BRT_DEBUG(...)	do {						\
248 	if ((zfs_flags & ZFS_DEBUG_BRT) != 0) {				\
249 		__dprintf(B_TRUE, __FILE__, __func__, __LINE__, __VA_ARGS__); \
250 	}								\
251 } while (0)
252 #else
253 #define	BRT_DEBUG(...)	do { } while (0)
254 #endif
255 
256 static int brt_zap_default_bs = 13;
257 static int brt_zap_default_ibs = 13;
258 
259 static kstat_t	*brt_ksp;
260 
261 typedef struct brt_stats {
262 	kstat_named_t brt_addref_entry_not_on_disk;
263 	kstat_named_t brt_addref_entry_on_disk;
264 	kstat_named_t brt_decref_entry_in_memory;
265 	kstat_named_t brt_decref_entry_loaded_from_disk;
266 	kstat_named_t brt_decref_entry_not_in_memory;
267 	kstat_named_t brt_decref_entry_read_lost_race;
268 	kstat_named_t brt_decref_entry_still_referenced;
269 	kstat_named_t brt_decref_free_data_later;
270 	kstat_named_t brt_decref_free_data_now;
271 	kstat_named_t brt_decref_no_entry;
272 } brt_stats_t;
273 
274 static brt_stats_t brt_stats = {
275 	{ "addref_entry_not_on_disk",		KSTAT_DATA_UINT64 },
276 	{ "addref_entry_on_disk",		KSTAT_DATA_UINT64 },
277 	{ "decref_entry_in_memory",		KSTAT_DATA_UINT64 },
278 	{ "decref_entry_loaded_from_disk",	KSTAT_DATA_UINT64 },
279 	{ "decref_entry_not_in_memory",		KSTAT_DATA_UINT64 },
280 	{ "decref_entry_read_lost_race",	KSTAT_DATA_UINT64 },
281 	{ "decref_entry_still_referenced",	KSTAT_DATA_UINT64 },
282 	{ "decref_free_data_later",		KSTAT_DATA_UINT64 },
283 	{ "decref_free_data_now",		KSTAT_DATA_UINT64 },
284 	{ "decref_no_entry",			KSTAT_DATA_UINT64 }
285 };
286 
287 struct {
288 	wmsum_t brt_addref_entry_not_on_disk;
289 	wmsum_t brt_addref_entry_on_disk;
290 	wmsum_t brt_decref_entry_in_memory;
291 	wmsum_t brt_decref_entry_loaded_from_disk;
292 	wmsum_t brt_decref_entry_not_in_memory;
293 	wmsum_t brt_decref_entry_read_lost_race;
294 	wmsum_t brt_decref_entry_still_referenced;
295 	wmsum_t brt_decref_free_data_later;
296 	wmsum_t brt_decref_free_data_now;
297 	wmsum_t brt_decref_no_entry;
298 } brt_sums;
299 
300 #define	BRTSTAT_BUMP(stat)	wmsum_add(&brt_sums.stat, 1)
301 
302 static int brt_entry_compare(const void *x1, const void *x2);
303 static void brt_vdevs_expand(spa_t *spa, uint64_t nvdevs);
304 
305 static void
brt_rlock(spa_t * spa)306 brt_rlock(spa_t *spa)
307 {
308 	rw_enter(&spa->spa_brt_lock, RW_READER);
309 }
310 
311 static void
brt_wlock(spa_t * spa)312 brt_wlock(spa_t *spa)
313 {
314 	rw_enter(&spa->spa_brt_lock, RW_WRITER);
315 }
316 
317 static void
brt_unlock(spa_t * spa)318 brt_unlock(spa_t *spa)
319 {
320 	rw_exit(&spa->spa_brt_lock);
321 }
322 
323 static uint16_t
brt_vdev_entcount_get(const brt_vdev_t * brtvd,uint64_t idx)324 brt_vdev_entcount_get(const brt_vdev_t *brtvd, uint64_t idx)
325 {
326 
327 	ASSERT3U(idx, <, brtvd->bv_size);
328 
329 	if (unlikely(brtvd->bv_need_byteswap)) {
330 		return (BSWAP_16(brtvd->bv_entcount[idx]));
331 	} else {
332 		return (brtvd->bv_entcount[idx]);
333 	}
334 }
335 
336 static void
brt_vdev_entcount_set(brt_vdev_t * brtvd,uint64_t idx,uint16_t entcnt)337 brt_vdev_entcount_set(brt_vdev_t *brtvd, uint64_t idx, uint16_t entcnt)
338 {
339 
340 	ASSERT3U(idx, <, brtvd->bv_size);
341 
342 	if (unlikely(brtvd->bv_need_byteswap)) {
343 		brtvd->bv_entcount[idx] = BSWAP_16(entcnt);
344 	} else {
345 		brtvd->bv_entcount[idx] = entcnt;
346 	}
347 }
348 
349 static void
brt_vdev_entcount_inc(brt_vdev_t * brtvd,uint64_t idx)350 brt_vdev_entcount_inc(brt_vdev_t *brtvd, uint64_t idx)
351 {
352 	uint16_t entcnt;
353 
354 	ASSERT3U(idx, <, brtvd->bv_size);
355 
356 	entcnt = brt_vdev_entcount_get(brtvd, idx);
357 	ASSERT(entcnt < UINT16_MAX);
358 
359 	brt_vdev_entcount_set(brtvd, idx, entcnt + 1);
360 }
361 
362 static void
brt_vdev_entcount_dec(brt_vdev_t * brtvd,uint64_t idx)363 brt_vdev_entcount_dec(brt_vdev_t *brtvd, uint64_t idx)
364 {
365 	uint16_t entcnt;
366 
367 	ASSERT3U(idx, <, brtvd->bv_size);
368 
369 	entcnt = brt_vdev_entcount_get(brtvd, idx);
370 	ASSERT(entcnt > 0);
371 
372 	brt_vdev_entcount_set(brtvd, idx, entcnt - 1);
373 }
374 
375 #ifdef ZFS_DEBUG
376 static void
brt_vdev_dump(brt_vdev_t * brtvd)377 brt_vdev_dump(brt_vdev_t *brtvd)
378 {
379 	uint64_t idx;
380 
381 	uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);
382 	zfs_dbgmsg("  BRT vdevid=%llu meta_dirty=%d entcount_dirty=%d "
383 	    "size=%llu totalcount=%llu nblocks=%llu bitmapsize=%zu",
384 	    (u_longlong_t)brtvd->bv_vdevid,
385 	    brtvd->bv_meta_dirty, brtvd->bv_entcount_dirty,
386 	    (u_longlong_t)brtvd->bv_size,
387 	    (u_longlong_t)brtvd->bv_totalcount,
388 	    (u_longlong_t)nblocks,
389 	    (size_t)BT_SIZEOFMAP(nblocks));
390 	if (brtvd->bv_totalcount > 0) {
391 		zfs_dbgmsg("    entcounts:");
392 		for (idx = 0; idx < brtvd->bv_size; idx++) {
393 			uint16_t entcnt = brt_vdev_entcount_get(brtvd, idx);
394 			if (entcnt > 0) {
395 				zfs_dbgmsg("      [%04llu] %hu",
396 				    (u_longlong_t)idx, entcnt);
397 			}
398 		}
399 	}
400 	if (brtvd->bv_entcount_dirty) {
401 		char *bitmap;
402 
403 		bitmap = kmem_alloc(nblocks + 1, KM_SLEEP);
404 		for (idx = 0; idx < nblocks; idx++) {
405 			bitmap[idx] =
406 			    BT_TEST(brtvd->bv_bitmap, idx) ? 'x' : '.';
407 		}
408 		bitmap[idx] = '\0';
409 		zfs_dbgmsg("    dirty: %s", bitmap);
410 		kmem_free(bitmap, nblocks + 1);
411 	}
412 }
413 #endif
414 
415 static brt_vdev_t *
brt_vdev(spa_t * spa,uint64_t vdevid,boolean_t alloc)416 brt_vdev(spa_t *spa, uint64_t vdevid, boolean_t alloc)
417 {
418 	brt_vdev_t *brtvd = NULL;
419 
420 	brt_rlock(spa);
421 	if (vdevid < spa->spa_brt_nvdevs) {
422 		brtvd = spa->spa_brt_vdevs[vdevid];
423 	} else if (alloc) {
424 		/* New VDEV was added. */
425 		brt_unlock(spa);
426 		brt_wlock(spa);
427 		if (vdevid >= spa->spa_brt_nvdevs)
428 			brt_vdevs_expand(spa, vdevid + 1);
429 		brtvd = spa->spa_brt_vdevs[vdevid];
430 	}
431 	brt_unlock(spa);
432 	return (brtvd);
433 }
434 
435 static void
brt_vdev_create(spa_t * spa,brt_vdev_t * brtvd,dmu_tx_t * tx)436 brt_vdev_create(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)
437 {
438 	char name[64];
439 
440 	ASSERT(brtvd->bv_initiated);
441 	ASSERT0(brtvd->bv_mos_brtvdev);
442 	ASSERT0(brtvd->bv_mos_entries);
443 
444 	uint64_t mos_entries = zap_create_flags(spa->spa_meta_objset, 0,
445 	    ZAP_FLAG_HASH64 | ZAP_FLAG_UINT64_KEY, DMU_OTN_ZAP_METADATA,
446 	    brt_zap_default_bs, brt_zap_default_ibs, DMU_OT_NONE, 0, tx);
447 	VERIFY(mos_entries != 0);
448 	VERIFY0(dnode_hold(spa->spa_meta_objset, mos_entries, brtvd,
449 	    &brtvd->bv_mos_entries_dnode));
450 	dnode_set_storage_type(brtvd->bv_mos_entries_dnode, DMU_OT_DDT_ZAP);
451 	rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);
452 	brtvd->bv_mos_entries = mos_entries;
453 	rw_exit(&brtvd->bv_mos_entries_lock);
454 	BRT_DEBUG("MOS entries created, object=%llu",
455 	    (u_longlong_t)brtvd->bv_mos_entries);
456 
457 	/*
458 	 * We allocate DMU buffer to store the bv_entcount[] array.
459 	 * We will keep array size (bv_size) and cummulative count for all
460 	 * bv_entcount[]s (bv_totalcount) in the bonus buffer.
461 	 */
462 	brtvd->bv_mos_brtvdev = dmu_object_alloc(spa->spa_meta_objset,
463 	    DMU_OTN_UINT64_METADATA, BRT_BLOCKSIZE,
464 	    DMU_OTN_UINT64_METADATA, sizeof (brt_vdev_phys_t), tx);
465 	VERIFY(brtvd->bv_mos_brtvdev != 0);
466 	BRT_DEBUG("MOS BRT VDEV created, object=%llu",
467 	    (u_longlong_t)brtvd->bv_mos_brtvdev);
468 
469 	snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,
470 	    (u_longlong_t)brtvd->bv_vdevid);
471 	VERIFY0(zap_add(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT, name,
472 	    sizeof (uint64_t), 1, &brtvd->bv_mos_brtvdev, tx));
473 	BRT_DEBUG("Pool directory object created, object=%s", name);
474 
475 	/*
476 	 * Activate the endian-fixed feature if this is the first BRT ZAP
477 	 * (i.e., BLOCK_CLONING is not yet active) and the feature is enabled.
478 	 */
479 	if (spa_feature_is_enabled(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN) &&
480 	    !spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
481 		spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);
482 	} else if (spa_feature_is_active(spa,
483 	    SPA_FEATURE_BLOCK_CLONING_ENDIAN)) {
484 		spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);
485 	}
486 
487 	spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING, tx);
488 }
489 
490 static void
brt_vdev_realloc(spa_t * spa,brt_vdev_t * brtvd)491 brt_vdev_realloc(spa_t *spa, brt_vdev_t *brtvd)
492 {
493 	vdev_t *vd;
494 	uint16_t *entcount;
495 	ulong_t *bitmap;
496 	uint64_t nblocks, onblocks, size;
497 
498 	ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));
499 
500 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
501 	vd = vdev_lookup_top(spa, brtvd->bv_vdevid);
502 	size = (vdev_get_min_asize(vd) - 1) / spa->spa_brt_rangesize + 1;
503 	spa_config_exit(spa, SCL_VDEV, FTAG);
504 
505 	nblocks = BRT_RANGESIZE_TO_NBLOCKS(size);
506 	entcount = vmem_zalloc(nblocks * BRT_BLOCKSIZE, KM_SLEEP);
507 	bitmap = kmem_zalloc(BT_SIZEOFMAP(nblocks), KM_SLEEP);
508 
509 	if (!brtvd->bv_initiated) {
510 		ASSERT0(brtvd->bv_size);
511 		ASSERT0P(brtvd->bv_entcount);
512 		ASSERT0P(brtvd->bv_bitmap);
513 	} else {
514 		ASSERT(brtvd->bv_size > 0);
515 		ASSERT(brtvd->bv_entcount != NULL);
516 		ASSERT(brtvd->bv_bitmap != NULL);
517 		/*
518 		 * TODO: Allow vdev shrinking. We only need to implement
519 		 * shrinking the on-disk BRT VDEV object.
520 		 * dmu_free_range(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,
521 		 *     offset, size, tx);
522 		 */
523 		ASSERT3U(brtvd->bv_size, <=, size);
524 
525 		memcpy(entcount, brtvd->bv_entcount,
526 		    sizeof (entcount[0]) * MIN(size, brtvd->bv_size));
527 		onblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);
528 		vmem_free(brtvd->bv_entcount, onblocks * BRT_BLOCKSIZE);
529 		memcpy(bitmap, brtvd->bv_bitmap, MIN(BT_SIZEOFMAP(nblocks),
530 		    BT_SIZEOFMAP(onblocks)));
531 		kmem_free(brtvd->bv_bitmap, BT_SIZEOFMAP(onblocks));
532 	}
533 
534 	brtvd->bv_size = size;
535 	brtvd->bv_entcount = entcount;
536 	brtvd->bv_bitmap = bitmap;
537 	if (!brtvd->bv_initiated) {
538 		brtvd->bv_need_byteswap = FALSE;
539 		brtvd->bv_initiated = TRUE;
540 		BRT_DEBUG("BRT VDEV %llu initiated.",
541 		    (u_longlong_t)brtvd->bv_vdevid);
542 	}
543 }
544 
545 static int
brt_vdev_load(spa_t * spa,brt_vdev_t * brtvd)546 brt_vdev_load(spa_t *spa, brt_vdev_t *brtvd)
547 {
548 	dmu_buf_t *db;
549 	brt_vdev_phys_t *bvphys;
550 	int error;
551 
552 	ASSERT(!brtvd->bv_initiated);
553 	ASSERT(brtvd->bv_mos_brtvdev != 0);
554 
555 	error = dmu_bonus_hold(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,
556 	    FTAG, &db);
557 	if (error != 0)
558 		return (error);
559 
560 	bvphys = db->db_data;
561 	if (spa->spa_brt_rangesize == 0) {
562 		spa->spa_brt_rangesize = bvphys->bvp_rangesize;
563 	} else {
564 		ASSERT3U(spa->spa_brt_rangesize, ==, bvphys->bvp_rangesize);
565 	}
566 
567 	brt_vdev_realloc(spa, brtvd);
568 
569 	/* TODO: We don't support VDEV shrinking. */
570 	ASSERT3U(bvphys->bvp_size, <=, brtvd->bv_size);
571 
572 	/*
573 	 * If VDEV grew, we will leave new bv_entcount[] entries zeroed out.
574 	 */
575 	error = dmu_read(spa->spa_meta_objset, brtvd->bv_mos_brtvdev, 0,
576 	    MIN(brtvd->bv_size, bvphys->bvp_size) * sizeof (uint16_t),
577 	    brtvd->bv_entcount, DMU_READ_NO_PREFETCH | DMU_UNCACHEDIO);
578 	if (error != 0) {
579 		dmu_buf_rele(db, FTAG);
580 		return (error);
581 	}
582 
583 	ASSERT(bvphys->bvp_mos_entries != 0);
584 	VERIFY0(dnode_hold(spa->spa_meta_objset, bvphys->bvp_mos_entries, brtvd,
585 	    &brtvd->bv_mos_entries_dnode));
586 	dnode_set_storage_type(brtvd->bv_mos_entries_dnode, DMU_OT_DDT_ZAP);
587 	rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);
588 	brtvd->bv_mos_entries = bvphys->bvp_mos_entries;
589 	rw_exit(&brtvd->bv_mos_entries_lock);
590 	brtvd->bv_need_byteswap =
591 	    (bvphys->bvp_byteorder != BRT_NATIVE_BYTEORDER);
592 	brtvd->bv_totalcount = bvphys->bvp_totalcount;
593 	brtvd->bv_usedspace = bvphys->bvp_usedspace;
594 	brtvd->bv_savedspace = bvphys->bvp_savedspace;
595 
596 	dmu_buf_rele(db, FTAG);
597 
598 	BRT_DEBUG("BRT VDEV %llu loaded: mos_brtvdev=%llu, mos_entries=%llu",
599 	    (u_longlong_t)brtvd->bv_vdevid,
600 	    (u_longlong_t)brtvd->bv_mos_brtvdev,
601 	    (u_longlong_t)brtvd->bv_mos_entries);
602 	return (0);
603 }
604 
605 static void
brt_vdev_dealloc(brt_vdev_t * brtvd)606 brt_vdev_dealloc(brt_vdev_t *brtvd)
607 {
608 	ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));
609 	ASSERT(brtvd->bv_initiated);
610 	ASSERT0(avl_numnodes(&brtvd->bv_tree));
611 
612 	uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);
613 	vmem_free(brtvd->bv_entcount, nblocks * BRT_BLOCKSIZE);
614 	brtvd->bv_entcount = NULL;
615 	kmem_free(brtvd->bv_bitmap, BT_SIZEOFMAP(nblocks));
616 	brtvd->bv_bitmap = NULL;
617 
618 	brtvd->bv_size = 0;
619 
620 	brtvd->bv_initiated = FALSE;
621 	BRT_DEBUG("BRT VDEV %llu deallocated.", (u_longlong_t)brtvd->bv_vdevid);
622 }
623 
624 static void
brt_vdev_destroy(spa_t * spa,brt_vdev_t * brtvd,dmu_tx_t * tx)625 brt_vdev_destroy(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)
626 {
627 	char name[64];
628 	uint64_t count;
629 
630 	ASSERT(brtvd->bv_initiated);
631 	ASSERT(brtvd->bv_mos_brtvdev != 0);
632 	ASSERT(brtvd->bv_mos_entries != 0);
633 	ASSERT0(brtvd->bv_totalcount);
634 	ASSERT0(brtvd->bv_usedspace);
635 	ASSERT0(brtvd->bv_savedspace);
636 
637 	uint64_t mos_entries = brtvd->bv_mos_entries;
638 	rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);
639 	brtvd->bv_mos_entries = 0;
640 	rw_exit(&brtvd->bv_mos_entries_lock);
641 	dnode_rele(brtvd->bv_mos_entries_dnode, brtvd);
642 	brtvd->bv_mos_entries_dnode = NULL;
643 	ASSERT0(zap_count(spa->spa_meta_objset, mos_entries, &count));
644 	ASSERT0(count);
645 	VERIFY0(zap_destroy(spa->spa_meta_objset, mos_entries, tx));
646 	BRT_DEBUG("MOS entries destroyed, object=%llu",
647 	    (u_longlong_t)mos_entries);
648 
649 	VERIFY0(dmu_object_free(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,
650 	    tx));
651 	BRT_DEBUG("MOS BRT VDEV destroyed, object=%llu",
652 	    (u_longlong_t)brtvd->bv_mos_brtvdev);
653 	brtvd->bv_mos_brtvdev = 0;
654 	brtvd->bv_entcount_dirty = FALSE;
655 
656 	snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,
657 	    (u_longlong_t)brtvd->bv_vdevid);
658 	VERIFY0(zap_remove(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
659 	    name, tx));
660 	BRT_DEBUG("Pool directory object removed, object=%s", name);
661 
662 	brtvd->bv_meta_dirty = FALSE;
663 
664 	rw_enter(&brtvd->bv_lock, RW_WRITER);
665 	brt_vdev_dealloc(brtvd);
666 	rw_exit(&brtvd->bv_lock);
667 
668 	spa_feature_decr(spa, SPA_FEATURE_BLOCK_CLONING, tx);
669 	if (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN))
670 		spa_feature_decr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);
671 }
672 
673 static void
brt_vdevs_expand(spa_t * spa,uint64_t nvdevs)674 brt_vdevs_expand(spa_t *spa, uint64_t nvdevs)
675 {
676 	brt_vdev_t **vdevs;
677 
678 	ASSERT(RW_WRITE_HELD(&spa->spa_brt_lock));
679 	ASSERT3U(nvdevs, >=, spa->spa_brt_nvdevs);
680 
681 	if (nvdevs == spa->spa_brt_nvdevs)
682 		return;
683 
684 	vdevs = kmem_zalloc(sizeof (*spa->spa_brt_vdevs) * nvdevs, KM_SLEEP);
685 	if (spa->spa_brt_nvdevs > 0) {
686 		ASSERT(spa->spa_brt_vdevs != NULL);
687 
688 		memcpy(vdevs, spa->spa_brt_vdevs,
689 		    sizeof (*spa->spa_brt_vdevs) * spa->spa_brt_nvdevs);
690 		kmem_free(spa->spa_brt_vdevs,
691 		    sizeof (*spa->spa_brt_vdevs) * spa->spa_brt_nvdevs);
692 	}
693 	spa->spa_brt_vdevs = vdevs;
694 
695 	for (uint64_t vdevid = spa->spa_brt_nvdevs; vdevid < nvdevs; vdevid++) {
696 		brt_vdev_t *brtvd = kmem_zalloc(sizeof (*brtvd), KM_SLEEP);
697 		rw_init(&brtvd->bv_lock, NULL, RW_DEFAULT, NULL);
698 		brtvd->bv_vdevid = vdevid;
699 		brtvd->bv_initiated = FALSE;
700 		rw_init(&brtvd->bv_mos_entries_lock, NULL, RW_DEFAULT, NULL);
701 		avl_create(&brtvd->bv_tree, brt_entry_compare,
702 		    sizeof (brt_entry_t), offsetof(brt_entry_t, bre_node));
703 		for (int i = 0; i < TXG_SIZE; i++) {
704 			avl_create(&brtvd->bv_pending_tree[i],
705 			    brt_entry_compare, sizeof (brt_entry_t),
706 			    offsetof(brt_entry_t, bre_node));
707 		}
708 		mutex_init(&brtvd->bv_pending_lock, NULL, MUTEX_DEFAULT, NULL);
709 		spa->spa_brt_vdevs[vdevid] = brtvd;
710 	}
711 
712 	BRT_DEBUG("BRT VDEVs expanded from %llu to %llu.",
713 	    (u_longlong_t)spa->spa_brt_nvdevs, (u_longlong_t)nvdevs);
714 	spa->spa_brt_nvdevs = nvdevs;
715 }
716 
717 static boolean_t
brt_vdev_lookup(spa_t * spa,brt_vdev_t * brtvd,uint64_t offset)718 brt_vdev_lookup(spa_t *spa, brt_vdev_t *brtvd, uint64_t offset)
719 {
720 	uint64_t idx = offset / spa->spa_brt_rangesize;
721 	if (idx < brtvd->bv_size) {
722 		/* VDEV wasn't expanded. */
723 		return (brt_vdev_entcount_get(brtvd, idx) > 0);
724 	}
725 	return (FALSE);
726 }
727 
728 static void
brt_vdev_addref(spa_t * spa,brt_vdev_t * brtvd,const brt_entry_t * bre,uint64_t dsize,uint64_t count)729 brt_vdev_addref(spa_t *spa, brt_vdev_t *brtvd, const brt_entry_t *bre,
730     uint64_t dsize, uint64_t count)
731 {
732 	uint64_t idx;
733 
734 	ASSERT(brtvd->bv_initiated);
735 
736 	brtvd->bv_savedspace += dsize * count;
737 	brtvd->bv_meta_dirty = TRUE;
738 
739 	if (bre->bre_count > 0)
740 		return;
741 
742 	brtvd->bv_usedspace += dsize;
743 
744 	idx = BRE_OFFSET(bre) / spa->spa_brt_rangesize;
745 	if (idx >= brtvd->bv_size) {
746 		/* VDEV has been expanded. */
747 		rw_enter(&brtvd->bv_lock, RW_WRITER);
748 		brt_vdev_realloc(spa, brtvd);
749 		rw_exit(&brtvd->bv_lock);
750 	}
751 
752 	ASSERT3U(idx, <, brtvd->bv_size);
753 
754 	brtvd->bv_totalcount++;
755 	brt_vdev_entcount_inc(brtvd, idx);
756 	brtvd->bv_entcount_dirty = TRUE;
757 	BT_SET(brtvd->bv_bitmap, idx / (BRT_BLOCKSIZE / sizeof (uint16_t)));
758 }
759 
760 static void
brt_vdev_decref(spa_t * spa,brt_vdev_t * brtvd,const brt_entry_t * bre,uint64_t dsize)761 brt_vdev_decref(spa_t *spa, brt_vdev_t *brtvd, const brt_entry_t *bre,
762     uint64_t dsize)
763 {
764 	uint64_t idx;
765 
766 	ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));
767 	ASSERT(brtvd->bv_initiated);
768 
769 	brtvd->bv_savedspace -= dsize;
770 	brtvd->bv_meta_dirty = TRUE;
771 
772 	if (bre->bre_count > 0)
773 		return;
774 
775 	brtvd->bv_usedspace -= dsize;
776 
777 	idx = BRE_OFFSET(bre) / spa->spa_brt_rangesize;
778 	ASSERT3U(idx, <, brtvd->bv_size);
779 
780 	ASSERT(brtvd->bv_totalcount > 0);
781 	brtvd->bv_totalcount--;
782 	brt_vdev_entcount_dec(brtvd, idx);
783 	brtvd->bv_entcount_dirty = TRUE;
784 	BT_SET(brtvd->bv_bitmap, idx / (BRT_BLOCKSIZE / sizeof (uint16_t)));
785 }
786 
787 static void
brt_vdev_sync(spa_t * spa,brt_vdev_t * brtvd,dmu_tx_t * tx)788 brt_vdev_sync(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)
789 {
790 	dmu_buf_t *db;
791 	brt_vdev_phys_t *bvphys;
792 
793 	ASSERT(brtvd->bv_meta_dirty);
794 	ASSERT(brtvd->bv_mos_brtvdev != 0);
795 	ASSERT(dmu_tx_is_syncing(tx));
796 
797 	VERIFY0(dmu_bonus_hold(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,
798 	    FTAG, &db));
799 
800 	if (brtvd->bv_entcount_dirty) {
801 		uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);
802 		for (uint64_t i = 0; i < nblocks; i++) {
803 			if (!BT_TEST(brtvd->bv_bitmap, i))
804 				continue;
805 			uint64_t end = i + 1;
806 			uint64_t maxend = MIN(i + DMU_MAX_ACCESS / 2 /
807 			    BRT_BLOCKSIZE, nblocks);
808 			while (end < maxend && BT_TEST(brtvd->bv_bitmap, end))
809 				end++;
810 			dmu_write(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,
811 			    i * BRT_BLOCKSIZE, (end - i) * BRT_BLOCKSIZE,
812 			    (char *)brtvd->bv_entcount + i * BRT_BLOCKSIZE,
813 			    tx, DMU_READ_NO_PREFETCH | DMU_UNCACHEDIO);
814 			i = end - 1;
815 		}
816 		memset(brtvd->bv_bitmap, 0, BT_SIZEOFMAP(nblocks));
817 		brtvd->bv_entcount_dirty = FALSE;
818 	}
819 
820 	dmu_buf_will_dirty(db, tx);
821 	bvphys = db->db_data;
822 	bvphys->bvp_mos_entries = brtvd->bv_mos_entries;
823 	bvphys->bvp_size = brtvd->bv_size;
824 	if (brtvd->bv_need_byteswap) {
825 		bvphys->bvp_byteorder = BRT_NON_NATIVE_BYTEORDER;
826 	} else {
827 		bvphys->bvp_byteorder = BRT_NATIVE_BYTEORDER;
828 	}
829 	bvphys->bvp_totalcount = brtvd->bv_totalcount;
830 	bvphys->bvp_rangesize = spa->spa_brt_rangesize;
831 	bvphys->bvp_usedspace = brtvd->bv_usedspace;
832 	bvphys->bvp_savedspace = brtvd->bv_savedspace;
833 	dmu_buf_rele(db, FTAG);
834 
835 	brtvd->bv_meta_dirty = FALSE;
836 }
837 
838 static void
brt_vdevs_free(spa_t * spa)839 brt_vdevs_free(spa_t *spa)
840 {
841 	if (spa->spa_brt_vdevs == 0)
842 		return;
843 	for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {
844 		brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];
845 		rw_enter(&brtvd->bv_lock, RW_WRITER);
846 		if (brtvd->bv_initiated)
847 			brt_vdev_dealloc(brtvd);
848 		rw_exit(&brtvd->bv_lock);
849 		rw_destroy(&brtvd->bv_lock);
850 		if (brtvd->bv_mos_entries != 0)
851 			dnode_rele(brtvd->bv_mos_entries_dnode, brtvd);
852 		rw_destroy(&brtvd->bv_mos_entries_lock);
853 		avl_destroy(&brtvd->bv_tree);
854 		for (int i = 0; i < TXG_SIZE; i++)
855 			avl_destroy(&brtvd->bv_pending_tree[i]);
856 		mutex_destroy(&brtvd->bv_pending_lock);
857 		kmem_free(brtvd, sizeof (*brtvd));
858 	}
859 	kmem_free(spa->spa_brt_vdevs, sizeof (*spa->spa_brt_vdevs) *
860 	    spa->spa_brt_nvdevs);
861 }
862 
863 static void
brt_entry_fill(const blkptr_t * bp,brt_entry_t * bre,uint64_t * vdevidp)864 brt_entry_fill(const blkptr_t *bp, brt_entry_t *bre, uint64_t *vdevidp)
865 {
866 
867 	bre->bre_bp = *bp;
868 	bre->bre_count = 0;
869 	bre->bre_pcount = 0;
870 
871 	*vdevidp = DVA_GET_VDEV(&bp->blk_dva[0]);
872 }
873 
874 static boolean_t
brt_has_endian_fixed(spa_t * spa)875 brt_has_endian_fixed(spa_t *spa)
876 {
877 	return (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN));
878 }
879 
880 static int
brt_entry_lookup(spa_t * spa,brt_vdev_t * brtvd,brt_entry_t * bre)881 brt_entry_lookup(spa_t *spa, brt_vdev_t *brtvd, brt_entry_t *bre)
882 {
883 	uint64_t off = BRE_OFFSET(bre);
884 
885 	if (brtvd->bv_mos_entries == 0)
886 		return (SET_ERROR(ENOENT));
887 
888 	if (brt_has_endian_fixed(spa)) {
889 		return (zap_lookup_uint64_by_dnode(brtvd->bv_mos_entries_dnode,
890 		    &off, BRT_KEY_WORDS, sizeof (bre->bre_count), 1,
891 		    &bre->bre_count));
892 	} else {
893 		return (zap_lookup_uint64_by_dnode(brtvd->bv_mos_entries_dnode,
894 		    &off, BRT_KEY_WORDS, 1, sizeof (bre->bre_count),
895 		    &bre->bre_count));
896 	}
897 }
898 
899 /*
900  * Return TRUE if we _can_ have BRT entry for this bp. It might be false
901  * positive, but gives us quick answer if we should look into BRT, which
902  * may require reads and thus will be more expensive.
903  */
904 boolean_t
brt_maybe_exists(spa_t * spa,const blkptr_t * bp)905 brt_maybe_exists(spa_t *spa, const blkptr_t *bp)
906 {
907 
908 	if (spa->spa_brt_nvdevs == 0)
909 		return (B_FALSE);
910 
911 	uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);
912 	brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);
913 	if (brtvd == NULL || !brtvd->bv_initiated)
914 		return (FALSE);
915 
916 	/*
917 	 * We don't need locks here, since bv_entcount pointer must be
918 	 * stable at this point, and we don't care about false positive
919 	 * races here, while false negative should be impossible, since
920 	 * all brt_vdev_addref() have already completed by this point.
921 	 */
922 	uint64_t off = DVA_GET_OFFSET(&bp->blk_dva[0]);
923 	return (brt_vdev_lookup(spa, brtvd, off));
924 }
925 
926 /*
927  * Estimate the worst-case amount of MOS data the sync thread may dirty
928  * to add, update or remove one BRT entry: one ZAP leaf block.  Unlike
929  * the DDT, BRT ZAPs do not use prehashed keys, so even consecutive
930  * offsets scatter across leaves and rarely combine.
931  */
932 uint64_t
brt_sync_dirty_est(spa_t * spa)933 brt_sync_dirty_est(spa_t *spa)
934 {
935 	(void) spa;
936 	return (1ULL << brt_zap_default_bs);
937 }
938 
939 uint64_t
brt_get_dspace(spa_t * spa)940 brt_get_dspace(spa_t *spa)
941 {
942 	if (spa->spa_brt_nvdevs == 0)
943 		return (0);
944 
945 	brt_rlock(spa);
946 	uint64_t s = 0;
947 	for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++)
948 		s += spa->spa_brt_vdevs[vdevid]->bv_savedspace;
949 	brt_unlock(spa);
950 	return (s);
951 }
952 
953 uint64_t
brt_get_used(spa_t * spa)954 brt_get_used(spa_t *spa)
955 {
956 	if (spa->spa_brt_nvdevs == 0)
957 		return (0);
958 
959 	brt_rlock(spa);
960 	uint64_t s = 0;
961 	for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++)
962 		s += spa->spa_brt_vdevs[vdevid]->bv_usedspace;
963 	brt_unlock(spa);
964 	return (s);
965 }
966 
967 uint64_t
brt_get_saved(spa_t * spa)968 brt_get_saved(spa_t *spa)
969 {
970 	return (brt_get_dspace(spa));
971 }
972 
973 uint64_t
brt_get_ratio(spa_t * spa)974 brt_get_ratio(spa_t *spa)
975 {
976 	uint64_t used = brt_get_used(spa);
977 	if (used == 0)
978 		return (100);
979 	return ((used + brt_get_saved(spa)) * 100 / used);
980 }
981 
982 static int
brt_kstats_update(kstat_t * ksp,int rw)983 brt_kstats_update(kstat_t *ksp, int rw)
984 {
985 	brt_stats_t *bs = ksp->ks_data;
986 
987 	if (rw == KSTAT_WRITE)
988 		return (EACCES);
989 
990 	bs->brt_addref_entry_not_on_disk.value.ui64 =
991 	    wmsum_value(&brt_sums.brt_addref_entry_not_on_disk);
992 	bs->brt_addref_entry_on_disk.value.ui64 =
993 	    wmsum_value(&brt_sums.brt_addref_entry_on_disk);
994 	bs->brt_decref_entry_in_memory.value.ui64 =
995 	    wmsum_value(&brt_sums.brt_decref_entry_in_memory);
996 	bs->brt_decref_entry_loaded_from_disk.value.ui64 =
997 	    wmsum_value(&brt_sums.brt_decref_entry_loaded_from_disk);
998 	bs->brt_decref_entry_not_in_memory.value.ui64 =
999 	    wmsum_value(&brt_sums.brt_decref_entry_not_in_memory);
1000 	bs->brt_decref_entry_read_lost_race.value.ui64 =
1001 	    wmsum_value(&brt_sums.brt_decref_entry_read_lost_race);
1002 	bs->brt_decref_entry_still_referenced.value.ui64 =
1003 	    wmsum_value(&brt_sums.brt_decref_entry_still_referenced);
1004 	bs->brt_decref_free_data_later.value.ui64 =
1005 	    wmsum_value(&brt_sums.brt_decref_free_data_later);
1006 	bs->brt_decref_free_data_now.value.ui64 =
1007 	    wmsum_value(&brt_sums.brt_decref_free_data_now);
1008 	bs->brt_decref_no_entry.value.ui64 =
1009 	    wmsum_value(&brt_sums.brt_decref_no_entry);
1010 
1011 	return (0);
1012 }
1013 
1014 static void
brt_stat_init(void)1015 brt_stat_init(void)
1016 {
1017 
1018 	wmsum_init(&brt_sums.brt_addref_entry_not_on_disk, 0);
1019 	wmsum_init(&brt_sums.brt_addref_entry_on_disk, 0);
1020 	wmsum_init(&brt_sums.brt_decref_entry_in_memory, 0);
1021 	wmsum_init(&brt_sums.brt_decref_entry_loaded_from_disk, 0);
1022 	wmsum_init(&brt_sums.brt_decref_entry_not_in_memory, 0);
1023 	wmsum_init(&brt_sums.brt_decref_entry_read_lost_race, 0);
1024 	wmsum_init(&brt_sums.brt_decref_entry_still_referenced, 0);
1025 	wmsum_init(&brt_sums.brt_decref_free_data_later, 0);
1026 	wmsum_init(&brt_sums.brt_decref_free_data_now, 0);
1027 	wmsum_init(&brt_sums.brt_decref_no_entry, 0);
1028 
1029 	brt_ksp = kstat_create("zfs", 0, "brtstats", "misc", KSTAT_TYPE_NAMED,
1030 	    sizeof (brt_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
1031 	if (brt_ksp != NULL) {
1032 		brt_ksp->ks_data = &brt_stats;
1033 		brt_ksp->ks_update = brt_kstats_update;
1034 		kstat_install(brt_ksp);
1035 	}
1036 }
1037 
1038 static void
brt_stat_fini(void)1039 brt_stat_fini(void)
1040 {
1041 	if (brt_ksp != NULL) {
1042 		kstat_delete(brt_ksp);
1043 		brt_ksp = NULL;
1044 	}
1045 
1046 	wmsum_fini(&brt_sums.brt_addref_entry_not_on_disk);
1047 	wmsum_fini(&brt_sums.brt_addref_entry_on_disk);
1048 	wmsum_fini(&brt_sums.brt_decref_entry_in_memory);
1049 	wmsum_fini(&brt_sums.brt_decref_entry_loaded_from_disk);
1050 	wmsum_fini(&brt_sums.brt_decref_entry_not_in_memory);
1051 	wmsum_fini(&brt_sums.brt_decref_entry_read_lost_race);
1052 	wmsum_fini(&brt_sums.brt_decref_entry_still_referenced);
1053 	wmsum_fini(&brt_sums.brt_decref_free_data_later);
1054 	wmsum_fini(&brt_sums.brt_decref_free_data_now);
1055 	wmsum_fini(&brt_sums.brt_decref_no_entry);
1056 }
1057 
1058 void
brt_init(void)1059 brt_init(void)
1060 {
1061 	brt_entry_cache = kmem_cache_create("brt_entry_cache",
1062 	    sizeof (brt_entry_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
1063 
1064 	brt_stat_init();
1065 }
1066 
1067 void
brt_fini(void)1068 brt_fini(void)
1069 {
1070 	brt_stat_fini();
1071 
1072 	kmem_cache_destroy(brt_entry_cache);
1073 }
1074 
1075 /* Return TRUE if block should be freed immediately. */
1076 boolean_t
brt_entry_decref(spa_t * spa,const blkptr_t * bp)1077 brt_entry_decref(spa_t *spa, const blkptr_t *bp)
1078 {
1079 	brt_entry_t *bre, *racebre;
1080 	brt_entry_t bre_search;
1081 	avl_index_t where;
1082 	uint64_t vdevid;
1083 	int error;
1084 
1085 	brt_entry_fill(bp, &bre_search, &vdevid);
1086 
1087 	brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);
1088 	ASSERT(brtvd != NULL);
1089 
1090 	rw_enter(&brtvd->bv_lock, RW_WRITER);
1091 	ASSERT(brtvd->bv_initiated);
1092 	bre = avl_find(&brtvd->bv_tree, &bre_search, NULL);
1093 	if (bre != NULL) {
1094 		BRTSTAT_BUMP(brt_decref_entry_in_memory);
1095 		goto out;
1096 	} else {
1097 		BRTSTAT_BUMP(brt_decref_entry_not_in_memory);
1098 	}
1099 	rw_exit(&brtvd->bv_lock);
1100 
1101 	error = brt_entry_lookup(spa, brtvd, &bre_search);
1102 	/* bre_search now contains correct bre_count */
1103 	if (error == ENOENT) {
1104 		BRTSTAT_BUMP(brt_decref_no_entry);
1105 		return (B_TRUE);
1106 	}
1107 	ASSERT0(error);
1108 
1109 	rw_enter(&brtvd->bv_lock, RW_WRITER);
1110 	racebre = avl_find(&brtvd->bv_tree, &bre_search, &where);
1111 	if (racebre != NULL) {
1112 		/* The entry was added when the lock was dropped. */
1113 		BRTSTAT_BUMP(brt_decref_entry_read_lost_race);
1114 		bre = racebre;
1115 		goto out;
1116 	}
1117 
1118 	BRTSTAT_BUMP(brt_decref_entry_loaded_from_disk);
1119 	bre = kmem_cache_alloc(brt_entry_cache, KM_SLEEP);
1120 	bre->bre_bp = bre_search.bre_bp;
1121 	bre->bre_count = bre_search.bre_count;
1122 	bre->bre_pcount = 0;
1123 	avl_insert(&brtvd->bv_tree, bre, where);
1124 
1125 out:
1126 	if (bre->bre_count == 0) {
1127 		rw_exit(&brtvd->bv_lock);
1128 		BRTSTAT_BUMP(brt_decref_free_data_now);
1129 		return (B_TRUE);
1130 	}
1131 
1132 	bre->bre_pcount--;
1133 	ASSERT(bre->bre_count > 0);
1134 	bre->bre_count--;
1135 	if (bre->bre_count == 0)
1136 		BRTSTAT_BUMP(brt_decref_free_data_later);
1137 	else
1138 		BRTSTAT_BUMP(brt_decref_entry_still_referenced);
1139 	brt_vdev_decref(spa, brtvd, bre, bp_get_dsize_sync(spa, bp));
1140 
1141 	rw_exit(&brtvd->bv_lock);
1142 
1143 	return (B_FALSE);
1144 }
1145 
1146 uint64_t
brt_entry_get_refcount(spa_t * spa,const blkptr_t * bp)1147 brt_entry_get_refcount(spa_t *spa, const blkptr_t *bp)
1148 {
1149 	brt_entry_t bre_search, *bre;
1150 	uint64_t vdevid, refcnt;
1151 	int error;
1152 
1153 	brt_entry_fill(bp, &bre_search, &vdevid);
1154 
1155 	brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);
1156 	ASSERT(brtvd != NULL);
1157 
1158 	rw_enter(&brtvd->bv_lock, RW_READER);
1159 	ASSERT(brtvd->bv_initiated);
1160 	bre = avl_find(&brtvd->bv_tree, &bre_search, NULL);
1161 	if (bre == NULL) {
1162 		rw_exit(&brtvd->bv_lock);
1163 		error = brt_entry_lookup(spa, brtvd, &bre_search);
1164 		if (error == ENOENT) {
1165 			refcnt = 0;
1166 		} else {
1167 			ASSERT0(error);
1168 			refcnt = bre_search.bre_count;
1169 		}
1170 	} else {
1171 		refcnt = bre->bre_count;
1172 		rw_exit(&brtvd->bv_lock);
1173 	}
1174 
1175 	return (refcnt);
1176 }
1177 
1178 static void
brt_prefetch(brt_vdev_t * brtvd,const blkptr_t * bp)1179 brt_prefetch(brt_vdev_t *brtvd, const blkptr_t *bp)
1180 {
1181 	if (!brt_zap_prefetch || brtvd->bv_mos_entries == 0)
1182 		return;
1183 
1184 	uint64_t off = DVA_GET_OFFSET(&bp->blk_dva[0]);
1185 	rw_enter(&brtvd->bv_mos_entries_lock, RW_READER);
1186 	if (brtvd->bv_mos_entries != 0) {
1187 		(void) zap_prefetch_uint64_by_dnode(brtvd->bv_mos_entries_dnode,
1188 		    &off, BRT_KEY_WORDS);
1189 	}
1190 	rw_exit(&brtvd->bv_mos_entries_lock);
1191 }
1192 
1193 static int
brt_entry_compare(const void * x1,const void * x2)1194 brt_entry_compare(const void *x1, const void *x2)
1195 {
1196 	const brt_entry_t *bre1 = x1, *bre2 = x2;
1197 	const blkptr_t *bp1 = &bre1->bre_bp, *bp2 = &bre2->bre_bp;
1198 
1199 	return (TREE_CMP(DVA_GET_OFFSET(&bp1->blk_dva[0]),
1200 	    DVA_GET_OFFSET(&bp2->blk_dva[0])));
1201 }
1202 
1203 static int
brt_entry_dedup_compare(const void * x1,const void * x2)1204 brt_entry_dedup_compare(const void *x1, const void *x2)
1205 {
1206 	const brt_entry_t *bre1 = x1, *bre2 = x2;
1207 	const blkptr_t *bp1 = &bre1->bre_bp, *bp2 = &bre2->bre_bp;
1208 	const uint64_t *k1 = bp1->blk_cksum.zc_word;
1209 	const uint64_t *k2 = bp2->blk_cksum.zc_word;
1210 	int cmp;
1211 
1212 	/* Sort by the checksum, matching the DDT ZAP hash order. */
1213 	for (int i = 0; i < (sizeof (zio_cksum_t) / sizeof (uint64_t)); i++) {
1214 		if (likely((cmp = TREE_CMP(k1[i], k2[i])) != 0))
1215 			return (cmp);
1216 	}
1217 
1218 	/*
1219 	 * The same checksum may reference different blocks if the DDT
1220 	 * entry for the older one was pruned.
1221 	 */
1222 	cmp = TREE_CMP(DVA_GET_VDEV(&bp1->blk_dva[0]),
1223 	    DVA_GET_VDEV(&bp2->blk_dva[0]));
1224 	if (likely(cmp == 0)) {
1225 		cmp = TREE_CMP(DVA_GET_OFFSET(&bp1->blk_dva[0]),
1226 		    DVA_GET_OFFSET(&bp2->blk_dva[0]));
1227 	}
1228 	return (cmp);
1229 }
1230 
1231 void
brt_pending_add(spa_t * spa,const blkptr_t * bp,dmu_tx_t * tx)1232 brt_pending_add(spa_t *spa, const blkptr_t *bp, dmu_tx_t *tx)
1233 {
1234 	brt_entry_t *bre, *newbre;
1235 	avl_index_t where;
1236 	uint64_t txg;
1237 
1238 	txg = dmu_tx_get_txg(tx);
1239 	ASSERT3U(txg, !=, 0);
1240 
1241 	newbre = kmem_cache_alloc(brt_entry_cache, KM_SLEEP);
1242 	newbre->bre_bp = *bp;
1243 	newbre->bre_count = 0;
1244 	newbre->bre_pcount = 1;
1245 
1246 	/*
1247 	 * Blocks with the DEDUP bit set are referenced in the DDT instead
1248 	 * of the BRT and are kept on separate trees until then.
1249 	 */
1250 	if (BP_GET_DEDUP(bp)) {
1251 		brt_dedup_shard_t *bds =
1252 		    &spa->spa_brt_dedup[BRT_DEDUP_SHARD(bp)];
1253 		avl_tree_t *pending_tree = &bds->bds_tree[txg & TXG_MASK];
1254 
1255 		mutex_enter(&bds->bds_lock);
1256 		bre = avl_find(pending_tree, newbre, &where);
1257 		if (bre == NULL) {
1258 			avl_insert(pending_tree, newbre, where);
1259 			newbre = NULL;
1260 		} else {
1261 			bre->bre_pcount++;
1262 		}
1263 		mutex_exit(&bds->bds_lock);
1264 
1265 		if (newbre != NULL) {
1266 			kmem_cache_free(brt_entry_cache, newbre);
1267 		} else {
1268 			/* Prefetch DDT entry for the syncing context. */
1269 			ddt_prefetch(spa, bp);
1270 		}
1271 		return;
1272 	}
1273 
1274 	uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);
1275 	brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_TRUE);
1276 	avl_tree_t *pending_tree = &brtvd->bv_pending_tree[txg & TXG_MASK];
1277 
1278 	mutex_enter(&brtvd->bv_pending_lock);
1279 	bre = avl_find(pending_tree, newbre, &where);
1280 	if (bre == NULL) {
1281 		avl_insert(pending_tree, newbre, where);
1282 		newbre = NULL;
1283 	} else {
1284 		bre->bre_pcount++;
1285 	}
1286 	mutex_exit(&brtvd->bv_pending_lock);
1287 
1288 	if (newbre != NULL) {
1289 		ASSERT(bre != NULL);
1290 		ASSERT(bre != newbre);
1291 		kmem_cache_free(brt_entry_cache, newbre);
1292 	} else {
1293 		ASSERT0P(bre);
1294 
1295 		/* Prefetch BRT entry for the syncing context. */
1296 		brt_prefetch(brtvd, bp);
1297 	}
1298 }
1299 
1300 void
brt_pending_remove(spa_t * spa,const blkptr_t * bp,dmu_tx_t * tx)1301 brt_pending_remove(spa_t *spa, const blkptr_t *bp, dmu_tx_t *tx)
1302 {
1303 	brt_entry_t *bre, bre_search;
1304 	uint64_t txg;
1305 
1306 	txg = dmu_tx_get_txg(tx);
1307 	ASSERT3U(txg, !=, 0);
1308 
1309 	bre_search.bre_bp = *bp;
1310 
1311 	kmutex_t *pending_lock;
1312 	avl_tree_t *pending_tree;
1313 	if (BP_GET_DEDUP(bp)) {
1314 		brt_dedup_shard_t *bds =
1315 		    &spa->spa_brt_dedup[BRT_DEDUP_SHARD(bp)];
1316 		pending_lock = &bds->bds_lock;
1317 		pending_tree = &bds->bds_tree[txg & TXG_MASK];
1318 	} else {
1319 		uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);
1320 		brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);
1321 		ASSERT(brtvd != NULL);
1322 		pending_lock = &brtvd->bv_pending_lock;
1323 		pending_tree = &brtvd->bv_pending_tree[txg & TXG_MASK];
1324 	}
1325 
1326 	mutex_enter(pending_lock);
1327 	bre = avl_find(pending_tree, &bre_search, NULL);
1328 	ASSERT(bre != NULL);
1329 	ASSERT(bre->bre_pcount > 0);
1330 	bre->bre_pcount--;
1331 	if (bre->bre_pcount == 0)
1332 		avl_remove(pending_tree, bre);
1333 	else
1334 		bre = NULL;
1335 	mutex_exit(pending_lock);
1336 
1337 	if (bre)
1338 		kmem_cache_free(brt_entry_cache, bre);
1339 }
1340 
1341 typedef struct brt_pending_vdev_arg {
1342 	spa_t		*bpva_spa;
1343 	brt_vdev_t	*bpva_brtvd;
1344 	uint64_t	bpva_txg;
1345 } brt_pending_vdev_arg_t;
1346 
1347 static void
brt_pending_apply_vdev(void * arg)1348 brt_pending_apply_vdev(void *arg)
1349 {
1350 	brt_pending_vdev_arg_t *bpva = arg;
1351 	spa_t *spa = bpva->bpva_spa;
1352 	brt_vdev_t *brtvd = bpva->bpva_brtvd;
1353 	uint64_t txg = bpva->bpva_txg;
1354 	brt_entry_t *bre, *nbre;
1355 
1356 	/*
1357 	 * We are in syncing context, so no other bv_pending_tree accesses
1358 	 * are possible for the TXG.  So we don't need bv_pending_lock.
1359 	 */
1360 	ASSERT(avl_is_empty(&brtvd->bv_tree));
1361 	avl_swap(&brtvd->bv_tree, &brtvd->bv_pending_tree[txg & TXG_MASK]);
1362 
1363 	for (bre = avl_first(&brtvd->bv_tree); bre; bre = nbre) {
1364 		nbre = AVL_NEXT(&brtvd->bv_tree, bre);
1365 
1366 		/*
1367 		 * Unless we know that the block is definitely not in ZAP,
1368 		 * try to get its reference count from there.
1369 		 */
1370 		uint64_t off = BRE_OFFSET(bre);
1371 		if (brtvd->bv_mos_entries != 0 &&
1372 		    brt_vdev_lookup(spa, brtvd, off)) {
1373 			int error;
1374 			if (brt_has_endian_fixed(spa)) {
1375 				error = zap_lookup_uint64_by_dnode(
1376 				    brtvd->bv_mos_entries_dnode, &off,
1377 				    BRT_KEY_WORDS, sizeof (bre->bre_count), 1,
1378 				    &bre->bre_count);
1379 			} else {
1380 				error = zap_lookup_uint64_by_dnode(
1381 				    brtvd->bv_mos_entries_dnode, &off,
1382 				    BRT_KEY_WORDS, 1, sizeof (bre->bre_count),
1383 				    &bre->bre_count);
1384 			}
1385 			if (error == 0) {
1386 				BRTSTAT_BUMP(brt_addref_entry_on_disk);
1387 			} else {
1388 				ASSERT3U(error, ==, ENOENT);
1389 				BRTSTAT_BUMP(brt_addref_entry_not_on_disk);
1390 			}
1391 		}
1392 	}
1393 
1394 	/* If we had no new clones for this vdev, we don't need to initiate. */
1395 	if (avl_is_empty(&brtvd->bv_tree))
1396 		return;
1397 
1398 	if (!brtvd->bv_initiated) {
1399 		rw_enter(&brtvd->bv_lock, RW_WRITER);
1400 		brt_vdev_realloc(spa, brtvd);
1401 		rw_exit(&brtvd->bv_lock);
1402 	}
1403 
1404 	/*
1405 	 * Convert pending references into proper ones.  This has to be a
1406 	 * separate loop, since entcount modifications would cause false
1407 	 * positives for brt_vdev_lookup() on following iterations.
1408 	 */
1409 	for (bre = avl_first(&brtvd->bv_tree); bre;
1410 	    bre = AVL_NEXT(&brtvd->bv_tree, bre)) {
1411 		brt_vdev_addref(spa, brtvd, bre,
1412 		    bp_get_dsize(spa, &bre->bre_bp), bre->bre_pcount);
1413 		bre->bre_count += bre->bre_pcount;
1414 	}
1415 }
1416 
1417 typedef struct brt_pending_dedup_arg {
1418 	spa_t		*bpda_spa;
1419 	avl_tree_t	*bpda_tree;
1420 } brt_pending_dedup_arg_t;
1421 
1422 static void
brt_pending_apply_dedup(void * arg)1423 brt_pending_apply_dedup(void *arg)
1424 {
1425 	brt_pending_dedup_arg_t *bpda = arg;
1426 	spa_t *spa = bpda->bpda_spa;
1427 	avl_tree_t *tree = bpda->bpda_tree;
1428 	brt_entry_t *bre, *nbre;
1429 
1430 	for (bre = avl_first(tree); bre; bre = nbre) {
1431 		nbre = AVL_NEXT(tree, bre);
1432 		while (bre->bre_pcount > 0) {
1433 			if (!ddt_addref(spa, &bre->bre_bp))
1434 				break;
1435 			bre->bre_pcount--;
1436 		}
1437 		if (bre->bre_pcount == 0) {
1438 			avl_remove(tree, bre);
1439 			kmem_cache_free(brt_entry_cache, bre);
1440 		}
1441 		/* Else leave it for the caller to reference in the BRT. */
1442 	}
1443 }
1444 
1445 void
brt_pending_apply(spa_t * spa,uint64_t txg)1446 brt_pending_apply(spa_t *spa, uint64_t txg)
1447 {
1448 	brt_pending_dedup_arg_t bpda[BRT_DEDUP_SHARDS];
1449 	taskq_t *tq = spa->spa_dsl_pool->dp_sync_taskq;
1450 
1451 	/*
1452 	 * We are in syncing context, so no open context accesses to the
1453 	 * pending trees of this TXG are possible and we need no locks.
1454 	 *
1455 	 * Reference the dedup'd blocks in the DDT.  Process the shards in
1456 	 * parallel, since random DDT ZAP lookups are CPU-expensive due to
1457 	 * the leaf block decompression.  Each shard covers a disjoint part
1458 	 * of the DDT ZAP hash space and is walked in the hash order, so
1459 	 * each leaf is decompressed at most once and only by one thread.
1460 	 */
1461 	for (int i = 0; i < BRT_DEDUP_SHARDS; i++) {
1462 		avl_tree_t *tree =
1463 		    &spa->spa_brt_dedup[i].bds_tree[txg & TXG_MASK];
1464 		if (avl_is_empty(tree))
1465 			continue;
1466 		bpda[i].bpda_spa = spa;
1467 		bpda[i].bpda_tree = tree;
1468 		VERIFY(taskq_dispatch(tq, brt_pending_apply_dedup,
1469 		    &bpda[i], TQ_SLEEP) != TASKQID_INVALID);
1470 	}
1471 	taskq_wait(tq);
1472 
1473 	/*
1474 	 * Turn blocks that could not be referenced in the DDT (their
1475 	 * entries were pruned or are over the dedup quota) into regular
1476 	 * BRT pending entries for their vdevs.
1477 	 */
1478 	for (int i = 0; i < BRT_DEDUP_SHARDS; i++) {
1479 		avl_tree_t *tree =
1480 		    &spa->spa_brt_dedup[i].bds_tree[txg & TXG_MASK];
1481 		brt_entry_t *bre;
1482 		void *cookie = NULL;
1483 
1484 		while ((bre = avl_destroy_nodes(tree, &cookie)) != NULL) {
1485 			uint64_t vdevid = DVA_GET_VDEV(&bre->bre_bp.blk_dva[0]);
1486 			brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_TRUE);
1487 			avl_add(&brtvd->bv_pending_tree[txg & TXG_MASK], bre);
1488 		}
1489 	}
1490 
1491 	/*
1492 	 * Add pending references to the BRTs of their vdevs.  Process the
1493 	 * vdevs in parallel, since random BRT ZAP lookups are CPU-expensive
1494 	 * due to the leaf block decompression.  The BRT ZAP hash is salted,
1495 	 * so unlike the DDT above the lookups can not be ordered to match
1496 	 * the leaf blocks order.
1497 	 */
1498 	brt_rlock(spa);
1499 	uint64_t nvdevs = spa->spa_brt_nvdevs;
1500 	brt_unlock(spa);
1501 	if (nvdevs == 0)
1502 		return;
1503 	brt_pending_vdev_arg_t *bpva =
1504 	    kmem_zalloc(sizeof (*bpva) * nvdevs, KM_SLEEP);
1505 	brt_rlock(spa);
1506 	for (uint64_t vdevid = 0; vdevid < nvdevs; vdevid++) {
1507 		brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];
1508 		if (avl_is_empty(&brtvd->bv_pending_tree[txg & TXG_MASK]))
1509 			continue;
1510 		bpva[vdevid].bpva_spa = spa;
1511 		bpva[vdevid].bpva_brtvd = brtvd;
1512 		bpva[vdevid].bpva_txg = txg;
1513 	}
1514 	brt_unlock(spa);
1515 	for (uint64_t vdevid = 0; vdevid < nvdevs; vdevid++) {
1516 		if (bpva[vdevid].bpva_spa == NULL)
1517 			continue;
1518 		VERIFY(taskq_dispatch(tq, brt_pending_apply_vdev,
1519 		    &bpva[vdevid], TQ_SLEEP) != TASKQID_INVALID);
1520 	}
1521 	taskq_wait(tq);
1522 	kmem_free(bpva, sizeof (*bpva) * nvdevs);
1523 }
1524 
1525 static void
brt_sync_entry(spa_t * spa,dnode_t * dn,brt_entry_t * bre,dmu_tx_t * tx)1526 brt_sync_entry(spa_t *spa, dnode_t *dn, brt_entry_t *bre, dmu_tx_t *tx)
1527 {
1528 	uint64_t off = BRE_OFFSET(bre);
1529 
1530 	if (bre->bre_pcount == 0) {
1531 		/* The net change is zero, nothing to do in ZAP. */
1532 	} else if (bre->bre_count == 0) {
1533 		int error = zap_remove_uint64_by_dnode(dn, &off,
1534 		    BRT_KEY_WORDS, tx);
1535 		VERIFY(error == 0 || error == ENOENT);
1536 	} else {
1537 		if (brt_has_endian_fixed(spa)) {
1538 			VERIFY0(zap_update_uint64_by_dnode(dn, &off,
1539 			    BRT_KEY_WORDS, sizeof (bre->bre_count), 1,
1540 			    &bre->bre_count, tx));
1541 		} else {
1542 			VERIFY0(zap_update_uint64_by_dnode(dn, &off,
1543 			    BRT_KEY_WORDS, 1, sizeof (bre->bre_count),
1544 			    &bre->bre_count, tx));
1545 		}
1546 	}
1547 }
1548 
1549 static void
brt_sync_table(spa_t * spa,dmu_tx_t * tx)1550 brt_sync_table(spa_t *spa, dmu_tx_t *tx)
1551 {
1552 	brt_entry_t *bre;
1553 
1554 	brt_rlock(spa);
1555 	for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {
1556 		brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];
1557 		brt_unlock(spa);
1558 
1559 		if (!brtvd->bv_meta_dirty) {
1560 			ASSERT(!brtvd->bv_entcount_dirty);
1561 			ASSERT0(avl_numnodes(&brtvd->bv_tree));
1562 			brt_rlock(spa);
1563 			continue;
1564 		}
1565 
1566 		ASSERT(!brtvd->bv_entcount_dirty ||
1567 		    avl_numnodes(&brtvd->bv_tree) != 0);
1568 
1569 		if (brtvd->bv_mos_brtvdev == 0)
1570 			brt_vdev_create(spa, brtvd, tx);
1571 
1572 		void *c = NULL;
1573 		while ((bre = avl_destroy_nodes(&brtvd->bv_tree, &c)) != NULL) {
1574 			brt_sync_entry(spa, brtvd->bv_mos_entries_dnode, bre,
1575 			    tx);
1576 			kmem_cache_free(brt_entry_cache, bre);
1577 		}
1578 
1579 #ifdef ZFS_DEBUG
1580 		if (zfs_flags & ZFS_DEBUG_BRT)
1581 			brt_vdev_dump(brtvd);
1582 #endif
1583 		if (brtvd->bv_totalcount == 0)
1584 			brt_vdev_destroy(spa, brtvd, tx);
1585 		else
1586 			brt_vdev_sync(spa, brtvd, tx);
1587 		brt_rlock(spa);
1588 	}
1589 	brt_unlock(spa);
1590 }
1591 
1592 void
brt_sync(spa_t * spa,uint64_t txg)1593 brt_sync(spa_t *spa, uint64_t txg)
1594 {
1595 	dmu_tx_t *tx;
1596 	uint64_t vdevid;
1597 
1598 	ASSERT3U(spa_syncing_txg(spa), ==, txg);
1599 
1600 	brt_rlock(spa);
1601 	for (vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {
1602 		if (spa->spa_brt_vdevs[vdevid]->bv_meta_dirty)
1603 			break;
1604 	}
1605 	if (vdevid >= spa->spa_brt_nvdevs) {
1606 		brt_unlock(spa);
1607 		return;
1608 	}
1609 	brt_unlock(spa);
1610 
1611 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1612 	brt_sync_table(spa, tx);
1613 	dmu_tx_commit(tx);
1614 }
1615 
1616 static void
brt_alloc(spa_t * spa)1617 brt_alloc(spa_t *spa)
1618 {
1619 	rw_init(&spa->spa_brt_lock, NULL, RW_DEFAULT, NULL);
1620 	spa->spa_brt_vdevs = NULL;
1621 	spa->spa_brt_nvdevs = 0;
1622 	spa->spa_brt_rangesize = 0;
1623 
1624 	spa->spa_brt_dedup = kmem_zalloc(sizeof (brt_dedup_shard_t) *
1625 	    BRT_DEDUP_SHARDS, KM_SLEEP);
1626 	for (int i = 0; i < BRT_DEDUP_SHARDS; i++) {
1627 		brt_dedup_shard_t *bds = &spa->spa_brt_dedup[i];
1628 		mutex_init(&bds->bds_lock, NULL, MUTEX_DEFAULT, NULL);
1629 		for (int t = 0; t < TXG_SIZE; t++) {
1630 			avl_create(&bds->bds_tree[t], brt_entry_dedup_compare,
1631 			    sizeof (brt_entry_t),
1632 			    offsetof(brt_entry_t, bre_node));
1633 		}
1634 	}
1635 }
1636 
1637 void
brt_create(spa_t * spa)1638 brt_create(spa_t *spa)
1639 {
1640 	brt_alloc(spa);
1641 	spa->spa_brt_rangesize = BRT_RANGESIZE;
1642 }
1643 
1644 int
brt_load(spa_t * spa)1645 brt_load(spa_t *spa)
1646 {
1647 	int error = 0;
1648 
1649 	brt_alloc(spa);
1650 	brt_wlock(spa);
1651 	for (uint64_t vdevid = 0; vdevid < spa->spa_root_vdev->vdev_children;
1652 	    vdevid++) {
1653 		char name[64];
1654 		uint64_t mos_brtvdev;
1655 
1656 		/* Look if this vdev had active block cloning. */
1657 		snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,
1658 		    (u_longlong_t)vdevid);
1659 		error = zap_lookup(spa->spa_meta_objset,
1660 		    DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,
1661 		    &mos_brtvdev);
1662 		if (error == ENOENT) {
1663 			error = 0;
1664 			continue;
1665 		}
1666 		if (error != 0)
1667 			break;
1668 
1669 		/* If it did, then allocate them all and load this one. */
1670 		brt_vdevs_expand(spa, spa->spa_root_vdev->vdev_children);
1671 		brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];
1672 		rw_enter(&brtvd->bv_lock, RW_WRITER);
1673 		brtvd->bv_mos_brtvdev = mos_brtvdev;
1674 		error = brt_vdev_load(spa, brtvd);
1675 		rw_exit(&brtvd->bv_lock);
1676 		if (error != 0)
1677 			break;
1678 	}
1679 
1680 	if (spa->spa_brt_rangesize == 0)
1681 		spa->spa_brt_rangesize = BRT_RANGESIZE;
1682 	brt_unlock(spa);
1683 	return (error);
1684 }
1685 
1686 void
brt_prefetch_all(spa_t * spa)1687 brt_prefetch_all(spa_t *spa)
1688 {
1689 	/*
1690 	 * Load all BRT entries for each vdev. This is intended to perform
1691 	 * a prefetch on all such blocks. For the same reason that brt_prefetch
1692 	 * (called from brt_pending_add) isn't locked, this is also not locked.
1693 	 */
1694 	brt_rlock(spa);
1695 	for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {
1696 		brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];
1697 		brt_unlock(spa);
1698 
1699 		rw_enter(&brtvd->bv_mos_entries_lock, RW_READER);
1700 		if (brtvd->bv_mos_entries != 0) {
1701 			(void) zap_prefetch_object(spa->spa_meta_objset,
1702 			    brtvd->bv_mos_entries);
1703 		}
1704 		rw_exit(&brtvd->bv_mos_entries_lock);
1705 
1706 		brt_rlock(spa);
1707 	}
1708 	brt_unlock(spa);
1709 }
1710 
1711 void
brt_unload(spa_t * spa)1712 brt_unload(spa_t *spa)
1713 {
1714 	if (spa->spa_brt_rangesize == 0)
1715 		return;
1716 	brt_vdevs_free(spa);
1717 	rw_destroy(&spa->spa_brt_lock);
1718 	spa->spa_brt_rangesize = 0;
1719 
1720 	for (int i = 0; i < BRT_DEDUP_SHARDS; i++) {
1721 		brt_dedup_shard_t *bds = &spa->spa_brt_dedup[i];
1722 		for (int t = 0; t < TXG_SIZE; t++)
1723 			avl_destroy(&bds->bds_tree[t]);
1724 		mutex_destroy(&bds->bds_lock);
1725 	}
1726 	kmem_free(spa->spa_brt_dedup, sizeof (brt_dedup_shard_t) *
1727 	    BRT_DEDUP_SHARDS);
1728 	spa->spa_brt_dedup = NULL;
1729 }
1730 
1731 ZFS_MODULE_PARAM(zfs_brt, , brt_zap_prefetch, INT, ZMOD_RW,
1732 	"Enable prefetching of BRT ZAP entries");
1733 ZFS_MODULE_PARAM(zfs_brt, , brt_zap_default_bs, UINT, ZMOD_RW,
1734 	"BRT ZAP leaf blockshift");
1735 ZFS_MODULE_PARAM(zfs_brt, , brt_zap_default_ibs, UINT, ZMOD_RW,
1736 	"BRT ZAP indirect blockshift");
1737