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.
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.
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]
22 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
24 * Copyright 2016 Gary Mills
25 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
26 * Copyright 2017 Joyent, Inc.
27 * Copyright (c) 2017 Datto Inc.
30 #include <sys/dsl_scan.h>
31 #include <sys/dsl_pool.h>
32 #include <sys/dsl_dataset.h>
33 #include <sys/dsl_prop.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dsl_synctask.h>
36 #include <sys/dnode.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/dmu_objset.h>
42 #include <sys/zfs_context.h>
43 #include <sys/fs/zfs.h>
44 #include <sys/zfs_znode.h>
45 #include <sys/spa_impl.h>
46 #include <sys/vdev_impl.h>
47 #include <sys/zil_impl.h>
48 #include <sys/zio_checksum.h>
51 #include <sys/sa_impl.h>
52 #include <sys/zfeature.h>
54 #include <sys/range_tree.h>
56 #include <sys/zfs_vfsops.h>
60 * Grand theory statement on scan queue sorting
62 * Scanning is implemented by recursively traversing all indirection levels
63 * in an object and reading all blocks referenced from said objects. This
64 * results in us approximately traversing the object from lowest logical
65 * offset to the highest. For best performance, we would want the logical
66 * blocks to be physically contiguous. However, this is frequently not the
67 * case with pools given the allocation patterns of copy-on-write filesystems.
68 * So instead, we put the I/Os into a reordering queue and issue them in a
69 * way that will most benefit physical disks (LBA-order).
73 * Ideally, we would want to scan all metadata and queue up all block I/O
74 * prior to starting to issue it, because that allows us to do an optimal
75 * sorting job. This can however consume large amounts of memory. Therefore
76 * we continuously monitor the size of the queues and constrain them to 5%
77 * (zfs_scan_mem_lim_fact) of physmem. If the queues grow larger than this
78 * limit, we clear out a few of the largest extents at the head of the queues
79 * to make room for more scanning. Hopefully, these extents will be fairly
80 * large and contiguous, allowing us to approach sequential I/O throughput
81 * even without a fully sorted tree.
83 * Metadata scanning takes place in dsl_scan_visit(), which is called from
84 * dsl_scan_sync() every spa_sync(). If we have either fully scanned all
85 * metadata on the pool, or we need to make room in memory because our
86 * queues are too large, dsl_scan_visit() is postponed and
87 * scan_io_queues_run() is called from dsl_scan_sync() instead. This implies
88 * that metadata scanning and queued I/O issuing are mutually exclusive. This
89 * allows us to provide maximum sequential I/O throughput for the majority of
90 * I/O's issued since sequential I/O performance is significantly negatively
91 * impacted if it is interleaved with random I/O.
93 * Implementation Notes
95 * One side effect of the queued scanning algorithm is that the scanning code
96 * needs to be notified whenever a block is freed. This is needed to allow
97 * the scanning code to remove these I/Os from the issuing queue. Additionally,
98 * we do not attempt to queue gang blocks to be issued sequentially since this
99 * is very hard to do and would have an extremely limitted performance benefit.
100 * Instead, we simply issue gang I/Os as soon as we find them using the legacy
103 * Backwards compatibility
105 * This new algorithm is backwards compatible with the legacy on-disk data
106 * structures (and therefore does not require a new feature flag).
107 * Periodically during scanning (see zfs_scan_checkpoint_intval), the scan
108 * will stop scanning metadata (in logical order) and wait for all outstanding
109 * sorted I/O to complete. Once this is done, we write out a checkpoint
110 * bookmark, indicating that we have scanned everything logically before it.
111 * If the pool is imported on a machine without the new sorting algorithm,
112 * the scan simply resumes from the last checkpoint using the legacy algorithm.
115 typedef int (scan_cb_t)(dsl_pool_t *, const blkptr_t *,
116 const zbookmark_phys_t *);
118 static scan_cb_t dsl_scan_scrub_cb;
120 static int scan_ds_queue_compare(const void *a, const void *b);
121 static int scan_prefetch_queue_compare(const void *a, const void *b);
122 static void scan_ds_queue_clear(dsl_scan_t *scn);
123 static boolean_t scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj,
125 static void scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg);
126 static void scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj);
127 static void scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx);
129 extern int zfs_vdev_async_write_active_min_dirty_percent;
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
137 int zfs_scan_strict_mem_lim = B_FALSE;
140 * Maximum number of parallelly executing I/Os per top-level vdev.
141 * Tune with care. Very high settings (hundreds) are known to trigger
142 * some firmware bugs and resets on certain SSDs.
144 int zfs_top_maxinflight = 32; /* maximum I/Os per top-level */
145 unsigned int zfs_resilver_delay = 2; /* number of ticks to delay resilver -- 2 is a good number */
146 unsigned int zfs_scrub_delay = 4; /* number of ticks to delay scrub -- 4 is a good number */
147 unsigned int zfs_scan_idle = 50; /* idle window in clock ticks */
150 * Maximum number of parallelly executed bytes per leaf vdev. We attempt
151 * to strike a balance here between keeping the vdev queues full of I/Os
152 * at all times and not overflowing the queues to cause long latency,
153 * which would cause long txg sync times. No matter what, we will not
154 * overload the drives with I/O, since that is protected by
155 * zfs_vdev_scrub_max_active.
157 unsigned long zfs_scan_vdev_limit = 4 << 20;
159 int zfs_scan_issue_strategy = 0;
160 int zfs_scan_legacy = B_FALSE; /* don't queue & sort zios, go direct */
161 uint64_t zfs_scan_max_ext_gap = 2 << 20; /* in bytes */
163 unsigned int zfs_scan_checkpoint_intval = 7200; /* seconds */
164 #define ZFS_SCAN_CHECKPOINT_INTVAL SEC_TO_TICK(zfs_scan_checkpoint_intval)
167 * fill_weight is non-tunable at runtime, so we copy it at module init from
168 * zfs_scan_fill_weight. Runtime adjustments to zfs_scan_fill_weight would
169 * break queue sorting.
171 uint64_t zfs_scan_fill_weight = 3;
172 static uint64_t fill_weight;
174 /* See dsl_scan_should_clear() for details on the memory limit tunables */
175 uint64_t zfs_scan_mem_lim_min = 16 << 20; /* bytes */
176 uint64_t zfs_scan_mem_lim_soft_max = 128 << 20; /* bytes */
177 int zfs_scan_mem_lim_fact = 20; /* fraction of physmem */
178 int zfs_scan_mem_lim_soft_fact = 20; /* fraction of mem lim above */
180 unsigned int zfs_scrub_min_time_ms = 1000; /* min millisecs to scrub per txg */
181 unsigned int zfs_free_min_time_ms = 1000; /* min millisecs to free per txg */
182 unsigned int zfs_obsolete_min_time_ms = 500; /* min millisecs to obsolete per txg */
183 unsigned int zfs_resilver_min_time_ms = 3000; /* min millisecs to resilver per txg */
184 boolean_t zfs_no_scrub_io = B_FALSE; /* set to disable scrub i/o */
185 boolean_t zfs_no_scrub_prefetch = B_FALSE; /* set to disable scrub prefetch */
187 SYSCTL_DECL(_vfs_zfs);
188 SYSCTL_UINT(_vfs_zfs, OID_AUTO, top_maxinflight, CTLFLAG_RWTUN,
189 &zfs_top_maxinflight, 0, "Maximum I/Os per top-level vdev");
190 SYSCTL_UINT(_vfs_zfs, OID_AUTO, resilver_delay, CTLFLAG_RWTUN,
191 &zfs_resilver_delay, 0, "Number of ticks to delay resilver");
192 SYSCTL_UINT(_vfs_zfs, OID_AUTO, scrub_delay, CTLFLAG_RWTUN,
193 &zfs_scrub_delay, 0, "Number of ticks to delay scrub");
194 SYSCTL_UINT(_vfs_zfs, OID_AUTO, scan_idle, CTLFLAG_RWTUN,
195 &zfs_scan_idle, 0, "Idle scan window in clock ticks");
196 SYSCTL_UINT(_vfs_zfs, OID_AUTO, scan_min_time_ms, CTLFLAG_RWTUN,
197 &zfs_scrub_min_time_ms, 0, "Min millisecs to scrub per txg");
198 SYSCTL_UINT(_vfs_zfs, OID_AUTO, free_min_time_ms, CTLFLAG_RWTUN,
199 &zfs_free_min_time_ms, 0, "Min millisecs to free per txg");
200 SYSCTL_UINT(_vfs_zfs, OID_AUTO, resilver_min_time_ms, CTLFLAG_RWTUN,
201 &zfs_resilver_min_time_ms, 0, "Min millisecs to resilver per txg");
202 SYSCTL_INT(_vfs_zfs, OID_AUTO, no_scrub_io, CTLFLAG_RWTUN,
203 &zfs_no_scrub_io, 0, "Disable scrub I/O");
204 SYSCTL_INT(_vfs_zfs, OID_AUTO, no_scrub_prefetch, CTLFLAG_RWTUN,
205 &zfs_no_scrub_prefetch, 0, "Disable scrub prefetching");
206 SYSCTL_UINT(_vfs_zfs, OID_AUTO, zfs_scan_legacy, CTLFLAG_RWTUN,
207 &zfs_scan_legacy, 0, "Scrub using legacy non-sequential method");
208 SYSCTL_UINT(_vfs_zfs, OID_AUTO, zfs_scan_checkpoint_interval, CTLFLAG_RWTUN,
209 &zfs_scan_checkpoint_intval, 0, "Scan progress on-disk checkpointing interval");
211 enum ddt_class zfs_scrub_ddt_class_max = DDT_CLASS_DUPLICATE;
212 /* max number of blocks to free in a single TXG */
213 uint64_t zfs_async_block_max_blocks = UINT64_MAX;
214 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, free_max_blocks, CTLFLAG_RWTUN,
215 &zfs_async_block_max_blocks, 0, "Maximum number of blocks to free in one TXG");
218 * We wait a few txgs after importing a pool to begin scanning so that
219 * the import / mounting code isn't held up by scrub / resilver IO.
220 * Unfortunately, it is a bit difficult to determine exactly how long
221 * this will take since userspace will trigger fs mounts asynchronously
222 * and the kernel will create zvol minors asynchronously. As a result,
223 * the value provided here is a bit arbitrary, but represents a
224 * reasonable estimate of how many txgs it will take to finish fully
227 #define SCAN_IMPORT_WAIT_TXGS 5
230 #define DSL_SCAN_IS_SCRUB_RESILVER(scn) \
231 ((scn)->scn_phys.scn_func == POOL_SCAN_SCRUB || \
232 (scn)->scn_phys.scn_func == POOL_SCAN_RESILVER)
234 extern int zfs_txg_timeout;
237 * Enable/disable the processing of the free_bpobj object.
239 boolean_t zfs_free_bpobj_enabled = B_TRUE;
241 SYSCTL_INT(_vfs_zfs, OID_AUTO, free_bpobj_enabled, CTLFLAG_RWTUN,
242 &zfs_free_bpobj_enabled, 0, "Enable free_bpobj processing");
244 /* the order has to match pool_scan_type */
245 static scan_cb_t *scan_funcs[POOL_SCAN_FUNCS] = {
247 dsl_scan_scrub_cb, /* POOL_SCAN_SCRUB */
248 dsl_scan_scrub_cb, /* POOL_SCAN_RESILVER */
251 /* In core node for the scn->scn_queue. Represents a dataset to be scanned */
259 * This controls what conditions are placed on dsl_scan_sync_state():
260 * SYNC_OPTIONAL) write out scn_phys iff scn_bytes_pending == 0
261 * SYNC_MANDATORY) write out scn_phys always. scn_bytes_pending must be 0.
262 * SYNC_CACHED) if scn_bytes_pending == 0, write out scn_phys. Otherwise
263 * write out the scn_phys_cached version.
264 * See dsl_scan_sync_state for details.
273 * This struct represents the minimum information needed to reconstruct a
274 * zio for sequential scanning. This is useful because many of these will
275 * accumulate in the sequential IO queues before being issued, so saving
276 * memory matters here.
278 typedef struct scan_io {
279 /* fields from blkptr_t */
281 uint64_t sio_blk_prop;
282 uint64_t sio_phys_birth;
284 zio_cksum_t sio_cksum;
287 /* fields from zio_t */
289 zbookmark_phys_t sio_zb;
291 /* members for queue sorting */
293 avl_node_t sio_addr_node; /* link into issueing queue */
294 list_node_t sio_list_node; /* link for issuing to disk */
298 struct dsl_scan_io_queue {
299 dsl_scan_t *q_scn; /* associated dsl_scan_t */
300 vdev_t *q_vd; /* top-level vdev that this queue represents */
302 /* trees used for sorting I/Os and extents of I/Os */
303 range_tree_t *q_exts_by_addr;
304 avl_tree_t q_exts_by_size;
305 avl_tree_t q_sios_by_addr;
307 /* members for zio rate limiting */
308 uint64_t q_maxinflight_bytes;
309 uint64_t q_inflight_bytes;
310 kcondvar_t q_zio_cv; /* used under vd->vdev_scan_io_queue_lock */
312 /* per txg statistics */
313 uint64_t q_total_seg_size_this_txg;
314 uint64_t q_segs_this_txg;
315 uint64_t q_total_zio_size_this_txg;
316 uint64_t q_zios_this_txg;
319 /* private data for dsl_scan_prefetch_cb() */
320 typedef struct scan_prefetch_ctx {
321 zfs_refcount_t spc_refcnt; /* refcount for memory management */
322 dsl_scan_t *spc_scn; /* dsl_scan_t for the pool */
323 boolean_t spc_root; /* is this prefetch for an objset? */
324 uint8_t spc_indblkshift; /* dn_indblkshift of current dnode */
325 uint16_t spc_datablkszsec; /* dn_idatablkszsec of current dnode */
326 } scan_prefetch_ctx_t;
328 /* private data for dsl_scan_prefetch() */
329 typedef struct scan_prefetch_issue_ctx {
330 avl_node_t spic_avl_node; /* link into scn->scn_prefetch_queue */
331 scan_prefetch_ctx_t *spic_spc; /* spc for the callback */
332 blkptr_t spic_bp; /* bp to prefetch */
333 zbookmark_phys_t spic_zb; /* bookmark to prefetch */
334 } scan_prefetch_issue_ctx_t;
336 static void scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
337 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue);
338 static void scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue,
341 static dsl_scan_io_queue_t *scan_io_queue_create(vdev_t *vd);
342 static void scan_io_queues_destroy(dsl_scan_t *scn);
344 static kmem_cache_t *sio_cache;
350 * This is used in ext_size_compare() to weight segments
351 * based on how sparse they are. This cannot be changed
352 * mid-scan and the tree comparison functions don't currently
353 * have a mechansim for passing additional context to the
354 * compare functions. Thus we store this value globally and
355 * we only allow it to be set at module intiailization time
357 fill_weight = zfs_scan_fill_weight;
359 sio_cache = kmem_cache_create("sio_cache",
360 sizeof (scan_io_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
366 kmem_cache_destroy(sio_cache);
369 static inline boolean_t
370 dsl_scan_is_running(const dsl_scan_t *scn)
372 return (scn->scn_phys.scn_state == DSS_SCANNING);
376 dsl_scan_resilvering(dsl_pool_t *dp)
378 return (dsl_scan_is_running(dp->dp_scan) &&
379 dp->dp_scan->scn_phys.scn_func == POOL_SCAN_RESILVER);
383 sio2bp(const scan_io_t *sio, blkptr_t *bp, uint64_t vdev_id)
385 bzero(bp, sizeof (*bp));
386 DVA_SET_ASIZE(&bp->blk_dva[0], sio->sio_asize);
387 DVA_SET_VDEV(&bp->blk_dva[0], vdev_id);
388 DVA_SET_OFFSET(&bp->blk_dva[0], sio->sio_offset);
389 bp->blk_prop = sio->sio_blk_prop;
390 bp->blk_phys_birth = sio->sio_phys_birth;
391 bp->blk_birth = sio->sio_birth;
392 bp->blk_fill = 1; /* we always only work with data pointers */
393 bp->blk_cksum = sio->sio_cksum;
397 bp2sio(const blkptr_t *bp, scan_io_t *sio, int dva_i)
399 /* we discard the vdev id, since we can deduce it from the queue */
400 sio->sio_offset = DVA_GET_OFFSET(&bp->blk_dva[dva_i]);
401 sio->sio_asize = DVA_GET_ASIZE(&bp->blk_dva[dva_i]);
402 sio->sio_blk_prop = bp->blk_prop;
403 sio->sio_phys_birth = bp->blk_phys_birth;
404 sio->sio_birth = bp->blk_birth;
405 sio->sio_cksum = bp->blk_cksum;
409 dsl_scan_global_init(void)
412 * This is used in ext_size_compare() to weight segments
413 * based on how sparse they are. This cannot be changed
414 * mid-scan and the tree comparison functions don't currently
415 * have a mechansim for passing additional context to the
416 * compare functions. Thus we store this value globally and
417 * we only allow it to be set at module intiailization time
419 fill_weight = zfs_scan_fill_weight;
423 dsl_scan_init(dsl_pool_t *dp, uint64_t txg)
427 spa_t *spa = dp->dp_spa;
430 scn = dp->dp_scan = kmem_zalloc(sizeof (dsl_scan_t), KM_SLEEP);
434 * It's possible that we're resuming a scan after a reboot so
435 * make sure that the scan_async_destroying flag is initialized
438 ASSERT(!scn->scn_async_destroying);
439 scn->scn_async_destroying = spa_feature_is_active(dp->dp_spa,
440 SPA_FEATURE_ASYNC_DESTROY);
442 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
443 avl_create(&scn->scn_queue, scan_ds_queue_compare, sizeof (scan_ds_t),
444 offsetof(scan_ds_t, sds_node));
445 avl_create(&scn->scn_prefetch_queue, scan_prefetch_queue_compare,
446 sizeof (scan_prefetch_issue_ctx_t),
447 offsetof(scan_prefetch_issue_ctx_t, spic_avl_node));
449 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
450 "scrub_func", sizeof (uint64_t), 1, &f);
453 * There was an old-style scrub in progress. Restart a
454 * new-style scrub from the beginning.
456 scn->scn_restart_txg = txg;
457 zfs_dbgmsg("old-style scrub was in progress; "
458 "restarting new-style scrub in txg %llu",
459 (longlong_t)scn->scn_restart_txg);
462 * Load the queue obj from the old location so that it
463 * can be freed by dsl_scan_done().
465 (void) zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
466 "scrub_queue", sizeof (uint64_t), 1,
467 &scn->scn_phys.scn_queue_obj);
469 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
470 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
478 * We might be restarting after a reboot, so jump the issued
479 * counter to how far we've scanned. We know we're consistent
482 scn->scn_issued_before_pass = scn->scn_phys.scn_examined;
484 if (dsl_scan_is_running(scn) &&
485 spa_prev_software_version(dp->dp_spa) < SPA_VERSION_SCAN) {
487 * A new-type scrub was in progress on an old
488 * pool, and the pool was accessed by old
489 * software. Restart from the beginning, since
490 * the old software may have changed the pool in
493 scn->scn_restart_txg = txg;
494 zfs_dbgmsg("new-style scrub was modified "
495 "by old software; restarting in txg %llu",
496 (longlong_t)scn->scn_restart_txg);
500 /* reload the queue into the in-core state */
501 if (scn->scn_phys.scn_queue_obj != 0) {
505 for (zap_cursor_init(&zc, dp->dp_meta_objset,
506 scn->scn_phys.scn_queue_obj);
507 zap_cursor_retrieve(&zc, &za) == 0;
508 (void) zap_cursor_advance(&zc)) {
509 scan_ds_queue_insert(scn,
510 zfs_strtonum(za.za_name, NULL),
511 za.za_first_integer);
513 zap_cursor_fini(&zc);
516 spa_scan_stat_init(spa);
521 dsl_scan_fini(dsl_pool_t *dp)
523 if (dp->dp_scan != NULL) {
524 dsl_scan_t *scn = dp->dp_scan;
526 if (scn->scn_taskq != NULL)
527 taskq_destroy(scn->scn_taskq);
528 scan_ds_queue_clear(scn);
529 avl_destroy(&scn->scn_queue);
530 avl_destroy(&scn->scn_prefetch_queue);
532 kmem_free(dp->dp_scan, sizeof (dsl_scan_t));
538 dsl_scan_restarting(dsl_scan_t *scn, dmu_tx_t *tx)
540 return (scn->scn_restart_txg != 0 &&
541 scn->scn_restart_txg <= tx->tx_txg);
545 dsl_scan_scrubbing(const dsl_pool_t *dp)
547 dsl_scan_phys_t *scn_phys = &dp->dp_scan->scn_phys;
549 return (scn_phys->scn_state == DSS_SCANNING &&
550 scn_phys->scn_func == POOL_SCAN_SCRUB);
554 dsl_scan_is_paused_scrub(const dsl_scan_t *scn)
556 return (dsl_scan_scrubbing(scn->scn_dp) &&
557 scn->scn_phys.scn_flags & DSF_SCRUB_PAUSED);
561 * Writes out a persistent dsl_scan_phys_t record to the pool directory.
562 * Because we can be running in the block sorting algorithm, we do not always
563 * want to write out the record, only when it is "safe" to do so. This safety
564 * condition is achieved by making sure that the sorting queues are empty
565 * (scn_bytes_pending == 0). When this condition is not true, the sync'd state
566 * is inconsistent with how much actual scanning progress has been made. The
567 * kind of sync to be performed is specified by the sync_type argument. If the
568 * sync is optional, we only sync if the queues are empty. If the sync is
569 * mandatory, we do a hard ASSERT to make sure that the queues are empty. The
570 * third possible state is a "cached" sync. This is done in response to:
571 * 1) The dataset that was in the last sync'd dsl_scan_phys_t having been
572 * destroyed, so we wouldn't be able to restart scanning from it.
573 * 2) The snapshot that was in the last sync'd dsl_scan_phys_t having been
574 * superseded by a newer snapshot.
575 * 3) The dataset that was in the last sync'd dsl_scan_phys_t having been
576 * swapped with its clone.
577 * In all cases, a cached sync simply rewrites the last record we've written,
578 * just slightly modified. For the modifications that are performed to the
579 * last written dsl_scan_phys_t, see dsl_scan_ds_destroyed,
580 * dsl_scan_ds_snapshotted and dsl_scan_ds_clone_swapped.
583 dsl_scan_sync_state(dsl_scan_t *scn, dmu_tx_t *tx, state_sync_type_t sync_type)
586 spa_t *spa = scn->scn_dp->dp_spa;
588 ASSERT(sync_type != SYNC_MANDATORY || scn->scn_bytes_pending == 0);
589 if (scn->scn_bytes_pending == 0) {
590 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
591 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
592 dsl_scan_io_queue_t *q = vd->vdev_scan_io_queue;
597 mutex_enter(&vd->vdev_scan_io_queue_lock);
598 ASSERT3P(avl_first(&q->q_sios_by_addr), ==, NULL);
599 ASSERT3P(avl_first(&q->q_exts_by_size), ==, NULL);
600 ASSERT3P(range_tree_first(q->q_exts_by_addr), ==, NULL);
601 mutex_exit(&vd->vdev_scan_io_queue_lock);
604 if (scn->scn_phys.scn_queue_obj != 0)
605 scan_ds_queue_sync(scn, tx);
606 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
607 DMU_POOL_DIRECTORY_OBJECT,
608 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
609 &scn->scn_phys, tx));
610 bcopy(&scn->scn_phys, &scn->scn_phys_cached,
611 sizeof (scn->scn_phys));
613 if (scn->scn_checkpointing)
614 zfs_dbgmsg("finish scan checkpoint");
616 scn->scn_checkpointing = B_FALSE;
617 scn->scn_last_checkpoint = ddi_get_lbolt();
618 } else if (sync_type == SYNC_CACHED) {
619 VERIFY0(zap_update(scn->scn_dp->dp_meta_objset,
620 DMU_POOL_DIRECTORY_OBJECT,
621 DMU_POOL_SCAN, sizeof (uint64_t), SCAN_PHYS_NUMINTS,
622 &scn->scn_phys_cached, tx));
628 dsl_scan_setup_check(void *arg, dmu_tx_t *tx)
630 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
632 if (dsl_scan_is_running(scn))
633 return (SET_ERROR(EBUSY));
639 dsl_scan_setup_sync(void *arg, dmu_tx_t *tx)
641 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
642 pool_scan_func_t *funcp = arg;
643 dmu_object_type_t ot = 0;
644 dsl_pool_t *dp = scn->scn_dp;
645 spa_t *spa = dp->dp_spa;
647 ASSERT(!dsl_scan_is_running(scn));
648 ASSERT(*funcp > POOL_SCAN_NONE && *funcp < POOL_SCAN_FUNCS);
649 bzero(&scn->scn_phys, sizeof (scn->scn_phys));
650 scn->scn_phys.scn_func = *funcp;
651 scn->scn_phys.scn_state = DSS_SCANNING;
652 scn->scn_phys.scn_min_txg = 0;
653 scn->scn_phys.scn_max_txg = tx->tx_txg;
654 scn->scn_phys.scn_ddt_class_max = DDT_CLASSES - 1; /* the entire DDT */
655 scn->scn_phys.scn_start_time = gethrestime_sec();
656 scn->scn_phys.scn_errors = 0;
657 scn->scn_phys.scn_to_examine = spa->spa_root_vdev->vdev_stat.vs_alloc;
658 scn->scn_issued_before_pass = 0;
659 scn->scn_restart_txg = 0;
660 scn->scn_done_txg = 0;
661 scn->scn_last_checkpoint = 0;
662 scn->scn_checkpointing = B_FALSE;
663 spa_scan_stat_init(spa);
665 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
666 scn->scn_phys.scn_ddt_class_max = zfs_scrub_ddt_class_max;
668 /* rewrite all disk labels */
669 vdev_config_dirty(spa->spa_root_vdev);
671 if (vdev_resilver_needed(spa->spa_root_vdev,
672 &scn->scn_phys.scn_min_txg, &scn->scn_phys.scn_max_txg)) {
673 spa_event_notify(spa, NULL, NULL,
674 ESC_ZFS_RESILVER_START);
676 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_START);
679 spa->spa_scrub_started = B_TRUE;
681 * If this is an incremental scrub, limit the DDT scrub phase
682 * to just the auto-ditto class (for correctness); the rest
683 * of the scrub should go faster using top-down pruning.
685 if (scn->scn_phys.scn_min_txg > TXG_INITIAL)
686 scn->scn_phys.scn_ddt_class_max = DDT_CLASS_DITTO;
690 /* back to the generic stuff */
692 if (dp->dp_blkstats == NULL) {
694 kmem_alloc(sizeof (zfs_all_blkstats_t), KM_SLEEP);
695 mutex_init(&dp->dp_blkstats->zab_lock, NULL,
696 MUTEX_DEFAULT, NULL);
698 bzero(&dp->dp_blkstats->zab_type, sizeof (dp->dp_blkstats->zab_type));
700 if (spa_version(spa) < SPA_VERSION_DSL_SCRUB)
701 ot = DMU_OT_ZAP_OTHER;
703 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset,
704 ot ? ot : DMU_OT_SCAN_QUEUE, DMU_OT_NONE, 0, tx);
706 bcopy(&scn->scn_phys, &scn->scn_phys_cached, sizeof (scn->scn_phys));
708 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
710 spa_history_log_internal(spa, "scan setup", tx,
711 "func=%u mintxg=%llu maxtxg=%llu",
712 *funcp, scn->scn_phys.scn_min_txg, scn->scn_phys.scn_max_txg);
716 * Called by the ZFS_IOC_POOL_SCAN ioctl to start a scrub or resilver.
717 * Can also be called to resume a paused scrub.
720 dsl_scan(dsl_pool_t *dp, pool_scan_func_t func)
722 spa_t *spa = dp->dp_spa;
723 dsl_scan_t *scn = dp->dp_scan;
726 * Purge all vdev caches and probe all devices. We do this here
727 * rather than in sync context because this requires a writer lock
728 * on the spa_config lock, which we can't do from sync context. The
729 * spa_scrub_reopen flag indicates that vdev_open() should not
730 * attempt to start another scrub.
732 spa_vdev_state_enter(spa, SCL_NONE);
733 spa->spa_scrub_reopen = B_TRUE;
734 vdev_reopen(spa->spa_root_vdev);
735 spa->spa_scrub_reopen = B_FALSE;
736 (void) spa_vdev_state_exit(spa, NULL, 0);
738 if (func == POOL_SCAN_SCRUB && dsl_scan_is_paused_scrub(scn)) {
739 /* got scrub start cmd, resume paused scrub */
740 int err = dsl_scrub_set_pause_resume(scn->scn_dp,
743 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_RESUME);
746 return (SET_ERROR(err));
749 return (dsl_sync_task(spa_name(spa), dsl_scan_setup_check,
750 dsl_scan_setup_sync, &func, 0, ZFS_SPACE_CHECK_EXTRA_RESERVED));
755 dsl_scan_done(dsl_scan_t *scn, boolean_t complete, dmu_tx_t *tx)
757 static const char *old_names[] = {
759 "scrub_ddt_bookmark",
760 "scrub_ddt_class_max",
769 dsl_pool_t *dp = scn->scn_dp;
770 spa_t *spa = dp->dp_spa;
773 /* Remove any remnants of an old-style scrub. */
774 for (i = 0; old_names[i]; i++) {
775 (void) zap_remove(dp->dp_meta_objset,
776 DMU_POOL_DIRECTORY_OBJECT, old_names[i], tx);
779 if (scn->scn_phys.scn_queue_obj != 0) {
780 VERIFY0(dmu_object_free(dp->dp_meta_objset,
781 scn->scn_phys.scn_queue_obj, tx));
782 scn->scn_phys.scn_queue_obj = 0;
784 scan_ds_queue_clear(scn);
786 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
789 * If we were "restarted" from a stopped state, don't bother
790 * with anything else.
792 if (!dsl_scan_is_running(scn)) {
793 ASSERT(!scn->scn_is_sorted);
797 if (scn->scn_is_sorted) {
798 scan_io_queues_destroy(scn);
799 scn->scn_is_sorted = B_FALSE;
801 if (scn->scn_taskq != NULL) {
802 taskq_destroy(scn->scn_taskq);
803 scn->scn_taskq = NULL;
807 scn->scn_phys.scn_state = complete ? DSS_FINISHED : DSS_CANCELED;
809 if (dsl_scan_restarting(scn, tx))
810 spa_history_log_internal(spa, "scan aborted, restarting", tx,
811 "errors=%llu", spa_get_errlog_size(spa));
813 spa_history_log_internal(spa, "scan cancelled", tx,
814 "errors=%llu", spa_get_errlog_size(spa));
816 spa_history_log_internal(spa, "scan done", tx,
817 "errors=%llu", spa_get_errlog_size(spa));
819 if (DSL_SCAN_IS_SCRUB_RESILVER(scn)) {
820 spa->spa_scrub_started = B_FALSE;
821 spa->spa_scrub_active = B_FALSE;
824 * If the scrub/resilver completed, update all DTLs to
825 * reflect this. Whether it succeeded or not, vacate
826 * all temporary scrub DTLs.
828 * As the scrub does not currently support traversing
829 * data that have been freed but are part of a checkpoint,
830 * we don't mark the scrub as done in the DTLs as faults
831 * may still exist in those vdevs.
834 !spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
835 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
836 scn->scn_phys.scn_max_txg, B_TRUE);
838 spa_event_notify(spa, NULL, NULL,
839 scn->scn_phys.scn_min_txg ?
840 ESC_ZFS_RESILVER_FINISH : ESC_ZFS_SCRUB_FINISH);
842 vdev_dtl_reassess(spa->spa_root_vdev, tx->tx_txg,
845 spa_errlog_rotate(spa);
848 * We may have finished replacing a device.
849 * Let the async thread assess this and handle the detach.
851 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
854 scn->scn_phys.scn_end_time = gethrestime_sec();
856 ASSERT(!dsl_scan_is_running(scn));
861 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
863 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
865 if (!dsl_scan_is_running(scn))
866 return (SET_ERROR(ENOENT));
872 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
874 dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
876 dsl_scan_done(scn, B_FALSE, tx);
877 dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
878 spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);
882 dsl_scan_cancel(dsl_pool_t *dp)
884 return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
885 dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
889 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
891 pool_scrub_cmd_t *cmd = arg;
892 dsl_pool_t *dp = dmu_tx_pool(tx);
893 dsl_scan_t *scn = dp->dp_scan;
895 if (*cmd == POOL_SCRUB_PAUSE) {
896 /* can't pause a scrub when there is no in-progress scrub */
897 if (!dsl_scan_scrubbing(dp))
898 return (SET_ERROR(ENOENT));
900 /* can't pause a paused scrub */
901 if (dsl_scan_is_paused_scrub(scn))
902 return (SET_ERROR(EBUSY));
903 } else if (*cmd != POOL_SCRUB_NORMAL) {
904 return (SET_ERROR(ENOTSUP));
911 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
913 pool_scrub_cmd_t *cmd = arg;
914 dsl_pool_t *dp = dmu_tx_pool(tx);
915 spa_t *spa = dp->dp_spa;
916 dsl_scan_t *scn = dp->dp_scan;
918 if (*cmd == POOL_SCRUB_PAUSE) {
919 /* can't pause a scrub when there is no in-progress scrub */
920 spa->spa_scan_pass_scrub_pause = gethrestime_sec();
921 scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
922 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
923 spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);
925 ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
926 if (dsl_scan_is_paused_scrub(scn)) {
928 * We need to keep track of how much time we spend
929 * paused per pass so that we can adjust the scrub rate
930 * shown in the output of 'zpool status'
932 spa->spa_scan_pass_scrub_spent_paused +=
933 gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
934 spa->spa_scan_pass_scrub_pause = 0;
935 scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
936 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
942 * Set scrub pause/resume state if it makes sense to do so
945 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
947 return (dsl_sync_task(spa_name(dp->dp_spa),
948 dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
949 ZFS_SPACE_CHECK_RESERVED));
953 /* start a new scan, or restart an existing one. */
955 dsl_resilver_restart(dsl_pool_t *dp, uint64_t txg)
959 tx = dmu_tx_create_dd(dp->dp_mos_dir);
960 VERIFY(0 == dmu_tx_assign(tx, TXG_WAIT));
962 txg = dmu_tx_get_txg(tx);
963 dp->dp_scan->scn_restart_txg = txg;
966 dp->dp_scan->scn_restart_txg = txg;
968 zfs_dbgmsg("restarting resilver txg=%llu", txg);
972 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
974 zio_free(dp->dp_spa, txg, bp);
978 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
980 ASSERT(dsl_pool_sync_context(dp));
981 zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, BP_GET_PSIZE(bpp),
986 scan_ds_queue_compare(const void *a, const void *b)
988 const scan_ds_t *sds_a = a, *sds_b = b;
990 if (sds_a->sds_dsobj < sds_b->sds_dsobj)
992 if (sds_a->sds_dsobj == sds_b->sds_dsobj)
998 scan_ds_queue_clear(dsl_scan_t *scn)
1000 void *cookie = NULL;
1002 while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {
1003 kmem_free(sds, sizeof (*sds));
1008 scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)
1010 scan_ds_t srch, *sds;
1012 srch.sds_dsobj = dsobj;
1013 sds = avl_find(&scn->scn_queue, &srch, NULL);
1014 if (sds != NULL && txg != NULL)
1015 *txg = sds->sds_txg;
1016 return (sds != NULL);
1020 scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)
1025 sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);
1026 sds->sds_dsobj = dsobj;
1029 VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);
1030 avl_insert(&scn->scn_queue, sds, where);
1034 scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)
1036 scan_ds_t srch, *sds;
1038 srch.sds_dsobj = dsobj;
1040 sds = avl_find(&scn->scn_queue, &srch, NULL);
1041 VERIFY(sds != NULL);
1042 avl_remove(&scn->scn_queue, sds);
1043 kmem_free(sds, sizeof (*sds));
1047 scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)
1049 dsl_pool_t *dp = scn->scn_dp;
1050 spa_t *spa = dp->dp_spa;
1051 dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?
1052 DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;
1054 ASSERT0(scn->scn_bytes_pending);
1055 ASSERT(scn->scn_phys.scn_queue_obj != 0);
1057 VERIFY0(dmu_object_free(dp->dp_meta_objset,
1058 scn->scn_phys.scn_queue_obj, tx));
1059 scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,
1060 DMU_OT_NONE, 0, tx);
1061 for (scan_ds_t *sds = avl_first(&scn->scn_queue);
1062 sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {
1063 VERIFY0(zap_add_int_key(dp->dp_meta_objset,
1064 scn->scn_phys.scn_queue_obj, sds->sds_dsobj,
1070 * Computes the memory limit state that we're currently in. A sorted scan
1071 * needs quite a bit of memory to hold the sorting queue, so we need to
1072 * reasonably constrain the size so it doesn't impact overall system
1073 * performance. We compute two limits:
1074 * 1) Hard memory limit: if the amount of memory used by the sorting
1075 * queues on a pool gets above this value, we stop the metadata
1076 * scanning portion and start issuing the queued up and sorted
1077 * I/Os to reduce memory usage.
1078 * This limit is calculated as a fraction of physmem (by default 5%).
1079 * We constrain the lower bound of the hard limit to an absolute
1080 * minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain
1081 * the upper bound to 5% of the total pool size - no chance we'll
1082 * ever need that much memory, but just to keep the value in check.
1083 * 2) Soft memory limit: once we hit the hard memory limit, we start
1084 * issuing I/O to reduce queue memory usage, but we don't want to
1085 * completely empty out the queues, since we might be able to find I/Os
1086 * that will fill in the gaps of our non-sequential IOs at some point
1087 * in the future. So we stop the issuing of I/Os once the amount of
1088 * memory used drops below the soft limit (at which point we stop issuing
1089 * I/O and start scanning metadata again).
1091 * This limit is calculated by subtracting a fraction of the hard
1092 * limit from the hard limit. By default this fraction is 5%, so
1093 * the soft limit is 95% of the hard limit. We cap the size of the
1094 * difference between the hard and soft limits at an absolute
1095 * maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is
1096 * sufficient to not cause too frequent switching between the
1097 * metadata scan and I/O issue (even at 2k recordsize, 128 MiB's
1098 * worth of queues is about 1.2 GiB of on-pool data, so scanning
1099 * that should take at least a decent fraction of a second).
1102 dsl_scan_should_clear(dsl_scan_t *scn)
1104 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
1105 uint64_t mlim_hard, mlim_soft, mused;
1106 uint64_t alloc = metaslab_class_get_alloc(spa_normal_class(
1107 scn->scn_dp->dp_spa));
1109 mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,
1110 zfs_scan_mem_lim_min);
1111 mlim_hard = MIN(mlim_hard, alloc / 20);
1112 mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,
1113 zfs_scan_mem_lim_soft_max);
1115 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1116 vdev_t *tvd = rvd->vdev_child[i];
1117 dsl_scan_io_queue_t *queue;
1119 mutex_enter(&tvd->vdev_scan_io_queue_lock);
1120 queue = tvd->vdev_scan_io_queue;
1121 if (queue != NULL) {
1122 /* #extents in exts_by_size = # in exts_by_addr */
1123 mused += avl_numnodes(&queue->q_exts_by_size) *
1124 sizeof (range_seg_t) +
1125 avl_numnodes(&queue->q_sios_by_addr) *
1128 mutex_exit(&tvd->vdev_scan_io_queue_lock);
1131 dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);
1134 ASSERT0(scn->scn_bytes_pending);
1137 * If we are above our hard limit, we need to clear out memory.
1138 * If we are below our soft limit, we need to accumulate sequential IOs.
1139 * Otherwise, we should keep doing whatever we are currently doing.
1141 if (mused >= mlim_hard)
1143 else if (mused < mlim_soft)
1146 return (scn->scn_clearing);
1150 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1152 /* we never skip user/group accounting objects */
1153 if (zb && (int64_t)zb->zb_object < 0)
1156 if (scn->scn_suspending)
1157 return (B_TRUE); /* we're already suspending */
1159 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
1160 return (B_FALSE); /* we're resuming */
1162 /* We only know how to resume from level-0 blocks. */
1163 if (zb && zb->zb_level != 0)
1168 * - we have scanned for at least the minimum time (default 1 sec
1169 * for scrub, 3 sec for resilver), and either we have sufficient
1170 * dirty data that we are starting to write more quickly
1171 * (default 30%), or someone is explicitly waiting for this txg
1174 * - the spa is shutting down because this pool is being exported
1175 * or the machine is rebooting.
1177 * - the scan queue has reached its memory use limit
1179 uint64_t elapsed_nanosecs = gethrtime();
1180 uint64_t curr_time_ns = gethrtime();
1181 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
1182 uint64_t sync_time_ns = curr_time_ns -
1183 scn->scn_dp->dp_spa->spa_sync_starttime;
1185 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
1186 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
1187 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
1189 if ((NSEC2MSEC(scan_time_ns) > mintime &&
1190 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
1191 txg_sync_waiting(scn->scn_dp) ||
1192 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1193 spa_shutting_down(scn->scn_dp->dp_spa) ||
1194 (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn))) {
1196 dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
1197 (longlong_t)zb->zb_objset,
1198 (longlong_t)zb->zb_object,
1199 (longlong_t)zb->zb_level,
1200 (longlong_t)zb->zb_blkid);
1201 scn->scn_phys.scn_bookmark = *zb;
1203 dsl_scan_phys_t *scnp = &scn->scn_phys;
1205 dprintf("suspending at at DDT bookmark "
1206 "%llx/%llx/%llx/%llx\n",
1207 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
1208 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
1209 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
1210 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
1212 scn->scn_suspending = B_TRUE;
1218 typedef struct zil_scan_arg {
1220 zil_header_t *zsa_zh;
1225 dsl_scan_zil_block(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1227 zil_scan_arg_t *zsa = arg;
1228 dsl_pool_t *dp = zsa->zsa_dp;
1229 dsl_scan_t *scn = dp->dp_scan;
1230 zil_header_t *zh = zsa->zsa_zh;
1231 zbookmark_phys_t zb;
1233 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
1237 * One block ("stubby") can be allocated a long time ago; we
1238 * want to visit that one because it has been allocated
1239 * (on-disk) even if it hasn't been claimed (even though for
1240 * scrub there's nothing to do to it).
1242 if (claim_txg == 0 && bp->blk_birth >= spa_min_claim_txg(dp->dp_spa))
1245 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1246 ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
1248 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1254 dsl_scan_zil_record(zilog_t *zilog, lr_t *lrc, void *arg, uint64_t claim_txg)
1256 if (lrc->lrc_txtype == TX_WRITE) {
1257 zil_scan_arg_t *zsa = arg;
1258 dsl_pool_t *dp = zsa->zsa_dp;
1259 dsl_scan_t *scn = dp->dp_scan;
1260 zil_header_t *zh = zsa->zsa_zh;
1261 lr_write_t *lr = (lr_write_t *)lrc;
1262 blkptr_t *bp = &lr->lr_blkptr;
1263 zbookmark_phys_t zb;
1265 if (BP_IS_HOLE(bp) ||
1266 bp->blk_birth <= scn->scn_phys.scn_cur_min_txg)
1270 * birth can be < claim_txg if this record's txg is
1271 * already txg sync'ed (but this log block contains
1272 * other records that are not synced)
1274 if (claim_txg == 0 || bp->blk_birth < claim_txg)
1277 SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1278 lr->lr_foid, ZB_ZIL_LEVEL,
1279 lr->lr_offset / BP_GET_LSIZE(bp));
1281 VERIFY(0 == scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1287 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
1289 uint64_t claim_txg = zh->zh_claim_txg;
1290 zil_scan_arg_t zsa = { dp, zh };
1293 ASSERT(spa_writeable(dp->dp_spa));
1296 * We only want to visit blocks that have been claimed
1297 * but not yet replayed.
1302 zilog = zil_alloc(dp->dp_meta_objset, zh);
1304 (void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
1311 * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea
1312 * here is to sort the AVL tree by the order each block will be needed.
1315 scan_prefetch_queue_compare(const void *a, const void *b)
1317 const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;
1318 const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;
1319 const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;
1321 return (zbookmark_compare(spc_a->spc_datablkszsec,
1322 spc_a->spc_indblkshift, spc_b->spc_datablkszsec,
1323 spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));
1327 scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, void *tag)
1329 if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {
1330 zfs_refcount_destroy(&spc->spc_refcnt);
1331 kmem_free(spc, sizeof (scan_prefetch_ctx_t));
1335 static scan_prefetch_ctx_t *
1336 scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, void *tag)
1338 scan_prefetch_ctx_t *spc;
1340 spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);
1341 zfs_refcount_create(&spc->spc_refcnt);
1342 zfs_refcount_add(&spc->spc_refcnt, tag);
1345 spc->spc_datablkszsec = dnp->dn_datablkszsec;
1346 spc->spc_indblkshift = dnp->dn_indblkshift;
1347 spc->spc_root = B_FALSE;
1349 spc->spc_datablkszsec = 0;
1350 spc->spc_indblkshift = 0;
1351 spc->spc_root = B_TRUE;
1358 scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, void *tag)
1360 zfs_refcount_add(&spc->spc_refcnt, tag);
1364 dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,
1365 const zbookmark_phys_t *zb)
1367 zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;
1368 dnode_phys_t tmp_dnp;
1369 dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;
1371 if (zb->zb_objset != last_zb->zb_objset)
1373 if ((int64_t)zb->zb_object < 0)
1376 tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;
1377 tmp_dnp.dn_indblkshift = spc->spc_indblkshift;
1379 if (zbookmark_subtree_completed(dnp, zb, last_zb))
1386 dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)
1389 dsl_scan_t *scn = spc->spc_scn;
1390 spa_t *spa = scn->scn_dp->dp_spa;
1391 scan_prefetch_issue_ctx_t *spic;
1393 if (zfs_no_scrub_prefetch)
1396 if (BP_IS_HOLE(bp) || bp->blk_birth <= scn->scn_phys.scn_cur_min_txg ||
1397 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
1398 BP_GET_TYPE(bp) != DMU_OT_OBJSET))
1401 if (dsl_scan_check_prefetch_resume(spc, zb))
1404 scan_prefetch_ctx_add_ref(spc, scn);
1405 spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);
1406 spic->spic_spc = spc;
1407 spic->spic_bp = *bp;
1408 spic->spic_zb = *zb;
1411 * Add the IO to the queue of blocks to prefetch. This allows us to
1412 * prioritize blocks that we will need first for the main traversal
1415 mutex_enter(&spa->spa_scrub_lock);
1416 if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {
1417 /* this block is already queued for prefetch */
1418 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1419 scan_prefetch_ctx_rele(spc, scn);
1420 mutex_exit(&spa->spa_scrub_lock);
1424 avl_insert(&scn->scn_prefetch_queue, spic, idx);
1425 cv_broadcast(&spa->spa_scrub_io_cv);
1426 mutex_exit(&spa->spa_scrub_lock);
1430 dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,
1431 uint64_t objset, uint64_t object)
1434 zbookmark_phys_t zb;
1435 scan_prefetch_ctx_t *spc;
1437 if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1440 SET_BOOKMARK(&zb, objset, object, 0, 0);
1442 spc = scan_prefetch_ctx_create(scn, dnp, FTAG);
1444 for (i = 0; i < dnp->dn_nblkptr; i++) {
1445 zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);
1447 dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);
1450 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1452 zb.zb_blkid = DMU_SPILL_BLKID;
1453 dsl_scan_prefetch(spc, &dnp->dn_spill, &zb);
1456 scan_prefetch_ctx_rele(spc, FTAG);
1460 dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
1461 arc_buf_t *buf, void *private)
1463 scan_prefetch_ctx_t *spc = private;
1464 dsl_scan_t *scn = spc->spc_scn;
1465 spa_t *spa = scn->scn_dp->dp_spa;
1467 /* broadcast that the IO has completed for rate limitting purposes */
1468 mutex_enter(&spa->spa_scrub_lock);
1469 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
1470 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
1471 cv_broadcast(&spa->spa_scrub_io_cv);
1472 mutex_exit(&spa->spa_scrub_lock);
1474 /* if there was an error or we are done prefetching, just cleanup */
1475 if (buf == NULL || scn->scn_suspending)
1478 if (BP_GET_LEVEL(bp) > 0) {
1481 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1482 zbookmark_phys_t czb;
1484 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
1485 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1486 zb->zb_level - 1, zb->zb_blkid * epb + i);
1487 dsl_scan_prefetch(spc, cbp, &czb);
1489 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
1490 dnode_phys_t *cdnp = buf->b_data;
1492 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
1494 for (i = 0, cdnp = buf->b_data; i < epb;
1495 i += cdnp->dn_extra_slots + 1,
1496 cdnp += cdnp->dn_extra_slots + 1) {
1497 dsl_scan_prefetch_dnode(scn, cdnp,
1498 zb->zb_objset, zb->zb_blkid * epb + i);
1500 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1501 objset_phys_t *osp = buf->b_data;
1503 dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,
1504 zb->zb_objset, DMU_META_DNODE_OBJECT);
1506 if (OBJSET_BUF_HAS_USERUSED(buf)) {
1507 dsl_scan_prefetch_dnode(scn,
1508 &osp->os_groupused_dnode, zb->zb_objset,
1509 DMU_GROUPUSED_OBJECT);
1510 dsl_scan_prefetch_dnode(scn,
1511 &osp->os_userused_dnode, zb->zb_objset,
1512 DMU_USERUSED_OBJECT);
1518 arc_buf_destroy(buf, private);
1519 scan_prefetch_ctx_rele(spc, scn);
1524 dsl_scan_prefetch_thread(void *arg)
1526 dsl_scan_t *scn = arg;
1527 spa_t *spa = scn->scn_dp->dp_spa;
1528 vdev_t *rvd = spa->spa_root_vdev;
1529 uint64_t maxinflight = rvd->vdev_children * zfs_top_maxinflight;
1530 scan_prefetch_issue_ctx_t *spic;
1532 /* loop until we are told to stop */
1533 while (!scn->scn_prefetch_stop) {
1534 arc_flags_t flags = ARC_FLAG_NOWAIT |
1535 ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;
1536 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
1538 mutex_enter(&spa->spa_scrub_lock);
1541 * Wait until we have an IO to issue and are not above our
1542 * maximum in flight limit.
1544 while (!scn->scn_prefetch_stop &&
1545 (avl_numnodes(&scn->scn_prefetch_queue) == 0 ||
1546 spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {
1547 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
1550 /* recheck if we should stop since we waited for the cv */
1551 if (scn->scn_prefetch_stop) {
1552 mutex_exit(&spa->spa_scrub_lock);
1556 /* remove the prefetch IO from the tree */
1557 spic = avl_first(&scn->scn_prefetch_queue);
1558 spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);
1559 avl_remove(&scn->scn_prefetch_queue, spic);
1561 mutex_exit(&spa->spa_scrub_lock);
1563 /* issue the prefetch asynchronously */
1564 (void) arc_read(scn->scn_zio_root, scn->scn_dp->dp_spa,
1565 &spic->spic_bp, dsl_scan_prefetch_cb, spic->spic_spc,
1566 ZIO_PRIORITY_SCRUB, zio_flags, &flags, &spic->spic_zb);
1568 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1571 ASSERT(scn->scn_prefetch_stop);
1573 /* free any prefetches we didn't get to complete */
1574 mutex_enter(&spa->spa_scrub_lock);
1575 while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {
1576 avl_remove(&scn->scn_prefetch_queue, spic);
1577 scan_prefetch_ctx_rele(spic->spic_spc, scn);
1578 kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
1580 ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));
1581 mutex_exit(&spa->spa_scrub_lock);
1585 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
1586 const zbookmark_phys_t *zb)
1589 * We never skip over user/group accounting objects (obj<0)
1591 if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
1592 (int64_t)zb->zb_object >= 0) {
1594 * If we already visited this bp & everything below (in
1595 * a prior txg sync), don't bother doing it again.
1597 if (zbookmark_subtree_completed(dnp, zb,
1598 &scn->scn_phys.scn_bookmark))
1602 * If we found the block we're trying to resume from, or
1603 * we went past it to a different object, zero it out to
1604 * indicate that it's OK to start checking for suspending
1607 if (bcmp(zb, &scn->scn_phys.scn_bookmark, sizeof (*zb)) == 0 ||
1608 zb->zb_object > scn->scn_phys.scn_bookmark.zb_object) {
1609 dprintf("resuming at %llx/%llx/%llx/%llx\n",
1610 (longlong_t)zb->zb_objset,
1611 (longlong_t)zb->zb_object,
1612 (longlong_t)zb->zb_level,
1613 (longlong_t)zb->zb_blkid);
1614 bzero(&scn->scn_phys.scn_bookmark, sizeof (*zb));
1620 static void dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
1621 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1622 dmu_objset_type_t ostype, dmu_tx_t *tx);
1623 static void dsl_scan_visitdnode(
1624 dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1625 dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
1628 * Return nonzero on i/o error.
1629 * Return new buf to write out in *bufp.
1632 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
1633 dnode_phys_t *dnp, const blkptr_t *bp,
1634 const zbookmark_phys_t *zb, dmu_tx_t *tx)
1636 dsl_pool_t *dp = scn->scn_dp;
1637 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
1640 if (BP_GET_LEVEL(bp) > 0) {
1641 arc_flags_t flags = ARC_FLAG_WAIT;
1644 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1647 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1648 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1650 scn->scn_phys.scn_errors++;
1653 for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
1654 zbookmark_phys_t czb;
1656 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1658 zb->zb_blkid * epb + i);
1659 dsl_scan_visitbp(cbp, &czb, dnp,
1660 ds, scn, ostype, tx);
1662 arc_buf_destroy(buf, &buf);
1663 } else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
1664 arc_flags_t flags = ARC_FLAG_WAIT;
1667 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
1670 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1671 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1673 scn->scn_phys.scn_errors++;
1676 for (i = 0, cdnp = buf->b_data; i < epb;
1677 i += cdnp->dn_extra_slots + 1,
1678 cdnp += cdnp->dn_extra_slots + 1) {
1679 dsl_scan_visitdnode(scn, ds, ostype,
1680 cdnp, zb->zb_blkid * epb + i, tx);
1683 arc_buf_destroy(buf, &buf);
1684 } else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1685 arc_flags_t flags = ARC_FLAG_WAIT;
1689 err = arc_read(NULL, dp->dp_spa, bp, arc_getbuf_func, &buf,
1690 ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
1692 scn->scn_phys.scn_errors++;
1698 dsl_scan_visitdnode(scn, ds, osp->os_type,
1699 &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
1701 if (OBJSET_BUF_HAS_USERUSED(buf)) {
1703 * We also always visit user/group accounting
1704 * objects, and never skip them, even if we are
1705 * suspending. This is necessary so that the space
1706 * deltas from this txg get integrated.
1708 dsl_scan_visitdnode(scn, ds, osp->os_type,
1709 &osp->os_groupused_dnode,
1710 DMU_GROUPUSED_OBJECT, tx);
1711 dsl_scan_visitdnode(scn, ds, osp->os_type,
1712 &osp->os_userused_dnode,
1713 DMU_USERUSED_OBJECT, tx);
1715 arc_buf_destroy(buf, &buf);
1722 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
1723 dmu_objset_type_t ostype, dnode_phys_t *dnp,
1724 uint64_t object, dmu_tx_t *tx)
1728 for (j = 0; j < dnp->dn_nblkptr; j++) {
1729 zbookmark_phys_t czb;
1731 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1732 dnp->dn_nlevels - 1, j);
1733 dsl_scan_visitbp(&dnp->dn_blkptr[j],
1734 &czb, dnp, ds, scn, ostype, tx);
1737 if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1738 zbookmark_phys_t czb;
1739 SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
1740 0, DMU_SPILL_BLKID);
1741 dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),
1742 &czb, dnp, ds, scn, ostype, tx);
1747 * The arguments are in this order because mdb can only print the
1748 * first 5; we want them to be useful.
1751 dsl_scan_visitbp(blkptr_t *bp, const zbookmark_phys_t *zb,
1752 dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
1753 dmu_objset_type_t ostype, dmu_tx_t *tx)
1755 dsl_pool_t *dp = scn->scn_dp;
1756 blkptr_t *bp_toread = NULL;
1758 if (dsl_scan_check_suspend(scn, zb))
1761 if (dsl_scan_check_resume(scn, dnp, zb))
1764 scn->scn_visited_this_txg++;
1767 "visiting ds=%p/%llu zb=%llx/%llx/%llx/%llx bp=%p",
1768 ds, ds ? ds->ds_object : 0,
1769 zb->zb_objset, zb->zb_object, zb->zb_level, zb->zb_blkid,
1772 if (BP_IS_HOLE(bp)) {
1773 scn->scn_holes_this_txg++;
1777 if (bp->blk_birth <= scn->scn_phys.scn_cur_min_txg) {
1778 scn->scn_lt_min_this_txg++;
1782 bp_toread = kmem_alloc(sizeof (blkptr_t), KM_SLEEP);
1785 if (dsl_scan_recurse(scn, ds, ostype, dnp, bp_toread, zb, tx) != 0)
1789 * If dsl_scan_ddt() has already visited this block, it will have
1790 * already done any translations or scrubbing, so don't call the
1793 if (ddt_class_contains(dp->dp_spa,
1794 scn->scn_phys.scn_ddt_class_max, bp)) {
1795 scn->scn_ddt_contained_this_txg++;
1800 * If this block is from the future (after cur_max_txg), then we
1801 * are doing this on behalf of a deleted snapshot, and we will
1802 * revisit the future block on the next pass of this dataset.
1803 * Don't scan it now unless we need to because something
1804 * under it was modified.
1806 if (BP_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {
1807 scn->scn_gt_max_this_txg++;
1811 scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
1813 kmem_free(bp_toread, sizeof (blkptr_t));
1817 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
1820 zbookmark_phys_t zb;
1821 scan_prefetch_ctx_t *spc;
1823 SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1824 ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1826 if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {
1827 SET_BOOKMARK(&scn->scn_prefetch_bookmark,
1828 zb.zb_objset, 0, 0, 0);
1830 scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;
1833 scn->scn_objsets_visited_this_txg++;
1835 spc = scan_prefetch_ctx_create(scn, NULL, FTAG);
1836 dsl_scan_prefetch(spc, bp, &zb);
1837 scan_prefetch_ctx_rele(spc, FTAG);
1839 dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);
1841 dprintf_ds(ds, "finished scan%s", "");
1845 ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)
1847 if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {
1848 if (ds->ds_is_snapshot) {
1851 * - scn_cur_{min,max}_txg stays the same.
1852 * - Setting the flag is not really necessary if
1853 * scn_cur_max_txg == scn_max_txg, because there
1854 * is nothing after this snapshot that we care
1855 * about. However, we set it anyway and then
1856 * ignore it when we retraverse it in
1857 * dsl_scan_visitds().
1859 scn_phys->scn_bookmark.zb_objset =
1860 dsl_dataset_phys(ds)->ds_next_snap_obj;
1861 zfs_dbgmsg("destroying ds %llu; currently traversing; "
1862 "reset zb_objset to %llu",
1863 (u_longlong_t)ds->ds_object,
1864 (u_longlong_t)dsl_dataset_phys(ds)->
1866 scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;
1868 SET_BOOKMARK(&scn_phys->scn_bookmark,
1869 ZB_DESTROYED_OBJSET, 0, 0, 0);
1870 zfs_dbgmsg("destroying ds %llu; currently traversing; "
1871 "reset bookmark to -1,0,0,0",
1872 (u_longlong_t)ds->ds_object);
1878 * Invoked when a dataset is destroyed. We need to make sure that:
1880 * 1) If it is the dataset that was currently being scanned, we write
1881 * a new dsl_scan_phys_t and marking the objset reference in it
1883 * 2) Remove it from the work queue, if it was present.
1885 * If the dataset was actually a snapshot, instead of marking the dataset
1886 * as destroyed, we instead substitute the next snapshot in line.
1889 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
1891 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1892 dsl_scan_t *scn = dp->dp_scan;
1895 if (!dsl_scan_is_running(scn))
1898 ds_destroyed_scn_phys(ds, &scn->scn_phys);
1899 ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);
1901 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
1902 scan_ds_queue_remove(scn, ds->ds_object);
1903 if (ds->ds_is_snapshot)
1904 scan_ds_queue_insert(scn,
1905 dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);
1908 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1909 ds->ds_object, &mintxg) == 0) {
1910 ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
1911 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1912 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
1913 if (ds->ds_is_snapshot) {
1915 * We keep the same mintxg; it could be >
1916 * ds_creation_txg if the previous snapshot was
1919 VERIFY(zap_add_int_key(dp->dp_meta_objset,
1920 scn->scn_phys.scn_queue_obj,
1921 dsl_dataset_phys(ds)->ds_next_snap_obj,
1923 zfs_dbgmsg("destroying ds %llu; in queue; "
1924 "replacing with %llu",
1925 (u_longlong_t)ds->ds_object,
1926 (u_longlong_t)dsl_dataset_phys(ds)->
1929 zfs_dbgmsg("destroying ds %llu; in queue; removing",
1930 (u_longlong_t)ds->ds_object);
1935 * dsl_scan_sync() should be called after this, and should sync
1936 * out our changed state, but just to be safe, do it here.
1938 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1942 ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)
1944 if (scn_bookmark->zb_objset == ds->ds_object) {
1945 scn_bookmark->zb_objset =
1946 dsl_dataset_phys(ds)->ds_prev_snap_obj;
1947 zfs_dbgmsg("snapshotting ds %llu; currently traversing; "
1948 "reset zb_objset to %llu",
1949 (u_longlong_t)ds->ds_object,
1950 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
1955 * Called when a dataset is snapshotted. If we were currently traversing
1956 * this snapshot, we reset our bookmark to point at the newly created
1957 * snapshot. We also modify our work queue to remove the old snapshot and
1958 * replace with the new one.
1961 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
1963 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1964 dsl_scan_t *scn = dp->dp_scan;
1967 if (!dsl_scan_is_running(scn))
1970 ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1972 ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);
1973 ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);
1975 if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
1976 scan_ds_queue_remove(scn, ds->ds_object);
1977 scan_ds_queue_insert(scn,
1978 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);
1981 if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
1982 ds->ds_object, &mintxg) == 0) {
1983 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
1984 scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
1985 VERIFY(zap_add_int_key(dp->dp_meta_objset,
1986 scn->scn_phys.scn_queue_obj,
1987 dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
1988 zfs_dbgmsg("snapshotting ds %llu; in queue; "
1989 "replacing with %llu",
1990 (u_longlong_t)ds->ds_object,
1991 (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
1994 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1998 ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,
1999 zbookmark_phys_t *scn_bookmark)
2001 if (scn_bookmark->zb_objset == ds1->ds_object) {
2002 scn_bookmark->zb_objset = ds2->ds_object;
2003 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2004 "reset zb_objset to %llu",
2005 (u_longlong_t)ds1->ds_object,
2006 (u_longlong_t)ds2->ds_object);
2007 } else if (scn_bookmark->zb_objset == ds2->ds_object) {
2008 scn_bookmark->zb_objset = ds1->ds_object;
2009 zfs_dbgmsg("clone_swap ds %llu; currently traversing; "
2010 "reset zb_objset to %llu",
2011 (u_longlong_t)ds2->ds_object,
2012 (u_longlong_t)ds1->ds_object);
2017 * Called when an origin dataset and its clone are swapped. If we were
2018 * currently traversing the dataset, we need to switch to traversing the
2019 * newly promoted clone.
2022 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
2024 dsl_pool_t *dp = ds1->ds_dir->dd_pool;
2025 dsl_scan_t *scn = dp->dp_scan;
2026 uint64_t mintxg1, mintxg2;
2027 boolean_t ds1_queued, ds2_queued;
2029 if (!dsl_scan_is_running(scn))
2032 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);
2033 ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);
2036 * Handle the in-memory scan queue.
2038 ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);
2039 ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);
2041 /* Sanity checking. */
2043 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2044 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2047 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2048 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2051 if (ds1_queued && ds2_queued) {
2053 * If both are queued, we don't need to do anything.
2054 * The swapping code below would not handle this case correctly,
2055 * since we can't insert ds2 if it is already there. That's
2056 * because scan_ds_queue_insert() prohibits a duplicate insert
2059 } else if (ds1_queued) {
2060 scan_ds_queue_remove(scn, ds1->ds_object);
2061 scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);
2062 } else if (ds2_queued) {
2063 scan_ds_queue_remove(scn, ds2->ds_object);
2064 scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);
2068 * Handle the on-disk scan queue.
2069 * The on-disk state is an out-of-date version of the in-memory state,
2070 * so the in-memory and on-disk values for ds1_queued and ds2_queued may
2071 * be different. Therefore we need to apply the swap logic to the
2072 * on-disk state independently of the in-memory state.
2074 ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,
2075 scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;
2076 ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,
2077 scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;
2079 /* Sanity checking. */
2081 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2082 ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2085 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2086 ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2089 if (ds1_queued && ds2_queued) {
2091 * If both are queued, we don't need to do anything.
2092 * Alternatively, we could check for EEXIST from
2093 * zap_add_int_key() and back out to the original state, but
2094 * that would be more work than checking for this case upfront.
2096 } else if (ds1_queued) {
2097 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2098 scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
2099 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2100 scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));
2101 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2102 "replacing with %llu",
2103 (u_longlong_t)ds1->ds_object,
2104 (u_longlong_t)ds2->ds_object);
2105 } else if (ds2_queued) {
2106 VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2107 scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
2108 VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2109 scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));
2110 zfs_dbgmsg("clone_swap ds %llu; in queue; "
2111 "replacing with %llu",
2112 (u_longlong_t)ds2->ds_object,
2113 (u_longlong_t)ds1->ds_object);
2116 dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2121 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2123 uint64_t originobj = *(uint64_t *)arg;
2126 dsl_scan_t *scn = dp->dp_scan;
2128 if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)
2131 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2135 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {
2136 dsl_dataset_t *prev;
2137 err = dsl_dataset_hold_obj(dp,
2138 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2140 dsl_dataset_rele(ds, FTAG);
2145 scan_ds_queue_insert(scn, ds->ds_object,
2146 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2147 dsl_dataset_rele(ds, FTAG);
2152 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
2154 dsl_pool_t *dp = scn->scn_dp;
2157 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2159 if (scn->scn_phys.scn_cur_min_txg >=
2160 scn->scn_phys.scn_max_txg) {
2162 * This can happen if this snapshot was created after the
2163 * scan started, and we already completed a previous snapshot
2164 * that was created after the scan started. This snapshot
2165 * only references blocks with:
2167 * birth < our ds_creation_txg
2168 * cur_min_txg is no less than ds_creation_txg.
2169 * We have already visited these blocks.
2171 * birth > scn_max_txg
2172 * The scan requested not to visit these blocks.
2174 * Subsequent snapshots (and clones) can reference our
2175 * blocks, or blocks with even higher birth times.
2176 * Therefore we do not need to visit them either,
2177 * so we do not add them to the work queue.
2179 * Note that checking for cur_min_txg >= cur_max_txg
2180 * is not sufficient, because in that case we may need to
2181 * visit subsequent snapshots. This happens when min_txg > 0,
2182 * which raises cur_min_txg. In this case we will visit
2183 * this dataset but skip all of its blocks, because the
2184 * rootbp's birth time is < cur_min_txg. Then we will
2185 * add the next snapshots/clones to the work queue.
2187 char *dsname = kmem_alloc(MAXNAMELEN, KM_SLEEP);
2188 dsl_dataset_name(ds, dsname);
2189 zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
2190 "cur_min_txg (%llu) >= max_txg (%llu)",
2191 (longlong_t)dsobj, dsname,
2192 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2193 (longlong_t)scn->scn_phys.scn_max_txg);
2194 kmem_free(dsname, MAXNAMELEN);
2200 * Only the ZIL in the head (non-snapshot) is valid. Even though
2201 * snapshots can have ZIL block pointers (which may be the same
2202 * BP as in the head), they must be ignored. In addition, $ORIGIN
2203 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
2204 * need to look for a ZIL in it either. So we traverse the ZIL here,
2205 * rather than in scan_recurse(), because the regular snapshot
2206 * block-sharing rules don't apply to it.
2208 if (DSL_SCAN_IS_SCRUB_RESILVER(scn) && !dsl_dataset_is_snapshot(ds) &&
2209 (dp->dp_origin_snap == NULL ||
2210 ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
2212 if (dmu_objset_from_ds(ds, &os) != 0) {
2215 dsl_scan_zil(dp, &os->os_zil_header);
2219 * Iterate over the bps in this ds.
2221 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2222 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2223 dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
2224 rrw_exit(&ds->ds_bp_rwlock, FTAG);
2226 char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2227 dsl_dataset_name(ds, dsname);
2228 zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
2230 (longlong_t)dsobj, dsname,
2231 (longlong_t)scn->scn_phys.scn_cur_min_txg,
2232 (longlong_t)scn->scn_phys.scn_cur_max_txg,
2233 (int)scn->scn_suspending);
2234 kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
2236 if (scn->scn_suspending)
2240 * We've finished this pass over this dataset.
2244 * If we did not completely visit this dataset, do another pass.
2246 if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
2247 zfs_dbgmsg("incomplete pass; visiting again");
2248 scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
2249 scan_ds_queue_insert(scn, ds->ds_object,
2250 scn->scn_phys.scn_cur_max_txg);
2255 * Add descendent datasets to work queue.
2257 if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
2258 scan_ds_queue_insert(scn,
2259 dsl_dataset_phys(ds)->ds_next_snap_obj,
2260 dsl_dataset_phys(ds)->ds_creation_txg);
2262 if (dsl_dataset_phys(ds)->ds_num_children > 1) {
2263 boolean_t usenext = B_FALSE;
2264 if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2267 * A bug in a previous version of the code could
2268 * cause upgrade_clones_cb() to not set
2269 * ds_next_snap_obj when it should, leading to a
2270 * missing entry. Therefore we can only use the
2271 * next_clones_obj when its count is correct.
2273 int err = zap_count(dp->dp_meta_objset,
2274 dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
2276 count == dsl_dataset_phys(ds)->ds_num_children - 1)
2283 for (zap_cursor_init(&zc, dp->dp_meta_objset,
2284 dsl_dataset_phys(ds)->ds_next_clones_obj);
2285 zap_cursor_retrieve(&zc, &za) == 0;
2286 (void) zap_cursor_advance(&zc)) {
2287 scan_ds_queue_insert(scn,
2288 zfs_strtonum(za.za_name, NULL),
2289 dsl_dataset_phys(ds)->ds_creation_txg);
2291 zap_cursor_fini(&zc);
2293 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2294 enqueue_clones_cb, &ds->ds_object,
2300 dsl_dataset_rele(ds, FTAG);
2305 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2309 dsl_scan_t *scn = dp->dp_scan;
2311 err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2315 while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2316 dsl_dataset_t *prev;
2317 err = dsl_dataset_hold_obj(dp,
2318 dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2320 dsl_dataset_rele(ds, FTAG);
2325 * If this is a clone, we don't need to worry about it for now.
2327 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
2328 dsl_dataset_rele(ds, FTAG);
2329 dsl_dataset_rele(prev, FTAG);
2332 dsl_dataset_rele(ds, FTAG);
2336 scan_ds_queue_insert(scn, ds->ds_object,
2337 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2338 dsl_dataset_rele(ds, FTAG);
2344 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
2345 ddt_entry_t *dde, dmu_tx_t *tx)
2347 const ddt_key_t *ddk = &dde->dde_key;
2348 ddt_phys_t *ddp = dde->dde_phys;
2350 zbookmark_phys_t zb = { 0 };
2353 if (scn->scn_phys.scn_state != DSS_SCANNING)
2356 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2357 if (ddp->ddp_phys_birth == 0 ||
2358 ddp->ddp_phys_birth > scn->scn_phys.scn_max_txg)
2360 ddt_bp_create(checksum, ddk, ddp, &bp);
2362 scn->scn_visited_this_txg++;
2363 scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
2368 * Scrub/dedup interaction.
2370 * If there are N references to a deduped block, we don't want to scrub it
2371 * N times -- ideally, we should scrub it exactly once.
2373 * We leverage the fact that the dde's replication class (enum ddt_class)
2374 * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
2375 * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
2377 * To prevent excess scrubbing, the scrub begins by walking the DDT
2378 * to find all blocks with refcnt > 1, and scrubs each of these once.
2379 * Since there are two replication classes which contain blocks with
2380 * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
2381 * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
2383 * There would be nothing more to say if a block's refcnt couldn't change
2384 * during a scrub, but of course it can so we must account for changes
2385 * in a block's replication class.
2387 * Here's an example of what can occur:
2389 * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
2390 * when visited during the top-down scrub phase, it will be scrubbed twice.
2391 * This negates our scrub optimization, but is otherwise harmless.
2393 * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
2394 * on each visit during the top-down scrub phase, it will never be scrubbed.
2395 * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
2396 * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
2397 * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
2398 * while a scrub is in progress, it scrubs the block right then.
2401 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
2403 ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
2404 ddt_entry_t dde = { 0 };
2408 while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &dde)) == 0) {
2411 if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
2413 dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
2414 (longlong_t)ddb->ddb_class,
2415 (longlong_t)ddb->ddb_type,
2416 (longlong_t)ddb->ddb_checksum,
2417 (longlong_t)ddb->ddb_cursor);
2419 /* There should be no pending changes to the dedup table */
2420 ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
2421 ASSERT(avl_first(&ddt->ddt_tree) == NULL);
2423 dsl_scan_ddt_entry(scn, ddb->ddb_checksum, &dde, tx);
2426 if (dsl_scan_check_suspend(scn, NULL))
2430 zfs_dbgmsg("scanned %llu ddt entries with class_max = %u; "
2431 "suspending=%u", (longlong_t)n,
2432 (int)scn->scn_phys.scn_ddt_class_max, (int)scn->scn_suspending);
2434 ASSERT(error == 0 || error == ENOENT);
2435 ASSERT(error != ENOENT ||
2436 ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
2440 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
2442 uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
2443 if (ds->ds_is_snapshot)
2444 return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
2449 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
2452 dsl_pool_t *dp = scn->scn_dp;
2454 if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
2455 scn->scn_phys.scn_ddt_class_max) {
2456 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2457 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2458 dsl_scan_ddt(scn, tx);
2459 if (scn->scn_suspending)
2463 if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
2464 /* First do the MOS & ORIGIN */
2466 scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
2467 scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
2468 dsl_scan_visit_rootbp(scn, NULL,
2469 &dp->dp_meta_rootbp, tx);
2470 spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
2471 if (scn->scn_suspending)
2474 if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
2475 VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2476 enqueue_cb, NULL, DS_FIND_CHILDREN));
2478 dsl_scan_visitds(scn,
2479 dp->dp_origin_snap->ds_object, tx);
2481 ASSERT(!scn->scn_suspending);
2482 } else if (scn->scn_phys.scn_bookmark.zb_objset !=
2483 ZB_DESTROYED_OBJSET) {
2484 uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
2486 * If we were suspended, continue from here. Note if the
2487 * ds we were suspended on was deleted, the zb_objset may
2488 * be -1, so we will skip this and find a new objset
2491 dsl_scan_visitds(scn, dsobj, tx);
2492 if (scn->scn_suspending)
2497 * In case we suspended right at the end of the ds, zero the
2498 * bookmark so we don't think that we're still trying to resume.
2500 bzero(&scn->scn_phys.scn_bookmark, sizeof (zbookmark_phys_t));
2503 * Keep pulling things out of the dataset avl queue. Updates to the
2504 * persistent zap-object-as-queue happen only at checkpoints.
2506 while ((sds = avl_first(&scn->scn_queue)) != NULL) {
2508 uint64_t dsobj = sds->sds_dsobj;
2509 uint64_t txg = sds->sds_txg;
2511 /* dequeue and free the ds from the queue */
2512 scan_ds_queue_remove(scn, dsobj);
2513 sds = NULL; /* must not be touched after removal */
2515 /* Set up min / max txg */
2516 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2518 scn->scn_phys.scn_cur_min_txg =
2519 MAX(scn->scn_phys.scn_min_txg, txg);
2521 scn->scn_phys.scn_cur_min_txg =
2522 MAX(scn->scn_phys.scn_min_txg,
2523 dsl_dataset_phys(ds)->ds_prev_snap_txg);
2525 scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
2526 dsl_dataset_rele(ds, FTAG);
2528 dsl_scan_visitds(scn, dsobj, tx);
2529 if (scn->scn_suspending)
2532 /* No more objsets to fetch, we're done */
2533 scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
2534 ASSERT0(scn->scn_suspending);
2538 dsl_scan_count_leaves(vdev_t *vd)
2540 uint64_t i, leaves = 0;
2542 /* we only count leaves that belong to the main pool and are readable */
2543 if (vd->vdev_islog || vd->vdev_isspare ||
2544 vd->vdev_isl2cache || !vdev_readable(vd))
2547 if (vd->vdev_ops->vdev_op_leaf)
2550 for (i = 0; i < vd->vdev_children; i++) {
2551 leaves += dsl_scan_count_leaves(vd->vdev_child[i]);
2559 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
2562 uint64_t cur_size = 0;
2564 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
2565 cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
2568 q->q_total_zio_size_this_txg += cur_size;
2569 q->q_zios_this_txg++;
2573 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
2576 q->q_total_seg_size_this_txg += end - start;
2577 q->q_segs_this_txg++;
2581 scan_io_queue_check_suspend(dsl_scan_t *scn)
2583 /* See comment in dsl_scan_check_suspend() */
2584 uint64_t curr_time_ns = gethrtime();
2585 uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
2586 uint64_t sync_time_ns = curr_time_ns -
2587 scn->scn_dp->dp_spa->spa_sync_starttime;
2588 int dirty_pct = scn->scn_dp->dp_dirty_total * 100 / zfs_dirty_data_max;
2589 int mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
2590 zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
2592 return ((NSEC2MSEC(scan_time_ns) > mintime &&
2593 (dirty_pct >= zfs_vdev_async_write_active_min_dirty_percent ||
2594 txg_sync_waiting(scn->scn_dp) ||
2595 NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
2596 spa_shutting_down(scn->scn_dp->dp_spa));
2600 * Given a list of scan_io_t's in io_list, this issues the io's out to
2601 * disk. This consumes the io_list and frees the scan_io_t's. This is
2602 * called when emptying queues, either when we're up against the memory
2603 * limit or when we have finished scanning. Returns B_TRUE if we stopped
2604 * processing the list before we finished. Any zios that were not issued
2605 * will remain in the io_list.
2608 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
2610 dsl_scan_t *scn = queue->q_scn;
2612 int64_t bytes_issued = 0;
2613 boolean_t suspended = B_FALSE;
2615 while ((sio = list_head(io_list)) != NULL) {
2618 if (scan_io_queue_check_suspend(scn)) {
2623 sio2bp(sio, &bp, queue->q_vd->vdev_id);
2624 bytes_issued += sio->sio_asize;
2625 scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
2626 &sio->sio_zb, queue);
2627 (void) list_remove_head(io_list);
2628 scan_io_queues_update_zio_stats(queue, &bp);
2629 kmem_free(sio, sizeof (*sio));
2632 atomic_add_64(&scn->scn_bytes_pending, -bytes_issued);
2638 * Given a range_seg_t (extent) and a list, this function passes over a
2639 * scan queue and gathers up the appropriate ios which fit into that
2640 * scan seg (starting from lowest LBA). At the end, we remove the segment
2641 * from the q_exts_by_addr range tree.
2644 scan_io_queue_gather(dsl_scan_io_queue_t *queue, range_seg_t *rs, list_t *list)
2646 scan_io_t srch_sio, *sio, *next_sio;
2648 uint_t num_sios = 0;
2649 int64_t bytes_issued = 0;
2652 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2654 srch_sio.sio_offset = rs->rs_start;
2657 * The exact start of the extent might not contain any matching zios,
2658 * so if that's the case, examine the next one in the tree.
2660 sio = avl_find(&queue->q_sios_by_addr, &srch_sio, &idx);
2662 sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
2664 while (sio != NULL && sio->sio_offset < rs->rs_end && num_sios <= 32) {
2665 ASSERT3U(sio->sio_offset, >=, rs->rs_start);
2666 ASSERT3U(sio->sio_offset + sio->sio_asize, <=, rs->rs_end);
2668 next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
2669 avl_remove(&queue->q_sios_by_addr, sio);
2671 bytes_issued += sio->sio_asize;
2673 list_insert_tail(list, sio);
2678 * We limit the number of sios we process at once to 32 to avoid
2679 * biting off more than we can chew. If we didn't take everything
2680 * in the segment we update it to reflect the work we were able to
2681 * complete. Otherwise, we remove it from the range tree entirely.
2683 if (sio != NULL && sio->sio_offset < rs->rs_end) {
2684 range_tree_adjust_fill(queue->q_exts_by_addr, rs,
2686 range_tree_resize_segment(queue->q_exts_by_addr, rs,
2687 sio->sio_offset, rs->rs_end - sio->sio_offset);
2691 range_tree_remove(queue->q_exts_by_addr, rs->rs_start,
2692 rs->rs_end - rs->rs_start);
2699 * This is called from the queue emptying thread and selects the next
2700 * extent from which we are to issue io's. The behavior of this function
2701 * depends on the state of the scan, the current memory consumption and
2702 * whether or not we are performing a scan shutdown.
2703 * 1) We select extents in an elevator algorithm (LBA-order) if the scan
2704 * needs to perform a checkpoint
2705 * 2) We select the largest available extent if we are up against the
2707 * 3) Otherwise we don't select any extents.
2709 static const range_seg_t *
2710 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
2712 dsl_scan_t *scn = queue->q_scn;
2714 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
2715 ASSERT(scn->scn_is_sorted);
2717 /* handle tunable overrides */
2718 if (scn->scn_checkpointing || scn->scn_clearing) {
2719 if (zfs_scan_issue_strategy == 1) {
2720 return (range_tree_first(queue->q_exts_by_addr));
2721 } else if (zfs_scan_issue_strategy == 2) {
2722 return (avl_first(&queue->q_exts_by_size));
2727 * During normal clearing, we want to issue our largest segments
2728 * first, keeping IO as sequential as possible, and leaving the
2729 * smaller extents for later with the hope that they might eventually
2730 * grow to larger sequential segments. However, when the scan is
2731 * checkpointing, no new extents will be added to the sorting queue,
2732 * so the way we are sorted now is as good as it will ever get.
2733 * In this case, we instead switch to issuing extents in LBA order.
2735 if (scn->scn_checkpointing) {
2736 return (range_tree_first(queue->q_exts_by_addr));
2737 } else if (scn->scn_clearing) {
2738 return (avl_first(&queue->q_exts_by_size));
2745 scan_io_queues_run_one(void *arg)
2747 dsl_scan_io_queue_t *queue = arg;
2748 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
2749 boolean_t suspended = B_FALSE;
2750 range_seg_t *rs = NULL;
2751 scan_io_t *sio = NULL;
2753 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
2754 uint64_t nr_leaves = dsl_scan_count_leaves(queue->q_vd);
2756 ASSERT(queue->q_scn->scn_is_sorted);
2758 list_create(&sio_list, sizeof (scan_io_t),
2759 offsetof(scan_io_t, sio_nodes.sio_list_node));
2760 mutex_enter(q_lock);
2762 /* calculate maximum in-flight bytes for this txg (min 1MB) */
2763 queue->q_maxinflight_bytes =
2764 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
2766 /* reset per-queue scan statistics for this txg */
2767 queue->q_total_seg_size_this_txg = 0;
2768 queue->q_segs_this_txg = 0;
2769 queue->q_total_zio_size_this_txg = 0;
2770 queue->q_zios_this_txg = 0;
2772 /* loop until we have run out of time or sios */
2773 while ((rs = (range_seg_t*)scan_io_queue_fetch_ext(queue)) != NULL) {
2774 uint64_t seg_start = 0, seg_end = 0;
2775 boolean_t more_left = B_TRUE;
2777 ASSERT(list_is_empty(&sio_list));
2779 /* loop while we still have sios left to process in this rs */
2781 scan_io_t *first_sio, *last_sio;
2784 * We have selected which extent needs to be
2785 * processed next. Gather up the corresponding sios.
2787 more_left = scan_io_queue_gather(queue, rs, &sio_list);
2788 ASSERT(!list_is_empty(&sio_list));
2789 first_sio = list_head(&sio_list);
2790 last_sio = list_tail(&sio_list);
2792 seg_end = last_sio->sio_offset + last_sio->sio_asize;
2794 seg_start = first_sio->sio_offset;
2797 * Issuing sios can take a long time so drop the
2798 * queue lock. The sio queue won't be updated by
2799 * other threads since we're in syncing context so
2800 * we can be sure that our trees will remain exactly
2804 suspended = scan_io_queue_issue(queue, &sio_list);
2805 mutex_enter(q_lock);
2810 /* update statistics for debugging purposes */
2811 scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
2818 /* If we were suspended in the middle of processing,
2819 * requeue any unfinished sios and exit.
2821 while ((sio = list_head(&sio_list)) != NULL) {
2822 list_remove(&sio_list, sio);
2823 scan_io_queue_insert_impl(queue, sio);
2827 list_destroy(&sio_list);
2831 * Performs an emptying run on all scan queues in the pool. This just
2832 * punches out one thread per top-level vdev, each of which processes
2833 * only that vdev's scan queue. We can parallelize the I/O here because
2834 * we know that each queue's io's only affect its own top-level vdev.
2836 * This function waits for the queue runs to complete, and must be
2837 * called from dsl_scan_sync (or in general, syncing context).
2840 scan_io_queues_run(dsl_scan_t *scn)
2842 spa_t *spa = scn->scn_dp->dp_spa;
2844 ASSERT(scn->scn_is_sorted);
2845 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
2847 if (scn->scn_bytes_pending == 0)
2850 if (scn->scn_taskq == NULL) {
2851 char *tq_name = kmem_zalloc(ZFS_MAX_DATASET_NAME_LEN + 16,
2853 int nthreads = spa->spa_root_vdev->vdev_children;
2856 * We need to make this taskq *always* execute as many
2857 * threads in parallel as we have top-level vdevs and no
2858 * less, otherwise strange serialization of the calls to
2859 * scan_io_queues_run_one can occur during spa_sync runs
2860 * and that significantly impacts performance.
2862 (void) snprintf(tq_name, ZFS_MAX_DATASET_NAME_LEN + 16,
2863 "dsl_scan_tq_%s", spa->spa_name);
2864 scn->scn_taskq = taskq_create(tq_name, nthreads, minclsyspri,
2865 nthreads, nthreads, TASKQ_PREPOPULATE);
2866 kmem_free(tq_name, ZFS_MAX_DATASET_NAME_LEN + 16);
2869 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2870 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2872 mutex_enter(&vd->vdev_scan_io_queue_lock);
2873 if (vd->vdev_scan_io_queue != NULL) {
2874 VERIFY(taskq_dispatch(scn->scn_taskq,
2875 scan_io_queues_run_one, vd->vdev_scan_io_queue,
2876 TQ_SLEEP) != TASKQID_INVALID);
2878 mutex_exit(&vd->vdev_scan_io_queue_lock);
2882 * Wait for the queues to finish issuing thir IOs for this run
2883 * before we return. There may still be IOs in flight at this
2886 taskq_wait(scn->scn_taskq);
2890 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
2892 uint64_t elapsed_nanosecs;
2897 if (scn->scn_visited_this_txg >= zfs_async_block_max_blocks)
2900 elapsed_nanosecs = gethrtime() - scn->scn_sync_start_time;
2901 return (elapsed_nanosecs / NANOSEC > zfs_txg_timeout ||
2902 (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
2903 txg_sync_waiting(scn->scn_dp)) ||
2904 spa_shutting_down(scn->scn_dp->dp_spa));
2908 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2910 dsl_scan_t *scn = arg;
2912 if (!scn->scn_is_bptree ||
2913 (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
2914 if (dsl_scan_async_block_should_pause(scn))
2915 return (SET_ERROR(ERESTART));
2918 zio_nowait(zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
2919 dmu_tx_get_txg(tx), bp, BP_GET_PSIZE(bp), 0));
2920 dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
2921 -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
2922 -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
2923 scn->scn_visited_this_txg++;
2928 dsl_scan_update_stats(dsl_scan_t *scn)
2930 spa_t *spa = scn->scn_dp->dp_spa;
2932 uint64_t seg_size_total = 0, zio_size_total = 0;
2933 uint64_t seg_count_total = 0, zio_count_total = 0;
2935 for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
2936 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
2937 dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
2942 seg_size_total += queue->q_total_seg_size_this_txg;
2943 zio_size_total += queue->q_total_zio_size_this_txg;
2944 seg_count_total += queue->q_segs_this_txg;
2945 zio_count_total += queue->q_zios_this_txg;
2948 if (seg_count_total == 0 || zio_count_total == 0) {
2949 scn->scn_avg_seg_size_this_txg = 0;
2950 scn->scn_avg_zio_size_this_txg = 0;
2951 scn->scn_segs_this_txg = 0;
2952 scn->scn_zios_this_txg = 0;
2956 scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
2957 scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
2958 scn->scn_segs_this_txg = seg_count_total;
2959 scn->scn_zios_this_txg = zio_count_total;
2963 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2965 dsl_scan_t *scn = arg;
2966 const dva_t *dva = &bp->blk_dva[0];
2968 if (dsl_scan_async_block_should_pause(scn))
2969 return (SET_ERROR(ERESTART));
2971 spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
2972 DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
2973 DVA_GET_ASIZE(dva), tx);
2974 scn->scn_visited_this_txg++;
2979 dsl_scan_active(dsl_scan_t *scn)
2981 spa_t *spa = scn->scn_dp->dp_spa;
2982 uint64_t used = 0, comp, uncomp;
2984 if (spa->spa_load_state != SPA_LOAD_NONE)
2986 if (spa_shutting_down(spa))
2988 if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
2989 (scn->scn_async_destroying && !scn->scn_async_stalled))
2992 if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
2993 (void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
2994 &used, &comp, &uncomp);
3000 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
3001 uint64_t phys_birth)
3005 vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3007 if (vd->vdev_ops == &vdev_indirect_ops) {
3009 * The indirect vdev can point to multiple
3010 * vdevs. For simplicity, always create
3011 * the resilver zio_t. zio_vdev_io_start()
3012 * will bypass the child resilver i/o's if
3013 * they are on vdevs that don't have DTL's.
3018 if (DVA_GET_GANG(dva)) {
3020 * Gang members may be spread across multiple
3021 * vdevs, so the best estimate we have is the
3022 * scrub range, which has already been checked.
3023 * XXX -- it would be better to change our
3024 * allocation policy to ensure that all
3025 * gang members reside on the same vdev.
3031 * Check if the txg falls within the range which must be
3032 * resilvered. DVAs outside this range can always be skipped.
3034 if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
3038 * Check if the top-level vdev must resilver this offset.
3039 * When the offset does not intersect with a dirty leaf DTL
3040 * then it may be possible to skip the resilver IO. The psize
3041 * is provided instead of asize to simplify the check for RAIDZ.
3043 if (!vdev_dtl_need_resilver(vd, DVA_GET_OFFSET(dva), psize))
3050 dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)
3053 dsl_scan_t *scn = dp->dp_scan;
3054 spa_t *spa = dp->dp_spa;
3056 if (spa_suspend_async_destroy(spa))
3059 if (zfs_free_bpobj_enabled &&
3060 spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3061 scn->scn_is_bptree = B_FALSE;
3062 scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
3063 scn->scn_zio_root = zio_root(spa, NULL,
3064 NULL, ZIO_FLAG_MUSTSUCCEED);
3065 err = bpobj_iterate(&dp->dp_free_bpobj,
3066 dsl_scan_free_block_cb, scn, tx);
3067 VERIFY0(zio_wait(scn->scn_zio_root));
3068 scn->scn_zio_root = NULL;
3070 if (err != 0 && err != ERESTART)
3071 zfs_panic_recover("error %u from bpobj_iterate()", err);
3074 if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3075 ASSERT(scn->scn_async_destroying);
3076 scn->scn_is_bptree = B_TRUE;
3077 scn->scn_zio_root = zio_root(spa, NULL,
3078 NULL, ZIO_FLAG_MUSTSUCCEED);
3079 err = bptree_iterate(dp->dp_meta_objset,
3080 dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3081 VERIFY0(zio_wait(scn->scn_zio_root));
3082 scn->scn_zio_root = NULL;
3084 if (err == EIO || err == ECKSUM) {
3086 } else if (err != 0 && err != ERESTART) {
3087 zfs_panic_recover("error %u from "
3088 "traverse_dataset_destroyed()", err);
3091 if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
3092 /* finished; deactivate async destroy feature */
3093 spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
3094 ASSERT(!spa_feature_is_active(spa,
3095 SPA_FEATURE_ASYNC_DESTROY));
3096 VERIFY0(zap_remove(dp->dp_meta_objset,
3097 DMU_POOL_DIRECTORY_OBJECT,
3098 DMU_POOL_BPTREE_OBJ, tx));
3099 VERIFY0(bptree_free(dp->dp_meta_objset,
3100 dp->dp_bptree_obj, tx));
3101 dp->dp_bptree_obj = 0;
3102 scn->scn_async_destroying = B_FALSE;
3103 scn->scn_async_stalled = B_FALSE;
3106 * If we didn't make progress, mark the async
3107 * destroy as stalled, so that we will not initiate
3108 * a spa_sync() on its behalf. Note that we only
3109 * check this if we are not finished, because if the
3110 * bptree had no blocks for us to visit, we can
3111 * finish without "making progress".
3113 scn->scn_async_stalled =
3114 (scn->scn_visited_this_txg == 0);
3117 if (scn->scn_visited_this_txg) {
3118 zfs_dbgmsg("freed %llu blocks in %llums from "
3119 "free_bpobj/bptree txg %llu; err=%d",
3120 (longlong_t)scn->scn_visited_this_txg,
3122 NSEC2MSEC(gethrtime() - scn->scn_sync_start_time),
3123 (longlong_t)tx->tx_txg, err);
3124 scn->scn_visited_this_txg = 0;
3127 * Write out changes to the DDT that may be required as a
3128 * result of the blocks freed. This ensures that the DDT
3129 * is clean when a scrub/resilver runs.
3131 ddt_sync(spa, tx->tx_txg);
3135 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
3136 zfs_free_leak_on_eio &&
3137 (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
3138 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
3139 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
3141 * We have finished background destroying, but there is still
3142 * some space left in the dp_free_dir. Transfer this leaked
3143 * space to the dp_leak_dir.
3145 if (dp->dp_leak_dir == NULL) {
3146 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
3147 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
3149 VERIFY0(dsl_pool_open_special_dir(dp,
3150 LEAK_DIR_NAME, &dp->dp_leak_dir));
3151 rrw_exit(&dp->dp_config_rwlock, FTAG);
3153 dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
3154 dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3155 dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3156 dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3157 dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
3158 -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
3159 -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
3160 -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
3163 if (dp->dp_free_dir != NULL && !scn->scn_async_destroying) {
3164 /* finished; verify that space accounting went to zero */
3165 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
3166 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
3167 ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
3170 EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
3171 0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3172 DMU_POOL_OBSOLETE_BPOBJ));
3173 if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3174 ASSERT(spa_feature_is_active(dp->dp_spa,
3175 SPA_FEATURE_OBSOLETE_COUNTS));
3177 scn->scn_is_bptree = B_FALSE;
3178 scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
3179 err = bpobj_iterate(&dp->dp_obsolete_bpobj,
3180 dsl_scan_obsolete_block_cb, scn, tx);
3181 if (err != 0 && err != ERESTART)
3182 zfs_panic_recover("error %u from bpobj_iterate()", err);
3184 if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
3185 dsl_pool_destroy_obsolete_bpobj(dp, tx);
3192 * This is the primary entry point for scans that is called from syncing
3193 * context. Scans must happen entirely during syncing context so that we
3194 * cna guarantee that blocks we are currently scanning will not change out
3195 * from under us. While a scan is active, this funciton controls how quickly
3196 * transaction groups proceed, instead of the normal handling provided by
3197 * txg_sync_thread().
3200 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
3202 dsl_scan_t *scn = dp->dp_scan;
3203 spa_t *spa = dp->dp_spa;
3205 state_sync_type_t sync_type = SYNC_OPTIONAL;
3208 * Check for scn_restart_txg before checking spa_load_state, so
3209 * that we can restart an old-style scan while the pool is being
3210 * imported (see dsl_scan_init).
3212 if (dsl_scan_restarting(scn, tx)) {
3213 pool_scan_func_t func = POOL_SCAN_SCRUB;
3214 dsl_scan_done(scn, B_FALSE, tx);
3215 if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3216 func = POOL_SCAN_RESILVER;
3217 zfs_dbgmsg("restarting scan func=%u txg=%llu",
3218 func, (longlong_t)tx->tx_txg);
3219 dsl_scan_setup_sync(&func, tx);
3223 * Only process scans in sync pass 1.
3225 if (spa_sync_pass(dp->dp_spa) > 1)
3229 * If the spa is shutting down, then stop scanning. This will
3230 * ensure that the scan does not dirty any new data during the
3233 if (spa_shutting_down(spa))
3237 * If the scan is inactive due to a stalled async destroy, try again.
3239 if (!scn->scn_async_stalled && !dsl_scan_active(scn))
3242 /* reset scan statistics */
3243 scn->scn_visited_this_txg = 0;
3244 scn->scn_holes_this_txg = 0;
3245 scn->scn_lt_min_this_txg = 0;
3246 scn->scn_gt_max_this_txg = 0;
3247 scn->scn_ddt_contained_this_txg = 0;
3248 scn->scn_objsets_visited_this_txg = 0;
3249 scn->scn_avg_seg_size_this_txg = 0;
3250 scn->scn_segs_this_txg = 0;
3251 scn->scn_avg_zio_size_this_txg = 0;
3252 scn->scn_zios_this_txg = 0;
3253 scn->scn_suspending = B_FALSE;
3254 scn->scn_sync_start_time = gethrtime();
3255 spa->spa_scrub_active = B_TRUE;
3258 * First process the async destroys. If we pause, don't do
3259 * any scrubbing or resilvering. This ensures that there are no
3260 * async destroys while we are scanning, so the scan code doesn't
3261 * have to worry about traversing it. It is also faster to free the
3262 * blocks than to scrub them.
3264 err = dsl_process_async_destroys(dp, tx);
3268 if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
3272 * Wait a few txgs after importing to begin scanning so that
3273 * we can get the pool imported quickly.
3275 if (spa->spa_syncing_txg < spa->spa_first_txg + SCAN_IMPORT_WAIT_TXGS)
3279 * It is possible to switch from unsorted to sorted at any time,
3280 * but afterwards the scan will remain sorted unless reloaded from
3281 * a checkpoint after a reboot.
3283 if (!zfs_scan_legacy) {
3284 scn->scn_is_sorted = B_TRUE;
3285 if (scn->scn_last_checkpoint == 0)
3286 scn->scn_last_checkpoint = ddi_get_lbolt();
3290 * For sorted scans, determine what kind of work we will be doing
3291 * this txg based on our memory limitations and whether or not we
3292 * need to perform a checkpoint.
3294 if (scn->scn_is_sorted) {
3296 * If we are over our checkpoint interval, set scn_clearing
3297 * so that we can begin checkpointing immediately. The
3298 * checkpoint allows us to save a consisent bookmark
3299 * representing how much data we have scrubbed so far.
3300 * Otherwise, use the memory limit to determine if we should
3301 * scan for metadata or start issue scrub IOs. We accumulate
3302 * metadata until we hit our hard memory limit at which point
3303 * we issue scrub IOs until we are at our soft memory limit.
3305 if (scn->scn_checkpointing ||
3306 ddi_get_lbolt() - scn->scn_last_checkpoint >
3307 SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
3308 if (!scn->scn_checkpointing)
3309 zfs_dbgmsg("begin scan checkpoint");
3311 scn->scn_checkpointing = B_TRUE;
3312 scn->scn_clearing = B_TRUE;
3314 boolean_t should_clear = dsl_scan_should_clear(scn);
3315 if (should_clear && !scn->scn_clearing) {
3316 zfs_dbgmsg("begin scan clearing");
3317 scn->scn_clearing = B_TRUE;
3318 } else if (!should_clear && scn->scn_clearing) {
3319 zfs_dbgmsg("finish scan clearing");
3320 scn->scn_clearing = B_FALSE;
3324 ASSERT0(scn->scn_checkpointing);
3325 ASSERT0(scn->scn_clearing);
3328 if (!scn->scn_clearing && scn->scn_done_txg == 0) {
3329 /* Need to scan metadata for more blocks to scrub */
3330 dsl_scan_phys_t *scnp = &scn->scn_phys;
3331 taskqid_t prefetch_tqid;
3332 uint64_t bytes_per_leaf = zfs_scan_vdev_limit;
3333 uint64_t nr_leaves = dsl_scan_count_leaves(spa->spa_root_vdev);
3336 * Calculate the max number of in-flight bytes for pool-wide
3337 * scanning operations (minimum 1MB). Limits for the issuing
3338 * phase are done per top-level vdev and are handled separately.
3340 scn->scn_maxinflight_bytes =
3341 MAX(nr_leaves * bytes_per_leaf, 1ULL << 20);
3343 if (scnp->scn_ddt_bookmark.ddb_class <=
3344 scnp->scn_ddt_class_max) {
3345 ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
3346 zfs_dbgmsg("doing scan sync txg %llu; "
3347 "ddt bm=%llu/%llu/%llu/%llx",
3348 (longlong_t)tx->tx_txg,
3349 (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
3350 (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
3351 (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
3352 (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
3354 zfs_dbgmsg("doing scan sync txg %llu; "
3355 "bm=%llu/%llu/%llu/%llu",
3356 (longlong_t)tx->tx_txg,
3357 (longlong_t)scnp->scn_bookmark.zb_objset,
3358 (longlong_t)scnp->scn_bookmark.zb_object,
3359 (longlong_t)scnp->scn_bookmark.zb_level,
3360 (longlong_t)scnp->scn_bookmark.zb_blkid);
3363 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3364 NULL, ZIO_FLAG_CANFAIL);
3366 scn->scn_prefetch_stop = B_FALSE;
3367 prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
3368 dsl_scan_prefetch_thread, scn, TQ_SLEEP);
3369 ASSERT(prefetch_tqid != TASKQID_INVALID);
3371 dsl_pool_config_enter(dp, FTAG);
3372 dsl_scan_visit(scn, tx);
3373 dsl_pool_config_exit(dp, FTAG);
3375 mutex_enter(&dp->dp_spa->spa_scrub_lock);
3376 scn->scn_prefetch_stop = B_TRUE;
3377 cv_broadcast(&spa->spa_scrub_io_cv);
3378 mutex_exit(&dp->dp_spa->spa_scrub_lock);
3380 taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
3381 (void) zio_wait(scn->scn_zio_root);
3382 scn->scn_zio_root = NULL;
3384 zfs_dbgmsg("scan visited %llu blocks in %llums "
3385 "(%llu os's, %llu holes, %llu < mintxg, "
3386 "%llu in ddt, %llu > maxtxg)",
3387 (longlong_t)scn->scn_visited_this_txg,
3388 (longlong_t)NSEC2MSEC(gethrtime() -
3389 scn->scn_sync_start_time),
3390 (longlong_t)scn->scn_objsets_visited_this_txg,
3391 (longlong_t)scn->scn_holes_this_txg,
3392 (longlong_t)scn->scn_lt_min_this_txg,
3393 (longlong_t)scn->scn_ddt_contained_this_txg,
3394 (longlong_t)scn->scn_gt_max_this_txg);
3396 if (!scn->scn_suspending) {
3397 ASSERT0(avl_numnodes(&scn->scn_queue));
3398 scn->scn_done_txg = tx->tx_txg + 1;
3399 if (scn->scn_is_sorted) {
3400 scn->scn_checkpointing = B_TRUE;
3401 scn->scn_clearing = B_TRUE;
3403 zfs_dbgmsg("scan complete txg %llu",
3404 (longlong_t)tx->tx_txg);
3406 } else if (scn->scn_is_sorted && scn->scn_bytes_pending != 0) {
3407 /* need to issue scrubbing IOs from per-vdev queues */
3408 scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
3409 NULL, ZIO_FLAG_CANFAIL);
3410 scan_io_queues_run(scn);
3411 (void) zio_wait(scn->scn_zio_root);
3412 scn->scn_zio_root = NULL;
3414 /* calculate and dprintf the current memory usage */
3415 (void) dsl_scan_should_clear(scn);
3416 dsl_scan_update_stats(scn);
3418 zfs_dbgmsg("scrubbed %llu blocks (%llu segs) in %llums "
3419 "(avg_block_size = %llu, avg_seg_size = %llu)",
3420 (longlong_t)scn->scn_zios_this_txg,
3421 (longlong_t)scn->scn_segs_this_txg,
3422 (longlong_t)NSEC2MSEC(gethrtime() -
3423 scn->scn_sync_start_time),
3424 (longlong_t)scn->scn_avg_zio_size_this_txg,
3425 (longlong_t)scn->scn_avg_seg_size_this_txg);
3426 } else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
3427 /* Finished with everything. Mark the scrub as complete */
3428 zfs_dbgmsg("scan issuing complete txg %llu",
3429 (longlong_t)tx->tx_txg);
3430 ASSERT3U(scn->scn_done_txg, !=, 0);
3431 ASSERT0(spa->spa_scrub_inflight);
3432 ASSERT0(scn->scn_bytes_pending);
3433 dsl_scan_done(scn, B_TRUE, tx);
3434 sync_type = SYNC_MANDATORY;
3437 dsl_scan_sync_state(scn, tx, sync_type);
3441 count_block(dsl_scan_t *scn, zfs_all_blkstats_t *zab, const blkptr_t *bp)
3445 /* update the spa's stats on how many bytes we have issued */
3446 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3447 atomic_add_64(&scn->scn_dp->dp_spa->spa_scan_pass_issued,
3448 DVA_GET_ASIZE(&bp->blk_dva[i]));
3452 * If we resume after a reboot, zab will be NULL; don't record
3453 * incomplete stats in that case.
3458 mutex_enter(&zab->zab_lock);
3460 for (i = 0; i < 4; i++) {
3461 int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
3462 int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
3463 if (t & DMU_OT_NEWTYPE)
3465 zfs_blkstat_t *zb = &zab->zab_type[l][t];
3469 zb->zb_asize += BP_GET_ASIZE(bp);
3470 zb->zb_lsize += BP_GET_LSIZE(bp);
3471 zb->zb_psize += BP_GET_PSIZE(bp);
3472 zb->zb_gangs += BP_COUNT_GANG(bp);
3474 switch (BP_GET_NDVAS(bp)) {
3476 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3477 DVA_GET_VDEV(&bp->blk_dva[1]))
3478 zb->zb_ditto_2_of_2_samevdev++;
3481 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3482 DVA_GET_VDEV(&bp->blk_dva[1])) +
3483 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3484 DVA_GET_VDEV(&bp->blk_dva[2])) +
3485 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3486 DVA_GET_VDEV(&bp->blk_dva[2]));
3488 zb->zb_ditto_2_of_3_samevdev++;
3489 else if (equal == 3)
3490 zb->zb_ditto_3_of_3_samevdev++;
3495 mutex_exit(&zab->zab_lock);
3499 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
3502 int64_t asize = sio->sio_asize;
3503 dsl_scan_t *scn = queue->q_scn;
3505 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3507 if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
3508 /* block is already scheduled for reading */
3509 atomic_add_64(&scn->scn_bytes_pending, -asize);
3510 kmem_free(sio, sizeof (*sio));
3513 avl_insert(&queue->q_sios_by_addr, sio, idx);
3514 range_tree_add(queue->q_exts_by_addr, sio->sio_offset, asize);
3518 * Given all the info we got from our metadata scanning process, we
3519 * construct a scan_io_t and insert it into the scan sorting queue. The
3520 * I/O must already be suitable for us to process. This is controlled
3521 * by dsl_scan_enqueue().
3524 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
3525 int zio_flags, const zbookmark_phys_t *zb)
3527 dsl_scan_t *scn = queue->q_scn;
3528 scan_io_t *sio = kmem_zalloc(sizeof (*sio), KM_SLEEP);
3530 ASSERT0(BP_IS_GANG(bp));
3531 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3533 bp2sio(bp, sio, dva_i);
3534 sio->sio_flags = zio_flags;
3538 * Increment the bytes pending counter now so that we can't
3539 * get an integer underflow in case the worker processes the
3540 * zio before we get to incrementing this counter.
3542 atomic_add_64(&scn->scn_bytes_pending, sio->sio_asize);
3544 scan_io_queue_insert_impl(queue, sio);
3548 * Given a set of I/O parameters as discovered by the metadata traversal
3549 * process, attempts to place the I/O into the sorted queues (if allowed),
3550 * or immediately executes the I/O.
3553 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3554 const zbookmark_phys_t *zb)
3556 spa_t *spa = dp->dp_spa;
3558 ASSERT(!BP_IS_EMBEDDED(bp));
3561 * Gang blocks are hard to issue sequentially, so we just issue them
3562 * here immediately instead of queuing them.
3564 if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
3565 scan_exec_io(dp, bp, zio_flags, zb, NULL);
3568 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
3572 dva = bp->blk_dva[i];
3573 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
3574 ASSERT(vdev != NULL);
3576 mutex_enter(&vdev->vdev_scan_io_queue_lock);
3577 if (vdev->vdev_scan_io_queue == NULL)
3578 vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
3579 ASSERT(dp->dp_scan != NULL);
3580 scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
3582 mutex_exit(&vdev->vdev_scan_io_queue_lock);
3587 dsl_scan_scrub_cb(dsl_pool_t *dp,
3588 const blkptr_t *bp, const zbookmark_phys_t *zb)
3590 dsl_scan_t *scn = dp->dp_scan;
3591 spa_t *spa = dp->dp_spa;
3592 uint64_t phys_birth = BP_PHYSICAL_BIRTH(bp);
3593 size_t psize = BP_GET_PSIZE(bp);
3595 int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL;
3598 if (phys_birth <= scn->scn_phys.scn_min_txg ||
3599 phys_birth >= scn->scn_phys.scn_max_txg) {
3600 count_block(scn, dp->dp_blkstats, bp);
3604 /* Embedded BP's have phys_birth==0, so we reject them above. */
3605 ASSERT(!BP_IS_EMBEDDED(bp));
3607 ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
3608 if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
3609 zio_flags |= ZIO_FLAG_SCRUB;
3612 ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
3613 zio_flags |= ZIO_FLAG_RESILVER;
3617 /* If it's an intent log block, failure is expected. */
3618 if (zb->zb_level == ZB_ZIL_LEVEL)
3619 zio_flags |= ZIO_FLAG_SPECULATIVE;
3621 for (d = 0; d < BP_GET_NDVAS(bp); d++) {
3622 const dva_t *dva = &bp->blk_dva[d];
3625 * Keep track of how much data we've examined so that
3626 * zpool(1M) status can make useful progress reports.
3628 scn->scn_phys.scn_examined += DVA_GET_ASIZE(dva);
3629 spa->spa_scan_pass_exam += DVA_GET_ASIZE(dva);
3631 /* if it's a resilver, this may not be in the target range */
3633 needs_io = dsl_scan_need_resilver(spa, dva, psize,
3637 if (needs_io && !zfs_no_scrub_io) {
3638 dsl_scan_enqueue(dp, bp, zio_flags, zb);
3640 count_block(scn, dp->dp_blkstats, bp);
3643 /* do not relocate this block */
3648 dsl_scan_scrub_done(zio_t *zio)
3650 spa_t *spa = zio->io_spa;
3651 blkptr_t *bp = zio->io_bp;
3652 dsl_scan_io_queue_t *queue = zio->io_private;
3654 abd_free(zio->io_abd);
3656 if (queue == NULL) {
3657 mutex_enter(&spa->spa_scrub_lock);
3658 ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
3659 spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
3660 cv_broadcast(&spa->spa_scrub_io_cv);
3661 mutex_exit(&spa->spa_scrub_lock);
3663 mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
3664 ASSERT3U(queue->q_inflight_bytes, >=, BP_GET_PSIZE(bp));
3665 queue->q_inflight_bytes -= BP_GET_PSIZE(bp);
3666 cv_broadcast(&queue->q_zio_cv);
3667 mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
3670 if (zio->io_error && (zio->io_error != ECKSUM ||
3671 !(zio->io_flags & ZIO_FLAG_SPECULATIVE))) {
3672 atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys.scn_errors);
3677 * Given a scanning zio's information, executes the zio. The zio need
3678 * not necessarily be only sortable, this function simply executes the
3679 * zio, no matter what it is. The optional queue argument allows the
3680 * caller to specify that they want per top level vdev IO rate limiting
3681 * instead of the legacy global limiting.
3684 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
3685 const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
3687 spa_t *spa = dp->dp_spa;
3688 dsl_scan_t *scn = dp->dp_scan;
3689 size_t size = BP_GET_PSIZE(bp);
3690 abd_t *data = abd_alloc_for_io(size, B_FALSE);
3691 unsigned int scan_delay = 0;
3693 if (queue == NULL) {
3694 mutex_enter(&spa->spa_scrub_lock);
3695 while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
3696 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3697 spa->spa_scrub_inflight += BP_GET_PSIZE(bp);
3698 mutex_exit(&spa->spa_scrub_lock);
3700 kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
3702 mutex_enter(q_lock);
3703 while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
3704 cv_wait(&queue->q_zio_cv, q_lock);
3705 queue->q_inflight_bytes += BP_GET_PSIZE(bp);
3709 if (zio_flags & ZIO_FLAG_RESILVER)
3710 scan_delay = zfs_resilver_delay;
3712 ASSERT(zio_flags & ZIO_FLAG_SCRUB);
3713 scan_delay = zfs_scrub_delay;
3716 if (scan_delay && (ddi_get_lbolt64() - spa->spa_last_io <= zfs_scan_idle))
3717 delay(MAX((int)scan_delay, 0));
3719 count_block(dp->dp_scan, dp->dp_blkstats, bp);
3720 zio_nowait(zio_read(dp->dp_scan->scn_zio_root, spa, bp, data, size,
3721 dsl_scan_scrub_done, queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
3725 * This is the primary extent sorting algorithm. We balance two parameters:
3726 * 1) how many bytes of I/O are in an extent
3727 * 2) how well the extent is filled with I/O (as a fraction of its total size)
3728 * Since we allow extents to have gaps between their constituent I/Os, it's
3729 * possible to have a fairly large extent that contains the same amount of
3730 * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
3731 * The algorithm sorts based on a score calculated from the extent's size,
3732 * the relative fill volume (in %) and a "fill weight" parameter that controls
3733 * the split between whether we prefer larger extents or more well populated
3736 * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
3739 * 1) assume extsz = 64 MiB
3740 * 2) assume fill = 32 MiB (extent is half full)
3741 * 3) assume fill_weight = 3
3742 * 4) SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
3743 * SCORE = 32M + (50 * 3 * 32M) / 100
3744 * SCORE = 32M + (4800M / 100)
3747 * | +--- final total relative fill-based score
3748 * +--------- final total fill-based score
3751 * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
3752 * extents that are more completely filled (in a 3:2 ratio) vs just larger.
3753 * Note that as an optimization, we replace multiplication and division by
3754 * 100 with bitshifting by 7 (which effecitvely multiplies and divides by 128).
3757 ext_size_compare(const void *x, const void *y)
3759 const range_seg_t *rsa = x, *rsb = y;
3760 uint64_t sa = rsa->rs_end - rsa->rs_start,
3761 sb = rsb->rs_end - rsb->rs_start;
3762 uint64_t score_a, score_b;
3764 score_a = rsa->rs_fill + ((((rsa->rs_fill << 7) / sa) *
3765 fill_weight * rsa->rs_fill) >> 7);
3766 score_b = rsb->rs_fill + ((((rsb->rs_fill << 7) / sb) *
3767 fill_weight * rsb->rs_fill) >> 7);
3769 if (score_a > score_b)
3771 if (score_a == score_b) {
3772 if (rsa->rs_start < rsb->rs_start)
3774 if (rsa->rs_start == rsb->rs_start)
3782 * Comparator for the q_sios_by_addr tree. Sorting is simply performed
3783 * based on LBA-order (from lowest to highest).
3786 io_addr_compare(const void *x, const void *y)
3788 const scan_io_t *a = x, *b = y;
3790 if (a->sio_offset < b->sio_offset)
3792 if (a->sio_offset == b->sio_offset)
3797 /* IO queues are created on demand when they are needed. */
3798 static dsl_scan_io_queue_t *
3799 scan_io_queue_create(vdev_t *vd)
3801 dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
3802 dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
3806 cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
3807 q->q_exts_by_addr = range_tree_create_impl(&rt_avl_ops,
3808 &q->q_exts_by_size, ext_size_compare, zfs_scan_max_ext_gap);
3809 avl_create(&q->q_sios_by_addr, io_addr_compare,
3810 sizeof (scan_io_t), offsetof(scan_io_t, sio_nodes.sio_addr_node));
3816 * Destroys a scan queue and all segments and scan_io_t's contained in it.
3817 * No further execution of I/O occurs, anything pending in the queue is
3818 * simply freed without being executed.
3821 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
3823 dsl_scan_t *scn = queue->q_scn;
3825 void *cookie = NULL;
3826 int64_t bytes_dequeued = 0;
3828 ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3830 while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
3832 ASSERT(range_tree_contains(queue->q_exts_by_addr,
3833 sio->sio_offset, sio->sio_asize));
3834 bytes_dequeued += sio->sio_asize;
3835 kmem_free(sio, sizeof (*sio));
3838 atomic_add_64(&scn->scn_bytes_pending, -bytes_dequeued);
3839 range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
3840 range_tree_destroy(queue->q_exts_by_addr);
3841 avl_destroy(&queue->q_sios_by_addr);
3842 cv_destroy(&queue->q_zio_cv);
3844 kmem_free(queue, sizeof (*queue));
3848 * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
3849 * called on behalf of vdev_top_transfer when creating or destroying
3850 * a mirror vdev due to zpool attach/detach.
3853 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
3855 mutex_enter(&svd->vdev_scan_io_queue_lock);
3856 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3858 VERIFY3P(tvd->vdev_scan_io_queue, ==, NULL);
3859 tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
3860 svd->vdev_scan_io_queue = NULL;
3861 if (tvd->vdev_scan_io_queue != NULL)
3862 tvd->vdev_scan_io_queue->q_vd = tvd;
3864 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3865 mutex_exit(&svd->vdev_scan_io_queue_lock);
3869 scan_io_queues_destroy(dsl_scan_t *scn)
3871 vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
3873 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3874 vdev_t *tvd = rvd->vdev_child[i];
3876 mutex_enter(&tvd->vdev_scan_io_queue_lock);
3877 if (tvd->vdev_scan_io_queue != NULL)
3878 dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
3879 tvd->vdev_scan_io_queue = NULL;
3880 mutex_exit(&tvd->vdev_scan_io_queue_lock);
3885 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
3887 dsl_pool_t *dp = spa->spa_dsl_pool;
3888 dsl_scan_t *scn = dp->dp_scan;
3891 dsl_scan_io_queue_t *queue;
3892 scan_io_t srch, *sio;
3894 uint64_t start, size;
3896 vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
3897 ASSERT(vdev != NULL);
3898 q_lock = &vdev->vdev_scan_io_queue_lock;
3899 queue = vdev->vdev_scan_io_queue;
3901 mutex_enter(q_lock);
3902 if (queue == NULL) {
3907 bp2sio(bp, &srch, dva_i);
3908 start = srch.sio_offset;
3909 size = srch.sio_asize;
3912 * We can find the zio in two states:
3913 * 1) Cold, just sitting in the queue of zio's to be issued at
3914 * some point in the future. In this case, all we do is
3915 * remove the zio from the q_sios_by_addr tree, decrement
3916 * its data volume from the containing range_seg_t and
3917 * resort the q_exts_by_size tree to reflect that the
3918 * range_seg_t has lost some of its 'fill'. We don't shorten
3919 * the range_seg_t - this is usually rare enough not to be
3920 * worth the extra hassle of trying keep track of precise
3921 * extent boundaries.
3922 * 2) Hot, where the zio is currently in-flight in
3923 * dsl_scan_issue_ios. In this case, we can't simply
3924 * reach in and stop the in-flight zio's, so we instead
3925 * block the caller. Eventually, dsl_scan_issue_ios will
3926 * be done with issuing the zio's it gathered and will
3929 sio = avl_find(&queue->q_sios_by_addr, &srch, &idx);
3931 int64_t asize = sio->sio_asize;
3934 /* Got it while it was cold in the queue */
3935 ASSERT3U(start, ==, sio->sio_offset);
3936 ASSERT3U(size, ==, asize);
3937 avl_remove(&queue->q_sios_by_addr, sio);
3939 ASSERT(range_tree_contains(queue->q_exts_by_addr, start, size));
3940 range_tree_remove_fill(queue->q_exts_by_addr, start, size);
3943 * We only update scn_bytes_pending in the cold path,
3944 * otherwise it will already have been accounted for as
3945 * part of the zio's execution.
3947 atomic_add_64(&scn->scn_bytes_pending, -asize);
3949 /* count the block as though we issued it */
3950 sio2bp(sio, &tmpbp, dva_i);
3951 count_block(scn, dp->dp_blkstats, &tmpbp);
3953 kmem_free(sio, sizeof (*sio));
3959 * Callback invoked when a zio_free() zio is executing. This needs to be
3960 * intercepted to prevent the zio from deallocating a particular portion
3961 * of disk space and it then getting reallocated and written to, while we
3962 * still have it queued up for processing.
3965 dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
3967 dsl_pool_t *dp = spa->spa_dsl_pool;
3968 dsl_scan_t *scn = dp->dp_scan;
3970 ASSERT(!BP_IS_EMBEDDED(bp));
3971 ASSERT(scn != NULL);
3972 if (!dsl_scan_is_running(scn))
3975 for (int i = 0; i < BP_GET_NDVAS(bp); i++)
3976 dsl_scan_freed_dva(spa, bp, i);