]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/dsl_scan.c
Fix ENXIO from spa_ld_verify_logs() in ztest
[mirror_zfs.git] / module / zfs / dsl_scan.c
CommitLineData
428870ff
BB
1/*
2 * CDDL HEADER START
3 *
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.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
a1d477c2 23 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
7c9abfa7 24 * Copyright 2016 Gary Mills
0ea05c64 25 * Copyright (c) 2017 Datto Inc.
12fa0466 26 * Copyright 2017 Joyent, Inc.
428870ff
BB
27 */
28
29#include <sys/dsl_scan.h>
30#include <sys/dsl_pool.h>
31#include <sys/dsl_dataset.h>
32#include <sys/dsl_prop.h>
33#include <sys/dsl_dir.h>
34#include <sys/dsl_synctask.h>
35#include <sys/dnode.h>
36#include <sys/dmu_tx.h>
37#include <sys/dmu_objset.h>
38#include <sys/arc.h>
39#include <sys/zap.h>
40#include <sys/zio.h>
41#include <sys/zfs_context.h>
42#include <sys/fs/zfs.h>
43#include <sys/zfs_znode.h>
44#include <sys/spa_impl.h>
45#include <sys/vdev_impl.h>
46#include <sys/zil_impl.h>
47#include <sys/zio_checksum.h>
48#include <sys/ddt.h>
49#include <sys/sa.h>
50#include <sys/sa_impl.h>
9ae529ec 51#include <sys/zfeature.h>
a6255b7f 52#include <sys/abd.h>
d4a72f23 53#include <sys/range_tree.h>
428870ff
BB
54#ifdef _KERNEL
55#include <sys/zfs_vfsops.h>
56#endif
57
d4a72f23
TC
58/*
59 * Grand theory statement on scan queue sorting
60 *
61 * Scanning is implemented by recursively traversing all indirection levels
62 * in an object and reading all blocks referenced from said objects. This
63 * results in us approximately traversing the object from lowest logical
64 * offset to the highest. For best performance, we would want the logical
65 * blocks to be physically contiguous. However, this is frequently not the
66 * case with pools given the allocation patterns of copy-on-write filesystems.
67 * So instead, we put the I/Os into a reordering queue and issue them in a
68 * way that will most benefit physical disks (LBA-order).
69 *
70 * Queue management:
71 *
72 * Ideally, we would want to scan all metadata and queue up all block I/O
73 * prior to starting to issue it, because that allows us to do an optimal
74 * sorting job. This can however consume large amounts of memory. Therefore
75 * we continuously monitor the size of the queues and constrain them to 5%
76 * (zfs_scan_mem_lim_fact) of physmem. If the queues grow larger than this
77 * limit, we clear out a few of the largest extents at the head of the queues
78 * to make room for more scanning. Hopefully, these extents will be fairly
79 * large and contiguous, allowing us to approach sequential I/O throughput
80 * even without a fully sorted tree.
81 *
82 * Metadata scanning takes place in dsl_scan_visit(), which is called from
83 * dsl_scan_sync() every spa_sync(). If we have either fully scanned all
84 * metadata on the pool, or we need to make room in memory because our
85 * queues are too large, dsl_scan_visit() is postponed and
86 * scan_io_queues_run() is called from dsl_scan_sync() instead. This implies
87 * that metadata scanning and queued I/O issuing are mutually exclusive. This
88 * allows us to provide maximum sequential I/O throughput for the majority of
89 * I/O's issued since sequential I/O performance is significantly negatively
90 * impacted if it is interleaved with random I/O.
91 *
92 * Implementation Notes
93 *
94 * One side effect of the queued scanning algorithm is that the scanning code
95 * needs to be notified whenever a block is freed. This is needed to allow
96 * the scanning code to remove these I/Os from the issuing queue. Additionally,
97 * we do not attempt to queue gang blocks to be issued sequentially since this
13a2ff27 98 * is very hard to do and would have an extremely limited performance benefit.
d4a72f23
TC
99 * Instead, we simply issue gang I/Os as soon as we find them using the legacy
100 * algorithm.
101 *
102 * Backwards compatibility
103 *
104 * This new algorithm is backwards compatible with the legacy on-disk data
105 * structures (and therefore does not require a new feature flag).
106 * Periodically during scanning (see zfs_scan_checkpoint_intval), the scan
107 * will stop scanning metadata (in logical order) and wait for all outstanding
108 * sorted I/O to complete. Once this is done, we write out a checkpoint
109 * bookmark, indicating that we have scanned everything logically before it.
110 * If the pool is imported on a machine without the new sorting algorithm,
111 * the scan simply resumes from the last checkpoint using the legacy algorithm.
112 */
113
5dbd68a3
MA
114typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,
115 const zbookmark_phys_t *);
428870ff 116
428870ff 117static scan_cb_t dsl_scan_scrub_cb;
428870ff 118
d4a72f23
TC
119static int scan_ds_queue_compare(const void *a, const void *b);
120static int scan_prefetch_queue_compare(const void *a, const void *b);
121static void scan_ds_queue_clear(dsl_scan_t *scn);
122static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj,
123 uint64_t *txg);
124static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg);
125static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj);
126static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx);
f90a30ad 127static uint64_t dsl_scan_count_leaves(vdev_t *vd);
d4a72f23
TC
128
129extern int zfs_vdev_async_write_active_min_dirty_percent;
130
131/*
132 * By default zfs will check to ensure it is not over the hard memory
133 * limit before each txg. If finer-grained control of this is needed
134 * this value can be set to 1 to enable checking before scanning each
135 * block.
136 */
137int zfs_scan_strict_mem_lim = B_FALSE;
138
139/*
140 * Maximum number of parallelly executed bytes per leaf vdev. We attempt
141 * to strike a balance here between keeping the vdev queues full of I/Os
142 * at all times and not overflowing the queues to cause long latency,
143 * which would cause long txg sync times. No matter what, we will not
144 * overload the drives with I/O, since that is protected by
145 * zfs_vdev_scrub_max_active.
146 */
147unsigned long zfs_scan_vdev_limit = 4 << 20;
148
149int zfs_scan_issue_strategy = 0;
150int zfs_scan_legacy = B_FALSE; /* don't queue & sort zios, go direct */
63f88c12 151unsigned long zfs_scan_max_ext_gap = 2 << 20; /* in bytes */
d4a72f23
TC
152
153/*
154 * fill_weight is non-tunable at runtime, so we copy it at module init from
155 * zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would
156 * break queue sorting.
157 */
158int zfs_scan_fill_weight = 3;
159static uint64_t fill_weight;
160
161/* See dsl_scan_should_clear() for details on the memory limit tunables */
162uint64_t zfs_scan_mem_lim_min = 16 << 20; /* bytes */
163uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */
164int zfs_scan_mem_lim_fact = 20; /* fraction of physmem */
165int zfs_scan_mem_lim_soft_fact = 20; /* fraction of mem lim above */
572e2857 166
d4a72f23 167int zfs_scrub_min_time_ms = 1000; /* min millisecs to scrub per txg */
a1d477c2 168int zfs_obsolete_min_time_ms = 500; /* min millisecs to obsolete per txg */
428870ff
BB
169int zfs_free_min_time_ms = 1000; /* min millisecs to free per txg */
170int zfs_resilver_min_time_ms = 3000; /* min millisecs to resilver per txg */
d4a72f23 171int zfs_scan_checkpoint_intval = 7200; /* in seconds */
c409e464 172int zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */
fbeddd60 173int zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */
428870ff 174enum ddt_class zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;
36283ca2 175/* max number of blocks to free in a single TXG */
a1d477c2 176unsigned long zfs_async_block_max_blocks = 100000;
428870ff 177
80a91e74
TC
178int zfs_resilver_disable_defer = 0; /* set to disable resilver deferring */
179
d4a72f23
TC
180/*
181 * We wait a few txgs after importing a pool to begin scanning so that
182 * the import / mounting code isn't held up by scrub / resilver IO.
183 * Unfortunately, it is a bit difficult to determine exactly how long
184 * this will take since userspace will trigger fs mounts asynchronously
185 * and the kernel will create zvol minors asynchronously. As a result,
186 * the value provided here is a bit arbitrary, but represents a
187 * reasonable estimate of how many txgs it will take to finish fully
188 * importing a pool
189 */
190#define SCAN_IMPORT_WAIT_TXGS 5
191
428870ff
BB
192#define DSL_SCAN_IS_SCRUB_RESILVER(scn) \
193 ((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \
194 (scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)
195
ba5ad9a4
GW
196/*
197 * Enable/disable the processing of the free_bpobj object.
198 */
199int zfs_free_bpobj_enabled = 1;
200
428870ff
BB
201/* the order has to match pool_scan_type */
202static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {
203 NULL,
204 dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */
205 dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */
206};
207
d4a72f23
TC
208/* In core node for the scn->scn_queue. Represents a dataset to be scanned */
209typedef struct {
210 uint64_t sds_dsobj;
211 uint64_t sds_txg;
212 avl_node_t sds_node;
213} scan_ds_t;
214
215/*
216 * This controls what conditions are placed on dsl_scan_sync_state():
217 * SYNC_OPTIONAL) write out scn_phys iff scn_bytes_pending == 0
218 * SYNC_MANDATORY) write out scn_phys always. scn_bytes_pending must be 0.
219 * SYNC_CACHED) if scn_bytes_pending == 0, write out scn_phys. Otherwise
220 * write out the scn_phys_cached version.
221 * See dsl_scan_sync_state for details.
222 */
223typedef enum {
224 SYNC_OPTIONAL,
225 SYNC_MANDATORY,
226 SYNC_CACHED
227} state_sync_type_t;
228
229/*
230 * This struct represents the minimum information needed to reconstruct a
231 * zio for sequential scanning. This is useful because many of these will
232 * accumulate in the sequential IO queues before being issued, so saving
233 * memory matters here.
234 */
235typedef struct scan_io {
236 /* fields from blkptr_t */
237 uint64_t sio_offset;
238 uint64_t sio_blk_prop;
239 uint64_t sio_phys_birth;
240 uint64_t sio_birth;
241 zio_cksum_t sio_cksum;
242 uint32_t sio_asize;
243
244 /* fields from zio_t */
245 int sio_flags;
246 zbookmark_phys_t sio_zb;
247
248 /* members for queue sorting */
249 union {
250 avl_node_t sio_addr_node; /* link into issueing queue */
251 list_node_t sio_list_node; /* link for issuing to disk */
252 } sio_nodes;
253} scan_io_t;
254
255struct dsl_scan_io_queue {
256 dsl_scan_t *q_scn; /* associated dsl_scan_t */
257 vdev_t *q_vd; /* top-level vdev that this queue represents */
258
259 /* trees used for sorting I/Os and extents of I/Os */
260 range_tree_t *q_exts_by_addr;
261 avl_tree_t q_exts_by_size;
262 avl_tree_t q_sios_by_addr;
263
264 /* members for zio rate limiting */
265 uint64_t q_maxinflight_bytes;
266 uint64_t q_inflight_bytes;
267 kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */
268
269 /* per txg statistics */
270 uint64_t q_total_seg_size_this_txg;
271 uint64_t q_segs_this_txg;
272 uint64_t q_total_zio_size_this_txg;
273 uint64_t q_zios_this_txg;
274};
275
276/* private data for dsl_scan_prefetch_cb() */
277typedef struct scan_prefetch_ctx {
c13060e4 278 zfs_refcount_t spc_refcnt; /* refcount for memory management */
d4a72f23
TC
279 dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */
280 boolean_t spc_root; /* is this prefetch for an objset? */
281 uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */
282 uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */
283} scan_prefetch_ctx_t;
284
285/* private data for dsl_scan_prefetch() */
286typedef struct scan_prefetch_issue_ctx {
287 avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */
288 scan_prefetch_ctx_t *spic_spc; /* spc for the callback */
289 blkptr_t spic_bp; /* bp to prefetch */
290 zbookmark_phys_t spic_zb; /* bookmark to prefetch */
291} scan_prefetch_issue_ctx_t;
292
293static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
294 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);
295static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,
296 scan_io_t *sio);
297
298static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);
299static void scan_io_queues_destroy(dsl_scan_t *scn);
300
301static kmem_cache_t *sio_cache;
302
303void
304scan_init(void)
305{
306 /*
307 * This is used in ext_size_compare() to weight segments
308 * based on how sparse they are. This cannot be changed
309 * mid-scan and the tree comparison functions don't currently
13a2ff27 310 * have a mechanism for passing additional context to the
d4a72f23 311 * compare functions. Thus we store this value globally and
13a2ff27 312 * we only allow it to be set at module initialization time
d4a72f23
TC
313 */
314 fill_weight = zfs_scan_fill_weight;
315
316 sio_cache = kmem_cache_create("sio_cache",
317 sizeof (scan_io_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
318}
319
320void
321scan_fini(void)
322{
323 kmem_cache_destroy(sio_cache);
324}
325
326static inline boolean_t
327dsl_scan_is_running(const dsl_scan_t *scn)
328{
329 return (scn->scn_phys.scn_state == DSS_SCANNING);
330}
331
332boolean_t
333dsl_scan_resilvering(dsl_pool_t *dp)
334{
335 return (dsl_scan_is_running(dp->dp_scan) &&
336 dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
337}
338
339static inline void
340sio2bp(const scan_io_t *sio, blkptr_t *bp, uint64_t vdev_id)
341{
342 bzero(bp, sizeof (*bp));
343 DVA_SET_ASIZE(&bp->blk_dva[0], sio->sio_asize);
344 DVA_SET_VDEV(&bp->blk_dva[0], vdev_id);
345 DVA_SET_OFFSET(&bp->blk_dva[0], sio->sio_offset);
346 bp->blk_prop = sio->sio_blk_prop;
347 bp->blk_phys_birth = sio->sio_phys_birth;
348 bp->blk_birth = sio->sio_birth;
349 bp->blk_fill = 1; /* we always only work with data pointers */
350 bp->blk_cksum = sio->sio_cksum;
351}
352
353static inline void
354bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)
355{
356 /* we discard the vdev id, since we can deduce it from the queue */
357 sio->sio_offset = DVA_GET_OFFSET(&bp->blk_dva[dva_i]);
358 sio->sio_asize = DVA_GET_ASIZE(&bp->blk_dva[dva_i]);
359 sio->sio_blk_prop = bp->blk_prop;
360 sio->sio_phys_birth = bp->blk_phys_birth;
361 sio->sio_birth = bp->blk_birth;
362 sio->sio_cksum = bp->blk_cksum;
363}
364
428870ff
BB
365int
366dsl_scan_init(dsl_pool_t *dp, uint64_t txg)
367{
368 int err;
369 dsl_scan_t *scn;
370 spa_t *spa = dp->dp_spa;
371 uint64_t f;
372
373 scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);
374 scn->scn_dp = dp;
375
2696dfaf
GW
376 /*
377 * It's possible that we're resuming a scan after a reboot so
378 * make sure that the scan_async_destroying flag is initialized
379 * appropriately.
380 */
381 ASSERT(!scn->scn_async_destroying);
382 scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,
fa86b5db 383 SPA_FEATURE_ASYNC_DESTROY);
2696dfaf 384
f90a30ad
BB
385 /*
386 * Calculate the max number of in-flight bytes for pool-wide
387 * scanning operations (minimum 1MB). Limits for the issuing
388 * phase are done per top-level vdev and are handled separately.
389 */
390 scn->scn_maxinflight_bytes = MAX(zfs_scan_vdev_limit *
391 dsl_scan_count_leaves(spa->spa_root_vdev), 1ULL << 20);
392
d4a72f23
TC
393 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
394 avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),
395 offsetof(scan_ds_t, sds_node));
396 avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,
397 sizeof (scan_prefetch_issue_ctx_t),
398 offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));
399
428870ff
BB
400 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
401 "scrub_func", sizeof (uint64_t), 1, &f);
402 if (err == 0) {
403 /*
404 * There was an old-style scrub in progress. Restart a
405 * new-style scrub from the beginning.
406 */
407 scn->scn_restart_txg = txg;
408 zfs_dbgmsg("old-style scrub was in progress; "
409 "restarting new-style scrub in txg %llu",
d4a72f23 410 (longlong_t)scn->scn_restart_txg);
428870ff
BB
411
412 /*
413 * Load the queue obj from the old location so that it
414 * can be freed by dsl_scan_done().
415 */
416 (void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
417 "scrub_queue", sizeof (uint64_t), 1,
418 &scn->scn_phys.scn_queue_obj);
419 } else {
420 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
421 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
422 &scn->scn_phys);
4f2dcb3e
RY
423 /*
424 * Detect if the pool contains the signature of #2094. If it
425 * does properly update the scn->scn_phys structure and notify
426 * the administrator by setting an errata for the pool.
427 */
428 if (err == EOVERFLOW) {
429 uint64_t zaptmp[SCAN_PHYS_NUMINTS + 1];
430 VERIFY3S(SCAN_PHYS_NUMINTS, ==, 24);
431 VERIFY3S(offsetof(dsl_scan_phys_t, scn_flags), ==,
432 (23 * sizeof (uint64_t)));
433
434 err = zap_lookup(dp->dp_meta_objset,
435 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SCAN,
436 sizeof (uint64_t), SCAN_PHYS_NUMINTS + 1, &zaptmp);
437 if (err == 0) {
438 uint64_t overflow = zaptmp[SCAN_PHYS_NUMINTS];
439
440 if (overflow & ~DSL_SCAN_FLAGS_MASK ||
441 scn->scn_async_destroying) {
442 spa->spa_errata =
443 ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY;
d4a72f23 444 return (EOVERFLOW);
4f2dcb3e
RY
445 }
446
447 bcopy(zaptmp, &scn->scn_phys,
448 SCAN_PHYS_NUMINTS * sizeof (uint64_t));
449 scn->scn_phys.scn_flags = overflow;
450
451 /* Required scrub already in progress. */
452 if (scn->scn_phys.scn_state == DSS_FINISHED ||
453 scn->scn_phys.scn_state == DSS_CANCELED)
454 spa->spa_errata =
455 ZPOOL_ERRATA_ZOL_2094_SCRUB;
456 }
457 }
458
428870ff
BB
459 if (err == ENOENT)
460 return (0);
461 else if (err)
462 return (err);
463
d4a72f23
TC
464 /*
465 * We might be restarting after a reboot, so jump the issued
466 * counter to how far we've scanned. We know we're consistent
467 * up to here.
468 */
469 scn->scn_issued_before_pass = scn->scn_phys.scn_examined;
470
471 if (dsl_scan_is_running(scn) &&
428870ff
BB
472 spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {
473 /*
474 * A new-type scrub was in progress on an old
475 * pool, and the pool was accessed by old
476 * software. Restart from the beginning, since
477 * the old software may have changed the pool in
478 * the meantime.
479 */
480 scn->scn_restart_txg = txg;
481 zfs_dbgmsg("new-style scrub was modified "
482 "by old software; restarting in txg %llu",
d4a72f23
TC
483 (longlong_t)scn->scn_restart_txg);
484 }
485 }
486
487 /* reload the queue into the in-core state */
488 if (scn->scn_phys.scn_queue_obj != 0) {
489 zap_cursor_t zc;
490 zap_attribute_t za;
491
492 for (zap_cursor_init(&zc, dp->dp_meta_objset,
493 scn->scn_phys.scn_queue_obj);
494 zap_cursor_retrieve(&zc, &za) == 0;
495 (void) zap_cursor_advance(&zc)) {
496 scan_ds_queue_insert(scn,
497 zfs_strtonum(za.za_name, NULL),
498 za.za_first_integer);
428870ff 499 }
d4a72f23 500 zap_cursor_fini(&zc);
428870ff
BB
501 }
502
503 spa_scan_stat_init(spa);
504 return (0);
505}
506
507void
508dsl_scan_fini(dsl_pool_t *dp)
509{
d4a72f23
TC
510 if (dp->dp_scan != NULL) {
511 dsl_scan_t *scn = dp->dp_scan;
512
513 if (scn->scn_taskq != NULL)
514 taskq_destroy(scn->scn_taskq);
515 scan_ds_queue_clear(scn);
516 avl_destroy(&scn->scn_queue);
517 avl_destroy(&scn->scn_prefetch_queue);
518
428870ff
BB
519 kmem_free(dp->dp_scan, sizeof (dsl_scan_t));
520 dp->dp_scan = NULL;
521 }
522}
523
d4a72f23
TC
524static boolean_t
525dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)
526{
527 return (scn->scn_restart_txg != 0 &&
528 scn->scn_restart_txg <= tx->tx_txg);
529}
530
531boolean_t
532dsl_scan_scrubbing(const dsl_pool_t *dp)
533{
534 dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;
535
536 return (scn_phys->scn_state == DSS_SCANNING &&
537 scn_phys->scn_func == POOL_SCAN_SCRUB);
538}
539
540boolean_t
541dsl_scan_is_paused_scrub(const dsl_scan_t *scn)
542{
543 return (dsl_scan_scrubbing(scn->scn_dp) &&
544 scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);
545}
546
547/*
548 * Writes out a persistent dsl_scan_phys_t record to the pool directory.
549 * Because we can be running in the block sorting algorithm, we do not always
550 * want to write out the record, only when it is "safe" to do so. This safety
551 * condition is achieved by making sure that the sorting queues are empty
552 * (scn_bytes_pending == 0). When this condition is not true, the sync'd state
553 * is inconsistent with how much actual scanning progress has been made. The
554 * kind of sync to be performed is specified by the sync_type argument. If the
555 * sync is optional, we only sync if the queues are empty. If the sync is
556 * mandatory, we do a hard ASSERT to make sure that the queues are empty. The
557 * third possible state is a "cached" sync. This is done in response to:
558 * 1) The dataset that was in the last sync'd dsl_scan_phys_t having been
559 * destroyed, so we wouldn't be able to restart scanning from it.
560 * 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been
561 * superseded by a newer snapshot.
562 * 3) The dataset that was in the last sync'd dsl_scan_phys_t having been
563 * swapped with its clone.
564 * In all cases, a cached sync simply rewrites the last record we've written,
565 * just slightly modified. For the modifications that are performed to the
566 * last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,
567 * dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.
568 */
569static void
570dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)
571{
572 int i;
573 spa_t *spa = scn->scn_dp->dp_spa;
574
575 ASSERT(sync_type != SYNC_MANDATORY || scn->scn_bytes_pending == 0);
576 if (scn->scn_bytes_pending == 0) {
577 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
578 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
579 dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;
580
581 if (q == NULL)
582 continue;
583
584 mutex_enter(&vd->vdev_scan_io_queue_lock);
585 ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);
586 ASSERT3P(avl_first(&q->q_exts_by_size), ==, NULL);
587 ASSERT3P(range_tree_first(q->q_exts_by_addr), ==, NULL);
588 mutex_exit(&vd->vdev_scan_io_queue_lock);
589 }
590
591 if (scn->scn_phys.scn_queue_obj != 0)
592 scan_ds_queue_sync(scn, tx);
593 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
594 DMU_POOL_DIRECTORY_OBJECT,
595 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
596 &scn->scn_phys, tx));
597 bcopy(&scn->scn_phys, &scn->scn_phys_cached,
598 sizeof (scn->scn_phys));
599
600 if (scn->scn_checkpointing)
601 zfs_dbgmsg("finish scan checkpoint");
602
603 scn->scn_checkpointing = B_FALSE;
604 scn->scn_last_checkpoint = ddi_get_lbolt();
605 } else if (sync_type == SYNC_CACHED) {
606 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
607 DMU_POOL_DIRECTORY_OBJECT,
608 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
609 &scn->scn_phys_cached, tx));
610 }
611}
612
428870ff
BB
613/* ARGSUSED */
614static int
13fe0198 615dsl_scan_setup_check(void *arg, dmu_tx_t *tx)
428870ff 616{
13fe0198 617 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
428870ff 618
d4a72f23 619 if (dsl_scan_is_running(scn))
2e528b49 620 return (SET_ERROR(EBUSY));
428870ff
BB
621
622 return (0);
623}
624
428870ff 625static void
13fe0198 626dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)
428870ff 627{
13fe0198
MA
628 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
629 pool_scan_func_t *funcp = arg;
428870ff
BB
630 dmu_object_type_t ot = 0;
631 dsl_pool_t *dp = scn->scn_dp;
632 spa_t *spa = dp->dp_spa;
633
d4a72f23 634 ASSERT(!dsl_scan_is_running(scn));
428870ff
BB
635 ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);
636 bzero(&scn->scn_phys, sizeof (scn->scn_phys));
637 scn->scn_phys.scn_func = *funcp;
638 scn->scn_phys.scn_state = DSS_SCANNING;
639 scn->scn_phys.scn_min_txg = 0;
640 scn->scn_phys.scn_max_txg = tx->tx_txg;
641 scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */
642 scn->scn_phys.scn_start_time = gethrestime_sec();
643 scn->scn_phys.scn_errors = 0;
644 scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;
d4a72f23 645 scn->scn_issued_before_pass = 0;
428870ff 646 scn->scn_restart_txg = 0;
5d1f7fb6 647 scn->scn_done_txg = 0;
d4a72f23
TC
648 scn->scn_last_checkpoint = 0;
649 scn->scn_checkpointing = B_FALSE;
428870ff
BB
650 spa_scan_stat_init(spa);
651
652 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
653 scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;
654
655 /* rewrite all disk labels */
656 vdev_config_dirty(spa->spa_root_vdev);
657
658 if (vdev_resilver_needed(spa->spa_root_vdev,
659 &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {
12fa0466
DE
660 spa_event_notify(spa, NULL, NULL,
661 ESC_ZFS_RESILVER_START);
428870ff 662 } else {
12fa0466 663 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);
428870ff
BB
664 }
665
666 spa->spa_scrub_started = B_TRUE;
667 /*
668 * If this is an incremental scrub, limit the DDT scrub phase
669 * to just the auto-ditto class (for correctness); the rest
670 * of the scrub should go faster using top-down pruning.
671 */
672 if (scn->scn_phys.scn_min_txg > TXG_INITIAL)
673 scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;
674
675 }
676
677 /* back to the generic stuff */
678
679 if (dp->dp_blkstats == NULL) {
79c76d5b
BB
680 dp->dp_blkstats =
681 vmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);
d4a72f23
TC
682 mutex_init(&dp->dp_blkstats->zab_lock, NULL,
683 MUTEX_DEFAULT, NULL);
428870ff 684 }
d4a72f23 685 bzero(&dp->dp_blkstats->zab_type, sizeof (dp->dp_blkstats->zab_type));
428870ff
BB
686
687 if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)
688 ot = DMU_OT_ZAP_OTHER;
689
690 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,
691 ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);
692
d4a72f23
TC
693 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
694
695 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
428870ff 696
6f1ffb06 697 spa_history_log_internal(spa, "scan setup", tx,
428870ff
BB
698 "func=%u mintxg=%llu maxtxg=%llu",
699 *funcp, scn->scn_phys.scn_min_txg, scn->scn_phys.scn_max_txg);
700}
701
d4a72f23
TC
702/*
703 * Called by the ZFS_IOC_POOL_SCAN ioctl to start a scrub or resilver.
704 * Can also be called to resume a paused scrub.
705 */
706int
707dsl_scan(dsl_pool_t *dp, pool_scan_func_t func)
708{
709 spa_t *spa = dp->dp_spa;
710 dsl_scan_t *scn = dp->dp_scan;
711
712 /*
713 * Purge all vdev caches and probe all devices. We do this here
714 * rather than in sync context because this requires a writer lock
715 * on the spa_config lock, which we can't do from sync context. The
716 * spa_scrub_reopen flag indicates that vdev_open() should not
717 * attempt to start another scrub.
718 */
719 spa_vdev_state_enter(spa, SCL_NONE);
720 spa->spa_scrub_reopen = B_TRUE;
721 vdev_reopen(spa->spa_root_vdev);
722 spa->spa_scrub_reopen = B_FALSE;
723 (void) spa_vdev_state_exit(spa, NULL, 0);
724
80a91e74
TC
725 if (func == POOL_SCAN_RESILVER) {
726 dsl_resilver_restart(spa->spa_dsl_pool, 0);
727 return (0);
728 }
729
d4a72f23
TC
730 if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {
731 /* got scrub start cmd, resume paused scrub */
732 int err = dsl_scrub_set_pause_resume(scn->scn_dp,
733 POOL_SCRUB_NORMAL);
43cb30b3
SEF
734 if (err == 0) {
735 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);
d4a72f23 736 return (ECANCELED);
43cb30b3 737 }
d4a72f23
TC
738
739 return (SET_ERROR(err));
740 }
741
742 return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
d2734cce 743 dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_EXTRA_RESERVED));
d4a72f23
TC
744}
745
80a91e74
TC
746/*
747 * Sets the resilver defer flag to B_FALSE on all leaf devs under vd. Returns
748 * B_TRUE if we have devices that need to be resilvered and are available to
749 * accept resilver I/Os.
750 */
751static boolean_t
752dsl_scan_clear_deferred(vdev_t *vd, dmu_tx_t *tx)
753{
754 boolean_t resilver_needed = B_FALSE;
755 spa_t *spa = vd->vdev_spa;
756
757 for (int c = 0; c < vd->vdev_children; c++) {
758 resilver_needed |=
759 dsl_scan_clear_deferred(vd->vdev_child[c], tx);
760 }
761
762 if (vd == spa->spa_root_vdev &&
763 spa_feature_is_active(spa, SPA_FEATURE_RESILVER_DEFER)) {
764 spa_feature_decr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
765 vdev_config_dirty(vd);
766 spa->spa_resilver_deferred = B_FALSE;
767 return (resilver_needed);
768 }
769
770 if (!vdev_is_concrete(vd) || vd->vdev_aux ||
771 !vd->vdev_ops->vdev_op_leaf)
772 return (resilver_needed);
773
774 if (vd->vdev_resilver_deferred)
775 vd->vdev_resilver_deferred = B_FALSE;
776
777 return (!vdev_is_dead(vd) && !vd->vdev_offline &&
778 vdev_resilver_needed(vd, NULL, NULL));
779}
780
428870ff
BB
781/* ARGSUSED */
782static void
783dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
784{
785 static const char *old_names[] = {
786 "scrub_bookmark",
787 "scrub_ddt_bookmark",
788 "scrub_ddt_class_max",
789 "scrub_queue",
790 "scrub_min_txg",
791 "scrub_max_txg",
792 "scrub_func",
793 "scrub_errors",
794 NULL
795 };
796
797 dsl_pool_t *dp = scn->scn_dp;
798 spa_t *spa = dp->dp_spa;
799 int i;
800
801 /* Remove any remnants of an old-style scrub. */
802 for (i = 0; old_names[i]; i++) {
803 (void) zap_remove(dp->dp_meta_objset,
804 DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);
805 }
806
807 if (scn->scn_phys.scn_queue_obj != 0) {
d4a72f23 808 VERIFY0(dmu_object_free(dp->dp_meta_objset,
428870ff
BB
809 scn->scn_phys.scn_queue_obj, tx));
810 scn->scn_phys.scn_queue_obj = 0;
811 }
d4a72f23 812 scan_ds_queue_clear(scn);
428870ff 813
0ea05c64
AP
814 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
815
428870ff
BB
816 /*
817 * If we were "restarted" from a stopped state, don't bother
818 * with anything else.
819 */
d4a72f23
TC
820 if (!dsl_scan_is_running(scn)) {
821 ASSERT(!scn->scn_is_sorted);
428870ff 822 return;
d4a72f23 823 }
428870ff 824
d4a72f23
TC
825 if (scn->scn_is_sorted) {
826 scan_io_queues_destroy(scn);
827 scn->scn_is_sorted = B_FALSE;
828
829 if (scn->scn_taskq != NULL) {
830 taskq_destroy(scn->scn_taskq);
831 scn->scn_taskq = NULL;
832 }
833 }
834
835 scn->scn_phys.scn_state = complete ? DSS_FINISHED : DSS_CANCELED;
428870ff 836
784d15c1
NR
837 if (dsl_scan_restarting(scn, tx))
838 spa_history_log_internal(spa, "scan aborted, restarting", tx,
839 "errors=%llu", spa_get_errlog_size(spa));
840 else if (!complete)
841 spa_history_log_internal(spa, "scan cancelled", tx,
842 "errors=%llu", spa_get_errlog_size(spa));
843 else
844 spa_history_log_internal(spa, "scan done", tx,
845 "errors=%llu", spa_get_errlog_size(spa));
428870ff
BB
846
847 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
428870ff
BB
848 spa->spa_scrub_started = B_FALSE;
849 spa->spa_scrub_active = B_FALSE;
850
851 /*
852 * If the scrub/resilver completed, update all DTLs to
853 * reflect this. Whether it succeeded or not, vacate
854 * all temporary scrub DTLs.
d2734cce
SD
855 *
856 * As the scrub does not currently support traversing
857 * data that have been freed but are part of a checkpoint,
858 * we don't mark the scrub as done in the DTLs as faults
859 * may still exist in those vdevs.
428870ff 860 */
d2734cce
SD
861 if (complete &&
862 !spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
863 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
864 scn->scn_phys.scn_max_txg, B_TRUE);
865
12fa0466
DE
866 spa_event_notify(spa, NULL, NULL,
867 scn->scn_phys.scn_min_txg ?
fb390aaf 868 ESC_ZFS_RESILVER_FINISH : ESC_ZFS_SCRUB_FINISH);
d2734cce
SD
869 } else {
870 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
871 0, B_TRUE);
428870ff
BB
872 }
873 spa_errlog_rotate(spa);
874
875 /*
876 * We may have finished replacing a device.
877 * Let the async thread assess this and handle the detach.
878 */
879 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
80a91e74
TC
880
881 /*
882 * Clear any deferred_resilver flags in the config.
883 * If there are drives that need resilvering, kick
884 * off an asynchronous request to start resilver.
885 * dsl_scan_clear_deferred() may update the config
886 * before the resilver can restart. In the event of
887 * a crash during this period, the spa loading code
888 * will find the drives that need to be resilvered
889 * when the machine reboots and start the resilver then.
890 */
891 boolean_t resilver_needed =
892 dsl_scan_clear_deferred(spa->spa_root_vdev, tx);
893 if (resilver_needed) {
894 spa_history_log_internal(spa,
895 "starting deferred resilver", tx,
896 "errors=%llu", spa_get_errlog_size(spa));
897 spa_async_request(spa, SPA_ASYNC_RESILVER);
898 }
428870ff
BB
899 }
900
901 scn->scn_phys.scn_end_time = gethrestime_sec();
4f2dcb3e
RY
902
903 if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)
904 spa->spa_errata = 0;
d4a72f23
TC
905
906 ASSERT(!dsl_scan_is_running(scn));
428870ff
BB
907}
908
909/* ARGSUSED */
910static int
13fe0198 911dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
428870ff 912{
13fe0198 913 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
428870ff 914
d4a72f23 915 if (!dsl_scan_is_running(scn))
2e528b49 916 return (SET_ERROR(ENOENT));
428870ff
BB
917 return (0);
918}
919
920/* ARGSUSED */
921static void
13fe0198 922dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
428870ff 923{
13fe0198 924 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
428870ff
BB
925
926 dsl_scan_done(scn, B_FALSE, tx);
d4a72f23 927 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
43cb30b3 928 spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);
428870ff
BB
929}
930
931int
932dsl_scan_cancel(dsl_pool_t *dp)
933{
13fe0198 934 return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
3d45fdd6 935 dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
428870ff
BB
936}
937
0ea05c64
AP
938static int
939dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
940{
941 pool_scrub_cmd_t *cmd = arg;
942 dsl_pool_t *dp = dmu_tx_pool(tx);
943 dsl_scan_t *scn = dp->dp_scan;
944
945 if (*cmd == POOL_SCRUB_PAUSE) {
946 /* can't pause a scrub when there is no in-progress scrub */
947 if (!dsl_scan_scrubbing(dp))
948 return (SET_ERROR(ENOENT));
949
950 /* can't pause a paused scrub */
951 if (dsl_scan_is_paused_scrub(scn))
952 return (SET_ERROR(EBUSY));
953 } else if (*cmd != POOL_SCRUB_NORMAL) {
954 return (SET_ERROR(ENOTSUP));
955 }
956
957 return (0);
958}
959
960static void
961dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
962{
963 pool_scrub_cmd_t *cmd = arg;
964 dsl_pool_t *dp = dmu_tx_pool(tx);
965 spa_t *spa = dp->dp_spa;
966 dsl_scan_t *scn = dp->dp_scan;
967
0ea05c64
AP
968 if (*cmd == POOL_SCRUB_PAUSE) {
969 /* can't pause a scrub when there is no in-progress scrub */
970 spa->spa_scan_pass_scrub_pause = gethrestime_sec();
971 scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
d4a72f23 972 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
43cb30b3 973 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);
0ea05c64
AP
974 } else {
975 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
976 if (dsl_scan_is_paused_scrub(scn)) {
977 /*
978 * We need to keep track of how much time we spend
979 * paused per pass so that we can adjust the scrub rate
980 * shown in the output of 'zpool status'
981 */
982 spa->spa_scan_pass_scrub_spent_paused +=
983 gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
984 spa->spa_scan_pass_scrub_pause = 0;
985 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
d4a72f23 986 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
0ea05c64
AP
987 }
988 }
989}
990
991/*
992 * Set scrub pause/resume state if it makes sense to do so
993 */
994int
995dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
996{
997 return (dsl_sync_task(spa_name(dp->dp_spa),
998 dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
999 ZFS_SPACE_CHECK_RESERVED));
1000}
1001
0ea05c64 1002
d4a72f23
TC
1003/* start a new scan, or restart an existing one. */
1004void
1005dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg)
1006{
1007 if (txg == 0) {
1008 dmu_tx_t *tx;
1009 tx = dmu_tx_create_dd(dp->dp_mos_dir);
1010 VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
0ea05c64 1011
d4a72f23
TC
1012 txg = dmu_tx_get_txg(tx);
1013 dp->dp_scan->scn_restart_txg = txg;
1014 dmu_tx_commit(tx);
1015 } else {
1016 dp->dp_scan->scn_restart_txg = txg;
1017 }
1018 zfs_dbgmsg("restarting resilver txg=%llu", (longlong_t)txg);
0ea05c64
AP
1019}
1020
428870ff
BB
1021void
1022dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
1023{
1024 zio_free(dp->dp_spa, txg, bp);
1025}
1026
1027void
1028dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
1029{
1030 ASSERT(dsl_pool_sync_context(dp));
1031 zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));
1032}
1033
d4a72f23
TC
1034static int
1035scan_ds_queue_compare(const void *a, const void *b)
428870ff 1036{
d4a72f23
TC
1037 const scan_ds_t *sds_a = a, *sds_b = b;
1038
1039 if (sds_a->sds_dsobj < sds_b->sds_dsobj)
1040 return (-1);
1041 if (sds_a->sds_dsobj == sds_b->sds_dsobj)
1042 return (0);
1043 return (1);
428870ff
BB
1044}
1045
1046static void
d4a72f23
TC
1047scan_ds_queue_clear(dsl_scan_t *scn)
1048{
1049 void *cookie = NULL;
1050 scan_ds_t *sds;
1051 while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {
1052 kmem_free(sds, sizeof (*sds));
1053 }
1054}
1055
1056static boolean_t
1057scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)
428870ff 1058{
d4a72f23
TC
1059 scan_ds_t srch, *sds;
1060
1061 srch.sds_dsobj = dsobj;
1062 sds = avl_find(&scn->scn_queue, &srch, NULL);
1063 if (sds != NULL && txg != NULL)
1064 *txg = sds->sds_txg;
1065 return (sds != NULL);
428870ff
BB
1066}
1067
d4a72f23
TC
1068static void
1069scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)
1070{
1071 scan_ds_t *sds;
1072 avl_index_t where;
1073
1074 sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);
1075 sds->sds_dsobj = dsobj;
1076 sds->sds_txg = txg;
1077
1078 VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);
1079 avl_insert(&scn->scn_queue, sds, where);
1080}
1081
1082static void
1083scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)
1084{
1085 scan_ds_t srch, *sds;
1086
1087 srch.sds_dsobj = dsobj;
1088
1089 sds = avl_find(&scn->scn_queue, &srch, NULL);
1090 VERIFY(sds != NULL);
1091 avl_remove(&scn->scn_queue, sds);
1092 kmem_free(sds, sizeof (*sds));
1093}
1094
1095static void
1096scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)
1097{
1098 dsl_pool_t *dp = scn->scn_dp;
1099 spa_t *spa = dp->dp_spa;
1100 dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?
1101 DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;
1102
1103 ASSERT0(scn->scn_bytes_pending);
1104 ASSERT(scn->scn_phys.scn_queue_obj != 0);
1105
1106 VERIFY0(dmu_object_free(dp->dp_meta_objset,
1107 scn->scn_phys.scn_queue_obj, tx));
1108 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,
1109 DMU_OT_NONE, 0, tx);
1110 for (scan_ds_t *sds = avl_first(&scn->scn_queue);
1111 sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {
1112 VERIFY0(zap_add_int_key(dp->dp_meta_objset,
1113 scn->scn_phys.scn_queue_obj, sds->sds_dsobj,
1114 sds->sds_txg, tx));
1115 }
1116}
1117
1118/*
1119 * Computes the memory limit state that we're currently in. A sorted scan
1120 * needs quite a bit of memory to hold the sorting queue, so we need to
1121 * reasonably constrain the size so it doesn't impact overall system
1122 * performance. We compute two limits:
1123 * 1) Hard memory limit: if the amount of memory used by the sorting
1124 * queues on a pool gets above this value, we stop the metadata
1125 * scanning portion and start issuing the queued up and sorted
1126 * I/Os to reduce memory usage.
1127 * This limit is calculated as a fraction of physmem (by default 5%).
1128 * We constrain the lower bound of the hard limit to an absolute
1129 * minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain
1130 * the upper bound to 5% of the total pool size - no chance we'll
1131 * ever need that much memory, but just to keep the value in check.
1132 * 2) Soft memory limit: once we hit the hard memory limit, we start
1133 * issuing I/O to reduce queue memory usage, but we don't want to
1134 * completely empty out the queues, since we might be able to find I/Os
1135 * that will fill in the gaps of our non-sequential IOs at some point
1136 * in the future. So we stop the issuing of I/Os once the amount of
1137 * memory used drops below the soft limit (at which point we stop issuing
1138 * I/O and start scanning metadata again).
1139 *
1140 * This limit is calculated by subtracting a fraction of the hard
1141 * limit from the hard limit. By default this fraction is 5%, so
1142 * the soft limit is 95% of the hard limit. We cap the size of the
1143 * difference between the hard and soft limits at an absolute
1144 * maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is
1145 * sufficient to not cause too frequent switching between the
1146 * metadata scan and I/O issue (even at 2k recordsize, 128 MiB's
1147 * worth of queues is about 1.2 GiB of on-pool data, so scanning
1148 * that should take at least a decent fraction of a second).
1149 */
1150static boolean_t
1151dsl_scan_should_clear(dsl_scan_t *scn)
1152{
1153 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
1154 uint64_t mlim_hard, mlim_soft, mused;
1155 uint64_t alloc = metaslab_class_get_alloc(spa_normal_class(
1156 scn->scn_dp->dp_spa));
1157
1158 mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,
1159 zfs_scan_mem_lim_min);
1160 mlim_hard = MIN(mlim_hard, alloc / 20);
1161 mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,
1162 zfs_scan_mem_lim_soft_max);
1163 mused = 0;
1164 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1165 vdev_t *tvd = rvd->vdev_child[i];
1166 dsl_scan_io_queue_t *queue;
1167
1168 mutex_enter(&tvd->vdev_scan_io_queue_lock);
1169 queue = tvd->vdev_scan_io_queue;
1170 if (queue != NULL) {
1171 /* #extents in exts_by_size = # in exts_by_addr */
1172 mused += avl_numnodes(&queue->q_exts_by_size) *
1173 sizeof (range_seg_t) +
1174 avl_numnodes(&queue->q_sios_by_addr) *
1175 sizeof (scan_io_t);
1176 }
1177 mutex_exit(&tvd->vdev_scan_io_queue_lock);
1178 }
1179
1180 dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);
1181
1182 if (mused == 0)
1183 ASSERT0(scn->scn_bytes_pending);
1184
1185 /*
1186 * If we are above our hard limit, we need to clear out memory.
1187 * If we are below our soft limit, we need to accumulate sequential IOs.
1188 * Otherwise, we should keep doing whatever we are currently doing.
1189 */
1190 if (mused >= mlim_hard)
1191 return (B_TRUE);
1192 else if (mused < mlim_soft)
1193 return (B_FALSE);
1194 else
1195 return (scn->scn_clearing);
1196}
10400bfe 1197
428870ff 1198static boolean_t
0ea05c64 1199dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
428870ff 1200{
428870ff
BB
1201 /* we never skip user/group accounting objects */
1202 if (zb && (int64_t)zb->zb_object < 0)
1203 return (B_FALSE);
1204
0ea05c64
AP
1205 if (scn->scn_suspending)
1206 return (B_TRUE); /* we're already suspending */
428870ff 1207
9ae529ec 1208 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
428870ff
BB
1209 return (B_FALSE); /* we're resuming */
1210
1211 /* We only know how to resume from level-0 blocks. */
1212 if (zb && zb->zb_level != 0)
1213 return (B_FALSE);
1214
10400bfe 1215 /*
0ea05c64 1216 * We suspend if:
10400bfe
MA
1217 * - we have scanned for at least the minimum time (default 1 sec
1218 * for scrub, 3 sec for resilver), and either we have sufficient
1219 * dirty data that we are starting to write more quickly
d4a72f23
TC
1220 * (default 30%), someone is explicitly waiting for this txg
1221 * to complete, or we have used up all of the time in the txg
1222 * timeout (default 5 sec).
10400bfe
MA
1223 * or
1224 * - the spa is shutting down because this pool is being exported
1225 * or the machine is rebooting.
d4a72f23
TC
1226 * or
1227 * - the scan queue has reached its memory use limit
10400bfe 1228 */
d4a72f23
TC
1229 uint64_t curr_time_ns = gethrtime();
1230 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
1231 uint64_t sync_time_ns = curr_time_ns -
1232 scn->scn_dp->dp_spa->spa_sync_starttime;
1c27024e 1233 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
d4a72f23
TC
1234 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
1235 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
1236
1237 if ((NSEC2MSEC(scan_time_ns) > mintime &&
1238 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
1239 txg_sync_waiting(scn->scn_dp) ||
1240 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1241 spa_shutting_down(scn->scn_dp->dp_spa) ||
1242 (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn))) {
428870ff 1243 if (zb) {
0ea05c64 1244 dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
428870ff
BB
1245 (longlong_t)zb->zb_objset,
1246 (longlong_t)zb->zb_object,
1247 (longlong_t)zb->zb_level,
1248 (longlong_t)zb->zb_blkid);
1249 scn->scn_phys.scn_bookmark = *zb;
d4a72f23 1250 } else {
21a4f5cc 1251#ifdef ZFS_DEBUG
d4a72f23 1252 dsl_scan_phys_t *scnp = &scn->scn_phys;
d4a72f23
TC
1253 dprintf("suspending at at DDT bookmark "
1254 "%llx/%llx/%llx/%llx\n",
1255 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
1256 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
1257 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
1258 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
21a4f5cc 1259#endif
428870ff 1260 }
0ea05c64 1261 scn->scn_suspending = B_TRUE;
428870ff
BB
1262 return (B_TRUE);
1263 }
1264 return (B_FALSE);
1265}
1266
1267typedef struct zil_scan_arg {
1268 dsl_pool_t *zsa_dp;
1269 zil_header_t *zsa_zh;
1270} zil_scan_arg_t;
1271
1272/* ARGSUSED */
1273static int
1274dsl_scan_zil_block(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1275{
1276 zil_scan_arg_t *zsa = arg;
1277 dsl_pool_t *dp = zsa->zsa_dp;
1278 dsl_scan_t *scn = dp->dp_scan;
1279 zil_header_t *zh = zsa->zsa_zh;
5dbd68a3 1280 zbookmark_phys_t zb;
428870ff 1281
b0bc7a84 1282 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
428870ff
BB
1283 return (0);
1284
1285 /*
1286 * One block ("stubby") can be allocated a long time ago; we
1287 * want to visit that one because it has been allocated
1288 * (on-disk) even if it hasn't been claimed (even though for
1289 * scrub there's nothing to do to it).
1290 */
d2734cce 1291 if (claim_txg == 0 && bp->blk_birth >= spa_min_claim_txg(dp->dp_spa))
428870ff
BB
1292 return (0);
1293
1294 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1295 ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
1296
1297 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1298 return (0);
1299}
1300
1301/* ARGSUSED */
1302static int
1303dsl_scan_zil_record(zilog_t *zilog, lr_t *lrc, void *arg, uint64_t claim_txg)
1304{
1305 if (lrc->lrc_txtype == TX_WRITE) {
1306 zil_scan_arg_t *zsa = arg;
1307 dsl_pool_t *dp = zsa->zsa_dp;
1308 dsl_scan_t *scn = dp->dp_scan;
1309 zil_header_t *zh = zsa->zsa_zh;
1310 lr_write_t *lr = (lr_write_t *)lrc;
1311 blkptr_t *bp = &lr->lr_blkptr;
5dbd68a3 1312 zbookmark_phys_t zb;
428870ff 1313
b0bc7a84
MG
1314 if (BP_IS_HOLE(bp) ||
1315 bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
428870ff
BB
1316 return (0);
1317
1318 /*
1319 * birth can be < claim_txg if this record's txg is
1320 * already txg sync'ed (but this log block contains
1321 * other records that are not synced)
1322 */
1323 if (claim_txg == 0 || bp->blk_birth < claim_txg)
1324 return (0);
1325
1326 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1327 lr->lr_foid, ZB_ZIL_LEVEL,
1328 lr->lr_offset / BP_GET_LSIZE(bp));
1329
1330 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1331 }
1332 return (0);
1333}
1334
1335static void
1336dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
1337{
1338 uint64_t claim_txg = zh->zh_claim_txg;
1339 zil_scan_arg_t zsa = { dp, zh };
1340 zilog_t *zilog;
1341
d2734cce
SD
1342 ASSERT(spa_writeable(dp->dp_spa));
1343
428870ff
BB
1344 /*
1345 * We only want to visit blocks that have been claimed but not yet
1346 * replayed (or, in read-only mode, blocks that *would* be claimed).
1347 */
d2734cce 1348 if (claim_txg == 0)
428870ff
BB
1349 return;
1350
1351 zilog = zil_alloc(dp->dp_meta_objset, zh);
1352
1353 (void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
b5256303 1354 claim_txg, B_FALSE);
428870ff
BB
1355
1356 zil_free(zilog);
1357}
1358
d4a72f23
TC
1359/*
1360 * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea
1361 * here is to sort the AVL tree by the order each block will be needed.
1362 */
1363static int
1364scan_prefetch_queue_compare(const void *a, const void *b)
428870ff 1365{
d4a72f23
TC
1366 const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;
1367 const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;
1368 const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;
428870ff 1369
d4a72f23
TC
1370 return (zbookmark_compare(spc_a->spc_datablkszsec,
1371 spc_a->spc_indblkshift, spc_b->spc_datablkszsec,
1372 spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));
1373}
428870ff 1374
d4a72f23
TC
1375static void
1376scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, void *tag)
1377{
424fd7c3
TS
1378 if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {
1379 zfs_refcount_destroy(&spc->spc_refcnt);
d4a72f23
TC
1380 kmem_free(spc, sizeof (scan_prefetch_ctx_t));
1381 }
1382}
1383
1384static scan_prefetch_ctx_t *
1385scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, void *tag)
1386{
1387 scan_prefetch_ctx_t *spc;
1388
1389 spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);
424fd7c3 1390 zfs_refcount_create(&spc->spc_refcnt);
c13060e4 1391 zfs_refcount_add(&spc->spc_refcnt, tag);
d4a72f23
TC
1392 spc->spc_scn = scn;
1393 if (dnp != NULL) {
1394 spc->spc_datablkszsec = dnp->dn_datablkszsec;
1395 spc->spc_indblkshift = dnp->dn_indblkshift;
1396 spc->spc_root = B_FALSE;
1397 } else {
1398 spc->spc_datablkszsec = 0;
1399 spc->spc_indblkshift = 0;
1400 spc->spc_root = B_TRUE;
1401 }
1402
1403 return (spc);
1404}
1405
1406static void
1407scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, void *tag)
1408{
c13060e4 1409 zfs_refcount_add(&spc->spc_refcnt, tag);
d4a72f23
TC
1410}
1411
1412static boolean_t
1413dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,
1414 const zbookmark_phys_t *zb)
1415{
1416 zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;
1417 dnode_phys_t tmp_dnp;
1418 dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;
1419
1420 if (zb->zb_objset != last_zb->zb_objset)
1421 return (B_TRUE);
1422 if ((int64_t)zb->zb_object < 0)
1423 return (B_FALSE);
1424
1425 tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;
1426 tmp_dnp.dn_indblkshift = spc->spc_indblkshift;
1427
1428 if (zbookmark_subtree_completed(dnp, zb, last_zb))
1429 return (B_TRUE);
1430
1431 return (B_FALSE);
1432}
1433
1434static void
1435dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)
1436{
1437 avl_index_t idx;
1438 dsl_scan_t *scn = spc->spc_scn;
1439 spa_t *spa = scn->scn_dp->dp_spa;
1440 scan_prefetch_issue_ctx_t *spic;
1441
1442 if (zfs_no_scrub_prefetch)
1443 return;
1444
1445 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg ||
1446 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
1447 BP_GET_TYPE(bp) != DMU_OT_OBJSET))
1448 return;
1449
1450 if (dsl_scan_check_prefetch_resume(spc, zb))
1451 return;
1452
1453 scan_prefetch_ctx_add_ref(spc, scn);
1454 spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);
1455 spic->spic_spc = spc;
1456 spic->spic_bp = *bp;
1457 spic->spic_zb = *zb;
1458
1459 /*
1460 * Add the IO to the queue of blocks to prefetch. This allows us to
1461 * prioritize blocks that we will need first for the main traversal
1462 * thread.
1463 */
1464 mutex_enter(&spa->spa_scrub_lock);
1465 if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {
1466 /* this block is already queued for prefetch */
1467 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1468 scan_prefetch_ctx_rele(spc, scn);
1469 mutex_exit(&spa->spa_scrub_lock);
1470 return;
1471 }
1472
1473 avl_insert(&scn->scn_prefetch_queue, spic, idx);
1474 cv_broadcast(&spa->spa_scrub_io_cv);
1475 mutex_exit(&spa->spa_scrub_lock);
1476}
1477
1478static void
1479dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,
1480 uint64_t objset, uint64_t object)
1481{
1482 int i;
1483 zbookmark_phys_t zb;
1484 scan_prefetch_ctx_t *spc;
1485
1486 if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1487 return;
1488
1489 SET_BOOKMARK(&zb, objset, object, 0, 0);
1490
1491 spc = scan_prefetch_ctx_create(scn, dnp, FTAG);
1492
1493 for (i = 0; i < dnp->dn_nblkptr; i++) {
1494 zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);
1495 zb.zb_blkid = i;
1496 dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);
1497 }
1498
1499 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1500 zb.zb_level = 0;
1501 zb.zb_blkid = DMU_SPILL_BLKID;
1502 dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);
1503 }
1504
1505 scan_prefetch_ctx_rele(spc, FTAG);
1506}
1507
1508void
1509dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
1510 arc_buf_t *buf, void *private)
1511{
1512 scan_prefetch_ctx_t *spc = private;
1513 dsl_scan_t *scn = spc->spc_scn;
1514 spa_t *spa = scn->scn_dp->dp_spa;
1515
13a2ff27 1516 /* broadcast that the IO has completed for rate limiting purposes */
d4a72f23
TC
1517 mutex_enter(&spa->spa_scrub_lock);
1518 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
1519 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
1520 cv_broadcast(&spa->spa_scrub_io_cv);
1521 mutex_exit(&spa->spa_scrub_lock);
1522
1523 /* if there was an error or we are done prefetching, just cleanup */
13a2ff27 1524 if (buf == NULL || scn->scn_prefetch_stop)
d4a72f23
TC
1525 goto out;
1526
1527 if (BP_GET_LEVEL(bp) > 0) {
1528 int i;
1529 blkptr_t *cbp;
1530 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1531 zbookmark_phys_t czb;
1532
1533 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
1534 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1535 zb->zb_level - 1, zb->zb_blkid * epb + i);
1536 dsl_scan_prefetch(spc, cbp, &czb);
1537 }
1538 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
1539 dnode_phys_t *cdnp;
1540 int i;
1541 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
1542
1543 for (i = 0, cdnp = buf->b_data; i < epb;
1544 i += cdnp->dn_extra_slots + 1,
1545 cdnp += cdnp->dn_extra_slots + 1) {
1546 dsl_scan_prefetch_dnode(scn, cdnp,
1547 zb->zb_objset, zb->zb_blkid * epb + i);
1548 }
1549 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1550 objset_phys_t *osp = buf->b_data;
1551
1552 dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,
1553 zb->zb_objset, DMU_META_DNODE_OBJECT);
1554
1555 if (OBJSET_BUF_HAS_USERUSED(buf)) {
1556 dsl_scan_prefetch_dnode(scn,
1557 &osp->os_groupused_dnode, zb->zb_objset,
1558 DMU_GROUPUSED_OBJECT);
1559 dsl_scan_prefetch_dnode(scn,
1560 &osp->os_userused_dnode, zb->zb_objset,
1561 DMU_USERUSED_OBJECT);
1562 }
1563 }
1564
1565out:
1566 if (buf != NULL)
1567 arc_buf_destroy(buf, private);
1568 scan_prefetch_ctx_rele(spc, scn);
1569}
1570
1571/* ARGSUSED */
1572static void
1573dsl_scan_prefetch_thread(void *arg)
1574{
1575 dsl_scan_t *scn = arg;
1576 spa_t *spa = scn->scn_dp->dp_spa;
1577 scan_prefetch_issue_ctx_t *spic;
1578
1579 /* loop until we are told to stop */
1580 while (!scn->scn_prefetch_stop) {
1581 arc_flags_t flags = ARC_FLAG_NOWAIT |
1582 ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;
1583 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
1584
1585 mutex_enter(&spa->spa_scrub_lock);
1586
1587 /*
1588 * Wait until we have an IO to issue and are not above our
1589 * maximum in flight limit.
1590 */
1591 while (!scn->scn_prefetch_stop &&
1592 (avl_numnodes(&scn->scn_prefetch_queue) == 0 ||
1593 spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {
1594 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1595 }
1596
1597 /* recheck if we should stop since we waited for the cv */
1598 if (scn->scn_prefetch_stop) {
1599 mutex_exit(&spa->spa_scrub_lock);
1600 break;
1601 }
1602
1603 /* remove the prefetch IO from the tree */
1604 spic = avl_first(&scn->scn_prefetch_queue);
1605 spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);
1606 avl_remove(&scn->scn_prefetch_queue, spic);
1607
1608 mutex_exit(&spa->spa_scrub_lock);
1609
1610 if (BP_IS_PROTECTED(&spic->spic_bp)) {
1611 ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||
1612 BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);
1613 ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);
1614 zio_flags |= ZIO_FLAG_RAW;
1615 }
1616
1617 /* issue the prefetch asynchronously */
1618 (void) arc_read(scn->scn_zio_root, scn->scn_dp->dp_spa,
1619 &spic->spic_bp, dsl_scan_prefetch_cb, spic->spic_spc,
a8b2e306 1620 ZIO_PRIORITY_SCRUB, zio_flags, &flags, &spic->spic_zb);
428870ff 1621
d4a72f23 1622 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
b5256303
TC
1623 }
1624
d4a72f23 1625 ASSERT(scn->scn_prefetch_stop);
428870ff 1626
d4a72f23
TC
1627 /* free any prefetches we didn't get to complete */
1628 mutex_enter(&spa->spa_scrub_lock);
1629 while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {
1630 avl_remove(&scn->scn_prefetch_queue, spic);
1631 scan_prefetch_ctx_rele(spic->spic_spc, scn);
1632 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1633 }
1634 ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));
1635 mutex_exit(&spa->spa_scrub_lock);
428870ff
BB
1636}
1637
1638static boolean_t
1639dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
5dbd68a3 1640 const zbookmark_phys_t *zb)
428870ff
BB
1641{
1642 /*
1643 * We never skip over user/group accounting objects (obj<0)
1644 */
9ae529ec 1645 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
428870ff
BB
1646 (int64_t)zb->zb_object >= 0) {
1647 /*
1648 * If we already visited this bp & everything below (in
1649 * a prior txg sync), don't bother doing it again.
1650 */
fcff0f35
PD
1651 if (zbookmark_subtree_completed(dnp, zb,
1652 &scn->scn_phys.scn_bookmark))
428870ff
BB
1653 return (B_TRUE);
1654
1655 /*
1656 * If we found the block we're trying to resume from, or
1657 * we went past it to a different object, zero it out to
0ea05c64 1658 * indicate that it's OK to start checking for suspending
428870ff
BB
1659 * again.
1660 */
1661 if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 ||
1662 zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) {
1663 dprintf("resuming at %llx/%llx/%llx/%llx\n",
1664 (longlong_t)zb->zb_objset,
1665 (longlong_t)zb->zb_object,
1666 (longlong_t)zb->zb_level,
1667 (longlong_t)zb->zb_blkid);
1668 bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb));
1669 }
1670 }
1671 return (B_FALSE);
1672}
1673
d4a72f23
TC
1674static void dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
1675 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1676 dmu_objset_type_t ostype, dmu_tx_t *tx);
1677inline __attribute__((always_inline)) static void dsl_scan_visitdnode(
1678 dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1679 dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
1680
428870ff
BB
1681/*
1682 * Return nonzero on i/o error.
1683 * Return new buf to write out in *bufp.
1684 */
10be533e 1685inline __attribute__((always_inline)) static int
428870ff
BB
1686dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1687 dnode_phys_t *dnp, const blkptr_t *bp,
ebcf4936 1688 const zbookmark_phys_t *zb, dmu_tx_t *tx)
428870ff
BB
1689{
1690 dsl_pool_t *dp = scn->scn_dp;
572e2857 1691 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
428870ff
BB
1692 int err;
1693
1694 if (BP_GET_LEVEL(bp) > 0) {
2a432414 1695 arc_flags_t flags = ARC_FLAG_WAIT;
428870ff
BB
1696 int i;
1697 blkptr_t *cbp;
1698 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
ebcf4936 1699 arc_buf_t *buf;
428870ff 1700
ebcf4936 1701 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
a8b2e306 1702 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
428870ff
BB
1703 if (err) {
1704 scn->scn_phys.scn_errors++;
1705 return (err);
1706 }
ebcf4936 1707 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
5dbd68a3 1708 zbookmark_phys_t czb;
428870ff
BB
1709
1710 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1711 zb->zb_level - 1,
1712 zb->zb_blkid * epb + i);
1713 dsl_scan_visitbp(cbp, &czb, dnp,
ebcf4936 1714 ds, scn, ostype, tx);
428870ff 1715 }
d3c2ae1c 1716 arc_buf_destroy(buf, &buf);
428870ff 1717 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
2a432414 1718 arc_flags_t flags = ARC_FLAG_WAIT;
428870ff 1719 dnode_phys_t *cdnp;
d4a72f23 1720 int i;
428870ff 1721 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
ebcf4936 1722 arc_buf_t *buf;
428870ff 1723
b5256303
TC
1724 if (BP_IS_PROTECTED(bp)) {
1725 ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
1726 zio_flags |= ZIO_FLAG_RAW;
1727 }
1728
ebcf4936 1729 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
a8b2e306 1730 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
428870ff
BB
1731 if (err) {
1732 scn->scn_phys.scn_errors++;
1733 return (err);
1734 }
50c957f7
NB
1735 for (i = 0, cdnp = buf->b_data; i < epb;
1736 i += cdnp->dn_extra_slots + 1,
1737 cdnp += cdnp->dn_extra_slots + 1) {
428870ff 1738 dsl_scan_visitdnode(scn, ds, ostype,
ebcf4936 1739 cdnp, zb->zb_blkid * epb + i, tx);
428870ff
BB
1740 }
1741
d3c2ae1c 1742 arc_buf_destroy(buf, &buf);
428870ff 1743 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
2a432414 1744 arc_flags_t flags = ARC_FLAG_WAIT;
428870ff 1745 objset_phys_t *osp;
ebcf4936 1746 arc_buf_t *buf;
428870ff 1747
ebcf4936 1748 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
a8b2e306 1749 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
428870ff
BB
1750 if (err) {
1751 scn->scn_phys.scn_errors++;
1752 return (err);
1753 }
1754
ebcf4936 1755 osp = buf->b_data;
428870ff 1756
428870ff 1757 dsl_scan_visitdnode(scn, ds, osp->os_type,
ebcf4936 1758 &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
428870ff 1759
ebcf4936 1760 if (OBJSET_BUF_HAS_USERUSED(buf)) {
428870ff 1761 /*
9c5167d1 1762 * We also always visit user/group/project accounting
428870ff 1763 * objects, and never skip them, even if we are
d4a72f23
TC
1764 * suspending. This is necessary so that the
1765 * space deltas from this txg get integrated.
428870ff 1766 */
9c5167d1
NF
1767 if (OBJSET_BUF_HAS_PROJECTUSED(buf))
1768 dsl_scan_visitdnode(scn, ds, osp->os_type,
1769 &osp->os_projectused_dnode,
1770 DMU_PROJECTUSED_OBJECT, tx);
428870ff 1771 dsl_scan_visitdnode(scn, ds, osp->os_type,
ebcf4936 1772 &osp->os_groupused_dnode,
428870ff
BB
1773 DMU_GROUPUSED_OBJECT, tx);
1774 dsl_scan_visitdnode(scn, ds, osp->os_type,
ebcf4936 1775 &osp->os_userused_dnode,
428870ff
BB
1776 DMU_USERUSED_OBJECT, tx);
1777 }
d3c2ae1c 1778 arc_buf_destroy(buf, &buf);
428870ff
BB
1779 }
1780
1781 return (0);
1782}
1783
10be533e 1784inline __attribute__((always_inline)) static void
428870ff 1785dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
ebcf4936 1786 dmu_objset_type_t ostype, dnode_phys_t *dnp,
428870ff
BB
1787 uint64_t object, dmu_tx_t *tx)
1788{
1789 int j;
1790
1791 for (j = 0; j < dnp->dn_nblkptr; j++) {
5dbd68a3 1792 zbookmark_phys_t czb;
428870ff
BB
1793
1794 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1795 dnp->dn_nlevels - 1, j);
1796 dsl_scan_visitbp(&dnp->dn_blkptr[j],
ebcf4936 1797 &czb, dnp, ds, scn, ostype, tx);
428870ff
BB
1798 }
1799
1800 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
5dbd68a3 1801 zbookmark_phys_t czb;
428870ff
BB
1802 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1803 0, DMU_SPILL_BLKID);
50c957f7 1804 dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),
ebcf4936 1805 &czb, dnp, ds, scn, ostype, tx);
428870ff
BB
1806 }
1807}
1808
1809/*
1810 * The arguments are in this order because mdb can only print the
1811 * first 5; we want them to be useful.
1812 */
1813static void
5dbd68a3 1814dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
ebcf4936
MA
1815 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1816 dmu_objset_type_t ostype, dmu_tx_t *tx)
428870ff
BB
1817{
1818 dsl_pool_t *dp = scn->scn_dp;
d4a72f23 1819 blkptr_t *bp_toread = NULL;
428870ff 1820
0ea05c64 1821 if (dsl_scan_check_suspend(scn, zb))
d4a72f23 1822 return;
428870ff
BB
1823
1824 if (dsl_scan_check_resume(scn, dnp, zb))
d4a72f23 1825 return;
428870ff
BB
1826
1827 scn->scn_visited_this_txg++;
1828
b81c4ac9
BB
1829 /*
1830 * This debugging is commented out to conserve stack space. This
1831 * function is called recursively and the debugging addes several
1832 * bytes to the stack for each call. It can be commented back in
1833 * if required to debug an issue in dsl_scan_visitbp().
1834 *
1835 * dprintf_bp(bp,
d4a72f23
TC
1836 * "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p",
1837 * ds, ds ? ds->ds_object : 0,
1838 * zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid,
1839 * bp);
b81c4ac9 1840 */
428870ff 1841
d4a72f23
TC
1842 if (BP_IS_HOLE(bp)) {
1843 scn->scn_holes_this_txg++;
1844 return;
1845 }
1846
1847 if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) {
1848 scn->scn_lt_min_this_txg++;
1849 return;
1850 }
1851
1852 bp_toread = kmem_alloc(sizeof (blkptr_t), KM_SLEEP);
1853 *bp_toread = *bp;
428870ff 1854
ebcf4936 1855 if (dsl_scan_recurse(scn, ds, ostype, dnp, bp_toread, zb, tx) != 0)
161ce7ce 1856 goto out;
428870ff
BB
1857
1858 /*
4e33ba4c 1859 * If dsl_scan_ddt() has already visited this block, it will have
428870ff
BB
1860 * already done any translations or scrubbing, so don't call the
1861 * callback again.
1862 */
1863 if (ddt_class_contains(dp->dp_spa,
1864 scn->scn_phys.scn_ddt_class_max, bp)) {
d4a72f23 1865 scn->scn_ddt_contained_this_txg++;
161ce7ce 1866 goto out;
428870ff
BB
1867 }
1868
1869 /*
1870 * If this block is from the future (after cur_max_txg), then we
1871 * are doing this on behalf of a deleted snapshot, and we will
1872 * revisit the future block on the next pass of this dataset.
1873 * Don't scan it now unless we need to because something
1874 * under it was modified.
1875 */
d4a72f23
TC
1876 if (BP_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {
1877 scn->scn_gt_max_this_txg++;
1878 goto out;
428870ff 1879 }
d4a72f23
TC
1880
1881 scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
1882
161ce7ce 1883out:
d1d7e268 1884 kmem_free(bp_toread, sizeof (blkptr_t));
428870ff
BB
1885}
1886
1887static void
1888dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
1889 dmu_tx_t *tx)
1890{
5dbd68a3 1891 zbookmark_phys_t zb;
d4a72f23 1892 scan_prefetch_ctx_t *spc;
428870ff
BB
1893
1894 SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1895 ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
d4a72f23
TC
1896
1897 if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {
1898 SET_BOOKMARK(&scn->scn_prefetch_bookmark,
1899 zb.zb_objset, 0, 0, 0);
1900 } else {
1901 scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;
1902 }
1903
1904 scn->scn_objsets_visited_this_txg++;
1905
1906 spc = scan_prefetch_ctx_create(scn, NULL, FTAG);
1907 dsl_scan_prefetch(spc, bp, &zb);
1908 scan_prefetch_ctx_rele(spc, FTAG);
1909
1910 dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);
428870ff
BB
1911
1912 dprintf_ds(ds, "finished scan%s", "");
1913}
1914
d4a72f23
TC
1915static void
1916ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)
428870ff 1917{
d4a72f23 1918 if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {
0c66c32d 1919 if (ds->ds_is_snapshot) {
b77222c8
MA
1920 /*
1921 * Note:
1922 * - scn_cur_{min,max}_txg stays the same.
1923 * - Setting the flag is not really necessary if
1924 * scn_cur_max_txg == scn_max_txg, because there
1925 * is nothing after this snapshot that we care
1926 * about. However, we set it anyway and then
1927 * ignore it when we retraverse it in
1928 * dsl_scan_visitds().
1929 */
d4a72f23 1930 scn_phys->scn_bookmark.zb_objset =
d683ddbb 1931 dsl_dataset_phys(ds)->ds_next_snap_obj;
428870ff
BB
1932 zfs_dbgmsg("destroying ds %llu; currently traversing; "
1933 "reset zb_objset to %llu",
1934 (u_longlong_t)ds->ds_object,
d683ddbb
JG
1935 (u_longlong_t)dsl_dataset_phys(ds)->
1936 ds_next_snap_obj);
d4a72f23 1937 scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;
428870ff 1938 } else {
d4a72f23 1939 SET_BOOKMARK(&scn_phys->scn_bookmark,
428870ff
BB
1940 ZB_DESTROYED_OBJSET, 0, 0, 0);
1941 zfs_dbgmsg("destroying ds %llu; currently traversing; "
1942 "reset bookmark to -1,0,0,0",
1943 (u_longlong_t)ds->ds_object);
1944 }
d4a72f23
TC
1945 }
1946}
1947
1948/*
1949 * Invoked when a dataset is destroyed. We need to make sure that:
1950 *
1951 * 1) If it is the dataset that was currently being scanned, we write
1952 * a new dsl_scan_phys_t and marking the objset reference in it
1953 * as destroyed.
1954 * 2) Remove it from the work queue, if it was present.
1955 *
1956 * If the dataset was actually a snapshot, instead of marking the dataset
1957 * as destroyed, we instead substitute the next snapshot in line.
1958 */
1959void
1960dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
1961{
1962 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1963 dsl_scan_t *scn = dp->dp_scan;
1964 uint64_t mintxg;
1965
1966 if (!dsl_scan_is_running(scn))
1967 return;
1968
1969 ds_destroyed_scn_phys(ds, &scn->scn_phys);
1970 ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);
1971
1972 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
1973 scan_ds_queue_remove(scn, ds->ds_object);
1974 if (ds->ds_is_snapshot)
1975 scan_ds_queue_insert(scn,
1976 dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);
1977 }
1978
1979 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1980 ds->ds_object, &mintxg) == 0) {
d683ddbb 1981 ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
428870ff
BB
1982 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1983 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
0c66c32d 1984 if (ds->ds_is_snapshot) {
428870ff
BB
1985 /*
1986 * We keep the same mintxg; it could be >
1987 * ds_creation_txg if the previous snapshot was
1988 * deleted too.
1989 */
1990 VERIFY(zap_add_int_key(dp->dp_meta_objset,
1991 scn->scn_phys.scn_queue_obj,
d683ddbb
JG
1992 dsl_dataset_phys(ds)->ds_next_snap_obj,
1993 mintxg, tx) == 0);
428870ff
BB
1994 zfs_dbgmsg("destroying ds %llu; in queue; "
1995 "replacing with %llu",
1996 (u_longlong_t)ds->ds_object,
d683ddbb
JG
1997 (u_longlong_t)dsl_dataset_phys(ds)->
1998 ds_next_snap_obj);
428870ff
BB
1999 } else {
2000 zfs_dbgmsg("destroying ds %llu; in queue; removing",
2001 (u_longlong_t)ds->ds_object);
2002 }
428870ff
BB
2003 }
2004
2005 /*
2006 * dsl_scan_sync() should be called after this, and should sync
2007 * out our changed state, but just to be safe, do it here.
2008 */
d4a72f23
TC
2009 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2010}
2011
2012static void
2013ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)
2014{
2015 if (scn_bookmark->zb_objset == ds->ds_object) {
2016 scn_bookmark->zb_objset =
2017 dsl_dataset_phys(ds)->ds_prev_snap_obj;
2018 zfs_dbgmsg("snapshotting ds %llu; currently traversing; "
2019 "reset zb_objset to %llu",
2020 (u_longlong_t)ds->ds_object,
2021 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2022 }
428870ff
BB
2023}
2024
d4a72f23
TC
2025/*
2026 * Called when a dataset is snapshotted. If we were currently traversing
2027 * this snapshot, we reset our bookmark to point at the newly created
2028 * snapshot. We also modify our work queue to remove the old snapshot and
2029 * replace with the new one.
2030 */
428870ff
BB
2031void
2032dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
2033{
2034 dsl_pool_t *dp = ds->ds_dir->dd_pool;
2035 dsl_scan_t *scn = dp->dp_scan;
2036 uint64_t mintxg;
2037
d4a72f23 2038 if (!dsl_scan_is_running(scn))
428870ff
BB
2039 return;
2040
d683ddbb 2041 ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
428870ff 2042
d4a72f23
TC
2043 ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);
2044 ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);
2045
2046 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2047 scan_ds_queue_remove(scn, ds->ds_object);
2048 scan_ds_queue_insert(scn,
2049 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);
2050 }
2051
2052 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2053 ds->ds_object, &mintxg) == 0) {
428870ff
BB
2054 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2055 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2056 VERIFY(zap_add_int_key(dp->dp_meta_objset,
2057 scn->scn_phys.scn_queue_obj,
d683ddbb 2058 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
428870ff
BB
2059 zfs_dbgmsg("snapshotting ds %llu; in queue; "
2060 "replacing with %llu",
2061 (u_longlong_t)ds->ds_object,
d683ddbb 2062 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
428870ff 2063 }
d4a72f23
TC
2064
2065 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
428870ff
BB
2066}
2067
d4a72f23
TC
2068static void
2069ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,
2070 zbookmark_phys_t *scn_bookmark)
428870ff 2071{
d4a72f23
TC
2072 if (scn_bookmark->zb_objset == ds1->ds_object) {
2073 scn_bookmark->zb_objset = ds2->ds_object;
428870ff
BB
2074 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2075 "reset zb_objset to %llu",
2076 (u_longlong_t)ds1->ds_object,
2077 (u_longlong_t)ds2->ds_object);
d4a72f23
TC
2078 } else if (scn_bookmark->zb_objset == ds2->ds_object) {
2079 scn_bookmark->zb_objset = ds1->ds_object;
428870ff
BB
2080 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2081 "reset zb_objset to %llu",
2082 (u_longlong_t)ds2->ds_object,
2083 (u_longlong_t)ds1->ds_object);
2084 }
d4a72f23
TC
2085}
2086
2087/*
2088 * Called when a parent dataset and its clone are swapped. If we were
2089 * currently traversing the dataset, we need to switch to traversing the
2090 * newly promoted parent.
2091 */
2092void
2093dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
2094{
2095 dsl_pool_t *dp = ds1->ds_dir->dd_pool;
2096 dsl_scan_t *scn = dp->dp_scan;
2097 uint64_t mintxg;
2098
2099 if (!dsl_scan_is_running(scn))
2100 return;
2101
2102 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);
2103 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);
2104
2105 if (scan_ds_queue_contains(scn, ds1->ds_object, &mintxg)) {
2106 scan_ds_queue_remove(scn, ds1->ds_object);
2107 scan_ds_queue_insert(scn, ds2->ds_object, mintxg);
2108 }
2109 if (scan_ds_queue_contains(scn, ds2->ds_object, &mintxg)) {
2110 scan_ds_queue_remove(scn, ds2->ds_object);
2111 scan_ds_queue_insert(scn, ds1->ds_object, mintxg);
2112 }
428870ff
BB
2113
2114 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2115 ds1->ds_object, &mintxg) == 0) {
2116 int err;
d683ddbb
JG
2117 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2118 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
428870ff
BB
2119 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2120 scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
2121 err = zap_add_int_key(dp->dp_meta_objset,
2122 scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg, tx);
2123 VERIFY(err == 0 || err == EEXIST);
2124 if (err == EEXIST) {
2125 /* Both were there to begin with */
2126 VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
2127 scn->scn_phys.scn_queue_obj,
2128 ds1->ds_object, mintxg, tx));
2129 }
2130 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2131 "replacing with %llu",
2132 (u_longlong_t)ds1->ds_object,
2133 (u_longlong_t)ds2->ds_object);
d4a72f23
TC
2134 }
2135 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2136 ds2->ds_object, &mintxg) == 0) {
d683ddbb
JG
2137 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2138 ASSERT3U(mintxg, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
428870ff
BB
2139 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2140 scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
2141 VERIFY(0 == zap_add_int_key(dp->dp_meta_objset,
2142 scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg, tx));
2143 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2144 "replacing with %llu",
2145 (u_longlong_t)ds2->ds_object,
2146 (u_longlong_t)ds1->ds_object);
2147 }
2148
d4a72f23 2149 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
428870ff
BB
2150}
2151
428870ff
BB
2152/* ARGSUSED */
2153static int
13fe0198 2154enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
428870ff 2155{
d4a72f23 2156 uint64_t originobj = *(uint64_t *)arg;
428870ff
BB
2157 dsl_dataset_t *ds;
2158 int err;
428870ff
BB
2159 dsl_scan_t *scn = dp->dp_scan;
2160
d4a72f23 2161 if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)
13fe0198
MA
2162 return (0);
2163
2164 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
428870ff
BB
2165 if (err)
2166 return (err);
2167
d4a72f23 2168 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {
13fe0198
MA
2169 dsl_dataset_t *prev;
2170 err = dsl_dataset_hold_obj(dp,
d683ddbb 2171 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
428870ff 2172
13fe0198
MA
2173 dsl_dataset_rele(ds, FTAG);
2174 if (err)
2175 return (err);
2176 ds = prev;
428870ff 2177 }
d4a72f23
TC
2178 scan_ds_queue_insert(scn, ds->ds_object,
2179 dsl_dataset_phys(ds)->ds_prev_snap_txg);
428870ff
BB
2180 dsl_dataset_rele(ds, FTAG);
2181 return (0);
2182}
2183
2184static void
2185dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
2186{
2187 dsl_pool_t *dp = scn->scn_dp;
2188 dsl_dataset_t *ds;
2189
2190 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2191
b77222c8
MA
2192 if (scn->scn_phys.scn_cur_min_txg >=
2193 scn->scn_phys.scn_max_txg) {
2194 /*
2195 * This can happen if this snapshot was created after the
2196 * scan started, and we already completed a previous snapshot
2197 * that was created after the scan started. This snapshot
2198 * only references blocks with:
2199 *
2200 * birth < our ds_creation_txg
2201 * cur_min_txg is no less than ds_creation_txg.
2202 * We have already visited these blocks.
2203 * or
2204 * birth > scn_max_txg
2205 * The scan requested not to visit these blocks.
2206 *
2207 * Subsequent snapshots (and clones) can reference our
2208 * blocks, or blocks with even higher birth times.
2209 * Therefore we do not need to visit them either,
2210 * so we do not add them to the work queue.
2211 *
2212 * Note that checking for cur_min_txg >= cur_max_txg
2213 * is not sufficient, because in that case we may need to
2214 * visit subsequent snapshots. This happens when min_txg > 0,
2215 * which raises cur_min_txg. In this case we will visit
2216 * this dataset but skip all of its blocks, because the
2217 * rootbp's birth time is < cur_min_txg. Then we will
2218 * add the next snapshots/clones to the work queue.
2219 */
eca7b760 2220 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
b77222c8
MA
2221 dsl_dataset_name(ds, dsname);
2222 zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
2223 "cur_min_txg (%llu) >= max_txg (%llu)",
d4a72f23
TC
2224 (longlong_t)dsobj, dsname,
2225 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2226 (longlong_t)scn->scn_phys.scn_max_txg);
b77222c8
MA
2227 kmem_free(dsname, MAXNAMELEN);
2228
2229 goto out;
2230 }
2231
572e2857 2232 /*
a1d477c2 2233 * Only the ZIL in the head (non-snapshot) is valid. Even though
572e2857 2234 * snapshots can have ZIL block pointers (which may be the same
a1d477c2
MA
2235 * BP as in the head), they must be ignored. In addition, $ORIGIN
2236 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
2237 * need to look for a ZIL in it either. So we traverse the ZIL here,
2238 * rather than in scan_recurse(), because the regular snapshot
2239 * block-sharing rules don't apply to it.
572e2857 2240 */
a1d477c2 2241 if (!dsl_dataset_is_snapshot(ds) &&
5e097c67
MA
2242 (dp->dp_origin_snap == NULL ||
2243 ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
a1d477c2
MA
2244 objset_t *os;
2245 if (dmu_objset_from_ds(ds, &os) != 0) {
2246 goto out;
2247 }
572e2857 2248 dsl_scan_zil(dp, &os->os_zil_header);
a1d477c2 2249 }
572e2857 2250
428870ff
BB
2251 /*
2252 * Iterate over the bps in this ds.
2253 */
2254 dmu_buf_will_dirty(ds->ds_dbuf, tx);
cc9bb3e5 2255 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
d683ddbb 2256 dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
cc9bb3e5 2257 rrw_exit(&ds->ds_bp_rwlock, FTAG);
428870ff 2258
1c27024e 2259 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
428870ff
BB
2260 dsl_dataset_name(ds, dsname);
2261 zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
0ea05c64 2262 "suspending=%u",
428870ff
BB
2263 (longlong_t)dsobj, dsname,
2264 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2265 (longlong_t)scn->scn_phys.scn_cur_max_txg,
0ea05c64 2266 (int)scn->scn_suspending);
eca7b760 2267 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
428870ff 2268
0ea05c64 2269 if (scn->scn_suspending)
428870ff
BB
2270 goto out;
2271
2272 /*
2273 * We've finished this pass over this dataset.
2274 */
2275
2276 /*
2277 * If we did not completely visit this dataset, do another pass.
2278 */
2279 if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
2280 zfs_dbgmsg("incomplete pass; visiting again");
2281 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
d4a72f23
TC
2282 scan_ds_queue_insert(scn, ds->ds_object,
2283 scn->scn_phys.scn_cur_max_txg);
428870ff
BB
2284 goto out;
2285 }
2286
2287 /*
13a2ff27 2288 * Add descendant datasets to work queue.
428870ff 2289 */
d683ddbb 2290 if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
d4a72f23 2291 scan_ds_queue_insert(scn,
d683ddbb 2292 dsl_dataset_phys(ds)->ds_next_snap_obj,
d4a72f23 2293 dsl_dataset_phys(ds)->ds_creation_txg);
428870ff 2294 }
d683ddbb 2295 if (dsl_dataset_phys(ds)->ds_num_children > 1) {
428870ff 2296 boolean_t usenext = B_FALSE;
d683ddbb 2297 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
428870ff
BB
2298 uint64_t count;
2299 /*
2300 * A bug in a previous version of the code could
2301 * cause upgrade_clones_cb() to not set
2302 * ds_next_snap_obj when it should, leading to a
2303 * missing entry. Therefore we can only use the
2304 * next_clones_obj when its count is correct.
2305 */
2306 int err = zap_count(dp->dp_meta_objset,
d683ddbb 2307 dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
428870ff 2308 if (err == 0 &&
d683ddbb 2309 count == dsl_dataset_phys(ds)->ds_num_children - 1)
428870ff
BB
2310 usenext = B_TRUE;
2311 }
2312
2313 if (usenext) {
d4a72f23
TC
2314 zap_cursor_t zc;
2315 zap_attribute_t za;
2316 for (zap_cursor_init(&zc, dp->dp_meta_objset,
2317 dsl_dataset_phys(ds)->ds_next_clones_obj);
2318 zap_cursor_retrieve(&zc, &za) == 0;
2319 (void) zap_cursor_advance(&zc)) {
2320 scan_ds_queue_insert(scn,
2321 zfs_strtonum(za.za_name, NULL),
2322 dsl_dataset_phys(ds)->ds_creation_txg);
2323 }
2324 zap_cursor_fini(&zc);
428870ff 2325 } else {
13fe0198 2326 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
d4a72f23
TC
2327 enqueue_clones_cb, &ds->ds_object,
2328 DS_FIND_CHILDREN));
428870ff
BB
2329 }
2330 }
2331
2332out:
2333 dsl_dataset_rele(ds, FTAG);
2334}
2335
2336/* ARGSUSED */
2337static int
13fe0198 2338enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
428870ff 2339{
428870ff
BB
2340 dsl_dataset_t *ds;
2341 int err;
428870ff
BB
2342 dsl_scan_t *scn = dp->dp_scan;
2343
13fe0198 2344 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
428870ff
BB
2345 if (err)
2346 return (err);
2347
d683ddbb 2348 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
428870ff 2349 dsl_dataset_t *prev;
d683ddbb
JG
2350 err = dsl_dataset_hold_obj(dp,
2351 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
428870ff
BB
2352 if (err) {
2353 dsl_dataset_rele(ds, FTAG);
2354 return (err);
2355 }
2356
2357 /*
2358 * If this is a clone, we don't need to worry about it for now.
2359 */
d683ddbb 2360 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
428870ff
BB
2361 dsl_dataset_rele(ds, FTAG);
2362 dsl_dataset_rele(prev, FTAG);
2363 return (0);
2364 }
2365 dsl_dataset_rele(ds, FTAG);
2366 ds = prev;
2367 }
2368
d4a72f23
TC
2369 scan_ds_queue_insert(scn, ds->ds_object,
2370 dsl_dataset_phys(ds)->ds_prev_snap_txg);
428870ff
BB
2371 dsl_dataset_rele(ds, FTAG);
2372 return (0);
2373}
2374
d4a72f23
TC
2375/* ARGSUSED */
2376void
2377dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
2378 ddt_entry_t *dde, dmu_tx_t *tx)
2379{
2380 const ddt_key_t *ddk = &dde->dde_key;
2381 ddt_phys_t *ddp = dde->dde_phys;
2382 blkptr_t bp;
2383 zbookmark_phys_t zb = { 0 };
2384 int p;
2385
f90a30ad 2386 if (!dsl_scan_is_running(scn))
d4a72f23
TC
2387 return;
2388
5e0bd0ae
TC
2389 /*
2390 * This function is special because it is the only thing
2391 * that can add scan_io_t's to the vdev scan queues from
2392 * outside dsl_scan_sync(). For the most part this is ok
2393 * as long as it is called from within syncing context.
2394 * However, dsl_scan_sync() expects that no new sio's will
2395 * be added between when all the work for a scan is done
2396 * and the next txg when the scan is actually marked as
2397 * completed. This check ensures we do not issue new sio's
2398 * during this period.
2399 */
2400 if (scn->scn_done_txg != 0)
2401 return;
2402
d4a72f23
TC
2403 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2404 if (ddp->ddp_phys_birth == 0 ||
2405 ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
2406 continue;
2407 ddt_bp_create(checksum, ddk, ddp, &bp);
2408
2409 scn->scn_visited_this_txg++;
2410 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
2411 }
2412}
2413
428870ff
BB
2414/*
2415 * Scrub/dedup interaction.
2416 *
2417 * If there are N references to a deduped block, we don't want to scrub it
2418 * N times -- ideally, we should scrub it exactly once.
2419 *
2420 * We leverage the fact that the dde's replication class (enum ddt_class)
2421 * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
2422 * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
2423 *
2424 * To prevent excess scrubbing, the scrub begins by walking the DDT
2425 * to find all blocks with refcnt > 1, and scrubs each of these once.
2426 * Since there are two replication classes which contain blocks with
2427 * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
2428 * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
2429 *
2430 * There would be nothing more to say if a block's refcnt couldn't change
2431 * during a scrub, but of course it can so we must account for changes
2432 * in a block's replication class.
2433 *
2434 * Here's an example of what can occur:
2435 *
2436 * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
2437 * when visited during the top-down scrub phase, it will be scrubbed twice.
2438 * This negates our scrub optimization, but is otherwise harmless.
2439 *
2440 * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
2441 * on each visit during the top-down scrub phase, it will never be scrubbed.
2442 * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
2443 * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
2444 * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
2445 * while a scrub is in progress, it scrubs the block right then.
2446 */
2447static void
2448dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
2449{
2450 ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
2598c001 2451 ddt_entry_t dde;
428870ff
BB
2452 int error;
2453 uint64_t n = 0;
2454
2598c001
BB
2455 bzero(&dde, sizeof (ddt_entry_t));
2456
428870ff
BB
2457 while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
2458 ddt_t *ddt;
2459
2460 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
2461 break;
2462 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
2463 (longlong_t)ddb->ddb_class,
2464 (longlong_t)ddb->ddb_type,
2465 (longlong_t)ddb->ddb_checksum,
2466 (longlong_t)ddb->ddb_cursor);
2467
2468 /* There should be no pending changes to the dedup table */
2469 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
2470 ASSERT(avl_first(&ddt->ddt_tree) == NULL);
2471
2472 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
2473 n++;
2474
0ea05c64 2475 if (dsl_scan_check_suspend(scn, NULL))
428870ff
BB
2476 break;
2477 }
2478
0ea05c64
AP
2479 zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; "
2480 "suspending=%u", (longlong_t)n,
2481 (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending);
428870ff
BB
2482
2483 ASSERT(error == 0 || error == ENOENT);
2484 ASSERT(error != ENOENT ||
2485 ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
2486}
2487
d4a72f23
TC
2488static uint64_t
2489dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
428870ff 2490{
d4a72f23
TC
2491 uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
2492 if (ds->ds_is_snapshot)
2493 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
2494 return (smt);
428870ff
BB
2495}
2496
2497static void
2498dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
2499{
d4a72f23 2500 scan_ds_t *sds;
428870ff 2501 dsl_pool_t *dp = scn->scn_dp;
428870ff
BB
2502
2503 if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
2504 scn->scn_phys.scn_ddt_class_max) {
2505 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2506 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2507 dsl_scan_ddt(scn, tx);
0ea05c64 2508 if (scn->scn_suspending)
428870ff
BB
2509 return;
2510 }
2511
2512 if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
2513 /* First do the MOS & ORIGIN */
2514
2515 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2516 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2517 dsl_scan_visit_rootbp(scn, NULL,
2518 &dp->dp_meta_rootbp, tx);
2519 spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
0ea05c64 2520 if (scn->scn_suspending)
428870ff
BB
2521 return;
2522
2523 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
13fe0198 2524 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
d4a72f23 2525 enqueue_cb, NULL, DS_FIND_CHILDREN));
428870ff
BB
2526 } else {
2527 dsl_scan_visitds(scn,
2528 dp->dp_origin_snap->ds_object, tx);
2529 }
0ea05c64 2530 ASSERT(!scn->scn_suspending);
428870ff
BB
2531 } else if (scn->scn_phys.scn_bookmark.zb_objset !=
2532 ZB_DESTROYED_OBJSET) {
d4a72f23 2533 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
428870ff 2534 /*
d4a72f23 2535 * If we were suspended, continue from here. Note if the
0ea05c64 2536 * ds we were suspended on was deleted, the zb_objset may
428870ff
BB
2537 * be -1, so we will skip this and find a new objset
2538 * below.
2539 */
d4a72f23 2540 dsl_scan_visitds(scn, dsobj, tx);
0ea05c64 2541 if (scn->scn_suspending)
428870ff
BB
2542 return;
2543 }
2544
2545 /*
d4a72f23 2546 * In case we suspended right at the end of the ds, zero the
428870ff
BB
2547 * bookmark so we don't think that we're still trying to resume.
2548 */
5dbd68a3 2549 bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
428870ff 2550
d4a72f23
TC
2551 /*
2552 * Keep pulling things out of the dataset avl queue. Updates to the
2553 * persistent zap-object-as-queue happen only at checkpoints.
2554 */
2555 while ((sds = avl_first(&scn->scn_queue)) != NULL) {
428870ff 2556 dsl_dataset_t *ds;
d4a72f23
TC
2557 uint64_t dsobj = sds->sds_dsobj;
2558 uint64_t txg = sds->sds_txg;
428870ff 2559
d4a72f23
TC
2560 /* dequeue and free the ds from the queue */
2561 scan_ds_queue_remove(scn, dsobj);
2562 sds = NULL;
428870ff 2563
d4a72f23 2564 /* set up min / max txg */
428870ff 2565 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
d4a72f23 2566 if (txg != 0) {
428870ff 2567 scn->scn_phys.scn_cur_min_txg =
d4a72f23 2568 MAX(scn->scn_phys.scn_min_txg, txg);
428870ff
BB
2569 } else {
2570 scn->scn_phys.scn_cur_min_txg =
2571 MAX(scn->scn_phys.scn_min_txg,
d683ddbb 2572 dsl_dataset_phys(ds)->ds_prev_snap_txg);
428870ff
BB
2573 }
2574 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
2575 dsl_dataset_rele(ds, FTAG);
2576
2577 dsl_scan_visitds(scn, dsobj, tx);
0ea05c64 2578 if (scn->scn_suspending)
d4a72f23 2579 return;
428870ff 2580 }
d4a72f23
TC
2581
2582 /* No more objsets to fetch, we're done */
2583 scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
2584 ASSERT0(scn->scn_suspending);
2585}
2586
2587static uint64_t
2588dsl_scan_count_leaves(vdev_t *vd)
2589{
2590 uint64_t i, leaves = 0;
2591
2592 /* we only count leaves that belong to the main pool and are readable */
2593 if (vd->vdev_islog || vd->vdev_isspare ||
2594 vd->vdev_isl2cache || !vdev_readable(vd))
2595 return (0);
2596
2597 if (vd->vdev_ops->vdev_op_leaf)
2598 return (1);
2599
2600 for (i = 0; i < vd->vdev_children; i++) {
2601 leaves += dsl_scan_count_leaves(vd->vdev_child[i]);
2602 }
2603
2604 return (leaves);
2605}
2606
2607static void
2608scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
2609{
2610 int i;
2611 uint64_t cur_size = 0;
2612
2613 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
2614 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
2615 }
2616
2617 q->q_total_zio_size_this_txg += cur_size;
2618 q->q_zios_this_txg++;
2619}
2620
2621static void
2622scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
2623 uint64_t end)
2624{
2625 q->q_total_seg_size_this_txg += end - start;
2626 q->q_segs_this_txg++;
2627}
2628
2629static boolean_t
2630scan_io_queue_check_suspend(dsl_scan_t *scn)
2631{
2632 /* See comment in dsl_scan_check_suspend() */
2633 uint64_t curr_time_ns = gethrtime();
2634 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
2635 uint64_t sync_time_ns = curr_time_ns -
2636 scn->scn_dp->dp_spa->spa_sync_starttime;
2637 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
2638 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
2639 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
2640
2641 return ((NSEC2MSEC(scan_time_ns) > mintime &&
2642 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
2643 txg_sync_waiting(scn->scn_dp) ||
2644 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
2645 spa_shutting_down(scn->scn_dp->dp_spa));
2646}
2647
2648/*
13a2ff27 2649 * Given a list of scan_io_t's in io_list, this issues the I/Os out to
d4a72f23
TC
2650 * disk. This consumes the io_list and frees the scan_io_t's. This is
2651 * called when emptying queues, either when we're up against the memory
2652 * limit or when we have finished scanning. Returns B_TRUE if we stopped
13a2ff27 2653 * processing the list before we finished. Any sios that were not issued
d4a72f23
TC
2654 * will remain in the io_list.
2655 */
2656static boolean_t
2657scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
2658{
2659 dsl_scan_t *scn = queue->q_scn;
2660 scan_io_t *sio;
2661 int64_t bytes_issued = 0;
2662 boolean_t suspended = B_FALSE;
2663
2664 while ((sio = list_head(io_list)) != NULL) {
2665 blkptr_t bp;
2666
2667 if (scan_io_queue_check_suspend(scn)) {
2668 suspended = B_TRUE;
2669 break;
2670 }
2671
2672 sio2bp(sio, &bp, queue->q_vd->vdev_id);
2673 bytes_issued += sio->sio_asize;
2674 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
2675 &sio->sio_zb, queue);
2676 (void) list_remove_head(io_list);
2677 scan_io_queues_update_zio_stats(queue, &bp);
2678 kmem_cache_free(sio_cache, sio);
2679 }
2680
2681 atomic_add_64(&scn->scn_bytes_pending, -bytes_issued);
2682
2683 return (suspended);
2684}
2685
2686/*
2687 * This function removes sios from an IO queue which reside within a given
2688 * range_seg_t and inserts them (in offset order) into a list. Note that
2689 * we only ever return a maximum of 32 sios at once. If there are more sios
2690 * to process within this segment that did not make it onto the list we
2691 * return B_TRUE and otherwise B_FALSE.
2692 */
2693static boolean_t
2694scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list)
2695{
2696 scan_io_t srch_sio, *sio, *next_sio;
2697 avl_index_t idx;
2698 uint_t num_sios = 0;
2699 int64_t bytes_issued = 0;
2700
2701 ASSERT(rs != NULL);
2702 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2703
2704 srch_sio.sio_offset = rs->rs_start;
2705
2706 /*
2707 * The exact start of the extent might not contain any matching zios,
2708 * so if that's the case, examine the next one in the tree.
2709 */
2710 sio = avl_find(&queue->q_sios_by_addr, &srch_sio, &idx);
2711 if (sio == NULL)
2712 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
2713
2714 while (sio != NULL && sio->sio_offset < rs->rs_end && num_sios <= 32) {
2715 ASSERT3U(sio->sio_offset, >=, rs->rs_start);
2716 ASSERT3U(sio->sio_offset + sio->sio_asize, <=, rs->rs_end);
2717
2718 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
2719 avl_remove(&queue->q_sios_by_addr, sio);
2720
2721 bytes_issued += sio->sio_asize;
2722 num_sios++;
2723 list_insert_tail(list, sio);
2724 sio = next_sio;
2725 }
2726
2727 /*
2728 * We limit the number of sios we process at once to 32 to avoid
2729 * biting off more than we can chew. If we didn't take everything
2730 * in the segment we update it to reflect the work we were able to
2731 * complete. Otherwise, we remove it from the range tree entirely.
2732 */
2733 if (sio != NULL && sio->sio_offset < rs->rs_end) {
2734 range_tree_adjust_fill(queue->q_exts_by_addr, rs,
2735 -bytes_issued);
2736 range_tree_resize_segment(queue->q_exts_by_addr, rs,
2737 sio->sio_offset, rs->rs_end - sio->sio_offset);
2738
2739 return (B_TRUE);
2740 } else {
2741 range_tree_remove(queue->q_exts_by_addr, rs->rs_start,
2742 rs->rs_end - rs->rs_start);
2743 return (B_FALSE);
2744 }
2745}
2746
2747/*
2748 * This is called from the queue emptying thread and selects the next
13a2ff27 2749 * extent from which we are to issue I/Os. The behavior of this function
d4a72f23
TC
2750 * depends on the state of the scan, the current memory consumption and
2751 * whether or not we are performing a scan shutdown.
2752 * 1) We select extents in an elevator algorithm (LBA-order) if the scan
2753 * needs to perform a checkpoint
2754 * 2) We select the largest available extent if we are up against the
2755 * memory limit.
2756 * 3) Otherwise we don't select any extents.
2757 */
2758static range_seg_t *
2759scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
2760{
2761 dsl_scan_t *scn = queue->q_scn;
2762
2763 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2764 ASSERT(scn->scn_is_sorted);
2765
2766 /* handle tunable overrides */
2767 if (scn->scn_checkpointing || scn->scn_clearing) {
2768 if (zfs_scan_issue_strategy == 1) {
2769 return (range_tree_first(queue->q_exts_by_addr));
2770 } else if (zfs_scan_issue_strategy == 2) {
2771 return (avl_first(&queue->q_exts_by_size));
2772 }
2773 }
2774
2775 /*
2776 * During normal clearing, we want to issue our largest segments
2777 * first, keeping IO as sequential as possible, and leaving the
2778 * smaller extents for later with the hope that they might eventually
2779 * grow to larger sequential segments. However, when the scan is
2780 * checkpointing, no new extents will be added to the sorting queue,
2781 * so the way we are sorted now is as good as it will ever get.
2782 * In this case, we instead switch to issuing extents in LBA order.
2783 */
2784 if (scn->scn_checkpointing) {
2785 return (range_tree_first(queue->q_exts_by_addr));
2786 } else if (scn->scn_clearing) {
2787 return (avl_first(&queue->q_exts_by_size));
2788 } else {
2789 return (NULL);
2790 }
2791}
2792
2793static void
2794scan_io_queues_run_one(void *arg)
2795{
2796 dsl_scan_io_queue_t *queue = arg;
2797 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
2798 boolean_t suspended = B_FALSE;
2799 range_seg_t *rs = NULL;
2800 scan_io_t *sio = NULL;
2801 list_t sio_list;
2802 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
2803 uint64_t nr_leaves = dsl_scan_count_leaves(queue->q_vd);
2804
2805 ASSERT(queue->q_scn->scn_is_sorted);
2806
2807 list_create(&sio_list, sizeof (scan_io_t),
2808 offsetof(scan_io_t, sio_nodes.sio_list_node));
2809 mutex_enter(q_lock);
2810
2811 /* calculate maximum in-flight bytes for this txg (min 1MB) */
2812 queue->q_maxinflight_bytes =
2813 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
2814
2815 /* reset per-queue scan statistics for this txg */
2816 queue->q_total_seg_size_this_txg = 0;
2817 queue->q_segs_this_txg = 0;
2818 queue->q_total_zio_size_this_txg = 0;
2819 queue->q_zios_this_txg = 0;
2820
2821 /* loop until we run out of time or sios */
2822 while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {
2823 uint64_t seg_start = 0, seg_end = 0;
2824 boolean_t more_left = B_TRUE;
2825
2826 ASSERT(list_is_empty(&sio_list));
2827
2828 /* loop while we still have sios left to process in this rs */
2829 while (more_left) {
2830 scan_io_t *first_sio, *last_sio;
2831
2832 /*
2833 * We have selected which extent needs to be
2834 * processed next. Gather up the corresponding sios.
2835 */
2836 more_left = scan_io_queue_gather(queue, rs, &sio_list);
2837 ASSERT(!list_is_empty(&sio_list));
2838 first_sio = list_head(&sio_list);
2839 last_sio = list_tail(&sio_list);
2840
2841 seg_end = last_sio->sio_offset + last_sio->sio_asize;
2842 if (seg_start == 0)
2843 seg_start = first_sio->sio_offset;
2844
2845 /*
2846 * Issuing sios can take a long time so drop the
2847 * queue lock. The sio queue won't be updated by
2848 * other threads since we're in syncing context so
2849 * we can be sure that our trees will remain exactly
2850 * as we left them.
2851 */
2852 mutex_exit(q_lock);
2853 suspended = scan_io_queue_issue(queue, &sio_list);
2854 mutex_enter(q_lock);
2855
2856 if (suspended)
2857 break;
2858 }
2859
2860 /* update statistics for debugging purposes */
2861 scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
2862
2863 if (suspended)
2864 break;
2865 }
2866
2867 /*
2868 * If we were suspended in the middle of processing,
2869 * requeue any unfinished sios and exit.
2870 */
2871 while ((sio = list_head(&sio_list)) != NULL) {
2872 list_remove(&sio_list, sio);
2873 scan_io_queue_insert_impl(queue, sio);
2874 }
2875
2876 mutex_exit(q_lock);
2877 list_destroy(&sio_list);
2878}
2879
2880/*
2881 * Performs an emptying run on all scan queues in the pool. This just
2882 * punches out one thread per top-level vdev, each of which processes
2883 * only that vdev's scan queue. We can parallelize the I/O here because
13a2ff27 2884 * we know that each queue's I/Os only affect its own top-level vdev.
d4a72f23
TC
2885 *
2886 * This function waits for the queue runs to complete, and must be
2887 * called from dsl_scan_sync (or in general, syncing context).
2888 */
2889static void
2890scan_io_queues_run(dsl_scan_t *scn)
2891{
2892 spa_t *spa = scn->scn_dp->dp_spa;
2893
2894 ASSERT(scn->scn_is_sorted);
2895 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2896
2897 if (scn->scn_bytes_pending == 0)
2898 return;
2899
2900 if (scn->scn_taskq == NULL) {
2901 int nthreads = spa->spa_root_vdev->vdev_children;
2902
2903 /*
2904 * We need to make this taskq *always* execute as many
2905 * threads in parallel as we have top-level vdevs and no
2906 * less, otherwise strange serialization of the calls to
2907 * scan_io_queues_run_one can occur during spa_sync runs
2908 * and that significantly impacts performance.
2909 */
2910 scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,
2911 minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);
2912 }
2913
2914 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2915 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2916
2917 mutex_enter(&vd->vdev_scan_io_queue_lock);
2918 if (vd->vdev_scan_io_queue != NULL) {
2919 VERIFY(taskq_dispatch(scn->scn_taskq,
2920 scan_io_queues_run_one, vd->vdev_scan_io_queue,
2921 TQ_SLEEP) != TASKQID_INVALID);
2922 }
2923 mutex_exit(&vd->vdev_scan_io_queue_lock);
2924 }
2925
2926 /*
13a2ff27 2927 * Wait for the queues to finish issuing their IOs for this run
d4a72f23
TC
2928 * before we return. There may still be IOs in flight at this
2929 * point.
2930 */
2931 taskq_wait(scn->scn_taskq);
428870ff
BB
2932}
2933
9ae529ec 2934static boolean_t
a1d477c2 2935dsl_scan_async_block_should_pause(dsl_scan_t *scn)
428870ff 2936{
428870ff
BB
2937 uint64_t elapsed_nanosecs;
2938
78e2739d
MA
2939 if (zfs_recover)
2940 return (B_FALSE);
2941
a1d477c2 2942 if (scn->scn_visited_this_txg >= zfs_async_block_max_blocks)
36283ca2
MG
2943 return (B_TRUE);
2944
428870ff 2945 elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
9ae529ec 2946 return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
a1d477c2 2947 (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
428870ff 2948 txg_sync_waiting(scn->scn_dp)) ||
9ae529ec
CS
2949 spa_shutting_down(scn->scn_dp->dp_spa));
2950}
2951
2952static int
2953dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2954{
2955 dsl_scan_t *scn = arg;
2956
2957 if (!scn->scn_is_bptree ||
2958 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
a1d477c2 2959 if (dsl_scan_async_block_should_pause(scn))
2e528b49 2960 return (SET_ERROR(ERESTART));
9ae529ec 2961 }
428870ff
BB
2962
2963 zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
2964 dmu_tx_get_txg(tx), bp, 0));
2965 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
2966 -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
2967 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
2968 scn->scn_visited_this_txg++;
2969 return (0);
2970}
2971
d4a72f23
TC
2972static void
2973dsl_scan_update_stats(dsl_scan_t *scn)
2974{
2975 spa_t *spa = scn->scn_dp->dp_spa;
2976 uint64_t i;
2977 uint64_t seg_size_total = 0, zio_size_total = 0;
2978 uint64_t seg_count_total = 0, zio_count_total = 0;
2979
2980 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2981 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2982 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
2983
2984 if (queue == NULL)
2985 continue;
2986
2987 seg_size_total += queue->q_total_seg_size_this_txg;
2988 zio_size_total += queue->q_total_zio_size_this_txg;
2989 seg_count_total += queue->q_segs_this_txg;
2990 zio_count_total += queue->q_zios_this_txg;
2991 }
2992
2993 if (seg_count_total == 0 || zio_count_total == 0) {
2994 scn->scn_avg_seg_size_this_txg = 0;
2995 scn->scn_avg_zio_size_this_txg = 0;
2996 scn->scn_segs_this_txg = 0;
2997 scn->scn_zios_this_txg = 0;
2998 return;
2999 }
3000
3001 scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
3002 scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
3003 scn->scn_segs_this_txg = seg_count_total;
3004 scn->scn_zios_this_txg = zio_count_total;
3005}
3006
a1d477c2
MA
3007static int
3008dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3009{
3010 dsl_scan_t *scn = arg;
3011 const dva_t *dva = &bp->blk_dva[0];
3012
3013 if (dsl_scan_async_block_should_pause(scn))
3014 return (SET_ERROR(ERESTART));
3015
3016 spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
3017 DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
3018 DVA_GET_ASIZE(dva), tx);
3019 scn->scn_visited_this_txg++;
3020 return (0);
3021}
3022
428870ff
BB
3023boolean_t
3024dsl_scan_active(dsl_scan_t *scn)
3025{
3026 spa_t *spa = scn->scn_dp->dp_spa;
3027 uint64_t used = 0, comp, uncomp;
3028
3029 if (spa->spa_load_state != SPA_LOAD_NONE)
3030 return (B_FALSE);
3031 if (spa_shutting_down(spa))
3032 return (B_FALSE);
d4a72f23 3033 if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
fbeddd60 3034 (scn->scn_async_destroying && !scn->scn_async_stalled))
428870ff
BB
3035 return (B_TRUE);
3036
3037 if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
3038 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
3039 &used, &comp, &uncomp);
3040 }
3041 return (used != 0);
3042}
3043
80a91e74
TC
3044static boolean_t
3045dsl_scan_check_deferred(vdev_t *vd)
3046{
3047 boolean_t need_resilver = B_FALSE;
3048
3049 for (int c = 0; c < vd->vdev_children; c++) {
3050 need_resilver |=
3051 dsl_scan_check_deferred(vd->vdev_child[c]);
3052 }
3053
3054 if (!vdev_is_concrete(vd) || vd->vdev_aux ||
3055 !vd->vdev_ops->vdev_op_leaf)
3056 return (need_resilver);
3057
3058 if (!vd->vdev_resilver_deferred)
3059 need_resilver = B_TRUE;
3060
3061 return (need_resilver);
3062}
3063
d4a72f23
TC
3064static boolean_t
3065dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
3066 uint64_t phys_birth)
3067{
3068 vdev_t *vd;
3069
9e052db4
MA
3070 vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3071
3072 if (vd->vdev_ops == &vdev_indirect_ops) {
3073 /*
3074 * The indirect vdev can point to multiple
3075 * vdevs. For simplicity, always create
3076 * the resilver zio_t. zio_vdev_io_start()
3077 * will bypass the child resilver i/o's if
3078 * they are on vdevs that don't have DTL's.
3079 */
3080 return (B_TRUE);
3081 }
3082
d4a72f23
TC
3083 if (DVA_GET_GANG(dva)) {
3084 /*
3085 * Gang members may be spread across multiple
3086 * vdevs, so the best estimate we have is the
3087 * scrub range, which has already been checked.
3088 * XXX -- it would be better to change our
3089 * allocation policy to ensure that all
3090 * gang members reside on the same vdev.
3091 */
3092 return (B_TRUE);
3093 }
3094
d4a72f23
TC
3095 /*
3096 * Check if the txg falls within the range which must be
3097 * resilvered. DVAs outside this range can always be skipped.
3098 */
3099 if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
3100 return (B_FALSE);
3101
3102 /*
3103 * Check if the top-level vdev must resilver this offset.
3104 * When the offset does not intersect with a dirty leaf DTL
3105 * then it may be possible to skip the resilver IO. The psize
3106 * is provided instead of asize to simplify the check for RAIDZ.
3107 */
3108 if (!vdev_dtl_need_resilver(vd, DVA_GET_OFFSET(dva), psize))
3109 return (B_FALSE);
3110
80a91e74
TC
3111 /*
3112 * Check that this top-level vdev has a device under it which
3113 * is resilvering and is not deferred.
3114 */
3115 if (!dsl_scan_check_deferred(vd))
3116 return (B_FALSE);
3117
d4a72f23
TC
3118 return (B_TRUE);
3119}
3120
d2734cce
SD
3121static int
3122dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)
428870ff
BB
3123{
3124 dsl_scan_t *scn = dp->dp_scan;
3125 spa_t *spa = dp->dp_spa;
d2734cce 3126 int err = 0;
428870ff 3127
d2734cce
SD
3128 if (spa_suspend_async_destroy(spa))
3129 return (0);
428870ff 3130
ba5ad9a4 3131 if (zfs_free_bpobj_enabled &&
d4a72f23 3132 spa_version(spa) >= SPA_VERSION_DEADLISTS) {
9ae529ec 3133 scn->scn_is_bptree = B_FALSE;
a1d477c2 3134 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
d4a72f23 3135 scn->scn_zio_root = zio_root(spa, NULL,
428870ff
BB
3136 NULL, ZIO_FLAG_MUSTSUCCEED);
3137 err = bpobj_iterate(&dp->dp_free_bpobj,
9ae529ec 3138 dsl_scan_free_block_cb, scn, tx);
d4a72f23
TC
3139 VERIFY0(zio_wait(scn->scn_zio_root));
3140 scn->scn_zio_root = NULL;
9ae529ec 3141
fbeddd60
MA
3142 if (err != 0 && err != ERESTART)
3143 zfs_panic_recover("error %u from bpobj_iterate()", err);
3144 }
13fe0198 3145
fbeddd60
MA
3146 if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3147 ASSERT(scn->scn_async_destroying);
3148 scn->scn_is_bptree = B_TRUE;
d4a72f23 3149 scn->scn_zio_root = zio_root(spa, NULL,
fbeddd60
MA
3150 NULL, ZIO_FLAG_MUSTSUCCEED);
3151 err = bptree_iterate(dp->dp_meta_objset,
3152 dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3153 VERIFY0(zio_wait(scn->scn_zio_root));
d4a72f23 3154 scn->scn_zio_root = NULL;
fbeddd60
MA
3155
3156 if (err == EIO || err == ECKSUM) {
3157 err = 0;
3158 } else if (err != 0 && err != ERESTART) {
3159 zfs_panic_recover("error %u from "
3160 "traverse_dataset_destroyed()", err);
9ae529ec 3161 }
fbeddd60 3162
fbeddd60
MA
3163 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
3164 /* finished; deactivate async destroy feature */
3165 spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
3166 ASSERT(!spa_feature_is_active(spa,
3167 SPA_FEATURE_ASYNC_DESTROY));
3168 VERIFY0(zap_remove(dp->dp_meta_objset,
3169 DMU_POOL_DIRECTORY_OBJECT,
3170 DMU_POOL_BPTREE_OBJ, tx));
3171 VERIFY0(bptree_free(dp->dp_meta_objset,
3172 dp->dp_bptree_obj, tx));
3173 dp->dp_bptree_obj = 0;
3174 scn->scn_async_destroying = B_FALSE;
905edb40 3175 scn->scn_async_stalled = B_FALSE;
89b1cd65 3176 } else {
3177 /*
905edb40
MA
3178 * If we didn't make progress, mark the async
3179 * destroy as stalled, so that we will not initiate
3180 * a spa_sync() on its behalf. Note that we only
3181 * check this if we are not finished, because if the
3182 * bptree had no blocks for us to visit, we can
3183 * finish without "making progress".
89b1cd65 3184 */
3185 scn->scn_async_stalled =
3186 (scn->scn_visited_this_txg == 0);
428870ff 3187 }
fbeddd60
MA
3188 }
3189 if (scn->scn_visited_this_txg) {
3190 zfs_dbgmsg("freed %llu blocks in %llums from "
3191 "free_bpobj/bptree txg %llu; err=%u",
3192 (longlong_t)scn->scn_visited_this_txg,
3193 (longlong_t)
3194 NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
3195 (longlong_t)tx->tx_txg, err);
3196 scn->scn_visited_this_txg = 0;
3197
3198 /*
3199 * Write out changes to the DDT that may be required as a
3200 * result of the blocks freed. This ensures that the DDT
3201 * is clean when a scrub/resilver runs.
3202 */
3203 ddt_sync(spa, tx->tx_txg);
3204 }
3205 if (err != 0)
d2734cce 3206 return (err);
7c9abfa7
GM
3207 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3208 zfs_free_leak_on_eio &&
d683ddbb
JG
3209 (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
3210 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
3211 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
fbeddd60
MA
3212 /*
3213 * We have finished background destroying, but there is still
3214 * some space left in the dp_free_dir. Transfer this leaked
3215 * space to the dp_leak_dir.
3216 */
3217 if (dp->dp_leak_dir == NULL) {
3218 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
3219 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
3220 LEAK_DIR_NAME, tx);
3221 VERIFY0(dsl_pool_open_special_dir(dp,
3222 LEAK_DIR_NAME, &dp->dp_leak_dir));
3223 rrw_exit(&dp->dp_config_rwlock, FTAG);
3224 }
3225 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
d683ddbb
JG
3226 dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3227 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3228 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
fbeddd60 3229 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
d683ddbb
JG
3230 -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3231 -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3232 -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
fbeddd60 3233 }
a1d477c2 3234
7c9abfa7 3235 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying) {
9b67f605 3236 /* finished; verify that space accounting went to zero */
d683ddbb
JG
3237 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
3238 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
3239 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
428870ff
BB
3240 }
3241
a1d477c2
MA
3242 EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
3243 0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3244 DMU_POOL_OBSOLETE_BPOBJ));
3245 if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3246 ASSERT(spa_feature_is_active(dp->dp_spa,
3247 SPA_FEATURE_OBSOLETE_COUNTS));
3248
3249 scn->scn_is_bptree = B_FALSE;
3250 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
3251 err = bpobj_iterate(&dp->dp_obsolete_bpobj,
3252 dsl_scan_obsolete_block_cb, scn, tx);
3253 if (err != 0 && err != ERESTART)
3254 zfs_panic_recover("error %u from bpobj_iterate()", err);
3255
3256 if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
3257 dsl_pool_destroy_obsolete_bpobj(dp, tx);
3258 }
d2734cce
SD
3259 return (0);
3260}
3261
3262/*
3263 * This is the primary entry point for scans that is called from syncing
3264 * context. Scans must happen entirely during syncing context so that we
3265 * cna guarantee that blocks we are currently scanning will not change out
3266 * from under us. While a scan is active, this function controls how quickly
3267 * transaction groups proceed, instead of the normal handling provided by
3268 * txg_sync_thread().
3269 */
3270void
3271dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
3272{
3273 int err = 0;
3274 dsl_scan_t *scn = dp->dp_scan;
3275 spa_t *spa = dp->dp_spa;
3276 state_sync_type_t sync_type = SYNC_OPTIONAL;
3277
80a91e74
TC
3278 if (spa->spa_resilver_deferred &&
3279 !spa_feature_is_active(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))
3280 spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
3281
d2734cce
SD
3282 /*
3283 * Check for scn_restart_txg before checking spa_load_state, so
3284 * that we can restart an old-style scan while the pool is being
80a91e74
TC
3285 * imported (see dsl_scan_init). We also restart scans if there
3286 * is a deferred resilver and the user has manually disabled
3287 * deferred resilvers via the tunable.
d2734cce 3288 */
80a91e74
TC
3289 if (dsl_scan_restarting(scn, tx) ||
3290 (spa->spa_resilver_deferred && zfs_resilver_disable_defer)) {
d2734cce
SD
3291 pool_scan_func_t func = POOL_SCAN_SCRUB;
3292 dsl_scan_done(scn, B_FALSE, tx);
3293 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3294 func = POOL_SCAN_RESILVER;
3295 zfs_dbgmsg("restarting scan func=%u txg=%llu",
3296 func, (longlong_t)tx->tx_txg);
3297 dsl_scan_setup_sync(&func, tx);
3298 }
3299
3300 /*
3301 * Only process scans in sync pass 1.
3302 */
3303 if (spa_sync_pass(spa) > 1)
3304 return;
3305
3306 /*
3307 * If the spa is shutting down, then stop scanning. This will
3308 * ensure that the scan does not dirty any new data during the
3309 * shutdown phase.
3310 */
3311 if (spa_shutting_down(spa))
3312 return;
3313
3314 /*
3315 * If the scan is inactive due to a stalled async destroy, try again.
3316 */
3317 if (!scn->scn_async_stalled && !dsl_scan_active(scn))
3318 return;
3319
3320 /* reset scan statistics */
3321 scn->scn_visited_this_txg = 0;
3322 scn->scn_holes_this_txg = 0;
3323 scn->scn_lt_min_this_txg = 0;
3324 scn->scn_gt_max_this_txg = 0;
3325 scn->scn_ddt_contained_this_txg = 0;
3326 scn->scn_objsets_visited_this_txg = 0;
3327 scn->scn_avg_seg_size_this_txg = 0;
3328 scn->scn_segs_this_txg = 0;
3329 scn->scn_avg_zio_size_this_txg = 0;
3330 scn->scn_zios_this_txg = 0;
3331 scn->scn_suspending = B_FALSE;
3332 scn->scn_sync_start_time = gethrtime();
3333 spa->spa_scrub_active = B_TRUE;
3334
3335 /*
3336 * First process the async destroys. If we suspend, don't do
3337 * any scrubbing or resilvering. This ensures that there are no
3338 * async destroys while we are scanning, so the scan code doesn't
3339 * have to worry about traversing it. It is also faster to free the
3340 * blocks than to scrub them.
3341 */
3342 err = dsl_process_async_destroys(dp, tx);
3343 if (err != 0)
3344 return;
a1d477c2 3345
d4a72f23 3346 if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
428870ff
BB
3347 return;
3348
d4a72f23
TC
3349 /*
3350 * Wait a few txgs after importing to begin scanning so that
3351 * we can get the pool imported quickly.
3352 */
3353 if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)
5d1f7fb6 3354 return;
5d1f7fb6 3355
d4a72f23
TC
3356 /*
3357 * It is possible to switch from unsorted to sorted at any time,
3358 * but afterwards the scan will remain sorted unless reloaded from
3359 * a checkpoint after a reboot.
3360 */
3361 if (!zfs_scan_legacy) {
3362 scn->scn_is_sorted = B_TRUE;
3363 if (scn->scn_last_checkpoint == 0)
3364 scn->scn_last_checkpoint = ddi_get_lbolt();
3365 }
0ea05c64 3366
d4a72f23
TC
3367 /*
3368 * For sorted scans, determine what kind of work we will be doing
3369 * this txg based on our memory limitations and whether or not we
3370 * need to perform a checkpoint.
3371 */
3372 if (scn->scn_is_sorted) {
3373 /*
3374 * If we are over our checkpoint interval, set scn_clearing
3375 * so that we can begin checkpointing immediately. The
13a2ff27 3376 * checkpoint allows us to save a consistent bookmark
d4a72f23
TC
3377 * representing how much data we have scrubbed so far.
3378 * Otherwise, use the memory limit to determine if we should
3379 * scan for metadata or start issue scrub IOs. We accumulate
3380 * metadata until we hit our hard memory limit at which point
3381 * we issue scrub IOs until we are at our soft memory limit.
3382 */
3383 if (scn->scn_checkpointing ||
3384 ddi_get_lbolt() - scn->scn_last_checkpoint >
3385 SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
3386 if (!scn->scn_checkpointing)
3387 zfs_dbgmsg("begin scan checkpoint");
3388
3389 scn->scn_checkpointing = B_TRUE;
3390 scn->scn_clearing = B_TRUE;
3391 } else {
3392 boolean_t should_clear = dsl_scan_should_clear(scn);
3393 if (should_clear && !scn->scn_clearing) {
3394 zfs_dbgmsg("begin scan clearing");
3395 scn->scn_clearing = B_TRUE;
3396 } else if (!should_clear && scn->scn_clearing) {
3397 zfs_dbgmsg("finish scan clearing");
3398 scn->scn_clearing = B_FALSE;
3399 }
3400 }
428870ff 3401 } else {
d4a72f23
TC
3402 ASSERT0(scn->scn_checkpointing);
3403 ASSERT0(scn->scn_clearing);
428870ff
BB
3404 }
3405
d4a72f23
TC
3406 if (!scn->scn_clearing && scn->scn_done_txg == 0) {
3407 /* Need to scan metadata for more blocks to scrub */
3408 dsl_scan_phys_t *scnp = &scn->scn_phys;
3409 taskqid_t prefetch_tqid;
3410 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
3411 uint64_t nr_leaves = dsl_scan_count_leaves(spa->spa_root_vdev);
428870ff 3412
d4a72f23 3413 /*
f90a30ad 3414 * Recalculate the max number of in-flight bytes for pool-wide
d4a72f23
TC
3415 * scanning operations (minimum 1MB). Limits for the issuing
3416 * phase are done per top-level vdev and are handled separately.
3417 */
3418 scn->scn_maxinflight_bytes =
3419 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
3420
3421 if (scnp->scn_ddt_bookmark.ddb_class <=
3422 scnp->scn_ddt_class_max) {
3423 ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
3424 zfs_dbgmsg("doing scan sync txg %llu; "
3425 "ddt bm=%llu/%llu/%llu/%llx",
3426 (longlong_t)tx->tx_txg,
3427 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
3428 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
3429 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
3430 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
3431 } else {
3432 zfs_dbgmsg("doing scan sync txg %llu; "
3433 "bm=%llu/%llu/%llu/%llu",
3434 (longlong_t)tx->tx_txg,
3435 (longlong_t)scnp->scn_bookmark.zb_objset,
3436 (longlong_t)scnp->scn_bookmark.zb_object,
3437 (longlong_t)scnp->scn_bookmark.zb_level,
3438 (longlong_t)scnp->scn_bookmark.zb_blkid);
3439 }
428870ff 3440
d4a72f23
TC
3441 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3442 NULL, ZIO_FLAG_CANFAIL);
428870ff 3443
d4a72f23
TC
3444 scn->scn_prefetch_stop = B_FALSE;
3445 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
3446 dsl_scan_prefetch_thread, scn, TQ_SLEEP);
3447 ASSERT(prefetch_tqid != TASKQID_INVALID);
428870ff 3448
d4a72f23
TC
3449 dsl_pool_config_enter(dp, FTAG);
3450 dsl_scan_visit(scn, tx);
3451 dsl_pool_config_exit(dp, FTAG);
428870ff 3452
d4a72f23
TC
3453 mutex_enter(&dp->dp_spa->spa_scrub_lock);
3454 scn->scn_prefetch_stop = B_TRUE;
3455 cv_broadcast(&spa->spa_scrub_io_cv);
3456 mutex_exit(&dp->dp_spa->spa_scrub_lock);
428870ff 3457
d4a72f23
TC
3458 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
3459 (void) zio_wait(scn->scn_zio_root);
3460 scn->scn_zio_root = NULL;
3461
3462 zfs_dbgmsg("scan visited %llu blocks in %llums "
3463 "(%llu os's, %llu holes, %llu < mintxg, "
3464 "%llu in ddt, %llu > maxtxg)",
3465 (longlong_t)scn->scn_visited_this_txg,
3466 (longlong_t)NSEC2MSEC(gethrtime() -
3467 scn->scn_sync_start_time),
3468 (longlong_t)scn->scn_objsets_visited_this_txg,
3469 (longlong_t)scn->scn_holes_this_txg,
3470 (longlong_t)scn->scn_lt_min_this_txg,
3471 (longlong_t)scn->scn_ddt_contained_this_txg,
3472 (longlong_t)scn->scn_gt_max_this_txg);
3473
3474 if (!scn->scn_suspending) {
3475 ASSERT0(avl_numnodes(&scn->scn_queue));
3476 scn->scn_done_txg = tx->tx_txg + 1;
3477 if (scn->scn_is_sorted) {
3478 scn->scn_checkpointing = B_TRUE;
3479 scn->scn_clearing = B_TRUE;
3480 }
3481 zfs_dbgmsg("scan complete txg %llu",
3482 (longlong_t)tx->tx_txg);
3483 }
3484 } else if (scn->scn_is_sorted && scn->scn_bytes_pending != 0) {
5e0bd0ae
TC
3485 ASSERT(scn->scn_clearing);
3486
d4a72f23
TC
3487 /* need to issue scrubbing IOs from per-vdev queues */
3488 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3489 NULL, ZIO_FLAG_CANFAIL);
3490 scan_io_queues_run(scn);
3491 (void) zio_wait(scn->scn_zio_root);
3492 scn->scn_zio_root = NULL;
3493
3494 /* calculate and dprintf the current memory usage */
3495 (void) dsl_scan_should_clear(scn);
3496 dsl_scan_update_stats(scn);
3497
3498 zfs_dbgmsg("scan issued %llu blocks (%llu segs) in %llums "
3499 "(avg_block_size = %llu, avg_seg_size = %llu)",
3500 (longlong_t)scn->scn_zios_this_txg,
3501 (longlong_t)scn->scn_segs_this_txg,
3502 (longlong_t)NSEC2MSEC(gethrtime() -
3503 scn->scn_sync_start_time),
3504 (longlong_t)scn->scn_avg_zio_size_this_txg,
3505 (longlong_t)scn->scn_avg_seg_size_this_txg);
3506 } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
3507 /* Finished with everything. Mark the scrub as complete */
3508 zfs_dbgmsg("scan issuing complete txg %llu",
3509 (longlong_t)tx->tx_txg);
3510 ASSERT3U(scn->scn_done_txg, !=, 0);
3511 ASSERT0(spa->spa_scrub_inflight);
3512 ASSERT0(scn->scn_bytes_pending);
3513 dsl_scan_done(scn, B_TRUE, tx);
3514 sync_type = SYNC_MANDATORY;
428870ff 3515 }
428870ff 3516
d4a72f23 3517 dsl_scan_sync_state(scn, tx, sync_type);
428870ff
BB
3518}
3519
428870ff 3520static void
d4a72f23 3521count_block(dsl_scan_t *scn, zfs_all_blkstats_t *zab, const blkptr_t *bp)
428870ff
BB
3522{
3523 int i;
3524
d4a72f23
TC
3525 /* update the spa's stats on how many bytes we have issued */
3526 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3527 atomic_add_64(&scn->scn_dp->dp_spa->spa_scan_pass_issued,
3528 DVA_GET_ASIZE(&bp->blk_dva[i]));
3529 }
3530
428870ff
BB
3531 /*
3532 * If we resume after a reboot, zab will be NULL; don't record
3533 * incomplete stats in that case.
3534 */
3535 if (zab == NULL)
3536 return;
3537
d4a72f23
TC
3538 mutex_enter(&zab->zab_lock);
3539
428870ff
BB
3540 for (i = 0; i < 4; i++) {
3541 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
3542 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
9ae529ec
CS
3543
3544 if (t & DMU_OT_NEWTYPE)
3545 t = DMU_OT_OTHER;
1c27024e
DB
3546 zfs_blkstat_t *zb = &zab->zab_type[l][t];
3547 int equal;
428870ff
BB
3548
3549 zb->zb_count++;
3550 zb->zb_asize += BP_GET_ASIZE(bp);
3551 zb->zb_lsize += BP_GET_LSIZE(bp);
3552 zb->zb_psize += BP_GET_PSIZE(bp);
3553 zb->zb_gangs += BP_COUNT_GANG(bp);
3554
3555 switch (BP_GET_NDVAS(bp)) {
3556 case 2:
3557 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3558 DVA_GET_VDEV(&bp->blk_dva[1]))
3559 zb->zb_ditto_2_of_2_samevdev++;
3560 break;
3561 case 3:
3562 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3563 DVA_GET_VDEV(&bp->blk_dva[1])) +
3564 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3565 DVA_GET_VDEV(&bp->blk_dva[2])) +
3566 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3567 DVA_GET_VDEV(&bp->blk_dva[2]));
3568 if (equal == 1)
3569 zb->zb_ditto_2_of_3_samevdev++;
3570 else if (equal == 3)
3571 zb->zb_ditto_3_of_3_samevdev++;
3572 break;
3573 }
3574 }
d4a72f23
TC
3575
3576 mutex_exit(&zab->zab_lock);
428870ff
BB
3577}
3578
3579static void
d4a72f23 3580scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
428870ff 3581{
d4a72f23
TC
3582 avl_index_t idx;
3583 int64_t asize = sio->sio_asize;
3584 dsl_scan_t *scn = queue->q_scn;
428870ff 3585
d4a72f23 3586 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
428870ff 3587
d4a72f23
TC
3588 if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
3589 /* block is already scheduled for reading */
3590 atomic_add_64(&scn->scn_bytes_pending, -asize);
3591 kmem_cache_free(sio_cache, sio);
3592 return;
428870ff 3593 }
d4a72f23
TC
3594 avl_insert(&queue->q_sios_by_addr, sio, idx);
3595 range_tree_add(queue->q_exts_by_addr, sio->sio_offset, asize);
428870ff
BB
3596}
3597
d4a72f23
TC
3598/*
3599 * Given all the info we got from our metadata scanning process, we
3600 * construct a scan_io_t and insert it into the scan sorting queue. The
3601 * I/O must already be suitable for us to process. This is controlled
3602 * by dsl_scan_enqueue().
3603 */
3604static void
3605scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
3606 int zio_flags, const zbookmark_phys_t *zb)
3d6da72d 3607{
d4a72f23
TC
3608 dsl_scan_t *scn = queue->q_scn;
3609 scan_io_t *sio = kmem_cache_alloc(sio_cache, KM_SLEEP);
3d6da72d 3610
d4a72f23
TC
3611 ASSERT0(BP_IS_GANG(bp));
3612 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3d6da72d 3613
d4a72f23
TC
3614 bp2sio(bp, sio, dva_i);
3615 sio->sio_flags = zio_flags;
3616 sio->sio_zb = *zb;
3d6da72d
IH
3617
3618 /*
d4a72f23
TC
3619 * Increment the bytes pending counter now so that we can't
3620 * get an integer underflow in case the worker processes the
3621 * zio before we get to incrementing this counter.
3d6da72d 3622 */
d4a72f23
TC
3623 atomic_add_64(&scn->scn_bytes_pending, sio->sio_asize);
3624
3625 scan_io_queue_insert_impl(queue, sio);
3626}
3627
3628/*
3629 * Given a set of I/O parameters as discovered by the metadata traversal
3630 * process, attempts to place the I/O into the sorted queues (if allowed),
3631 * or immediately executes the I/O.
3632 */
3633static void
3634dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3635 const zbookmark_phys_t *zb)
3636{
3637 spa_t *spa = dp->dp_spa;
3638
3639 ASSERT(!BP_IS_EMBEDDED(bp));
3d6da72d
IH
3640
3641 /*
d4a72f23
TC
3642 * Gang blocks are hard to issue sequentially, so we just issue them
3643 * here immediately instead of queuing them.
3d6da72d 3644 */
d4a72f23
TC
3645 if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
3646 scan_exec_io(dp, bp, zio_flags, zb, NULL);
3647 return;
3648 }
3d6da72d 3649
d4a72f23
TC
3650 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
3651 dva_t dva;
3652 vdev_t *vdev;
3653
3654 dva = bp->blk_dva[i];
3655 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
3656 ASSERT(vdev != NULL);
3657
3658 mutex_enter(&vdev->vdev_scan_io_queue_lock);
3659 if (vdev->vdev_scan_io_queue == NULL)
3660 vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
3661 ASSERT(dp->dp_scan != NULL);
3662 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
3663 i, zio_flags, zb);
3664 mutex_exit(&vdev->vdev_scan_io_queue_lock);
3665 }
3d6da72d
IH
3666}
3667
428870ff
BB
3668static int
3669dsl_scan_scrub_cb(dsl_pool_t *dp,
5dbd68a3 3670 const blkptr_t *bp, const zbookmark_phys_t *zb)
428870ff
BB
3671{
3672 dsl_scan_t *scn = dp->dp_scan;
428870ff
BB
3673 spa_t *spa = dp->dp_spa;
3674 uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
d4a72f23 3675 size_t psize = BP_GET_PSIZE(bp);
d6320ddb 3676 boolean_t needs_io = B_FALSE;
572e2857 3677 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
428870ff 3678
00c405b4 3679
428870ff 3680 if (phys_birth <= scn->scn_phys.scn_min_txg ||
863522b1
SN
3681 phys_birth >= scn->scn_phys.scn_max_txg) {
3682 count_block(scn, dp->dp_blkstats, bp);
428870ff 3683 return (0);
863522b1 3684 }
428870ff 3685
00c405b4
MA
3686 /* Embedded BP's have phys_birth==0, so we reject them above. */
3687 ASSERT(!BP_IS_EMBEDDED(bp));
9b67f605 3688
428870ff
BB
3689 ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
3690 if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
3691 zio_flags |= ZIO_FLAG_SCRUB;
428870ff 3692 needs_io = B_TRUE;
a117a6d6
GW
3693 } else {
3694 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
428870ff 3695 zio_flags |= ZIO_FLAG_RESILVER;
428870ff
BB
3696 needs_io = B_FALSE;
3697 }
3698
3699 /* If it's an intent log block, failure is expected. */
3700 if (zb->zb_level == ZB_ZIL_LEVEL)
3701 zio_flags |= ZIO_FLAG_SPECULATIVE;
3702
1c27024e 3703 for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
3d6da72d 3704 const dva_t *dva = &bp->blk_dva[d];
428870ff
BB
3705
3706 /*
3707 * Keep track of how much data we've examined so that
3708 * zpool(1M) status can make useful progress reports.
3709 */
3d6da72d
IH
3710 scn->scn_phys.scn_examined += DVA_GET_ASIZE(dva);
3711 spa->spa_scan_pass_exam += DVA_GET_ASIZE(dva);
428870ff
BB
3712
3713 /* if it's a resilver, this may not be in the target range */
3d6da72d
IH
3714 if (!needs_io)
3715 needs_io = dsl_scan_need_resilver(spa, dva, psize,
3716 phys_birth);
428870ff
BB
3717 }
3718
3719 if (needs_io && !zfs_no_scrub_io) {
d4a72f23
TC
3720 dsl_scan_enqueue(dp, bp, zio_flags, zb);
3721 } else {
3722 count_block(scn, dp->dp_blkstats, bp);
3723 }
3724
3725 /* do not relocate this block */
3726 return (0);
3727}
3728
3729static void
3730dsl_scan_scrub_done(zio_t *zio)
3731{
3732 spa_t *spa = zio->io_spa;
3733 blkptr_t *bp = zio->io_bp;
3734 dsl_scan_io_queue_t *queue = zio->io_private;
3735
3736 abd_free(zio->io_abd);
3737
3738 if (queue == NULL) {
3739 mutex_enter(&spa->spa_scrub_lock);
3740 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
3741 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
3742 cv_broadcast(&spa->spa_scrub_io_cv);
3743 mutex_exit(&spa->spa_scrub_lock);
3744 } else {
3745 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
3746 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));
3747 queue->q_inflight_bytes -= BP_GET_PSIZE(bp);
3748 cv_broadcast(&queue->q_zio_cv);
3749 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
3750 }
3751
3752 if (zio->io_error && (zio->io_error != ECKSUM ||
3753 !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
3754 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors);
3755 }
3756}
428870ff 3757
d4a72f23
TC
3758/*
3759 * Given a scanning zio's information, executes the zio. The zio need
3760 * not necessarily be only sortable, this function simply executes the
3761 * zio, no matter what it is. The optional queue argument allows the
3762 * caller to specify that they want per top level vdev IO rate limiting
3763 * instead of the legacy global limiting.
3764 */
3765static void
3766scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3767 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
3768{
3769 spa_t *spa = dp->dp_spa;
3770 dsl_scan_t *scn = dp->dp_scan;
3771 size_t size = BP_GET_PSIZE(bp);
3772 abd_t *data = abd_alloc_for_io(size, B_FALSE);
3773
f90a30ad
BB
3774 ASSERT3U(scn->scn_maxinflight_bytes, >, 0);
3775
d4a72f23 3776 if (queue == NULL) {
428870ff 3777 mutex_enter(&spa->spa_scrub_lock);
d4a72f23 3778 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
428870ff 3779 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
d4a72f23 3780 spa->spa_scrub_inflight += BP_GET_PSIZE(bp);
428870ff 3781 mutex_exit(&spa->spa_scrub_lock);
d4a72f23
TC
3782 } else {
3783 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
428870ff 3784
d4a72f23
TC
3785 mutex_enter(q_lock);
3786 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
3787 cv_wait(&queue->q_zio_cv, q_lock);
3788 queue->q_inflight_bytes += BP_GET_PSIZE(bp);
3789 mutex_exit(q_lock);
3790 }
3791
3792 count_block(scn, dp->dp_blkstats, bp);
3793 zio_nowait(zio_read(scn->scn_zio_root, spa, bp, data, size,
3794 dsl_scan_scrub_done, queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
3795}
572e2857 3796
d4a72f23
TC
3797/*
3798 * This is the primary extent sorting algorithm. We balance two parameters:
3799 * 1) how many bytes of I/O are in an extent
3800 * 2) how well the extent is filled with I/O (as a fraction of its total size)
3801 * Since we allow extents to have gaps between their constituent I/Os, it's
3802 * possible to have a fairly large extent that contains the same amount of
3803 * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
3804 * The algorithm sorts based on a score calculated from the extent's size,
3805 * the relative fill volume (in %) and a "fill weight" parameter that controls
3806 * the split between whether we prefer larger extents or more well populated
3807 * extents:
3808 *
3809 * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
3810 *
3811 * Example:
3812 * 1) assume extsz = 64 MiB
3813 * 2) assume fill = 32 MiB (extent is half full)
3814 * 3) assume fill_weight = 3
3815 * 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
3816 * SCORE = 32M + (50 * 3 * 32M) / 100
3817 * SCORE = 32M + (4800M / 100)
3818 * SCORE = 32M + 48M
3819 * ^ ^
3820 * | +--- final total relative fill-based score
3821 * +--------- final total fill-based score
3822 * SCORE = 80M
3823 *
3824 * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
3825 * extents that are more completely filled (in a 3:2 ratio) vs just larger.
3826 * Note that as an optimization, we replace multiplication and division by
3827 * 100 with bitshifting by 7 (which effecitvely multiplies and divides by 128).
3828 */
3829static int
3830ext_size_compare(const void *x, const void *y)
3831{
3832 const range_seg_t *rsa = x, *rsb = y;
3833 uint64_t sa = rsa->rs_end - rsa->rs_start,
3834 sb = rsb->rs_end - rsb->rs_start;
3835 uint64_t score_a, score_b;
3836
3837 score_a = rsa->rs_fill + ((((rsa->rs_fill << 7) / sa) *
3838 fill_weight * rsa->rs_fill) >> 7);
3839 score_b = rsb->rs_fill + ((((rsb->rs_fill << 7) / sb) *
3840 fill_weight * rsb->rs_fill) >> 7);
3841
3842 if (score_a > score_b)
3843 return (-1);
3844 if (score_a == score_b) {
3845 if (rsa->rs_start < rsb->rs_start)
3846 return (-1);
3847 if (rsa->rs_start == rsb->rs_start)
3848 return (0);
3849 return (1);
428870ff 3850 }
d4a72f23
TC
3851 return (1);
3852}
428870ff 3853
d4a72f23
TC
3854/*
3855 * Comparator for the q_sios_by_addr tree. Sorting is simply performed
3856 * based on LBA-order (from lowest to highest).
3857 */
3858static int
3859sio_addr_compare(const void *x, const void *y)
3860{
3861 const scan_io_t *a = x, *b = y;
3862
3863 if (a->sio_offset < b->sio_offset)
3864 return (-1);
3865 if (a->sio_offset == b->sio_offset)
3866 return (0);
3867 return (1);
3868}
3869
3870/* IO queues are created on demand when they are needed. */
3871static dsl_scan_io_queue_t *
3872scan_io_queue_create(vdev_t *vd)
3873{
3874 dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
3875 dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
3876
3877 q->q_scn = scn;
3878 q->q_vd = vd;
3879 cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
3880 q->q_exts_by_addr = range_tree_create_impl(&rt_avl_ops,
a1d477c2 3881 &q->q_exts_by_size, ext_size_compare, zfs_scan_max_ext_gap);
d4a72f23
TC
3882 avl_create(&q->q_sios_by_addr, sio_addr_compare,
3883 sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));
3884
3885 return (q);
428870ff
BB
3886}
3887
0ea05c64 3888/*
d4a72f23
TC
3889 * Destroys a scan queue and all segments and scan_io_t's contained in it.
3890 * No further execution of I/O occurs, anything pending in the queue is
3891 * simply freed without being executed.
0ea05c64 3892 */
d4a72f23
TC
3893void
3894dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
428870ff 3895{
d4a72f23
TC
3896 dsl_scan_t *scn = queue->q_scn;
3897 scan_io_t *sio;
3898 void *cookie = NULL;
3899 int64_t bytes_dequeued = 0;
3900
3901 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3902
3903 while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
3904 NULL) {
3905 ASSERT(range_tree_contains(queue->q_exts_by_addr,
3906 sio->sio_offset, sio->sio_asize));
3907 bytes_dequeued += sio->sio_asize;
3908 kmem_cache_free(sio_cache, sio);
3909 }
428870ff 3910
d4a72f23
TC
3911 atomic_add_64(&scn->scn_bytes_pending, -bytes_dequeued);
3912 range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
3913 range_tree_destroy(queue->q_exts_by_addr);
3914 avl_destroy(&queue->q_sios_by_addr);
3915 cv_destroy(&queue->q_zio_cv);
428870ff 3916
d4a72f23
TC
3917 kmem_free(queue, sizeof (*queue));
3918}
0ea05c64 3919
d4a72f23
TC
3920/*
3921 * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
3922 * called on behalf of vdev_top_transfer when creating or destroying
3923 * a mirror vdev due to zpool attach/detach.
3924 */
3925void
3926dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
3927{
3928 mutex_enter(&svd->vdev_scan_io_queue_lock);
3929 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3930
3931 VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL);
3932 tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
3933 svd->vdev_scan_io_queue = NULL;
a1d477c2 3934 if (tvd->vdev_scan_io_queue != NULL)
d4a72f23 3935 tvd->vdev_scan_io_queue->q_vd = tvd;
0ea05c64 3936
d4a72f23
TC
3937 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3938 mutex_exit(&svd->vdev_scan_io_queue_lock);
428870ff 3939}
c409e464 3940
d4a72f23
TC
3941static void
3942scan_io_queues_destroy(dsl_scan_t *scn)
784d15c1 3943{
d4a72f23
TC
3944 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
3945
3946 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3947 vdev_t *tvd = rvd->vdev_child[i];
3948
3949 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3950 if (tvd->vdev_scan_io_queue != NULL)
3951 dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
3952 tvd->vdev_scan_io_queue = NULL;
3953 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3954 }
784d15c1
NR
3955}
3956
d4a72f23
TC
3957static void
3958dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
3959{
3960 dsl_pool_t *dp = spa->spa_dsl_pool;
3961 dsl_scan_t *scn = dp->dp_scan;
3962 vdev_t *vdev;
3963 kmutex_t *q_lock;
3964 dsl_scan_io_queue_t *queue;
3965 scan_io_t srch, *sio;
3966 avl_index_t idx;
3967 uint64_t start, size;
3968
3969 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
3970 ASSERT(vdev != NULL);
3971 q_lock = &vdev->vdev_scan_io_queue_lock;
3972 queue = vdev->vdev_scan_io_queue;
3973
3974 mutex_enter(q_lock);
3975 if (queue == NULL) {
3976 mutex_exit(q_lock);
3977 return;
3978 }
3979
3980 bp2sio(bp, &srch, dva_i);
3981 start = srch.sio_offset;
3982 size = srch.sio_asize;
3983
3984 /*
3985 * We can find the zio in two states:
3986 * 1) Cold, just sitting in the queue of zio's to be issued at
3987 * some point in the future. In this case, all we do is
3988 * remove the zio from the q_sios_by_addr tree, decrement
3989 * its data volume from the containing range_seg_t and
3990 * resort the q_exts_by_size tree to reflect that the
3991 * range_seg_t has lost some of its 'fill'. We don't shorten
3992 * the range_seg_t - this is usually rare enough not to be
3993 * worth the extra hassle of trying keep track of precise
3994 * extent boundaries.
3995 * 2) Hot, where the zio is currently in-flight in
3996 * dsl_scan_issue_ios. In this case, we can't simply
3997 * reach in and stop the in-flight zio's, so we instead
3998 * block the caller. Eventually, dsl_scan_issue_ios will
3999 * be done with issuing the zio's it gathered and will
4000 * signal us.
4001 */
4002 sio = avl_find(&queue->q_sios_by_addr, &srch, &idx);
4003 if (sio != NULL) {
4004 int64_t asize = sio->sio_asize;
4005 blkptr_t tmpbp;
4006
4007 /* Got it while it was cold in the queue */
4008 ASSERT3U(start, ==, sio->sio_offset);
4009 ASSERT3U(size, ==, asize);
4010 avl_remove(&queue->q_sios_by_addr, sio);
c409e464 4011
d4a72f23
TC
4012 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size));
4013 range_tree_remove_fill(queue->q_exts_by_addr, start, size);
4014
4015 /*
4016 * We only update scn_bytes_pending in the cold path,
4017 * otherwise it will already have been accounted for as
4018 * part of the zio's execution.
4019 */
4020 atomic_add_64(&scn->scn_bytes_pending, -asize);
c409e464 4021
d4a72f23
TC
4022 /* count the block as though we issued it */
4023 sio2bp(sio, &tmpbp, dva_i);
4024 count_block(scn, dp->dp_blkstats, &tmpbp);
c409e464 4025
d4a72f23
TC
4026 kmem_cache_free(sio_cache, sio);
4027 }
4028 mutex_exit(q_lock);
4029}
c409e464 4030
d4a72f23
TC
4031/*
4032 * Callback invoked when a zio_free() zio is executing. This needs to be
4033 * intercepted to prevent the zio from deallocating a particular portion
4034 * of disk space and it then getting reallocated and written to, while we
4035 * still have it queued up for processing.
4036 */
4037void
4038dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
4039{
4040 dsl_pool_t *dp = spa->spa_dsl_pool;
4041 dsl_scan_t *scn = dp->dp_scan;
4042
4043 ASSERT(!BP_IS_EMBEDDED(bp));
4044 ASSERT(scn != NULL);
4045 if (!dsl_scan_is_running(scn))
4046 return;
4047
4048 for (int i = 0; i < BP_GET_NDVAS(bp); i++)
4049 dsl_scan_freed_dva(spa, bp, i);
4050}
4051
93ce2b4c 4052#if defined(_KERNEL)
d4a72f23
TC
4053/* CSTYLED */
4054module_param(zfs_scan_vdev_limit, ulong, 0644);
4055MODULE_PARM_DESC(zfs_scan_vdev_limit,
4056 "Max bytes in flight per leaf vdev for scrubs and resilvers");
4057
4058module_param(zfs_scrub_min_time_ms, int, 0644);
4059MODULE_PARM_DESC(zfs_scrub_min_time_ms, "Min millisecs to scrub per txg");
c409e464 4060
a1d477c2
MA
4061module_param(zfs_obsolete_min_time_ms, int, 0644);
4062MODULE_PARM_DESC(zfs_obsolete_min_time_ms, "Min millisecs to obsolete per txg");
4063
c409e464
BB
4064module_param(zfs_free_min_time_ms, int, 0644);
4065MODULE_PARM_DESC(zfs_free_min_time_ms, "Min millisecs to free per txg");
4066
4067module_param(zfs_resilver_min_time_ms, int, 0644);
4068MODULE_PARM_DESC(zfs_resilver_min_time_ms, "Min millisecs to resilver per txg");
4069
4070module_param(zfs_no_scrub_io, int, 0644);
4071MODULE_PARM_DESC(zfs_no_scrub_io, "Set to disable scrub I/O");
4072
4073module_param(zfs_no_scrub_prefetch, int, 0644);
4074MODULE_PARM_DESC(zfs_no_scrub_prefetch, "Set to disable scrub prefetching");
36283ca2 4075
02730c33 4076/* CSTYLED */
a1d477c2
MA
4077module_param(zfs_async_block_max_blocks, ulong, 0644);
4078MODULE_PARM_DESC(zfs_async_block_max_blocks,
4079 "Max number of blocks freed in one txg");
ba5ad9a4
GW
4080
4081module_param(zfs_free_bpobj_enabled, int, 0644);
4082MODULE_PARM_DESC(zfs_free_bpobj_enabled, "Enable processing of the free_bpobj");
d4a72f23
TC
4083
4084module_param(zfs_scan_mem_lim_fact, int, 0644);
4085MODULE_PARM_DESC(zfs_scan_mem_lim_fact, "Fraction of RAM for scan hard limit");
4086
4087module_param(zfs_scan_issue_strategy, int, 0644);
4088MODULE_PARM_DESC(zfs_scan_issue_strategy,
4089 "IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");
4090
4091module_param(zfs_scan_legacy, int, 0644);
4092MODULE_PARM_DESC(zfs_scan_legacy, "Scrub using legacy non-sequential method");
4093
4094module_param(zfs_scan_checkpoint_intval, int, 0644);
4095MODULE_PARM_DESC(zfs_scan_checkpoint_intval,
4096 "Scan progress on-disk checkpointing interval");
4097
63f88c12 4098/* CSTYLED */
4099module_param(zfs_scan_max_ext_gap, ulong, 0644);
4100MODULE_PARM_DESC(zfs_scan_max_ext_gap,
4101 "Max gap in bytes between sequential scrub / resilver I/Os");
4102
d4a72f23
TC
4103module_param(zfs_scan_mem_lim_soft_fact, int, 0644);
4104MODULE_PARM_DESC(zfs_scan_mem_lim_soft_fact,
4105 "Fraction of hard limit used as soft limit");
4106
4107module_param(zfs_scan_strict_mem_lim, int, 0644);
4108MODULE_PARM_DESC(zfs_scan_strict_mem_lim,
4109 "Tunable to attempt to reduce lock contention");
4110
4111module_param(zfs_scan_fill_weight, int, 0644);
4112MODULE_PARM_DESC(zfs_scan_fill_weight,
4113 "Tunable to adjust bias towards more filled segments during scans");
80a91e74
TC
4114
4115module_param(zfs_resilver_disable_defer, int, 0644);
4116MODULE_PARM_DESC(zfs_resilver_disable_defer,
4117 "Process all resilvers immediately");
c409e464 4118#endif