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