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