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