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