Path: blob/main/sys/contrib/openzfs/module/zfs/ddt.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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.24* Copyright (c) 2012, 2016 by Delphix. All rights reserved.25* Copyright (c) 2022 by Pawel Jakub Dawidek26* Copyright (c) 2019, 2023, Klara Inc.27*/2829#include <sys/zfs_context.h>30#include <sys/spa.h>31#include <sys/spa_impl.h>32#include <sys/zio.h>33#include <sys/ddt.h>34#include <sys/ddt_impl.h>35#include <sys/zap.h>36#include <sys/dmu_tx.h>37#include <sys/arc.h>38#include <sys/dsl_pool.h>39#include <sys/zio_checksum.h>40#include <sys/dsl_scan.h>41#include <sys/abd.h>42#include <sys/zfeature.h>4344/*45* # DDT: Deduplication tables46*47* The dedup subsystem provides block-level deduplication. When enabled, blocks48* to be written will have the dedup (D) bit set, which causes them to be49* tracked in a "dedup table", or DDT. If a block has been seen before (exists50* in the DDT), instead of being written, it will instead be made to reference51* the existing on-disk data, and a refcount bumped in the DDT instead.52*53* ## Dedup tables and entries54*55* Conceptually, a DDT is a dictionary or map. Each entry has a "key"56* (ddt_key_t) made up a block's checksum and certian properties, and a "value"57* (one or more ddt_phys_t) containing valid DVAs for the block's data, birth58* time and refcount. Together these are enough to track references to a59* specific block, to build a valid block pointer to reference that block (for60* freeing, scrubbing, etc), and to fill a new block pointer with the missing61* pieces to make it seem like it was written.62*63* There's a single DDT (ddt_t) for each checksum type, held in spa_ddt[].64* Within each DDT, there can be multiple storage "types" (ddt_type_t, on-disk65* object data formats, each with their own implementations) and "classes"66* (ddt_class_t, instance of a storage type object, for entries with a specific67* characteristic). An entry (key) will only ever exist on one of these objects68* at any given time, but may be moved from one to another if their type or69* class changes.70*71* The DDT is driven by the write IO pipeline (zio_ddt_write()). When a block72* is to be written, before DVAs have been allocated, ddt_lookup() is called to73* see if the block has been seen before. If its not found, the write proceeds74* as normal, and after it succeeds, a new entry is created. If it is found, we75* fill the BP with the DVAs from the entry, increment the refcount and cause76* the write IO to return immediately.77*78* Traditionally, each ddt_phys_t slot in the entry represents a separate dedup79* block for the same content/checksum. The slot is selected based on the80* zp_copies parameter the block is written with, that is, the number of DVAs81* in the block. The "ditto" slot (DDT_PHYS_DITTO) used to be used for82* now-removed "dedupditto" feature. These are no longer written, and will be83* freed if encountered on old pools.84*85* If the "fast_dedup" feature is enabled, new dedup tables will be created86* with the "flat phys" option. In this mode, there is only one ddt_phys_t87* slot. If a write is issued for an entry that exists, but has fewer DVAs,88* then only as many new DVAs are allocated and written to make up the89* shortfall. The existing entry is then extended (ddt_phys_extend()) with the90* new DVAs.91*92* ## Lifetime of an entry93*94* A DDT can be enormous, and typically is not held in memory all at once.95* Instead, the changes to an entry are tracked in memory, and written down to96* disk at the end of each txg.97*98* A "live" in-memory entry (ddt_entry_t) is a node on the live tree99* (ddt_tree). At the start of a txg, ddt_tree is empty. When an entry is100* required for IO, ddt_lookup() is called. If an entry already exists on101* ddt_tree, it is returned. Otherwise, a new one is created, and the102* type/class objects for the DDT are searched for that key. If its found, its103* value is copied into the live entry. If not, an empty entry is created.104*105* The live entry will be modified during the txg, usually by modifying the106* refcount, but sometimes by adding or updating DVAs. At the end of the txg107* (during spa_sync()), type and class are recalculated for entry (see108* ddt_sync_entry()), and the entry is written to the appropriate storage109* object and (if necessary), removed from an old one. ddt_tree is cleared and110* the next txg can start.111*112* ## Dedup quota113*114* A maximum size for all DDTs on the pool can be set with the115* dedup_table_quota property. This is determined in ddt_over_quota() and116* enforced during ddt_lookup(). If the pool is at or over its quota limit,117* ddt_lookup() will only return entries for existing blocks, as updates are118* still possible. New entries will not be created; instead, ddt_lookup() will119* return NULL. In response, the DDT write stage (zio_ddt_write()) will remove120* the D bit on the block and reissue the IO as a regular write. The block will121* not be deduplicated.122*123* Note that this is based on the on-disk size of the dedup store. Reclaiming124* this space after deleting entries relies on the ZAP "shrinking" behaviour,125* without which, no space would be recovered and the DDT would continue to be126* considered "over quota". See zap_shrink_enabled.127*128* ## Dedup table pruning129*130* As a complement to the dedup quota feature, ddtprune allows removal of older131* non-duplicate entries to make room for newer duplicate entries. The amount132* to prune can be based on a target percentage of the unique entries or based133* on the age (i.e., prune unique entry older than N days).134*135* ## Dedup log136*137* Historically, all entries modified on a txg were written back to dedup138* storage objects at the end of every txg. This could cause significant139* overheads, as each entry only takes up a tiny portion of a ZAP leaf node,140* and so required reading the whole node, updating the entry, and writing it141* back. On busy pools, this could add serious IO and memory overheads.142*143* To address this, the dedup log was added. If the "fast_dedup" feature is144* enabled, at the end of each txg, modified entries will be copied to an145* in-memory "log" object (ddt_log_t), and appended to an on-disk log. If the146* same block is requested again, the in-memory object will be checked first,147* and if its there, the entry inflated back onto the live tree without going148* to storage. The on-disk log is only read at pool import time, to reload the149* in-memory log.150*151* Each txg, some amount of the in-memory log will be flushed out to a DDT152* storage object (ie ZAP) as normal. OpenZFS will try hard to flush enough to153* keep up with the rate of change on dedup entries, but not so much that it154* would impact overall throughput, and not using too much memory. See the155* zfs_dedup_log_* tunables in zfs(4) for more details.156*157* ## Repair IO158*159* If a read on a dedup block fails, but there are other copies of the block in160* the other ddt_phys_t slots, reads will be issued for those instead161* (zio_ddt_read_start()). If one of those succeeds, the read is returned to162* the caller, and a copy is stashed on the entry's dde_repair_abd.163*164* During the end-of-txg sync, any entries with a dde_repair_abd get a165* "rewrite" write issued for the original block pointer, with the data read166* from the alternate block. If the block is actually damaged, this will invoke167* the pool's "self-healing" mechanism, and repair the block.168*169* If the "fast_dedup" feature is enabled, the "flat phys" option will be in170* use, so there is only ever one ddt_phys_t slot. The repair process will171* still happen in this case, though it is unlikely to succeed as there will172* usually be no other equivalent blocks to fall back on (though there might173* be, if this was an early version of a dedup'd block that has since been174* extended).175*176* Note that this repair mechanism is in addition to and separate from the177* regular OpenZFS scrub and self-healing mechanisms.178*179* ## Scanning (scrub/resilver)180*181* If dedup is active, the scrub machinery will walk the dedup table first, and182* scrub all blocks with refcnt > 1 first. After that it will move on to the183* regular top-down scrub, and exclude the refcnt > 1 blocks when it sees them.184* In this way, heavily deduplicated blocks are only scrubbed once. See the185* commentary on dsl_scan_ddt() for more details.186*187* Walking the DDT is done via ddt_walk(). The current position is stored in a188* ddt_bookmark_t, which represents a stable position in the storage object.189* This bookmark is stored by the scan machinery, and must reference the same190* position on the object even if the object changes, the pool is exported, or191* OpenZFS is upgraded.192*193* If the "fast_dedup" feature is enabled and the table has a log, the scan194* cannot begin until entries on the log are flushed, as the on-disk log has no195* concept of a "stable position". Instead, the log flushing process will enter196* a more aggressive mode, to flush out as much as is necesary as soon as197* possible, in order to begin the scan as soon as possible.198*199* ## Interaction with block cloning200*201* If block cloning and dedup are both enabled on a pool, BRT will look for the202* dedup bit on an incoming block pointer. If set, it will call into the DDT203* (ddt_addref()) to add a reference to the block, instead of adding a204* reference to the BRT. See brt_pending_apply().205*/206207/*208* These are the only checksums valid for dedup. They must match the list209* from dedup_table in zfs_prop.c210*/211#define DDT_CHECKSUM_VALID(c) \212(c == ZIO_CHECKSUM_SHA256 || c == ZIO_CHECKSUM_SHA512 || \213c == ZIO_CHECKSUM_SKEIN || c == ZIO_CHECKSUM_EDONR || \214c == ZIO_CHECKSUM_BLAKE3)215216static kmem_cache_t *ddt_cache;217218static kmem_cache_t *ddt_entry_flat_cache;219static kmem_cache_t *ddt_entry_trad_cache;220221#define DDT_ENTRY_FLAT_SIZE (sizeof (ddt_entry_t) + DDT_FLAT_PHYS_SIZE)222#define DDT_ENTRY_TRAD_SIZE (sizeof (ddt_entry_t) + DDT_TRAD_PHYS_SIZE)223224#define DDT_ENTRY_SIZE(ddt) \225_DDT_PHYS_SWITCH(ddt, DDT_ENTRY_FLAT_SIZE, DDT_ENTRY_TRAD_SIZE)226227/*228* Enable/disable prefetching of dedup-ed blocks which are going to be freed.229*/230int zfs_dedup_prefetch = 0;231232/*233* If the dedup class cannot satisfy a DDT allocation, treat as over quota234* for this many TXGs.235*/236uint_t dedup_class_wait_txgs = 5;237238/*239* How many DDT prune entries to add to the DDT sync AVL tree.240* Note these addtional entries have a memory footprint of a241* ddt_entry_t (216 bytes).242*/243static uint32_t zfs_ddt_prunes_per_txg = 50000;244245/*246* For testing, synthesize aged DDT entries247* (in global scope for ztest)248*/249boolean_t ddt_prune_artificial_age = B_FALSE;250boolean_t ddt_dump_prune_histogram = B_FALSE;251252/*253* Minimum time to flush per txg.254*/255uint_t zfs_dedup_log_flush_min_time_ms = 1000;256257/*258* Minimum entries to flush per txg.259*/260uint_t zfs_dedup_log_flush_entries_min = 200;261262/*263* Target number of TXGs until the whole dedup log has been flushed.264* The log size will float around this value times the ingest rate.265*/266uint_t zfs_dedup_log_flush_txgs = 100;267268/*269* Maximum entries to flush per txg. Used for testing the dedup log.270*/271uint_t zfs_dedup_log_flush_entries_max = UINT_MAX;272273/*274* Soft cap for the size of the current dedup log. If the log is larger275* than this size, we slightly increase the aggressiveness of the flushing to276* try to bring it back down to the soft cap.277*/278uint_t zfs_dedup_log_cap = UINT_MAX;279280/*281* If this is set to B_TRUE, the cap above acts more like a hard cap:282* flushing is significantly more aggressive, increasing the minimum amount we283* flush per txg, as well as the maximum.284*/285boolean_t zfs_dedup_log_hard_cap = B_FALSE;286287/*288* Number of txgs to average flow rates across.289*/290uint_t zfs_dedup_log_flush_flow_rate_txgs = 10;291292static const ddt_ops_t *const ddt_ops[DDT_TYPES] = {293&ddt_zap_ops,294};295296static const char *const ddt_class_name[DDT_CLASSES] = {297"ditto",298"duplicate",299"unique",300};301302/*303* DDT feature flags automatically enabled for each on-disk version. Note that304* versions >0 cannot exist on disk without SPA_FEATURE_FAST_DEDUP enabled.305*/306static const uint64_t ddt_version_flags[] = {307[DDT_VERSION_LEGACY] = 0,308[DDT_VERSION_FDT] = DDT_FLAG_FLAT | DDT_FLAG_LOG,309};310311/* per-DDT kstats */312typedef struct {313/* total lookups and whether they returned new or existing entries */314kstat_named_t dds_lookup;315kstat_named_t dds_lookup_new;316kstat_named_t dds_lookup_existing;317318/* entries found on live tree, and if we had to wait for load */319kstat_named_t dds_lookup_live_hit;320kstat_named_t dds_lookup_live_wait;321kstat_named_t dds_lookup_live_miss;322323/* entries found on log trees */324kstat_named_t dds_lookup_log_hit;325kstat_named_t dds_lookup_log_active_hit;326kstat_named_t dds_lookup_log_flushing_hit;327kstat_named_t dds_lookup_log_miss;328329/* entries found on store objects */330kstat_named_t dds_lookup_stored_hit;331kstat_named_t dds_lookup_stored_miss;332333/* number of entries on log trees */334kstat_named_t dds_log_active_entries;335kstat_named_t dds_log_flushing_entries;336337/* avg updated/flushed entries per txg */338kstat_named_t dds_log_ingest_rate;339kstat_named_t dds_log_flush_rate;340kstat_named_t dds_log_flush_time_rate;341} ddt_kstats_t;342343static const ddt_kstats_t ddt_kstats_template = {344{ "lookup", KSTAT_DATA_UINT64 },345{ "lookup_new", KSTAT_DATA_UINT64 },346{ "lookup_existing", KSTAT_DATA_UINT64 },347{ "lookup_live_hit", KSTAT_DATA_UINT64 },348{ "lookup_live_wait", KSTAT_DATA_UINT64 },349{ "lookup_live_miss", KSTAT_DATA_UINT64 },350{ "lookup_log_hit", KSTAT_DATA_UINT64 },351{ "lookup_log_active_hit", KSTAT_DATA_UINT64 },352{ "lookup_log_flushing_hit", KSTAT_DATA_UINT64 },353{ "lookup_log_miss", KSTAT_DATA_UINT64 },354{ "lookup_stored_hit", KSTAT_DATA_UINT64 },355{ "lookup_stored_miss", KSTAT_DATA_UINT64 },356{ "log_active_entries", KSTAT_DATA_UINT64 },357{ "log_flushing_entries", KSTAT_DATA_UINT64 },358{ "log_ingest_rate", KSTAT_DATA_UINT32 },359{ "log_flush_rate", KSTAT_DATA_UINT32 },360{ "log_flush_time_rate", KSTAT_DATA_UINT32 },361};362363#ifdef _KERNEL364#define _DDT_KSTAT_STAT(ddt, stat) \365&((ddt_kstats_t *)(ddt)->ddt_ksp->ks_data)->stat.value.ui64366#define DDT_KSTAT_BUMP(ddt, stat) \367do { atomic_inc_64(_DDT_KSTAT_STAT(ddt, stat)); } while (0)368#define DDT_KSTAT_ADD(ddt, stat, val) \369do { atomic_add_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)370#define DDT_KSTAT_SUB(ddt, stat, val) \371do { atomic_sub_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)372#define DDT_KSTAT_SET(ddt, stat, val) \373do { atomic_store_64(_DDT_KSTAT_STAT(ddt, stat), val); } while (0)374#define DDT_KSTAT_ZERO(ddt, stat) DDT_KSTAT_SET(ddt, stat, 0)375#else376#define DDT_KSTAT_BUMP(ddt, stat) do {} while (0)377#define DDT_KSTAT_ADD(ddt, stat, val) do {} while (0)378#define DDT_KSTAT_SUB(ddt, stat, val) do {} while (0)379#define DDT_KSTAT_SET(ddt, stat, val) do {} while (0)380#define DDT_KSTAT_ZERO(ddt, stat) do {} while (0)381#endif /* _KERNEL */382383384static void385ddt_object_create(ddt_t *ddt, ddt_type_t type, ddt_class_t class,386dmu_tx_t *tx)387{388spa_t *spa = ddt->ddt_spa;389objset_t *os = ddt->ddt_os;390uint64_t *objectp = &ddt->ddt_object[type][class];391boolean_t prehash = zio_checksum_table[ddt->ddt_checksum].ci_flags &392ZCHECKSUM_FLAG_DEDUP;393char name[DDT_NAMELEN];394395ASSERT3U(ddt->ddt_dir_object, >, 0);396397ddt_object_name(ddt, type, class, name);398399ASSERT0(*objectp);400VERIFY0(ddt_ops[type]->ddt_op_create(os, objectp, tx, prehash));401ASSERT3U(*objectp, !=, 0);402403ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);404405VERIFY0(zap_add(os, ddt->ddt_dir_object, name, sizeof (uint64_t), 1,406objectp, tx));407408VERIFY0(zap_add(os, spa->spa_ddt_stat_object, name,409sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),410&ddt->ddt_histogram[type][class], tx));411}412413static void414ddt_object_destroy(ddt_t *ddt, ddt_type_t type, ddt_class_t class,415dmu_tx_t *tx)416{417spa_t *spa = ddt->ddt_spa;418objset_t *os = ddt->ddt_os;419uint64_t *objectp = &ddt->ddt_object[type][class];420uint64_t count;421char name[DDT_NAMELEN];422423ASSERT3U(ddt->ddt_dir_object, >, 0);424425ddt_object_name(ddt, type, class, name);426427ASSERT3U(*objectp, !=, 0);428ASSERT(ddt_histogram_empty(&ddt->ddt_histogram[type][class]));429VERIFY0(ddt_object_count(ddt, type, class, &count));430VERIFY0(count);431VERIFY0(zap_remove(os, ddt->ddt_dir_object, name, tx));432VERIFY0(zap_remove(os, spa->spa_ddt_stat_object, name, tx));433VERIFY0(ddt_ops[type]->ddt_op_destroy(os, *objectp, tx));434memset(&ddt->ddt_object_stats[type][class], 0, sizeof (ddt_object_t));435436*objectp = 0;437}438439static int440ddt_object_load(ddt_t *ddt, ddt_type_t type, ddt_class_t class)441{442ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];443dmu_object_info_t doi;444uint64_t count;445char name[DDT_NAMELEN];446int error;447448if (ddt->ddt_dir_object == 0) {449/*450* If we're configured but the containing dir doesn't exist451* yet, then this object can't possibly exist either.452*/453ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);454return (SET_ERROR(ENOENT));455}456457ddt_object_name(ddt, type, class, name);458459error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object, name,460sizeof (uint64_t), 1, &ddt->ddt_object[type][class]);461if (error != 0)462return (error);463464error = zap_lookup(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,465sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),466&ddt->ddt_histogram[type][class]);467if (error != 0)468return (error);469470/*471* Seed the cached statistics.472*/473error = ddt_object_info(ddt, type, class, &doi);474if (error)475return (error);476477error = ddt_object_count(ddt, type, class, &count);478if (error)479return (error);480481ddo->ddo_count = count;482ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;483ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;484485return (0);486}487488static void489ddt_object_sync(ddt_t *ddt, ddt_type_t type, ddt_class_t class,490dmu_tx_t *tx)491{492ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];493dmu_object_info_t doi;494uint64_t count;495char name[DDT_NAMELEN];496497ddt_object_name(ddt, type, class, name);498499VERIFY0(zap_update(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,500sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),501&ddt->ddt_histogram[type][class], tx));502503/*504* Cache DDT statistics; this is the only time they'll change.505*/506VERIFY0(ddt_object_info(ddt, type, class, &doi));507VERIFY0(ddt_object_count(ddt, type, class, &count));508509ddo->ddo_count = count;510ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;511ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;512}513514static boolean_t515ddt_object_exists(ddt_t *ddt, ddt_type_t type, ddt_class_t class)516{517return (!!ddt->ddt_object[type][class]);518}519520static int521ddt_object_lookup(ddt_t *ddt, ddt_type_t type, ddt_class_t class,522ddt_entry_t *dde)523{524if (!ddt_object_exists(ddt, type, class))525return (SET_ERROR(ENOENT));526527return (ddt_ops[type]->ddt_op_lookup(ddt->ddt_os,528ddt->ddt_object[type][class], &dde->dde_key,529dde->dde_phys, DDT_PHYS_SIZE(ddt)));530}531532static int533ddt_object_contains(ddt_t *ddt, ddt_type_t type, ddt_class_t class,534const ddt_key_t *ddk)535{536if (!ddt_object_exists(ddt, type, class))537return (SET_ERROR(ENOENT));538539return (ddt_ops[type]->ddt_op_contains(ddt->ddt_os,540ddt->ddt_object[type][class], ddk));541}542543static void544ddt_object_prefetch(ddt_t *ddt, ddt_type_t type, ddt_class_t class,545const ddt_key_t *ddk)546{547if (!ddt_object_exists(ddt, type, class))548return;549550ddt_ops[type]->ddt_op_prefetch(ddt->ddt_os,551ddt->ddt_object[type][class], ddk);552}553554static void555ddt_object_prefetch_all(ddt_t *ddt, ddt_type_t type, ddt_class_t class)556{557if (!ddt_object_exists(ddt, type, class))558return;559560ddt_ops[type]->ddt_op_prefetch_all(ddt->ddt_os,561ddt->ddt_object[type][class]);562}563564static int565ddt_object_update(ddt_t *ddt, ddt_type_t type, ddt_class_t class,566const ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)567{568ASSERT(ddt_object_exists(ddt, type, class));569570return (ddt_ops[type]->ddt_op_update(ddt->ddt_os,571ddt->ddt_object[type][class], &ddlwe->ddlwe_key,572&ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt), tx));573}574575static int576ddt_object_remove(ddt_t *ddt, ddt_type_t type, ddt_class_t class,577const ddt_key_t *ddk, dmu_tx_t *tx)578{579ASSERT(ddt_object_exists(ddt, type, class));580581return (ddt_ops[type]->ddt_op_remove(ddt->ddt_os,582ddt->ddt_object[type][class], ddk, tx));583}584585int586ddt_object_walk(ddt_t *ddt, ddt_type_t type, ddt_class_t class,587uint64_t *walk, ddt_lightweight_entry_t *ddlwe)588{589ASSERT(ddt_object_exists(ddt, type, class));590591int error = ddt_ops[type]->ddt_op_walk(ddt->ddt_os,592ddt->ddt_object[type][class], walk, &ddlwe->ddlwe_key,593&ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt));594if (error == 0) {595ddlwe->ddlwe_type = type;596ddlwe->ddlwe_class = class;597return (0);598}599return (error);600}601602int603ddt_object_count(ddt_t *ddt, ddt_type_t type, ddt_class_t class,604uint64_t *count)605{606ASSERT(ddt_object_exists(ddt, type, class));607608return (ddt_ops[type]->ddt_op_count(ddt->ddt_os,609ddt->ddt_object[type][class], count));610}611612int613ddt_object_info(ddt_t *ddt, ddt_type_t type, ddt_class_t class,614dmu_object_info_t *doi)615{616if (!ddt_object_exists(ddt, type, class))617return (SET_ERROR(ENOENT));618619return (dmu_object_info(ddt->ddt_os, ddt->ddt_object[type][class],620doi));621}622623void624ddt_object_name(ddt_t *ddt, ddt_type_t type, ddt_class_t class,625char *name)626{627(void) snprintf(name, DDT_NAMELEN, DMU_POOL_DDT,628zio_checksum_table[ddt->ddt_checksum].ci_name,629ddt_ops[type]->ddt_op_name, ddt_class_name[class]);630}631632void633ddt_bp_fill(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,634blkptr_t *bp, uint64_t txg)635{636ASSERT3U(txg, !=, 0);637ASSERT3U(v, <, DDT_PHYS_NONE);638uint64_t phys_birth;639const dva_t *dvap;640641if (v == DDT_PHYS_FLAT) {642phys_birth = ddp->ddp_flat.ddp_phys_birth;643dvap = ddp->ddp_flat.ddp_dva;644} else {645phys_birth = ddp->ddp_trad[v].ddp_phys_birth;646dvap = ddp->ddp_trad[v].ddp_dva;647}648649for (int d = 0; d < SPA_DVAS_PER_BP; d++)650bp->blk_dva[d] = dvap[d];651BP_SET_BIRTH(bp, txg, phys_birth);652}653654/*655* The bp created via this function may be used for repairs and scrub, but it656* will be missing the salt / IV required to do a full decrypting read.657*/658void659ddt_bp_create(enum zio_checksum checksum, const ddt_key_t *ddk,660const ddt_univ_phys_t *ddp, ddt_phys_variant_t v, blkptr_t *bp)661{662BP_ZERO(bp);663664if (ddp != NULL)665ddt_bp_fill(ddp, v, bp, ddt_phys_birth(ddp, v));666667bp->blk_cksum = ddk->ddk_cksum;668669BP_SET_LSIZE(bp, DDK_GET_LSIZE(ddk));670BP_SET_PSIZE(bp, DDK_GET_PSIZE(ddk));671BP_SET_COMPRESS(bp, DDK_GET_COMPRESS(ddk));672BP_SET_CRYPT(bp, DDK_GET_CRYPT(ddk));673BP_SET_FILL(bp, 1);674BP_SET_CHECKSUM(bp, checksum);675BP_SET_TYPE(bp, DMU_OT_DEDUP);676BP_SET_LEVEL(bp, 0);677BP_SET_DEDUP(bp, 1);678BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);679}680681void682ddt_key_fill(ddt_key_t *ddk, const blkptr_t *bp)683{684ddk->ddk_cksum = bp->blk_cksum;685ddk->ddk_prop = 0;686687ASSERT(BP_IS_ENCRYPTED(bp) || !BP_USES_CRYPT(bp));688689DDK_SET_LSIZE(ddk, BP_GET_LSIZE(bp));690DDK_SET_PSIZE(ddk, BP_GET_PSIZE(bp));691DDK_SET_COMPRESS(ddk, BP_GET_COMPRESS(bp));692DDK_SET_CRYPT(ddk, BP_USES_CRYPT(bp));693}694695void696ddt_phys_extend(ddt_univ_phys_t *ddp, ddt_phys_variant_t v, const blkptr_t *bp)697{698ASSERT3U(v, <, DDT_PHYS_NONE);699int bp_ndvas = BP_GET_NDVAS(bp);700int ddp_max_dvas = BP_IS_ENCRYPTED(bp) ?701SPA_DVAS_PER_BP - 1 : SPA_DVAS_PER_BP;702dva_t *dvas = (v == DDT_PHYS_FLAT) ?703ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;704705int s = 0, d = 0;706while (s < bp_ndvas && d < ddp_max_dvas) {707if (DVA_IS_VALID(&dvas[d])) {708d++;709continue;710}711dvas[d] = bp->blk_dva[s];712s++; d++;713}714715/*716* If the caller offered us more DVAs than we can fit, something has717* gone wrong in their accounting. zio_ddt_write() should never ask for718* more than we need.719*/720ASSERT3U(s, ==, bp_ndvas);721722if (BP_IS_ENCRYPTED(bp))723dvas[2] = bp->blk_dva[2];724725if (ddt_phys_birth(ddp, v) == 0) {726if (v == DDT_PHYS_FLAT) {727ddp->ddp_flat.ddp_phys_birth =728BP_GET_PHYSICAL_BIRTH(bp);729} else {730ddp->ddp_trad[v].ddp_phys_birth =731BP_GET_PHYSICAL_BIRTH(bp);732}733}734}735736void737ddt_phys_unextend(ddt_univ_phys_t *cur, ddt_univ_phys_t *orig,738ddt_phys_variant_t v)739{740ASSERT3U(v, <, DDT_PHYS_NONE);741dva_t *cur_dvas = (v == DDT_PHYS_FLAT) ?742cur->ddp_flat.ddp_dva : cur->ddp_trad[v].ddp_dva;743dva_t *orig_dvas = (v == DDT_PHYS_FLAT) ?744orig->ddp_flat.ddp_dva : orig->ddp_trad[v].ddp_dva;745746for (int d = 0; d < SPA_DVAS_PER_BP; d++)747cur_dvas[d] = orig_dvas[d];748749if (ddt_phys_birth(orig, v) == 0) {750if (v == DDT_PHYS_FLAT)751cur->ddp_flat.ddp_phys_birth = 0;752else753cur->ddp_trad[v].ddp_phys_birth = 0;754}755}756757void758ddt_phys_copy(ddt_univ_phys_t *dst, const ddt_univ_phys_t *src,759ddt_phys_variant_t v)760{761ASSERT3U(v, <, DDT_PHYS_NONE);762763if (v == DDT_PHYS_FLAT)764dst->ddp_flat = src->ddp_flat;765else766dst->ddp_trad[v] = src->ddp_trad[v];767}768769void770ddt_phys_clear(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)771{772ASSERT3U(v, <, DDT_PHYS_NONE);773774if (v == DDT_PHYS_FLAT)775memset(&ddp->ddp_flat, 0, DDT_FLAT_PHYS_SIZE);776else777memset(&ddp->ddp_trad[v], 0, DDT_TRAD_PHYS_SIZE / DDT_PHYS_MAX);778}779780static uint64_t781ddt_class_start(void)782{783uint64_t start = gethrestime_sec();784785if (ddt_prune_artificial_age) {786/*787* debug aide -- simulate a wider distribution788* so we don't have to wait for an aged DDT789* to test prune.790*/791int range = 1 << 21;792int percent = random_in_range(100);793if (percent < 50) {794range = range >> 4;795} else if (percent > 75) {796range /= 2;797}798start -= random_in_range(range);799}800801return (start);802}803804void805ddt_phys_addref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)806{807ASSERT3U(v, <, DDT_PHYS_NONE);808809if (v == DDT_PHYS_FLAT)810ddp->ddp_flat.ddp_refcnt++;811else812ddp->ddp_trad[v].ddp_refcnt++;813}814815uint64_t816ddt_phys_decref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)817{818ASSERT3U(v, <, DDT_PHYS_NONE);819820uint64_t *refcntp;821822if (v == DDT_PHYS_FLAT)823refcntp = &ddp->ddp_flat.ddp_refcnt;824else825refcntp = &ddp->ddp_trad[v].ddp_refcnt;826827ASSERT3U(*refcntp, >, 0);828(*refcntp)--;829return (*refcntp);830}831832static void833ddt_phys_free(ddt_t *ddt, ddt_key_t *ddk, ddt_univ_phys_t *ddp,834ddt_phys_variant_t v, uint64_t txg)835{836blkptr_t blk;837838ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);839840/*841* We clear the dedup bit so that zio_free() will actually free the842* space, rather than just decrementing the refcount in the DDT.843*/844BP_SET_DEDUP(&blk, 0);845846ddt_phys_clear(ddp, v);847zio_free(ddt->ddt_spa, txg, &blk);848}849850uint64_t851ddt_phys_birth(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)852{853ASSERT3U(v, <, DDT_PHYS_NONE);854855if (v == DDT_PHYS_FLAT)856return (ddp->ddp_flat.ddp_phys_birth);857else858return (ddp->ddp_trad[v].ddp_phys_birth);859}860861int862ddt_phys_is_gang(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)863{864ASSERT3U(v, <, DDT_PHYS_NONE);865866const dva_t *dvas = (v == DDT_PHYS_FLAT) ?867ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;868869return (DVA_GET_GANG(&dvas[0]));870}871872int873ddt_phys_dva_count(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,874boolean_t encrypted)875{876ASSERT3U(v, <, DDT_PHYS_NONE);877878const dva_t *dvas = (v == DDT_PHYS_FLAT) ?879ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;880881return (DVA_IS_VALID(&dvas[0]) +882DVA_IS_VALID(&dvas[1]) +883DVA_IS_VALID(&dvas[2]) * !encrypted);884}885886ddt_phys_variant_t887ddt_phys_select(const ddt_t *ddt, const ddt_entry_t *dde, const blkptr_t *bp)888{889if (dde == NULL)890return (DDT_PHYS_NONE);891892const ddt_univ_phys_t *ddp = dde->dde_phys;893894if (ddt->ddt_flags & DDT_FLAG_FLAT) {895if (DVA_EQUAL(BP_IDENTITY(bp), &ddp->ddp_flat.ddp_dva[0]) &&896BP_GET_PHYSICAL_BIRTH(bp) == ddp->ddp_flat.ddp_phys_birth) {897return (DDT_PHYS_FLAT);898}899} else /* traditional phys */ {900for (int p = 0; p < DDT_PHYS_MAX; p++) {901if (DVA_EQUAL(BP_IDENTITY(bp),902&ddp->ddp_trad[p].ddp_dva[0]) &&903BP_GET_PHYSICAL_BIRTH(bp) ==904ddp->ddp_trad[p].ddp_phys_birth) {905return (p);906}907}908}909return (DDT_PHYS_NONE);910}911912uint64_t913ddt_phys_refcnt(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)914{915ASSERT3U(v, <, DDT_PHYS_NONE);916917if (v == DDT_PHYS_FLAT)918return (ddp->ddp_flat.ddp_refcnt);919else920return (ddp->ddp_trad[v].ddp_refcnt);921}922923uint64_t924ddt_phys_total_refcnt(const ddt_t *ddt, const ddt_univ_phys_t *ddp)925{926uint64_t refcnt = 0;927928if (ddt->ddt_flags & DDT_FLAG_FLAT)929refcnt = ddp->ddp_flat.ddp_refcnt;930else931for (int v = DDT_PHYS_SINGLE; v <= DDT_PHYS_TRIPLE; v++)932refcnt += ddp->ddp_trad[v].ddp_refcnt;933934return (refcnt);935}936937ddt_t *938ddt_select(spa_t *spa, const blkptr_t *bp)939{940ASSERT(DDT_CHECKSUM_VALID(BP_GET_CHECKSUM(bp)));941return (spa->spa_ddt[BP_GET_CHECKSUM(bp)]);942}943944void945ddt_enter(ddt_t *ddt)946{947mutex_enter(&ddt->ddt_lock);948}949950void951ddt_exit(ddt_t *ddt)952{953mutex_exit(&ddt->ddt_lock);954}955956void957ddt_init(void)958{959ddt_cache = kmem_cache_create("ddt_cache",960sizeof (ddt_t), 0, NULL, NULL, NULL, NULL, NULL, 0);961ddt_entry_flat_cache = kmem_cache_create("ddt_entry_flat_cache",962DDT_ENTRY_FLAT_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);963ddt_entry_trad_cache = kmem_cache_create("ddt_entry_trad_cache",964DDT_ENTRY_TRAD_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);965966ddt_log_init();967}968969void970ddt_fini(void)971{972ddt_log_fini();973974kmem_cache_destroy(ddt_entry_trad_cache);975kmem_cache_destroy(ddt_entry_flat_cache);976kmem_cache_destroy(ddt_cache);977}978979static ddt_entry_t *980ddt_alloc(const ddt_t *ddt, const ddt_key_t *ddk)981{982ddt_entry_t *dde;983984if (ddt->ddt_flags & DDT_FLAG_FLAT) {985dde = kmem_cache_alloc(ddt_entry_flat_cache, KM_SLEEP);986memset(dde, 0, DDT_ENTRY_FLAT_SIZE);987} else {988dde = kmem_cache_alloc(ddt_entry_trad_cache, KM_SLEEP);989memset(dde, 0, DDT_ENTRY_TRAD_SIZE);990}991992cv_init(&dde->dde_cv, NULL, CV_DEFAULT, NULL);993994dde->dde_key = *ddk;995996return (dde);997}998999void1000ddt_alloc_entry_io(ddt_entry_t *dde)1001{1002if (dde->dde_io != NULL)1003return;10041005dde->dde_io = kmem_zalloc(sizeof (ddt_entry_io_t), KM_SLEEP);1006}10071008static void1009ddt_free(const ddt_t *ddt, ddt_entry_t *dde)1010{1011if (dde->dde_io != NULL) {1012for (int p = 0; p < DDT_NPHYS(ddt); p++)1013ASSERT0P(dde->dde_io->dde_lead_zio[p]);10141015if (dde->dde_io->dde_repair_abd != NULL)1016abd_free(dde->dde_io->dde_repair_abd);10171018kmem_free(dde->dde_io, sizeof (ddt_entry_io_t));1019}10201021cv_destroy(&dde->dde_cv);1022kmem_cache_free(ddt->ddt_flags & DDT_FLAG_FLAT ?1023ddt_entry_flat_cache : ddt_entry_trad_cache, dde);1024}10251026void1027ddt_remove(ddt_t *ddt, ddt_entry_t *dde)1028{1029ASSERT(MUTEX_HELD(&ddt->ddt_lock));10301031/* Entry is still in the log, so charge the entry back to it */1032if (dde->dde_flags & DDE_FLAG_LOGGED) {1033ddt_lightweight_entry_t ddlwe;1034DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);1035ddt_histogram_add_entry(ddt, &ddt->ddt_log_histogram, &ddlwe);1036}10371038avl_remove(&ddt->ddt_tree, dde);1039ddt_free(ddt, dde);1040}10411042/*1043* We're considered over quota when we hit 85% full, or for larger drives,1044* when there is less than 8GB free.1045*/1046static boolean_t1047ddt_special_over_quota(metaslab_class_t *mc)1048{1049uint64_t allocated = metaslab_class_get_alloc(mc);1050uint64_t capacity = metaslab_class_get_space(mc);1051uint64_t limit = MAX(capacity * 85 / 100,1052(capacity > (1LL<<33)) ? capacity - (1LL<<33) : 0);1053return (allocated >= limit);1054}10551056/*1057* Check if the DDT is over its quota. This can be due to a few conditions:1058* 1. 'dedup_table_quota' property is not 0 (none) and the dedup dsize1059* exceeds this limit1060*1061* 2. 'dedup_table_quota' property is set to automatic and1062* a. the dedup or special allocation class could not satisfy a DDT1063* allocation in a recent transaction1064* b. the dedup or special allocation class has exceeded its 85% limit1065*/1066static boolean_t1067ddt_over_quota(spa_t *spa)1068{1069if (spa->spa_dedup_table_quota == 0)1070return (B_FALSE);10711072if (spa->spa_dedup_table_quota != UINT64_MAX)1073return (ddt_get_ddt_dsize(spa) > spa->spa_dedup_table_quota);10741075/*1076* Over quota if have to allocate outside of the dedup/special class.1077*/1078if (spa_syncing_txg(spa) <= spa->spa_dedup_class_full_txg +1079dedup_class_wait_txgs) {1080/* Waiting for some deferred frees to be processed */1081return (B_TRUE);1082}10831084/*1085* For automatic quota, table size is limited by dedup or special class1086*/1087if (spa_has_dedup(spa))1088return (ddt_special_over_quota(spa_dedup_class(spa)));1089else if (spa_special_has_ddt(spa))1090return (ddt_special_over_quota(spa_special_class(spa)));10911092return (B_FALSE);1093}10941095void1096ddt_prefetch_all(spa_t *spa)1097{1098/*1099* Load all DDT entries for each type/class combination. This is1100* indended to perform a prefetch on all such blocks. For the same1101* reason that ddt_prefetch isn't locked, this is also not locked.1102*/1103for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1104ddt_t *ddt = spa->spa_ddt[c];1105if (!ddt)1106continue;11071108for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1109for (ddt_class_t class = 0; class < DDT_CLASSES;1110class++) {1111ddt_object_prefetch_all(ddt, type, class);1112}1113}1114}1115}11161117static int ddt_configure(ddt_t *ddt, boolean_t new);11181119/*1120* If the BP passed to ddt_lookup has valid DVAs, then we need to compare them1121* to the ones in the entry. If they're different, then the passed-in BP is1122* from a previous generation of this entry (ie was previously pruned) and we1123* have to act like the entry doesn't exist at all.1124*1125* This should only happen during a lookup to free the block (zio_ddt_free()).1126*1127* XXX this is similar in spirit to ddt_phys_select(), maybe can combine1128* -- robn, 2024-02-091129*/1130static boolean_t1131ddt_entry_lookup_is_valid(ddt_t *ddt, const blkptr_t *bp, ddt_entry_t *dde)1132{1133/* If the BP has no DVAs, then this entry is good */1134uint_t ndvas = BP_GET_NDVAS(bp);1135if (ndvas == 0)1136return (B_TRUE);11371138/*1139* Only checking the phys for the copies. For flat, there's only one;1140* for trad it'll be the one that has the matching set of DVAs.1141*/1142const dva_t *dvas = (ddt->ddt_flags & DDT_FLAG_FLAT) ?1143dde->dde_phys->ddp_flat.ddp_dva :1144dde->dde_phys->ddp_trad[ndvas].ddp_dva;11451146/*1147* Compare entry DVAs with the BP. They should all be there, but1148* there's not really anything we can do if its only partial anyway,1149* that's an error somewhere else, maybe long ago.1150*/1151uint_t d;1152for (d = 0; d < ndvas; d++)1153if (!DVA_EQUAL(&dvas[d], &bp->blk_dva[d]))1154return (B_FALSE);1155ASSERT3U(d, ==, ndvas);11561157return (B_TRUE);1158}11591160ddt_entry_t *1161ddt_lookup(ddt_t *ddt, const blkptr_t *bp, boolean_t verify)1162{1163spa_t *spa = ddt->ddt_spa;1164ddt_key_t search;1165ddt_entry_t *dde;1166ddt_type_t type;1167ddt_class_t class;1168avl_index_t where;1169int error;11701171ASSERT(MUTEX_HELD(&ddt->ddt_lock));11721173if (ddt->ddt_version == DDT_VERSION_UNCONFIGURED) {1174/*1175* This is the first use of this DDT since the pool was1176* created; finish getting it ready for use.1177*/1178VERIFY0(ddt_configure(ddt, B_TRUE));1179ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);1180}11811182DDT_KSTAT_BUMP(ddt, dds_lookup);11831184ddt_key_fill(&search, bp);11851186/* Find an existing live entry */1187dde = avl_find(&ddt->ddt_tree, &search, &where);1188if (dde != NULL) {1189/* If we went over quota, act like we didn't find it */1190if (dde->dde_flags & DDE_FLAG_OVERQUOTA)1191return (NULL);11921193/* If it's already loaded, we can just return it. */1194DDT_KSTAT_BUMP(ddt, dds_lookup_live_hit);1195if (dde->dde_flags & DDE_FLAG_LOADED) {1196if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))1197return (dde);1198return (NULL);1199}12001201/* Someone else is loading it, wait for it. */1202dde->dde_waiters++;1203DDT_KSTAT_BUMP(ddt, dds_lookup_live_wait);1204while (!(dde->dde_flags & DDE_FLAG_LOADED))1205cv_wait(&dde->dde_cv, &ddt->ddt_lock);1206dde->dde_waiters--;12071208/* Loaded but over quota, forget we were ever here */1209if (dde->dde_flags & DDE_FLAG_OVERQUOTA) {1210if (dde->dde_waiters == 0) {1211avl_remove(&ddt->ddt_tree, dde);1212ddt_free(ddt, dde);1213}1214return (NULL);1215}12161217DDT_KSTAT_BUMP(ddt, dds_lookup_existing);12181219/* Make sure the loaded entry matches the BP */1220if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))1221return (dde);1222return (NULL);1223} else1224DDT_KSTAT_BUMP(ddt, dds_lookup_live_miss);12251226/* Time to make a new entry. */1227dde = ddt_alloc(ddt, &search);12281229/* Record the time this class was created (used by ddt prune) */1230if (ddt->ddt_flags & DDT_FLAG_FLAT)1231dde->dde_phys->ddp_flat.ddp_class_start = ddt_class_start();12321233avl_insert(&ddt->ddt_tree, dde, where);12341235/* If its in the log tree, we can "load" it from there */1236if (ddt->ddt_flags & DDT_FLAG_LOG) {1237ddt_lightweight_entry_t ddlwe;12381239if (ddt_log_find_key(ddt, &search, &ddlwe)) {1240/*1241* See if we have the key first, and if so, set up1242* the entry.1243*/1244dde->dde_type = ddlwe.ddlwe_type;1245dde->dde_class = ddlwe.ddlwe_class;1246memcpy(dde->dde_phys, &ddlwe.ddlwe_phys,1247DDT_PHYS_SIZE(ddt));1248/* Whatever we found isn't valid for this BP, eject */1249if (verify &&1250!ddt_entry_lookup_is_valid(ddt, bp, dde)) {1251avl_remove(&ddt->ddt_tree, dde);1252ddt_free(ddt, dde);1253return (NULL);1254}12551256/* Remove it and count it */1257if (ddt_log_remove_key(ddt,1258ddt->ddt_log_active, &search)) {1259DDT_KSTAT_BUMP(ddt, dds_lookup_log_active_hit);1260} else {1261VERIFY(ddt_log_remove_key(ddt,1262ddt->ddt_log_flushing, &search));1263DDT_KSTAT_BUMP(ddt,1264dds_lookup_log_flushing_hit);1265}12661267dde->dde_flags = DDE_FLAG_LOADED | DDE_FLAG_LOGGED;12681269DDT_KSTAT_BUMP(ddt, dds_lookup_log_hit);1270DDT_KSTAT_BUMP(ddt, dds_lookup_existing);12711272return (dde);1273}12741275DDT_KSTAT_BUMP(ddt, dds_lookup_log_miss);1276}12771278/*1279* ddt_tree is now stable, so unlock and let everyone else keep moving.1280* Anyone landing on this entry will find it without DDE_FLAG_LOADED,1281* and go to sleep waiting for it above.1282*/1283ddt_exit(ddt);12841285/* Search all store objects for the entry. */1286error = ENOENT;1287for (type = 0; type < DDT_TYPES; type++) {1288for (class = 0; class < DDT_CLASSES; class++) {1289error = ddt_object_lookup(ddt, type, class, dde);1290if (error != ENOENT) {1291ASSERT0(error);1292break;1293}1294}1295if (error != ENOENT)1296break;1297}12981299ddt_enter(ddt);13001301ASSERT(!(dde->dde_flags & DDE_FLAG_LOADED));13021303dde->dde_type = type; /* will be DDT_TYPES if no entry found */1304dde->dde_class = class; /* will be DDT_CLASSES if no entry found */13051306boolean_t valid = B_TRUE;13071308if (dde->dde_type == DDT_TYPES &&1309dde->dde_class == DDT_CLASSES &&1310ddt_over_quota(spa)) {1311/* Over quota. If no one is waiting, clean up right now. */1312if (dde->dde_waiters == 0) {1313avl_remove(&ddt->ddt_tree, dde);1314ddt_free(ddt, dde);1315return (NULL);1316}13171318/* Flag cleanup required */1319dde->dde_flags |= DDE_FLAG_OVERQUOTA;1320} else if (error == 0) {1321/*1322* If what we loaded is no good for this BP and there's no one1323* waiting for it, we can just remove it and get out. If its no1324* good but there are waiters, we have to leave it, because we1325* don't know what they want. If its not needed we'll end up1326* taking an entry log/sync, but it can only happen if more1327* than one previous version of this block is being deleted at1328* the same time. This is extremely unlikely to happen and not1329* worth the effort to deal with without taking an entry1330* update.1331*/1332valid = !verify || ddt_entry_lookup_is_valid(ddt, bp, dde);1333if (!valid && dde->dde_waiters == 0) {1334avl_remove(&ddt->ddt_tree, dde);1335ddt_free(ddt, dde);1336return (NULL);1337}13381339DDT_KSTAT_BUMP(ddt, dds_lookup_stored_hit);1340DDT_KSTAT_BUMP(ddt, dds_lookup_existing);13411342/*1343* The histograms only track inactive (stored or logged) blocks.1344* We've just put an entry onto the live list, so we need to1345* remove its counts. When its synced back, it'll be re-added1346* to the right one.1347*1348* We only do this when we successfully found it in the store.1349* error == ENOENT means this is a new entry, and so its already1350* not counted.1351*/1352ddt_histogram_t *ddh =1353&ddt->ddt_histogram[dde->dde_type][dde->dde_class];13541355ddt_lightweight_entry_t ddlwe;1356DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);1357ddt_histogram_sub_entry(ddt, ddh, &ddlwe);1358} else {1359DDT_KSTAT_BUMP(ddt, dds_lookup_stored_miss);1360DDT_KSTAT_BUMP(ddt, dds_lookup_new);1361}13621363/* Entry loaded, everyone can proceed now */1364dde->dde_flags |= DDE_FLAG_LOADED;1365cv_broadcast(&dde->dde_cv);13661367if ((dde->dde_flags & DDE_FLAG_OVERQUOTA) || !valid)1368return (NULL);13691370return (dde);1371}13721373void1374ddt_prefetch(spa_t *spa, const blkptr_t *bp)1375{1376ddt_t *ddt;1377ddt_key_t ddk;13781379if (!zfs_dedup_prefetch || bp == NULL || !BP_GET_DEDUP(bp))1380return;13811382/*1383* We only remove the DDT once all tables are empty and only1384* prefetch dedup blocks when there are entries in the DDT.1385* Thus no locking is required as the DDT can't disappear on us.1386*/1387ddt = ddt_select(spa, bp);1388ddt_key_fill(&ddk, bp);13891390for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1391for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1392ddt_object_prefetch(ddt, type, class, &ddk);1393}1394}1395}13961397/*1398* ddt_key_t comparison. Any struct wanting to make use of this function must1399* have the key as the first element. Casts it to N uint64_ts, and checks until1400* we find there's a difference. This is intended to match how ddt_zap.c drives1401* the ZAPs (first uint64_t as the key prehash), which will minimise the number1402* of ZAP blocks touched when flushing logged entries from an AVL walk. This is1403* not an invariant for this function though, should you wish to change it.1404*/1405int1406ddt_key_compare(const void *x1, const void *x2)1407{1408const uint64_t *k1 = (const uint64_t *)x1;1409const uint64_t *k2 = (const uint64_t *)x2;14101411int cmp;1412for (int i = 0; i < (sizeof (ddt_key_t) / sizeof (uint64_t)); i++)1413if (likely((cmp = TREE_CMP(k1[i], k2[i])) != 0))1414return (cmp);14151416return (0);1417}14181419/* Create the containing dir for this DDT and bump the feature count */1420static void1421ddt_create_dir(ddt_t *ddt, dmu_tx_t *tx)1422{1423ASSERT0(ddt->ddt_dir_object);1424ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);14251426char name[DDT_NAMELEN];1427snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1428zio_checksum_table[ddt->ddt_checksum].ci_name);14291430ddt->ddt_dir_object = zap_create_link(ddt->ddt_os,1431DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT, name, tx);14321433VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_VERSION,1434sizeof (uint64_t), 1, &ddt->ddt_version, tx));1435VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS,1436sizeof (uint64_t), 1, &ddt->ddt_flags, tx));14371438spa_feature_incr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);1439}14401441/* Destroy the containing dir and deactivate the feature */1442static void1443ddt_destroy_dir(ddt_t *ddt, dmu_tx_t *tx)1444{1445ASSERT3U(ddt->ddt_dir_object, !=, 0);1446ASSERT3U(ddt->ddt_dir_object, !=, DMU_POOL_DIRECTORY_OBJECT);1447ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);14481449char name[DDT_NAMELEN];1450snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1451zio_checksum_table[ddt->ddt_checksum].ci_name);14521453for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1454for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1455ASSERT(!ddt_object_exists(ddt, type, class));1456}1457}14581459ddt_log_destroy(ddt, tx);14601461uint64_t count;1462ASSERT0(zap_count(ddt->ddt_os, ddt->ddt_dir_object, &count));1463ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object,1464DDT_DIR_VERSION));1465ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS));1466ASSERT3U(count, ==, 2);14671468VERIFY0(zap_remove(ddt->ddt_os, DMU_POOL_DIRECTORY_OBJECT, name, tx));1469VERIFY0(zap_destroy(ddt->ddt_os, ddt->ddt_dir_object, tx));14701471ddt->ddt_dir_object = 0;14721473spa_feature_decr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);1474}14751476/*1477* Determine, flags and on-disk layout from what's already stored. If there's1478* nothing stored, then if new is false, returns ENOENT, and if true, selects1479* based on pool config.1480*/1481static int1482ddt_configure(ddt_t *ddt, boolean_t new)1483{1484spa_t *spa = ddt->ddt_spa;1485char name[DDT_NAMELEN];1486int error;14871488ASSERT3U(spa_load_state(spa), !=, SPA_LOAD_CREATE);14891490boolean_t fdt_enabled =1491spa_feature_is_enabled(spa, SPA_FEATURE_FAST_DEDUP);1492boolean_t fdt_active =1493spa_feature_is_active(spa, SPA_FEATURE_FAST_DEDUP);14941495/*1496* First, look for the global DDT stats object. If its not there, then1497* there's never been a DDT written before ever, and we know we're1498* starting from scratch.1499*/1500error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,1501DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,1502&spa->spa_ddt_stat_object);1503if (error != 0) {1504if (error != ENOENT)1505return (error);1506goto not_found;1507}15081509if (fdt_active) {1510/*1511* Now look for a DDT directory. If it exists, then it has1512* everything we need.1513*/1514snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1515zio_checksum_table[ddt->ddt_checksum].ci_name);15161517error = zap_lookup(spa->spa_meta_objset,1518DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,1519&ddt->ddt_dir_object);1520if (error == 0) {1521ASSERT3U(spa->spa_meta_objset, ==, ddt->ddt_os);15221523error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,1524DDT_DIR_VERSION, sizeof (uint64_t), 1,1525&ddt->ddt_version);1526if (error != 0)1527return (error);15281529error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,1530DDT_DIR_FLAGS, sizeof (uint64_t), 1,1531&ddt->ddt_flags);1532if (error != 0)1533return (error);15341535if (ddt->ddt_version != DDT_VERSION_FDT) {1536zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "1537"unknown version %llu", spa_name(spa),1538name, (u_longlong_t)ddt->ddt_version);1539return (SET_ERROR(EINVAL));1540}15411542if ((ddt->ddt_flags & ~DDT_FLAG_MASK) != 0) {1543zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "1544"version=%llu unknown flags %llx",1545spa_name(spa), name,1546(u_longlong_t)ddt->ddt_flags,1547(u_longlong_t)ddt->ddt_version);1548return (SET_ERROR(EINVAL));1549}15501551return (0);1552}1553if (error != ENOENT)1554return (error);1555}15561557/* Any object in the root indicates a traditional setup. */1558for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1559for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1560ddt_object_name(ddt, type, class, name);1561uint64_t obj;1562error = zap_lookup(spa->spa_meta_objset,1563DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t),15641, &obj);1565if (error == ENOENT)1566continue;1567if (error != 0)1568return (error);15691570ddt->ddt_version = DDT_VERSION_LEGACY;1571ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1572ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;15731574return (0);1575}1576}15771578not_found:1579if (!new)1580return (SET_ERROR(ENOENT));15811582/* Nothing on disk, so set up for the best version we can */1583if (fdt_enabled) {1584ddt->ddt_version = DDT_VERSION_FDT;1585ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1586ddt->ddt_dir_object = 0; /* create on first use */1587} else {1588ddt->ddt_version = DDT_VERSION_LEGACY;1589ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1590ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;1591}15921593return (0);1594}15951596static void1597ddt_table_alloc_kstats(ddt_t *ddt)1598{1599char *mod = kmem_asprintf("zfs/%s", spa_name(ddt->ddt_spa));1600char *name = kmem_asprintf("ddt_stats_%s",1601zio_checksum_table[ddt->ddt_checksum].ci_name);16021603ddt->ddt_ksp = kstat_create(mod, 0, name, "misc", KSTAT_TYPE_NAMED,1604sizeof (ddt_kstats_t) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);1605if (ddt->ddt_ksp != NULL) {1606ddt_kstats_t *dds = kmem_alloc(sizeof (ddt_kstats_t), KM_SLEEP);1607memcpy(dds, &ddt_kstats_template, sizeof (ddt_kstats_t));1608ddt->ddt_ksp->ks_data = dds;1609kstat_install(ddt->ddt_ksp);1610}16111612kmem_strfree(name);1613kmem_strfree(mod);1614}16151616static ddt_t *1617ddt_table_alloc(spa_t *spa, enum zio_checksum c)1618{1619ddt_t *ddt;16201621ddt = kmem_cache_alloc(ddt_cache, KM_SLEEP);1622memset(ddt, 0, sizeof (ddt_t));1623mutex_init(&ddt->ddt_lock, NULL, MUTEX_DEFAULT, NULL);1624avl_create(&ddt->ddt_tree, ddt_key_compare,1625sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));1626avl_create(&ddt->ddt_repair_tree, ddt_key_compare,1627sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));16281629ddt->ddt_checksum = c;1630ddt->ddt_spa = spa;1631ddt->ddt_os = spa->spa_meta_objset;1632ddt->ddt_version = DDT_VERSION_UNCONFIGURED;1633ddt->ddt_log_flush_pressure = 10;16341635ddt_log_alloc(ddt);1636ddt_table_alloc_kstats(ddt);16371638return (ddt);1639}16401641static void1642ddt_table_free(ddt_t *ddt)1643{1644if (ddt->ddt_ksp != NULL) {1645kmem_free(ddt->ddt_ksp->ks_data, sizeof (ddt_kstats_t));1646ddt->ddt_ksp->ks_data = NULL;1647kstat_delete(ddt->ddt_ksp);1648}16491650ddt_log_free(ddt);1651ASSERT0(avl_numnodes(&ddt->ddt_tree));1652ASSERT0(avl_numnodes(&ddt->ddt_repair_tree));1653avl_destroy(&ddt->ddt_tree);1654avl_destroy(&ddt->ddt_repair_tree);1655mutex_destroy(&ddt->ddt_lock);1656kmem_cache_free(ddt_cache, ddt);1657}16581659void1660ddt_create(spa_t *spa)1661{1662spa->spa_dedup_checksum = ZIO_DEDUPCHECKSUM;16631664for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1665if (DDT_CHECKSUM_VALID(c))1666spa->spa_ddt[c] = ddt_table_alloc(spa, c);1667}1668}16691670int1671ddt_load(spa_t *spa)1672{1673int error;16741675ddt_create(spa);16761677error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,1678DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,1679&spa->spa_ddt_stat_object);1680if (error)1681return (error == ENOENT ? 0 : error);16821683for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1684if (!DDT_CHECKSUM_VALID(c))1685continue;16861687ddt_t *ddt = spa->spa_ddt[c];1688error = ddt_configure(ddt, B_FALSE);1689if (error == ENOENT)1690continue;1691if (error != 0)1692return (error);16931694for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1695for (ddt_class_t class = 0; class < DDT_CLASSES;1696class++) {1697error = ddt_object_load(ddt, type, class);1698if (error != 0 && error != ENOENT)1699return (error);1700}1701}17021703if (ddt->ddt_flags & DDT_FLAG_LOG) {1704error = ddt_log_load(ddt);1705if (error != 0 && error != ENOENT)1706return (error);1707}17081709DDT_KSTAT_SET(ddt, dds_log_active_entries,1710avl_numnodes(&ddt->ddt_log_active->ddl_tree));1711DDT_KSTAT_SET(ddt, dds_log_flushing_entries,1712avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));17131714/*1715* Seed the cached histograms.1716*/1717memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,1718sizeof (ddt->ddt_histogram));1719}17201721spa->spa_dedup_dspace = ~0ULL;1722spa->spa_dedup_dsize = ~0ULL;17231724return (0);1725}17261727void1728ddt_unload(spa_t *spa)1729{1730for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1731if (spa->spa_ddt[c]) {1732ddt_table_free(spa->spa_ddt[c]);1733spa->spa_ddt[c] = NULL;1734}1735}1736}17371738boolean_t1739ddt_class_contains(spa_t *spa, ddt_class_t max_class, const blkptr_t *bp)1740{1741ddt_t *ddt;1742ddt_key_t ddk;17431744if (!BP_GET_DEDUP(bp))1745return (B_FALSE);17461747if (max_class == DDT_CLASS_UNIQUE)1748return (B_TRUE);17491750ddt = spa->spa_ddt[BP_GET_CHECKSUM(bp)];17511752ddt_key_fill(&ddk, bp);17531754for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1755for (ddt_class_t class = 0; class <= max_class; class++) {1756if (ddt_object_contains(ddt, type, class, &ddk) == 0)1757return (B_TRUE);1758}1759}17601761return (B_FALSE);1762}17631764ddt_entry_t *1765ddt_repair_start(ddt_t *ddt, const blkptr_t *bp)1766{1767ddt_key_t ddk;1768ddt_entry_t *dde;17691770ddt_key_fill(&ddk, bp);17711772dde = ddt_alloc(ddt, &ddk);1773ddt_alloc_entry_io(dde);17741775for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1776for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1777/*1778* We can only do repair if there are multiple copies1779* of the block. For anything in the UNIQUE class,1780* there's definitely only one copy, so don't even try.1781*/1782if (class != DDT_CLASS_UNIQUE &&1783ddt_object_lookup(ddt, type, class, dde) == 0)1784return (dde);1785}1786}17871788memset(dde->dde_phys, 0, DDT_PHYS_SIZE(ddt));17891790return (dde);1791}17921793void1794ddt_repair_done(ddt_t *ddt, ddt_entry_t *dde)1795{1796avl_index_t where;17971798ddt_enter(ddt);17991800if (dde->dde_io->dde_repair_abd != NULL &&1801spa_writeable(ddt->ddt_spa) &&1802avl_find(&ddt->ddt_repair_tree, dde, &where) == NULL)1803avl_insert(&ddt->ddt_repair_tree, dde, where);1804else1805ddt_free(ddt, dde);18061807ddt_exit(ddt);1808}18091810static void1811ddt_repair_entry_done(zio_t *zio)1812{1813ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);1814ddt_entry_t *rdde = zio->io_private;18151816ddt_free(ddt, rdde);1817}18181819static void1820ddt_repair_entry(ddt_t *ddt, ddt_entry_t *dde, ddt_entry_t *rdde, zio_t *rio)1821{1822ddt_key_t *ddk = &dde->dde_key;1823ddt_key_t *rddk = &rdde->dde_key;1824zio_t *zio;1825blkptr_t blk;18261827zio = zio_null(rio, rio->io_spa, NULL,1828ddt_repair_entry_done, rdde, rio->io_flags);18291830for (int p = 0; p < DDT_NPHYS(ddt); p++) {1831ddt_univ_phys_t *ddp = dde->dde_phys;1832ddt_univ_phys_t *rddp = rdde->dde_phys;1833ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);1834uint64_t phys_birth = ddt_phys_birth(ddp, v);1835const dva_t *dvas, *rdvas;18361837if (ddt->ddt_flags & DDT_FLAG_FLAT) {1838dvas = ddp->ddp_flat.ddp_dva;1839rdvas = rddp->ddp_flat.ddp_dva;1840} else {1841dvas = ddp->ddp_trad[p].ddp_dva;1842rdvas = rddp->ddp_trad[p].ddp_dva;1843}18441845if (phys_birth == 0 ||1846phys_birth != ddt_phys_birth(rddp, v) ||1847memcmp(dvas, rdvas, sizeof (dva_t) * SPA_DVAS_PER_BP))1848continue;18491850ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);1851zio_nowait(zio_rewrite(zio, zio->io_spa, 0, &blk,1852rdde->dde_io->dde_repair_abd, DDK_GET_PSIZE(rddk),1853NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,1854ZIO_DDT_CHILD_FLAGS(zio), NULL));1855}18561857zio_nowait(zio);1858}18591860static void1861ddt_repair_table(ddt_t *ddt, zio_t *rio)1862{1863spa_t *spa = ddt->ddt_spa;1864ddt_entry_t *dde, *rdde_next, *rdde;1865avl_tree_t *t = &ddt->ddt_repair_tree;1866blkptr_t blk;18671868if (spa_sync_pass(spa) > 1)1869return;18701871ddt_enter(ddt);1872for (rdde = avl_first(t); rdde != NULL; rdde = rdde_next) {1873rdde_next = AVL_NEXT(t, rdde);1874avl_remove(&ddt->ddt_repair_tree, rdde);1875ddt_exit(ddt);1876ddt_bp_create(ddt->ddt_checksum, &rdde->dde_key, NULL,1877DDT_PHYS_NONE, &blk);1878dde = ddt_repair_start(ddt, &blk);1879ddt_repair_entry(ddt, dde, rdde, rio);1880ddt_repair_done(ddt, dde);1881ddt_enter(ddt);1882}1883ddt_exit(ddt);1884}18851886static void1887ddt_sync_update_stats(ddt_t *ddt, dmu_tx_t *tx)1888{1889/*1890* Count all the entries stored for each type/class, and updates the1891* stats within (ddt_object_sync()). If there's no entries for the1892* type/class, the whole object is removed. If all objects for the DDT1893* are removed, its containing dir is removed, effectively resetting1894* the entire DDT to an empty slate.1895*/1896uint64_t count = 0;1897for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1898uint64_t add, tcount = 0;1899for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1900if (ddt_object_exists(ddt, type, class)) {1901ddt_object_sync(ddt, type, class, tx);1902VERIFY0(ddt_object_count(ddt, type, class,1903&add));1904tcount += add;1905}1906}1907for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1908if (tcount == 0 && ddt_object_exists(ddt, type, class))1909ddt_object_destroy(ddt, type, class, tx);1910}1911count += tcount;1912}19131914if (ddt->ddt_flags & DDT_FLAG_LOG) {1915/* Include logged entries in the total count */1916count += avl_numnodes(&ddt->ddt_log_active->ddl_tree);1917count += avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);1918}19191920if (count == 0) {1921/*1922* No entries left on the DDT, so reset the version for next1923* time. This allows us to handle the feature being changed1924* since the DDT was originally created. New entries should get1925* whatever the feature currently demands.1926*/1927if (ddt->ddt_version == DDT_VERSION_FDT)1928ddt_destroy_dir(ddt, tx);19291930ddt->ddt_version = DDT_VERSION_UNCONFIGURED;1931ddt->ddt_flags = 0;1932}19331934memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,1935sizeof (ddt->ddt_histogram));1936ddt->ddt_spa->spa_dedup_dspace = ~0ULL;1937ddt->ddt_spa->spa_dedup_dsize = ~0ULL;1938}19391940static void1941ddt_sync_scan_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)1942{1943dsl_pool_t *dp = ddt->ddt_spa->spa_dsl_pool;19441945/*1946* Compute the target class, so we can decide whether or not to inform1947* the scrub traversal (below). Note that we don't store this in the1948* entry, as it might change multiple times before finally being1949* committed (if we're logging). Instead, we recompute it in1950* ddt_sync_entry().1951*/1952uint64_t refcnt = ddt_phys_total_refcnt(ddt, &ddlwe->ddlwe_phys);1953ddt_class_t nclass =1954(refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;19551956/*1957* If the class changes, the order that we scan this bp changes. If it1958* decreases, we could miss it, so scan it right now. (This covers both1959* class changing while we are doing ddt_walk(), and when we are1960* traversing.)1961*1962* We also do this when the refcnt goes to zero, because that change is1963* only in the log so far; the blocks on disk won't be freed until1964* the log is flushed, and the refcnt might increase before that. If it1965* does, then we could miss it in the same way.1966*/1967if (refcnt == 0 || nclass < ddlwe->ddlwe_class)1968dsl_scan_ddt_entry(dp->dp_scan, ddt->ddt_checksum, ddt,1969ddlwe, tx);1970}19711972static void1973ddt_sync_flush_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe,1974ddt_type_t otype, ddt_class_t oclass, dmu_tx_t *tx)1975{1976ddt_key_t *ddk = &ddlwe->ddlwe_key;1977ddt_type_t ntype = DDT_TYPE_DEFAULT;1978uint64_t refcnt = 0;19791980/*1981* Compute the total refcnt. Along the way, issue frees for any DVAs1982* we no longer want.1983*/1984for (int p = 0; p < DDT_NPHYS(ddt); p++) {1985ddt_univ_phys_t *ddp = &ddlwe->ddlwe_phys;1986ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);1987uint64_t phys_refcnt = ddt_phys_refcnt(ddp, v);19881989if (ddt_phys_birth(ddp, v) == 0) {1990ASSERT0(phys_refcnt);1991continue;1992}1993if (DDT_PHYS_IS_DITTO(ddt, p)) {1994/*1995* We don't want to keep any obsolete slots (eg ditto),1996* regardless of their refcount, but we don't want to1997* leak them either. So, free them.1998*/1999ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);2000continue;2001}2002if (phys_refcnt == 0)2003/* No remaining references, free it! */2004ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);2005refcnt += phys_refcnt;2006}20072008/* Select the best class for the entry. */2009ddt_class_t nclass =2010(refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;20112012/*2013* If an existing entry changed type or class, or its refcount reached2014* zero, delete it from the DDT object2015*/2016if (otype != DDT_TYPES &&2017(otype != ntype || oclass != nclass || refcnt == 0)) {2018VERIFY0(ddt_object_remove(ddt, otype, oclass, ddk, tx));2019ASSERT(ddt_object_contains(ddt, otype, oclass, ddk) == ENOENT);2020}20212022/*2023* Add or update the entry2024*/2025if (refcnt != 0) {2026ddt_histogram_t *ddh =2027&ddt->ddt_histogram[ntype][nclass];20282029ddt_histogram_add_entry(ddt, ddh, ddlwe);20302031if (!ddt_object_exists(ddt, ntype, nclass))2032ddt_object_create(ddt, ntype, nclass, tx);2033VERIFY0(ddt_object_update(ddt, ntype, nclass, ddlwe, tx));2034}2035}20362037/* Calculate an exponential weighted moving average, lower limited to zero */2038static inline int32_t2039_ewma(int32_t val, int32_t prev, uint32_t weight)2040{2041ASSERT3U(val, >=, 0);2042ASSERT3U(prev, >=, 0);2043const int32_t new =2044MAX(0, prev + (val-prev) / (int32_t)MAX(weight, 1));2045ASSERT3U(new, >=, 0);2046return (new);2047}20482049static inline void2050ddt_flush_force_update_txg(ddt_t *ddt, uint64_t txg)2051{2052/*2053* If we're not forcing flush, and not being asked to start, then2054* there's nothing more to do.2055*/2056if (txg == 0) {2057/* Update requested, are we currently forcing flush? */2058if (ddt->ddt_flush_force_txg == 0)2059return;2060txg = ddt->ddt_flush_force_txg;2061}20622063/*2064* If either of the logs have entries unflushed entries before2065* the wanted txg, set the force txg, otherwise clear it.2066*/20672068if ((!avl_is_empty(&ddt->ddt_log_active->ddl_tree) &&2069ddt->ddt_log_active->ddl_first_txg <= txg) ||2070(!avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&2071ddt->ddt_log_flushing->ddl_first_txg <= txg)) {2072ddt->ddt_flush_force_txg = txg;2073return;2074}20752076/*2077* Nothing to flush behind the given txg, so we can clear force flush2078* state.2079*/2080ddt->ddt_flush_force_txg = 0;2081}20822083static void2084ddt_sync_flush_log(ddt_t *ddt, dmu_tx_t *tx)2085{2086spa_t *spa = ddt->ddt_spa;2087ASSERT(avl_is_empty(&ddt->ddt_tree));20882089/*2090* Don't do any flushing when the pool is ready to shut down, or in2091* passes beyond the first.2092*/2093if (spa_sync_pass(spa) > 1 || tx->tx_txg > spa_final_dirty_txg(spa))2094return;20952096hrtime_t flush_start = gethrtime();2097uint32_t count = 0;20982099/*2100* How many entries we need to flush. We need to at2101* least match the ingest rate, and also consider the2102* current backlog of entries.2103*/2104uint64_t backlog = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) +2105avl_numnodes(&ddt->ddt_log_active->ddl_tree);21062107if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree))2108goto housekeeping;21092110uint64_t txgs = MAX(1, zfs_dedup_log_flush_txgs);2111uint64_t cap = MAX(1, zfs_dedup_log_cap);2112uint64_t flush_min = MAX(backlog / txgs,2113zfs_dedup_log_flush_entries_min);21142115/*2116* The theory for this block is that if we increase the pressure while2117* we're growing above the cap, and remove it when we're significantly2118* below the cap, we'll stay near cap while not bouncing around too2119* much.2120*2121* The factor of 10 is to smooth the pressure effect by expressing it2122* in tenths. The addition of the cap to the backlog in the second2123* block is to round up, instead of down. We never let the pressure go2124* below 1 (10 tenths).2125*/2126if (cap != UINT_MAX && backlog > cap &&2127backlog > ddt->ddt_log_flush_prev_backlog) {2128ddt->ddt_log_flush_pressure += 10 * backlog / cap;2129} else if (cap != UINT_MAX && backlog < cap) {2130ddt->ddt_log_flush_pressure -=213111 - (((10 * backlog) + cap - 1) / cap);2132ddt->ddt_log_flush_pressure =2133MAX(ddt->ddt_log_flush_pressure, 10);2134}21352136if (zfs_dedup_log_hard_cap && cap != UINT_MAX)2137flush_min = MAX(flush_min, MIN(backlog - cap,2138(flush_min * ddt->ddt_log_flush_pressure) / 10));21392140uint64_t flush_max;21412142/*2143* If we've been asked to flush everything in a hurry,2144* try to dump as much as possible on this txg. In2145* this case we're only limited by time, not amount.2146*2147* Otherwise, if we are over the cap, try to get back down to it.2148*2149* Finally if there is no cap (or no pressure), just set the max a2150* little higher than the min to help smooth out variations in flush2151* times.2152*/2153if (ddt->ddt_flush_force_txg > 0)2154flush_max = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);2155else if (cap != UINT32_MAX && !zfs_dedup_log_hard_cap)2156flush_max = MAX(flush_min * 5 / 4, MIN(backlog - cap,2157(flush_min * ddt->ddt_log_flush_pressure) / 10));2158else2159flush_max = flush_min * 5 / 4;2160flush_max = MIN(flush_max, zfs_dedup_log_flush_entries_max);21612162/*2163* When the pool is busy or someone is explicitly waiting for this txg2164* to complete, use the zfs_dedup_log_flush_min_time_ms. Otherwise use2165* half of the time in the txg timeout.2166*/2167uint64_t target_time;21682169if (txg_sync_waiting(ddt->ddt_spa->spa_dsl_pool) ||2170vdev_queue_pool_busy(spa)) {2171target_time = MIN(MSEC2NSEC(zfs_dedup_log_flush_min_time_ms),2172SEC2NSEC(zfs_txg_timeout) / 2);2173} else {2174target_time = SEC2NSEC(zfs_txg_timeout) / 2;2175}21762177ddt_lightweight_entry_t ddlwe;2178while (ddt_log_take_first(ddt, ddt->ddt_log_flushing, &ddlwe)) {2179ddt_sync_flush_entry(ddt, &ddlwe,2180ddlwe.ddlwe_type, ddlwe.ddlwe_class, tx);21812182/* End if we've synced as much as we needed to. */2183if (++count >= flush_max)2184break;21852186/*2187* As long as we've flushed the absolute minimum,2188* stop if we're way over our target time.2189*/2190uint64_t diff = gethrtime() - flush_start;2191if (count > zfs_dedup_log_flush_entries_min &&2192diff >= target_time * 2)2193break;21942195/*2196* End if we've passed the minimum flush and we're out of time.2197*/2198if (count > flush_min && diff >= target_time)2199break;2200}22012202if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree)) {2203/* We emptied it, so truncate on-disk */2204DDT_KSTAT_ZERO(ddt, dds_log_flushing_entries);2205ddt_log_truncate(ddt, tx);2206} else {2207/* More to do next time, save checkpoint */2208DDT_KSTAT_SUB(ddt, dds_log_flushing_entries, count);2209ddt_log_checkpoint(ddt, &ddlwe, tx);2210}22112212ddt_sync_update_stats(ddt, tx);22132214housekeeping:2215if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&2216!avl_is_empty(&ddt->ddt_log_active->ddl_tree)) {2217/*2218* No more to flush, and the active list has stuff, so2219* try to swap the logs for next time.2220*/2221if (ddt_log_swap(ddt, tx)) {2222DDT_KSTAT_ZERO(ddt, dds_log_active_entries);2223DDT_KSTAT_SET(ddt, dds_log_flushing_entries,2224avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));2225}2226}22272228/* If force flush is no longer necessary, turn it off. */2229ddt_flush_force_update_txg(ddt, 0);22302231ddt->ddt_log_flush_prev_backlog = backlog;22322233/*2234* Update flush rate. This is an exponential weighted moving2235* average of the number of entries flushed over recent txgs.2236*/2237ddt->ddt_log_flush_rate = _ewma(count, ddt->ddt_log_flush_rate,2238zfs_dedup_log_flush_flow_rate_txgs);2239DDT_KSTAT_SET(ddt, dds_log_flush_rate, ddt->ddt_log_flush_rate);22402241/*2242* Update flush time rate. This is an exponential weighted moving2243* average of the total time taken to flush over recent txgs.2244*/2245ddt->ddt_log_flush_time_rate = _ewma(ddt->ddt_log_flush_time_rate,2246(int32_t)NSEC2MSEC(gethrtime() - flush_start),2247zfs_dedup_log_flush_flow_rate_txgs);2248DDT_KSTAT_SET(ddt, dds_log_flush_time_rate,2249ddt->ddt_log_flush_time_rate);2250if (avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) > 0 &&2251zfs_flags & ZFS_DEBUG_DDT) {2252zfs_dbgmsg("%lu entries remain(%lu in active), flushed %u @ "2253"txg %llu, in %llu ms, flush rate %d, time rate %d",2254(ulong_t)avl_numnodes(&ddt->ddt_log_flushing->ddl_tree),2255(ulong_t)avl_numnodes(&ddt->ddt_log_active->ddl_tree),2256count, (u_longlong_t)tx->tx_txg,2257(u_longlong_t)NSEC2MSEC(gethrtime() - flush_start),2258ddt->ddt_log_flush_rate, ddt->ddt_log_flush_time_rate);2259}2260}22612262static void2263ddt_sync_table_log(ddt_t *ddt, dmu_tx_t *tx)2264{2265uint64_t count = avl_numnodes(&ddt->ddt_tree);22662267if (count > 0) {2268ddt_log_update_t dlu = {0};2269ddt_log_begin(ddt, count, tx, &dlu);22702271ddt_entry_t *dde;2272void *cookie = NULL;2273ddt_lightweight_entry_t ddlwe;2274while ((dde =2275avl_destroy_nodes(&ddt->ddt_tree, &cookie)) != NULL) {2276ASSERT(dde->dde_flags & DDE_FLAG_LOADED);2277DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);2278ddt_log_entry(ddt, &ddlwe, &dlu);2279ddt_sync_scan_entry(ddt, &ddlwe, tx);2280ddt_free(ddt, dde);2281}22822283ddt_log_commit(ddt, &dlu);22842285DDT_KSTAT_SET(ddt, dds_log_active_entries,2286avl_numnodes(&ddt->ddt_log_active->ddl_tree));22872288/*2289* Sync the stats for the store objects. Even though we haven't2290* modified anything on those objects, they're no longer the2291* source of truth for entries that are now in the log, and we2292* need the on-disk counts to reflect that, otherwise we'll2293* miscount later when importing.2294*/2295for (ddt_type_t type = 0; type < DDT_TYPES; type++) {2296for (ddt_class_t class = 0;2297class < DDT_CLASSES; class++) {2298if (ddt_object_exists(ddt, type, class))2299ddt_object_sync(ddt, type, class, tx);2300}2301}23022303memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,2304sizeof (ddt->ddt_histogram));2305ddt->ddt_spa->spa_dedup_dspace = ~0ULL;2306ddt->ddt_spa->spa_dedup_dsize = ~0ULL;2307}23082309if (spa_sync_pass(ddt->ddt_spa) == 1) {2310/*2311* Update ingest rate. This is an exponential weighted moving2312* average of the number of entries changed over recent txgs.2313* The ramp-up cost shouldn't matter too much because the2314* flusher will be trying to take at least the minimum anyway.2315*/2316ddt->ddt_log_ingest_rate = _ewma(2317count, ddt->ddt_log_ingest_rate,2318zfs_dedup_log_flush_flow_rate_txgs);2319DDT_KSTAT_SET(ddt, dds_log_ingest_rate,2320ddt->ddt_log_ingest_rate);2321}2322}23232324static void2325ddt_sync_table_flush(ddt_t *ddt, dmu_tx_t *tx)2326{2327if (avl_numnodes(&ddt->ddt_tree) == 0)2328return;23292330ddt_entry_t *dde;2331void *cookie = NULL;2332while ((dde = avl_destroy_nodes(2333&ddt->ddt_tree, &cookie)) != NULL) {2334ASSERT(dde->dde_flags & DDE_FLAG_LOADED);23352336ddt_lightweight_entry_t ddlwe;2337DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);2338ddt_sync_flush_entry(ddt, &ddlwe,2339dde->dde_type, dde->dde_class, tx);2340ddt_sync_scan_entry(ddt, &ddlwe, tx);2341ddt_free(ddt, dde);2342}23432344memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,2345sizeof (ddt->ddt_histogram));2346ddt->ddt_spa->spa_dedup_dspace = ~0ULL;2347ddt->ddt_spa->spa_dedup_dsize = ~0ULL;2348ddt_sync_update_stats(ddt, tx);2349}23502351static void2352ddt_sync_table(ddt_t *ddt, dmu_tx_t *tx)2353{2354spa_t *spa = ddt->ddt_spa;23552356if (ddt->ddt_version == UINT64_MAX)2357return;23582359if (spa->spa_uberblock.ub_version < SPA_VERSION_DEDUP) {2360ASSERT0(avl_numnodes(&ddt->ddt_tree));2361return;2362}23632364if (spa->spa_ddt_stat_object == 0) {2365spa->spa_ddt_stat_object = zap_create_link(ddt->ddt_os,2366DMU_OT_DDT_STATS, DMU_POOL_DIRECTORY_OBJECT,2367DMU_POOL_DDT_STATS, tx);2368}23692370if (ddt->ddt_version == DDT_VERSION_FDT && ddt->ddt_dir_object == 0)2371ddt_create_dir(ddt, tx);23722373if (ddt->ddt_flags & DDT_FLAG_LOG)2374ddt_sync_table_log(ddt, tx);2375else2376ddt_sync_table_flush(ddt, tx);2377}23782379void2380ddt_sync(spa_t *spa, uint64_t txg)2381{2382dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;2383dmu_tx_t *tx;2384zio_t *rio;23852386ASSERT3U(spa_syncing_txg(spa), ==, txg);23872388tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);23892390rio = zio_root(spa, NULL, NULL,2391ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SELF_HEAL);23922393/*2394* This function may cause an immediate scan of ddt blocks (see2395* the comment above dsl_scan_ddt() for details). We set the2396* scan's root zio here so that we can wait for any scan IOs in2397* addition to the regular ddt IOs.2398*/2399ASSERT0P(scn->scn_zio_root);2400scn->scn_zio_root = rio;24012402for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2403ddt_t *ddt = spa->spa_ddt[c];2404if (ddt == NULL)2405continue;2406ddt_sync_table(ddt, tx);2407if (ddt->ddt_flags & DDT_FLAG_LOG)2408ddt_sync_flush_log(ddt, tx);2409ddt_repair_table(ddt, rio);2410}24112412(void) zio_wait(rio);2413scn->scn_zio_root = NULL;24142415dmu_tx_commit(tx);2416}24172418void2419ddt_walk_init(spa_t *spa, uint64_t txg)2420{2421if (txg == 0)2422txg = spa_syncing_txg(spa);24232424for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2425ddt_t *ddt = spa->spa_ddt[c];2426if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))2427continue;24282429ddt_enter(ddt);2430ddt_flush_force_update_txg(ddt, txg);2431ddt_exit(ddt);2432}2433}24342435boolean_t2436ddt_walk_ready(spa_t *spa)2437{2438for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2439ddt_t *ddt = spa->spa_ddt[c];2440if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))2441continue;24422443if (ddt->ddt_flush_force_txg > 0)2444return (B_FALSE);2445}24462447return (B_TRUE);2448}24492450static int2451ddt_walk_impl(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe,2452uint64_t flags, boolean_t wait)2453{2454do {2455do {2456do {2457ddt_t *ddt = spa->spa_ddt[ddb->ddb_checksum];2458if (ddt == NULL)2459continue;24602461if (flags != 0 &&2462(ddt->ddt_flags & flags) != flags)2463continue;24642465if (wait && ddt->ddt_flush_force_txg > 0)2466return (EAGAIN);24672468int error = ENOENT;2469if (ddt_object_exists(ddt, ddb->ddb_type,2470ddb->ddb_class)) {2471error = ddt_object_walk(ddt,2472ddb->ddb_type, ddb->ddb_class,2473&ddb->ddb_cursor, ddlwe);2474}2475if (error == 0)2476return (0);2477if (error != ENOENT)2478return (error);2479ddb->ddb_cursor = 0;2480} while (++ddb->ddb_checksum < ZIO_CHECKSUM_FUNCTIONS);2481ddb->ddb_checksum = 0;2482} while (++ddb->ddb_type < DDT_TYPES);2483ddb->ddb_type = 0;2484} while (++ddb->ddb_class < DDT_CLASSES);24852486return (SET_ERROR(ENOENT));2487}24882489int2490ddt_walk(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe)2491{2492return (ddt_walk_impl(spa, ddb, ddlwe, 0, B_TRUE));2493}24942495/*2496* This function is used by Block Cloning (brt.c) to increase reference2497* counter for the DDT entry if the block is already in DDT.2498*2499* Return false if the block, despite having the D bit set, is not present2500* in the DDT. This is possible when the DDT has been pruned by an admin2501* or by the DDT quota mechanism.2502*/2503boolean_t2504ddt_addref(spa_t *spa, const blkptr_t *bp)2505{2506ddt_t *ddt;2507ddt_entry_t *dde;2508boolean_t result;25092510spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);2511ddt = ddt_select(spa, bp);2512ddt_enter(ddt);25132514dde = ddt_lookup(ddt, bp, B_TRUE);25152516/* Can be NULL if the entry for this block was pruned. */2517if (dde == NULL) {2518ddt_exit(ddt);2519spa_config_exit(spa, SCL_ZIO, FTAG);2520return (B_FALSE);2521}25222523if ((dde->dde_type < DDT_TYPES) || (dde->dde_flags & DDE_FLAG_LOGGED)) {2524/*2525* This entry was either synced to a store object (dde_type is2526* real) or was logged. It must be properly on disk at this2527* point, so we can just bump its refcount.2528*/2529int p = DDT_PHYS_FOR_COPIES(ddt, BP_GET_NDVAS(bp));2530ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);25312532ddt_phys_addref(dde->dde_phys, v);2533result = B_TRUE;2534} else {2535/*2536* If the block has the DEDUP flag set it still might not2537* exist in the DEDUP table due to DDT pruning of entries2538* where refcnt=1.2539*/2540ddt_remove(ddt, dde);2541result = B_FALSE;2542}25432544ddt_exit(ddt);2545spa_config_exit(spa, SCL_ZIO, FTAG);25462547return (result);2548}25492550typedef struct ddt_prune_entry {2551ddt_t *dpe_ddt;2552ddt_key_t dpe_key;2553list_node_t dpe_node;2554ddt_univ_phys_t dpe_phys[];2555} ddt_prune_entry_t;25562557typedef struct ddt_prune_info {2558spa_t *dpi_spa;2559uint64_t dpi_txg_syncs;2560uint64_t dpi_pruned;2561list_t dpi_candidates;2562} ddt_prune_info_t;25632564/*2565* Add prune candidates for ddt_sync during spa_sync2566*/2567static void2568prune_candidates_sync(void *arg, dmu_tx_t *tx)2569{2570(void) tx;2571ddt_prune_info_t *dpi = arg;2572ddt_prune_entry_t *dpe;25732574spa_config_enter(dpi->dpi_spa, SCL_ZIO, FTAG, RW_READER);25752576/* Process the prune candidates collected so far */2577while ((dpe = list_remove_head(&dpi->dpi_candidates)) != NULL) {2578blkptr_t blk;2579ddt_t *ddt = dpe->dpe_ddt;25802581ddt_enter(ddt);25822583/*2584* If it's on the live list, then it was loaded for update2585* this txg and is no longer stale; skip it.2586*/2587if (avl_find(&ddt->ddt_tree, &dpe->dpe_key, NULL)) {2588ddt_exit(ddt);2589kmem_free(dpe, sizeof (*dpe));2590continue;2591}25922593ddt_bp_create(ddt->ddt_checksum, &dpe->dpe_key,2594dpe->dpe_phys, DDT_PHYS_FLAT, &blk);25952596ddt_entry_t *dde = ddt_lookup(ddt, &blk, B_TRUE);2597if (dde != NULL && !(dde->dde_flags & DDE_FLAG_LOGGED)) {2598ASSERT(dde->dde_flags & DDE_FLAG_LOADED);2599/*2600* Zero the physical, so we don't try to free DVAs2601* at flush nor try to reuse this entry.2602*/2603ddt_phys_clear(dde->dde_phys, DDT_PHYS_FLAT);26042605dpi->dpi_pruned++;2606}26072608ddt_exit(ddt);2609kmem_free(dpe, sizeof (*dpe));2610}26112612spa_config_exit(dpi->dpi_spa, SCL_ZIO, FTAG);2613dpi->dpi_txg_syncs++;2614}26152616/*2617* Prune candidates are collected in open context and processed2618* in sync context as part of ddt_sync_table().2619*/2620static void2621ddt_prune_entry(list_t *list, ddt_t *ddt, const ddt_key_t *ddk,2622const ddt_univ_phys_t *ddp)2623{2624ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);26252626size_t dpe_size = sizeof (ddt_prune_entry_t) + DDT_FLAT_PHYS_SIZE;2627ddt_prune_entry_t *dpe = kmem_alloc(dpe_size, KM_SLEEP);26282629dpe->dpe_ddt = ddt;2630dpe->dpe_key = *ddk;2631memcpy(dpe->dpe_phys, ddp, DDT_FLAT_PHYS_SIZE);2632list_insert_head(list, dpe);2633}26342635/*2636* Interate over all the entries in the DDT unique class.2637* The walk will perform one of the following operations:2638* (a) build a histogram than can be used when pruning2639* (b) prune entries older than the cutoff2640*2641* Also called by zdb(8) to dump the age histogram2642*/2643void2644ddt_prune_walk(spa_t *spa, uint64_t cutoff, ddt_age_histo_t *histogram)2645{2646ddt_bookmark_t ddb = {2647.ddb_class = DDT_CLASS_UNIQUE,2648.ddb_type = 0,2649.ddb_checksum = 0,2650.ddb_cursor = 02651};2652ddt_lightweight_entry_t ddlwe = {0};2653int error;2654int valid = 0;2655int candidates = 0;2656uint64_t now = gethrestime_sec();2657ddt_prune_info_t dpi;2658boolean_t pruning = (cutoff != 0);26592660if (pruning) {2661dpi.dpi_txg_syncs = 0;2662dpi.dpi_pruned = 0;2663dpi.dpi_spa = spa;2664list_create(&dpi.dpi_candidates, sizeof (ddt_prune_entry_t),2665offsetof(ddt_prune_entry_t, dpe_node));2666}26672668if (histogram != NULL)2669memset(histogram, 0, sizeof (ddt_age_histo_t));26702671while ((error =2672ddt_walk_impl(spa, &ddb, &ddlwe, DDT_FLAG_FLAT, B_FALSE)) == 0) {2673ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];2674VERIFY(ddt);26752676if (spa_shutting_down(spa) || issig())2677break;26782679ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);2680ASSERT3U(ddlwe.ddlwe_phys.ddp_flat.ddp_refcnt, <=, 1);26812682uint64_t class_start =2683ddlwe.ddlwe_phys.ddp_flat.ddp_class_start;26842685/*2686* If this entry is on the log, then the stored entry is stale2687* and we should skip it.2688*/2689if (ddt_log_find_key(ddt, &ddlwe.ddlwe_key, NULL))2690continue;26912692/* prune older entries */2693if (pruning && class_start < cutoff) {2694if (candidates++ >= zfs_ddt_prunes_per_txg) {2695/* sync prune candidates in batches */2696VERIFY0(dsl_sync_task(spa_name(spa),2697NULL, prune_candidates_sync,2698&dpi, 0, ZFS_SPACE_CHECK_NONE));2699candidates = 1;2700}2701ddt_prune_entry(&dpi.dpi_candidates, ddt,2702&ddlwe.ddlwe_key, &ddlwe.ddlwe_phys);2703}27042705/* build a histogram */2706if (histogram != NULL) {2707uint64_t age = MAX(1, (now - class_start) / 3600);2708int bin = MIN(highbit64(age) - 1, HIST_BINS - 1);2709histogram->dah_entries++;2710histogram->dah_age_histo[bin]++;2711}27122713valid++;2714}27152716if (pruning && valid > 0) {2717if (!list_is_empty(&dpi.dpi_candidates)) {2718/* sync out final batch of prune candidates */2719VERIFY0(dsl_sync_task(spa_name(spa), NULL,2720prune_candidates_sync, &dpi, 0,2721ZFS_SPACE_CHECK_NONE));2722}2723list_destroy(&dpi.dpi_candidates);27242725zfs_dbgmsg("pruned %llu entries (%d%%) across %llu txg syncs",2726(u_longlong_t)dpi.dpi_pruned,2727(int)((dpi.dpi_pruned * 100) / valid),2728(u_longlong_t)dpi.dpi_txg_syncs);2729}2730}27312732static uint64_t2733ddt_total_entries(spa_t *spa)2734{2735ddt_object_t ddo;2736ddt_get_dedup_object_stats(spa, &ddo);27372738return (ddo.ddo_count);2739}27402741int2742ddt_prune_unique_entries(spa_t *spa, zpool_ddt_prune_unit_t unit,2743uint64_t amount)2744{2745uint64_t cutoff;2746uint64_t start_time = gethrtime();27472748if (spa->spa_active_ddt_prune)2749return (SET_ERROR(EALREADY));2750if (ddt_total_entries(spa) == 0)2751return (0);27522753spa->spa_active_ddt_prune = B_TRUE;27542755zfs_dbgmsg("prune %llu %s", (u_longlong_t)amount,2756unit == ZPOOL_DDT_PRUNE_PERCENTAGE ? "%" : "seconds old or older");27572758if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {2759ddt_age_histo_t histogram;2760uint64_t oldest = 0;27612762/* Make a pass over DDT to build a histogram */2763ddt_prune_walk(spa, 0, &histogram);27642765int target = (histogram.dah_entries * amount) / 100;27662767/*2768* Figure out our cutoff date2769* (i.e., which bins to prune from)2770*/2771for (int i = HIST_BINS - 1; i >= 0 && target > 0; i--) {2772if (histogram.dah_age_histo[i] != 0) {2773/* less than this bucket remaining */2774if (target < histogram.dah_age_histo[i]) {2775oldest = MAX(1, (1<<i) * 3600);2776target = 0;2777} else {2778target -= histogram.dah_age_histo[i];2779}2780}2781}2782cutoff = gethrestime_sec() - oldest;27832784if (ddt_dump_prune_histogram)2785ddt_dump_age_histogram(&histogram, cutoff);2786} else if (unit == ZPOOL_DDT_PRUNE_AGE) {2787cutoff = gethrestime_sec() - amount;2788} else {2789return (EINVAL);2790}27912792if (cutoff > 0 && !spa_shutting_down(spa) && !issig()) {2793/* Traverse DDT to prune entries older that our cuttoff */2794ddt_prune_walk(spa, cutoff, NULL);2795}27962797zfs_dbgmsg("%s: prune completed in %llu ms",2798spa_name(spa), (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));27992800spa->spa_active_ddt_prune = B_FALSE;2801return (0);2802}28032804ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, prefetch, INT, ZMOD_RW,2805"Enable prefetching dedup-ed blks");28062807ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_min_time_ms, UINT, ZMOD_RW,2808"Min time to spend on incremental dedup log flush each transaction");28092810ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_min, UINT, ZMOD_RW,2811"Min number of log entries to flush each transaction");28122813ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_max, UINT, ZMOD_RW,2814"Max number of log entries to flush each transaction");28152816ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_txgs, UINT, ZMOD_RW,2817"Number of TXGs to try to rotate the log in");28182819ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_cap, UINT, ZMOD_RW,2820"Soft cap for the size of the current dedup log");28212822ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_hard_cap, UINT, ZMOD_RW,2823"Whether to use the soft cap as a hard cap");28242825ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_flow_rate_txgs, UINT, ZMOD_RW,2826"Number of txgs to average flow rates across");282728282829