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