]> git.proxmox.com Git - mirror_zfs.git/blob - module/zfs/dsl_scan.c
OpenZFS 9235 - rename zpool_rewind_policy_t to zpool_load_policy_t
[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 (dp->dp_origin_snap == NULL ||
2170 ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
2171 objset_t *os;
2172 if (dmu_objset_from_ds(ds, &os) != 0) {
2173 goto out;
2174 }
2175 dsl_scan_zil(dp, &os->os_zil_header);
2176 }
2177
2178 /*
2179 * Iterate over the bps in this ds.
2180 */
2181 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2182 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2183 dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
2184 rrw_exit(&ds->ds_bp_rwlock, FTAG);
2185
2186 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2187 dsl_dataset_name(ds, dsname);
2188 zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
2189 "suspending=%u",
2190 (longlong_t)dsobj, dsname,
2191 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2192 (longlong_t)scn->scn_phys.scn_cur_max_txg,
2193 (int)scn->scn_suspending);
2194 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
2195
2196 if (scn->scn_suspending)
2197 goto out;
2198
2199 /*
2200 * We've finished this pass over this dataset.
2201 */
2202
2203 /*
2204 * If we did not completely visit this dataset, do another pass.
2205 */
2206 if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
2207 zfs_dbgmsg("incomplete pass; visiting again");
2208 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
2209 scan_ds_queue_insert(scn, ds->ds_object,
2210 scn->scn_phys.scn_cur_max_txg);
2211 goto out;
2212 }
2213
2214 /*
2215 * Add descendant datasets to work queue.
2216 */
2217 if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
2218 scan_ds_queue_insert(scn,
2219 dsl_dataset_phys(ds)->ds_next_snap_obj,
2220 dsl_dataset_phys(ds)->ds_creation_txg);
2221 }
2222 if (dsl_dataset_phys(ds)->ds_num_children > 1) {
2223 boolean_t usenext = B_FALSE;
2224 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2225 uint64_t count;
2226 /*
2227 * A bug in a previous version of the code could
2228 * cause upgrade_clones_cb() to not set
2229 * ds_next_snap_obj when it should, leading to a
2230 * missing entry. Therefore we can only use the
2231 * next_clones_obj when its count is correct.
2232 */
2233 int err = zap_count(dp->dp_meta_objset,
2234 dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
2235 if (err == 0 &&
2236 count == dsl_dataset_phys(ds)->ds_num_children - 1)
2237 usenext = B_TRUE;
2238 }
2239
2240 if (usenext) {
2241 zap_cursor_t zc;
2242 zap_attribute_t za;
2243 for (zap_cursor_init(&zc, dp->dp_meta_objset,
2244 dsl_dataset_phys(ds)->ds_next_clones_obj);
2245 zap_cursor_retrieve(&zc, &za) == 0;
2246 (void) zap_cursor_advance(&zc)) {
2247 scan_ds_queue_insert(scn,
2248 zfs_strtonum(za.za_name, NULL),
2249 dsl_dataset_phys(ds)->ds_creation_txg);
2250 }
2251 zap_cursor_fini(&zc);
2252 } else {
2253 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2254 enqueue_clones_cb, &ds->ds_object,
2255 DS_FIND_CHILDREN));
2256 }
2257 }
2258
2259 out:
2260 dsl_dataset_rele(ds, FTAG);
2261 }
2262
2263 /* ARGSUSED */
2264 static int
2265 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2266 {
2267 dsl_dataset_t *ds;
2268 int err;
2269 dsl_scan_t *scn = dp->dp_scan;
2270
2271 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2272 if (err)
2273 return (err);
2274
2275 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2276 dsl_dataset_t *prev;
2277 err = dsl_dataset_hold_obj(dp,
2278 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2279 if (err) {
2280 dsl_dataset_rele(ds, FTAG);
2281 return (err);
2282 }
2283
2284 /*
2285 * If this is a clone, we don't need to worry about it for now.
2286 */
2287 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
2288 dsl_dataset_rele(ds, FTAG);
2289 dsl_dataset_rele(prev, FTAG);
2290 return (0);
2291 }
2292 dsl_dataset_rele(ds, FTAG);
2293 ds = prev;
2294 }
2295
2296 scan_ds_queue_insert(scn, ds->ds_object,
2297 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2298 dsl_dataset_rele(ds, FTAG);
2299 return (0);
2300 }
2301
2302 /* ARGSUSED */
2303 void
2304 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
2305 ddt_entry_t *dde, dmu_tx_t *tx)
2306 {
2307 const ddt_key_t *ddk = &dde->dde_key;
2308 ddt_phys_t *ddp = dde->dde_phys;
2309 blkptr_t bp;
2310 zbookmark_phys_t zb = { 0 };
2311 int p;
2312
2313 if (!dsl_scan_is_running(scn))
2314 return;
2315
2316 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2317 if (ddp->ddp_phys_birth == 0 ||
2318 ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
2319 continue;
2320 ddt_bp_create(checksum, ddk, ddp, &bp);
2321
2322 scn->scn_visited_this_txg++;
2323 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
2324 }
2325 }
2326
2327 /*
2328 * Scrub/dedup interaction.
2329 *
2330 * If there are N references to a deduped block, we don't want to scrub it
2331 * N times -- ideally, we should scrub it exactly once.
2332 *
2333 * We leverage the fact that the dde's replication class (enum ddt_class)
2334 * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
2335 * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
2336 *
2337 * To prevent excess scrubbing, the scrub begins by walking the DDT
2338 * to find all blocks with refcnt > 1, and scrubs each of these once.
2339 * Since there are two replication classes which contain blocks with
2340 * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
2341 * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
2342 *
2343 * There would be nothing more to say if a block's refcnt couldn't change
2344 * during a scrub, but of course it can so we must account for changes
2345 * in a block's replication class.
2346 *
2347 * Here's an example of what can occur:
2348 *
2349 * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
2350 * when visited during the top-down scrub phase, it will be scrubbed twice.
2351 * This negates our scrub optimization, but is otherwise harmless.
2352 *
2353 * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
2354 * on each visit during the top-down scrub phase, it will never be scrubbed.
2355 * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
2356 * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
2357 * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
2358 * while a scrub is in progress, it scrubs the block right then.
2359 */
2360 static void
2361 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
2362 {
2363 ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
2364 ddt_entry_t dde;
2365 int error;
2366 uint64_t n = 0;
2367
2368 bzero(&dde, sizeof (ddt_entry_t));
2369
2370 while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
2371 ddt_t *ddt;
2372
2373 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
2374 break;
2375 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
2376 (longlong_t)ddb->ddb_class,
2377 (longlong_t)ddb->ddb_type,
2378 (longlong_t)ddb->ddb_checksum,
2379 (longlong_t)ddb->ddb_cursor);
2380
2381 /* There should be no pending changes to the dedup table */
2382 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
2383 ASSERT(avl_first(&ddt->ddt_tree) == NULL);
2384
2385 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
2386 n++;
2387
2388 if (dsl_scan_check_suspend(scn, NULL))
2389 break;
2390 }
2391
2392 zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; "
2393 "suspending=%u", (longlong_t)n,
2394 (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending);
2395
2396 ASSERT(error == 0 || error == ENOENT);
2397 ASSERT(error != ENOENT ||
2398 ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
2399 }
2400
2401 static uint64_t
2402 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
2403 {
2404 uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
2405 if (ds->ds_is_snapshot)
2406 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
2407 return (smt);
2408 }
2409
2410 static void
2411 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
2412 {
2413 scan_ds_t *sds;
2414 dsl_pool_t *dp = scn->scn_dp;
2415
2416 if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
2417 scn->scn_phys.scn_ddt_class_max) {
2418 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2419 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2420 dsl_scan_ddt(scn, tx);
2421 if (scn->scn_suspending)
2422 return;
2423 }
2424
2425 if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
2426 /* First do the MOS & ORIGIN */
2427
2428 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2429 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2430 dsl_scan_visit_rootbp(scn, NULL,
2431 &dp->dp_meta_rootbp, tx);
2432 spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
2433 if (scn->scn_suspending)
2434 return;
2435
2436 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
2437 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2438 enqueue_cb, NULL, DS_FIND_CHILDREN));
2439 } else {
2440 dsl_scan_visitds(scn,
2441 dp->dp_origin_snap->ds_object, tx);
2442 }
2443 ASSERT(!scn->scn_suspending);
2444 } else if (scn->scn_phys.scn_bookmark.zb_objset !=
2445 ZB_DESTROYED_OBJSET) {
2446 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
2447 /*
2448 * If we were suspended, continue from here. Note if the
2449 * ds we were suspended on was deleted, the zb_objset may
2450 * be -1, so we will skip this and find a new objset
2451 * below.
2452 */
2453 dsl_scan_visitds(scn, dsobj, tx);
2454 if (scn->scn_suspending)
2455 return;
2456 }
2457
2458 /*
2459 * In case we suspended right at the end of the ds, zero the
2460 * bookmark so we don't think that we're still trying to resume.
2461 */
2462 bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
2463
2464 /*
2465 * Keep pulling things out of the dataset avl queue. Updates to the
2466 * persistent zap-object-as-queue happen only at checkpoints.
2467 */
2468 while ((sds = avl_first(&scn->scn_queue)) != NULL) {
2469 dsl_dataset_t *ds;
2470 uint64_t dsobj = sds->sds_dsobj;
2471 uint64_t txg = sds->sds_txg;
2472
2473 /* dequeue and free the ds from the queue */
2474 scan_ds_queue_remove(scn, dsobj);
2475 sds = NULL;
2476
2477 /* set up min / max txg */
2478 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2479 if (txg != 0) {
2480 scn->scn_phys.scn_cur_min_txg =
2481 MAX(scn->scn_phys.scn_min_txg, txg);
2482 } else {
2483 scn->scn_phys.scn_cur_min_txg =
2484 MAX(scn->scn_phys.scn_min_txg,
2485 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2486 }
2487 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
2488 dsl_dataset_rele(ds, FTAG);
2489
2490 dsl_scan_visitds(scn, dsobj, tx);
2491 if (scn->scn_suspending)
2492 return;
2493 }
2494
2495 /* No more objsets to fetch, we're done */
2496 scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
2497 ASSERT0(scn->scn_suspending);
2498 }
2499
2500 static uint64_t
2501 dsl_scan_count_leaves(vdev_t *vd)
2502 {
2503 uint64_t i, leaves = 0;
2504
2505 /* we only count leaves that belong to the main pool and are readable */
2506 if (vd->vdev_islog || vd->vdev_isspare ||
2507 vd->vdev_isl2cache || !vdev_readable(vd))
2508 return (0);
2509
2510 if (vd->vdev_ops->vdev_op_leaf)
2511 return (1);
2512
2513 for (i = 0; i < vd->vdev_children; i++) {
2514 leaves += dsl_scan_count_leaves(vd->vdev_child[i]);
2515 }
2516
2517 return (leaves);
2518 }
2519
2520 static void
2521 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
2522 {
2523 int i;
2524 uint64_t cur_size = 0;
2525
2526 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
2527 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
2528 }
2529
2530 q->q_total_zio_size_this_txg += cur_size;
2531 q->q_zios_this_txg++;
2532 }
2533
2534 static void
2535 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
2536 uint64_t end)
2537 {
2538 q->q_total_seg_size_this_txg += end - start;
2539 q->q_segs_this_txg++;
2540 }
2541
2542 static boolean_t
2543 scan_io_queue_check_suspend(dsl_scan_t *scn)
2544 {
2545 /* See comment in dsl_scan_check_suspend() */
2546 uint64_t curr_time_ns = gethrtime();
2547 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
2548 uint64_t sync_time_ns = curr_time_ns -
2549 scn->scn_dp->dp_spa->spa_sync_starttime;
2550 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
2551 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
2552 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
2553
2554 return ((NSEC2MSEC(scan_time_ns) > mintime &&
2555 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
2556 txg_sync_waiting(scn->scn_dp) ||
2557 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
2558 spa_shutting_down(scn->scn_dp->dp_spa));
2559 }
2560
2561 /*
2562 * Given a list of scan_io_t's in io_list, this issues the I/Os out to
2563 * disk. This consumes the io_list and frees the scan_io_t's. This is
2564 * called when emptying queues, either when we're up against the memory
2565 * limit or when we have finished scanning. Returns B_TRUE if we stopped
2566 * processing the list before we finished. Any sios that were not issued
2567 * will remain in the io_list.
2568 */
2569 static boolean_t
2570 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
2571 {
2572 dsl_scan_t *scn = queue->q_scn;
2573 scan_io_t *sio;
2574 int64_t bytes_issued = 0;
2575 boolean_t suspended = B_FALSE;
2576
2577 while ((sio = list_head(io_list)) != NULL) {
2578 blkptr_t bp;
2579
2580 if (scan_io_queue_check_suspend(scn)) {
2581 suspended = B_TRUE;
2582 break;
2583 }
2584
2585 sio2bp(sio, &bp, queue->q_vd->vdev_id);
2586 bytes_issued += sio->sio_asize;
2587 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
2588 &sio->sio_zb, queue);
2589 (void) list_remove_head(io_list);
2590 scan_io_queues_update_zio_stats(queue, &bp);
2591 kmem_cache_free(sio_cache, sio);
2592 }
2593
2594 atomic_add_64(&scn->scn_bytes_pending, -bytes_issued);
2595
2596 return (suspended);
2597 }
2598
2599 /*
2600 * This function removes sios from an IO queue which reside within a given
2601 * range_seg_t and inserts them (in offset order) into a list. Note that
2602 * we only ever return a maximum of 32 sios at once. If there are more sios
2603 * to process within this segment that did not make it onto the list we
2604 * return B_TRUE and otherwise B_FALSE.
2605 */
2606 static boolean_t
2607 scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list)
2608 {
2609 scan_io_t srch_sio, *sio, *next_sio;
2610 avl_index_t idx;
2611 uint_t num_sios = 0;
2612 int64_t bytes_issued = 0;
2613
2614 ASSERT(rs != NULL);
2615 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2616
2617 srch_sio.sio_offset = rs->rs_start;
2618
2619 /*
2620 * The exact start of the extent might not contain any matching zios,
2621 * so if that's the case, examine the next one in the tree.
2622 */
2623 sio = avl_find(&queue->q_sios_by_addr, &srch_sio, &idx);
2624 if (sio == NULL)
2625 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
2626
2627 while (sio != NULL && sio->sio_offset < rs->rs_end && num_sios <= 32) {
2628 ASSERT3U(sio->sio_offset, >=, rs->rs_start);
2629 ASSERT3U(sio->sio_offset + sio->sio_asize, <=, rs->rs_end);
2630
2631 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
2632 avl_remove(&queue->q_sios_by_addr, sio);
2633
2634 bytes_issued += sio->sio_asize;
2635 num_sios++;
2636 list_insert_tail(list, sio);
2637 sio = next_sio;
2638 }
2639
2640 /*
2641 * We limit the number of sios we process at once to 32 to avoid
2642 * biting off more than we can chew. If we didn't take everything
2643 * in the segment we update it to reflect the work we were able to
2644 * complete. Otherwise, we remove it from the range tree entirely.
2645 */
2646 if (sio != NULL && sio->sio_offset < rs->rs_end) {
2647 range_tree_adjust_fill(queue->q_exts_by_addr, rs,
2648 -bytes_issued);
2649 range_tree_resize_segment(queue->q_exts_by_addr, rs,
2650 sio->sio_offset, rs->rs_end - sio->sio_offset);
2651
2652 return (B_TRUE);
2653 } else {
2654 range_tree_remove(queue->q_exts_by_addr, rs->rs_start,
2655 rs->rs_end - rs->rs_start);
2656 return (B_FALSE);
2657 }
2658 }
2659
2660 /*
2661 * This is called from the queue emptying thread and selects the next
2662 * extent from which we are to issue I/Os. The behavior of this function
2663 * depends on the state of the scan, the current memory consumption and
2664 * whether or not we are performing a scan shutdown.
2665 * 1) We select extents in an elevator algorithm (LBA-order) if the scan
2666 * needs to perform a checkpoint
2667 * 2) We select the largest available extent if we are up against the
2668 * memory limit.
2669 * 3) Otherwise we don't select any extents.
2670 */
2671 static range_seg_t *
2672 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
2673 {
2674 dsl_scan_t *scn = queue->q_scn;
2675
2676 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2677 ASSERT(scn->scn_is_sorted);
2678
2679 /* handle tunable overrides */
2680 if (scn->scn_checkpointing || scn->scn_clearing) {
2681 if (zfs_scan_issue_strategy == 1) {
2682 return (range_tree_first(queue->q_exts_by_addr));
2683 } else if (zfs_scan_issue_strategy == 2) {
2684 return (avl_first(&queue->q_exts_by_size));
2685 }
2686 }
2687
2688 /*
2689 * During normal clearing, we want to issue our largest segments
2690 * first, keeping IO as sequential as possible, and leaving the
2691 * smaller extents for later with the hope that they might eventually
2692 * grow to larger sequential segments. However, when the scan is
2693 * checkpointing, no new extents will be added to the sorting queue,
2694 * so the way we are sorted now is as good as it will ever get.
2695 * In this case, we instead switch to issuing extents in LBA order.
2696 */
2697 if (scn->scn_checkpointing) {
2698 return (range_tree_first(queue->q_exts_by_addr));
2699 } else if (scn->scn_clearing) {
2700 return (avl_first(&queue->q_exts_by_size));
2701 } else {
2702 return (NULL);
2703 }
2704 }
2705
2706 static void
2707 scan_io_queues_run_one(void *arg)
2708 {
2709 dsl_scan_io_queue_t *queue = arg;
2710 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
2711 boolean_t suspended = B_FALSE;
2712 range_seg_t *rs = NULL;
2713 scan_io_t *sio = NULL;
2714 list_t sio_list;
2715 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
2716 uint64_t nr_leaves = dsl_scan_count_leaves(queue->q_vd);
2717
2718 ASSERT(queue->q_scn->scn_is_sorted);
2719
2720 list_create(&sio_list, sizeof (scan_io_t),
2721 offsetof(scan_io_t, sio_nodes.sio_list_node));
2722 mutex_enter(q_lock);
2723
2724 /* calculate maximum in-flight bytes for this txg (min 1MB) */
2725 queue->q_maxinflight_bytes =
2726 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
2727
2728 /* reset per-queue scan statistics for this txg */
2729 queue->q_total_seg_size_this_txg = 0;
2730 queue->q_segs_this_txg = 0;
2731 queue->q_total_zio_size_this_txg = 0;
2732 queue->q_zios_this_txg = 0;
2733
2734 /* loop until we run out of time or sios */
2735 while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {
2736 uint64_t seg_start = 0, seg_end = 0;
2737 boolean_t more_left = B_TRUE;
2738
2739 ASSERT(list_is_empty(&sio_list));
2740
2741 /* loop while we still have sios left to process in this rs */
2742 while (more_left) {
2743 scan_io_t *first_sio, *last_sio;
2744
2745 /*
2746 * We have selected which extent needs to be
2747 * processed next. Gather up the corresponding sios.
2748 */
2749 more_left = scan_io_queue_gather(queue, rs, &sio_list);
2750 ASSERT(!list_is_empty(&sio_list));
2751 first_sio = list_head(&sio_list);
2752 last_sio = list_tail(&sio_list);
2753
2754 seg_end = last_sio->sio_offset + last_sio->sio_asize;
2755 if (seg_start == 0)
2756 seg_start = first_sio->sio_offset;
2757
2758 /*
2759 * Issuing sios can take a long time so drop the
2760 * queue lock. The sio queue won't be updated by
2761 * other threads since we're in syncing context so
2762 * we can be sure that our trees will remain exactly
2763 * as we left them.
2764 */
2765 mutex_exit(q_lock);
2766 suspended = scan_io_queue_issue(queue, &sio_list);
2767 mutex_enter(q_lock);
2768
2769 if (suspended)
2770 break;
2771 }
2772
2773 /* update statistics for debugging purposes */
2774 scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
2775
2776 if (suspended)
2777 break;
2778 }
2779
2780 /*
2781 * If we were suspended in the middle of processing,
2782 * requeue any unfinished sios and exit.
2783 */
2784 while ((sio = list_head(&sio_list)) != NULL) {
2785 list_remove(&sio_list, sio);
2786 scan_io_queue_insert_impl(queue, sio);
2787 }
2788
2789 mutex_exit(q_lock);
2790 list_destroy(&sio_list);
2791 }
2792
2793 /*
2794 * Performs an emptying run on all scan queues in the pool. This just
2795 * punches out one thread per top-level vdev, each of which processes
2796 * only that vdev's scan queue. We can parallelize the I/O here because
2797 * we know that each queue's I/Os only affect its own top-level vdev.
2798 *
2799 * This function waits for the queue runs to complete, and must be
2800 * called from dsl_scan_sync (or in general, syncing context).
2801 */
2802 static void
2803 scan_io_queues_run(dsl_scan_t *scn)
2804 {
2805 spa_t *spa = scn->scn_dp->dp_spa;
2806
2807 ASSERT(scn->scn_is_sorted);
2808 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2809
2810 if (scn->scn_bytes_pending == 0)
2811 return;
2812
2813 if (scn->scn_taskq == NULL) {
2814 int nthreads = spa->spa_root_vdev->vdev_children;
2815
2816 /*
2817 * We need to make this taskq *always* execute as many
2818 * threads in parallel as we have top-level vdevs and no
2819 * less, otherwise strange serialization of the calls to
2820 * scan_io_queues_run_one can occur during spa_sync runs
2821 * and that significantly impacts performance.
2822 */
2823 scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,
2824 minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);
2825 }
2826
2827 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2828 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2829
2830 mutex_enter(&vd->vdev_scan_io_queue_lock);
2831 if (vd->vdev_scan_io_queue != NULL) {
2832 VERIFY(taskq_dispatch(scn->scn_taskq,
2833 scan_io_queues_run_one, vd->vdev_scan_io_queue,
2834 TQ_SLEEP) != TASKQID_INVALID);
2835 }
2836 mutex_exit(&vd->vdev_scan_io_queue_lock);
2837 }
2838
2839 /*
2840 * Wait for the queues to finish issuing their IOs for this run
2841 * before we return. There may still be IOs in flight at this
2842 * point.
2843 */
2844 taskq_wait(scn->scn_taskq);
2845 }
2846
2847 static boolean_t
2848 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
2849 {
2850 uint64_t elapsed_nanosecs;
2851
2852 if (zfs_recover)
2853 return (B_FALSE);
2854
2855 if (scn->scn_visited_this_txg >= zfs_async_block_max_blocks)
2856 return (B_TRUE);
2857
2858 elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
2859 return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
2860 (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
2861 txg_sync_waiting(scn->scn_dp)) ||
2862 spa_shutting_down(scn->scn_dp->dp_spa));
2863 }
2864
2865 static int
2866 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2867 {
2868 dsl_scan_t *scn = arg;
2869
2870 if (!scn->scn_is_bptree ||
2871 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
2872 if (dsl_scan_async_block_should_pause(scn))
2873 return (SET_ERROR(ERESTART));
2874 }
2875
2876 zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
2877 dmu_tx_get_txg(tx), bp, 0));
2878 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
2879 -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
2880 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
2881 scn->scn_visited_this_txg++;
2882 return (0);
2883 }
2884
2885 static void
2886 dsl_scan_update_stats(dsl_scan_t *scn)
2887 {
2888 spa_t *spa = scn->scn_dp->dp_spa;
2889 uint64_t i;
2890 uint64_t seg_size_total = 0, zio_size_total = 0;
2891 uint64_t seg_count_total = 0, zio_count_total = 0;
2892
2893 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2894 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2895 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
2896
2897 if (queue == NULL)
2898 continue;
2899
2900 seg_size_total += queue->q_total_seg_size_this_txg;
2901 zio_size_total += queue->q_total_zio_size_this_txg;
2902 seg_count_total += queue->q_segs_this_txg;
2903 zio_count_total += queue->q_zios_this_txg;
2904 }
2905
2906 if (seg_count_total == 0 || zio_count_total == 0) {
2907 scn->scn_avg_seg_size_this_txg = 0;
2908 scn->scn_avg_zio_size_this_txg = 0;
2909 scn->scn_segs_this_txg = 0;
2910 scn->scn_zios_this_txg = 0;
2911 return;
2912 }
2913
2914 scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
2915 scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
2916 scn->scn_segs_this_txg = seg_count_total;
2917 scn->scn_zios_this_txg = zio_count_total;
2918 }
2919
2920 static int
2921 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2922 {
2923 dsl_scan_t *scn = arg;
2924 const dva_t *dva = &bp->blk_dva[0];
2925
2926 if (dsl_scan_async_block_should_pause(scn))
2927 return (SET_ERROR(ERESTART));
2928
2929 spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
2930 DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
2931 DVA_GET_ASIZE(dva), tx);
2932 scn->scn_visited_this_txg++;
2933 return (0);
2934 }
2935
2936 boolean_t
2937 dsl_scan_active(dsl_scan_t *scn)
2938 {
2939 spa_t *spa = scn->scn_dp->dp_spa;
2940 uint64_t used = 0, comp, uncomp;
2941
2942 if (spa->spa_load_state != SPA_LOAD_NONE)
2943 return (B_FALSE);
2944 if (spa_shutting_down(spa))
2945 return (B_FALSE);
2946 if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
2947 (scn->scn_async_destroying && !scn->scn_async_stalled))
2948 return (B_TRUE);
2949
2950 if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
2951 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
2952 &used, &comp, &uncomp);
2953 }
2954 return (used != 0);
2955 }
2956
2957 static boolean_t
2958 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
2959 uint64_t phys_birth)
2960 {
2961 vdev_t *vd;
2962
2963 vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
2964
2965 if (vd->vdev_ops == &vdev_indirect_ops) {
2966 /*
2967 * The indirect vdev can point to multiple
2968 * vdevs. For simplicity, always create
2969 * the resilver zio_t. zio_vdev_io_start()
2970 * will bypass the child resilver i/o's if
2971 * they are on vdevs that don't have DTL's.
2972 */
2973 return (B_TRUE);
2974 }
2975
2976 if (DVA_GET_GANG(dva)) {
2977 /*
2978 * Gang members may be spread across multiple
2979 * vdevs, so the best estimate we have is the
2980 * scrub range, which has already been checked.
2981 * XXX -- it would be better to change our
2982 * allocation policy to ensure that all
2983 * gang members reside on the same vdev.
2984 */
2985 return (B_TRUE);
2986 }
2987
2988 /*
2989 * Check if the txg falls within the range which must be
2990 * resilvered. DVAs outside this range can always be skipped.
2991 */
2992 if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
2993 return (B_FALSE);
2994
2995 /*
2996 * Check if the top-level vdev must resilver this offset.
2997 * When the offset does not intersect with a dirty leaf DTL
2998 * then it may be possible to skip the resilver IO. The psize
2999 * is provided instead of asize to simplify the check for RAIDZ.
3000 */
3001 if (!vdev_dtl_need_resilver(vd, DVA_GET_OFFSET(dva), psize))
3002 return (B_FALSE);
3003
3004 return (B_TRUE);
3005 }
3006
3007 /*
3008 * This is the primary entry point for scans that is called from syncing
3009 * context. Scans must happen entirely during syncing context so that we
3010 * cna guarantee that blocks we are currently scanning will not change out
3011 * from under us. While a scan is active, this function controls how quickly
3012 * transaction groups proceed, instead of the normal handling provided by
3013 * txg_sync_thread().
3014 */
3015 void
3016 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
3017 {
3018 int err = 0;
3019 dsl_scan_t *scn = dp->dp_scan;
3020 spa_t *spa = dp->dp_spa;
3021 state_sync_type_t sync_type = SYNC_OPTIONAL;
3022
3023 /*
3024 * Check for scn_restart_txg before checking spa_load_state, so
3025 * that we can restart an old-style scan while the pool is being
3026 * imported (see dsl_scan_init).
3027 */
3028 if (dsl_scan_restarting(scn, tx)) {
3029 pool_scan_func_t func = POOL_SCAN_SCRUB;
3030 dsl_scan_done(scn, B_FALSE, tx);
3031 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3032 func = POOL_SCAN_RESILVER;
3033 zfs_dbgmsg("restarting scan func=%u txg=%llu",
3034 func, (longlong_t)tx->tx_txg);
3035 dsl_scan_setup_sync(&func, tx);
3036 }
3037
3038 /*
3039 * Only process scans in sync pass 1.
3040 */
3041 if (spa_sync_pass(spa) > 1)
3042 return;
3043
3044 /*
3045 * If the spa is shutting down, then stop scanning. This will
3046 * ensure that the scan does not dirty any new data during the
3047 * shutdown phase.
3048 */
3049 if (spa_shutting_down(spa))
3050 return;
3051
3052 /*
3053 * If the scan is inactive due to a stalled async destroy, try again.
3054 */
3055 if (!scn->scn_async_stalled && !dsl_scan_active(scn))
3056 return;
3057
3058 /* reset scan statistics */
3059 scn->scn_visited_this_txg = 0;
3060 scn->scn_holes_this_txg = 0;
3061 scn->scn_lt_min_this_txg = 0;
3062 scn->scn_gt_max_this_txg = 0;
3063 scn->scn_ddt_contained_this_txg = 0;
3064 scn->scn_objsets_visited_this_txg = 0;
3065 scn->scn_avg_seg_size_this_txg = 0;
3066 scn->scn_segs_this_txg = 0;
3067 scn->scn_avg_zio_size_this_txg = 0;
3068 scn->scn_zios_this_txg = 0;
3069 scn->scn_suspending = B_FALSE;
3070 scn->scn_sync_start_time = gethrtime();
3071 spa->spa_scrub_active = B_TRUE;
3072
3073 /*
3074 * First process the async destroys. If we suspend, don't do
3075 * any scrubbing or resilvering. This ensures that there are no
3076 * async destroys while we are scanning, so the scan code doesn't
3077 * have to worry about traversing it. It is also faster to free the
3078 * blocks than to scrub them.
3079 */
3080 if (zfs_free_bpobj_enabled &&
3081 spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3082 scn->scn_is_bptree = B_FALSE;
3083 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
3084 scn->scn_zio_root = zio_root(spa, NULL,
3085 NULL, ZIO_FLAG_MUSTSUCCEED);
3086 err = bpobj_iterate(&dp->dp_free_bpobj,
3087 dsl_scan_free_block_cb, scn, tx);
3088 VERIFY0(zio_wait(scn->scn_zio_root));
3089 scn->scn_zio_root = NULL;
3090
3091 if (err != 0 && err != ERESTART)
3092 zfs_panic_recover("error %u from bpobj_iterate()", err);
3093 }
3094
3095 if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3096 ASSERT(scn->scn_async_destroying);
3097 scn->scn_is_bptree = B_TRUE;
3098 scn->scn_zio_root = zio_root(spa, NULL,
3099 NULL, ZIO_FLAG_MUSTSUCCEED);
3100 err = bptree_iterate(dp->dp_meta_objset,
3101 dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3102 VERIFY0(zio_wait(scn->scn_zio_root));
3103 scn->scn_zio_root = NULL;
3104
3105 if (err == EIO || err == ECKSUM) {
3106 err = 0;
3107 } else if (err != 0 && err != ERESTART) {
3108 zfs_panic_recover("error %u from "
3109 "traverse_dataset_destroyed()", err);
3110 }
3111
3112 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
3113 /* finished; deactivate async destroy feature */
3114 spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
3115 ASSERT(!spa_feature_is_active(spa,
3116 SPA_FEATURE_ASYNC_DESTROY));
3117 VERIFY0(zap_remove(dp->dp_meta_objset,
3118 DMU_POOL_DIRECTORY_OBJECT,
3119 DMU_POOL_BPTREE_OBJ, tx));
3120 VERIFY0(bptree_free(dp->dp_meta_objset,
3121 dp->dp_bptree_obj, tx));
3122 dp->dp_bptree_obj = 0;
3123 scn->scn_async_destroying = B_FALSE;
3124 scn->scn_async_stalled = B_FALSE;
3125 } else {
3126 /*
3127 * If we didn't make progress, mark the async
3128 * destroy as stalled, so that we will not initiate
3129 * a spa_sync() on its behalf. Note that we only
3130 * check this if we are not finished, because if the
3131 * bptree had no blocks for us to visit, we can
3132 * finish without "making progress".
3133 */
3134 scn->scn_async_stalled =
3135 (scn->scn_visited_this_txg == 0);
3136 }
3137 }
3138 if (scn->scn_visited_this_txg) {
3139 zfs_dbgmsg("freed %llu blocks in %llums from "
3140 "free_bpobj/bptree txg %llu; err=%u",
3141 (longlong_t)scn->scn_visited_this_txg,
3142 (longlong_t)
3143 NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
3144 (longlong_t)tx->tx_txg, err);
3145 scn->scn_visited_this_txg = 0;
3146
3147 /*
3148 * Write out changes to the DDT that may be required as a
3149 * result of the blocks freed. This ensures that the DDT
3150 * is clean when a scrub/resilver runs.
3151 */
3152 ddt_sync(spa, tx->tx_txg);
3153 }
3154 if (err != 0)
3155 return;
3156 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3157 zfs_free_leak_on_eio &&
3158 (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
3159 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
3160 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
3161 /*
3162 * We have finished background destroying, but there is still
3163 * some space left in the dp_free_dir. Transfer this leaked
3164 * space to the dp_leak_dir.
3165 */
3166 if (dp->dp_leak_dir == NULL) {
3167 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
3168 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
3169 LEAK_DIR_NAME, tx);
3170 VERIFY0(dsl_pool_open_special_dir(dp,
3171 LEAK_DIR_NAME, &dp->dp_leak_dir));
3172 rrw_exit(&dp->dp_config_rwlock, FTAG);
3173 }
3174 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
3175 dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3176 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3177 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3178 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
3179 -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3180 -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3181 -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3182 }
3183
3184 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying) {
3185 /* finished; verify that space accounting went to zero */
3186 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
3187 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
3188 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
3189 }
3190
3191 EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
3192 0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3193 DMU_POOL_OBSOLETE_BPOBJ));
3194 if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3195 ASSERT(spa_feature_is_active(dp->dp_spa,
3196 SPA_FEATURE_OBSOLETE_COUNTS));
3197
3198 scn->scn_is_bptree = B_FALSE;
3199 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
3200 err = bpobj_iterate(&dp->dp_obsolete_bpobj,
3201 dsl_scan_obsolete_block_cb, scn, tx);
3202 if (err != 0 && err != ERESTART)
3203 zfs_panic_recover("error %u from bpobj_iterate()", err);
3204
3205 if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
3206 dsl_pool_destroy_obsolete_bpobj(dp, tx);
3207 }
3208
3209 if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
3210 return;
3211
3212 /*
3213 * Wait a few txgs after importing to begin scanning so that
3214 * we can get the pool imported quickly.
3215 */
3216 if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)
3217 return;
3218
3219 /*
3220 * It is possible to switch from unsorted to sorted at any time,
3221 * but afterwards the scan will remain sorted unless reloaded from
3222 * a checkpoint after a reboot.
3223 */
3224 if (!zfs_scan_legacy) {
3225 scn->scn_is_sorted = B_TRUE;
3226 if (scn->scn_last_checkpoint == 0)
3227 scn->scn_last_checkpoint = ddi_get_lbolt();
3228 }
3229
3230 /*
3231 * For sorted scans, determine what kind of work we will be doing
3232 * this txg based on our memory limitations and whether or not we
3233 * need to perform a checkpoint.
3234 */
3235 if (scn->scn_is_sorted) {
3236 /*
3237 * If we are over our checkpoint interval, set scn_clearing
3238 * so that we can begin checkpointing immediately. The
3239 * checkpoint allows us to save a consistent bookmark
3240 * representing how much data we have scrubbed so far.
3241 * Otherwise, use the memory limit to determine if we should
3242 * scan for metadata or start issue scrub IOs. We accumulate
3243 * metadata until we hit our hard memory limit at which point
3244 * we issue scrub IOs until we are at our soft memory limit.
3245 */
3246 if (scn->scn_checkpointing ||
3247 ddi_get_lbolt() - scn->scn_last_checkpoint >
3248 SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
3249 if (!scn->scn_checkpointing)
3250 zfs_dbgmsg("begin scan checkpoint");
3251
3252 scn->scn_checkpointing = B_TRUE;
3253 scn->scn_clearing = B_TRUE;
3254 } else {
3255 boolean_t should_clear = dsl_scan_should_clear(scn);
3256 if (should_clear && !scn->scn_clearing) {
3257 zfs_dbgmsg("begin scan clearing");
3258 scn->scn_clearing = B_TRUE;
3259 } else if (!should_clear && scn->scn_clearing) {
3260 zfs_dbgmsg("finish scan clearing");
3261 scn->scn_clearing = B_FALSE;
3262 }
3263 }
3264 } else {
3265 ASSERT0(scn->scn_checkpointing);
3266 ASSERT0(scn->scn_clearing);
3267 }
3268
3269 if (!scn->scn_clearing && scn->scn_done_txg == 0) {
3270 /* Need to scan metadata for more blocks to scrub */
3271 dsl_scan_phys_t *scnp = &scn->scn_phys;
3272 taskqid_t prefetch_tqid;
3273 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
3274 uint64_t nr_leaves = dsl_scan_count_leaves(spa->spa_root_vdev);
3275
3276 /*
3277 * Recalculate the max number of in-flight bytes for pool-wide
3278 * scanning operations (minimum 1MB). Limits for the issuing
3279 * phase are done per top-level vdev and are handled separately.
3280 */
3281 scn->scn_maxinflight_bytes =
3282 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
3283
3284 if (scnp->scn_ddt_bookmark.ddb_class <=
3285 scnp->scn_ddt_class_max) {
3286 ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
3287 zfs_dbgmsg("doing scan sync txg %llu; "
3288 "ddt bm=%llu/%llu/%llu/%llx",
3289 (longlong_t)tx->tx_txg,
3290 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
3291 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
3292 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
3293 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
3294 } else {
3295 zfs_dbgmsg("doing scan sync txg %llu; "
3296 "bm=%llu/%llu/%llu/%llu",
3297 (longlong_t)tx->tx_txg,
3298 (longlong_t)scnp->scn_bookmark.zb_objset,
3299 (longlong_t)scnp->scn_bookmark.zb_object,
3300 (longlong_t)scnp->scn_bookmark.zb_level,
3301 (longlong_t)scnp->scn_bookmark.zb_blkid);
3302 }
3303
3304 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3305 NULL, ZIO_FLAG_CANFAIL);
3306
3307 scn->scn_prefetch_stop = B_FALSE;
3308 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
3309 dsl_scan_prefetch_thread, scn, TQ_SLEEP);
3310 ASSERT(prefetch_tqid != TASKQID_INVALID);
3311
3312 dsl_pool_config_enter(dp, FTAG);
3313 dsl_scan_visit(scn, tx);
3314 dsl_pool_config_exit(dp, FTAG);
3315
3316 mutex_enter(&dp->dp_spa->spa_scrub_lock);
3317 scn->scn_prefetch_stop = B_TRUE;
3318 cv_broadcast(&spa->spa_scrub_io_cv);
3319 mutex_exit(&dp->dp_spa->spa_scrub_lock);
3320
3321 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
3322 (void) zio_wait(scn->scn_zio_root);
3323 scn->scn_zio_root = NULL;
3324
3325 zfs_dbgmsg("scan visited %llu blocks in %llums "
3326 "(%llu os's, %llu holes, %llu < mintxg, "
3327 "%llu in ddt, %llu > maxtxg)",
3328 (longlong_t)scn->scn_visited_this_txg,
3329 (longlong_t)NSEC2MSEC(gethrtime() -
3330 scn->scn_sync_start_time),
3331 (longlong_t)scn->scn_objsets_visited_this_txg,
3332 (longlong_t)scn->scn_holes_this_txg,
3333 (longlong_t)scn->scn_lt_min_this_txg,
3334 (longlong_t)scn->scn_ddt_contained_this_txg,
3335 (longlong_t)scn->scn_gt_max_this_txg);
3336
3337 if (!scn->scn_suspending) {
3338 ASSERT0(avl_numnodes(&scn->scn_queue));
3339 scn->scn_done_txg = tx->tx_txg + 1;
3340 if (scn->scn_is_sorted) {
3341 scn->scn_checkpointing = B_TRUE;
3342 scn->scn_clearing = B_TRUE;
3343 }
3344 zfs_dbgmsg("scan complete txg %llu",
3345 (longlong_t)tx->tx_txg);
3346 }
3347 } else if (scn->scn_is_sorted && scn->scn_bytes_pending != 0) {
3348 /* need to issue scrubbing IOs from per-vdev queues */
3349 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3350 NULL, ZIO_FLAG_CANFAIL);
3351 scan_io_queues_run(scn);
3352 (void) zio_wait(scn->scn_zio_root);
3353 scn->scn_zio_root = NULL;
3354
3355 /* calculate and dprintf the current memory usage */
3356 (void) dsl_scan_should_clear(scn);
3357 dsl_scan_update_stats(scn);
3358
3359 zfs_dbgmsg("scan issued %llu blocks (%llu segs) in %llums "
3360 "(avg_block_size = %llu, avg_seg_size = %llu)",
3361 (longlong_t)scn->scn_zios_this_txg,
3362 (longlong_t)scn->scn_segs_this_txg,
3363 (longlong_t)NSEC2MSEC(gethrtime() -
3364 scn->scn_sync_start_time),
3365 (longlong_t)scn->scn_avg_zio_size_this_txg,
3366 (longlong_t)scn->scn_avg_seg_size_this_txg);
3367 } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
3368 /* Finished with everything. Mark the scrub as complete */
3369 zfs_dbgmsg("scan issuing complete txg %llu",
3370 (longlong_t)tx->tx_txg);
3371 ASSERT3U(scn->scn_done_txg, !=, 0);
3372 ASSERT0(spa->spa_scrub_inflight);
3373 ASSERT0(scn->scn_bytes_pending);
3374 dsl_scan_done(scn, B_TRUE, tx);
3375 sync_type = SYNC_MANDATORY;
3376 }
3377
3378 dsl_scan_sync_state(scn, tx, sync_type);
3379 }
3380
3381 static void
3382 count_block(dsl_scan_t *scn, zfs_all_blkstats_t *zab, const blkptr_t *bp)
3383 {
3384 int i;
3385
3386 /* update the spa's stats on how many bytes we have issued */
3387 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3388 atomic_add_64(&scn->scn_dp->dp_spa->spa_scan_pass_issued,
3389 DVA_GET_ASIZE(&bp->blk_dva[i]));
3390 }
3391
3392 /*
3393 * If we resume after a reboot, zab will be NULL; don't record
3394 * incomplete stats in that case.
3395 */
3396 if (zab == NULL)
3397 return;
3398
3399 mutex_enter(&zab->zab_lock);
3400
3401 for (i = 0; i < 4; i++) {
3402 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
3403 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
3404
3405 if (t & DMU_OT_NEWTYPE)
3406 t = DMU_OT_OTHER;
3407 zfs_blkstat_t *zb = &zab->zab_type[l][t];
3408 int equal;
3409
3410 zb->zb_count++;
3411 zb->zb_asize += BP_GET_ASIZE(bp);
3412 zb->zb_lsize += BP_GET_LSIZE(bp);
3413 zb->zb_psize += BP_GET_PSIZE(bp);
3414 zb->zb_gangs += BP_COUNT_GANG(bp);
3415
3416 switch (BP_GET_NDVAS(bp)) {
3417 case 2:
3418 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3419 DVA_GET_VDEV(&bp->blk_dva[1]))
3420 zb->zb_ditto_2_of_2_samevdev++;
3421 break;
3422 case 3:
3423 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3424 DVA_GET_VDEV(&bp->blk_dva[1])) +
3425 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3426 DVA_GET_VDEV(&bp->blk_dva[2])) +
3427 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3428 DVA_GET_VDEV(&bp->blk_dva[2]));
3429 if (equal == 1)
3430 zb->zb_ditto_2_of_3_samevdev++;
3431 else if (equal == 3)
3432 zb->zb_ditto_3_of_3_samevdev++;
3433 break;
3434 }
3435 }
3436
3437 mutex_exit(&zab->zab_lock);
3438 }
3439
3440 static void
3441 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
3442 {
3443 avl_index_t idx;
3444 int64_t asize = sio->sio_asize;
3445 dsl_scan_t *scn = queue->q_scn;
3446
3447 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3448
3449 if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
3450 /* block is already scheduled for reading */
3451 atomic_add_64(&scn->scn_bytes_pending, -asize);
3452 kmem_cache_free(sio_cache, sio);
3453 return;
3454 }
3455 avl_insert(&queue->q_sios_by_addr, sio, idx);
3456 range_tree_add(queue->q_exts_by_addr, sio->sio_offset, asize);
3457 }
3458
3459 /*
3460 * Given all the info we got from our metadata scanning process, we
3461 * construct a scan_io_t and insert it into the scan sorting queue. The
3462 * I/O must already be suitable for us to process. This is controlled
3463 * by dsl_scan_enqueue().
3464 */
3465 static void
3466 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
3467 int zio_flags, const zbookmark_phys_t *zb)
3468 {
3469 dsl_scan_t *scn = queue->q_scn;
3470 scan_io_t *sio = kmem_cache_alloc(sio_cache, KM_SLEEP);
3471
3472 ASSERT0(BP_IS_GANG(bp));
3473 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3474
3475 bp2sio(bp, sio, dva_i);
3476 sio->sio_flags = zio_flags;
3477 sio->sio_zb = *zb;
3478
3479 /*
3480 * Increment the bytes pending counter now so that we can't
3481 * get an integer underflow in case the worker processes the
3482 * zio before we get to incrementing this counter.
3483 */
3484 atomic_add_64(&scn->scn_bytes_pending, sio->sio_asize);
3485
3486 scan_io_queue_insert_impl(queue, sio);
3487 }
3488
3489 /*
3490 * Given a set of I/O parameters as discovered by the metadata traversal
3491 * process, attempts to place the I/O into the sorted queues (if allowed),
3492 * or immediately executes the I/O.
3493 */
3494 static void
3495 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3496 const zbookmark_phys_t *zb)
3497 {
3498 spa_t *spa = dp->dp_spa;
3499
3500 ASSERT(!BP_IS_EMBEDDED(bp));
3501
3502 /*
3503 * Gang blocks are hard to issue sequentially, so we just issue them
3504 * here immediately instead of queuing them.
3505 */
3506 if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
3507 scan_exec_io(dp, bp, zio_flags, zb, NULL);
3508 return;
3509 }
3510
3511 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
3512 dva_t dva;
3513 vdev_t *vdev;
3514
3515 dva = bp->blk_dva[i];
3516 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
3517 ASSERT(vdev != NULL);
3518
3519 mutex_enter(&vdev->vdev_scan_io_queue_lock);
3520 if (vdev->vdev_scan_io_queue == NULL)
3521 vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
3522 ASSERT(dp->dp_scan != NULL);
3523 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
3524 i, zio_flags, zb);
3525 mutex_exit(&vdev->vdev_scan_io_queue_lock);
3526 }
3527 }
3528
3529 static int
3530 dsl_scan_scrub_cb(dsl_pool_t *dp,
3531 const blkptr_t *bp, const zbookmark_phys_t *zb)
3532 {
3533 dsl_scan_t *scn = dp->dp_scan;
3534 spa_t *spa = dp->dp_spa;
3535 uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
3536 size_t psize = BP_GET_PSIZE(bp);
3537 boolean_t needs_io = B_FALSE;
3538 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
3539
3540 if (phys_birth <= scn->scn_phys.scn_min_txg ||
3541 phys_birth >= scn->scn_phys.scn_max_txg)
3542 return (0);
3543
3544 if (BP_IS_EMBEDDED(bp)) {
3545 count_block(scn, dp->dp_blkstats, bp);
3546 return (0);
3547 }
3548
3549 ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
3550 if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
3551 zio_flags |= ZIO_FLAG_SCRUB;
3552 needs_io = B_TRUE;
3553 } else {
3554 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
3555 zio_flags |= ZIO_FLAG_RESILVER;
3556 needs_io = B_FALSE;
3557 }
3558
3559 /* If it's an intent log block, failure is expected. */
3560 if (zb->zb_level == ZB_ZIL_LEVEL)
3561 zio_flags |= ZIO_FLAG_SPECULATIVE;
3562
3563 for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
3564 const dva_t *dva = &bp->blk_dva[d];
3565
3566 /*
3567 * Keep track of how much data we've examined so that
3568 * zpool(1M) status can make useful progress reports.
3569 */
3570 scn->scn_phys.scn_examined += DVA_GET_ASIZE(dva);
3571 spa->spa_scan_pass_exam += DVA_GET_ASIZE(dva);
3572
3573 /* if it's a resilver, this may not be in the target range */
3574 if (!needs_io)
3575 needs_io = dsl_scan_need_resilver(spa, dva, psize,
3576 phys_birth);
3577 }
3578
3579 if (needs_io && !zfs_no_scrub_io) {
3580 dsl_scan_enqueue(dp, bp, zio_flags, zb);
3581 } else {
3582 count_block(scn, dp->dp_blkstats, bp);
3583 }
3584
3585 /* do not relocate this block */
3586 return (0);
3587 }
3588
3589 static void
3590 dsl_scan_scrub_done(zio_t *zio)
3591 {
3592 spa_t *spa = zio->io_spa;
3593 blkptr_t *bp = zio->io_bp;
3594 dsl_scan_io_queue_t *queue = zio->io_private;
3595
3596 abd_free(zio->io_abd);
3597
3598 if (queue == NULL) {
3599 mutex_enter(&spa->spa_scrub_lock);
3600 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
3601 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
3602 cv_broadcast(&spa->spa_scrub_io_cv);
3603 mutex_exit(&spa->spa_scrub_lock);
3604 } else {
3605 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
3606 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));
3607 queue->q_inflight_bytes -= BP_GET_PSIZE(bp);
3608 cv_broadcast(&queue->q_zio_cv);
3609 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
3610 }
3611
3612 if (zio->io_error && (zio->io_error != ECKSUM ||
3613 !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
3614 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors);
3615 }
3616 }
3617
3618 /*
3619 * Given a scanning zio's information, executes the zio. The zio need
3620 * not necessarily be only sortable, this function simply executes the
3621 * zio, no matter what it is. The optional queue argument allows the
3622 * caller to specify that they want per top level vdev IO rate limiting
3623 * instead of the legacy global limiting.
3624 */
3625 static void
3626 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3627 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
3628 {
3629 spa_t *spa = dp->dp_spa;
3630 dsl_scan_t *scn = dp->dp_scan;
3631 size_t size = BP_GET_PSIZE(bp);
3632 abd_t *data = abd_alloc_for_io(size, B_FALSE);
3633
3634 ASSERT3U(scn->scn_maxinflight_bytes, >, 0);
3635
3636 if (queue == NULL) {
3637 mutex_enter(&spa->spa_scrub_lock);
3638 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
3639 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3640 spa->spa_scrub_inflight += BP_GET_PSIZE(bp);
3641 mutex_exit(&spa->spa_scrub_lock);
3642 } else {
3643 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
3644
3645 mutex_enter(q_lock);
3646 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
3647 cv_wait(&queue->q_zio_cv, q_lock);
3648 queue->q_inflight_bytes += BP_GET_PSIZE(bp);
3649 mutex_exit(q_lock);
3650 }
3651
3652 count_block(scn, dp->dp_blkstats, bp);
3653 zio_nowait(zio_read(scn->scn_zio_root, spa, bp, data, size,
3654 dsl_scan_scrub_done, queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
3655 }
3656
3657 /*
3658 * This is the primary extent sorting algorithm. We balance two parameters:
3659 * 1) how many bytes of I/O are in an extent
3660 * 2) how well the extent is filled with I/O (as a fraction of its total size)
3661 * Since we allow extents to have gaps between their constituent I/Os, it's
3662 * possible to have a fairly large extent that contains the same amount of
3663 * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
3664 * The algorithm sorts based on a score calculated from the extent's size,
3665 * the relative fill volume (in %) and a "fill weight" parameter that controls
3666 * the split between whether we prefer larger extents or more well populated
3667 * extents:
3668 *
3669 * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
3670 *
3671 * Example:
3672 * 1) assume extsz = 64 MiB
3673 * 2) assume fill = 32 MiB (extent is half full)
3674 * 3) assume fill_weight = 3
3675 * 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
3676 * SCORE = 32M + (50 * 3 * 32M) / 100
3677 * SCORE = 32M + (4800M / 100)
3678 * SCORE = 32M + 48M
3679 * ^ ^
3680 * | +--- final total relative fill-based score
3681 * +--------- final total fill-based score
3682 * SCORE = 80M
3683 *
3684 * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
3685 * extents that are more completely filled (in a 3:2 ratio) vs just larger.
3686 * Note that as an optimization, we replace multiplication and division by
3687 * 100 with bitshifting by 7 (which effecitvely multiplies and divides by 128).
3688 */
3689 static int
3690 ext_size_compare(const void *x, const void *y)
3691 {
3692 const range_seg_t *rsa = x, *rsb = y;
3693 uint64_t sa = rsa->rs_end - rsa->rs_start,
3694 sb = rsb->rs_end - rsb->rs_start;
3695 uint64_t score_a, score_b;
3696
3697 score_a = rsa->rs_fill + ((((rsa->rs_fill << 7) / sa) *
3698 fill_weight * rsa->rs_fill) >> 7);
3699 score_b = rsb->rs_fill + ((((rsb->rs_fill << 7) / sb) *
3700 fill_weight * rsb->rs_fill) >> 7);
3701
3702 if (score_a > score_b)
3703 return (-1);
3704 if (score_a == score_b) {
3705 if (rsa->rs_start < rsb->rs_start)
3706 return (-1);
3707 if (rsa->rs_start == rsb->rs_start)
3708 return (0);
3709 return (1);
3710 }
3711 return (1);
3712 }
3713
3714 /*
3715 * Comparator for the q_sios_by_addr tree. Sorting is simply performed
3716 * based on LBA-order (from lowest to highest).
3717 */
3718 static int
3719 sio_addr_compare(const void *x, const void *y)
3720 {
3721 const scan_io_t *a = x, *b = y;
3722
3723 if (a->sio_offset < b->sio_offset)
3724 return (-1);
3725 if (a->sio_offset == b->sio_offset)
3726 return (0);
3727 return (1);
3728 }
3729
3730 /* IO queues are created on demand when they are needed. */
3731 static dsl_scan_io_queue_t *
3732 scan_io_queue_create(vdev_t *vd)
3733 {
3734 dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
3735 dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
3736
3737 q->q_scn = scn;
3738 q->q_vd = vd;
3739 cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
3740 q->q_exts_by_addr = range_tree_create_impl(&rt_avl_ops,
3741 &q->q_exts_by_size, ext_size_compare, zfs_scan_max_ext_gap);
3742 avl_create(&q->q_sios_by_addr, sio_addr_compare,
3743 sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));
3744
3745 return (q);
3746 }
3747
3748 /*
3749 * Destroys a scan queue and all segments and scan_io_t's contained in it.
3750 * No further execution of I/O occurs, anything pending in the queue is
3751 * simply freed without being executed.
3752 */
3753 void
3754 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
3755 {
3756 dsl_scan_t *scn = queue->q_scn;
3757 scan_io_t *sio;
3758 void *cookie = NULL;
3759 int64_t bytes_dequeued = 0;
3760
3761 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3762
3763 while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
3764 NULL) {
3765 ASSERT(range_tree_contains(queue->q_exts_by_addr,
3766 sio->sio_offset, sio->sio_asize));
3767 bytes_dequeued += sio->sio_asize;
3768 kmem_cache_free(sio_cache, sio);
3769 }
3770
3771 atomic_add_64(&scn->scn_bytes_pending, -bytes_dequeued);
3772 range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
3773 range_tree_destroy(queue->q_exts_by_addr);
3774 avl_destroy(&queue->q_sios_by_addr);
3775 cv_destroy(&queue->q_zio_cv);
3776
3777 kmem_free(queue, sizeof (*queue));
3778 }
3779
3780 /*
3781 * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
3782 * called on behalf of vdev_top_transfer when creating or destroying
3783 * a mirror vdev due to zpool attach/detach.
3784 */
3785 void
3786 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
3787 {
3788 mutex_enter(&svd->vdev_scan_io_queue_lock);
3789 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3790
3791 VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL);
3792 tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
3793 svd->vdev_scan_io_queue = NULL;
3794 if (tvd->vdev_scan_io_queue != NULL)
3795 tvd->vdev_scan_io_queue->q_vd = tvd;
3796
3797 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3798 mutex_exit(&svd->vdev_scan_io_queue_lock);
3799 }
3800
3801 static void
3802 scan_io_queues_destroy(dsl_scan_t *scn)
3803 {
3804 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
3805
3806 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3807 vdev_t *tvd = rvd->vdev_child[i];
3808
3809 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3810 if (tvd->vdev_scan_io_queue != NULL)
3811 dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
3812 tvd->vdev_scan_io_queue = NULL;
3813 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3814 }
3815 }
3816
3817 static void
3818 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
3819 {
3820 dsl_pool_t *dp = spa->spa_dsl_pool;
3821 dsl_scan_t *scn = dp->dp_scan;
3822 vdev_t *vdev;
3823 kmutex_t *q_lock;
3824 dsl_scan_io_queue_t *queue;
3825 scan_io_t srch, *sio;
3826 avl_index_t idx;
3827 uint64_t start, size;
3828
3829 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
3830 ASSERT(vdev != NULL);
3831 q_lock = &vdev->vdev_scan_io_queue_lock;
3832 queue = vdev->vdev_scan_io_queue;
3833
3834 mutex_enter(q_lock);
3835 if (queue == NULL) {
3836 mutex_exit(q_lock);
3837 return;
3838 }
3839
3840 bp2sio(bp, &srch, dva_i);
3841 start = srch.sio_offset;
3842 size = srch.sio_asize;
3843
3844 /*
3845 * We can find the zio in two states:
3846 * 1) Cold, just sitting in the queue of zio's to be issued at
3847 * some point in the future. In this case, all we do is
3848 * remove the zio from the q_sios_by_addr tree, decrement
3849 * its data volume from the containing range_seg_t and
3850 * resort the q_exts_by_size tree to reflect that the
3851 * range_seg_t has lost some of its 'fill'. We don't shorten
3852 * the range_seg_t - this is usually rare enough not to be
3853 * worth the extra hassle of trying keep track of precise
3854 * extent boundaries.
3855 * 2) Hot, where the zio is currently in-flight in
3856 * dsl_scan_issue_ios. In this case, we can't simply
3857 * reach in and stop the in-flight zio's, so we instead
3858 * block the caller. Eventually, dsl_scan_issue_ios will
3859 * be done with issuing the zio's it gathered and will
3860 * signal us.
3861 */
3862 sio = avl_find(&queue->q_sios_by_addr, &srch, &idx);
3863 if (sio != NULL) {
3864 int64_t asize = sio->sio_asize;
3865 blkptr_t tmpbp;
3866
3867 /* Got it while it was cold in the queue */
3868 ASSERT3U(start, ==, sio->sio_offset);
3869 ASSERT3U(size, ==, asize);
3870 avl_remove(&queue->q_sios_by_addr, sio);
3871
3872 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size));
3873 range_tree_remove_fill(queue->q_exts_by_addr, start, size);
3874
3875 /*
3876 * We only update scn_bytes_pending in the cold path,
3877 * otherwise it will already have been accounted for as
3878 * part of the zio's execution.
3879 */
3880 atomic_add_64(&scn->scn_bytes_pending, -asize);
3881
3882 /* count the block as though we issued it */
3883 sio2bp(sio, &tmpbp, dva_i);
3884 count_block(scn, dp->dp_blkstats, &tmpbp);
3885
3886 kmem_cache_free(sio_cache, sio);
3887 }
3888 mutex_exit(q_lock);
3889 }
3890
3891 /*
3892 * Callback invoked when a zio_free() zio is executing. This needs to be
3893 * intercepted to prevent the zio from deallocating a particular portion
3894 * of disk space and it then getting reallocated and written to, while we
3895 * still have it queued up for processing.
3896 */
3897 void
3898 dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
3899 {
3900 dsl_pool_t *dp = spa->spa_dsl_pool;
3901 dsl_scan_t *scn = dp->dp_scan;
3902
3903 ASSERT(!BP_IS_EMBEDDED(bp));
3904 ASSERT(scn != NULL);
3905 if (!dsl_scan_is_running(scn))
3906 return;
3907
3908 for (int i = 0; i < BP_GET_NDVAS(bp); i++)
3909 dsl_scan_freed_dva(spa, bp, i);
3910 }
3911
3912 #if defined(_KERNEL)
3913 /* CSTYLED */
3914 module_param(zfs_scan_vdev_limit, ulong, 0644);
3915 MODULE_PARM_DESC(zfs_scan_vdev_limit,
3916 "Max bytes in flight per leaf vdev for scrubs and resilvers");
3917
3918 module_param(zfs_scrub_min_time_ms, int, 0644);
3919 MODULE_PARM_DESC(zfs_scrub_min_time_ms, "Min millisecs to scrub per txg");
3920
3921 module_param(zfs_obsolete_min_time_ms, int, 0644);
3922 MODULE_PARM_DESC(zfs_obsolete_min_time_ms, "Min millisecs to obsolete per txg");
3923
3924 module_param(zfs_free_min_time_ms, int, 0644);
3925 MODULE_PARM_DESC(zfs_free_min_time_ms, "Min millisecs to free per txg");
3926
3927 module_param(zfs_resilver_min_time_ms, int, 0644);
3928 MODULE_PARM_DESC(zfs_resilver_min_time_ms, "Min millisecs to resilver per txg");
3929
3930 module_param(zfs_no_scrub_io, int, 0644);
3931 MODULE_PARM_DESC(zfs_no_scrub_io, "Set to disable scrub I/O");
3932
3933 module_param(zfs_no_scrub_prefetch, int, 0644);
3934 MODULE_PARM_DESC(zfs_no_scrub_prefetch, "Set to disable scrub prefetching");
3935
3936 /* CSTYLED */
3937 module_param(zfs_async_block_max_blocks, ulong, 0644);
3938 MODULE_PARM_DESC(zfs_async_block_max_blocks,
3939 "Max number of blocks freed in one txg");
3940
3941 module_param(zfs_free_bpobj_enabled, int, 0644);
3942 MODULE_PARM_DESC(zfs_free_bpobj_enabled, "Enable processing of the free_bpobj");
3943
3944 module_param(zfs_scan_mem_lim_fact, int, 0644);
3945 MODULE_PARM_DESC(zfs_scan_mem_lim_fact, "Fraction of RAM for scan hard limit");
3946
3947 module_param(zfs_scan_issue_strategy, int, 0644);
3948 MODULE_PARM_DESC(zfs_scan_issue_strategy,
3949 "IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");
3950
3951 module_param(zfs_scan_legacy, int, 0644);
3952 MODULE_PARM_DESC(zfs_scan_legacy, "Scrub using legacy non-sequential method");
3953
3954 module_param(zfs_scan_checkpoint_intval, int, 0644);
3955 MODULE_PARM_DESC(zfs_scan_checkpoint_intval,
3956 "Scan progress on-disk checkpointing interval");
3957
3958 /* CSTYLED */
3959 module_param(zfs_scan_max_ext_gap, ulong, 0644);
3960 MODULE_PARM_DESC(zfs_scan_max_ext_gap,
3961 "Max gap in bytes between sequential scrub / resilver I/Os");
3962
3963 module_param(zfs_scan_mem_lim_soft_fact, int, 0644);
3964 MODULE_PARM_DESC(zfs_scan_mem_lim_soft_fact,
3965 "Fraction of hard limit used as soft limit");
3966
3967 module_param(zfs_scan_strict_mem_lim, int, 0644);
3968 MODULE_PARM_DESC(zfs_scan_strict_mem_lim,
3969 "Tunable to attempt to reduce lock contention");
3970
3971 module_param(zfs_scan_fill_weight, int, 0644);
3972 MODULE_PARM_DESC(zfs_scan_fill_weight,
3973 "Tunable to adjust bias towards more filled segments during scans");
3974 #endif