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