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