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