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