Path: blob/main/sys/contrib/openzfs/module/zfs/brt.c
48383 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/2122/*23* Copyright (c) 2020, 2021, 2022 by Pawel Jakub Dawidek24*/2526#include <sys/zfs_context.h>27#include <sys/spa.h>28#include <sys/spa_impl.h>29#include <sys/zio.h>30#include <sys/brt.h>31#include <sys/brt_impl.h>32#include <sys/ddt.h>33#include <sys/bitmap.h>34#include <sys/zap.h>35#include <sys/dmu_tx.h>36#include <sys/arc.h>37#include <sys/dsl_pool.h>38#include <sys/dsl_scan.h>39#include <sys/vdev_impl.h>40#include <sys/kstat.h>41#include <sys/wmsum.h>4243/*44* Block Cloning design.45*46* Block Cloning allows to manually clone a file (or a subset of its blocks)47* into another (or the same) file by just creating additional references to48* the data blocks without copying the data itself. Those references are kept49* in the Block Reference Tables (BRTs).50*51* In many ways this is similar to the existing deduplication, but there are52* some important differences:53*54* - Deduplication is automatic and Block Cloning is not - one has to use a55* dedicated system call(s) to clone the given file/blocks.56* - Deduplication keeps all data blocks in its table, even those referenced57* just once. Block Cloning creates an entry in its tables only when there58* are at least two references to the given data block. If the block was59* never explicitly cloned or the second to last reference was dropped,60* there will be neither space nor performance overhead.61* - Deduplication needs data to work - one needs to pass real data to the62* write(2) syscall, so hash can be calculated. Block Cloning doesn't require63* data, just block pointers to the data, so it is extremely fast, as we pay64* neither the cost of reading the data, nor the cost of writing the data -65* we operate exclusively on metadata.66* - If the D (dedup) bit is not set in the block pointer, it means that67* the block is not in the dedup table (DDT) and we won't consult the DDT68* when we need to free the block. Block Cloning must be consulted on every69* free, because we cannot modify the source BP (eg. by setting something70* similar to the D bit), thus we have no hint if the block is in the71* Block Reference Table (BRT), so we need to look into the BRT. There is72* an optimization in place that allows us to eliminate the majority of BRT73* lookups which is described below in the "Minimizing free penalty" section.74* - The BRT entry is much smaller than the DDT entry - for BRT we only store75* 64bit offset and 64bit reference counter.76* - Dedup keys are cryptographic hashes, so two blocks that are close to each77* other on disk are most likely in totally different parts of the DDT.78* The BRT entry keys are offsets into a single top-level VDEV, so data blocks79* from one file should have BRT entries close to each other.80* - Scrub will only do a single pass over a block that is referenced multiple81* times in the DDT. Unfortunately it is not currently (if at all) possible82* with Block Cloning and block referenced multiple times will be scrubbed83* multiple times. The new, sorted scrub should be able to eliminate84* duplicated reads given enough memory.85* - Deduplication requires cryptographically strong hash as a checksum or86* additional data verification. Block Cloning works with any checksum87* algorithm or even with checksumming disabled.88*89* As mentioned above, the BRT entries are much smaller than the DDT entries.90* To uniquely identify a block we just need its vdev id and offset. We also91* need to maintain a reference counter. The vdev id will often repeat, as there92* is a small number of top-level VDEVs and a large number of blocks stored in93* each VDEV. We take advantage of that to reduce the BRT entry size further by94* maintaining one BRT for each top-level VDEV, so we can then have only offset95* and counter as the BRT entry.96*97* Minimizing free penalty.98*99* Block Cloning allows creating additional references to any existing block.100* When we free a block there is no hint in the block pointer whether the block101* was cloned or not, so on each free we have to check if there is a102* corresponding entry in the BRT or not. If there is, we need to decrease103* the reference counter. Doing BRT lookup on every free can potentially be104* expensive by requiring additional I/Os if the BRT doesn't fit into memory.105* This is the main problem with deduplication, so we've learned our lesson and106* try not to repeat the same mistake here. How do we do that? We divide each107* top-level VDEV into 16MB regions. For each region we maintain a counter that108* is a sum of all the BRT entries that have offsets within the region. This109* creates the entries count array of 16bit numbers for each top-level VDEV.110* The entries count array is always kept in memory and updated on disk in the111* same transaction group as the BRT updates to keep everything in-sync. We can112* keep the array in memory, because it is very small. With 16MB regions and113* 1TB VDEV the array requires only 128kB of memory (we may decide to decrease114* the region size even further in the future). Now, when we want to free115* a block, we first consult the array. If the counter for the whole region is116* zero, there is no need to look for the BRT entry, as there isn't one for117* sure. If the counter for the region is greater than zero, only then we will118* do a BRT lookup and if an entry is found we will decrease the reference119* counter in the BRT entry and in the entry counters array.120*121* The entry counters array is small, but can potentially be larger for very122* large VDEVs or smaller regions. In this case we don't want to rewrite entire123* array on every change. We then divide the array into 32kB block and keep124* a bitmap of dirty blocks within a transaction group. When we sync the125* transaction group we can only update the parts of the entry counters array126* that were modified. Note: Keeping track of the dirty parts of the entry127* counters array is implemented, but updating only parts of the array on disk128* is not yet implemented - for now we will update entire array if there was129* any change.130*131* The implementation tries to be economic: if BRT is not used, or no longer132* used, there will be no entries in the MOS and no additional memory used (eg.133* the entry counters array is only allocated if needed).134*135* Interaction between Deduplication and Block Cloning.136*137* If both functionalities are in use, we could end up with a block that is138* referenced multiple times in both DDT and BRT. When we free one of the139* references we couldn't tell where it belongs, so we would have to decide140* what table takes the precedence: do we first clear DDT references or BRT141* references? To avoid this dilemma BRT cooperates with DDT - if a given block142* is being cloned using BRT and the BP has the D (dedup) bit set, BRT will143* lookup DDT entry instead and increase the counter there. No BRT entry144* will be created for a block which has the D (dedup) bit set.145* BRT may be more efficient for manual deduplication, but if the block is146* already in the DDT, then creating additional BRT entry would be less147* efficient. This clever idea was proposed by Allan Jude.148*149* Block Cloning across datasets.150*151* Block Cloning is not limited to cloning blocks within the same dataset.152* It is possible (and very useful) to clone blocks between different datasets.153* One use case is recovering files from snapshots. By cloning the files into154* dataset we need no additional storage. Without Block Cloning we would need155* additional space for those files.156* Another interesting use case is moving the files between datasets157* (copying the file content to the new dataset and removing the source file).158* In that case Block Cloning will only be used briefly, because the BRT entries159* will be removed when the source is removed.160* Block Cloning across encrypted datasets is supported as long as both161* datasets share the same master key (e.g. snapshots and clones)162*163* Block Cloning flow through ZFS layers.164*165* Note: Block Cloning can be used both for cloning file system blocks and ZVOL166* blocks. As of this writing no interface is implemented that allows for block167* cloning within a ZVOL.168* FreeBSD and Linux provides copy_file_range(2) system call and we will use it169* for blocking cloning.170*171* ssize_t172* copy_file_range(int infd, off_t *inoffp, int outfd, off_t *outoffp,173* size_t len, unsigned int flags);174*175* Even though offsets and length represent bytes, they have to be176* block-aligned or we will return an error so the upper layer can177* fallback to the generic mechanism that will just copy the data.178* Using copy_file_range(2) will call OS-independent zfs_clone_range() function.179* This function was implemented based on zfs_write(), but instead of writing180* the given data we first read block pointers using the new dmu_read_l0_bps()181* function from the source file. Once we have BPs from the source file we call182* the dmu_brt_clone() function on the destination file. This function183* allocates BPs for us. We iterate over all source BPs. If the given BP is184* a hole or an embedded block, we just copy BP as-is. If it points to a real185* data we place this BP on a BRT pending list using the brt_pending_add()186* function.187*188* We use this pending list to keep track of all BPs that got new references189* within this transaction group.190*191* Some special cases to consider and how we address them:192* - The block we want to clone may have been created within the same193* transaction group that we are trying to clone. Such block has no BP194* allocated yet, so cannot be immediately cloned. We return EAGAIN.195* - The block we want to clone may have been modified within the same196* transaction group. We return EAGAIN.197* - A block may be cloned multiple times during one transaction group (that's198* why pending list is actually a tree and not an append-only list - this199* way we can figure out faster if this block is cloned for the first time200* in this txg or consecutive time).201* - A block may be cloned and freed within the same transaction group202* (see dbuf_undirty()).203* - A block may be cloned and within the same transaction group the clone204* can be cloned again (see dmu_read_l0_bps()).205* - A file might have been deleted, but the caller still has a file descriptor206* open to this file and clones it.207*208* When we free a block we have an additional step in the ZIO pipeline where we209* call the zio_brt_free() function. We then call the brt_entry_decref()210* that loads the corresponding BRT entry (if one exists) and decreases211* reference counter. If this is not the last reference we will stop ZIO212* pipeline here. If this is the last reference or the block is not in the213* BRT, we continue the pipeline and free the block as usual.214*215* At the beginning of spa_sync() where there can be no more block cloning,216* but before issuing frees we call brt_pending_apply(). This function applies217* all the new clones to the BRT table - we load BRT entries and update218* reference counters. To sync new BRT entries to disk, we use brt_sync()219* function. This function will sync all dirty per-top-level-vdev BRTs,220* the entry counters arrays, etc.221*222* Block Cloning and ZIL.223*224* Every clone operation is divided into chunks (similar to write) and each225* chunk is cloned in a separate transaction. The chunk size is determined by226* how many BPs we can fit into a single ZIL entry.227* Replaying clone operation is different from the regular clone operation,228* as when we log clone operations we cannot use the source object - it may229* reside on a different dataset, so we log BPs we want to clone.230* The ZIL is replayed when we mount the given dataset, not when the pool is231* imported. Taking this into account it is possible that the pool is imported232* without mounting datasets and the source dataset is destroyed before the233* destination dataset is mounted and its ZIL replayed.234* To address this situation we leverage zil_claim() mechanism where ZFS will235* parse all the ZILs on pool import. When we come across TX_CLONE_RANGE236* entries, we will bump reference counters for their BPs in the BRT. Then237* on mount and ZIL replay we bump the reference counters once more, while the238* first references are dropped during ZIL destroy by zil_free_clone_range().239* It is possible that after zil_claim() we never mount the destination, so240* we never replay its ZIL and just destroy it. In this case the only taken241* references will be dropped by zil_free_clone_range(), since the cloning is242* not going to ever take place.243*/244245static kmem_cache_t *brt_entry_cache;246247/*248* Enable/disable prefetching of BRT entries that we are going to modify.249*/250static int brt_zap_prefetch = 1;251252#ifdef ZFS_DEBUG253#define BRT_DEBUG(...) do { \254if ((zfs_flags & ZFS_DEBUG_BRT) != 0) { \255__dprintf(B_TRUE, __FILE__, __func__, __LINE__, __VA_ARGS__); \256} \257} while (0)258#else259#define BRT_DEBUG(...) do { } while (0)260#endif261262static int brt_zap_default_bs = 12;263static int brt_zap_default_ibs = 12;264265static kstat_t *brt_ksp;266267typedef struct brt_stats {268kstat_named_t brt_addref_entry_not_on_disk;269kstat_named_t brt_addref_entry_on_disk;270kstat_named_t brt_decref_entry_in_memory;271kstat_named_t brt_decref_entry_loaded_from_disk;272kstat_named_t brt_decref_entry_not_in_memory;273kstat_named_t brt_decref_entry_read_lost_race;274kstat_named_t brt_decref_entry_still_referenced;275kstat_named_t brt_decref_free_data_later;276kstat_named_t brt_decref_free_data_now;277kstat_named_t brt_decref_no_entry;278} brt_stats_t;279280static brt_stats_t brt_stats = {281{ "addref_entry_not_on_disk", KSTAT_DATA_UINT64 },282{ "addref_entry_on_disk", KSTAT_DATA_UINT64 },283{ "decref_entry_in_memory", KSTAT_DATA_UINT64 },284{ "decref_entry_loaded_from_disk", KSTAT_DATA_UINT64 },285{ "decref_entry_not_in_memory", KSTAT_DATA_UINT64 },286{ "decref_entry_read_lost_race", KSTAT_DATA_UINT64 },287{ "decref_entry_still_referenced", KSTAT_DATA_UINT64 },288{ "decref_free_data_later", KSTAT_DATA_UINT64 },289{ "decref_free_data_now", KSTAT_DATA_UINT64 },290{ "decref_no_entry", KSTAT_DATA_UINT64 }291};292293struct {294wmsum_t brt_addref_entry_not_on_disk;295wmsum_t brt_addref_entry_on_disk;296wmsum_t brt_decref_entry_in_memory;297wmsum_t brt_decref_entry_loaded_from_disk;298wmsum_t brt_decref_entry_not_in_memory;299wmsum_t brt_decref_entry_read_lost_race;300wmsum_t brt_decref_entry_still_referenced;301wmsum_t brt_decref_free_data_later;302wmsum_t brt_decref_free_data_now;303wmsum_t brt_decref_no_entry;304} brt_sums;305306#define BRTSTAT_BUMP(stat) wmsum_add(&brt_sums.stat, 1)307308static int brt_entry_compare(const void *x1, const void *x2);309static void brt_vdevs_expand(spa_t *spa, uint64_t nvdevs);310311static void312brt_rlock(spa_t *spa)313{314rw_enter(&spa->spa_brt_lock, RW_READER);315}316317static void318brt_wlock(spa_t *spa)319{320rw_enter(&spa->spa_brt_lock, RW_WRITER);321}322323static void324brt_unlock(spa_t *spa)325{326rw_exit(&spa->spa_brt_lock);327}328329static uint16_t330brt_vdev_entcount_get(const brt_vdev_t *brtvd, uint64_t idx)331{332333ASSERT3U(idx, <, brtvd->bv_size);334335if (unlikely(brtvd->bv_need_byteswap)) {336return (BSWAP_16(brtvd->bv_entcount[idx]));337} else {338return (brtvd->bv_entcount[idx]);339}340}341342static void343brt_vdev_entcount_set(brt_vdev_t *brtvd, uint64_t idx, uint16_t entcnt)344{345346ASSERT3U(idx, <, brtvd->bv_size);347348if (unlikely(brtvd->bv_need_byteswap)) {349brtvd->bv_entcount[idx] = BSWAP_16(entcnt);350} else {351brtvd->bv_entcount[idx] = entcnt;352}353}354355static void356brt_vdev_entcount_inc(brt_vdev_t *brtvd, uint64_t idx)357{358uint16_t entcnt;359360ASSERT3U(idx, <, brtvd->bv_size);361362entcnt = brt_vdev_entcount_get(brtvd, idx);363ASSERT(entcnt < UINT16_MAX);364365brt_vdev_entcount_set(brtvd, idx, entcnt + 1);366}367368static void369brt_vdev_entcount_dec(brt_vdev_t *brtvd, uint64_t idx)370{371uint16_t entcnt;372373ASSERT3U(idx, <, brtvd->bv_size);374375entcnt = brt_vdev_entcount_get(brtvd, idx);376ASSERT(entcnt > 0);377378brt_vdev_entcount_set(brtvd, idx, entcnt - 1);379}380381#ifdef ZFS_DEBUG382static void383brt_vdev_dump(brt_vdev_t *brtvd)384{385uint64_t idx;386387uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);388zfs_dbgmsg(" BRT vdevid=%llu meta_dirty=%d entcount_dirty=%d "389"size=%llu totalcount=%llu nblocks=%llu bitmapsize=%zu",390(u_longlong_t)brtvd->bv_vdevid,391brtvd->bv_meta_dirty, brtvd->bv_entcount_dirty,392(u_longlong_t)brtvd->bv_size,393(u_longlong_t)brtvd->bv_totalcount,394(u_longlong_t)nblocks,395(size_t)BT_SIZEOFMAP(nblocks));396if (brtvd->bv_totalcount > 0) {397zfs_dbgmsg(" entcounts:");398for (idx = 0; idx < brtvd->bv_size; idx++) {399uint16_t entcnt = brt_vdev_entcount_get(brtvd, idx);400if (entcnt > 0) {401zfs_dbgmsg(" [%04llu] %hu",402(u_longlong_t)idx, entcnt);403}404}405}406if (brtvd->bv_entcount_dirty) {407char *bitmap;408409bitmap = kmem_alloc(nblocks + 1, KM_SLEEP);410for (idx = 0; idx < nblocks; idx++) {411bitmap[idx] =412BT_TEST(brtvd->bv_bitmap, idx) ? 'x' : '.';413}414bitmap[idx] = '\0';415zfs_dbgmsg(" dirty: %s", bitmap);416kmem_free(bitmap, nblocks + 1);417}418}419#endif420421static brt_vdev_t *422brt_vdev(spa_t *spa, uint64_t vdevid, boolean_t alloc)423{424brt_vdev_t *brtvd = NULL;425426brt_rlock(spa);427if (vdevid < spa->spa_brt_nvdevs) {428brtvd = spa->spa_brt_vdevs[vdevid];429} else if (alloc) {430/* New VDEV was added. */431brt_unlock(spa);432brt_wlock(spa);433if (vdevid >= spa->spa_brt_nvdevs)434brt_vdevs_expand(spa, vdevid + 1);435brtvd = spa->spa_brt_vdevs[vdevid];436}437brt_unlock(spa);438return (brtvd);439}440441static void442brt_vdev_create(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)443{444char name[64];445446ASSERT(brtvd->bv_initiated);447ASSERT0(brtvd->bv_mos_brtvdev);448ASSERT0(brtvd->bv_mos_entries);449450uint64_t mos_entries = zap_create_flags(spa->spa_meta_objset, 0,451ZAP_FLAG_HASH64 | ZAP_FLAG_UINT64_KEY, DMU_OTN_ZAP_METADATA,452brt_zap_default_bs, brt_zap_default_ibs, DMU_OT_NONE, 0, tx);453VERIFY(mos_entries != 0);454VERIFY0(dnode_hold(spa->spa_meta_objset, mos_entries, brtvd,455&brtvd->bv_mos_entries_dnode));456rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);457brtvd->bv_mos_entries = mos_entries;458rw_exit(&brtvd->bv_mos_entries_lock);459BRT_DEBUG("MOS entries created, object=%llu",460(u_longlong_t)brtvd->bv_mos_entries);461462/*463* We allocate DMU buffer to store the bv_entcount[] array.464* We will keep array size (bv_size) and cummulative count for all465* bv_entcount[]s (bv_totalcount) in the bonus buffer.466*/467brtvd->bv_mos_brtvdev = dmu_object_alloc(spa->spa_meta_objset,468DMU_OTN_UINT64_METADATA, BRT_BLOCKSIZE,469DMU_OTN_UINT64_METADATA, sizeof (brt_vdev_phys_t), tx);470VERIFY(brtvd->bv_mos_brtvdev != 0);471BRT_DEBUG("MOS BRT VDEV created, object=%llu",472(u_longlong_t)brtvd->bv_mos_brtvdev);473474snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,475(u_longlong_t)brtvd->bv_vdevid);476VERIFY0(zap_add(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT, name,477sizeof (uint64_t), 1, &brtvd->bv_mos_brtvdev, tx));478BRT_DEBUG("Pool directory object created, object=%s", name);479480/*481* Activate the endian-fixed feature if this is the first BRT ZAP482* (i.e., BLOCK_CLONING is not yet active) and the feature is enabled.483*/484if (spa_feature_is_enabled(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN) &&485!spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {486spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);487} else if (spa_feature_is_active(spa,488SPA_FEATURE_BLOCK_CLONING_ENDIAN)) {489spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);490}491492spa_feature_incr(spa, SPA_FEATURE_BLOCK_CLONING, tx);493}494495static void496brt_vdev_realloc(spa_t *spa, brt_vdev_t *brtvd)497{498vdev_t *vd;499uint16_t *entcount;500ulong_t *bitmap;501uint64_t nblocks, onblocks, size;502503ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));504505spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);506vd = vdev_lookup_top(spa, brtvd->bv_vdevid);507size = (vdev_get_min_asize(vd) - 1) / spa->spa_brt_rangesize + 1;508spa_config_exit(spa, SCL_VDEV, FTAG);509510entcount = vmem_zalloc(sizeof (entcount[0]) * size, KM_SLEEP);511nblocks = BRT_RANGESIZE_TO_NBLOCKS(size);512bitmap = kmem_zalloc(BT_SIZEOFMAP(nblocks), KM_SLEEP);513514if (!brtvd->bv_initiated) {515ASSERT0(brtvd->bv_size);516ASSERT0P(brtvd->bv_entcount);517ASSERT0P(brtvd->bv_bitmap);518} else {519ASSERT(brtvd->bv_size > 0);520ASSERT(brtvd->bv_entcount != NULL);521ASSERT(brtvd->bv_bitmap != NULL);522/*523* TODO: Allow vdev shrinking. We only need to implement524* shrinking the on-disk BRT VDEV object.525* dmu_free_range(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,526* offset, size, tx);527*/528ASSERT3U(brtvd->bv_size, <=, size);529530memcpy(entcount, brtvd->bv_entcount,531sizeof (entcount[0]) * MIN(size, brtvd->bv_size));532vmem_free(brtvd->bv_entcount,533sizeof (entcount[0]) * brtvd->bv_size);534onblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);535memcpy(bitmap, brtvd->bv_bitmap, MIN(BT_SIZEOFMAP(nblocks),536BT_SIZEOFMAP(onblocks)));537kmem_free(brtvd->bv_bitmap, BT_SIZEOFMAP(onblocks));538}539540brtvd->bv_size = size;541brtvd->bv_entcount = entcount;542brtvd->bv_bitmap = bitmap;543if (!brtvd->bv_initiated) {544brtvd->bv_need_byteswap = FALSE;545brtvd->bv_initiated = TRUE;546BRT_DEBUG("BRT VDEV %llu initiated.",547(u_longlong_t)brtvd->bv_vdevid);548}549}550551static int552brt_vdev_load(spa_t *spa, brt_vdev_t *brtvd)553{554dmu_buf_t *db;555brt_vdev_phys_t *bvphys;556int error;557558ASSERT(!brtvd->bv_initiated);559ASSERT(brtvd->bv_mos_brtvdev != 0);560561error = dmu_bonus_hold(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,562FTAG, &db);563if (error != 0)564return (error);565566bvphys = db->db_data;567if (spa->spa_brt_rangesize == 0) {568spa->spa_brt_rangesize = bvphys->bvp_rangesize;569} else {570ASSERT3U(spa->spa_brt_rangesize, ==, bvphys->bvp_rangesize);571}572573brt_vdev_realloc(spa, brtvd);574575/* TODO: We don't support VDEV shrinking. */576ASSERT3U(bvphys->bvp_size, <=, brtvd->bv_size);577578/*579* If VDEV grew, we will leave new bv_entcount[] entries zeroed out.580*/581error = dmu_read(spa->spa_meta_objset, brtvd->bv_mos_brtvdev, 0,582MIN(brtvd->bv_size, bvphys->bvp_size) * sizeof (uint16_t),583brtvd->bv_entcount, DMU_READ_NO_PREFETCH);584if (error != 0)585return (error);586587ASSERT(bvphys->bvp_mos_entries != 0);588VERIFY0(dnode_hold(spa->spa_meta_objset, bvphys->bvp_mos_entries, brtvd,589&brtvd->bv_mos_entries_dnode));590rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);591brtvd->bv_mos_entries = bvphys->bvp_mos_entries;592rw_exit(&brtvd->bv_mos_entries_lock);593brtvd->bv_need_byteswap =594(bvphys->bvp_byteorder != BRT_NATIVE_BYTEORDER);595brtvd->bv_totalcount = bvphys->bvp_totalcount;596brtvd->bv_usedspace = bvphys->bvp_usedspace;597brtvd->bv_savedspace = bvphys->bvp_savedspace;598599dmu_buf_rele(db, FTAG);600601BRT_DEBUG("BRT VDEV %llu loaded: mos_brtvdev=%llu, mos_entries=%llu",602(u_longlong_t)brtvd->bv_vdevid,603(u_longlong_t)brtvd->bv_mos_brtvdev,604(u_longlong_t)brtvd->bv_mos_entries);605return (0);606}607608static void609brt_vdev_dealloc(brt_vdev_t *brtvd)610{611ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));612ASSERT(brtvd->bv_initiated);613ASSERT0(avl_numnodes(&brtvd->bv_tree));614615vmem_free(brtvd->bv_entcount, sizeof (uint16_t) * brtvd->bv_size);616brtvd->bv_entcount = NULL;617uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);618kmem_free(brtvd->bv_bitmap, BT_SIZEOFMAP(nblocks));619brtvd->bv_bitmap = NULL;620621brtvd->bv_size = 0;622623brtvd->bv_initiated = FALSE;624BRT_DEBUG("BRT VDEV %llu deallocated.", (u_longlong_t)brtvd->bv_vdevid);625}626627static void628brt_vdev_destroy(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)629{630char name[64];631uint64_t count;632633ASSERT(brtvd->bv_initiated);634ASSERT(brtvd->bv_mos_brtvdev != 0);635ASSERT(brtvd->bv_mos_entries != 0);636ASSERT0(brtvd->bv_totalcount);637ASSERT0(brtvd->bv_usedspace);638ASSERT0(brtvd->bv_savedspace);639640uint64_t mos_entries = brtvd->bv_mos_entries;641rw_enter(&brtvd->bv_mos_entries_lock, RW_WRITER);642brtvd->bv_mos_entries = 0;643rw_exit(&brtvd->bv_mos_entries_lock);644dnode_rele(brtvd->bv_mos_entries_dnode, brtvd);645brtvd->bv_mos_entries_dnode = NULL;646ASSERT0(zap_count(spa->spa_meta_objset, mos_entries, &count));647ASSERT0(count);648VERIFY0(zap_destroy(spa->spa_meta_objset, mos_entries, tx));649BRT_DEBUG("MOS entries destroyed, object=%llu",650(u_longlong_t)mos_entries);651652VERIFY0(dmu_object_free(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,653tx));654BRT_DEBUG("MOS BRT VDEV destroyed, object=%llu",655(u_longlong_t)brtvd->bv_mos_brtvdev);656brtvd->bv_mos_brtvdev = 0;657brtvd->bv_entcount_dirty = FALSE;658659snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,660(u_longlong_t)brtvd->bv_vdevid);661VERIFY0(zap_remove(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,662name, tx));663BRT_DEBUG("Pool directory object removed, object=%s", name);664665brtvd->bv_meta_dirty = FALSE;666667rw_enter(&brtvd->bv_lock, RW_WRITER);668brt_vdev_dealloc(brtvd);669rw_exit(&brtvd->bv_lock);670671spa_feature_decr(spa, SPA_FEATURE_BLOCK_CLONING, tx);672if (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN))673spa_feature_decr(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN, tx);674}675676static void677brt_vdevs_expand(spa_t *spa, uint64_t nvdevs)678{679brt_vdev_t **vdevs;680681ASSERT(RW_WRITE_HELD(&spa->spa_brt_lock));682ASSERT3U(nvdevs, >=, spa->spa_brt_nvdevs);683684if (nvdevs == spa->spa_brt_nvdevs)685return;686687vdevs = kmem_zalloc(sizeof (*spa->spa_brt_vdevs) * nvdevs, KM_SLEEP);688if (spa->spa_brt_nvdevs > 0) {689ASSERT(spa->spa_brt_vdevs != NULL);690691memcpy(vdevs, spa->spa_brt_vdevs,692sizeof (*spa->spa_brt_vdevs) * spa->spa_brt_nvdevs);693kmem_free(spa->spa_brt_vdevs,694sizeof (*spa->spa_brt_vdevs) * spa->spa_brt_nvdevs);695}696spa->spa_brt_vdevs = vdevs;697698for (uint64_t vdevid = spa->spa_brt_nvdevs; vdevid < nvdevs; vdevid++) {699brt_vdev_t *brtvd = kmem_zalloc(sizeof (*brtvd), KM_SLEEP);700rw_init(&brtvd->bv_lock, NULL, RW_DEFAULT, NULL);701brtvd->bv_vdevid = vdevid;702brtvd->bv_initiated = FALSE;703rw_init(&brtvd->bv_mos_entries_lock, NULL, RW_DEFAULT, NULL);704avl_create(&brtvd->bv_tree, brt_entry_compare,705sizeof (brt_entry_t), offsetof(brt_entry_t, bre_node));706for (int i = 0; i < TXG_SIZE; i++) {707avl_create(&brtvd->bv_pending_tree[i],708brt_entry_compare, sizeof (brt_entry_t),709offsetof(brt_entry_t, bre_node));710}711mutex_init(&brtvd->bv_pending_lock, NULL, MUTEX_DEFAULT, NULL);712spa->spa_brt_vdevs[vdevid] = brtvd;713}714715BRT_DEBUG("BRT VDEVs expanded from %llu to %llu.",716(u_longlong_t)spa->spa_brt_nvdevs, (u_longlong_t)nvdevs);717spa->spa_brt_nvdevs = nvdevs;718}719720static boolean_t721brt_vdev_lookup(spa_t *spa, brt_vdev_t *brtvd, uint64_t offset)722{723uint64_t idx = offset / spa->spa_brt_rangesize;724if (idx < brtvd->bv_size) {725/* VDEV wasn't expanded. */726return (brt_vdev_entcount_get(brtvd, idx) > 0);727}728return (FALSE);729}730731static void732brt_vdev_addref(spa_t *spa, brt_vdev_t *brtvd, const brt_entry_t *bre,733uint64_t dsize, uint64_t count)734{735uint64_t idx;736737ASSERT(brtvd->bv_initiated);738739brtvd->bv_savedspace += dsize * count;740brtvd->bv_meta_dirty = TRUE;741742if (bre->bre_count > 0)743return;744745brtvd->bv_usedspace += dsize;746747idx = BRE_OFFSET(bre) / spa->spa_brt_rangesize;748if (idx >= brtvd->bv_size) {749/* VDEV has been expanded. */750rw_enter(&brtvd->bv_lock, RW_WRITER);751brt_vdev_realloc(spa, brtvd);752rw_exit(&brtvd->bv_lock);753}754755ASSERT3U(idx, <, brtvd->bv_size);756757brtvd->bv_totalcount++;758brt_vdev_entcount_inc(brtvd, idx);759brtvd->bv_entcount_dirty = TRUE;760idx = idx / BRT_BLOCKSIZE / 8;761BT_SET(brtvd->bv_bitmap, idx);762}763764static void765brt_vdev_decref(spa_t *spa, brt_vdev_t *brtvd, const brt_entry_t *bre,766uint64_t dsize)767{768uint64_t idx;769770ASSERT(RW_WRITE_HELD(&brtvd->bv_lock));771ASSERT(brtvd->bv_initiated);772773brtvd->bv_savedspace -= dsize;774brtvd->bv_meta_dirty = TRUE;775776if (bre->bre_count > 0)777return;778779brtvd->bv_usedspace -= dsize;780781idx = BRE_OFFSET(bre) / spa->spa_brt_rangesize;782ASSERT3U(idx, <, brtvd->bv_size);783784ASSERT(brtvd->bv_totalcount > 0);785brtvd->bv_totalcount--;786brt_vdev_entcount_dec(brtvd, idx);787brtvd->bv_entcount_dirty = TRUE;788idx = idx / BRT_BLOCKSIZE / 8;789BT_SET(brtvd->bv_bitmap, idx);790}791792static void793brt_vdev_sync(spa_t *spa, brt_vdev_t *brtvd, dmu_tx_t *tx)794{795dmu_buf_t *db;796brt_vdev_phys_t *bvphys;797798ASSERT(brtvd->bv_meta_dirty);799ASSERT(brtvd->bv_mos_brtvdev != 0);800ASSERT(dmu_tx_is_syncing(tx));801802VERIFY0(dmu_bonus_hold(spa->spa_meta_objset, brtvd->bv_mos_brtvdev,803FTAG, &db));804805if (brtvd->bv_entcount_dirty) {806/*807* TODO: Walk brtvd->bv_bitmap and write only the dirty blocks.808*/809dmu_write(spa->spa_meta_objset, brtvd->bv_mos_brtvdev, 0,810brtvd->bv_size * sizeof (brtvd->bv_entcount[0]),811brtvd->bv_entcount, tx);812uint64_t nblocks = BRT_RANGESIZE_TO_NBLOCKS(brtvd->bv_size);813memset(brtvd->bv_bitmap, 0, BT_SIZEOFMAP(nblocks));814brtvd->bv_entcount_dirty = FALSE;815}816817dmu_buf_will_dirty(db, tx);818bvphys = db->db_data;819bvphys->bvp_mos_entries = brtvd->bv_mos_entries;820bvphys->bvp_size = brtvd->bv_size;821if (brtvd->bv_need_byteswap) {822bvphys->bvp_byteorder = BRT_NON_NATIVE_BYTEORDER;823} else {824bvphys->bvp_byteorder = BRT_NATIVE_BYTEORDER;825}826bvphys->bvp_totalcount = brtvd->bv_totalcount;827bvphys->bvp_rangesize = spa->spa_brt_rangesize;828bvphys->bvp_usedspace = brtvd->bv_usedspace;829bvphys->bvp_savedspace = brtvd->bv_savedspace;830dmu_buf_rele(db, FTAG);831832brtvd->bv_meta_dirty = FALSE;833}834835static void836brt_vdevs_free(spa_t *spa)837{838if (spa->spa_brt_vdevs == 0)839return;840for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {841brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];842rw_enter(&brtvd->bv_lock, RW_WRITER);843if (brtvd->bv_initiated)844brt_vdev_dealloc(brtvd);845rw_exit(&brtvd->bv_lock);846rw_destroy(&brtvd->bv_lock);847if (brtvd->bv_mos_entries != 0)848dnode_rele(brtvd->bv_mos_entries_dnode, brtvd);849rw_destroy(&brtvd->bv_mos_entries_lock);850avl_destroy(&brtvd->bv_tree);851for (int i = 0; i < TXG_SIZE; i++)852avl_destroy(&brtvd->bv_pending_tree[i]);853mutex_destroy(&brtvd->bv_pending_lock);854kmem_free(brtvd, sizeof (*brtvd));855}856kmem_free(spa->spa_brt_vdevs, sizeof (*spa->spa_brt_vdevs) *857spa->spa_brt_nvdevs);858}859860static void861brt_entry_fill(const blkptr_t *bp, brt_entry_t *bre, uint64_t *vdevidp)862{863864bre->bre_bp = *bp;865bre->bre_count = 0;866bre->bre_pcount = 0;867868*vdevidp = DVA_GET_VDEV(&bp->blk_dva[0]);869}870871static boolean_t872brt_has_endian_fixed(spa_t *spa)873{874return (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING_ENDIAN));875}876877static int878brt_entry_lookup(spa_t *spa, brt_vdev_t *brtvd, brt_entry_t *bre)879{880uint64_t off = BRE_OFFSET(bre);881882if (brtvd->bv_mos_entries == 0)883return (SET_ERROR(ENOENT));884885if (brt_has_endian_fixed(spa)) {886return (zap_lookup_uint64_by_dnode(brtvd->bv_mos_entries_dnode,887&off, BRT_KEY_WORDS, sizeof (bre->bre_count), 1,888&bre->bre_count));889} else {890return (zap_lookup_uint64_by_dnode(brtvd->bv_mos_entries_dnode,891&off, BRT_KEY_WORDS, 1, sizeof (bre->bre_count),892&bre->bre_count));893}894}895896/*897* Return TRUE if we _can_ have BRT entry for this bp. It might be false898* positive, but gives us quick answer if we should look into BRT, which899* may require reads and thus will be more expensive.900*/901boolean_t902brt_maybe_exists(spa_t *spa, const blkptr_t *bp)903{904905if (spa->spa_brt_nvdevs == 0)906return (B_FALSE);907908uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);909brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);910if (brtvd == NULL || !brtvd->bv_initiated)911return (FALSE);912913/*914* We don't need locks here, since bv_entcount pointer must be915* stable at this point, and we don't care about false positive916* races here, while false negative should be impossible, since917* all brt_vdev_addref() have already completed by this point.918*/919uint64_t off = DVA_GET_OFFSET(&bp->blk_dva[0]);920return (brt_vdev_lookup(spa, brtvd, off));921}922923uint64_t924brt_get_dspace(spa_t *spa)925{926if (spa->spa_brt_nvdevs == 0)927return (0);928929brt_rlock(spa);930uint64_t s = 0;931for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++)932s += spa->spa_brt_vdevs[vdevid]->bv_savedspace;933brt_unlock(spa);934return (s);935}936937uint64_t938brt_get_used(spa_t *spa)939{940if (spa->spa_brt_nvdevs == 0)941return (0);942943brt_rlock(spa);944uint64_t s = 0;945for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++)946s += spa->spa_brt_vdevs[vdevid]->bv_usedspace;947brt_unlock(spa);948return (s);949}950951uint64_t952brt_get_saved(spa_t *spa)953{954return (brt_get_dspace(spa));955}956957uint64_t958brt_get_ratio(spa_t *spa)959{960uint64_t used = brt_get_used(spa);961if (used == 0)962return (100);963return ((used + brt_get_saved(spa)) * 100 / used);964}965966static int967brt_kstats_update(kstat_t *ksp, int rw)968{969brt_stats_t *bs = ksp->ks_data;970971if (rw == KSTAT_WRITE)972return (EACCES);973974bs->brt_addref_entry_not_on_disk.value.ui64 =975wmsum_value(&brt_sums.brt_addref_entry_not_on_disk);976bs->brt_addref_entry_on_disk.value.ui64 =977wmsum_value(&brt_sums.brt_addref_entry_on_disk);978bs->brt_decref_entry_in_memory.value.ui64 =979wmsum_value(&brt_sums.brt_decref_entry_in_memory);980bs->brt_decref_entry_loaded_from_disk.value.ui64 =981wmsum_value(&brt_sums.brt_decref_entry_loaded_from_disk);982bs->brt_decref_entry_not_in_memory.value.ui64 =983wmsum_value(&brt_sums.brt_decref_entry_not_in_memory);984bs->brt_decref_entry_read_lost_race.value.ui64 =985wmsum_value(&brt_sums.brt_decref_entry_read_lost_race);986bs->brt_decref_entry_still_referenced.value.ui64 =987wmsum_value(&brt_sums.brt_decref_entry_still_referenced);988bs->brt_decref_free_data_later.value.ui64 =989wmsum_value(&brt_sums.brt_decref_free_data_later);990bs->brt_decref_free_data_now.value.ui64 =991wmsum_value(&brt_sums.brt_decref_free_data_now);992bs->brt_decref_no_entry.value.ui64 =993wmsum_value(&brt_sums.brt_decref_no_entry);994995return (0);996}997998static void999brt_stat_init(void)1000{10011002wmsum_init(&brt_sums.brt_addref_entry_not_on_disk, 0);1003wmsum_init(&brt_sums.brt_addref_entry_on_disk, 0);1004wmsum_init(&brt_sums.brt_decref_entry_in_memory, 0);1005wmsum_init(&brt_sums.brt_decref_entry_loaded_from_disk, 0);1006wmsum_init(&brt_sums.brt_decref_entry_not_in_memory, 0);1007wmsum_init(&brt_sums.brt_decref_entry_read_lost_race, 0);1008wmsum_init(&brt_sums.brt_decref_entry_still_referenced, 0);1009wmsum_init(&brt_sums.brt_decref_free_data_later, 0);1010wmsum_init(&brt_sums.brt_decref_free_data_now, 0);1011wmsum_init(&brt_sums.brt_decref_no_entry, 0);10121013brt_ksp = kstat_create("zfs", 0, "brtstats", "misc", KSTAT_TYPE_NAMED,1014sizeof (brt_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);1015if (brt_ksp != NULL) {1016brt_ksp->ks_data = &brt_stats;1017brt_ksp->ks_update = brt_kstats_update;1018kstat_install(brt_ksp);1019}1020}10211022static void1023brt_stat_fini(void)1024{1025if (brt_ksp != NULL) {1026kstat_delete(brt_ksp);1027brt_ksp = NULL;1028}10291030wmsum_fini(&brt_sums.brt_addref_entry_not_on_disk);1031wmsum_fini(&brt_sums.brt_addref_entry_on_disk);1032wmsum_fini(&brt_sums.brt_decref_entry_in_memory);1033wmsum_fini(&brt_sums.brt_decref_entry_loaded_from_disk);1034wmsum_fini(&brt_sums.brt_decref_entry_not_in_memory);1035wmsum_fini(&brt_sums.brt_decref_entry_read_lost_race);1036wmsum_fini(&brt_sums.brt_decref_entry_still_referenced);1037wmsum_fini(&brt_sums.brt_decref_free_data_later);1038wmsum_fini(&brt_sums.brt_decref_free_data_now);1039wmsum_fini(&brt_sums.brt_decref_no_entry);1040}10411042void1043brt_init(void)1044{1045brt_entry_cache = kmem_cache_create("brt_entry_cache",1046sizeof (brt_entry_t), 0, NULL, NULL, NULL, NULL, NULL, 0);10471048brt_stat_init();1049}10501051void1052brt_fini(void)1053{1054brt_stat_fini();10551056kmem_cache_destroy(brt_entry_cache);1057}10581059/* Return TRUE if block should be freed immediately. */1060boolean_t1061brt_entry_decref(spa_t *spa, const blkptr_t *bp)1062{1063brt_entry_t *bre, *racebre;1064brt_entry_t bre_search;1065avl_index_t where;1066uint64_t vdevid;1067int error;10681069brt_entry_fill(bp, &bre_search, &vdevid);10701071brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);1072ASSERT(brtvd != NULL);10731074rw_enter(&brtvd->bv_lock, RW_WRITER);1075ASSERT(brtvd->bv_initiated);1076bre = avl_find(&brtvd->bv_tree, &bre_search, NULL);1077if (bre != NULL) {1078BRTSTAT_BUMP(brt_decref_entry_in_memory);1079goto out;1080} else {1081BRTSTAT_BUMP(brt_decref_entry_not_in_memory);1082}1083rw_exit(&brtvd->bv_lock);10841085error = brt_entry_lookup(spa, brtvd, &bre_search);1086/* bre_search now contains correct bre_count */1087if (error == ENOENT) {1088BRTSTAT_BUMP(brt_decref_no_entry);1089return (B_TRUE);1090}1091ASSERT0(error);10921093rw_enter(&brtvd->bv_lock, RW_WRITER);1094racebre = avl_find(&brtvd->bv_tree, &bre_search, &where);1095if (racebre != NULL) {1096/* The entry was added when the lock was dropped. */1097BRTSTAT_BUMP(brt_decref_entry_read_lost_race);1098bre = racebre;1099goto out;1100}11011102BRTSTAT_BUMP(brt_decref_entry_loaded_from_disk);1103bre = kmem_cache_alloc(brt_entry_cache, KM_SLEEP);1104bre->bre_bp = bre_search.bre_bp;1105bre->bre_count = bre_search.bre_count;1106bre->bre_pcount = 0;1107avl_insert(&brtvd->bv_tree, bre, where);11081109out:1110if (bre->bre_count == 0) {1111rw_exit(&brtvd->bv_lock);1112BRTSTAT_BUMP(brt_decref_free_data_now);1113return (B_TRUE);1114}11151116bre->bre_pcount--;1117ASSERT(bre->bre_count > 0);1118bre->bre_count--;1119if (bre->bre_count == 0)1120BRTSTAT_BUMP(brt_decref_free_data_later);1121else1122BRTSTAT_BUMP(brt_decref_entry_still_referenced);1123brt_vdev_decref(spa, brtvd, bre, bp_get_dsize_sync(spa, bp));11241125rw_exit(&brtvd->bv_lock);11261127return (B_FALSE);1128}11291130uint64_t1131brt_entry_get_refcount(spa_t *spa, const blkptr_t *bp)1132{1133brt_entry_t bre_search, *bre;1134uint64_t vdevid, refcnt;1135int error;11361137brt_entry_fill(bp, &bre_search, &vdevid);11381139brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);1140ASSERT(brtvd != NULL);11411142rw_enter(&brtvd->bv_lock, RW_READER);1143ASSERT(brtvd->bv_initiated);1144bre = avl_find(&brtvd->bv_tree, &bre_search, NULL);1145if (bre == NULL) {1146rw_exit(&brtvd->bv_lock);1147error = brt_entry_lookup(spa, brtvd, &bre_search);1148if (error == ENOENT) {1149refcnt = 0;1150} else {1151ASSERT0(error);1152refcnt = bre_search.bre_count;1153}1154} else {1155refcnt = bre->bre_count;1156rw_exit(&brtvd->bv_lock);1157}11581159return (refcnt);1160}11611162static void1163brt_prefetch(brt_vdev_t *brtvd, const blkptr_t *bp)1164{1165if (!brt_zap_prefetch || brtvd->bv_mos_entries == 0)1166return;11671168uint64_t off = DVA_GET_OFFSET(&bp->blk_dva[0]);1169rw_enter(&brtvd->bv_mos_entries_lock, RW_READER);1170if (brtvd->bv_mos_entries != 0) {1171(void) zap_prefetch_uint64_by_dnode(brtvd->bv_mos_entries_dnode,1172&off, BRT_KEY_WORDS);1173}1174rw_exit(&brtvd->bv_mos_entries_lock);1175}11761177static int1178brt_entry_compare(const void *x1, const void *x2)1179{1180const brt_entry_t *bre1 = x1, *bre2 = x2;1181const blkptr_t *bp1 = &bre1->bre_bp, *bp2 = &bre2->bre_bp;11821183return (TREE_CMP(DVA_GET_OFFSET(&bp1->blk_dva[0]),1184DVA_GET_OFFSET(&bp2->blk_dva[0])));1185}11861187void1188brt_pending_add(spa_t *spa, const blkptr_t *bp, dmu_tx_t *tx)1189{1190brt_entry_t *bre, *newbre;1191avl_index_t where;1192uint64_t txg;11931194txg = dmu_tx_get_txg(tx);1195ASSERT3U(txg, !=, 0);11961197uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);1198brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_TRUE);1199avl_tree_t *pending_tree = &brtvd->bv_pending_tree[txg & TXG_MASK];12001201newbre = kmem_cache_alloc(brt_entry_cache, KM_SLEEP);1202newbre->bre_bp = *bp;1203newbre->bre_count = 0;1204newbre->bre_pcount = 1;12051206mutex_enter(&brtvd->bv_pending_lock);1207bre = avl_find(pending_tree, newbre, &where);1208if (bre == NULL) {1209avl_insert(pending_tree, newbre, where);1210newbre = NULL;1211} else {1212bre->bre_pcount++;1213}1214mutex_exit(&brtvd->bv_pending_lock);12151216if (newbre != NULL) {1217ASSERT(bre != NULL);1218ASSERT(bre != newbre);1219kmem_cache_free(brt_entry_cache, newbre);1220} else {1221ASSERT0P(bre);12221223/* Prefetch BRT entry for the syncing context. */1224brt_prefetch(brtvd, bp);1225}1226}12271228void1229brt_pending_remove(spa_t *spa, const blkptr_t *bp, dmu_tx_t *tx)1230{1231brt_entry_t *bre, bre_search;1232uint64_t txg;12331234txg = dmu_tx_get_txg(tx);1235ASSERT3U(txg, !=, 0);12361237uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[0]);1238brt_vdev_t *brtvd = brt_vdev(spa, vdevid, B_FALSE);1239ASSERT(brtvd != NULL);1240avl_tree_t *pending_tree = &brtvd->bv_pending_tree[txg & TXG_MASK];12411242bre_search.bre_bp = *bp;12431244mutex_enter(&brtvd->bv_pending_lock);1245bre = avl_find(pending_tree, &bre_search, NULL);1246ASSERT(bre != NULL);1247ASSERT(bre->bre_pcount > 0);1248bre->bre_pcount--;1249if (bre->bre_pcount == 0)1250avl_remove(pending_tree, bre);1251else1252bre = NULL;1253mutex_exit(&brtvd->bv_pending_lock);12541255if (bre)1256kmem_cache_free(brt_entry_cache, bre);1257}12581259static void1260brt_pending_apply_vdev(spa_t *spa, brt_vdev_t *brtvd, uint64_t txg)1261{1262brt_entry_t *bre, *nbre;12631264/*1265* We are in syncing context, so no other bv_pending_tree accesses1266* are possible for the TXG. So we don't need bv_pending_lock.1267*/1268ASSERT(avl_is_empty(&brtvd->bv_tree));1269avl_swap(&brtvd->bv_tree, &brtvd->bv_pending_tree[txg & TXG_MASK]);12701271for (bre = avl_first(&brtvd->bv_tree); bre; bre = nbre) {1272nbre = AVL_NEXT(&brtvd->bv_tree, bre);12731274/*1275* If the block has DEDUP bit set, it means that it1276* already exists in the DEDUP table, so we can just1277* use that instead of creating new entry in the BRT.1278*/1279if (BP_GET_DEDUP(&bre->bre_bp)) {1280while (bre->bre_pcount > 0) {1281if (!ddt_addref(spa, &bre->bre_bp))1282break;1283bre->bre_pcount--;1284}1285if (bre->bre_pcount == 0) {1286avl_remove(&brtvd->bv_tree, bre);1287kmem_cache_free(brt_entry_cache, bre);1288continue;1289}1290}12911292/*1293* Unless we know that the block is definitely not in ZAP,1294* try to get its reference count from there.1295*/1296uint64_t off = BRE_OFFSET(bre);1297if (brtvd->bv_mos_entries != 0 &&1298brt_vdev_lookup(spa, brtvd, off)) {1299int error;1300if (brt_has_endian_fixed(spa)) {1301error = zap_lookup_uint64_by_dnode(1302brtvd->bv_mos_entries_dnode, &off,1303BRT_KEY_WORDS, sizeof (bre->bre_count), 1,1304&bre->bre_count);1305} else {1306error = zap_lookup_uint64_by_dnode(1307brtvd->bv_mos_entries_dnode, &off,1308BRT_KEY_WORDS, 1, sizeof (bre->bre_count),1309&bre->bre_count);1310}1311if (error == 0) {1312BRTSTAT_BUMP(brt_addref_entry_on_disk);1313} else {1314ASSERT3U(error, ==, ENOENT);1315BRTSTAT_BUMP(brt_addref_entry_not_on_disk);1316}1317}1318}13191320/*1321* If all the cloned blocks we had were handled by DDT, we don't need1322* to initiate the vdev.1323*/1324if (avl_is_empty(&brtvd->bv_tree))1325return;13261327if (!brtvd->bv_initiated) {1328rw_enter(&brtvd->bv_lock, RW_WRITER);1329brt_vdev_realloc(spa, brtvd);1330rw_exit(&brtvd->bv_lock);1331}13321333/*1334* Convert pending references into proper ones. This has to be a1335* separate loop, since entcount modifications would cause false1336* positives for brt_vdev_lookup() on following iterations.1337*/1338for (bre = avl_first(&brtvd->bv_tree); bre;1339bre = AVL_NEXT(&brtvd->bv_tree, bre)) {1340brt_vdev_addref(spa, brtvd, bre,1341bp_get_dsize(spa, &bre->bre_bp), bre->bre_pcount);1342bre->bre_count += bre->bre_pcount;1343}1344}13451346void1347brt_pending_apply(spa_t *spa, uint64_t txg)1348{13491350brt_rlock(spa);1351for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {1352brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];1353brt_unlock(spa);13541355brt_pending_apply_vdev(spa, brtvd, txg);13561357brt_rlock(spa);1358}1359brt_unlock(spa);1360}13611362static void1363brt_sync_entry(spa_t *spa, dnode_t *dn, brt_entry_t *bre, dmu_tx_t *tx)1364{1365uint64_t off = BRE_OFFSET(bre);13661367if (bre->bre_pcount == 0) {1368/* The net change is zero, nothing to do in ZAP. */1369} else if (bre->bre_count == 0) {1370int error = zap_remove_uint64_by_dnode(dn, &off,1371BRT_KEY_WORDS, tx);1372VERIFY(error == 0 || error == ENOENT);1373} else {1374if (brt_has_endian_fixed(spa)) {1375VERIFY0(zap_update_uint64_by_dnode(dn, &off,1376BRT_KEY_WORDS, sizeof (bre->bre_count), 1,1377&bre->bre_count, tx));1378} else {1379VERIFY0(zap_update_uint64_by_dnode(dn, &off,1380BRT_KEY_WORDS, 1, sizeof (bre->bre_count),1381&bre->bre_count, tx));1382}1383}1384}13851386static void1387brt_sync_table(spa_t *spa, dmu_tx_t *tx)1388{1389brt_entry_t *bre;13901391brt_rlock(spa);1392for (uint64_t vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {1393brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];1394brt_unlock(spa);13951396if (!brtvd->bv_meta_dirty) {1397ASSERT(!brtvd->bv_entcount_dirty);1398ASSERT0(avl_numnodes(&brtvd->bv_tree));1399brt_rlock(spa);1400continue;1401}14021403ASSERT(!brtvd->bv_entcount_dirty ||1404avl_numnodes(&brtvd->bv_tree) != 0);14051406if (brtvd->bv_mos_brtvdev == 0)1407brt_vdev_create(spa, brtvd, tx);14081409void *c = NULL;1410while ((bre = avl_destroy_nodes(&brtvd->bv_tree, &c)) != NULL) {1411brt_sync_entry(spa, brtvd->bv_mos_entries_dnode, bre,1412tx);1413kmem_cache_free(brt_entry_cache, bre);1414}14151416#ifdef ZFS_DEBUG1417if (zfs_flags & ZFS_DEBUG_BRT)1418brt_vdev_dump(brtvd);1419#endif1420if (brtvd->bv_totalcount == 0)1421brt_vdev_destroy(spa, brtvd, tx);1422else1423brt_vdev_sync(spa, brtvd, tx);1424brt_rlock(spa);1425}1426brt_unlock(spa);1427}14281429void1430brt_sync(spa_t *spa, uint64_t txg)1431{1432dmu_tx_t *tx;1433uint64_t vdevid;14341435ASSERT3U(spa_syncing_txg(spa), ==, txg);14361437brt_rlock(spa);1438for (vdevid = 0; vdevid < spa->spa_brt_nvdevs; vdevid++) {1439if (spa->spa_brt_vdevs[vdevid]->bv_meta_dirty)1440break;1441}1442if (vdevid >= spa->spa_brt_nvdevs) {1443brt_unlock(spa);1444return;1445}1446brt_unlock(spa);14471448tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);1449brt_sync_table(spa, tx);1450dmu_tx_commit(tx);1451}14521453static void1454brt_alloc(spa_t *spa)1455{1456rw_init(&spa->spa_brt_lock, NULL, RW_DEFAULT, NULL);1457spa->spa_brt_vdevs = NULL;1458spa->spa_brt_nvdevs = 0;1459spa->spa_brt_rangesize = 0;1460}14611462void1463brt_create(spa_t *spa)1464{1465brt_alloc(spa);1466spa->spa_brt_rangesize = BRT_RANGESIZE;1467}14681469int1470brt_load(spa_t *spa)1471{1472int error = 0;14731474brt_alloc(spa);1475brt_wlock(spa);1476for (uint64_t vdevid = 0; vdevid < spa->spa_root_vdev->vdev_children;1477vdevid++) {1478char name[64];1479uint64_t mos_brtvdev;14801481/* Look if this vdev had active block cloning. */1482snprintf(name, sizeof (name), "%s%llu", BRT_OBJECT_VDEV_PREFIX,1483(u_longlong_t)vdevid);1484error = zap_lookup(spa->spa_meta_objset,1485DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,1486&mos_brtvdev);1487if (error == ENOENT) {1488error = 0;1489continue;1490}1491if (error != 0)1492break;14931494/* If it did, then allocate them all and load this one. */1495brt_vdevs_expand(spa, spa->spa_root_vdev->vdev_children);1496brt_vdev_t *brtvd = spa->spa_brt_vdevs[vdevid];1497rw_enter(&brtvd->bv_lock, RW_WRITER);1498brtvd->bv_mos_brtvdev = mos_brtvdev;1499error = brt_vdev_load(spa, brtvd);1500rw_exit(&brtvd->bv_lock);1501if (error != 0)1502break;1503}15041505if (spa->spa_brt_rangesize == 0)1506spa->spa_brt_rangesize = BRT_RANGESIZE;1507brt_unlock(spa);1508return (error);1509}15101511void1512brt_unload(spa_t *spa)1513{1514if (spa->spa_brt_rangesize == 0)1515return;1516brt_vdevs_free(spa);1517rw_destroy(&spa->spa_brt_lock);1518spa->spa_brt_rangesize = 0;1519}15201521ZFS_MODULE_PARAM(zfs_brt, , brt_zap_prefetch, INT, ZMOD_RW,1522"Enable prefetching of BRT ZAP entries");1523ZFS_MODULE_PARAM(zfs_brt, , brt_zap_default_bs, UINT, ZMOD_RW,1524"BRT ZAP leaf blockshift");1525ZFS_MODULE_PARAM(zfs_brt, , brt_zap_default_ibs, UINT, ZMOD_RW,1526"BRT ZAP indirect blockshift");152715281529