Path: blob/main/sys/contrib/openzfs/module/zfs/ddt.c
107074 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/*365* Hot-path lookup counters use wmsums to avoid cache line bouncing.366* DDT_KSTAT_BUMP: Increment a wmsum counter (lookup stats).367*368* Sync-only counters use direct kstat assignment (no atomics needed).369* DDT_KSTAT_SET: Set a value (log entry counts, rates).370* DDT_KSTAT_SUB: Subtract from a value (decrement log entry counts).371* DDT_KSTAT_ZERO: Zero a value (clear log entry counts).372*/373#define _DDT_KSTAT_STAT(ddt, stat) \374&((ddt_kstats_t *)(ddt)->ddt_ksp->ks_data)->stat.value.ui64375#define DDT_KSTAT_BUMP(ddt, stat) \376wmsum_add(&(ddt)->ddt_kstat_##stat, 1)377#define DDT_KSTAT_SUB(ddt, stat, val) \378do { *_DDT_KSTAT_STAT(ddt, stat) -= (val); } while (0)379#define DDT_KSTAT_SET(ddt, stat, val) \380do { *_DDT_KSTAT_STAT(ddt, stat) = (val); } while (0)381#define DDT_KSTAT_ZERO(ddt, stat) DDT_KSTAT_SET(ddt, stat, 0)382#else383#define DDT_KSTAT_BUMP(ddt, stat) do {} while (0)384#define DDT_KSTAT_SUB(ddt, stat, val) do {} while (0)385#define DDT_KSTAT_SET(ddt, stat, val) do {} while (0)386#define DDT_KSTAT_ZERO(ddt, stat) do {} while (0)387#endif /* _KERNEL */388389390static void391ddt_object_create(ddt_t *ddt, ddt_type_t type, ddt_class_t class,392dmu_tx_t *tx)393{394spa_t *spa = ddt->ddt_spa;395objset_t *os = ddt->ddt_os;396uint64_t *objectp = &ddt->ddt_object[type][class];397boolean_t prehash = zio_checksum_table[ddt->ddt_checksum].ci_flags &398ZCHECKSUM_FLAG_DEDUP;399char name[DDT_NAMELEN];400401ASSERT3U(ddt->ddt_dir_object, >, 0);402403ddt_object_name(ddt, type, class, name);404405ASSERT0(*objectp);406VERIFY0(ddt_ops[type]->ddt_op_create(os, objectp, tx, prehash));407ASSERT3U(*objectp, !=, 0);408409VERIFY0(dnode_hold(os, *objectp, ddt,410&ddt->ddt_object_dnode[type][class]));411412ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);413414VERIFY0(zap_add(os, ddt->ddt_dir_object, name, sizeof (uint64_t), 1,415objectp, tx));416417VERIFY0(zap_add(os, spa->spa_ddt_stat_object, name,418sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),419&ddt->ddt_histogram[type][class], tx));420}421422static void423ddt_object_destroy(ddt_t *ddt, ddt_type_t type, ddt_class_t class,424dmu_tx_t *tx)425{426spa_t *spa = ddt->ddt_spa;427objset_t *os = ddt->ddt_os;428uint64_t *objectp = &ddt->ddt_object[type][class];429uint64_t count;430char name[DDT_NAMELEN];431432ASSERT3U(ddt->ddt_dir_object, >, 0);433434ddt_object_name(ddt, type, class, name);435436ASSERT3U(*objectp, !=, 0);437ASSERT(ddt_histogram_empty(&ddt->ddt_histogram[type][class]));438VERIFY0(ddt_object_count(ddt, type, class, &count));439VERIFY0(count);440VERIFY0(zap_remove(os, ddt->ddt_dir_object, name, tx));441VERIFY0(zap_remove(os, spa->spa_ddt_stat_object, name, tx));442if (ddt->ddt_object_dnode[type][class] != NULL) {443dnode_rele(ddt->ddt_object_dnode[type][class], ddt);444ddt->ddt_object_dnode[type][class] = NULL;445}446VERIFY0(ddt_ops[type]->ddt_op_destroy(os, *objectp, tx));447memset(&ddt->ddt_object_stats[type][class], 0, sizeof (ddt_object_t));448449*objectp = 0;450}451452static int453ddt_object_load(ddt_t *ddt, ddt_type_t type, ddt_class_t class)454{455ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];456dmu_object_info_t doi;457uint64_t count;458char name[DDT_NAMELEN];459int error;460461if (ddt->ddt_dir_object == 0) {462/*463* If we're configured but the containing dir doesn't exist464* yet, then this object can't possibly exist either.465*/466ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);467return (SET_ERROR(ENOENT));468}469470ddt_object_name(ddt, type, class, name);471472error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object, name,473sizeof (uint64_t), 1, &ddt->ddt_object[type][class]);474if (error != 0)475return (error);476477error = dnode_hold(ddt->ddt_os, ddt->ddt_object[type][class], ddt,478&ddt->ddt_object_dnode[type][class]);479if (error != 0)480return (error);481482error = zap_lookup(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,483sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),484&ddt->ddt_histogram[type][class]);485if (error != 0)486goto error;487488/*489* Seed the cached statistics.490*/491error = ddt_object_info(ddt, type, class, &doi);492if (error)493goto error;494495error = ddt_object_count(ddt, type, class, &count);496if (error)497goto error;498499ddo->ddo_count = count;500ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;501ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;502503return (0);504505error:506dnode_rele(ddt->ddt_object_dnode[type][class], ddt);507ddt->ddt_object_dnode[type][class] = NULL;508return (error);509}510511static void512ddt_object_sync(ddt_t *ddt, ddt_type_t type, ddt_class_t class,513dmu_tx_t *tx)514{515ddt_object_t *ddo = &ddt->ddt_object_stats[type][class];516dmu_object_info_t doi;517uint64_t count;518char name[DDT_NAMELEN];519520ddt_object_name(ddt, type, class, name);521522VERIFY0(zap_update(ddt->ddt_os, ddt->ddt_spa->spa_ddt_stat_object, name,523sizeof (uint64_t), sizeof (ddt_histogram_t) / sizeof (uint64_t),524&ddt->ddt_histogram[type][class], tx));525526/*527* Cache DDT statistics; this is the only time they'll change.528*/529VERIFY0(ddt_object_info(ddt, type, class, &doi));530VERIFY0(ddt_object_count(ddt, type, class, &count));531532ddo->ddo_count = count;533ddo->ddo_dspace = doi.doi_physical_blocks_512 << 9;534ddo->ddo_mspace = doi.doi_fill_count * doi.doi_data_block_size;535}536537static boolean_t538ddt_object_exists(ddt_t *ddt, ddt_type_t type, ddt_class_t class)539{540return (!!ddt->ddt_object[type][class]);541}542543static int544ddt_object_lookup(ddt_t *ddt, ddt_type_t type, ddt_class_t class,545ddt_entry_t *dde)546{547dnode_t *dn = ddt->ddt_object_dnode[type][class];548if (dn == NULL)549return (SET_ERROR(ENOENT));550551return (ddt_ops[type]->ddt_op_lookup(dn, &dde->dde_key,552dde->dde_phys, DDT_PHYS_SIZE(ddt)));553}554555static int556ddt_object_contains(ddt_t *ddt, ddt_type_t type, ddt_class_t class,557const ddt_key_t *ddk)558{559dnode_t *dn = ddt->ddt_object_dnode[type][class];560if (dn == NULL)561return (SET_ERROR(ENOENT));562563return (ddt_ops[type]->ddt_op_contains(dn, ddk));564}565566static void567ddt_object_prefetch(ddt_t *ddt, ddt_type_t type, ddt_class_t class,568const ddt_key_t *ddk)569{570dnode_t *dn = ddt->ddt_object_dnode[type][class];571if (dn == NULL)572return;573574ddt_ops[type]->ddt_op_prefetch(dn, ddk);575}576577static void578ddt_object_prefetch_all(ddt_t *ddt, ddt_type_t type, ddt_class_t class)579{580dnode_t *dn = ddt->ddt_object_dnode[type][class];581if (dn == NULL)582return;583584ddt_ops[type]->ddt_op_prefetch_all(dn);585}586587static int588ddt_object_update(ddt_t *ddt, ddt_type_t type, ddt_class_t class,589const ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)590{591dnode_t *dn = ddt->ddt_object_dnode[type][class];592ASSERT(dn != NULL);593594return (ddt_ops[type]->ddt_op_update(dn, &ddlwe->ddlwe_key,595&ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt), tx));596}597598static int599ddt_object_remove(ddt_t *ddt, ddt_type_t type, ddt_class_t class,600const ddt_key_t *ddk, dmu_tx_t *tx)601{602dnode_t *dn = ddt->ddt_object_dnode[type][class];603ASSERT(dn != NULL);604605return (ddt_ops[type]->ddt_op_remove(dn, ddk, tx));606}607608int609ddt_object_walk(ddt_t *ddt, ddt_type_t type, ddt_class_t class,610uint64_t *walk, ddt_lightweight_entry_t *ddlwe)611{612dnode_t *dn = ddt->ddt_object_dnode[type][class];613ASSERT(dn != NULL);614615int error = ddt_ops[type]->ddt_op_walk(dn, walk, &ddlwe->ddlwe_key,616&ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt));617if (error == 0) {618ddlwe->ddlwe_type = type;619ddlwe->ddlwe_class = class;620return (0);621}622return (error);623}624625int626ddt_object_count(ddt_t *ddt, ddt_type_t type, ddt_class_t class,627uint64_t *count)628{629dnode_t *dn = ddt->ddt_object_dnode[type][class];630ASSERT(dn != NULL);631632return (ddt_ops[type]->ddt_op_count(dn, count));633}634635int636ddt_object_info(ddt_t *ddt, ddt_type_t type, ddt_class_t class,637dmu_object_info_t *doi)638{639if (!ddt_object_exists(ddt, type, class))640return (SET_ERROR(ENOENT));641642return (dmu_object_info(ddt->ddt_os, ddt->ddt_object[type][class],643doi));644}645646void647ddt_object_name(ddt_t *ddt, ddt_type_t type, ddt_class_t class,648char *name)649{650(void) snprintf(name, DDT_NAMELEN, DMU_POOL_DDT,651zio_checksum_table[ddt->ddt_checksum].ci_name,652ddt_ops[type]->ddt_op_name, ddt_class_name[class]);653}654655void656ddt_bp_fill(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,657blkptr_t *bp, uint64_t txg)658{659ASSERT3U(txg, !=, 0);660ASSERT3U(v, <, DDT_PHYS_NONE);661uint64_t phys_birth;662const dva_t *dvap;663664if (v == DDT_PHYS_FLAT) {665phys_birth = ddp->ddp_flat.ddp_phys_birth;666dvap = ddp->ddp_flat.ddp_dva;667} else {668phys_birth = ddp->ddp_trad[v].ddp_phys_birth;669dvap = ddp->ddp_trad[v].ddp_dva;670}671672for (int d = 0; d < SPA_DVAS_PER_BP; d++)673bp->blk_dva[d] = dvap[d];674BP_SET_BIRTH(bp, txg, phys_birth);675}676677/*678* The bp created via this function may be used for repairs and scrub, but it679* will be missing the salt / IV required to do a full decrypting read.680*/681void682ddt_bp_create(enum zio_checksum checksum, const ddt_key_t *ddk,683const ddt_univ_phys_t *ddp, ddt_phys_variant_t v, blkptr_t *bp)684{685BP_ZERO(bp);686687if (ddp != NULL)688ddt_bp_fill(ddp, v, bp, ddt_phys_birth(ddp, v));689690bp->blk_cksum = ddk->ddk_cksum;691692BP_SET_LSIZE(bp, DDK_GET_LSIZE(ddk));693BP_SET_PSIZE(bp, DDK_GET_PSIZE(ddk));694BP_SET_COMPRESS(bp, DDK_GET_COMPRESS(ddk));695BP_SET_CRYPT(bp, DDK_GET_CRYPT(ddk));696BP_SET_FILL(bp, 1);697BP_SET_CHECKSUM(bp, checksum);698BP_SET_TYPE(bp, DMU_OT_DEDUP);699BP_SET_LEVEL(bp, 0);700BP_SET_DEDUP(bp, 1);701BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);702}703704void705ddt_key_fill(ddt_key_t *ddk, const blkptr_t *bp)706{707ddk->ddk_cksum = bp->blk_cksum;708ddk->ddk_prop = 0;709710ASSERT(BP_IS_ENCRYPTED(bp) || !BP_USES_CRYPT(bp));711712DDK_SET_LSIZE(ddk, BP_GET_LSIZE(bp));713DDK_SET_PSIZE(ddk, BP_GET_PSIZE(bp));714DDK_SET_COMPRESS(ddk, BP_GET_COMPRESS(bp));715DDK_SET_CRYPT(ddk, BP_USES_CRYPT(bp));716}717718void719ddt_phys_extend(ddt_univ_phys_t *ddp, ddt_phys_variant_t v, const blkptr_t *bp)720{721ASSERT3U(v, <, DDT_PHYS_NONE);722int bp_ndvas = BP_GET_NDVAS(bp);723int ddp_max_dvas = BP_IS_ENCRYPTED(bp) ?724SPA_DVAS_PER_BP - 1 : SPA_DVAS_PER_BP;725dva_t *dvas = (v == DDT_PHYS_FLAT) ?726ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;727728int s = 0, d = 0;729while (s < bp_ndvas && d < ddp_max_dvas) {730if (DVA_IS_VALID(&dvas[d])) {731d++;732continue;733}734dvas[d] = bp->blk_dva[s];735s++; d++;736}737738/*739* If the caller offered us more DVAs than we can fit, something has740* gone wrong in their accounting. zio_ddt_write() should never ask for741* more than we need.742*/743ASSERT3U(s, ==, bp_ndvas);744745if (BP_IS_ENCRYPTED(bp))746dvas[2] = bp->blk_dva[2];747748if (ddt_phys_birth(ddp, v) == 0) {749if (v == DDT_PHYS_FLAT) {750ddp->ddp_flat.ddp_phys_birth =751BP_GET_PHYSICAL_BIRTH(bp);752} else {753ddp->ddp_trad[v].ddp_phys_birth =754BP_GET_PHYSICAL_BIRTH(bp);755}756}757}758759void760ddt_phys_unextend(ddt_univ_phys_t *cur, ddt_univ_phys_t *orig,761ddt_phys_variant_t v)762{763ASSERT3U(v, <, DDT_PHYS_NONE);764dva_t *cur_dvas = (v == DDT_PHYS_FLAT) ?765cur->ddp_flat.ddp_dva : cur->ddp_trad[v].ddp_dva;766dva_t *orig_dvas = (v == DDT_PHYS_FLAT) ?767orig->ddp_flat.ddp_dva : orig->ddp_trad[v].ddp_dva;768769for (int d = 0; d < SPA_DVAS_PER_BP; d++)770cur_dvas[d] = orig_dvas[d];771772if (ddt_phys_birth(orig, v) == 0) {773if (v == DDT_PHYS_FLAT)774cur->ddp_flat.ddp_phys_birth = 0;775else776cur->ddp_trad[v].ddp_phys_birth = 0;777}778}779780void781ddt_phys_copy(ddt_univ_phys_t *dst, const ddt_univ_phys_t *src,782ddt_phys_variant_t v)783{784ASSERT3U(v, <, DDT_PHYS_NONE);785786if (v == DDT_PHYS_FLAT)787dst->ddp_flat = src->ddp_flat;788else789dst->ddp_trad[v] = src->ddp_trad[v];790}791792void793ddt_phys_clear(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)794{795ASSERT3U(v, <, DDT_PHYS_NONE);796797if (v == DDT_PHYS_FLAT)798memset(&ddp->ddp_flat, 0, DDT_FLAT_PHYS_SIZE);799else800memset(&ddp->ddp_trad[v], 0, DDT_TRAD_PHYS_SIZE / DDT_PHYS_MAX);801}802803static uint64_t804ddt_class_start(void)805{806uint64_t start = gethrestime_sec();807808if (unlikely(ddt_prune_artificial_age)) {809/*810* debug aide -- simulate a wider distribution811* so we don't have to wait for an aged DDT812* to test prune.813*/814int range = 1 << 21;815int percent = random_in_range(100);816if (percent < 50) {817range = range >> 4;818} else if (percent > 75) {819range /= 2;820}821start -= random_in_range(range);822}823824return (start);825}826827void828ddt_phys_addref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)829{830ASSERT3U(v, <, DDT_PHYS_NONE);831832if (v == DDT_PHYS_FLAT)833ddp->ddp_flat.ddp_refcnt++;834else835ddp->ddp_trad[v].ddp_refcnt++;836}837838uint64_t839ddt_phys_decref(ddt_univ_phys_t *ddp, ddt_phys_variant_t v)840{841ASSERT3U(v, <, DDT_PHYS_NONE);842843uint64_t *refcntp;844845if (v == DDT_PHYS_FLAT)846refcntp = &ddp->ddp_flat.ddp_refcnt;847else848refcntp = &ddp->ddp_trad[v].ddp_refcnt;849850ASSERT3U(*refcntp, >, 0);851(*refcntp)--;852return (*refcntp);853}854855static void856ddt_phys_free(ddt_t *ddt, ddt_key_t *ddk, ddt_univ_phys_t *ddp,857ddt_phys_variant_t v, uint64_t txg)858{859blkptr_t blk;860861ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);862863/*864* We clear the dedup bit so that zio_free() will actually free the865* space, rather than just decrementing the refcount in the DDT.866*/867BP_SET_DEDUP(&blk, 0);868869ddt_phys_clear(ddp, v);870zio_free(ddt->ddt_spa, txg, &blk);871}872873uint64_t874ddt_phys_birth(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)875{876ASSERT3U(v, <, DDT_PHYS_NONE);877878if (v == DDT_PHYS_FLAT)879return (ddp->ddp_flat.ddp_phys_birth);880else881return (ddp->ddp_trad[v].ddp_phys_birth);882}883884int885ddt_phys_is_gang(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)886{887ASSERT3U(v, <, DDT_PHYS_NONE);888889const dva_t *dvas = (v == DDT_PHYS_FLAT) ?890ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;891892return (DVA_GET_GANG(&dvas[0]));893}894895int896ddt_phys_dva_count(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v,897boolean_t encrypted)898{899ASSERT3U(v, <, DDT_PHYS_NONE);900901const dva_t *dvas = (v == DDT_PHYS_FLAT) ?902ddp->ddp_flat.ddp_dva : ddp->ddp_trad[v].ddp_dva;903904return (DVA_IS_VALID(&dvas[0]) +905DVA_IS_VALID(&dvas[1]) +906DVA_IS_VALID(&dvas[2]) * !encrypted);907}908909ddt_phys_variant_t910ddt_phys_select(const ddt_t *ddt, const ddt_entry_t *dde, const blkptr_t *bp)911{912if (dde == NULL)913return (DDT_PHYS_NONE);914915const ddt_univ_phys_t *ddp = dde->dde_phys;916917if (ddt->ddt_flags & DDT_FLAG_FLAT) {918if (DVA_EQUAL(BP_IDENTITY(bp), &ddp->ddp_flat.ddp_dva[0]) &&919BP_GET_PHYSICAL_BIRTH(bp) == ddp->ddp_flat.ddp_phys_birth) {920return (DDT_PHYS_FLAT);921}922} else /* traditional phys */ {923for (int p = 0; p < DDT_PHYS_MAX; p++) {924if (DVA_EQUAL(BP_IDENTITY(bp),925&ddp->ddp_trad[p].ddp_dva[0]) &&926BP_GET_PHYSICAL_BIRTH(bp) ==927ddp->ddp_trad[p].ddp_phys_birth) {928return (p);929}930}931}932return (DDT_PHYS_NONE);933}934935uint64_t936ddt_phys_refcnt(const ddt_univ_phys_t *ddp, ddt_phys_variant_t v)937{938ASSERT3U(v, <, DDT_PHYS_NONE);939940if (v == DDT_PHYS_FLAT)941return (ddp->ddp_flat.ddp_refcnt);942else943return (ddp->ddp_trad[v].ddp_refcnt);944}945946uint64_t947ddt_phys_total_refcnt(const ddt_t *ddt, const ddt_univ_phys_t *ddp)948{949uint64_t refcnt = 0;950951if (ddt->ddt_flags & DDT_FLAG_FLAT)952refcnt = ddp->ddp_flat.ddp_refcnt;953else954for (int v = DDT_PHYS_SINGLE; v <= DDT_PHYS_TRIPLE; v++)955refcnt += ddp->ddp_trad[v].ddp_refcnt;956957return (refcnt);958}959960ddt_t *961ddt_select(spa_t *spa, const blkptr_t *bp)962{963ASSERT(DDT_CHECKSUM_VALID(BP_GET_CHECKSUM(bp)));964return (spa->spa_ddt[BP_GET_CHECKSUM(bp)]);965}966967void968ddt_enter(ddt_t *ddt)969{970mutex_enter(&ddt->ddt_lock);971}972973void974ddt_exit(ddt_t *ddt)975{976mutex_exit(&ddt->ddt_lock);977}978979void980ddt_init(void)981{982ddt_cache = kmem_cache_create("ddt_cache",983sizeof (ddt_t), 0, NULL, NULL, NULL, NULL, NULL, 0);984ddt_entry_flat_cache = kmem_cache_create("ddt_entry_flat_cache",985DDT_ENTRY_FLAT_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);986ddt_entry_trad_cache = kmem_cache_create("ddt_entry_trad_cache",987DDT_ENTRY_TRAD_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);988989ddt_log_init();990}991992void993ddt_fini(void)994{995ddt_log_fini();996997kmem_cache_destroy(ddt_entry_trad_cache);998kmem_cache_destroy(ddt_entry_flat_cache);999kmem_cache_destroy(ddt_cache);1000}10011002static ddt_entry_t *1003ddt_alloc(const ddt_t *ddt, const ddt_key_t *ddk)1004{1005ddt_entry_t *dde;10061007if (ddt->ddt_flags & DDT_FLAG_FLAT) {1008dde = kmem_cache_alloc(ddt_entry_flat_cache, KM_SLEEP);1009memset(dde, 0, DDT_ENTRY_FLAT_SIZE);1010} else {1011dde = kmem_cache_alloc(ddt_entry_trad_cache, KM_SLEEP);1012memset(dde, 0, DDT_ENTRY_TRAD_SIZE);1013}10141015cv_init(&dde->dde_cv, NULL, CV_DEFAULT, NULL);10161017dde->dde_key = *ddk;10181019return (dde);1020}10211022void1023ddt_alloc_entry_io(ddt_entry_t *dde)1024{1025if (dde->dde_io != NULL)1026return;10271028dde->dde_io = kmem_zalloc(sizeof (ddt_entry_io_t), KM_SLEEP);1029mutex_init(&dde->dde_io->dde_io_lock, NULL, MUTEX_DEFAULT, NULL);1030}10311032static void1033ddt_free(const ddt_t *ddt, ddt_entry_t *dde)1034{1035if (dde->dde_io != NULL) {1036for (int p = 0; p < DDT_NPHYS(ddt); p++)1037ASSERT0P(dde->dde_io->dde_lead_zio[p]);10381039if (dde->dde_io->dde_repair_abd != NULL)1040abd_free(dde->dde_io->dde_repair_abd);10411042mutex_destroy(&dde->dde_io->dde_io_lock);1043kmem_free(dde->dde_io, sizeof (ddt_entry_io_t));1044}10451046cv_destroy(&dde->dde_cv);1047kmem_cache_free(ddt->ddt_flags & DDT_FLAG_FLAT ?1048ddt_entry_flat_cache : ddt_entry_trad_cache, dde);1049}10501051void1052ddt_remove(ddt_t *ddt, ddt_entry_t *dde)1053{1054ASSERT(MUTEX_HELD(&ddt->ddt_lock));10551056avl_remove(&ddt->ddt_tree, dde);1057ddt_free(ddt, dde);1058}10591060/*1061* We're considered over quota when we hit 85% full, or for larger drives,1062* when there is less than 8GB free.1063*/1064static boolean_t1065ddt_special_over_quota(metaslab_class_t *mc)1066{1067uint64_t allocated = metaslab_class_get_alloc(mc);1068uint64_t capacity = metaslab_class_get_space(mc);1069uint64_t limit = MAX(capacity * 85 / 100,1070(capacity > (1LL<<33)) ? capacity - (1LL<<33) : 0);1071return (allocated >= limit);1072}10731074/*1075* Check if the DDT is over its quota. This can be due to a few conditions:1076* 1. 'dedup_table_quota' property is not 0 (none) and the dedup dsize1077* exceeds this limit1078*1079* 2. 'dedup_table_quota' property is set to automatic and1080* a. the dedup or special allocation class could not satisfy a DDT1081* allocation in a recent transaction1082* b. the dedup or special allocation class has exceeded its 85% limit1083*/1084static boolean_t1085ddt_over_quota(spa_t *spa)1086{1087if (spa->spa_dedup_table_quota == 0)1088return (B_FALSE);10891090if (spa->spa_dedup_table_quota != UINT64_MAX)1091return (ddt_get_ddt_dsize(spa) > spa->spa_dedup_table_quota);10921093/*1094* Over quota if have to allocate outside of the dedup/special class.1095*/1096if (spa_syncing_txg(spa) <= spa->spa_dedup_class_full_txg +1097dedup_class_wait_txgs) {1098/* Waiting for some deferred frees to be processed */1099return (B_TRUE);1100}11011102/*1103* For automatic quota, table size is limited by dedup or special class1104*/1105if (spa_has_dedup(spa))1106return (ddt_special_over_quota(spa_dedup_class(spa)));1107else if (spa_special_has_ddt(spa))1108return (ddt_special_over_quota(spa_special_class(spa)));11091110return (B_FALSE);1111}11121113void1114ddt_prefetch_all(spa_t *spa)1115{1116/*1117* Load all DDT entries for each type/class combination. This is1118* indended to perform a prefetch on all such blocks. For the same1119* reason that ddt_prefetch isn't locked, this is also not locked.1120*/1121for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1122ddt_t *ddt = spa->spa_ddt[c];1123if (!ddt)1124continue;11251126for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1127for (ddt_class_t class = 0; class < DDT_CLASSES;1128class++) {1129ddt_object_prefetch_all(ddt, type, class);1130}1131}1132}1133}11341135static int ddt_configure(ddt_t *ddt, boolean_t new);11361137/*1138* If the BP passed to ddt_lookup has valid DVAs, then we need to compare them1139* to the ones in the entry. If they're different, then the passed-in BP is1140* from a previous generation of this entry (ie was previously pruned) and we1141* have to act like the entry doesn't exist at all.1142*1143* This should only happen during a lookup to free the block (zio_ddt_free()).1144*1145* XXX this is similar in spirit to ddt_phys_select(), maybe can combine1146* -- robn, 2024-02-091147*/1148static boolean_t1149ddt_entry_lookup_is_valid(ddt_t *ddt, const blkptr_t *bp, ddt_entry_t *dde)1150{1151/* If the BP has no DVAs, then this entry is good */1152uint_t ndvas = BP_GET_NDVAS(bp);1153if (ndvas == 0)1154return (B_TRUE);11551156/*1157* Only checking the phys for the copies. For flat, there's only one;1158* for trad it'll be the one that has the matching set of DVAs.1159*/1160const dva_t *dvas = (ddt->ddt_flags & DDT_FLAG_FLAT) ?1161dde->dde_phys->ddp_flat.ddp_dva :1162dde->dde_phys->ddp_trad[ndvas].ddp_dva;11631164/*1165* Compare entry DVAs with the BP. They should all be there, but1166* there's not really anything we can do if its only partial anyway,1167* that's an error somewhere else, maybe long ago.1168*/1169uint_t d;1170for (d = 0; d < ndvas; d++)1171if (!DVA_EQUAL(&dvas[d], &bp->blk_dva[d]))1172return (B_FALSE);1173ASSERT3U(d, ==, ndvas);11741175return (B_TRUE);1176}11771178ddt_entry_t *1179ddt_lookup(ddt_t *ddt, const blkptr_t *bp, boolean_t verify)1180{1181spa_t *spa = ddt->ddt_spa;1182ddt_key_t search;1183ddt_entry_t *dde;1184ddt_type_t type;1185ddt_class_t class;1186avl_index_t where;1187int error;11881189ASSERT(MUTEX_HELD(&ddt->ddt_lock));11901191if (unlikely(ddt->ddt_version == DDT_VERSION_UNCONFIGURED)) {1192/*1193* This is the first use of this DDT since the pool was1194* created; finish getting it ready for use.1195*/1196VERIFY0(ddt_configure(ddt, B_TRUE));1197ASSERT3U(ddt->ddt_version, !=, DDT_VERSION_UNCONFIGURED);1198}11991200DDT_KSTAT_BUMP(ddt, dds_lookup);12011202ddt_key_fill(&search, bp);12031204/* Find an existing live entry */1205dde = avl_find(&ddt->ddt_tree, &search, &where);1206if (dde != NULL) {1207/* If we went over quota, act like we didn't find it */1208if (dde->dde_flags & DDE_FLAG_OVERQUOTA)1209return (NULL);12101211/* If it's already loaded, we can just return it. */1212DDT_KSTAT_BUMP(ddt, dds_lookup_live_hit);1213if (dde->dde_flags & DDE_FLAG_LOADED) {1214if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))1215return (dde);1216return (NULL);1217}12181219/* Someone else is loading it, wait for it. */1220dde->dde_waiters++;1221DDT_KSTAT_BUMP(ddt, dds_lookup_live_wait);1222while (!(dde->dde_flags & DDE_FLAG_LOADED))1223cv_wait(&dde->dde_cv, &ddt->ddt_lock);1224dde->dde_waiters--;12251226/* Loaded but over quota, forget we were ever here */1227if (dde->dde_flags & DDE_FLAG_OVERQUOTA) {1228if (dde->dde_waiters == 0) {1229avl_remove(&ddt->ddt_tree, dde);1230ddt_free(ddt, dde);1231}1232return (NULL);1233}12341235DDT_KSTAT_BUMP(ddt, dds_lookup_existing);12361237/* Make sure the loaded entry matches the BP */1238if (!verify || ddt_entry_lookup_is_valid(ddt, bp, dde))1239return (dde);1240return (NULL);1241} else1242DDT_KSTAT_BUMP(ddt, dds_lookup_live_miss);12431244/* Time to make a new entry. */1245dde = ddt_alloc(ddt, &search);1246avl_insert(&ddt->ddt_tree, dde, where);12471248/*1249* The entry in ddt_tree has no DDE_FLAG_LOADED, so other possible1250* threads will wait even while we drop the lock.1251*/1252ddt_exit(ddt);12531254/*1255* If there is a log, we should try to "load" from there first.1256*/1257if (ddt->ddt_flags & DDT_FLAG_LOG) {1258ddt_lightweight_entry_t ddlwe;1259boolean_t from_flushing;12601261/* Read-only search, no locks needed (logs stable during I/O) */1262if (ddt_log_find_key(ddt, &search, &ddlwe, &from_flushing)) {1263dde->dde_type = ddlwe.ddlwe_type;1264dde->dde_class = ddlwe.ddlwe_class;1265memcpy(dde->dde_phys, &ddlwe.ddlwe_phys,1266DDT_PHYS_SIZE(ddt));12671268/*1269* Check validity. If invalid and no waiters, clean up1270* immediately. Otherwise continue setup for waiters.1271*/1272boolean_t valid = !verify ||1273ddt_entry_lookup_is_valid(ddt, bp, dde);1274ddt_enter(ddt);1275if (!valid && dde->dde_waiters == 0) {1276avl_remove(&ddt->ddt_tree, dde);1277ddt_free(ddt, dde);1278return (NULL);1279}12801281dde->dde_flags = DDE_FLAG_LOADED | DDE_FLAG_LOGGED;1282if (from_flushing) {1283dde->dde_flags |= DDE_FLAG_FROM_FLUSHING;1284DDT_KSTAT_BUMP(ddt,1285dds_lookup_log_flushing_hit);1286} else {1287DDT_KSTAT_BUMP(ddt, dds_lookup_log_active_hit);1288}12891290DDT_KSTAT_BUMP(ddt, dds_lookup_log_hit);1291DDT_KSTAT_BUMP(ddt, dds_lookup_existing);12921293cv_broadcast(&dde->dde_cv);12941295return (valid ? dde : NULL);1296}12971298DDT_KSTAT_BUMP(ddt, dds_lookup_log_miss);1299}13001301/* Search all store objects for the entry. */1302error = ENOENT;1303for (type = 0; type < DDT_TYPES; type++) {1304for (class = 0; class < DDT_CLASSES; class++) {1305error = ddt_object_lookup(ddt, type, class, dde);1306if (error != ENOENT) {1307ASSERT0(error);1308break;1309}1310}1311if (error != ENOENT)1312break;1313}13141315ddt_enter(ddt);13161317ASSERT(!(dde->dde_flags & DDE_FLAG_LOADED));13181319dde->dde_type = type; /* will be DDT_TYPES if no entry found */1320dde->dde_class = class; /* will be DDT_CLASSES if no entry found */13211322boolean_t valid = B_TRUE;13231324if (dde->dde_type == DDT_TYPES &&1325dde->dde_class == DDT_CLASSES &&1326ddt_over_quota(spa)) {1327/* Over quota. If no one is waiting, clean up right now. */1328if (dde->dde_waiters == 0) {1329avl_remove(&ddt->ddt_tree, dde);1330ddt_free(ddt, dde);1331return (NULL);1332}13331334/* Flag cleanup required */1335dde->dde_flags |= DDE_FLAG_OVERQUOTA;1336} else if (error == 0) {1337/*1338* If what we loaded is no good for this BP and there's no one1339* waiting for it, we can just remove it and get out. If its no1340* good but there are waiters, we have to leave it, because we1341* don't know what they want. If its not needed we'll end up1342* taking an entry log/sync, but it can only happen if more1343* than one previous version of this block is being deleted at1344* the same time. This is extremely unlikely to happen and not1345* worth the effort to deal with without taking an entry1346* update.1347*/1348valid = !verify || ddt_entry_lookup_is_valid(ddt, bp, dde);1349if (!valid && dde->dde_waiters == 0) {1350avl_remove(&ddt->ddt_tree, dde);1351ddt_free(ddt, dde);1352return (NULL);1353}13541355DDT_KSTAT_BUMP(ddt, dds_lookup_stored_hit);1356DDT_KSTAT_BUMP(ddt, dds_lookup_existing);13571358/*1359* The histograms only track inactive (stored or logged) blocks.1360* We've just put an entry onto the live list, so we need to1361* remove its counts. When its synced back, it'll be re-added1362* to the right one.1363*1364* We only do this when we successfully found it in the store.1365* error == ENOENT means this is a new entry, and so its already1366* not counted.1367*/1368ddt_histogram_t *ddh =1369&ddt->ddt_histogram[dde->dde_type][dde->dde_class];13701371ddt_lightweight_entry_t ddlwe;1372DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);1373ddt_histogram_sub_entry(ddt, ddh, &ddlwe);1374} else {1375DDT_KSTAT_BUMP(ddt, dds_lookup_stored_miss);1376DDT_KSTAT_BUMP(ddt, dds_lookup_new);1377}13781379/* Entry loaded, everyone can proceed now */1380dde->dde_flags |= DDE_FLAG_LOADED;1381cv_broadcast(&dde->dde_cv);13821383if ((dde->dde_flags & DDE_FLAG_OVERQUOTA) || !valid)1384return (NULL);13851386return (dde);1387}13881389void1390ddt_prefetch(spa_t *spa, const blkptr_t *bp)1391{1392ddt_t *ddt;1393ddt_key_t ddk;13941395if (!zfs_dedup_prefetch || bp == NULL || !BP_GET_DEDUP(bp))1396return;13971398/*1399* We only remove the DDT once all tables are empty and only1400* prefetch dedup blocks when there are entries in the DDT.1401* Thus no locking is required as the DDT can't disappear on us.1402*/1403ddt = ddt_select(spa, bp);1404ddt_key_fill(&ddk, bp);14051406for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1407for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1408ddt_object_prefetch(ddt, type, class, &ddk);1409}1410}1411}14121413/*1414* ddt_key_t comparison. Any struct wanting to make use of this function must1415* have the key as the first element. Casts it to N uint64_ts, and checks until1416* we find there's a difference. This is intended to match how ddt_zap.c drives1417* the ZAPs (first uint64_t as the key prehash), which will minimise the number1418* of ZAP blocks touched when flushing logged entries from an AVL walk. This is1419* not an invariant for this function though, should you wish to change it.1420*/1421int1422ddt_key_compare(const void *x1, const void *x2)1423{1424const uint64_t *k1 = (const uint64_t *)x1;1425const uint64_t *k2 = (const uint64_t *)x2;14261427int cmp;1428for (int i = 0; i < (sizeof (ddt_key_t) / sizeof (uint64_t)); i++)1429if (likely((cmp = TREE_CMP(k1[i], k2[i])) != 0))1430return (cmp);14311432return (0);1433}14341435/* Create the containing dir for this DDT and bump the feature count */1436static void1437ddt_create_dir(ddt_t *ddt, dmu_tx_t *tx)1438{1439ASSERT0(ddt->ddt_dir_object);1440ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);14411442char name[DDT_NAMELEN];1443snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1444zio_checksum_table[ddt->ddt_checksum].ci_name);14451446ddt->ddt_dir_object = zap_create_link(ddt->ddt_os,1447DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT, name, tx);14481449VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_VERSION,1450sizeof (uint64_t), 1, &ddt->ddt_version, tx));1451VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS,1452sizeof (uint64_t), 1, &ddt->ddt_flags, tx));14531454spa_feature_incr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);1455}14561457/* Destroy the containing dir and deactivate the feature */1458static void1459ddt_destroy_dir(ddt_t *ddt, dmu_tx_t *tx)1460{1461ASSERT3U(ddt->ddt_dir_object, !=, 0);1462ASSERT3U(ddt->ddt_dir_object, !=, DMU_POOL_DIRECTORY_OBJECT);1463ASSERT3U(ddt->ddt_version, ==, DDT_VERSION_FDT);14641465char name[DDT_NAMELEN];1466snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1467zio_checksum_table[ddt->ddt_checksum].ci_name);14681469for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1470for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1471ASSERT(!ddt_object_exists(ddt, type, class));1472}1473}14741475ddt_log_destroy(ddt, tx);14761477uint64_t count;1478ASSERT0(zap_count(ddt->ddt_os, ddt->ddt_dir_object, &count));1479ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object,1480DDT_DIR_VERSION));1481ASSERT0(zap_contains(ddt->ddt_os, ddt->ddt_dir_object, DDT_DIR_FLAGS));1482ASSERT3U(count, ==, 2);14831484VERIFY0(zap_remove(ddt->ddt_os, DMU_POOL_DIRECTORY_OBJECT, name, tx));1485VERIFY0(zap_destroy(ddt->ddt_os, ddt->ddt_dir_object, tx));14861487ddt->ddt_dir_object = 0;14881489spa_feature_decr(ddt->ddt_spa, SPA_FEATURE_FAST_DEDUP, tx);1490}14911492/*1493* Determine, flags and on-disk layout from what's already stored. If there's1494* nothing stored, then if new is false, returns ENOENT, and if true, selects1495* based on pool config.1496*/1497static int1498ddt_configure(ddt_t *ddt, boolean_t new)1499{1500spa_t *spa = ddt->ddt_spa;1501char name[DDT_NAMELEN];1502int error;15031504ASSERT3U(spa_load_state(spa), !=, SPA_LOAD_CREATE);15051506boolean_t fdt_enabled =1507spa_feature_is_enabled(spa, SPA_FEATURE_FAST_DEDUP);1508boolean_t fdt_active =1509spa_feature_is_active(spa, SPA_FEATURE_FAST_DEDUP);15101511/*1512* First, look for the global DDT stats object. If its not there, then1513* there's never been a DDT written before ever, and we know we're1514* starting from scratch.1515*/1516error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,1517DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,1518&spa->spa_ddt_stat_object);1519if (error != 0) {1520if (error != ENOENT)1521return (error);1522goto not_found;1523}15241525if (fdt_active) {1526/*1527* Now look for a DDT directory. If it exists, then it has1528* everything we need.1529*/1530snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_DIR,1531zio_checksum_table[ddt->ddt_checksum].ci_name);15321533error = zap_lookup(spa->spa_meta_objset,1534DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t), 1,1535&ddt->ddt_dir_object);1536if (error == 0) {1537ASSERT3U(spa->spa_meta_objset, ==, ddt->ddt_os);15381539error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,1540DDT_DIR_VERSION, sizeof (uint64_t), 1,1541&ddt->ddt_version);1542if (error != 0)1543return (error);15441545error = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object,1546DDT_DIR_FLAGS, sizeof (uint64_t), 1,1547&ddt->ddt_flags);1548if (error != 0)1549return (error);15501551if (ddt->ddt_version != DDT_VERSION_FDT) {1552zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "1553"unknown version %llu", spa_name(spa),1554name, (u_longlong_t)ddt->ddt_version);1555return (SET_ERROR(EINVAL));1556}15571558if ((ddt->ddt_flags & ~DDT_FLAG_MASK) != 0) {1559zfs_dbgmsg("ddt_configure: spa=%s ddt_dir=%s "1560"version=%llu unknown flags %llx",1561spa_name(spa), name,1562(u_longlong_t)ddt->ddt_flags,1563(u_longlong_t)ddt->ddt_version);1564return (SET_ERROR(EINVAL));1565}15661567return (0);1568}1569if (error != ENOENT)1570return (error);1571}15721573/* Any object in the root indicates a traditional setup. */1574for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1575for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1576ddt_object_name(ddt, type, class, name);1577uint64_t obj;1578error = zap_lookup(spa->spa_meta_objset,1579DMU_POOL_DIRECTORY_OBJECT, name, sizeof (uint64_t),15801, &obj);1581if (error == ENOENT)1582continue;1583if (error != 0)1584return (error);15851586ddt->ddt_version = DDT_VERSION_LEGACY;1587ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1588ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;15891590return (0);1591}1592}15931594not_found:1595if (!new)1596return (SET_ERROR(ENOENT));15971598/* Nothing on disk, so set up for the best version we can */1599if (fdt_enabled) {1600ddt->ddt_version = DDT_VERSION_FDT;1601ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1602ddt->ddt_dir_object = 0; /* create on first use */1603} else {1604ddt->ddt_version = DDT_VERSION_LEGACY;1605ddt->ddt_flags = ddt_version_flags[ddt->ddt_version];1606ddt->ddt_dir_object = DMU_POOL_DIRECTORY_OBJECT;1607}16081609return (0);1610}16111612static int1613ddt_kstat_update(kstat_t *ksp, int rw)1614{1615ddt_t *ddt = ksp->ks_private;1616ddt_kstats_t *dds = ksp->ks_data;16171618if (rw == KSTAT_WRITE)1619return (SET_ERROR(EACCES));16201621/* Aggregate wmsum counters for lookup stats */1622dds->dds_lookup.value.ui64 =1623wmsum_value(&ddt->ddt_kstat_dds_lookup);1624dds->dds_lookup_live_hit.value.ui64 =1625wmsum_value(&ddt->ddt_kstat_dds_lookup_live_hit);1626dds->dds_lookup_live_wait.value.ui64 =1627wmsum_value(&ddt->ddt_kstat_dds_lookup_live_wait);1628dds->dds_lookup_live_miss.value.ui64 =1629wmsum_value(&ddt->ddt_kstat_dds_lookup_live_miss);1630dds->dds_lookup_existing.value.ui64 =1631wmsum_value(&ddt->ddt_kstat_dds_lookup_existing);1632dds->dds_lookup_new.value.ui64 =1633wmsum_value(&ddt->ddt_kstat_dds_lookup_new);1634dds->dds_lookup_log_hit.value.ui64 =1635wmsum_value(&ddt->ddt_kstat_dds_lookup_log_hit);1636dds->dds_lookup_log_active_hit.value.ui64 =1637wmsum_value(&ddt->ddt_kstat_dds_lookup_log_active_hit);1638dds->dds_lookup_log_flushing_hit.value.ui64 =1639wmsum_value(&ddt->ddt_kstat_dds_lookup_log_flushing_hit);1640dds->dds_lookup_log_miss.value.ui64 =1641wmsum_value(&ddt->ddt_kstat_dds_lookup_log_miss);1642dds->dds_lookup_stored_hit.value.ui64 =1643wmsum_value(&ddt->ddt_kstat_dds_lookup_stored_hit);1644dds->dds_lookup_stored_miss.value.ui64 =1645wmsum_value(&ddt->ddt_kstat_dds_lookup_stored_miss);16461647/* Sync-only counters are already set directly in kstats */16481649return (0);1650}16511652static void1653ddt_table_alloc_kstats(ddt_t *ddt)1654{1655char *mod = kmem_asprintf("zfs/%s", spa_name(ddt->ddt_spa));1656char *name = kmem_asprintf("ddt_stats_%s",1657zio_checksum_table[ddt->ddt_checksum].ci_name);16581659/* Initialize wmsums for lookup counters */1660wmsum_init(&ddt->ddt_kstat_dds_lookup, 0);1661wmsum_init(&ddt->ddt_kstat_dds_lookup_live_hit, 0);1662wmsum_init(&ddt->ddt_kstat_dds_lookup_live_wait, 0);1663wmsum_init(&ddt->ddt_kstat_dds_lookup_live_miss, 0);1664wmsum_init(&ddt->ddt_kstat_dds_lookup_existing, 0);1665wmsum_init(&ddt->ddt_kstat_dds_lookup_new, 0);1666wmsum_init(&ddt->ddt_kstat_dds_lookup_log_hit, 0);1667wmsum_init(&ddt->ddt_kstat_dds_lookup_log_active_hit, 0);1668wmsum_init(&ddt->ddt_kstat_dds_lookup_log_flushing_hit, 0);1669wmsum_init(&ddt->ddt_kstat_dds_lookup_log_miss, 0);1670wmsum_init(&ddt->ddt_kstat_dds_lookup_stored_hit, 0);1671wmsum_init(&ddt->ddt_kstat_dds_lookup_stored_miss, 0);16721673ddt->ddt_ksp = kstat_create(mod, 0, name, "misc", KSTAT_TYPE_NAMED,1674sizeof (ddt_kstats_t) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);1675if (ddt->ddt_ksp != NULL) {1676ddt_kstats_t *dds = kmem_alloc(sizeof (ddt_kstats_t), KM_SLEEP);1677memcpy(dds, &ddt_kstats_template, sizeof (ddt_kstats_t));1678ddt->ddt_ksp->ks_data = dds;1679ddt->ddt_ksp->ks_update = ddt_kstat_update;1680ddt->ddt_ksp->ks_private = ddt;1681kstat_install(ddt->ddt_ksp);1682}16831684kmem_strfree(name);1685kmem_strfree(mod);1686}16871688static ddt_t *1689ddt_table_alloc(spa_t *spa, enum zio_checksum c)1690{1691ddt_t *ddt;16921693ddt = kmem_cache_alloc(ddt_cache, KM_SLEEP);1694memset(ddt, 0, sizeof (ddt_t));1695mutex_init(&ddt->ddt_lock, NULL, MUTEX_DEFAULT, NULL);1696avl_create(&ddt->ddt_tree, ddt_key_compare,1697sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));1698avl_create(&ddt->ddt_repair_tree, ddt_key_compare,1699sizeof (ddt_entry_t), offsetof(ddt_entry_t, dde_node));17001701ddt->ddt_checksum = c;1702ddt->ddt_spa = spa;1703ddt->ddt_os = spa->spa_meta_objset;1704ddt->ddt_version = DDT_VERSION_UNCONFIGURED;1705ddt->ddt_log_flush_pressure = 10;17061707ddt_log_alloc(ddt);1708ddt_table_alloc_kstats(ddt);17091710return (ddt);1711}17121713static void1714ddt_table_free(ddt_t *ddt)1715{1716if (ddt->ddt_ksp != NULL) {1717kmem_free(ddt->ddt_ksp->ks_data, sizeof (ddt_kstats_t));1718ddt->ddt_ksp->ks_data = NULL;1719kstat_delete(ddt->ddt_ksp);1720}17211722/* Cleanup wmsums for lookup counters */1723wmsum_fini(&ddt->ddt_kstat_dds_lookup);1724wmsum_fini(&ddt->ddt_kstat_dds_lookup_live_hit);1725wmsum_fini(&ddt->ddt_kstat_dds_lookup_live_wait);1726wmsum_fini(&ddt->ddt_kstat_dds_lookup_live_miss);1727wmsum_fini(&ddt->ddt_kstat_dds_lookup_existing);1728wmsum_fini(&ddt->ddt_kstat_dds_lookup_new);1729wmsum_fini(&ddt->ddt_kstat_dds_lookup_log_hit);1730wmsum_fini(&ddt->ddt_kstat_dds_lookup_log_active_hit);1731wmsum_fini(&ddt->ddt_kstat_dds_lookup_log_flushing_hit);1732wmsum_fini(&ddt->ddt_kstat_dds_lookup_log_miss);1733wmsum_fini(&ddt->ddt_kstat_dds_lookup_stored_hit);1734wmsum_fini(&ddt->ddt_kstat_dds_lookup_stored_miss);17351736ddt_log_free(ddt);1737for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1738for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1739if (ddt->ddt_object_dnode[type][class] != NULL) {1740dnode_rele(ddt->ddt_object_dnode[type][class],1741ddt);1742ddt->ddt_object_dnode[type][class] = NULL;1743}1744}1745}1746ASSERT0(avl_numnodes(&ddt->ddt_tree));1747ASSERT0(avl_numnodes(&ddt->ddt_repair_tree));1748avl_destroy(&ddt->ddt_tree);1749avl_destroy(&ddt->ddt_repair_tree);1750mutex_destroy(&ddt->ddt_lock);1751kmem_cache_free(ddt_cache, ddt);1752}17531754void1755ddt_create(spa_t *spa)1756{1757spa->spa_dedup_checksum = ZIO_DEDUPCHECKSUM;17581759for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1760if (DDT_CHECKSUM_VALID(c))1761spa->spa_ddt[c] = ddt_table_alloc(spa, c);1762}1763}17641765int1766ddt_load(spa_t *spa)1767{1768int error;17691770ddt_create(spa);17711772error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,1773DMU_POOL_DDT_STATS, sizeof (uint64_t), 1,1774&spa->spa_ddt_stat_object);1775if (error)1776return (error == ENOENT ? 0 : error);17771778for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1779if (!DDT_CHECKSUM_VALID(c))1780continue;17811782ddt_t *ddt = spa->spa_ddt[c];1783error = ddt_configure(ddt, B_FALSE);1784if (error == ENOENT)1785continue;1786if (error != 0)1787return (error);17881789for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1790for (ddt_class_t class = 0; class < DDT_CLASSES;1791class++) {1792error = ddt_object_load(ddt, type, class);1793if (error != 0 && error != ENOENT)1794return (error);1795}1796}17971798if (ddt->ddt_flags & DDT_FLAG_LOG) {1799error = ddt_log_load(ddt);1800if (error != 0 && error != ENOENT)1801return (error);1802}18031804DDT_KSTAT_SET(ddt, dds_log_active_entries,1805avl_numnodes(&ddt->ddt_log_active->ddl_tree));1806DDT_KSTAT_SET(ddt, dds_log_flushing_entries,1807avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));18081809/*1810* Seed the cached histograms.1811*/1812memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,1813sizeof (ddt->ddt_histogram));1814}18151816spa->spa_dedup_dspace = ~0ULL;1817spa->spa_dedup_dsize = ~0ULL;18181819return (0);1820}18211822void1823ddt_unload(spa_t *spa)1824{1825for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {1826if (spa->spa_ddt[c]) {1827ddt_table_free(spa->spa_ddt[c]);1828spa->spa_ddt[c] = NULL;1829}1830}1831}18321833boolean_t1834ddt_class_contains(spa_t *spa, ddt_class_t max_class, const blkptr_t *bp)1835{1836ddt_t *ddt;1837ddt_key_t ddk;18381839if (!BP_GET_DEDUP(bp))1840return (B_FALSE);18411842if (max_class == DDT_CLASS_UNIQUE)1843return (B_TRUE);18441845ddt = spa->spa_ddt[BP_GET_CHECKSUM(bp)];18461847ddt_key_fill(&ddk, bp);18481849for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1850for (ddt_class_t class = 0; class <= max_class; class++) {1851if (ddt_object_contains(ddt, type, class, &ddk) == 0)1852return (B_TRUE);1853}1854}18551856return (B_FALSE);1857}18581859ddt_entry_t *1860ddt_repair_start(ddt_t *ddt, const blkptr_t *bp)1861{1862ddt_key_t ddk;1863ddt_entry_t *dde;18641865ddt_key_fill(&ddk, bp);18661867dde = ddt_alloc(ddt, &ddk);1868ddt_alloc_entry_io(dde);18691870for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1871for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1872/*1873* We can only do repair if there are multiple copies1874* of the block. For anything in the UNIQUE class,1875* there's definitely only one copy, so don't even try.1876*/1877if (class != DDT_CLASS_UNIQUE &&1878ddt_object_lookup(ddt, type, class, dde) == 0)1879return (dde);1880}1881}18821883memset(dde->dde_phys, 0, DDT_PHYS_SIZE(ddt));18841885return (dde);1886}18871888void1889ddt_repair_done(ddt_t *ddt, ddt_entry_t *dde)1890{1891avl_index_t where;18921893ddt_enter(ddt);18941895if (dde->dde_io->dde_repair_abd != NULL &&1896spa_writeable(ddt->ddt_spa) &&1897avl_find(&ddt->ddt_repair_tree, dde, &where) == NULL)1898avl_insert(&ddt->ddt_repair_tree, dde, where);1899else1900ddt_free(ddt, dde);19011902ddt_exit(ddt);1903}19041905static void1906ddt_repair_entry_done(zio_t *zio)1907{1908ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);1909ddt_entry_t *rdde = zio->io_private;19101911ddt_free(ddt, rdde);1912}19131914static void1915ddt_repair_entry(ddt_t *ddt, ddt_entry_t *dde, ddt_entry_t *rdde, zio_t *rio)1916{1917ddt_key_t *ddk = &dde->dde_key;1918ddt_key_t *rddk = &rdde->dde_key;1919zio_t *zio;1920blkptr_t blk;19211922zio = zio_null(rio, rio->io_spa, NULL,1923ddt_repair_entry_done, rdde, rio->io_flags);19241925for (int p = 0; p < DDT_NPHYS(ddt); p++) {1926ddt_univ_phys_t *ddp = dde->dde_phys;1927ddt_univ_phys_t *rddp = rdde->dde_phys;1928ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);1929uint64_t phys_birth = ddt_phys_birth(ddp, v);1930const dva_t *dvas, *rdvas;19311932if (ddt->ddt_flags & DDT_FLAG_FLAT) {1933dvas = ddp->ddp_flat.ddp_dva;1934rdvas = rddp->ddp_flat.ddp_dva;1935} else {1936dvas = ddp->ddp_trad[p].ddp_dva;1937rdvas = rddp->ddp_trad[p].ddp_dva;1938}19391940if (phys_birth == 0 ||1941phys_birth != ddt_phys_birth(rddp, v) ||1942memcmp(dvas, rdvas, sizeof (dva_t) * SPA_DVAS_PER_BP))1943continue;19441945ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);1946zio_nowait(zio_rewrite(zio, zio->io_spa, 0, &blk,1947rdde->dde_io->dde_repair_abd, DDK_GET_PSIZE(rddk),1948NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,1949ZIO_DDT_CHILD_FLAGS(zio), NULL));1950}19511952zio_nowait(zio);1953}19541955static void1956ddt_repair_table(ddt_t *ddt, zio_t *rio)1957{1958spa_t *spa = ddt->ddt_spa;1959ddt_entry_t *dde, *rdde_next, *rdde;1960avl_tree_t *t = &ddt->ddt_repair_tree;1961blkptr_t blk;19621963if (spa_sync_pass(spa) > 1)1964return;19651966ddt_enter(ddt);1967for (rdde = avl_first(t); rdde != NULL; rdde = rdde_next) {1968rdde_next = AVL_NEXT(t, rdde);1969avl_remove(&ddt->ddt_repair_tree, rdde);1970ddt_exit(ddt);1971ddt_bp_create(ddt->ddt_checksum, &rdde->dde_key, NULL,1972DDT_PHYS_NONE, &blk);1973dde = ddt_repair_start(ddt, &blk);1974ddt_repair_entry(ddt, dde, rdde, rio);1975ddt_repair_done(ddt, dde);1976ddt_enter(ddt);1977}1978ddt_exit(ddt);1979}19801981static void1982ddt_sync_update_stats(ddt_t *ddt, dmu_tx_t *tx)1983{1984/*1985* Count all the entries stored for each type/class, and updates the1986* stats within (ddt_object_sync()). If there's no entries for the1987* type/class, the whole object is removed. If all objects for the DDT1988* are removed, its containing dir is removed, effectively resetting1989* the entire DDT to an empty slate.1990*/1991uint64_t count = 0;1992for (ddt_type_t type = 0; type < DDT_TYPES; type++) {1993uint64_t add, tcount = 0;1994for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {1995if (ddt_object_exists(ddt, type, class)) {1996ddt_object_sync(ddt, type, class, tx);1997VERIFY0(ddt_object_count(ddt, type, class,1998&add));1999tcount += add;2000}2001}2002for (ddt_class_t class = 0; class < DDT_CLASSES; class++) {2003if (tcount == 0 && ddt_object_exists(ddt, type, class))2004ddt_object_destroy(ddt, type, class, tx);2005}2006count += tcount;2007}20082009if (ddt->ddt_flags & DDT_FLAG_LOG) {2010/* Include logged entries in the total count */2011count += avl_numnodes(&ddt->ddt_log_active->ddl_tree);2012count += avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);2013}20142015if (count == 0) {2016/*2017* No entries left on the DDT, so reset the version for next2018* time. This allows us to handle the feature being changed2019* since the DDT was originally created. New entries should get2020* whatever the feature currently demands.2021*/2022if (ddt->ddt_version == DDT_VERSION_FDT)2023ddt_destroy_dir(ddt, tx);20242025ddt->ddt_version = DDT_VERSION_UNCONFIGURED;2026ddt->ddt_flags = 0;2027}20282029memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,2030sizeof (ddt->ddt_histogram));2031ddt->ddt_spa->spa_dedup_dspace = ~0ULL;2032ddt->ddt_spa->spa_dedup_dsize = ~0ULL;2033}20342035static void2036ddt_sync_scan_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)2037{2038dsl_pool_t *dp = ddt->ddt_spa->spa_dsl_pool;20392040/*2041* Compute the target class, so we can decide whether or not to inform2042* the scrub traversal (below). Note that we don't store this in the2043* entry, as it might change multiple times before finally being2044* committed (if we're logging). Instead, we recompute it in2045* ddt_sync_entry().2046*/2047uint64_t refcnt = ddt_phys_total_refcnt(ddt, &ddlwe->ddlwe_phys);2048ddt_class_t nclass =2049(refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;20502051/*2052* If the class changes, the order that we scan this bp changes. If it2053* decreases, we could miss it, so scan it right now. (This covers both2054* class changing while we are doing ddt_walk(), and when we are2055* traversing.)2056*2057* We also do this when the refcnt goes to zero, because that change is2058* only in the log so far; the blocks on disk won't be freed until2059* the log is flushed, and the refcnt might increase before that. If it2060* does, then we could miss it in the same way.2061*/2062if (refcnt == 0 || nclass < ddlwe->ddlwe_class)2063dsl_scan_ddt_entry(dp->dp_scan, ddt->ddt_checksum, ddt,2064ddlwe, tx);2065}20662067static void2068ddt_sync_flush_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe,2069ddt_type_t otype, ddt_class_t oclass, dmu_tx_t *tx)2070{2071ddt_key_t *ddk = &ddlwe->ddlwe_key;2072ddt_type_t ntype = DDT_TYPE_DEFAULT;2073uint64_t refcnt = 0;20742075/*2076* Compute the total refcnt. Along the way, issue frees for any DVAs2077* we no longer want.2078*/2079for (int p = 0; p < DDT_NPHYS(ddt); p++) {2080ddt_univ_phys_t *ddp = &ddlwe->ddlwe_phys;2081ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);2082uint64_t phys_refcnt = ddt_phys_refcnt(ddp, v);20832084if (ddt_phys_birth(ddp, v) == 0) {2085ASSERT0(phys_refcnt);2086continue;2087}2088if (DDT_PHYS_IS_DITTO(ddt, p)) {2089/*2090* We don't want to keep any obsolete slots (eg ditto),2091* regardless of their refcount, but we don't want to2092* leak them either. So, free them.2093*/2094ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);2095continue;2096}2097if (phys_refcnt == 0)2098/* No remaining references, free it! */2099ddt_phys_free(ddt, ddk, ddp, v, tx->tx_txg);2100refcnt += phys_refcnt;2101}21022103/* Select the best class for the entry. */2104ddt_class_t nclass =2105(refcnt > 1) ? DDT_CLASS_DUPLICATE : DDT_CLASS_UNIQUE;21062107/*2108* If an existing entry changed type or class, or its refcount reached2109* zero, delete it from the DDT object2110*/2111if (otype != DDT_TYPES &&2112(otype != ntype || oclass != nclass || refcnt == 0)) {2113VERIFY0(ddt_object_remove(ddt, otype, oclass, ddk, tx));2114ASSERT(ddt_object_contains(ddt, otype, oclass, ddk) == ENOENT);2115}21162117/*2118* Add or update the entry2119*/2120if (refcnt != 0) {2121ddt_histogram_t *ddh =2122&ddt->ddt_histogram[ntype][nclass];21232124ddt_histogram_add_entry(ddt, ddh, ddlwe);21252126if (!ddt_object_exists(ddt, ntype, nclass))2127ddt_object_create(ddt, ntype, nclass, tx);2128VERIFY0(ddt_object_update(ddt, ntype, nclass, ddlwe, tx));2129}2130}21312132/* Calculate an exponential weighted moving average, lower limited to zero */2133static inline int32_t2134_ewma(int32_t val, int32_t prev, uint32_t weight)2135{2136ASSERT3U(val, >=, 0);2137ASSERT3U(prev, >=, 0);2138const int32_t new =2139MAX(0, prev + (val-prev) / (int32_t)MAX(weight, 1));2140ASSERT3U(new, >=, 0);2141return (new);2142}21432144static inline void2145ddt_flush_force_update_txg(ddt_t *ddt, uint64_t txg)2146{2147/*2148* If we're not forcing flush, and not being asked to start, then2149* there's nothing more to do.2150*/2151if (txg == 0) {2152/* Update requested, are we currently forcing flush? */2153if (ddt->ddt_flush_force_txg == 0)2154return;2155txg = ddt->ddt_flush_force_txg;2156}21572158/*2159* If either of the logs have entries unflushed entries before2160* the wanted txg, set the force txg, otherwise clear it.2161*/21622163if ((!avl_is_empty(&ddt->ddt_log_active->ddl_tree) &&2164ddt->ddt_log_active->ddl_first_txg <= txg) ||2165(!avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&2166ddt->ddt_log_flushing->ddl_first_txg <= txg)) {2167ddt->ddt_flush_force_txg = txg;2168return;2169}21702171/*2172* Nothing to flush behind the given txg, so we can clear force flush2173* state.2174*/2175ddt->ddt_flush_force_txg = 0;2176}21772178static void2179ddt_sync_flush_log(ddt_t *ddt, dmu_tx_t *tx)2180{2181spa_t *spa = ddt->ddt_spa;2182ASSERT(avl_is_empty(&ddt->ddt_tree));21832184/*2185* Don't do any flushing when the pool is ready to shut down, or in2186* passes beyond the first.2187*/2188if (spa_sync_pass(spa) > 1 || tx->tx_txg > spa_final_dirty_txg(spa))2189return;21902191hrtime_t flush_start = gethrtime();2192uint32_t count = 0;21932194/*2195* How many entries we need to flush. We need to at2196* least match the ingest rate, and also consider the2197* current backlog of entries.2198*/2199uint64_t backlog = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) +2200avl_numnodes(&ddt->ddt_log_active->ddl_tree);22012202if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree))2203goto housekeeping;22042205uint64_t txgs = MAX(1, zfs_dedup_log_flush_txgs);2206uint64_t cap = MAX(1, zfs_dedup_log_cap);2207uint64_t flush_min = MAX(backlog / txgs,2208zfs_dedup_log_flush_entries_min);22092210/*2211* The theory for this block is that if we increase the pressure while2212* we're growing above the cap, and remove it when we're significantly2213* below the cap, we'll stay near cap while not bouncing around too2214* much.2215*2216* The factor of 10 is to smooth the pressure effect by expressing it2217* in tenths. The addition of the cap to the backlog in the second2218* block is to round up, instead of down. We never let the pressure go2219* below 1 (10 tenths).2220*/2221if (cap != UINT_MAX && backlog > cap &&2222backlog > ddt->ddt_log_flush_prev_backlog) {2223ddt->ddt_log_flush_pressure += 10 * backlog / cap;2224} else if (cap != UINT_MAX && backlog < cap) {2225ddt->ddt_log_flush_pressure -=222611 - (((10 * backlog) + cap - 1) / cap);2227ddt->ddt_log_flush_pressure =2228MAX(ddt->ddt_log_flush_pressure, 10);2229}22302231if (zfs_dedup_log_hard_cap && cap != UINT_MAX)2232flush_min = MAX(flush_min, MIN(backlog - cap,2233(flush_min * ddt->ddt_log_flush_pressure) / 10));22342235uint64_t flush_max;22362237/*2238* If we've been asked to flush everything in a hurry,2239* try to dump as much as possible on this txg. In2240* this case we're only limited by time, not amount.2241*2242* Otherwise, if we are over the cap, try to get back down to it.2243*2244* Finally if there is no cap (or no pressure), just set the max a2245* little higher than the min to help smooth out variations in flush2246* times.2247*/2248if (ddt->ddt_flush_force_txg > 0)2249flush_max = avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);2250else if (cap != UINT32_MAX && !zfs_dedup_log_hard_cap)2251flush_max = MAX(flush_min * 5 / 4, MIN(backlog - cap,2252(flush_min * ddt->ddt_log_flush_pressure) / 10));2253else2254flush_max = flush_min * 5 / 4;2255flush_max = MIN(flush_max, zfs_dedup_log_flush_entries_max);22562257/*2258* When the pool is busy or someone is explicitly waiting for this txg2259* to complete, use the zfs_dedup_log_flush_min_time_ms. Otherwise use2260* half of the time in the txg timeout.2261*/2262uint64_t target_time;22632264if (txg_sync_waiting(ddt->ddt_spa->spa_dsl_pool) ||2265vdev_queue_pool_busy(spa)) {2266target_time = MIN(MSEC2NSEC(zfs_dedup_log_flush_min_time_ms),2267SEC2NSEC(zfs_txg_timeout) / 2);2268} else {2269target_time = SEC2NSEC(zfs_txg_timeout) / 2;2270}22712272ddt_lightweight_entry_t ddlwe;2273while (ddt_log_take_first(ddt, ddt->ddt_log_flushing, &ddlwe)) {2274ddt_sync_flush_entry(ddt, &ddlwe,2275ddlwe.ddlwe_type, ddlwe.ddlwe_class, tx);22762277/* End if we've synced as much as we needed to. */2278if (++count >= flush_max)2279break;22802281/*2282* As long as we've flushed the absolute minimum,2283* stop if we're way over our target time.2284*/2285uint64_t diff = gethrtime() - flush_start;2286if (count > zfs_dedup_log_flush_entries_min &&2287diff >= target_time * 2)2288break;22892290/*2291* End if we've passed the minimum flush and we're out of time.2292*/2293if (count > flush_min && diff >= target_time)2294break;2295}22962297if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree)) {2298/* We emptied it, so truncate on-disk */2299DDT_KSTAT_ZERO(ddt, dds_log_flushing_entries);2300ddt_log_truncate(ddt, tx);2301} else {2302/* More to do next time, save checkpoint */2303DDT_KSTAT_SUB(ddt, dds_log_flushing_entries, count);2304ddt_log_checkpoint(ddt, &ddlwe, tx);2305}23062307ddt_sync_update_stats(ddt, tx);23082309housekeeping:2310if (avl_is_empty(&ddt->ddt_log_flushing->ddl_tree) &&2311!avl_is_empty(&ddt->ddt_log_active->ddl_tree)) {2312/*2313* No more to flush, and the active list has stuff, so2314* try to swap the logs for next time.2315*/2316if (ddt_log_swap(ddt, tx)) {2317DDT_KSTAT_ZERO(ddt, dds_log_active_entries);2318DDT_KSTAT_SET(ddt, dds_log_flushing_entries,2319avl_numnodes(&ddt->ddt_log_flushing->ddl_tree));2320}2321}23222323/* If force flush is no longer necessary, turn it off. */2324ddt_flush_force_update_txg(ddt, 0);23252326ddt->ddt_log_flush_prev_backlog = backlog;23272328/*2329* Update flush rate. This is an exponential weighted moving2330* average of the number of entries flushed over recent txgs.2331*/2332ddt->ddt_log_flush_rate = _ewma(count, ddt->ddt_log_flush_rate,2333zfs_dedup_log_flush_flow_rate_txgs);2334DDT_KSTAT_SET(ddt, dds_log_flush_rate, ddt->ddt_log_flush_rate);23352336/*2337* Update flush time rate. This is an exponential weighted moving2338* average of the total time taken to flush over recent txgs.2339*/2340ddt->ddt_log_flush_time_rate = _ewma(ddt->ddt_log_flush_time_rate,2341(int32_t)NSEC2MSEC(gethrtime() - flush_start),2342zfs_dedup_log_flush_flow_rate_txgs);2343DDT_KSTAT_SET(ddt, dds_log_flush_time_rate,2344ddt->ddt_log_flush_time_rate);2345if (avl_numnodes(&ddt->ddt_log_flushing->ddl_tree) > 0 &&2346zfs_flags & ZFS_DEBUG_DDT) {2347zfs_dbgmsg("%lu entries remain(%lu in active), flushed %u @ "2348"txg %llu, in %llu ms, flush rate %d, time rate %d",2349(ulong_t)avl_numnodes(&ddt->ddt_log_flushing->ddl_tree),2350(ulong_t)avl_numnodes(&ddt->ddt_log_active->ddl_tree),2351count, (u_longlong_t)tx->tx_txg,2352(u_longlong_t)NSEC2MSEC(gethrtime() - flush_start),2353ddt->ddt_log_flush_rate, ddt->ddt_log_flush_time_rate);2354}2355}23562357static void2358ddt_sync_table_log(ddt_t *ddt, dmu_tx_t *tx)2359{2360uint64_t count = avl_numnodes(&ddt->ddt_tree);23612362if (count > 0) {2363ddt_log_update_t dlu = {0};2364ddt_log_begin(ddt, count, tx, &dlu);23652366ddt_entry_t *dde;2367void *cookie = NULL;2368ddt_lightweight_entry_t ddlwe;2369while ((dde =2370avl_destroy_nodes(&ddt->ddt_tree, &cookie)) != NULL) {2371ASSERT(dde->dde_flags & DDE_FLAG_LOADED);2372DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);23732374/* If from flushing log, remove it. */2375if (dde->dde_flags & DDE_FLAG_FROM_FLUSHING) {2376VERIFY(ddt_log_remove_key(ddt,2377ddt->ddt_log_flushing, &ddlwe.ddlwe_key));2378}23792380/* Update class_start to track last modification time */2381if (ddt->ddt_flags & DDT_FLAG_FLAT) {2382ddlwe.ddlwe_phys.ddp_flat.ddp_class_start =2383ddt_class_start();2384}23852386ddt_log_entry(ddt, &ddlwe, &dlu);2387ddt_sync_scan_entry(ddt, &ddlwe, tx);2388ddt_free(ddt, dde);2389}23902391ddt_log_commit(ddt, &dlu);23922393DDT_KSTAT_SET(ddt, dds_log_active_entries,2394avl_numnodes(&ddt->ddt_log_active->ddl_tree));23952396/*2397* Sync the stats for the store objects. Even though we haven't2398* modified anything on those objects, they're no longer the2399* source of truth for entries that are now in the log, and we2400* need the on-disk counts to reflect that, otherwise we'll2401* miscount later when importing.2402*/2403for (ddt_type_t type = 0; type < DDT_TYPES; type++) {2404for (ddt_class_t class = 0;2405class < DDT_CLASSES; class++) {2406if (ddt_object_exists(ddt, type, class))2407ddt_object_sync(ddt, type, class, tx);2408}2409}24102411memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,2412sizeof (ddt->ddt_histogram));2413ddt->ddt_spa->spa_dedup_dspace = ~0ULL;2414ddt->ddt_spa->spa_dedup_dsize = ~0ULL;2415}24162417if (spa_sync_pass(ddt->ddt_spa) == 1) {2418/*2419* Update ingest rate. This is an exponential weighted moving2420* average of the number of entries changed over recent txgs.2421* The ramp-up cost shouldn't matter too much because the2422* flusher will be trying to take at least the minimum anyway.2423*/2424ddt->ddt_log_ingest_rate = _ewma(2425count, ddt->ddt_log_ingest_rate,2426zfs_dedup_log_flush_flow_rate_txgs);2427DDT_KSTAT_SET(ddt, dds_log_ingest_rate,2428ddt->ddt_log_ingest_rate);2429}2430}24312432static void2433ddt_sync_table_flush(ddt_t *ddt, dmu_tx_t *tx)2434{2435if (avl_numnodes(&ddt->ddt_tree) == 0)2436return;24372438ddt_entry_t *dde;2439void *cookie = NULL;2440while ((dde = avl_destroy_nodes(2441&ddt->ddt_tree, &cookie)) != NULL) {2442ASSERT(dde->dde_flags & DDE_FLAG_LOADED);24432444ddt_lightweight_entry_t ddlwe;2445DDT_ENTRY_TO_LIGHTWEIGHT(ddt, dde, &ddlwe);24462447/* Update class_start to track last modification time */2448if (ddt->ddt_flags & DDT_FLAG_FLAT) {2449ddlwe.ddlwe_phys.ddp_flat.ddp_class_start =2450ddt_class_start();2451}24522453ddt_sync_flush_entry(ddt, &ddlwe,2454dde->dde_type, dde->dde_class, tx);2455ddt_sync_scan_entry(ddt, &ddlwe, tx);2456ddt_free(ddt, dde);2457}24582459memcpy(&ddt->ddt_histogram_cache, ddt->ddt_histogram,2460sizeof (ddt->ddt_histogram));2461ddt->ddt_spa->spa_dedup_dspace = ~0ULL;2462ddt->ddt_spa->spa_dedup_dsize = ~0ULL;2463ddt_sync_update_stats(ddt, tx);2464}24652466static void2467ddt_sync_table(ddt_t *ddt, dmu_tx_t *tx)2468{2469spa_t *spa = ddt->ddt_spa;24702471if (ddt->ddt_version == UINT64_MAX)2472return;24732474if (spa->spa_uberblock.ub_version < SPA_VERSION_DEDUP) {2475ASSERT0(avl_numnodes(&ddt->ddt_tree));2476return;2477}24782479if (spa->spa_ddt_stat_object == 0) {2480spa->spa_ddt_stat_object = zap_create_link(ddt->ddt_os,2481DMU_OT_DDT_STATS, DMU_POOL_DIRECTORY_OBJECT,2482DMU_POOL_DDT_STATS, tx);2483}24842485if (ddt->ddt_version == DDT_VERSION_FDT && ddt->ddt_dir_object == 0)2486ddt_create_dir(ddt, tx);24872488if (ddt->ddt_flags & DDT_FLAG_LOG)2489ddt_sync_table_log(ddt, tx);2490else2491ddt_sync_table_flush(ddt, tx);2492}24932494void2495ddt_sync(spa_t *spa, uint64_t txg)2496{2497dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;2498dmu_tx_t *tx;2499zio_t *rio;25002501ASSERT3U(spa_syncing_txg(spa), ==, txg);25022503tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);25042505rio = zio_root(spa, NULL, NULL,2506ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SELF_HEAL);25072508/*2509* This function may cause an immediate scan of ddt blocks (see2510* the comment above dsl_scan_ddt() for details). We set the2511* scan's root zio here so that we can wait for any scan IOs in2512* addition to the regular ddt IOs.2513*/2514ASSERT0P(scn->scn_zio_root);2515scn->scn_zio_root = rio;25162517for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2518ddt_t *ddt = spa->spa_ddt[c];2519if (ddt == NULL)2520continue;2521ddt_sync_table(ddt, tx);2522if (ddt->ddt_flags & DDT_FLAG_LOG)2523ddt_sync_flush_log(ddt, tx);2524ddt_repair_table(ddt, rio);2525}25262527(void) zio_wait(rio);2528scn->scn_zio_root = NULL;25292530dmu_tx_commit(tx);2531}25322533void2534ddt_walk_init(spa_t *spa, uint64_t txg)2535{2536if (txg == 0)2537txg = spa_syncing_txg(spa);25382539for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2540ddt_t *ddt = spa->spa_ddt[c];2541if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))2542continue;25432544ddt_enter(ddt);2545ddt_flush_force_update_txg(ddt, txg);2546ddt_exit(ddt);2547}2548}25492550boolean_t2551ddt_walk_ready(spa_t *spa)2552{2553for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {2554ddt_t *ddt = spa->spa_ddt[c];2555if (ddt == NULL || !(ddt->ddt_flags & DDT_FLAG_LOG))2556continue;25572558if (ddt->ddt_flush_force_txg > 0)2559return (B_FALSE);2560}25612562return (B_TRUE);2563}25642565static int2566ddt_walk_impl(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe,2567uint64_t flags, boolean_t wait)2568{2569do {2570do {2571do {2572ddt_t *ddt = spa->spa_ddt[ddb->ddb_checksum];2573if (ddt == NULL)2574continue;25752576if (flags != 0 &&2577(ddt->ddt_flags & flags) != flags)2578continue;25792580if (wait && ddt->ddt_flush_force_txg > 0)2581return (EAGAIN);25822583int error = ENOENT;2584if (ddt_object_exists(ddt, ddb->ddb_type,2585ddb->ddb_class)) {2586error = ddt_object_walk(ddt,2587ddb->ddb_type, ddb->ddb_class,2588&ddb->ddb_cursor, ddlwe);2589}2590if (error == 0)2591return (0);2592if (error != ENOENT)2593return (error);2594ddb->ddb_cursor = 0;2595} while (++ddb->ddb_checksum < ZIO_CHECKSUM_FUNCTIONS);2596ddb->ddb_checksum = 0;2597} while (++ddb->ddb_type < DDT_TYPES);2598ddb->ddb_type = 0;2599} while (++ddb->ddb_class < DDT_CLASSES);26002601return (SET_ERROR(ENOENT));2602}26032604int2605ddt_walk(spa_t *spa, ddt_bookmark_t *ddb, ddt_lightweight_entry_t *ddlwe)2606{2607return (ddt_walk_impl(spa, ddb, ddlwe, 0, B_TRUE));2608}26092610/*2611* This function is used by Block Cloning (brt.c) to increase reference2612* counter for the DDT entry if the block is already in DDT.2613*2614* Return false if the block, despite having the D bit set, is not present2615* in the DDT. This is possible when the DDT has been pruned by an admin2616* or by the DDT quota mechanism.2617*/2618boolean_t2619ddt_addref(spa_t *spa, const blkptr_t *bp)2620{2621ddt_t *ddt;2622ddt_entry_t *dde;2623boolean_t result;26242625spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);2626ddt = ddt_select(spa, bp);2627ddt_enter(ddt);26282629dde = ddt_lookup(ddt, bp, B_TRUE);26302631/* Can be NULL if the entry for this block was pruned. */2632if (dde == NULL) {2633ddt_exit(ddt);2634spa_config_exit(spa, SCL_ZIO, FTAG);2635return (B_FALSE);2636}26372638if ((dde->dde_type < DDT_TYPES) || (dde->dde_flags & DDE_FLAG_LOGGED)) {2639/*2640* This entry was either synced to a store object (dde_type is2641* real) or was logged. It must be properly on disk at this2642* point, so we can just bump its refcount.2643*/2644int p = DDT_PHYS_FOR_COPIES(ddt, BP_GET_NDVAS(bp));2645ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);26462647ddt_phys_addref(dde->dde_phys, v);2648result = B_TRUE;2649} else {2650/*2651* If the block has the DEDUP flag set it still might not2652* exist in the DEDUP table due to DDT pruning of entries2653* where refcnt=1.2654*/2655ddt_remove(ddt, dde);2656result = B_FALSE;2657}26582659ddt_exit(ddt);2660spa_config_exit(spa, SCL_ZIO, FTAG);26612662return (result);2663}26642665typedef struct ddt_prune_entry {2666ddt_t *dpe_ddt;2667ddt_key_t dpe_key;2668list_node_t dpe_node;2669ddt_univ_phys_t dpe_phys[];2670} ddt_prune_entry_t;26712672typedef struct ddt_prune_info {2673spa_t *dpi_spa;2674uint64_t dpi_txg_syncs;2675uint64_t dpi_pruned;2676list_t dpi_candidates;2677} ddt_prune_info_t;26782679/*2680* Add prune candidates for ddt_sync during spa_sync2681*/2682static void2683prune_candidates_sync(void *arg, dmu_tx_t *tx)2684{2685(void) tx;2686ddt_prune_info_t *dpi = arg;2687ddt_prune_entry_t *dpe;26882689spa_config_enter(dpi->dpi_spa, SCL_ZIO, FTAG, RW_READER);26902691/* Process the prune candidates collected so far */2692while ((dpe = list_remove_head(&dpi->dpi_candidates)) != NULL) {2693blkptr_t blk;2694ddt_t *ddt = dpe->dpe_ddt;26952696ddt_enter(ddt);26972698/*2699* If it's on the live list, then it was loaded for update2700* this txg and is no longer stale; skip it.2701*/2702if (avl_find(&ddt->ddt_tree, &dpe->dpe_key, NULL)) {2703ddt_exit(ddt);2704kmem_free(dpe, sizeof (*dpe));2705continue;2706}27072708ddt_bp_create(ddt->ddt_checksum, &dpe->dpe_key,2709dpe->dpe_phys, DDT_PHYS_FLAT, &blk);27102711ddt_entry_t *dde = ddt_lookup(ddt, &blk, B_TRUE);2712if (dde != NULL && !(dde->dde_flags & DDE_FLAG_LOGGED)) {2713ASSERT(dde->dde_flags & DDE_FLAG_LOADED);2714/*2715* Zero the physical, so we don't try to free DVAs2716* at flush nor try to reuse this entry.2717*/2718ddt_phys_clear(dde->dde_phys, DDT_PHYS_FLAT);27192720dpi->dpi_pruned++;2721}27222723ddt_exit(ddt);2724kmem_free(dpe, sizeof (*dpe));2725}27262727spa_config_exit(dpi->dpi_spa, SCL_ZIO, FTAG);2728dpi->dpi_txg_syncs++;2729}27302731/*2732* Prune candidates are collected in open context and processed2733* in sync context as part of ddt_sync_table().2734*/2735static void2736ddt_prune_entry(list_t *list, ddt_t *ddt, const ddt_key_t *ddk,2737const ddt_univ_phys_t *ddp)2738{2739ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);27402741size_t dpe_size = sizeof (ddt_prune_entry_t) + DDT_FLAT_PHYS_SIZE;2742ddt_prune_entry_t *dpe = kmem_alloc(dpe_size, KM_SLEEP);27432744dpe->dpe_ddt = ddt;2745dpe->dpe_key = *ddk;2746memcpy(dpe->dpe_phys, ddp, DDT_FLAT_PHYS_SIZE);2747list_insert_head(list, dpe);2748}27492750/*2751* Interate over all the entries in the DDT unique class.2752* The walk will perform one of the following operations:2753* (a) build a histogram than can be used when pruning2754* (b) prune entries older than the cutoff2755*2756* Also called by zdb(8) to dump the age histogram2757*/2758void2759ddt_prune_walk(spa_t *spa, uint64_t cutoff, ddt_age_histo_t *histogram)2760{2761ddt_bookmark_t ddb = {2762.ddb_class = DDT_CLASS_UNIQUE,2763.ddb_type = 0,2764.ddb_checksum = 0,2765.ddb_cursor = 02766};2767ddt_lightweight_entry_t ddlwe = {0};2768int error;2769int valid = 0;2770int candidates = 0;2771uint64_t now = gethrestime_sec();2772ddt_prune_info_t dpi;2773boolean_t pruning = (cutoff != 0);27742775if (pruning) {2776dpi.dpi_txg_syncs = 0;2777dpi.dpi_pruned = 0;2778dpi.dpi_spa = spa;2779list_create(&dpi.dpi_candidates, sizeof (ddt_prune_entry_t),2780offsetof(ddt_prune_entry_t, dpe_node));2781}27822783if (histogram != NULL)2784memset(histogram, 0, sizeof (ddt_age_histo_t));27852786while ((error =2787ddt_walk_impl(spa, &ddb, &ddlwe, DDT_FLAG_FLAT, B_FALSE)) == 0) {2788ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];2789VERIFY(ddt);27902791if (spa_shutting_down(spa) || issig())2792break;27932794ASSERT(ddt->ddt_flags & DDT_FLAG_FLAT);2795ASSERT3U(ddlwe.ddlwe_phys.ddp_flat.ddp_refcnt, <=, 1);27962797uint64_t class_start =2798ddlwe.ddlwe_phys.ddp_flat.ddp_class_start;27992800/*2801* If this entry is on the log, then the stored entry is stale2802* and we should skip it.2803*/2804if (ddt_log_find_key(ddt, &ddlwe.ddlwe_key, NULL, NULL))2805continue;28062807/* prune older entries */2808if (pruning && class_start < cutoff) {2809if (candidates++ >= zfs_ddt_prunes_per_txg) {2810/* sync prune candidates in batches */2811VERIFY0(dsl_sync_task(spa_name(spa),2812NULL, prune_candidates_sync,2813&dpi, 0, ZFS_SPACE_CHECK_NONE));2814candidates = 1;2815}2816ddt_prune_entry(&dpi.dpi_candidates, ddt,2817&ddlwe.ddlwe_key, &ddlwe.ddlwe_phys);2818}28192820/* build a histogram */2821if (histogram != NULL) {2822uint64_t age = MAX(1, (now - class_start) / 3600);2823int bin = MIN(highbit64(age) - 1, HIST_BINS - 1);2824histogram->dah_entries++;2825histogram->dah_age_histo[bin]++;2826}28272828valid++;2829}28302831if (pruning && valid > 0) {2832if (!list_is_empty(&dpi.dpi_candidates)) {2833/* sync out final batch of prune candidates */2834VERIFY0(dsl_sync_task(spa_name(spa), NULL,2835prune_candidates_sync, &dpi, 0,2836ZFS_SPACE_CHECK_NONE));2837}2838list_destroy(&dpi.dpi_candidates);28392840zfs_dbgmsg("pruned %llu entries (%d%%) across %llu txg syncs",2841(u_longlong_t)dpi.dpi_pruned,2842(int)((dpi.dpi_pruned * 100) / valid),2843(u_longlong_t)dpi.dpi_txg_syncs);2844}2845}28462847static uint64_t2848ddt_total_entries(spa_t *spa)2849{2850ddt_object_t ddo;2851ddt_get_dedup_object_stats(spa, &ddo);28522853return (ddo.ddo_count);2854}28552856int2857ddt_prune_unique_entries(spa_t *spa, zpool_ddt_prune_unit_t unit,2858uint64_t amount)2859{2860uint64_t cutoff;2861uint64_t start_time = gethrtime();28622863if (spa->spa_active_ddt_prune)2864return (SET_ERROR(EALREADY));2865if (ddt_total_entries(spa) == 0)2866return (0);28672868spa->spa_active_ddt_prune = B_TRUE;28692870zfs_dbgmsg("prune %llu %s", (u_longlong_t)amount,2871unit == ZPOOL_DDT_PRUNE_PERCENTAGE ? "%" : "seconds old or older");28722873if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {2874ddt_age_histo_t histogram;2875uint64_t oldest = 0;28762877/* Make a pass over DDT to build a histogram */2878ddt_prune_walk(spa, 0, &histogram);28792880int target = (histogram.dah_entries * amount) / 100;28812882/*2883* Figure out our cutoff date2884* (i.e., which bins to prune from)2885*/2886for (int i = HIST_BINS - 1; i >= 0 && target > 0; i--) {2887if (histogram.dah_age_histo[i] != 0) {2888/* less than this bucket remaining */2889if (target < histogram.dah_age_histo[i]) {2890oldest = MAX(1, (1<<i) * 3600);2891target = 0;2892} else {2893target -= histogram.dah_age_histo[i];2894}2895}2896}2897cutoff = gethrestime_sec() - oldest;28982899if (ddt_dump_prune_histogram)2900ddt_dump_age_histogram(&histogram, cutoff);2901} else if (unit == ZPOOL_DDT_PRUNE_AGE) {2902cutoff = gethrestime_sec() - amount;2903} else {2904return (EINVAL);2905}29062907if (cutoff > 0 && !spa_shutting_down(spa) && !issig()) {2908/* Traverse DDT to prune entries older that our cuttoff */2909ddt_prune_walk(spa, cutoff, NULL);2910}29112912zfs_dbgmsg("%s: prune completed in %llu ms",2913spa_name(spa), (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));29142915spa->spa_active_ddt_prune = B_FALSE;2916return (0);2917}29182919ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, prefetch, INT, ZMOD_RW,2920"Enable prefetching dedup-ed blks");29212922ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_min_time_ms, UINT, ZMOD_RW,2923"Min time to spend on incremental dedup log flush each transaction");29242925ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_min, UINT, ZMOD_RW,2926"Min number of log entries to flush each transaction");29272928ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_entries_max, UINT, ZMOD_RW,2929"Max number of log entries to flush each transaction");29302931ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_txgs, UINT, ZMOD_RW,2932"Number of TXGs to try to rotate the log in");29332934ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_cap, UINT, ZMOD_RW,2935"Soft cap for the size of the current dedup log");29362937ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_hard_cap, UINT, ZMOD_RW,2938"Whether to use the soft cap as a hard cap");29392940ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_flush_flow_rate_txgs, UINT, ZMOD_RW,2941"Number of txgs to average flow rates across");294229432944