Path: blob/main/sys/contrib/openzfs/module/zfs/dsl_scan.c
108653 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*/21/*22* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.23* Copyright (c) 2011, 2021 by Delphix. All rights reserved.24* Copyright 2016 Gary Mills25* Copyright (c) 2017, 2019, Datto Inc. All rights reserved.26* Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.27* Copyright 2019 Joyent, Inc.28*/2930#include <sys/dsl_scan.h>31#include <sys/dsl_pool.h>32#include <sys/dsl_dataset.h>33#include <sys/dsl_prop.h>34#include <sys/dsl_dir.h>35#include <sys/dsl_synctask.h>36#include <sys/dnode.h>37#include <sys/dmu_tx.h>38#include <sys/dmu_objset.h>39#include <sys/arc.h>40#include <sys/arc_impl.h>41#include <sys/zap.h>42#include <sys/zio.h>43#include <sys/zfs_context.h>44#include <sys/fs/zfs.h>45#include <sys/zfs_znode.h>46#include <sys/spa_impl.h>47#include <sys/vdev_impl.h>48#include <sys/zil_impl.h>49#include <sys/zio_checksum.h>50#include <sys/brt.h>51#include <sys/ddt.h>52#include <sys/sa.h>53#include <sys/sa_impl.h>54#include <sys/zfeature.h>55#include <sys/abd.h>56#include <sys/range_tree.h>57#include <sys/dbuf.h>58#ifdef _KERNEL59#include <sys/zfs_vfsops.h>60#endif6162/*63* Grand theory statement on scan queue sorting64*65* Scanning is implemented by recursively traversing all indirection levels66* in an object and reading all blocks referenced from said objects. This67* results in us approximately traversing the object from lowest logical68* offset to the highest. For best performance, we would want the logical69* blocks to be physically contiguous. However, this is frequently not the70* case with pools given the allocation patterns of copy-on-write filesystems.71* So instead, we put the I/Os into a reordering queue and issue them in a72* way that will most benefit physical disks (LBA-order).73*74* Queue management:75*76* Ideally, we would want to scan all metadata and queue up all block I/O77* prior to starting to issue it, because that allows us to do an optimal78* sorting job. This can however consume large amounts of memory. Therefore79* we continuously monitor the size of the queues and constrain them to 5%80* (zfs_scan_mem_lim_fact) of physmem. If the queues grow larger than this81* limit, we clear out a few of the largest extents at the head of the queues82* to make room for more scanning. Hopefully, these extents will be fairly83* large and contiguous, allowing us to approach sequential I/O throughput84* even without a fully sorted tree.85*86* Metadata scanning takes place in dsl_scan_visit(), which is called from87* dsl_scan_sync() every spa_sync(). If we have either fully scanned all88* metadata on the pool, or we need to make room in memory because our89* queues are too large, dsl_scan_visit() is postponed and90* scan_io_queues_run() is called from dsl_scan_sync() instead. This implies91* that metadata scanning and queued I/O issuing are mutually exclusive. This92* allows us to provide maximum sequential I/O throughput for the majority of93* I/O's issued since sequential I/O performance is significantly negatively94* impacted if it is interleaved with random I/O.95*96* Implementation Notes97*98* One side effect of the queued scanning algorithm is that the scanning code99* needs to be notified whenever a block is freed. This is needed to allow100* the scanning code to remove these I/Os from the issuing queue. Additionally,101* we do not attempt to queue gang blocks to be issued sequentially since this102* is very hard to do and would have an extremely limited performance benefit.103* Instead, we simply issue gang I/Os as soon as we find them using the legacy104* algorithm.105*106* Backwards compatibility107*108* This new algorithm is backwards compatible with the legacy on-disk data109* structures (and therefore does not require a new feature flag).110* Periodically during scanning (see zfs_scan_checkpoint_intval), the scan111* will stop scanning metadata (in logical order) and wait for all outstanding112* sorted I/O to complete. Once this is done, we write out a checkpoint113* bookmark, indicating that we have scanned everything logically before it.114* If the pool is imported on a machine without the new sorting algorithm,115* the scan simply resumes from the last checkpoint using the legacy algorithm.116*/117118typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,119const zbookmark_phys_t *);120121static scan_cb_t dsl_scan_scrub_cb;122123static int scan_ds_queue_compare(const void *a, const void *b);124static int scan_prefetch_queue_compare(const void *a, const void *b);125static void scan_ds_queue_clear(dsl_scan_t *scn);126static void scan_ds_prefetch_queue_clear(dsl_scan_t *scn);127static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj,128uint64_t *txg);129static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg);130static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj);131static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx);132static uint64_t dsl_scan_count_data_disks(spa_t *spa);133static void read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb);134135extern uint_t zfs_vdev_async_write_active_min_dirty_percent;136static int zfs_scan_blkstats = 0;137138/*139* 'zpool status' uses bytes processed per pass to report throughput and140* estimate time remaining. We define a pass to start when the scanning141* phase completes for a sequential resilver. Optionally, this value142* may be used to reset the pass statistics every N txgs to provide an143* estimated completion time based on currently observed performance.144*/145static uint_t zfs_scan_report_txgs = 0;146147/*148* By default zfs will check to ensure it is not over the hard memory149* limit before each txg. If finer-grained control of this is needed150* this value can be set to 1 to enable checking before scanning each151* block.152*/153static int zfs_scan_strict_mem_lim = B_FALSE;154155/*156* Maximum number of parallelly executed bytes per leaf vdev. We attempt157* to strike a balance here between keeping the vdev queues full of I/Os158* at all times and not overflowing the queues to cause long latency,159* which would cause long txg sync times. No matter what, we will not160* overload the drives with I/O, since that is protected by161* zfs_vdev_scrub_max_active.162*/163static uint64_t zfs_scan_vdev_limit = 16 << 20;164165static uint_t zfs_scan_issue_strategy = 0;166167/* don't queue & sort zios, go direct */168static int zfs_scan_legacy = B_FALSE;169static uint64_t zfs_scan_max_ext_gap = 2 << 20; /* in bytes */170171/*172* fill_weight is non-tunable at runtime, so we copy it at module init from173* zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would174* break queue sorting.175*/176static uint_t zfs_scan_fill_weight = 3;177static uint64_t fill_weight;178179/* See dsl_scan_should_clear() for details on the memory limit tunables */180static const uint64_t zfs_scan_mem_lim_min = 16 << 20; /* bytes */181static const uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */182183184/* fraction of physmem */185static uint_t zfs_scan_mem_lim_fact = 20;186187/* fraction of mem lim above */188static uint_t zfs_scan_mem_lim_soft_fact = 20;189190/* minimum milliseconds to scrub per txg */191static uint_t zfs_scrub_min_time_ms = 750;192193/* minimum milliseconds to obsolete per txg */194static uint_t zfs_obsolete_min_time_ms = 500;195196/* minimum milliseconds to free per txg */197static uint_t zfs_free_min_time_ms = 500;198199/* minimum milliseconds to resilver per txg */200static uint_t zfs_resilver_min_time_ms = 1500;201202static uint_t zfs_scan_checkpoint_intval = 7200; /* in seconds */203int zfs_scan_suspend_progress = 0; /* set to prevent scans from progressing */204static int zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */205static int zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */206static const ddt_class_t zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;207/* max number of blocks to free in a single TXG */208static uint64_t zfs_async_block_max_blocks = UINT64_MAX;209/* max number of dedup blocks to free in a single TXG */210static uint64_t zfs_max_async_dedup_frees = 250000;211212/*213* After freeing this many async ZIOs (dedup, clone, gang blocks), wait for214* them to complete before continuing. This prevents unbounded I/O queueing.215*/216static uint64_t zfs_async_free_zio_wait_interval = 2000;217218/* set to disable resilver deferring */219static int zfs_resilver_disable_defer = B_FALSE;220221/* Don't defer a resilver if the one in progress only got this far: */222static uint_t zfs_resilver_defer_percent = 10;223224/*225* Number of TXGs to wait after importing before starting background226* work (async destroys, scan/scrub/resilver operations). This allows227* the import command and filesystem mounts to complete quickly without228* being delayed by background activities. The value is somewhat arbitrary229* since userspace triggers filesystem mounts asynchronously, but 5 TXGs230* provides a reasonable window for import completion in most cases.231*/232static uint_t zfs_import_defer_txgs = 5;233234#define DSL_SCAN_IS_SCRUB_RESILVER(scn) \235((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \236(scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)237238#define DSL_SCAN_IS_SCRUB(scn) \239((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB)240241#define DSL_SCAN_IS_RESILVER(scn) \242((scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)243244/*245* Enable/disable the processing of the free_bpobj object.246*/247static int zfs_free_bpobj_enabled = 1;248249/* Error blocks to be scrubbed in one txg. */250static uint_t zfs_scrub_error_blocks_per_txg = 1 << 12;251252/* the order has to match pool_scan_type */253static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {254NULL,255dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */256dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */257};258259/* In core node for the scn->scn_queue. Represents a dataset to be scanned */260typedef struct {261uint64_t sds_dsobj;262uint64_t sds_txg;263avl_node_t sds_node;264} scan_ds_t;265266/*267* This controls what conditions are placed on dsl_scan_sync_state():268* SYNC_OPTIONAL) write out scn_phys iff scn_queues_pending == 0269* SYNC_MANDATORY) write out scn_phys always. scn_queues_pending must be 0.270* SYNC_CACHED) if scn_queues_pending == 0, write out scn_phys. Otherwise271* write out the scn_phys_cached version.272* See dsl_scan_sync_state for details.273*/274typedef enum {275SYNC_OPTIONAL,276SYNC_MANDATORY,277SYNC_CACHED278} state_sync_type_t;279280/*281* This struct represents the minimum information needed to reconstruct a282* zio for sequential scanning. This is useful because many of these will283* accumulate in the sequential IO queues before being issued, so saving284* memory matters here.285*/286typedef struct scan_io {287/* fields from blkptr_t */288uint64_t sio_blk_prop;289uint64_t sio_phys_birth;290uint64_t sio_birth;291zio_cksum_t sio_cksum;292uint32_t sio_nr_dvas;293294/* fields from zio_t */295uint32_t sio_flags;296zbookmark_phys_t sio_zb;297298/* members for queue sorting */299union {300avl_node_t sio_addr_node; /* link into issuing queue */301list_node_t sio_list_node; /* link for issuing to disk */302} sio_nodes;303304/*305* There may be up to SPA_DVAS_PER_BP DVAs here from the bp,306* depending on how many were in the original bp. Only the307* first DVA is really used for sorting and issuing purposes.308* The other DVAs (if provided) simply exist so that the zio309* layer can find additional copies to repair from in the310* event of an error. This array must go at the end of the311* struct to allow this for the variable number of elements.312*/313dva_t sio_dva[];314} scan_io_t;315316#define SIO_SET_OFFSET(sio, x) DVA_SET_OFFSET(&(sio)->sio_dva[0], x)317#define SIO_SET_ASIZE(sio, x) DVA_SET_ASIZE(&(sio)->sio_dva[0], x)318#define SIO_GET_OFFSET(sio) DVA_GET_OFFSET(&(sio)->sio_dva[0])319#define SIO_GET_ASIZE(sio) DVA_GET_ASIZE(&(sio)->sio_dva[0])320#define SIO_GET_END_OFFSET(sio) \321(SIO_GET_OFFSET(sio) + SIO_GET_ASIZE(sio))322#define SIO_GET_MUSED(sio) \323(sizeof (scan_io_t) + ((sio)->sio_nr_dvas * sizeof (dva_t)))324325struct dsl_scan_io_queue {326dsl_scan_t *q_scn; /* associated dsl_scan_t */327vdev_t *q_vd; /* top-level vdev that this queue represents */328zio_t *q_zio; /* scn_zio_root child for waiting on IO */329330/* trees used for sorting I/Os and extents of I/Os */331zfs_range_tree_t *q_exts_by_addr;332zfs_btree_t q_exts_by_size;333avl_tree_t q_sios_by_addr;334uint64_t q_sio_memused;335uint64_t q_last_ext_addr;336337/* members for zio rate limiting */338uint64_t q_maxinflight_bytes;339uint64_t q_inflight_bytes;340kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */341342/* per txg statistics */343uint64_t q_total_seg_size_this_txg;344uint64_t q_segs_this_txg;345uint64_t q_total_zio_size_this_txg;346uint64_t q_zios_this_txg;347};348349/* private data for dsl_scan_prefetch_cb() */350typedef struct scan_prefetch_ctx {351zfs_refcount_t spc_refcnt; /* refcount for memory management */352dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */353boolean_t spc_root; /* is this prefetch for an objset? */354uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */355uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */356} scan_prefetch_ctx_t;357358/* private data for dsl_scan_prefetch() */359typedef struct scan_prefetch_issue_ctx {360avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */361scan_prefetch_ctx_t *spic_spc; /* spc for the callback */362blkptr_t spic_bp; /* bp to prefetch */363zbookmark_phys_t spic_zb; /* bookmark to prefetch */364} scan_prefetch_issue_ctx_t;365366static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,367const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);368static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,369scan_io_t *sio);370371static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);372static void scan_io_queues_destroy(dsl_scan_t *scn);373374static kmem_cache_t *sio_cache[SPA_DVAS_PER_BP];375376/* sio->sio_nr_dvas must be set so we know which cache to free from */377static void378sio_free(scan_io_t *sio)379{380ASSERT3U(sio->sio_nr_dvas, >, 0);381ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);382383kmem_cache_free(sio_cache[sio->sio_nr_dvas - 1], sio);384}385386/* It is up to the caller to set sio->sio_nr_dvas for freeing */387static scan_io_t *388sio_alloc(unsigned short nr_dvas)389{390ASSERT3U(nr_dvas, >, 0);391ASSERT3U(nr_dvas, <=, SPA_DVAS_PER_BP);392393return (kmem_cache_alloc(sio_cache[nr_dvas - 1], KM_SLEEP));394}395396void397scan_init(void)398{399/*400* This is used in ext_size_compare() to weight segments401* based on how sparse they are. This cannot be changed402* mid-scan and the tree comparison functions don't currently403* have a mechanism for passing additional context to the404* compare functions. Thus we store this value globally and405* we only allow it to be set at module initialization time406*/407fill_weight = zfs_scan_fill_weight;408409for (int i = 0; i < SPA_DVAS_PER_BP; i++) {410char name[36];411412(void) snprintf(name, sizeof (name), "sio_cache_%d", i);413sio_cache[i] = kmem_cache_create(name,414(sizeof (scan_io_t) + ((i + 1) * sizeof (dva_t))),4150, NULL, NULL, NULL, NULL, NULL, 0);416}417}418419void420scan_fini(void)421{422for (int i = 0; i < SPA_DVAS_PER_BP; i++) {423kmem_cache_destroy(sio_cache[i]);424}425}426427static inline boolean_t428dsl_scan_is_running(const dsl_scan_t *scn)429{430return (scn->scn_phys.scn_state == DSS_SCANNING);431}432433boolean_t434dsl_scan_resilvering(dsl_pool_t *dp)435{436return (dsl_scan_is_running(dp->dp_scan) &&437dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);438}439440static inline void441sio2bp(const scan_io_t *sio, blkptr_t *bp)442{443memset(bp, 0, sizeof (*bp));444bp->blk_prop = sio->sio_blk_prop;445BP_SET_PHYSICAL_BIRTH(bp, sio->sio_phys_birth);446BP_SET_LOGICAL_BIRTH(bp, sio->sio_birth);447bp->blk_fill = 1; /* we always only work with data pointers */448bp->blk_cksum = sio->sio_cksum;449450ASSERT3U(sio->sio_nr_dvas, >, 0);451ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);452453memcpy(bp->blk_dva, sio->sio_dva, sio->sio_nr_dvas * sizeof (dva_t));454}455456static inline void457bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)458{459sio->sio_blk_prop = bp->blk_prop;460sio->sio_phys_birth = BP_GET_RAW_PHYSICAL_BIRTH(bp);461sio->sio_birth = BP_GET_LOGICAL_BIRTH(bp);462sio->sio_cksum = bp->blk_cksum;463sio->sio_nr_dvas = BP_GET_NDVAS(bp);464465/*466* Copy the DVAs to the sio. We need all copies of the block so467* that the self healing code can use the alternate copies if the468* first is corrupted. We want the DVA at index dva_i to be first469* in the sio since this is the primary one that we want to issue.470*/471for (int i = 0, j = dva_i; i < sio->sio_nr_dvas; i++, j++) {472sio->sio_dva[i] = bp->blk_dva[j % sio->sio_nr_dvas];473}474}475476int477dsl_scan_init(dsl_pool_t *dp, uint64_t txg)478{479int err;480dsl_scan_t *scn;481spa_t *spa = dp->dp_spa;482uint64_t f;483484scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);485scn->scn_dp = dp;486487/*488* It's possible that we're resuming a scan after a reboot so489* make sure that the scan_async_destroying flag is initialized490* appropriately.491*/492ASSERT(!scn->scn_async_destroying);493scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,494SPA_FEATURE_ASYNC_DESTROY);495496/*497* Calculate the max number of in-flight bytes for pool-wide498* scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).499* Limits for the issuing phase are done per top-level vdev and500* are handled separately.501*/502scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,503zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));504505avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),506offsetof(scan_ds_t, sds_node));507mutex_init(&scn->scn_queue_lock, NULL, MUTEX_DEFAULT, NULL);508avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,509sizeof (scan_prefetch_issue_ctx_t),510offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));511512err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,513"scrub_func", sizeof (uint64_t), 1, &f);514if (err == 0) {515/*516* There was an old-style scrub in progress. Restart a517* new-style scrub from the beginning.518*/519scn->scn_restart_txg = txg;520zfs_dbgmsg("old-style scrub was in progress for %s; "521"restarting new-style scrub in txg %llu",522spa->spa_name,523(longlong_t)scn->scn_restart_txg);524525/*526* Load the queue obj from the old location so that it527* can be freed by dsl_scan_done().528*/529(void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,530"scrub_queue", sizeof (uint64_t), 1,531&scn->scn_phys.scn_queue_obj);532} else {533err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,534DMU_POOL_ERRORSCRUB, sizeof (uint64_t),535ERRORSCRUB_PHYS_NUMINTS, &scn->errorscrub_phys);536537if (err != 0 && err != ENOENT)538return (err);539540err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,541DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,542&scn->scn_phys);543544/*545* Detect if the pool contains the signature of #2094. If it546* does properly update the scn->scn_phys structure and notify547* the administrator by setting an errata for the pool.548*/549if (err == EOVERFLOW) {550uint64_t zaptmp[SCAN_PHYS_NUMINTS + 1];551VERIFY3S(SCAN_PHYS_NUMINTS, ==, 24);552VERIFY3S(offsetof(dsl_scan_phys_t, scn_flags), ==,553(23 * sizeof (uint64_t)));554555err = zap_lookup(dp->dp_meta_objset,556DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SCAN,557sizeof (uint64_t), SCAN_PHYS_NUMINTS + 1, &zaptmp);558if (err == 0) {559uint64_t overflow = zaptmp[SCAN_PHYS_NUMINTS];560561if (overflow & ~DSL_SCAN_FLAGS_MASK ||562scn->scn_async_destroying) {563spa->spa_errata =564ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY;565return (EOVERFLOW);566}567568memcpy(&scn->scn_phys, zaptmp,569SCAN_PHYS_NUMINTS * sizeof (uint64_t));570scn->scn_phys.scn_flags = overflow;571572/* Required scrub already in progress. */573if (scn->scn_phys.scn_state == DSS_FINISHED ||574scn->scn_phys.scn_state == DSS_CANCELED)575spa->spa_errata =576ZPOOL_ERRATA_ZOL_2094_SCRUB;577}578}579580if (err == ENOENT)581return (0);582else if (err)583return (err);584585/*586* We might be restarting after a reboot, so jump the issued587* counter to how far we've scanned. We know we're consistent588* up to here.589*/590scn->scn_issued_before_pass = scn->scn_phys.scn_examined -591scn->scn_phys.scn_skipped;592593if (dsl_scan_is_running(scn) &&594spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {595/*596* A new-type scrub was in progress on an old597* pool, and the pool was accessed by old598* software. Restart from the beginning, since599* the old software may have changed the pool in600* the meantime.601*/602scn->scn_restart_txg = txg;603zfs_dbgmsg("new-style scrub for %s was modified "604"by old software; restarting in txg %llu",605spa->spa_name,606(longlong_t)scn->scn_restart_txg);607} else if (dsl_scan_resilvering(dp)) {608/*609* If a resilver is in progress and there are already610* errors, restart it instead of finishing this scan and611* then restarting it. If there haven't been any errors612* then remember that the incore DTL is valid.613*/614if (scn->scn_phys.scn_errors > 0) {615scn->scn_restart_txg = txg;616zfs_dbgmsg("resilver can't excise DTL_MISSING "617"when finished; restarting on %s in txg "618"%llu",619spa->spa_name,620(u_longlong_t)scn->scn_restart_txg);621} else {622/* it's safe to excise DTL when finished */623spa->spa_scrub_started = B_TRUE;624}625}626}627628memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));629630/* reload the queue into the in-core state */631if (scn->scn_phys.scn_queue_obj != 0) {632zap_cursor_t zc;633zap_attribute_t *za = zap_attribute_alloc();634635for (zap_cursor_init(&zc, dp->dp_meta_objset,636scn->scn_phys.scn_queue_obj);637zap_cursor_retrieve(&zc, za) == 0;638(void) zap_cursor_advance(&zc)) {639scan_ds_queue_insert(scn,640zfs_strtonum(za->za_name, NULL),641za->za_first_integer);642}643zap_cursor_fini(&zc);644zap_attribute_free(za);645}646647ddt_walk_init(spa, scn->scn_phys.scn_max_txg);648649spa_scan_stat_init(spa);650vdev_scan_stat_init(spa->spa_root_vdev);651652return (0);653}654655void656dsl_scan_fini(dsl_pool_t *dp)657{658if (dp->dp_scan != NULL) {659dsl_scan_t *scn = dp->dp_scan;660661if (scn->scn_taskq != NULL)662taskq_destroy(scn->scn_taskq);663664scan_ds_queue_clear(scn);665avl_destroy(&scn->scn_queue);666mutex_destroy(&scn->scn_queue_lock);667scan_ds_prefetch_queue_clear(scn);668avl_destroy(&scn->scn_prefetch_queue);669670kmem_free(dp->dp_scan, sizeof (dsl_scan_t));671dp->dp_scan = NULL;672}673}674675static boolean_t676dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)677{678return (scn->scn_restart_txg != 0 &&679scn->scn_restart_txg <= tx->tx_txg);680}681682boolean_t683dsl_scan_resilver_scheduled(dsl_pool_t *dp)684{685return ((dp->dp_scan && dp->dp_scan->scn_restart_txg != 0) ||686(spa_async_tasks(dp->dp_spa) & SPA_ASYNC_RESILVER));687}688689boolean_t690dsl_scan_scrubbing(const dsl_pool_t *dp)691{692dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;693694return (scn_phys->scn_state == DSS_SCANNING &&695scn_phys->scn_func == POOL_SCAN_SCRUB);696}697698boolean_t699dsl_errorscrubbing(const dsl_pool_t *dp)700{701dsl_errorscrub_phys_t *errorscrub_phys = &dp->dp_scan->errorscrub_phys;702703return (errorscrub_phys->dep_state == DSS_ERRORSCRUBBING &&704errorscrub_phys->dep_func == POOL_SCAN_ERRORSCRUB);705}706707boolean_t708dsl_errorscrub_is_paused(const dsl_scan_t *scn)709{710return (dsl_errorscrubbing(scn->scn_dp) &&711scn->errorscrub_phys.dep_paused_flags);712}713714boolean_t715dsl_scan_is_paused_scrub(const dsl_scan_t *scn)716{717return (dsl_scan_scrubbing(scn->scn_dp) &&718scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);719}720721static void722dsl_errorscrub_sync_state(dsl_scan_t *scn, dmu_tx_t *tx)723{724scn->errorscrub_phys.dep_cursor =725zap_cursor_serialize(&scn->errorscrub_cursor);726727VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,728DMU_POOL_DIRECTORY_OBJECT,729DMU_POOL_ERRORSCRUB, sizeof (uint64_t), ERRORSCRUB_PHYS_NUMINTS,730&scn->errorscrub_phys, tx));731}732733static void734dsl_errorscrub_setup_sync(void *arg, dmu_tx_t *tx)735{736dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;737pool_scan_func_t *funcp = arg;738dsl_pool_t *dp = scn->scn_dp;739spa_t *spa = dp->dp_spa;740741ASSERT(!dsl_scan_is_running(scn));742ASSERT(!dsl_errorscrubbing(scn->scn_dp));743ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);744745memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));746scn->errorscrub_phys.dep_func = *funcp;747scn->errorscrub_phys.dep_state = DSS_ERRORSCRUBBING;748scn->errorscrub_phys.dep_start_time = gethrestime_sec();749scn->errorscrub_phys.dep_to_examine = spa_get_last_errlog_size(spa);750scn->errorscrub_phys.dep_examined = 0;751scn->errorscrub_phys.dep_errors = 0;752scn->errorscrub_phys.dep_cursor = 0;753zap_cursor_init_serialized(&scn->errorscrub_cursor,754spa->spa_meta_objset, spa->spa_errlog_last,755scn->errorscrub_phys.dep_cursor);756757vdev_config_dirty(spa->spa_root_vdev);758spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_START);759760dsl_errorscrub_sync_state(scn, tx);761762spa_history_log_internal(spa, "error scrub setup", tx,763"func=%u mintxg=%u maxtxg=%llu",764*funcp, 0, (u_longlong_t)tx->tx_txg);765}766767static int768dsl_errorscrub_setup_check(void *arg, dmu_tx_t *tx)769{770(void) arg;771dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;772773if (dsl_scan_is_running(scn) || (dsl_errorscrubbing(scn->scn_dp))) {774return (SET_ERROR(EBUSY));775}776777if (spa_get_last_errlog_size(scn->scn_dp->dp_spa) == 0) {778return (ECANCELED);779}780return (0);781}782783/*784* Writes out a persistent dsl_scan_phys_t record to the pool directory.785* Because we can be running in the block sorting algorithm, we do not always786* want to write out the record, only when it is "safe" to do so. This safety787* condition is achieved by making sure that the sorting queues are empty788* (scn_queues_pending == 0). When this condition is not true, the sync'd state789* is inconsistent with how much actual scanning progress has been made. The790* kind of sync to be performed is specified by the sync_type argument. If the791* sync is optional, we only sync if the queues are empty. If the sync is792* mandatory, we do a hard ASSERT to make sure that the queues are empty. The793* third possible state is a "cached" sync. This is done in response to:794* 1) The dataset that was in the last sync'd dsl_scan_phys_t having been795* destroyed, so we wouldn't be able to restart scanning from it.796* 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been797* superseded by a newer snapshot.798* 3) The dataset that was in the last sync'd dsl_scan_phys_t having been799* swapped with its clone.800* In all cases, a cached sync simply rewrites the last record we've written,801* just slightly modified. For the modifications that are performed to the802* last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,803* dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.804*/805static void806dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)807{808int i;809spa_t *spa = scn->scn_dp->dp_spa;810811ASSERT(sync_type != SYNC_MANDATORY || scn->scn_queues_pending == 0);812if (scn->scn_queues_pending == 0) {813for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {814vdev_t *vd = spa->spa_root_vdev->vdev_child[i];815dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;816817if (q == NULL)818continue;819820mutex_enter(&vd->vdev_scan_io_queue_lock);821ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);822ASSERT3P(zfs_btree_first(&q->q_exts_by_size, NULL), ==,823NULL);824ASSERT3P(zfs_range_tree_first(q->q_exts_by_addr), ==,825NULL);826mutex_exit(&vd->vdev_scan_io_queue_lock);827}828829if (scn->scn_phys.scn_queue_obj != 0)830scan_ds_queue_sync(scn, tx);831VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,832DMU_POOL_DIRECTORY_OBJECT,833DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,834&scn->scn_phys, tx));835memcpy(&scn->scn_phys_cached, &scn->scn_phys,836sizeof (scn->scn_phys));837838if (scn->scn_checkpointing)839zfs_dbgmsg("finish scan checkpoint for %s",840spa->spa_name);841842scn->scn_checkpointing = B_FALSE;843scn->scn_last_checkpoint = ddi_get_lbolt();844} else if (sync_type == SYNC_CACHED) {845VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,846DMU_POOL_DIRECTORY_OBJECT,847DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,848&scn->scn_phys_cached, tx));849}850}851852int853dsl_scan_setup_check(void *arg, dmu_tx_t *tx)854{855(void) arg;856dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;857vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;858859if (dsl_scan_is_running(scn) || vdev_rebuild_active(rvd) ||860dsl_errorscrubbing(scn->scn_dp))861return (SET_ERROR(EBUSY));862863return (0);864}865866void867dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)868{869setup_sync_arg_t *setup_sync_arg = (setup_sync_arg_t *)arg;870dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;871dmu_object_type_t ot = 0;872dsl_pool_t *dp = scn->scn_dp;873spa_t *spa = dp->dp_spa;874875ASSERT(!dsl_scan_is_running(scn));876ASSERT3U(setup_sync_arg->func, >, POOL_SCAN_NONE);877ASSERT3U(setup_sync_arg->func, <, POOL_SCAN_FUNCS);878memset(&scn->scn_phys, 0, sizeof (scn->scn_phys));879880/*881* If we are starting a fresh scrub, we erase the error scrub882* information from disk.883*/884memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));885dsl_errorscrub_sync_state(scn, tx);886887scn->scn_phys.scn_func = setup_sync_arg->func;888scn->scn_phys.scn_state = DSS_SCANNING;889scn->scn_phys.scn_min_txg = setup_sync_arg->txgstart;890if (setup_sync_arg->txgend == 0) {891scn->scn_phys.scn_max_txg = tx->tx_txg;892} else {893scn->scn_phys.scn_max_txg = setup_sync_arg->txgend;894}895scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */896scn->scn_phys.scn_start_time = gethrestime_sec();897scn->scn_phys.scn_errors = 0;898scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;899scn->scn_issued_before_pass = 0;900scn->scn_restart_txg = 0;901scn->scn_done_txg = 0;902scn->scn_last_checkpoint = 0;903scn->scn_checkpointing = B_FALSE;904spa_scan_stat_init(spa);905vdev_scan_stat_init(spa->spa_root_vdev);906907if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {908scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;909910/* rewrite all disk labels */911vdev_config_dirty(spa->spa_root_vdev);912913if (vdev_resilver_needed(spa->spa_root_vdev,914&scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {915nvlist_t *aux = fnvlist_alloc();916fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,917"healing");918spa_event_notify(spa, NULL, aux,919ESC_ZFS_RESILVER_START);920nvlist_free(aux);921} else {922spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);923}924925spa->spa_scrub_started = B_TRUE;926/*927* If this is an incremental scrub, limit the DDT scrub phase928* to just the auto-ditto class (for correctness); the rest929* of the scrub should go faster using top-down pruning.930*/931if (scn->scn_phys.scn_min_txg > TXG_INITIAL)932scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;933934/*935* When starting a resilver clear any existing rebuild state.936* This is required to prevent stale rebuild status from937* being reported when a rebuild is run, then a resilver and938* finally a scrub. In which case only the scrub status939* should be reported by 'zpool status'.940*/941if (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) {942vdev_t *rvd = spa->spa_root_vdev;943for (uint64_t i = 0; i < rvd->vdev_children; i++) {944vdev_t *vd = rvd->vdev_child[i];945vdev_rebuild_clear_sync(946(void *)(uintptr_t)vd->vdev_id, tx);947}948}949}950951/* back to the generic stuff */952953if (zfs_scan_blkstats) {954if (dp->dp_blkstats == NULL) {955dp->dp_blkstats =956vmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);957}958memset(&dp->dp_blkstats->zab_type, 0,959sizeof (dp->dp_blkstats->zab_type));960} else {961if (dp->dp_blkstats) {962vmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));963dp->dp_blkstats = NULL;964}965}966967if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)968ot = DMU_OT_ZAP_OTHER;969970scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,971ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);972973memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));974975ddt_walk_init(spa, scn->scn_phys.scn_max_txg);976977dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);978979spa_history_log_internal(spa, "scan setup", tx,980"func=%u mintxg=%llu maxtxg=%llu",981setup_sync_arg->func, (u_longlong_t)scn->scn_phys.scn_min_txg,982(u_longlong_t)scn->scn_phys.scn_max_txg);983}984985/*986* Called by ZFS_IOC_POOL_SCRUB and ZFS_IOC_POOL_SCAN ioctl to start a scrub,987* error scrub or resilver. Can also be called to resume a paused scrub or988* error scrub.989*/990int991dsl_scan(dsl_pool_t *dp, pool_scan_func_t func, uint64_t txgstart,992uint64_t txgend)993{994spa_t *spa = dp->dp_spa;995dsl_scan_t *scn = dp->dp_scan;996setup_sync_arg_t setup_sync_arg;997998if (func != POOL_SCAN_SCRUB && (txgstart != 0 || txgend != 0)) {999return (EINVAL);1000}10011002/*1003* Purge all vdev caches and probe all devices. We do this here1004* rather than in sync context because this requires a writer lock1005* on the spa_config lock, which we can't do from sync context. The1006* spa_scrub_reopen flag indicates that vdev_open() should not1007* attempt to start another scrub.1008*/1009spa_vdev_state_enter(spa, SCL_NONE);1010spa->spa_scrub_reopen = B_TRUE;1011vdev_reopen(spa->spa_root_vdev);1012spa->spa_scrub_reopen = B_FALSE;1013(void) spa_vdev_state_exit(spa, NULL, 0);10141015if (func == POOL_SCAN_RESILVER) {1016dsl_scan_restart_resilver(spa->spa_dsl_pool, 0);1017return (0);1018}10191020if (func == POOL_SCAN_ERRORSCRUB) {1021if (dsl_errorscrub_is_paused(dp->dp_scan)) {1022/*1023* got error scrub start cmd, resume paused error scrub.1024*/1025int err = dsl_scrub_set_pause_resume(scn->scn_dp,1026POOL_SCRUB_NORMAL);1027if (err == 0) {1028spa_event_notify(spa, NULL, NULL,1029ESC_ZFS_ERRORSCRUB_RESUME);1030return (0);1031}1032return (SET_ERROR(err));1033}10341035return (dsl_sync_task(spa_name(dp->dp_spa),1036dsl_errorscrub_setup_check, dsl_errorscrub_setup_sync,1037&func, 0, ZFS_SPACE_CHECK_RESERVED));1038}10391040if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {1041/* got scrub start cmd, resume paused scrub */1042int err = dsl_scrub_set_pause_resume(scn->scn_dp,1043POOL_SCRUB_NORMAL);1044if (err == 0) {1045spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);1046return (0);1047}1048return (SET_ERROR(err));1049}10501051setup_sync_arg.func = func;1052setup_sync_arg.txgstart = txgstart;1053setup_sync_arg.txgend = txgend;10541055return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,1056dsl_scan_setup_sync, &setup_sync_arg, 0,1057ZFS_SPACE_CHECK_EXTRA_RESERVED));1058}10591060static void1061dsl_errorscrub_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)1062{1063dsl_pool_t *dp = scn->scn_dp;1064spa_t *spa = dp->dp_spa;10651066if (complete) {1067spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_FINISH);1068spa_history_log_internal(spa, "error scrub done", tx,1069"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1070} else {1071spa_history_log_internal(spa, "error scrub canceled", tx,1072"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1073}10741075scn->errorscrub_phys.dep_state = complete ? DSS_FINISHED : DSS_CANCELED;1076spa->spa_scrub_active = B_FALSE;1077spa_errlog_rotate(spa);1078scn->errorscrub_phys.dep_end_time = gethrestime_sec();1079zap_cursor_fini(&scn->errorscrub_cursor);10801081if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)1082spa->spa_errata = 0;10831084ASSERT(!dsl_errorscrubbing(scn->scn_dp));1085}10861087static void1088dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)1089{1090static const char *old_names[] = {1091"scrub_bookmark",1092"scrub_ddt_bookmark",1093"scrub_ddt_class_max",1094"scrub_queue",1095"scrub_min_txg",1096"scrub_max_txg",1097"scrub_func",1098"scrub_errors",1099NULL1100};11011102dsl_pool_t *dp = scn->scn_dp;1103spa_t *spa = dp->dp_spa;1104int i;11051106/* Remove any remnants of an old-style scrub. */1107for (i = 0; old_names[i]; i++) {1108(void) zap_remove(dp->dp_meta_objset,1109DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);1110}11111112if (scn->scn_phys.scn_queue_obj != 0) {1113VERIFY0(dmu_object_free(dp->dp_meta_objset,1114scn->scn_phys.scn_queue_obj, tx));1115scn->scn_phys.scn_queue_obj = 0;1116}1117scan_ds_queue_clear(scn);1118scan_ds_prefetch_queue_clear(scn);11191120scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;11211122/*1123* If we were "restarted" from a stopped state, don't bother1124* with anything else.1125*/1126if (!dsl_scan_is_running(scn)) {1127ASSERT(!scn->scn_is_sorted);1128return;1129}11301131if (scn->scn_is_sorted) {1132scan_io_queues_destroy(scn);1133scn->scn_is_sorted = B_FALSE;11341135if (scn->scn_taskq != NULL) {1136taskq_destroy(scn->scn_taskq);1137scn->scn_taskq = NULL;1138}1139}11401141if (dsl_scan_restarting(scn, tx)) {1142spa_history_log_internal(spa, "scan aborted, restarting", tx,1143"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1144} else if (!complete) {1145spa_history_log_internal(spa, "scan cancelled", tx,1146"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1147} else {1148spa_history_log_internal(spa, "scan done", tx,1149"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1150if (DSL_SCAN_IS_SCRUB(scn)) {1151VERIFY0(zap_update(dp->dp_meta_objset,1152DMU_POOL_DIRECTORY_OBJECT,1153DMU_POOL_LAST_SCRUBBED_TXG,1154sizeof (uint64_t), 1,1155&scn->scn_phys.scn_max_txg, tx));1156spa->spa_scrubbed_last_txg = scn->scn_phys.scn_max_txg;1157}1158}11591160if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {1161spa->spa_scrub_active = B_FALSE;11621163/*1164* If the scrub/resilver completed, update all DTLs to1165* reflect this. Whether it succeeded or not, vacate1166* all temporary scrub DTLs.1167*1168* As the scrub does not currently support traversing1169* data that have been freed but are part of a checkpoint,1170* we don't mark the scrub as done in the DTLs as faults1171* may still exist in those vdevs.1172*/1173if (complete &&1174!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {1175vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,1176scn->scn_phys.scn_max_txg, B_TRUE, B_FALSE);11771178if (DSL_SCAN_IS_RESILVER(scn)) {1179nvlist_t *aux = fnvlist_alloc();1180fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,1181"healing");1182spa_event_notify(spa, NULL, aux,1183ESC_ZFS_RESILVER_FINISH);1184nvlist_free(aux);1185} else {1186spa_event_notify(spa, NULL, NULL,1187ESC_ZFS_SCRUB_FINISH);1188}1189} else {1190vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,11910, B_TRUE, B_FALSE);1192}1193spa_errlog_rotate(spa);11941195/*1196* Don't clear flag until after vdev_dtl_reassess to ensure that1197* DTL_MISSING will get updated when possible.1198*/1199scn->scn_phys.scn_state = complete ? DSS_FINISHED :1200DSS_CANCELED;1201scn->scn_phys.scn_end_time = gethrestime_sec();1202spa->spa_scrub_started = B_FALSE;12031204/*1205* We may have finished replacing a device.1206* Let the async thread assess this and handle the detach.1207*/1208spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);12091210/*1211* Clear any resilver_deferred flags in the config.1212* If there are drives that need resilvering, kick1213* off an asynchronous request to start resilver.1214* vdev_clear_resilver_deferred() may update the config1215* before the resilver can restart. In the event of1216* a crash during this period, the spa loading code1217* will find the drives that need to be resilvered1218* and start the resilver then.1219*/1220if (spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER) &&1221vdev_clear_resilver_deferred(spa->spa_root_vdev, tx)) {1222spa_history_log_internal(spa,1223"starting deferred resilver", tx, "errors=%llu",1224(u_longlong_t)spa_approx_errlog_size(spa));1225spa_async_request(spa, SPA_ASYNC_RESILVER);1226}12271228/* Clear recent error events (i.e. duplicate events tracking) */1229if (complete)1230zfs_ereport_clear(spa, NULL);1231} else {1232scn->scn_phys.scn_state = complete ? DSS_FINISHED :1233DSS_CANCELED;1234scn->scn_phys.scn_end_time = gethrestime_sec();1235}12361237spa_notify_waiters(spa);12381239if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)1240spa->spa_errata = 0;12411242ASSERT(!dsl_scan_is_running(scn));1243}12441245static int1246dsl_errorscrub_pause_resume_check(void *arg, dmu_tx_t *tx)1247{1248pool_scrub_cmd_t *cmd = arg;1249dsl_pool_t *dp = dmu_tx_pool(tx);1250dsl_scan_t *scn = dp->dp_scan;12511252if (*cmd == POOL_SCRUB_PAUSE) {1253/*1254* can't pause a error scrub when there is no in-progress1255* error scrub.1256*/1257if (!dsl_errorscrubbing(dp))1258return (SET_ERROR(ENOENT));12591260/* can't pause a paused error scrub */1261if (dsl_errorscrub_is_paused(scn))1262return (SET_ERROR(EBUSY));1263} else if (*cmd != POOL_SCRUB_NORMAL) {1264return (SET_ERROR(ENOTSUP));1265}12661267return (0);1268}12691270static void1271dsl_errorscrub_pause_resume_sync(void *arg, dmu_tx_t *tx)1272{1273pool_scrub_cmd_t *cmd = arg;1274dsl_pool_t *dp = dmu_tx_pool(tx);1275spa_t *spa = dp->dp_spa;1276dsl_scan_t *scn = dp->dp_scan;12771278if (*cmd == POOL_SCRUB_PAUSE) {1279spa->spa_scan_pass_errorscrub_pause = gethrestime_sec();1280scn->errorscrub_phys.dep_paused_flags = B_TRUE;1281dsl_errorscrub_sync_state(scn, tx);1282spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_PAUSED);1283} else {1284ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);1285if (dsl_errorscrub_is_paused(scn)) {1286/*1287* We need to keep track of how much time we spend1288* paused per pass so that we can adjust the error scrub1289* rate shown in the output of 'zpool status'.1290*/1291spa->spa_scan_pass_errorscrub_spent_paused +=1292gethrestime_sec() -1293spa->spa_scan_pass_errorscrub_pause;12941295spa->spa_scan_pass_errorscrub_pause = 0;1296scn->errorscrub_phys.dep_paused_flags = B_FALSE;12971298zap_cursor_init_serialized(1299&scn->errorscrub_cursor,1300spa->spa_meta_objset, spa->spa_errlog_last,1301scn->errorscrub_phys.dep_cursor);13021303dsl_errorscrub_sync_state(scn, tx);1304}1305}1306}13071308static int1309dsl_errorscrub_cancel_check(void *arg, dmu_tx_t *tx)1310{1311(void) arg;1312dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;1313/* can't cancel a error scrub when there is no one in-progress */1314if (!dsl_errorscrubbing(scn->scn_dp))1315return (SET_ERROR(ENOENT));1316return (0);1317}13181319static void1320dsl_errorscrub_cancel_sync(void *arg, dmu_tx_t *tx)1321{1322(void) arg;1323dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13241325dsl_errorscrub_done(scn, B_FALSE, tx);1326dsl_errorscrub_sync_state(scn, tx);1327spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL,1328ESC_ZFS_ERRORSCRUB_ABORT);1329}13301331static int1332dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)1333{1334(void) arg;1335dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13361337if (!dsl_scan_is_running(scn))1338return (SET_ERROR(ENOENT));1339return (0);1340}13411342static void1343dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)1344{1345(void) arg;1346dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13471348dsl_scan_done(scn, B_FALSE, tx);1349dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);1350spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);1351}13521353int1354dsl_scan_cancel(dsl_pool_t *dp)1355{1356if (dsl_errorscrubbing(dp)) {1357return (dsl_sync_task(spa_name(dp->dp_spa),1358dsl_errorscrub_cancel_check, dsl_errorscrub_cancel_sync,1359NULL, 3, ZFS_SPACE_CHECK_RESERVED));1360}1361return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,1362dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));1363}13641365static int1366dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)1367{1368pool_scrub_cmd_t *cmd = arg;1369dsl_pool_t *dp = dmu_tx_pool(tx);1370dsl_scan_t *scn = dp->dp_scan;13711372if (*cmd == POOL_SCRUB_PAUSE) {1373/* can't pause a scrub when there is no in-progress scrub */1374if (!dsl_scan_scrubbing(dp))1375return (SET_ERROR(ENOENT));13761377/* can't pause a paused scrub */1378if (dsl_scan_is_paused_scrub(scn))1379return (SET_ERROR(EBUSY));1380} else if (*cmd != POOL_SCRUB_NORMAL) {1381return (SET_ERROR(ENOTSUP));1382}13831384return (0);1385}13861387static void1388dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)1389{1390pool_scrub_cmd_t *cmd = arg;1391dsl_pool_t *dp = dmu_tx_pool(tx);1392spa_t *spa = dp->dp_spa;1393dsl_scan_t *scn = dp->dp_scan;13941395if (*cmd == POOL_SCRUB_PAUSE) {1396/* can't pause a scrub when there is no in-progress scrub */1397spa->spa_scan_pass_scrub_pause = gethrestime_sec();1398scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;1399scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED;1400dsl_scan_sync_state(scn, tx, SYNC_CACHED);1401spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);1402spa_notify_waiters(spa);1403} else {1404ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);1405if (dsl_scan_is_paused_scrub(scn)) {1406/*1407* We need to keep track of how much time we spend1408* paused per pass so that we can adjust the scrub rate1409* shown in the output of 'zpool status'1410*/1411spa->spa_scan_pass_scrub_spent_paused +=1412gethrestime_sec() - spa->spa_scan_pass_scrub_pause;1413spa->spa_scan_pass_scrub_pause = 0;1414scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;1415scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED;1416dsl_scan_sync_state(scn, tx, SYNC_CACHED);1417}1418}1419}14201421/*1422* Set scrub pause/resume state if it makes sense to do so1423*/1424int1425dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)1426{1427if (dsl_errorscrubbing(dp)) {1428return (dsl_sync_task(spa_name(dp->dp_spa),1429dsl_errorscrub_pause_resume_check,1430dsl_errorscrub_pause_resume_sync, &cmd, 3,1431ZFS_SPACE_CHECK_RESERVED));1432}1433return (dsl_sync_task(spa_name(dp->dp_spa),1434dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,1435ZFS_SPACE_CHECK_RESERVED));1436}143714381439/* start a new scan, or restart an existing one. */1440void1441dsl_scan_restart_resilver(dsl_pool_t *dp, uint64_t txg)1442{1443if (txg == 0) {1444dmu_tx_t *tx;1445tx = dmu_tx_create_dd(dp->dp_mos_dir);1446VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));14471448txg = dmu_tx_get_txg(tx);1449dp->dp_scan->scn_restart_txg = txg;1450dmu_tx_commit(tx);1451} else {1452dp->dp_scan->scn_restart_txg = txg;1453}1454zfs_dbgmsg("restarting resilver for %s at txg=%llu",1455dp->dp_spa->spa_name, (longlong_t)txg);1456}14571458void1459dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)1460{1461zio_free(dp->dp_spa, txg, bp);1462}14631464void1465dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)1466{1467ASSERT(dsl_pool_sync_context(dp));1468zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));1469}14701471static int1472scan_ds_queue_compare(const void *a, const void *b)1473{1474const scan_ds_t *sds_a = a, *sds_b = b;14751476if (sds_a->sds_dsobj < sds_b->sds_dsobj)1477return (-1);1478if (sds_a->sds_dsobj == sds_b->sds_dsobj)1479return (0);1480return (1);1481}14821483static void1484scan_ds_queue_clear(dsl_scan_t *scn)1485{1486void *cookie = NULL;1487scan_ds_t *sds;1488while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {1489kmem_free(sds, sizeof (*sds));1490}1491}14921493static boolean_t1494scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)1495{1496scan_ds_t srch, *sds;14971498srch.sds_dsobj = dsobj;1499sds = avl_find(&scn->scn_queue, &srch, NULL);1500if (sds != NULL && txg != NULL)1501*txg = sds->sds_txg;1502return (sds != NULL);1503}15041505static void1506scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)1507{1508scan_ds_t *sds;1509avl_index_t where;15101511sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);1512sds->sds_dsobj = dsobj;1513sds->sds_txg = txg;15141515VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);1516avl_insert(&scn->scn_queue, sds, where);1517}15181519static void1520scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)1521{1522scan_ds_t srch, *sds;15231524srch.sds_dsobj = dsobj;15251526sds = avl_find(&scn->scn_queue, &srch, NULL);1527VERIFY(sds != NULL);1528avl_remove(&scn->scn_queue, sds);1529kmem_free(sds, sizeof (*sds));1530}15311532static void1533scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)1534{1535dsl_pool_t *dp = scn->scn_dp;1536spa_t *spa = dp->dp_spa;1537dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?1538DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;15391540ASSERT0(scn->scn_queues_pending);1541ASSERT(scn->scn_phys.scn_queue_obj != 0);15421543VERIFY0(dmu_object_free(dp->dp_meta_objset,1544scn->scn_phys.scn_queue_obj, tx));1545scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,1546DMU_OT_NONE, 0, tx);1547for (scan_ds_t *sds = avl_first(&scn->scn_queue);1548sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {1549VERIFY0(zap_add_int_key(dp->dp_meta_objset,1550scn->scn_phys.scn_queue_obj, sds->sds_dsobj,1551sds->sds_txg, tx));1552}1553}15541555/*1556* Computes the memory limit state that we're currently in. A sorted scan1557* needs quite a bit of memory to hold the sorting queue, so we need to1558* reasonably constrain the size so it doesn't impact overall system1559* performance. We compute two limits:1560* 1) Hard memory limit: if the amount of memory used by the sorting1561* queues on a pool gets above this value, we stop the metadata1562* scanning portion and start issuing the queued up and sorted1563* I/Os to reduce memory usage.1564* This limit is calculated as a fraction of physmem (by default 5%).1565* We constrain the lower bound of the hard limit to an absolute1566* minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain1567* the upper bound to 5% of the total pool size - no chance we'll1568* ever need that much memory, but just to keep the value in check.1569* 2) Soft memory limit: once we hit the hard memory limit, we start1570* issuing I/O to reduce queue memory usage, but we don't want to1571* completely empty out the queues, since we might be able to find I/Os1572* that will fill in the gaps of our non-sequential IOs at some point1573* in the future. So we stop the issuing of I/Os once the amount of1574* memory used drops below the soft limit (at which point we stop issuing1575* I/O and start scanning metadata again).1576*1577* This limit is calculated by subtracting a fraction of the hard1578* limit from the hard limit. By default this fraction is 5%, so1579* the soft limit is 95% of the hard limit. We cap the size of the1580* difference between the hard and soft limits at an absolute1581* maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is1582* sufficient to not cause too frequent switching between the1583* metadata scan and I/O issue (even at 2k recordsize, 128 MiB's1584* worth of queues is about 1.2 GiB of on-pool data, so scanning1585* that should take at least a decent fraction of a second).1586*/1587static boolean_t1588dsl_scan_should_clear(dsl_scan_t *scn)1589{1590spa_t *spa = scn->scn_dp->dp_spa;1591vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;1592uint64_t alloc, mlim_hard, mlim_soft, mused;15931594alloc = metaslab_class_get_alloc(spa_normal_class(spa));1595alloc += metaslab_class_get_alloc(spa_special_class(spa));1596alloc += metaslab_class_get_alloc(spa_dedup_class(spa));15971598mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,1599zfs_scan_mem_lim_min);1600mlim_hard = MIN(mlim_hard, alloc / 20);1601mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,1602zfs_scan_mem_lim_soft_max);1603mused = 0;1604for (uint64_t i = 0; i < rvd->vdev_children; i++) {1605vdev_t *tvd = rvd->vdev_child[i];1606dsl_scan_io_queue_t *queue;16071608mutex_enter(&tvd->vdev_scan_io_queue_lock);1609queue = tvd->vdev_scan_io_queue;1610if (queue != NULL) {1611/*1612* # of extents in exts_by_addr = # in exts_by_size.1613* B-tree efficiency is ~75%, but can be as low as 50%.1614*/1615mused += zfs_btree_numnodes(&queue->q_exts_by_size) * ((1616sizeof (zfs_range_seg_gap_t) + sizeof (uint64_t)) *16173 / 2) + queue->q_sio_memused;1618}1619mutex_exit(&tvd->vdev_scan_io_queue_lock);1620}16211622dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);16231624if (mused == 0)1625ASSERT0(scn->scn_queues_pending);16261627/*1628* If we are above our hard limit, we need to clear out memory.1629* If we are below our soft limit, we need to accumulate sequential IOs.1630* Otherwise, we should keep doing whatever we are currently doing.1631*/1632if (mused >= mlim_hard)1633return (B_TRUE);1634else if (mused < mlim_soft)1635return (B_FALSE);1636else1637return (scn->scn_clearing);1638}16391640static boolean_t1641dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)1642{1643/* we never skip user/group accounting objects */1644if (zb && (int64_t)zb->zb_object < 0)1645return (B_FALSE);16461647if (scn->scn_suspending)1648return (B_TRUE); /* we're already suspending */16491650if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))1651return (B_FALSE); /* we're resuming */16521653/* We only know how to resume from level-0 and objset blocks. */1654if (zb && (zb->zb_level != 0 && zb->zb_level != ZB_ROOT_LEVEL))1655return (B_FALSE);16561657/*1658* We suspend if:1659* - we have scanned for at least the minimum time (default 1 sec1660* for scrub, 3 sec for resilver), and either we have sufficient1661* dirty data that we are starting to write more quickly1662* (default 30%), someone is explicitly waiting for this txg1663* to complete, or we have used up all of the time in the txg1664* timeout (default 5 sec).1665* or1666* - the spa is shutting down because this pool is being exported1667* or the machine is rebooting.1668* or1669* - the scan queue has reached its memory use limit1670*/1671uint64_t curr_time_ns = getlrtime();1672uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;1673uint64_t sync_time_ns = curr_time_ns -1674scn->scn_dp->dp_spa->spa_sync_starttime;1675uint64_t dirty_min_bytes = zfs_dirty_data_max *1676zfs_vdev_async_write_active_min_dirty_percent / 100;1677uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?1678zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;16791680if ((NSEC2MSEC(scan_time_ns) > mintime &&1681(scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||1682txg_sync_waiting(scn->scn_dp) ||1683NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||1684spa_shutting_down(scn->scn_dp->dp_spa) ||1685(zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn)) ||1686!ddt_walk_ready(scn->scn_dp->dp_spa)) {1687if (zb && zb->zb_level == ZB_ROOT_LEVEL) {1688dprintf("suspending at first available bookmark "1689"%llx/%llx/%llx/%llx\n",1690(longlong_t)zb->zb_objset,1691(longlong_t)zb->zb_object,1692(longlong_t)zb->zb_level,1693(longlong_t)zb->zb_blkid);1694SET_BOOKMARK(&scn->scn_phys.scn_bookmark,1695zb->zb_objset, 0, 0, 0);1696} else if (zb != NULL) {1697dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",1698(longlong_t)zb->zb_objset,1699(longlong_t)zb->zb_object,1700(longlong_t)zb->zb_level,1701(longlong_t)zb->zb_blkid);1702scn->scn_phys.scn_bookmark = *zb;1703} else {1704#ifdef ZFS_DEBUG1705dsl_scan_phys_t *scnp = &scn->scn_phys;1706dprintf("suspending at at DDT bookmark "1707"%llx/%llx/%llx/%llx\n",1708(longlong_t)scnp->scn_ddt_bookmark.ddb_class,1709(longlong_t)scnp->scn_ddt_bookmark.ddb_type,1710(longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,1711(longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);1712#endif1713}1714scn->scn_suspending = B_TRUE;1715return (B_TRUE);1716}1717return (B_FALSE);1718}17191720static boolean_t1721dsl_error_scrub_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)1722{1723/*1724* We suspend if:1725* - we have scrubbed for at least the minimum time (default 1 sec1726* for error scrub), someone is explicitly waiting for this txg1727* to complete, or we have used up all of the time in the txg1728* timeout (default 5 sec).1729* or1730* - the spa is shutting down because this pool is being exported1731* or the machine is rebooting.1732*/1733uint64_t curr_time_ns = getlrtime();1734uint64_t error_scrub_time_ns = curr_time_ns - scn->scn_sync_start_time;1735uint64_t sync_time_ns = curr_time_ns -1736scn->scn_dp->dp_spa->spa_sync_starttime;1737int mintime = zfs_scrub_min_time_ms;17381739if ((NSEC2MSEC(error_scrub_time_ns) > mintime &&1740(txg_sync_waiting(scn->scn_dp) ||1741NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||1742spa_shutting_down(scn->scn_dp->dp_spa)) {1743if (zb) {1744dprintf("error scrub suspending at bookmark "1745"%llx/%llx/%llx/%llx\n",1746(longlong_t)zb->zb_objset,1747(longlong_t)zb->zb_object,1748(longlong_t)zb->zb_level,1749(longlong_t)zb->zb_blkid);1750}1751return (B_TRUE);1752}1753return (B_FALSE);1754}17551756typedef struct zil_scan_arg {1757dsl_pool_t *zsa_dp;1758zil_header_t *zsa_zh;1759} zil_scan_arg_t;17601761static int1762dsl_scan_zil_block(zilog_t *zilog, const blkptr_t *bp, void *arg,1763uint64_t claim_txg)1764{1765(void) zilog;1766zil_scan_arg_t *zsa = arg;1767dsl_pool_t *dp = zsa->zsa_dp;1768dsl_scan_t *scn = dp->dp_scan;1769zil_header_t *zh = zsa->zsa_zh;1770zbookmark_phys_t zb;17711772ASSERT(!BP_IS_REDACTED(bp));1773if (BP_IS_HOLE(bp) ||1774BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)1775return (0);17761777/*1778* One block ("stubby") can be allocated a long time ago; we1779* want to visit that one because it has been allocated1780* (on-disk) even if it hasn't been claimed (even though for1781* scrub there's nothing to do to it).1782*/1783if (claim_txg == 0 &&1784BP_GET_BIRTH(bp) >= spa_min_claim_txg(dp->dp_spa))1785return (0);17861787SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],1788ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);17891790VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));1791return (0);1792}17931794static int1795dsl_scan_zil_record(zilog_t *zilog, const lr_t *lrc, void *arg,1796uint64_t claim_txg)1797{1798(void) zilog;1799if (lrc->lrc_txtype == TX_WRITE) {1800zil_scan_arg_t *zsa = arg;1801dsl_pool_t *dp = zsa->zsa_dp;1802dsl_scan_t *scn = dp->dp_scan;1803zil_header_t *zh = zsa->zsa_zh;1804const lr_write_t *lr = (const lr_write_t *)lrc;1805const blkptr_t *bp = &lr->lr_blkptr;1806zbookmark_phys_t zb;18071808ASSERT(!BP_IS_REDACTED(bp));1809if (BP_IS_HOLE(bp) ||1810BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)1811return (0);18121813/*1814* birth can be < claim_txg if this record's txg is1815* already txg sync'ed (but this log block contains1816* other records that are not synced)1817*/1818if (claim_txg == 0 || BP_GET_BIRTH(bp) < claim_txg)1819return (0);18201821ASSERT3U(BP_GET_LSIZE(bp), !=, 0);1822SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],1823lr->lr_foid, ZB_ZIL_LEVEL,1824lr->lr_offset / BP_GET_LSIZE(bp));18251826VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));1827}1828return (0);1829}18301831static void1832dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)1833{1834uint64_t claim_txg = zh->zh_claim_txg;1835zil_scan_arg_t zsa = { dp, zh };1836zilog_t *zilog;18371838ASSERT(spa_writeable(dp->dp_spa));18391840/*1841* We only want to visit blocks that have been claimed but not yet1842* replayed (or, in read-only mode, blocks that *would* be claimed).1843*/1844if (claim_txg == 0)1845return;18461847zilog = zil_alloc(dp->dp_meta_objset, zh);18481849(void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,1850claim_txg, B_FALSE);18511852zil_free(zilog);1853}18541855/*1856* We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea1857* here is to sort the AVL tree by the order each block will be needed.1858*/1859static int1860scan_prefetch_queue_compare(const void *a, const void *b)1861{1862const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;1863const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;1864const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;18651866return (zbookmark_compare(spc_a->spc_datablkszsec,1867spc_a->spc_indblkshift, spc_b->spc_datablkszsec,1868spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));1869}18701871static void1872scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, const void *tag)1873{1874if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {1875zfs_refcount_destroy(&spc->spc_refcnt);1876kmem_free(spc, sizeof (scan_prefetch_ctx_t));1877}1878}18791880static scan_prefetch_ctx_t *1881scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, const void *tag)1882{1883scan_prefetch_ctx_t *spc;18841885spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);1886zfs_refcount_create(&spc->spc_refcnt);1887zfs_refcount_add(&spc->spc_refcnt, tag);1888spc->spc_scn = scn;1889if (dnp != NULL) {1890spc->spc_datablkszsec = dnp->dn_datablkszsec;1891spc->spc_indblkshift = dnp->dn_indblkshift;1892spc->spc_root = B_FALSE;1893} else {1894spc->spc_datablkszsec = 0;1895spc->spc_indblkshift = 0;1896spc->spc_root = B_TRUE;1897}18981899return (spc);1900}19011902static void1903scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, const void *tag)1904{1905zfs_refcount_add(&spc->spc_refcnt, tag);1906}19071908static void1909scan_ds_prefetch_queue_clear(dsl_scan_t *scn)1910{1911spa_t *spa = scn->scn_dp->dp_spa;1912void *cookie = NULL;1913scan_prefetch_issue_ctx_t *spic = NULL;19141915mutex_enter(&spa->spa_scrub_lock);1916while ((spic = avl_destroy_nodes(&scn->scn_prefetch_queue,1917&cookie)) != NULL) {1918scan_prefetch_ctx_rele(spic->spic_spc, scn);1919kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));1920}1921mutex_exit(&spa->spa_scrub_lock);1922}19231924static boolean_t1925dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,1926const zbookmark_phys_t *zb)1927{1928zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;1929dnode_phys_t tmp_dnp;1930dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;19311932if (zb->zb_objset != last_zb->zb_objset)1933return (B_TRUE);1934if ((int64_t)zb->zb_object < 0)1935return (B_FALSE);19361937tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;1938tmp_dnp.dn_indblkshift = spc->spc_indblkshift;19391940if (zbookmark_subtree_completed(dnp, zb, last_zb))1941return (B_TRUE);19421943return (B_FALSE);1944}19451946static void1947dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)1948{1949avl_index_t idx;1950dsl_scan_t *scn = spc->spc_scn;1951spa_t *spa = scn->scn_dp->dp_spa;1952scan_prefetch_issue_ctx_t *spic;19531954if (zfs_no_scrub_prefetch || BP_IS_REDACTED(bp))1955return;19561957if (BP_IS_HOLE(bp) ||1958BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg ||1959(BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&1960BP_GET_TYPE(bp) != DMU_OT_OBJSET))1961return;19621963if (dsl_scan_check_prefetch_resume(spc, zb))1964return;19651966scan_prefetch_ctx_add_ref(spc, scn);1967spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);1968spic->spic_spc = spc;1969spic->spic_bp = *bp;1970spic->spic_zb = *zb;19711972/*1973* Add the IO to the queue of blocks to prefetch. This allows us to1974* prioritize blocks that we will need first for the main traversal1975* thread.1976*/1977mutex_enter(&spa->spa_scrub_lock);1978if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {1979/* this block is already queued for prefetch */1980kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));1981scan_prefetch_ctx_rele(spc, scn);1982mutex_exit(&spa->spa_scrub_lock);1983return;1984}19851986avl_insert(&scn->scn_prefetch_queue, spic, idx);1987cv_broadcast(&spa->spa_scrub_io_cv);1988mutex_exit(&spa->spa_scrub_lock);1989}19901991static void1992dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,1993uint64_t objset, uint64_t object)1994{1995int i;1996zbookmark_phys_t zb;1997scan_prefetch_ctx_t *spc;19981999if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))2000return;20012002SET_BOOKMARK(&zb, objset, object, 0, 0);20032004spc = scan_prefetch_ctx_create(scn, dnp, FTAG);20052006for (i = 0; i < dnp->dn_nblkptr; i++) {2007zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);2008zb.zb_blkid = i;2009dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);2010}20112012if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {2013zb.zb_level = 0;2014zb.zb_blkid = DMU_SPILL_BLKID;2015dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);2016}20172018scan_prefetch_ctx_rele(spc, FTAG);2019}20202021static void2022dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,2023arc_buf_t *buf, void *private)2024{2025(void) zio;2026scan_prefetch_ctx_t *spc = private;2027dsl_scan_t *scn = spc->spc_scn;2028spa_t *spa = scn->scn_dp->dp_spa;20292030/* broadcast that the IO has completed for rate limiting purposes */2031mutex_enter(&spa->spa_scrub_lock);2032ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));2033spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);2034cv_broadcast(&spa->spa_scrub_io_cv);2035mutex_exit(&spa->spa_scrub_lock);20362037/* if there was an error or we are done prefetching, just cleanup */2038if (buf == NULL || scn->scn_prefetch_stop)2039goto out;20402041if (BP_GET_LEVEL(bp) > 0) {2042int i;2043blkptr_t *cbp;2044int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;2045zbookmark_phys_t czb;20462047for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {2048SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,2049zb->zb_level - 1, zb->zb_blkid * epb + i);2050dsl_scan_prefetch(spc, cbp, &czb);2051}2052} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {2053dnode_phys_t *cdnp;2054int i;2055int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;20562057for (i = 0, cdnp = buf->b_data; i < epb;2058i += cdnp->dn_extra_slots + 1,2059cdnp += cdnp->dn_extra_slots + 1) {2060dsl_scan_prefetch_dnode(scn, cdnp,2061zb->zb_objset, zb->zb_blkid * epb + i);2062}2063} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {2064objset_phys_t *osp = buf->b_data;20652066dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,2067zb->zb_objset, DMU_META_DNODE_OBJECT);20682069if (OBJSET_BUF_HAS_USERUSED(buf)) {2070if (OBJSET_BUF_HAS_PROJECTUSED(buf)) {2071dsl_scan_prefetch_dnode(scn,2072&osp->os_projectused_dnode, zb->zb_objset,2073DMU_PROJECTUSED_OBJECT);2074}2075dsl_scan_prefetch_dnode(scn,2076&osp->os_groupused_dnode, zb->zb_objset,2077DMU_GROUPUSED_OBJECT);2078dsl_scan_prefetch_dnode(scn,2079&osp->os_userused_dnode, zb->zb_objset,2080DMU_USERUSED_OBJECT);2081}2082}20832084out:2085if (buf != NULL)2086arc_buf_destroy(buf, private);2087scan_prefetch_ctx_rele(spc, scn);2088}20892090static void2091dsl_scan_prefetch_thread(void *arg)2092{2093dsl_scan_t *scn = arg;2094spa_t *spa = scn->scn_dp->dp_spa;2095scan_prefetch_issue_ctx_t *spic;20962097/* loop until we are told to stop */2098while (!scn->scn_prefetch_stop) {2099arc_flags_t flags = ARC_FLAG_NOWAIT |2100ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;2101int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;21022103mutex_enter(&spa->spa_scrub_lock);21042105/*2106* Wait until we have an IO to issue and are not above our2107* maximum in flight limit.2108*/2109while (!scn->scn_prefetch_stop &&2110(avl_numnodes(&scn->scn_prefetch_queue) == 0 ||2111spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {2112cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);2113}21142115/* recheck if we should stop since we waited for the cv */2116if (scn->scn_prefetch_stop) {2117mutex_exit(&spa->spa_scrub_lock);2118break;2119}21202121/* remove the prefetch IO from the tree */2122spic = avl_first(&scn->scn_prefetch_queue);2123spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);2124avl_remove(&scn->scn_prefetch_queue, spic);21252126mutex_exit(&spa->spa_scrub_lock);21272128if (BP_IS_PROTECTED(&spic->spic_bp)) {2129ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||2130BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);2131ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);2132zio_flags |= ZIO_FLAG_RAW;2133}21342135/* We don't need data L1 buffer since we do not prefetch L0. */2136blkptr_t *bp = &spic->spic_bp;2137if (BP_GET_LEVEL(bp) == 1 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&2138BP_GET_TYPE(bp) != DMU_OT_OBJSET)2139flags |= ARC_FLAG_NO_BUF;21402141/* issue the prefetch asynchronously */2142(void) arc_read(scn->scn_zio_root, spa, bp,2143dsl_scan_prefetch_cb, spic->spic_spc, ZIO_PRIORITY_SCRUB,2144zio_flags, &flags, &spic->spic_zb);21452146kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));2147}21482149ASSERT(scn->scn_prefetch_stop);21502151/* free any prefetches we didn't get to complete */2152mutex_enter(&spa->spa_scrub_lock);2153while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {2154avl_remove(&scn->scn_prefetch_queue, spic);2155scan_prefetch_ctx_rele(spic->spic_spc, scn);2156kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));2157}2158ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));2159mutex_exit(&spa->spa_scrub_lock);2160}21612162static boolean_t2163dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,2164const zbookmark_phys_t *zb)2165{2166/*2167* We never skip over user/group accounting objects (obj<0)2168*/2169if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&2170(int64_t)zb->zb_object >= 0) {2171/*2172* If we already visited this bp & everything below (in2173* a prior txg sync), don't bother doing it again.2174*/2175if (zbookmark_subtree_completed(dnp, zb,2176&scn->scn_phys.scn_bookmark))2177return (B_TRUE);21782179/*2180* If we found the block we're trying to resume from, or2181* we went past it, zero it out to indicate that it's OK2182* to start checking for suspending again.2183*/2184if (zbookmark_subtree_tbd(dnp, zb,2185&scn->scn_phys.scn_bookmark)) {2186dprintf("resuming at %llx/%llx/%llx/%llx\n",2187(longlong_t)zb->zb_objset,2188(longlong_t)zb->zb_object,2189(longlong_t)zb->zb_level,2190(longlong_t)zb->zb_blkid);2191memset(&scn->scn_phys.scn_bookmark, 0, sizeof (*zb));2192}2193}2194return (B_FALSE);2195}21962197static void dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,2198dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,2199dmu_objset_type_t ostype, dmu_tx_t *tx);2200inline __attribute__((always_inline)) static void dsl_scan_visitdnode(2201dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,2202dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);22032204/*2205* Return nonzero on i/o error.2206* Return new buf to write out in *bufp.2207*/2208inline __attribute__((always_inline)) static int2209dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,2210dnode_phys_t *dnp, const blkptr_t *bp,2211const zbookmark_phys_t *zb, dmu_tx_t *tx)2212{2213dsl_pool_t *dp = scn->scn_dp;2214spa_t *spa = dp->dp_spa;2215int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;2216int err;22172218ASSERT(!BP_IS_REDACTED(bp));22192220/*2221* There is an unlikely case of encountering dnodes with contradicting2222* dn_bonuslen and DNODE_FLAG_SPILL_BLKPTR flag before in files created2223* or modified before commit 4254acb was merged. As it is not possible2224* to know which of the two is correct, report an error.2225*/2226if (dnp != NULL &&2227dnp->dn_bonuslen > DN_MAX_BONUS_LEN(dnp)) {2228scn->scn_phys.scn_errors++;2229spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));2230return (SET_ERROR(EINVAL));2231}22322233if (BP_GET_LEVEL(bp) > 0) {2234arc_flags_t flags = ARC_FLAG_WAIT;2235int i;2236blkptr_t *cbp;2237int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;2238arc_buf_t *buf;22392240err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2241ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2242if (err) {2243scn->scn_phys.scn_errors++;2244return (err);2245}2246for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {2247zbookmark_phys_t czb;22482249SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,2250zb->zb_level - 1,2251zb->zb_blkid * epb + i);2252dsl_scan_visitbp(cbp, &czb, dnp,2253ds, scn, ostype, tx);2254}2255arc_buf_destroy(buf, &buf);2256} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {2257arc_flags_t flags = ARC_FLAG_WAIT;2258dnode_phys_t *cdnp;2259int i;2260int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;2261arc_buf_t *buf;22622263if (BP_IS_PROTECTED(bp)) {2264ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);2265zio_flags |= ZIO_FLAG_RAW;2266}22672268err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2269ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2270if (err) {2271scn->scn_phys.scn_errors++;2272return (err);2273}2274for (i = 0, cdnp = buf->b_data; i < epb;2275i += cdnp->dn_extra_slots + 1,2276cdnp += cdnp->dn_extra_slots + 1) {2277dsl_scan_visitdnode(scn, ds, ostype,2278cdnp, zb->zb_blkid * epb + i, tx);2279}22802281arc_buf_destroy(buf, &buf);2282} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {2283arc_flags_t flags = ARC_FLAG_WAIT;2284objset_phys_t *osp;2285arc_buf_t *buf;22862287err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2288ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2289if (err) {2290scn->scn_phys.scn_errors++;2291return (err);2292}22932294osp = buf->b_data;22952296dsl_scan_visitdnode(scn, ds, osp->os_type,2297&osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);22982299if (OBJSET_BUF_HAS_USERUSED(buf)) {2300/*2301* We also always visit user/group/project accounting2302* objects, and never skip them, even if we are2303* suspending. This is necessary so that the2304* space deltas from this txg get integrated.2305*/2306if (OBJSET_BUF_HAS_PROJECTUSED(buf))2307dsl_scan_visitdnode(scn, ds, osp->os_type,2308&osp->os_projectused_dnode,2309DMU_PROJECTUSED_OBJECT, tx);2310dsl_scan_visitdnode(scn, ds, osp->os_type,2311&osp->os_groupused_dnode,2312DMU_GROUPUSED_OBJECT, tx);2313dsl_scan_visitdnode(scn, ds, osp->os_type,2314&osp->os_userused_dnode,2315DMU_USERUSED_OBJECT, tx);2316}2317arc_buf_destroy(buf, &buf);2318} else if (zfs_blkptr_verify(spa, bp,2319BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {2320/*2321* Sanity check the block pointer contents, this is handled2322* by arc_read() for the cases above.2323*/2324scn->scn_phys.scn_errors++;2325spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));2326return (SET_ERROR(EINVAL));2327}23282329return (0);2330}23312332inline __attribute__((always_inline)) static void2333dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,2334dmu_objset_type_t ostype, dnode_phys_t *dnp,2335uint64_t object, dmu_tx_t *tx)2336{2337int j;23382339for (j = 0; j < dnp->dn_nblkptr; j++) {2340zbookmark_phys_t czb;23412342SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,2343dnp->dn_nlevels - 1, j);2344dsl_scan_visitbp(&dnp->dn_blkptr[j],2345&czb, dnp, ds, scn, ostype, tx);2346}23472348if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {2349zbookmark_phys_t czb;2350SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,23510, DMU_SPILL_BLKID);2352dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),2353&czb, dnp, ds, scn, ostype, tx);2354}2355}23562357/*2358* The arguments are in this order because mdb can only print the2359* first 5; we want them to be useful.2360*/2361static void2362dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,2363dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,2364dmu_objset_type_t ostype, dmu_tx_t *tx)2365{2366dsl_pool_t *dp = scn->scn_dp;23672368if (dsl_scan_check_suspend(scn, zb))2369return;23702371if (dsl_scan_check_resume(scn, dnp, zb))2372return;23732374scn->scn_visited_this_txg++;23752376if (BP_IS_HOLE(bp)) {2377scn->scn_holes_this_txg++;2378return;2379}23802381if (BP_IS_REDACTED(bp)) {2382ASSERT(dsl_dataset_feature_is_active(ds,2383SPA_FEATURE_REDACTED_DATASETS));2384return;2385}23862387/*2388* Check if this block contradicts any filesystem flags.2389*/2390spa_feature_t f = SPA_FEATURE_LARGE_BLOCKS;2391if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE)2392ASSERT(dsl_dataset_feature_is_active(ds, f));23932394f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));2395if (f != SPA_FEATURE_NONE)2396ASSERT(dsl_dataset_feature_is_active(ds, f));23972398f = zio_compress_to_feature(BP_GET_COMPRESS(bp));2399if (f != SPA_FEATURE_NONE)2400ASSERT(dsl_dataset_feature_is_active(ds, f));24012402/*2403* Recurse any blocks that were written either logically or physically2404* at or after cur_min_txg. About logical birth we care for traversal,2405* looking for any changes, while about physical for the actual scan.2406*/2407if (BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg) {2408scn->scn_lt_min_this_txg++;2409return;2410}24112412if (dsl_scan_recurse(scn, ds, ostype, dnp, bp, zb, tx) != 0)2413return;24142415/*2416* If dsl_scan_ddt() has already visited this block, it will have2417* already done any translations or scrubbing, so don't call the2418* callback again.2419*/2420if (ddt_class_contains(dp->dp_spa,2421scn->scn_phys.scn_ddt_class_max, bp)) {2422scn->scn_ddt_contained_this_txg++;2423return;2424}24252426/*2427* If this block is from the future (after cur_max_txg), then we2428* are doing this on behalf of a deleted snapshot, and we will2429* revisit the future block on the next pass of this dataset.2430* Don't scan it now unless we need to because something2431* under it was modified.2432*/2433if (BP_GET_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {2434scn->scn_gt_max_this_txg++;2435return;2436}24372438scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);2439}24402441static void2442dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,2443dmu_tx_t *tx)2444{2445zbookmark_phys_t zb;2446scan_prefetch_ctx_t *spc;24472448SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,2449ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);24502451if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {2452SET_BOOKMARK(&scn->scn_prefetch_bookmark,2453zb.zb_objset, 0, 0, 0);2454} else {2455scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;2456}24572458scn->scn_objsets_visited_this_txg++;24592460spc = scan_prefetch_ctx_create(scn, NULL, FTAG);2461dsl_scan_prefetch(spc, bp, &zb);2462scan_prefetch_ctx_rele(spc, FTAG);24632464dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);24652466dprintf_ds(ds, "finished scan%s", "");2467}24682469static void2470ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)2471{2472if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {2473if (ds->ds_is_snapshot) {2474/*2475* Note:2476* - scn_cur_{min,max}_txg stays the same.2477* - Setting the flag is not really necessary if2478* scn_cur_max_txg == scn_max_txg, because there2479* is nothing after this snapshot that we care2480* about. However, we set it anyway and then2481* ignore it when we retraverse it in2482* dsl_scan_visitds().2483*/2484scn_phys->scn_bookmark.zb_objset =2485dsl_dataset_phys(ds)->ds_next_snap_obj;2486zfs_dbgmsg("destroying ds %llu on %s; currently "2487"traversing; reset zb_objset to %llu",2488(u_longlong_t)ds->ds_object,2489ds->ds_dir->dd_pool->dp_spa->spa_name,2490(u_longlong_t)dsl_dataset_phys(ds)->2491ds_next_snap_obj);2492scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;2493} else {2494SET_BOOKMARK(&scn_phys->scn_bookmark,2495ZB_DESTROYED_OBJSET, 0, 0, 0);2496zfs_dbgmsg("destroying ds %llu on %s; currently "2497"traversing; reset bookmark to -1,0,0,0",2498(u_longlong_t)ds->ds_object,2499ds->ds_dir->dd_pool->dp_spa->spa_name);2500}2501}2502}25032504/*2505* Invoked when a dataset is destroyed. We need to make sure that:2506*2507* 1) If it is the dataset that was currently being scanned, we write2508* a new dsl_scan_phys_t and marking the objset reference in it2509* as destroyed.2510* 2) Remove it from the work queue, if it was present.2511*2512* If the dataset was actually a snapshot, instead of marking the dataset2513* as destroyed, we instead substitute the next snapshot in line.2514*/2515void2516dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)2517{2518dsl_pool_t *dp = ds->ds_dir->dd_pool;2519dsl_scan_t *scn = dp->dp_scan;2520uint64_t mintxg;25212522if (!dsl_scan_is_running(scn))2523return;25242525ds_destroyed_scn_phys(ds, &scn->scn_phys);2526ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);25272528if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {2529scan_ds_queue_remove(scn, ds->ds_object);2530if (ds->ds_is_snapshot)2531scan_ds_queue_insert(scn,2532dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);2533}25342535if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,2536ds->ds_object, &mintxg) == 0) {2537ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);2538VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,2539scn->scn_phys.scn_queue_obj, ds->ds_object, tx));2540if (ds->ds_is_snapshot) {2541/*2542* We keep the same mintxg; it could be >2543* ds_creation_txg if the previous snapshot was2544* deleted too.2545*/2546VERIFY(zap_add_int_key(dp->dp_meta_objset,2547scn->scn_phys.scn_queue_obj,2548dsl_dataset_phys(ds)->ds_next_snap_obj,2549mintxg, tx) == 0);2550zfs_dbgmsg("destroying ds %llu on %s; in queue; "2551"replacing with %llu",2552(u_longlong_t)ds->ds_object,2553dp->dp_spa->spa_name,2554(u_longlong_t)dsl_dataset_phys(ds)->2555ds_next_snap_obj);2556} else {2557zfs_dbgmsg("destroying ds %llu on %s; in queue; "2558"removing",2559(u_longlong_t)ds->ds_object,2560dp->dp_spa->spa_name);2561}2562}25632564/*2565* dsl_scan_sync() should be called after this, and should sync2566* out our changed state, but just to be safe, do it here.2567*/2568dsl_scan_sync_state(scn, tx, SYNC_CACHED);2569}25702571static void2572ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)2573{2574if (scn_bookmark->zb_objset == ds->ds_object) {2575scn_bookmark->zb_objset =2576dsl_dataset_phys(ds)->ds_prev_snap_obj;2577zfs_dbgmsg("snapshotting ds %llu on %s; currently traversing; "2578"reset zb_objset to %llu",2579(u_longlong_t)ds->ds_object,2580ds->ds_dir->dd_pool->dp_spa->spa_name,2581(u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);2582}2583}25842585/*2586* Called when a dataset is snapshotted. If we were currently traversing2587* this snapshot, we reset our bookmark to point at the newly created2588* snapshot. We also modify our work queue to remove the old snapshot and2589* replace with the new one.2590*/2591void2592dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)2593{2594dsl_pool_t *dp = ds->ds_dir->dd_pool;2595dsl_scan_t *scn = dp->dp_scan;2596uint64_t mintxg;25972598if (!dsl_scan_is_running(scn))2599return;26002601ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);26022603ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);2604ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);26052606if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {2607scan_ds_queue_remove(scn, ds->ds_object);2608scan_ds_queue_insert(scn,2609dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);2610}26112612if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,2613ds->ds_object, &mintxg) == 0) {2614VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,2615scn->scn_phys.scn_queue_obj, ds->ds_object, tx));2616VERIFY(zap_add_int_key(dp->dp_meta_objset,2617scn->scn_phys.scn_queue_obj,2618dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);2619zfs_dbgmsg("snapshotting ds %llu on %s; in queue; "2620"replacing with %llu",2621(u_longlong_t)ds->ds_object,2622dp->dp_spa->spa_name,2623(u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);2624}26252626dsl_scan_sync_state(scn, tx, SYNC_CACHED);2627}26282629static void2630ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,2631zbookmark_phys_t *scn_bookmark)2632{2633if (scn_bookmark->zb_objset == ds1->ds_object) {2634scn_bookmark->zb_objset = ds2->ds_object;2635zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "2636"reset zb_objset to %llu",2637(u_longlong_t)ds1->ds_object,2638ds1->ds_dir->dd_pool->dp_spa->spa_name,2639(u_longlong_t)ds2->ds_object);2640} else if (scn_bookmark->zb_objset == ds2->ds_object) {2641scn_bookmark->zb_objset = ds1->ds_object;2642zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "2643"reset zb_objset to %llu",2644(u_longlong_t)ds2->ds_object,2645ds2->ds_dir->dd_pool->dp_spa->spa_name,2646(u_longlong_t)ds1->ds_object);2647}2648}26492650/*2651* Called when an origin dataset and its clone are swapped. If we were2652* currently traversing the dataset, we need to switch to traversing the2653* newly promoted clone.2654*/2655void2656dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)2657{2658dsl_pool_t *dp = ds1->ds_dir->dd_pool;2659dsl_scan_t *scn = dp->dp_scan;2660uint64_t mintxg1, mintxg2;2661boolean_t ds1_queued, ds2_queued;26622663if (!dsl_scan_is_running(scn))2664return;26652666ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);2667ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);26682669/*2670* Handle the in-memory scan queue.2671*/2672ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);2673ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);26742675/* Sanity checking. */2676if (ds1_queued) {2677ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2678ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2679}2680if (ds2_queued) {2681ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2682ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2683}26842685if (ds1_queued && ds2_queued) {2686/*2687* If both are queued, we don't need to do anything.2688* The swapping code below would not handle this case correctly,2689* since we can't insert ds2 if it is already there. That's2690* because scan_ds_queue_insert() prohibits a duplicate insert2691* and panics.2692*/2693} else if (ds1_queued) {2694scan_ds_queue_remove(scn, ds1->ds_object);2695scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);2696} else if (ds2_queued) {2697scan_ds_queue_remove(scn, ds2->ds_object);2698scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);2699}27002701/*2702* Handle the on-disk scan queue.2703* The on-disk state is an out-of-date version of the in-memory state,2704* so the in-memory and on-disk values for ds1_queued and ds2_queued may2705* be different. Therefore we need to apply the swap logic to the2706* on-disk state independently of the in-memory state.2707*/2708ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,2709scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;2710ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,2711scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;27122713/* Sanity checking. */2714if (ds1_queued) {2715ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2716ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2717}2718if (ds2_queued) {2719ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2720ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2721}27222723if (ds1_queued && ds2_queued) {2724/*2725* If both are queued, we don't need to do anything.2726* Alternatively, we could check for EEXIST from2727* zap_add_int_key() and back out to the original state, but2728* that would be more work than checking for this case upfront.2729*/2730} else if (ds1_queued) {2731VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,2732scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));2733VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,2734scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));2735zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "2736"replacing with %llu",2737(u_longlong_t)ds1->ds_object,2738dp->dp_spa->spa_name,2739(u_longlong_t)ds2->ds_object);2740} else if (ds2_queued) {2741VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,2742scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));2743VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,2744scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));2745zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "2746"replacing with %llu",2747(u_longlong_t)ds2->ds_object,2748dp->dp_spa->spa_name,2749(u_longlong_t)ds1->ds_object);2750}27512752dsl_scan_sync_state(scn, tx, SYNC_CACHED);2753}27542755static int2756enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)2757{2758uint64_t originobj = *(uint64_t *)arg;2759dsl_dataset_t *ds;2760int err;2761dsl_scan_t *scn = dp->dp_scan;27622763if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)2764return (0);27652766err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);2767if (err)2768return (err);27692770while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {2771dsl_dataset_t *prev;2772err = dsl_dataset_hold_obj(dp,2773dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);27742775dsl_dataset_rele(ds, FTAG);2776if (err)2777return (err);2778ds = prev;2779}2780mutex_enter(&scn->scn_queue_lock);2781scan_ds_queue_insert(scn, ds->ds_object,2782dsl_dataset_phys(ds)->ds_prev_snap_txg);2783mutex_exit(&scn->scn_queue_lock);2784dsl_dataset_rele(ds, FTAG);2785return (0);2786}27872788static void2789dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)2790{2791dsl_pool_t *dp = scn->scn_dp;2792dsl_dataset_t *ds;27932794VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));27952796if (scn->scn_phys.scn_cur_min_txg >=2797scn->scn_phys.scn_max_txg) {2798/*2799* This can happen if this snapshot was created after the2800* scan started, and we already completed a previous snapshot2801* that was created after the scan started. This snapshot2802* only references blocks with:2803*2804* birth < our ds_creation_txg2805* cur_min_txg is no less than ds_creation_txg.2806* We have already visited these blocks.2807* or2808* birth > scn_max_txg2809* The scan requested not to visit these blocks.2810*2811* Subsequent snapshots (and clones) can reference our2812* blocks, or blocks with even higher birth times.2813* Therefore we do not need to visit them either,2814* so we do not add them to the work queue.2815*2816* Note that checking for cur_min_txg >= cur_max_txg2817* is not sufficient, because in that case we may need to2818* visit subsequent snapshots. This happens when min_txg > 0,2819* which raises cur_min_txg. In this case we will visit2820* this dataset but skip all of its blocks, because the2821* rootbp's birth time is < cur_min_txg. Then we will2822* add the next snapshots/clones to the work queue.2823*/2824char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);2825dsl_dataset_name(ds, dsname);2826zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "2827"cur_min_txg (%llu) >= max_txg (%llu)",2828(longlong_t)dsobj, dsname,2829(longlong_t)scn->scn_phys.scn_cur_min_txg,2830(longlong_t)scn->scn_phys.scn_max_txg);2831kmem_free(dsname, MAXNAMELEN);28322833goto out;2834}28352836/*2837* Only the ZIL in the head (non-snapshot) is valid. Even though2838* snapshots can have ZIL block pointers (which may be the same2839* BP as in the head), they must be ignored. In addition, $ORIGIN2840* doesn't have a objset (i.e. its ds_bp is a hole) so we don't2841* need to look for a ZIL in it either. So we traverse the ZIL here,2842* rather than in scan_recurse(), because the regular snapshot2843* block-sharing rules don't apply to it.2844*/2845if (!dsl_dataset_is_snapshot(ds) &&2846(dp->dp_origin_snap == NULL ||2847ds->ds_dir != dp->dp_origin_snap->ds_dir)) {2848objset_t *os;2849if (dmu_objset_from_ds(ds, &os) != 0) {2850goto out;2851}2852dsl_scan_zil(dp, &os->os_zil_header);2853}28542855/*2856* Iterate over the bps in this ds.2857*/2858dmu_buf_will_dirty(ds->ds_dbuf, tx);2859rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);2860dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);2861rrw_exit(&ds->ds_bp_rwlock, FTAG);28622863char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);2864dsl_dataset_name(ds, dsname);2865zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "2866"suspending=%u",2867(longlong_t)dsobj, dsname,2868(longlong_t)scn->scn_phys.scn_cur_min_txg,2869(longlong_t)scn->scn_phys.scn_cur_max_txg,2870(int)scn->scn_suspending);2871kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);28722873if (scn->scn_suspending)2874goto out;28752876/*2877* We've finished this pass over this dataset.2878*/28792880/*2881* If we did not completely visit this dataset, do another pass.2882*/2883if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {2884zfs_dbgmsg("incomplete pass on %s; visiting again",2885dp->dp_spa->spa_name);2886scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;2887scan_ds_queue_insert(scn, ds->ds_object,2888scn->scn_phys.scn_cur_max_txg);2889goto out;2890}28912892/*2893* Add descendant datasets to work queue.2894*/2895if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {2896scan_ds_queue_insert(scn,2897dsl_dataset_phys(ds)->ds_next_snap_obj,2898dsl_dataset_phys(ds)->ds_creation_txg);2899}2900if (dsl_dataset_phys(ds)->ds_num_children > 1) {2901boolean_t usenext = B_FALSE;2902if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {2903uint64_t count;2904/*2905* A bug in a previous version of the code could2906* cause upgrade_clones_cb() to not set2907* ds_next_snap_obj when it should, leading to a2908* missing entry. Therefore we can only use the2909* next_clones_obj when its count is correct.2910*/2911int err = zap_count(dp->dp_meta_objset,2912dsl_dataset_phys(ds)->ds_next_clones_obj, &count);2913if (err == 0 &&2914count == dsl_dataset_phys(ds)->ds_num_children - 1)2915usenext = B_TRUE;2916}29172918if (usenext) {2919zap_cursor_t zc;2920zap_attribute_t *za = zap_attribute_alloc();2921for (zap_cursor_init(&zc, dp->dp_meta_objset,2922dsl_dataset_phys(ds)->ds_next_clones_obj);2923zap_cursor_retrieve(&zc, za) == 0;2924(void) zap_cursor_advance(&zc)) {2925scan_ds_queue_insert(scn,2926zfs_strtonum(za->za_name, NULL),2927dsl_dataset_phys(ds)->ds_creation_txg);2928}2929zap_cursor_fini(&zc);2930zap_attribute_free(za);2931} else {2932VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,2933enqueue_clones_cb, &ds->ds_object,2934DS_FIND_CHILDREN));2935}2936}29372938out:2939dsl_dataset_rele(ds, FTAG);2940}29412942static int2943enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)2944{2945(void) arg;2946dsl_dataset_t *ds;2947int err;2948dsl_scan_t *scn = dp->dp_scan;29492950err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);2951if (err)2952return (err);29532954while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {2955dsl_dataset_t *prev;2956err = dsl_dataset_hold_obj(dp,2957dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);2958if (err) {2959dsl_dataset_rele(ds, FTAG);2960return (err);2961}29622963/*2964* If this is a clone, we don't need to worry about it for now.2965*/2966if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {2967dsl_dataset_rele(ds, FTAG);2968dsl_dataset_rele(prev, FTAG);2969return (0);2970}2971dsl_dataset_rele(ds, FTAG);2972ds = prev;2973}29742975mutex_enter(&scn->scn_queue_lock);2976scan_ds_queue_insert(scn, ds->ds_object,2977dsl_dataset_phys(ds)->ds_prev_snap_txg);2978mutex_exit(&scn->scn_queue_lock);2979dsl_dataset_rele(ds, FTAG);2980return (0);2981}29822983void2984dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,2985ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)2986{2987(void) tx;2988const ddt_key_t *ddk = &ddlwe->ddlwe_key;2989blkptr_t bp;2990zbookmark_phys_t zb = { 0 };29912992if (!dsl_scan_is_running(scn))2993return;29942995/*2996* This function is special because it is the only thing2997* that can add scan_io_t's to the vdev scan queues from2998* outside dsl_scan_sync(). For the most part this is ok2999* as long as it is called from within syncing context.3000* However, dsl_scan_sync() expects that no new sio's will3001* be added between when all the work for a scan is done3002* and the next txg when the scan is actually marked as3003* completed. This check ensures we do not issue new sio's3004* during this period.3005*/3006if (scn->scn_done_txg != 0)3007return;30083009for (int p = 0; p < DDT_NPHYS(ddt); p++) {3010ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);3011uint64_t phys_birth = ddt_phys_birth(&ddlwe->ddlwe_phys, v);30123013if (phys_birth == 0 || phys_birth > scn->scn_phys.scn_max_txg)3014continue;3015ddt_bp_create(checksum, ddk, &ddlwe->ddlwe_phys, v, &bp);30163017scn->scn_visited_this_txg++;3018scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);3019}3020}30213022/*3023* Scrub/dedup interaction.3024*3025* If there are N references to a deduped block, we don't want to scrub it3026* N times -- ideally, we should scrub it exactly once.3027*3028* We leverage the fact that the dde's replication class (ddt_class_t)3029* is ordered from highest replication class (DDT_CLASS_DITTO) to lowest3030* (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.3031*3032* To prevent excess scrubbing, the scrub begins by walking the DDT3033* to find all blocks with refcnt > 1, and scrubs each of these once.3034* Since there are two replication classes which contain blocks with3035* refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.3036* Finally the top-down scrub begins, only visiting blocks with refcnt == 1.3037*3038* There would be nothing more to say if a block's refcnt couldn't change3039* during a scrub, but of course it can so we must account for changes3040* in a block's replication class.3041*3042* Here's an example of what can occur:3043*3044* If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 13045* when visited during the top-down scrub phase, it will be scrubbed twice.3046* This negates our scrub optimization, but is otherwise harmless.3047*3048* If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 13049* on each visit during the top-down scrub phase, it will never be scrubbed.3050* To catch this, ddt_sync_entry() notifies the scrub code whenever a block's3051* reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to3052* DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 13053* while a scrub is in progress, it scrubs the block right then.3054*/3055static void3056dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)3057{3058ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;3059ddt_lightweight_entry_t ddlwe = {0};3060int error;3061uint64_t n = 0;30623063while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &ddlwe)) == 0) {3064ddt_t *ddt;30653066if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)3067break;3068dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",3069(longlong_t)ddb->ddb_class,3070(longlong_t)ddb->ddb_type,3071(longlong_t)ddb->ddb_checksum,3072(longlong_t)ddb->ddb_cursor);30733074/* There should be no pending changes to the dedup table */3075ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];3076ASSERT(avl_first(&ddt->ddt_tree) == NULL);30773078dsl_scan_ddt_entry(scn, ddb->ddb_checksum, ddt, &ddlwe, tx);3079n++;30803081if (dsl_scan_check_suspend(scn, NULL))3082break;3083}30843085if (error == EAGAIN) {3086dsl_scan_check_suspend(scn, NULL);3087error = 0;30883089zfs_dbgmsg("waiting for ddt to become ready for scan "3090"on %s with class_max = %u; suspending=%u",3091scn->scn_dp->dp_spa->spa_name,3092(int)scn->scn_phys.scn_ddt_class_max,3093(int)scn->scn_suspending);3094} else3095zfs_dbgmsg("scanned %llu ddt entries on %s with "3096"class_max = %u; suspending=%u", (longlong_t)n,3097scn->scn_dp->dp_spa->spa_name,3098(int)scn->scn_phys.scn_ddt_class_max,3099(int)scn->scn_suspending);31003101ASSERT(error == 0 || error == ENOENT);3102ASSERT(error != ENOENT ||3103ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);3104}31053106static uint64_t3107dsl_scan_ds_maxtxg(dsl_dataset_t *ds)3108{3109uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;3110if (ds->ds_is_snapshot)3111return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));3112return (smt);3113}31143115static void3116dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)3117{3118scan_ds_t *sds;3119dsl_pool_t *dp = scn->scn_dp;31203121if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=3122scn->scn_phys.scn_ddt_class_max) {3123scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;3124scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;3125dsl_scan_ddt(scn, tx);3126if (scn->scn_suspending)3127return;3128}31293130if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {3131/* First do the MOS & ORIGIN */31323133scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;3134scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;3135dsl_scan_visit_rootbp(scn, NULL,3136&dp->dp_meta_rootbp, tx);3137if (scn->scn_suspending)3138return;31393140if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {3141VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,3142enqueue_cb, NULL, DS_FIND_CHILDREN));3143} else {3144dsl_scan_visitds(scn,3145dp->dp_origin_snap->ds_object, tx);3146}3147ASSERT(!scn->scn_suspending);3148} else if (scn->scn_phys.scn_bookmark.zb_objset !=3149ZB_DESTROYED_OBJSET) {3150uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;3151/*3152* If we were suspended, continue from here. Note if the3153* ds we were suspended on was deleted, the zb_objset may3154* be -1, so we will skip this and find a new objset3155* below.3156*/3157dsl_scan_visitds(scn, dsobj, tx);3158if (scn->scn_suspending)3159return;3160}31613162/*3163* In case we suspended right at the end of the ds, zero the3164* bookmark so we don't think that we're still trying to resume.3165*/3166memset(&scn->scn_phys.scn_bookmark, 0, sizeof (zbookmark_phys_t));31673168/*3169* Keep pulling things out of the dataset avl queue. Updates to the3170* persistent zap-object-as-queue happen only at checkpoints.3171*/3172while ((sds = avl_first(&scn->scn_queue)) != NULL) {3173dsl_dataset_t *ds;3174uint64_t dsobj = sds->sds_dsobj;3175uint64_t txg = sds->sds_txg;31763177/* dequeue and free the ds from the queue */3178scan_ds_queue_remove(scn, dsobj);3179sds = NULL;31803181/* set up min / max txg */3182VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));3183if (txg != 0) {3184scn->scn_phys.scn_cur_min_txg =3185MAX(scn->scn_phys.scn_min_txg, txg);3186} else {3187scn->scn_phys.scn_cur_min_txg =3188MAX(scn->scn_phys.scn_min_txg,3189dsl_dataset_phys(ds)->ds_prev_snap_txg);3190}3191scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);3192dsl_dataset_rele(ds, FTAG);31933194dsl_scan_visitds(scn, dsobj, tx);3195if (scn->scn_suspending)3196return;3197}31983199/* No more objsets to fetch, we're done */3200scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;3201ASSERT0(scn->scn_suspending);3202}32033204static uint64_t3205dsl_scan_count_data_disks(spa_t *spa)3206{3207vdev_t *rvd = spa->spa_root_vdev;3208uint64_t i, leaves = 0;32093210for (i = 0; i < rvd->vdev_children; i++) {3211vdev_t *vd = rvd->vdev_child[i];3212if (vd->vdev_islog || vd->vdev_isspare || vd->vdev_isl2cache)3213continue;3214leaves += vdev_get_ndisks(vd) - vdev_get_nparity(vd);3215}3216return (leaves);3217}32183219static void3220scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)3221{3222int i;3223uint64_t cur_size = 0;32243225for (i = 0; i < BP_GET_NDVAS(bp); i++) {3226cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);3227}32283229q->q_total_zio_size_this_txg += cur_size;3230q->q_zios_this_txg++;3231}32323233static void3234scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,3235uint64_t end)3236{3237q->q_total_seg_size_this_txg += end - start;3238q->q_segs_this_txg++;3239}32403241static boolean_t3242scan_io_queue_check_suspend(dsl_scan_t *scn)3243{3244/* See comment in dsl_scan_check_suspend() */3245uint64_t curr_time_ns = getlrtime();3246uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;3247uint64_t sync_time_ns = curr_time_ns -3248scn->scn_dp->dp_spa->spa_sync_starttime;3249uint64_t dirty_min_bytes = zfs_dirty_data_max *3250zfs_vdev_async_write_active_min_dirty_percent / 100;3251uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?3252zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;32533254return ((NSEC2MSEC(scan_time_ns) > mintime &&3255(scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||3256txg_sync_waiting(scn->scn_dp) ||3257NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||3258spa_shutting_down(scn->scn_dp->dp_spa));3259}32603261/*3262* Given a list of scan_io_t's in io_list, this issues the I/Os out to3263* disk. This consumes the io_list and frees the scan_io_t's. This is3264* called when emptying queues, either when we're up against the memory3265* limit or when we have finished scanning. Returns B_TRUE if we stopped3266* processing the list before we finished. Any sios that were not issued3267* will remain in the io_list.3268*/3269static boolean_t3270scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)3271{3272dsl_scan_t *scn = queue->q_scn;3273scan_io_t *sio;3274boolean_t suspended = B_FALSE;32753276while ((sio = list_head(io_list)) != NULL) {3277blkptr_t bp;32783279if (scan_io_queue_check_suspend(scn)) {3280suspended = B_TRUE;3281break;3282}32833284sio2bp(sio, &bp);3285scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,3286&sio->sio_zb, queue);3287(void) list_remove_head(io_list);3288scan_io_queues_update_zio_stats(queue, &bp);3289sio_free(sio);3290}3291return (suspended);3292}32933294/*3295* This function removes sios from an IO queue which reside within a given3296* zfs_range_seg_t and inserts them (in offset order) into a list. Note that3297* we only ever return a maximum of 32 sios at once. If there are more sios3298* to process within this segment that did not make it onto the list we3299* return B_TRUE and otherwise B_FALSE.3300*/3301static boolean_t3302scan_io_queue_gather(dsl_scan_io_queue_t *queue, zfs_range_seg_t *rs,3303list_t *list)3304{3305scan_io_t *srch_sio, *sio, *next_sio;3306avl_index_t idx;3307uint_t num_sios = 0;3308int64_t bytes_issued = 0;33093310ASSERT(rs != NULL);3311ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));33123313srch_sio = sio_alloc(1);3314srch_sio->sio_nr_dvas = 1;3315SIO_SET_OFFSET(srch_sio, zfs_rs_get_start(rs, queue->q_exts_by_addr));33163317/*3318* The exact start of the extent might not contain any matching zios,3319* so if that's the case, examine the next one in the tree.3320*/3321sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);3322sio_free(srch_sio);33233324if (sio == NULL)3325sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);33263327while (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,3328queue->q_exts_by_addr) && num_sios <= 32) {3329ASSERT3U(SIO_GET_OFFSET(sio), >=, zfs_rs_get_start(rs,3330queue->q_exts_by_addr));3331ASSERT3U(SIO_GET_END_OFFSET(sio), <=, zfs_rs_get_end(rs,3332queue->q_exts_by_addr));33333334next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);3335avl_remove(&queue->q_sios_by_addr, sio);3336if (avl_is_empty(&queue->q_sios_by_addr))3337atomic_add_64(&queue->q_scn->scn_queues_pending, -1);3338queue->q_sio_memused -= SIO_GET_MUSED(sio);33393340bytes_issued += SIO_GET_ASIZE(sio);3341num_sios++;3342list_insert_tail(list, sio);3343sio = next_sio;3344}33453346/*3347* We limit the number of sios we process at once to 32 to avoid3348* biting off more than we can chew. If we didn't take everything3349* in the segment we update it to reflect the work we were able to3350* complete. Otherwise, we remove it from the range tree entirely.3351*/3352if (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,3353queue->q_exts_by_addr)) {3354zfs_range_tree_adjust_fill(queue->q_exts_by_addr, rs,3355-bytes_issued);3356zfs_range_tree_resize_segment(queue->q_exts_by_addr, rs,3357SIO_GET_OFFSET(sio), zfs_rs_get_end(rs,3358queue->q_exts_by_addr) - SIO_GET_OFFSET(sio));3359queue->q_last_ext_addr = SIO_GET_OFFSET(sio);3360return (B_TRUE);3361} else {3362uint64_t rstart = zfs_rs_get_start(rs, queue->q_exts_by_addr);3363uint64_t rend = zfs_rs_get_end(rs, queue->q_exts_by_addr);3364zfs_range_tree_remove(queue->q_exts_by_addr, rstart, rend -3365rstart);3366queue->q_last_ext_addr = -1;3367return (B_FALSE);3368}3369}33703371/*3372* This is called from the queue emptying thread and selects the next3373* extent from which we are to issue I/Os. The behavior of this function3374* depends on the state of the scan, the current memory consumption and3375* whether or not we are performing a scan shutdown.3376* 1) We select extents in an elevator algorithm (LBA-order) if the scan3377* needs to perform a checkpoint3378* 2) We select the largest available extent if we are up against the3379* memory limit.3380* 3) Otherwise we don't select any extents.3381*/3382static zfs_range_seg_t *3383scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)3384{3385dsl_scan_t *scn = queue->q_scn;3386zfs_range_tree_t *rt = queue->q_exts_by_addr;33873388ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));3389ASSERT(scn->scn_is_sorted);33903391if (!scn->scn_checkpointing && !scn->scn_clearing)3392return (NULL);33933394/*3395* During normal clearing, we want to issue our largest segments3396* first, keeping IO as sequential as possible, and leaving the3397* smaller extents for later with the hope that they might eventually3398* grow to larger sequential segments. However, when the scan is3399* checkpointing, no new extents will be added to the sorting queue,3400* so the way we are sorted now is as good as it will ever get.3401* In this case, we instead switch to issuing extents in LBA order.3402*/3403if ((zfs_scan_issue_strategy < 1 && scn->scn_checkpointing) ||3404zfs_scan_issue_strategy == 1)3405return (zfs_range_tree_first(rt));34063407/*3408* Try to continue previous extent if it is not completed yet. After3409* shrink in scan_io_queue_gather() it may no longer be the best, but3410* otherwise we leave shorter remnant every txg.3411*/3412uint64_t start;3413uint64_t size = 1ULL << rt->rt_shift;3414zfs_range_seg_t *addr_rs;3415if (queue->q_last_ext_addr != -1) {3416start = queue->q_last_ext_addr;3417addr_rs = zfs_range_tree_find(rt, start, size);3418if (addr_rs != NULL)3419return (addr_rs);3420}34213422/*3423* Nothing to continue, so find new best extent.3424*/3425uint64_t *v = zfs_btree_first(&queue->q_exts_by_size, NULL);3426if (v == NULL)3427return (NULL);3428queue->q_last_ext_addr = start = *v << rt->rt_shift;34293430/*3431* We need to get the original entry in the by_addr tree so we can3432* modify it.3433*/3434addr_rs = zfs_range_tree_find(rt, start, size);3435ASSERT3P(addr_rs, !=, NULL);3436ASSERT3U(zfs_rs_get_start(addr_rs, rt), ==, start);3437ASSERT3U(zfs_rs_get_end(addr_rs, rt), >, start);3438return (addr_rs);3439}34403441static void3442scan_io_queues_run_one(void *arg)3443{3444dsl_scan_io_queue_t *queue = arg;3445kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;3446boolean_t suspended = B_FALSE;3447zfs_range_seg_t *rs;3448scan_io_t *sio;3449zio_t *zio;3450list_t sio_list;34513452ASSERT(queue->q_scn->scn_is_sorted);34533454list_create(&sio_list, sizeof (scan_io_t),3455offsetof(scan_io_t, sio_nodes.sio_list_node));3456zio = zio_null(queue->q_scn->scn_zio_root, queue->q_scn->scn_dp->dp_spa,3457NULL, NULL, NULL, ZIO_FLAG_CANFAIL);3458mutex_enter(q_lock);3459queue->q_zio = zio;34603461/* Calculate maximum in-flight bytes for this vdev. */3462queue->q_maxinflight_bytes = MAX(1, zfs_scan_vdev_limit *3463(vdev_get_ndisks(queue->q_vd) - vdev_get_nparity(queue->q_vd)));34643465/* reset per-queue scan statistics for this txg */3466queue->q_total_seg_size_this_txg = 0;3467queue->q_segs_this_txg = 0;3468queue->q_total_zio_size_this_txg = 0;3469queue->q_zios_this_txg = 0;34703471/* loop until we run out of time or sios */3472while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {3473uint64_t seg_start = 0, seg_end = 0;3474boolean_t more_left;34753476ASSERT(list_is_empty(&sio_list));34773478/* loop while we still have sios left to process in this rs */3479do {3480scan_io_t *first_sio, *last_sio;34813482/*3483* We have selected which extent needs to be3484* processed next. Gather up the corresponding sios.3485*/3486more_left = scan_io_queue_gather(queue, rs, &sio_list);3487ASSERT(!list_is_empty(&sio_list));3488first_sio = list_head(&sio_list);3489last_sio = list_tail(&sio_list);34903491seg_end = SIO_GET_END_OFFSET(last_sio);3492if (seg_start == 0)3493seg_start = SIO_GET_OFFSET(first_sio);34943495/*3496* Issuing sios can take a long time so drop the3497* queue lock. The sio queue won't be updated by3498* other threads since we're in syncing context so3499* we can be sure that our trees will remain exactly3500* as we left them.3501*/3502mutex_exit(q_lock);3503suspended = scan_io_queue_issue(queue, &sio_list);3504mutex_enter(q_lock);35053506if (suspended)3507break;3508} while (more_left);35093510/* update statistics for debugging purposes */3511scan_io_queues_update_seg_stats(queue, seg_start, seg_end);35123513if (suspended)3514break;3515}35163517/*3518* If we were suspended in the middle of processing,3519* requeue any unfinished sios and exit.3520*/3521while ((sio = list_remove_head(&sio_list)) != NULL)3522scan_io_queue_insert_impl(queue, sio);35233524queue->q_zio = NULL;3525mutex_exit(q_lock);3526zio_nowait(zio);3527list_destroy(&sio_list);3528}35293530/*3531* Performs an emptying run on all scan queues in the pool. This just3532* punches out one thread per top-level vdev, each of which processes3533* only that vdev's scan queue. We can parallelize the I/O here because3534* we know that each queue's I/Os only affect its own top-level vdev.3535*3536* This function waits for the queue runs to complete, and must be3537* called from dsl_scan_sync (or in general, syncing context).3538*/3539static void3540scan_io_queues_run(dsl_scan_t *scn)3541{3542spa_t *spa = scn->scn_dp->dp_spa;35433544ASSERT(scn->scn_is_sorted);3545ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));35463547if (scn->scn_queues_pending == 0)3548return;35493550if (scn->scn_taskq == NULL) {3551int nthreads = spa->spa_root_vdev->vdev_children;35523553/*3554* We need to make this taskq *always* execute as many3555* threads in parallel as we have top-level vdevs and no3556* less, otherwise strange serialization of the calls to3557* scan_io_queues_run_one can occur during spa_sync runs3558* and that significantly impacts performance.3559*/3560scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,3561minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);3562}35633564for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {3565vdev_t *vd = spa->spa_root_vdev->vdev_child[i];35663567mutex_enter(&vd->vdev_scan_io_queue_lock);3568if (vd->vdev_scan_io_queue != NULL) {3569VERIFY(taskq_dispatch(scn->scn_taskq,3570scan_io_queues_run_one, vd->vdev_scan_io_queue,3571TQ_SLEEP) != TASKQID_INVALID);3572}3573mutex_exit(&vd->vdev_scan_io_queue_lock);3574}35753576/*3577* Wait for the queues to finish issuing their IOs for this run3578* before we return. There may still be IOs in flight at this3579* point.3580*/3581taskq_wait(scn->scn_taskq);3582}35833584static boolean_t3585dsl_scan_async_block_should_pause(dsl_scan_t *scn)3586{3587uint64_t elapsed_nanosecs;35883589if (zfs_recover)3590return (B_FALSE);35913592if (zfs_async_block_max_blocks != 0 &&3593scn->scn_visited_this_txg >= zfs_async_block_max_blocks) {3594return (B_TRUE);3595}35963597if (zfs_max_async_dedup_frees != 0 &&3598scn->scn_async_frees_this_txg >= zfs_max_async_dedup_frees) {3599return (B_TRUE);3600}36013602elapsed_nanosecs = getlrtime() - scn->scn_sync_start_time;3603return (elapsed_nanosecs / (NANOSEC / 2) > zfs_txg_timeout ||3604(NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&3605txg_sync_waiting(scn->scn_dp)) ||3606spa_shutting_down(scn->scn_dp->dp_spa));3607}36083609static int3610dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)3611{3612dsl_scan_t *scn = arg;36133614if (!scn->scn_is_bptree ||3615(BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {3616if (dsl_scan_async_block_should_pause(scn))3617return (SET_ERROR(ERESTART));3618}36193620zio_t *zio = zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,3621dmu_tx_get_txg(tx), bp, 0);3622dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,3623-bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),3624-BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);3625scn->scn_visited_this_txg++;3626if (zio != NULL) {3627/*3628* zio_free_sync() returned a ZIO, meaning this is an3629* async I/O (dedup, clone or gang block).3630*/3631scn->scn_async_frees_this_txg++;3632zio_nowait(zio);36333634/*3635* After issuing N async ZIOs, wait for them to complete.3636* This makes time limits work with actual I/O completion3637* times, not just queuing times.3638*/3639uint64_t i = zfs_async_free_zio_wait_interval;3640if (i != 0 && (scn->scn_async_frees_this_txg % i) == 0) {3641VERIFY0(zio_wait(scn->scn_zio_root));3642scn->scn_zio_root = zio_root(scn->scn_dp->dp_spa, NULL,3643NULL, ZIO_FLAG_MUSTSUCCEED);3644}3645}3646return (0);3647}36483649static void3650dsl_scan_update_stats(dsl_scan_t *scn)3651{3652spa_t *spa = scn->scn_dp->dp_spa;3653uint64_t i;3654uint64_t seg_size_total = 0, zio_size_total = 0;3655uint64_t seg_count_total = 0, zio_count_total = 0;36563657for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {3658vdev_t *vd = spa->spa_root_vdev->vdev_child[i];3659dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;36603661if (queue == NULL)3662continue;36633664seg_size_total += queue->q_total_seg_size_this_txg;3665zio_size_total += queue->q_total_zio_size_this_txg;3666seg_count_total += queue->q_segs_this_txg;3667zio_count_total += queue->q_zios_this_txg;3668}36693670if (seg_count_total == 0 || zio_count_total == 0) {3671scn->scn_avg_seg_size_this_txg = 0;3672scn->scn_avg_zio_size_this_txg = 0;3673scn->scn_segs_this_txg = 0;3674scn->scn_zios_this_txg = 0;3675return;3676}36773678scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;3679scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;3680scn->scn_segs_this_txg = seg_count_total;3681scn->scn_zios_this_txg = zio_count_total;3682}36833684static int3685bpobj_dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,3686dmu_tx_t *tx)3687{3688ASSERT(!bp_freed);3689return (dsl_scan_free_block_cb(arg, bp, tx));3690}36913692static int3693dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,3694dmu_tx_t *tx)3695{3696ASSERT(!bp_freed);3697dsl_scan_t *scn = arg;3698const dva_t *dva = &bp->blk_dva[0];36993700if (dsl_scan_async_block_should_pause(scn))3701return (SET_ERROR(ERESTART));37023703spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,3704DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),3705DVA_GET_ASIZE(dva), tx);3706scn->scn_visited_this_txg++;3707return (0);3708}37093710boolean_t3711dsl_scan_active(dsl_scan_t *scn)3712{3713spa_t *spa = scn->scn_dp->dp_spa;3714uint64_t used = 0, comp, uncomp;3715boolean_t clones_left;37163717if (spa->spa_load_state != SPA_LOAD_NONE)3718return (B_FALSE);3719if (spa_shutting_down(spa))3720return (B_FALSE);3721if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||3722(scn->scn_async_destroying && !scn->scn_async_stalled))3723return (B_TRUE);37243725if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {3726(void) bpobj_space(&scn->scn_dp->dp_free_bpobj,3727&used, &comp, &uncomp);3728}3729clones_left = spa_livelist_delete_check(spa);3730return ((used != 0) || (clones_left));3731}37323733boolean_t3734dsl_errorscrub_active(dsl_scan_t *scn)3735{3736spa_t *spa = scn->scn_dp->dp_spa;3737if (spa->spa_load_state != SPA_LOAD_NONE)3738return (B_FALSE);3739if (spa_shutting_down(spa))3740return (B_FALSE);3741if (dsl_errorscrubbing(scn->scn_dp))3742return (B_TRUE);3743return (B_FALSE);3744}37453746static boolean_t3747dsl_scan_check_deferred(vdev_t *vd)3748{3749boolean_t need_resilver = B_FALSE;37503751for (int c = 0; c < vd->vdev_children; c++) {3752need_resilver |=3753dsl_scan_check_deferred(vd->vdev_child[c]);3754}37553756if (!vdev_is_concrete(vd) || vd->vdev_aux ||3757!vd->vdev_ops->vdev_op_leaf)3758return (need_resilver);37593760if (!vd->vdev_resilver_deferred)3761need_resilver = B_TRUE;37623763return (need_resilver);3764}37653766static boolean_t3767dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,3768uint64_t phys_birth)3769{3770vdev_t *vd;37713772vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));37733774if (vd->vdev_ops == &vdev_indirect_ops) {3775/*3776* The indirect vdev can point to multiple3777* vdevs. For simplicity, always create3778* the resilver zio_t. zio_vdev_io_start()3779* will bypass the child resilver i/o's if3780* they are on vdevs that don't have DTL's.3781*/3782return (B_TRUE);3783}37843785if (DVA_GET_GANG(dva)) {3786/*3787* Gang members may be spread across multiple3788* vdevs, so the best estimate we have is the3789* scrub range, which has already been checked.3790* XXX -- it would be better to change our3791* allocation policy to ensure that all3792* gang members reside on the same vdev.3793*/3794return (B_TRUE);3795}37963797/*3798* Check if the top-level vdev must resilver this offset.3799* When the offset does not intersect with a dirty leaf DTL3800* then it may be possible to skip the resilver IO. The psize3801* is provided instead of asize to simplify the check for RAIDZ.3802*/3803if (!vdev_dtl_need_resilver(vd, dva, psize, phys_birth))3804return (B_FALSE);38053806/*3807* Check that this top-level vdev has a device under it which3808* is resilvering and is not deferred.3809*/3810if (!dsl_scan_check_deferred(vd))3811return (B_FALSE);38123813return (B_TRUE);3814}38153816static int3817dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)3818{3819dsl_scan_t *scn = dp->dp_scan;3820spa_t *spa = dp->dp_spa;3821int err = 0;38223823if (spa_suspend_async_destroy(spa))3824return (0);38253826if (zfs_free_bpobj_enabled &&3827spa_version(spa) >= SPA_VERSION_DEADLISTS) {3828scn->scn_is_bptree = B_FALSE;3829scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;3830scn->scn_zio_root = zio_root(spa, NULL,3831NULL, ZIO_FLAG_MUSTSUCCEED);3832err = bpobj_iterate(&dp->dp_free_bpobj,3833bpobj_dsl_scan_free_block_cb, scn, tx);3834VERIFY0(zio_wait(scn->scn_zio_root));3835scn->scn_zio_root = NULL;38363837if (err != 0 && err != ERESTART)3838zfs_panic_recover("error %u from bpobj_iterate()", err);3839}38403841if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {3842ASSERT(scn->scn_async_destroying);3843scn->scn_is_bptree = B_TRUE;3844scn->scn_zio_root = zio_root(spa, NULL,3845NULL, ZIO_FLAG_MUSTSUCCEED);3846err = bptree_iterate(dp->dp_meta_objset,3847dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);3848VERIFY0(zio_wait(scn->scn_zio_root));3849scn->scn_zio_root = NULL;38503851if (err == EIO || err == ECKSUM) {3852err = 0;3853} else if (err != 0 && err != ERESTART) {3854zfs_panic_recover("error %u from "3855"traverse_dataset_destroyed()", err);3856}38573858if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {3859/* finished; deactivate async destroy feature */3860spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);3861ASSERT(!spa_feature_is_active(spa,3862SPA_FEATURE_ASYNC_DESTROY));3863VERIFY0(zap_remove(dp->dp_meta_objset,3864DMU_POOL_DIRECTORY_OBJECT,3865DMU_POOL_BPTREE_OBJ, tx));3866VERIFY0(bptree_free(dp->dp_meta_objset,3867dp->dp_bptree_obj, tx));3868dp->dp_bptree_obj = 0;3869scn->scn_async_destroying = B_FALSE;3870scn->scn_async_stalled = B_FALSE;3871} else {3872/*3873* If we didn't make progress, mark the async3874* destroy as stalled, so that we will not initiate3875* a spa_sync() on its behalf. Note that we only3876* check this if we are not finished, because if the3877* bptree had no blocks for us to visit, we can3878* finish without "making progress".3879*/3880scn->scn_async_stalled =3881(scn->scn_visited_this_txg == 0);3882}3883}3884if (scn->scn_visited_this_txg) {3885zfs_dbgmsg("freed %llu blocks in %llums from "3886"free_bpobj/bptree on %s in txg %llu; err=%u",3887(longlong_t)scn->scn_visited_this_txg,3888(longlong_t)3889NSEC2MSEC(getlrtime() - scn->scn_sync_start_time),3890spa->spa_name, (longlong_t)tx->tx_txg, err);3891scn->scn_visited_this_txg = 0;3892scn->scn_async_frees_this_txg = 0;38933894/*3895* Write out changes to the DDT and the BRT that may be required3896* as a result of the blocks freed. This ensures that the DDT3897* and the BRT are clean when a scrub/resilver runs.3898*/3899ddt_sync(spa, tx->tx_txg);3900brt_sync(spa, tx->tx_txg);3901}3902if (err != 0)3903return (err);3904if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&3905zfs_free_leak_on_eio &&3906(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||3907dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||3908dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {3909/*3910* We have finished background destroying, but there is still3911* some space left in the dp_free_dir. Transfer this leaked3912* space to the dp_leak_dir.3913*/3914if (dp->dp_leak_dir == NULL) {3915rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);3916(void) dsl_dir_create_sync(dp, dp->dp_root_dir,3917LEAK_DIR_NAME, tx);3918VERIFY0(dsl_pool_open_special_dir(dp,3919LEAK_DIR_NAME, &dp->dp_leak_dir));3920rrw_exit(&dp->dp_config_rwlock, FTAG);3921}3922dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,3923dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,3924dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,3925dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);3926dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,3927-dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,3928-dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,3929-dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);3930}39313932if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&3933!spa_livelist_delete_check(spa)) {3934/* finished; verify that space accounting went to zero */3935ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);3936ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);3937ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);3938}39393940spa_notify_waiters(spa);39413942EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),39430 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,3944DMU_POOL_OBSOLETE_BPOBJ));3945if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {3946ASSERT(spa_feature_is_active(dp->dp_spa,3947SPA_FEATURE_OBSOLETE_COUNTS));39483949scn->scn_is_bptree = B_FALSE;3950scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;3951err = bpobj_iterate(&dp->dp_obsolete_bpobj,3952dsl_scan_obsolete_block_cb, scn, tx);3953if (err != 0 && err != ERESTART)3954zfs_panic_recover("error %u from bpobj_iterate()", err);39553956if (bpobj_is_empty(&dp->dp_obsolete_bpobj))3957dsl_pool_destroy_obsolete_bpobj(dp, tx);3958}3959return (0);3960}39613962static void3963name_to_bookmark(char *buf, zbookmark_phys_t *zb)3964{3965zb->zb_objset = zfs_strtonum(buf, &buf);3966ASSERT(*buf == ':');3967zb->zb_object = zfs_strtonum(buf + 1, &buf);3968ASSERT(*buf == ':');3969zb->zb_level = (int)zfs_strtonum(buf + 1, &buf);3970ASSERT(*buf == ':');3971zb->zb_blkid = zfs_strtonum(buf + 1, &buf);3972ASSERT(*buf == '\0');3973}39743975static void3976name_to_object(char *buf, uint64_t *obj)3977{3978*obj = zfs_strtonum(buf, &buf);3979ASSERT(*buf == '\0');3980}39813982static void3983read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb)3984{3985dsl_pool_t *dp = scn->scn_dp;3986dsl_dataset_t *ds;3987objset_t *os;3988if (dsl_dataset_hold_obj(dp, zb.zb_objset, FTAG, &ds) != 0)3989return;39903991if (dmu_objset_from_ds(ds, &os) != 0) {3992dsl_dataset_rele(ds, FTAG);3993return;3994}39953996/*3997* If the key is not loaded dbuf_dnode_findbp() will error out with3998* EACCES. However in that case dnode_hold() will eventually call3999* dbuf_read()->zio_wait() which may call spa_log_error(). This will4000* lead to a deadlock due to us holding the mutex spa_errlist_lock.4001* Avoid this by checking here if the keys are loaded, if not return.4002* If the keys are not loaded the head_errlog feature is meaningless4003* as we cannot figure out the birth txg of the block pointer.4004*/4005if (dsl_dataset_get_keystatus(ds->ds_dir) ==4006ZFS_KEYSTATUS_UNAVAILABLE) {4007dsl_dataset_rele(ds, FTAG);4008return;4009}40104011dnode_t *dn;4012blkptr_t bp;40134014if (dnode_hold(os, zb.zb_object, FTAG, &dn) != 0) {4015dsl_dataset_rele(ds, FTAG);4016return;4017}40184019rw_enter(&dn->dn_struct_rwlock, RW_READER);4020int error = dbuf_dnode_findbp(dn, zb.zb_level, zb.zb_blkid, &bp, NULL,4021NULL);40224023if (error) {4024rw_exit(&dn->dn_struct_rwlock);4025dnode_rele(dn, FTAG);4026dsl_dataset_rele(ds, FTAG);4027return;4028}40294030if (!error && BP_IS_HOLE(&bp)) {4031rw_exit(&dn->dn_struct_rwlock);4032dnode_rele(dn, FTAG);4033dsl_dataset_rele(ds, FTAG);4034return;4035}40364037int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW |4038ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB;40394040/* If it's an intent log block, failure is expected. */4041if (zb.zb_level == ZB_ZIL_LEVEL)4042zio_flags |= ZIO_FLAG_SPECULATIVE;40434044ASSERT(!BP_IS_EMBEDDED(&bp));4045scan_exec_io(dp, &bp, zio_flags, &zb, NULL);4046rw_exit(&dn->dn_struct_rwlock);4047dnode_rele(dn, FTAG);4048dsl_dataset_rele(ds, FTAG);4049}40504051/*4052* We keep track of the scrubbed error blocks in "count". This will be used4053* when deciding whether we exceeded zfs_scrub_error_blocks_per_txg. This4054* function is modelled after check_filesystem().4055*/4056static int4057scrub_filesystem(spa_t *spa, uint64_t fs, zbookmark_err_phys_t *zep,4058int *count)4059{4060dsl_dataset_t *ds;4061dsl_pool_t *dp = spa->spa_dsl_pool;4062dsl_scan_t *scn = dp->dp_scan;40634064int error = dsl_dataset_hold_obj(dp, fs, FTAG, &ds);4065if (error != 0)4066return (error);40674068uint64_t latest_txg;4069uint64_t txg_to_consider = spa->spa_syncing_txg;4070boolean_t check_snapshot = B_TRUE;40714072error = find_birth_txg(ds, zep, &latest_txg);40734074/*4075* If find_birth_txg() errors out, then err on the side of caution and4076* proceed. In worst case scenario scrub all objects. If zep->zb_birth4077* is 0 (e.g. in case of encryption with unloaded keys) also proceed to4078* scrub all objects.4079*/4080if (error == 0 && zep->zb_birth == latest_txg) {4081/* Block neither free nor re written. */4082zbookmark_phys_t zb;4083zep_to_zb(fs, zep, &zb);4084scn->scn_zio_root = zio_root(spa, NULL, NULL,4085ZIO_FLAG_CANFAIL);4086/* We have already acquired the config lock for spa */4087read_by_block_level(scn, zb);40884089(void) zio_wait(scn->scn_zio_root);4090scn->scn_zio_root = NULL;40914092scn->errorscrub_phys.dep_examined++;4093scn->errorscrub_phys.dep_to_examine--;4094(*count)++;4095if ((*count) == zfs_scrub_error_blocks_per_txg ||4096dsl_error_scrub_check_suspend(scn, &zb)) {4097dsl_dataset_rele(ds, FTAG);4098return (SET_ERROR(EFAULT));4099}41004101check_snapshot = B_FALSE;4102} else if (error == 0) {4103txg_to_consider = latest_txg;4104}41054106/*4107* Retrieve the number of snapshots if the dataset is not a snapshot.4108*/4109uint64_t snap_count = 0;4110if (dsl_dataset_phys(ds)->ds_snapnames_zapobj != 0) {41114112error = zap_count(spa->spa_meta_objset,4113dsl_dataset_phys(ds)->ds_snapnames_zapobj, &snap_count);41144115if (error != 0) {4116dsl_dataset_rele(ds, FTAG);4117return (error);4118}4119}41204121if (snap_count == 0) {4122/* Filesystem without snapshots. */4123dsl_dataset_rele(ds, FTAG);4124return (0);4125}41264127uint64_t snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4128uint64_t snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;41294130dsl_dataset_rele(ds, FTAG);41314132/* Check only snapshots created from this file system. */4133while (snap_obj != 0 && zep->zb_birth < snap_obj_txg &&4134snap_obj_txg <= txg_to_consider) {41354136error = dsl_dataset_hold_obj(dp, snap_obj, FTAG, &ds);4137if (error != 0)4138return (error);41394140if (dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj != fs) {4141snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4142snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;4143dsl_dataset_rele(ds, FTAG);4144continue;4145}41464147boolean_t affected = B_TRUE;4148if (check_snapshot) {4149uint64_t blk_txg;4150error = find_birth_txg(ds, zep, &blk_txg);41514152/*4153* Scrub the snapshot also when zb_birth == 0 or when4154* find_birth_txg() returns an error.4155*/4156affected = (error == 0 && zep->zb_birth == blk_txg) ||4157(error != 0) || (zep->zb_birth == 0);4158}41594160/* Scrub snapshots. */4161if (affected) {4162zbookmark_phys_t zb;4163zep_to_zb(snap_obj, zep, &zb);4164scn->scn_zio_root = zio_root(spa, NULL, NULL,4165ZIO_FLAG_CANFAIL);4166/* We have already acquired the config lock for spa */4167read_by_block_level(scn, zb);41684169(void) zio_wait(scn->scn_zio_root);4170scn->scn_zio_root = NULL;41714172scn->errorscrub_phys.dep_examined++;4173scn->errorscrub_phys.dep_to_examine--;4174(*count)++;4175if ((*count) == zfs_scrub_error_blocks_per_txg ||4176dsl_error_scrub_check_suspend(scn, &zb)) {4177dsl_dataset_rele(ds, FTAG);4178return (EFAULT);4179}4180}4181snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;4182snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4183dsl_dataset_rele(ds, FTAG);4184}4185return (0);4186}41874188void4189dsl_errorscrub_sync(dsl_pool_t *dp, dmu_tx_t *tx)4190{4191spa_t *spa = dp->dp_spa;4192dsl_scan_t *scn = dp->dp_scan;41934194/*4195* Only process scans in sync pass 1.4196*/41974198if (spa_sync_pass(spa) > 1)4199return;42004201/*4202* If the spa is shutting down, then stop scanning. This will4203* ensure that the scan does not dirty any new data during the4204* shutdown phase.4205*/4206if (spa_shutting_down(spa))4207return;42084209if (!dsl_errorscrub_active(scn) || dsl_errorscrub_is_paused(scn)) {4210return;4211}42124213if (dsl_scan_resilvering(scn->scn_dp)) {4214/* cancel the error scrub if resilver started */4215dsl_scan_cancel(scn->scn_dp);4216return;4217}42184219spa->spa_scrub_active = B_TRUE;4220scn->scn_sync_start_time = getlrtime();42214222/*4223* zfs_scan_suspend_progress can be set to disable scrub progress.4224* See more detailed comment in dsl_scan_sync().4225*/4226if (zfs_scan_suspend_progress) {4227uint64_t scan_time_ns = getlrtime() - scn->scn_sync_start_time;4228int mintime = zfs_scrub_min_time_ms;42294230while (zfs_scan_suspend_progress &&4231!txg_sync_waiting(scn->scn_dp) &&4232!spa_shutting_down(scn->scn_dp->dp_spa) &&4233NSEC2MSEC(scan_time_ns) < mintime) {4234delay(hz);4235scan_time_ns = getlrtime() - scn->scn_sync_start_time;4236}4237return;4238}42394240int i = 0;4241zap_attribute_t *za;4242zbookmark_phys_t *zb;4243boolean_t limit_exceeded = B_FALSE;42444245za = zap_attribute_alloc();4246zb = kmem_zalloc(sizeof (zbookmark_phys_t), KM_SLEEP);42474248if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {4249for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;4250zap_cursor_advance(&scn->errorscrub_cursor)) {4251name_to_bookmark(za->za_name, zb);42524253scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4254NULL, ZIO_FLAG_CANFAIL);4255dsl_pool_config_enter(dp, FTAG);4256read_by_block_level(scn, *zb);4257dsl_pool_config_exit(dp, FTAG);42584259(void) zio_wait(scn->scn_zio_root);4260scn->scn_zio_root = NULL;42614262scn->errorscrub_phys.dep_examined += 1;4263scn->errorscrub_phys.dep_to_examine -= 1;4264i++;4265if (i == zfs_scrub_error_blocks_per_txg ||4266dsl_error_scrub_check_suspend(scn, zb)) {4267limit_exceeded = B_TRUE;4268break;4269}4270}42714272if (!limit_exceeded)4273dsl_errorscrub_done(scn, B_TRUE, tx);42744275dsl_errorscrub_sync_state(scn, tx);4276zap_attribute_free(za);4277kmem_free(zb, sizeof (*zb));4278return;4279}42804281int error = 0;4282for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;4283zap_cursor_advance(&scn->errorscrub_cursor)) {42844285zap_cursor_t *head_ds_cursor;4286zap_attribute_t *head_ds_attr;4287zbookmark_err_phys_t head_ds_block;42884289head_ds_cursor = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);4290head_ds_attr = zap_attribute_alloc();42914292uint64_t head_ds_err_obj = za->za_first_integer;4293uint64_t head_ds;4294name_to_object(za->za_name, &head_ds);4295boolean_t config_held = B_FALSE;4296uint64_t top_affected_fs;42974298for (zap_cursor_init(head_ds_cursor, spa->spa_meta_objset,4299head_ds_err_obj); zap_cursor_retrieve(head_ds_cursor,4300head_ds_attr) == 0; zap_cursor_advance(head_ds_cursor)) {43014302name_to_errphys(head_ds_attr->za_name, &head_ds_block);43034304/*4305* In case we are called from spa_sync the pool4306* config is already held.4307*/4308if (!dsl_pool_config_held(dp)) {4309dsl_pool_config_enter(dp, FTAG);4310config_held = B_TRUE;4311}43124313error = find_top_affected_fs(spa,4314head_ds, &head_ds_block, &top_affected_fs);4315if (error)4316break;43174318error = scrub_filesystem(spa, top_affected_fs,4319&head_ds_block, &i);43204321if (error == SET_ERROR(EFAULT)) {4322limit_exceeded = B_TRUE;4323break;4324}4325}43264327zap_cursor_fini(head_ds_cursor);4328kmem_free(head_ds_cursor, sizeof (*head_ds_cursor));4329zap_attribute_free(head_ds_attr);43304331if (config_held)4332dsl_pool_config_exit(dp, FTAG);4333}43344335zap_attribute_free(za);4336kmem_free(zb, sizeof (*zb));4337if (!limit_exceeded)4338dsl_errorscrub_done(scn, B_TRUE, tx);43394340dsl_errorscrub_sync_state(scn, tx);4341}43424343/*4344* This is the primary entry point for scans that is called from syncing4345* context. Scans must happen entirely during syncing context so that we4346* can guarantee that blocks we are currently scanning will not change out4347* from under us. While a scan is active, this function controls how quickly4348* transaction groups proceed, instead of the normal handling provided by4349* txg_sync_thread().4350*/4351void4352dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)4353{4354int err = 0;4355dsl_scan_t *scn = dp->dp_scan;4356spa_t *spa = dp->dp_spa;4357state_sync_type_t sync_type = SYNC_OPTIONAL;4358int restart_early = 0;43594360if (spa->spa_resilver_deferred) {4361uint64_t to_issue, issued;43624363if (!spa_feature_is_active(dp->dp_spa,4364SPA_FEATURE_RESILVER_DEFER))4365spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);43664367/*4368* See print_scan_scrub_resilver_status() issued/total_i4369* @ cmd/zpool/zpool_main.c4370*/4371to_issue =4372scn->scn_phys.scn_to_examine - scn->scn_phys.scn_skipped;4373issued =4374scn->scn_issued_before_pass + spa->spa_scan_pass_issued;4375restart_early =4376zfs_resilver_disable_defer ||4377(issued < (to_issue * zfs_resilver_defer_percent / 100));4378}43794380/*4381* Only process scans in sync pass 1.4382*/4383if (spa_sync_pass(spa) > 1)4384return;438543864387/*4388* Check for scn_restart_txg before checking spa_load_state, so4389* that we can restart an old-style scan while the pool is being4390* imported (see dsl_scan_init). We also restart scans if there4391* is a deferred resilver and the user has manually disabled4392* deferred resilvers via zfs_resilver_disable_defer, or if the4393* current scan progress is below zfs_resilver_defer_percent.4394*/4395if (dsl_scan_restarting(scn, tx) || restart_early) {4396setup_sync_arg_t setup_sync_arg = {4397.func = POOL_SCAN_SCRUB,4398.txgstart = 0,4399.txgend = 0,4400};4401dsl_scan_done(scn, B_FALSE, tx);4402if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))4403setup_sync_arg.func = POOL_SCAN_RESILVER;4404zfs_dbgmsg("restarting scan func=%u on %s txg=%llu early=%d",4405setup_sync_arg.func, dp->dp_spa->spa_name,4406(longlong_t)tx->tx_txg, restart_early);4407dsl_scan_setup_sync(&setup_sync_arg, tx);4408}44094410/*4411* If the spa is shutting down, then stop scanning. This will4412* ensure that the scan does not dirty any new data during the4413* shutdown phase.4414*/4415if (spa_shutting_down(spa))4416return;44174418/*4419* Wait a few txgs after importing before doing background work4420* (async destroys and scanning). This should help the import4421* command to complete quickly.4422*/4423if (spa->spa_syncing_txg < spa->spa_first_txg + zfs_import_defer_txgs)4424return;44254426/*4427* If the scan is inactive due to a stalled async destroy, try again.4428*/4429if (!scn->scn_async_stalled && !dsl_scan_active(scn))4430return;44314432/* reset scan statistics */4433scn->scn_visited_this_txg = 0;4434scn->scn_async_frees_this_txg = 0;4435scn->scn_holes_this_txg = 0;4436scn->scn_lt_min_this_txg = 0;4437scn->scn_gt_max_this_txg = 0;4438scn->scn_ddt_contained_this_txg = 0;4439scn->scn_objsets_visited_this_txg = 0;4440scn->scn_avg_seg_size_this_txg = 0;4441scn->scn_segs_this_txg = 0;4442scn->scn_avg_zio_size_this_txg = 0;4443scn->scn_zios_this_txg = 0;4444scn->scn_suspending = B_FALSE;4445scn->scn_sync_start_time = getlrtime();4446spa->spa_scrub_active = B_TRUE;44474448/*4449* First process the async destroys. If we suspend, don't do4450* any scrubbing or resilvering. This ensures that there are no4451* async destroys while we are scanning, so the scan code doesn't4452* have to worry about traversing it. It is also faster to free the4453* blocks than to scrub them.4454*/4455err = dsl_process_async_destroys(dp, tx);4456if (err != 0)4457return;44584459if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))4460return;44614462/*4463* zfs_scan_suspend_progress can be set to disable scan progress.4464* We don't want to spin the txg_sync thread, so we add a delay4465* here to simulate the time spent doing a scan. This is mostly4466* useful for testing and debugging.4467*/4468if (zfs_scan_suspend_progress) {4469uint64_t scan_time_ns = getlrtime() - scn->scn_sync_start_time;4470uint_t mintime = (scn->scn_phys.scn_func ==4471POOL_SCAN_RESILVER) ? zfs_resilver_min_time_ms :4472zfs_scrub_min_time_ms;44734474while (zfs_scan_suspend_progress &&4475!txg_sync_waiting(scn->scn_dp) &&4476!spa_shutting_down(scn->scn_dp->dp_spa) &&4477NSEC2MSEC(scan_time_ns) < mintime) {4478delay(hz);4479scan_time_ns = getlrtime() - scn->scn_sync_start_time;4480}4481return;4482}44834484/*4485* Disabled by default, set zfs_scan_report_txgs to report4486* average performance over the last zfs_scan_report_txgs TXGs.4487*/4488if (zfs_scan_report_txgs != 0 &&4489tx->tx_txg % zfs_scan_report_txgs == 0) {4490scn->scn_issued_before_pass += spa->spa_scan_pass_issued;4491spa_scan_stat_init(spa);4492}44934494/*4495* It is possible to switch from unsorted to sorted at any time,4496* but afterwards the scan will remain sorted unless reloaded from4497* a checkpoint after a reboot.4498*/4499if (!zfs_scan_legacy) {4500scn->scn_is_sorted = B_TRUE;4501if (scn->scn_last_checkpoint == 0)4502scn->scn_last_checkpoint = ddi_get_lbolt();4503}45044505/*4506* For sorted scans, determine what kind of work we will be doing4507* this txg based on our memory limitations and whether or not we4508* need to perform a checkpoint.4509*/4510if (scn->scn_is_sorted) {4511/*4512* If we are over our checkpoint interval, set scn_clearing4513* so that we can begin checkpointing immediately. The4514* checkpoint allows us to save a consistent bookmark4515* representing how much data we have scrubbed so far.4516* Otherwise, use the memory limit to determine if we should4517* scan for metadata or start issue scrub IOs. We accumulate4518* metadata until we hit our hard memory limit at which point4519* we issue scrub IOs until we are at our soft memory limit.4520*/4521if (scn->scn_checkpointing ||4522ddi_get_lbolt() - scn->scn_last_checkpoint >4523SEC_TO_TICK(zfs_scan_checkpoint_intval)) {4524if (!scn->scn_checkpointing)4525zfs_dbgmsg("begin scan checkpoint for %s",4526spa->spa_name);45274528scn->scn_checkpointing = B_TRUE;4529scn->scn_clearing = B_TRUE;4530} else {4531boolean_t should_clear = dsl_scan_should_clear(scn);4532if (should_clear && !scn->scn_clearing) {4533zfs_dbgmsg("begin scan clearing for %s",4534spa->spa_name);4535scn->scn_clearing = B_TRUE;4536} else if (!should_clear && scn->scn_clearing) {4537zfs_dbgmsg("finish scan clearing for %s",4538spa->spa_name);4539scn->scn_clearing = B_FALSE;4540}4541}4542} else {4543ASSERT0(scn->scn_checkpointing);4544ASSERT0(scn->scn_clearing);4545}45464547if (!scn->scn_clearing && scn->scn_done_txg == 0) {4548/* Need to scan metadata for more blocks to scrub */4549dsl_scan_phys_t *scnp = &scn->scn_phys;4550taskqid_t prefetch_tqid;45514552/*4553* Calculate the max number of in-flight bytes for pool-wide4554* scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).4555* Limits for the issuing phase are done per top-level vdev and4556* are handled separately.4557*/4558scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,4559zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));45604561if (scnp->scn_ddt_bookmark.ddb_class <=4562scnp->scn_ddt_class_max) {4563ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));4564zfs_dbgmsg("doing scan sync for %s txg %llu; "4565"ddt bm=%llu/%llu/%llu/%llx",4566spa->spa_name,4567(longlong_t)tx->tx_txg,4568(longlong_t)scnp->scn_ddt_bookmark.ddb_class,4569(longlong_t)scnp->scn_ddt_bookmark.ddb_type,4570(longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,4571(longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);4572} else {4573zfs_dbgmsg("doing scan sync for %s txg %llu; "4574"bm=%llu/%llu/%llu/%llu",4575spa->spa_name,4576(longlong_t)tx->tx_txg,4577(longlong_t)scnp->scn_bookmark.zb_objset,4578(longlong_t)scnp->scn_bookmark.zb_object,4579(longlong_t)scnp->scn_bookmark.zb_level,4580(longlong_t)scnp->scn_bookmark.zb_blkid);4581}45824583scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4584NULL, ZIO_FLAG_CANFAIL);45854586scn->scn_prefetch_stop = B_FALSE;4587prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,4588dsl_scan_prefetch_thread, scn, TQ_SLEEP);4589ASSERT(prefetch_tqid != TASKQID_INVALID);45904591dsl_pool_config_enter(dp, FTAG);4592dsl_scan_visit(scn, tx);4593dsl_pool_config_exit(dp, FTAG);45944595mutex_enter(&dp->dp_spa->spa_scrub_lock);4596scn->scn_prefetch_stop = B_TRUE;4597cv_broadcast(&spa->spa_scrub_io_cv);4598mutex_exit(&dp->dp_spa->spa_scrub_lock);45994600taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);4601(void) zio_wait(scn->scn_zio_root);4602scn->scn_zio_root = NULL;46034604zfs_dbgmsg("scan visited %llu blocks of %s in %llums "4605"(%llu os's, %llu holes, %llu < mintxg, "4606"%llu in ddt, %llu > maxtxg)",4607(longlong_t)scn->scn_visited_this_txg,4608spa->spa_name,4609(longlong_t)NSEC2MSEC(getlrtime() -4610scn->scn_sync_start_time),4611(longlong_t)scn->scn_objsets_visited_this_txg,4612(longlong_t)scn->scn_holes_this_txg,4613(longlong_t)scn->scn_lt_min_this_txg,4614(longlong_t)scn->scn_ddt_contained_this_txg,4615(longlong_t)scn->scn_gt_max_this_txg);46164617if (!scn->scn_suspending) {4618ASSERT0(avl_numnodes(&scn->scn_queue));4619scn->scn_done_txg = tx->tx_txg + 1;4620if (scn->scn_is_sorted) {4621scn->scn_checkpointing = B_TRUE;4622scn->scn_clearing = B_TRUE;4623scn->scn_issued_before_pass +=4624spa->spa_scan_pass_issued;4625spa_scan_stat_init(spa);4626}4627zfs_dbgmsg("scan complete for %s txg %llu",4628spa->spa_name,4629(longlong_t)tx->tx_txg);4630}4631} else if (scn->scn_is_sorted && scn->scn_queues_pending != 0) {4632ASSERT(scn->scn_clearing);46334634/* need to issue scrubbing IOs from per-vdev queues */4635scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4636NULL, ZIO_FLAG_CANFAIL);4637scan_io_queues_run(scn);4638(void) zio_wait(scn->scn_zio_root);4639scn->scn_zio_root = NULL;46404641/* calculate and dprintf the current memory usage */4642(void) dsl_scan_should_clear(scn);4643dsl_scan_update_stats(scn);46444645zfs_dbgmsg("scan issued %llu blocks for %s (%llu segs) "4646"in %llums (avg_block_size = %llu, avg_seg_size = %llu)",4647(longlong_t)scn->scn_zios_this_txg,4648spa->spa_name,4649(longlong_t)scn->scn_segs_this_txg,4650(longlong_t)NSEC2MSEC(getlrtime() -4651scn->scn_sync_start_time),4652(longlong_t)scn->scn_avg_zio_size_this_txg,4653(longlong_t)scn->scn_avg_seg_size_this_txg);4654} else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {4655/* Finished with everything. Mark the scrub as complete */4656zfs_dbgmsg("scan issuing complete txg %llu for %s",4657(longlong_t)tx->tx_txg,4658spa->spa_name);4659ASSERT3U(scn->scn_done_txg, !=, 0);4660ASSERT0(spa->spa_scrub_inflight);4661ASSERT0(scn->scn_queues_pending);4662dsl_scan_done(scn, B_TRUE, tx);4663sync_type = SYNC_MANDATORY;4664}46654666dsl_scan_sync_state(scn, tx, sync_type);4667}46684669static void4670count_block_issued(spa_t *spa, const blkptr_t *bp, boolean_t all)4671{4672/*4673* Don't count embedded bp's, since we already did the work of4674* scanning these when we scanned the containing block.4675*/4676if (BP_IS_EMBEDDED(bp))4677return;46784679/*4680* Update the spa's stats on how many bytes we have issued.4681* Sequential scrubs create a zio for each DVA of the bp. Each4682* of these will include all DVAs for repair purposes, but the4683* zio code will only try the first one unless there is an issue.4684* Therefore, we should only count the first DVA for these IOs.4685*/4686atomic_add_64(&spa->spa_scan_pass_issued,4687all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));4688}46894690static void4691count_block_skipped(dsl_scan_t *scn, const blkptr_t *bp, boolean_t all)4692{4693if (BP_IS_EMBEDDED(bp))4694return;4695atomic_add_64(&scn->scn_phys.scn_skipped,4696all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));4697}46984699static void4700count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)4701{4702/*4703* If we resume after a reboot, zab will be NULL; don't record4704* incomplete stats in that case.4705*/4706if (zab == NULL)4707return;47084709for (int i = 0; i < 4; i++) {4710int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;4711int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;47124713if (t & DMU_OT_NEWTYPE)4714t = DMU_OT_OTHER;4715zfs_blkstat_t *zb = &zab->zab_type[l][t];4716int equal;47174718zb->zb_count++;4719zb->zb_asize += BP_GET_ASIZE(bp);4720zb->zb_lsize += BP_GET_LSIZE(bp);4721zb->zb_psize += BP_GET_PSIZE(bp);4722zb->zb_gangs += BP_COUNT_GANG(bp);47234724switch (BP_GET_NDVAS(bp)) {4725case 2:4726if (DVA_GET_VDEV(&bp->blk_dva[0]) ==4727DVA_GET_VDEV(&bp->blk_dva[1]))4728zb->zb_ditto_2_of_2_samevdev++;4729break;4730case 3:4731equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==4732DVA_GET_VDEV(&bp->blk_dva[1])) +4733(DVA_GET_VDEV(&bp->blk_dva[0]) ==4734DVA_GET_VDEV(&bp->blk_dva[2])) +4735(DVA_GET_VDEV(&bp->blk_dva[1]) ==4736DVA_GET_VDEV(&bp->blk_dva[2]));4737if (equal == 1)4738zb->zb_ditto_2_of_3_samevdev++;4739else if (equal == 3)4740zb->zb_ditto_3_of_3_samevdev++;4741break;4742}4743}4744}47454746static void4747scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)4748{4749avl_index_t idx;4750dsl_scan_t *scn = queue->q_scn;47514752ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));47534754if (unlikely(avl_is_empty(&queue->q_sios_by_addr)))4755atomic_add_64(&scn->scn_queues_pending, 1);4756if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {4757/* block is already scheduled for reading */4758sio_free(sio);4759return;4760}4761avl_insert(&queue->q_sios_by_addr, sio, idx);4762queue->q_sio_memused += SIO_GET_MUSED(sio);4763zfs_range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio),4764SIO_GET_ASIZE(sio));4765}47664767/*4768* Given all the info we got from our metadata scanning process, we4769* construct a scan_io_t and insert it into the scan sorting queue. The4770* I/O must already be suitable for us to process. This is controlled4771* by dsl_scan_enqueue().4772*/4773static void4774scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,4775int zio_flags, const zbookmark_phys_t *zb)4776{4777scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp));47784779ASSERT0(BP_IS_GANG(bp));4780ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));47814782bp2sio(bp, sio, dva_i);4783sio->sio_flags = zio_flags;4784sio->sio_zb = *zb;47854786queue->q_last_ext_addr = -1;4787scan_io_queue_insert_impl(queue, sio);4788}47894790/*4791* Given a set of I/O parameters as discovered by the metadata traversal4792* process, attempts to place the I/O into the sorted queues (if allowed),4793* or immediately executes the I/O.4794*/4795static void4796dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,4797const zbookmark_phys_t *zb)4798{4799spa_t *spa = dp->dp_spa;48004801ASSERT(!BP_IS_EMBEDDED(bp));48024803/*4804* Gang blocks are hard to issue sequentially, so we just issue them4805* here immediately instead of queuing them.4806*/4807if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {4808scan_exec_io(dp, bp, zio_flags, zb, NULL);4809return;4810}48114812for (int i = 0; i < BP_GET_NDVAS(bp); i++) {4813dva_t dva;4814vdev_t *vdev;48154816dva = bp->blk_dva[i];4817vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));4818ASSERT(vdev != NULL);48194820mutex_enter(&vdev->vdev_scan_io_queue_lock);4821if (vdev->vdev_scan_io_queue == NULL)4822vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);4823ASSERT(dp->dp_scan != NULL);4824scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,4825i, zio_flags, zb);4826mutex_exit(&vdev->vdev_scan_io_queue_lock);4827}4828}48294830static int4831dsl_scan_scrub_cb(dsl_pool_t *dp,4832const blkptr_t *bp, const zbookmark_phys_t *zb)4833{4834dsl_scan_t *scn = dp->dp_scan;4835spa_t *spa = dp->dp_spa;4836uint64_t phys_birth = BP_GET_PHYSICAL_BIRTH(bp);4837size_t psize = BP_GET_PSIZE(bp);4838boolean_t needs_io = B_FALSE;4839int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;48404841count_block(dp->dp_blkstats, bp);4842if (phys_birth <= scn->scn_phys.scn_min_txg ||4843phys_birth >= scn->scn_phys.scn_max_txg) {4844count_block_skipped(scn, bp, B_TRUE);4845return (0);4846}48474848/* Embedded BP's have phys_birth==0, so we reject them above. */4849ASSERT(!BP_IS_EMBEDDED(bp));48504851ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));4852if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {4853zio_flags |= ZIO_FLAG_SCRUB;4854needs_io = B_TRUE;4855} else {4856ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);4857zio_flags |= ZIO_FLAG_RESILVER;4858needs_io = B_FALSE;4859}48604861/* If it's an intent log block, failure is expected. */4862if (zb->zb_level == ZB_ZIL_LEVEL)4863zio_flags |= ZIO_FLAG_SPECULATIVE;48644865for (int d = 0; d < BP_GET_NDVAS(bp); d++) {4866const dva_t *dva = &bp->blk_dva[d];48674868/*4869* Keep track of how much data we've examined so that4870* zpool(8) status can make useful progress reports.4871*/4872uint64_t asize = DVA_GET_ASIZE(dva);4873scn->scn_phys.scn_examined += asize;4874spa->spa_scan_pass_exam += asize;48754876/* if it's a resilver, this may not be in the target range */4877if (!needs_io)4878needs_io = dsl_scan_need_resilver(spa, dva, psize,4879phys_birth);4880}48814882if (needs_io && !zfs_no_scrub_io) {4883dsl_scan_enqueue(dp, bp, zio_flags, zb);4884} else {4885count_block_skipped(scn, bp, B_TRUE);4886}48874888/* do not relocate this block */4889return (0);4890}48914892static void4893dsl_scan_scrub_done(zio_t *zio)4894{4895spa_t *spa = zio->io_spa;4896blkptr_t *bp = zio->io_bp;4897dsl_scan_io_queue_t *queue = zio->io_private;48984899abd_free(zio->io_abd);49004901if (queue == NULL) {4902mutex_enter(&spa->spa_scrub_lock);4903ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));4904spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);4905cv_broadcast(&spa->spa_scrub_io_cv);4906mutex_exit(&spa->spa_scrub_lock);4907} else {4908mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);4909ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));4910queue->q_inflight_bytes -= BP_GET_PSIZE(bp);4911cv_broadcast(&queue->q_zio_cv);4912mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);4913}49144915if (zio->io_error && (zio->io_error != ECKSUM ||4916!(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {4917if (dsl_errorscrubbing(spa->spa_dsl_pool) &&4918!dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan)) {4919atomic_inc_64(&spa->spa_dsl_pool->dp_scan4920->errorscrub_phys.dep_errors);4921} else {4922atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys4923.scn_errors);4924}4925}4926}49274928/*4929* Given a scanning zio's information, executes the zio. The zio need4930* not necessarily be only sortable, this function simply executes the4931* zio, no matter what it is. The optional queue argument allows the4932* caller to specify that they want per top level vdev IO rate limiting4933* instead of the legacy global limiting.4934*/4935static void4936scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,4937const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)4938{4939spa_t *spa = dp->dp_spa;4940dsl_scan_t *scn = dp->dp_scan;4941size_t size = BP_GET_PSIZE(bp);4942abd_t *data = abd_alloc_for_io(size, B_FALSE);4943zio_t *pio;49444945if (queue == NULL) {4946ASSERT3U(scn->scn_maxinflight_bytes, >, 0);4947mutex_enter(&spa->spa_scrub_lock);4948while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)4949cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);4950spa->spa_scrub_inflight += BP_GET_PSIZE(bp);4951mutex_exit(&spa->spa_scrub_lock);4952pio = scn->scn_zio_root;4953} else {4954kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;49554956ASSERT3U(queue->q_maxinflight_bytes, >, 0);4957mutex_enter(q_lock);4958while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)4959cv_wait(&queue->q_zio_cv, q_lock);4960queue->q_inflight_bytes += BP_GET_PSIZE(bp);4961pio = queue->q_zio;4962mutex_exit(q_lock);4963}49644965ASSERT(pio != NULL);4966count_block_issued(spa, bp, queue == NULL);4967zio_nowait(zio_read(pio, spa, bp, data, size, dsl_scan_scrub_done,4968queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));4969}49704971/*4972* This is the primary extent sorting algorithm. We balance two parameters:4973* 1) how many bytes of I/O are in an extent4974* 2) how well the extent is filled with I/O (as a fraction of its total size)4975* Since we allow extents to have gaps between their constituent I/Os, it's4976* possible to have a fairly large extent that contains the same amount of4977* I/O bytes than a much smaller extent, which just packs the I/O more tightly.4978* The algorithm sorts based on a score calculated from the extent's size,4979* the relative fill volume (in %) and a "fill weight" parameter that controls4980* the split between whether we prefer larger extents or more well populated4981* extents:4982*4983* SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)4984*4985* Example:4986* 1) assume extsz = 64 MiB4987* 2) assume fill = 32 MiB (extent is half full)4988* 3) assume fill_weight = 34989* 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 1004990* SCORE = 32M + (50 * 3 * 32M) / 1004991* SCORE = 32M + (4800M / 100)4992* SCORE = 32M + 48M4993* ^ ^4994* | +--- final total relative fill-based score4995* +--------- final total fill-based score4996* SCORE = 80M4997*4998* As can be seen, at fill_ratio=3, the algorithm is slightly biased towards4999* extents that are more completely filled (in a 3:2 ratio) vs just larger.5000* Note that as an optimization, we replace multiplication and division by5001* 100 with bitshifting by 7 (which effectively multiplies and divides by 128).5002*5003* Since we do not care if one extent is only few percent better than another,5004* compress the score into 6 bits via binary logarithm AKA highbit64() and5005* put into otherwise unused due to ashift high bits of offset. This allows5006* to reduce q_exts_by_size B-tree elements to only 64 bits and compare them5007* with single operation. Plus it makes scrubs more sequential and reduces5008* chances that minor extent change move it within the B-tree.5009*/5010__attribute__((always_inline)) inline5011static int5012ext_size_compare(const void *x, const void *y)5013{5014const uint64_t *a = x, *b = y;50155016return (TREE_CMP(*a, *b));5017}50185019ZFS_BTREE_FIND_IN_BUF_FUNC(ext_size_find_in_buf, uint64_t,5020ext_size_compare)50215022static void5023ext_size_create(zfs_range_tree_t *rt, void *arg)5024{5025(void) rt;5026zfs_btree_t *size_tree = arg;50275028zfs_btree_create(size_tree, ext_size_compare, ext_size_find_in_buf,5029sizeof (uint64_t));5030}50315032static void5033ext_size_destroy(zfs_range_tree_t *rt, void *arg)5034{5035(void) rt;5036zfs_btree_t *size_tree = arg;5037ASSERT0(zfs_btree_numnodes(size_tree));50385039zfs_btree_destroy(size_tree);5040}50415042static uint64_t5043ext_size_value(zfs_range_tree_t *rt, zfs_range_seg_gap_t *rsg)5044{5045(void) rt;5046uint64_t size = rsg->rs_end - rsg->rs_start;5047uint64_t score = rsg->rs_fill + ((((rsg->rs_fill << 7) / size) *5048fill_weight * rsg->rs_fill) >> 7);5049ASSERT3U(rt->rt_shift, >=, 8);5050return (((uint64_t)(64 - highbit64(score)) << 56) | rsg->rs_start);5051}50525053static void5054ext_size_add(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)5055{5056zfs_btree_t *size_tree = arg;5057ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);5058uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);5059zfs_btree_add(size_tree, &v);5060}50615062static void5063ext_size_remove(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)5064{5065zfs_btree_t *size_tree = arg;5066ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);5067uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);5068zfs_btree_remove(size_tree, &v);5069}50705071static void5072ext_size_vacate(zfs_range_tree_t *rt, void *arg)5073{5074zfs_btree_t *size_tree = arg;5075zfs_btree_clear(size_tree);5076zfs_btree_destroy(size_tree);50775078ext_size_create(rt, arg);5079}50805081static const zfs_range_tree_ops_t ext_size_ops = {5082.rtop_create = ext_size_create,5083.rtop_destroy = ext_size_destroy,5084.rtop_add = ext_size_add,5085.rtop_remove = ext_size_remove,5086.rtop_vacate = ext_size_vacate5087};50885089/*5090* Comparator for the q_sios_by_addr tree. Sorting is simply performed5091* based on LBA-order (from lowest to highest).5092*/5093static int5094sio_addr_compare(const void *x, const void *y)5095{5096const scan_io_t *a = x, *b = y;50975098return (TREE_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b)));5099}51005101/* IO queues are created on demand when they are needed. */5102static dsl_scan_io_queue_t *5103scan_io_queue_create(vdev_t *vd)5104{5105dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;5106dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);51075108q->q_scn = scn;5109q->q_vd = vd;5110q->q_sio_memused = 0;5111q->q_last_ext_addr = -1;5112cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);5113q->q_exts_by_addr = zfs_range_tree_create_gap(&ext_size_ops,5114ZFS_RANGE_SEG_GAP, &q->q_exts_by_size, 0, vd->vdev_ashift,5115zfs_scan_max_ext_gap);5116avl_create(&q->q_sios_by_addr, sio_addr_compare,5117sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));51185119return (q);5120}51215122/*5123* Destroys a scan queue and all segments and scan_io_t's contained in it.5124* No further execution of I/O occurs, anything pending in the queue is5125* simply freed without being executed.5126*/5127void5128dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)5129{5130dsl_scan_t *scn = queue->q_scn;5131scan_io_t *sio;5132void *cookie = NULL;51335134ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));51355136if (!avl_is_empty(&queue->q_sios_by_addr))5137atomic_add_64(&scn->scn_queues_pending, -1);5138while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=5139NULL) {5140ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr,5141SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio)));5142queue->q_sio_memused -= SIO_GET_MUSED(sio);5143sio_free(sio);5144}51455146ASSERT0(queue->q_sio_memused);5147zfs_range_tree_vacate(queue->q_exts_by_addr, NULL, queue);5148zfs_range_tree_destroy(queue->q_exts_by_addr);5149avl_destroy(&queue->q_sios_by_addr);5150cv_destroy(&queue->q_zio_cv);51515152kmem_free(queue, sizeof (*queue));5153}51545155/*5156* Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is5157* called on behalf of vdev_top_transfer when creating or destroying5158* a mirror vdev due to zpool attach/detach.5159*/5160void5161dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)5162{5163mutex_enter(&svd->vdev_scan_io_queue_lock);5164mutex_enter(&tvd->vdev_scan_io_queue_lock);51655166VERIFY0P(tvd->vdev_scan_io_queue);5167tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;5168svd->vdev_scan_io_queue = NULL;5169if (tvd->vdev_scan_io_queue != NULL)5170tvd->vdev_scan_io_queue->q_vd = tvd;51715172mutex_exit(&tvd->vdev_scan_io_queue_lock);5173mutex_exit(&svd->vdev_scan_io_queue_lock);5174}51755176static void5177scan_io_queues_destroy(dsl_scan_t *scn)5178{5179vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;51805181for (uint64_t i = 0; i < rvd->vdev_children; i++) {5182vdev_t *tvd = rvd->vdev_child[i];51835184mutex_enter(&tvd->vdev_scan_io_queue_lock);5185if (tvd->vdev_scan_io_queue != NULL)5186dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);5187tvd->vdev_scan_io_queue = NULL;5188mutex_exit(&tvd->vdev_scan_io_queue_lock);5189}5190}51915192static void5193dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)5194{5195dsl_pool_t *dp = spa->spa_dsl_pool;5196dsl_scan_t *scn = dp->dp_scan;5197vdev_t *vdev;5198kmutex_t *q_lock;5199dsl_scan_io_queue_t *queue;5200scan_io_t *srch_sio, *sio;5201avl_index_t idx;5202uint64_t start, size;52035204vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));5205ASSERT(vdev != NULL);5206q_lock = &vdev->vdev_scan_io_queue_lock;5207queue = vdev->vdev_scan_io_queue;52085209mutex_enter(q_lock);5210if (queue == NULL) {5211mutex_exit(q_lock);5212return;5213}52145215srch_sio = sio_alloc(BP_GET_NDVAS(bp));5216bp2sio(bp, srch_sio, dva_i);5217start = SIO_GET_OFFSET(srch_sio);5218size = SIO_GET_ASIZE(srch_sio);52195220/*5221* We can find the zio in two states:5222* 1) Cold, just sitting in the queue of zio's to be issued at5223* some point in the future. In this case, all we do is5224* remove the zio from the q_sios_by_addr tree, decrement5225* its data volume from the containing zfs_range_seg_t and5226* resort the q_exts_by_size tree to reflect that the5227* zfs_range_seg_t has lost some of its 'fill'. We don't shorten5228* the zfs_range_seg_t - this is usually rare enough not to be5229* worth the extra hassle of trying keep track of precise5230* extent boundaries.5231* 2) Hot, where the zio is currently in-flight in5232* dsl_scan_issue_ios. In this case, we can't simply5233* reach in and stop the in-flight zio's, so we instead5234* block the caller. Eventually, dsl_scan_issue_ios will5235* be done with issuing the zio's it gathered and will5236* signal us.5237*/5238sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);5239sio_free(srch_sio);52405241if (sio != NULL) {5242blkptr_t tmpbp;52435244/* Got it while it was cold in the queue */5245ASSERT3U(start, ==, SIO_GET_OFFSET(sio));5246ASSERT3U(size, ==, SIO_GET_ASIZE(sio));5247avl_remove(&queue->q_sios_by_addr, sio);5248if (avl_is_empty(&queue->q_sios_by_addr))5249atomic_add_64(&scn->scn_queues_pending, -1);5250queue->q_sio_memused -= SIO_GET_MUSED(sio);52515252ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr, start,5253size));5254zfs_range_tree_remove_fill(queue->q_exts_by_addr, start, size);52555256/* count the block as though we skipped it */5257sio2bp(sio, &tmpbp);5258count_block_skipped(scn, &tmpbp, B_FALSE);52595260sio_free(sio);5261}5262mutex_exit(q_lock);5263}52645265/*5266* Callback invoked when a zio_free() zio is executing. This needs to be5267* intercepted to prevent the zio from deallocating a particular portion5268* of disk space and it then getting reallocated and written to, while we5269* still have it queued up for processing.5270*/5271void5272dsl_scan_freed(spa_t *spa, const blkptr_t *bp)5273{5274dsl_pool_t *dp = spa->spa_dsl_pool;5275dsl_scan_t *scn = dp->dp_scan;52765277ASSERT(!BP_IS_EMBEDDED(bp));5278ASSERT(scn != NULL);5279if (!dsl_scan_is_running(scn))5280return;52815282for (int i = 0; i < BP_GET_NDVAS(bp); i++)5283dsl_scan_freed_dva(spa, bp, i);5284}52855286/*5287* Check if a vdev needs resilvering (non-empty DTL), if so, and resilver has5288* not started, start it. Otherwise, only restart if max txg in DTL range is5289* greater than the max txg in the current scan. If the DTL max is less than5290* the scan max, then the vdev has not missed any new data since the resilver5291* started, so a restart is not needed.5292*/5293void5294dsl_scan_assess_vdev(dsl_pool_t *dp, vdev_t *vd)5295{5296uint64_t min, max;52975298if (!vdev_resilver_needed(vd, &min, &max))5299return;53005301if (!dsl_scan_resilvering(dp)) {5302spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);5303return;5304}53055306if (max <= dp->dp_scan->scn_phys.scn_max_txg)5307return;53085309/* restart is needed, check if it can be deferred */5310if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))5311vdev_defer_resilver(vd);5312else5313spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);5314}53155316ZFS_MODULE_PARAM(zfs, zfs_, scan_vdev_limit, U64, ZMOD_RW,5317"Max bytes in flight per leaf vdev for scrubs and resilvers");53185319ZFS_MODULE_PARAM(zfs, zfs_, scrub_min_time_ms, UINT, ZMOD_RW,5320"Min millisecs to scrub per txg");53215322ZFS_MODULE_PARAM(zfs, zfs_, obsolete_min_time_ms, UINT, ZMOD_RW,5323"Min millisecs to obsolete per txg");53245325ZFS_MODULE_PARAM(zfs, zfs_, free_min_time_ms, UINT, ZMOD_RW,5326"Min millisecs to free per txg");53275328ZFS_MODULE_PARAM(zfs, zfs_, resilver_min_time_ms, UINT, ZMOD_RW,5329"Min millisecs to resilver per txg");53305331ZFS_MODULE_PARAM(zfs, zfs_, scan_suspend_progress, INT, ZMOD_RW,5332"Set to prevent scans from progressing");53335334ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_io, INT, ZMOD_RW,5335"Set to disable scrub I/O");53365337ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_prefetch, INT, ZMOD_RW,5338"Set to disable scrub prefetching");53395340ZFS_MODULE_PARAM(zfs, zfs_, async_block_max_blocks, U64, ZMOD_RW,5341"Max number of blocks freed in one txg");53425343ZFS_MODULE_PARAM(zfs, zfs_, max_async_dedup_frees, U64, ZMOD_RW,5344"Max number of dedup, clone or gang blocks freed in one txg");53455346ZFS_MODULE_PARAM(zfs, zfs_, async_free_zio_wait_interval, U64, ZMOD_RW,5347"Wait for pending free I/Os after issuing this many asynchronously");53485349ZFS_MODULE_PARAM(zfs, zfs_, free_bpobj_enabled, INT, ZMOD_RW,5350"Enable processing of the free_bpobj");53515352ZFS_MODULE_PARAM(zfs, zfs_, scan_blkstats, INT, ZMOD_RW,5353"Enable block statistics calculation during scrub");53545355ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_fact, UINT, ZMOD_RW,5356"Fraction of RAM for scan hard limit");53575358ZFS_MODULE_PARAM(zfs, zfs_, scan_issue_strategy, UINT, ZMOD_RW,5359"IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");53605361ZFS_MODULE_PARAM(zfs, zfs_, scan_legacy, INT, ZMOD_RW,5362"Scrub using legacy non-sequential method");53635364ZFS_MODULE_PARAM(zfs, zfs_, import_defer_txgs, UINT, ZMOD_RW,5365"Number of TXGs to defer background work after pool import");53665367ZFS_MODULE_PARAM(zfs, zfs_, scan_checkpoint_intval, UINT, ZMOD_RW,5368"Scan progress on-disk checkpointing interval");53695370ZFS_MODULE_PARAM(zfs, zfs_, scan_max_ext_gap, U64, ZMOD_RW,5371"Max gap in bytes between sequential scrub / resilver I/Os");53725373ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_soft_fact, UINT, ZMOD_RW,5374"Fraction of hard limit used as soft limit");53755376ZFS_MODULE_PARAM(zfs, zfs_, scan_strict_mem_lim, INT, ZMOD_RW,5377"Tunable to attempt to reduce lock contention");53785379ZFS_MODULE_PARAM(zfs, zfs_, scan_fill_weight, UINT, ZMOD_RW,5380"Tunable to adjust bias towards more filled segments during scans");53815382ZFS_MODULE_PARAM(zfs, zfs_, scan_report_txgs, UINT, ZMOD_RW,5383"Tunable to report resilver performance over the last N txgs");53845385ZFS_MODULE_PARAM(zfs, zfs_, resilver_disable_defer, INT, ZMOD_RW,5386"Process all resilvers immediately");53875388ZFS_MODULE_PARAM(zfs, zfs_, resilver_defer_percent, UINT, ZMOD_RW,5389"Issued IO percent complete after which resilvers are deferred");53905391ZFS_MODULE_PARAM(zfs, zfs_, scrub_error_blocks_per_txg, UINT, ZMOD_RW,5392"Error blocks to be scrubbed in one txg");539353945395