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