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