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