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