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