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