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