Path: blob/main/sys/contrib/openzfs/module/zfs/dsl_scan.c
48383 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/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 = 1000;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 = 1000;198199/* minimum milliseconds to resilver per txg */200static uint_t zfs_resilver_min_time_ms = 3000;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 = 100000;211212/* set to disable resilver deferring */213static int zfs_resilver_disable_defer = B_FALSE;214215/* Don't defer a resilver if the one in progress only got this far: */216static uint_t zfs_resilver_defer_percent = 10;217218/*219* We wait a few txgs after importing a pool to begin scanning so that220* the import / mounting code isn't held up by scrub / resilver IO.221* Unfortunately, it is a bit difficult to determine exactly how long222* this will take since userspace will trigger fs mounts asynchronously223* and the kernel will create zvol minors asynchronously. As a result,224* the value provided here is a bit arbitrary, but represents a225* reasonable estimate of how many txgs it will take to finish fully226* importing a pool227*/228#define SCAN_IMPORT_WAIT_TXGS 5229230#define DSL_SCAN_IS_SCRUB_RESILVER(scn) \231((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \232(scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)233234#define DSL_SCAN_IS_SCRUB(scn) \235((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB)236237#define DSL_SCAN_IS_RESILVER(scn) \238((scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)239240/*241* Enable/disable the processing of the free_bpobj object.242*/243static int zfs_free_bpobj_enabled = 1;244245/* Error blocks to be scrubbed in one txg. */246static uint_t zfs_scrub_error_blocks_per_txg = 1 << 12;247248/* the order has to match pool_scan_type */249static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {250NULL,251dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */252dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */253};254255/* In core node for the scn->scn_queue. Represents a dataset to be scanned */256typedef struct {257uint64_t sds_dsobj;258uint64_t sds_txg;259avl_node_t sds_node;260} scan_ds_t;261262/*263* This controls what conditions are placed on dsl_scan_sync_state():264* SYNC_OPTIONAL) write out scn_phys iff scn_queues_pending == 0265* SYNC_MANDATORY) write out scn_phys always. scn_queues_pending must be 0.266* SYNC_CACHED) if scn_queues_pending == 0, write out scn_phys. Otherwise267* write out the scn_phys_cached version.268* See dsl_scan_sync_state for details.269*/270typedef enum {271SYNC_OPTIONAL,272SYNC_MANDATORY,273SYNC_CACHED274} state_sync_type_t;275276/*277* This struct represents the minimum information needed to reconstruct a278* zio for sequential scanning. This is useful because many of these will279* accumulate in the sequential IO queues before being issued, so saving280* memory matters here.281*/282typedef struct scan_io {283/* fields from blkptr_t */284uint64_t sio_blk_prop;285uint64_t sio_phys_birth;286uint64_t sio_birth;287zio_cksum_t sio_cksum;288uint32_t sio_nr_dvas;289290/* fields from zio_t */291uint32_t sio_flags;292zbookmark_phys_t sio_zb;293294/* members for queue sorting */295union {296avl_node_t sio_addr_node; /* link into issuing queue */297list_node_t sio_list_node; /* link for issuing to disk */298} sio_nodes;299300/*301* There may be up to SPA_DVAS_PER_BP DVAs here from the bp,302* depending on how many were in the original bp. Only the303* first DVA is really used for sorting and issuing purposes.304* The other DVAs (if provided) simply exist so that the zio305* layer can find additional copies to repair from in the306* event of an error. This array must go at the end of the307* struct to allow this for the variable number of elements.308*/309dva_t sio_dva[];310} scan_io_t;311312#define SIO_SET_OFFSET(sio, x) DVA_SET_OFFSET(&(sio)->sio_dva[0], x)313#define SIO_SET_ASIZE(sio, x) DVA_SET_ASIZE(&(sio)->sio_dva[0], x)314#define SIO_GET_OFFSET(sio) DVA_GET_OFFSET(&(sio)->sio_dva[0])315#define SIO_GET_ASIZE(sio) DVA_GET_ASIZE(&(sio)->sio_dva[0])316#define SIO_GET_END_OFFSET(sio) \317(SIO_GET_OFFSET(sio) + SIO_GET_ASIZE(sio))318#define SIO_GET_MUSED(sio) \319(sizeof (scan_io_t) + ((sio)->sio_nr_dvas * sizeof (dva_t)))320321struct dsl_scan_io_queue {322dsl_scan_t *q_scn; /* associated dsl_scan_t */323vdev_t *q_vd; /* top-level vdev that this queue represents */324zio_t *q_zio; /* scn_zio_root child for waiting on IO */325326/* trees used for sorting I/Os and extents of I/Os */327zfs_range_tree_t *q_exts_by_addr;328zfs_btree_t q_exts_by_size;329avl_tree_t q_sios_by_addr;330uint64_t q_sio_memused;331uint64_t q_last_ext_addr;332333/* members for zio rate limiting */334uint64_t q_maxinflight_bytes;335uint64_t q_inflight_bytes;336kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */337338/* per txg statistics */339uint64_t q_total_seg_size_this_txg;340uint64_t q_segs_this_txg;341uint64_t q_total_zio_size_this_txg;342uint64_t q_zios_this_txg;343};344345/* private data for dsl_scan_prefetch_cb() */346typedef struct scan_prefetch_ctx {347zfs_refcount_t spc_refcnt; /* refcount for memory management */348dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */349boolean_t spc_root; /* is this prefetch for an objset? */350uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */351uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */352} scan_prefetch_ctx_t;353354/* private data for dsl_scan_prefetch() */355typedef struct scan_prefetch_issue_ctx {356avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */357scan_prefetch_ctx_t *spic_spc; /* spc for the callback */358blkptr_t spic_bp; /* bp to prefetch */359zbookmark_phys_t spic_zb; /* bookmark to prefetch */360} scan_prefetch_issue_ctx_t;361362static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,363const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);364static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,365scan_io_t *sio);366367static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);368static void scan_io_queues_destroy(dsl_scan_t *scn);369370static kmem_cache_t *sio_cache[SPA_DVAS_PER_BP];371372/* sio->sio_nr_dvas must be set so we know which cache to free from */373static void374sio_free(scan_io_t *sio)375{376ASSERT3U(sio->sio_nr_dvas, >, 0);377ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);378379kmem_cache_free(sio_cache[sio->sio_nr_dvas - 1], sio);380}381382/* It is up to the caller to set sio->sio_nr_dvas for freeing */383static scan_io_t *384sio_alloc(unsigned short nr_dvas)385{386ASSERT3U(nr_dvas, >, 0);387ASSERT3U(nr_dvas, <=, SPA_DVAS_PER_BP);388389return (kmem_cache_alloc(sio_cache[nr_dvas - 1], KM_SLEEP));390}391392void393scan_init(void)394{395/*396* This is used in ext_size_compare() to weight segments397* based on how sparse they are. This cannot be changed398* mid-scan and the tree comparison functions don't currently399* have a mechanism for passing additional context to the400* compare functions. Thus we store this value globally and401* we only allow it to be set at module initialization time402*/403fill_weight = zfs_scan_fill_weight;404405for (int i = 0; i < SPA_DVAS_PER_BP; i++) {406char name[36];407408(void) snprintf(name, sizeof (name), "sio_cache_%d", i);409sio_cache[i] = kmem_cache_create(name,410(sizeof (scan_io_t) + ((i + 1) * sizeof (dva_t))),4110, NULL, NULL, NULL, NULL, NULL, 0);412}413}414415void416scan_fini(void)417{418for (int i = 0; i < SPA_DVAS_PER_BP; i++) {419kmem_cache_destroy(sio_cache[i]);420}421}422423static inline boolean_t424dsl_scan_is_running(const dsl_scan_t *scn)425{426return (scn->scn_phys.scn_state == DSS_SCANNING);427}428429boolean_t430dsl_scan_resilvering(dsl_pool_t *dp)431{432return (dsl_scan_is_running(dp->dp_scan) &&433dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);434}435436static inline void437sio2bp(const scan_io_t *sio, blkptr_t *bp)438{439memset(bp, 0, sizeof (*bp));440bp->blk_prop = sio->sio_blk_prop;441BP_SET_PHYSICAL_BIRTH(bp, sio->sio_phys_birth);442BP_SET_LOGICAL_BIRTH(bp, sio->sio_birth);443bp->blk_fill = 1; /* we always only work with data pointers */444bp->blk_cksum = sio->sio_cksum;445446ASSERT3U(sio->sio_nr_dvas, >, 0);447ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);448449memcpy(bp->blk_dva, sio->sio_dva, sio->sio_nr_dvas * sizeof (dva_t));450}451452static inline void453bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)454{455sio->sio_blk_prop = bp->blk_prop;456sio->sio_phys_birth = BP_GET_RAW_PHYSICAL_BIRTH(bp);457sio->sio_birth = BP_GET_LOGICAL_BIRTH(bp);458sio->sio_cksum = bp->blk_cksum;459sio->sio_nr_dvas = BP_GET_NDVAS(bp);460461/*462* Copy the DVAs to the sio. We need all copies of the block so463* that the self healing code can use the alternate copies if the464* first is corrupted. We want the DVA at index dva_i to be first465* in the sio since this is the primary one that we want to issue.466*/467for (int i = 0, j = dva_i; i < sio->sio_nr_dvas; i++, j++) {468sio->sio_dva[i] = bp->blk_dva[j % sio->sio_nr_dvas];469}470}471472int473dsl_scan_init(dsl_pool_t *dp, uint64_t txg)474{475int err;476dsl_scan_t *scn;477spa_t *spa = dp->dp_spa;478uint64_t f;479480scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);481scn->scn_dp = dp;482483/*484* It's possible that we're resuming a scan after a reboot so485* make sure that the scan_async_destroying flag is initialized486* appropriately.487*/488ASSERT(!scn->scn_async_destroying);489scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,490SPA_FEATURE_ASYNC_DESTROY);491492/*493* Calculate the max number of in-flight bytes for pool-wide494* scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).495* Limits for the issuing phase are done per top-level vdev and496* are handled separately.497*/498scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,499zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));500501avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),502offsetof(scan_ds_t, sds_node));503mutex_init(&scn->scn_queue_lock, NULL, MUTEX_DEFAULT, NULL);504avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,505sizeof (scan_prefetch_issue_ctx_t),506offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));507508err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,509"scrub_func", sizeof (uint64_t), 1, &f);510if (err == 0) {511/*512* There was an old-style scrub in progress. Restart a513* new-style scrub from the beginning.514*/515scn->scn_restart_txg = txg;516zfs_dbgmsg("old-style scrub was in progress for %s; "517"restarting new-style scrub in txg %llu",518spa->spa_name,519(longlong_t)scn->scn_restart_txg);520521/*522* Load the queue obj from the old location so that it523* can be freed by dsl_scan_done().524*/525(void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,526"scrub_queue", sizeof (uint64_t), 1,527&scn->scn_phys.scn_queue_obj);528} else {529err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,530DMU_POOL_ERRORSCRUB, sizeof (uint64_t),531ERRORSCRUB_PHYS_NUMINTS, &scn->errorscrub_phys);532533if (err != 0 && err != ENOENT)534return (err);535536err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,537DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,538&scn->scn_phys);539540/*541* Detect if the pool contains the signature of #2094. If it542* does properly update the scn->scn_phys structure and notify543* the administrator by setting an errata for the pool.544*/545if (err == EOVERFLOW) {546uint64_t zaptmp[SCAN_PHYS_NUMINTS + 1];547VERIFY3S(SCAN_PHYS_NUMINTS, ==, 24);548VERIFY3S(offsetof(dsl_scan_phys_t, scn_flags), ==,549(23 * sizeof (uint64_t)));550551err = zap_lookup(dp->dp_meta_objset,552DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SCAN,553sizeof (uint64_t), SCAN_PHYS_NUMINTS + 1, &zaptmp);554if (err == 0) {555uint64_t overflow = zaptmp[SCAN_PHYS_NUMINTS];556557if (overflow & ~DSL_SCAN_FLAGS_MASK ||558scn->scn_async_destroying) {559spa->spa_errata =560ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY;561return (EOVERFLOW);562}563564memcpy(&scn->scn_phys, zaptmp,565SCAN_PHYS_NUMINTS * sizeof (uint64_t));566scn->scn_phys.scn_flags = overflow;567568/* Required scrub already in progress. */569if (scn->scn_phys.scn_state == DSS_FINISHED ||570scn->scn_phys.scn_state == DSS_CANCELED)571spa->spa_errata =572ZPOOL_ERRATA_ZOL_2094_SCRUB;573}574}575576if (err == ENOENT)577return (0);578else if (err)579return (err);580581/*582* We might be restarting after a reboot, so jump the issued583* counter to how far we've scanned. We know we're consistent584* up to here.585*/586scn->scn_issued_before_pass = scn->scn_phys.scn_examined -587scn->scn_phys.scn_skipped;588589if (dsl_scan_is_running(scn) &&590spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {591/*592* A new-type scrub was in progress on an old593* pool, and the pool was accessed by old594* software. Restart from the beginning, since595* the old software may have changed the pool in596* the meantime.597*/598scn->scn_restart_txg = txg;599zfs_dbgmsg("new-style scrub for %s was modified "600"by old software; restarting in txg %llu",601spa->spa_name,602(longlong_t)scn->scn_restart_txg);603} else if (dsl_scan_resilvering(dp)) {604/*605* If a resilver is in progress and there are already606* errors, restart it instead of finishing this scan and607* then restarting it. If there haven't been any errors608* then remember that the incore DTL is valid.609*/610if (scn->scn_phys.scn_errors > 0) {611scn->scn_restart_txg = txg;612zfs_dbgmsg("resilver can't excise DTL_MISSING "613"when finished; restarting on %s in txg "614"%llu",615spa->spa_name,616(u_longlong_t)scn->scn_restart_txg);617} else {618/* it's safe to excise DTL when finished */619spa->spa_scrub_started = B_TRUE;620}621}622}623624memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));625626/* reload the queue into the in-core state */627if (scn->scn_phys.scn_queue_obj != 0) {628zap_cursor_t zc;629zap_attribute_t *za = zap_attribute_alloc();630631for (zap_cursor_init(&zc, dp->dp_meta_objset,632scn->scn_phys.scn_queue_obj);633zap_cursor_retrieve(&zc, za) == 0;634(void) zap_cursor_advance(&zc)) {635scan_ds_queue_insert(scn,636zfs_strtonum(za->za_name, NULL),637za->za_first_integer);638}639zap_cursor_fini(&zc);640zap_attribute_free(za);641}642643ddt_walk_init(spa, scn->scn_phys.scn_max_txg);644645spa_scan_stat_init(spa);646vdev_scan_stat_init(spa->spa_root_vdev);647648return (0);649}650651void652dsl_scan_fini(dsl_pool_t *dp)653{654if (dp->dp_scan != NULL) {655dsl_scan_t *scn = dp->dp_scan;656657if (scn->scn_taskq != NULL)658taskq_destroy(scn->scn_taskq);659660scan_ds_queue_clear(scn);661avl_destroy(&scn->scn_queue);662mutex_destroy(&scn->scn_queue_lock);663scan_ds_prefetch_queue_clear(scn);664avl_destroy(&scn->scn_prefetch_queue);665666kmem_free(dp->dp_scan, sizeof (dsl_scan_t));667dp->dp_scan = NULL;668}669}670671static boolean_t672dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)673{674return (scn->scn_restart_txg != 0 &&675scn->scn_restart_txg <= tx->tx_txg);676}677678boolean_t679dsl_scan_resilver_scheduled(dsl_pool_t *dp)680{681return ((dp->dp_scan && dp->dp_scan->scn_restart_txg != 0) ||682(spa_async_tasks(dp->dp_spa) & SPA_ASYNC_RESILVER));683}684685boolean_t686dsl_scan_scrubbing(const dsl_pool_t *dp)687{688dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;689690return (scn_phys->scn_state == DSS_SCANNING &&691scn_phys->scn_func == POOL_SCAN_SCRUB);692}693694boolean_t695dsl_errorscrubbing(const dsl_pool_t *dp)696{697dsl_errorscrub_phys_t *errorscrub_phys = &dp->dp_scan->errorscrub_phys;698699return (errorscrub_phys->dep_state == DSS_ERRORSCRUBBING &&700errorscrub_phys->dep_func == POOL_SCAN_ERRORSCRUB);701}702703boolean_t704dsl_errorscrub_is_paused(const dsl_scan_t *scn)705{706return (dsl_errorscrubbing(scn->scn_dp) &&707scn->errorscrub_phys.dep_paused_flags);708}709710boolean_t711dsl_scan_is_paused_scrub(const dsl_scan_t *scn)712{713return (dsl_scan_scrubbing(scn->scn_dp) &&714scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);715}716717static void718dsl_errorscrub_sync_state(dsl_scan_t *scn, dmu_tx_t *tx)719{720scn->errorscrub_phys.dep_cursor =721zap_cursor_serialize(&scn->errorscrub_cursor);722723VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,724DMU_POOL_DIRECTORY_OBJECT,725DMU_POOL_ERRORSCRUB, sizeof (uint64_t), ERRORSCRUB_PHYS_NUMINTS,726&scn->errorscrub_phys, tx));727}728729static void730dsl_errorscrub_setup_sync(void *arg, dmu_tx_t *tx)731{732dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;733pool_scan_func_t *funcp = arg;734dsl_pool_t *dp = scn->scn_dp;735spa_t *spa = dp->dp_spa;736737ASSERT(!dsl_scan_is_running(scn));738ASSERT(!dsl_errorscrubbing(scn->scn_dp));739ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);740741memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));742scn->errorscrub_phys.dep_func = *funcp;743scn->errorscrub_phys.dep_state = DSS_ERRORSCRUBBING;744scn->errorscrub_phys.dep_start_time = gethrestime_sec();745scn->errorscrub_phys.dep_to_examine = spa_get_last_errlog_size(spa);746scn->errorscrub_phys.dep_examined = 0;747scn->errorscrub_phys.dep_errors = 0;748scn->errorscrub_phys.dep_cursor = 0;749zap_cursor_init_serialized(&scn->errorscrub_cursor,750spa->spa_meta_objset, spa->spa_errlog_last,751scn->errorscrub_phys.dep_cursor);752753vdev_config_dirty(spa->spa_root_vdev);754spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_START);755756dsl_errorscrub_sync_state(scn, tx);757758spa_history_log_internal(spa, "error scrub setup", tx,759"func=%u mintxg=%u maxtxg=%llu",760*funcp, 0, (u_longlong_t)tx->tx_txg);761}762763static int764dsl_errorscrub_setup_check(void *arg, dmu_tx_t *tx)765{766(void) arg;767dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;768769if (dsl_scan_is_running(scn) || (dsl_errorscrubbing(scn->scn_dp))) {770return (SET_ERROR(EBUSY));771}772773if (spa_get_last_errlog_size(scn->scn_dp->dp_spa) == 0) {774return (ECANCELED);775}776return (0);777}778779/*780* Writes out a persistent dsl_scan_phys_t record to the pool directory.781* Because we can be running in the block sorting algorithm, we do not always782* want to write out the record, only when it is "safe" to do so. This safety783* condition is achieved by making sure that the sorting queues are empty784* (scn_queues_pending == 0). When this condition is not true, the sync'd state785* is inconsistent with how much actual scanning progress has been made. The786* kind of sync to be performed is specified by the sync_type argument. If the787* sync is optional, we only sync if the queues are empty. If the sync is788* mandatory, we do a hard ASSERT to make sure that the queues are empty. The789* third possible state is a "cached" sync. This is done in response to:790* 1) The dataset that was in the last sync'd dsl_scan_phys_t having been791* destroyed, so we wouldn't be able to restart scanning from it.792* 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been793* superseded by a newer snapshot.794* 3) The dataset that was in the last sync'd dsl_scan_phys_t having been795* swapped with its clone.796* In all cases, a cached sync simply rewrites the last record we've written,797* just slightly modified. For the modifications that are performed to the798* last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,799* dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.800*/801static void802dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)803{804int i;805spa_t *spa = scn->scn_dp->dp_spa;806807ASSERT(sync_type != SYNC_MANDATORY || scn->scn_queues_pending == 0);808if (scn->scn_queues_pending == 0) {809for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {810vdev_t *vd = spa->spa_root_vdev->vdev_child[i];811dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;812813if (q == NULL)814continue;815816mutex_enter(&vd->vdev_scan_io_queue_lock);817ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);818ASSERT3P(zfs_btree_first(&q->q_exts_by_size, NULL), ==,819NULL);820ASSERT3P(zfs_range_tree_first(q->q_exts_by_addr), ==,821NULL);822mutex_exit(&vd->vdev_scan_io_queue_lock);823}824825if (scn->scn_phys.scn_queue_obj != 0)826scan_ds_queue_sync(scn, tx);827VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,828DMU_POOL_DIRECTORY_OBJECT,829DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,830&scn->scn_phys, tx));831memcpy(&scn->scn_phys_cached, &scn->scn_phys,832sizeof (scn->scn_phys));833834if (scn->scn_checkpointing)835zfs_dbgmsg("finish scan checkpoint for %s",836spa->spa_name);837838scn->scn_checkpointing = B_FALSE;839scn->scn_last_checkpoint = ddi_get_lbolt();840} else if (sync_type == SYNC_CACHED) {841VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,842DMU_POOL_DIRECTORY_OBJECT,843DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,844&scn->scn_phys_cached, tx));845}846}847848int849dsl_scan_setup_check(void *arg, dmu_tx_t *tx)850{851(void) arg;852dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;853vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;854855if (dsl_scan_is_running(scn) || vdev_rebuild_active(rvd) ||856dsl_errorscrubbing(scn->scn_dp))857return (SET_ERROR(EBUSY));858859return (0);860}861862void863dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)864{865setup_sync_arg_t *setup_sync_arg = (setup_sync_arg_t *)arg;866dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;867dmu_object_type_t ot = 0;868dsl_pool_t *dp = scn->scn_dp;869spa_t *spa = dp->dp_spa;870871ASSERT(!dsl_scan_is_running(scn));872ASSERT3U(setup_sync_arg->func, >, POOL_SCAN_NONE);873ASSERT3U(setup_sync_arg->func, <, POOL_SCAN_FUNCS);874memset(&scn->scn_phys, 0, sizeof (scn->scn_phys));875876/*877* If we are starting a fresh scrub, we erase the error scrub878* information from disk.879*/880memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));881dsl_errorscrub_sync_state(scn, tx);882883scn->scn_phys.scn_func = setup_sync_arg->func;884scn->scn_phys.scn_state = DSS_SCANNING;885scn->scn_phys.scn_min_txg = setup_sync_arg->txgstart;886if (setup_sync_arg->txgend == 0) {887scn->scn_phys.scn_max_txg = tx->tx_txg;888} else {889scn->scn_phys.scn_max_txg = setup_sync_arg->txgend;890}891scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */892scn->scn_phys.scn_start_time = gethrestime_sec();893scn->scn_phys.scn_errors = 0;894scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;895scn->scn_issued_before_pass = 0;896scn->scn_restart_txg = 0;897scn->scn_done_txg = 0;898scn->scn_last_checkpoint = 0;899scn->scn_checkpointing = B_FALSE;900spa_scan_stat_init(spa);901vdev_scan_stat_init(spa->spa_root_vdev);902903if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {904scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;905906/* rewrite all disk labels */907vdev_config_dirty(spa->spa_root_vdev);908909if (vdev_resilver_needed(spa->spa_root_vdev,910&scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {911nvlist_t *aux = fnvlist_alloc();912fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,913"healing");914spa_event_notify(spa, NULL, aux,915ESC_ZFS_RESILVER_START);916nvlist_free(aux);917} else {918spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);919}920921spa->spa_scrub_started = B_TRUE;922/*923* If this is an incremental scrub, limit the DDT scrub phase924* to just the auto-ditto class (for correctness); the rest925* of the scrub should go faster using top-down pruning.926*/927if (scn->scn_phys.scn_min_txg > TXG_INITIAL)928scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;929930/*931* When starting a resilver clear any existing rebuild state.932* This is required to prevent stale rebuild status from933* being reported when a rebuild is run, then a resilver and934* finally a scrub. In which case only the scrub status935* should be reported by 'zpool status'.936*/937if (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) {938vdev_t *rvd = spa->spa_root_vdev;939for (uint64_t i = 0; i < rvd->vdev_children; i++) {940vdev_t *vd = rvd->vdev_child[i];941vdev_rebuild_clear_sync(942(void *)(uintptr_t)vd->vdev_id, tx);943}944}945}946947/* back to the generic stuff */948949if (zfs_scan_blkstats) {950if (dp->dp_blkstats == NULL) {951dp->dp_blkstats =952vmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);953}954memset(&dp->dp_blkstats->zab_type, 0,955sizeof (dp->dp_blkstats->zab_type));956} else {957if (dp->dp_blkstats) {958vmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));959dp->dp_blkstats = NULL;960}961}962963if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)964ot = DMU_OT_ZAP_OTHER;965966scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,967ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);968969memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));970971ddt_walk_init(spa, scn->scn_phys.scn_max_txg);972973dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);974975spa_history_log_internal(spa, "scan setup", tx,976"func=%u mintxg=%llu maxtxg=%llu",977setup_sync_arg->func, (u_longlong_t)scn->scn_phys.scn_min_txg,978(u_longlong_t)scn->scn_phys.scn_max_txg);979}980981/*982* Called by ZFS_IOC_POOL_SCRUB and ZFS_IOC_POOL_SCAN ioctl to start a scrub,983* error scrub or resilver. Can also be called to resume a paused scrub or984* error scrub.985*/986int987dsl_scan(dsl_pool_t *dp, pool_scan_func_t func, uint64_t txgstart,988uint64_t txgend)989{990spa_t *spa = dp->dp_spa;991dsl_scan_t *scn = dp->dp_scan;992setup_sync_arg_t setup_sync_arg;993994if (func != POOL_SCAN_SCRUB && (txgstart != 0 || txgend != 0)) {995return (EINVAL);996}997998/*999* Purge all vdev caches and probe all devices. We do this here1000* rather than in sync context because this requires a writer lock1001* on the spa_config lock, which we can't do from sync context. The1002* spa_scrub_reopen flag indicates that vdev_open() should not1003* attempt to start another scrub.1004*/1005spa_vdev_state_enter(spa, SCL_NONE);1006spa->spa_scrub_reopen = B_TRUE;1007vdev_reopen(spa->spa_root_vdev);1008spa->spa_scrub_reopen = B_FALSE;1009(void) spa_vdev_state_exit(spa, NULL, 0);10101011if (func == POOL_SCAN_RESILVER) {1012dsl_scan_restart_resilver(spa->spa_dsl_pool, 0);1013return (0);1014}10151016if (func == POOL_SCAN_ERRORSCRUB) {1017if (dsl_errorscrub_is_paused(dp->dp_scan)) {1018/*1019* got error scrub start cmd, resume paused error scrub.1020*/1021int err = dsl_scrub_set_pause_resume(scn->scn_dp,1022POOL_SCRUB_NORMAL);1023if (err == 0) {1024spa_event_notify(spa, NULL, NULL,1025ESC_ZFS_ERRORSCRUB_RESUME);1026return (0);1027}1028return (SET_ERROR(err));1029}10301031return (dsl_sync_task(spa_name(dp->dp_spa),1032dsl_errorscrub_setup_check, dsl_errorscrub_setup_sync,1033&func, 0, ZFS_SPACE_CHECK_RESERVED));1034}10351036if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {1037/* got scrub start cmd, resume paused scrub */1038int err = dsl_scrub_set_pause_resume(scn->scn_dp,1039POOL_SCRUB_NORMAL);1040if (err == 0) {1041spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);1042return (0);1043}1044return (SET_ERROR(err));1045}10461047setup_sync_arg.func = func;1048setup_sync_arg.txgstart = txgstart;1049setup_sync_arg.txgend = txgend;10501051return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,1052dsl_scan_setup_sync, &setup_sync_arg, 0,1053ZFS_SPACE_CHECK_EXTRA_RESERVED));1054}10551056static void1057dsl_errorscrub_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)1058{1059dsl_pool_t *dp = scn->scn_dp;1060spa_t *spa = dp->dp_spa;10611062if (complete) {1063spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_FINISH);1064spa_history_log_internal(spa, "error scrub done", tx,1065"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1066} else {1067spa_history_log_internal(spa, "error scrub canceled", tx,1068"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1069}10701071scn->errorscrub_phys.dep_state = complete ? DSS_FINISHED : DSS_CANCELED;1072spa->spa_scrub_active = B_FALSE;1073spa_errlog_rotate(spa);1074scn->errorscrub_phys.dep_end_time = gethrestime_sec();1075zap_cursor_fini(&scn->errorscrub_cursor);10761077if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)1078spa->spa_errata = 0;10791080ASSERT(!dsl_errorscrubbing(scn->scn_dp));1081}10821083static void1084dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)1085{1086static const char *old_names[] = {1087"scrub_bookmark",1088"scrub_ddt_bookmark",1089"scrub_ddt_class_max",1090"scrub_queue",1091"scrub_min_txg",1092"scrub_max_txg",1093"scrub_func",1094"scrub_errors",1095NULL1096};10971098dsl_pool_t *dp = scn->scn_dp;1099spa_t *spa = dp->dp_spa;1100int i;11011102/* Remove any remnants of an old-style scrub. */1103for (i = 0; old_names[i]; i++) {1104(void) zap_remove(dp->dp_meta_objset,1105DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);1106}11071108if (scn->scn_phys.scn_queue_obj != 0) {1109VERIFY0(dmu_object_free(dp->dp_meta_objset,1110scn->scn_phys.scn_queue_obj, tx));1111scn->scn_phys.scn_queue_obj = 0;1112}1113scan_ds_queue_clear(scn);1114scan_ds_prefetch_queue_clear(scn);11151116scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;11171118/*1119* If we were "restarted" from a stopped state, don't bother1120* with anything else.1121*/1122if (!dsl_scan_is_running(scn)) {1123ASSERT(!scn->scn_is_sorted);1124return;1125}11261127if (scn->scn_is_sorted) {1128scan_io_queues_destroy(scn);1129scn->scn_is_sorted = B_FALSE;11301131if (scn->scn_taskq != NULL) {1132taskq_destroy(scn->scn_taskq);1133scn->scn_taskq = NULL;1134}1135}11361137if (dsl_scan_restarting(scn, tx)) {1138spa_history_log_internal(spa, "scan aborted, restarting", tx,1139"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1140} else if (!complete) {1141spa_history_log_internal(spa, "scan cancelled", tx,1142"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1143} else {1144spa_history_log_internal(spa, "scan done", tx,1145"errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));1146if (DSL_SCAN_IS_SCRUB(scn)) {1147VERIFY0(zap_update(dp->dp_meta_objset,1148DMU_POOL_DIRECTORY_OBJECT,1149DMU_POOL_LAST_SCRUBBED_TXG,1150sizeof (uint64_t), 1,1151&scn->scn_phys.scn_max_txg, tx));1152spa->spa_scrubbed_last_txg = scn->scn_phys.scn_max_txg;1153}1154}11551156if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {1157spa->spa_scrub_active = B_FALSE;11581159/*1160* If the scrub/resilver completed, update all DTLs to1161* reflect this. Whether it succeeded or not, vacate1162* all temporary scrub DTLs.1163*1164* As the scrub does not currently support traversing1165* data that have been freed but are part of a checkpoint,1166* we don't mark the scrub as done in the DTLs as faults1167* may still exist in those vdevs.1168*/1169if (complete &&1170!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {1171vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,1172scn->scn_phys.scn_max_txg, B_TRUE, B_FALSE);11731174if (DSL_SCAN_IS_RESILVER(scn)) {1175nvlist_t *aux = fnvlist_alloc();1176fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,1177"healing");1178spa_event_notify(spa, NULL, aux,1179ESC_ZFS_RESILVER_FINISH);1180nvlist_free(aux);1181} else {1182spa_event_notify(spa, NULL, NULL,1183ESC_ZFS_SCRUB_FINISH);1184}1185} else {1186vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,11870, B_TRUE, B_FALSE);1188}1189spa_errlog_rotate(spa);11901191/*1192* Don't clear flag until after vdev_dtl_reassess to ensure that1193* DTL_MISSING will get updated when possible.1194*/1195scn->scn_phys.scn_state = complete ? DSS_FINISHED :1196DSS_CANCELED;1197scn->scn_phys.scn_end_time = gethrestime_sec();1198spa->spa_scrub_started = B_FALSE;11991200/*1201* We may have finished replacing a device.1202* Let the async thread assess this and handle the detach.1203*/1204spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);12051206/*1207* Clear any resilver_deferred flags in the config.1208* If there are drives that need resilvering, kick1209* off an asynchronous request to start resilver.1210* vdev_clear_resilver_deferred() may update the config1211* before the resilver can restart. In the event of1212* a crash during this period, the spa loading code1213* will find the drives that need to be resilvered1214* and start the resilver then.1215*/1216if (spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER) &&1217vdev_clear_resilver_deferred(spa->spa_root_vdev, tx)) {1218spa_history_log_internal(spa,1219"starting deferred resilver", tx, "errors=%llu",1220(u_longlong_t)spa_approx_errlog_size(spa));1221spa_async_request(spa, SPA_ASYNC_RESILVER);1222}12231224/* Clear recent error events (i.e. duplicate events tracking) */1225if (complete)1226zfs_ereport_clear(spa, NULL);1227} else {1228scn->scn_phys.scn_state = complete ? DSS_FINISHED :1229DSS_CANCELED;1230scn->scn_phys.scn_end_time = gethrestime_sec();1231}12321233spa_notify_waiters(spa);12341235if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)1236spa->spa_errata = 0;12371238ASSERT(!dsl_scan_is_running(scn));1239}12401241static int1242dsl_errorscrub_pause_resume_check(void *arg, dmu_tx_t *tx)1243{1244pool_scrub_cmd_t *cmd = arg;1245dsl_pool_t *dp = dmu_tx_pool(tx);1246dsl_scan_t *scn = dp->dp_scan;12471248if (*cmd == POOL_SCRUB_PAUSE) {1249/*1250* can't pause a error scrub when there is no in-progress1251* error scrub.1252*/1253if (!dsl_errorscrubbing(dp))1254return (SET_ERROR(ENOENT));12551256/* can't pause a paused error scrub */1257if (dsl_errorscrub_is_paused(scn))1258return (SET_ERROR(EBUSY));1259} else if (*cmd != POOL_SCRUB_NORMAL) {1260return (SET_ERROR(ENOTSUP));1261}12621263return (0);1264}12651266static void1267dsl_errorscrub_pause_resume_sync(void *arg, dmu_tx_t *tx)1268{1269pool_scrub_cmd_t *cmd = arg;1270dsl_pool_t *dp = dmu_tx_pool(tx);1271spa_t *spa = dp->dp_spa;1272dsl_scan_t *scn = dp->dp_scan;12731274if (*cmd == POOL_SCRUB_PAUSE) {1275spa->spa_scan_pass_errorscrub_pause = gethrestime_sec();1276scn->errorscrub_phys.dep_paused_flags = B_TRUE;1277dsl_errorscrub_sync_state(scn, tx);1278spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_PAUSED);1279} else {1280ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);1281if (dsl_errorscrub_is_paused(scn)) {1282/*1283* We need to keep track of how much time we spend1284* paused per pass so that we can adjust the error scrub1285* rate shown in the output of 'zpool status'.1286*/1287spa->spa_scan_pass_errorscrub_spent_paused +=1288gethrestime_sec() -1289spa->spa_scan_pass_errorscrub_pause;12901291spa->spa_scan_pass_errorscrub_pause = 0;1292scn->errorscrub_phys.dep_paused_flags = B_FALSE;12931294zap_cursor_init_serialized(1295&scn->errorscrub_cursor,1296spa->spa_meta_objset, spa->spa_errlog_last,1297scn->errorscrub_phys.dep_cursor);12981299dsl_errorscrub_sync_state(scn, tx);1300}1301}1302}13031304static int1305dsl_errorscrub_cancel_check(void *arg, dmu_tx_t *tx)1306{1307(void) arg;1308dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;1309/* can't cancel a error scrub when there is no one in-progress */1310if (!dsl_errorscrubbing(scn->scn_dp))1311return (SET_ERROR(ENOENT));1312return (0);1313}13141315static void1316dsl_errorscrub_cancel_sync(void *arg, dmu_tx_t *tx)1317{1318(void) arg;1319dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13201321dsl_errorscrub_done(scn, B_FALSE, tx);1322dsl_errorscrub_sync_state(scn, tx);1323spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL,1324ESC_ZFS_ERRORSCRUB_ABORT);1325}13261327static int1328dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)1329{1330(void) arg;1331dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13321333if (!dsl_scan_is_running(scn))1334return (SET_ERROR(ENOENT));1335return (0);1336}13371338static void1339dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)1340{1341(void) arg;1342dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;13431344dsl_scan_done(scn, B_FALSE, tx);1345dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);1346spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);1347}13481349int1350dsl_scan_cancel(dsl_pool_t *dp)1351{1352if (dsl_errorscrubbing(dp)) {1353return (dsl_sync_task(spa_name(dp->dp_spa),1354dsl_errorscrub_cancel_check, dsl_errorscrub_cancel_sync,1355NULL, 3, ZFS_SPACE_CHECK_RESERVED));1356}1357return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,1358dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));1359}13601361static int1362dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)1363{1364pool_scrub_cmd_t *cmd = arg;1365dsl_pool_t *dp = dmu_tx_pool(tx);1366dsl_scan_t *scn = dp->dp_scan;13671368if (*cmd == POOL_SCRUB_PAUSE) {1369/* can't pause a scrub when there is no in-progress scrub */1370if (!dsl_scan_scrubbing(dp))1371return (SET_ERROR(ENOENT));13721373/* can't pause a paused scrub */1374if (dsl_scan_is_paused_scrub(scn))1375return (SET_ERROR(EBUSY));1376} else if (*cmd != POOL_SCRUB_NORMAL) {1377return (SET_ERROR(ENOTSUP));1378}13791380return (0);1381}13821383static void1384dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)1385{1386pool_scrub_cmd_t *cmd = arg;1387dsl_pool_t *dp = dmu_tx_pool(tx);1388spa_t *spa = dp->dp_spa;1389dsl_scan_t *scn = dp->dp_scan;13901391if (*cmd == POOL_SCRUB_PAUSE) {1392/* can't pause a scrub when there is no in-progress scrub */1393spa->spa_scan_pass_scrub_pause = gethrestime_sec();1394scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;1395scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED;1396dsl_scan_sync_state(scn, tx, SYNC_CACHED);1397spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);1398spa_notify_waiters(spa);1399} else {1400ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);1401if (dsl_scan_is_paused_scrub(scn)) {1402/*1403* We need to keep track of how much time we spend1404* paused per pass so that we can adjust the scrub rate1405* shown in the output of 'zpool status'1406*/1407spa->spa_scan_pass_scrub_spent_paused +=1408gethrestime_sec() - spa->spa_scan_pass_scrub_pause;1409spa->spa_scan_pass_scrub_pause = 0;1410scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;1411scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED;1412dsl_scan_sync_state(scn, tx, SYNC_CACHED);1413}1414}1415}14161417/*1418* Set scrub pause/resume state if it makes sense to do so1419*/1420int1421dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)1422{1423if (dsl_errorscrubbing(dp)) {1424return (dsl_sync_task(spa_name(dp->dp_spa),1425dsl_errorscrub_pause_resume_check,1426dsl_errorscrub_pause_resume_sync, &cmd, 3,1427ZFS_SPACE_CHECK_RESERVED));1428}1429return (dsl_sync_task(spa_name(dp->dp_spa),1430dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,1431ZFS_SPACE_CHECK_RESERVED));1432}143314341435/* start a new scan, or restart an existing one. */1436void1437dsl_scan_restart_resilver(dsl_pool_t *dp, uint64_t txg)1438{1439if (txg == 0) {1440dmu_tx_t *tx;1441tx = dmu_tx_create_dd(dp->dp_mos_dir);1442VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));14431444txg = dmu_tx_get_txg(tx);1445dp->dp_scan->scn_restart_txg = txg;1446dmu_tx_commit(tx);1447} else {1448dp->dp_scan->scn_restart_txg = txg;1449}1450zfs_dbgmsg("restarting resilver for %s at txg=%llu",1451dp->dp_spa->spa_name, (longlong_t)txg);1452}14531454void1455dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)1456{1457zio_free(dp->dp_spa, txg, bp);1458}14591460void1461dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)1462{1463ASSERT(dsl_pool_sync_context(dp));1464zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));1465}14661467static int1468scan_ds_queue_compare(const void *a, const void *b)1469{1470const scan_ds_t *sds_a = a, *sds_b = b;14711472if (sds_a->sds_dsobj < sds_b->sds_dsobj)1473return (-1);1474if (sds_a->sds_dsobj == sds_b->sds_dsobj)1475return (0);1476return (1);1477}14781479static void1480scan_ds_queue_clear(dsl_scan_t *scn)1481{1482void *cookie = NULL;1483scan_ds_t *sds;1484while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {1485kmem_free(sds, sizeof (*sds));1486}1487}14881489static boolean_t1490scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)1491{1492scan_ds_t srch, *sds;14931494srch.sds_dsobj = dsobj;1495sds = avl_find(&scn->scn_queue, &srch, NULL);1496if (sds != NULL && txg != NULL)1497*txg = sds->sds_txg;1498return (sds != NULL);1499}15001501static void1502scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)1503{1504scan_ds_t *sds;1505avl_index_t where;15061507sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);1508sds->sds_dsobj = dsobj;1509sds->sds_txg = txg;15101511VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);1512avl_insert(&scn->scn_queue, sds, where);1513}15141515static void1516scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)1517{1518scan_ds_t srch, *sds;15191520srch.sds_dsobj = dsobj;15211522sds = avl_find(&scn->scn_queue, &srch, NULL);1523VERIFY(sds != NULL);1524avl_remove(&scn->scn_queue, sds);1525kmem_free(sds, sizeof (*sds));1526}15271528static void1529scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)1530{1531dsl_pool_t *dp = scn->scn_dp;1532spa_t *spa = dp->dp_spa;1533dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?1534DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;15351536ASSERT0(scn->scn_queues_pending);1537ASSERT(scn->scn_phys.scn_queue_obj != 0);15381539VERIFY0(dmu_object_free(dp->dp_meta_objset,1540scn->scn_phys.scn_queue_obj, tx));1541scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,1542DMU_OT_NONE, 0, tx);1543for (scan_ds_t *sds = avl_first(&scn->scn_queue);1544sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {1545VERIFY0(zap_add_int_key(dp->dp_meta_objset,1546scn->scn_phys.scn_queue_obj, sds->sds_dsobj,1547sds->sds_txg, tx));1548}1549}15501551/*1552* Computes the memory limit state that we're currently in. A sorted scan1553* needs quite a bit of memory to hold the sorting queue, so we need to1554* reasonably constrain the size so it doesn't impact overall system1555* performance. We compute two limits:1556* 1) Hard memory limit: if the amount of memory used by the sorting1557* queues on a pool gets above this value, we stop the metadata1558* scanning portion and start issuing the queued up and sorted1559* I/Os to reduce memory usage.1560* This limit is calculated as a fraction of physmem (by default 5%).1561* We constrain the lower bound of the hard limit to an absolute1562* minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain1563* the upper bound to 5% of the total pool size - no chance we'll1564* ever need that much memory, but just to keep the value in check.1565* 2) Soft memory limit: once we hit the hard memory limit, we start1566* issuing I/O to reduce queue memory usage, but we don't want to1567* completely empty out the queues, since we might be able to find I/Os1568* that will fill in the gaps of our non-sequential IOs at some point1569* in the future. So we stop the issuing of I/Os once the amount of1570* memory used drops below the soft limit (at which point we stop issuing1571* I/O and start scanning metadata again).1572*1573* This limit is calculated by subtracting a fraction of the hard1574* limit from the hard limit. By default this fraction is 5%, so1575* the soft limit is 95% of the hard limit. We cap the size of the1576* difference between the hard and soft limits at an absolute1577* maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is1578* sufficient to not cause too frequent switching between the1579* metadata scan and I/O issue (even at 2k recordsize, 128 MiB's1580* worth of queues is about 1.2 GiB of on-pool data, so scanning1581* that should take at least a decent fraction of a second).1582*/1583static boolean_t1584dsl_scan_should_clear(dsl_scan_t *scn)1585{1586spa_t *spa = scn->scn_dp->dp_spa;1587vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;1588uint64_t alloc, mlim_hard, mlim_soft, mused;15891590alloc = metaslab_class_get_alloc(spa_normal_class(spa));1591alloc += metaslab_class_get_alloc(spa_special_class(spa));1592alloc += metaslab_class_get_alloc(spa_dedup_class(spa));15931594mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,1595zfs_scan_mem_lim_min);1596mlim_hard = MIN(mlim_hard, alloc / 20);1597mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,1598zfs_scan_mem_lim_soft_max);1599mused = 0;1600for (uint64_t i = 0; i < rvd->vdev_children; i++) {1601vdev_t *tvd = rvd->vdev_child[i];1602dsl_scan_io_queue_t *queue;16031604mutex_enter(&tvd->vdev_scan_io_queue_lock);1605queue = tvd->vdev_scan_io_queue;1606if (queue != NULL) {1607/*1608* # of extents in exts_by_addr = # in exts_by_size.1609* B-tree efficiency is ~75%, but can be as low as 50%.1610*/1611mused += zfs_btree_numnodes(&queue->q_exts_by_size) * ((1612sizeof (zfs_range_seg_gap_t) + sizeof (uint64_t)) *16133 / 2) + queue->q_sio_memused;1614}1615mutex_exit(&tvd->vdev_scan_io_queue_lock);1616}16171618dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);16191620if (mused == 0)1621ASSERT0(scn->scn_queues_pending);16221623/*1624* If we are above our hard limit, we need to clear out memory.1625* If we are below our soft limit, we need to accumulate sequential IOs.1626* Otherwise, we should keep doing whatever we are currently doing.1627*/1628if (mused >= mlim_hard)1629return (B_TRUE);1630else if (mused < mlim_soft)1631return (B_FALSE);1632else1633return (scn->scn_clearing);1634}16351636static boolean_t1637dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)1638{1639/* we never skip user/group accounting objects */1640if (zb && (int64_t)zb->zb_object < 0)1641return (B_FALSE);16421643if (scn->scn_suspending)1644return (B_TRUE); /* we're already suspending */16451646if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))1647return (B_FALSE); /* we're resuming */16481649/* We only know how to resume from level-0 and objset blocks. */1650if (zb && (zb->zb_level != 0 && zb->zb_level != ZB_ROOT_LEVEL))1651return (B_FALSE);16521653/*1654* We suspend if:1655* - we have scanned for at least the minimum time (default 1 sec1656* for scrub, 3 sec for resilver), and either we have sufficient1657* dirty data that we are starting to write more quickly1658* (default 30%), someone is explicitly waiting for this txg1659* to complete, or we have used up all of the time in the txg1660* timeout (default 5 sec).1661* or1662* - the spa is shutting down because this pool is being exported1663* or the machine is rebooting.1664* or1665* - the scan queue has reached its memory use limit1666*/1667uint64_t curr_time_ns = gethrtime();1668uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;1669uint64_t sync_time_ns = curr_time_ns -1670scn->scn_dp->dp_spa->spa_sync_starttime;1671uint64_t dirty_min_bytes = zfs_dirty_data_max *1672zfs_vdev_async_write_active_min_dirty_percent / 100;1673uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?1674zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;16751676if ((NSEC2MSEC(scan_time_ns) > mintime &&1677(scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||1678txg_sync_waiting(scn->scn_dp) ||1679NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||1680spa_shutting_down(scn->scn_dp->dp_spa) ||1681(zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn)) ||1682!ddt_walk_ready(scn->scn_dp->dp_spa)) {1683if (zb && zb->zb_level == ZB_ROOT_LEVEL) {1684dprintf("suspending at first available bookmark "1685"%llx/%llx/%llx/%llx\n",1686(longlong_t)zb->zb_objset,1687(longlong_t)zb->zb_object,1688(longlong_t)zb->zb_level,1689(longlong_t)zb->zb_blkid);1690SET_BOOKMARK(&scn->scn_phys.scn_bookmark,1691zb->zb_objset, 0, 0, 0);1692} else if (zb != NULL) {1693dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",1694(longlong_t)zb->zb_objset,1695(longlong_t)zb->zb_object,1696(longlong_t)zb->zb_level,1697(longlong_t)zb->zb_blkid);1698scn->scn_phys.scn_bookmark = *zb;1699} else {1700#ifdef ZFS_DEBUG1701dsl_scan_phys_t *scnp = &scn->scn_phys;1702dprintf("suspending at at DDT bookmark "1703"%llx/%llx/%llx/%llx\n",1704(longlong_t)scnp->scn_ddt_bookmark.ddb_class,1705(longlong_t)scnp->scn_ddt_bookmark.ddb_type,1706(longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,1707(longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);1708#endif1709}1710scn->scn_suspending = B_TRUE;1711return (B_TRUE);1712}1713return (B_FALSE);1714}17151716static boolean_t1717dsl_error_scrub_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)1718{1719/*1720* We suspend if:1721* - we have scrubbed for at least the minimum time (default 1 sec1722* for error scrub), someone is explicitly waiting for this txg1723* to complete, or we have used up all of the time in the txg1724* timeout (default 5 sec).1725* or1726* - the spa is shutting down because this pool is being exported1727* or the machine is rebooting.1728*/1729uint64_t curr_time_ns = gethrtime();1730uint64_t error_scrub_time_ns = curr_time_ns - scn->scn_sync_start_time;1731uint64_t sync_time_ns = curr_time_ns -1732scn->scn_dp->dp_spa->spa_sync_starttime;1733int mintime = zfs_scrub_min_time_ms;17341735if ((NSEC2MSEC(error_scrub_time_ns) > mintime &&1736(txg_sync_waiting(scn->scn_dp) ||1737NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||1738spa_shutting_down(scn->scn_dp->dp_spa)) {1739if (zb) {1740dprintf("error scrub suspending at bookmark "1741"%llx/%llx/%llx/%llx\n",1742(longlong_t)zb->zb_objset,1743(longlong_t)zb->zb_object,1744(longlong_t)zb->zb_level,1745(longlong_t)zb->zb_blkid);1746}1747return (B_TRUE);1748}1749return (B_FALSE);1750}17511752typedef struct zil_scan_arg {1753dsl_pool_t *zsa_dp;1754zil_header_t *zsa_zh;1755} zil_scan_arg_t;17561757static int1758dsl_scan_zil_block(zilog_t *zilog, const blkptr_t *bp, void *arg,1759uint64_t claim_txg)1760{1761(void) zilog;1762zil_scan_arg_t *zsa = arg;1763dsl_pool_t *dp = zsa->zsa_dp;1764dsl_scan_t *scn = dp->dp_scan;1765zil_header_t *zh = zsa->zsa_zh;1766zbookmark_phys_t zb;17671768ASSERT(!BP_IS_REDACTED(bp));1769if (BP_IS_HOLE(bp) ||1770BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)1771return (0);17721773/*1774* One block ("stubby") can be allocated a long time ago; we1775* want to visit that one because it has been allocated1776* (on-disk) even if it hasn't been claimed (even though for1777* scrub there's nothing to do to it).1778*/1779if (claim_txg == 0 &&1780BP_GET_BIRTH(bp) >= spa_min_claim_txg(dp->dp_spa))1781return (0);17821783SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],1784ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);17851786VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));1787return (0);1788}17891790static int1791dsl_scan_zil_record(zilog_t *zilog, const lr_t *lrc, void *arg,1792uint64_t claim_txg)1793{1794(void) zilog;1795if (lrc->lrc_txtype == TX_WRITE) {1796zil_scan_arg_t *zsa = arg;1797dsl_pool_t *dp = zsa->zsa_dp;1798dsl_scan_t *scn = dp->dp_scan;1799zil_header_t *zh = zsa->zsa_zh;1800const lr_write_t *lr = (const lr_write_t *)lrc;1801const blkptr_t *bp = &lr->lr_blkptr;1802zbookmark_phys_t zb;18031804ASSERT(!BP_IS_REDACTED(bp));1805if (BP_IS_HOLE(bp) ||1806BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)1807return (0);18081809/*1810* birth can be < claim_txg if this record's txg is1811* already txg sync'ed (but this log block contains1812* other records that are not synced)1813*/1814if (claim_txg == 0 || BP_GET_BIRTH(bp) < claim_txg)1815return (0);18161817ASSERT3U(BP_GET_LSIZE(bp), !=, 0);1818SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],1819lr->lr_foid, ZB_ZIL_LEVEL,1820lr->lr_offset / BP_GET_LSIZE(bp));18211822VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));1823}1824return (0);1825}18261827static void1828dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)1829{1830uint64_t claim_txg = zh->zh_claim_txg;1831zil_scan_arg_t zsa = { dp, zh };1832zilog_t *zilog;18331834ASSERT(spa_writeable(dp->dp_spa));18351836/*1837* We only want to visit blocks that have been claimed but not yet1838* replayed (or, in read-only mode, blocks that *would* be claimed).1839*/1840if (claim_txg == 0)1841return;18421843zilog = zil_alloc(dp->dp_meta_objset, zh);18441845(void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,1846claim_txg, B_FALSE);18471848zil_free(zilog);1849}18501851/*1852* We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea1853* here is to sort the AVL tree by the order each block will be needed.1854*/1855static int1856scan_prefetch_queue_compare(const void *a, const void *b)1857{1858const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;1859const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;1860const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;18611862return (zbookmark_compare(spc_a->spc_datablkszsec,1863spc_a->spc_indblkshift, spc_b->spc_datablkszsec,1864spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));1865}18661867static void1868scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, const void *tag)1869{1870if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {1871zfs_refcount_destroy(&spc->spc_refcnt);1872kmem_free(spc, sizeof (scan_prefetch_ctx_t));1873}1874}18751876static scan_prefetch_ctx_t *1877scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, const void *tag)1878{1879scan_prefetch_ctx_t *spc;18801881spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);1882zfs_refcount_create(&spc->spc_refcnt);1883zfs_refcount_add(&spc->spc_refcnt, tag);1884spc->spc_scn = scn;1885if (dnp != NULL) {1886spc->spc_datablkszsec = dnp->dn_datablkszsec;1887spc->spc_indblkshift = dnp->dn_indblkshift;1888spc->spc_root = B_FALSE;1889} else {1890spc->spc_datablkszsec = 0;1891spc->spc_indblkshift = 0;1892spc->spc_root = B_TRUE;1893}18941895return (spc);1896}18971898static void1899scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, const void *tag)1900{1901zfs_refcount_add(&spc->spc_refcnt, tag);1902}19031904static void1905scan_ds_prefetch_queue_clear(dsl_scan_t *scn)1906{1907spa_t *spa = scn->scn_dp->dp_spa;1908void *cookie = NULL;1909scan_prefetch_issue_ctx_t *spic = NULL;19101911mutex_enter(&spa->spa_scrub_lock);1912while ((spic = avl_destroy_nodes(&scn->scn_prefetch_queue,1913&cookie)) != NULL) {1914scan_prefetch_ctx_rele(spic->spic_spc, scn);1915kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));1916}1917mutex_exit(&spa->spa_scrub_lock);1918}19191920static boolean_t1921dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,1922const zbookmark_phys_t *zb)1923{1924zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;1925dnode_phys_t tmp_dnp;1926dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;19271928if (zb->zb_objset != last_zb->zb_objset)1929return (B_TRUE);1930if ((int64_t)zb->zb_object < 0)1931return (B_FALSE);19321933tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;1934tmp_dnp.dn_indblkshift = spc->spc_indblkshift;19351936if (zbookmark_subtree_completed(dnp, zb, last_zb))1937return (B_TRUE);19381939return (B_FALSE);1940}19411942static void1943dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)1944{1945avl_index_t idx;1946dsl_scan_t *scn = spc->spc_scn;1947spa_t *spa = scn->scn_dp->dp_spa;1948scan_prefetch_issue_ctx_t *spic;19491950if (zfs_no_scrub_prefetch || BP_IS_REDACTED(bp))1951return;19521953if (BP_IS_HOLE(bp) ||1954BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg ||1955(BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&1956BP_GET_TYPE(bp) != DMU_OT_OBJSET))1957return;19581959if (dsl_scan_check_prefetch_resume(spc, zb))1960return;19611962scan_prefetch_ctx_add_ref(spc, scn);1963spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);1964spic->spic_spc = spc;1965spic->spic_bp = *bp;1966spic->spic_zb = *zb;19671968/*1969* Add the IO to the queue of blocks to prefetch. This allows us to1970* prioritize blocks that we will need first for the main traversal1971* thread.1972*/1973mutex_enter(&spa->spa_scrub_lock);1974if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {1975/* this block is already queued for prefetch */1976kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));1977scan_prefetch_ctx_rele(spc, scn);1978mutex_exit(&spa->spa_scrub_lock);1979return;1980}19811982avl_insert(&scn->scn_prefetch_queue, spic, idx);1983cv_broadcast(&spa->spa_scrub_io_cv);1984mutex_exit(&spa->spa_scrub_lock);1985}19861987static void1988dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,1989uint64_t objset, uint64_t object)1990{1991int i;1992zbookmark_phys_t zb;1993scan_prefetch_ctx_t *spc;19941995if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))1996return;19971998SET_BOOKMARK(&zb, objset, object, 0, 0);19992000spc = scan_prefetch_ctx_create(scn, dnp, FTAG);20012002for (i = 0; i < dnp->dn_nblkptr; i++) {2003zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);2004zb.zb_blkid = i;2005dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);2006}20072008if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {2009zb.zb_level = 0;2010zb.zb_blkid = DMU_SPILL_BLKID;2011dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);2012}20132014scan_prefetch_ctx_rele(spc, FTAG);2015}20162017static void2018dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,2019arc_buf_t *buf, void *private)2020{2021(void) zio;2022scan_prefetch_ctx_t *spc = private;2023dsl_scan_t *scn = spc->spc_scn;2024spa_t *spa = scn->scn_dp->dp_spa;20252026/* broadcast that the IO has completed for rate limiting purposes */2027mutex_enter(&spa->spa_scrub_lock);2028ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));2029spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);2030cv_broadcast(&spa->spa_scrub_io_cv);2031mutex_exit(&spa->spa_scrub_lock);20322033/* if there was an error or we are done prefetching, just cleanup */2034if (buf == NULL || scn->scn_prefetch_stop)2035goto out;20362037if (BP_GET_LEVEL(bp) > 0) {2038int i;2039blkptr_t *cbp;2040int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;2041zbookmark_phys_t czb;20422043for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {2044SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,2045zb->zb_level - 1, zb->zb_blkid * epb + i);2046dsl_scan_prefetch(spc, cbp, &czb);2047}2048} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {2049dnode_phys_t *cdnp;2050int i;2051int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;20522053for (i = 0, cdnp = buf->b_data; i < epb;2054i += cdnp->dn_extra_slots + 1,2055cdnp += cdnp->dn_extra_slots + 1) {2056dsl_scan_prefetch_dnode(scn, cdnp,2057zb->zb_objset, zb->zb_blkid * epb + i);2058}2059} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {2060objset_phys_t *osp = buf->b_data;20612062dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,2063zb->zb_objset, DMU_META_DNODE_OBJECT);20642065if (OBJSET_BUF_HAS_USERUSED(buf)) {2066if (OBJSET_BUF_HAS_PROJECTUSED(buf)) {2067dsl_scan_prefetch_dnode(scn,2068&osp->os_projectused_dnode, zb->zb_objset,2069DMU_PROJECTUSED_OBJECT);2070}2071dsl_scan_prefetch_dnode(scn,2072&osp->os_groupused_dnode, zb->zb_objset,2073DMU_GROUPUSED_OBJECT);2074dsl_scan_prefetch_dnode(scn,2075&osp->os_userused_dnode, zb->zb_objset,2076DMU_USERUSED_OBJECT);2077}2078}20792080out:2081if (buf != NULL)2082arc_buf_destroy(buf, private);2083scan_prefetch_ctx_rele(spc, scn);2084}20852086static void2087dsl_scan_prefetch_thread(void *arg)2088{2089dsl_scan_t *scn = arg;2090spa_t *spa = scn->scn_dp->dp_spa;2091scan_prefetch_issue_ctx_t *spic;20922093/* loop until we are told to stop */2094while (!scn->scn_prefetch_stop) {2095arc_flags_t flags = ARC_FLAG_NOWAIT |2096ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;2097int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;20982099mutex_enter(&spa->spa_scrub_lock);21002101/*2102* Wait until we have an IO to issue and are not above our2103* maximum in flight limit.2104*/2105while (!scn->scn_prefetch_stop &&2106(avl_numnodes(&scn->scn_prefetch_queue) == 0 ||2107spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {2108cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);2109}21102111/* recheck if we should stop since we waited for the cv */2112if (scn->scn_prefetch_stop) {2113mutex_exit(&spa->spa_scrub_lock);2114break;2115}21162117/* remove the prefetch IO from the tree */2118spic = avl_first(&scn->scn_prefetch_queue);2119spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);2120avl_remove(&scn->scn_prefetch_queue, spic);21212122mutex_exit(&spa->spa_scrub_lock);21232124if (BP_IS_PROTECTED(&spic->spic_bp)) {2125ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||2126BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);2127ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);2128zio_flags |= ZIO_FLAG_RAW;2129}21302131/* We don't need data L1 buffer since we do not prefetch L0. */2132blkptr_t *bp = &spic->spic_bp;2133if (BP_GET_LEVEL(bp) == 1 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&2134BP_GET_TYPE(bp) != DMU_OT_OBJSET)2135flags |= ARC_FLAG_NO_BUF;21362137/* issue the prefetch asynchronously */2138(void) arc_read(scn->scn_zio_root, spa, bp,2139dsl_scan_prefetch_cb, spic->spic_spc, ZIO_PRIORITY_SCRUB,2140zio_flags, &flags, &spic->spic_zb);21412142kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));2143}21442145ASSERT(scn->scn_prefetch_stop);21462147/* free any prefetches we didn't get to complete */2148mutex_enter(&spa->spa_scrub_lock);2149while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {2150avl_remove(&scn->scn_prefetch_queue, spic);2151scan_prefetch_ctx_rele(spic->spic_spc, scn);2152kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));2153}2154ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));2155mutex_exit(&spa->spa_scrub_lock);2156}21572158static boolean_t2159dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,2160const zbookmark_phys_t *zb)2161{2162/*2163* We never skip over user/group accounting objects (obj<0)2164*/2165if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&2166(int64_t)zb->zb_object >= 0) {2167/*2168* If we already visited this bp & everything below (in2169* a prior txg sync), don't bother doing it again.2170*/2171if (zbookmark_subtree_completed(dnp, zb,2172&scn->scn_phys.scn_bookmark))2173return (B_TRUE);21742175/*2176* If we found the block we're trying to resume from, or2177* we went past it, zero it out to indicate that it's OK2178* to start checking for suspending again.2179*/2180if (zbookmark_subtree_tbd(dnp, zb,2181&scn->scn_phys.scn_bookmark)) {2182dprintf("resuming at %llx/%llx/%llx/%llx\n",2183(longlong_t)zb->zb_objset,2184(longlong_t)zb->zb_object,2185(longlong_t)zb->zb_level,2186(longlong_t)zb->zb_blkid);2187memset(&scn->scn_phys.scn_bookmark, 0, sizeof (*zb));2188}2189}2190return (B_FALSE);2191}21922193static void dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,2194dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,2195dmu_objset_type_t ostype, dmu_tx_t *tx);2196inline __attribute__((always_inline)) static void dsl_scan_visitdnode(2197dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,2198dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);21992200/*2201* Return nonzero on i/o error.2202* Return new buf to write out in *bufp.2203*/2204inline __attribute__((always_inline)) static int2205dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,2206dnode_phys_t *dnp, const blkptr_t *bp,2207const zbookmark_phys_t *zb, dmu_tx_t *tx)2208{2209dsl_pool_t *dp = scn->scn_dp;2210spa_t *spa = dp->dp_spa;2211int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;2212int err;22132214ASSERT(!BP_IS_REDACTED(bp));22152216/*2217* There is an unlikely case of encountering dnodes with contradicting2218* dn_bonuslen and DNODE_FLAG_SPILL_BLKPTR flag before in files created2219* or modified before commit 4254acb was merged. As it is not possible2220* to know which of the two is correct, report an error.2221*/2222if (dnp != NULL &&2223dnp->dn_bonuslen > DN_MAX_BONUS_LEN(dnp)) {2224scn->scn_phys.scn_errors++;2225spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));2226return (SET_ERROR(EINVAL));2227}22282229if (BP_GET_LEVEL(bp) > 0) {2230arc_flags_t flags = ARC_FLAG_WAIT;2231int i;2232blkptr_t *cbp;2233int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;2234arc_buf_t *buf;22352236err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2237ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2238if (err) {2239scn->scn_phys.scn_errors++;2240return (err);2241}2242for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {2243zbookmark_phys_t czb;22442245SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,2246zb->zb_level - 1,2247zb->zb_blkid * epb + i);2248dsl_scan_visitbp(cbp, &czb, dnp,2249ds, scn, ostype, tx);2250}2251arc_buf_destroy(buf, &buf);2252} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {2253arc_flags_t flags = ARC_FLAG_WAIT;2254dnode_phys_t *cdnp;2255int i;2256int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;2257arc_buf_t *buf;22582259if (BP_IS_PROTECTED(bp)) {2260ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);2261zio_flags |= ZIO_FLAG_RAW;2262}22632264err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2265ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2266if (err) {2267scn->scn_phys.scn_errors++;2268return (err);2269}2270for (i = 0, cdnp = buf->b_data; i < epb;2271i += cdnp->dn_extra_slots + 1,2272cdnp += cdnp->dn_extra_slots + 1) {2273dsl_scan_visitdnode(scn, ds, ostype,2274cdnp, zb->zb_blkid * epb + i, tx);2275}22762277arc_buf_destroy(buf, &buf);2278} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {2279arc_flags_t flags = ARC_FLAG_WAIT;2280objset_phys_t *osp;2281arc_buf_t *buf;22822283err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,2284ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);2285if (err) {2286scn->scn_phys.scn_errors++;2287return (err);2288}22892290osp = buf->b_data;22912292dsl_scan_visitdnode(scn, ds, osp->os_type,2293&osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);22942295if (OBJSET_BUF_HAS_USERUSED(buf)) {2296/*2297* We also always visit user/group/project accounting2298* objects, and never skip them, even if we are2299* suspending. This is necessary so that the2300* space deltas from this txg get integrated.2301*/2302if (OBJSET_BUF_HAS_PROJECTUSED(buf))2303dsl_scan_visitdnode(scn, ds, osp->os_type,2304&osp->os_projectused_dnode,2305DMU_PROJECTUSED_OBJECT, tx);2306dsl_scan_visitdnode(scn, ds, osp->os_type,2307&osp->os_groupused_dnode,2308DMU_GROUPUSED_OBJECT, tx);2309dsl_scan_visitdnode(scn, ds, osp->os_type,2310&osp->os_userused_dnode,2311DMU_USERUSED_OBJECT, tx);2312}2313arc_buf_destroy(buf, &buf);2314} else if (zfs_blkptr_verify(spa, bp,2315BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {2316/*2317* Sanity check the block pointer contents, this is handled2318* by arc_read() for the cases above.2319*/2320scn->scn_phys.scn_errors++;2321spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));2322return (SET_ERROR(EINVAL));2323}23242325return (0);2326}23272328inline __attribute__((always_inline)) static void2329dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,2330dmu_objset_type_t ostype, dnode_phys_t *dnp,2331uint64_t object, dmu_tx_t *tx)2332{2333int j;23342335for (j = 0; j < dnp->dn_nblkptr; j++) {2336zbookmark_phys_t czb;23372338SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,2339dnp->dn_nlevels - 1, j);2340dsl_scan_visitbp(&dnp->dn_blkptr[j],2341&czb, dnp, ds, scn, ostype, tx);2342}23432344if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {2345zbookmark_phys_t czb;2346SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,23470, DMU_SPILL_BLKID);2348dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),2349&czb, dnp, ds, scn, ostype, tx);2350}2351}23522353/*2354* The arguments are in this order because mdb can only print the2355* first 5; we want them to be useful.2356*/2357static void2358dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,2359dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,2360dmu_objset_type_t ostype, dmu_tx_t *tx)2361{2362dsl_pool_t *dp = scn->scn_dp;23632364if (dsl_scan_check_suspend(scn, zb))2365return;23662367if (dsl_scan_check_resume(scn, dnp, zb))2368return;23692370scn->scn_visited_this_txg++;23712372if (BP_IS_HOLE(bp)) {2373scn->scn_holes_this_txg++;2374return;2375}23762377if (BP_IS_REDACTED(bp)) {2378ASSERT(dsl_dataset_feature_is_active(ds,2379SPA_FEATURE_REDACTED_DATASETS));2380return;2381}23822383/*2384* Check if this block contradicts any filesystem flags.2385*/2386spa_feature_t f = SPA_FEATURE_LARGE_BLOCKS;2387if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE)2388ASSERT(dsl_dataset_feature_is_active(ds, f));23892390f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));2391if (f != SPA_FEATURE_NONE)2392ASSERT(dsl_dataset_feature_is_active(ds, f));23932394f = zio_compress_to_feature(BP_GET_COMPRESS(bp));2395if (f != SPA_FEATURE_NONE)2396ASSERT(dsl_dataset_feature_is_active(ds, f));23972398/*2399* Recurse any blocks that were written either logically or physically2400* at or after cur_min_txg. About logical birth we care for traversal,2401* looking for any changes, while about physical for the actual scan.2402*/2403if (BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg) {2404scn->scn_lt_min_this_txg++;2405return;2406}24072408if (dsl_scan_recurse(scn, ds, ostype, dnp, bp, zb, tx) != 0)2409return;24102411/*2412* If dsl_scan_ddt() has already visited this block, it will have2413* already done any translations or scrubbing, so don't call the2414* callback again.2415*/2416if (ddt_class_contains(dp->dp_spa,2417scn->scn_phys.scn_ddt_class_max, bp)) {2418scn->scn_ddt_contained_this_txg++;2419return;2420}24212422/*2423* If this block is from the future (after cur_max_txg), then we2424* are doing this on behalf of a deleted snapshot, and we will2425* revisit the future block on the next pass of this dataset.2426* Don't scan it now unless we need to because something2427* under it was modified.2428*/2429if (BP_GET_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {2430scn->scn_gt_max_this_txg++;2431return;2432}24332434scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);2435}24362437static void2438dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,2439dmu_tx_t *tx)2440{2441zbookmark_phys_t zb;2442scan_prefetch_ctx_t *spc;24432444SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,2445ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);24462447if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {2448SET_BOOKMARK(&scn->scn_prefetch_bookmark,2449zb.zb_objset, 0, 0, 0);2450} else {2451scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;2452}24532454scn->scn_objsets_visited_this_txg++;24552456spc = scan_prefetch_ctx_create(scn, NULL, FTAG);2457dsl_scan_prefetch(spc, bp, &zb);2458scan_prefetch_ctx_rele(spc, FTAG);24592460dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);24612462dprintf_ds(ds, "finished scan%s", "");2463}24642465static void2466ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)2467{2468if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {2469if (ds->ds_is_snapshot) {2470/*2471* Note:2472* - scn_cur_{min,max}_txg stays the same.2473* - Setting the flag is not really necessary if2474* scn_cur_max_txg == scn_max_txg, because there2475* is nothing after this snapshot that we care2476* about. However, we set it anyway and then2477* ignore it when we retraverse it in2478* dsl_scan_visitds().2479*/2480scn_phys->scn_bookmark.zb_objset =2481dsl_dataset_phys(ds)->ds_next_snap_obj;2482zfs_dbgmsg("destroying ds %llu on %s; currently "2483"traversing; reset zb_objset to %llu",2484(u_longlong_t)ds->ds_object,2485ds->ds_dir->dd_pool->dp_spa->spa_name,2486(u_longlong_t)dsl_dataset_phys(ds)->2487ds_next_snap_obj);2488scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;2489} else {2490SET_BOOKMARK(&scn_phys->scn_bookmark,2491ZB_DESTROYED_OBJSET, 0, 0, 0);2492zfs_dbgmsg("destroying ds %llu on %s; currently "2493"traversing; reset bookmark to -1,0,0,0",2494(u_longlong_t)ds->ds_object,2495ds->ds_dir->dd_pool->dp_spa->spa_name);2496}2497}2498}24992500/*2501* Invoked when a dataset is destroyed. We need to make sure that:2502*2503* 1) If it is the dataset that was currently being scanned, we write2504* a new dsl_scan_phys_t and marking the objset reference in it2505* as destroyed.2506* 2) Remove it from the work queue, if it was present.2507*2508* If the dataset was actually a snapshot, instead of marking the dataset2509* as destroyed, we instead substitute the next snapshot in line.2510*/2511void2512dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)2513{2514dsl_pool_t *dp = ds->ds_dir->dd_pool;2515dsl_scan_t *scn = dp->dp_scan;2516uint64_t mintxg;25172518if (!dsl_scan_is_running(scn))2519return;25202521ds_destroyed_scn_phys(ds, &scn->scn_phys);2522ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);25232524if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {2525scan_ds_queue_remove(scn, ds->ds_object);2526if (ds->ds_is_snapshot)2527scan_ds_queue_insert(scn,2528dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);2529}25302531if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,2532ds->ds_object, &mintxg) == 0) {2533ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);2534VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,2535scn->scn_phys.scn_queue_obj, ds->ds_object, tx));2536if (ds->ds_is_snapshot) {2537/*2538* We keep the same mintxg; it could be >2539* ds_creation_txg if the previous snapshot was2540* deleted too.2541*/2542VERIFY(zap_add_int_key(dp->dp_meta_objset,2543scn->scn_phys.scn_queue_obj,2544dsl_dataset_phys(ds)->ds_next_snap_obj,2545mintxg, tx) == 0);2546zfs_dbgmsg("destroying ds %llu on %s; in queue; "2547"replacing with %llu",2548(u_longlong_t)ds->ds_object,2549dp->dp_spa->spa_name,2550(u_longlong_t)dsl_dataset_phys(ds)->2551ds_next_snap_obj);2552} else {2553zfs_dbgmsg("destroying ds %llu on %s; in queue; "2554"removing",2555(u_longlong_t)ds->ds_object,2556dp->dp_spa->spa_name);2557}2558}25592560/*2561* dsl_scan_sync() should be called after this, and should sync2562* out our changed state, but just to be safe, do it here.2563*/2564dsl_scan_sync_state(scn, tx, SYNC_CACHED);2565}25662567static void2568ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)2569{2570if (scn_bookmark->zb_objset == ds->ds_object) {2571scn_bookmark->zb_objset =2572dsl_dataset_phys(ds)->ds_prev_snap_obj;2573zfs_dbgmsg("snapshotting ds %llu on %s; currently traversing; "2574"reset zb_objset to %llu",2575(u_longlong_t)ds->ds_object,2576ds->ds_dir->dd_pool->dp_spa->spa_name,2577(u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);2578}2579}25802581/*2582* Called when a dataset is snapshotted. If we were currently traversing2583* this snapshot, we reset our bookmark to point at the newly created2584* snapshot. We also modify our work queue to remove the old snapshot and2585* replace with the new one.2586*/2587void2588dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)2589{2590dsl_pool_t *dp = ds->ds_dir->dd_pool;2591dsl_scan_t *scn = dp->dp_scan;2592uint64_t mintxg;25932594if (!dsl_scan_is_running(scn))2595return;25962597ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);25982599ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);2600ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);26012602if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {2603scan_ds_queue_remove(scn, ds->ds_object);2604scan_ds_queue_insert(scn,2605dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);2606}26072608if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,2609ds->ds_object, &mintxg) == 0) {2610VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,2611scn->scn_phys.scn_queue_obj, ds->ds_object, tx));2612VERIFY(zap_add_int_key(dp->dp_meta_objset,2613scn->scn_phys.scn_queue_obj,2614dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);2615zfs_dbgmsg("snapshotting ds %llu on %s; in queue; "2616"replacing with %llu",2617(u_longlong_t)ds->ds_object,2618dp->dp_spa->spa_name,2619(u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);2620}26212622dsl_scan_sync_state(scn, tx, SYNC_CACHED);2623}26242625static void2626ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,2627zbookmark_phys_t *scn_bookmark)2628{2629if (scn_bookmark->zb_objset == ds1->ds_object) {2630scn_bookmark->zb_objset = ds2->ds_object;2631zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "2632"reset zb_objset to %llu",2633(u_longlong_t)ds1->ds_object,2634ds1->ds_dir->dd_pool->dp_spa->spa_name,2635(u_longlong_t)ds2->ds_object);2636} else if (scn_bookmark->zb_objset == ds2->ds_object) {2637scn_bookmark->zb_objset = ds1->ds_object;2638zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "2639"reset zb_objset to %llu",2640(u_longlong_t)ds2->ds_object,2641ds2->ds_dir->dd_pool->dp_spa->spa_name,2642(u_longlong_t)ds1->ds_object);2643}2644}26452646/*2647* Called when an origin dataset and its clone are swapped. If we were2648* currently traversing the dataset, we need to switch to traversing the2649* newly promoted clone.2650*/2651void2652dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)2653{2654dsl_pool_t *dp = ds1->ds_dir->dd_pool;2655dsl_scan_t *scn = dp->dp_scan;2656uint64_t mintxg1, mintxg2;2657boolean_t ds1_queued, ds2_queued;26582659if (!dsl_scan_is_running(scn))2660return;26612662ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);2663ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);26642665/*2666* Handle the in-memory scan queue.2667*/2668ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);2669ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);26702671/* Sanity checking. */2672if (ds1_queued) {2673ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2674ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2675}2676if (ds2_queued) {2677ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2678ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2679}26802681if (ds1_queued && ds2_queued) {2682/*2683* If both are queued, we don't need to do anything.2684* The swapping code below would not handle this case correctly,2685* since we can't insert ds2 if it is already there. That's2686* because scan_ds_queue_insert() prohibits a duplicate insert2687* and panics.2688*/2689} else if (ds1_queued) {2690scan_ds_queue_remove(scn, ds1->ds_object);2691scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);2692} else if (ds2_queued) {2693scan_ds_queue_remove(scn, ds2->ds_object);2694scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);2695}26962697/*2698* Handle the on-disk scan queue.2699* The on-disk state is an out-of-date version of the in-memory state,2700* so the in-memory and on-disk values for ds1_queued and ds2_queued may2701* be different. Therefore we need to apply the swap logic to the2702* on-disk state independently of the in-memory state.2703*/2704ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,2705scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;2706ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,2707scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;27082709/* Sanity checking. */2710if (ds1_queued) {2711ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2712ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2713}2714if (ds2_queued) {2715ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);2716ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);2717}27182719if (ds1_queued && ds2_queued) {2720/*2721* If both are queued, we don't need to do anything.2722* Alternatively, we could check for EEXIST from2723* zap_add_int_key() and back out to the original state, but2724* that would be more work than checking for this case upfront.2725*/2726} else if (ds1_queued) {2727VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,2728scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));2729VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,2730scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));2731zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "2732"replacing with %llu",2733(u_longlong_t)ds1->ds_object,2734dp->dp_spa->spa_name,2735(u_longlong_t)ds2->ds_object);2736} else if (ds2_queued) {2737VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,2738scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));2739VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,2740scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));2741zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "2742"replacing with %llu",2743(u_longlong_t)ds2->ds_object,2744dp->dp_spa->spa_name,2745(u_longlong_t)ds1->ds_object);2746}27472748dsl_scan_sync_state(scn, tx, SYNC_CACHED);2749}27502751static int2752enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)2753{2754uint64_t originobj = *(uint64_t *)arg;2755dsl_dataset_t *ds;2756int err;2757dsl_scan_t *scn = dp->dp_scan;27582759if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)2760return (0);27612762err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);2763if (err)2764return (err);27652766while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {2767dsl_dataset_t *prev;2768err = dsl_dataset_hold_obj(dp,2769dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);27702771dsl_dataset_rele(ds, FTAG);2772if (err)2773return (err);2774ds = prev;2775}2776mutex_enter(&scn->scn_queue_lock);2777scan_ds_queue_insert(scn, ds->ds_object,2778dsl_dataset_phys(ds)->ds_prev_snap_txg);2779mutex_exit(&scn->scn_queue_lock);2780dsl_dataset_rele(ds, FTAG);2781return (0);2782}27832784static void2785dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)2786{2787dsl_pool_t *dp = scn->scn_dp;2788dsl_dataset_t *ds;27892790VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));27912792if (scn->scn_phys.scn_cur_min_txg >=2793scn->scn_phys.scn_max_txg) {2794/*2795* This can happen if this snapshot was created after the2796* scan started, and we already completed a previous snapshot2797* that was created after the scan started. This snapshot2798* only references blocks with:2799*2800* birth < our ds_creation_txg2801* cur_min_txg is no less than ds_creation_txg.2802* We have already visited these blocks.2803* or2804* birth > scn_max_txg2805* The scan requested not to visit these blocks.2806*2807* Subsequent snapshots (and clones) can reference our2808* blocks, or blocks with even higher birth times.2809* Therefore we do not need to visit them either,2810* so we do not add them to the work queue.2811*2812* Note that checking for cur_min_txg >= cur_max_txg2813* is not sufficient, because in that case we may need to2814* visit subsequent snapshots. This happens when min_txg > 0,2815* which raises cur_min_txg. In this case we will visit2816* this dataset but skip all of its blocks, because the2817* rootbp's birth time is < cur_min_txg. Then we will2818* add the next snapshots/clones to the work queue.2819*/2820char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);2821dsl_dataset_name(ds, dsname);2822zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "2823"cur_min_txg (%llu) >= max_txg (%llu)",2824(longlong_t)dsobj, dsname,2825(longlong_t)scn->scn_phys.scn_cur_min_txg,2826(longlong_t)scn->scn_phys.scn_max_txg);2827kmem_free(dsname, MAXNAMELEN);28282829goto out;2830}28312832/*2833* Only the ZIL in the head (non-snapshot) is valid. Even though2834* snapshots can have ZIL block pointers (which may be the same2835* BP as in the head), they must be ignored. In addition, $ORIGIN2836* doesn't have a objset (i.e. its ds_bp is a hole) so we don't2837* need to look for a ZIL in it either. So we traverse the ZIL here,2838* rather than in scan_recurse(), because the regular snapshot2839* block-sharing rules don't apply to it.2840*/2841if (!dsl_dataset_is_snapshot(ds) &&2842(dp->dp_origin_snap == NULL ||2843ds->ds_dir != dp->dp_origin_snap->ds_dir)) {2844objset_t *os;2845if (dmu_objset_from_ds(ds, &os) != 0) {2846goto out;2847}2848dsl_scan_zil(dp, &os->os_zil_header);2849}28502851/*2852* Iterate over the bps in this ds.2853*/2854dmu_buf_will_dirty(ds->ds_dbuf, tx);2855rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);2856dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);2857rrw_exit(&ds->ds_bp_rwlock, FTAG);28582859char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);2860dsl_dataset_name(ds, dsname);2861zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "2862"suspending=%u",2863(longlong_t)dsobj, dsname,2864(longlong_t)scn->scn_phys.scn_cur_min_txg,2865(longlong_t)scn->scn_phys.scn_cur_max_txg,2866(int)scn->scn_suspending);2867kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);28682869if (scn->scn_suspending)2870goto out;28712872/*2873* We've finished this pass over this dataset.2874*/28752876/*2877* If we did not completely visit this dataset, do another pass.2878*/2879if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {2880zfs_dbgmsg("incomplete pass on %s; visiting again",2881dp->dp_spa->spa_name);2882scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;2883scan_ds_queue_insert(scn, ds->ds_object,2884scn->scn_phys.scn_cur_max_txg);2885goto out;2886}28872888/*2889* Add descendant datasets to work queue.2890*/2891if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {2892scan_ds_queue_insert(scn,2893dsl_dataset_phys(ds)->ds_next_snap_obj,2894dsl_dataset_phys(ds)->ds_creation_txg);2895}2896if (dsl_dataset_phys(ds)->ds_num_children > 1) {2897boolean_t usenext = B_FALSE;2898if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {2899uint64_t count;2900/*2901* A bug in a previous version of the code could2902* cause upgrade_clones_cb() to not set2903* ds_next_snap_obj when it should, leading to a2904* missing entry. Therefore we can only use the2905* next_clones_obj when its count is correct.2906*/2907int err = zap_count(dp->dp_meta_objset,2908dsl_dataset_phys(ds)->ds_next_clones_obj, &count);2909if (err == 0 &&2910count == dsl_dataset_phys(ds)->ds_num_children - 1)2911usenext = B_TRUE;2912}29132914if (usenext) {2915zap_cursor_t zc;2916zap_attribute_t *za = zap_attribute_alloc();2917for (zap_cursor_init(&zc, dp->dp_meta_objset,2918dsl_dataset_phys(ds)->ds_next_clones_obj);2919zap_cursor_retrieve(&zc, za) == 0;2920(void) zap_cursor_advance(&zc)) {2921scan_ds_queue_insert(scn,2922zfs_strtonum(za->za_name, NULL),2923dsl_dataset_phys(ds)->ds_creation_txg);2924}2925zap_cursor_fini(&zc);2926zap_attribute_free(za);2927} else {2928VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,2929enqueue_clones_cb, &ds->ds_object,2930DS_FIND_CHILDREN));2931}2932}29332934out:2935dsl_dataset_rele(ds, FTAG);2936}29372938static int2939enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)2940{2941(void) arg;2942dsl_dataset_t *ds;2943int err;2944dsl_scan_t *scn = dp->dp_scan;29452946err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);2947if (err)2948return (err);29492950while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {2951dsl_dataset_t *prev;2952err = dsl_dataset_hold_obj(dp,2953dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);2954if (err) {2955dsl_dataset_rele(ds, FTAG);2956return (err);2957}29582959/*2960* If this is a clone, we don't need to worry about it for now.2961*/2962if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {2963dsl_dataset_rele(ds, FTAG);2964dsl_dataset_rele(prev, FTAG);2965return (0);2966}2967dsl_dataset_rele(ds, FTAG);2968ds = prev;2969}29702971mutex_enter(&scn->scn_queue_lock);2972scan_ds_queue_insert(scn, ds->ds_object,2973dsl_dataset_phys(ds)->ds_prev_snap_txg);2974mutex_exit(&scn->scn_queue_lock);2975dsl_dataset_rele(ds, FTAG);2976return (0);2977}29782979void2980dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,2981ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)2982{2983(void) tx;2984const ddt_key_t *ddk = &ddlwe->ddlwe_key;2985blkptr_t bp;2986zbookmark_phys_t zb = { 0 };29872988if (!dsl_scan_is_running(scn))2989return;29902991/*2992* This function is special because it is the only thing2993* that can add scan_io_t's to the vdev scan queues from2994* outside dsl_scan_sync(). For the most part this is ok2995* as long as it is called from within syncing context.2996* However, dsl_scan_sync() expects that no new sio's will2997* be added between when all the work for a scan is done2998* and the next txg when the scan is actually marked as2999* completed. This check ensures we do not issue new sio's3000* during this period.3001*/3002if (scn->scn_done_txg != 0)3003return;30043005for (int p = 0; p < DDT_NPHYS(ddt); p++) {3006ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);3007uint64_t phys_birth = ddt_phys_birth(&ddlwe->ddlwe_phys, v);30083009if (phys_birth == 0 || phys_birth > scn->scn_phys.scn_max_txg)3010continue;3011ddt_bp_create(checksum, ddk, &ddlwe->ddlwe_phys, v, &bp);30123013scn->scn_visited_this_txg++;3014scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);3015}3016}30173018/*3019* Scrub/dedup interaction.3020*3021* If there are N references to a deduped block, we don't want to scrub it3022* N times -- ideally, we should scrub it exactly once.3023*3024* We leverage the fact that the dde's replication class (ddt_class_t)3025* is ordered from highest replication class (DDT_CLASS_DITTO) to lowest3026* (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.3027*3028* To prevent excess scrubbing, the scrub begins by walking the DDT3029* to find all blocks with refcnt > 1, and scrubs each of these once.3030* Since there are two replication classes which contain blocks with3031* refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.3032* Finally the top-down scrub begins, only visiting blocks with refcnt == 1.3033*3034* There would be nothing more to say if a block's refcnt couldn't change3035* during a scrub, but of course it can so we must account for changes3036* in a block's replication class.3037*3038* Here's an example of what can occur:3039*3040* If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 13041* when visited during the top-down scrub phase, it will be scrubbed twice.3042* This negates our scrub optimization, but is otherwise harmless.3043*3044* If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 13045* on each visit during the top-down scrub phase, it will never be scrubbed.3046* To catch this, ddt_sync_entry() notifies the scrub code whenever a block's3047* reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to3048* DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 13049* while a scrub is in progress, it scrubs the block right then.3050*/3051static void3052dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)3053{3054ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;3055ddt_lightweight_entry_t ddlwe = {0};3056int error;3057uint64_t n = 0;30583059while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &ddlwe)) == 0) {3060ddt_t *ddt;30613062if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)3063break;3064dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",3065(longlong_t)ddb->ddb_class,3066(longlong_t)ddb->ddb_type,3067(longlong_t)ddb->ddb_checksum,3068(longlong_t)ddb->ddb_cursor);30693070/* There should be no pending changes to the dedup table */3071ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];3072ASSERT(avl_first(&ddt->ddt_tree) == NULL);30733074dsl_scan_ddt_entry(scn, ddb->ddb_checksum, ddt, &ddlwe, tx);3075n++;30763077if (dsl_scan_check_suspend(scn, NULL))3078break;3079}30803081if (error == EAGAIN) {3082dsl_scan_check_suspend(scn, NULL);3083error = 0;30843085zfs_dbgmsg("waiting for ddt to become ready for scan "3086"on %s with class_max = %u; suspending=%u",3087scn->scn_dp->dp_spa->spa_name,3088(int)scn->scn_phys.scn_ddt_class_max,3089(int)scn->scn_suspending);3090} else3091zfs_dbgmsg("scanned %llu ddt entries on %s with "3092"class_max = %u; suspending=%u", (longlong_t)n,3093scn->scn_dp->dp_spa->spa_name,3094(int)scn->scn_phys.scn_ddt_class_max,3095(int)scn->scn_suspending);30963097ASSERT(error == 0 || error == ENOENT);3098ASSERT(error != ENOENT ||3099ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);3100}31013102static uint64_t3103dsl_scan_ds_maxtxg(dsl_dataset_t *ds)3104{3105uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;3106if (ds->ds_is_snapshot)3107return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));3108return (smt);3109}31103111static void3112dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)3113{3114scan_ds_t *sds;3115dsl_pool_t *dp = scn->scn_dp;31163117if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=3118scn->scn_phys.scn_ddt_class_max) {3119scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;3120scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;3121dsl_scan_ddt(scn, tx);3122if (scn->scn_suspending)3123return;3124}31253126if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {3127/* First do the MOS & ORIGIN */31283129scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;3130scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;3131dsl_scan_visit_rootbp(scn, NULL,3132&dp->dp_meta_rootbp, tx);3133if (scn->scn_suspending)3134return;31353136if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {3137VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,3138enqueue_cb, NULL, DS_FIND_CHILDREN));3139} else {3140dsl_scan_visitds(scn,3141dp->dp_origin_snap->ds_object, tx);3142}3143ASSERT(!scn->scn_suspending);3144} else if (scn->scn_phys.scn_bookmark.zb_objset !=3145ZB_DESTROYED_OBJSET) {3146uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;3147/*3148* If we were suspended, continue from here. Note if the3149* ds we were suspended on was deleted, the zb_objset may3150* be -1, so we will skip this and find a new objset3151* below.3152*/3153dsl_scan_visitds(scn, dsobj, tx);3154if (scn->scn_suspending)3155return;3156}31573158/*3159* In case we suspended right at the end of the ds, zero the3160* bookmark so we don't think that we're still trying to resume.3161*/3162memset(&scn->scn_phys.scn_bookmark, 0, sizeof (zbookmark_phys_t));31633164/*3165* Keep pulling things out of the dataset avl queue. Updates to the3166* persistent zap-object-as-queue happen only at checkpoints.3167*/3168while ((sds = avl_first(&scn->scn_queue)) != NULL) {3169dsl_dataset_t *ds;3170uint64_t dsobj = sds->sds_dsobj;3171uint64_t txg = sds->sds_txg;31723173/* dequeue and free the ds from the queue */3174scan_ds_queue_remove(scn, dsobj);3175sds = NULL;31763177/* set up min / max txg */3178VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));3179if (txg != 0) {3180scn->scn_phys.scn_cur_min_txg =3181MAX(scn->scn_phys.scn_min_txg, txg);3182} else {3183scn->scn_phys.scn_cur_min_txg =3184MAX(scn->scn_phys.scn_min_txg,3185dsl_dataset_phys(ds)->ds_prev_snap_txg);3186}3187scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);3188dsl_dataset_rele(ds, FTAG);31893190dsl_scan_visitds(scn, dsobj, tx);3191if (scn->scn_suspending)3192return;3193}31943195/* No more objsets to fetch, we're done */3196scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;3197ASSERT0(scn->scn_suspending);3198}31993200static uint64_t3201dsl_scan_count_data_disks(spa_t *spa)3202{3203vdev_t *rvd = spa->spa_root_vdev;3204uint64_t i, leaves = 0;32053206for (i = 0; i < rvd->vdev_children; i++) {3207vdev_t *vd = rvd->vdev_child[i];3208if (vd->vdev_islog || vd->vdev_isspare || vd->vdev_isl2cache)3209continue;3210leaves += vdev_get_ndisks(vd) - vdev_get_nparity(vd);3211}3212return (leaves);3213}32143215static void3216scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)3217{3218int i;3219uint64_t cur_size = 0;32203221for (i = 0; i < BP_GET_NDVAS(bp); i++) {3222cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);3223}32243225q->q_total_zio_size_this_txg += cur_size;3226q->q_zios_this_txg++;3227}32283229static void3230scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,3231uint64_t end)3232{3233q->q_total_seg_size_this_txg += end - start;3234q->q_segs_this_txg++;3235}32363237static boolean_t3238scan_io_queue_check_suspend(dsl_scan_t *scn)3239{3240/* See comment in dsl_scan_check_suspend() */3241uint64_t curr_time_ns = gethrtime();3242uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;3243uint64_t sync_time_ns = curr_time_ns -3244scn->scn_dp->dp_spa->spa_sync_starttime;3245uint64_t dirty_min_bytes = zfs_dirty_data_max *3246zfs_vdev_async_write_active_min_dirty_percent / 100;3247uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?3248zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;32493250return ((NSEC2MSEC(scan_time_ns) > mintime &&3251(scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||3252txg_sync_waiting(scn->scn_dp) ||3253NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||3254spa_shutting_down(scn->scn_dp->dp_spa));3255}32563257/*3258* Given a list of scan_io_t's in io_list, this issues the I/Os out to3259* disk. This consumes the io_list and frees the scan_io_t's. This is3260* called when emptying queues, either when we're up against the memory3261* limit or when we have finished scanning. Returns B_TRUE if we stopped3262* processing the list before we finished. Any sios that were not issued3263* will remain in the io_list.3264*/3265static boolean_t3266scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)3267{3268dsl_scan_t *scn = queue->q_scn;3269scan_io_t *sio;3270boolean_t suspended = B_FALSE;32713272while ((sio = list_head(io_list)) != NULL) {3273blkptr_t bp;32743275if (scan_io_queue_check_suspend(scn)) {3276suspended = B_TRUE;3277break;3278}32793280sio2bp(sio, &bp);3281scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,3282&sio->sio_zb, queue);3283(void) list_remove_head(io_list);3284scan_io_queues_update_zio_stats(queue, &bp);3285sio_free(sio);3286}3287return (suspended);3288}32893290/*3291* This function removes sios from an IO queue which reside within a given3292* zfs_range_seg_t and inserts them (in offset order) into a list. Note that3293* we only ever return a maximum of 32 sios at once. If there are more sios3294* to process within this segment that did not make it onto the list we3295* return B_TRUE and otherwise B_FALSE.3296*/3297static boolean_t3298scan_io_queue_gather(dsl_scan_io_queue_t *queue, zfs_range_seg_t *rs,3299list_t *list)3300{3301scan_io_t *srch_sio, *sio, *next_sio;3302avl_index_t idx;3303uint_t num_sios = 0;3304int64_t bytes_issued = 0;33053306ASSERT(rs != NULL);3307ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));33083309srch_sio = sio_alloc(1);3310srch_sio->sio_nr_dvas = 1;3311SIO_SET_OFFSET(srch_sio, zfs_rs_get_start(rs, queue->q_exts_by_addr));33123313/*3314* The exact start of the extent might not contain any matching zios,3315* so if that's the case, examine the next one in the tree.3316*/3317sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);3318sio_free(srch_sio);33193320if (sio == NULL)3321sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);33223323while (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,3324queue->q_exts_by_addr) && num_sios <= 32) {3325ASSERT3U(SIO_GET_OFFSET(sio), >=, zfs_rs_get_start(rs,3326queue->q_exts_by_addr));3327ASSERT3U(SIO_GET_END_OFFSET(sio), <=, zfs_rs_get_end(rs,3328queue->q_exts_by_addr));33293330next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);3331avl_remove(&queue->q_sios_by_addr, sio);3332if (avl_is_empty(&queue->q_sios_by_addr))3333atomic_add_64(&queue->q_scn->scn_queues_pending, -1);3334queue->q_sio_memused -= SIO_GET_MUSED(sio);33353336bytes_issued += SIO_GET_ASIZE(sio);3337num_sios++;3338list_insert_tail(list, sio);3339sio = next_sio;3340}33413342/*3343* We limit the number of sios we process at once to 32 to avoid3344* biting off more than we can chew. If we didn't take everything3345* in the segment we update it to reflect the work we were able to3346* complete. Otherwise, we remove it from the range tree entirely.3347*/3348if (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,3349queue->q_exts_by_addr)) {3350zfs_range_tree_adjust_fill(queue->q_exts_by_addr, rs,3351-bytes_issued);3352zfs_range_tree_resize_segment(queue->q_exts_by_addr, rs,3353SIO_GET_OFFSET(sio), zfs_rs_get_end(rs,3354queue->q_exts_by_addr) - SIO_GET_OFFSET(sio));3355queue->q_last_ext_addr = SIO_GET_OFFSET(sio);3356return (B_TRUE);3357} else {3358uint64_t rstart = zfs_rs_get_start(rs, queue->q_exts_by_addr);3359uint64_t rend = zfs_rs_get_end(rs, queue->q_exts_by_addr);3360zfs_range_tree_remove(queue->q_exts_by_addr, rstart, rend -3361rstart);3362queue->q_last_ext_addr = -1;3363return (B_FALSE);3364}3365}33663367/*3368* This is called from the queue emptying thread and selects the next3369* extent from which we are to issue I/Os. The behavior of this function3370* depends on the state of the scan, the current memory consumption and3371* whether or not we are performing a scan shutdown.3372* 1) We select extents in an elevator algorithm (LBA-order) if the scan3373* needs to perform a checkpoint3374* 2) We select the largest available extent if we are up against the3375* memory limit.3376* 3) Otherwise we don't select any extents.3377*/3378static zfs_range_seg_t *3379scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)3380{3381dsl_scan_t *scn = queue->q_scn;3382zfs_range_tree_t *rt = queue->q_exts_by_addr;33833384ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));3385ASSERT(scn->scn_is_sorted);33863387if (!scn->scn_checkpointing && !scn->scn_clearing)3388return (NULL);33893390/*3391* During normal clearing, we want to issue our largest segments3392* first, keeping IO as sequential as possible, and leaving the3393* smaller extents for later with the hope that they might eventually3394* grow to larger sequential segments. However, when the scan is3395* checkpointing, no new extents will be added to the sorting queue,3396* so the way we are sorted now is as good as it will ever get.3397* In this case, we instead switch to issuing extents in LBA order.3398*/3399if ((zfs_scan_issue_strategy < 1 && scn->scn_checkpointing) ||3400zfs_scan_issue_strategy == 1)3401return (zfs_range_tree_first(rt));34023403/*3404* Try to continue previous extent if it is not completed yet. After3405* shrink in scan_io_queue_gather() it may no longer be the best, but3406* otherwise we leave shorter remnant every txg.3407*/3408uint64_t start;3409uint64_t size = 1ULL << rt->rt_shift;3410zfs_range_seg_t *addr_rs;3411if (queue->q_last_ext_addr != -1) {3412start = queue->q_last_ext_addr;3413addr_rs = zfs_range_tree_find(rt, start, size);3414if (addr_rs != NULL)3415return (addr_rs);3416}34173418/*3419* Nothing to continue, so find new best extent.3420*/3421uint64_t *v = zfs_btree_first(&queue->q_exts_by_size, NULL);3422if (v == NULL)3423return (NULL);3424queue->q_last_ext_addr = start = *v << rt->rt_shift;34253426/*3427* We need to get the original entry in the by_addr tree so we can3428* modify it.3429*/3430addr_rs = zfs_range_tree_find(rt, start, size);3431ASSERT3P(addr_rs, !=, NULL);3432ASSERT3U(zfs_rs_get_start(addr_rs, rt), ==, start);3433ASSERT3U(zfs_rs_get_end(addr_rs, rt), >, start);3434return (addr_rs);3435}34363437static void3438scan_io_queues_run_one(void *arg)3439{3440dsl_scan_io_queue_t *queue = arg;3441kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;3442boolean_t suspended = B_FALSE;3443zfs_range_seg_t *rs;3444scan_io_t *sio;3445zio_t *zio;3446list_t sio_list;34473448ASSERT(queue->q_scn->scn_is_sorted);34493450list_create(&sio_list, sizeof (scan_io_t),3451offsetof(scan_io_t, sio_nodes.sio_list_node));3452zio = zio_null(queue->q_scn->scn_zio_root, queue->q_scn->scn_dp->dp_spa,3453NULL, NULL, NULL, ZIO_FLAG_CANFAIL);3454mutex_enter(q_lock);3455queue->q_zio = zio;34563457/* Calculate maximum in-flight bytes for this vdev. */3458queue->q_maxinflight_bytes = MAX(1, zfs_scan_vdev_limit *3459(vdev_get_ndisks(queue->q_vd) - vdev_get_nparity(queue->q_vd)));34603461/* reset per-queue scan statistics for this txg */3462queue->q_total_seg_size_this_txg = 0;3463queue->q_segs_this_txg = 0;3464queue->q_total_zio_size_this_txg = 0;3465queue->q_zios_this_txg = 0;34663467/* loop until we run out of time or sios */3468while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {3469uint64_t seg_start = 0, seg_end = 0;3470boolean_t more_left;34713472ASSERT(list_is_empty(&sio_list));34733474/* loop while we still have sios left to process in this rs */3475do {3476scan_io_t *first_sio, *last_sio;34773478/*3479* We have selected which extent needs to be3480* processed next. Gather up the corresponding sios.3481*/3482more_left = scan_io_queue_gather(queue, rs, &sio_list);3483ASSERT(!list_is_empty(&sio_list));3484first_sio = list_head(&sio_list);3485last_sio = list_tail(&sio_list);34863487seg_end = SIO_GET_END_OFFSET(last_sio);3488if (seg_start == 0)3489seg_start = SIO_GET_OFFSET(first_sio);34903491/*3492* Issuing sios can take a long time so drop the3493* queue lock. The sio queue won't be updated by3494* other threads since we're in syncing context so3495* we can be sure that our trees will remain exactly3496* as we left them.3497*/3498mutex_exit(q_lock);3499suspended = scan_io_queue_issue(queue, &sio_list);3500mutex_enter(q_lock);35013502if (suspended)3503break;3504} while (more_left);35053506/* update statistics for debugging purposes */3507scan_io_queues_update_seg_stats(queue, seg_start, seg_end);35083509if (suspended)3510break;3511}35123513/*3514* If we were suspended in the middle of processing,3515* requeue any unfinished sios and exit.3516*/3517while ((sio = list_remove_head(&sio_list)) != NULL)3518scan_io_queue_insert_impl(queue, sio);35193520queue->q_zio = NULL;3521mutex_exit(q_lock);3522zio_nowait(zio);3523list_destroy(&sio_list);3524}35253526/*3527* Performs an emptying run on all scan queues in the pool. This just3528* punches out one thread per top-level vdev, each of which processes3529* only that vdev's scan queue. We can parallelize the I/O here because3530* we know that each queue's I/Os only affect its own top-level vdev.3531*3532* This function waits for the queue runs to complete, and must be3533* called from dsl_scan_sync (or in general, syncing context).3534*/3535static void3536scan_io_queues_run(dsl_scan_t *scn)3537{3538spa_t *spa = scn->scn_dp->dp_spa;35393540ASSERT(scn->scn_is_sorted);3541ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));35423543if (scn->scn_queues_pending == 0)3544return;35453546if (scn->scn_taskq == NULL) {3547int nthreads = spa->spa_root_vdev->vdev_children;35483549/*3550* We need to make this taskq *always* execute as many3551* threads in parallel as we have top-level vdevs and no3552* less, otherwise strange serialization of the calls to3553* scan_io_queues_run_one can occur during spa_sync runs3554* and that significantly impacts performance.3555*/3556scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,3557minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);3558}35593560for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {3561vdev_t *vd = spa->spa_root_vdev->vdev_child[i];35623563mutex_enter(&vd->vdev_scan_io_queue_lock);3564if (vd->vdev_scan_io_queue != NULL) {3565VERIFY(taskq_dispatch(scn->scn_taskq,3566scan_io_queues_run_one, vd->vdev_scan_io_queue,3567TQ_SLEEP) != TASKQID_INVALID);3568}3569mutex_exit(&vd->vdev_scan_io_queue_lock);3570}35713572/*3573* Wait for the queues to finish issuing their IOs for this run3574* before we return. There may still be IOs in flight at this3575* point.3576*/3577taskq_wait(scn->scn_taskq);3578}35793580static boolean_t3581dsl_scan_async_block_should_pause(dsl_scan_t *scn)3582{3583uint64_t elapsed_nanosecs;35843585if (zfs_recover)3586return (B_FALSE);35873588if (zfs_async_block_max_blocks != 0 &&3589scn->scn_visited_this_txg >= zfs_async_block_max_blocks) {3590return (B_TRUE);3591}35923593if (zfs_max_async_dedup_frees != 0 &&3594scn->scn_dedup_frees_this_txg >= zfs_max_async_dedup_frees) {3595return (B_TRUE);3596}35973598elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;3599return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||3600(NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&3601txg_sync_waiting(scn->scn_dp)) ||3602spa_shutting_down(scn->scn_dp->dp_spa));3603}36043605static int3606dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)3607{3608dsl_scan_t *scn = arg;36093610if (!scn->scn_is_bptree ||3611(BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {3612if (dsl_scan_async_block_should_pause(scn))3613return (SET_ERROR(ERESTART));3614}36153616zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,3617dmu_tx_get_txg(tx), bp, 0));3618dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,3619-bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),3620-BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);3621scn->scn_visited_this_txg++;3622if (BP_GET_DEDUP(bp))3623scn->scn_dedup_frees_this_txg++;3624return (0);3625}36263627static void3628dsl_scan_update_stats(dsl_scan_t *scn)3629{3630spa_t *spa = scn->scn_dp->dp_spa;3631uint64_t i;3632uint64_t seg_size_total = 0, zio_size_total = 0;3633uint64_t seg_count_total = 0, zio_count_total = 0;36343635for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {3636vdev_t *vd = spa->spa_root_vdev->vdev_child[i];3637dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;36383639if (queue == NULL)3640continue;36413642seg_size_total += queue->q_total_seg_size_this_txg;3643zio_size_total += queue->q_total_zio_size_this_txg;3644seg_count_total += queue->q_segs_this_txg;3645zio_count_total += queue->q_zios_this_txg;3646}36473648if (seg_count_total == 0 || zio_count_total == 0) {3649scn->scn_avg_seg_size_this_txg = 0;3650scn->scn_avg_zio_size_this_txg = 0;3651scn->scn_segs_this_txg = 0;3652scn->scn_zios_this_txg = 0;3653return;3654}36553656scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;3657scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;3658scn->scn_segs_this_txg = seg_count_total;3659scn->scn_zios_this_txg = zio_count_total;3660}36613662static int3663bpobj_dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,3664dmu_tx_t *tx)3665{3666ASSERT(!bp_freed);3667return (dsl_scan_free_block_cb(arg, bp, tx));3668}36693670static int3671dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,3672dmu_tx_t *tx)3673{3674ASSERT(!bp_freed);3675dsl_scan_t *scn = arg;3676const dva_t *dva = &bp->blk_dva[0];36773678if (dsl_scan_async_block_should_pause(scn))3679return (SET_ERROR(ERESTART));36803681spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,3682DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),3683DVA_GET_ASIZE(dva), tx);3684scn->scn_visited_this_txg++;3685return (0);3686}36873688boolean_t3689dsl_scan_active(dsl_scan_t *scn)3690{3691spa_t *spa = scn->scn_dp->dp_spa;3692uint64_t used = 0, comp, uncomp;3693boolean_t clones_left;36943695if (spa->spa_load_state != SPA_LOAD_NONE)3696return (B_FALSE);3697if (spa_shutting_down(spa))3698return (B_FALSE);3699if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||3700(scn->scn_async_destroying && !scn->scn_async_stalled))3701return (B_TRUE);37023703if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {3704(void) bpobj_space(&scn->scn_dp->dp_free_bpobj,3705&used, &comp, &uncomp);3706}3707clones_left = spa_livelist_delete_check(spa);3708return ((used != 0) || (clones_left));3709}37103711boolean_t3712dsl_errorscrub_active(dsl_scan_t *scn)3713{3714spa_t *spa = scn->scn_dp->dp_spa;3715if (spa->spa_load_state != SPA_LOAD_NONE)3716return (B_FALSE);3717if (spa_shutting_down(spa))3718return (B_FALSE);3719if (dsl_errorscrubbing(scn->scn_dp))3720return (B_TRUE);3721return (B_FALSE);3722}37233724static boolean_t3725dsl_scan_check_deferred(vdev_t *vd)3726{3727boolean_t need_resilver = B_FALSE;37283729for (int c = 0; c < vd->vdev_children; c++) {3730need_resilver |=3731dsl_scan_check_deferred(vd->vdev_child[c]);3732}37333734if (!vdev_is_concrete(vd) || vd->vdev_aux ||3735!vd->vdev_ops->vdev_op_leaf)3736return (need_resilver);37373738if (!vd->vdev_resilver_deferred)3739need_resilver = B_TRUE;37403741return (need_resilver);3742}37433744static boolean_t3745dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,3746uint64_t phys_birth)3747{3748vdev_t *vd;37493750vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));37513752if (vd->vdev_ops == &vdev_indirect_ops) {3753/*3754* The indirect vdev can point to multiple3755* vdevs. For simplicity, always create3756* the resilver zio_t. zio_vdev_io_start()3757* will bypass the child resilver i/o's if3758* they are on vdevs that don't have DTL's.3759*/3760return (B_TRUE);3761}37623763if (DVA_GET_GANG(dva)) {3764/*3765* Gang members may be spread across multiple3766* vdevs, so the best estimate we have is the3767* scrub range, which has already been checked.3768* XXX -- it would be better to change our3769* allocation policy to ensure that all3770* gang members reside on the same vdev.3771*/3772return (B_TRUE);3773}37743775/*3776* Check if the top-level vdev must resilver this offset.3777* When the offset does not intersect with a dirty leaf DTL3778* then it may be possible to skip the resilver IO. The psize3779* is provided instead of asize to simplify the check for RAIDZ.3780*/3781if (!vdev_dtl_need_resilver(vd, dva, psize, phys_birth))3782return (B_FALSE);37833784/*3785* Check that this top-level vdev has a device under it which3786* is resilvering and is not deferred.3787*/3788if (!dsl_scan_check_deferred(vd))3789return (B_FALSE);37903791return (B_TRUE);3792}37933794static int3795dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)3796{3797dsl_scan_t *scn = dp->dp_scan;3798spa_t *spa = dp->dp_spa;3799int err = 0;38003801if (spa_suspend_async_destroy(spa))3802return (0);38033804if (zfs_free_bpobj_enabled &&3805spa_version(spa) >= SPA_VERSION_DEADLISTS) {3806scn->scn_is_bptree = B_FALSE;3807scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;3808scn->scn_zio_root = zio_root(spa, NULL,3809NULL, ZIO_FLAG_MUSTSUCCEED);3810err = bpobj_iterate(&dp->dp_free_bpobj,3811bpobj_dsl_scan_free_block_cb, scn, tx);3812VERIFY0(zio_wait(scn->scn_zio_root));3813scn->scn_zio_root = NULL;38143815if (err != 0 && err != ERESTART)3816zfs_panic_recover("error %u from bpobj_iterate()", err);3817}38183819if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {3820ASSERT(scn->scn_async_destroying);3821scn->scn_is_bptree = B_TRUE;3822scn->scn_zio_root = zio_root(spa, NULL,3823NULL, ZIO_FLAG_MUSTSUCCEED);3824err = bptree_iterate(dp->dp_meta_objset,3825dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);3826VERIFY0(zio_wait(scn->scn_zio_root));3827scn->scn_zio_root = NULL;38283829if (err == EIO || err == ECKSUM) {3830err = 0;3831} else if (err != 0 && err != ERESTART) {3832zfs_panic_recover("error %u from "3833"traverse_dataset_destroyed()", err);3834}38353836if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {3837/* finished; deactivate async destroy feature */3838spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);3839ASSERT(!spa_feature_is_active(spa,3840SPA_FEATURE_ASYNC_DESTROY));3841VERIFY0(zap_remove(dp->dp_meta_objset,3842DMU_POOL_DIRECTORY_OBJECT,3843DMU_POOL_BPTREE_OBJ, tx));3844VERIFY0(bptree_free(dp->dp_meta_objset,3845dp->dp_bptree_obj, tx));3846dp->dp_bptree_obj = 0;3847scn->scn_async_destroying = B_FALSE;3848scn->scn_async_stalled = B_FALSE;3849} else {3850/*3851* If we didn't make progress, mark the async3852* destroy as stalled, so that we will not initiate3853* a spa_sync() on its behalf. Note that we only3854* check this if we are not finished, because if the3855* bptree had no blocks for us to visit, we can3856* finish without "making progress".3857*/3858scn->scn_async_stalled =3859(scn->scn_visited_this_txg == 0);3860}3861}3862if (scn->scn_visited_this_txg) {3863zfs_dbgmsg("freed %llu blocks in %llums from "3864"free_bpobj/bptree on %s in txg %llu; err=%u",3865(longlong_t)scn->scn_visited_this_txg,3866(longlong_t)3867NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),3868spa->spa_name, (longlong_t)tx->tx_txg, err);3869scn->scn_visited_this_txg = 0;3870scn->scn_dedup_frees_this_txg = 0;38713872/*3873* Write out changes to the DDT and the BRT that may be required3874* as a result of the blocks freed. This ensures that the DDT3875* and the BRT are clean when a scrub/resilver runs.3876*/3877ddt_sync(spa, tx->tx_txg);3878brt_sync(spa, tx->tx_txg);3879}3880if (err != 0)3881return (err);3882if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&3883zfs_free_leak_on_eio &&3884(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||3885dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||3886dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {3887/*3888* We have finished background destroying, but there is still3889* some space left in the dp_free_dir. Transfer this leaked3890* space to the dp_leak_dir.3891*/3892if (dp->dp_leak_dir == NULL) {3893rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);3894(void) dsl_dir_create_sync(dp, dp->dp_root_dir,3895LEAK_DIR_NAME, tx);3896VERIFY0(dsl_pool_open_special_dir(dp,3897LEAK_DIR_NAME, &dp->dp_leak_dir));3898rrw_exit(&dp->dp_config_rwlock, FTAG);3899}3900dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,3901dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,3902dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,3903dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);3904dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,3905-dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,3906-dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,3907-dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);3908}39093910if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&3911!spa_livelist_delete_check(spa)) {3912/* finished; verify that space accounting went to zero */3913ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);3914ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);3915ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);3916}39173918spa_notify_waiters(spa);39193920EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),39210 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,3922DMU_POOL_OBSOLETE_BPOBJ));3923if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {3924ASSERT(spa_feature_is_active(dp->dp_spa,3925SPA_FEATURE_OBSOLETE_COUNTS));39263927scn->scn_is_bptree = B_FALSE;3928scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;3929err = bpobj_iterate(&dp->dp_obsolete_bpobj,3930dsl_scan_obsolete_block_cb, scn, tx);3931if (err != 0 && err != ERESTART)3932zfs_panic_recover("error %u from bpobj_iterate()", err);39333934if (bpobj_is_empty(&dp->dp_obsolete_bpobj))3935dsl_pool_destroy_obsolete_bpobj(dp, tx);3936}3937return (0);3938}39393940static void3941name_to_bookmark(char *buf, zbookmark_phys_t *zb)3942{3943zb->zb_objset = zfs_strtonum(buf, &buf);3944ASSERT(*buf == ':');3945zb->zb_object = zfs_strtonum(buf + 1, &buf);3946ASSERT(*buf == ':');3947zb->zb_level = (int)zfs_strtonum(buf + 1, &buf);3948ASSERT(*buf == ':');3949zb->zb_blkid = zfs_strtonum(buf + 1, &buf);3950ASSERT(*buf == '\0');3951}39523953static void3954name_to_object(char *buf, uint64_t *obj)3955{3956*obj = zfs_strtonum(buf, &buf);3957ASSERT(*buf == '\0');3958}39593960static void3961read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb)3962{3963dsl_pool_t *dp = scn->scn_dp;3964dsl_dataset_t *ds;3965objset_t *os;3966if (dsl_dataset_hold_obj(dp, zb.zb_objset, FTAG, &ds) != 0)3967return;39683969if (dmu_objset_from_ds(ds, &os) != 0) {3970dsl_dataset_rele(ds, FTAG);3971return;3972}39733974/*3975* If the key is not loaded dbuf_dnode_findbp() will error out with3976* EACCES. However in that case dnode_hold() will eventually call3977* dbuf_read()->zio_wait() which may call spa_log_error(). This will3978* lead to a deadlock due to us holding the mutex spa_errlist_lock.3979* Avoid this by checking here if the keys are loaded, if not return.3980* If the keys are not loaded the head_errlog feature is meaningless3981* as we cannot figure out the birth txg of the block pointer.3982*/3983if (dsl_dataset_get_keystatus(ds->ds_dir) ==3984ZFS_KEYSTATUS_UNAVAILABLE) {3985dsl_dataset_rele(ds, FTAG);3986return;3987}39883989dnode_t *dn;3990blkptr_t bp;39913992if (dnode_hold(os, zb.zb_object, FTAG, &dn) != 0) {3993dsl_dataset_rele(ds, FTAG);3994return;3995}39963997rw_enter(&dn->dn_struct_rwlock, RW_READER);3998int error = dbuf_dnode_findbp(dn, zb.zb_level, zb.zb_blkid, &bp, NULL,3999NULL);40004001if (error) {4002rw_exit(&dn->dn_struct_rwlock);4003dnode_rele(dn, FTAG);4004dsl_dataset_rele(ds, FTAG);4005return;4006}40074008if (!error && BP_IS_HOLE(&bp)) {4009rw_exit(&dn->dn_struct_rwlock);4010dnode_rele(dn, FTAG);4011dsl_dataset_rele(ds, FTAG);4012return;4013}40144015int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW |4016ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB;40174018/* If it's an intent log block, failure is expected. */4019if (zb.zb_level == ZB_ZIL_LEVEL)4020zio_flags |= ZIO_FLAG_SPECULATIVE;40214022ASSERT(!BP_IS_EMBEDDED(&bp));4023scan_exec_io(dp, &bp, zio_flags, &zb, NULL);4024rw_exit(&dn->dn_struct_rwlock);4025dnode_rele(dn, FTAG);4026dsl_dataset_rele(ds, FTAG);4027}40284029/*4030* We keep track of the scrubbed error blocks in "count". This will be used4031* when deciding whether we exceeded zfs_scrub_error_blocks_per_txg. This4032* function is modelled after check_filesystem().4033*/4034static int4035scrub_filesystem(spa_t *spa, uint64_t fs, zbookmark_err_phys_t *zep,4036int *count)4037{4038dsl_dataset_t *ds;4039dsl_pool_t *dp = spa->spa_dsl_pool;4040dsl_scan_t *scn = dp->dp_scan;40414042int error = dsl_dataset_hold_obj(dp, fs, FTAG, &ds);4043if (error != 0)4044return (error);40454046uint64_t latest_txg;4047uint64_t txg_to_consider = spa->spa_syncing_txg;4048boolean_t check_snapshot = B_TRUE;40494050error = find_birth_txg(ds, zep, &latest_txg);40514052/*4053* If find_birth_txg() errors out, then err on the side of caution and4054* proceed. In worst case scenario scrub all objects. If zep->zb_birth4055* is 0 (e.g. in case of encryption with unloaded keys) also proceed to4056* scrub all objects.4057*/4058if (error == 0 && zep->zb_birth == latest_txg) {4059/* Block neither free nor re written. */4060zbookmark_phys_t zb;4061zep_to_zb(fs, zep, &zb);4062scn->scn_zio_root = zio_root(spa, NULL, NULL,4063ZIO_FLAG_CANFAIL);4064/* We have already acquired the config lock for spa */4065read_by_block_level(scn, zb);40664067(void) zio_wait(scn->scn_zio_root);4068scn->scn_zio_root = NULL;40694070scn->errorscrub_phys.dep_examined++;4071scn->errorscrub_phys.dep_to_examine--;4072(*count)++;4073if ((*count) == zfs_scrub_error_blocks_per_txg ||4074dsl_error_scrub_check_suspend(scn, &zb)) {4075dsl_dataset_rele(ds, FTAG);4076return (SET_ERROR(EFAULT));4077}40784079check_snapshot = B_FALSE;4080} else if (error == 0) {4081txg_to_consider = latest_txg;4082}40834084/*4085* Retrieve the number of snapshots if the dataset is not a snapshot.4086*/4087uint64_t snap_count = 0;4088if (dsl_dataset_phys(ds)->ds_snapnames_zapobj != 0) {40894090error = zap_count(spa->spa_meta_objset,4091dsl_dataset_phys(ds)->ds_snapnames_zapobj, &snap_count);40924093if (error != 0) {4094dsl_dataset_rele(ds, FTAG);4095return (error);4096}4097}40984099if (snap_count == 0) {4100/* Filesystem without snapshots. */4101dsl_dataset_rele(ds, FTAG);4102return (0);4103}41044105uint64_t snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4106uint64_t snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;41074108dsl_dataset_rele(ds, FTAG);41094110/* Check only snapshots created from this file system. */4111while (snap_obj != 0 && zep->zb_birth < snap_obj_txg &&4112snap_obj_txg <= txg_to_consider) {41134114error = dsl_dataset_hold_obj(dp, snap_obj, FTAG, &ds);4115if (error != 0)4116return (error);41174118if (dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj != fs) {4119snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4120snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;4121dsl_dataset_rele(ds, FTAG);4122continue;4123}41244125boolean_t affected = B_TRUE;4126if (check_snapshot) {4127uint64_t blk_txg;4128error = find_birth_txg(ds, zep, &blk_txg);41294130/*4131* Scrub the snapshot also when zb_birth == 0 or when4132* find_birth_txg() returns an error.4133*/4134affected = (error == 0 && zep->zb_birth == blk_txg) ||4135(error != 0) || (zep->zb_birth == 0);4136}41374138/* Scrub snapshots. */4139if (affected) {4140zbookmark_phys_t zb;4141zep_to_zb(snap_obj, zep, &zb);4142scn->scn_zio_root = zio_root(spa, NULL, NULL,4143ZIO_FLAG_CANFAIL);4144/* We have already acquired the config lock for spa */4145read_by_block_level(scn, zb);41464147(void) zio_wait(scn->scn_zio_root);4148scn->scn_zio_root = NULL;41494150scn->errorscrub_phys.dep_examined++;4151scn->errorscrub_phys.dep_to_examine--;4152(*count)++;4153if ((*count) == zfs_scrub_error_blocks_per_txg ||4154dsl_error_scrub_check_suspend(scn, &zb)) {4155dsl_dataset_rele(ds, FTAG);4156return (EFAULT);4157}4158}4159snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;4160snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;4161dsl_dataset_rele(ds, FTAG);4162}4163return (0);4164}41654166void4167dsl_errorscrub_sync(dsl_pool_t *dp, dmu_tx_t *tx)4168{4169spa_t *spa = dp->dp_spa;4170dsl_scan_t *scn = dp->dp_scan;41714172/*4173* Only process scans in sync pass 1.4174*/41754176if (spa_sync_pass(spa) > 1)4177return;41784179/*4180* If the spa is shutting down, then stop scanning. This will4181* ensure that the scan does not dirty any new data during the4182* shutdown phase.4183*/4184if (spa_shutting_down(spa))4185return;41864187if (!dsl_errorscrub_active(scn) || dsl_errorscrub_is_paused(scn)) {4188return;4189}41904191if (dsl_scan_resilvering(scn->scn_dp)) {4192/* cancel the error scrub if resilver started */4193dsl_scan_cancel(scn->scn_dp);4194return;4195}41964197spa->spa_scrub_active = B_TRUE;4198scn->scn_sync_start_time = gethrtime();41994200/*4201* zfs_scan_suspend_progress can be set to disable scrub progress.4202* See more detailed comment in dsl_scan_sync().4203*/4204if (zfs_scan_suspend_progress) {4205uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time;4206int mintime = zfs_scrub_min_time_ms;42074208while (zfs_scan_suspend_progress &&4209!txg_sync_waiting(scn->scn_dp) &&4210!spa_shutting_down(scn->scn_dp->dp_spa) &&4211NSEC2MSEC(scan_time_ns) < mintime) {4212delay(hz);4213scan_time_ns = gethrtime() - scn->scn_sync_start_time;4214}4215return;4216}42174218int i = 0;4219zap_attribute_t *za;4220zbookmark_phys_t *zb;4221boolean_t limit_exceeded = B_FALSE;42224223za = zap_attribute_alloc();4224zb = kmem_zalloc(sizeof (zbookmark_phys_t), KM_SLEEP);42254226if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {4227for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;4228zap_cursor_advance(&scn->errorscrub_cursor)) {4229name_to_bookmark(za->za_name, zb);42304231scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4232NULL, ZIO_FLAG_CANFAIL);4233dsl_pool_config_enter(dp, FTAG);4234read_by_block_level(scn, *zb);4235dsl_pool_config_exit(dp, FTAG);42364237(void) zio_wait(scn->scn_zio_root);4238scn->scn_zio_root = NULL;42394240scn->errorscrub_phys.dep_examined += 1;4241scn->errorscrub_phys.dep_to_examine -= 1;4242i++;4243if (i == zfs_scrub_error_blocks_per_txg ||4244dsl_error_scrub_check_suspend(scn, zb)) {4245limit_exceeded = B_TRUE;4246break;4247}4248}42494250if (!limit_exceeded)4251dsl_errorscrub_done(scn, B_TRUE, tx);42524253dsl_errorscrub_sync_state(scn, tx);4254zap_attribute_free(za);4255kmem_free(zb, sizeof (*zb));4256return;4257}42584259int error = 0;4260for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;4261zap_cursor_advance(&scn->errorscrub_cursor)) {42624263zap_cursor_t *head_ds_cursor;4264zap_attribute_t *head_ds_attr;4265zbookmark_err_phys_t head_ds_block;42664267head_ds_cursor = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);4268head_ds_attr = zap_attribute_alloc();42694270uint64_t head_ds_err_obj = za->za_first_integer;4271uint64_t head_ds;4272name_to_object(za->za_name, &head_ds);4273boolean_t config_held = B_FALSE;4274uint64_t top_affected_fs;42754276for (zap_cursor_init(head_ds_cursor, spa->spa_meta_objset,4277head_ds_err_obj); zap_cursor_retrieve(head_ds_cursor,4278head_ds_attr) == 0; zap_cursor_advance(head_ds_cursor)) {42794280name_to_errphys(head_ds_attr->za_name, &head_ds_block);42814282/*4283* In case we are called from spa_sync the pool4284* config is already held.4285*/4286if (!dsl_pool_config_held(dp)) {4287dsl_pool_config_enter(dp, FTAG);4288config_held = B_TRUE;4289}42904291error = find_top_affected_fs(spa,4292head_ds, &head_ds_block, &top_affected_fs);4293if (error)4294break;42954296error = scrub_filesystem(spa, top_affected_fs,4297&head_ds_block, &i);42984299if (error == SET_ERROR(EFAULT)) {4300limit_exceeded = B_TRUE;4301break;4302}4303}43044305zap_cursor_fini(head_ds_cursor);4306kmem_free(head_ds_cursor, sizeof (*head_ds_cursor));4307zap_attribute_free(head_ds_attr);43084309if (config_held)4310dsl_pool_config_exit(dp, FTAG);4311}43124313zap_attribute_free(za);4314kmem_free(zb, sizeof (*zb));4315if (!limit_exceeded)4316dsl_errorscrub_done(scn, B_TRUE, tx);43174318dsl_errorscrub_sync_state(scn, tx);4319}43204321/*4322* This is the primary entry point for scans that is called from syncing4323* context. Scans must happen entirely during syncing context so that we4324* can guarantee that blocks we are currently scanning will not change out4325* from under us. While a scan is active, this function controls how quickly4326* transaction groups proceed, instead of the normal handling provided by4327* txg_sync_thread().4328*/4329void4330dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)4331{4332int err = 0;4333dsl_scan_t *scn = dp->dp_scan;4334spa_t *spa = dp->dp_spa;4335state_sync_type_t sync_type = SYNC_OPTIONAL;4336int restart_early = 0;43374338if (spa->spa_resilver_deferred) {4339uint64_t to_issue, issued;43404341if (!spa_feature_is_active(dp->dp_spa,4342SPA_FEATURE_RESILVER_DEFER))4343spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);43444345/*4346* See print_scan_scrub_resilver_status() issued/total_i4347* @ cmd/zpool/zpool_main.c4348*/4349to_issue =4350scn->scn_phys.scn_to_examine - scn->scn_phys.scn_skipped;4351issued =4352scn->scn_issued_before_pass + spa->spa_scan_pass_issued;4353restart_early =4354zfs_resilver_disable_defer ||4355(issued < (to_issue * zfs_resilver_defer_percent / 100));4356}43574358/*4359* Only process scans in sync pass 1.4360*/4361if (spa_sync_pass(spa) > 1)4362return;436343644365/*4366* Check for scn_restart_txg before checking spa_load_state, so4367* that we can restart an old-style scan while the pool is being4368* imported (see dsl_scan_init). We also restart scans if there4369* is a deferred resilver and the user has manually disabled4370* deferred resilvers via zfs_resilver_disable_defer, or if the4371* current scan progress is below zfs_resilver_defer_percent.4372*/4373if (dsl_scan_restarting(scn, tx) || restart_early) {4374setup_sync_arg_t setup_sync_arg = {4375.func = POOL_SCAN_SCRUB,4376.txgstart = 0,4377.txgend = 0,4378};4379dsl_scan_done(scn, B_FALSE, tx);4380if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))4381setup_sync_arg.func = POOL_SCAN_RESILVER;4382zfs_dbgmsg("restarting scan func=%u on %s txg=%llu early=%d",4383setup_sync_arg.func, dp->dp_spa->spa_name,4384(longlong_t)tx->tx_txg, restart_early);4385dsl_scan_setup_sync(&setup_sync_arg, tx);4386}43874388/*4389* If the spa is shutting down, then stop scanning. This will4390* ensure that the scan does not dirty any new data during the4391* shutdown phase.4392*/4393if (spa_shutting_down(spa))4394return;43954396/*4397* If the scan is inactive due to a stalled async destroy, try again.4398*/4399if (!scn->scn_async_stalled && !dsl_scan_active(scn))4400return;44014402/* reset scan statistics */4403scn->scn_visited_this_txg = 0;4404scn->scn_dedup_frees_this_txg = 0;4405scn->scn_holes_this_txg = 0;4406scn->scn_lt_min_this_txg = 0;4407scn->scn_gt_max_this_txg = 0;4408scn->scn_ddt_contained_this_txg = 0;4409scn->scn_objsets_visited_this_txg = 0;4410scn->scn_avg_seg_size_this_txg = 0;4411scn->scn_segs_this_txg = 0;4412scn->scn_avg_zio_size_this_txg = 0;4413scn->scn_zios_this_txg = 0;4414scn->scn_suspending = B_FALSE;4415scn->scn_sync_start_time = gethrtime();4416spa->spa_scrub_active = B_TRUE;44174418/*4419* First process the async destroys. If we suspend, don't do4420* any scrubbing or resilvering. This ensures that there are no4421* async destroys while we are scanning, so the scan code doesn't4422* have to worry about traversing it. It is also faster to free the4423* blocks than to scrub them.4424*/4425err = dsl_process_async_destroys(dp, tx);4426if (err != 0)4427return;44284429if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))4430return;44314432/*4433* Wait a few txgs after importing to begin scanning so that4434* we can get the pool imported quickly.4435*/4436if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)4437return;44384439/*4440* zfs_scan_suspend_progress can be set to disable scan progress.4441* We don't want to spin the txg_sync thread, so we add a delay4442* here to simulate the time spent doing a scan. This is mostly4443* useful for testing and debugging.4444*/4445if (zfs_scan_suspend_progress) {4446uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time;4447uint_t mintime = (scn->scn_phys.scn_func ==4448POOL_SCAN_RESILVER) ? zfs_resilver_min_time_ms :4449zfs_scrub_min_time_ms;44504451while (zfs_scan_suspend_progress &&4452!txg_sync_waiting(scn->scn_dp) &&4453!spa_shutting_down(scn->scn_dp->dp_spa) &&4454NSEC2MSEC(scan_time_ns) < mintime) {4455delay(hz);4456scan_time_ns = gethrtime() - scn->scn_sync_start_time;4457}4458return;4459}44604461/*4462* Disabled by default, set zfs_scan_report_txgs to report4463* average performance over the last zfs_scan_report_txgs TXGs.4464*/4465if (zfs_scan_report_txgs != 0 &&4466tx->tx_txg % zfs_scan_report_txgs == 0) {4467scn->scn_issued_before_pass += spa->spa_scan_pass_issued;4468spa_scan_stat_init(spa);4469}44704471/*4472* It is possible to switch from unsorted to sorted at any time,4473* but afterwards the scan will remain sorted unless reloaded from4474* a checkpoint after a reboot.4475*/4476if (!zfs_scan_legacy) {4477scn->scn_is_sorted = B_TRUE;4478if (scn->scn_last_checkpoint == 0)4479scn->scn_last_checkpoint = ddi_get_lbolt();4480}44814482/*4483* For sorted scans, determine what kind of work we will be doing4484* this txg based on our memory limitations and whether or not we4485* need to perform a checkpoint.4486*/4487if (scn->scn_is_sorted) {4488/*4489* If we are over our checkpoint interval, set scn_clearing4490* so that we can begin checkpointing immediately. The4491* checkpoint allows us to save a consistent bookmark4492* representing how much data we have scrubbed so far.4493* Otherwise, use the memory limit to determine if we should4494* scan for metadata or start issue scrub IOs. We accumulate4495* metadata until we hit our hard memory limit at which point4496* we issue scrub IOs until we are at our soft memory limit.4497*/4498if (scn->scn_checkpointing ||4499ddi_get_lbolt() - scn->scn_last_checkpoint >4500SEC_TO_TICK(zfs_scan_checkpoint_intval)) {4501if (!scn->scn_checkpointing)4502zfs_dbgmsg("begin scan checkpoint for %s",4503spa->spa_name);45044505scn->scn_checkpointing = B_TRUE;4506scn->scn_clearing = B_TRUE;4507} else {4508boolean_t should_clear = dsl_scan_should_clear(scn);4509if (should_clear && !scn->scn_clearing) {4510zfs_dbgmsg("begin scan clearing for %s",4511spa->spa_name);4512scn->scn_clearing = B_TRUE;4513} else if (!should_clear && scn->scn_clearing) {4514zfs_dbgmsg("finish scan clearing for %s",4515spa->spa_name);4516scn->scn_clearing = B_FALSE;4517}4518}4519} else {4520ASSERT0(scn->scn_checkpointing);4521ASSERT0(scn->scn_clearing);4522}45234524if (!scn->scn_clearing && scn->scn_done_txg == 0) {4525/* Need to scan metadata for more blocks to scrub */4526dsl_scan_phys_t *scnp = &scn->scn_phys;4527taskqid_t prefetch_tqid;45284529/*4530* Calculate the max number of in-flight bytes for pool-wide4531* scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).4532* Limits for the issuing phase are done per top-level vdev and4533* are handled separately.4534*/4535scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,4536zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));45374538if (scnp->scn_ddt_bookmark.ddb_class <=4539scnp->scn_ddt_class_max) {4540ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));4541zfs_dbgmsg("doing scan sync for %s txg %llu; "4542"ddt bm=%llu/%llu/%llu/%llx",4543spa->spa_name,4544(longlong_t)tx->tx_txg,4545(longlong_t)scnp->scn_ddt_bookmark.ddb_class,4546(longlong_t)scnp->scn_ddt_bookmark.ddb_type,4547(longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,4548(longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);4549} else {4550zfs_dbgmsg("doing scan sync for %s txg %llu; "4551"bm=%llu/%llu/%llu/%llu",4552spa->spa_name,4553(longlong_t)tx->tx_txg,4554(longlong_t)scnp->scn_bookmark.zb_objset,4555(longlong_t)scnp->scn_bookmark.zb_object,4556(longlong_t)scnp->scn_bookmark.zb_level,4557(longlong_t)scnp->scn_bookmark.zb_blkid);4558}45594560scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4561NULL, ZIO_FLAG_CANFAIL);45624563scn->scn_prefetch_stop = B_FALSE;4564prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,4565dsl_scan_prefetch_thread, scn, TQ_SLEEP);4566ASSERT(prefetch_tqid != TASKQID_INVALID);45674568dsl_pool_config_enter(dp, FTAG);4569dsl_scan_visit(scn, tx);4570dsl_pool_config_exit(dp, FTAG);45714572mutex_enter(&dp->dp_spa->spa_scrub_lock);4573scn->scn_prefetch_stop = B_TRUE;4574cv_broadcast(&spa->spa_scrub_io_cv);4575mutex_exit(&dp->dp_spa->spa_scrub_lock);45764577taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);4578(void) zio_wait(scn->scn_zio_root);4579scn->scn_zio_root = NULL;45804581zfs_dbgmsg("scan visited %llu blocks of %s in %llums "4582"(%llu os's, %llu holes, %llu < mintxg, "4583"%llu in ddt, %llu > maxtxg)",4584(longlong_t)scn->scn_visited_this_txg,4585spa->spa_name,4586(longlong_t)NSEC2MSEC(gethrtime() -4587scn->scn_sync_start_time),4588(longlong_t)scn->scn_objsets_visited_this_txg,4589(longlong_t)scn->scn_holes_this_txg,4590(longlong_t)scn->scn_lt_min_this_txg,4591(longlong_t)scn->scn_ddt_contained_this_txg,4592(longlong_t)scn->scn_gt_max_this_txg);45934594if (!scn->scn_suspending) {4595ASSERT0(avl_numnodes(&scn->scn_queue));4596scn->scn_done_txg = tx->tx_txg + 1;4597if (scn->scn_is_sorted) {4598scn->scn_checkpointing = B_TRUE;4599scn->scn_clearing = B_TRUE;4600scn->scn_issued_before_pass +=4601spa->spa_scan_pass_issued;4602spa_scan_stat_init(spa);4603}4604zfs_dbgmsg("scan complete for %s txg %llu",4605spa->spa_name,4606(longlong_t)tx->tx_txg);4607}4608} else if (scn->scn_is_sorted && scn->scn_queues_pending != 0) {4609ASSERT(scn->scn_clearing);46104611/* need to issue scrubbing IOs from per-vdev queues */4612scn->scn_zio_root = zio_root(dp->dp_spa, NULL,4613NULL, ZIO_FLAG_CANFAIL);4614scan_io_queues_run(scn);4615(void) zio_wait(scn->scn_zio_root);4616scn->scn_zio_root = NULL;46174618/* calculate and dprintf the current memory usage */4619(void) dsl_scan_should_clear(scn);4620dsl_scan_update_stats(scn);46214622zfs_dbgmsg("scan issued %llu blocks for %s (%llu segs) "4623"in %llums (avg_block_size = %llu, avg_seg_size = %llu)",4624(longlong_t)scn->scn_zios_this_txg,4625spa->spa_name,4626(longlong_t)scn->scn_segs_this_txg,4627(longlong_t)NSEC2MSEC(gethrtime() -4628scn->scn_sync_start_time),4629(longlong_t)scn->scn_avg_zio_size_this_txg,4630(longlong_t)scn->scn_avg_seg_size_this_txg);4631} else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {4632/* Finished with everything. Mark the scrub as complete */4633zfs_dbgmsg("scan issuing complete txg %llu for %s",4634(longlong_t)tx->tx_txg,4635spa->spa_name);4636ASSERT3U(scn->scn_done_txg, !=, 0);4637ASSERT0(spa->spa_scrub_inflight);4638ASSERT0(scn->scn_queues_pending);4639dsl_scan_done(scn, B_TRUE, tx);4640sync_type = SYNC_MANDATORY;4641}46424643dsl_scan_sync_state(scn, tx, sync_type);4644}46454646static void4647count_block_issued(spa_t *spa, const blkptr_t *bp, boolean_t all)4648{4649/*4650* Don't count embedded bp's, since we already did the work of4651* scanning these when we scanned the containing block.4652*/4653if (BP_IS_EMBEDDED(bp))4654return;46554656/*4657* Update the spa's stats on how many bytes we have issued.4658* Sequential scrubs create a zio for each DVA of the bp. Each4659* of these will include all DVAs for repair purposes, but the4660* zio code will only try the first one unless there is an issue.4661* Therefore, we should only count the first DVA for these IOs.4662*/4663atomic_add_64(&spa->spa_scan_pass_issued,4664all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));4665}46664667static void4668count_block_skipped(dsl_scan_t *scn, const blkptr_t *bp, boolean_t all)4669{4670if (BP_IS_EMBEDDED(bp))4671return;4672atomic_add_64(&scn->scn_phys.scn_skipped,4673all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));4674}46754676static void4677count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)4678{4679/*4680* If we resume after a reboot, zab will be NULL; don't record4681* incomplete stats in that case.4682*/4683if (zab == NULL)4684return;46854686for (int i = 0; i < 4; i++) {4687int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;4688int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;46894690if (t & DMU_OT_NEWTYPE)4691t = DMU_OT_OTHER;4692zfs_blkstat_t *zb = &zab->zab_type[l][t];4693int equal;46944695zb->zb_count++;4696zb->zb_asize += BP_GET_ASIZE(bp);4697zb->zb_lsize += BP_GET_LSIZE(bp);4698zb->zb_psize += BP_GET_PSIZE(bp);4699zb->zb_gangs += BP_COUNT_GANG(bp);47004701switch (BP_GET_NDVAS(bp)) {4702case 2:4703if (DVA_GET_VDEV(&bp->blk_dva[0]) ==4704DVA_GET_VDEV(&bp->blk_dva[1]))4705zb->zb_ditto_2_of_2_samevdev++;4706break;4707case 3:4708equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==4709DVA_GET_VDEV(&bp->blk_dva[1])) +4710(DVA_GET_VDEV(&bp->blk_dva[0]) ==4711DVA_GET_VDEV(&bp->blk_dva[2])) +4712(DVA_GET_VDEV(&bp->blk_dva[1]) ==4713DVA_GET_VDEV(&bp->blk_dva[2]));4714if (equal == 1)4715zb->zb_ditto_2_of_3_samevdev++;4716else if (equal == 3)4717zb->zb_ditto_3_of_3_samevdev++;4718break;4719}4720}4721}47224723static void4724scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)4725{4726avl_index_t idx;4727dsl_scan_t *scn = queue->q_scn;47284729ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));47304731if (unlikely(avl_is_empty(&queue->q_sios_by_addr)))4732atomic_add_64(&scn->scn_queues_pending, 1);4733if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {4734/* block is already scheduled for reading */4735sio_free(sio);4736return;4737}4738avl_insert(&queue->q_sios_by_addr, sio, idx);4739queue->q_sio_memused += SIO_GET_MUSED(sio);4740zfs_range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio),4741SIO_GET_ASIZE(sio));4742}47434744/*4745* Given all the info we got from our metadata scanning process, we4746* construct a scan_io_t and insert it into the scan sorting queue. The4747* I/O must already be suitable for us to process. This is controlled4748* by dsl_scan_enqueue().4749*/4750static void4751scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,4752int zio_flags, const zbookmark_phys_t *zb)4753{4754scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp));47554756ASSERT0(BP_IS_GANG(bp));4757ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));47584759bp2sio(bp, sio, dva_i);4760sio->sio_flags = zio_flags;4761sio->sio_zb = *zb;47624763queue->q_last_ext_addr = -1;4764scan_io_queue_insert_impl(queue, sio);4765}47664767/*4768* Given a set of I/O parameters as discovered by the metadata traversal4769* process, attempts to place the I/O into the sorted queues (if allowed),4770* or immediately executes the I/O.4771*/4772static void4773dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,4774const zbookmark_phys_t *zb)4775{4776spa_t *spa = dp->dp_spa;47774778ASSERT(!BP_IS_EMBEDDED(bp));47794780/*4781* Gang blocks are hard to issue sequentially, so we just issue them4782* here immediately instead of queuing them.4783*/4784if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {4785scan_exec_io(dp, bp, zio_flags, zb, NULL);4786return;4787}47884789for (int i = 0; i < BP_GET_NDVAS(bp); i++) {4790dva_t dva;4791vdev_t *vdev;47924793dva = bp->blk_dva[i];4794vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));4795ASSERT(vdev != NULL);47964797mutex_enter(&vdev->vdev_scan_io_queue_lock);4798if (vdev->vdev_scan_io_queue == NULL)4799vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);4800ASSERT(dp->dp_scan != NULL);4801scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,4802i, zio_flags, zb);4803mutex_exit(&vdev->vdev_scan_io_queue_lock);4804}4805}48064807static int4808dsl_scan_scrub_cb(dsl_pool_t *dp,4809const blkptr_t *bp, const zbookmark_phys_t *zb)4810{4811dsl_scan_t *scn = dp->dp_scan;4812spa_t *spa = dp->dp_spa;4813uint64_t phys_birth = BP_GET_PHYSICAL_BIRTH(bp);4814size_t psize = BP_GET_PSIZE(bp);4815boolean_t needs_io = B_FALSE;4816int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;48174818count_block(dp->dp_blkstats, bp);4819if (phys_birth <= scn->scn_phys.scn_min_txg ||4820phys_birth >= scn->scn_phys.scn_max_txg) {4821count_block_skipped(scn, bp, B_TRUE);4822return (0);4823}48244825/* Embedded BP's have phys_birth==0, so we reject them above. */4826ASSERT(!BP_IS_EMBEDDED(bp));48274828ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));4829if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {4830zio_flags |= ZIO_FLAG_SCRUB;4831needs_io = B_TRUE;4832} else {4833ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);4834zio_flags |= ZIO_FLAG_RESILVER;4835needs_io = B_FALSE;4836}48374838/* If it's an intent log block, failure is expected. */4839if (zb->zb_level == ZB_ZIL_LEVEL)4840zio_flags |= ZIO_FLAG_SPECULATIVE;48414842for (int d = 0; d < BP_GET_NDVAS(bp); d++) {4843const dva_t *dva = &bp->blk_dva[d];48444845/*4846* Keep track of how much data we've examined so that4847* zpool(8) status can make useful progress reports.4848*/4849uint64_t asize = DVA_GET_ASIZE(dva);4850scn->scn_phys.scn_examined += asize;4851spa->spa_scan_pass_exam += asize;48524853/* if it's a resilver, this may not be in the target range */4854if (!needs_io)4855needs_io = dsl_scan_need_resilver(spa, dva, psize,4856phys_birth);4857}48584859if (needs_io && !zfs_no_scrub_io) {4860dsl_scan_enqueue(dp, bp, zio_flags, zb);4861} else {4862count_block_skipped(scn, bp, B_TRUE);4863}48644865/* do not relocate this block */4866return (0);4867}48684869static void4870dsl_scan_scrub_done(zio_t *zio)4871{4872spa_t *spa = zio->io_spa;4873blkptr_t *bp = zio->io_bp;4874dsl_scan_io_queue_t *queue = zio->io_private;48754876abd_free(zio->io_abd);48774878if (queue == NULL) {4879mutex_enter(&spa->spa_scrub_lock);4880ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));4881spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);4882cv_broadcast(&spa->spa_scrub_io_cv);4883mutex_exit(&spa->spa_scrub_lock);4884} else {4885mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);4886ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));4887queue->q_inflight_bytes -= BP_GET_PSIZE(bp);4888cv_broadcast(&queue->q_zio_cv);4889mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);4890}48914892if (zio->io_error && (zio->io_error != ECKSUM ||4893!(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {4894if (dsl_errorscrubbing(spa->spa_dsl_pool) &&4895!dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan)) {4896atomic_inc_64(&spa->spa_dsl_pool->dp_scan4897->errorscrub_phys.dep_errors);4898} else {4899atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys4900.scn_errors);4901}4902}4903}49044905/*4906* Given a scanning zio's information, executes the zio. The zio need4907* not necessarily be only sortable, this function simply executes the4908* zio, no matter what it is. The optional queue argument allows the4909* caller to specify that they want per top level vdev IO rate limiting4910* instead of the legacy global limiting.4911*/4912static void4913scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,4914const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)4915{4916spa_t *spa = dp->dp_spa;4917dsl_scan_t *scn = dp->dp_scan;4918size_t size = BP_GET_PSIZE(bp);4919abd_t *data = abd_alloc_for_io(size, B_FALSE);4920zio_t *pio;49214922if (queue == NULL) {4923ASSERT3U(scn->scn_maxinflight_bytes, >, 0);4924mutex_enter(&spa->spa_scrub_lock);4925while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)4926cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);4927spa->spa_scrub_inflight += BP_GET_PSIZE(bp);4928mutex_exit(&spa->spa_scrub_lock);4929pio = scn->scn_zio_root;4930} else {4931kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;49324933ASSERT3U(queue->q_maxinflight_bytes, >, 0);4934mutex_enter(q_lock);4935while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)4936cv_wait(&queue->q_zio_cv, q_lock);4937queue->q_inflight_bytes += BP_GET_PSIZE(bp);4938pio = queue->q_zio;4939mutex_exit(q_lock);4940}49414942ASSERT(pio != NULL);4943count_block_issued(spa, bp, queue == NULL);4944zio_nowait(zio_read(pio, spa, bp, data, size, dsl_scan_scrub_done,4945queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));4946}49474948/*4949* This is the primary extent sorting algorithm. We balance two parameters:4950* 1) how many bytes of I/O are in an extent4951* 2) how well the extent is filled with I/O (as a fraction of its total size)4952* Since we allow extents to have gaps between their constituent I/Os, it's4953* possible to have a fairly large extent that contains the same amount of4954* I/O bytes than a much smaller extent, which just packs the I/O more tightly.4955* The algorithm sorts based on a score calculated from the extent's size,4956* the relative fill volume (in %) and a "fill weight" parameter that controls4957* the split between whether we prefer larger extents or more well populated4958* extents:4959*4960* SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)4961*4962* Example:4963* 1) assume extsz = 64 MiB4964* 2) assume fill = 32 MiB (extent is half full)4965* 3) assume fill_weight = 34966* 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 1004967* SCORE = 32M + (50 * 3 * 32M) / 1004968* SCORE = 32M + (4800M / 100)4969* SCORE = 32M + 48M4970* ^ ^4971* | +--- final total relative fill-based score4972* +--------- final total fill-based score4973* SCORE = 80M4974*4975* As can be seen, at fill_ratio=3, the algorithm is slightly biased towards4976* extents that are more completely filled (in a 3:2 ratio) vs just larger.4977* Note that as an optimization, we replace multiplication and division by4978* 100 with bitshifting by 7 (which effectively multiplies and divides by 128).4979*4980* Since we do not care if one extent is only few percent better than another,4981* compress the score into 6 bits via binary logarithm AKA highbit64() and4982* put into otherwise unused due to ashift high bits of offset. This allows4983* to reduce q_exts_by_size B-tree elements to only 64 bits and compare them4984* with single operation. Plus it makes scrubs more sequential and reduces4985* chances that minor extent change move it within the B-tree.4986*/4987__attribute__((always_inline)) inline4988static int4989ext_size_compare(const void *x, const void *y)4990{4991const uint64_t *a = x, *b = y;49924993return (TREE_CMP(*a, *b));4994}49954996ZFS_BTREE_FIND_IN_BUF_FUNC(ext_size_find_in_buf, uint64_t,4997ext_size_compare)49984999static void5000ext_size_create(zfs_range_tree_t *rt, void *arg)5001{5002(void) rt;5003zfs_btree_t *size_tree = arg;50045005zfs_btree_create(size_tree, ext_size_compare, ext_size_find_in_buf,5006sizeof (uint64_t));5007}50085009static void5010ext_size_destroy(zfs_range_tree_t *rt, void *arg)5011{5012(void) rt;5013zfs_btree_t *size_tree = arg;5014ASSERT0(zfs_btree_numnodes(size_tree));50155016zfs_btree_destroy(size_tree);5017}50185019static uint64_t5020ext_size_value(zfs_range_tree_t *rt, zfs_range_seg_gap_t *rsg)5021{5022(void) rt;5023uint64_t size = rsg->rs_end - rsg->rs_start;5024uint64_t score = rsg->rs_fill + ((((rsg->rs_fill << 7) / size) *5025fill_weight * rsg->rs_fill) >> 7);5026ASSERT3U(rt->rt_shift, >=, 8);5027return (((uint64_t)(64 - highbit64(score)) << 56) | rsg->rs_start);5028}50295030static void5031ext_size_add(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)5032{5033zfs_btree_t *size_tree = arg;5034ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);5035uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);5036zfs_btree_add(size_tree, &v);5037}50385039static void5040ext_size_remove(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)5041{5042zfs_btree_t *size_tree = arg;5043ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);5044uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);5045zfs_btree_remove(size_tree, &v);5046}50475048static void5049ext_size_vacate(zfs_range_tree_t *rt, void *arg)5050{5051zfs_btree_t *size_tree = arg;5052zfs_btree_clear(size_tree);5053zfs_btree_destroy(size_tree);50545055ext_size_create(rt, arg);5056}50575058static const zfs_range_tree_ops_t ext_size_ops = {5059.rtop_create = ext_size_create,5060.rtop_destroy = ext_size_destroy,5061.rtop_add = ext_size_add,5062.rtop_remove = ext_size_remove,5063.rtop_vacate = ext_size_vacate5064};50655066/*5067* Comparator for the q_sios_by_addr tree. Sorting is simply performed5068* based on LBA-order (from lowest to highest).5069*/5070static int5071sio_addr_compare(const void *x, const void *y)5072{5073const scan_io_t *a = x, *b = y;50745075return (TREE_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b)));5076}50775078/* IO queues are created on demand when they are needed. */5079static dsl_scan_io_queue_t *5080scan_io_queue_create(vdev_t *vd)5081{5082dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;5083dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);50845085q->q_scn = scn;5086q->q_vd = vd;5087q->q_sio_memused = 0;5088q->q_last_ext_addr = -1;5089cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);5090q->q_exts_by_addr = zfs_range_tree_create_gap(&ext_size_ops,5091ZFS_RANGE_SEG_GAP, &q->q_exts_by_size, 0, vd->vdev_ashift,5092zfs_scan_max_ext_gap);5093avl_create(&q->q_sios_by_addr, sio_addr_compare,5094sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));50955096return (q);5097}50985099/*5100* Destroys a scan queue and all segments and scan_io_t's contained in it.5101* No further execution of I/O occurs, anything pending in the queue is5102* simply freed without being executed.5103*/5104void5105dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)5106{5107dsl_scan_t *scn = queue->q_scn;5108scan_io_t *sio;5109void *cookie = NULL;51105111ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));51125113if (!avl_is_empty(&queue->q_sios_by_addr))5114atomic_add_64(&scn->scn_queues_pending, -1);5115while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=5116NULL) {5117ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr,5118SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio)));5119queue->q_sio_memused -= SIO_GET_MUSED(sio);5120sio_free(sio);5121}51225123ASSERT0(queue->q_sio_memused);5124zfs_range_tree_vacate(queue->q_exts_by_addr, NULL, queue);5125zfs_range_tree_destroy(queue->q_exts_by_addr);5126avl_destroy(&queue->q_sios_by_addr);5127cv_destroy(&queue->q_zio_cv);51285129kmem_free(queue, sizeof (*queue));5130}51315132/*5133* Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is5134* called on behalf of vdev_top_transfer when creating or destroying5135* a mirror vdev due to zpool attach/detach.5136*/5137void5138dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)5139{5140mutex_enter(&svd->vdev_scan_io_queue_lock);5141mutex_enter(&tvd->vdev_scan_io_queue_lock);51425143VERIFY0P(tvd->vdev_scan_io_queue);5144tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;5145svd->vdev_scan_io_queue = NULL;5146if (tvd->vdev_scan_io_queue != NULL)5147tvd->vdev_scan_io_queue->q_vd = tvd;51485149mutex_exit(&tvd->vdev_scan_io_queue_lock);5150mutex_exit(&svd->vdev_scan_io_queue_lock);5151}51525153static void5154scan_io_queues_destroy(dsl_scan_t *scn)5155{5156vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;51575158for (uint64_t i = 0; i < rvd->vdev_children; i++) {5159vdev_t *tvd = rvd->vdev_child[i];51605161mutex_enter(&tvd->vdev_scan_io_queue_lock);5162if (tvd->vdev_scan_io_queue != NULL)5163dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);5164tvd->vdev_scan_io_queue = NULL;5165mutex_exit(&tvd->vdev_scan_io_queue_lock);5166}5167}51685169static void5170dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)5171{5172dsl_pool_t *dp = spa->spa_dsl_pool;5173dsl_scan_t *scn = dp->dp_scan;5174vdev_t *vdev;5175kmutex_t *q_lock;5176dsl_scan_io_queue_t *queue;5177scan_io_t *srch_sio, *sio;5178avl_index_t idx;5179uint64_t start, size;51805181vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));5182ASSERT(vdev != NULL);5183q_lock = &vdev->vdev_scan_io_queue_lock;5184queue = vdev->vdev_scan_io_queue;51855186mutex_enter(q_lock);5187if (queue == NULL) {5188mutex_exit(q_lock);5189return;5190}51915192srch_sio = sio_alloc(BP_GET_NDVAS(bp));5193bp2sio(bp, srch_sio, dva_i);5194start = SIO_GET_OFFSET(srch_sio);5195size = SIO_GET_ASIZE(srch_sio);51965197/*5198* We can find the zio in two states:5199* 1) Cold, just sitting in the queue of zio's to be issued at5200* some point in the future. In this case, all we do is5201* remove the zio from the q_sios_by_addr tree, decrement5202* its data volume from the containing zfs_range_seg_t and5203* resort the q_exts_by_size tree to reflect that the5204* zfs_range_seg_t has lost some of its 'fill'. We don't shorten5205* the zfs_range_seg_t - this is usually rare enough not to be5206* worth the extra hassle of trying keep track of precise5207* extent boundaries.5208* 2) Hot, where the zio is currently in-flight in5209* dsl_scan_issue_ios. In this case, we can't simply5210* reach in and stop the in-flight zio's, so we instead5211* block the caller. Eventually, dsl_scan_issue_ios will5212* be done with issuing the zio's it gathered and will5213* signal us.5214*/5215sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);5216sio_free(srch_sio);52175218if (sio != NULL) {5219blkptr_t tmpbp;52205221/* Got it while it was cold in the queue */5222ASSERT3U(start, ==, SIO_GET_OFFSET(sio));5223ASSERT3U(size, ==, SIO_GET_ASIZE(sio));5224avl_remove(&queue->q_sios_by_addr, sio);5225if (avl_is_empty(&queue->q_sios_by_addr))5226atomic_add_64(&scn->scn_queues_pending, -1);5227queue->q_sio_memused -= SIO_GET_MUSED(sio);52285229ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr, start,5230size));5231zfs_range_tree_remove_fill(queue->q_exts_by_addr, start, size);52325233/* count the block as though we skipped it */5234sio2bp(sio, &tmpbp);5235count_block_skipped(scn, &tmpbp, B_FALSE);52365237sio_free(sio);5238}5239mutex_exit(q_lock);5240}52415242/*5243* Callback invoked when a zio_free() zio is executing. This needs to be5244* intercepted to prevent the zio from deallocating a particular portion5245* of disk space and it then getting reallocated and written to, while we5246* still have it queued up for processing.5247*/5248void5249dsl_scan_freed(spa_t *spa, const blkptr_t *bp)5250{5251dsl_pool_t *dp = spa->spa_dsl_pool;5252dsl_scan_t *scn = dp->dp_scan;52535254ASSERT(!BP_IS_EMBEDDED(bp));5255ASSERT(scn != NULL);5256if (!dsl_scan_is_running(scn))5257return;52585259for (int i = 0; i < BP_GET_NDVAS(bp); i++)5260dsl_scan_freed_dva(spa, bp, i);5261}52625263/*5264* Check if a vdev needs resilvering (non-empty DTL), if so, and resilver has5265* not started, start it. Otherwise, only restart if max txg in DTL range is5266* greater than the max txg in the current scan. If the DTL max is less than5267* the scan max, then the vdev has not missed any new data since the resilver5268* started, so a restart is not needed.5269*/5270void5271dsl_scan_assess_vdev(dsl_pool_t *dp, vdev_t *vd)5272{5273uint64_t min, max;52745275if (!vdev_resilver_needed(vd, &min, &max))5276return;52775278if (!dsl_scan_resilvering(dp)) {5279spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);5280return;5281}52825283if (max <= dp->dp_scan->scn_phys.scn_max_txg)5284return;52855286/* restart is needed, check if it can be deferred */5287if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))5288vdev_defer_resilver(vd);5289else5290spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);5291}52925293ZFS_MODULE_PARAM(zfs, zfs_, scan_vdev_limit, U64, ZMOD_RW,5294"Max bytes in flight per leaf vdev for scrubs and resilvers");52955296ZFS_MODULE_PARAM(zfs, zfs_, scrub_min_time_ms, UINT, ZMOD_RW,5297"Min millisecs to scrub per txg");52985299ZFS_MODULE_PARAM(zfs, zfs_, obsolete_min_time_ms, UINT, ZMOD_RW,5300"Min millisecs to obsolete per txg");53015302ZFS_MODULE_PARAM(zfs, zfs_, free_min_time_ms, UINT, ZMOD_RW,5303"Min millisecs to free per txg");53045305ZFS_MODULE_PARAM(zfs, zfs_, resilver_min_time_ms, UINT, ZMOD_RW,5306"Min millisecs to resilver per txg");53075308ZFS_MODULE_PARAM(zfs, zfs_, scan_suspend_progress, INT, ZMOD_RW,5309"Set to prevent scans from progressing");53105311ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_io, INT, ZMOD_RW,5312"Set to disable scrub I/O");53135314ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_prefetch, INT, ZMOD_RW,5315"Set to disable scrub prefetching");53165317ZFS_MODULE_PARAM(zfs, zfs_, async_block_max_blocks, U64, ZMOD_RW,5318"Max number of blocks freed in one txg");53195320ZFS_MODULE_PARAM(zfs, zfs_, max_async_dedup_frees, U64, ZMOD_RW,5321"Max number of dedup blocks freed in one txg");53225323ZFS_MODULE_PARAM(zfs, zfs_, free_bpobj_enabled, INT, ZMOD_RW,5324"Enable processing of the free_bpobj");53255326ZFS_MODULE_PARAM(zfs, zfs_, scan_blkstats, INT, ZMOD_RW,5327"Enable block statistics calculation during scrub");53285329ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_fact, UINT, ZMOD_RW,5330"Fraction of RAM for scan hard limit");53315332ZFS_MODULE_PARAM(zfs, zfs_, scan_issue_strategy, UINT, ZMOD_RW,5333"IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");53345335ZFS_MODULE_PARAM(zfs, zfs_, scan_legacy, INT, ZMOD_RW,5336"Scrub using legacy non-sequential method");53375338ZFS_MODULE_PARAM(zfs, zfs_, scan_checkpoint_intval, UINT, ZMOD_RW,5339"Scan progress on-disk checkpointing interval");53405341ZFS_MODULE_PARAM(zfs, zfs_, scan_max_ext_gap, U64, ZMOD_RW,5342"Max gap in bytes between sequential scrub / resilver I/Os");53435344ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_soft_fact, UINT, ZMOD_RW,5345"Fraction of hard limit used as soft limit");53465347ZFS_MODULE_PARAM(zfs, zfs_, scan_strict_mem_lim, INT, ZMOD_RW,5348"Tunable to attempt to reduce lock contention");53495350ZFS_MODULE_PARAM(zfs, zfs_, scan_fill_weight, UINT, ZMOD_RW,5351"Tunable to adjust bias towards more filled segments during scans");53525353ZFS_MODULE_PARAM(zfs, zfs_, scan_report_txgs, UINT, ZMOD_RW,5354"Tunable to report resilver performance over the last N txgs");53555356ZFS_MODULE_PARAM(zfs, zfs_, resilver_disable_defer, INT, ZMOD_RW,5357"Process all resilvers immediately");53585359ZFS_MODULE_PARAM(zfs, zfs_, resilver_defer_percent, UINT, ZMOD_RW,5360"Issued IO percent complete after which resilvers are deferred");53615362ZFS_MODULE_PARAM(zfs, zfs_, scrub_error_blocks_per_txg, UINT, ZMOD_RW,5363"Error blocks to be scrubbed in one txg");536453655366