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