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