xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_scan.c (revision 2f10ffc003be396f3fc23cd2888023896560252b)
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 		/*
1316 		 * The new state, and the config and labels updated above,
1317 		 * reach disk when this txg syncs.  Note it so that
1318 		 * "zpool wait" does not return before then.
1319 		 */
1320 		scn->scn_finished_txg = tx->tx_txg;
1321 		spa->spa_scrub_started = B_FALSE;
1322 
1323 		/*
1324 		 * We may have finished replacing a device.
1325 		 * Let the async thread assess this and handle the detach.
1326 		 */
1327 		spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
1328 
1329 		/*
1330 		 * Clear any resilver_deferred flags in the config.
1331 		 * If there are drives that need resilvering, kick
1332 		 * off an asynchronous request to start resilver.
1333 		 * vdev_clear_resilver_deferred() may update the config
1334 		 * before the resilver can restart. In the event of
1335 		 * a crash during this period, the spa loading code
1336 		 * will find the drives that need to be resilvered
1337 		 * and start the resilver then.
1338 		 */
1339 		if (spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER) &&
1340 		    vdev_clear_resilver_deferred(spa->spa_root_vdev, tx)) {
1341 			spa_history_log_internal(spa,
1342 			    "starting deferred resilver", tx, "errors=%llu",
1343 			    (u_longlong_t)spa_approx_errlog_size(spa));
1344 			spa_async_request(spa, SPA_ASYNC_RESILVER);
1345 		}
1346 
1347 		/* Clear recent error events (i.e. duplicate events tracking) */
1348 		if (complete)
1349 			zfs_ereport_clear(spa, NULL);
1350 	} else {
1351 		scn->scn_phys.scn_state = complete ? DSS_FINISHED :
1352 		    DSS_CANCELED;
1353 		scn->scn_phys.scn_end_time = gethrestime_sec();
1354 		scn->scn_finished_txg = tx->tx_txg;
1355 	}
1356 
1357 	spa_notify_waiters(spa);
1358 
1359 	if (spa->spa_errata == ZPOOL_ERRATA_ZOL_2094_SCRUB)
1360 		spa->spa_errata = 0;
1361 
1362 	ASSERT(!dsl_scan_is_running(scn));
1363 }
1364 
1365 static int
dsl_errorscrub_pause_resume_check(void * arg,dmu_tx_t * tx)1366 dsl_errorscrub_pause_resume_check(void *arg, dmu_tx_t *tx)
1367 {
1368 	pool_scrub_cmd_t *cmd = arg;
1369 	dsl_pool_t *dp = dmu_tx_pool(tx);
1370 	dsl_scan_t *scn = dp->dp_scan;
1371 
1372 	if (*cmd == POOL_SCRUB_PAUSE) {
1373 		/*
1374 		 * can't pause a error scrub when there is no in-progress
1375 		 * error scrub.
1376 		 */
1377 		if (!dsl_errorscrubbing(dp))
1378 			return (SET_ERROR(ENOENT));
1379 
1380 		/* can't pause a paused error scrub */
1381 		if (dsl_errorscrub_is_paused(scn))
1382 			return (SET_ERROR(EBUSY));
1383 	} else if (*cmd != POOL_SCRUB_NORMAL) {
1384 		return (SET_ERROR(ENOTSUP));
1385 	}
1386 
1387 	return (0);
1388 }
1389 
1390 static void
dsl_errorscrub_pause_resume_sync(void * arg,dmu_tx_t * tx)1391 dsl_errorscrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
1392 {
1393 	pool_scrub_cmd_t *cmd = arg;
1394 	dsl_pool_t *dp = dmu_tx_pool(tx);
1395 	spa_t *spa = dp->dp_spa;
1396 	dsl_scan_t *scn = dp->dp_scan;
1397 
1398 	if (*cmd == POOL_SCRUB_PAUSE) {
1399 		spa->spa_scan_pass_errorscrub_pause = gethrestime_sec();
1400 		scn->errorscrub_phys.dep_paused_flags = B_TRUE;
1401 		dsl_errorscrub_sync_state(scn, tx);
1402 		zap_cursor_fini(&scn->errorscrub_cursor);
1403 		spa_event_notify(spa, NULL, NULL, ESC_ZFS_ERRORSCRUB_PAUSED);
1404 	} else {
1405 		ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
1406 		if (dsl_errorscrub_is_paused(scn)) {
1407 			/*
1408 			 * We need to keep track of how much time we spend
1409 			 * paused per pass so that we can adjust the error scrub
1410 			 * rate shown in the output of 'zpool status'.
1411 			 */
1412 			spa->spa_scan_pass_errorscrub_spent_paused +=
1413 			    gethrestime_sec() -
1414 			    spa->spa_scan_pass_errorscrub_pause;
1415 
1416 			spa->spa_scan_pass_errorscrub_pause = 0;
1417 			scn->errorscrub_phys.dep_paused_flags = B_FALSE;
1418 
1419 			zap_cursor_init_serialized(
1420 			    &scn->errorscrub_cursor,
1421 			    spa->spa_meta_objset, spa->spa_errlog_last,
1422 			    scn->errorscrub_phys.dep_cursor);
1423 
1424 			dsl_errorscrub_sync_state(scn, tx);
1425 		}
1426 	}
1427 }
1428 
1429 static int
dsl_errorscrub_cancel_check(void * arg,dmu_tx_t * tx)1430 dsl_errorscrub_cancel_check(void *arg, dmu_tx_t *tx)
1431 {
1432 	(void) arg;
1433 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1434 	/* can't cancel a error scrub when there is no one in-progress */
1435 	if (!dsl_errorscrubbing(scn->scn_dp))
1436 		return (SET_ERROR(ENOENT));
1437 	return (0);
1438 }
1439 
1440 static void
dsl_errorscrub_cancel_sync(void * arg,dmu_tx_t * tx)1441 dsl_errorscrub_cancel_sync(void *arg, dmu_tx_t *tx)
1442 {
1443 	(void) arg;
1444 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1445 
1446 	dsl_errorscrub_done(scn, B_FALSE, tx);
1447 	dsl_errorscrub_sync_state(scn, tx);
1448 	spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL,
1449 	    ESC_ZFS_ERRORSCRUB_ABORT);
1450 }
1451 
1452 static int
dsl_scan_cancel_check(void * arg,dmu_tx_t * tx)1453 dsl_scan_cancel_check(void *arg, dmu_tx_t *tx)
1454 {
1455 	(void) arg;
1456 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1457 
1458 	if (!dsl_scan_is_running(scn))
1459 		return (SET_ERROR(ENOENT));
1460 	return (0);
1461 }
1462 
1463 static void
dsl_scan_cancel_sync(void * arg,dmu_tx_t * tx)1464 dsl_scan_cancel_sync(void *arg, dmu_tx_t *tx)
1465 {
1466 	(void) arg;
1467 	dsl_scan_t *scn = dmu_tx_pool(tx)->dp_scan;
1468 
1469 	dsl_scan_done(scn, B_FALSE, tx);
1470 	dsl_scan_sync_state(scn, tx, SYNC_MANDATORY);
1471 	spa_event_notify(scn->scn_dp->dp_spa, NULL, NULL, ESC_ZFS_SCRUB_ABORT);
1472 }
1473 
1474 int
dsl_scan_cancel(dsl_pool_t * dp)1475 dsl_scan_cancel(dsl_pool_t *dp)
1476 {
1477 	if (dsl_errorscrubbing(dp)) {
1478 		return (dsl_sync_task(spa_name(dp->dp_spa),
1479 		    dsl_errorscrub_cancel_check, dsl_errorscrub_cancel_sync,
1480 		    NULL, 3, ZFS_SPACE_CHECK_RESERVED));
1481 	}
1482 	return (dsl_sync_task(spa_name(dp->dp_spa), dsl_scan_cancel_check,
1483 	    dsl_scan_cancel_sync, NULL, 3, ZFS_SPACE_CHECK_RESERVED));
1484 }
1485 
1486 static int
dsl_scrub_pause_resume_check(void * arg,dmu_tx_t * tx)1487 dsl_scrub_pause_resume_check(void *arg, dmu_tx_t *tx)
1488 {
1489 	pool_scrub_cmd_t *cmd = arg;
1490 	dsl_pool_t *dp = dmu_tx_pool(tx);
1491 	dsl_scan_t *scn = dp->dp_scan;
1492 
1493 	if (*cmd == POOL_SCRUB_PAUSE) {
1494 		/* can't pause a scrub when there is no in-progress scrub */
1495 		if (!dsl_scan_scrubbing(dp))
1496 			return (SET_ERROR(ENOENT));
1497 
1498 		/* can't pause a paused scrub */
1499 		if (dsl_scan_is_paused_scrub(scn))
1500 			return (SET_ERROR(EBUSY));
1501 	} else if (*cmd != POOL_SCRUB_NORMAL) {
1502 		return (SET_ERROR(ENOTSUP));
1503 	}
1504 
1505 	return (0);
1506 }
1507 
1508 static void
dsl_scrub_pause_resume_sync(void * arg,dmu_tx_t * tx)1509 dsl_scrub_pause_resume_sync(void *arg, dmu_tx_t *tx)
1510 {
1511 	pool_scrub_cmd_t *cmd = arg;
1512 	dsl_pool_t *dp = dmu_tx_pool(tx);
1513 	spa_t *spa = dp->dp_spa;
1514 	dsl_scan_t *scn = dp->dp_scan;
1515 
1516 	if (*cmd == POOL_SCRUB_PAUSE) {
1517 		/* can't pause a scrub when there is no in-progress scrub */
1518 		spa->spa_scan_pass_scrub_pause = gethrestime_sec();
1519 		scn->scn_phys.scn_flags |= DSF_SCRUB_PAUSED;
1520 		scn->scn_phys_cached.scn_flags |= DSF_SCRUB_PAUSED;
1521 		dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1522 		spa_event_notify(spa, NULL, NULL, ESC_ZFS_SCRUB_PAUSED);
1523 		spa_notify_waiters(spa);
1524 	} else {
1525 		ASSERT3U(*cmd, ==, POOL_SCRUB_NORMAL);
1526 		if (dsl_scan_is_paused_scrub(scn)) {
1527 			/*
1528 			 * We need to keep track of how much time we spend
1529 			 * paused per pass so that we can adjust the scrub rate
1530 			 * shown in the output of 'zpool status'
1531 			 */
1532 			spa->spa_scan_pass_scrub_spent_paused +=
1533 			    gethrestime_sec() - spa->spa_scan_pass_scrub_pause;
1534 			spa->spa_scan_pass_scrub_pause = 0;
1535 			scn->scn_phys.scn_flags &= ~DSF_SCRUB_PAUSED;
1536 			scn->scn_phys_cached.scn_flags &= ~DSF_SCRUB_PAUSED;
1537 			dsl_scan_sync_state(scn, tx, SYNC_CACHED);
1538 		}
1539 	}
1540 }
1541 
1542 /*
1543  * Set scrub pause/resume state if it makes sense to do so
1544  */
1545 int
dsl_scrub_set_pause_resume(const dsl_pool_t * dp,pool_scrub_cmd_t cmd)1546 dsl_scrub_set_pause_resume(const dsl_pool_t *dp, pool_scrub_cmd_t cmd)
1547 {
1548 	if (dsl_errorscrubbing(dp)) {
1549 		return (dsl_sync_task(spa_name(dp->dp_spa),
1550 		    dsl_errorscrub_pause_resume_check,
1551 		    dsl_errorscrub_pause_resume_sync, &cmd, 3,
1552 		    ZFS_SPACE_CHECK_RESERVED));
1553 	}
1554 	return (dsl_sync_task(spa_name(dp->dp_spa),
1555 	    dsl_scrub_pause_resume_check, dsl_scrub_pause_resume_sync, &cmd, 3,
1556 	    ZFS_SPACE_CHECK_RESERVED));
1557 }
1558 
1559 
1560 /* start a new scan, or restart an existing one. */
1561 void
dsl_scan_restart_resilver(dsl_pool_t * dp,uint64_t txg)1562 dsl_scan_restart_resilver(dsl_pool_t *dp, uint64_t txg)
1563 {
1564 	if (txg == 0) {
1565 		dmu_tx_t *tx;
1566 		tx = dmu_tx_create_dd(dp->dp_mos_dir);
1567 		VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
1568 
1569 		txg = dmu_tx_get_txg(tx);
1570 		dp->dp_scan->scn_restart_txg = txg;
1571 		dmu_tx_commit(tx);
1572 	} else {
1573 		dp->dp_scan->scn_restart_txg = txg;
1574 	}
1575 	zfs_dbgmsg("restarting resilver for %s at txg=%llu",
1576 	    dp->dp_spa->spa_name, (longlong_t)txg);
1577 }
1578 
1579 void
dsl_free(dsl_pool_t * dp,uint64_t txg,const blkptr_t * bp)1580 dsl_free(dsl_pool_t *dp, uint64_t txg, const blkptr_t *bp)
1581 {
1582 	zio_free(dp->dp_spa, txg, bp);
1583 }
1584 
1585 void
dsl_free_sync(zio_t * pio,dsl_pool_t * dp,uint64_t txg,const blkptr_t * bpp)1586 dsl_free_sync(zio_t *pio, dsl_pool_t *dp, uint64_t txg, const blkptr_t *bpp)
1587 {
1588 	ASSERT(dsl_pool_sync_context(dp));
1589 	zio_nowait(zio_free_sync(pio, dp->dp_spa, txg, bpp, pio->io_flags));
1590 }
1591 
1592 static int
scan_ds_queue_compare(const void * a,const void * b)1593 scan_ds_queue_compare(const void *a, const void *b)
1594 {
1595 	const scan_ds_t *sds_a = a, *sds_b = b;
1596 	return (TREE_CMP(sds_a->sds_dsobj, sds_b->sds_dsobj));
1597 }
1598 
1599 static void
scan_ds_queue_clear(dsl_scan_t * scn)1600 scan_ds_queue_clear(dsl_scan_t *scn)
1601 {
1602 	void *cookie = NULL;
1603 	scan_ds_t *sds;
1604 	while ((sds = avl_destroy_nodes(&scn->scn_queue, &cookie)) != NULL) {
1605 		kmem_free(sds, sizeof (*sds));
1606 	}
1607 }
1608 
1609 static boolean_t
scan_ds_queue_contains(dsl_scan_t * scn,uint64_t dsobj,uint64_t * txg)1610 scan_ds_queue_contains(dsl_scan_t *scn, uint64_t dsobj, uint64_t *txg)
1611 {
1612 	scan_ds_t srch, *sds;
1613 
1614 	srch.sds_dsobj = dsobj;
1615 	sds = avl_find(&scn->scn_queue, &srch, NULL);
1616 	if (sds != NULL && txg != NULL)
1617 		*txg = sds->sds_txg;
1618 	return (sds != NULL);
1619 }
1620 
1621 static void
scan_ds_queue_insert(dsl_scan_t * scn,uint64_t dsobj,uint64_t txg)1622 scan_ds_queue_insert(dsl_scan_t *scn, uint64_t dsobj, uint64_t txg)
1623 {
1624 	scan_ds_t *sds;
1625 	avl_index_t where;
1626 
1627 	sds = kmem_zalloc(sizeof (*sds), KM_SLEEP);
1628 	sds->sds_dsobj = dsobj;
1629 	sds->sds_txg = txg;
1630 
1631 	VERIFY3P(avl_find(&scn->scn_queue, sds, &where), ==, NULL);
1632 	avl_insert(&scn->scn_queue, sds, where);
1633 }
1634 
1635 static void
scan_ds_queue_remove(dsl_scan_t * scn,uint64_t dsobj)1636 scan_ds_queue_remove(dsl_scan_t *scn, uint64_t dsobj)
1637 {
1638 	scan_ds_t srch, *sds;
1639 
1640 	srch.sds_dsobj = dsobj;
1641 
1642 	sds = avl_find(&scn->scn_queue, &srch, NULL);
1643 	VERIFY(sds != NULL);
1644 	avl_remove(&scn->scn_queue, sds);
1645 	kmem_free(sds, sizeof (*sds));
1646 }
1647 
1648 static void
scan_ds_queue_sync(dsl_scan_t * scn,dmu_tx_t * tx)1649 scan_ds_queue_sync(dsl_scan_t *scn, dmu_tx_t *tx)
1650 {
1651 	dsl_pool_t *dp = scn->scn_dp;
1652 	spa_t *spa = dp->dp_spa;
1653 	dmu_object_type_t ot = (spa_version(spa) >= SPA_VERSION_DSL_SCRUB) ?
1654 	    DMU_OT_SCAN_QUEUE : DMU_OT_ZAP_OTHER;
1655 
1656 	ASSERT0(scn->scn_queues_pending);
1657 	ASSERT(scn->scn_phys.scn_queue_obj != 0);
1658 
1659 	VERIFY0(dmu_object_free(dp->dp_meta_objset,
1660 	    scn->scn_phys.scn_queue_obj, tx));
1661 	scn->scn_phys.scn_queue_obj = zap_create(dp->dp_meta_objset, ot,
1662 	    DMU_OT_NONE, 0, tx);
1663 	for (scan_ds_t *sds = avl_first(&scn->scn_queue);
1664 	    sds != NULL; sds = AVL_NEXT(&scn->scn_queue, sds)) {
1665 		VERIFY0(zap_add_int_key(dp->dp_meta_objset,
1666 		    scn->scn_phys.scn_queue_obj, sds->sds_dsobj,
1667 		    sds->sds_txg, tx));
1668 	}
1669 }
1670 
1671 /*
1672  * Computes the memory limit state that we're currently in. A sorted scan
1673  * needs quite a bit of memory to hold the sorting queue, so we need to
1674  * reasonably constrain the size so it doesn't impact overall system
1675  * performance. We compute two limits:
1676  * 1) Hard memory limit: if the amount of memory used by the sorting
1677  *	queues on a pool gets above this value, we stop the metadata
1678  *	scanning portion and start issuing the queued up and sorted
1679  *	I/Os to reduce memory usage.
1680  *	This limit is calculated as a fraction of physmem (by default 5%).
1681  *	We constrain the lower bound of the hard limit to an absolute
1682  *	minimum of zfs_scan_mem_lim_min (default: 16 MiB). We also constrain
1683  *	the upper bound to 5% of the total pool size - no chance we'll
1684  *	ever need that much memory, but just to keep the value in check.
1685  * 2) Soft memory limit: once we hit the hard memory limit, we start
1686  *	issuing I/O to reduce queue memory usage, but we don't want to
1687  *	completely empty out the queues, since we might be able to find I/Os
1688  *	that will fill in the gaps of our non-sequential IOs at some point
1689  *	in the future. So we stop the issuing of I/Os once the amount of
1690  *	memory used drops below the soft limit (at which point we stop issuing
1691  *	I/O and start scanning metadata again).
1692  *
1693  *	This limit is calculated by subtracting a fraction of the hard
1694  *	limit from the hard limit. By default this fraction is 5%, so
1695  *	the soft limit is 95% of the hard limit. We cap the size of the
1696  *	difference between the hard and soft limits at an absolute
1697  *	maximum of zfs_scan_mem_lim_soft_max (default: 128 MiB) - this is
1698  *	sufficient to not cause too frequent switching between the
1699  *	metadata scan and I/O issue (even at 2k recordsize, 128 MiB's
1700  *	worth of queues is about 1.2 GiB of on-pool data, so scanning
1701  *	that should take at least a decent fraction of a second).
1702  */
1703 static boolean_t
dsl_scan_should_clear(dsl_scan_t * scn)1704 dsl_scan_should_clear(dsl_scan_t *scn)
1705 {
1706 	spa_t *spa = scn->scn_dp->dp_spa;
1707 	vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
1708 	uint64_t alloc, mlim_hard, mlim_soft, mused;
1709 
1710 	alloc = metaslab_class_get_alloc(spa_normal_class(spa));
1711 	alloc += metaslab_class_get_alloc(spa_special_class(spa));
1712 	alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
1713 
1714 	mlim_hard = MAX((physmem / zfs_scan_mem_lim_fact) * PAGESIZE,
1715 	    zfs_scan_mem_lim_min);
1716 	mlim_hard = MIN(mlim_hard, alloc / 20);
1717 	mlim_soft = mlim_hard - MIN(mlim_hard / zfs_scan_mem_lim_soft_fact,
1718 	    zfs_scan_mem_lim_soft_max);
1719 	mused = 0;
1720 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1721 		vdev_t *tvd = rvd->vdev_child[i];
1722 		dsl_scan_io_queue_t *queue;
1723 
1724 		mutex_enter(&tvd->vdev_scan_io_queue_lock);
1725 		queue = tvd->vdev_scan_io_queue;
1726 		if (queue != NULL) {
1727 			/*
1728 			 * # of extents in exts_by_addr = # in exts_by_size.
1729 			 * B-tree efficiency is ~75%, but can be as low as 50%.
1730 			 */
1731 			mused += zfs_btree_numnodes(&queue->q_exts_by_size) * ((
1732 			    sizeof (zfs_range_seg_gap_t) + sizeof (uint64_t)) *
1733 			    3 / 2) + queue->q_sio_memused;
1734 		}
1735 		mutex_exit(&tvd->vdev_scan_io_queue_lock);
1736 	}
1737 
1738 	dprintf("current scan memory usage: %llu bytes\n", (longlong_t)mused);
1739 
1740 	if (mused == 0)
1741 		ASSERT0(scn->scn_queues_pending);
1742 
1743 	/*
1744 	 * If we are above our hard limit, we need to clear out memory.
1745 	 * If we are below our soft limit, we need to accumulate sequential IOs.
1746 	 * Otherwise, we should keep doing whatever we are currently doing.
1747 	 */
1748 	if (mused >= mlim_hard)
1749 		return (B_TRUE);
1750 	else if (mused < mlim_soft)
1751 		return (B_FALSE);
1752 	else
1753 		return (scn->scn_clearing);
1754 }
1755 
1756 static boolean_t
dsl_scan_check_suspend(dsl_scan_t * scn,const zbookmark_phys_t * zb)1757 dsl_scan_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1758 {
1759 	/* we never skip user/group accounting objects */
1760 	if (zb && (int64_t)zb->zb_object < 0)
1761 		return (B_FALSE);
1762 
1763 	if (scn->scn_suspending)
1764 		return (B_TRUE); /* we're already suspending */
1765 
1766 	if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark))
1767 		return (B_FALSE); /* we're resuming */
1768 
1769 	/* We only know how to resume from level-0 and objset blocks. */
1770 	if (zb && (zb->zb_level != 0 && zb->zb_level != ZB_ROOT_LEVEL))
1771 		return (B_FALSE);
1772 
1773 	/*
1774 	 * We suspend if:
1775 	 *  - we have scanned for at least the minimum time (default 1 sec
1776 	 *    for scrub, 3 sec for resilver), and either we have sufficient
1777 	 *    dirty data that we are starting to write more quickly
1778 	 *    (default 30%), someone is explicitly waiting for this txg
1779 	 *    to complete, or we have used up all of the time in the txg
1780 	 *    timeout (default 5 sec).
1781 	 *  or
1782 	 *  - the spa is shutting down because this pool is being exported
1783 	 *    or the machine is rebooting.
1784 	 *  or
1785 	 *  - the scan queue has reached its memory use limit
1786 	 */
1787 	uint64_t curr_time_ns = getlrtime();
1788 	uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
1789 	uint64_t sync_time_ns = curr_time_ns -
1790 	    scn->scn_dp->dp_spa->spa_sync_starttime;
1791 	uint64_t dirty_min_bytes = zfs_dirty_data_max *
1792 	    zfs_vdev_async_write_active_min_dirty_percent / 100;
1793 	uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
1794 	    zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
1795 
1796 	if ((NSEC2MSEC(scan_time_ns) > mintime &&
1797 	    (scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||
1798 	    txg_sync_waiting(scn->scn_dp) ||
1799 	    NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1800 	    spa_shutting_down(scn->scn_dp->dp_spa) ||
1801 	    (zfs_scan_strict_mem_lim && dsl_scan_should_clear(scn)) ||
1802 	    !ddt_walk_ready(scn->scn_dp->dp_spa)) {
1803 		if (zb && zb->zb_level == ZB_ROOT_LEVEL) {
1804 			dprintf("suspending at first available bookmark "
1805 			    "%llx/%llx/%llx/%llx\n",
1806 			    (longlong_t)zb->zb_objset,
1807 			    (longlong_t)zb->zb_object,
1808 			    (longlong_t)zb->zb_level,
1809 			    (longlong_t)zb->zb_blkid);
1810 			SET_BOOKMARK(&scn->scn_phys.scn_bookmark,
1811 			    zb->zb_objset, 0, 0, 0);
1812 		} else if (zb != NULL) {
1813 			dprintf("suspending at bookmark %llx/%llx/%llx/%llx\n",
1814 			    (longlong_t)zb->zb_objset,
1815 			    (longlong_t)zb->zb_object,
1816 			    (longlong_t)zb->zb_level,
1817 			    (longlong_t)zb->zb_blkid);
1818 			scn->scn_phys.scn_bookmark = *zb;
1819 		} else {
1820 #ifdef ZFS_DEBUG
1821 			dsl_scan_phys_t *scnp = &scn->scn_phys;
1822 			dprintf("suspending at at DDT bookmark "
1823 			    "%llx/%llx/%llx/%llx\n",
1824 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
1825 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
1826 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
1827 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
1828 #endif
1829 		}
1830 		scn->scn_suspending = B_TRUE;
1831 		return (B_TRUE);
1832 	}
1833 	return (B_FALSE);
1834 }
1835 
1836 static boolean_t
dsl_error_scrub_check_suspend(dsl_scan_t * scn,const zbookmark_phys_t * zb)1837 dsl_error_scrub_check_suspend(dsl_scan_t *scn, const zbookmark_phys_t *zb)
1838 {
1839 	/*
1840 	 * We suspend if:
1841 	 *  - we have scrubbed for at least the minimum time (default 1 sec
1842 	 *    for error scrub), someone is explicitly waiting for this txg
1843 	 *    to complete, or we have used up all of the time in the txg
1844 	 *    timeout (default 5 sec).
1845 	 *  or
1846 	 *  - the spa is shutting down because this pool is being exported
1847 	 *    or the machine is rebooting.
1848 	 */
1849 	uint64_t curr_time_ns = getlrtime();
1850 	uint64_t error_scrub_time_ns = curr_time_ns - scn->scn_sync_start_time;
1851 	uint64_t sync_time_ns = curr_time_ns -
1852 	    scn->scn_dp->dp_spa->spa_sync_starttime;
1853 	int mintime = zfs_scrub_min_time_ms;
1854 
1855 	if ((NSEC2MSEC(error_scrub_time_ns) > mintime &&
1856 	    (txg_sync_waiting(scn->scn_dp) ||
1857 	    NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
1858 	    spa_shutting_down(scn->scn_dp->dp_spa)) {
1859 		if (zb) {
1860 			dprintf("error scrub suspending at bookmark "
1861 			    "%llx/%llx/%llx/%llx\n",
1862 			    (longlong_t)zb->zb_objset,
1863 			    (longlong_t)zb->zb_object,
1864 			    (longlong_t)zb->zb_level,
1865 			    (longlong_t)zb->zb_blkid);
1866 		}
1867 		return (B_TRUE);
1868 	}
1869 	return (B_FALSE);
1870 }
1871 
1872 typedef struct zil_scan_arg {
1873 	dsl_pool_t	*zsa_dp;
1874 	zil_header_t	*zsa_zh;
1875 } zil_scan_arg_t;
1876 
1877 static int
dsl_scan_zil_block(zilog_t * zilog,const blkptr_t * bp,void * arg,uint64_t claim_txg)1878 dsl_scan_zil_block(zilog_t *zilog, const blkptr_t *bp, void *arg,
1879     uint64_t claim_txg)
1880 {
1881 	(void) zilog;
1882 	zil_scan_arg_t *zsa = arg;
1883 	dsl_pool_t *dp = zsa->zsa_dp;
1884 	dsl_scan_t *scn = dp->dp_scan;
1885 	zil_header_t *zh = zsa->zsa_zh;
1886 	zbookmark_phys_t zb;
1887 
1888 	ASSERT(!BP_IS_REDACTED(bp));
1889 	if (BP_IS_HOLE(bp) ||
1890 	    BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)
1891 		return (0);
1892 
1893 	/*
1894 	 * One block ("stubby") can be allocated a long time ago; we
1895 	 * want to visit that one because it has been allocated
1896 	 * (on-disk) even if it hasn't been claimed (even though for
1897 	 * scrub there's nothing to do to it).
1898 	 */
1899 	if (claim_txg == 0 &&
1900 	    BP_GET_BIRTH(bp) >= spa_min_claim_txg(dp->dp_spa))
1901 		return (0);
1902 
1903 	SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1904 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
1905 
1906 	VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1907 	return (0);
1908 }
1909 
1910 static int
dsl_scan_zil_record(zilog_t * zilog,const lr_t * lrc,void * arg,uint64_t claim_txg)1911 dsl_scan_zil_record(zilog_t *zilog, const lr_t *lrc, void *arg,
1912     uint64_t claim_txg)
1913 {
1914 	(void) zilog;
1915 	if (lrc->lrc_txtype == TX_WRITE) {
1916 		zil_scan_arg_t *zsa = arg;
1917 		dsl_pool_t *dp = zsa->zsa_dp;
1918 		dsl_scan_t *scn = dp->dp_scan;
1919 		zil_header_t *zh = zsa->zsa_zh;
1920 		const lr_write_t *lr = (const lr_write_t *)lrc;
1921 		const blkptr_t *bp = &lr->lr_blkptr;
1922 		zbookmark_phys_t zb;
1923 
1924 		ASSERT(!BP_IS_REDACTED(bp));
1925 		if (BP_IS_HOLE(bp) ||
1926 		    BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg)
1927 			return (0);
1928 
1929 		/*
1930 		 * birth can be < claim_txg if this record's txg is
1931 		 * already txg sync'ed (but this log block contains
1932 		 * other records that are not synced)
1933 		 */
1934 		if (claim_txg == 0 || BP_GET_BIRTH(bp) < claim_txg)
1935 			return (0);
1936 
1937 		ASSERT3U(BP_GET_LSIZE(bp), !=, 0);
1938 		SET_BOOKMARK(&zb, zh->zh_log.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1939 		    lr->lr_foid, ZB_ZIL_LEVEL,
1940 		    lr->lr_offset / BP_GET_LSIZE(bp));
1941 
1942 		VERIFY0(scan_funcs[scn->scn_phys.scn_func](dp, bp, &zb));
1943 	}
1944 	return (0);
1945 }
1946 
1947 static void
dsl_scan_zil(dsl_pool_t * dp,zil_header_t * zh)1948 dsl_scan_zil(dsl_pool_t *dp, zil_header_t *zh)
1949 {
1950 	uint64_t claim_txg = zh->zh_claim_txg;
1951 	zil_scan_arg_t zsa = { dp, zh };
1952 	zilog_t *zilog;
1953 
1954 	ASSERT(spa_writeable(dp->dp_spa));
1955 
1956 	/*
1957 	 * We only want to visit blocks that have been claimed but not yet
1958 	 * replayed (or, in read-only mode, blocks that *would* be claimed).
1959 	 */
1960 	if (claim_txg == 0)
1961 		return;
1962 
1963 	zilog = zil_alloc(dp->dp_meta_objset, zh);
1964 
1965 	(void) zil_parse(zilog, dsl_scan_zil_block, dsl_scan_zil_record, &zsa,
1966 	    claim_txg, B_FALSE);
1967 
1968 	zil_free(zilog);
1969 }
1970 
1971 /*
1972  * We compare scan_prefetch_issue_ctx_t's based on their bookmarks. The idea
1973  * here is to sort the AVL tree by the order each block will be needed.
1974  */
1975 static int
scan_prefetch_queue_compare(const void * a,const void * b)1976 scan_prefetch_queue_compare(const void *a, const void *b)
1977 {
1978 	const scan_prefetch_issue_ctx_t *spic_a = a, *spic_b = b;
1979 	const scan_prefetch_ctx_t *spc_a = spic_a->spic_spc;
1980 	const scan_prefetch_ctx_t *spc_b = spic_b->spic_spc;
1981 
1982 	return (zbookmark_compare(spc_a->spc_datablkszsec,
1983 	    spc_a->spc_indblkshift, spc_b->spc_datablkszsec,
1984 	    spc_b->spc_indblkshift, &spic_a->spic_zb, &spic_b->spic_zb));
1985 }
1986 
1987 static void
scan_prefetch_ctx_rele(scan_prefetch_ctx_t * spc,const void * tag)1988 scan_prefetch_ctx_rele(scan_prefetch_ctx_t *spc, const void *tag)
1989 {
1990 	if (zfs_refcount_remove(&spc->spc_refcnt, tag) == 0) {
1991 		zfs_refcount_destroy(&spc->spc_refcnt);
1992 		kmem_free(spc, sizeof (scan_prefetch_ctx_t));
1993 	}
1994 }
1995 
1996 static scan_prefetch_ctx_t *
scan_prefetch_ctx_create(dsl_scan_t * scn,dnode_phys_t * dnp,const void * tag)1997 scan_prefetch_ctx_create(dsl_scan_t *scn, dnode_phys_t *dnp, const void *tag)
1998 {
1999 	scan_prefetch_ctx_t *spc;
2000 
2001 	spc = kmem_alloc(sizeof (scan_prefetch_ctx_t), KM_SLEEP);
2002 	zfs_refcount_create(&spc->spc_refcnt);
2003 	zfs_refcount_add(&spc->spc_refcnt, tag);
2004 	spc->spc_scn = scn;
2005 	if (dnp != NULL) {
2006 		spc->spc_datablkszsec = dnp->dn_datablkszsec;
2007 		spc->spc_indblkshift = dnp->dn_indblkshift;
2008 		spc->spc_root = B_FALSE;
2009 	} else {
2010 		spc->spc_datablkszsec = 0;
2011 		spc->spc_indblkshift = 0;
2012 		spc->spc_root = B_TRUE;
2013 	}
2014 
2015 	return (spc);
2016 }
2017 
2018 static void
scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t * spc,const void * tag)2019 scan_prefetch_ctx_add_ref(scan_prefetch_ctx_t *spc, const void *tag)
2020 {
2021 	zfs_refcount_add(&spc->spc_refcnt, tag);
2022 }
2023 
2024 static void
scan_ds_prefetch_queue_clear(dsl_scan_t * scn)2025 scan_ds_prefetch_queue_clear(dsl_scan_t *scn)
2026 {
2027 	spa_t *spa = scn->scn_dp->dp_spa;
2028 	void *cookie = NULL;
2029 	scan_prefetch_issue_ctx_t *spic = NULL;
2030 
2031 	mutex_enter(&spa->spa_scrub_lock);
2032 	while ((spic = avl_destroy_nodes(&scn->scn_prefetch_queue,
2033 	    &cookie)) != NULL) {
2034 		scan_prefetch_ctx_rele(spic->spic_spc, scn);
2035 		kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2036 	}
2037 	mutex_exit(&spa->spa_scrub_lock);
2038 }
2039 
2040 static boolean_t
dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t * spc,const zbookmark_phys_t * zb)2041 dsl_scan_check_prefetch_resume(scan_prefetch_ctx_t *spc,
2042     const zbookmark_phys_t *zb)
2043 {
2044 	zbookmark_phys_t *last_zb = &spc->spc_scn->scn_prefetch_bookmark;
2045 	dnode_phys_t tmp_dnp;
2046 	dnode_phys_t *dnp = (spc->spc_root) ? NULL : &tmp_dnp;
2047 
2048 	if (zb->zb_objset != last_zb->zb_objset)
2049 		return (B_TRUE);
2050 	if ((int64_t)zb->zb_object < 0)
2051 		return (B_FALSE);
2052 
2053 	tmp_dnp.dn_datablkszsec = spc->spc_datablkszsec;
2054 	tmp_dnp.dn_indblkshift = spc->spc_indblkshift;
2055 
2056 	if (zbookmark_subtree_completed(dnp, zb, last_zb))
2057 		return (B_TRUE);
2058 
2059 	return (B_FALSE);
2060 }
2061 
2062 static void
dsl_scan_prefetch(scan_prefetch_ctx_t * spc,blkptr_t * bp,zbookmark_phys_t * zb)2063 dsl_scan_prefetch(scan_prefetch_ctx_t *spc, blkptr_t *bp, zbookmark_phys_t *zb)
2064 {
2065 	avl_index_t idx;
2066 	dsl_scan_t *scn = spc->spc_scn;
2067 	spa_t *spa = scn->scn_dp->dp_spa;
2068 	scan_prefetch_issue_ctx_t *spic;
2069 
2070 	if (zfs_no_scrub_prefetch || BP_IS_REDACTED(bp))
2071 		return;
2072 
2073 	if (BP_IS_HOLE(bp) ||
2074 	    BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg ||
2075 	    (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
2076 	    BP_GET_TYPE(bp) != DMU_OT_OBJSET))
2077 		return;
2078 
2079 	if (dsl_scan_check_prefetch_resume(spc, zb))
2080 		return;
2081 
2082 	scan_prefetch_ctx_add_ref(spc, scn);
2083 	spic = kmem_alloc(sizeof (scan_prefetch_issue_ctx_t), KM_SLEEP);
2084 	spic->spic_spc = spc;
2085 	spic->spic_bp = *bp;
2086 	spic->spic_zb = *zb;
2087 
2088 	/*
2089 	 * Add the IO to the queue of blocks to prefetch. This allows us to
2090 	 * prioritize blocks that we will need first for the main traversal
2091 	 * thread.
2092 	 */
2093 	mutex_enter(&spa->spa_scrub_lock);
2094 	if (avl_find(&scn->scn_prefetch_queue, spic, &idx) != NULL) {
2095 		/* this block is already queued for prefetch */
2096 		kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2097 		scan_prefetch_ctx_rele(spc, scn);
2098 		mutex_exit(&spa->spa_scrub_lock);
2099 		return;
2100 	}
2101 
2102 	avl_insert(&scn->scn_prefetch_queue, spic, idx);
2103 	cv_broadcast(&spa->spa_scrub_io_cv);
2104 	mutex_exit(&spa->spa_scrub_lock);
2105 }
2106 
2107 static void
dsl_scan_prefetch_dnode(dsl_scan_t * scn,dnode_phys_t * dnp,uint64_t objset,uint64_t object)2108 dsl_scan_prefetch_dnode(dsl_scan_t *scn, dnode_phys_t *dnp,
2109     uint64_t objset, uint64_t object)
2110 {
2111 	int i;
2112 	zbookmark_phys_t zb;
2113 	scan_prefetch_ctx_t *spc;
2114 
2115 	if (dnp->dn_nblkptr == 0 && !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2116 		return;
2117 
2118 	SET_BOOKMARK(&zb, objset, object, 0, 0);
2119 
2120 	spc = scan_prefetch_ctx_create(scn, dnp, FTAG);
2121 
2122 	for (i = 0; i < dnp->dn_nblkptr; i++) {
2123 		zb.zb_level = BP_GET_LEVEL(&dnp->dn_blkptr[i]);
2124 		zb.zb_blkid = i;
2125 		dsl_scan_prefetch(spc, &dnp->dn_blkptr[i], &zb);
2126 	}
2127 
2128 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
2129 		zb.zb_level = 0;
2130 		zb.zb_blkid = DMU_SPILL_BLKID;
2131 		dsl_scan_prefetch(spc, DN_SPILL_BLKPTR(dnp), &zb);
2132 	}
2133 
2134 	scan_prefetch_ctx_rele(spc, FTAG);
2135 }
2136 
2137 static void
dsl_scan_prefetch_cb(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * bp,arc_buf_t * buf,void * private)2138 dsl_scan_prefetch_cb(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
2139     arc_buf_t *buf, void *private)
2140 {
2141 	(void) zio;
2142 	scan_prefetch_ctx_t *spc = private;
2143 	dsl_scan_t *scn = spc->spc_scn;
2144 	spa_t *spa = scn->scn_dp->dp_spa;
2145 
2146 	/* broadcast that the IO has completed for rate limiting purposes */
2147 	mutex_enter(&spa->spa_scrub_lock);
2148 	ASSERT3U(spa->spa_scrub_inflight, >=, BP_GET_PSIZE(bp));
2149 	spa->spa_scrub_inflight -= BP_GET_PSIZE(bp);
2150 	cv_broadcast(&spa->spa_scrub_io_cv);
2151 	mutex_exit(&spa->spa_scrub_lock);
2152 
2153 	/* if there was an error or we are done prefetching, just cleanup */
2154 	if (buf == NULL || scn->scn_prefetch_stop)
2155 		goto out;
2156 
2157 	if (BP_GET_LEVEL(bp) > 0) {
2158 		int i;
2159 		blkptr_t *cbp;
2160 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2161 		zbookmark_phys_t czb;
2162 
2163 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
2164 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2165 			    zb->zb_level - 1, zb->zb_blkid * epb + i);
2166 			dsl_scan_prefetch(spc, cbp, &czb);
2167 		}
2168 	} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
2169 		dnode_phys_t *cdnp;
2170 		int i;
2171 		int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
2172 
2173 		for (i = 0, cdnp = buf->b_data; i < epb;
2174 		    i += cdnp->dn_extra_slots + 1,
2175 		    cdnp += cdnp->dn_extra_slots + 1) {
2176 			dsl_scan_prefetch_dnode(scn, cdnp,
2177 			    zb->zb_objset, zb->zb_blkid * epb + i);
2178 		}
2179 	} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
2180 		objset_phys_t *osp = buf->b_data;
2181 
2182 		dsl_scan_prefetch_dnode(scn, &osp->os_meta_dnode,
2183 		    zb->zb_objset, DMU_META_DNODE_OBJECT);
2184 
2185 		if (OBJSET_BUF_HAS_USERUSED(buf)) {
2186 			if (OBJSET_BUF_HAS_PROJECTUSED(buf)) {
2187 				dsl_scan_prefetch_dnode(scn,
2188 				    &osp->os_projectused_dnode, zb->zb_objset,
2189 				    DMU_PROJECTUSED_OBJECT);
2190 			}
2191 			dsl_scan_prefetch_dnode(scn,
2192 			    &osp->os_groupused_dnode, zb->zb_objset,
2193 			    DMU_GROUPUSED_OBJECT);
2194 			dsl_scan_prefetch_dnode(scn,
2195 			    &osp->os_userused_dnode, zb->zb_objset,
2196 			    DMU_USERUSED_OBJECT);
2197 		}
2198 	}
2199 
2200 out:
2201 	if (buf != NULL)
2202 		arc_buf_destroy(buf, private);
2203 	scan_prefetch_ctx_rele(spc, scn);
2204 }
2205 
2206 static void
dsl_scan_prefetch_thread(void * arg)2207 dsl_scan_prefetch_thread(void *arg)
2208 {
2209 	dsl_scan_t *scn = arg;
2210 	spa_t *spa = scn->scn_dp->dp_spa;
2211 	scan_prefetch_issue_ctx_t *spic;
2212 
2213 	/* loop until we are told to stop */
2214 	while (!scn->scn_prefetch_stop) {
2215 		arc_flags_t flags = ARC_FLAG_NOWAIT |
2216 		    ARC_FLAG_PRESCIENT_PREFETCH | ARC_FLAG_PREFETCH;
2217 		int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
2218 
2219 		mutex_enter(&spa->spa_scrub_lock);
2220 
2221 		/*
2222 		 * Wait until we have an IO to issue and are not above our
2223 		 * maximum in flight limit.
2224 		 */
2225 		while (!scn->scn_prefetch_stop &&
2226 		    (avl_numnodes(&scn->scn_prefetch_queue) == 0 ||
2227 		    spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)) {
2228 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2229 		}
2230 
2231 		/* recheck if we should stop since we waited for the cv */
2232 		if (scn->scn_prefetch_stop) {
2233 			mutex_exit(&spa->spa_scrub_lock);
2234 			break;
2235 		}
2236 
2237 		/* remove the prefetch IO from the tree */
2238 		spic = avl_first(&scn->scn_prefetch_queue);
2239 		spa->spa_scrub_inflight += BP_GET_PSIZE(&spic->spic_bp);
2240 		avl_remove(&scn->scn_prefetch_queue, spic);
2241 
2242 		mutex_exit(&spa->spa_scrub_lock);
2243 
2244 		if (BP_IS_PROTECTED(&spic->spic_bp)) {
2245 			ASSERT(BP_GET_TYPE(&spic->spic_bp) == DMU_OT_DNODE ||
2246 			    BP_GET_TYPE(&spic->spic_bp) == DMU_OT_OBJSET);
2247 			ASSERT3U(BP_GET_LEVEL(&spic->spic_bp), ==, 0);
2248 			zio_flags |= ZIO_FLAG_RAW;
2249 		}
2250 
2251 		/* We don't need data L1 buffer since we do not prefetch L0. */
2252 		blkptr_t *bp = &spic->spic_bp;
2253 		if (BP_GET_LEVEL(bp) == 1 && BP_GET_TYPE(bp) != DMU_OT_DNODE &&
2254 		    BP_GET_TYPE(bp) != DMU_OT_OBJSET)
2255 			flags |= ARC_FLAG_NO_BUF;
2256 
2257 		/* issue the prefetch asynchronously */
2258 		(void) arc_read(scn->scn_zio_root, spa, bp,
2259 		    dsl_scan_prefetch_cb, spic->spic_spc, ZIO_PRIORITY_SCRUB,
2260 		    zio_flags, &flags, &spic->spic_zb);
2261 
2262 		kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2263 	}
2264 
2265 	ASSERT(scn->scn_prefetch_stop);
2266 
2267 	/* free any prefetches we didn't get to complete */
2268 	mutex_enter(&spa->spa_scrub_lock);
2269 	while ((spic = avl_first(&scn->scn_prefetch_queue)) != NULL) {
2270 		avl_remove(&scn->scn_prefetch_queue, spic);
2271 		scan_prefetch_ctx_rele(spic->spic_spc, scn);
2272 		kmem_free(spic, sizeof (scan_prefetch_issue_ctx_t));
2273 	}
2274 	ASSERT0(avl_numnodes(&scn->scn_prefetch_queue));
2275 	mutex_exit(&spa->spa_scrub_lock);
2276 }
2277 
2278 static boolean_t
dsl_scan_check_resume(dsl_scan_t * scn,const dnode_phys_t * dnp,const zbookmark_phys_t * zb)2279 dsl_scan_check_resume(dsl_scan_t *scn, const dnode_phys_t *dnp,
2280     const zbookmark_phys_t *zb)
2281 {
2282 	/*
2283 	 * We never skip over user/group accounting objects (obj<0)
2284 	 */
2285 	if (!ZB_IS_ZERO(&scn->scn_phys.scn_bookmark) &&
2286 	    (int64_t)zb->zb_object >= 0) {
2287 		/*
2288 		 * If we already visited this bp & everything below (in
2289 		 * a prior txg sync), don't bother doing it again.
2290 		 */
2291 		if (zbookmark_subtree_completed(dnp, zb,
2292 		    &scn->scn_phys.scn_bookmark))
2293 			return (B_TRUE);
2294 
2295 		/*
2296 		 * If we found the block we're trying to resume from, or
2297 		 * we went past it, zero it out to indicate that it's OK
2298 		 * to start checking for suspending again.
2299 		 */
2300 		if (zbookmark_subtree_tbd(dnp, zb,
2301 		    &scn->scn_phys.scn_bookmark)) {
2302 			dprintf("resuming at %llx/%llx/%llx/%llx\n",
2303 			    (longlong_t)zb->zb_objset,
2304 			    (longlong_t)zb->zb_object,
2305 			    (longlong_t)zb->zb_level,
2306 			    (longlong_t)zb->zb_blkid);
2307 			memset(&scn->scn_phys.scn_bookmark, 0, sizeof (*zb));
2308 		}
2309 	}
2310 	return (B_FALSE);
2311 }
2312 
2313 static void dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,
2314     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
2315     dmu_objset_type_t ostype, dmu_tx_t *tx);
2316 inline __attribute__((always_inline)) static void dsl_scan_visitdnode(
2317     dsl_scan_t *, dsl_dataset_t *ds, dmu_objset_type_t ostype,
2318     dnode_phys_t *dnp, uint64_t object, dmu_tx_t *tx);
2319 
2320 /*
2321  * Return nonzero on i/o error.
2322  * Return new buf to write out in *bufp.
2323  */
2324 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)2325 dsl_scan_recurse(dsl_scan_t *scn, dsl_dataset_t *ds, dmu_objset_type_t ostype,
2326     dnode_phys_t *dnp, const blkptr_t *bp,
2327     const zbookmark_phys_t *zb, dmu_tx_t *tx)
2328 {
2329 	dsl_pool_t *dp = scn->scn_dp;
2330 	spa_t *spa = dp->dp_spa;
2331 	int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCAN_THREAD;
2332 	int err;
2333 
2334 	ASSERT(!BP_IS_REDACTED(bp));
2335 
2336 	/*
2337 	 * There is an unlikely case of encountering dnodes with contradicting
2338 	 * dn_bonuslen and DNODE_FLAG_SPILL_BLKPTR flag before in files created
2339 	 * or modified before commit 4254acb was merged. As it is not possible
2340 	 * to know which of the two is correct, report an error.
2341 	 */
2342 	if (dnp != NULL &&
2343 	    dnp->dn_bonuslen > DN_MAX_BONUS_LEN(dnp)) {
2344 		scn->scn_phys.scn_errors++;
2345 		spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));
2346 		return (SET_ERROR(EINVAL));
2347 	}
2348 
2349 	if (BP_GET_LEVEL(bp) > 0) {
2350 		arc_flags_t flags = ARC_FLAG_WAIT;
2351 		int i;
2352 		blkptr_t *cbp;
2353 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2354 		arc_buf_t *buf;
2355 
2356 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2357 		    ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2358 		if (err) {
2359 			scn->scn_phys.scn_errors++;
2360 			return (err);
2361 		}
2362 		for (i = 0, cbp = buf->b_data; i < epb; i++, cbp++) {
2363 			zbookmark_phys_t czb;
2364 
2365 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2366 			    zb->zb_level - 1,
2367 			    zb->zb_blkid * epb + i);
2368 			dsl_scan_visitbp(cbp, &czb, dnp,
2369 			    ds, scn, ostype, tx);
2370 		}
2371 		arc_buf_destroy(buf, &buf);
2372 	} else if (BP_GET_TYPE(bp) == DMU_OT_DNODE) {
2373 		arc_flags_t flags = ARC_FLAG_WAIT;
2374 		dnode_phys_t *cdnp;
2375 		int i;
2376 		int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
2377 		arc_buf_t *buf;
2378 
2379 		if (BP_IS_PROTECTED(bp)) {
2380 			ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
2381 			zio_flags |= ZIO_FLAG_RAW;
2382 		}
2383 
2384 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2385 		    ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2386 		if (err) {
2387 			scn->scn_phys.scn_errors++;
2388 			return (err);
2389 		}
2390 		for (i = 0, cdnp = buf->b_data; i < epb;
2391 		    i += cdnp->dn_extra_slots + 1,
2392 		    cdnp += cdnp->dn_extra_slots + 1) {
2393 			dsl_scan_visitdnode(scn, ds, ostype,
2394 			    cdnp, zb->zb_blkid * epb + i, tx);
2395 		}
2396 
2397 		arc_buf_destroy(buf, &buf);
2398 	} else if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
2399 		arc_flags_t flags = ARC_FLAG_WAIT;
2400 		objset_phys_t *osp;
2401 		arc_buf_t *buf;
2402 
2403 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2404 		    ZIO_PRIORITY_SCRUB, zio_flags, &flags, zb);
2405 		if (err) {
2406 			scn->scn_phys.scn_errors++;
2407 			return (err);
2408 		}
2409 
2410 		osp = buf->b_data;
2411 
2412 		dsl_scan_visitdnode(scn, ds, osp->os_type,
2413 		    &osp->os_meta_dnode, DMU_META_DNODE_OBJECT, tx);
2414 
2415 		if (OBJSET_BUF_HAS_USERUSED(buf)) {
2416 			/*
2417 			 * We also always visit user/group/project accounting
2418 			 * objects, and never skip them, even if we are
2419 			 * suspending. This is necessary so that the
2420 			 * space deltas from this txg get integrated.
2421 			 */
2422 			if (OBJSET_BUF_HAS_PROJECTUSED(buf))
2423 				dsl_scan_visitdnode(scn, ds, osp->os_type,
2424 				    &osp->os_projectused_dnode,
2425 				    DMU_PROJECTUSED_OBJECT, tx);
2426 			dsl_scan_visitdnode(scn, ds, osp->os_type,
2427 			    &osp->os_groupused_dnode,
2428 			    DMU_GROUPUSED_OBJECT, tx);
2429 			dsl_scan_visitdnode(scn, ds, osp->os_type,
2430 			    &osp->os_userused_dnode,
2431 			    DMU_USERUSED_OBJECT, tx);
2432 		}
2433 		arc_buf_destroy(buf, &buf);
2434 	} else if (zfs_blkptr_verify(spa, bp,
2435 	    BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {
2436 		/*
2437 		 * Sanity check the block pointer contents, this is handled
2438 		 * by arc_read() for the cases above.
2439 		 */
2440 		scn->scn_phys.scn_errors++;
2441 		spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));
2442 		return (SET_ERROR(EINVAL));
2443 	}
2444 
2445 	return (0);
2446 }
2447 
2448 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)2449 dsl_scan_visitdnode(dsl_scan_t *scn, dsl_dataset_t *ds,
2450     dmu_objset_type_t ostype, dnode_phys_t *dnp,
2451     uint64_t object, dmu_tx_t *tx)
2452 {
2453 	int j;
2454 
2455 	for (j = 0; j < dnp->dn_nblkptr; j++) {
2456 		zbookmark_phys_t czb;
2457 
2458 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
2459 		    dnp->dn_nlevels - 1, j);
2460 		dsl_scan_visitbp(&dnp->dn_blkptr[j],
2461 		    &czb, dnp, ds, scn, ostype, tx);
2462 	}
2463 
2464 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
2465 		zbookmark_phys_t czb;
2466 		SET_BOOKMARK(&czb, ds ? ds->ds_object : 0, object,
2467 		    0, DMU_SPILL_BLKID);
2468 		dsl_scan_visitbp(DN_SPILL_BLKPTR(dnp),
2469 		    &czb, dnp, ds, scn, ostype, tx);
2470 	}
2471 }
2472 
2473 /*
2474  * The arguments are in this order because mdb can only print the
2475  * first 5; we want them to be useful.
2476  */
2477 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)2478 dsl_scan_visitbp(const blkptr_t *bp, const zbookmark_phys_t *zb,
2479     dnode_phys_t *dnp, dsl_dataset_t *ds, dsl_scan_t *scn,
2480     dmu_objset_type_t ostype, dmu_tx_t *tx)
2481 {
2482 	dsl_pool_t *dp = scn->scn_dp;
2483 
2484 	if (dsl_scan_check_suspend(scn, zb))
2485 		return;
2486 
2487 	if (dsl_scan_check_resume(scn, dnp, zb))
2488 		return;
2489 
2490 	scn->scn_visited_this_txg++;
2491 
2492 	if (BP_IS_HOLE(bp)) {
2493 		scn->scn_holes_this_txg++;
2494 		return;
2495 	}
2496 
2497 	if (BP_IS_REDACTED(bp)) {
2498 		ASSERT(dsl_dataset_feature_is_active(ds,
2499 		    SPA_FEATURE_REDACTED_DATASETS));
2500 		return;
2501 	}
2502 
2503 	/*
2504 	 * Check if this block contradicts any filesystem flags.
2505 	 */
2506 	spa_feature_t f = SPA_FEATURE_LARGE_BLOCKS;
2507 	if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE)
2508 		ASSERT(dsl_dataset_feature_is_active(ds, f));
2509 
2510 	f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
2511 	if (f != SPA_FEATURE_NONE)
2512 		ASSERT(dsl_dataset_feature_is_active(ds, f));
2513 
2514 	f = zio_compress_to_feature(BP_GET_COMPRESS(bp));
2515 	if (f != SPA_FEATURE_NONE)
2516 		ASSERT(dsl_dataset_feature_is_active(ds, f));
2517 
2518 	/*
2519 	 * Recurse any blocks that were written either logically or physically
2520 	 * at or after cur_min_txg.  About logical birth we care for traversal,
2521 	 * looking for any changes, while about physical for the actual scan.
2522 	 */
2523 	if (BP_GET_BIRTH(bp) <= scn->scn_phys.scn_cur_min_txg) {
2524 		scn->scn_lt_min_this_txg++;
2525 		return;
2526 	}
2527 
2528 	if (dsl_scan_recurse(scn, ds, ostype, dnp, bp, zb, tx) != 0)
2529 		return;
2530 
2531 	/*
2532 	 * If dsl_scan_ddt() has already visited this block, it will have
2533 	 * already done any translations or scrubbing, so don't call the
2534 	 * callback again.
2535 	 */
2536 	if (ddt_class_contains(dp->dp_spa,
2537 	    scn->scn_phys.scn_ddt_class_max, bp)) {
2538 		scn->scn_ddt_contained_this_txg++;
2539 		return;
2540 	}
2541 
2542 	/*
2543 	 * If this block is from the future (after cur_max_txg), then we
2544 	 * are doing this on behalf of a deleted snapshot, and we will
2545 	 * revisit the future block on the next pass of this dataset.
2546 	 * Don't scan it now unless we need to because something
2547 	 * under it was modified.
2548 	 */
2549 	if (BP_GET_PHYSICAL_BIRTH(bp) > scn->scn_phys.scn_cur_max_txg) {
2550 		scn->scn_gt_max_this_txg++;
2551 		return;
2552 	}
2553 
2554 	scan_funcs[scn->scn_phys.scn_func](dp, bp, zb);
2555 }
2556 
2557 static void
dsl_scan_visit_rootbp(dsl_scan_t * scn,dsl_dataset_t * ds,blkptr_t * bp,dmu_tx_t * tx)2558 dsl_scan_visit_rootbp(dsl_scan_t *scn, dsl_dataset_t *ds, blkptr_t *bp,
2559     dmu_tx_t *tx)
2560 {
2561 	zbookmark_phys_t zb;
2562 	scan_prefetch_ctx_t *spc;
2563 
2564 	SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
2565 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
2566 
2567 	if (ZB_IS_ZERO(&scn->scn_phys.scn_bookmark)) {
2568 		SET_BOOKMARK(&scn->scn_prefetch_bookmark,
2569 		    zb.zb_objset, 0, 0, 0);
2570 	} else {
2571 		scn->scn_prefetch_bookmark = scn->scn_phys.scn_bookmark;
2572 	}
2573 
2574 	scn->scn_objsets_visited_this_txg++;
2575 
2576 	spc = scan_prefetch_ctx_create(scn, NULL, FTAG);
2577 	dsl_scan_prefetch(spc, bp, &zb);
2578 	scan_prefetch_ctx_rele(spc, FTAG);
2579 
2580 	dsl_scan_visitbp(bp, &zb, NULL, ds, scn, DMU_OST_NONE, tx);
2581 
2582 	dprintf_ds(ds, "finished scan%s", "");
2583 }
2584 
2585 static void
ds_destroyed_scn_phys(dsl_dataset_t * ds,dsl_scan_phys_t * scn_phys)2586 ds_destroyed_scn_phys(dsl_dataset_t *ds, dsl_scan_phys_t *scn_phys)
2587 {
2588 	if (scn_phys->scn_bookmark.zb_objset == ds->ds_object) {
2589 		if (ds->ds_is_snapshot) {
2590 			/*
2591 			 * Note:
2592 			 *  - scn_cur_{min,max}_txg stays the same.
2593 			 *  - Setting the flag is not really necessary if
2594 			 *    scn_cur_max_txg == scn_max_txg, because there
2595 			 *    is nothing after this snapshot that we care
2596 			 *    about.  However, we set it anyway and then
2597 			 *    ignore it when we retraverse it in
2598 			 *    dsl_scan_visitds().
2599 			 */
2600 			scn_phys->scn_bookmark.zb_objset =
2601 			    dsl_dataset_phys(ds)->ds_next_snap_obj;
2602 			zfs_dbgmsg("destroying ds %llu on %s; currently "
2603 			    "traversing; reset zb_objset to %llu",
2604 			    (u_longlong_t)ds->ds_object,
2605 			    ds->ds_dir->dd_pool->dp_spa->spa_name,
2606 			    (u_longlong_t)dsl_dataset_phys(ds)->
2607 			    ds_next_snap_obj);
2608 			scn_phys->scn_flags |= DSF_VISIT_DS_AGAIN;
2609 		} else {
2610 			SET_BOOKMARK(&scn_phys->scn_bookmark,
2611 			    ZB_DESTROYED_OBJSET, 0, 0, 0);
2612 			zfs_dbgmsg("destroying ds %llu on %s; currently "
2613 			    "traversing; reset bookmark to -1,0,0,0",
2614 			    (u_longlong_t)ds->ds_object,
2615 			    ds->ds_dir->dd_pool->dp_spa->spa_name);
2616 		}
2617 	}
2618 }
2619 
2620 /*
2621  * Invoked when a dataset is destroyed. We need to make sure that:
2622  *
2623  * 1) If it is the dataset that was currently being scanned, we write
2624  *	a new dsl_scan_phys_t and marking the objset reference in it
2625  *	as destroyed.
2626  * 2) Remove it from the work queue, if it was present.
2627  *
2628  * If the dataset was actually a snapshot, instead of marking the dataset
2629  * as destroyed, we instead substitute the next snapshot in line.
2630  */
2631 void
dsl_scan_ds_destroyed(dsl_dataset_t * ds,dmu_tx_t * tx)2632 dsl_scan_ds_destroyed(dsl_dataset_t *ds, dmu_tx_t *tx)
2633 {
2634 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2635 	dsl_scan_t *scn = dp->dp_scan;
2636 	uint64_t mintxg;
2637 
2638 	if (!dsl_scan_is_running(scn))
2639 		return;
2640 
2641 	ds_destroyed_scn_phys(ds, &scn->scn_phys);
2642 	ds_destroyed_scn_phys(ds, &scn->scn_phys_cached);
2643 
2644 	if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2645 		scan_ds_queue_remove(scn, ds->ds_object);
2646 		if (ds->ds_is_snapshot)
2647 			scan_ds_queue_insert(scn,
2648 			    dsl_dataset_phys(ds)->ds_next_snap_obj, mintxg);
2649 	}
2650 
2651 	if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2652 	    ds->ds_object, &mintxg) == 0) {
2653 		ASSERT3U(dsl_dataset_phys(ds)->ds_num_children, <=, 1);
2654 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2655 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2656 		if (ds->ds_is_snapshot) {
2657 			/*
2658 			 * We keep the same mintxg; it could be >
2659 			 * ds_creation_txg if the previous snapshot was
2660 			 * deleted too.
2661 			 */
2662 			VERIFY(zap_add_int_key(dp->dp_meta_objset,
2663 			    scn->scn_phys.scn_queue_obj,
2664 			    dsl_dataset_phys(ds)->ds_next_snap_obj,
2665 			    mintxg, tx) == 0);
2666 			zfs_dbgmsg("destroying ds %llu on %s; in queue; "
2667 			    "replacing with %llu",
2668 			    (u_longlong_t)ds->ds_object,
2669 			    dp->dp_spa->spa_name,
2670 			    (u_longlong_t)dsl_dataset_phys(ds)->
2671 			    ds_next_snap_obj);
2672 		} else {
2673 			zfs_dbgmsg("destroying ds %llu on %s; in queue; "
2674 			    "removing",
2675 			    (u_longlong_t)ds->ds_object,
2676 			    dp->dp_spa->spa_name);
2677 		}
2678 	}
2679 
2680 	/*
2681 	 * dsl_scan_sync() should be called after this, and should sync
2682 	 * out our changed state, but just to be safe, do it here.
2683 	 */
2684 	dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2685 }
2686 
2687 static void
ds_snapshotted_bookmark(dsl_dataset_t * ds,zbookmark_phys_t * scn_bookmark)2688 ds_snapshotted_bookmark(dsl_dataset_t *ds, zbookmark_phys_t *scn_bookmark)
2689 {
2690 	if (scn_bookmark->zb_objset == ds->ds_object) {
2691 		scn_bookmark->zb_objset =
2692 		    dsl_dataset_phys(ds)->ds_prev_snap_obj;
2693 		zfs_dbgmsg("snapshotting ds %llu on %s; currently traversing; "
2694 		    "reset zb_objset to %llu",
2695 		    (u_longlong_t)ds->ds_object,
2696 		    ds->ds_dir->dd_pool->dp_spa->spa_name,
2697 		    (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2698 	}
2699 }
2700 
2701 /*
2702  * Called when a dataset is snapshotted. If we were currently traversing
2703  * this snapshot, we reset our bookmark to point at the newly created
2704  * snapshot. We also modify our work queue to remove the old snapshot and
2705  * replace with the new one.
2706  */
2707 void
dsl_scan_ds_snapshotted(dsl_dataset_t * ds,dmu_tx_t * tx)2708 dsl_scan_ds_snapshotted(dsl_dataset_t *ds, dmu_tx_t *tx)
2709 {
2710 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2711 	dsl_scan_t *scn = dp->dp_scan;
2712 	uint64_t mintxg;
2713 
2714 	if (!dsl_scan_is_running(scn))
2715 		return;
2716 
2717 	ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
2718 
2719 	ds_snapshotted_bookmark(ds, &scn->scn_phys.scn_bookmark);
2720 	ds_snapshotted_bookmark(ds, &scn->scn_phys_cached.scn_bookmark);
2721 
2722 	if (scan_ds_queue_contains(scn, ds->ds_object, &mintxg)) {
2723 		scan_ds_queue_remove(scn, ds->ds_object);
2724 		scan_ds_queue_insert(scn,
2725 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg);
2726 	}
2727 
2728 	if (zap_lookup_int_key(dp->dp_meta_objset, scn->scn_phys.scn_queue_obj,
2729 	    ds->ds_object, &mintxg) == 0) {
2730 		VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2731 		    scn->scn_phys.scn_queue_obj, ds->ds_object, tx));
2732 		VERIFY(zap_add_int_key(dp->dp_meta_objset,
2733 		    scn->scn_phys.scn_queue_obj,
2734 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, mintxg, tx) == 0);
2735 		zfs_dbgmsg("snapshotting ds %llu on %s; in queue; "
2736 		    "replacing with %llu",
2737 		    (u_longlong_t)ds->ds_object,
2738 		    dp->dp_spa->spa_name,
2739 		    (u_longlong_t)dsl_dataset_phys(ds)->ds_prev_snap_obj);
2740 	}
2741 
2742 	dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2743 }
2744 
2745 static void
ds_clone_swapped_bookmark(dsl_dataset_t * ds1,dsl_dataset_t * ds2,zbookmark_phys_t * scn_bookmark)2746 ds_clone_swapped_bookmark(dsl_dataset_t *ds1, dsl_dataset_t *ds2,
2747     zbookmark_phys_t *scn_bookmark)
2748 {
2749 	if (scn_bookmark->zb_objset == ds1->ds_object) {
2750 		scn_bookmark->zb_objset = ds2->ds_object;
2751 		zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "
2752 		    "reset zb_objset to %llu",
2753 		    (u_longlong_t)ds1->ds_object,
2754 		    ds1->ds_dir->dd_pool->dp_spa->spa_name,
2755 		    (u_longlong_t)ds2->ds_object);
2756 	} else if (scn_bookmark->zb_objset == ds2->ds_object) {
2757 		scn_bookmark->zb_objset = ds1->ds_object;
2758 		zfs_dbgmsg("clone_swap ds %llu on %s; currently traversing; "
2759 		    "reset zb_objset to %llu",
2760 		    (u_longlong_t)ds2->ds_object,
2761 		    ds2->ds_dir->dd_pool->dp_spa->spa_name,
2762 		    (u_longlong_t)ds1->ds_object);
2763 	}
2764 }
2765 
2766 /*
2767  * Called when an origin dataset and its clone are swapped.  If we were
2768  * currently traversing the dataset, we need to switch to traversing the
2769  * newly promoted clone.
2770  */
2771 void
dsl_scan_ds_clone_swapped(dsl_dataset_t * ds1,dsl_dataset_t * ds2,dmu_tx_t * tx)2772 dsl_scan_ds_clone_swapped(dsl_dataset_t *ds1, dsl_dataset_t *ds2, dmu_tx_t *tx)
2773 {
2774 	dsl_pool_t *dp = ds1->ds_dir->dd_pool;
2775 	dsl_scan_t *scn = dp->dp_scan;
2776 	uint64_t mintxg1, mintxg2;
2777 	boolean_t ds1_queued, ds2_queued;
2778 
2779 	if (!dsl_scan_is_running(scn))
2780 		return;
2781 
2782 	ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys.scn_bookmark);
2783 	ds_clone_swapped_bookmark(ds1, ds2, &scn->scn_phys_cached.scn_bookmark);
2784 
2785 	/*
2786 	 * Handle the in-memory scan queue.
2787 	 */
2788 	ds1_queued = scan_ds_queue_contains(scn, ds1->ds_object, &mintxg1);
2789 	ds2_queued = scan_ds_queue_contains(scn, ds2->ds_object, &mintxg2);
2790 
2791 	/* Sanity checking. */
2792 	if (ds1_queued) {
2793 		ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2794 		ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2795 	}
2796 	if (ds2_queued) {
2797 		ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2798 		ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2799 	}
2800 
2801 	if (ds1_queued && ds2_queued) {
2802 		/*
2803 		 * If both are queued, we don't need to do anything.
2804 		 * The swapping code below would not handle this case correctly,
2805 		 * since we can't insert ds2 if it is already there. That's
2806 		 * because scan_ds_queue_insert() prohibits a duplicate insert
2807 		 * and panics.
2808 		 */
2809 	} else if (ds1_queued) {
2810 		scan_ds_queue_remove(scn, ds1->ds_object);
2811 		scan_ds_queue_insert(scn, ds2->ds_object, mintxg1);
2812 	} else if (ds2_queued) {
2813 		scan_ds_queue_remove(scn, ds2->ds_object);
2814 		scan_ds_queue_insert(scn, ds1->ds_object, mintxg2);
2815 	}
2816 
2817 	/*
2818 	 * Handle the on-disk scan queue.
2819 	 * The on-disk state is an out-of-date version of the in-memory state,
2820 	 * so the in-memory and on-disk values for ds1_queued and ds2_queued may
2821 	 * be different. Therefore we need to apply the swap logic to the
2822 	 * on-disk state independently of the in-memory state.
2823 	 */
2824 	ds1_queued = zap_lookup_int_key(dp->dp_meta_objset,
2825 	    scn->scn_phys.scn_queue_obj, ds1->ds_object, &mintxg1) == 0;
2826 	ds2_queued = zap_lookup_int_key(dp->dp_meta_objset,
2827 	    scn->scn_phys.scn_queue_obj, ds2->ds_object, &mintxg2) == 0;
2828 
2829 	/* Sanity checking. */
2830 	if (ds1_queued) {
2831 		ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2832 		ASSERT3U(mintxg1, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2833 	}
2834 	if (ds2_queued) {
2835 		ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds1)->ds_prev_snap_txg);
2836 		ASSERT3U(mintxg2, ==, dsl_dataset_phys(ds2)->ds_prev_snap_txg);
2837 	}
2838 
2839 	if (ds1_queued && ds2_queued) {
2840 		/*
2841 		 * If both are queued, we don't need to do anything.
2842 		 * Alternatively, we could check for EEXIST from
2843 		 * zap_add_int_key() and back out to the original state, but
2844 		 * that would be more work than checking for this case upfront.
2845 		 */
2846 	} else if (ds1_queued) {
2847 		VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2848 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, tx));
2849 		VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2850 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, mintxg1, tx));
2851 		zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "
2852 		    "replacing with %llu",
2853 		    (u_longlong_t)ds1->ds_object,
2854 		    dp->dp_spa->spa_name,
2855 		    (u_longlong_t)ds2->ds_object);
2856 	} else if (ds2_queued) {
2857 		VERIFY3S(0, ==, zap_remove_int(dp->dp_meta_objset,
2858 		    scn->scn_phys.scn_queue_obj, ds2->ds_object, tx));
2859 		VERIFY3S(0, ==, zap_add_int_key(dp->dp_meta_objset,
2860 		    scn->scn_phys.scn_queue_obj, ds1->ds_object, mintxg2, tx));
2861 		zfs_dbgmsg("clone_swap ds %llu on %s; in queue; "
2862 		    "replacing with %llu",
2863 		    (u_longlong_t)ds2->ds_object,
2864 		    dp->dp_spa->spa_name,
2865 		    (u_longlong_t)ds1->ds_object);
2866 	}
2867 
2868 	dsl_scan_sync_state(scn, tx, SYNC_CACHED);
2869 }
2870 
2871 static int
enqueue_clones_cb(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)2872 enqueue_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
2873 {
2874 	uint64_t originobj = *(uint64_t *)arg;
2875 	dsl_dataset_t *ds;
2876 	int err;
2877 	dsl_scan_t *scn = dp->dp_scan;
2878 
2879 	if (dsl_dir_phys(hds->ds_dir)->dd_origin_obj != originobj)
2880 		return (0);
2881 
2882 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
2883 	if (err)
2884 		return (err);
2885 
2886 	while (dsl_dataset_phys(ds)->ds_prev_snap_obj != originobj) {
2887 		dsl_dataset_t *prev;
2888 		err = dsl_dataset_hold_obj(dp,
2889 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2890 
2891 		dsl_dataset_rele(ds, FTAG);
2892 		if (err)
2893 			return (err);
2894 		ds = prev;
2895 	}
2896 	mutex_enter(&scn->scn_queue_lock);
2897 	scan_ds_queue_insert(scn, ds->ds_object,
2898 	    dsl_dataset_phys(ds)->ds_prev_snap_txg);
2899 	mutex_exit(&scn->scn_queue_lock);
2900 	dsl_dataset_rele(ds, FTAG);
2901 	return (0);
2902 }
2903 
2904 static void
dsl_scan_visitds(dsl_scan_t * scn,uint64_t dsobj,dmu_tx_t * tx)2905 dsl_scan_visitds(dsl_scan_t *scn, uint64_t dsobj, dmu_tx_t *tx)
2906 {
2907 	dsl_pool_t *dp = scn->scn_dp;
2908 	dsl_dataset_t *ds;
2909 
2910 	VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
2911 
2912 	if (scn->scn_phys.scn_cur_min_txg >=
2913 	    scn->scn_phys.scn_max_txg) {
2914 		/*
2915 		 * This can happen if this snapshot was created after the
2916 		 * scan started, and we already completed a previous snapshot
2917 		 * that was created after the scan started.  This snapshot
2918 		 * only references blocks with:
2919 		 *
2920 		 *	birth < our ds_creation_txg
2921 		 *	cur_min_txg is no less than ds_creation_txg.
2922 		 *	We have already visited these blocks.
2923 		 * or
2924 		 *	birth > scn_max_txg
2925 		 *	The scan requested not to visit these blocks.
2926 		 *
2927 		 * Subsequent snapshots (and clones) can reference our
2928 		 * blocks, or blocks with even higher birth times.
2929 		 * Therefore we do not need to visit them either,
2930 		 * so we do not add them to the work queue.
2931 		 *
2932 		 * Note that checking for cur_min_txg >= cur_max_txg
2933 		 * is not sufficient, because in that case we may need to
2934 		 * visit subsequent snapshots.  This happens when min_txg > 0,
2935 		 * which raises cur_min_txg.  In this case we will visit
2936 		 * this dataset but skip all of its blocks, because the
2937 		 * rootbp's birth time is < cur_min_txg.  Then we will
2938 		 * add the next snapshots/clones to the work queue.
2939 		 */
2940 		char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2941 		dsl_dataset_name(ds, dsname);
2942 		zfs_dbgmsg("scanning dataset %llu (%s) is unnecessary because "
2943 		    "cur_min_txg (%llu) >= max_txg (%llu)",
2944 		    (longlong_t)dsobj, dsname,
2945 		    (longlong_t)scn->scn_phys.scn_cur_min_txg,
2946 		    (longlong_t)scn->scn_phys.scn_max_txg);
2947 		kmem_free(dsname, MAXNAMELEN);
2948 
2949 		goto out;
2950 	}
2951 
2952 	/*
2953 	 * Only the ZIL in the head (non-snapshot) is valid. Even though
2954 	 * snapshots can have ZIL block pointers (which may be the same
2955 	 * BP as in the head), they must be ignored. In addition, $ORIGIN
2956 	 * doesn't have a objset (i.e. its ds_bp is a hole) so we don't
2957 	 * need to look for a ZIL in it either. So we traverse the ZIL here,
2958 	 * rather than in scan_recurse(), because the regular snapshot
2959 	 * block-sharing rules don't apply to it.
2960 	 */
2961 	if (!dsl_dataset_is_snapshot(ds) &&
2962 	    (dp->dp_origin_snap == NULL ||
2963 	    ds->ds_dir != dp->dp_origin_snap->ds_dir)) {
2964 		objset_t *os;
2965 		if (dmu_objset_from_ds(ds, &os) != 0) {
2966 			goto out;
2967 		}
2968 		dsl_scan_zil(dp, &os->os_zil_header);
2969 	}
2970 
2971 	/*
2972 	 * Iterate over the bps in this ds.
2973 	 */
2974 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2975 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2976 	dsl_scan_visit_rootbp(scn, ds, &dsl_dataset_phys(ds)->ds_bp, tx);
2977 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2978 
2979 	char *dsname = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN, KM_SLEEP);
2980 	dsl_dataset_name(ds, dsname);
2981 	zfs_dbgmsg("scanned dataset %llu (%s) with min=%llu max=%llu; "
2982 	    "suspending=%u",
2983 	    (longlong_t)dsobj, dsname,
2984 	    (longlong_t)scn->scn_phys.scn_cur_min_txg,
2985 	    (longlong_t)scn->scn_phys.scn_cur_max_txg,
2986 	    (int)scn->scn_suspending);
2987 	kmem_free(dsname, ZFS_MAX_DATASET_NAME_LEN);
2988 
2989 	if (scn->scn_suspending)
2990 		goto out;
2991 
2992 	/*
2993 	 * We've finished this pass over this dataset.
2994 	 */
2995 
2996 	/*
2997 	 * If we did not completely visit this dataset, do another pass.
2998 	 */
2999 	if (scn->scn_phys.scn_flags & DSF_VISIT_DS_AGAIN) {
3000 		zfs_dbgmsg("incomplete pass on %s; visiting again",
3001 		    dp->dp_spa->spa_name);
3002 		scn->scn_phys.scn_flags &= ~DSF_VISIT_DS_AGAIN;
3003 		scan_ds_queue_insert(scn, ds->ds_object,
3004 		    scn->scn_phys.scn_cur_max_txg);
3005 		goto out;
3006 	}
3007 
3008 	/*
3009 	 * Add descendant datasets to work queue.
3010 	 */
3011 	if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0) {
3012 		scan_ds_queue_insert(scn,
3013 		    dsl_dataset_phys(ds)->ds_next_snap_obj,
3014 		    dsl_dataset_phys(ds)->ds_creation_txg);
3015 	}
3016 	if (dsl_dataset_phys(ds)->ds_num_children > 1) {
3017 		boolean_t usenext = B_FALSE;
3018 		if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
3019 			uint64_t count;
3020 			/*
3021 			 * A bug in a previous version of the code could
3022 			 * cause upgrade_clones_cb() to not set
3023 			 * ds_next_snap_obj when it should, leading to a
3024 			 * missing entry.  Therefore we can only use the
3025 			 * next_clones_obj when its count is correct.
3026 			 */
3027 			int err = zap_count(dp->dp_meta_objset,
3028 			    dsl_dataset_phys(ds)->ds_next_clones_obj, &count);
3029 			if (err == 0 &&
3030 			    count == dsl_dataset_phys(ds)->ds_num_children - 1)
3031 				usenext = B_TRUE;
3032 		}
3033 
3034 		if (usenext) {
3035 			zap_cursor_t zc;
3036 			zap_attribute_t *za = zap_attribute_alloc();
3037 			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3038 			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3039 			    zap_cursor_retrieve(&zc, za) == 0;
3040 			    (void) zap_cursor_advance(&zc)) {
3041 				scan_ds_queue_insert(scn,
3042 				    zfs_strtonum(za->za_name, NULL),
3043 				    dsl_dataset_phys(ds)->ds_creation_txg);
3044 			}
3045 			zap_cursor_fini(&zc);
3046 			zap_attribute_free(za);
3047 		} else {
3048 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3049 			    enqueue_clones_cb, &ds->ds_object,
3050 			    DS_FIND_CHILDREN));
3051 		}
3052 	}
3053 
3054 out:
3055 	dsl_dataset_rele(ds, FTAG);
3056 }
3057 
3058 static int
enqueue_cb(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)3059 enqueue_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
3060 {
3061 	(void) arg;
3062 	dsl_dataset_t *ds;
3063 	int err;
3064 	dsl_scan_t *scn = dp->dp_scan;
3065 
3066 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
3067 	if (err)
3068 		return (err);
3069 
3070 	while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
3071 		dsl_dataset_t *prev;
3072 		err = dsl_dataset_hold_obj(dp,
3073 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
3074 		if (err) {
3075 			dsl_dataset_rele(ds, FTAG);
3076 			return (err);
3077 		}
3078 
3079 		/*
3080 		 * If this is a clone, we don't need to worry about it for now.
3081 		 */
3082 		if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object) {
3083 			dsl_dataset_rele(ds, FTAG);
3084 			dsl_dataset_rele(prev, FTAG);
3085 			return (0);
3086 		}
3087 		dsl_dataset_rele(ds, FTAG);
3088 		ds = prev;
3089 	}
3090 
3091 	mutex_enter(&scn->scn_queue_lock);
3092 	scan_ds_queue_insert(scn, ds->ds_object,
3093 	    dsl_dataset_phys(ds)->ds_prev_snap_txg);
3094 	mutex_exit(&scn->scn_queue_lock);
3095 	dsl_dataset_rele(ds, FTAG);
3096 	return (0);
3097 }
3098 
3099 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)3100 dsl_scan_ddt_entry(dsl_scan_t *scn, enum zio_checksum checksum,
3101     ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
3102 {
3103 	(void) tx;
3104 	const ddt_key_t *ddk = &ddlwe->ddlwe_key;
3105 	blkptr_t bp;
3106 	zbookmark_phys_t zb = { 0 };
3107 
3108 	if (!dsl_scan_is_running(scn))
3109 		return;
3110 
3111 	/*
3112 	 * This function is special because it is the only thing
3113 	 * that can add scan_io_t's to the vdev scan queues from
3114 	 * outside dsl_scan_sync(). For the most part this is ok
3115 	 * as long as it is called from within syncing context.
3116 	 * However, dsl_scan_sync() expects that no new sio's will
3117 	 * be added between when all the work for a scan is done
3118 	 * and the next txg when the scan is actually marked as
3119 	 * completed. This check ensures we do not issue new sio's
3120 	 * during this period.
3121 	 */
3122 	if (scn->scn_done_txg != 0)
3123 		return;
3124 
3125 	for (int p = 0; p < DDT_NPHYS(ddt); p++) {
3126 		ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
3127 		uint64_t phys_birth = ddt_phys_birth(&ddlwe->ddlwe_phys, v);
3128 
3129 		if (phys_birth == 0 || phys_birth > scn->scn_phys.scn_max_txg)
3130 			continue;
3131 		ddt_bp_create(checksum, ddk, &ddlwe->ddlwe_phys, v, &bp);
3132 
3133 		scn->scn_visited_this_txg++;
3134 		scan_funcs[scn->scn_phys.scn_func](scn->scn_dp, &bp, &zb);
3135 	}
3136 }
3137 
3138 /*
3139  * Scrub/dedup interaction.
3140  *
3141  * If there are N references to a deduped block, we don't want to scrub it
3142  * N times -- ideally, we should scrub it exactly once.
3143  *
3144  * We leverage the fact that the dde's replication class (ddt_class_t)
3145  * is ordered from highest replication class (DDT_CLASS_DITTO) to lowest
3146  * (DDT_CLASS_UNIQUE) so that we may walk the DDT in that order.
3147  *
3148  * To prevent excess scrubbing, the scrub begins by walking the DDT
3149  * to find all blocks with refcnt > 1, and scrubs each of these once.
3150  * Since there are two replication classes which contain blocks with
3151  * refcnt > 1, we scrub the highest replication class (DDT_CLASS_DITTO) first.
3152  * Finally the top-down scrub begins, only visiting blocks with refcnt == 1.
3153  *
3154  * There would be nothing more to say if a block's refcnt couldn't change
3155  * during a scrub, but of course it can so we must account for changes
3156  * in a block's replication class.
3157  *
3158  * Here's an example of what can occur:
3159  *
3160  * If a block has refcnt > 1 during the DDT scrub phase, but has refcnt == 1
3161  * when visited during the top-down scrub phase, it will be scrubbed twice.
3162  * This negates our scrub optimization, but is otherwise harmless.
3163  *
3164  * If a block has refcnt == 1 during the DDT scrub phase, but has refcnt > 1
3165  * on each visit during the top-down scrub phase, it will never be scrubbed.
3166  * To catch this, ddt_sync_entry() notifies the scrub code whenever a block's
3167  * reference class transitions to a higher level (i.e DDT_CLASS_UNIQUE to
3168  * DDT_CLASS_DUPLICATE); if it transitions from refcnt == 1 to refcnt > 1
3169  * while a scrub is in progress, it scrubs the block right then.
3170  */
3171 static void
dsl_scan_ddt(dsl_scan_t * scn,dmu_tx_t * tx)3172 dsl_scan_ddt(dsl_scan_t *scn, dmu_tx_t *tx)
3173 {
3174 	ddt_bookmark_t *ddb = &scn->scn_phys.scn_ddt_bookmark;
3175 	ddt_lightweight_entry_t ddlwe = {0};
3176 	int error;
3177 	uint64_t n = 0;
3178 
3179 	while ((error = ddt_walk(scn->scn_dp->dp_spa, ddb, &ddlwe)) == 0) {
3180 		ddt_t *ddt;
3181 
3182 		if (ddb->ddb_class > scn->scn_phys.scn_ddt_class_max)
3183 			break;
3184 		dprintf("visiting ddb=%llu/%llu/%llu/%llx\n",
3185 		    (longlong_t)ddb->ddb_class,
3186 		    (longlong_t)ddb->ddb_type,
3187 		    (longlong_t)ddb->ddb_checksum,
3188 		    (longlong_t)ddb->ddb_cursor);
3189 
3190 		/* There should be no pending changes to the dedup table */
3191 		ddt = scn->scn_dp->dp_spa->spa_ddt[ddb->ddb_checksum];
3192 		ASSERT(avl_first(&ddt->ddt_tree) == NULL);
3193 
3194 		dsl_scan_ddt_entry(scn, ddb->ddb_checksum, ddt, &ddlwe, tx);
3195 		n++;
3196 
3197 		if (dsl_scan_check_suspend(scn, NULL))
3198 			break;
3199 	}
3200 
3201 	if (error == EAGAIN) {
3202 		dsl_scan_check_suspend(scn, NULL);
3203 		error = 0;
3204 
3205 		zfs_dbgmsg("waiting for ddt to become ready for scan "
3206 		    "on %s with class_max = %u; suspending=%u",
3207 		    scn->scn_dp->dp_spa->spa_name,
3208 		    (int)scn->scn_phys.scn_ddt_class_max,
3209 		    (int)scn->scn_suspending);
3210 	} else
3211 		zfs_dbgmsg("scanned %llu ddt entries on %s with "
3212 		    "class_max = %u; suspending=%u", (longlong_t)n,
3213 		    scn->scn_dp->dp_spa->spa_name,
3214 		    (int)scn->scn_phys.scn_ddt_class_max,
3215 		    (int)scn->scn_suspending);
3216 
3217 	ASSERT(error == 0 || error == ENOENT);
3218 	ASSERT(error != ENOENT ||
3219 	    ddb->ddb_class > scn->scn_phys.scn_ddt_class_max);
3220 }
3221 
3222 static uint64_t
dsl_scan_ds_maxtxg(dsl_dataset_t * ds)3223 dsl_scan_ds_maxtxg(dsl_dataset_t *ds)
3224 {
3225 	uint64_t smt = ds->ds_dir->dd_pool->dp_scan->scn_phys.scn_max_txg;
3226 	if (ds->ds_is_snapshot)
3227 		return (MIN(smt, dsl_dataset_phys(ds)->ds_creation_txg));
3228 	return (smt);
3229 }
3230 
3231 static void
dsl_scan_visit(dsl_scan_t * scn,dmu_tx_t * tx)3232 dsl_scan_visit(dsl_scan_t *scn, dmu_tx_t *tx)
3233 {
3234 	scan_ds_t *sds;
3235 	dsl_pool_t *dp = scn->scn_dp;
3236 
3237 	if (scn->scn_phys.scn_ddt_bookmark.ddb_class <=
3238 	    scn->scn_phys.scn_ddt_class_max) {
3239 		scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
3240 		scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
3241 		dsl_scan_ddt(scn, tx);
3242 		if (scn->scn_suspending)
3243 			return;
3244 	}
3245 
3246 	if (scn->scn_phys.scn_bookmark.zb_objset == DMU_META_OBJSET) {
3247 		/* First do the MOS & ORIGIN */
3248 
3249 		scn->scn_phys.scn_cur_min_txg = scn->scn_phys.scn_min_txg;
3250 		scn->scn_phys.scn_cur_max_txg = scn->scn_phys.scn_max_txg;
3251 		dsl_scan_visit_rootbp(scn, NULL,
3252 		    &dp->dp_meta_rootbp, tx);
3253 		if (scn->scn_suspending)
3254 			return;
3255 
3256 		if (spa_version(dp->dp_spa) < SPA_VERSION_DSL_SCRUB) {
3257 			VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3258 			    enqueue_cb, NULL, DS_FIND_CHILDREN));
3259 		} else {
3260 			dsl_scan_visitds(scn,
3261 			    dp->dp_origin_snap->ds_object, tx);
3262 		}
3263 		ASSERT(!scn->scn_suspending);
3264 	} else if (scn->scn_phys.scn_bookmark.zb_objset !=
3265 	    ZB_DESTROYED_OBJSET) {
3266 		uint64_t dsobj = scn->scn_phys.scn_bookmark.zb_objset;
3267 		/*
3268 		 * If we were suspended, continue from here. Note if the
3269 		 * ds we were suspended on was deleted, the zb_objset may
3270 		 * be -1, so we will skip this and find a new objset
3271 		 * below.
3272 		 */
3273 		dsl_scan_visitds(scn, dsobj, tx);
3274 		if (scn->scn_suspending)
3275 			return;
3276 	}
3277 
3278 	/*
3279 	 * In case we suspended right at the end of the ds, zero the
3280 	 * bookmark so we don't think that we're still trying to resume.
3281 	 */
3282 	memset(&scn->scn_phys.scn_bookmark, 0, sizeof (zbookmark_phys_t));
3283 
3284 	/*
3285 	 * Keep pulling things out of the dataset avl queue. Updates to the
3286 	 * persistent zap-object-as-queue happen only at checkpoints.
3287 	 */
3288 	while ((sds = avl_first(&scn->scn_queue)) != NULL) {
3289 		dsl_dataset_t *ds;
3290 		uint64_t dsobj = sds->sds_dsobj;
3291 		uint64_t txg = sds->sds_txg;
3292 
3293 		/* dequeue and free the ds from the queue */
3294 		scan_ds_queue_remove(scn, dsobj);
3295 		sds = NULL;
3296 
3297 		/* set up min / max txg */
3298 		VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
3299 		if (txg != 0) {
3300 			scn->scn_phys.scn_cur_min_txg =
3301 			    MAX(scn->scn_phys.scn_min_txg, txg);
3302 		} else {
3303 			scn->scn_phys.scn_cur_min_txg =
3304 			    MAX(scn->scn_phys.scn_min_txg,
3305 			    dsl_dataset_phys(ds)->ds_prev_snap_txg);
3306 		}
3307 		scn->scn_phys.scn_cur_max_txg = dsl_scan_ds_maxtxg(ds);
3308 		dsl_dataset_rele(ds, FTAG);
3309 
3310 		dsl_scan_visitds(scn, dsobj, tx);
3311 		if (scn->scn_suspending)
3312 			return;
3313 	}
3314 
3315 	/* No more objsets to fetch, we're done */
3316 	scn->scn_phys.scn_bookmark.zb_objset = ZB_DESTROYED_OBJSET;
3317 	ASSERT0(scn->scn_suspending);
3318 }
3319 
3320 static uint64_t
dsl_scan_count_data_disks(spa_t * spa)3321 dsl_scan_count_data_disks(spa_t *spa)
3322 {
3323 	vdev_t *rvd = spa->spa_root_vdev;
3324 	uint64_t i, leaves = 0;
3325 
3326 	for (i = 0; i < rvd->vdev_children; i++) {
3327 		vdev_t *vd = rvd->vdev_child[i];
3328 		if (vd->vdev_islog || vd->vdev_isspare || vd->vdev_isl2cache)
3329 			continue;
3330 		leaves += vdev_get_ndisks(vd) - vdev_get_nparity(vd);
3331 	}
3332 	return (leaves);
3333 }
3334 
3335 static void
scan_io_queues_update_zio_stats(dsl_scan_io_queue_t * q,const blkptr_t * bp)3336 scan_io_queues_update_zio_stats(dsl_scan_io_queue_t *q, const blkptr_t *bp)
3337 {
3338 	int i;
3339 	uint64_t cur_size = 0;
3340 
3341 	for (i = 0; i < BP_GET_NDVAS(bp); i++) {
3342 		cur_size += DVA_GET_ASIZE(&bp->blk_dva[i]);
3343 	}
3344 
3345 	q->q_total_zio_size_this_txg += cur_size;
3346 	q->q_zios_this_txg++;
3347 }
3348 
3349 static void
scan_io_queues_update_seg_stats(dsl_scan_io_queue_t * q,uint64_t start,uint64_t end)3350 scan_io_queues_update_seg_stats(dsl_scan_io_queue_t *q, uint64_t start,
3351     uint64_t end)
3352 {
3353 	q->q_total_seg_size_this_txg += end - start;
3354 	q->q_segs_this_txg++;
3355 }
3356 
3357 static boolean_t
scan_io_queue_check_suspend(dsl_scan_t * scn)3358 scan_io_queue_check_suspend(dsl_scan_t *scn)
3359 {
3360 	/* See comment in dsl_scan_check_suspend() */
3361 	uint64_t curr_time_ns = getlrtime();
3362 	uint64_t scan_time_ns = curr_time_ns - scn->scn_sync_start_time;
3363 	uint64_t sync_time_ns = curr_time_ns -
3364 	    scn->scn_dp->dp_spa->spa_sync_starttime;
3365 	uint64_t dirty_min_bytes = zfs_dirty_data_max *
3366 	    zfs_vdev_async_write_active_min_dirty_percent / 100;
3367 	uint_t mintime = (scn->scn_phys.scn_func == POOL_SCAN_RESILVER) ?
3368 	    zfs_resilver_min_time_ms : zfs_scrub_min_time_ms;
3369 
3370 	return ((NSEC2MSEC(scan_time_ns) > mintime &&
3371 	    (scn->scn_dp->dp_dirty_total >= dirty_min_bytes ||
3372 	    txg_sync_waiting(scn->scn_dp) ||
3373 	    NSEC2SEC(sync_time_ns) >= zfs_txg_timeout)) ||
3374 	    spa_shutting_down(scn->scn_dp->dp_spa));
3375 }
3376 
3377 /*
3378  * Given a list of scan_io_t's in io_list, this issues the I/Os out to
3379  * disk. This consumes the io_list and frees the scan_io_t's. This is
3380  * called when emptying queues, either when we're up against the memory
3381  * limit or when we have finished scanning. Returns B_TRUE if we stopped
3382  * processing the list before we finished. Any sios that were not issued
3383  * will remain in the io_list.
3384  */
3385 static boolean_t
scan_io_queue_issue(dsl_scan_io_queue_t * queue,list_t * io_list)3386 scan_io_queue_issue(dsl_scan_io_queue_t *queue, list_t *io_list)
3387 {
3388 	dsl_scan_t *scn = queue->q_scn;
3389 	scan_io_t *sio;
3390 	boolean_t suspended = B_FALSE;
3391 
3392 	while ((sio = list_head(io_list)) != NULL) {
3393 		blkptr_t bp;
3394 
3395 		if (scan_io_queue_check_suspend(scn)) {
3396 			suspended = B_TRUE;
3397 			break;
3398 		}
3399 
3400 		sio2bp(sio, &bp);
3401 		scan_exec_io(scn->scn_dp, &bp, sio->sio_flags,
3402 		    &sio->sio_zb, queue);
3403 		(void) list_remove_head(io_list);
3404 		scan_io_queues_update_zio_stats(queue, &bp);
3405 		sio_free(sio);
3406 	}
3407 	return (suspended);
3408 }
3409 
3410 /*
3411  * This function removes sios from an IO queue which reside within a given
3412  * zfs_range_seg_t and inserts them (in offset order) into a list. Note that
3413  * we only ever return a maximum of 32 sios at once. If there are more sios
3414  * to process within this segment that did not make it onto the list we
3415  * return B_TRUE and otherwise B_FALSE.
3416  */
3417 static boolean_t
scan_io_queue_gather(dsl_scan_io_queue_t * queue,zfs_range_seg_t * rs,list_t * list)3418 scan_io_queue_gather(dsl_scan_io_queue_t *queue, zfs_range_seg_t *rs,
3419     list_t *list)
3420 {
3421 	scan_io_t *srch_sio, *sio, *next_sio;
3422 	avl_index_t idx;
3423 	uint_t num_sios = 0;
3424 	int64_t bytes_issued = 0;
3425 
3426 	ASSERT(rs != NULL);
3427 	ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3428 
3429 	srch_sio = sio_alloc(1, B_FALSE);
3430 	srch_sio->sio_nr_dvas = 1;
3431 	SIO_SET_OFFSET(srch_sio, zfs_rs_get_start(rs, queue->q_exts_by_addr));
3432 
3433 	/*
3434 	 * The exact start of the extent might not contain any matching zios,
3435 	 * so if that's the case, examine the next one in the tree.
3436 	 */
3437 	sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
3438 	sio_free(srch_sio);
3439 
3440 	if (sio == NULL)
3441 		sio = avl_nearest(&queue->q_sios_by_addr, idx, AVL_AFTER);
3442 
3443 	while (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,
3444 	    queue->q_exts_by_addr) && num_sios <= 32) {
3445 		ASSERT3U(SIO_GET_OFFSET(sio), >=, zfs_rs_get_start(rs,
3446 		    queue->q_exts_by_addr));
3447 		ASSERT3U(SIO_GET_END_OFFSET(sio), <=, zfs_rs_get_end(rs,
3448 		    queue->q_exts_by_addr));
3449 
3450 		next_sio = AVL_NEXT(&queue->q_sios_by_addr, sio);
3451 		avl_remove(&queue->q_sios_by_addr, sio);
3452 		if (avl_is_empty(&queue->q_sios_by_addr))
3453 			atomic_add_64(&queue->q_scn->scn_queues_pending, -1);
3454 		queue->q_sio_memused -= SIO_GET_MUSED(sio);
3455 
3456 		bytes_issued += SIO_GET_ASIZE(sio);
3457 		num_sios++;
3458 		list_insert_tail(list, sio);
3459 		sio = next_sio;
3460 	}
3461 
3462 	/*
3463 	 * We limit the number of sios we process at once to 32 to avoid
3464 	 * biting off more than we can chew. If we didn't take everything
3465 	 * in the segment we update it to reflect the work we were able to
3466 	 * complete. Otherwise, we remove it from the range tree entirely.
3467 	 */
3468 	if (sio != NULL && SIO_GET_OFFSET(sio) < zfs_rs_get_end(rs,
3469 	    queue->q_exts_by_addr)) {
3470 		zfs_range_tree_adjust_fill(queue->q_exts_by_addr, rs,
3471 		    -bytes_issued);
3472 		zfs_range_tree_resize_segment(queue->q_exts_by_addr, rs,
3473 		    SIO_GET_OFFSET(sio), zfs_rs_get_end(rs,
3474 		    queue->q_exts_by_addr) - SIO_GET_OFFSET(sio));
3475 		queue->q_last_ext_addr = SIO_GET_OFFSET(sio);
3476 		return (B_TRUE);
3477 	} else {
3478 		uint64_t rstart = zfs_rs_get_start(rs, queue->q_exts_by_addr);
3479 		uint64_t rend = zfs_rs_get_end(rs, queue->q_exts_by_addr);
3480 		zfs_range_tree_remove(queue->q_exts_by_addr, rstart, rend -
3481 		    rstart);
3482 		queue->q_last_ext_addr = -1;
3483 		return (B_FALSE);
3484 	}
3485 }
3486 
3487 /*
3488  * This is called from the queue emptying thread and selects the next
3489  * extent from which we are to issue I/Os. The behavior of this function
3490  * depends on the state of the scan, the current memory consumption and
3491  * whether or not we are performing a scan shutdown.
3492  * 1) We select extents in an elevator algorithm (LBA-order) if the scan
3493  * 	needs to perform a checkpoint
3494  * 2) We select the largest available extent if we are up against the
3495  * 	memory limit.
3496  * 3) Otherwise we don't select any extents.
3497  */
3498 static zfs_range_seg_t *
scan_io_queue_fetch_ext(dsl_scan_io_queue_t * queue)3499 scan_io_queue_fetch_ext(dsl_scan_io_queue_t *queue)
3500 {
3501 	dsl_scan_t *scn = queue->q_scn;
3502 	zfs_range_tree_t *rt = queue->q_exts_by_addr;
3503 
3504 	ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
3505 	ASSERT(scn->scn_is_sorted);
3506 
3507 	if (!scn->scn_checkpointing && !scn->scn_clearing)
3508 		return (NULL);
3509 
3510 	/*
3511 	 * During normal clearing, we want to issue our largest segments
3512 	 * first, keeping IO as sequential as possible, and leaving the
3513 	 * smaller extents for later with the hope that they might eventually
3514 	 * grow to larger sequential segments. However, when the scan is
3515 	 * checkpointing, no new extents will be added to the sorting queue,
3516 	 * so the way we are sorted now is as good as it will ever get.
3517 	 * In this case, we instead switch to issuing extents in LBA order.
3518 	 */
3519 	if ((zfs_scan_issue_strategy < 1 && scn->scn_checkpointing) ||
3520 	    zfs_scan_issue_strategy == 1)
3521 		return (zfs_range_tree_first(rt));
3522 
3523 	/*
3524 	 * Try to continue previous extent if it is not completed yet.  After
3525 	 * shrink in scan_io_queue_gather() it may no longer be the best, but
3526 	 * otherwise we leave shorter remnant every txg.
3527 	 */
3528 	uint64_t start;
3529 	uint64_t size = 1ULL << rt->rt_shift;
3530 	zfs_range_seg_t *addr_rs;
3531 	if (queue->q_last_ext_addr != -1) {
3532 		start = queue->q_last_ext_addr;
3533 		addr_rs = zfs_range_tree_find(rt, start, size);
3534 		if (addr_rs != NULL)
3535 			return (addr_rs);
3536 	}
3537 
3538 	/*
3539 	 * Nothing to continue, so find new best extent.
3540 	 */
3541 	uint64_t *v = zfs_btree_first(&queue->q_exts_by_size, NULL);
3542 	if (v == NULL)
3543 		return (NULL);
3544 	queue->q_last_ext_addr = start = *v << rt->rt_shift;
3545 
3546 	/*
3547 	 * We need to get the original entry in the by_addr tree so we can
3548 	 * modify it.
3549 	 */
3550 	addr_rs = zfs_range_tree_find(rt, start, size);
3551 	ASSERT3P(addr_rs, !=, NULL);
3552 	ASSERT3U(zfs_rs_get_start(addr_rs, rt), ==, start);
3553 	ASSERT3U(zfs_rs_get_end(addr_rs, rt), >, start);
3554 	return (addr_rs);
3555 }
3556 
3557 static void
scan_io_queues_run_one(void * arg)3558 scan_io_queues_run_one(void *arg)
3559 {
3560 	dsl_scan_io_queue_t *queue = arg;
3561 	kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
3562 	boolean_t suspended = B_FALSE;
3563 	zfs_range_seg_t *rs;
3564 	scan_io_t *sio;
3565 	zio_t *zio;
3566 	list_t sio_list;
3567 
3568 	ASSERT(queue->q_scn->scn_is_sorted);
3569 
3570 	list_create(&sio_list, sizeof (scan_io_t),
3571 	    offsetof(scan_io_t, sio_nodes.sio_list_node));
3572 	zio = zio_null(queue->q_scn->scn_zio_root, queue->q_scn->scn_dp->dp_spa,
3573 	    NULL, NULL, NULL, ZIO_FLAG_CANFAIL);
3574 	mutex_enter(q_lock);
3575 	queue->q_zio = zio;
3576 
3577 	/* Calculate maximum in-flight bytes for this vdev. */
3578 	queue->q_maxinflight_bytes = MAX(1, zfs_scan_vdev_limit *
3579 	    (vdev_get_ndisks(queue->q_vd) - vdev_get_nparity(queue->q_vd)));
3580 
3581 	/* reset per-queue scan statistics for this txg */
3582 	queue->q_total_seg_size_this_txg = 0;
3583 	queue->q_segs_this_txg = 0;
3584 	queue->q_total_zio_size_this_txg = 0;
3585 	queue->q_zios_this_txg = 0;
3586 
3587 	/* loop until we run out of time or sios */
3588 	while ((rs = scan_io_queue_fetch_ext(queue)) != NULL) {
3589 		uint64_t seg_start = 0, seg_end = 0;
3590 		boolean_t more_left;
3591 
3592 		ASSERT(list_is_empty(&sio_list));
3593 
3594 		/* loop while we still have sios left to process in this rs */
3595 		do {
3596 			scan_io_t *first_sio, *last_sio;
3597 
3598 			/*
3599 			 * We have selected which extent needs to be
3600 			 * processed next. Gather up the corresponding sios.
3601 			 */
3602 			more_left = scan_io_queue_gather(queue, rs, &sio_list);
3603 			ASSERT(!list_is_empty(&sio_list));
3604 			first_sio = list_head(&sio_list);
3605 			last_sio = list_tail(&sio_list);
3606 
3607 			seg_end = SIO_GET_END_OFFSET(last_sio);
3608 			if (seg_start == 0)
3609 				seg_start = SIO_GET_OFFSET(first_sio);
3610 
3611 			/*
3612 			 * Issuing sios can take a long time so drop the
3613 			 * queue lock. The sio queue won't be updated by
3614 			 * other threads since we're in syncing context so
3615 			 * we can be sure that our trees will remain exactly
3616 			 * as we left them.
3617 			 */
3618 			mutex_exit(q_lock);
3619 			suspended = scan_io_queue_issue(queue, &sio_list);
3620 			mutex_enter(q_lock);
3621 
3622 			if (suspended)
3623 				break;
3624 		} while (more_left);
3625 
3626 		/* update statistics for debugging purposes */
3627 		scan_io_queues_update_seg_stats(queue, seg_start, seg_end);
3628 
3629 		if (suspended)
3630 			break;
3631 	}
3632 
3633 	/*
3634 	 * If we were suspended in the middle of processing,
3635 	 * requeue any unfinished sios and exit.
3636 	 */
3637 	while ((sio = list_remove_head(&sio_list)) != NULL)
3638 		scan_io_queue_insert_impl(queue, sio);
3639 
3640 	queue->q_zio = NULL;
3641 	mutex_exit(q_lock);
3642 	zio_nowait(zio);
3643 	list_destroy(&sio_list);
3644 }
3645 
3646 /*
3647  * Performs an emptying run on all scan queues in the pool. This just
3648  * punches out one thread per top-level vdev, each of which processes
3649  * only that vdev's scan queue. We can parallelize the I/O here because
3650  * we know that each queue's I/Os only affect its own top-level vdev.
3651  *
3652  * This function waits for the queue runs to complete, and must be
3653  * called from dsl_scan_sync (or in general, syncing context).
3654  */
3655 static void
scan_io_queues_run(dsl_scan_t * scn)3656 scan_io_queues_run(dsl_scan_t *scn)
3657 {
3658 	spa_t *spa = scn->scn_dp->dp_spa;
3659 
3660 	ASSERT(scn->scn_is_sorted);
3661 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3662 
3663 	if (scn->scn_queues_pending == 0)
3664 		return;
3665 
3666 	if (scn->scn_taskq == NULL) {
3667 		int nthreads = spa->spa_root_vdev->vdev_children;
3668 
3669 		/*
3670 		 * We need to make this taskq *always* execute as many
3671 		 * threads in parallel as we have top-level vdevs and no
3672 		 * less, otherwise strange serialization of the calls to
3673 		 * scan_io_queues_run_one can occur during spa_sync runs
3674 		 * and that significantly impacts performance.
3675 		 */
3676 		scn->scn_taskq = taskq_create("dsl_scan_iss", nthreads,
3677 		    minclsyspri, nthreads, nthreads, TASKQ_PREPOPULATE);
3678 	}
3679 
3680 	for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3681 		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3682 
3683 		mutex_enter(&vd->vdev_scan_io_queue_lock);
3684 		if (vd->vdev_scan_io_queue != NULL) {
3685 			VERIFY(taskq_dispatch(scn->scn_taskq,
3686 			    scan_io_queues_run_one, vd->vdev_scan_io_queue,
3687 			    TQ_SLEEP) != TASKQID_INVALID);
3688 		}
3689 		mutex_exit(&vd->vdev_scan_io_queue_lock);
3690 	}
3691 
3692 	/*
3693 	 * Wait for the queues to finish issuing their IOs for this run
3694 	 * before we return. There may still be IOs in flight at this
3695 	 * point.
3696 	 */
3697 	taskq_wait(scn->scn_taskq);
3698 }
3699 
3700 static boolean_t
dsl_scan_async_block_should_pause(dsl_scan_t * scn)3701 dsl_scan_async_block_should_pause(dsl_scan_t *scn)
3702 {
3703 	uint64_t elapsed_nanosecs;
3704 
3705 	if (zfs_recover)
3706 		return (B_FALSE);
3707 
3708 	if (zfs_async_block_max_blocks != 0 &&
3709 	    scn->scn_visited_this_txg >= zfs_async_block_max_blocks) {
3710 		return (B_TRUE);
3711 	}
3712 
3713 	if (zfs_max_async_dedup_frees != 0 &&
3714 	    scn->scn_async_frees_this_txg >= zfs_max_async_dedup_frees) {
3715 		return (B_TRUE);
3716 	}
3717 
3718 	/*
3719 	 * Async frees of deduplicated or cloned blocks dirty DDT/BRT
3720 	 * ZAPs in this txg's sync context, which is not limited by the
3721 	 * write throttle.  Pause if this txg has already accumulated too
3722 	 * much dirty data, including the reservations for DDT/BRT updates
3723 	 * that have not been applied yet at this point of the sync.
3724 	 */
3725 	dsl_pool_t *dp = scn->scn_dp;
3726 	uint64_t txg = spa_syncing_txg(dp->dp_spa) & TXG_MASK;
3727 	if (dp->dp_dirty_pertxg[txg] + dp->dp_sync_reserve_pertxg[txg] >
3728 	    zfs_dirty_data_max / 2) {
3729 		return (B_TRUE);
3730 	}
3731 
3732 	elapsed_nanosecs = getlrtime() - scn->scn_sync_start_time;
3733 	return (elapsed_nanosecs / (NANOSEC / 2) > zfs_txg_timeout ||
3734 	    (NSEC2MSEC(elapsed_nanosecs) > scn->scn_async_block_min_time_ms &&
3735 	    txg_sync_waiting(scn->scn_dp)) ||
3736 	    spa_shutting_down(scn->scn_dp->dp_spa));
3737 }
3738 
3739 static int
dsl_scan_free_block_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)3740 dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3741 {
3742 	dsl_scan_t *scn = arg;
3743 
3744 	if (!scn->scn_is_bptree ||
3745 	    (BP_GET_LEVEL(bp) == 0 && BP_GET_TYPE(bp) != DMU_OT_OBJSET)) {
3746 		if (dsl_scan_async_block_should_pause(scn))
3747 			return (SET_ERROR(ERESTART));
3748 	}
3749 
3750 	zio_t *zio = zio_free_sync(scn->scn_zio_root, scn->scn_dp->dp_spa,
3751 	    dmu_tx_get_txg(tx), bp, 0);
3752 	dsl_dir_diduse_space(tx->tx_pool->dp_free_dir, DD_USED_HEAD,
3753 	    -bp_get_dsize_sync(scn->scn_dp->dp_spa, bp),
3754 	    -BP_GET_PSIZE(bp), -BP_GET_UCSIZE(bp), tx);
3755 	scn->scn_visited_this_txg++;
3756 	if (zio != NULL) {
3757 		/*
3758 		 * zio_free_sync() returned a ZIO, meaning this is an
3759 		 * async I/O (dedup, clone or gang block).
3760 		 */
3761 		scn->scn_async_frees_this_txg++;
3762 
3763 		/*
3764 		 * Reserve dirty space for the DDT/BRT ZAP updates this
3765 		 * free will produce later in this txg's sync, providing
3766 		 * feedback for the pause check above.
3767 		 */
3768 		spa_t *spa = scn->scn_dp->dp_spa;
3769 		uint64_t space = 0;
3770 		if (BP_GET_DEDUP(bp))
3771 			space = ddt_sync_dirty_est(spa);
3772 		else if (brt_maybe_exists(spa, bp))
3773 			space = brt_sync_dirty_est(spa);
3774 		dsl_pool_sync_reserve(scn->scn_dp, space, tx);
3775 
3776 		zio_nowait(zio);
3777 
3778 		/*
3779 		 * After issuing N async ZIOs, wait for them to complete.
3780 		 * This makes time limits work with actual I/O completion
3781 		 * times, not just queuing times.
3782 		 */
3783 		uint64_t i = zfs_async_free_zio_wait_interval;
3784 		if (i != 0 && (scn->scn_async_frees_this_txg % i) == 0) {
3785 			VERIFY0(zio_wait(scn->scn_zio_root));
3786 			scn->scn_zio_root = zio_root(scn->scn_dp->dp_spa, NULL,
3787 			    NULL, ZIO_FLAG_MUSTSUCCEED);
3788 		}
3789 	}
3790 	return (0);
3791 }
3792 
3793 static void
dsl_scan_update_stats(dsl_scan_t * scn)3794 dsl_scan_update_stats(dsl_scan_t *scn)
3795 {
3796 	spa_t *spa = scn->scn_dp->dp_spa;
3797 	uint64_t i;
3798 	uint64_t seg_size_total = 0, zio_size_total = 0;
3799 	uint64_t seg_count_total = 0, zio_count_total = 0;
3800 
3801 	for (i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3802 		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3803 		dsl_scan_io_queue_t *queue = vd->vdev_scan_io_queue;
3804 
3805 		if (queue == NULL)
3806 			continue;
3807 
3808 		seg_size_total += queue->q_total_seg_size_this_txg;
3809 		zio_size_total += queue->q_total_zio_size_this_txg;
3810 		seg_count_total += queue->q_segs_this_txg;
3811 		zio_count_total += queue->q_zios_this_txg;
3812 	}
3813 
3814 	if (seg_count_total == 0 || zio_count_total == 0) {
3815 		scn->scn_avg_seg_size_this_txg = 0;
3816 		scn->scn_avg_zio_size_this_txg = 0;
3817 		scn->scn_segs_this_txg = 0;
3818 		scn->scn_zios_this_txg = 0;
3819 		return;
3820 	}
3821 
3822 	scn->scn_avg_seg_size_this_txg = seg_size_total / seg_count_total;
3823 	scn->scn_avg_zio_size_this_txg = zio_size_total / zio_count_total;
3824 	scn->scn_segs_this_txg = seg_count_total;
3825 	scn->scn_zios_this_txg = zio_count_total;
3826 }
3827 
3828 static int
bpobj_dsl_scan_free_block_cb(void * arg,const blkptr_t * bp,boolean_t bp_freed,dmu_tx_t * tx)3829 bpobj_dsl_scan_free_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3830     dmu_tx_t *tx)
3831 {
3832 	ASSERT(!bp_freed);
3833 	return (dsl_scan_free_block_cb(arg, bp, tx));
3834 }
3835 
3836 static int
dsl_scan_obsolete_block_cb(void * arg,const blkptr_t * bp,boolean_t bp_freed,dmu_tx_t * tx)3837 dsl_scan_obsolete_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
3838     dmu_tx_t *tx)
3839 {
3840 	ASSERT(!bp_freed);
3841 	dsl_scan_t *scn = arg;
3842 	const dva_t *dva = &bp->blk_dva[0];
3843 
3844 	if (dsl_scan_async_block_should_pause(scn))
3845 		return (SET_ERROR(ERESTART));
3846 
3847 	spa_vdev_indirect_mark_obsolete(scn->scn_dp->dp_spa,
3848 	    DVA_GET_VDEV(dva), DVA_GET_OFFSET(dva),
3849 	    DVA_GET_ASIZE(dva), tx);
3850 	scn->scn_visited_this_txg++;
3851 	return (0);
3852 }
3853 
3854 boolean_t
dsl_scan_active(dsl_scan_t * scn)3855 dsl_scan_active(dsl_scan_t *scn)
3856 {
3857 	spa_t *spa = scn->scn_dp->dp_spa;
3858 	uint64_t used = 0, comp, uncomp;
3859 	boolean_t clones_left;
3860 
3861 	if (spa->spa_load_state != SPA_LOAD_NONE)
3862 		return (B_FALSE);
3863 	if (spa_shutting_down(spa))
3864 		return (B_FALSE);
3865 	if ((dsl_scan_is_running(scn) && !dsl_scan_is_paused_scrub(scn)) ||
3866 	    (scn->scn_async_destroying && !scn->scn_async_stalled))
3867 		return (B_TRUE);
3868 
3869 	if (spa_version(scn->scn_dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
3870 		(void) bpobj_space(&scn->scn_dp->dp_free_bpobj,
3871 		    &used, &comp, &uncomp);
3872 	}
3873 	clones_left = spa_livelist_delete_check(spa);
3874 	return ((used != 0) || (clones_left));
3875 }
3876 
3877 boolean_t
dsl_errorscrub_active(dsl_scan_t * scn)3878 dsl_errorscrub_active(dsl_scan_t *scn)
3879 {
3880 	spa_t *spa = scn->scn_dp->dp_spa;
3881 	if (spa->spa_load_state != SPA_LOAD_NONE)
3882 		return (B_FALSE);
3883 	if (spa_shutting_down(spa))
3884 		return (B_FALSE);
3885 	if (dsl_errorscrubbing(scn->scn_dp))
3886 		return (B_TRUE);
3887 	return (B_FALSE);
3888 }
3889 
3890 static boolean_t
dsl_scan_check_deferred(vdev_t * vd)3891 dsl_scan_check_deferred(vdev_t *vd)
3892 {
3893 	boolean_t need_resilver = B_FALSE;
3894 
3895 	for (int c = 0; c < vd->vdev_children; c++) {
3896 		need_resilver |=
3897 		    dsl_scan_check_deferred(vd->vdev_child[c]);
3898 	}
3899 
3900 	if (!vdev_is_concrete(vd) || vd->vdev_aux ||
3901 	    !vd->vdev_ops->vdev_op_leaf)
3902 		return (need_resilver);
3903 
3904 	if (!vd->vdev_resilver_deferred)
3905 		need_resilver = B_TRUE;
3906 
3907 	return (need_resilver);
3908 }
3909 
3910 static boolean_t
dsl_scan_need_resilver(spa_t * spa,const dva_t * dva,size_t psize,uint64_t phys_birth)3911 dsl_scan_need_resilver(spa_t *spa, const dva_t *dva, size_t psize,
3912     uint64_t phys_birth)
3913 {
3914 	vdev_t *vd;
3915 
3916 	vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3917 
3918 	if (vd->vdev_ops == &vdev_indirect_ops) {
3919 		/*
3920 		 * The indirect vdev can point to multiple
3921 		 * vdevs.  For simplicity, always create
3922 		 * the resilver zio_t. zio_vdev_io_start()
3923 		 * will bypass the child resilver i/o's if
3924 		 * they are on vdevs that don't have DTL's.
3925 		 */
3926 		return (B_TRUE);
3927 	}
3928 
3929 	if (DVA_GET_GANG(dva)) {
3930 		/*
3931 		 * Gang members may be spread across multiple
3932 		 * vdevs, so the best estimate we have is the
3933 		 * scrub range, which has already been checked.
3934 		 * XXX -- it would be better to change our
3935 		 * allocation policy to ensure that all
3936 		 * gang members reside on the same vdev.
3937 		 */
3938 		return (B_TRUE);
3939 	}
3940 
3941 	/*
3942 	 * Check if the top-level vdev must resilver this offset.
3943 	 * When the offset does not intersect with a dirty leaf DTL
3944 	 * then it may be possible to skip the resilver IO.  The psize
3945 	 * is provided instead of asize to simplify the check for RAIDZ.
3946 	 */
3947 	if (!vdev_dtl_need_resilver(vd, dva, psize, phys_birth))
3948 		return (B_FALSE);
3949 
3950 	/*
3951 	 * Check that this top-level vdev has a device under it which
3952 	 * is resilvering and is not deferred.
3953 	 */
3954 	if (!dsl_scan_check_deferred(vd))
3955 		return (B_FALSE);
3956 
3957 	return (B_TRUE);
3958 }
3959 
3960 static int
dsl_process_async_destroys(dsl_pool_t * dp,dmu_tx_t * tx)3961 dsl_process_async_destroys(dsl_pool_t *dp, dmu_tx_t *tx)
3962 {
3963 	dsl_scan_t *scn = dp->dp_scan;
3964 	spa_t *spa = dp->dp_spa;
3965 	int err = 0;
3966 
3967 	if (spa_suspend_async_destroy(spa))
3968 		return (0);
3969 
3970 	if (zfs_free_bpobj_enabled &&
3971 	    spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3972 		scn->scn_is_bptree = B_FALSE;
3973 		scn->scn_async_block_min_time_ms = zfs_free_min_time_ms;
3974 		scn->scn_zio_root = zio_root(spa, NULL,
3975 		    NULL, ZIO_FLAG_MUSTSUCCEED);
3976 		err = bpobj_iterate(&dp->dp_free_bpobj,
3977 		    bpobj_dsl_scan_free_block_cb, scn, tx);
3978 		VERIFY0(zio_wait(scn->scn_zio_root));
3979 		scn->scn_zio_root = NULL;
3980 
3981 		if (err != 0 && err != ERESTART)
3982 			zfs_panic_recover("error %u from bpobj_iterate()", err);
3983 	}
3984 
3985 	if (err == 0 && spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3986 		ASSERT(scn->scn_async_destroying);
3987 		scn->scn_is_bptree = B_TRUE;
3988 		scn->scn_zio_root = zio_root(spa, NULL,
3989 		    NULL, ZIO_FLAG_MUSTSUCCEED);
3990 		err = bptree_iterate(dp->dp_meta_objset,
3991 		    dp->dp_bptree_obj, B_TRUE, dsl_scan_free_block_cb, scn, tx);
3992 		VERIFY0(zio_wait(scn->scn_zio_root));
3993 		scn->scn_zio_root = NULL;
3994 
3995 		if (err == EIO || err == ECKSUM) {
3996 			err = 0;
3997 		} else if (err != 0 && err != ERESTART) {
3998 			zfs_panic_recover("error %u from "
3999 			    "traverse_dataset_destroyed()", err);
4000 		}
4001 
4002 		if (bptree_is_empty(dp->dp_meta_objset, dp->dp_bptree_obj)) {
4003 			/* finished; deactivate async destroy feature */
4004 			spa_feature_decr(spa, SPA_FEATURE_ASYNC_DESTROY, tx);
4005 			ASSERT(!spa_feature_is_active(spa,
4006 			    SPA_FEATURE_ASYNC_DESTROY));
4007 			VERIFY0(zap_remove(dp->dp_meta_objset,
4008 			    DMU_POOL_DIRECTORY_OBJECT,
4009 			    DMU_POOL_BPTREE_OBJ, tx));
4010 			VERIFY0(bptree_free(dp->dp_meta_objset,
4011 			    dp->dp_bptree_obj, tx));
4012 			dp->dp_bptree_obj = 0;
4013 			scn->scn_async_destroying = B_FALSE;
4014 			scn->scn_async_stalled = B_FALSE;
4015 		} else {
4016 			/*
4017 			 * If we didn't make progress, mark the async
4018 			 * destroy as stalled, so that we will not initiate
4019 			 * a spa_sync() on its behalf.  Note that we only
4020 			 * check this if we are not finished, because if the
4021 			 * bptree had no blocks for us to visit, we can
4022 			 * finish without "making progress".
4023 			 */
4024 			scn->scn_async_stalled =
4025 			    (scn->scn_visited_this_txg == 0);
4026 		}
4027 	}
4028 	if (scn->scn_visited_this_txg) {
4029 		zfs_dbgmsg("freed %llu blocks in %llums from "
4030 		    "free_bpobj/bptree on %s in txg %llu; err=%u",
4031 		    (longlong_t)scn->scn_visited_this_txg,
4032 		    (longlong_t)
4033 		    NSEC2MSEC(getlrtime() - scn->scn_sync_start_time),
4034 		    spa->spa_name, (longlong_t)tx->tx_txg, err);
4035 		scn->scn_visited_this_txg = 0;
4036 		scn->scn_async_frees_this_txg = 0;
4037 
4038 		/*
4039 		 * Write out changes to the DDT and the BRT that may be required
4040 		 * as a result of the blocks freed.  This ensures that the DDT
4041 		 * and the BRT are clean when a scrub/resilver runs.
4042 		 */
4043 		ddt_sync(spa, tx->tx_txg);
4044 		brt_sync(spa, tx->tx_txg);
4045 	}
4046 	if (err != 0)
4047 		return (err);
4048 	if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
4049 	    zfs_free_leak_on_eio &&
4050 	    (dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes != 0 ||
4051 	    dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes != 0 ||
4052 	    dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes != 0)) {
4053 		/*
4054 		 * We have finished background destroying, but there is still
4055 		 * some space left in the dp_free_dir. Transfer this leaked
4056 		 * space to the dp_leak_dir.
4057 		 */
4058 		if (dp->dp_leak_dir == NULL) {
4059 			rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
4060 			(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
4061 			    LEAK_DIR_NAME, tx);
4062 			VERIFY0(dsl_pool_open_special_dir(dp,
4063 			    LEAK_DIR_NAME, &dp->dp_leak_dir));
4064 			rrw_exit(&dp->dp_config_rwlock, FTAG);
4065 		}
4066 		dsl_dir_diduse_space(dp->dp_leak_dir, DD_USED_HEAD,
4067 		    dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
4068 		    dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
4069 		    dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
4070 		dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
4071 		    -dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes,
4072 		    -dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes,
4073 		    -dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes, tx);
4074 	}
4075 
4076 	if (dp->dp_free_dir != NULL && !scn->scn_async_destroying &&
4077 	    !spa_livelist_delete_check(spa)) {
4078 		/* finished; verify that space accounting went to zero */
4079 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_used_bytes);
4080 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_compressed_bytes);
4081 		ASSERT0(dsl_dir_phys(dp->dp_free_dir)->dd_uncompressed_bytes);
4082 	}
4083 
4084 	spa_notify_waiters(spa);
4085 
4086 	EQUIV(bpobj_is_open(&dp->dp_obsolete_bpobj),
4087 	    0 == zap_contains(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4088 	    DMU_POOL_OBSOLETE_BPOBJ));
4089 	if (err == 0 && bpobj_is_open(&dp->dp_obsolete_bpobj)) {
4090 		ASSERT(spa_feature_is_active(dp->dp_spa,
4091 		    SPA_FEATURE_OBSOLETE_COUNTS));
4092 
4093 		scn->scn_is_bptree = B_FALSE;
4094 		scn->scn_async_block_min_time_ms = zfs_obsolete_min_time_ms;
4095 		err = bpobj_iterate(&dp->dp_obsolete_bpobj,
4096 		    dsl_scan_obsolete_block_cb, scn, tx);
4097 		if (err != 0 && err != ERESTART)
4098 			zfs_panic_recover("error %u from bpobj_iterate()", err);
4099 
4100 		if (bpobj_is_empty(&dp->dp_obsolete_bpobj))
4101 			dsl_pool_destroy_obsolete_bpobj(dp, tx);
4102 	}
4103 	return (0);
4104 }
4105 
4106 static void
name_to_bookmark(char * buf,zbookmark_phys_t * zb)4107 name_to_bookmark(char *buf, zbookmark_phys_t *zb)
4108 {
4109 	zb->zb_objset = zfs_strtonum(buf, &buf);
4110 	ASSERT(*buf == ':');
4111 	zb->zb_object = zfs_strtonum(buf + 1, &buf);
4112 	ASSERT(*buf == ':');
4113 	zb->zb_level = (int)zfs_strtonum(buf + 1, &buf);
4114 	ASSERT(*buf == ':');
4115 	zb->zb_blkid = zfs_strtonum(buf + 1, &buf);
4116 	ASSERT(*buf == '\0');
4117 }
4118 
4119 static void
name_to_object(char * buf,uint64_t * obj)4120 name_to_object(char *buf, uint64_t *obj)
4121 {
4122 	*obj = zfs_strtonum(buf, &buf);
4123 	ASSERT(*buf == '\0');
4124 }
4125 
4126 static void
read_by_block_level(dsl_scan_t * scn,zbookmark_phys_t zb)4127 read_by_block_level(dsl_scan_t *scn, zbookmark_phys_t zb)
4128 {
4129 	dsl_pool_t *dp = scn->scn_dp;
4130 	dsl_dataset_t *ds;
4131 	objset_t *os;
4132 	if (dsl_dataset_hold_obj(dp, zb.zb_objset, FTAG, &ds) != 0)
4133 		return;
4134 
4135 	if (dmu_objset_from_ds(ds, &os) != 0) {
4136 		dsl_dataset_rele(ds, FTAG);
4137 		return;
4138 	}
4139 
4140 	/*
4141 	 * If the key is not loaded dbuf_dnode_findbp() will error out with
4142 	 * EACCES. However in that case dnode_hold() will eventually call
4143 	 * dbuf_read()->zio_wait() which may call spa_log_error(). This will
4144 	 * lead to a deadlock due to us holding the mutex spa_errlist_lock.
4145 	 * Avoid this by checking here if the keys are loaded, if not return.
4146 	 * If the keys are not loaded the head_errlog feature is meaningless
4147 	 * as we cannot figure out the birth txg of the block pointer.
4148 	 */
4149 	if (dsl_dataset_get_keystatus(ds->ds_dir) ==
4150 	    ZFS_KEYSTATUS_UNAVAILABLE) {
4151 		dsl_dataset_rele(ds, FTAG);
4152 		return;
4153 	}
4154 
4155 	dnode_t *dn;
4156 	blkptr_t bp;
4157 
4158 	if (dnode_hold(os, zb.zb_object, FTAG, &dn) != 0) {
4159 		dsl_dataset_rele(ds, FTAG);
4160 		return;
4161 	}
4162 
4163 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
4164 	int error = dbuf_dnode_findbp(dn, zb.zb_level, zb.zb_blkid, &bp, NULL,
4165 	    NULL);
4166 
4167 	if (error) {
4168 		rw_exit(&dn->dn_struct_rwlock);
4169 		dnode_rele(dn, FTAG);
4170 		dsl_dataset_rele(ds, FTAG);
4171 		return;
4172 	}
4173 
4174 	if (!error && BP_IS_HOLE(&bp)) {
4175 		rw_exit(&dn->dn_struct_rwlock);
4176 		dnode_rele(dn, FTAG);
4177 		dsl_dataset_rele(ds, FTAG);
4178 		return;
4179 	}
4180 
4181 	int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_CANFAIL |
4182 	    ZIO_FLAG_SCRUB;
4183 
4184 	/*
4185 	 * A normal scrub reads raw blocks, but a thorough scrub
4186 	 * must decrypt/decompress, so it does not set ZIO_FLAG_RAW.
4187 	 */
4188 	if (!dsl_scan_is_thorough_scrub(scn))
4189 		zio_flags |= ZIO_FLAG_RAW;
4190 
4191 	/* If it's an intent log block, failure is expected. */
4192 	if (zb.zb_level == ZB_ZIL_LEVEL)
4193 		zio_flags |= ZIO_FLAG_SPECULATIVE;
4194 
4195 	ASSERT(!BP_IS_EMBEDDED(&bp));
4196 	scan_exec_io(dp, &bp, zio_flags, &zb, NULL);
4197 	rw_exit(&dn->dn_struct_rwlock);
4198 	dnode_rele(dn, FTAG);
4199 	dsl_dataset_rele(ds, FTAG);
4200 }
4201 
4202 /*
4203  * We keep track of the scrubbed error blocks in "count". This will be used
4204  * when deciding whether we exceeded zfs_scrub_error_blocks_per_txg. This
4205  * function is modelled after check_filesystem().
4206  */
4207 static int
scrub_filesystem(spa_t * spa,uint64_t fs,zbookmark_err_phys_t * zep,int * count)4208 scrub_filesystem(spa_t *spa, uint64_t fs, zbookmark_err_phys_t *zep,
4209     int *count)
4210 {
4211 	dsl_dataset_t *ds;
4212 	dsl_pool_t *dp = spa->spa_dsl_pool;
4213 	dsl_scan_t *scn = dp->dp_scan;
4214 
4215 	int error = dsl_dataset_hold_obj(dp, fs, FTAG, &ds);
4216 	if (error != 0)
4217 		return (error);
4218 
4219 	uint64_t latest_txg;
4220 	uint64_t txg_to_consider = spa->spa_syncing_txg;
4221 	boolean_t check_snapshot = B_TRUE;
4222 
4223 	error = find_birth_txg(ds, zep, &latest_txg);
4224 
4225 	/*
4226 	 * If find_birth_txg() errors out, then err on the side of caution and
4227 	 * proceed. In worst case scenario scrub all objects. If zep->zb_birth
4228 	 * is 0 (e.g. in case of encryption with unloaded keys) also proceed to
4229 	 * scrub all objects.
4230 	 */
4231 	if (error == 0 && zep->zb_birth == latest_txg) {
4232 		/* Block neither free nor re written. */
4233 		zbookmark_phys_t zb;
4234 		zep_to_zb(fs, zep, &zb);
4235 		scn->scn_zio_root = zio_root(spa, NULL, NULL,
4236 		    ZIO_FLAG_CANFAIL);
4237 		/* We have already acquired the config lock for spa */
4238 		read_by_block_level(scn, zb);
4239 
4240 		(void) zio_wait(scn->scn_zio_root);
4241 		scn->scn_zio_root = NULL;
4242 
4243 		scn->errorscrub_phys.dep_examined++;
4244 		scn->errorscrub_phys.dep_to_examine--;
4245 		(*count)++;
4246 		if ((*count) == zfs_scrub_error_blocks_per_txg ||
4247 		    dsl_error_scrub_check_suspend(scn, &zb)) {
4248 			dsl_dataset_rele(ds, FTAG);
4249 			return (SET_ERROR(EFAULT));
4250 		}
4251 
4252 		check_snapshot = B_FALSE;
4253 	} else if (error == 0) {
4254 		txg_to_consider = latest_txg;
4255 	}
4256 
4257 	/*
4258 	 * Retrieve the number of snapshots if the dataset is not a snapshot.
4259 	 */
4260 	uint64_t snap_count = 0;
4261 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj != 0) {
4262 
4263 		error = zap_count(spa->spa_meta_objset,
4264 		    dsl_dataset_phys(ds)->ds_snapnames_zapobj, &snap_count);
4265 
4266 		if (error != 0) {
4267 			dsl_dataset_rele(ds, FTAG);
4268 			return (error);
4269 		}
4270 	}
4271 
4272 	if (snap_count == 0) {
4273 		/* Filesystem without snapshots. */
4274 		dsl_dataset_rele(ds, FTAG);
4275 		return (0);
4276 	}
4277 
4278 	uint64_t snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4279 	uint64_t snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4280 
4281 	dsl_dataset_rele(ds, FTAG);
4282 
4283 	/* Check only snapshots created from this file system. */
4284 	while (snap_obj != 0 && zep->zb_birth < snap_obj_txg &&
4285 	    snap_obj_txg <= txg_to_consider) {
4286 
4287 		error = dsl_dataset_hold_obj(dp, snap_obj, FTAG, &ds);
4288 		if (error != 0)
4289 			return (error);
4290 
4291 		if (dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj != fs) {
4292 			snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4293 			snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4294 			dsl_dataset_rele(ds, FTAG);
4295 			continue;
4296 		}
4297 
4298 		boolean_t affected = B_TRUE;
4299 		if (check_snapshot) {
4300 			uint64_t blk_txg;
4301 			error = find_birth_txg(ds, zep, &blk_txg);
4302 
4303 			/*
4304 			 * Scrub the snapshot also when zb_birth == 0 or when
4305 			 * find_birth_txg() returns an error.
4306 			 */
4307 			affected = (error == 0 && zep->zb_birth == blk_txg) ||
4308 			    (error != 0) || (zep->zb_birth == 0);
4309 		}
4310 
4311 		/* Scrub snapshots. */
4312 		if (affected) {
4313 			zbookmark_phys_t zb;
4314 			zep_to_zb(snap_obj, zep, &zb);
4315 			scn->scn_zio_root = zio_root(spa, NULL, NULL,
4316 			    ZIO_FLAG_CANFAIL);
4317 			/* We have already acquired the config lock for spa */
4318 			read_by_block_level(scn, zb);
4319 
4320 			(void) zio_wait(scn->scn_zio_root);
4321 			scn->scn_zio_root = NULL;
4322 
4323 			scn->errorscrub_phys.dep_examined++;
4324 			scn->errorscrub_phys.dep_to_examine--;
4325 			(*count)++;
4326 			if ((*count) == zfs_scrub_error_blocks_per_txg ||
4327 			    dsl_error_scrub_check_suspend(scn, &zb)) {
4328 				dsl_dataset_rele(ds, FTAG);
4329 				return (EFAULT);
4330 			}
4331 		}
4332 		snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
4333 		snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4334 		dsl_dataset_rele(ds, FTAG);
4335 	}
4336 	return (0);
4337 }
4338 
4339 void
dsl_errorscrub_sync(dsl_pool_t * dp,dmu_tx_t * tx)4340 dsl_errorscrub_sync(dsl_pool_t *dp, dmu_tx_t *tx)
4341 {
4342 	spa_t *spa = dp->dp_spa;
4343 	dsl_scan_t *scn = dp->dp_scan;
4344 
4345 	/*
4346 	 * Only process scans in sync pass 1.
4347 	 */
4348 
4349 	if (spa_sync_pass(spa) > 1)
4350 		return;
4351 
4352 	/*
4353 	 * If the spa is shutting down, then stop scanning. This will
4354 	 * ensure that the scan does not dirty any new data during the
4355 	 * shutdown phase.
4356 	 */
4357 	if (spa_shutting_down(spa))
4358 		return;
4359 
4360 	if (!dsl_errorscrub_active(scn) || dsl_errorscrub_is_paused(scn)) {
4361 		return;
4362 	}
4363 
4364 	if (dsl_scan_resilvering(scn->scn_dp)) {
4365 		/* cancel the error scrub if resilver started */
4366 		dsl_scan_cancel(scn->scn_dp);
4367 		return;
4368 	}
4369 
4370 	spa->spa_scrub_active = B_TRUE;
4371 	scn->scn_sync_start_time = getlrtime();
4372 
4373 	/*
4374 	 * zfs_scan_suspend_progress can be set to disable scrub progress.
4375 	 * See more detailed comment in dsl_scan_sync().
4376 	 */
4377 	if (zfs_scan_suspend_progress) {
4378 		uint64_t scan_time_ns = getlrtime() - scn->scn_sync_start_time;
4379 		int mintime = zfs_scrub_min_time_ms;
4380 
4381 		while (zfs_scan_suspend_progress &&
4382 		    !txg_sync_waiting(scn->scn_dp) &&
4383 		    !spa_shutting_down(scn->scn_dp->dp_spa) &&
4384 		    NSEC2MSEC(scan_time_ns) < mintime) {
4385 			delay(hz);
4386 			scan_time_ns = getlrtime() - scn->scn_sync_start_time;
4387 		}
4388 		return;
4389 	}
4390 
4391 	int i = 0;
4392 	zap_attribute_t *za;
4393 	zbookmark_phys_t *zb;
4394 	boolean_t limit_exceeded = B_FALSE;
4395 
4396 	za = zap_attribute_alloc();
4397 	zb = kmem_zalloc(sizeof (zbookmark_phys_t), KM_SLEEP);
4398 
4399 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
4400 		for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;
4401 		    zap_cursor_advance(&scn->errorscrub_cursor)) {
4402 			name_to_bookmark(za->za_name, zb);
4403 
4404 			scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4405 			    NULL, ZIO_FLAG_CANFAIL);
4406 			dsl_pool_config_enter(dp, FTAG);
4407 			read_by_block_level(scn, *zb);
4408 			dsl_pool_config_exit(dp, FTAG);
4409 
4410 			(void) zio_wait(scn->scn_zio_root);
4411 			scn->scn_zio_root = NULL;
4412 
4413 			scn->errorscrub_phys.dep_examined += 1;
4414 			scn->errorscrub_phys.dep_to_examine -= 1;
4415 			i++;
4416 			if (i == zfs_scrub_error_blocks_per_txg ||
4417 			    dsl_error_scrub_check_suspend(scn, zb)) {
4418 				limit_exceeded = B_TRUE;
4419 				break;
4420 			}
4421 		}
4422 
4423 		if (!limit_exceeded)
4424 			dsl_errorscrub_done(scn, B_TRUE, tx);
4425 
4426 		dsl_errorscrub_sync_state(scn, tx);
4427 		zap_attribute_free(za);
4428 		kmem_free(zb, sizeof (*zb));
4429 		return;
4430 	}
4431 
4432 	int error = 0;
4433 	for (; zap_cursor_retrieve(&scn->errorscrub_cursor, za) == 0;
4434 	    zap_cursor_advance(&scn->errorscrub_cursor)) {
4435 
4436 		zap_cursor_t *head_ds_cursor;
4437 		zap_attribute_t *head_ds_attr;
4438 		zbookmark_err_phys_t head_ds_block;
4439 
4440 		head_ds_cursor = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);
4441 		head_ds_attr = zap_attribute_alloc();
4442 
4443 		uint64_t head_ds_err_obj = za->za_first_integer;
4444 		uint64_t head_ds;
4445 		name_to_object(za->za_name, &head_ds);
4446 		boolean_t config_held = B_FALSE;
4447 		uint64_t top_affected_fs;
4448 
4449 		for (zap_cursor_init(head_ds_cursor, spa->spa_meta_objset,
4450 		    head_ds_err_obj); zap_cursor_retrieve(head_ds_cursor,
4451 		    head_ds_attr) == 0; zap_cursor_advance(head_ds_cursor)) {
4452 
4453 			name_to_errphys(head_ds_attr->za_name, &head_ds_block);
4454 
4455 			/*
4456 			 * In case we are called from spa_sync the pool
4457 			 * config is already held.
4458 			 */
4459 			if (!dsl_pool_config_held(dp)) {
4460 				dsl_pool_config_enter(dp, FTAG);
4461 				config_held = B_TRUE;
4462 			}
4463 
4464 			error = find_top_affected_fs(spa,
4465 			    head_ds, &head_ds_block, &top_affected_fs);
4466 			if (error)
4467 				break;
4468 
4469 			error = scrub_filesystem(spa, top_affected_fs,
4470 			    &head_ds_block, &i);
4471 
4472 			if (error == SET_ERROR(EFAULT)) {
4473 				limit_exceeded = B_TRUE;
4474 				break;
4475 			}
4476 		}
4477 
4478 		zap_cursor_fini(head_ds_cursor);
4479 		kmem_free(head_ds_cursor, sizeof (*head_ds_cursor));
4480 		zap_attribute_free(head_ds_attr);
4481 
4482 		if (config_held)
4483 			dsl_pool_config_exit(dp, FTAG);
4484 	}
4485 
4486 	zap_attribute_free(za);
4487 	kmem_free(zb, sizeof (*zb));
4488 	if (!limit_exceeded)
4489 		dsl_errorscrub_done(scn, B_TRUE, tx);
4490 
4491 	dsl_errorscrub_sync_state(scn, tx);
4492 }
4493 
4494 /*
4495  * This is the primary entry point for scans that is called from syncing
4496  * context. Scans must happen entirely during syncing context so that we
4497  * can guarantee that blocks we are currently scanning will not change out
4498  * from under us. While a scan is active, this function controls how quickly
4499  * transaction groups proceed, instead of the normal handling provided by
4500  * txg_sync_thread().
4501  */
4502 void
dsl_scan_sync(dsl_pool_t * dp,dmu_tx_t * tx)4503 dsl_scan_sync(dsl_pool_t *dp, dmu_tx_t *tx)
4504 {
4505 	int err = 0;
4506 	dsl_scan_t *scn = dp->dp_scan;
4507 	spa_t *spa = dp->dp_spa;
4508 	state_sync_type_t sync_type = SYNC_OPTIONAL;
4509 	int restart_early = 0;
4510 
4511 	if (spa->spa_resilver_deferred) {
4512 		uint64_t to_issue, issued;
4513 
4514 		if (!spa_feature_is_active(dp->dp_spa,
4515 		    SPA_FEATURE_RESILVER_DEFER))
4516 			spa_feature_incr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
4517 
4518 		/*
4519 		 * See print_scan_scrub_resilver_status() issued/total_i
4520 		 * @ cmd/zpool/zpool_main.c
4521 		 */
4522 		/* scn_to_examine is sampled once; scn_skipped keeps growing. */
4523 		to_issue = scn->scn_phys.scn_to_examine >
4524 		    scn->scn_phys.scn_skipped ? scn->scn_phys.scn_to_examine -
4525 		    scn->scn_phys.scn_skipped : 0;
4526 		issued =
4527 		    scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
4528 		restart_early =
4529 		    zfs_resilver_disable_defer ||
4530 		    (issued < (to_issue * zfs_resilver_defer_percent / 100));
4531 	}
4532 
4533 	/*
4534 	 * Only process scans in sync pass 1.
4535 	 */
4536 	if (spa_sync_pass(spa) > 1)
4537 		return;
4538 
4539 
4540 	/*
4541 	 * Check for scn_restart_txg before checking spa_load_state, so
4542 	 * that we can restart an old-style scan while the pool is being
4543 	 * imported (see dsl_scan_init). We also restart scans if there
4544 	 * is a deferred resilver and the user has manually disabled
4545 	 * deferred resilvers via zfs_resilver_disable_defer, or if the
4546 	 * current scan progress is below zfs_resilver_defer_percent.
4547 	 */
4548 	if (dsl_scan_restarting(scn, tx) || restart_early) {
4549 		setup_sync_arg_t setup_sync_arg = {
4550 			.func = POOL_SCAN_SCRUB,
4551 			.txgstart = 0,
4552 			.txgend = 0,
4553 		};
4554 		dsl_scan_done(scn, B_FALSE, tx);
4555 		if (vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4556 			setup_sync_arg.func = POOL_SCAN_RESILVER;
4557 		zfs_dbgmsg("restarting scan func=%u on %s txg=%llu early=%d",
4558 		    setup_sync_arg.func, dp->dp_spa->spa_name,
4559 		    (longlong_t)tx->tx_txg, restart_early);
4560 		dsl_scan_setup_sync(&setup_sync_arg, tx);
4561 	}
4562 
4563 	/*
4564 	 * If the spa is shutting down, then stop scanning. This will
4565 	 * ensure that the scan does not dirty any new data during the
4566 	 * shutdown phase.
4567 	 */
4568 	if (spa_shutting_down(spa))
4569 		return;
4570 
4571 	/*
4572 	 * Wait a few txgs after importing before doing background work
4573 	 * (async destroys and scanning).  This should help the import
4574 	 * command to complete quickly.
4575 	 */
4576 	if (spa->spa_syncing_txg < spa->spa_first_txg + zfs_import_defer_txgs)
4577 		return;
4578 
4579 	/*
4580 	 * If the scan is inactive due to a stalled async destroy, try again.
4581 	 */
4582 	if (!scn->scn_async_stalled && !dsl_scan_active(scn))
4583 		return;
4584 
4585 	/* reset scan statistics */
4586 	scn->scn_visited_this_txg = 0;
4587 	scn->scn_async_frees_this_txg = 0;
4588 	scn->scn_holes_this_txg = 0;
4589 	scn->scn_lt_min_this_txg = 0;
4590 	scn->scn_gt_max_this_txg = 0;
4591 	scn->scn_ddt_contained_this_txg = 0;
4592 	scn->scn_objsets_visited_this_txg = 0;
4593 	scn->scn_avg_seg_size_this_txg = 0;
4594 	scn->scn_segs_this_txg = 0;
4595 	scn->scn_avg_zio_size_this_txg = 0;
4596 	scn->scn_zios_this_txg = 0;
4597 	scn->scn_suspending = B_FALSE;
4598 	scn->scn_sync_start_time = getlrtime();
4599 	spa->spa_scrub_active = B_TRUE;
4600 
4601 	/*
4602 	 * First process the async destroys.  If we suspend, don't do
4603 	 * any scrubbing or resilvering.  This ensures that there are no
4604 	 * async destroys while we are scanning, so the scan code doesn't
4605 	 * have to worry about traversing it.  It is also faster to free the
4606 	 * blocks than to scrub them.
4607 	 */
4608 	err = dsl_process_async_destroys(dp, tx);
4609 	if (err != 0)
4610 		return;
4611 
4612 	if (!dsl_scan_is_running(scn) || dsl_scan_is_paused_scrub(scn))
4613 		return;
4614 
4615 	/*
4616 	 * zfs_scan_suspend_progress can be set to disable scan progress.
4617 	 * We don't want to spin the txg_sync thread, so we add a delay
4618 	 * here to simulate the time spent doing a scan. This is mostly
4619 	 * useful for testing and debugging.
4620 	 */
4621 	if (zfs_scan_suspend_progress) {
4622 		uint64_t scan_time_ns = getlrtime() - scn->scn_sync_start_time;
4623 		uint_t mintime = (scn->scn_phys.scn_func ==
4624 		    POOL_SCAN_RESILVER) ? zfs_resilver_min_time_ms :
4625 		    zfs_scrub_min_time_ms;
4626 
4627 		while (zfs_scan_suspend_progress &&
4628 		    !txg_sync_waiting(scn->scn_dp) &&
4629 		    !spa_shutting_down(scn->scn_dp->dp_spa) &&
4630 		    NSEC2MSEC(scan_time_ns) < mintime) {
4631 			delay(hz);
4632 			scan_time_ns = getlrtime() - scn->scn_sync_start_time;
4633 		}
4634 		return;
4635 	}
4636 
4637 	/*
4638 	 * Disabled by default, set zfs_scan_report_txgs to report
4639 	 * average performance over the last zfs_scan_report_txgs TXGs.
4640 	 */
4641 	if (zfs_scan_report_txgs != 0 &&
4642 	    tx->tx_txg % zfs_scan_report_txgs == 0) {
4643 		scn->scn_issued_before_pass += spa->spa_scan_pass_issued;
4644 		spa_scan_stat_init(spa);
4645 	}
4646 
4647 	/*
4648 	 * It is possible to switch from unsorted to sorted at any time,
4649 	 * but afterwards the scan will remain sorted unless reloaded from
4650 	 * a checkpoint after a reboot.
4651 	 */
4652 	if (!zfs_scan_legacy) {
4653 		scn->scn_is_sorted = B_TRUE;
4654 		if (scn->scn_last_checkpoint == 0)
4655 			scn->scn_last_checkpoint = ddi_get_lbolt();
4656 	}
4657 
4658 	/*
4659 	 * For sorted scans, determine what kind of work we will be doing
4660 	 * this txg based on our memory limitations and whether or not we
4661 	 * need to perform a checkpoint.
4662 	 */
4663 	if (scn->scn_is_sorted) {
4664 		/*
4665 		 * If we are over our checkpoint interval, set scn_clearing
4666 		 * so that we can begin checkpointing immediately. The
4667 		 * checkpoint allows us to save a consistent bookmark
4668 		 * representing how much data we have scrubbed so far.
4669 		 * Otherwise, use the memory limit to determine if we should
4670 		 * scan for metadata or start issue scrub IOs. We accumulate
4671 		 * metadata until we hit our hard memory limit at which point
4672 		 * we issue scrub IOs until we are at our soft memory limit.
4673 		 */
4674 		if (scn->scn_checkpointing ||
4675 		    ddi_get_lbolt() - scn->scn_last_checkpoint >
4676 		    SEC_TO_TICK(zfs_scan_checkpoint_intval)) {
4677 			if (!scn->scn_checkpointing)
4678 				zfs_dbgmsg("begin scan checkpoint for %s",
4679 				    spa->spa_name);
4680 
4681 			scn->scn_checkpointing = B_TRUE;
4682 			scn->scn_clearing = B_TRUE;
4683 		} else {
4684 			boolean_t should_clear = dsl_scan_should_clear(scn);
4685 			if (should_clear && !scn->scn_clearing) {
4686 				zfs_dbgmsg("begin scan clearing for %s",
4687 				    spa->spa_name);
4688 				scn->scn_clearing = B_TRUE;
4689 			} else if (!should_clear && scn->scn_clearing) {
4690 				zfs_dbgmsg("finish scan clearing for %s",
4691 				    spa->spa_name);
4692 				scn->scn_clearing = B_FALSE;
4693 			}
4694 		}
4695 	} else {
4696 		ASSERT0(scn->scn_checkpointing);
4697 		ASSERT0(scn->scn_clearing);
4698 	}
4699 
4700 	if (!scn->scn_clearing && scn->scn_done_txg == 0) {
4701 		/* Need to scan metadata for more blocks to scrub */
4702 		dsl_scan_phys_t *scnp = &scn->scn_phys;
4703 		taskqid_t prefetch_tqid;
4704 
4705 		/*
4706 		 * Calculate the max number of in-flight bytes for pool-wide
4707 		 * scanning operations (minimum 1MB, maximum 1/4 of arc_c_max).
4708 		 * Limits for the issuing phase are done per top-level vdev and
4709 		 * are handled separately.
4710 		 */
4711 		scn->scn_maxinflight_bytes = MIN(arc_c_max / 4, MAX(1ULL << 20,
4712 		    zfs_scan_vdev_limit * dsl_scan_count_data_disks(spa)));
4713 
4714 		if (scnp->scn_ddt_bookmark.ddb_class <=
4715 		    scnp->scn_ddt_class_max) {
4716 			ASSERT(ZB_IS_ZERO(&scnp->scn_bookmark));
4717 			zfs_dbgmsg("doing scan sync for %s txg %llu; "
4718 			    "ddt bm=%llu/%llu/%llu/%llx",
4719 			    spa->spa_name,
4720 			    (longlong_t)tx->tx_txg,
4721 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_class,
4722 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_type,
4723 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_checksum,
4724 			    (longlong_t)scnp->scn_ddt_bookmark.ddb_cursor);
4725 		} else {
4726 			zfs_dbgmsg("doing scan sync for %s txg %llu; "
4727 			    "bm=%llu/%llu/%llu/%llu",
4728 			    spa->spa_name,
4729 			    (longlong_t)tx->tx_txg,
4730 			    (longlong_t)scnp->scn_bookmark.zb_objset,
4731 			    (longlong_t)scnp->scn_bookmark.zb_object,
4732 			    (longlong_t)scnp->scn_bookmark.zb_level,
4733 			    (longlong_t)scnp->scn_bookmark.zb_blkid);
4734 		}
4735 
4736 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4737 		    NULL, ZIO_FLAG_CANFAIL);
4738 
4739 		scn->scn_prefetch_stop = B_FALSE;
4740 		prefetch_tqid = taskq_dispatch(dp->dp_sync_taskq,
4741 		    dsl_scan_prefetch_thread, scn, TQ_SLEEP);
4742 		ASSERT(prefetch_tqid != TASKQID_INVALID);
4743 
4744 		dsl_pool_config_enter(dp, FTAG);
4745 		dsl_scan_visit(scn, tx);
4746 		dsl_pool_config_exit(dp, FTAG);
4747 
4748 		mutex_enter(&dp->dp_spa->spa_scrub_lock);
4749 		scn->scn_prefetch_stop = B_TRUE;
4750 		cv_broadcast(&spa->spa_scrub_io_cv);
4751 		mutex_exit(&dp->dp_spa->spa_scrub_lock);
4752 
4753 		taskq_wait_id(dp->dp_sync_taskq, prefetch_tqid);
4754 		(void) zio_wait(scn->scn_zio_root);
4755 		scn->scn_zio_root = NULL;
4756 
4757 		zfs_dbgmsg("scan visited %llu blocks of %s in %llums "
4758 		    "(%llu os's, %llu holes, %llu < mintxg, "
4759 		    "%llu in ddt, %llu > maxtxg)",
4760 		    (longlong_t)scn->scn_visited_this_txg,
4761 		    spa->spa_name,
4762 		    (longlong_t)NSEC2MSEC(getlrtime() -
4763 		    scn->scn_sync_start_time),
4764 		    (longlong_t)scn->scn_objsets_visited_this_txg,
4765 		    (longlong_t)scn->scn_holes_this_txg,
4766 		    (longlong_t)scn->scn_lt_min_this_txg,
4767 		    (longlong_t)scn->scn_ddt_contained_this_txg,
4768 		    (longlong_t)scn->scn_gt_max_this_txg);
4769 
4770 		if (!scn->scn_suspending) {
4771 			ASSERT0(avl_numnodes(&scn->scn_queue));
4772 			scn->scn_done_txg = tx->tx_txg + 1;
4773 			if (scn->scn_is_sorted) {
4774 				scn->scn_checkpointing = B_TRUE;
4775 				scn->scn_clearing = B_TRUE;
4776 				scn->scn_issued_before_pass +=
4777 				    spa->spa_scan_pass_issued;
4778 				spa_scan_stat_init(spa);
4779 			}
4780 			zfs_dbgmsg("scan complete for %s txg %llu",
4781 			    spa->spa_name,
4782 			    (longlong_t)tx->tx_txg);
4783 		}
4784 	} else if (scn->scn_is_sorted && scn->scn_queues_pending != 0) {
4785 		ASSERT(scn->scn_clearing);
4786 
4787 		/* need to issue scrubbing IOs from per-vdev queues */
4788 		scn->scn_zio_root = zio_root(dp->dp_spa, NULL,
4789 		    NULL, ZIO_FLAG_CANFAIL);
4790 		scan_io_queues_run(scn);
4791 		(void) zio_wait(scn->scn_zio_root);
4792 		scn->scn_zio_root = NULL;
4793 
4794 		/* calculate and dprintf the current memory usage */
4795 		(void) dsl_scan_should_clear(scn);
4796 		dsl_scan_update_stats(scn);
4797 
4798 		zfs_dbgmsg("scan issued %llu blocks for %s (%llu segs) "
4799 		    "in %llums (avg_block_size = %llu, avg_seg_size = %llu)",
4800 		    (longlong_t)scn->scn_zios_this_txg,
4801 		    spa->spa_name,
4802 		    (longlong_t)scn->scn_segs_this_txg,
4803 		    (longlong_t)NSEC2MSEC(getlrtime() -
4804 		    scn->scn_sync_start_time),
4805 		    (longlong_t)scn->scn_avg_zio_size_this_txg,
4806 		    (longlong_t)scn->scn_avg_seg_size_this_txg);
4807 	} else if (scn->scn_done_txg != 0 && scn->scn_done_txg <= tx->tx_txg) {
4808 		/* Finished with everything. Mark the scrub as complete */
4809 		zfs_dbgmsg("scan issuing complete txg %llu for %s",
4810 		    (longlong_t)tx->tx_txg,
4811 		    spa->spa_name);
4812 		ASSERT3U(scn->scn_done_txg, !=, 0);
4813 		ASSERT0(spa->spa_scrub_inflight);
4814 		ASSERT0(scn->scn_queues_pending);
4815 		dsl_scan_done(scn, B_TRUE, tx);
4816 		sync_type = SYNC_MANDATORY;
4817 	}
4818 
4819 	dsl_scan_sync_state(scn, tx, sync_type);
4820 }
4821 
4822 static void
count_block_issued(spa_t * spa,const blkptr_t * bp,boolean_t all)4823 count_block_issued(spa_t *spa, const blkptr_t *bp, boolean_t all)
4824 {
4825 	/*
4826 	 * Don't count embedded bp's, since we already did the work of
4827 	 * scanning these when we scanned the containing block.
4828 	 */
4829 	if (BP_IS_EMBEDDED(bp))
4830 		return;
4831 
4832 	/*
4833 	 * Update the spa's stats on how many bytes we have issued.
4834 	 * Sequential scrubs create a zio for each DVA of the bp. Each
4835 	 * of these will include all DVAs for repair purposes, but the
4836 	 * zio code will only try the first one unless there is an issue.
4837 	 * Therefore, we should only count the first DVA for these IOs.
4838 	 */
4839 	atomic_add_64(&spa->spa_scan_pass_issued,
4840 	    all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));
4841 }
4842 
4843 static void
count_block_skipped(dsl_scan_t * scn,const blkptr_t * bp,boolean_t all)4844 count_block_skipped(dsl_scan_t *scn, const blkptr_t *bp, boolean_t all)
4845 {
4846 	if (BP_IS_EMBEDDED(bp))
4847 		return;
4848 	atomic_add_64(&scn->scn_phys.scn_skipped,
4849 	    all ? BP_GET_ASIZE(bp) : DVA_GET_ASIZE(&bp->blk_dva[0]));
4850 }
4851 
4852 static void
count_block(zfs_all_blkstats_t * zab,const blkptr_t * bp)4853 count_block(zfs_all_blkstats_t *zab, const blkptr_t *bp)
4854 {
4855 	/*
4856 	 * If we resume after a reboot, zab will be NULL; don't record
4857 	 * incomplete stats in that case.
4858 	 */
4859 	if (zab == NULL)
4860 		return;
4861 
4862 	for (int i = 0; i < 4; i++) {
4863 		int l = (i < 2) ? BP_GET_LEVEL(bp) : DN_MAX_LEVELS;
4864 		int t = (i & 1) ? BP_GET_TYPE(bp) : DMU_OT_TOTAL;
4865 
4866 		if (t & DMU_OT_NEWTYPE)
4867 			t = DMU_OT_OTHER;
4868 		zfs_blkstat_t *zb = &zab->zab_type[l][t];
4869 		int equal;
4870 
4871 		zb->zb_count++;
4872 		zb->zb_asize += BP_GET_ASIZE(bp);
4873 		zb->zb_lsize += BP_GET_LSIZE(bp);
4874 		zb->zb_psize += BP_GET_PSIZE(bp);
4875 		zb->zb_gangs += BP_COUNT_GANG(bp);
4876 
4877 		switch (BP_GET_NDVAS(bp)) {
4878 		case 2:
4879 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4880 			    DVA_GET_VDEV(&bp->blk_dva[1]))
4881 				zb->zb_ditto_2_of_2_samevdev++;
4882 			break;
4883 		case 3:
4884 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4885 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
4886 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
4887 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
4888 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
4889 			    DVA_GET_VDEV(&bp->blk_dva[2]));
4890 			if (equal == 1)
4891 				zb->zb_ditto_2_of_3_samevdev++;
4892 			else if (equal == 3)
4893 				zb->zb_ditto_3_of_3_samevdev++;
4894 			break;
4895 		}
4896 	}
4897 }
4898 
4899 static void
scan_io_queue_insert_impl(dsl_scan_io_queue_t * queue,scan_io_t * sio)4900 scan_io_queue_insert_impl(dsl_scan_io_queue_t *queue, scan_io_t *sio)
4901 {
4902 	avl_index_t idx;
4903 	dsl_scan_t *scn = queue->q_scn;
4904 
4905 	ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
4906 
4907 	if (unlikely(avl_is_empty(&queue->q_sios_by_addr)))
4908 		atomic_add_64(&scn->scn_queues_pending, 1);
4909 	if (avl_find(&queue->q_sios_by_addr, sio, &idx) != NULL) {
4910 		/* block is already scheduled for reading */
4911 		sio_free(sio);
4912 		return;
4913 	}
4914 	avl_insert(&queue->q_sios_by_addr, sio, idx);
4915 	queue->q_sio_memused += SIO_GET_MUSED(sio);
4916 	zfs_range_tree_add(queue->q_exts_by_addr, SIO_GET_OFFSET(sio),
4917 	    SIO_GET_ASIZE(sio));
4918 }
4919 
4920 /*
4921  * Given all the info we got from our metadata scanning process, we
4922  * construct a scan_io_t and insert it into the scan sorting queue. The
4923  * I/O must already be suitable for us to process. This is controlled
4924  * by dsl_scan_enqueue().
4925  */
4926 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)4927 scan_io_queue_insert(dsl_scan_io_queue_t *queue, const blkptr_t *bp, int dva_i,
4928     int zio_flags, const zbookmark_phys_t *zb)
4929 {
4930 	boolean_t ext = dsl_scan_is_thorough_scrub(queue->q_scn) &&
4931 	    BP_IS_ENCRYPTED(bp);
4932 	scan_io_t *sio = sio_alloc(BP_GET_NDVAS(bp), ext);
4933 
4934 	ASSERT0(BP_IS_GANG(bp));
4935 	ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
4936 
4937 	bp2sio(bp, sio, dva_i);
4938 	sio->sio_flags = zio_flags;
4939 	sio->sio_zb = *zb;
4940 
4941 	queue->q_last_ext_addr = -1;
4942 	scan_io_queue_insert_impl(queue, sio);
4943 }
4944 
4945 /*
4946  * Given a set of I/O parameters as discovered by the metadata traversal
4947  * process, attempts to place the I/O into the sorted queues (if allowed),
4948  * or immediately executes the I/O.
4949  */
4950 static void
dsl_scan_enqueue(dsl_pool_t * dp,const blkptr_t * bp,int zio_flags,const zbookmark_phys_t * zb)4951 dsl_scan_enqueue(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
4952     const zbookmark_phys_t *zb)
4953 {
4954 	spa_t *spa = dp->dp_spa;
4955 
4956 	ASSERT(!BP_IS_EMBEDDED(bp));
4957 
4958 	/*
4959 	 * Gang blocks are hard to issue sequentially, so we just issue them
4960 	 * here immediately instead of queuing them.
4961 	 */
4962 	if (!dp->dp_scan->scn_is_sorted || BP_IS_GANG(bp)) {
4963 		scan_exec_io(dp, bp, zio_flags, zb, NULL);
4964 		return;
4965 	}
4966 
4967 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
4968 		dva_t dva;
4969 		vdev_t *vdev;
4970 
4971 		dva = bp->blk_dva[i];
4972 		vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&dva));
4973 		ASSERT(vdev != NULL);
4974 
4975 		mutex_enter(&vdev->vdev_scan_io_queue_lock);
4976 		if (vdev->vdev_scan_io_queue == NULL)
4977 			vdev->vdev_scan_io_queue = scan_io_queue_create(vdev);
4978 		ASSERT(dp->dp_scan != NULL);
4979 		scan_io_queue_insert(vdev->vdev_scan_io_queue, bp,
4980 		    i, zio_flags, zb);
4981 		mutex_exit(&vdev->vdev_scan_io_queue_lock);
4982 	}
4983 }
4984 
4985 static int
dsl_scan_scrub_cb(dsl_pool_t * dp,const blkptr_t * bp,const zbookmark_phys_t * zb)4986 dsl_scan_scrub_cb(dsl_pool_t *dp,
4987     const blkptr_t *bp, const zbookmark_phys_t *zb)
4988 {
4989 	dsl_scan_t *scn = dp->dp_scan;
4990 	spa_t *spa = dp->dp_spa;
4991 	uint64_t phys_birth = BP_GET_PHYSICAL_BIRTH(bp);
4992 	size_t psize = BP_GET_PSIZE(bp);
4993 	boolean_t needs_io = B_FALSE;
4994 	int zio_flags = ZIO_FLAG_SCAN_THREAD | ZIO_FLAG_CANFAIL;
4995 
4996 	/* A thorough scrub decrypts/decompresses, so it must not read raw. */
4997 	if (!dsl_scan_is_thorough_scrub(scn))
4998 		zio_flags |= ZIO_FLAG_RAW;
4999 
5000 	count_block(dp->dp_blkstats, bp);
5001 	if (phys_birth <= scn->scn_phys.scn_min_txg ||
5002 	    phys_birth >= scn->scn_phys.scn_max_txg) {
5003 		/* Traversed but not scrubbed; both counters must see it. */
5004 		uint64_t asize = BP_GET_ASIZE(bp);
5005 		scn->scn_phys.scn_examined += asize;
5006 		spa->spa_scan_pass_exam += asize;
5007 		count_block_skipped(scn, bp, B_TRUE);
5008 		return (0);
5009 	}
5010 
5011 	/* Embedded BP's have phys_birth==0, so we reject them above. */
5012 	ASSERT(!BP_IS_EMBEDDED(bp));
5013 
5014 	ASSERT(DSL_SCAN_IS_SCRUB_RESILVER(scn));
5015 	if (scn->scn_phys.scn_func == POOL_SCAN_SCRUB) {
5016 		zio_flags |= ZIO_FLAG_SCRUB;
5017 		needs_io = B_TRUE;
5018 	} else {
5019 		ASSERT3U(scn->scn_phys.scn_func, ==, POOL_SCAN_RESILVER);
5020 		zio_flags |= ZIO_FLAG_RESILVER;
5021 		needs_io = B_FALSE;
5022 	}
5023 
5024 	/* If it's an intent log block, failure is expected. */
5025 	if (zb->zb_level == ZB_ZIL_LEVEL)
5026 		zio_flags |= ZIO_FLAG_SPECULATIVE;
5027 
5028 	for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
5029 		const dva_t *dva = &bp->blk_dva[d];
5030 
5031 		/*
5032 		 * Keep track of how much data we've examined so that
5033 		 * zpool(8) status can make useful progress reports.
5034 		 */
5035 		uint64_t asize = DVA_GET_ASIZE(dva);
5036 		scn->scn_phys.scn_examined += asize;
5037 		spa->spa_scan_pass_exam += asize;
5038 
5039 		/* if it's a resilver, this may not be in the target range */
5040 		if (!needs_io)
5041 			needs_io = dsl_scan_need_resilver(spa, dva, psize,
5042 			    phys_birth);
5043 	}
5044 
5045 	if (needs_io && !zfs_no_scrub_io) {
5046 		dsl_scan_enqueue(dp, bp, zio_flags, zb);
5047 	} else {
5048 		count_block_skipped(scn, bp, B_TRUE);
5049 	}
5050 
5051 	/* do not relocate this block */
5052 	return (0);
5053 }
5054 
5055 static void
dsl_scan_scrub_done(zio_t * zio)5056 dsl_scan_scrub_done(zio_t *zio)
5057 {
5058 	spa_t *spa = zio->io_spa;
5059 	dsl_scan_io_queue_t *queue = zio->io_private;
5060 
5061 	abd_free(zio->io_abd);
5062 
5063 	if (queue == NULL) {
5064 		mutex_enter(&spa->spa_scrub_lock);
5065 		ASSERT3U(spa->spa_scrub_inflight, >=, zio->io_size);
5066 		spa->spa_scrub_inflight -= zio->io_size;
5067 		cv_broadcast(&spa->spa_scrub_io_cv);
5068 		mutex_exit(&spa->spa_scrub_lock);
5069 	} else {
5070 		mutex_enter(&queue->q_vd->vdev_scan_io_queue_lock);
5071 		ASSERT3U(queue->q_inflight_bytes, >=, zio->io_size);
5072 		queue->q_inflight_bytes -= zio->io_size;
5073 		cv_broadcast(&queue->q_zio_cv);
5074 		mutex_exit(&queue->q_vd->vdev_scan_io_queue_lock);
5075 	}
5076 
5077 	/*
5078 	 * A normal scrub issues ZIO_FLAG_RAW reads which are never decrypted
5079 	 * and so can never produce EACCES here.
5080 	 */
5081 	ASSERT(zio->io_error != EACCES || !(zio->io_flags & ZIO_FLAG_SCRUB) ||
5082 	    !(zio->io_flags & ZIO_FLAG_RAW));
5083 	/*
5084 	 * During a thorough scrub we read blocks without ZIO_FLAG_RAW. If the
5085 	 * dataset's key is not loaded the decryption (or MAC verification)
5086 	 * fails with EACCES (see spa_do_crypt_abd() and the MAC helpers).
5087 	 * The checksum has already been verified, so this is as much as we
5088 	 * can do for the block without keys; treat it as success.
5089 	 */
5090 	if (zio->io_error && (zio->io_error != ECKSUM ||
5091 	    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) &&
5092 	    !(zio->io_error == EACCES && (zio->io_flags & ZIO_FLAG_SCRUB) &&
5093 	    !(zio->io_flags & ZIO_FLAG_RAW))) {
5094 		if (dsl_errorscrubbing(spa->spa_dsl_pool) &&
5095 		    !dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan)) {
5096 			atomic_inc_64(&spa->spa_dsl_pool->dp_scan
5097 			    ->errorscrub_phys.dep_errors);
5098 		} else {
5099 			atomic_inc_64(&spa->spa_dsl_pool->dp_scan->scn_phys
5100 			    .scn_errors);
5101 		}
5102 	}
5103 }
5104 
5105 /*
5106  * Given a scanning zio's information, executes the zio. The zio need
5107  * not necessarily be only sortable, this function simply executes the
5108  * zio, no matter what it is. The optional queue argument allows the
5109  * caller to specify that they want per top level vdev IO rate limiting
5110  * instead of the legacy global limiting.
5111  */
5112 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)5113 scan_exec_io(dsl_pool_t *dp, const blkptr_t *bp, int zio_flags,
5114     const zbookmark_phys_t *zb, dsl_scan_io_queue_t *queue)
5115 {
5116 	spa_t *spa = dp->dp_spa;
5117 	dsl_scan_t *scn = dp->dp_scan;
5118 	/*
5119 	 * If raw flags is not set - this is a thorough scrub.
5120 	 */
5121 	size_t size = (zio_flags & ZIO_FLAG_RAW) ?
5122 	    BP_GET_PSIZE(bp) : BP_GET_LSIZE(bp);
5123 	abd_t *data = abd_alloc_for_io(size, B_FALSE);
5124 	zio_t *pio;
5125 
5126 	if (queue == NULL) {
5127 		ASSERT3U(scn->scn_maxinflight_bytes, >, 0);
5128 		mutex_enter(&spa->spa_scrub_lock);
5129 		while (spa->spa_scrub_inflight >= scn->scn_maxinflight_bytes)
5130 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5131 		spa->spa_scrub_inflight += size;
5132 		mutex_exit(&spa->spa_scrub_lock);
5133 		pio = scn->scn_zio_root;
5134 	} else {
5135 		kmutex_t *q_lock = &queue->q_vd->vdev_scan_io_queue_lock;
5136 
5137 		ASSERT3U(queue->q_maxinflight_bytes, >, 0);
5138 		mutex_enter(q_lock);
5139 		while (queue->q_inflight_bytes >= queue->q_maxinflight_bytes)
5140 			cv_wait(&queue->q_zio_cv, q_lock);
5141 		queue->q_inflight_bytes += size;
5142 		pio = queue->q_zio;
5143 		mutex_exit(q_lock);
5144 	}
5145 
5146 	ASSERT(pio != NULL);
5147 	count_block_issued(spa, bp, queue == NULL);
5148 	zio_nowait(zio_read(pio, spa, bp, data, size, dsl_scan_scrub_done,
5149 	    queue, ZIO_PRIORITY_SCRUB, zio_flags, zb));
5150 }
5151 
5152 /*
5153  * This is the primary extent sorting algorithm. We balance two parameters:
5154  * 1) how many bytes of I/O are in an extent
5155  * 2) how well the extent is filled with I/O (as a fraction of its total size)
5156  * Since we allow extents to have gaps between their constituent I/Os, it's
5157  * possible to have a fairly large extent that contains the same amount of
5158  * I/O bytes than a much smaller extent, which just packs the I/O more tightly.
5159  * The algorithm sorts based on a score calculated from the extent's size,
5160  * the relative fill volume (in %) and a "fill weight" parameter that controls
5161  * the split between whether we prefer larger extents or more well populated
5162  * extents:
5163  *
5164  * SCORE = FILL_IN_BYTES + (FILL_IN_PERCENT * FILL_IN_BYTES * FILL_WEIGHT)
5165  *
5166  * Example:
5167  * 1) assume extsz = 64 MiB
5168  * 2) assume fill = 32 MiB (extent is half full)
5169  * 3) assume fill_weight = 3
5170  * 4)	SCORE = 32M + (((32M * 100) / 64M) * 3 * 32M) / 100
5171  *	SCORE = 32M + (50 * 3 * 32M) / 100
5172  *	SCORE = 32M + (4800M / 100)
5173  *	SCORE = 32M + 48M
5174  *	         ^     ^
5175  *	         |     +--- final total relative fill-based score
5176  *	         +--------- final total fill-based score
5177  *	SCORE = 80M
5178  *
5179  * As can be seen, at fill_ratio=3, the algorithm is slightly biased towards
5180  * extents that are more completely filled (in a 3:2 ratio) vs just larger.
5181  * Note that as an optimization, we replace multiplication and division by
5182  * 100 with bitshifting by 7 (which effectively multiplies and divides by 128).
5183  *
5184  * Since we do not care if one extent is only few percent better than another,
5185  * compress the score into 6 bits via binary logarithm AKA highbit64() and
5186  * put into otherwise unused due to ashift high bits of offset.  This allows
5187  * to reduce q_exts_by_size B-tree elements to only 64 bits and compare them
5188  * with single operation.  Plus it makes scrubs more sequential and reduces
5189  * chances that minor extent change move it within the B-tree.
5190  */
5191 __attribute__((always_inline)) inline
5192 static int
ext_size_compare(const void * x,const void * y)5193 ext_size_compare(const void *x, const void *y)
5194 {
5195 	const uint64_t *a = x, *b = y;
5196 
5197 	return (TREE_CMP(*a, *b));
5198 }
5199 
ZFS_BTREE_FIND_IN_BUF_FUNC(ext_size_find_in_buf,uint64_t,ext_size_compare)5200 ZFS_BTREE_FIND_IN_BUF_FUNC(ext_size_find_in_buf, uint64_t,
5201     ext_size_compare)
5202 
5203 static void
5204 ext_size_create(zfs_range_tree_t *rt, void *arg)
5205 {
5206 	(void) rt;
5207 	zfs_btree_t *size_tree = arg;
5208 
5209 	zfs_btree_create(size_tree, ext_size_compare, ext_size_find_in_buf,
5210 	    sizeof (uint64_t));
5211 }
5212 
5213 static void
ext_size_destroy(zfs_range_tree_t * rt,void * arg)5214 ext_size_destroy(zfs_range_tree_t *rt, void *arg)
5215 {
5216 	(void) rt;
5217 	zfs_btree_t *size_tree = arg;
5218 	ASSERT0(zfs_btree_numnodes(size_tree));
5219 
5220 	zfs_btree_destroy(size_tree);
5221 }
5222 
5223 static uint64_t
ext_size_value(zfs_range_tree_t * rt,zfs_range_seg_gap_t * rsg)5224 ext_size_value(zfs_range_tree_t *rt, zfs_range_seg_gap_t *rsg)
5225 {
5226 	(void) rt;
5227 	uint64_t size = rsg->rs_end - rsg->rs_start;
5228 	uint64_t score = rsg->rs_fill + ((((rsg->rs_fill << 7) / size) *
5229 	    fill_weight * rsg->rs_fill) >> 7);
5230 	ASSERT3U(rt->rt_shift, >=, 8);
5231 	return (((uint64_t)(64 - highbit64(score)) << 56) | rsg->rs_start);
5232 }
5233 
5234 static void
ext_size_add(zfs_range_tree_t * rt,zfs_range_seg_t * rs,void * arg)5235 ext_size_add(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)
5236 {
5237 	zfs_btree_t *size_tree = arg;
5238 	ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);
5239 	uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);
5240 	zfs_btree_add(size_tree, &v);
5241 }
5242 
5243 static void
ext_size_remove(zfs_range_tree_t * rt,zfs_range_seg_t * rs,void * arg)5244 ext_size_remove(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)
5245 {
5246 	zfs_btree_t *size_tree = arg;
5247 	ASSERT3U(rt->rt_type, ==, ZFS_RANGE_SEG_GAP);
5248 	uint64_t v = ext_size_value(rt, (zfs_range_seg_gap_t *)rs);
5249 	zfs_btree_remove(size_tree, &v);
5250 }
5251 
5252 static void
ext_size_vacate(zfs_range_tree_t * rt,void * arg)5253 ext_size_vacate(zfs_range_tree_t *rt, void *arg)
5254 {
5255 	zfs_btree_t *size_tree = arg;
5256 	zfs_btree_clear(size_tree);
5257 	zfs_btree_destroy(size_tree);
5258 
5259 	ext_size_create(rt, arg);
5260 }
5261 
5262 static const zfs_range_tree_ops_t ext_size_ops = {
5263 	.rtop_create = ext_size_create,
5264 	.rtop_destroy = ext_size_destroy,
5265 	.rtop_add = ext_size_add,
5266 	.rtop_remove = ext_size_remove,
5267 	.rtop_vacate = ext_size_vacate
5268 };
5269 
5270 /*
5271  * Comparator for the q_sios_by_addr tree. Sorting is simply performed
5272  * based on LBA-order (from lowest to highest). The tree can contain compact
5273  * and extended sios, so use the per-sio DVA helper.
5274  */
5275 static int
sio_addr_compare(const void * x,const void * y)5276 sio_addr_compare(const void *x, const void *y)
5277 {
5278 	const scan_io_t *a = x, *b = y;
5279 
5280 	return (TREE_CMP(SIO_GET_OFFSET(a), SIO_GET_OFFSET(b)));
5281 }
5282 
5283 /* IO queues are created on demand when they are needed. */
5284 static dsl_scan_io_queue_t *
scan_io_queue_create(vdev_t * vd)5285 scan_io_queue_create(vdev_t *vd)
5286 {
5287 	dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
5288 	dsl_scan_io_queue_t *q = kmem_zalloc(sizeof (*q), KM_SLEEP);
5289 
5290 	q->q_scn = scn;
5291 	q->q_vd = vd;
5292 	q->q_sio_memused = 0;
5293 	q->q_last_ext_addr = -1;
5294 	cv_init(&q->q_zio_cv, NULL, CV_DEFAULT, NULL);
5295 	q->q_exts_by_addr = zfs_range_tree_create_gap(&ext_size_ops,
5296 	    ZFS_RANGE_SEG_GAP, &q->q_exts_by_size, 0, vd->vdev_ashift,
5297 	    zfs_scan_max_ext_gap);
5298 	avl_create(&q->q_sios_by_addr, sio_addr_compare, sizeof (scan_io_t),
5299 	    offsetof(scan_io_t, sio_nodes.sio_addr_node));
5300 
5301 	return (q);
5302 }
5303 
5304 /*
5305  * Destroys a scan queue and all segments and scan_io_t's contained in it.
5306  * No further execution of I/O occurs, anything pending in the queue is
5307  * simply freed without being executed.
5308  */
5309 void
dsl_scan_io_queue_destroy(dsl_scan_io_queue_t * queue)5310 dsl_scan_io_queue_destroy(dsl_scan_io_queue_t *queue)
5311 {
5312 	dsl_scan_t *scn = queue->q_scn;
5313 	scan_io_t *sio;
5314 	void *cookie = NULL;
5315 
5316 	ASSERT(MUTEX_HELD(&queue->q_vd->vdev_scan_io_queue_lock));
5317 
5318 	if (!avl_is_empty(&queue->q_sios_by_addr))
5319 		atomic_add_64(&scn->scn_queues_pending, -1);
5320 	while ((sio = avl_destroy_nodes(&queue->q_sios_by_addr, &cookie)) !=
5321 	    NULL) {
5322 		ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr,
5323 		    SIO_GET_OFFSET(sio), SIO_GET_ASIZE(sio)));
5324 		queue->q_sio_memused -= SIO_GET_MUSED(sio);
5325 		sio_free(sio);
5326 	}
5327 
5328 	ASSERT0(queue->q_sio_memused);
5329 	zfs_range_tree_vacate(queue->q_exts_by_addr, NULL, queue);
5330 	zfs_range_tree_destroy(queue->q_exts_by_addr);
5331 	avl_destroy(&queue->q_sios_by_addr);
5332 	cv_destroy(&queue->q_zio_cv);
5333 
5334 	kmem_free(queue, sizeof (*queue));
5335 }
5336 
5337 /*
5338  * Properly transfers a dsl_scan_queue_t from `svd' to `tvd'. This is
5339  * called on behalf of vdev_top_transfer when creating or destroying
5340  * a mirror vdev due to zpool attach/detach.
5341  */
5342 void
dsl_scan_io_queue_vdev_xfer(vdev_t * svd,vdev_t * tvd)5343 dsl_scan_io_queue_vdev_xfer(vdev_t *svd, vdev_t *tvd)
5344 {
5345 	mutex_enter(&svd->vdev_scan_io_queue_lock);
5346 	mutex_enter(&tvd->vdev_scan_io_queue_lock);
5347 
5348 	VERIFY0P(tvd->vdev_scan_io_queue);
5349 	tvd->vdev_scan_io_queue = svd->vdev_scan_io_queue;
5350 	svd->vdev_scan_io_queue = NULL;
5351 	if (tvd->vdev_scan_io_queue != NULL)
5352 		tvd->vdev_scan_io_queue->q_vd = tvd;
5353 
5354 	mutex_exit(&tvd->vdev_scan_io_queue_lock);
5355 	mutex_exit(&svd->vdev_scan_io_queue_lock);
5356 }
5357 
5358 static void
scan_io_queues_destroy(dsl_scan_t * scn)5359 scan_io_queues_destroy(dsl_scan_t *scn)
5360 {
5361 	vdev_t *rvd = scn->scn_dp->dp_spa->spa_root_vdev;
5362 
5363 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5364 		vdev_t *tvd = rvd->vdev_child[i];
5365 
5366 		mutex_enter(&tvd->vdev_scan_io_queue_lock);
5367 		if (tvd->vdev_scan_io_queue != NULL)
5368 			dsl_scan_io_queue_destroy(tvd->vdev_scan_io_queue);
5369 		tvd->vdev_scan_io_queue = NULL;
5370 		mutex_exit(&tvd->vdev_scan_io_queue_lock);
5371 	}
5372 }
5373 
5374 static void
dsl_scan_freed_dva(spa_t * spa,const blkptr_t * bp,int dva_i)5375 dsl_scan_freed_dva(spa_t *spa, const blkptr_t *bp, int dva_i)
5376 {
5377 	dsl_pool_t *dp = spa->spa_dsl_pool;
5378 	dsl_scan_t *scn = dp->dp_scan;
5379 	vdev_t *vdev;
5380 	kmutex_t *q_lock;
5381 	dsl_scan_io_queue_t *queue;
5382 	scan_io_t *srch_sio, *sio;
5383 	avl_index_t idx;
5384 	uint64_t start, size;
5385 
5386 	vdev = vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[dva_i]));
5387 	ASSERT(vdev != NULL);
5388 	q_lock = &vdev->vdev_scan_io_queue_lock;
5389 	queue = vdev->vdev_scan_io_queue;
5390 
5391 	mutex_enter(q_lock);
5392 	if (queue == NULL) {
5393 		mutex_exit(q_lock);
5394 		return;
5395 	}
5396 
5397 	srch_sio = sio_alloc(BP_GET_NDVAS(bp), B_FALSE);
5398 	bp2sio(bp, srch_sio, dva_i);
5399 	start = SIO_GET_OFFSET(srch_sio);
5400 	size = SIO_GET_ASIZE(srch_sio);
5401 
5402 	/*
5403 	 * We can find the zio in two states:
5404 	 * 1) Cold, just sitting in the queue of zio's to be issued at
5405 	 *	some point in the future. In this case, all we do is
5406 	 *	remove the zio from the q_sios_by_addr tree, decrement
5407 	 *	its data volume from the containing zfs_range_seg_t and
5408 	 *	resort the q_exts_by_size tree to reflect that the
5409 	 *	zfs_range_seg_t has lost some of its 'fill'. We don't shorten
5410 	 *	the zfs_range_seg_t - this is usually rare enough not to be
5411 	 *	worth the extra hassle of trying keep track of precise
5412 	 *	extent boundaries.
5413 	 * 2) Hot, where the zio is currently in-flight in
5414 	 *	dsl_scan_issue_ios. In this case, we can't simply
5415 	 *	reach in and stop the in-flight zio's, so we instead
5416 	 *	block the caller. Eventually, dsl_scan_issue_ios will
5417 	 *	be done with issuing the zio's it gathered and will
5418 	 *	signal us.
5419 	 */
5420 	sio = avl_find(&queue->q_sios_by_addr, srch_sio, &idx);
5421 	sio_free(srch_sio);
5422 
5423 	if (sio != NULL) {
5424 		blkptr_t tmpbp;
5425 
5426 		/* Got it while it was cold in the queue */
5427 		ASSERT3U(start, ==, SIO_GET_OFFSET(sio));
5428 		ASSERT3U(size, ==, SIO_GET_ASIZE(sio));
5429 		avl_remove(&queue->q_sios_by_addr, sio);
5430 		if (avl_is_empty(&queue->q_sios_by_addr))
5431 			atomic_add_64(&scn->scn_queues_pending, -1);
5432 		queue->q_sio_memused -= SIO_GET_MUSED(sio);
5433 
5434 		ASSERT(zfs_range_tree_contains(queue->q_exts_by_addr, start,
5435 		    size));
5436 		zfs_range_tree_remove_fill(queue->q_exts_by_addr, start, size);
5437 
5438 		/* count the block as though we skipped it */
5439 		sio2bp(sio, &tmpbp);
5440 		count_block_skipped(scn, &tmpbp, B_FALSE);
5441 
5442 		sio_free(sio);
5443 	}
5444 	mutex_exit(q_lock);
5445 }
5446 
5447 /*
5448  * Callback invoked when a zio_free() zio is executing. This needs to be
5449  * intercepted to prevent the zio from deallocating a particular portion
5450  * of disk space and it then getting reallocated and written to, while we
5451  * still have it queued up for processing.
5452  */
5453 void
dsl_scan_freed(spa_t * spa,const blkptr_t * bp)5454 dsl_scan_freed(spa_t *spa, const blkptr_t *bp)
5455 {
5456 	dsl_pool_t *dp = spa->spa_dsl_pool;
5457 	dsl_scan_t *scn = dp->dp_scan;
5458 
5459 	ASSERT(!BP_IS_EMBEDDED(bp));
5460 	ASSERT(scn != NULL);
5461 	if (!dsl_scan_is_running(scn))
5462 		return;
5463 
5464 	for (int i = 0; i < BP_GET_NDVAS(bp); i++)
5465 		dsl_scan_freed_dva(spa, bp, i);
5466 }
5467 
5468 /*
5469  * Check if a vdev needs resilvering (non-empty DTL), if so, and resilver has
5470  * not started, start it. Otherwise, only restart if max txg in DTL range is
5471  * greater than the max txg in the current scan. If the DTL max is less than
5472  * the scan max, then the vdev has not missed any new data since the resilver
5473  * started, so a restart is not needed.
5474  */
5475 void
dsl_scan_assess_vdev(dsl_pool_t * dp,vdev_t * vd)5476 dsl_scan_assess_vdev(dsl_pool_t *dp, vdev_t *vd)
5477 {
5478 	uint64_t min, max;
5479 
5480 	if (!vdev_resilver_needed(vd, &min, &max))
5481 		return;
5482 
5483 	if (!dsl_scan_resilvering(dp)) {
5484 		spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);
5485 		return;
5486 	}
5487 
5488 	if (max <= dp->dp_scan->scn_phys.scn_max_txg)
5489 		return;
5490 
5491 	/* restart is needed, check if it can be deferred */
5492 	if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER))
5493 		vdev_defer_resilver(vd);
5494 	else
5495 		spa_async_request(dp->dp_spa, SPA_ASYNC_RESILVER);
5496 }
5497 
5498 ZFS_MODULE_PARAM(zfs, zfs_, scan_vdev_limit, U64, ZMOD_RW,
5499 	"Max bytes in flight per leaf vdev for scrubs and resilvers");
5500 
5501 ZFS_MODULE_PARAM(zfs, zfs_, scrub_min_time_ms, UINT, ZMOD_RW,
5502 	"Min millisecs to scrub per txg");
5503 
5504 ZFS_MODULE_PARAM(zfs, zfs_, obsolete_min_time_ms, UINT, ZMOD_RW,
5505 	"Min millisecs to obsolete per txg");
5506 
5507 ZFS_MODULE_PARAM(zfs, zfs_, free_min_time_ms, UINT, ZMOD_RW,
5508 	"Min millisecs to free per txg");
5509 
5510 ZFS_MODULE_PARAM(zfs, zfs_, resilver_min_time_ms, UINT, ZMOD_RW,
5511 	"Min millisecs to resilver per txg");
5512 
5513 ZFS_MODULE_PARAM(zfs, zfs_, scan_suspend_progress, INT, ZMOD_RW,
5514 	"Set to prevent scans from progressing");
5515 
5516 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_io, INT, ZMOD_RW,
5517 	"Set to disable scrub I/O");
5518 
5519 ZFS_MODULE_PARAM(zfs, zfs_, no_scrub_prefetch, INT, ZMOD_RW,
5520 	"Set to disable scrub prefetching");
5521 
5522 ZFS_MODULE_PARAM(zfs, zfs_, async_block_max_blocks, U64, ZMOD_RW,
5523 	"Max number of blocks freed in one txg");
5524 
5525 ZFS_MODULE_PARAM(zfs, zfs_, max_async_dedup_frees, U64, ZMOD_RW,
5526 	"Max number of dedup, clone or gang blocks freed in one txg");
5527 
5528 ZFS_MODULE_PARAM(zfs, zfs_, async_free_zio_wait_interval, U64, ZMOD_RW,
5529 	"Wait for pending free I/Os after issuing this many asynchronously");
5530 
5531 ZFS_MODULE_PARAM(zfs, zfs_, free_bpobj_enabled, INT, ZMOD_RW,
5532 	"Enable processing of the free_bpobj");
5533 
5534 ZFS_MODULE_PARAM(zfs, zfs_, scan_blkstats, INT, ZMOD_RW,
5535 	"Enable block statistics calculation during scrub");
5536 
5537 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_fact, UINT, ZMOD_RW,
5538 	"Fraction of RAM for scan hard limit");
5539 
5540 ZFS_MODULE_PARAM(zfs, zfs_, scan_issue_strategy, UINT, ZMOD_RW,
5541 	"IO issuing strategy during scrubbing. 0 = default, 1 = LBA, 2 = size");
5542 
5543 ZFS_MODULE_PARAM(zfs, zfs_, scan_legacy, INT, ZMOD_RW,
5544 	"Scrub using legacy non-sequential method");
5545 
5546 ZFS_MODULE_PARAM(zfs, zfs_, import_defer_txgs, UINT, ZMOD_RW,
5547 	"Number of TXGs to defer background work after pool import");
5548 
5549 ZFS_MODULE_PARAM(zfs, zfs_, scan_checkpoint_intval, UINT, ZMOD_RW,
5550 	"Scan progress on-disk checkpointing interval");
5551 
5552 ZFS_MODULE_PARAM(zfs, zfs_, scan_max_ext_gap, U64, ZMOD_RW,
5553 	"Max gap in bytes between sequential scrub / resilver I/Os");
5554 
5555 ZFS_MODULE_PARAM(zfs, zfs_, scan_mem_lim_soft_fact, UINT, ZMOD_RW,
5556 	"Fraction of hard limit used as soft limit");
5557 
5558 ZFS_MODULE_PARAM(zfs, zfs_, scan_strict_mem_lim, INT, ZMOD_RW,
5559 	"Tunable to attempt to reduce lock contention");
5560 
5561 ZFS_MODULE_PARAM(zfs, zfs_, scan_fill_weight, UINT, ZMOD_RW,
5562 	"Tunable to adjust bias towards more filled segments during scans");
5563 
5564 ZFS_MODULE_PARAM(zfs, zfs_, scan_report_txgs, UINT, ZMOD_RW,
5565 	"Tunable to report resilver performance over the last N txgs");
5566 
5567 ZFS_MODULE_PARAM(zfs, zfs_, resilver_disable_defer, INT, ZMOD_RW,
5568 	"Process all resilvers immediately");
5569 
5570 ZFS_MODULE_PARAM(zfs, zfs_, resilver_defer_percent, UINT, ZMOD_RW,
5571 	"Issued IO percent complete after which resilvers are deferred");
5572 
5573 ZFS_MODULE_PARAM(zfs, zfs_, scrub_error_blocks_per_txg, UINT, ZMOD_RW,
5574 	"Error blocks to be scrubbed in one txg");
5575