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