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