Allow dsl_deadlist_open() return errors
[zfs.git] / module / zfs / dsl_scan.c
blob19fa76931b6e0b62ac5c4a6349880ee0f6801bcd
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
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 Mills
25 * Copyright (c) 2017, 2019, Datto Inc. All rights reserved.
26 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
27 * Copyright 2019 Joyent, Inc.
30 #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 _KERNEL
59 #include <sys/zfs_vfsops.h>
60 #endif
63 * Grand theory statement on scan queue sorting
65 * Scanning is implemented by recursively traversing all indirection levels
66 * in an object and reading all blocks referenced from said objects. This
67 * results in us approximately traversing the object from lowest logical
68 * offset to the highest. For best performance, we would want the logical
69 * blocks to be physically contiguous. However, this is frequently not the
70 * 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 a
72 * way that will most benefit physical disks (LBA-order).
74 * Queue management:
76 * Ideally, we would want to scan all metadata and queue up all block I/O
77 * prior to starting to issue it, because that allows us to do an optimal
78 * sorting job. This can however consume large amounts of memory. Therefore
79 * 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 this
81 * limit, we clear out a few of the largest extents at the head of the queues
82 * to make room for more scanning. Hopefully, these extents will be fairly
83 * large and contiguous, allowing us to approach sequential I/O throughput
84 * even without a fully sorted tree.
86 * Metadata scanning takes place in dsl_scan_visit(), which is called from
87 * dsl_scan_sync() every spa_sync(). If we have either fully scanned all
88 * metadata on the pool, or we need to make room in memory because our
89 * queues are too large, dsl_scan_visit() is postponed and
90 * scan_io_queues_run() is called from dsl_scan_sync() instead. This implies
91 * that metadata scanning and queued I/O issuing are mutually exclusive. This
92 * allows us to provide maximum sequential I/O throughput for the majority of
93 * I/O's issued since sequential I/O performance is significantly negatively
94 * impacted if it is interleaved with random I/O.
96 * Implementation Notes
98 * One side effect of the queued scanning algorithm is that the scanning code
99 * needs to be notified whenever a block is freed. This is needed to allow
100 * 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 this
102 * 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 legacy
104 * algorithm.
106 * Backwards compatibility
108 * This new algorithm is backwards compatible with the legacy on-disk data
109 * structures (and therefore does not require a new feature flag).
110 * Periodically during scanning (see zfs_scan_checkpoint_intval), the scan
111 * will stop scanning metadata (in logical order) and wait for all outstanding
112 * sorted I/O to complete. Once this is done, we write out a checkpoint
113 * 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.
118 typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,
119 const zbookmark_phys_t *);
121 static scan_cb_t dsl_scan_scrub_cb;
123 static int scan_ds_queue_compare(const void *a, const void *b);
124 static int scan_prefetch_queue_compare(const void *a, const void *b);
125 static void scan_ds_queue_clear(dsl_scan_t *scn);
126 static void scan_ds_prefetch_queue_clear(dsl_scan_t *scn);
127 static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj,
128 uint64_t *txg);
129 static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg);
130 static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj);
131 static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx);
132 static uint64_t dsl_scan_count_data_disks(spa_t *spa);
133 static void read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb);
135 extern uint_t zfs_vdev_async_write_active_min_dirty_percent;
136 static int zfs_scan_blkstats = 0;
139 * 'zpool status' uses bytes processed per pass to report throughput and
140 * estimate time remaining. We define a pass to start when the scanning
141 * phase completes for a sequential resilver. Optionally, this value
142 * may be used to reset the pass statistics every N txgs to provide an
143 * estimated completion time based on currently observed performance.
145 static uint_t zfs_scan_report_txgs = 0;
148 * By default zfs will check to ensure it is not over the hard memory
149 * limit before each txg. If finer-grained control of this is needed
150 * this value can be set to 1 to enable checking before scanning each
151 * block.
153 static int zfs_scan_strict_mem_lim = B_FALSE;
156 * Maximum number of parallelly executed bytes per leaf vdev. We attempt
157 * to strike a balance here between keeping the vdev queues full of I/Os
158 * 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 not
160 * overload the drives with I/O, since that is protected by
161 * zfs_vdev_scrub_max_active.
163 static uint64_t zfs_scan_vdev_limit = 16 << 20;
165 static uint_t zfs_scan_issue_strategy = 0;
167 /* don't queue & sort zios, go direct */
168 static int zfs_scan_legacy = B_FALSE;
169 static uint64_t zfs_scan_max_ext_gap = 2 << 20; /* in bytes */
172 * fill_weight is non-tunable at runtime, so we copy it at module init from
173 * zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would
174 * break queue sorting.
176 static uint_t zfs_scan_fill_weight = 3;
177 static uint64_t fill_weight;
179 /* See dsl_scan_should_clear() for details on the memory limit tunables */
180 static const uint64_t zfs_scan_mem_lim_min = 16 << 20; /* bytes */
181 static const uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */
184 /* fraction of physmem */
185 static uint_t zfs_scan_mem_lim_fact = 20;
187 /* fraction of mem lim above */
188 static uint_t zfs_scan_mem_lim_soft_fact = 20;
190 /* minimum milliseconds to scrub per txg */
191 static uint_t zfs_scrub_min_time_ms = 1000;
193 /* minimum milliseconds to obsolete per txg */
194 static uint_t zfs_obsolete_min_time_ms = 500;
196 /* minimum milliseconds to free per txg */
197 static uint_t zfs_free_min_time_ms = 1000;
199 /* minimum milliseconds to resilver per txg */
200 static uint_t zfs_resilver_min_time_ms = 3000;
202 static uint_t zfs_scan_checkpoint_intval = 7200; /* in seconds */
203 int zfs_scan_suspend_progress = 0; /* set to prevent scans from progressing */
204 static int zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */
205 static int zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */
206 static const ddt_class_t zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;
207 /* max number of blocks to free in a single TXG */
208 static uint64_t zfs_async_block_max_blocks = UINT64_MAX;
209 /* max number of dedup blocks to free in a single TXG */
210 static uint64_t zfs_max_async_dedup_frees = 100000;
212 /* set to disable resilver deferring */
213 static int zfs_resilver_disable_defer = B_FALSE;
215 /* Don't defer a resilver if the one in progress only got this far: */
216 static uint_t zfs_resilver_defer_percent = 10;
219 * We wait a few txgs after importing a pool to begin scanning so that
220 * the import / mounting code isn't held up by scrub / resilver IO.
221 * Unfortunately, it is a bit difficult to determine exactly how long
222 * this will take since userspace will trigger fs mounts asynchronously
223 * and the kernel will create zvol minors asynchronously. As a result,
224 * the value provided here is a bit arbitrary, but represents a
225 * reasonable estimate of how many txgs it will take to finish fully
226 * importing a pool
228 #define SCAN_IMPORT_WAIT_TXGS 5
230 #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)
234 #define DSL_SCAN_IS_SCRUB(scn) \
235 ((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB)
238 * Enable/disable the processing of the free_bpobj object.
240 static int zfs_free_bpobj_enabled = 1;
242 /* Error blocks to be scrubbed in one txg. */
243 static uint_t zfs_scrub_error_blocks_per_txg = 1 << 12;
245 /* the order has to match pool_scan_type */
246 static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {
247 NULL,
248 dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */
249 dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */
252 /* In core node for the scn->scn_queue. Represents a dataset to be scanned */
253 typedef struct {
254 uint64_t sds_dsobj;
255 uint64_t sds_txg;
256 avl_node_t sds_node;
257 } scan_ds_t;
260 * This controls what conditions are placed on dsl_scan_sync_state():
261 * SYNC_OPTIONAL) write out scn_phys iff scn_queues_pending == 0
262 * SYNC_MANDATORY) write out scn_phys always. scn_queues_pending must be 0.
263 * SYNC_CACHED) if scn_queues_pending == 0, write out scn_phys. Otherwise
264 * write out the scn_phys_cached version.
265 * See dsl_scan_sync_state for details.
267 typedef enum {
268 SYNC_OPTIONAL,
269 SYNC_MANDATORY,
270 SYNC_CACHED
271 } state_sync_type_t;
274 * This struct represents the minimum information needed to reconstruct a
275 * zio for sequential scanning. This is useful because many of these will
276 * accumulate in the sequential IO queues before being issued, so saving
277 * memory matters here.
279 typedef struct scan_io {
280 /* fields from blkptr_t */
281 uint64_t sio_blk_prop;
282 uint64_t sio_phys_birth;
283 uint64_t sio_birth;
284 zio_cksum_t sio_cksum;
285 uint32_t sio_nr_dvas;
287 /* fields from zio_t */
288 uint32_t sio_flags;
289 zbookmark_phys_t sio_zb;
291 /* members for queue sorting */
292 union {
293 avl_node_t sio_addr_node; /* link into issuing queue */
294 list_node_t sio_list_node; /* link for issuing to disk */
295 } sio_nodes;
298 * There may be up to SPA_DVAS_PER_BP DVAs here from the bp,
299 * depending on how many were in the original bp. Only the
300 * first DVA is really used for sorting and issuing purposes.
301 * The other DVAs (if provided) simply exist so that the zio
302 * layer can find additional copies to repair from in the
303 * event of an error. This array must go at the end of the
304 * struct to allow this for the variable number of elements.
306 dva_t sio_dva[];
307 } scan_io_t;
309 #define SIO_SET_OFFSET(sio, x) DVA_SET_OFFSET(&(sio)->sio_dva[0], x)
310 #define SIO_SET_ASIZE(sio, x) DVA_SET_ASIZE(&(sio)->sio_dva[0], x)
311 #define SIO_GET_OFFSET(sio) DVA_GET_OFFSET(&(sio)->sio_dva[0])
312 #define SIO_GET_ASIZE(sio) DVA_GET_ASIZE(&(sio)->sio_dva[0])
313 #define SIO_GET_END_OFFSET(sio) \
314 (SIO_GET_OFFSET(sio) + SIO_GET_ASIZE(sio))
315 #define SIO_GET_MUSED(sio) \
316 (sizeof (scan_io_t) + ((sio)->sio_nr_dvas * sizeof (dva_t)))
318 struct dsl_scan_io_queue {
319 dsl_scan_t *q_scn; /* associated dsl_scan_t */
320 vdev_t *q_vd; /* top-level vdev that this queue represents */
321 zio_t *q_zio; /* scn_zio_root child for waiting on IO */
323 /* trees used for sorting I/Os and extents of I/Os */
324 range_tree_t *q_exts_by_addr;
325 zfs_btree_t q_exts_by_size;
326 avl_tree_t q_sios_by_addr;
327 uint64_t q_sio_memused;
328 uint64_t q_last_ext_addr;
330 /* members for zio rate limiting */
331 uint64_t q_maxinflight_bytes;
332 uint64_t q_inflight_bytes;
333 kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */
335 /* per txg statistics */
336 uint64_t q_total_seg_size_this_txg;
337 uint64_t q_segs_this_txg;
338 uint64_t q_total_zio_size_this_txg;
339 uint64_t q_zios_this_txg;
342 /* private data for dsl_scan_prefetch_cb() */
343 typedef struct scan_prefetch_ctx {
344 zfs_refcount_t spc_refcnt; /* refcount for memory management */
345 dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */
346 boolean_t spc_root; /* is this prefetch for an objset? */
347 uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */
348 uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */
349 } scan_prefetch_ctx_t;
351 /* private data for dsl_scan_prefetch() */
352 typedef struct scan_prefetch_issue_ctx {
353 avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */
354 scan_prefetch_ctx_t *spic_spc; /* spc for the callback */
355 blkptr_t spic_bp; /* bp to prefetch */
356 zbookmark_phys_t spic_zb; /* bookmark to prefetch */
357 } scan_prefetch_issue_ctx_t;
359 static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
360 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);
361 static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,
362 scan_io_t *sio);
364 static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);
365 static void scan_io_queues_destroy(dsl_scan_t *scn);
367 static kmem_cache_t *sio_cache[SPA_DVAS_PER_BP];
369 /* sio->sio_nr_dvas must be set so we know which cache to free from */
370 static void
371 sio_free(scan_io_t *sio)
373 ASSERT3U(sio->sio_nr_dvas, >, 0);
374 ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);
376 kmem_cache_free(sio_cache[sio->sio_nr_dvas - 1], sio);
379 /* It is up to the caller to set sio->sio_nr_dvas for freeing */
380 static scan_io_t *
381 sio_alloc(unsigned short nr_dvas)
383 ASSERT3U(nr_dvas, >, 0);
384 ASSERT3U(nr_dvas, <=, SPA_DVAS_PER_BP);
386 return (kmem_cache_alloc(sio_cache[nr_dvas - 1], KM_SLEEP));
389 void
390 scan_init(void)
393 * This is used in ext_size_compare() to weight segments
394 * based on how sparse they are. This cannot be changed
395 * mid-scan and the tree comparison functions don't currently
396 * have a mechanism for passing additional context to the
397 * compare functions. Thus we store this value globally and
398 * we only allow it to be set at module initialization time
400 fill_weight = zfs_scan_fill_weight;
402 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
403 char name[36];
405 (void) snprintf(name, sizeof (name), "sio_cache_%d", i);
406 sio_cache[i] = kmem_cache_create(name,
407 (sizeof (scan_io_t) + ((i + 1) * sizeof (dva_t))),
408 0, NULL, NULL, NULL, NULL, NULL, 0);
412 void
413 scan_fini(void)
415 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
416 kmem_cache_destroy(sio_cache[i]);
420 static inline boolean_t
421 dsl_scan_is_running(const dsl_scan_t *scn)
423 return (scn->scn_phys.scn_state == DSS_SCANNING);
426 boolean_t
427 dsl_scan_resilvering(dsl_pool_t *dp)
429 return (dsl_scan_is_running(dp->dp_scan) &&
430 dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
433 static inline void
434 sio2bp(const scan_io_t *sio, blkptr_t *bp)
436 memset(bp, 0, sizeof (*bp));
437 bp->blk_prop = sio->sio_blk_prop;
438 BP_SET_PHYSICAL_BIRTH(bp, sio->sio_phys_birth);
439 BP_SET_LOGICAL_BIRTH(bp, sio->sio_birth);
440 bp->blk_fill = 1; /* we always only work with data pointers */
441 bp->blk_cksum = sio->sio_cksum;
443 ASSERT3U(sio->sio_nr_dvas, >, 0);
444 ASSERT3U(sio->sio_nr_dvas, <=, SPA_DVAS_PER_BP);
446 memcpy(bp->blk_dva, sio->sio_dva, sio->sio_nr_dvas * sizeof (dva_t));
449 static inline void
450 bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)
452 sio->sio_blk_prop = bp->blk_prop;
453 sio->sio_phys_birth = BP_GET_PHYSICAL_BIRTH(bp);
454 sio->sio_birth = BP_GET_LOGICAL_BIRTH(bp);
455 sio->sio_cksum = bp->blk_cksum;
456 sio->sio_nr_dvas = BP_GET_NDVAS(bp);
459 * Copy the DVAs to the sio. We need all copies of the block so
460 * that the self healing code can use the alternate copies if the
461 * first is corrupted. We want the DVA at index dva_i to be first
462 * in the sio since this is the primary one that we want to issue.
464 for (int i = 0, j = dva_i; i < sio->sio_nr_dvas; i++, j++) {
465 sio->sio_dva[i] = bp->blk_dva[j % sio->sio_nr_dvas];
470 dsl_scan_init(dsl_pool_t *dp, uint64_t txg)
472 int err;
473 dsl_scan_t *scn;
474 spa_t *spa = dp->dp_spa;
475 uint64_t f;
477 scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);
478 scn->scn_dp = dp;
481 * It's possible that we're resuming a scan after a reboot so
482 * make sure that the scan_async_destroying flag is initialized
483 * appropriately.
485 ASSERT(!scn->scn_async_destroying);
486 scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,
487 SPA_FEATURE_ASYNC_DESTROY);
490 * Calculate the max number of in-flight bytes for pool-wide
491 * scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).
492 * Limits for the issuing phase are done per top-level vdev and
493 * are handled separately.
495 scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,
496 zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));
498 avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),
499 offsetof(scan_ds_t, sds_node));
500 mutex_init(&scn->scn_queue_lock, NULL, MUTEX_DEFAULT, NULL);
501 avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,
502 sizeof (scan_prefetch_issue_ctx_t),
503 offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));
505 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
506 "scrub_func", sizeof (uint64_t), 1, &f);
507 if (err == 0) {
509 * There was an old-style scrub in progress. Restart a
510 * new-style scrub from the beginning.
512 scn->scn_restart_txg = txg;
513 zfs_dbgmsg("old-style scrub was in progress for %s; "
514 "restarting new-style scrub in txg %llu",
515 spa->spa_name,
516 (longlong_t)scn->scn_restart_txg);
519 * Load the queue obj from the old location so that it
520 * can be freed by dsl_scan_done().
522 (void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
523 "scrub_queue", sizeof (uint64_t), 1,
524 &scn->scn_phys.scn_queue_obj);
525 } else {
526 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
527 DMU_POOL_ERRORSCRUB, sizeof (uint64_t),
528 ERRORSCRUB_PHYS_NUMINTS, &scn->errorscrub_phys);
530 if (err != 0 && err != ENOENT)
531 return (err);
533 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
534 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
535 &scn->scn_phys);
538 * Detect if the pool contains the signature of #2094. If it
539 * does properly update the scn->scn_phys structure and notify
540 * the administrator by setting an errata for the pool.
542 if (err == EOVERFLOW) {
543 uint64_t zaptmp[SCAN_PHYS_NUMINTS + 1];
544 VERIFY3S(SCAN_PHYS_NUMINTS, ==, 24);
545 VERIFY3S(offsetof(dsl_scan_phys_t, scn_flags), ==,
546 (23 * sizeof (uint64_t)));
548 err = zap_lookup(dp->dp_meta_objset,
549 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SCAN,
550 sizeof (uint64_t), SCAN_PHYS_NUMINTS + 1, &zaptmp);
551 if (err == 0) {
552 uint64_t overflow = zaptmp[SCAN_PHYS_NUMINTS];
554 if (overflow & ~DSL_SCAN_FLAGS_MASK ||
555 scn->scn_async_destroying) {
556 spa->spa_errata =
557 ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY;
558 return (EOVERFLOW);
561 memcpy(&scn->scn_phys, zaptmp,
562 SCAN_PHYS_NUMINTS * sizeof (uint64_t));
563 scn->scn_phys.scn_flags = overflow;
565 /* Required scrub already in progress. */
566 if (scn->scn_phys.scn_state == DSS_FINISHED ||
567 scn->scn_phys.scn_state == DSS_CANCELED)
568 spa->spa_errata =
569 ZPOOL_ERRATA_ZOL_2094_SCRUB;
573 if (err == ENOENT)
574 return (0);
575 else if (err)
576 return (err);
579 * We might be restarting after a reboot, so jump the issued
580 * counter to how far we've scanned. We know we're consistent
581 * up to here.
583 scn->scn_issued_before_pass = scn->scn_phys.scn_examined -
584 scn->scn_phys.scn_skipped;
586 if (dsl_scan_is_running(scn) &&
587 spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {
589 * A new-type scrub was in progress on an old
590 * pool, and the pool was accessed by old
591 * software. Restart from the beginning, since
592 * the old software may have changed the pool in
593 * the meantime.
595 scn->scn_restart_txg = txg;
596 zfs_dbgmsg("new-style scrub for %s was modified "
597 "by old software; restarting in txg %llu",
598 spa->spa_name,
599 (longlong_t)scn->scn_restart_txg);
600 } else if (dsl_scan_resilvering(dp)) {
602 * If a resilver is in progress and there are already
603 * errors, restart it instead of finishing this scan and
604 * then restarting it. If there haven't been any errors
605 * then remember that the incore DTL is valid.
607 if (scn->scn_phys.scn_errors > 0) {
608 scn->scn_restart_txg = txg;
609 zfs_dbgmsg("resilver can't excise DTL_MISSING "
610 "when finished; restarting on %s in txg "
611 "%llu",
612 spa->spa_name,
613 (u_longlong_t)scn->scn_restart_txg);
614 } else {
615 /* it's safe to excise DTL when finished */
616 spa->spa_scrub_started = B_TRUE;
621 memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));
623 /* reload the queue into the in-core state */
624 if (scn->scn_phys.scn_queue_obj != 0) {
625 zap_cursor_t zc;
626 zap_attribute_t *za = zap_attribute_alloc();
628 for (zap_cursor_init(&zc, dp->dp_meta_objset,
629 scn->scn_phys.scn_queue_obj);
630 zap_cursor_retrieve(&zc, za) == 0;
631 (void) zap_cursor_advance(&zc)) {
632 scan_ds_queue_insert(scn,
633 zfs_strtonum(za->za_name, NULL),
634 za->za_first_integer);
636 zap_cursor_fini(&zc);
637 zap_attribute_free(za);
640 ddt_walk_init(spa, scn->scn_phys.scn_max_txg);
642 spa_scan_stat_init(spa);
643 vdev_scan_stat_init(spa->spa_root_vdev);
645 return (0);
648 void
649 dsl_scan_fini(dsl_pool_t *dp)
651 if (dp->dp_scan != NULL) {
652 dsl_scan_t *scn = dp->dp_scan;
654 if (scn->scn_taskq != NULL)
655 taskq_destroy(scn->scn_taskq);
657 scan_ds_queue_clear(scn);
658 avl_destroy(&scn->scn_queue);
659 mutex_destroy(&scn->scn_queue_lock);
660 scan_ds_prefetch_queue_clear(scn);
661 avl_destroy(&scn->scn_prefetch_queue);
663 kmem_free(dp->dp_scan, sizeof (dsl_scan_t));
664 dp->dp_scan = NULL;
668 static boolean_t
669 dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)
671 return (scn->scn_restart_txg != 0 &&
672 scn->scn_restart_txg <= tx->tx_txg);
675 boolean_t
676 dsl_scan_resilver_scheduled(dsl_pool_t *dp)
678 return ((dp->dp_scan && dp->dp_scan->scn_restart_txg != 0) ||
679 (spa_async_tasks(dp->dp_spa) & SPA_ASYNC_RESILVER));
682 boolean_t
683 dsl_scan_scrubbing(const dsl_pool_t *dp)
685 dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;
687 return (scn_phys->scn_state == DSS_SCANNING &&
688 scn_phys->scn_func == POOL_SCAN_SCRUB);
691 boolean_t
692 dsl_errorscrubbing(const dsl_pool_t *dp)
694 dsl_errorscrub_phys_t *errorscrub_phys = &dp->dp_scan->errorscrub_phys;
696 return (errorscrub_phys->dep_state == DSS_ERRORSCRUBBING &&
697 errorscrub_phys->dep_func == POOL_SCAN_ERRORSCRUB);
700 boolean_t
701 dsl_errorscrub_is_paused(const dsl_scan_t *scn)
703 return (dsl_errorscrubbing(scn->scn_dp) &&
704 scn->errorscrub_phys.dep_paused_flags);
707 boolean_t
708 dsl_scan_is_paused_scrub(const dsl_scan_t *scn)
710 return (dsl_scan_scrubbing(scn->scn_dp) &&
711 scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);
714 static void
715 dsl_errorscrub_sync_state(dsl_scan_t *scn, dmu_tx_t *tx)
717 scn->errorscrub_phys.dep_cursor =
718 zap_cursor_serialize(&scn->errorscrub_cursor);
720 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
721 DMU_POOL_DIRECTORY_OBJECT,
722 DMU_POOL_ERRORSCRUB, sizeof (uint64_t), ERRORSCRUB_PHYS_NUMINTS,
723 &scn->errorscrub_phys, tx));
726 static void
727 dsl_errorscrub_setup_sync(void *arg, dmu_tx_t *tx)
729 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
730 pool_scan_func_t *funcp = arg;
731 dsl_pool_t *dp = scn->scn_dp;
732 spa_t *spa = dp->dp_spa;
734 ASSERT(!dsl_scan_is_running(scn));
735 ASSERT(!dsl_errorscrubbing(scn->scn_dp));
736 ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);
738 memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));
739 scn->errorscrub_phys.dep_func = *funcp;
740 scn->errorscrub_phys.dep_state = DSS_ERRORSCRUBBING;
741 scn->errorscrub_phys.dep_start_time = gethrestime_sec();
742 scn->errorscrub_phys.dep_to_examine = spa_get_last_errlog_size(spa);
743 scn->errorscrub_phys.dep_examined = 0;
744 scn->errorscrub_phys.dep_errors = 0;
745 scn->errorscrub_phys.dep_cursor = 0;
746 zap_cursor_init_serialized(&scn->errorscrub_cursor,
747 spa->spa_meta_objset, spa->spa_errlog_last,
748 scn->errorscrub_phys.dep_cursor);
750 vdev_config_dirty(spa->spa_root_vdev);
751 spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_START);
753 dsl_errorscrub_sync_state(scn, tx);
755 spa_history_log_internal(spa, "error scrub setup", tx,
756 "func=%u mintxg=%u maxtxg=%llu",
757 *funcp, 0, (u_longlong_t)tx->tx_txg);
760 static int
761 dsl_errorscrub_setup_check(void *arg, dmu_tx_t *tx)
763 (void) arg;
764 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
766 if (dsl_scan_is_running(scn) || (dsl_errorscrubbing(scn->scn_dp))) {
767 return (SET_ERROR(EBUSY));
770 if (spa_get_last_errlog_size(scn->scn_dp->dp_spa) == 0) {
771 return (ECANCELED);
773 return (0);
777 * Writes out a persistent dsl_scan_phys_t record to the pool directory.
778 * Because we can be running in the block sorting algorithm, we do not always
779 * want to write out the record, only when it is "safe" to do so. This safety
780 * condition is achieved by making sure that the sorting queues are empty
781 * (scn_queues_pending == 0). When this condition is not true, the sync'd state
782 * is inconsistent with how much actual scanning progress has been made. The
783 * kind of sync to be performed is specified by the sync_type argument. If the
784 * sync is optional, we only sync if the queues are empty. If the sync is
785 * mandatory, we do a hard ASSERT to make sure that the queues are empty. The
786 * third possible state is a "cached" sync. This is done in response to:
787 * 1) The dataset that was in the last sync'd dsl_scan_phys_t having been
788 * destroyed, so we wouldn't be able to restart scanning from it.
789 * 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been
790 * superseded by a newer snapshot.
791 * 3) The dataset that was in the last sync'd dsl_scan_phys_t having been
792 * swapped with its clone.
793 * In all cases, a cached sync simply rewrites the last record we've written,
794 * just slightly modified. For the modifications that are performed to the
795 * last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,
796 * dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.
798 static void
799 dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)
801 int i;
802 spa_t *spa = scn->scn_dp->dp_spa;
804 ASSERT(sync_type != SYNC_MANDATORY || scn->scn_queues_pending == 0);
805 if (scn->scn_queues_pending == 0) {
806 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
807 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
808 dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;
810 if (q == NULL)
811 continue;
813 mutex_enter(&vd->vdev_scan_io_queue_lock);
814 ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);
815 ASSERT3P(zfs_btree_first(&q->q_exts_by_size, NULL), ==,
816 NULL);
817 ASSERT3P(range_tree_first(q->q_exts_by_addr), ==, NULL);
818 mutex_exit(&vd->vdev_scan_io_queue_lock);
821 if (scn->scn_phys.scn_queue_obj != 0)
822 scan_ds_queue_sync(scn, tx);
823 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
824 DMU_POOL_DIRECTORY_OBJECT,
825 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
826 &scn->scn_phys, tx));
827 memcpy(&scn->scn_phys_cached, &scn->scn_phys,
828 sizeof (scn->scn_phys));
830 if (scn->scn_checkpointing)
831 zfs_dbgmsg("finish scan checkpoint for %s",
832 spa->spa_name);
834 scn->scn_checkpointing = B_FALSE;
835 scn->scn_last_checkpoint = ddi_get_lbolt();
836 } else if (sync_type == SYNC_CACHED) {
837 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
838 DMU_POOL_DIRECTORY_OBJECT,
839 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
840 &scn->scn_phys_cached, tx));
845 dsl_scan_setup_check(void *arg, dmu_tx_t *tx)
847 (void) arg;
848 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
849 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
851 if (dsl_scan_is_running(scn) || vdev_rebuild_active(rvd) ||
852 dsl_errorscrubbing(scn->scn_dp))
853 return (SET_ERROR(EBUSY));
855 return (0);
858 void
859 dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)
861 setup_sync_arg_t *setup_sync_arg = (setup_sync_arg_t *)arg;
862 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
863 dmu_object_type_t ot = 0;
864 dsl_pool_t *dp = scn->scn_dp;
865 spa_t *spa = dp->dp_spa;
867 ASSERT(!dsl_scan_is_running(scn));
868 ASSERT3U(setup_sync_arg->func, >, POOL_SCAN_NONE);
869 ASSERT3U(setup_sync_arg->func, <, POOL_SCAN_FUNCS);
870 memset(&scn->scn_phys, 0, sizeof (scn->scn_phys));
873 * If we are starting a fresh scrub, we erase the error scrub
874 * information from disk.
876 memset(&scn->errorscrub_phys, 0, sizeof (scn->errorscrub_phys));
877 dsl_errorscrub_sync_state(scn, tx);
879 scn->scn_phys.scn_func = setup_sync_arg->func;
880 scn->scn_phys.scn_state = DSS_SCANNING;
881 scn->scn_phys.scn_min_txg = setup_sync_arg->txgstart;
882 if (setup_sync_arg->txgend == 0) {
883 scn->scn_phys.scn_max_txg = tx->tx_txg;
884 } else {
885 scn->scn_phys.scn_max_txg = setup_sync_arg->txgend;
887 scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */
888 scn->scn_phys.scn_start_time = gethrestime_sec();
889 scn->scn_phys.scn_errors = 0;
890 scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;
891 scn->scn_issued_before_pass = 0;
892 scn->scn_restart_txg = 0;
893 scn->scn_done_txg = 0;
894 scn->scn_last_checkpoint = 0;
895 scn->scn_checkpointing = B_FALSE;
896 spa_scan_stat_init(spa);
897 vdev_scan_stat_init(spa->spa_root_vdev);
899 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
900 scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;
902 /* rewrite all disk labels */
903 vdev_config_dirty(spa->spa_root_vdev);
905 if (vdev_resilver_needed(spa->spa_root_vdev,
906 &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {
907 nvlist_t *aux = fnvlist_alloc();
908 fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,
909 "healing");
910 spa_event_notify(spa, NULL, aux,
911 ESC_ZFS_RESILVER_START);
912 nvlist_free(aux);
913 } else {
914 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);
917 spa->spa_scrub_started = B_TRUE;
919 * If this is an incremental scrub, limit the DDT scrub phase
920 * to just the auto-ditto class (for correctness); the rest
921 * of the scrub should go faster using top-down pruning.
923 if (scn->scn_phys.scn_min_txg > TXG_INITIAL)
924 scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;
927 * When starting a resilver clear any existing rebuild state.
928 * This is required to prevent stale rebuild status from
929 * being reported when a rebuild is run, then a resilver and
930 * finally a scrub. In which case only the scrub status
931 * should be reported by 'zpool status'.
933 if (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) {
934 vdev_t *rvd = spa->spa_root_vdev;
935 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
936 vdev_t *vd = rvd->vdev_child[i];
937 vdev_rebuild_clear_sync(
938 (void *)(uintptr_t)vd->vdev_id, tx);
943 /* back to the generic stuff */
945 if (zfs_scan_blkstats) {
946 if (dp->dp_blkstats == NULL) {
947 dp->dp_blkstats =
948 vmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);
950 memset(&dp->dp_blkstats->zab_type, 0,
951 sizeof (dp->dp_blkstats->zab_type));
952 } else {
953 if (dp->dp_blkstats) {
954 vmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
955 dp->dp_blkstats = NULL;
959 if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)
960 ot = DMU_OT_ZAP_OTHER;
962 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,
963 ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);
965 memcpy(&scn->scn_phys_cached, &scn->scn_phys, sizeof (scn->scn_phys));
967 ddt_walk_init(spa, scn->scn_phys.scn_max_txg);
969 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
971 spa_history_log_internal(spa, "scan setup", tx,
972 "func=%u mintxg=%llu maxtxg=%llu",
973 setup_sync_arg->func, (u_longlong_t)scn->scn_phys.scn_min_txg,
974 (u_longlong_t)scn->scn_phys.scn_max_txg);
978 * Called by ZFS_IOC_POOL_SCRUB and ZFS_IOC_POOL_SCAN ioctl to start a scrub,
979 * error scrub or resilver. Can also be called to resume a paused scrub or
980 * error scrub.
983 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func, uint64_t txgstart,
984 uint64_t txgend)
986 spa_t *spa = dp->dp_spa;
987 dsl_scan_t *scn = dp->dp_scan;
988 setup_sync_arg_t setup_sync_arg;
990 if (func != POOL_SCAN_SCRUB && (txgstart != 0 || txgend != 0)) {
991 return (EINVAL);
995 * Purge all vdev caches and probe all devices. We do this here
996 * rather than in sync context because this requires a writer lock
997 * on the spa_config lock, which we can't do from sync context. The
998 * spa_scrub_reopen flag indicates that vdev_open() should not
999 * attempt to start another scrub.
1001 spa_vdev_state_enter(spa, SCL_NONE);
1002 spa->spa_scrub_reopen = B_TRUE;
1003 vdev_reopen(spa->spa_root_vdev);
1004 spa->spa_scrub_reopen = B_FALSE;
1005 (void) spa_vdev_state_exit(spa, NULL, 0);
1007 if (func == POOL_SCAN_RESILVER) {
1008 dsl_scan_restart_resilver(spa->spa_dsl_pool, 0);
1009 return (0);
1012 if (func == POOL_SCAN_ERRORSCRUB) {
1013 if (dsl_errorscrub_is_paused(dp->dp_scan)) {
1015 * got error scrub start cmd, resume paused error scrub.
1017 int err = dsl_scrub_set_pause_resume(scn->scn_dp,
1018 POOL_SCRUB_NORMAL);
1019 if (err == 0) {
1020 spa_event_notify(spa, NULL, NULL,
1021 ESC_ZFS_ERRORSCRUB_RESUME);
1022 return (ECANCELED);
1024 return (SET_ERROR(err));
1027 return (dsl_sync_task(spa_name(dp->dp_spa),
1028 dsl_errorscrub_setup_check, dsl_errorscrub_setup_sync,
1029 &func, 0, ZFS_SPACE_CHECK_RESERVED));
1032 if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {
1033 /* got scrub start cmd, resume paused scrub */
1034 int err = dsl_scrub_set_pause_resume(scn->scn_dp,
1035 POOL_SCRUB_NORMAL);
1036 if (err == 0) {
1037 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);
1038 return (SET_ERROR(ECANCELED));
1040 return (SET_ERROR(err));
1043 setup_sync_arg.func = func;
1044 setup_sync_arg.txgstart = txgstart;
1045 setup_sync_arg.txgend = txgend;
1047 return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
1048 dsl_scan_setup_sync, &setup_sync_arg, 0,
1049 ZFS_SPACE_CHECK_EXTRA_RESERVED));
1052 static void
1053 dsl_errorscrub_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
1055 dsl_pool_t *dp = scn->scn_dp;
1056 spa_t *spa = dp->dp_spa;
1058 if (complete) {
1059 spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_FINISH);
1060 spa_history_log_internal(spa, "error scrub done", tx,
1061 "errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));
1062 } else {
1063 spa_history_log_internal(spa, "error scrub canceled", tx,
1064 "errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));
1067 scn->errorscrub_phys.dep_state = complete ? DSS_FINISHED : DSS_CANCELED;
1068 spa->spa_scrub_active = B_FALSE;
1069 spa_errlog_rotate(spa);
1070 scn->errorscrub_phys.dep_end_time = gethrestime_sec();
1071 zap_cursor_fini(&scn->errorscrub_cursor);
1073 if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)
1074 spa->spa_errata = 0;
1076 ASSERT(!dsl_errorscrubbing(scn->scn_dp));
1079 static void
1080 dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
1082 static const char *old_names[] = {
1083 "scrub_bookmark",
1084 "scrub_ddt_bookmark",
1085 "scrub_ddt_class_max",
1086 "scrub_queue",
1087 "scrub_min_txg",
1088 "scrub_max_txg",
1089 "scrub_func",
1090 "scrub_errors",
1091 NULL
1094 dsl_pool_t *dp = scn->scn_dp;
1095 spa_t *spa = dp->dp_spa;
1096 int i;
1098 /* Remove any remnants of an old-style scrub. */
1099 for (i = 0; old_names[i]; i++) {
1100 (void) zap_remove(dp->dp_meta_objset,
1101 DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);
1104 if (scn->scn_phys.scn_queue_obj != 0) {
1105 VERIFY0(dmu_object_free(dp->dp_meta_objset,
1106 scn->scn_phys.scn_queue_obj, tx));
1107 scn->scn_phys.scn_queue_obj = 0;
1109 scan_ds_queue_clear(scn);
1110 scan_ds_prefetch_queue_clear(scn);
1112 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
1115 * If we were "restarted" from a stopped state, don't bother
1116 * with anything else.
1118 if (!dsl_scan_is_running(scn)) {
1119 ASSERT(!scn->scn_is_sorted);
1120 return;
1123 if (scn->scn_is_sorted) {
1124 scan_io_queues_destroy(scn);
1125 scn->scn_is_sorted = B_FALSE;
1127 if (scn->scn_taskq != NULL) {
1128 taskq_destroy(scn->scn_taskq);
1129 scn->scn_taskq = NULL;
1133 scn->scn_phys.scn_state = complete ? DSS_FINISHED : DSS_CANCELED;
1135 spa_notify_waiters(spa);
1137 if (dsl_scan_restarting(scn, tx)) {
1138 spa_history_log_internal(spa, "scan aborted, restarting", tx,
1139 "errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));
1140 } else if (!complete) {
1141 spa_history_log_internal(spa, "scan cancelled", tx,
1142 "errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));
1143 } else {
1144 spa_history_log_internal(spa, "scan done", tx,
1145 "errors=%llu", (u_longlong_t)spa_approx_errlog_size(spa));
1146 if (DSL_SCAN_IS_SCRUB(scn)) {
1147 VERIFY0(zap_update(dp->dp_meta_objset,
1148 DMU_POOL_DIRECTORY_OBJECT,
1149 DMU_POOL_LAST_SCRUBBED_TXG,
1150 sizeof (uint64_t), 1,
1151 &scn->scn_phys.scn_max_txg, tx));
1152 spa->spa_scrubbed_last_txg = scn->scn_phys.scn_max_txg;
1156 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
1157 spa->spa_scrub_active = B_FALSE;
1160 * If the scrub/resilver completed, update all DTLs to
1161 * reflect this. Whether it succeeded or not, vacate
1162 * all temporary scrub DTLs.
1164 * As the scrub does not currently support traversing
1165 * data that have been freed but are part of a checkpoint,
1166 * we don't mark the scrub as done in the DTLs as faults
1167 * may still exist in those vdevs.
1169 if (complete &&
1170 !spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
1171 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
1172 scn->scn_phys.scn_max_txg, B_TRUE, B_FALSE);
1174 if (scn->scn_phys.scn_min_txg) {
1175 nvlist_t *aux = fnvlist_alloc();
1176 fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE,
1177 "healing");
1178 spa_event_notify(spa, NULL, aux,
1179 ESC_ZFS_RESILVER_FINISH);
1180 nvlist_free(aux);
1181 } else {
1182 spa_event_notify(spa, NULL, NULL,
1183 ESC_ZFS_SCRUB_FINISH);
1185 } else {
1186 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
1187 0, B_TRUE, B_FALSE);
1189 spa_errlog_rotate(spa);
1192 * Don't clear flag until after vdev_dtl_reassess to ensure that
1193 * DTL_MISSING will get updated when possible.
1195 spa->spa_scrub_started = B_FALSE;
1198 * We may have finished replacing a device.
1199 * Let the async thread assess this and handle the detach.
1201 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
1204 * Clear any resilver_deferred flags in the config.
1205 * If there are drives that need resilvering, kick
1206 * off an asynchronous request to start resilver.
1207 * vdev_clear_resilver_deferred() may update the config
1208 * before the resilver can restart. In the event of
1209 * a crash during this period, the spa loading code
1210 * will find the drives that need to be resilvered
1211 * and start the resilver then.
1213 if (spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER) &&
1214 vdev_clear_resilver_deferred(spa->spa_root_vdev, tx)) {
1215 spa_history_log_internal(spa,
1216 "starting deferred resilver", tx, "errors=%llu",
1217 (u_longlong_t)spa_approx_errlog_size(spa));
1218 spa_async_request(spa, SPA_ASYNC_RESILVER);
1221 /* Clear recent error events (i.e. duplicate events tracking) */
1222 if (complete)
1223 zfs_ereport_clear(spa, NULL);
1226 scn->scn_phys.scn_end_time = gethrestime_sec();
1228 if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)
1229 spa->spa_errata = 0;
1231 ASSERT(!dsl_scan_is_running(scn));
1234 static int
1235 dsl_errorscrub_pause_resume_check(void *arg, dmu_tx_t *tx)
1237 pool_scrub_cmd_t *cmd = arg;
1238 dsl_pool_t *dp = dmu_tx_pool(tx);
1239 dsl_scan_t *scn = dp->dp_scan;
1241 if (*cmd == POOL_SCRUB_PAUSE) {
1243 * can't pause a error scrub when there is no in-progress
1244 * error scrub.
1246 if (!dsl_errorscrubbing(dp))
1247 return (SET_ERROR(ENOENT));
1249 /* can't pause a paused error scrub */
1250 if (dsl_errorscrub_is_paused(scn))
1251 return (SET_ERROR(EBUSY));
1252 } else if (*cmd != POOL_SCRUB_NORMAL) {
1253 return (SET_ERROR(ENOTSUP));
1256 return (0);
1259 static void
1260 dsl_errorscrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
1262 pool_scrub_cmd_t *cmd = arg;
1263 dsl_pool_t *dp = dmu_tx_pool(tx);
1264 spa_t *spa = dp->dp_spa;
1265 dsl_scan_t *scn = dp->dp_scan;
1267 if (*cmd == POOL_SCRUB_PAUSE) {
1268 spa->spa_scan_pass_errorscrub_pause = gethrestime_sec();
1269 scn->errorscrub_phys.dep_paused_flags = B_TRUE;
1270 dsl_errorscrub_sync_state(scn, tx);
1271 spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_PAUSED);
1272 } else {
1273 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
1274 if (dsl_errorscrub_is_paused(scn)) {
1276 * We need to keep track of how much time we spend
1277 * paused per pass so that we can adjust the error scrub
1278 * rate shown in the output of 'zpool status'.
1280 spa->spa_scan_pass_errorscrub_spent_paused +=
1281 gethrestime_sec() -
1282 spa->spa_scan_pass_errorscrub_pause;
1284 spa->spa_scan_pass_errorscrub_pause = 0;
1285 scn->errorscrub_phys.dep_paused_flags = B_FALSE;
1287 zap_cursor_init_serialized(
1288 &scn->errorscrub_cursor,
1289 spa->spa_meta_objset, spa->spa_errlog_last,
1290 scn->errorscrub_phys.dep_cursor);
1292 dsl_errorscrub_sync_state(scn, tx);
1297 static int
1298 dsl_errorscrub_cancel_check(void *arg, dmu_tx_t *tx)
1300 (void) arg;
1301 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1302 /* can't cancel a error scrub when there is no one in-progress */
1303 if (!dsl_errorscrubbing(scn->scn_dp))
1304 return (SET_ERROR(ENOENT));
1305 return (0);
1308 static void
1309 dsl_errorscrub_cancel_sync(void *arg, dmu_tx_t *tx)
1311 (void) arg;
1312 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1314 dsl_errorscrub_done(scn, B_FALSE, tx);
1315 dsl_errorscrub_sync_state(scn, tx);
1316 spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL,
1317 ESC_ZFS_ERRORSCRUB_ABORT);
1320 static int
1321 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
1323 (void) arg;
1324 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1326 if (!dsl_scan_is_running(scn))
1327 return (SET_ERROR(ENOENT));
1328 return (0);
1331 static void
1332 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
1334 (void) arg;
1335 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1337 dsl_scan_done(scn, B_FALSE, tx);
1338 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
1339 spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);
1343 dsl_scan_cancel(dsl_pool_t *dp)
1345 if (dsl_errorscrubbing(dp)) {
1346 return (dsl_sync_task(spa_name(dp->dp_spa),
1347 dsl_errorscrub_cancel_check, dsl_errorscrub_cancel_sync,
1348 NULL, 3, ZFS_SPACE_CHECK_RESERVED));
1350 return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
1351 dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
1354 static int
1355 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
1357 pool_scrub_cmd_t *cmd = arg;
1358 dsl_pool_t *dp = dmu_tx_pool(tx);
1359 dsl_scan_t *scn = dp->dp_scan;
1361 if (*cmd == POOL_SCRUB_PAUSE) {
1362 /* can't pause a scrub when there is no in-progress scrub */
1363 if (!dsl_scan_scrubbing(dp))
1364 return (SET_ERROR(ENOENT));
1366 /* can't pause a paused scrub */
1367 if (dsl_scan_is_paused_scrub(scn))
1368 return (SET_ERROR(EBUSY));
1369 } else if (*cmd != POOL_SCRUB_NORMAL) {
1370 return (SET_ERROR(ENOTSUP));
1373 return (0);
1376 static void
1377 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
1379 pool_scrub_cmd_t *cmd = arg;
1380 dsl_pool_t *dp = dmu_tx_pool(tx);
1381 spa_t *spa = dp->dp_spa;
1382 dsl_scan_t *scn = dp->dp_scan;
1384 if (*cmd == POOL_SCRUB_PAUSE) {
1385 /* can't pause a scrub when there is no in-progress scrub */
1386 spa->spa_scan_pass_scrub_pause = gethrestime_sec();
1387 scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
1388 scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED;
1389 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1390 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);
1391 spa_notify_waiters(spa);
1392 } else {
1393 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
1394 if (dsl_scan_is_paused_scrub(scn)) {
1396 * We need to keep track of how much time we spend
1397 * paused per pass so that we can adjust the scrub rate
1398 * shown in the output of 'zpool status'
1400 spa->spa_scan_pass_scrub_spent_paused +=
1401 gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
1402 spa->spa_scan_pass_scrub_pause = 0;
1403 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
1404 scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED;
1405 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1411 * Set scrub pause/resume state if it makes sense to do so
1414 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
1416 if (dsl_errorscrubbing(dp)) {
1417 return (dsl_sync_task(spa_name(dp->dp_spa),
1418 dsl_errorscrub_pause_resume_check,
1419 dsl_errorscrub_pause_resume_sync, &cmd, 3,
1420 ZFS_SPACE_CHECK_RESERVED));
1422 return (dsl_sync_task(spa_name(dp->dp_spa),
1423 dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
1424 ZFS_SPACE_CHECK_RESERVED));
1428 /* start a new scan, or restart an existing one. */
1429 void
1430 dsl_scan_restart_resilver(dsl_pool_t *dp, uint64_t txg)
1432 if (txg == 0) {
1433 dmu_tx_t *tx;
1434 tx = dmu_tx_create_dd(dp->dp_mos_dir);
1435 VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
1437 txg = dmu_tx_get_txg(tx);
1438 dp->dp_scan->scn_restart_txg = txg;
1439 dmu_tx_commit(tx);
1440 } else {
1441 dp->dp_scan->scn_restart_txg = txg;
1443 zfs_dbgmsg("restarting resilver for %s at txg=%llu",
1444 dp->dp_spa->spa_name, (longlong_t)txg);
1447 void
1448 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
1450 zio_free(dp->dp_spa, txg, bp);
1453 void
1454 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
1456 ASSERT(dsl_pool_sync_context(dp));
1457 zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));
1460 static int
1461 scan_ds_queue_compare(const void *a, const void *b)
1463 const scan_ds_t *sds_a = a, *sds_b = b;
1465 if (sds_a->sds_dsobj < sds_b->sds_dsobj)
1466 return (-1);
1467 if (sds_a->sds_dsobj == sds_b->sds_dsobj)
1468 return (0);
1469 return (1);
1472 static void
1473 scan_ds_queue_clear(dsl_scan_t *scn)
1475 void *cookie = NULL;
1476 scan_ds_t *sds;
1477 while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {
1478 kmem_free(sds, sizeof (*sds));
1482 static boolean_t
1483 scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)
1485 scan_ds_t srch, *sds;
1487 srch.sds_dsobj = dsobj;
1488 sds = avl_find(&scn->scn_queue, &srch, NULL);
1489 if (sds != NULL && txg != NULL)
1490 *txg = sds->sds_txg;
1491 return (sds != NULL);
1494 static void
1495 scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)
1497 scan_ds_t *sds;
1498 avl_index_t where;
1500 sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);
1501 sds->sds_dsobj = dsobj;
1502 sds->sds_txg = txg;
1504 VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);
1505 avl_insert(&scn->scn_queue, sds, where);
1508 static void
1509 scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)
1511 scan_ds_t srch, *sds;
1513 srch.sds_dsobj = dsobj;
1515 sds = avl_find(&scn->scn_queue, &srch, NULL);
1516 VERIFY(sds != NULL);
1517 avl_remove(&scn->scn_queue, sds);
1518 kmem_free(sds, sizeof (*sds));
1521 static void
1522 scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)
1524 dsl_pool_t *dp = scn->scn_dp;
1525 spa_t *spa = dp->dp_spa;
1526 dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?
1527 DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;
1529 ASSERT0(scn->scn_queues_pending);
1530 ASSERT(scn->scn_phys.scn_queue_obj != 0);
1532 VERIFY0(dmu_object_free(dp->dp_meta_objset,
1533 scn->scn_phys.scn_queue_obj, tx));
1534 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,
1535 DMU_OT_NONE, 0, tx);
1536 for (scan_ds_t *sds = avl_first(&scn->scn_queue);
1537 sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {
1538 VERIFY0(zap_add_int_key(dp->dp_meta_objset,
1539 scn->scn_phys.scn_queue_obj, sds->sds_dsobj,
1540 sds->sds_txg, tx));
1545 * Computes the memory limit state that we're currently in. A sorted scan
1546 * needs quite a bit of memory to hold the sorting queue, so we need to
1547 * reasonably constrain the size so it doesn't impact overall system
1548 * performance. We compute two limits:
1549 * 1) Hard memory limit: if the amount of memory used by the sorting
1550 * queues on a pool gets above this value, we stop the metadata
1551 * scanning portion and start issuing the queued up and sorted
1552 * I/Os to reduce memory usage.
1553 * This limit is calculated as a fraction of physmem (by default 5%).
1554 * We constrain the lower bound of the hard limit to an absolute
1555 * minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain
1556 * the upper bound to 5% of the total pool size - no chance we'll
1557 * ever need that much memory, but just to keep the value in check.
1558 * 2) Soft memory limit: once we hit the hard memory limit, we start
1559 * issuing I/O to reduce queue memory usage, but we don't want to
1560 * completely empty out the queues, since we might be able to find I/Os
1561 * that will fill in the gaps of our non-sequential IOs at some point
1562 * in the future. So we stop the issuing of I/Os once the amount of
1563 * memory used drops below the soft limit (at which point we stop issuing
1564 * I/O and start scanning metadata again).
1566 * This limit is calculated by subtracting a fraction of the hard
1567 * limit from the hard limit. By default this fraction is 5%, so
1568 * the soft limit is 95% of the hard limit. We cap the size of the
1569 * difference between the hard and soft limits at an absolute
1570 * maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is
1571 * sufficient to not cause too frequent switching between the
1572 * metadata scan and I/O issue (even at 2k recordsize, 128 MiB's
1573 * worth of queues is about 1.2 GiB of on-pool data, so scanning
1574 * that should take at least a decent fraction of a second).
1576 static boolean_t
1577 dsl_scan_should_clear(dsl_scan_t *scn)
1579 spa_t *spa = scn->scn_dp->dp_spa;
1580 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
1581 uint64_t alloc, mlim_hard, mlim_soft, mused;
1583 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
1584 alloc += metaslab_class_get_alloc(spa_special_class(spa));
1585 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
1587 mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,
1588 zfs_scan_mem_lim_min);
1589 mlim_hard = MIN(mlim_hard, alloc / 20);
1590 mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,
1591 zfs_scan_mem_lim_soft_max);
1592 mused = 0;
1593 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1594 vdev_t *tvd = rvd->vdev_child[i];
1595 dsl_scan_io_queue_t *queue;
1597 mutex_enter(&tvd->vdev_scan_io_queue_lock);
1598 queue = tvd->vdev_scan_io_queue;
1599 if (queue != NULL) {
1601 * # of extents in exts_by_addr = # in exts_by_size.
1602 * B-tree efficiency is ~75%, but can be as low as 50%.
1604 mused += zfs_btree_numnodes(&queue->q_exts_by_size) *
1605 ((sizeof (range_seg_gap_t) + sizeof (uint64_t)) *
1606 3 / 2) + queue->q_sio_memused;
1608 mutex_exit(&tvd->vdev_scan_io_queue_lock);
1611 dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);
1613 if (mused == 0)
1614 ASSERT0(scn->scn_queues_pending);
1617 * If we are above our hard limit, we need to clear out memory.
1618 * If we are below our soft limit, we need to accumulate sequential IOs.
1619 * Otherwise, we should keep doing whatever we are currently doing.
1621 if (mused >= mlim_hard)
1622 return (B_TRUE);
1623 else if (mused < mlim_soft)
1624 return (B_FALSE);
1625 else
1626 return (scn->scn_clearing);
1629 static boolean_t
1630 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1632 /* we never skip user/group accounting objects */
1633 if (zb && (int64_t)zb->zb_object < 0)
1634 return (B_FALSE);
1636 if (scn->scn_suspending)
1637 return (B_TRUE); /* we're already suspending */
1639 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
1640 return (B_FALSE); /* we're resuming */
1642 /* We only know how to resume from level-0 and objset blocks. */
1643 if (zb && (zb->zb_level != 0 && zb->zb_level != ZB_ROOT_LEVEL))
1644 return (B_FALSE);
1647 * We suspend if:
1648 * - we have scanned for at least the minimum time (default 1 sec
1649 * for scrub, 3 sec for resilver), and either we have sufficient
1650 * dirty data that we are starting to write more quickly
1651 * (default 30%), someone is explicitly waiting for this txg
1652 * to complete, or we have used up all of the time in the txg
1653 * timeout (default 5 sec).
1654 * or
1655 * - the spa is shutting down because this pool is being exported
1656 * or the machine is rebooting.
1657 * or
1658 * - the scan queue has reached its memory use limit
1660 uint64_t curr_time_ns = gethrtime();
1661 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
1662 uint64_t sync_time_ns = curr_time_ns -
1663 scn->scn_dp->dp_spa->spa_sync_starttime;
1664 uint64_t dirty_min_bytes = zfs_dirty_data_max *
1665 zfs_vdev_async_write_active_min_dirty_percent / 100;
1666 uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
1667 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
1669 if ((NSEC2MSEC(scan_time_ns) > mintime &&
1670 (scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||
1671 txg_sync_waiting(scn->scn_dp) ||
1672 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1673 spa_shutting_down(scn->scn_dp->dp_spa) ||
1674 (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn)) ||
1675 !ddt_walk_ready(scn->scn_dp->dp_spa)) {
1676 if (zb && zb->zb_level == ZB_ROOT_LEVEL) {
1677 dprintf("suspending at first available bookmark "
1678 "%llx/%llx/%llx/%llx\n",
1679 (longlong_t)zb->zb_objset,
1680 (longlong_t)zb->zb_object,
1681 (longlong_t)zb->zb_level,
1682 (longlong_t)zb->zb_blkid);
1683 SET_BOOKMARK(&scn->scn_phys.scn_bookmark,
1684 zb->zb_objset, 0, 0, 0);
1685 } else if (zb != NULL) {
1686 dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
1687 (longlong_t)zb->zb_objset,
1688 (longlong_t)zb->zb_object,
1689 (longlong_t)zb->zb_level,
1690 (longlong_t)zb->zb_blkid);
1691 scn->scn_phys.scn_bookmark = *zb;
1692 } else {
1693 #ifdef ZFS_DEBUG
1694 dsl_scan_phys_t *scnp = &scn->scn_phys;
1695 dprintf("suspending at at DDT bookmark "
1696 "%llx/%llx/%llx/%llx\n",
1697 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
1698 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
1699 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
1700 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
1701 #endif
1703 scn->scn_suspending = B_TRUE;
1704 return (B_TRUE);
1706 return (B_FALSE);
1709 static boolean_t
1710 dsl_error_scrub_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1713 * We suspend if:
1714 * - we have scrubbed for at least the minimum time (default 1 sec
1715 * for error scrub), someone is explicitly waiting for this txg
1716 * to complete, or we have used up all of the time in the txg
1717 * timeout (default 5 sec).
1718 * or
1719 * - the spa is shutting down because this pool is being exported
1720 * or the machine is rebooting.
1722 uint64_t curr_time_ns = gethrtime();
1723 uint64_t error_scrub_time_ns = curr_time_ns - scn->scn_sync_start_time;
1724 uint64_t sync_time_ns = curr_time_ns -
1725 scn->scn_dp->dp_spa->spa_sync_starttime;
1726 int mintime = zfs_scrub_min_time_ms;
1728 if ((NSEC2MSEC(error_scrub_time_ns) > mintime &&
1729 (txg_sync_waiting(scn->scn_dp) ||
1730 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1731 spa_shutting_down(scn->scn_dp->dp_spa)) {
1732 if (zb) {
1733 dprintf("error scrub suspending at bookmark "
1734 "%llx/%llx/%llx/%llx\n",
1735 (longlong_t)zb->zb_objset,
1736 (longlong_t)zb->zb_object,
1737 (longlong_t)zb->zb_level,
1738 (longlong_t)zb->zb_blkid);
1740 return (B_TRUE);
1742 return (B_FALSE);
1745 typedef struct zil_scan_arg {
1746 dsl_pool_t *zsa_dp;
1747 zil_header_t *zsa_zh;
1748 } zil_scan_arg_t;
1750 static int
1751 dsl_scan_zil_block(zilog_t *zilog, const blkptr_t *bp, void *arg,
1752 uint64_t claim_txg)
1754 (void) zilog;
1755 zil_scan_arg_t *zsa = arg;
1756 dsl_pool_t *dp = zsa->zsa_dp;
1757 dsl_scan_t *scn = dp->dp_scan;
1758 zil_header_t *zh = zsa->zsa_zh;
1759 zbookmark_phys_t zb;
1761 ASSERT(!BP_IS_REDACTED(bp));
1762 if (BP_IS_HOLE(bp) ||
1763 BP_GET_LOGICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)
1764 return (0);
1767 * One block ("stubby") can be allocated a long time ago; we
1768 * want to visit that one because it has been allocated
1769 * (on-disk) even if it hasn't been claimed (even though for
1770 * scrub there's nothing to do to it).
1772 if (claim_txg == 0 &&
1773 BP_GET_LOGICAL_BIRTH(bp) >= spa_min_claim_txg(dp->dp_spa))
1774 return (0);
1776 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1777 ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
1779 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1780 return (0);
1783 static int
1784 dsl_scan_zil_record(zilog_t *zilog, const lr_t *lrc, void *arg,
1785 uint64_t claim_txg)
1787 (void) zilog;
1788 if (lrc->lrc_txtype == TX_WRITE) {
1789 zil_scan_arg_t *zsa = arg;
1790 dsl_pool_t *dp = zsa->zsa_dp;
1791 dsl_scan_t *scn = dp->dp_scan;
1792 zil_header_t *zh = zsa->zsa_zh;
1793 const lr_write_t *lr = (const lr_write_t *)lrc;
1794 const blkptr_t *bp = &lr->lr_blkptr;
1795 zbookmark_phys_t zb;
1797 ASSERT(!BP_IS_REDACTED(bp));
1798 if (BP_IS_HOLE(bp) ||
1799 BP_GET_LOGICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)
1800 return (0);
1803 * birth can be < claim_txg if this record's txg is
1804 * already txg sync'ed (but this log block contains
1805 * other records that are not synced)
1807 if (claim_txg == 0 || BP_GET_LOGICAL_BIRTH(bp) < claim_txg)
1808 return (0);
1810 ASSERT3U(BP_GET_LSIZE(bp), !=, 0);
1811 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1812 lr->lr_foid, ZB_ZIL_LEVEL,
1813 lr->lr_offset / BP_GET_LSIZE(bp));
1815 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1817 return (0);
1820 static void
1821 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
1823 uint64_t claim_txg = zh->zh_claim_txg;
1824 zil_scan_arg_t zsa = { dp, zh };
1825 zilog_t *zilog;
1827 ASSERT(spa_writeable(dp->dp_spa));
1830 * We only want to visit blocks that have been claimed but not yet
1831 * replayed (or, in read-only mode, blocks that *would* be claimed).
1833 if (claim_txg == 0)
1834 return;
1836 zilog = zil_alloc(dp->dp_meta_objset, zh);
1838 (void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
1839 claim_txg, B_FALSE);
1841 zil_free(zilog);
1845 * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea
1846 * here is to sort the AVL tree by the order each block will be needed.
1848 static int
1849 scan_prefetch_queue_compare(const void *a, const void *b)
1851 const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;
1852 const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;
1853 const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;
1855 return (zbookmark_compare(spc_a->spc_datablkszsec,
1856 spc_a->spc_indblkshift, spc_b->spc_datablkszsec,
1857 spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));
1860 static void
1861 scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, const void *tag)
1863 if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {
1864 zfs_refcount_destroy(&spc->spc_refcnt);
1865 kmem_free(spc, sizeof (scan_prefetch_ctx_t));
1869 static scan_prefetch_ctx_t *
1870 scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, const void *tag)
1872 scan_prefetch_ctx_t *spc;
1874 spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);
1875 zfs_refcount_create(&spc->spc_refcnt);
1876 zfs_refcount_add(&spc->spc_refcnt, tag);
1877 spc->spc_scn = scn;
1878 if (dnp != NULL) {
1879 spc->spc_datablkszsec = dnp->dn_datablkszsec;
1880 spc->spc_indblkshift = dnp->dn_indblkshift;
1881 spc->spc_root = B_FALSE;
1882 } else {
1883 spc->spc_datablkszsec = 0;
1884 spc->spc_indblkshift = 0;
1885 spc->spc_root = B_TRUE;
1888 return (spc);
1891 static void
1892 scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, const void *tag)
1894 zfs_refcount_add(&spc->spc_refcnt, tag);
1897 static void
1898 scan_ds_prefetch_queue_clear(dsl_scan_t *scn)
1900 spa_t *spa = scn->scn_dp->dp_spa;
1901 void *cookie = NULL;
1902 scan_prefetch_issue_ctx_t *spic = NULL;
1904 mutex_enter(&spa->spa_scrub_lock);
1905 while ((spic = avl_destroy_nodes(&scn->scn_prefetch_queue,
1906 &cookie)) != NULL) {
1907 scan_prefetch_ctx_rele(spic->spic_spc, scn);
1908 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1910 mutex_exit(&spa->spa_scrub_lock);
1913 static boolean_t
1914 dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,
1915 const zbookmark_phys_t *zb)
1917 zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;
1918 dnode_phys_t tmp_dnp;
1919 dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;
1921 if (zb->zb_objset != last_zb->zb_objset)
1922 return (B_TRUE);
1923 if ((int64_t)zb->zb_object < 0)
1924 return (B_FALSE);
1926 tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;
1927 tmp_dnp.dn_indblkshift = spc->spc_indblkshift;
1929 if (zbookmark_subtree_completed(dnp, zb, last_zb))
1930 return (B_TRUE);
1932 return (B_FALSE);
1935 static void
1936 dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)
1938 avl_index_t idx;
1939 dsl_scan_t *scn = spc->spc_scn;
1940 spa_t *spa = scn->scn_dp->dp_spa;
1941 scan_prefetch_issue_ctx_t *spic;
1943 if (zfs_no_scrub_prefetch || BP_IS_REDACTED(bp))
1944 return;
1946 if (BP_IS_HOLE(bp) ||
1947 BP_GET_LOGICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg ||
1948 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
1949 BP_GET_TYPE(bp) != DMU_OT_OBJSET))
1950 return;
1952 if (dsl_scan_check_prefetch_resume(spc, zb))
1953 return;
1955 scan_prefetch_ctx_add_ref(spc, scn);
1956 spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);
1957 spic->spic_spc = spc;
1958 spic->spic_bp = *bp;
1959 spic->spic_zb = *zb;
1962 * Add the IO to the queue of blocks to prefetch. This allows us to
1963 * prioritize blocks that we will need first for the main traversal
1964 * thread.
1966 mutex_enter(&spa->spa_scrub_lock);
1967 if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {
1968 /* this block is already queued for prefetch */
1969 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1970 scan_prefetch_ctx_rele(spc, scn);
1971 mutex_exit(&spa->spa_scrub_lock);
1972 return;
1975 avl_insert(&scn->scn_prefetch_queue, spic, idx);
1976 cv_broadcast(&spa->spa_scrub_io_cv);
1977 mutex_exit(&spa->spa_scrub_lock);
1980 static void
1981 dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,
1982 uint64_t objset, uint64_t object)
1984 int i;
1985 zbookmark_phys_t zb;
1986 scan_prefetch_ctx_t *spc;
1988 if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1989 return;
1991 SET_BOOKMARK(&zb, objset, object, 0, 0);
1993 spc = scan_prefetch_ctx_create(scn, dnp, FTAG);
1995 for (i = 0; i < dnp->dn_nblkptr; i++) {
1996 zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);
1997 zb.zb_blkid = i;
1998 dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);
2001 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
2002 zb.zb_level = 0;
2003 zb.zb_blkid = DMU_SPILL_BLKID;
2004 dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);
2007 scan_prefetch_ctx_rele(spc, FTAG);
2010 static void
2011 dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
2012 arc_buf_t *buf, void *private)
2014 (void) zio;
2015 scan_prefetch_ctx_t *spc = private;
2016 dsl_scan_t *scn = spc->spc_scn;
2017 spa_t *spa = scn->scn_dp->dp_spa;
2019 /* broadcast that the IO has completed for rate limiting purposes */
2020 mutex_enter(&spa->spa_scrub_lock);
2021 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
2022 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
2023 cv_broadcast(&spa->spa_scrub_io_cv);
2024 mutex_exit(&spa->spa_scrub_lock);
2026 /* if there was an error or we are done prefetching, just cleanup */
2027 if (buf == NULL || scn->scn_prefetch_stop)
2028 goto out;
2030 if (BP_GET_LEVEL(bp) > 0) {
2031 int i;
2032 blkptr_t *cbp;
2033 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2034 zbookmark_phys_t czb;
2036 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
2037 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2038 zb->zb_level - 1, zb->zb_blkid * epb + i);
2039 dsl_scan_prefetch(spc, cbp, &czb);
2041 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
2042 dnode_phys_t *cdnp;
2043 int i;
2044 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
2046 for (i = 0, cdnp = buf->b_data; i < epb;
2047 i += cdnp->dn_extra_slots + 1,
2048 cdnp += cdnp->dn_extra_slots + 1) {
2049 dsl_scan_prefetch_dnode(scn, cdnp,
2050 zb->zb_objset, zb->zb_blkid * epb + i);
2052 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
2053 objset_phys_t *osp = buf->b_data;
2055 dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,
2056 zb->zb_objset, DMU_META_DNODE_OBJECT);
2058 if (OBJSET_BUF_HAS_USERUSED(buf)) {
2059 if (OBJSET_BUF_HAS_PROJECTUSED(buf)) {
2060 dsl_scan_prefetch_dnode(scn,
2061 &osp->os_projectused_dnode, zb->zb_objset,
2062 DMU_PROJECTUSED_OBJECT);
2064 dsl_scan_prefetch_dnode(scn,
2065 &osp->os_groupused_dnode, zb->zb_objset,
2066 DMU_GROUPUSED_OBJECT);
2067 dsl_scan_prefetch_dnode(scn,
2068 &osp->os_userused_dnode, zb->zb_objset,
2069 DMU_USERUSED_OBJECT);
2073 out:
2074 if (buf != NULL)
2075 arc_buf_destroy(buf, private);
2076 scan_prefetch_ctx_rele(spc, scn);
2079 static void
2080 dsl_scan_prefetch_thread(void *arg)
2082 dsl_scan_t *scn = arg;
2083 spa_t *spa = scn->scn_dp->dp_spa;
2084 scan_prefetch_issue_ctx_t *spic;
2086 /* loop until we are told to stop */
2087 while (!scn->scn_prefetch_stop) {
2088 arc_flags_t flags = ARC_FLAG_NOWAIT |
2089 ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;
2090 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
2092 mutex_enter(&spa->spa_scrub_lock);
2095 * Wait until we have an IO to issue and are not above our
2096 * maximum in flight limit.
2098 while (!scn->scn_prefetch_stop &&
2099 (avl_numnodes(&scn->scn_prefetch_queue) == 0 ||
2100 spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {
2101 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2104 /* recheck if we should stop since we waited for the cv */
2105 if (scn->scn_prefetch_stop) {
2106 mutex_exit(&spa->spa_scrub_lock);
2107 break;
2110 /* remove the prefetch IO from the tree */
2111 spic = avl_first(&scn->scn_prefetch_queue);
2112 spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);
2113 avl_remove(&scn->scn_prefetch_queue, spic);
2115 mutex_exit(&spa->spa_scrub_lock);
2117 if (BP_IS_PROTECTED(&spic->spic_bp)) {
2118 ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||
2119 BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);
2120 ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);
2121 zio_flags |= ZIO_FLAG_RAW;
2124 /* We don't need data L1 buffer since we do not prefetch L0. */
2125 blkptr_t *bp = &spic->spic_bp;
2126 if (BP_GET_LEVEL(bp) == 1 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
2127 BP_GET_TYPE(bp) != DMU_OT_OBJSET)
2128 flags |= ARC_FLAG_NO_BUF;
2130 /* issue the prefetch asynchronously */
2131 (void) arc_read(scn->scn_zio_root, spa, bp,
2132 dsl_scan_prefetch_cb, spic->spic_spc, ZIO_PRIORITY_SCRUB,
2133 zio_flags, &flags, &spic->spic_zb);
2135 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2138 ASSERT(scn->scn_prefetch_stop);
2140 /* free any prefetches we didn't get to complete */
2141 mutex_enter(&spa->spa_scrub_lock);
2142 while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {
2143 avl_remove(&scn->scn_prefetch_queue, spic);
2144 scan_prefetch_ctx_rele(spic->spic_spc, scn);
2145 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2147 ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));
2148 mutex_exit(&spa->spa_scrub_lock);
2151 static boolean_t
2152 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
2153 const zbookmark_phys_t *zb)
2156 * We never skip over user/group accounting objects (obj<0)
2158 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
2159 (int64_t)zb->zb_object >= 0) {
2161 * If we already visited this bp & everything below (in
2162 * a prior txg sync), don't bother doing it again.
2164 if (zbookmark_subtree_completed(dnp, zb,
2165 &scn->scn_phys.scn_bookmark))
2166 return (B_TRUE);
2169 * If we found the block we're trying to resume from, or
2170 * we went past it, zero it out to indicate that it's OK
2171 * to start checking for suspending again.
2173 if (zbookmark_subtree_tbd(dnp, zb,
2174 &scn->scn_phys.scn_bookmark)) {
2175 dprintf("resuming at %llx/%llx/%llx/%llx\n",
2176 (longlong_t)zb->zb_objset,
2177 (longlong_t)zb->zb_object,
2178 (longlong_t)zb->zb_level,
2179 (longlong_t)zb->zb_blkid);
2180 memset(&scn->scn_phys.scn_bookmark, 0, sizeof (*zb));
2183 return (B_FALSE);
2186 static void dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,
2187 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
2188 dmu_objset_type_t ostype, dmu_tx_t *tx);
2189 inline __attribute__((always_inline)) static void dsl_scan_visitdnode(
2190 dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,
2191 dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
2194 * Return nonzero on i/o error.
2195 * Return new buf to write out in *bufp.
2197 inline __attribute__((always_inline)) static int
2198 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
2199 dnode_phys_t *dnp, const blkptr_t *bp,
2200 const zbookmark_phys_t *zb, dmu_tx_t *tx)
2202 dsl_pool_t *dp = scn->scn_dp;
2203 spa_t *spa = dp->dp_spa;
2204 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
2205 int err;
2207 ASSERT(!BP_IS_REDACTED(bp));
2210 * There is an unlikely case of encountering dnodes with contradicting
2211 * dn_bonuslen and DNODE_FLAG_SPILL_BLKPTR flag before in files created
2212 * or modified before commit 4254acb was merged. As it is not possible
2213 * to know which of the two is correct, report an error.
2215 if (dnp != NULL &&
2216 dnp->dn_bonuslen > DN_MAX_BONUS_LEN(dnp)) {
2217 scn->scn_phys.scn_errors++;
2218 spa_log_error(spa, zb, BP_GET_LOGICAL_BIRTH(bp));
2219 return (SET_ERROR(EINVAL));
2222 if (BP_GET_LEVEL(bp) > 0) {
2223 arc_flags_t flags = ARC_FLAG_WAIT;
2224 int i;
2225 blkptr_t *cbp;
2226 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2227 arc_buf_t *buf;
2229 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2230 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2231 if (err) {
2232 scn->scn_phys.scn_errors++;
2233 return (err);
2235 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
2236 zbookmark_phys_t czb;
2238 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2239 zb->zb_level - 1,
2240 zb->zb_blkid * epb + i);
2241 dsl_scan_visitbp(cbp, &czb, dnp,
2242 ds, scn, ostype, tx);
2244 arc_buf_destroy(buf, &buf);
2245 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
2246 arc_flags_t flags = ARC_FLAG_WAIT;
2247 dnode_phys_t *cdnp;
2248 int i;
2249 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
2250 arc_buf_t *buf;
2252 if (BP_IS_PROTECTED(bp)) {
2253 ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
2254 zio_flags |= ZIO_FLAG_RAW;
2257 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2258 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2259 if (err) {
2260 scn->scn_phys.scn_errors++;
2261 return (err);
2263 for (i = 0, cdnp = buf->b_data; i < epb;
2264 i += cdnp->dn_extra_slots + 1,
2265 cdnp += cdnp->dn_extra_slots + 1) {
2266 dsl_scan_visitdnode(scn, ds, ostype,
2267 cdnp, zb->zb_blkid * epb + i, tx);
2270 arc_buf_destroy(buf, &buf);
2271 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
2272 arc_flags_t flags = ARC_FLAG_WAIT;
2273 objset_phys_t *osp;
2274 arc_buf_t *buf;
2276 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2277 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2278 if (err) {
2279 scn->scn_phys.scn_errors++;
2280 return (err);
2283 osp = buf->b_data;
2285 dsl_scan_visitdnode(scn, ds, osp->os_type,
2286 &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
2288 if (OBJSET_BUF_HAS_USERUSED(buf)) {
2290 * We also always visit user/group/project accounting
2291 * objects, and never skip them, even if we are
2292 * suspending. This is necessary so that the
2293 * space deltas from this txg get integrated.
2295 if (OBJSET_BUF_HAS_PROJECTUSED(buf))
2296 dsl_scan_visitdnode(scn, ds, osp->os_type,
2297 &osp->os_projectused_dnode,
2298 DMU_PROJECTUSED_OBJECT, tx);
2299 dsl_scan_visitdnode(scn, ds, osp->os_type,
2300 &osp->os_groupused_dnode,
2301 DMU_GROUPUSED_OBJECT, tx);
2302 dsl_scan_visitdnode(scn, ds, osp->os_type,
2303 &osp->os_userused_dnode,
2304 DMU_USERUSED_OBJECT, tx);
2306 arc_buf_destroy(buf, &buf);
2307 } else if (!zfs_blkptr_verify(spa, bp,
2308 BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {
2310 * Sanity check the block pointer contents, this is handled
2311 * by arc_read() for the cases above.
2313 scn->scn_phys.scn_errors++;
2314 spa_log_error(spa, zb, BP_GET_LOGICAL_BIRTH(bp));
2315 return (SET_ERROR(EINVAL));
2318 return (0);
2321 inline __attribute__((always_inline)) static void
2322 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
2323 dmu_objset_type_t ostype, dnode_phys_t *dnp,
2324 uint64_t object, dmu_tx_t *tx)
2326 int j;
2328 for (j = 0; j < dnp->dn_nblkptr; j++) {
2329 zbookmark_phys_t czb;
2331 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
2332 dnp->dn_nlevels - 1, j);
2333 dsl_scan_visitbp(&dnp->dn_blkptr[j],
2334 &czb, dnp, ds, scn, ostype, tx);
2337 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
2338 zbookmark_phys_t czb;
2339 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
2340 0, DMU_SPILL_BLKID);
2341 dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),
2342 &czb, dnp, ds, scn, ostype, tx);
2347 * The arguments are in this order because mdb can only print the
2348 * first 5; we want them to be useful.
2350 static void
2351 dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,
2352 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
2353 dmu_objset_type_t ostype, dmu_tx_t *tx)
2355 dsl_pool_t *dp = scn->scn_dp;
2357 if (dsl_scan_check_suspend(scn, zb))
2358 return;
2360 if (dsl_scan_check_resume(scn, dnp, zb))
2361 return;
2363 scn->scn_visited_this_txg++;
2365 if (BP_IS_HOLE(bp)) {
2366 scn->scn_holes_this_txg++;
2367 return;
2370 if (BP_IS_REDACTED(bp)) {
2371 ASSERT(dsl_dataset_feature_is_active(ds,
2372 SPA_FEATURE_REDACTED_DATASETS));
2373 return;
2377 * Check if this block contradicts any filesystem flags.
2379 spa_feature_t f = SPA_FEATURE_LARGE_BLOCKS;
2380 if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE)
2381 ASSERT(dsl_dataset_feature_is_active(ds, f));
2383 f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
2384 if (f != SPA_FEATURE_NONE)
2385 ASSERT(dsl_dataset_feature_is_active(ds, f));
2387 f = zio_compress_to_feature(BP_GET_COMPRESS(bp));
2388 if (f != SPA_FEATURE_NONE)
2389 ASSERT(dsl_dataset_feature_is_active(ds, f));
2391 if (BP_GET_LOGICAL_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg) {
2392 scn->scn_lt_min_this_txg++;
2393 return;
2396 if (dsl_scan_recurse(scn, ds, ostype, dnp, bp, zb, tx) != 0)
2397 return;
2400 * If dsl_scan_ddt() has already visited this block, it will have
2401 * already done any translations or scrubbing, so don't call the
2402 * callback again.
2404 if (ddt_class_contains(dp->dp_spa,
2405 scn->scn_phys.scn_ddt_class_max, bp)) {
2406 scn->scn_ddt_contained_this_txg++;
2407 return;
2411 * If this block is from the future (after cur_max_txg), then we
2412 * are doing this on behalf of a deleted snapshot, and we will
2413 * revisit the future block on the next pass of this dataset.
2414 * Don't scan it now unless we need to because something
2415 * under it was modified.
2417 if (BP_GET_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {
2418 scn->scn_gt_max_this_txg++;
2419 return;
2422 scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
2425 static void
2426 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
2427 dmu_tx_t *tx)
2429 zbookmark_phys_t zb;
2430 scan_prefetch_ctx_t *spc;
2432 SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
2433 ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
2435 if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {
2436 SET_BOOKMARK(&scn->scn_prefetch_bookmark,
2437 zb.zb_objset, 0, 0, 0);
2438 } else {
2439 scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;
2442 scn->scn_objsets_visited_this_txg++;
2444 spc = scan_prefetch_ctx_create(scn, NULL, FTAG);
2445 dsl_scan_prefetch(spc, bp, &zb);
2446 scan_prefetch_ctx_rele(spc, FTAG);
2448 dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);
2450 dprintf_ds(ds, "finished scan%s", "");
2453 static void
2454 ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)
2456 if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {
2457 if (ds->ds_is_snapshot) {
2459 * Note:
2460 * - scn_cur_{min,max}_txg stays the same.
2461 * - Setting the flag is not really necessary if
2462 * scn_cur_max_txg == scn_max_txg, because there
2463 * is nothing after this snapshot that we care
2464 * about. However, we set it anyway and then
2465 * ignore it when we retraverse it in
2466 * dsl_scan_visitds().
2468 scn_phys->scn_bookmark.zb_objset =
2469 dsl_dataset_phys(ds)->ds_next_snap_obj;
2470 zfs_dbgmsg("destroying ds %llu on %s; currently "
2471 "traversing; reset zb_objset to %llu",
2472 (u_longlong_t)ds->ds_object,
2473 ds->ds_dir->dd_pool->dp_spa->spa_name,
2474 (u_longlong_t)dsl_dataset_phys(ds)->
2475 ds_next_snap_obj);
2476 scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;
2477 } else {
2478 SET_BOOKMARK(&scn_phys->scn_bookmark,
2479 ZB_DESTROYED_OBJSET, 0, 0, 0);
2480 zfs_dbgmsg("destroying ds %llu on %s; currently "
2481 "traversing; reset bookmark to -1,0,0,0",
2482 (u_longlong_t)ds->ds_object,
2483 ds->ds_dir->dd_pool->dp_spa->spa_name);
2489 * Invoked when a dataset is destroyed. We need to make sure that:
2491 * 1) If it is the dataset that was currently being scanned, we write
2492 * a new dsl_scan_phys_t and marking the objset reference in it
2493 * as destroyed.
2494 * 2) Remove it from the work queue, if it was present.
2496 * If the dataset was actually a snapshot, instead of marking the dataset
2497 * as destroyed, we instead substitute the next snapshot in line.
2499 void
2500 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
2502 dsl_pool_t *dp = ds->ds_dir->dd_pool;
2503 dsl_scan_t *scn = dp->dp_scan;
2504 uint64_t mintxg;
2506 if (!dsl_scan_is_running(scn))
2507 return;
2509 ds_destroyed_scn_phys(ds, &scn->scn_phys);
2510 ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);
2512 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2513 scan_ds_queue_remove(scn, ds->ds_object);
2514 if (ds->ds_is_snapshot)
2515 scan_ds_queue_insert(scn,
2516 dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);
2519 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2520 ds->ds_object, &mintxg) == 0) {
2521 ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
2522 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2523 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2524 if (ds->ds_is_snapshot) {
2526 * We keep the same mintxg; it could be >
2527 * ds_creation_txg if the previous snapshot was
2528 * deleted too.
2530 VERIFY(zap_add_int_key(dp->dp_meta_objset,
2531 scn->scn_phys.scn_queue_obj,
2532 dsl_dataset_phys(ds)->ds_next_snap_obj,
2533 mintxg, tx) == 0);
2534 zfs_dbgmsg("destroying ds %llu on %s; in queue; "
2535 "replacing with %llu",
2536 (u_longlong_t)ds->ds_object,
2537 dp->dp_spa->spa_name,
2538 (u_longlong_t)dsl_dataset_phys(ds)->
2539 ds_next_snap_obj);
2540 } else {
2541 zfs_dbgmsg("destroying ds %llu on %s; in queue; "
2542 "removing",
2543 (u_longlong_t)ds->ds_object,
2544 dp->dp_spa->spa_name);
2549 * dsl_scan_sync() should be called after this, and should sync
2550 * out our changed state, but just to be safe, do it here.
2552 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2555 static void
2556 ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)
2558 if (scn_bookmark->zb_objset == ds->ds_object) {
2559 scn_bookmark->zb_objset =
2560 dsl_dataset_phys(ds)->ds_prev_snap_obj;
2561 zfs_dbgmsg("snapshotting ds %llu on %s; currently traversing; "
2562 "reset zb_objset to %llu",
2563 (u_longlong_t)ds->ds_object,
2564 ds->ds_dir->dd_pool->dp_spa->spa_name,
2565 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2570 * Called when a dataset is snapshotted. If we were currently traversing
2571 * this snapshot, we reset our bookmark to point at the newly created
2572 * snapshot. We also modify our work queue to remove the old snapshot and
2573 * replace with the new one.
2575 void
2576 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
2578 dsl_pool_t *dp = ds->ds_dir->dd_pool;
2579 dsl_scan_t *scn = dp->dp_scan;
2580 uint64_t mintxg;
2582 if (!dsl_scan_is_running(scn))
2583 return;
2585 ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
2587 ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);
2588 ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);
2590 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2591 scan_ds_queue_remove(scn, ds->ds_object);
2592 scan_ds_queue_insert(scn,
2593 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);
2596 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2597 ds->ds_object, &mintxg) == 0) {
2598 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2599 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2600 VERIFY(zap_add_int_key(dp->dp_meta_objset,
2601 scn->scn_phys.scn_queue_obj,
2602 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
2603 zfs_dbgmsg("snapshotting ds %llu on %s; in queue; "
2604 "replacing with %llu",
2605 (u_longlong_t)ds->ds_object,
2606 dp->dp_spa->spa_name,
2607 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2610 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2613 static void
2614 ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,
2615 zbookmark_phys_t *scn_bookmark)
2617 if (scn_bookmark->zb_objset == ds1->ds_object) {
2618 scn_bookmark->zb_objset = ds2->ds_object;
2619 zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "
2620 "reset zb_objset to %llu",
2621 (u_longlong_t)ds1->ds_object,
2622 ds1->ds_dir->dd_pool->dp_spa->spa_name,
2623 (u_longlong_t)ds2->ds_object);
2624 } else if (scn_bookmark->zb_objset == ds2->ds_object) {
2625 scn_bookmark->zb_objset = ds1->ds_object;
2626 zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "
2627 "reset zb_objset to %llu",
2628 (u_longlong_t)ds2->ds_object,
2629 ds2->ds_dir->dd_pool->dp_spa->spa_name,
2630 (u_longlong_t)ds1->ds_object);
2635 * Called when an origin dataset and its clone are swapped. If we were
2636 * currently traversing the dataset, we need to switch to traversing the
2637 * newly promoted clone.
2639 void
2640 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
2642 dsl_pool_t *dp = ds1->ds_dir->dd_pool;
2643 dsl_scan_t *scn = dp->dp_scan;
2644 uint64_t mintxg1, mintxg2;
2645 boolean_t ds1_queued, ds2_queued;
2647 if (!dsl_scan_is_running(scn))
2648 return;
2650 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);
2651 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);
2654 * Handle the in-memory scan queue.
2656 ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);
2657 ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);
2659 /* Sanity checking. */
2660 if (ds1_queued) {
2661 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2662 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2664 if (ds2_queued) {
2665 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2666 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2669 if (ds1_queued && ds2_queued) {
2671 * If both are queued, we don't need to do anything.
2672 * The swapping code below would not handle this case correctly,
2673 * since we can't insert ds2 if it is already there. That's
2674 * because scan_ds_queue_insert() prohibits a duplicate insert
2675 * and panics.
2677 } else if (ds1_queued) {
2678 scan_ds_queue_remove(scn, ds1->ds_object);
2679 scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);
2680 } else if (ds2_queued) {
2681 scan_ds_queue_remove(scn, ds2->ds_object);
2682 scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);
2686 * Handle the on-disk scan queue.
2687 * The on-disk state is an out-of-date version of the in-memory state,
2688 * so the in-memory and on-disk values for ds1_queued and ds2_queued may
2689 * be different. Therefore we need to apply the swap logic to the
2690 * on-disk state independently of the in-memory state.
2692 ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,
2693 scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;
2694 ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,
2695 scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;
2697 /* Sanity checking. */
2698 if (ds1_queued) {
2699 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2700 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2702 if (ds2_queued) {
2703 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2704 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2707 if (ds1_queued && ds2_queued) {
2709 * If both are queued, we don't need to do anything.
2710 * Alternatively, we could check for EEXIST from
2711 * zap_add_int_key() and back out to the original state, but
2712 * that would be more work than checking for this case upfront.
2714 } else if (ds1_queued) {
2715 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2716 scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
2717 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2718 scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));
2719 zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "
2720 "replacing with %llu",
2721 (u_longlong_t)ds1->ds_object,
2722 dp->dp_spa->spa_name,
2723 (u_longlong_t)ds2->ds_object);
2724 } else if (ds2_queued) {
2725 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2726 scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
2727 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2728 scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));
2729 zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "
2730 "replacing with %llu",
2731 (u_longlong_t)ds2->ds_object,
2732 dp->dp_spa->spa_name,
2733 (u_longlong_t)ds1->ds_object);
2736 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2739 static int
2740 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2742 uint64_t originobj = *(uint64_t *)arg;
2743 dsl_dataset_t *ds;
2744 int err;
2745 dsl_scan_t *scn = dp->dp_scan;
2747 if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)
2748 return (0);
2750 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2751 if (err)
2752 return (err);
2754 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {
2755 dsl_dataset_t *prev;
2756 err = dsl_dataset_hold_obj(dp,
2757 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2759 dsl_dataset_rele(ds, FTAG);
2760 if (err)
2761 return (err);
2762 ds = prev;
2764 mutex_enter(&scn->scn_queue_lock);
2765 scan_ds_queue_insert(scn, ds->ds_object,
2766 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2767 mutex_exit(&scn->scn_queue_lock);
2768 dsl_dataset_rele(ds, FTAG);
2769 return (0);
2772 static void
2773 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
2775 dsl_pool_t *dp = scn->scn_dp;
2776 dsl_dataset_t *ds;
2778 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2780 if (scn->scn_phys.scn_cur_min_txg >=
2781 scn->scn_phys.scn_max_txg) {
2783 * This can happen if this snapshot was created after the
2784 * scan started, and we already completed a previous snapshot
2785 * that was created after the scan started. This snapshot
2786 * only references blocks with:
2788 * birth < our ds_creation_txg
2789 * cur_min_txg is no less than ds_creation_txg.
2790 * We have already visited these blocks.
2791 * or
2792 * birth > scn_max_txg
2793 * The scan requested not to visit these blocks.
2795 * Subsequent snapshots (and clones) can reference our
2796 * blocks, or blocks with even higher birth times.
2797 * Therefore we do not need to visit them either,
2798 * so we do not add them to the work queue.
2800 * Note that checking for cur_min_txg >= cur_max_txg
2801 * is not sufficient, because in that case we may need to
2802 * visit subsequent snapshots. This happens when min_txg > 0,
2803 * which raises cur_min_txg. In this case we will visit
2804 * this dataset but skip all of its blocks, because the
2805 * rootbp's birth time is < cur_min_txg. Then we will
2806 * add the next snapshots/clones to the work queue.
2808 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2809 dsl_dataset_name(ds, dsname);
2810 zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
2811 "cur_min_txg (%llu) >= max_txg (%llu)",
2812 (longlong_t)dsobj, dsname,
2813 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2814 (longlong_t)scn->scn_phys.scn_max_txg);
2815 kmem_free(dsname, MAXNAMELEN);
2817 goto out;
2821 * Only the ZIL in the head (non-snapshot) is valid. Even though
2822 * snapshots can have ZIL block pointers (which may be the same
2823 * BP as in the head), they must be ignored. In addition, $ORIGIN
2824 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
2825 * need to look for a ZIL in it either. So we traverse the ZIL here,
2826 * rather than in scan_recurse(), because the regular snapshot
2827 * block-sharing rules don't apply to it.
2829 if (!dsl_dataset_is_snapshot(ds) &&
2830 (dp->dp_origin_snap == NULL ||
2831 ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
2832 objset_t *os;
2833 if (dmu_objset_from_ds(ds, &os) != 0) {
2834 goto out;
2836 dsl_scan_zil(dp, &os->os_zil_header);
2840 * Iterate over the bps in this ds.
2842 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2843 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2844 dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
2845 rrw_exit(&ds->ds_bp_rwlock, FTAG);
2847 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2848 dsl_dataset_name(ds, dsname);
2849 zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
2850 "suspending=%u",
2851 (longlong_t)dsobj, dsname,
2852 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2853 (longlong_t)scn->scn_phys.scn_cur_max_txg,
2854 (int)scn->scn_suspending);
2855 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
2857 if (scn->scn_suspending)
2858 goto out;
2861 * We've finished this pass over this dataset.
2865 * If we did not completely visit this dataset, do another pass.
2867 if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
2868 zfs_dbgmsg("incomplete pass on %s; visiting again",
2869 dp->dp_spa->spa_name);
2870 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
2871 scan_ds_queue_insert(scn, ds->ds_object,
2872 scn->scn_phys.scn_cur_max_txg);
2873 goto out;
2877 * Add descendant datasets to work queue.
2879 if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
2880 scan_ds_queue_insert(scn,
2881 dsl_dataset_phys(ds)->ds_next_snap_obj,
2882 dsl_dataset_phys(ds)->ds_creation_txg);
2884 if (dsl_dataset_phys(ds)->ds_num_children > 1) {
2885 boolean_t usenext = B_FALSE;
2886 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2887 uint64_t count;
2889 * A bug in a previous version of the code could
2890 * cause upgrade_clones_cb() to not set
2891 * ds_next_snap_obj when it should, leading to a
2892 * missing entry. Therefore we can only use the
2893 * next_clones_obj when its count is correct.
2895 int err = zap_count(dp->dp_meta_objset,
2896 dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
2897 if (err == 0 &&
2898 count == dsl_dataset_phys(ds)->ds_num_children - 1)
2899 usenext = B_TRUE;
2902 if (usenext) {
2903 zap_cursor_t zc;
2904 zap_attribute_t *za = zap_attribute_alloc();
2905 for (zap_cursor_init(&zc, dp->dp_meta_objset,
2906 dsl_dataset_phys(ds)->ds_next_clones_obj);
2907 zap_cursor_retrieve(&zc, za) == 0;
2908 (void) zap_cursor_advance(&zc)) {
2909 scan_ds_queue_insert(scn,
2910 zfs_strtonum(za->za_name, NULL),
2911 dsl_dataset_phys(ds)->ds_creation_txg);
2913 zap_cursor_fini(&zc);
2914 zap_attribute_free(za);
2915 } else {
2916 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2917 enqueue_clones_cb, &ds->ds_object,
2918 DS_FIND_CHILDREN));
2922 out:
2923 dsl_dataset_rele(ds, FTAG);
2926 static int
2927 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2929 (void) arg;
2930 dsl_dataset_t *ds;
2931 int err;
2932 dsl_scan_t *scn = dp->dp_scan;
2934 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2935 if (err)
2936 return (err);
2938 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2939 dsl_dataset_t *prev;
2940 err = dsl_dataset_hold_obj(dp,
2941 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2942 if (err) {
2943 dsl_dataset_rele(ds, FTAG);
2944 return (err);
2948 * If this is a clone, we don't need to worry about it for now.
2950 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
2951 dsl_dataset_rele(ds, FTAG);
2952 dsl_dataset_rele(prev, FTAG);
2953 return (0);
2955 dsl_dataset_rele(ds, FTAG);
2956 ds = prev;
2959 mutex_enter(&scn->scn_queue_lock);
2960 scan_ds_queue_insert(scn, ds->ds_object,
2961 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2962 mutex_exit(&scn->scn_queue_lock);
2963 dsl_dataset_rele(ds, FTAG);
2964 return (0);
2967 void
2968 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
2969 ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
2971 (void) tx;
2972 const ddt_key_t *ddk = &ddlwe->ddlwe_key;
2973 blkptr_t bp;
2974 zbookmark_phys_t zb = { 0 };
2976 if (!dsl_scan_is_running(scn))
2977 return;
2980 * This function is special because it is the only thing
2981 * that can add scan_io_t's to the vdev scan queues from
2982 * outside dsl_scan_sync(). For the most part this is ok
2983 * as long as it is called from within syncing context.
2984 * However, dsl_scan_sync() expects that no new sio's will
2985 * be added between when all the work for a scan is done
2986 * and the next txg when the scan is actually marked as
2987 * completed. This check ensures we do not issue new sio's
2988 * during this period.
2990 if (scn->scn_done_txg != 0)
2991 return;
2993 for (int p = 0; p < DDT_NPHYS(ddt); p++) {
2994 ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
2995 uint64_t phys_birth = ddt_phys_birth(&ddlwe->ddlwe_phys, v);
2997 if (phys_birth == 0 || phys_birth > scn->scn_phys.scn_max_txg)
2998 continue;
2999 ddt_bp_create(checksum, ddk, &ddlwe->ddlwe_phys, v, &bp);
3001 scn->scn_visited_this_txg++;
3002 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
3007 * Scrub/dedup interaction.
3009 * If there are N references to a deduped block, we don't want to scrub it
3010 * N times -- ideally, we should scrub it exactly once.
3012 * We leverage the fact that the dde's replication class (ddt_class_t)
3013 * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
3014 * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
3016 * To prevent excess scrubbing, the scrub begins by walking the DDT
3017 * to find all blocks with refcnt > 1, and scrubs each of these once.
3018 * Since there are two replication classes which contain blocks with
3019 * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
3020 * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
3022 * There would be nothing more to say if a block's refcnt couldn't change
3023 * during a scrub, but of course it can so we must account for changes
3024 * in a block's replication class.
3026 * Here's an example of what can occur:
3028 * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
3029 * when visited during the top-down scrub phase, it will be scrubbed twice.
3030 * This negates our scrub optimization, but is otherwise harmless.
3032 * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
3033 * on each visit during the top-down scrub phase, it will never be scrubbed.
3034 * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
3035 * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
3036 * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
3037 * while a scrub is in progress, it scrubs the block right then.
3039 static void
3040 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
3042 ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
3043 ddt_lightweight_entry_t ddlwe = {0};
3044 int error;
3045 uint64_t n = 0;
3047 while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &ddlwe)) == 0) {
3048 ddt_t *ddt;
3050 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
3051 break;
3052 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
3053 (longlong_t)ddb->ddb_class,
3054 (longlong_t)ddb->ddb_type,
3055 (longlong_t)ddb->ddb_checksum,
3056 (longlong_t)ddb->ddb_cursor);
3058 /* There should be no pending changes to the dedup table */
3059 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
3060 ASSERT(avl_first(&ddt->ddt_tree) == NULL);
3062 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, ddt, &ddlwe, tx);
3063 n++;
3065 if (dsl_scan_check_suspend(scn, NULL))
3066 break;
3069 if (error == EAGAIN) {
3070 dsl_scan_check_suspend(scn, NULL);
3071 error = 0;
3073 zfs_dbgmsg("waiting for ddt to become ready for scan "
3074 "on %s with class_max = %u; suspending=%u",
3075 scn->scn_dp->dp_spa->spa_name,
3076 (int)scn->scn_phys.scn_ddt_class_max,
3077 (int)scn->scn_suspending);
3078 } else
3079 zfs_dbgmsg("scanned %llu ddt entries on %s with "
3080 "class_max = %u; suspending=%u", (longlong_t)n,
3081 scn->scn_dp->dp_spa->spa_name,
3082 (int)scn->scn_phys.scn_ddt_class_max,
3083 (int)scn->scn_suspending);
3085 ASSERT(error == 0 || error == ENOENT);
3086 ASSERT(error != ENOENT ||
3087 ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
3090 static uint64_t
3091 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
3093 uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
3094 if (ds->ds_is_snapshot)
3095 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
3096 return (smt);
3099 static void
3100 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
3102 scan_ds_t *sds;
3103 dsl_pool_t *dp = scn->scn_dp;
3105 if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
3106 scn->scn_phys.scn_ddt_class_max) {
3107 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
3108 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
3109 dsl_scan_ddt(scn, tx);
3110 if (scn->scn_suspending)
3111 return;
3114 if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
3115 /* First do the MOS & ORIGIN */
3117 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
3118 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
3119 dsl_scan_visit_rootbp(scn, NULL,
3120 &dp->dp_meta_rootbp, tx);
3121 if (scn->scn_suspending)
3122 return;
3124 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
3125 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3126 enqueue_cb, NULL, DS_FIND_CHILDREN));
3127 } else {
3128 dsl_scan_visitds(scn,
3129 dp->dp_origin_snap->ds_object, tx);
3131 ASSERT(!scn->scn_suspending);
3132 } else if (scn->scn_phys.scn_bookmark.zb_objset !=
3133 ZB_DESTROYED_OBJSET) {
3134 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
3136 * If we were suspended, continue from here. Note if the
3137 * ds we were suspended on was deleted, the zb_objset may
3138 * be -1, so we will skip this and find a new objset
3139 * below.
3141 dsl_scan_visitds(scn, dsobj, tx);
3142 if (scn->scn_suspending)
3143 return;
3147 * In case we suspended right at the end of the ds, zero the
3148 * bookmark so we don't think that we're still trying to resume.
3150 memset(&scn->scn_phys.scn_bookmark, 0, sizeof (zbookmark_phys_t));
3153 * Keep pulling things out of the dataset avl queue. Updates to the
3154 * persistent zap-object-as-queue happen only at checkpoints.
3156 while ((sds = avl_first(&scn->scn_queue)) != NULL) {
3157 dsl_dataset_t *ds;
3158 uint64_t dsobj = sds->sds_dsobj;
3159 uint64_t txg = sds->sds_txg;
3161 /* dequeue and free the ds from the queue */
3162 scan_ds_queue_remove(scn, dsobj);
3163 sds = NULL;
3165 /* set up min / max txg */
3166 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
3167 if (txg != 0) {
3168 scn->scn_phys.scn_cur_min_txg =
3169 MAX(scn->scn_phys.scn_min_txg, txg);
3170 } else {
3171 scn->scn_phys.scn_cur_min_txg =
3172 MAX(scn->scn_phys.scn_min_txg,
3173 dsl_dataset_phys(ds)->ds_prev_snap_txg);
3175 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
3176 dsl_dataset_rele(ds, FTAG);
3178 dsl_scan_visitds(scn, dsobj, tx);
3179 if (scn->scn_suspending)
3180 return;
3183 /* No more objsets to fetch, we're done */
3184 scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
3185 ASSERT0(scn->scn_suspending);
3188 static uint64_t
3189 dsl_scan_count_data_disks(spa_t *spa)
3191 vdev_t *rvd = spa->spa_root_vdev;
3192 uint64_t i, leaves = 0;
3194 for (i = 0; i < rvd->vdev_children; i++) {
3195 vdev_t *vd = rvd->vdev_child[i];
3196 if (vd->vdev_islog || vd->vdev_isspare || vd->vdev_isl2cache)
3197 continue;
3198 leaves += vdev_get_ndisks(vd) - vdev_get_nparity(vd);
3200 return (leaves);
3203 static void
3204 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
3206 int i;
3207 uint64_t cur_size = 0;
3209 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3210 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
3213 q->q_total_zio_size_this_txg += cur_size;
3214 q->q_zios_this_txg++;
3217 static void
3218 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
3219 uint64_t end)
3221 q->q_total_seg_size_this_txg += end - start;
3222 q->q_segs_this_txg++;
3225 static boolean_t
3226 scan_io_queue_check_suspend(dsl_scan_t *scn)
3228 /* See comment in dsl_scan_check_suspend() */
3229 uint64_t curr_time_ns = gethrtime();
3230 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
3231 uint64_t sync_time_ns = curr_time_ns -
3232 scn->scn_dp->dp_spa->spa_sync_starttime;
3233 uint64_t dirty_min_bytes = zfs_dirty_data_max *
3234 zfs_vdev_async_write_active_min_dirty_percent / 100;
3235 uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
3236 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
3238 return ((NSEC2MSEC(scan_time_ns) > mintime &&
3239 (scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||
3240 txg_sync_waiting(scn->scn_dp) ||
3241 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
3242 spa_shutting_down(scn->scn_dp->dp_spa));
3246 * Given a list of scan_io_t's in io_list, this issues the I/Os out to
3247 * disk. This consumes the io_list and frees the scan_io_t's. This is
3248 * called when emptying queues, either when we're up against the memory
3249 * limit or when we have finished scanning. Returns B_TRUE if we stopped
3250 * processing the list before we finished. Any sios that were not issued
3251 * will remain in the io_list.
3253 static boolean_t
3254 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
3256 dsl_scan_t *scn = queue->q_scn;
3257 scan_io_t *sio;
3258 boolean_t suspended = B_FALSE;
3260 while ((sio = list_head(io_list)) != NULL) {
3261 blkptr_t bp;
3263 if (scan_io_queue_check_suspend(scn)) {
3264 suspended = B_TRUE;
3265 break;
3268 sio2bp(sio, &bp);
3269 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
3270 &sio->sio_zb, queue);
3271 (void) list_remove_head(io_list);
3272 scan_io_queues_update_zio_stats(queue, &bp);
3273 sio_free(sio);
3275 return (suspended);
3279 * This function removes sios from an IO queue which reside within a given
3280 * range_seg_t and inserts them (in offset order) into a list. Note that
3281 * we only ever return a maximum of 32 sios at once. If there are more sios
3282 * to process within this segment that did not make it onto the list we
3283 * return B_TRUE and otherwise B_FALSE.
3285 static boolean_t
3286 scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list)
3288 scan_io_t *srch_sio, *sio, *next_sio;
3289 avl_index_t idx;
3290 uint_t num_sios = 0;
3291 int64_t bytes_issued = 0;
3293 ASSERT(rs != NULL);
3294 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3296 srch_sio = sio_alloc(1);
3297 srch_sio->sio_nr_dvas = 1;
3298 SIO_SET_OFFSET(srch_sio, rs_get_start(rs, queue->q_exts_by_addr));
3301 * The exact start of the extent might not contain any matching zios,
3302 * so if that's the case, examine the next one in the tree.
3304 sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
3305 sio_free(srch_sio);
3307 if (sio == NULL)
3308 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
3310 while (sio != NULL && SIO_GET_OFFSET(sio) < rs_get_end(rs,
3311 queue->q_exts_by_addr) && num_sios <= 32) {
3312 ASSERT3U(SIO_GET_OFFSET(sio), >=, rs_get_start(rs,
3313 queue->q_exts_by_addr));
3314 ASSERT3U(SIO_GET_END_OFFSET(sio), <=, rs_get_end(rs,
3315 queue->q_exts_by_addr));
3317 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
3318 avl_remove(&queue->q_sios_by_addr, sio);
3319 if (avl_is_empty(&queue->q_sios_by_addr))
3320 atomic_add_64(&queue->q_scn->scn_queues_pending, -1);
3321 queue->q_sio_memused -= SIO_GET_MUSED(sio);
3323 bytes_issued += SIO_GET_ASIZE(sio);
3324 num_sios++;
3325 list_insert_tail(list, sio);
3326 sio = next_sio;
3330 * We limit the number of sios we process at once to 32 to avoid
3331 * biting off more than we can chew. If we didn't take everything
3332 * in the segment we update it to reflect the work we were able to
3333 * complete. Otherwise, we remove it from the range tree entirely.
3335 if (sio != NULL && SIO_GET_OFFSET(sio) < rs_get_end(rs,
3336 queue->q_exts_by_addr)) {
3337 range_tree_adjust_fill(queue->q_exts_by_addr, rs,
3338 -bytes_issued);
3339 range_tree_resize_segment(queue->q_exts_by_addr, rs,
3340 SIO_GET_OFFSET(sio), rs_get_end(rs,
3341 queue->q_exts_by_addr) - SIO_GET_OFFSET(sio));
3342 queue->q_last_ext_addr = SIO_GET_OFFSET(sio);
3343 return (B_TRUE);
3344 } else {
3345 uint64_t rstart = rs_get_start(rs, queue->q_exts_by_addr);
3346 uint64_t rend = rs_get_end(rs, queue->q_exts_by_addr);
3347 range_tree_remove(queue->q_exts_by_addr, rstart, rend - rstart);
3348 queue->q_last_ext_addr = -1;
3349 return (B_FALSE);
3354 * This is called from the queue emptying thread and selects the next
3355 * extent from which we are to issue I/Os. The behavior of this function
3356 * depends on the state of the scan, the current memory consumption and
3357 * whether or not we are performing a scan shutdown.
3358 * 1) We select extents in an elevator algorithm (LBA-order) if the scan
3359 * needs to perform a checkpoint
3360 * 2) We select the largest available extent if we are up against the
3361 * memory limit.
3362 * 3) Otherwise we don't select any extents.
3364 static range_seg_t *
3365 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
3367 dsl_scan_t *scn = queue->q_scn;
3368 range_tree_t *rt = queue->q_exts_by_addr;
3370 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3371 ASSERT(scn->scn_is_sorted);
3373 if (!scn->scn_checkpointing && !scn->scn_clearing)
3374 return (NULL);
3377 * During normal clearing, we want to issue our largest segments
3378 * first, keeping IO as sequential as possible, and leaving the
3379 * smaller extents for later with the hope that they might eventually
3380 * grow to larger sequential segments. However, when the scan is
3381 * checkpointing, no new extents will be added to the sorting queue,
3382 * so the way we are sorted now is as good as it will ever get.
3383 * In this case, we instead switch to issuing extents in LBA order.
3385 if ((zfs_scan_issue_strategy < 1 && scn->scn_checkpointing) ||
3386 zfs_scan_issue_strategy == 1)
3387 return (range_tree_first(rt));
3390 * Try to continue previous extent if it is not completed yet. After
3391 * shrink in scan_io_queue_gather() it may no longer be the best, but
3392 * otherwise we leave shorter remnant every txg.
3394 uint64_t start;
3395 uint64_t size = 1ULL << rt->rt_shift;
3396 range_seg_t *addr_rs;
3397 if (queue->q_last_ext_addr != -1) {
3398 start = queue->q_last_ext_addr;
3399 addr_rs = range_tree_find(rt, start, size);
3400 if (addr_rs != NULL)
3401 return (addr_rs);
3405 * Nothing to continue, so find new best extent.
3407 uint64_t *v = zfs_btree_first(&queue->q_exts_by_size, NULL);
3408 if (v == NULL)
3409 return (NULL);
3410 queue->q_last_ext_addr = start = *v << rt->rt_shift;
3413 * We need to get the original entry in the by_addr tree so we can
3414 * modify it.
3416 addr_rs = range_tree_find(rt, start, size);
3417 ASSERT3P(addr_rs, !=, NULL);
3418 ASSERT3U(rs_get_start(addr_rs, rt), ==, start);
3419 ASSERT3U(rs_get_end(addr_rs, rt), >, start);
3420 return (addr_rs);
3423 static void
3424 scan_io_queues_run_one(void *arg)
3426 dsl_scan_io_queue_t *queue = arg;
3427 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
3428 boolean_t suspended = B_FALSE;
3429 range_seg_t *rs;
3430 scan_io_t *sio;
3431 zio_t *zio;
3432 list_t sio_list;
3434 ASSERT(queue->q_scn->scn_is_sorted);
3436 list_create(&sio_list, sizeof (scan_io_t),
3437 offsetof(scan_io_t, sio_nodes.sio_list_node));
3438 zio = zio_null(queue->q_scn->scn_zio_root, queue->q_scn->scn_dp->dp_spa,
3439 NULL, NULL, NULL, ZIO_FLAG_CANFAIL);
3440 mutex_enter(q_lock);
3441 queue->q_zio = zio;
3443 /* Calculate maximum in-flight bytes for this vdev. */
3444 queue->q_maxinflight_bytes = MAX(1, zfs_scan_vdev_limit *
3445 (vdev_get_ndisks(queue->q_vd) - vdev_get_nparity(queue->q_vd)));
3447 /* reset per-queue scan statistics for this txg */
3448 queue->q_total_seg_size_this_txg = 0;
3449 queue->q_segs_this_txg = 0;
3450 queue->q_total_zio_size_this_txg = 0;
3451 queue->q_zios_this_txg = 0;
3453 /* loop until we run out of time or sios */
3454 while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {
3455 uint64_t seg_start = 0, seg_end = 0;
3456 boolean_t more_left;
3458 ASSERT(list_is_empty(&sio_list));
3460 /* loop while we still have sios left to process in this rs */
3461 do {
3462 scan_io_t *first_sio, *last_sio;
3465 * We have selected which extent needs to be
3466 * processed next. Gather up the corresponding sios.
3468 more_left = scan_io_queue_gather(queue, rs, &sio_list);
3469 ASSERT(!list_is_empty(&sio_list));
3470 first_sio = list_head(&sio_list);
3471 last_sio = list_tail(&sio_list);
3473 seg_end = SIO_GET_END_OFFSET(last_sio);
3474 if (seg_start == 0)
3475 seg_start = SIO_GET_OFFSET(first_sio);
3478 * Issuing sios can take a long time so drop the
3479 * queue lock. The sio queue won't be updated by
3480 * other threads since we're in syncing context so
3481 * we can be sure that our trees will remain exactly
3482 * as we left them.
3484 mutex_exit(q_lock);
3485 suspended = scan_io_queue_issue(queue, &sio_list);
3486 mutex_enter(q_lock);
3488 if (suspended)
3489 break;
3490 } while (more_left);
3492 /* update statistics for debugging purposes */
3493 scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
3495 if (suspended)
3496 break;
3500 * If we were suspended in the middle of processing,
3501 * requeue any unfinished sios and exit.
3503 while ((sio = list_remove_head(&sio_list)) != NULL)
3504 scan_io_queue_insert_impl(queue, sio);
3506 queue->q_zio = NULL;
3507 mutex_exit(q_lock);
3508 zio_nowait(zio);
3509 list_destroy(&sio_list);
3513 * Performs an emptying run on all scan queues in the pool. This just
3514 * punches out one thread per top-level vdev, each of which processes
3515 * only that vdev's scan queue. We can parallelize the I/O here because
3516 * we know that each queue's I/Os only affect its own top-level vdev.
3518 * This function waits for the queue runs to complete, and must be
3519 * called from dsl_scan_sync (or in general, syncing context).
3521 static void
3522 scan_io_queues_run(dsl_scan_t *scn)
3524 spa_t *spa = scn->scn_dp->dp_spa;
3526 ASSERT(scn->scn_is_sorted);
3527 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3529 if (scn->scn_queues_pending == 0)
3530 return;
3532 if (scn->scn_taskq == NULL) {
3533 int nthreads = spa->spa_root_vdev->vdev_children;
3536 * We need to make this taskq *always* execute as many
3537 * threads in parallel as we have top-level vdevs and no
3538 * less, otherwise strange serialization of the calls to
3539 * scan_io_queues_run_one can occur during spa_sync runs
3540 * and that significantly impacts performance.
3542 scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,
3543 minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);
3546 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3547 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3549 mutex_enter(&vd->vdev_scan_io_queue_lock);
3550 if (vd->vdev_scan_io_queue != NULL) {
3551 VERIFY(taskq_dispatch(scn->scn_taskq,
3552 scan_io_queues_run_one, vd->vdev_scan_io_queue,
3553 TQ_SLEEP) != TASKQID_INVALID);
3555 mutex_exit(&vd->vdev_scan_io_queue_lock);
3559 * Wait for the queues to finish issuing their IOs for this run
3560 * before we return. There may still be IOs in flight at this
3561 * point.
3563 taskq_wait(scn->scn_taskq);
3566 static boolean_t
3567 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
3569 uint64_t elapsed_nanosecs;
3571 if (zfs_recover)
3572 return (B_FALSE);
3574 if (zfs_async_block_max_blocks != 0 &&
3575 scn->scn_visited_this_txg >= zfs_async_block_max_blocks) {
3576 return (B_TRUE);
3579 if (zfs_max_async_dedup_frees != 0 &&
3580 scn->scn_dedup_frees_this_txg >= zfs_max_async_dedup_frees) {
3581 return (B_TRUE);
3584 elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
3585 return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
3586 (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
3587 txg_sync_waiting(scn->scn_dp)) ||
3588 spa_shutting_down(scn->scn_dp->dp_spa));
3591 static int
3592 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3594 dsl_scan_t *scn = arg;
3596 if (!scn->scn_is_bptree ||
3597 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
3598 if (dsl_scan_async_block_should_pause(scn))
3599 return (SET_ERROR(ERESTART));
3602 zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
3603 dmu_tx_get_txg(tx), bp, 0));
3604 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
3605 -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
3606 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
3607 scn->scn_visited_this_txg++;
3608 if (BP_GET_DEDUP(bp))
3609 scn->scn_dedup_frees_this_txg++;
3610 return (0);
3613 static void
3614 dsl_scan_update_stats(dsl_scan_t *scn)
3616 spa_t *spa = scn->scn_dp->dp_spa;
3617 uint64_t i;
3618 uint64_t seg_size_total = 0, zio_size_total = 0;
3619 uint64_t seg_count_total = 0, zio_count_total = 0;
3621 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3622 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3623 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
3625 if (queue == NULL)
3626 continue;
3628 seg_size_total += queue->q_total_seg_size_this_txg;
3629 zio_size_total += queue->q_total_zio_size_this_txg;
3630 seg_count_total += queue->q_segs_this_txg;
3631 zio_count_total += queue->q_zios_this_txg;
3634 if (seg_count_total == 0 || zio_count_total == 0) {
3635 scn->scn_avg_seg_size_this_txg = 0;
3636 scn->scn_avg_zio_size_this_txg = 0;
3637 scn->scn_segs_this_txg = 0;
3638 scn->scn_zios_this_txg = 0;
3639 return;
3642 scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
3643 scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
3644 scn->scn_segs_this_txg = seg_count_total;
3645 scn->scn_zios_this_txg = zio_count_total;
3648 static int
3649 bpobj_dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3650 dmu_tx_t *tx)
3652 ASSERT(!bp_freed);
3653 return (dsl_scan_free_block_cb(arg, bp, tx));
3656 static int
3657 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3658 dmu_tx_t *tx)
3660 ASSERT(!bp_freed);
3661 dsl_scan_t *scn = arg;
3662 const dva_t *dva = &bp->blk_dva[0];
3664 if (dsl_scan_async_block_should_pause(scn))
3665 return (SET_ERROR(ERESTART));
3667 spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
3668 DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
3669 DVA_GET_ASIZE(dva), tx);
3670 scn->scn_visited_this_txg++;
3671 return (0);
3674 boolean_t
3675 dsl_scan_active(dsl_scan_t *scn)
3677 spa_t *spa = scn->scn_dp->dp_spa;
3678 uint64_t used = 0, comp, uncomp;
3679 boolean_t clones_left;
3681 if (spa->spa_load_state != SPA_LOAD_NONE)
3682 return (B_FALSE);
3683 if (spa_shutting_down(spa))
3684 return (B_FALSE);
3685 if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
3686 (scn->scn_async_destroying && !scn->scn_async_stalled))
3687 return (B_TRUE);
3689 if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
3690 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
3691 &used, &comp, &uncomp);
3693 clones_left = spa_livelist_delete_check(spa);
3694 return ((used != 0) || (clones_left));
3697 boolean_t
3698 dsl_errorscrub_active(dsl_scan_t *scn)
3700 spa_t *spa = scn->scn_dp->dp_spa;
3701 if (spa->spa_load_state != SPA_LOAD_NONE)
3702 return (B_FALSE);
3703 if (spa_shutting_down(spa))
3704 return (B_FALSE);
3705 if (dsl_errorscrubbing(scn->scn_dp))
3706 return (B_TRUE);
3707 return (B_FALSE);
3710 static boolean_t
3711 dsl_scan_check_deferred(vdev_t *vd)
3713 boolean_t need_resilver = B_FALSE;
3715 for (int c = 0; c < vd->vdev_children; c++) {
3716 need_resilver |=
3717 dsl_scan_check_deferred(vd->vdev_child[c]);
3720 if (!vdev_is_concrete(vd) || vd->vdev_aux ||
3721 !vd->vdev_ops->vdev_op_leaf)
3722 return (need_resilver);
3724 if (!vd->vdev_resilver_deferred)
3725 need_resilver = B_TRUE;
3727 return (need_resilver);
3730 static boolean_t
3731 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
3732 uint64_t phys_birth)
3734 vdev_t *vd;
3736 vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3738 if (vd->vdev_ops == &vdev_indirect_ops) {
3740 * The indirect vdev can point to multiple
3741 * vdevs. For simplicity, always create
3742 * the resilver zio_t. zio_vdev_io_start()
3743 * will bypass the child resilver i/o's if
3744 * they are on vdevs that don't have DTL's.
3746 return (B_TRUE);
3749 if (DVA_GET_GANG(dva)) {
3751 * Gang members may be spread across multiple
3752 * vdevs, so the best estimate we have is the
3753 * scrub range, which has already been checked.
3754 * XXX -- it would be better to change our
3755 * allocation policy to ensure that all
3756 * gang members reside on the same vdev.
3758 return (B_TRUE);
3762 * Check if the top-level vdev must resilver this offset.
3763 * When the offset does not intersect with a dirty leaf DTL
3764 * then it may be possible to skip the resilver IO. The psize
3765 * is provided instead of asize to simplify the check for RAIDZ.
3767 if (!vdev_dtl_need_resilver(vd, dva, psize, phys_birth))
3768 return (B_FALSE);
3771 * Check that this top-level vdev has a device under it which
3772 * is resilvering and is not deferred.
3774 if (!dsl_scan_check_deferred(vd))
3775 return (B_FALSE);
3777 return (B_TRUE);
3780 static int
3781 dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)
3783 dsl_scan_t *scn = dp->dp_scan;
3784 spa_t *spa = dp->dp_spa;
3785 int err = 0;
3787 if (spa_suspend_async_destroy(spa))
3788 return (0);
3790 if (zfs_free_bpobj_enabled &&
3791 spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3792 scn->scn_is_bptree = B_FALSE;
3793 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
3794 scn->scn_zio_root = zio_root(spa, NULL,
3795 NULL, ZIO_FLAG_MUSTSUCCEED);
3796 err = bpobj_iterate(&dp->dp_free_bpobj,
3797 bpobj_dsl_scan_free_block_cb, scn, tx);
3798 VERIFY0(zio_wait(scn->scn_zio_root));
3799 scn->scn_zio_root = NULL;
3801 if (err != 0 && err != ERESTART)
3802 zfs_panic_recover("error %u from bpobj_iterate()", err);
3805 if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3806 ASSERT(scn->scn_async_destroying);
3807 scn->scn_is_bptree = B_TRUE;
3808 scn->scn_zio_root = zio_root(spa, NULL,
3809 NULL, ZIO_FLAG_MUSTSUCCEED);
3810 err = bptree_iterate(dp->dp_meta_objset,
3811 dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3812 VERIFY0(zio_wait(scn->scn_zio_root));
3813 scn->scn_zio_root = NULL;
3815 if (err == EIO || err == ECKSUM) {
3816 err = 0;
3817 } else if (err != 0 && err != ERESTART) {
3818 zfs_panic_recover("error %u from "
3819 "traverse_dataset_destroyed()", err);
3822 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
3823 /* finished; deactivate async destroy feature */
3824 spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
3825 ASSERT(!spa_feature_is_active(spa,
3826 SPA_FEATURE_ASYNC_DESTROY));
3827 VERIFY0(zap_remove(dp->dp_meta_objset,
3828 DMU_POOL_DIRECTORY_OBJECT,
3829 DMU_POOL_BPTREE_OBJ, tx));
3830 VERIFY0(bptree_free(dp->dp_meta_objset,
3831 dp->dp_bptree_obj, tx));
3832 dp->dp_bptree_obj = 0;
3833 scn->scn_async_destroying = B_FALSE;
3834 scn->scn_async_stalled = B_FALSE;
3835 } else {
3837 * If we didn't make progress, mark the async
3838 * destroy as stalled, so that we will not initiate
3839 * a spa_sync() on its behalf. Note that we only
3840 * check this if we are not finished, because if the
3841 * bptree had no blocks for us to visit, we can
3842 * finish without "making progress".
3844 scn->scn_async_stalled =
3845 (scn->scn_visited_this_txg == 0);
3848 if (scn->scn_visited_this_txg) {
3849 zfs_dbgmsg("freed %llu blocks in %llums from "
3850 "free_bpobj/bptree on %s in txg %llu; err=%u",
3851 (longlong_t)scn->scn_visited_this_txg,
3852 (longlong_t)
3853 NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
3854 spa->spa_name, (longlong_t)tx->tx_txg, err);
3855 scn->scn_visited_this_txg = 0;
3856 scn->scn_dedup_frees_this_txg = 0;
3859 * Write out changes to the DDT and the BRT that may be required
3860 * as a result of the blocks freed. This ensures that the DDT
3861 * and the BRT are clean when a scrub/resilver runs.
3863 ddt_sync(spa, tx->tx_txg);
3864 brt_sync(spa, tx->tx_txg);
3866 if (err != 0)
3867 return (err);
3868 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3869 zfs_free_leak_on_eio &&
3870 (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
3871 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
3872 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
3874 * We have finished background destroying, but there is still
3875 * some space left in the dp_free_dir. Transfer this leaked
3876 * space to the dp_leak_dir.
3878 if (dp->dp_leak_dir == NULL) {
3879 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
3880 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
3881 LEAK_DIR_NAME, tx);
3882 VERIFY0(dsl_pool_open_special_dir(dp,
3883 LEAK_DIR_NAME, &dp->dp_leak_dir));
3884 rrw_exit(&dp->dp_config_rwlock, FTAG);
3886 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
3887 dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3888 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3889 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3890 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
3891 -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3892 -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3893 -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3896 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3897 !spa_livelist_delete_check(spa)) {
3898 /* finished; verify that space accounting went to zero */
3899 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
3900 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
3901 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
3904 spa_notify_waiters(spa);
3906 EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
3907 0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3908 DMU_POOL_OBSOLETE_BPOBJ));
3909 if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3910 ASSERT(spa_feature_is_active(dp->dp_spa,
3911 SPA_FEATURE_OBSOLETE_COUNTS));
3913 scn->scn_is_bptree = B_FALSE;
3914 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
3915 err = bpobj_iterate(&dp->dp_obsolete_bpobj,
3916 dsl_scan_obsolete_block_cb, scn, tx);
3917 if (err != 0 && err != ERESTART)
3918 zfs_panic_recover("error %u from bpobj_iterate()", err);
3920 if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
3921 dsl_pool_destroy_obsolete_bpobj(dp, tx);
3923 return (0);
3926 static void
3927 name_to_bookmark(char *buf, zbookmark_phys_t *zb)
3929 zb->zb_objset = zfs_strtonum(buf, &buf);
3930 ASSERT(*buf == ':');
3931 zb->zb_object = zfs_strtonum(buf + 1, &buf);
3932 ASSERT(*buf == ':');
3933 zb->zb_level = (int)zfs_strtonum(buf + 1, &buf);
3934 ASSERT(*buf == ':');
3935 zb->zb_blkid = zfs_strtonum(buf + 1, &buf);
3936 ASSERT(*buf == '\0');
3939 static void
3940 name_to_object(char *buf, uint64_t *obj)
3942 *obj = zfs_strtonum(buf, &buf);
3943 ASSERT(*buf == '\0');
3946 static void
3947 read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb)
3949 dsl_pool_t *dp = scn->scn_dp;
3950 dsl_dataset_t *ds;
3951 objset_t *os;
3952 if (dsl_dataset_hold_obj(dp, zb.zb_objset, FTAG, &ds) != 0)
3953 return;
3955 if (dmu_objset_from_ds(ds, &os) != 0) {
3956 dsl_dataset_rele(ds, FTAG);
3957 return;
3961 * If the key is not loaded dbuf_dnode_findbp() will error out with
3962 * EACCES. However in that case dnode_hold() will eventually call
3963 * dbuf_read()->zio_wait() which may call spa_log_error(). This will
3964 * lead to a deadlock due to us holding the mutex spa_errlist_lock.
3965 * Avoid this by checking here if the keys are loaded, if not return.
3966 * If the keys are not loaded the head_errlog feature is meaningless
3967 * as we cannot figure out the birth txg of the block pointer.
3969 if (dsl_dataset_get_keystatus(ds->ds_dir) ==
3970 ZFS_KEYSTATUS_UNAVAILABLE) {
3971 dsl_dataset_rele(ds, FTAG);
3972 return;
3975 dnode_t *dn;
3976 blkptr_t bp;
3978 if (dnode_hold(os, zb.zb_object, FTAG, &dn) != 0) {
3979 dsl_dataset_rele(ds, FTAG);
3980 return;
3983 rw_enter(&dn->dn_struct_rwlock, RW_READER);
3984 int error = dbuf_dnode_findbp(dn, zb.zb_level, zb.zb_blkid, &bp, NULL,
3985 NULL);
3987 if (error) {
3988 rw_exit(&dn->dn_struct_rwlock);
3989 dnode_rele(dn, FTAG);
3990 dsl_dataset_rele(ds, FTAG);
3991 return;
3994 if (!error && BP_IS_HOLE(&bp)) {
3995 rw_exit(&dn->dn_struct_rwlock);
3996 dnode_rele(dn, FTAG);
3997 dsl_dataset_rele(ds, FTAG);
3998 return;
4001 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW |
4002 ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB;
4004 /* If it's an intent log block, failure is expected. */
4005 if (zb.zb_level == ZB_ZIL_LEVEL)
4006 zio_flags |= ZIO_FLAG_SPECULATIVE;
4008 ASSERT(!BP_IS_EMBEDDED(&bp));
4009 scan_exec_io(dp, &bp, zio_flags, &zb, NULL);
4010 rw_exit(&dn->dn_struct_rwlock);
4011 dnode_rele(dn, FTAG);
4012 dsl_dataset_rele(ds, FTAG);
4016 * We keep track of the scrubbed error blocks in "count". This will be used
4017 * when deciding whether we exceeded zfs_scrub_error_blocks_per_txg. This
4018 * function is modelled after check_filesystem().
4020 static int
4021 scrub_filesystem(spa_t *spa, uint64_t fs, zbookmark_err_phys_t *zep,
4022 int *count)
4024 dsl_dataset_t *ds;
4025 dsl_pool_t *dp = spa->spa_dsl_pool;
4026 dsl_scan_t *scn = dp->dp_scan;
4028 int error = dsl_dataset_hold_obj(dp, fs, FTAG, &ds);
4029 if (error != 0)
4030 return (error);
4032 uint64_t latest_txg;
4033 uint64_t txg_to_consider = spa->spa_syncing_txg;
4034 boolean_t check_snapshot = B_TRUE;
4036 error = find_birth_txg(ds, zep, &latest_txg);
4039 * If find_birth_txg() errors out, then err on the side of caution and
4040 * proceed. In worst case scenario scrub all objects. If zep->zb_birth
4041 * is 0 (e.g. in case of encryption with unloaded keys) also proceed to
4042 * scrub all objects.
4044 if (error == 0 && zep->zb_birth == latest_txg) {
4045 /* Block neither free nor re written. */
4046 zbookmark_phys_t zb;
4047 zep_to_zb(fs, zep, &zb);
4048 scn->scn_zio_root = zio_root(spa, NULL, NULL,
4049 ZIO_FLAG_CANFAIL);
4050 /* We have already acquired the config lock for spa */
4051 read_by_block_level(scn, zb);
4053 (void) zio_wait(scn->scn_zio_root);
4054 scn->scn_zio_root = NULL;
4056 scn->errorscrub_phys.dep_examined++;
4057 scn->errorscrub_phys.dep_to_examine--;
4058 (*count)++;
4059 if ((*count) == zfs_scrub_error_blocks_per_txg ||
4060 dsl_error_scrub_check_suspend(scn, &zb)) {
4061 dsl_dataset_rele(ds, FTAG);
4062 return (SET_ERROR(EFAULT));
4065 check_snapshot = B_FALSE;
4066 } else if (error == 0) {
4067 txg_to_consider = latest_txg;
4071 * Retrieve the number of snapshots if the dataset is not a snapshot.
4073 uint64_t snap_count = 0;
4074 if (dsl_dataset_phys(ds)->ds_snapnames_zapobj != 0) {
4076 error = zap_count(spa->spa_meta_objset,
4077 dsl_dataset_phys(ds)->ds_snapnames_zapobj, &snap_count);
4079 if (error != 0) {
4080 dsl_dataset_rele(ds, FTAG);
4081 return (error);
4085 if (snap_count == 0) {
4086 /* Filesystem without snapshots. */
4087 dsl_dataset_rele(ds, FTAG);
4088 return (0);
4091 uint64_t snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4092 uint64_t snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4094 dsl_dataset_rele(ds, FTAG);
4096 /* Check only snapshots created from this file system. */
4097 while (snap_obj != 0 && zep->zb_birth < snap_obj_txg &&
4098 snap_obj_txg <= txg_to_consider) {
4100 error = dsl_dataset_hold_obj(dp, snap_obj, FTAG, &ds);
4101 if (error != 0)
4102 return (error);
4104 if (dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj != fs) {
4105 snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4106 snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4107 dsl_dataset_rele(ds, FTAG);
4108 continue;
4111 boolean_t affected = B_TRUE;
4112 if (check_snapshot) {
4113 uint64_t blk_txg;
4114 error = find_birth_txg(ds, zep, &blk_txg);
4117 * Scrub the snapshot also when zb_birth == 0 or when
4118 * find_birth_txg() returns an error.
4120 affected = (error == 0 && zep->zb_birth == blk_txg) ||
4121 (error != 0) || (zep->zb_birth == 0);
4124 /* Scrub snapshots. */
4125 if (affected) {
4126 zbookmark_phys_t zb;
4127 zep_to_zb(snap_obj, zep, &zb);
4128 scn->scn_zio_root = zio_root(spa, NULL, NULL,
4129 ZIO_FLAG_CANFAIL);
4130 /* We have already acquired the config lock for spa */
4131 read_by_block_level(scn, zb);
4133 (void) zio_wait(scn->scn_zio_root);
4134 scn->scn_zio_root = NULL;
4136 scn->errorscrub_phys.dep_examined++;
4137 scn->errorscrub_phys.dep_to_examine--;
4138 (*count)++;
4139 if ((*count) == zfs_scrub_error_blocks_per_txg ||
4140 dsl_error_scrub_check_suspend(scn, &zb)) {
4141 dsl_dataset_rele(ds, FTAG);
4142 return (EFAULT);
4145 snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4146 snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4147 dsl_dataset_rele(ds, FTAG);
4149 return (0);
4152 void
4153 dsl_errorscrub_sync(dsl_pool_t *dp, dmu_tx_t *tx)
4155 spa_t *spa = dp->dp_spa;
4156 dsl_scan_t *scn = dp->dp_scan;
4159 * Only process scans in sync pass 1.
4162 if (spa_sync_pass(spa) > 1)
4163 return;
4166 * If the spa is shutting down, then stop scanning. This will
4167 * ensure that the scan does not dirty any new data during the
4168 * shutdown phase.
4170 if (spa_shutting_down(spa))
4171 return;
4173 if (!dsl_errorscrub_active(scn) || dsl_errorscrub_is_paused(scn)) {
4174 return;
4177 if (dsl_scan_resilvering(scn->scn_dp)) {
4178 /* cancel the error scrub if resilver started */
4179 dsl_scan_cancel(scn->scn_dp);
4180 return;
4183 spa->spa_scrub_active = B_TRUE;
4184 scn->scn_sync_start_time = gethrtime();
4187 * zfs_scan_suspend_progress can be set to disable scrub progress.
4188 * See more detailed comment in dsl_scan_sync().
4190 if (zfs_scan_suspend_progress) {
4191 uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time;
4192 int mintime = zfs_scrub_min_time_ms;
4194 while (zfs_scan_suspend_progress &&
4195 !txg_sync_waiting(scn->scn_dp) &&
4196 !spa_shutting_down(scn->scn_dp->dp_spa) &&
4197 NSEC2MSEC(scan_time_ns) < mintime) {
4198 delay(hz);
4199 scan_time_ns = gethrtime() - scn->scn_sync_start_time;
4201 return;
4204 int i = 0;
4205 zap_attribute_t *za;
4206 zbookmark_phys_t *zb;
4207 boolean_t limit_exceeded = B_FALSE;
4209 za = zap_attribute_alloc();
4210 zb = kmem_zalloc(sizeof (zbookmark_phys_t), KM_SLEEP);
4212 if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
4213 for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;
4214 zap_cursor_advance(&scn->errorscrub_cursor)) {
4215 name_to_bookmark(za->za_name, zb);
4217 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4218 NULL, ZIO_FLAG_CANFAIL);
4219 dsl_pool_config_enter(dp, FTAG);
4220 read_by_block_level(scn, *zb);
4221 dsl_pool_config_exit(dp, FTAG);
4223 (void) zio_wait(scn->scn_zio_root);
4224 scn->scn_zio_root = NULL;
4226 scn->errorscrub_phys.dep_examined += 1;
4227 scn->errorscrub_phys.dep_to_examine -= 1;
4228 i++;
4229 if (i == zfs_scrub_error_blocks_per_txg ||
4230 dsl_error_scrub_check_suspend(scn, zb)) {
4231 limit_exceeded = B_TRUE;
4232 break;
4236 if (!limit_exceeded)
4237 dsl_errorscrub_done(scn, B_TRUE, tx);
4239 dsl_errorscrub_sync_state(scn, tx);
4240 zap_attribute_free(za);
4241 kmem_free(zb, sizeof (*zb));
4242 return;
4245 int error = 0;
4246 for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;
4247 zap_cursor_advance(&scn->errorscrub_cursor)) {
4249 zap_cursor_t *head_ds_cursor;
4250 zap_attribute_t *head_ds_attr;
4251 zbookmark_err_phys_t head_ds_block;
4253 head_ds_cursor = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);
4254 head_ds_attr = zap_attribute_alloc();
4256 uint64_t head_ds_err_obj = za->za_first_integer;
4257 uint64_t head_ds;
4258 name_to_object(za->za_name, &head_ds);
4259 boolean_t config_held = B_FALSE;
4260 uint64_t top_affected_fs;
4262 for (zap_cursor_init(head_ds_cursor, spa->spa_meta_objset,
4263 head_ds_err_obj); zap_cursor_retrieve(head_ds_cursor,
4264 head_ds_attr) == 0; zap_cursor_advance(head_ds_cursor)) {
4266 name_to_errphys(head_ds_attr->za_name, &head_ds_block);
4269 * In case we are called from spa_sync the pool
4270 * config is already held.
4272 if (!dsl_pool_config_held(dp)) {
4273 dsl_pool_config_enter(dp, FTAG);
4274 config_held = B_TRUE;
4277 error = find_top_affected_fs(spa,
4278 head_ds, &head_ds_block, &top_affected_fs);
4279 if (error)
4280 break;
4282 error = scrub_filesystem(spa, top_affected_fs,
4283 &head_ds_block, &i);
4285 if (error == SET_ERROR(EFAULT)) {
4286 limit_exceeded = B_TRUE;
4287 break;
4291 zap_cursor_fini(head_ds_cursor);
4292 kmem_free(head_ds_cursor, sizeof (*head_ds_cursor));
4293 zap_attribute_free(head_ds_attr);
4295 if (config_held)
4296 dsl_pool_config_exit(dp, FTAG);
4299 zap_attribute_free(za);
4300 kmem_free(zb, sizeof (*zb));
4301 if (!limit_exceeded)
4302 dsl_errorscrub_done(scn, B_TRUE, tx);
4304 dsl_errorscrub_sync_state(scn, tx);
4308 * This is the primary entry point for scans that is called from syncing
4309 * context. Scans must happen entirely during syncing context so that we
4310 * can guarantee that blocks we are currently scanning will not change out
4311 * from under us. While a scan is active, this function controls how quickly
4312 * transaction groups proceed, instead of the normal handling provided by
4313 * txg_sync_thread().
4315 void
4316 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
4318 int err = 0;
4319 dsl_scan_t *scn = dp->dp_scan;
4320 spa_t *spa = dp->dp_spa;
4321 state_sync_type_t sync_type = SYNC_OPTIONAL;
4322 int restart_early = 0;
4324 if (spa->spa_resilver_deferred) {
4325 uint64_t to_issue, issued;
4327 if (!spa_feature_is_active(dp->dp_spa,
4328 SPA_FEATURE_RESILVER_DEFER))
4329 spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
4332 * See print_scan_scrub_resilver_status() issued/total_i
4333 * @ cmd/zpool/zpool_main.c
4335 to_issue =
4336 scn->scn_phys.scn_to_examine - scn->scn_phys.scn_skipped;
4337 issued =
4338 scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
4339 restart_early =
4340 zfs_resilver_disable_defer ||
4341 (issued < (to_issue * zfs_resilver_defer_percent / 100));
4345 * Only process scans in sync pass 1.
4347 if (spa_sync_pass(spa) > 1)
4348 return;
4352 * Check for scn_restart_txg before checking spa_load_state, so
4353 * that we can restart an old-style scan while the pool is being
4354 * imported (see dsl_scan_init). We also restart scans if there
4355 * is a deferred resilver and the user has manually disabled
4356 * deferred resilvers via zfs_resilver_disable_defer, or if the
4357 * current scan progress is below zfs_resilver_defer_percent.
4359 if (dsl_scan_restarting(scn, tx) || restart_early) {
4360 setup_sync_arg_t setup_sync_arg = {
4361 .func = POOL_SCAN_SCRUB,
4362 .txgstart = 0,
4363 .txgend = 0,
4365 dsl_scan_done(scn, B_FALSE, tx);
4366 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4367 setup_sync_arg.func = POOL_SCAN_RESILVER;
4368 zfs_dbgmsg("restarting scan func=%u on %s txg=%llu early=%d",
4369 setup_sync_arg.func, dp->dp_spa->spa_name,
4370 (longlong_t)tx->tx_txg, restart_early);
4371 dsl_scan_setup_sync(&setup_sync_arg, tx);
4375 * If the spa is shutting down, then stop scanning. This will
4376 * ensure that the scan does not dirty any new data during the
4377 * shutdown phase.
4379 if (spa_shutting_down(spa))
4380 return;
4383 * If the scan is inactive due to a stalled async destroy, try again.
4385 if (!scn->scn_async_stalled && !dsl_scan_active(scn))
4386 return;
4388 /* reset scan statistics */
4389 scn->scn_visited_this_txg = 0;
4390 scn->scn_dedup_frees_this_txg = 0;
4391 scn->scn_holes_this_txg = 0;
4392 scn->scn_lt_min_this_txg = 0;
4393 scn->scn_gt_max_this_txg = 0;
4394 scn->scn_ddt_contained_this_txg = 0;
4395 scn->scn_objsets_visited_this_txg = 0;
4396 scn->scn_avg_seg_size_this_txg = 0;
4397 scn->scn_segs_this_txg = 0;
4398 scn->scn_avg_zio_size_this_txg = 0;
4399 scn->scn_zios_this_txg = 0;
4400 scn->scn_suspending = B_FALSE;
4401 scn->scn_sync_start_time = gethrtime();
4402 spa->spa_scrub_active = B_TRUE;
4405 * First process the async destroys. If we suspend, don't do
4406 * any scrubbing or resilvering. This ensures that there are no
4407 * async destroys while we are scanning, so the scan code doesn't
4408 * have to worry about traversing it. It is also faster to free the
4409 * blocks than to scrub them.
4411 err = dsl_process_async_destroys(dp, tx);
4412 if (err != 0)
4413 return;
4415 if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
4416 return;
4419 * Wait a few txgs after importing to begin scanning so that
4420 * we can get the pool imported quickly.
4422 if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)
4423 return;
4426 * zfs_scan_suspend_progress can be set to disable scan progress.
4427 * We don't want to spin the txg_sync thread, so we add a delay
4428 * here to simulate the time spent doing a scan. This is mostly
4429 * useful for testing and debugging.
4431 if (zfs_scan_suspend_progress) {
4432 uint64_t scan_time_ns = gethrtime() - scn->scn_sync_start_time;
4433 uint_t mintime = (scn->scn_phys.scn_func ==
4434 POOL_SCAN_RESILVER) ? zfs_resilver_min_time_ms :
4435 zfs_scrub_min_time_ms;
4437 while (zfs_scan_suspend_progress &&
4438 !txg_sync_waiting(scn->scn_dp) &&
4439 !spa_shutting_down(scn->scn_dp->dp_spa) &&
4440 NSEC2MSEC(scan_time_ns) < mintime) {
4441 delay(hz);
4442 scan_time_ns = gethrtime() - scn->scn_sync_start_time;
4444 return;
4448 * Disabled by default, set zfs_scan_report_txgs to report
4449 * average performance over the last zfs_scan_report_txgs TXGs.
4451 if (zfs_scan_report_txgs != 0 &&
4452 tx->tx_txg % zfs_scan_report_txgs == 0) {
4453 scn->scn_issued_before_pass += spa->spa_scan_pass_issued;
4454 spa_scan_stat_init(spa);
4458 * It is possible to switch from unsorted to sorted at any time,
4459 * but afterwards the scan will remain sorted unless reloaded from
4460 * a checkpoint after a reboot.
4462 if (!zfs_scan_legacy) {
4463 scn->scn_is_sorted = B_TRUE;
4464 if (scn->scn_last_checkpoint == 0)
4465 scn->scn_last_checkpoint = ddi_get_lbolt();
4469 * For sorted scans, determine what kind of work we will be doing
4470 * this txg based on our memory limitations and whether or not we
4471 * need to perform a checkpoint.
4473 if (scn->scn_is_sorted) {
4475 * If we are over our checkpoint interval, set scn_clearing
4476 * so that we can begin checkpointing immediately. The
4477 * checkpoint allows us to save a consistent bookmark
4478 * representing how much data we have scrubbed so far.
4479 * Otherwise, use the memory limit to determine if we should
4480 * scan for metadata or start issue scrub IOs. We accumulate
4481 * metadata until we hit our hard memory limit at which point
4482 * we issue scrub IOs until we are at our soft memory limit.
4484 if (scn->scn_checkpointing ||
4485 ddi_get_lbolt() - scn->scn_last_checkpoint >
4486 SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
4487 if (!scn->scn_checkpointing)
4488 zfs_dbgmsg("begin scan checkpoint for %s",
4489 spa->spa_name);
4491 scn->scn_checkpointing = B_TRUE;
4492 scn->scn_clearing = B_TRUE;
4493 } else {
4494 boolean_t should_clear = dsl_scan_should_clear(scn);
4495 if (should_clear && !scn->scn_clearing) {
4496 zfs_dbgmsg("begin scan clearing for %s",
4497 spa->spa_name);
4498 scn->scn_clearing = B_TRUE;
4499 } else if (!should_clear && scn->scn_clearing) {
4500 zfs_dbgmsg("finish scan clearing for %s",
4501 spa->spa_name);
4502 scn->scn_clearing = B_FALSE;
4505 } else {
4506 ASSERT0(scn->scn_checkpointing);
4507 ASSERT0(scn->scn_clearing);
4510 if (!scn->scn_clearing && scn->scn_done_txg == 0) {
4511 /* Need to scan metadata for more blocks to scrub */
4512 dsl_scan_phys_t *scnp = &scn->scn_phys;
4513 taskqid_t prefetch_tqid;
4516 * Calculate the max number of in-flight bytes for pool-wide
4517 * scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).
4518 * Limits for the issuing phase are done per top-level vdev and
4519 * are handled separately.
4521 scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,
4522 zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));
4524 if (scnp->scn_ddt_bookmark.ddb_class <=
4525 scnp->scn_ddt_class_max) {
4526 ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
4527 zfs_dbgmsg("doing scan sync for %s txg %llu; "
4528 "ddt bm=%llu/%llu/%llu/%llx",
4529 spa->spa_name,
4530 (longlong_t)tx->tx_txg,
4531 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
4532 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
4533 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
4534 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
4535 } else {
4536 zfs_dbgmsg("doing scan sync for %s txg %llu; "
4537 "bm=%llu/%llu/%llu/%llu",
4538 spa->spa_name,
4539 (longlong_t)tx->tx_txg,
4540 (longlong_t)scnp->scn_bookmark.zb_objset,
4541 (longlong_t)scnp->scn_bookmark.zb_object,
4542 (longlong_t)scnp->scn_bookmark.zb_level,
4543 (longlong_t)scnp->scn_bookmark.zb_blkid);
4546 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4547 NULL, ZIO_FLAG_CANFAIL);
4549 scn->scn_prefetch_stop = B_FALSE;
4550 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
4551 dsl_scan_prefetch_thread, scn, TQ_SLEEP);
4552 ASSERT(prefetch_tqid != TASKQID_INVALID);
4554 dsl_pool_config_enter(dp, FTAG);
4555 dsl_scan_visit(scn, tx);
4556 dsl_pool_config_exit(dp, FTAG);
4558 mutex_enter(&dp->dp_spa->spa_scrub_lock);
4559 scn->scn_prefetch_stop = B_TRUE;
4560 cv_broadcast(&spa->spa_scrub_io_cv);
4561 mutex_exit(&dp->dp_spa->spa_scrub_lock);
4563 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
4564 (void) zio_wait(scn->scn_zio_root);
4565 scn->scn_zio_root = NULL;
4567 zfs_dbgmsg("scan visited %llu blocks of %s in %llums "
4568 "(%llu os's, %llu holes, %llu < mintxg, "
4569 "%llu in ddt, %llu > maxtxg)",
4570 (longlong_t)scn->scn_visited_this_txg,
4571 spa->spa_name,
4572 (longlong_t)NSEC2MSEC(gethrtime() -
4573 scn->scn_sync_start_time),
4574 (longlong_t)scn->scn_objsets_visited_this_txg,
4575 (longlong_t)scn->scn_holes_this_txg,
4576 (longlong_t)scn->scn_lt_min_this_txg,
4577 (longlong_t)scn->scn_ddt_contained_this_txg,
4578 (longlong_t)scn->scn_gt_max_this_txg);
4580 if (!scn->scn_suspending) {
4581 ASSERT0(avl_numnodes(&scn->scn_queue));
4582 scn->scn_done_txg = tx->tx_txg + 1;
4583 if (scn->scn_is_sorted) {
4584 scn->scn_checkpointing = B_TRUE;
4585 scn->scn_clearing = B_TRUE;
4586 scn->scn_issued_before_pass +=
4587 spa->spa_scan_pass_issued;
4588 spa_scan_stat_init(spa);
4590 zfs_dbgmsg("scan complete for %s txg %llu",
4591 spa->spa_name,
4592 (longlong_t)tx->tx_txg);
4594 } else if (scn->scn_is_sorted && scn->scn_queues_pending != 0) {
4595 ASSERT(scn->scn_clearing);
4597 /* need to issue scrubbing IOs from per-vdev queues */
4598 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4599 NULL, ZIO_FLAG_CANFAIL);
4600 scan_io_queues_run(scn);
4601 (void) zio_wait(scn->scn_zio_root);
4602 scn->scn_zio_root = NULL;
4604 /* calculate and dprintf the current memory usage */
4605 (void) dsl_scan_should_clear(scn);
4606 dsl_scan_update_stats(scn);
4608 zfs_dbgmsg("scan issued %llu blocks for %s (%llu segs) "
4609 "in %llums (avg_block_size = %llu, avg_seg_size = %llu)",
4610 (longlong_t)scn->scn_zios_this_txg,
4611 spa->spa_name,
4612 (longlong_t)scn->scn_segs_this_txg,
4613 (longlong_t)NSEC2MSEC(gethrtime() -
4614 scn->scn_sync_start_time),
4615 (longlong_t)scn->scn_avg_zio_size_this_txg,
4616 (longlong_t)scn->scn_avg_seg_size_this_txg);
4617 } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
4618 /* Finished with everything. Mark the scrub as complete */
4619 zfs_dbgmsg("scan issuing complete txg %llu for %s",
4620 (longlong_t)tx->tx_txg,
4621 spa->spa_name);
4622 ASSERT3U(scn->scn_done_txg, !=, 0);
4623 ASSERT0(spa->spa_scrub_inflight);
4624 ASSERT0(scn->scn_queues_pending);
4625 dsl_scan_done(scn, B_TRUE, tx);
4626 sync_type = SYNC_MANDATORY;
4629 dsl_scan_sync_state(scn, tx, sync_type);
4632 static void
4633 count_block_issued(spa_t *spa, const blkptr_t *bp, boolean_t all)
4636 * Don't count embedded bp's, since we already did the work of
4637 * scanning these when we scanned the containing block.
4639 if (BP_IS_EMBEDDED(bp))
4640 return;
4643 * Update the spa's stats on how many bytes we have issued.
4644 * Sequential scrubs create a zio for each DVA of the bp. Each
4645 * of these will include all DVAs for repair purposes, but the
4646 * zio code will only try the first one unless there is an issue.
4647 * Therefore, we should only count the first DVA for these IOs.
4649 atomic_add_64(&spa->spa_scan_pass_issued,
4650 all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));
4653 static void
4654 count_block_skipped(dsl_scan_t *scn, const blkptr_t *bp, boolean_t all)
4656 if (BP_IS_EMBEDDED(bp))
4657 return;
4658 atomic_add_64(&scn->scn_phys.scn_skipped,
4659 all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));
4662 static void
4663 count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)
4666 * If we resume after a reboot, zab will be NULL; don't record
4667 * incomplete stats in that case.
4669 if (zab == NULL)
4670 return;
4672 for (int i = 0; i < 4; i++) {
4673 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
4674 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
4676 if (t & DMU_OT_NEWTYPE)
4677 t = DMU_OT_OTHER;
4678 zfs_blkstat_t *zb = &zab->zab_type[l][t];
4679 int equal;
4681 zb->zb_count++;
4682 zb->zb_asize += BP_GET_ASIZE(bp);
4683 zb->zb_lsize += BP_GET_LSIZE(bp);
4684 zb->zb_psize += BP_GET_PSIZE(bp);
4685 zb->zb_gangs += BP_COUNT_GANG(bp);
4687 switch (BP_GET_NDVAS(bp)) {
4688 case 2:
4689 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4690 DVA_GET_VDEV(&bp->blk_dva[1]))
4691 zb->zb_ditto_2_of_2_samevdev++;
4692 break;
4693 case 3:
4694 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4695 DVA_GET_VDEV(&bp->blk_dva[1])) +
4696 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4697 DVA_GET_VDEV(&bp->blk_dva[2])) +
4698 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
4699 DVA_GET_VDEV(&bp->blk_dva[2]));
4700 if (equal == 1)
4701 zb->zb_ditto_2_of_3_samevdev++;
4702 else if (equal == 3)
4703 zb->zb_ditto_3_of_3_samevdev++;
4704 break;
4709 static void
4710 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
4712 avl_index_t idx;
4713 dsl_scan_t *scn = queue->q_scn;
4715 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
4717 if (unlikely(avl_is_empty(&queue->q_sios_by_addr)))
4718 atomic_add_64(&scn->scn_queues_pending, 1);
4719 if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
4720 /* block is already scheduled for reading */
4721 sio_free(sio);
4722 return;
4724 avl_insert(&queue->q_sios_by_addr, sio, idx);
4725 queue->q_sio_memused += SIO_GET_MUSED(sio);
4726 range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio),
4727 SIO_GET_ASIZE(sio));
4731 * Given all the info we got from our metadata scanning process, we
4732 * construct a scan_io_t and insert it into the scan sorting queue. The
4733 * I/O must already be suitable for us to process. This is controlled
4734 * by dsl_scan_enqueue().
4736 static void
4737 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
4738 int zio_flags, const zbookmark_phys_t *zb)
4740 scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp));
4742 ASSERT0(BP_IS_GANG(bp));
4743 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
4745 bp2sio(bp, sio, dva_i);
4746 sio->sio_flags = zio_flags;
4747 sio->sio_zb = *zb;
4749 queue->q_last_ext_addr = -1;
4750 scan_io_queue_insert_impl(queue, sio);
4754 * Given a set of I/O parameters as discovered by the metadata traversal
4755 * process, attempts to place the I/O into the sorted queues (if allowed),
4756 * or immediately executes the I/O.
4758 static void
4759 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
4760 const zbookmark_phys_t *zb)
4762 spa_t *spa = dp->dp_spa;
4764 ASSERT(!BP_IS_EMBEDDED(bp));
4767 * Gang blocks are hard to issue sequentially, so we just issue them
4768 * here immediately instead of queuing them.
4770 if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
4771 scan_exec_io(dp, bp, zio_flags, zb, NULL);
4772 return;
4775 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
4776 dva_t dva;
4777 vdev_t *vdev;
4779 dva = bp->blk_dva[i];
4780 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
4781 ASSERT(vdev != NULL);
4783 mutex_enter(&vdev->vdev_scan_io_queue_lock);
4784 if (vdev->vdev_scan_io_queue == NULL)
4785 vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
4786 ASSERT(dp->dp_scan != NULL);
4787 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
4788 i, zio_flags, zb);
4789 mutex_exit(&vdev->vdev_scan_io_queue_lock);
4793 static int
4794 dsl_scan_scrub_cb(dsl_pool_t *dp,
4795 const blkptr_t *bp, const zbookmark_phys_t *zb)
4797 dsl_scan_t *scn = dp->dp_scan;
4798 spa_t *spa = dp->dp_spa;
4799 uint64_t phys_birth = BP_GET_BIRTH(bp);
4800 size_t psize = BP_GET_PSIZE(bp);
4801 boolean_t needs_io = B_FALSE;
4802 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
4804 count_block(dp->dp_blkstats, bp);
4805 if (phys_birth <= scn->scn_phys.scn_min_txg ||
4806 phys_birth >= scn->scn_phys.scn_max_txg) {
4807 count_block_skipped(scn, bp, B_TRUE);
4808 return (0);
4811 /* Embedded BP's have phys_birth==0, so we reject them above. */
4812 ASSERT(!BP_IS_EMBEDDED(bp));
4814 ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
4815 if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
4816 zio_flags |= ZIO_FLAG_SCRUB;
4817 needs_io = B_TRUE;
4818 } else {
4819 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
4820 zio_flags |= ZIO_FLAG_RESILVER;
4821 needs_io = B_FALSE;
4824 /* If it's an intent log block, failure is expected. */
4825 if (zb->zb_level == ZB_ZIL_LEVEL)
4826 zio_flags |= ZIO_FLAG_SPECULATIVE;
4828 for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
4829 const dva_t *dva = &bp->blk_dva[d];
4832 * Keep track of how much data we've examined so that
4833 * zpool(8) status can make useful progress reports.
4835 uint64_t asize = DVA_GET_ASIZE(dva);
4836 scn->scn_phys.scn_examined += asize;
4837 spa->spa_scan_pass_exam += asize;
4839 /* if it's a resilver, this may not be in the target range */
4840 if (!needs_io)
4841 needs_io = dsl_scan_need_resilver(spa, dva, psize,
4842 phys_birth);
4845 if (needs_io && !zfs_no_scrub_io) {
4846 dsl_scan_enqueue(dp, bp, zio_flags, zb);
4847 } else {
4848 count_block_skipped(scn, bp, B_TRUE);
4851 /* do not relocate this block */
4852 return (0);
4855 static void
4856 dsl_scan_scrub_done(zio_t *zio)
4858 spa_t *spa = zio->io_spa;
4859 blkptr_t *bp = zio->io_bp;
4860 dsl_scan_io_queue_t *queue = zio->io_private;
4862 abd_free(zio->io_abd);
4864 if (queue == NULL) {
4865 mutex_enter(&spa->spa_scrub_lock);
4866 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
4867 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
4868 cv_broadcast(&spa->spa_scrub_io_cv);
4869 mutex_exit(&spa->spa_scrub_lock);
4870 } else {
4871 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
4872 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));
4873 queue->q_inflight_bytes -= BP_GET_PSIZE(bp);
4874 cv_broadcast(&queue->q_zio_cv);
4875 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
4878 if (zio->io_error && (zio->io_error != ECKSUM ||
4879 !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
4880 if (dsl_errorscrubbing(spa->spa_dsl_pool) &&
4881 !dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan)) {
4882 atomic_inc_64(&spa->spa_dsl_pool->dp_scan
4883 ->errorscrub_phys.dep_errors);
4884 } else {
4885 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys
4886 .scn_errors);
4892 * Given a scanning zio's information, executes the zio. The zio need
4893 * not necessarily be only sortable, this function simply executes the
4894 * zio, no matter what it is. The optional queue argument allows the
4895 * caller to specify that they want per top level vdev IO rate limiting
4896 * instead of the legacy global limiting.
4898 static void
4899 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
4900 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
4902 spa_t *spa = dp->dp_spa;
4903 dsl_scan_t *scn = dp->dp_scan;
4904 size_t size = BP_GET_PSIZE(bp);
4905 abd_t *data = abd_alloc_for_io(size, B_FALSE);
4906 zio_t *pio;
4908 if (queue == NULL) {
4909 ASSERT3U(scn->scn_maxinflight_bytes, >, 0);
4910 mutex_enter(&spa->spa_scrub_lock);
4911 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
4912 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
4913 spa->spa_scrub_inflight += BP_GET_PSIZE(bp);
4914 mutex_exit(&spa->spa_scrub_lock);
4915 pio = scn->scn_zio_root;
4916 } else {
4917 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
4919 ASSERT3U(queue->q_maxinflight_bytes, >, 0);
4920 mutex_enter(q_lock);
4921 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
4922 cv_wait(&queue->q_zio_cv, q_lock);
4923 queue->q_inflight_bytes += BP_GET_PSIZE(bp);
4924 pio = queue->q_zio;
4925 mutex_exit(q_lock);
4928 ASSERT(pio != NULL);
4929 count_block_issued(spa, bp, queue == NULL);
4930 zio_nowait(zio_read(pio, spa, bp, data, size, dsl_scan_scrub_done,
4931 queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
4935 * This is the primary extent sorting algorithm. We balance two parameters:
4936 * 1) how many bytes of I/O are in an extent
4937 * 2) how well the extent is filled with I/O (as a fraction of its total size)
4938 * Since we allow extents to have gaps between their constituent I/Os, it's
4939 * possible to have a fairly large extent that contains the same amount of
4940 * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
4941 * The algorithm sorts based on a score calculated from the extent's size,
4942 * the relative fill volume (in %) and a "fill weight" parameter that controls
4943 * the split between whether we prefer larger extents or more well populated
4944 * extents:
4946 * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
4948 * Example:
4949 * 1) assume extsz = 64 MiB
4950 * 2) assume fill = 32 MiB (extent is half full)
4951 * 3) assume fill_weight = 3
4952 * 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
4953 * SCORE = 32M + (50 * 3 * 32M) / 100
4954 * SCORE = 32M + (4800M / 100)
4955 * SCORE = 32M + 48M
4956 * ^ ^
4957 * | +--- final total relative fill-based score
4958 * +--------- final total fill-based score
4959 * SCORE = 80M
4961 * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
4962 * extents that are more completely filled (in a 3:2 ratio) vs just larger.
4963 * Note that as an optimization, we replace multiplication and division by
4964 * 100 with bitshifting by 7 (which effectively multiplies and divides by 128).
4966 * Since we do not care if one extent is only few percent better than another,
4967 * compress the score into 6 bits via binary logarithm AKA highbit64() and
4968 * put into otherwise unused due to ashift high bits of offset. This allows
4969 * to reduce q_exts_by_size B-tree elements to only 64 bits and compare them
4970 * with single operation. Plus it makes scrubs more sequential and reduces
4971 * chances that minor extent change move it within the B-tree.
4973 __attribute__((always_inline)) inline
4974 static int
4975 ext_size_compare(const void *x, const void *y)
4977 const uint64_t *a = x, *b = y;
4979 return (TREE_CMP(*a, *b));
4982 ZFS_BTREE_FIND_IN_BUF_FUNC(ext_size_find_in_buf, uint64_t,
4983 ext_size_compare)
4985 static void
4986 ext_size_create(range_tree_t *rt, void *arg)
4988 (void) rt;
4989 zfs_btree_t *size_tree = arg;
4991 zfs_btree_create(size_tree, ext_size_compare, ext_size_find_in_buf,
4992 sizeof (uint64_t));
4995 static void
4996 ext_size_destroy(range_tree_t *rt, void *arg)
4998 (void) rt;
4999 zfs_btree_t *size_tree = arg;
5000 ASSERT0(zfs_btree_numnodes(size_tree));
5002 zfs_btree_destroy(size_tree);
5005 static uint64_t
5006 ext_size_value(range_tree_t *rt, range_seg_gap_t *rsg)
5008 (void) rt;
5009 uint64_t size = rsg->rs_end - rsg->rs_start;
5010 uint64_t score = rsg->rs_fill + ((((rsg->rs_fill << 7) / size) *
5011 fill_weight * rsg->rs_fill) >> 7);
5012 ASSERT3U(rt->rt_shift, >=, 8);
5013 return (((uint64_t)(64 - highbit64(score)) << 56) | rsg->rs_start);
5016 static void
5017 ext_size_add(range_tree_t *rt, range_seg_t *rs, void *arg)
5019 zfs_btree_t *size_tree = arg;
5020 ASSERT3U(rt->rt_type, ==, RANGE_SEG_GAP);
5021 uint64_t v = ext_size_value(rt, (range_seg_gap_t *)rs);
5022 zfs_btree_add(size_tree, &v);
5025 static void
5026 ext_size_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
5028 zfs_btree_t *size_tree = arg;
5029 ASSERT3U(rt->rt_type, ==, RANGE_SEG_GAP);
5030 uint64_t v = ext_size_value(rt, (range_seg_gap_t *)rs);
5031 zfs_btree_remove(size_tree, &v);
5034 static void
5035 ext_size_vacate(range_tree_t *rt, void *arg)
5037 zfs_btree_t *size_tree = arg;
5038 zfs_btree_clear(size_tree);
5039 zfs_btree_destroy(size_tree);
5041 ext_size_create(rt, arg);
5044 static const range_tree_ops_t ext_size_ops = {
5045 .rtop_create = ext_size_create,
5046 .rtop_destroy = ext_size_destroy,
5047 .rtop_add = ext_size_add,
5048 .rtop_remove = ext_size_remove,
5049 .rtop_vacate = ext_size_vacate
5053 * Comparator for the q_sios_by_addr tree. Sorting is simply performed
5054 * based on LBA-order (from lowest to highest).
5056 static int
5057 sio_addr_compare(const void *x, const void *y)
5059 const scan_io_t *a = x, *b = y;
5061 return (TREE_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b)));
5064 /* IO queues are created on demand when they are needed. */
5065 static dsl_scan_io_queue_t *
5066 scan_io_queue_create(vdev_t *vd)
5068 dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
5069 dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
5071 q->q_scn = scn;
5072 q->q_vd = vd;
5073 q->q_sio_memused = 0;
5074 q->q_last_ext_addr = -1;
5075 cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
5076 q->q_exts_by_addr = range_tree_create_gap(&ext_size_ops, RANGE_SEG_GAP,
5077 &q->q_exts_by_size, 0, vd->vdev_ashift, zfs_scan_max_ext_gap);
5078 avl_create(&q->q_sios_by_addr, sio_addr_compare,
5079 sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));
5081 return (q);
5085 * Destroys a scan queue and all segments and scan_io_t's contained in it.
5086 * No further execution of I/O occurs, anything pending in the queue is
5087 * simply freed without being executed.
5089 void
5090 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
5092 dsl_scan_t *scn = queue->q_scn;
5093 scan_io_t *sio;
5094 void *cookie = NULL;
5096 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
5098 if (!avl_is_empty(&queue->q_sios_by_addr))
5099 atomic_add_64(&scn->scn_queues_pending, -1);
5100 while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
5101 NULL) {
5102 ASSERT(range_tree_contains(queue->q_exts_by_addr,
5103 SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio)));
5104 queue->q_sio_memused -= SIO_GET_MUSED(sio);
5105 sio_free(sio);
5108 ASSERT0(queue->q_sio_memused);
5109 range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
5110 range_tree_destroy(queue->q_exts_by_addr);
5111 avl_destroy(&queue->q_sios_by_addr);
5112 cv_destroy(&queue->q_zio_cv);
5114 kmem_free(queue, sizeof (*queue));
5118 * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
5119 * called on behalf of vdev_top_transfer when creating or destroying
5120 * a mirror vdev due to zpool attach/detach.
5122 void
5123 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
5125 mutex_enter(&svd->vdev_scan_io_queue_lock);
5126 mutex_enter(&tvd->vdev_scan_io_queue_lock);
5128 VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL);
5129 tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
5130 svd->vdev_scan_io_queue = NULL;
5131 if (tvd->vdev_scan_io_queue != NULL)
5132 tvd->vdev_scan_io_queue->q_vd = tvd;
5134 mutex_exit(&tvd->vdev_scan_io_queue_lock);
5135 mutex_exit(&svd->vdev_scan_io_queue_lock);
5138 static void
5139 scan_io_queues_destroy(dsl_scan_t *scn)
5141 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
5143 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5144 vdev_t *tvd = rvd->vdev_child[i];
5146 mutex_enter(&tvd->vdev_scan_io_queue_lock);
5147 if (tvd->vdev_scan_io_queue != NULL)
5148 dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
5149 tvd->vdev_scan_io_queue = NULL;
5150 mutex_exit(&tvd->vdev_scan_io_queue_lock);
5154 static void
5155 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
5157 dsl_pool_t *dp = spa->spa_dsl_pool;
5158 dsl_scan_t *scn = dp->dp_scan;
5159 vdev_t *vdev;
5160 kmutex_t *q_lock;
5161 dsl_scan_io_queue_t *queue;
5162 scan_io_t *srch_sio, *sio;
5163 avl_index_t idx;
5164 uint64_t start, size;
5166 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
5167 ASSERT(vdev != NULL);
5168 q_lock = &vdev->vdev_scan_io_queue_lock;
5169 queue = vdev->vdev_scan_io_queue;
5171 mutex_enter(q_lock);
5172 if (queue == NULL) {
5173 mutex_exit(q_lock);
5174 return;
5177 srch_sio = sio_alloc(BP_GET_NDVAS(bp));
5178 bp2sio(bp, srch_sio, dva_i);
5179 start = SIO_GET_OFFSET(srch_sio);
5180 size = SIO_GET_ASIZE(srch_sio);
5183 * We can find the zio in two states:
5184 * 1) Cold, just sitting in the queue of zio's to be issued at
5185 * some point in the future. In this case, all we do is
5186 * remove the zio from the q_sios_by_addr tree, decrement
5187 * its data volume from the containing range_seg_t and
5188 * resort the q_exts_by_size tree to reflect that the
5189 * range_seg_t has lost some of its 'fill'. We don't shorten
5190 * the range_seg_t - this is usually rare enough not to be
5191 * worth the extra hassle of trying keep track of precise
5192 * extent boundaries.
5193 * 2) Hot, where the zio is currently in-flight in
5194 * dsl_scan_issue_ios. In this case, we can't simply
5195 * reach in and stop the in-flight zio's, so we instead
5196 * block the caller. Eventually, dsl_scan_issue_ios will
5197 * be done with issuing the zio's it gathered and will
5198 * signal us.
5200 sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
5201 sio_free(srch_sio);
5203 if (sio != NULL) {
5204 blkptr_t tmpbp;
5206 /* Got it while it was cold in the queue */
5207 ASSERT3U(start, ==, SIO_GET_OFFSET(sio));
5208 ASSERT3U(size, ==, SIO_GET_ASIZE(sio));
5209 avl_remove(&queue->q_sios_by_addr, sio);
5210 if (avl_is_empty(&queue->q_sios_by_addr))
5211 atomic_add_64(&scn->scn_queues_pending, -1);
5212 queue->q_sio_memused -= SIO_GET_MUSED(sio);
5214 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size));
5215 range_tree_remove_fill(queue->q_exts_by_addr, start, size);
5217 /* count the block as though we skipped it */
5218 sio2bp(sio, &tmpbp);
5219 count_block_skipped(scn, &tmpbp, B_FALSE);
5221 sio_free(sio);
5223 mutex_exit(q_lock);
5227 * Callback invoked when a zio_free() zio is executing. This needs to be
5228 * intercepted to prevent the zio from deallocating a particular portion
5229 * of disk space and it then getting reallocated and written to, while we
5230 * still have it queued up for processing.
5232 void
5233 dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
5235 dsl_pool_t *dp = spa->spa_dsl_pool;
5236 dsl_scan_t *scn = dp->dp_scan;
5238 ASSERT(!BP_IS_EMBEDDED(bp));
5239 ASSERT(scn != NULL);
5240 if (!dsl_scan_is_running(scn))
5241 return;
5243 for (int i = 0; i < BP_GET_NDVAS(bp); i++)
5244 dsl_scan_freed_dva(spa, bp, i);
5248 * Check if a vdev needs resilvering (non-empty DTL), if so, and resilver has
5249 * not started, start it. Otherwise, only restart if max txg in DTL range is
5250 * greater than the max txg in the current scan. If the DTL max is less than
5251 * the scan max, then the vdev has not missed any new data since the resilver
5252 * started, so a restart is not needed.
5254 void
5255 dsl_scan_assess_vdev(dsl_pool_t *dp, vdev_t *vd)
5257 uint64_t min, max;
5259 if (!vdev_resilver_needed(vd, &min, &max))
5260 return;
5262 if (!dsl_scan_resilvering(dp)) {
5263 spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);
5264 return;
5267 if (max <= dp->dp_scan->scn_phys.scn_max_txg)
5268 return;
5270 /* restart is needed, check if it can be deferred */
5271 if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))
5272 vdev_defer_resilver(vd);
5273 else
5274 spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);
5277 ZFS_MODULE_PARAM(zfs, zfs_, scan_vdev_limit, U64, ZMOD_RW,
5278 "Max bytes in flight per leaf vdev for scrubs and resilvers");
5280 ZFS_MODULE_PARAM(zfs, zfs_, scrub_min_time_ms, UINT, ZMOD_RW,
5281 "Min millisecs to scrub per txg");
5283 ZFS_MODULE_PARAM(zfs, zfs_, obsolete_min_time_ms, UINT, ZMOD_RW,
5284 "Min millisecs to obsolete per txg");
5286 ZFS_MODULE_PARAM(zfs, zfs_, free_min_time_ms, UINT, ZMOD_RW,
5287 "Min millisecs to free per txg");
5289 ZFS_MODULE_PARAM(zfs, zfs_, resilver_min_time_ms, UINT, ZMOD_RW,
5290 "Min millisecs to resilver per txg");
5292 ZFS_MODULE_PARAM(zfs, zfs_, scan_suspend_progress, INT, ZMOD_RW,
5293 "Set to prevent scans from progressing");
5295 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_io, INT, ZMOD_RW,
5296 "Set to disable scrub I/O");
5298 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_prefetch, INT, ZMOD_RW,
5299 "Set to disable scrub prefetching");
5301 ZFS_MODULE_PARAM(zfs, zfs_, async_block_max_blocks, U64, ZMOD_RW,
5302 "Max number of blocks freed in one txg");
5304 ZFS_MODULE_PARAM(zfs, zfs_, max_async_dedup_frees, U64, ZMOD_RW,
5305 "Max number of dedup blocks freed in one txg");
5307 ZFS_MODULE_PARAM(zfs, zfs_, free_bpobj_enabled, INT, ZMOD_RW,
5308 "Enable processing of the free_bpobj");
5310 ZFS_MODULE_PARAM(zfs, zfs_, scan_blkstats, INT, ZMOD_RW,
5311 "Enable block statistics calculation during scrub");
5313 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_fact, UINT, ZMOD_RW,
5314 "Fraction of RAM for scan hard limit");
5316 ZFS_MODULE_PARAM(zfs, zfs_, scan_issue_strategy, UINT, ZMOD_RW,
5317 "IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");
5319 ZFS_MODULE_PARAM(zfs, zfs_, scan_legacy, INT, ZMOD_RW,
5320 "Scrub using legacy non-sequential method");
5322 ZFS_MODULE_PARAM(zfs, zfs_, scan_checkpoint_intval, UINT, ZMOD_RW,
5323 "Scan progress on-disk checkpointing interval");
5325 ZFS_MODULE_PARAM(zfs, zfs_, scan_max_ext_gap, U64, ZMOD_RW,
5326 "Max gap in bytes between sequential scrub / resilver I/Os");
5328 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_soft_fact, UINT, ZMOD_RW,
5329 "Fraction of hard limit used as soft limit");
5331 ZFS_MODULE_PARAM(zfs, zfs_, scan_strict_mem_lim, INT, ZMOD_RW,
5332 "Tunable to attempt to reduce lock contention");
5334 ZFS_MODULE_PARAM(zfs, zfs_, scan_fill_weight, UINT, ZMOD_RW,
5335 "Tunable to adjust bias towards more filled segments during scans");
5337 ZFS_MODULE_PARAM(zfs, zfs_, scan_report_txgs, UINT, ZMOD_RW,
5338 "Tunable to report resilver performance over the last N txgs");
5340 ZFS_MODULE_PARAM(zfs, zfs_, resilver_disable_defer, INT, ZMOD_RW,
5341 "Process all resilvers immediately");
5343 ZFS_MODULE_PARAM(zfs, zfs_, resilver_defer_percent, UINT, ZMOD_RW,
5344 "Issued IO percent complete after which resilvers are deferred");
5346 ZFS_MODULE_PARAM(zfs, zfs_, scrub_error_blocks_per_txg, UINT, ZMOD_RW,
5347 "Error blocks to be scrubbed in one txg");
5348 /* END CSTYLED */