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