xref: /linux/fs/btrfs/scrub.c (revision 1fd742c7479961da6d0bb794ef8ac6b7b9442847)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011, 2012 STRATO.  All rights reserved.
4  */
5 
6 #include <linux/blkdev.h>
7 #include <linux/ratelimit.h>
8 #include <linux/sched/mm.h>
9 #include "ctree.h"
10 #include "discard.h"
11 #include "volumes.h"
12 #include "disk-io.h"
13 #include "ordered-data.h"
14 #include "transaction.h"
15 #include "backref.h"
16 #include "extent_io.h"
17 #include "dev-replace.h"
18 #include "raid56.h"
19 #include "block-group.h"
20 #include "zoned.h"
21 #include "fs.h"
22 #include "accessors.h"
23 #include "file-item.h"
24 #include "scrub.h"
25 #include "raid-stripe-tree.h"
26 
27 /*
28  * This is only the first step towards a full-features scrub. It reads all
29  * extent and super block and verifies the checksums. In case a bad checksum
30  * is found or the extent cannot be read, good data will be written back if
31  * any can be found.
32  *
33  * Future enhancements:
34  *  - In case an unrepairable extent is encountered, track which files are
35  *    affected and report them
36  *  - track and record media errors, throw out bad devices
37  *  - add a mode to also read unallocated space
38  */
39 
40 struct scrub_ctx;
41 
42 /*
43  * The following value only influences the performance.
44  *
45  * This determines how many stripes would be submitted in one go,
46  * which is 512KiB (BTRFS_STRIPE_LEN * SCRUB_STRIPES_PER_GROUP).
47  */
48 #define SCRUB_STRIPES_PER_GROUP		8
49 
50 /*
51  * How many groups we have for each sctx.
52  *
53  * This would be 8M per device, the same value as the old scrub in-flight bios
54  * size limit.
55  */
56 #define SCRUB_GROUPS_PER_SCTX		16
57 
58 #define SCRUB_TOTAL_STRIPES		(SCRUB_GROUPS_PER_SCTX * SCRUB_STRIPES_PER_GROUP)
59 
60 /* Represent one sector and its needed info to verify the content. */
61 struct scrub_sector_verification {
62 	union {
63 		/*
64 		 * Csum pointer for data csum verification.  Should point to a
65 		 * sector csum inside scrub_stripe::csums.
66 		 *
67 		 * NULL if this data sector has no csum.
68 		 */
69 		u8 *csum;
70 
71 		/*
72 		 * Extra info for metadata verification.  All sectors inside a
73 		 * tree block share the same generation.
74 		 */
75 		u64 generation;
76 	};
77 };
78 
79 enum scrub_stripe_flags {
80 	/* Set when @mirror_num, @dev, @physical and @logical are set. */
81 	SCRUB_STRIPE_FLAG_INITIALIZED,
82 
83 	/* Set when the read-repair is finished. */
84 	SCRUB_STRIPE_FLAG_REPAIR_DONE,
85 
86 	/*
87 	 * Set for data stripes if it's triggered from P/Q stripe.
88 	 * During such scrub, we should not report errors in data stripes, nor
89 	 * update the accounting.
90 	 */
91 	SCRUB_STRIPE_FLAG_NO_REPORT,
92 };
93 
94 /*
95  * We have multiple bitmaps for one scrub_stripe.
96  * However each bitmap has at most (BTRFS_STRIPE_LEN / blocksize) bits,
97  * which is normally 16, and much smaller than BITS_PER_LONG (32 or 64).
98  *
99  * So to reduce memory usage for each scrub_stripe, we pack those bitmaps
100  * into a larger one.
101  *
102  * These enum records where the sub-bitmap are inside the larger one.
103  * Each subbitmap starts at scrub_bitmap_nr_##name * nr_sectors bit.
104  */
105 enum {
106 	/* Which blocks are covered by extent items. */
107 	scrub_bitmap_nr_has_extent = 0,
108 
109 	/* Which blocks are metadata. */
110 	scrub_bitmap_nr_is_metadata,
111 
112 	/*
113 	 * Which blocks have errors, including IO, csum, and metadata
114 	 * errors.
115 	 * This sub-bitmap is the OR results of the next few error related
116 	 * sub-bitmaps.
117 	 */
118 	scrub_bitmap_nr_error,
119 	scrub_bitmap_nr_io_error,
120 	scrub_bitmap_nr_csum_error,
121 	scrub_bitmap_nr_meta_error,
122 	scrub_bitmap_nr_meta_gen_error,
123 	scrub_bitmap_nr_last,
124 };
125 
126 /*
127  * Represent one contiguous range with a length of BTRFS_STRIPE_LEN.
128  */
129 struct scrub_stripe {
130 	struct scrub_ctx *sctx;
131 	struct btrfs_block_group *bg;
132 	struct scrub_sector_verification *sectors;
133 	struct btrfs_device *dev;
134 
135 	void *buffer;
136 
137 	u64 logical;
138 	u64 physical;
139 
140 	u16 mirror_num;
141 
142 	/* Should be BTRFS_STRIPE_LEN / sectorsize. */
143 	u16 nr_sectors;
144 
145 	/*
146 	 * How many data/meta extents are in this stripe.  Only for scrub status
147 	 * reporting purposes.
148 	 */
149 	u16 nr_data_extents;
150 	u16 nr_meta_extents;
151 
152 	atomic_t pending_io;
153 	wait_queue_head_t io_wait;
154 	wait_queue_head_t repair_wait;
155 
156 	/*
157 	 * Indicate the states of the stripe.  Bits are defined in
158 	 * scrub_stripe_flags enum.
159 	 */
160 	unsigned long state;
161 
162 	/* The large bitmap contains all the sub-bitmaps. */
163 	unsigned long bitmaps[BITS_TO_LONGS(scrub_bitmap_nr_last *
164 					    (BTRFS_STRIPE_LEN / BTRFS_MIN_BLOCKSIZE))];
165 
166 	/*
167 	 * For writeback (repair or replace) error reporting.
168 	 * This one is protected by a spinlock, thus can not be packed into
169 	 * the larger bitmap.
170 	 */
171 	unsigned long write_error_bitmap;
172 
173 	/* Writeback can be concurrent, thus we need to protect the bitmap. */
174 	spinlock_t write_error_lock;
175 
176 	/*
177 	 * Checksum for the whole stripe if this stripe is inside a data block
178 	 * group.
179 	 */
180 	u8 *csums;
181 
182 	struct work_struct work;
183 };
184 
185 struct scrub_ctx {
186 	struct scrub_stripe	stripes[SCRUB_TOTAL_STRIPES];
187 	struct scrub_stripe	*raid56_data_stripes;
188 	struct btrfs_fs_info	*fs_info;
189 	struct btrfs_path	extent_path;
190 	struct btrfs_path	csum_path;
191 	int			first_free;
192 	int			cur_stripe;
193 	atomic_t		cancel_req;
194 	int			readonly;
195 
196 	/* State of IO submission throttling affecting the associated device */
197 	ktime_t			throttle_deadline;
198 	u64			throttle_sent;
199 
200 	bool			is_dev_replace;
201 	u64			write_pointer;
202 
203 	struct mutex            wr_lock;
204 	struct btrfs_device     *wr_tgtdev;
205 
206 	/*
207 	 * statistics
208 	 */
209 	struct btrfs_scrub_progress stat;
210 	spinlock_t		stat_lock;
211 
212 	/*
213 	 * Use a ref counter to avoid use-after-free issues. Scrub workers
214 	 * decrement bios_in_flight and workers_pending and then do a wakeup
215 	 * on the list_wait wait queue. We must ensure the main scrub task
216 	 * doesn't free the scrub context before or while the workers are
217 	 * doing the wakeup() call.
218 	 */
219 	refcount_t              refs;
220 };
221 
222 static_assert(BTRFS_STRIPE_LEN >= PAGE_SIZE);
223 static_assert(IS_ALIGNED(BTRFS_STRIPE_LEN, PAGE_SIZE));
224 
225 #define scrub_calc_start_bit(stripe, name, block_nr)			\
226 ({									\
227 	unsigned int __start_bit;					\
228 									\
229 	ASSERT(block_nr < stripe->nr_sectors,				\
230 		"nr_sectors=%u block_nr=%u", stripe->nr_sectors, block_nr); \
231 	__start_bit = scrub_bitmap_nr_##name * stripe->nr_sectors + block_nr; \
232 	__start_bit;							\
233 })
234 
235 #define IMPLEMENT_SCRUB_BITMAP_OPS(name)				\
236 static inline void scrub_bitmap_set_##name(struct scrub_stripe *stripe,	\
237 				    unsigned int block_nr,		\
238 				    unsigned int nr_blocks)		\
239 {									\
240 	const unsigned int start_bit = scrub_calc_start_bit(stripe,	\
241 							    name, block_nr); \
242 									\
243 	bitmap_set(stripe->bitmaps, start_bit, nr_blocks);		\
244 }									\
245 static inline void scrub_bitmap_clear_##name(struct scrub_stripe *stripe, \
246 				      unsigned int block_nr,		\
247 				      unsigned int nr_blocks)		\
248 {									\
249 	const unsigned int start_bit = scrub_calc_start_bit(stripe, name, \
250 							    block_nr);	\
251 									\
252 	bitmap_clear(stripe->bitmaps, start_bit, nr_blocks);		\
253 }									\
254 static inline bool scrub_bitmap_test_bit_##name(struct scrub_stripe *stripe, \
255 				     unsigned int block_nr)		\
256 {									\
257 	const unsigned int start_bit = scrub_calc_start_bit(stripe, name, \
258 							    block_nr);	\
259 									\
260 	return test_bit(start_bit, stripe->bitmaps);			\
261 }									\
262 static inline void scrub_bitmap_set_bit_##name(struct scrub_stripe *stripe, \
263 				     unsigned int block_nr)		\
264 {									\
265 	const unsigned int start_bit = scrub_calc_start_bit(stripe, name, \
266 							    block_nr);	\
267 									\
268 	set_bit(start_bit, stripe->bitmaps);				\
269 }									\
270 static inline void scrub_bitmap_clear_bit_##name(struct scrub_stripe *stripe, \
271 				     unsigned int block_nr)		\
272 {									\
273 	const unsigned int start_bit = scrub_calc_start_bit(stripe, name, \
274 							    block_nr);	\
275 									\
276 	clear_bit(start_bit, stripe->bitmaps);				\
277 }									\
278 static inline unsigned long scrub_bitmap_read_##name(struct scrub_stripe *stripe) \
279 {									\
280 	const unsigned int nr_blocks = stripe->nr_sectors;		\
281 									\
282 	ASSERT(nr_blocks > 0 && nr_blocks <= BITS_PER_LONG,		\
283 	       "nr_blocks=%u BITS_PER_LONG=%u",				\
284 	       nr_blocks, BITS_PER_LONG);				\
285 									\
286 	return bitmap_read(stripe->bitmaps, nr_blocks * scrub_bitmap_nr_##name, \
287 			   stripe->nr_sectors);				\
288 }									\
289 static inline bool scrub_bitmap_empty_##name(struct scrub_stripe *stripe) \
290 {									\
291 	unsigned long bitmap = scrub_bitmap_read_##name(stripe);	\
292 									\
293 	return bitmap_empty(&bitmap, stripe->nr_sectors);		\
294 }									\
295 static inline unsigned int scrub_bitmap_weight_##name(struct scrub_stripe *stripe) \
296 {									\
297 	unsigned long bitmap = scrub_bitmap_read_##name(stripe);	\
298 									\
299 	return bitmap_weight(&bitmap, stripe->nr_sectors);		\
300 }
301 IMPLEMENT_SCRUB_BITMAP_OPS(has_extent);
302 IMPLEMENT_SCRUB_BITMAP_OPS(is_metadata);
303 IMPLEMENT_SCRUB_BITMAP_OPS(error);
304 IMPLEMENT_SCRUB_BITMAP_OPS(io_error);
305 IMPLEMENT_SCRUB_BITMAP_OPS(csum_error);
306 IMPLEMENT_SCRUB_BITMAP_OPS(meta_error);
307 IMPLEMENT_SCRUB_BITMAP_OPS(meta_gen_error);
308 
309 struct scrub_warning {
310 	struct btrfs_path	*path;
311 	u64			extent_item_size;
312 	const char		*errstr;
313 	u64			physical;
314 	u64			logical;
315 	struct btrfs_device	*dev;
316 };
317 
318 struct scrub_error_records {
319 	/*
320 	 * Bitmap recording which blocks hit errors (IO/csum/...) during the
321 	 * initial read.
322 	 */
323 	unsigned long init_error_bitmap;
324 
325 	unsigned int nr_io_errors;
326 	unsigned int nr_csum_errors;
327 	unsigned int nr_meta_errors;
328 	unsigned int nr_meta_gen_errors;
329 };
330 
331 static void release_scrub_stripe(struct scrub_stripe *stripe)
332 {
333 	if (!stripe)
334 		return;
335 
336 	kvfree(stripe->buffer);
337 	kfree(stripe->sectors);
338 	kfree(stripe->csums);
339 	stripe->buffer = NULL;
340 	stripe->sectors = NULL;
341 	stripe->csums = NULL;
342 	stripe->sctx = NULL;
343 	stripe->state = 0;
344 }
345 
346 static int init_scrub_stripe(struct btrfs_fs_info *fs_info,
347 			     struct scrub_stripe *stripe)
348 {
349 	memset(stripe, 0, sizeof(*stripe));
350 
351 	stripe->nr_sectors = BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits;
352 	stripe->state = 0;
353 
354 	init_waitqueue_head(&stripe->io_wait);
355 	init_waitqueue_head(&stripe->repair_wait);
356 	atomic_set(&stripe->pending_io, 0);
357 	spin_lock_init(&stripe->write_error_lock);
358 
359 	stripe->buffer = kvmalloc(BTRFS_STRIPE_LEN, GFP_NOFS);
360 	if (!stripe->buffer)
361 		goto error;
362 
363 	stripe->sectors = kzalloc_objs(struct scrub_sector_verification,
364 				       stripe->nr_sectors);
365 	if (!stripe->sectors)
366 		goto error;
367 
368 	stripe->csums = kcalloc(BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits,
369 				fs_info->csum_size, GFP_KERNEL);
370 	if (!stripe->csums)
371 		goto error;
372 	return 0;
373 error:
374 	release_scrub_stripe(stripe);
375 	return -ENOMEM;
376 }
377 
378 static void wait_scrub_stripe_io(struct scrub_stripe *stripe)
379 {
380 	wait_event(stripe->io_wait, atomic_read(&stripe->pending_io) == 0);
381 }
382 
383 static void scrub_put_ctx(struct scrub_ctx *sctx);
384 
385 static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
386 {
387 	while (atomic_read(&fs_info->scrub_pause_req)) {
388 		mutex_unlock(&fs_info->scrub_lock);
389 		wait_event(fs_info->scrub_pause_wait,
390 		   atomic_read(&fs_info->scrub_pause_req) == 0);
391 		mutex_lock(&fs_info->scrub_lock);
392 	}
393 }
394 
395 static void scrub_pause_on(struct btrfs_fs_info *fs_info)
396 {
397 	atomic_inc(&fs_info->scrubs_paused);
398 	wake_up(&fs_info->scrub_pause_wait);
399 }
400 
401 static void scrub_pause_off(struct btrfs_fs_info *fs_info)
402 {
403 	mutex_lock(&fs_info->scrub_lock);
404 	__scrub_blocked_if_needed(fs_info);
405 	atomic_dec(&fs_info->scrubs_paused);
406 	mutex_unlock(&fs_info->scrub_lock);
407 
408 	wake_up(&fs_info->scrub_pause_wait);
409 }
410 
411 static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
412 {
413 	scrub_pause_on(fs_info);
414 	scrub_pause_off(fs_info);
415 }
416 
417 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
418 {
419 	int i;
420 
421 	if (!sctx)
422 		return;
423 
424 	for (i = 0; i < SCRUB_TOTAL_STRIPES; i++)
425 		release_scrub_stripe(&sctx->stripes[i]);
426 
427 	kvfree(sctx);
428 }
429 
430 static void scrub_put_ctx(struct scrub_ctx *sctx)
431 {
432 	if (refcount_dec_and_test(&sctx->refs))
433 		scrub_free_ctx(sctx);
434 }
435 
436 static noinline_for_stack struct scrub_ctx *scrub_setup_ctx(
437 		struct btrfs_fs_info *fs_info, bool is_dev_replace)
438 {
439 	struct scrub_ctx *sctx;
440 	int		i;
441 
442 	/* Since sctx has inline 128 stripes, it can go beyond 64K easily.  Use
443 	 * kvzalloc().
444 	 */
445 	sctx = kvzalloc_obj(*sctx);
446 	if (!sctx)
447 		goto nomem;
448 	refcount_set(&sctx->refs, 1);
449 	sctx->is_dev_replace = is_dev_replace;
450 	sctx->fs_info = fs_info;
451 	sctx->extent_path.search_commit_root = true;
452 	sctx->extent_path.skip_locking = true;
453 	sctx->csum_path.search_commit_root = true;
454 	sctx->csum_path.skip_locking = true;
455 	for (i = 0; i < SCRUB_TOTAL_STRIPES; i++) {
456 		int ret;
457 
458 		ret = init_scrub_stripe(fs_info, &sctx->stripes[i]);
459 		if (ret < 0)
460 			goto nomem;
461 		sctx->stripes[i].sctx = sctx;
462 	}
463 	sctx->first_free = 0;
464 	atomic_set(&sctx->cancel_req, 0);
465 
466 	spin_lock_init(&sctx->stat_lock);
467 	sctx->throttle_deadline = 0;
468 
469 	mutex_init(&sctx->wr_lock);
470 	if (is_dev_replace) {
471 		WARN_ON(!fs_info->dev_replace.tgtdev);
472 		sctx->wr_tgtdev = fs_info->dev_replace.tgtdev;
473 	}
474 
475 	return sctx;
476 
477 nomem:
478 	scrub_free_ctx(sctx);
479 	return ERR_PTR(-ENOMEM);
480 }
481 
482 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
483 				     u64 root, void *warn_ctx)
484 {
485 	u32 nlink;
486 	int ret;
487 	int i;
488 	unsigned nofs_flag;
489 	struct extent_buffer *eb;
490 	struct btrfs_inode_item *inode_item;
491 	struct scrub_warning *swarn = warn_ctx;
492 	struct btrfs_fs_info *fs_info = swarn->dev->fs_info;
493 	struct inode_fs_paths *ipath __free(inode_fs_paths) = NULL;
494 	struct btrfs_root *local_root;
495 	struct btrfs_key key;
496 
497 	local_root = btrfs_get_fs_root(fs_info, root, true);
498 	if (IS_ERR(local_root)) {
499 		ret = PTR_ERR(local_root);
500 		goto err;
501 	}
502 
503 	/*
504 	 * this makes the path point to (inum INODE_ITEM ioff)
505 	 */
506 	key.objectid = inum;
507 	key.type = BTRFS_INODE_ITEM_KEY;
508 	key.offset = 0;
509 
510 	ret = btrfs_search_slot(NULL, local_root, &key, swarn->path, 0, 0);
511 	if (ret) {
512 		btrfs_put_root(local_root);
513 		btrfs_release_path(swarn->path);
514 		goto err;
515 	}
516 
517 	eb = swarn->path->nodes[0];
518 	inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
519 					struct btrfs_inode_item);
520 	nlink = btrfs_inode_nlink(eb, inode_item);
521 	btrfs_release_path(swarn->path);
522 
523 	/*
524 	 * init_path might indirectly call vmalloc, or use GFP_KERNEL. Scrub
525 	 * uses GFP_NOFS in this context, so we keep it consistent but it does
526 	 * not seem to be strictly necessary.
527 	 */
528 	nofs_flag = memalloc_nofs_save();
529 	ipath = init_ipath(4096, local_root, swarn->path);
530 	memalloc_nofs_restore(nofs_flag);
531 	if (IS_ERR(ipath)) {
532 		btrfs_put_root(local_root);
533 		ret = PTR_ERR(ipath);
534 		ipath = NULL;
535 		goto err;
536 	}
537 	ret = paths_from_inode(inum, ipath);
538 
539 	if (ret < 0) {
540 		btrfs_put_root(local_root);
541 		goto err;
542 	}
543 
544 	/*
545 	 * we deliberately ignore the bit ipath might have been too small to
546 	 * hold all of the paths here
547 	 */
548 	for (i = 0; i < ipath->fspath->elem_cnt; ++i)
549 		btrfs_warn(fs_info,
550 "scrub: %s at logical %llu on dev %s, physical %llu root %llu inode %llu offset %llu length %u links %u (path: %s)",
551 				  swarn->errstr, swarn->logical,
552 				  btrfs_dev_name(swarn->dev),
553 				  swarn->physical,
554 				  root, inum, offset,
555 				  fs_info->sectorsize, nlink,
556 				  (char *)(unsigned long)ipath->fspath->val[i]);
557 
558 	btrfs_put_root(local_root);
559 	return 0;
560 
561 err:
562 	btrfs_warn(fs_info,
563 			  "scrub: %s at logical %llu on dev %s, physical %llu root %llu inode %llu offset %llu: path resolving failed with ret=%d",
564 			  swarn->errstr, swarn->logical,
565 			  btrfs_dev_name(swarn->dev),
566 			  swarn->physical,
567 			  root, inum, offset, ret);
568 
569 	return 0;
570 }
571 
572 static void scrub_print_common_warning(const char *errstr, struct btrfs_device *dev,
573 				       bool is_super, u64 logical, u64 physical)
574 {
575 	struct btrfs_fs_info *fs_info = dev->fs_info;
576 	BTRFS_PATH_AUTO_FREE(path);
577 	struct btrfs_key found_key;
578 	struct extent_buffer *eb;
579 	struct btrfs_extent_item *ei;
580 	struct scrub_warning swarn;
581 	u64 flags = 0;
582 	u32 item_size;
583 	int ret;
584 
585 	/* Super block error, no need to search extent tree. */
586 	if (is_super) {
587 		btrfs_warn(fs_info, "scrub: %s on device %s, physical %llu",
588 				  errstr, btrfs_dev_name(dev), physical);
589 		return;
590 	}
591 	path = btrfs_alloc_path();
592 	if (!path)
593 		return;
594 
595 	swarn.physical = physical;
596 	swarn.logical = logical;
597 	swarn.errstr = errstr;
598 	swarn.dev = NULL;
599 
600 	ret = extent_from_logical(fs_info, swarn.logical, path, &found_key,
601 				  &flags);
602 	if (ret < 0)
603 		return;
604 
605 	swarn.extent_item_size = found_key.offset;
606 
607 	eb = path->nodes[0];
608 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
609 	item_size = btrfs_item_size(eb, path->slots[0]);
610 
611 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
612 		unsigned long ptr = 0;
613 		u8 ref_level;
614 		u64 ref_root;
615 
616 		while (true) {
617 			ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
618 						      item_size, &ref_root,
619 						      &ref_level);
620 			if (ret < 0) {
621 				btrfs_warn(fs_info,
622 		   "scrub: failed to resolve tree backref for logical %llu: %d",
623 					   swarn.logical, ret);
624 				break;
625 			}
626 			if (ret > 0)
627 				break;
628 			btrfs_warn(fs_info,
629 "scrub: %s at logical %llu on dev %s, physical %llu: metadata %s (level %d) in tree %llu",
630 				errstr, swarn.logical, btrfs_dev_name(dev),
631 				swarn.physical, (ref_level ? "node" : "leaf"),
632 				ref_level, ref_root);
633 		}
634 		btrfs_release_path(path);
635 	} else {
636 		struct btrfs_backref_walk_ctx ctx = { 0 };
637 
638 		btrfs_release_path(path);
639 
640 		ctx.bytenr = found_key.objectid;
641 		ctx.extent_item_pos = swarn.logical - found_key.objectid;
642 		ctx.fs_info = fs_info;
643 
644 		swarn.path = path;
645 		swarn.dev = dev;
646 
647 		iterate_extent_inodes(&ctx, true, scrub_print_warning_inode, &swarn);
648 	}
649 }
650 
651 static int fill_writer_pointer_gap(struct scrub_ctx *sctx, u64 physical)
652 {
653 	int ret = 0;
654 	u64 length;
655 
656 	if (!btrfs_is_zoned(sctx->fs_info))
657 		return 0;
658 
659 	if (!btrfs_dev_is_sequential(sctx->wr_tgtdev, physical))
660 		return 0;
661 
662 	if (sctx->write_pointer < physical) {
663 		length = physical - sctx->write_pointer;
664 
665 		ret = btrfs_zoned_issue_zeroout(sctx->wr_tgtdev,
666 						sctx->write_pointer, length);
667 		if (!ret)
668 			sctx->write_pointer = physical;
669 	}
670 	return ret;
671 }
672 
673 /*
674  * Unlike the existing csum which is based on paddr, this version is fully on
675  * vaddr, so no extra per-page iteration needed.
676  */
677 static void scrub_calc_vaddr_csum(struct btrfs_fs_info *fs_info,
678 				  void *vaddr, unsigned int len, u8 *dest)
679 {
680 	struct btrfs_csum_ctx csum;
681 
682 	btrfs_csum_init(&csum, fs_info->csum_type);
683 	btrfs_csum_update(&csum, vaddr, len);
684 	btrfs_csum_final(&csum, dest);
685 }
686 
687 static void scrub_verify_one_metadata(struct scrub_stripe *stripe, int sector_nr)
688 {
689 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
690 	const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
691 	const u64 logical = stripe->logical + (sector_nr << fs_info->sectorsize_bits);
692 	void *first_vaddr = stripe->buffer + (sector_nr << fs_info->sectorsize_bits);
693 	struct btrfs_header *header = first_vaddr;
694 	u8 calculated_csum[BTRFS_CSUM_SIZE];
695 
696 	if (logical != btrfs_stack_header_bytenr(header)) {
697 		scrub_bitmap_set_meta_error(stripe, sector_nr, sectors_per_tree);
698 		scrub_bitmap_set_error(stripe, sector_nr, sectors_per_tree);
699 		btrfs_warn_rl(fs_info,
700 	  "scrub: tree block %llu mirror %u has bad bytenr, has %llu want %llu",
701 			      logical, stripe->mirror_num,
702 			      btrfs_stack_header_bytenr(header), logical);
703 		return;
704 	}
705 	if (memcmp(header->fsid, fs_info->fs_devices->metadata_uuid,
706 		   BTRFS_FSID_SIZE) != 0) {
707 		scrub_bitmap_set_meta_error(stripe, sector_nr, sectors_per_tree);
708 		scrub_bitmap_set_error(stripe, sector_nr, sectors_per_tree);
709 		btrfs_warn_rl(fs_info,
710 	      "scrub: tree block %llu mirror %u has bad fsid, has %pU want %pU",
711 			      logical, stripe->mirror_num,
712 			      header->fsid, fs_info->fs_devices->metadata_uuid);
713 		return;
714 	}
715 	if (memcmp(header->chunk_tree_uuid, fs_info->chunk_tree_uuid,
716 		   BTRFS_UUID_SIZE) != 0) {
717 		scrub_bitmap_set_meta_error(stripe, sector_nr, sectors_per_tree);
718 		scrub_bitmap_set_error(stripe, sector_nr, sectors_per_tree);
719 		btrfs_warn_rl(fs_info,
720    "scrub: tree block %llu mirror %u has bad chunk tree uuid, has %pU want %pU",
721 			      logical, stripe->mirror_num,
722 			      header->chunk_tree_uuid, fs_info->chunk_tree_uuid);
723 		return;
724 	}
725 
726 	/* Now check tree block csum. */
727 	scrub_calc_vaddr_csum(fs_info, first_vaddr + BTRFS_CSUM_SIZE,
728 			      fs_info->nodesize - BTRFS_CSUM_SIZE, calculated_csum);
729 	if (memcmp(calculated_csum, header->csum, fs_info->csum_size) != 0) {
730 		scrub_bitmap_set_meta_error(stripe, sector_nr, sectors_per_tree);
731 		scrub_bitmap_set_error(stripe, sector_nr, sectors_per_tree);
732 		btrfs_warn_rl(fs_info,
733 "scrub: tree block %llu mirror %u has bad csum, has " BTRFS_CSUM_FMT " want " BTRFS_CSUM_FMT,
734 			      logical, stripe->mirror_num,
735 			      BTRFS_CSUM_FMT_VALUE(fs_info->csum_size, header->csum),
736 			      BTRFS_CSUM_FMT_VALUE(fs_info->csum_size, calculated_csum));
737 		return;
738 	}
739 	if (stripe->sectors[sector_nr].generation !=
740 	    btrfs_stack_header_generation(header)) {
741 		scrub_bitmap_set_meta_gen_error(stripe, sector_nr, sectors_per_tree);
742 		scrub_bitmap_set_error(stripe, sector_nr, sectors_per_tree);
743 		btrfs_warn_rl(fs_info,
744       "scrub: tree block %llu mirror %u has bad generation, has %llu want %llu",
745 			      logical, stripe->mirror_num,
746 			      btrfs_stack_header_generation(header),
747 			      stripe->sectors[sector_nr].generation);
748 		return;
749 	}
750 	scrub_bitmap_clear_error(stripe, sector_nr, sectors_per_tree);
751 	scrub_bitmap_clear_csum_error(stripe, sector_nr, sectors_per_tree);
752 	scrub_bitmap_clear_meta_error(stripe, sector_nr, sectors_per_tree);
753 	scrub_bitmap_clear_meta_gen_error(stripe, sector_nr, sectors_per_tree);
754 }
755 
756 static void scrub_verify_one_sector(struct scrub_stripe *stripe, int sector_nr)
757 {
758 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
759 	struct scrub_sector_verification *sector = &stripe->sectors[sector_nr];
760 	const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
761 	u8 csum_buf[BTRFS_CSUM_SIZE];
762 
763 	ASSERT(sector_nr >= 0 && sector_nr < stripe->nr_sectors);
764 
765 	/* Sector not utilized, skip it. */
766 	if (!scrub_bitmap_test_bit_has_extent(stripe, sector_nr))
767 		return;
768 
769 	/* IO error, no need to check. */
770 	if (scrub_bitmap_test_bit_io_error(stripe, sector_nr))
771 		return;
772 
773 	/* Metadata, verify the full tree block. */
774 	if (scrub_bitmap_test_bit_is_metadata(stripe, sector_nr)) {
775 		/*
776 		 * Check if the tree block crosses the stripe boundary.  If
777 		 * crossed the boundary, we cannot verify it but only give a
778 		 * warning.
779 		 *
780 		 * This can only happen on a very old filesystem where chunks
781 		 * are not ensured to be stripe aligned.
782 		 */
783 		if (unlikely(sector_nr + sectors_per_tree > stripe->nr_sectors)) {
784 			btrfs_warn_rl(fs_info,
785 			"scrub: tree block at %llu crosses stripe boundary %llu",
786 				      stripe->logical +
787 				      (sector_nr << fs_info->sectorsize_bits),
788 				      stripe->logical);
789 			return;
790 		}
791 		scrub_verify_one_metadata(stripe, sector_nr);
792 		return;
793 	}
794 
795 	/*
796 	 * Data is easier, we just verify the data csum (if we have it).  For
797 	 * cases without csum, we have no other choice but to trust it.
798 	 */
799 	if (!sector->csum) {
800 		scrub_bitmap_clear_bit_error(stripe, sector_nr);
801 		return;
802 	}
803 
804 	scrub_calc_vaddr_csum(fs_info,
805 			      stripe->buffer + (sector_nr << fs_info->sectorsize_bits),
806 			      fs_info->sectorsize, csum_buf);
807 	if (memcmp(csum_buf, sector->csum, fs_info->csum_size)) {
808 		scrub_bitmap_set_bit_csum_error(stripe, sector_nr);
809 		scrub_bitmap_set_bit_error(stripe, sector_nr);
810 	} else {
811 		scrub_bitmap_clear_bit_csum_error(stripe, sector_nr);
812 		scrub_bitmap_clear_bit_error(stripe, sector_nr);
813 	}
814 }
815 
816 /* Verify specified sectors of a stripe. */
817 static void scrub_verify_one_stripe(struct scrub_stripe *stripe, unsigned long bitmap)
818 {
819 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
820 	const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
821 	int sector_nr;
822 
823 	for_each_set_bit(sector_nr, &bitmap, stripe->nr_sectors) {
824 		scrub_verify_one_sector(stripe, sector_nr);
825 		if (scrub_bitmap_test_bit_is_metadata(stripe, sector_nr))
826 			sector_nr += sectors_per_tree - 1;
827 	}
828 }
829 
830 static unsigned int calc_sector_number(const struct btrfs_bio *bbio)
831 {
832 	const struct scrub_stripe *stripe = bbio->private;
833 	const struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
834 
835 	/* Scrub bbios all have their @file_offset set to the logical bytenr. */
836 	ASSERT(bbio->file_offset >= stripe->logical &&
837 	       bbio->file_offset < stripe->logical + (stripe->nr_sectors <<
838 						      fs_info->sectorsize_bits),
839 	       "scrub bio logical=%llu stripe logical=%llu stripe len=%u",
840 	       bbio->file_offset, stripe->logical,
841 	       stripe->nr_sectors << fs_info->sectorsize_bits);
842 	return (bbio->file_offset - stripe->logical) >> fs_info->sectorsize_bits;
843 }
844 
845 /*
846  * Common handling of read endio.
847  *
848  * The bbio will be released, so no more access to @bbio after this function.
849  */
850 static void scrub_read_endio_common(struct btrfs_bio *bbio)
851 {
852 	struct scrub_stripe *stripe = bbio->private;
853 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
854 	unsigned int sector_nr = calc_sector_number(bbio);
855 	const u32 bio_size = bio_get_size(&bbio->bio);
856 	const u32 sectors = bio_size >> fs_info->sectorsize_bits;
857 
858 
859 	/*
860 	 * For vmallocated space, readers need to call invalidate_kernel_vmap_range()
861 	 * to manage the coherency between kernel mapping and devie space mapping.
862 	 */
863 	if (is_vmalloc_addr(stripe->buffer))
864 		invalidate_kernel_vmap_range(
865 			stripe->buffer + (sector_nr << fs_info->sectorsize_bits),
866 			bio_size);
867 
868 	if (bbio->bio.bi_status) {
869 		scrub_bitmap_set_io_error(stripe, sector_nr, sectors);
870 		scrub_bitmap_set_error(stripe, sector_nr, sectors);
871 	} else {
872 		scrub_bitmap_clear_io_error(stripe, sector_nr, sectors);
873 	}
874 	bio_put(&bbio->bio);
875 }
876 
877 /*
878  * Repair read is different to the regular read:
879  *
880  * - Only reads the failed sectors
881  * - May have extra blocksize limits
882  */
883 static void scrub_repair_read_endio(struct btrfs_bio *bbio)
884 {
885 	struct scrub_stripe *stripe = bbio->private;
886 
887 	scrub_read_endio_common(bbio);
888 
889 	if (atomic_dec_and_test(&stripe->pending_io))
890 		wake_up(&stripe->io_wait);
891 }
892 
893 static int calc_next_mirror(int mirror, int num_copies)
894 {
895 	ASSERT(mirror <= num_copies);
896 	return (mirror + 1 > num_copies) ? 1 : mirror + 1;
897 }
898 
899 static void scrub_bio_add_sector(struct btrfs_bio *bbio, struct scrub_stripe *stripe,
900 				 int sector_nr)
901 {
902 	struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
903 	const u32 offset = sector_nr << fs_info->sectorsize_bits;
904 	int ret;
905 
906 	ASSERT(offset + fs_info->sectorsize <= BTRFS_STRIPE_LEN);
907 
908 	if (is_vmalloc_addr(stripe->buffer)) {
909 		ret = bio_add_vmalloc(&bbio->bio, stripe->buffer + offset, fs_info->sectorsize);
910 		ASSERT(ret == true);
911 		return;
912 	}
913 	ret = bio_add_page(&bbio->bio, virt_to_page(stripe->buffer + offset),
914 			   fs_info->sectorsize, offset_in_page(stripe->buffer + offset));
915 	ASSERT(ret == fs_info->sectorsize);
916 }
917 
918 static struct btrfs_bio *alloc_scrub_bbio(struct btrfs_fs_info *fs_info,
919 					  blk_opf_t opf,
920 					  u64 logical,
921 					  btrfs_bio_end_io_t end_io, void *private)
922 {
923 	struct btrfs_bio *bbio;
924 
925 	/*
926 	 * Stripe->buffer is allocated by kvmalloc(), which can be pages at
927 	 * different physical addresses, we have to ensure the bbio is large
928 	 * enough to contain the full stripe.
929 	 */
930 	bbio = btrfs_bio_alloc(BTRFS_STRIPE_LEN >> PAGE_SHIFT, opf,
931 			       BTRFS_I(fs_info->btree_inode),
932 			       logical, end_io, private);
933 	bbio->is_scrub = true;
934 	bbio->bio.bi_iter.bi_sector = logical >> SECTOR_SHIFT;
935 	return bbio;
936 }
937 
938 static void scrub_stripe_submit_repair_read(struct scrub_stripe *stripe,
939 					    int mirror, int blocksize, bool wait)
940 {
941 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
942 	struct btrfs_bio *bbio = NULL;
943 	const unsigned long old_error_bitmap = scrub_bitmap_read_error(stripe);
944 	int i;
945 
946 	ASSERT(stripe->mirror_num >= 1, "stripe->mirror_num=%d", stripe->mirror_num);
947 	ASSERT(atomic_read(&stripe->pending_io) == 0,
948 	       "atomic_read(&stripe->pending_io)=%d", atomic_read(&stripe->pending_io));
949 
950 	for_each_set_bit(i, &old_error_bitmap, stripe->nr_sectors) {
951 		/* The current sector cannot be merged, submit the bio. */
952 		if (bbio && ((i > 0 && !test_bit(i - 1, &old_error_bitmap)) ||
953 			     bbio->bio.bi_iter.bi_size >= blocksize)) {
954 			ASSERT(bbio->bio.bi_iter.bi_size);
955 			atomic_inc(&stripe->pending_io);
956 			btrfs_submit_bbio(bbio, mirror);
957 			if (wait)
958 				wait_scrub_stripe_io(stripe);
959 			bbio = NULL;
960 		}
961 
962 		if (!bbio)
963 			bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ,
964 						stripe->logical + (i << fs_info->sectorsize_bits),
965 						scrub_repair_read_endio, stripe);
966 
967 		scrub_bio_add_sector(bbio, stripe, i);
968 	}
969 	if (bbio) {
970 		ASSERT(bbio->bio.bi_iter.bi_size);
971 		atomic_inc(&stripe->pending_io);
972 		btrfs_submit_bbio(bbio, mirror);
973 		if (wait)
974 			wait_scrub_stripe_io(stripe);
975 	}
976 }
977 
978 static void scrub_stripe_report_errors(struct scrub_ctx *sctx,
979 				       struct scrub_stripe *stripe,
980 				       const struct scrub_error_records *errors)
981 {
982 	static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
983 				      DEFAULT_RATELIMIT_BURST);
984 	struct btrfs_fs_info *fs_info = sctx->fs_info;
985 	struct btrfs_device *dev = NULL;
986 	const unsigned long extent_bitmap = scrub_bitmap_read_has_extent(stripe);
987 	const unsigned long error_bitmap = scrub_bitmap_read_error(stripe);
988 	u64 physical = 0;
989 	int nr_data_sectors = 0;
990 	int nr_meta_sectors = 0;
991 	int nr_nodatacsum_sectors = 0;
992 	int nr_repaired_sectors = 0;
993 	int sector_nr;
994 
995 	if (test_bit(SCRUB_STRIPE_FLAG_NO_REPORT, &stripe->state))
996 		return;
997 
998 	/*
999 	 * Init needed infos for error reporting.
1000 	 *
1001 	 * Although our scrub_stripe infrastructure is mostly based on btrfs_submit_bio()
1002 	 * thus no need for dev/physical, error reporting still needs dev and physical.
1003 	 */
1004 	if (!bitmap_empty(&errors->init_error_bitmap, stripe->nr_sectors)) {
1005 		u64 mapped_len = fs_info->sectorsize;
1006 		struct btrfs_io_context *bioc = NULL;
1007 		int stripe_index = stripe->mirror_num - 1;
1008 		int ret;
1009 
1010 		/* For scrub, our mirror_num should always start at 1. */
1011 		ASSERT(stripe->mirror_num >= 1, "stripe->mirror_num=%d", stripe->mirror_num);
1012 		ret = btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
1013 				      stripe->logical, &mapped_len, &bioc,
1014 				      NULL, NULL);
1015 		/*
1016 		 * If we failed, dev will be NULL, and later detailed reports
1017 		 * will just be skipped.
1018 		 */
1019 		if (ret < 0)
1020 			goto skip;
1021 		physical = bioc->stripes[stripe_index].physical;
1022 		dev = bioc->stripes[stripe_index].dev;
1023 		btrfs_put_bioc(bioc);
1024 	}
1025 
1026 skip:
1027 	for_each_set_bit(sector_nr, &extent_bitmap, stripe->nr_sectors) {
1028 		const u64 sector_logical = stripe->logical +
1029 					   ((u64)sector_nr << fs_info->sectorsize_bits);
1030 		const u64 sector_physical = physical +
1031 					   ((u64)sector_nr << fs_info->sectorsize_bits);
1032 		bool repaired = false;
1033 
1034 		if (scrub_bitmap_test_bit_is_metadata(stripe, sector_nr)) {
1035 			nr_meta_sectors++;
1036 		} else {
1037 			nr_data_sectors++;
1038 			if (!stripe->sectors[sector_nr].csum)
1039 				nr_nodatacsum_sectors++;
1040 		}
1041 
1042 		if (test_bit(sector_nr, &errors->init_error_bitmap) &&
1043 		    !test_bit(sector_nr, &error_bitmap)) {
1044 			nr_repaired_sectors++;
1045 			repaired = true;
1046 		}
1047 
1048 		/* Good sector from the beginning, nothing need to be done. */
1049 		if (!test_bit(sector_nr, &errors->init_error_bitmap))
1050 			continue;
1051 
1052 		/*
1053 		 * Report error for the corrupted sectors.  If repaired, just
1054 		 * output the message of repaired message.
1055 		 */
1056 		if (repaired) {
1057 			if (dev) {
1058 				btrfs_err_rl(fs_info,
1059 		"scrub: fixed up error at logical %llu on dev %s physical %llu",
1060 					    sector_logical, btrfs_dev_name(dev),
1061 					    sector_physical);
1062 			} else {
1063 				btrfs_err_rl(fs_info,
1064 			   "scrub: fixed up error at logical %llu on mirror %u",
1065 					    sector_logical, stripe->mirror_num);
1066 			}
1067 			continue;
1068 		}
1069 
1070 		/* The remaining are all for unrepaired. */
1071 		if (dev) {
1072 			btrfs_err_rl(fs_info,
1073 "scrub: unable to fixup (regular) error at logical %llu on dev %s physical %llu",
1074 					    sector_logical, btrfs_dev_name(dev),
1075 					    sector_physical);
1076 		} else {
1077 			btrfs_err_rl(fs_info,
1078 	  "scrub: unable to fixup (regular) error at logical %llu on mirror %u",
1079 					    sector_logical, stripe->mirror_num);
1080 		}
1081 
1082 		if (scrub_bitmap_test_bit_io_error(stripe, sector_nr))
1083 			if (__ratelimit(&rs) && dev)
1084 				scrub_print_common_warning("i/o error", dev, false,
1085 						     sector_logical, sector_physical);
1086 		if (scrub_bitmap_test_bit_csum_error(stripe, sector_nr))
1087 			if (__ratelimit(&rs) && dev)
1088 				scrub_print_common_warning("checksum error", dev, false,
1089 						     sector_logical, sector_physical);
1090 		if (scrub_bitmap_test_bit_meta_error(stripe, sector_nr))
1091 			if (__ratelimit(&rs) && dev)
1092 				scrub_print_common_warning("header error", dev, false,
1093 						     sector_logical, sector_physical);
1094 		if (scrub_bitmap_test_bit_meta_gen_error(stripe, sector_nr))
1095 			if (__ratelimit(&rs) && dev)
1096 				scrub_print_common_warning("generation error", dev, false,
1097 						     sector_logical, sector_physical);
1098 	}
1099 
1100 	/* Update the device stats. */
1101 	for (int i = 0; i < errors->nr_io_errors; i++)
1102 		btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_READ_ERRS);
1103 	for (int i = 0; i < errors->nr_csum_errors; i++)
1104 		btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
1105 	/* Generation mismatch error is based on each metadata, not each block. */
1106 	for (int i = 0; i < errors->nr_meta_gen_errors;
1107 	     i += (fs_info->nodesize >> fs_info->sectorsize_bits))
1108 		btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_GENERATION_ERRS);
1109 
1110 	spin_lock(&sctx->stat_lock);
1111 	sctx->stat.data_extents_scrubbed += stripe->nr_data_extents;
1112 	sctx->stat.tree_extents_scrubbed += stripe->nr_meta_extents;
1113 	sctx->stat.data_bytes_scrubbed += nr_data_sectors << fs_info->sectorsize_bits;
1114 	sctx->stat.tree_bytes_scrubbed += nr_meta_sectors << fs_info->sectorsize_bits;
1115 	sctx->stat.no_csum += nr_nodatacsum_sectors;
1116 	sctx->stat.read_errors += errors->nr_io_errors;
1117 	sctx->stat.csum_errors += errors->nr_csum_errors;
1118 	sctx->stat.verify_errors += errors->nr_meta_errors +
1119 				    errors->nr_meta_gen_errors;
1120 	sctx->stat.uncorrectable_errors +=
1121 		bitmap_weight(&error_bitmap, stripe->nr_sectors);
1122 	sctx->stat.corrected_errors += nr_repaired_sectors;
1123 	spin_unlock(&sctx->stat_lock);
1124 }
1125 
1126 static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *stripe,
1127 				unsigned long write_bitmap, bool dev_replace);
1128 
1129 /*
1130  * The main entrance for all read related scrub work, including:
1131  *
1132  * - Wait for the initial read to finish
1133  * - Verify and locate any bad sectors
1134  * - Go through the remaining mirrors and try to read as large blocksize as
1135  *   possible
1136  * - Go through all mirrors (including the failed mirror) sector-by-sector
1137  * - Submit writeback for repaired sectors
1138  *
1139  * Writeback for dev-replace does not happen here, it needs extra
1140  * synchronization for zoned devices.
1141  */
1142 static void scrub_stripe_read_repair_worker(struct work_struct *work)
1143 {
1144 	struct scrub_stripe *stripe = container_of(work, struct scrub_stripe, work);
1145 	struct scrub_ctx *sctx = stripe->sctx;
1146 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1147 	struct scrub_error_records errors = { 0 };
1148 	int num_copies = btrfs_num_copies(fs_info, stripe->bg->start,
1149 					  stripe->bg->length);
1150 	unsigned long repaired;
1151 	unsigned long error;
1152 	int mirror;
1153 	int i;
1154 
1155 	ASSERT(stripe->mirror_num >= 1, "stripe->mirror_num=%d", stripe->mirror_num);
1156 
1157 	wait_scrub_stripe_io(stripe);
1158 	scrub_verify_one_stripe(stripe, scrub_bitmap_read_has_extent(stripe));
1159 	/* Save the initial failed bitmap for later repair and report usage. */
1160 	errors.init_error_bitmap = scrub_bitmap_read_error(stripe);
1161 	errors.nr_io_errors = scrub_bitmap_weight_io_error(stripe);
1162 	errors.nr_csum_errors = scrub_bitmap_weight_csum_error(stripe);
1163 	errors.nr_meta_errors = scrub_bitmap_weight_meta_error(stripe);
1164 	errors.nr_meta_gen_errors = scrub_bitmap_weight_meta_gen_error(stripe);
1165 
1166 	if (bitmap_empty(&errors.init_error_bitmap, stripe->nr_sectors))
1167 		goto out;
1168 
1169 	/*
1170 	 * Try all remaining mirrors.
1171 	 *
1172 	 * Here we still try to read as large block as possible, as this is
1173 	 * faster and we have extra safety nets to rely on.
1174 	 */
1175 	for (mirror = calc_next_mirror(stripe->mirror_num, num_copies);
1176 	     mirror != stripe->mirror_num;
1177 	     mirror = calc_next_mirror(mirror, num_copies)) {
1178 		const unsigned long old_error_bitmap = scrub_bitmap_read_error(stripe);
1179 
1180 		scrub_stripe_submit_repair_read(stripe, mirror,
1181 						BTRFS_STRIPE_LEN, false);
1182 		wait_scrub_stripe_io(stripe);
1183 		scrub_verify_one_stripe(stripe, old_error_bitmap);
1184 		if (scrub_bitmap_empty_error(stripe))
1185 			goto out;
1186 	}
1187 
1188 	/*
1189 	 * Last safety net, try re-checking all mirrors, including the failed
1190 	 * one, sector-by-sector.
1191 	 *
1192 	 * As if one sector failed the drive's internal csum, the whole read
1193 	 * containing the offending sector would be marked as error.
1194 	 * Thus here we do sector-by-sector read.
1195 	 *
1196 	 * This can be slow, thus we only try it as the last resort.
1197 	 */
1198 
1199 	for (i = 0, mirror = stripe->mirror_num;
1200 	     i < num_copies;
1201 	     i++, mirror = calc_next_mirror(mirror, num_copies)) {
1202 		const unsigned long old_error_bitmap = scrub_bitmap_read_error(stripe);
1203 
1204 		scrub_stripe_submit_repair_read(stripe, mirror,
1205 						fs_info->sectorsize, true);
1206 		wait_scrub_stripe_io(stripe);
1207 		scrub_verify_one_stripe(stripe, old_error_bitmap);
1208 		if (scrub_bitmap_empty_error(stripe))
1209 			goto out;
1210 	}
1211 out:
1212 	error = scrub_bitmap_read_error(stripe);
1213 	/*
1214 	 * Submit the repaired sectors.  For zoned case, we cannot do repair
1215 	 * in-place, but queue the bg to be relocated.
1216 	 */
1217 	bitmap_andnot(&repaired, &errors.init_error_bitmap, &error,
1218 		      stripe->nr_sectors);
1219 	if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors)) {
1220 		if (btrfs_is_zoned(fs_info)) {
1221 			btrfs_repair_one_zone(fs_info, sctx->stripes[0].bg->start);
1222 		} else {
1223 			scrub_write_sectors(sctx, stripe, repaired, false);
1224 			wait_scrub_stripe_io(stripe);
1225 		}
1226 	}
1227 
1228 	scrub_stripe_report_errors(sctx, stripe, &errors);
1229 	set_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state);
1230 	wake_up(&stripe->repair_wait);
1231 }
1232 
1233 static void scrub_read_endio(struct btrfs_bio *bbio)
1234 {
1235 	struct scrub_stripe *stripe = bbio->private;
1236 
1237 	scrub_read_endio_common(bbio);
1238 
1239 	if (atomic_dec_and_test(&stripe->pending_io)) {
1240 		wake_up(&stripe->io_wait);
1241 		INIT_WORK(&stripe->work, scrub_stripe_read_repair_worker);
1242 		queue_work(stripe->bg->fs_info->scrub_workers, &stripe->work);
1243 	}
1244 }
1245 
1246 static void scrub_write_endio(struct btrfs_bio *bbio)
1247 {
1248 	struct scrub_stripe *stripe = bbio->private;
1249 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
1250 	unsigned int sector_nr = calc_sector_number(bbio);
1251 	const u32 bio_size = bio_get_size(&bbio->bio);
1252 
1253 	if (bbio->bio.bi_status) {
1254 		unsigned long flags;
1255 
1256 		spin_lock_irqsave(&stripe->write_error_lock, flags);
1257 		bitmap_set(&stripe->write_error_bitmap, sector_nr,
1258 			   bio_size >> fs_info->sectorsize_bits);
1259 		spin_unlock_irqrestore(&stripe->write_error_lock, flags);
1260 		for (int i = 0; i < (bio_size >> fs_info->sectorsize_bits); i++)
1261 			btrfs_dev_stat_inc_and_print(stripe->dev,
1262 						     BTRFS_DEV_STAT_WRITE_ERRS);
1263 	}
1264 	bio_put(&bbio->bio);
1265 
1266 	if (atomic_dec_and_test(&stripe->pending_io))
1267 		wake_up(&stripe->io_wait);
1268 }
1269 
1270 static void scrub_submit_write_bio(struct scrub_ctx *sctx,
1271 				   struct scrub_stripe *stripe,
1272 				   struct btrfs_bio *bbio, bool dev_replace)
1273 {
1274 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1275 	u32 bio_len = bbio->bio.bi_iter.bi_size;
1276 	u32 bio_off = (bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT) -
1277 		      stripe->logical;
1278 
1279 	fill_writer_pointer_gap(sctx, stripe->physical + bio_off);
1280 	atomic_inc(&stripe->pending_io);
1281 	btrfs_submit_repair_write(bbio, stripe->mirror_num, dev_replace);
1282 	if (!btrfs_is_zoned(fs_info))
1283 		return;
1284 	/*
1285 	 * For zoned writeback, queue depth must be 1, thus we must wait for
1286 	 * the write to finish before the next write.
1287 	 */
1288 	wait_scrub_stripe_io(stripe);
1289 
1290 	/*
1291 	 * And also need to update the write pointer if write finished
1292 	 * successfully.
1293 	 */
1294 	if (!test_bit(bio_off >> fs_info->sectorsize_bits,
1295 		      &stripe->write_error_bitmap))
1296 		sctx->write_pointer += bio_len;
1297 }
1298 
1299 /*
1300  * Submit the write bio(s) for the sectors specified by @write_bitmap.
1301  *
1302  * Here we utilize btrfs_submit_repair_write(), which has some extra benefits:
1303  *
1304  * - Only needs logical bytenr and mirror_num
1305  *   Just like the scrub read path
1306  *
1307  * - Would only result in writes to the specified mirror
1308  *   Unlike the regular writeback path, which would write back to all stripes
1309  *
1310  * - Handle dev-replace and read-repair writeback differently
1311  */
1312 static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *stripe,
1313 				unsigned long write_bitmap, bool dev_replace)
1314 {
1315 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
1316 	struct btrfs_bio *bbio = NULL;
1317 	int sector_nr;
1318 
1319 	for_each_set_bit(sector_nr, &write_bitmap, stripe->nr_sectors) {
1320 		/* We should only writeback sectors covered by an extent. */
1321 		ASSERT(scrub_bitmap_test_bit_has_extent(stripe, sector_nr));
1322 
1323 		/* Cannot merge with previous sector, submit the current one. */
1324 		if (bbio && sector_nr && !test_bit(sector_nr - 1, &write_bitmap)) {
1325 			scrub_submit_write_bio(sctx, stripe, bbio, dev_replace);
1326 			bbio = NULL;
1327 		}
1328 		if (!bbio)
1329 			bbio = alloc_scrub_bbio(fs_info, REQ_OP_WRITE,
1330 					stripe->logical + (sector_nr << fs_info->sectorsize_bits),
1331 					scrub_write_endio, stripe);
1332 		scrub_bio_add_sector(bbio, stripe, sector_nr);
1333 	}
1334 	if (bbio)
1335 		scrub_submit_write_bio(sctx, stripe, bbio, dev_replace);
1336 }
1337 
1338 /*
1339  * Throttling of IO submission, bandwidth-limit based, the timeslice is 1
1340  * second.  Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max.
1341  */
1342 static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *device,
1343 				  unsigned int bio_size)
1344 {
1345 	const int time_slice = 1000;
1346 	s64 delta;
1347 	ktime_t now;
1348 	u32 div;
1349 	u64 bwlimit;
1350 
1351 	bwlimit = READ_ONCE(device->scrub_speed_max);
1352 	if (bwlimit == 0)
1353 		return;
1354 
1355 	/*
1356 	 * Slice is divided into intervals when the IO is submitted, adjust by
1357 	 * bwlimit and maximum of 64 intervals.
1358 	 */
1359 	div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
1360 
1361 	/* Start new epoch, set deadline */
1362 	now = ktime_get();
1363 	if (sctx->throttle_deadline == 0) {
1364 		sctx->throttle_deadline = ktime_add_ms(now, time_slice / div);
1365 		sctx->throttle_sent = 0;
1366 	}
1367 
1368 	/* Still in the time to send? */
1369 	if (ktime_before(now, sctx->throttle_deadline)) {
1370 		/* If current bio is within the limit, send it */
1371 		sctx->throttle_sent += bio_size;
1372 		if (sctx->throttle_sent <= div_u64(bwlimit, div))
1373 			return;
1374 
1375 		/* We're over the limit, sleep until the rest of the slice */
1376 		delta = ktime_ms_delta(sctx->throttle_deadline, now);
1377 	} else {
1378 		/* New request after deadline, start new epoch */
1379 		delta = 0;
1380 	}
1381 
1382 	if (delta) {
1383 		long timeout;
1384 
1385 		timeout = div_u64(delta * HZ, 1000);
1386 		schedule_timeout_interruptible(timeout);
1387 	}
1388 
1389 	/* Next call will start the deadline period */
1390 	sctx->throttle_deadline = 0;
1391 }
1392 
1393 /*
1394  * Given a physical address, this will calculate it's
1395  * logical offset. if this is a parity stripe, it will return
1396  * the most left data stripe's logical offset.
1397  *
1398  * return 0 if it is a data stripe, 1 means parity stripe.
1399  */
1400 static int get_raid56_logic_offset(u64 physical, int num,
1401 				   struct btrfs_chunk_map *map, u64 *offset,
1402 				   u64 *stripe_start)
1403 {
1404 	int i;
1405 	int j = 0;
1406 	u64 last_offset;
1407 	const int data_stripes = nr_data_stripes(map);
1408 
1409 	last_offset = (physical - map->stripes[num].physical) * data_stripes;
1410 	if (stripe_start)
1411 		*stripe_start = last_offset;
1412 
1413 	*offset = last_offset;
1414 	for (i = 0; i < data_stripes; i++) {
1415 		u32 stripe_nr;
1416 		u32 stripe_index;
1417 		u32 rot;
1418 
1419 		*offset = last_offset + btrfs_stripe_nr_to_offset(i);
1420 
1421 		stripe_nr = (u32)(*offset >> BTRFS_STRIPE_LEN_SHIFT) / data_stripes;
1422 
1423 		/* Work out the disk rotation on this stripe-set */
1424 		rot = stripe_nr % map->num_stripes;
1425 		/* calculate which stripe this data locates */
1426 		rot += i;
1427 		stripe_index = rot % map->num_stripes;
1428 		if (stripe_index == num)
1429 			return 0;
1430 		if (stripe_index < num)
1431 			j++;
1432 	}
1433 	*offset = last_offset + btrfs_stripe_nr_to_offset(j);
1434 	return 1;
1435 }
1436 
1437 /*
1438  * Return 0 if the extent item range covers any byte of the range.
1439  * Return <0 if the extent item is before @search_start.
1440  * Return >0 if the extent item is after @start_start + @search_len.
1441  */
1442 static int compare_extent_item_range(struct btrfs_path *path,
1443 				     u64 search_start, u64 search_len)
1444 {
1445 	struct btrfs_fs_info *fs_info = path->nodes[0]->fs_info;
1446 	u64 len;
1447 	struct btrfs_key key;
1448 
1449 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1450 	ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY ||
1451 	       key.type == BTRFS_METADATA_ITEM_KEY, "key.type=%u", key.type);
1452 	if (key.type == BTRFS_METADATA_ITEM_KEY)
1453 		len = fs_info->nodesize;
1454 	else
1455 		len = key.offset;
1456 
1457 	if (key.objectid + len <= search_start)
1458 		return -1;
1459 	if (key.objectid >= search_start + search_len)
1460 		return 1;
1461 	return 0;
1462 }
1463 
1464 /*
1465  * Locate one extent item which covers any byte in range
1466  * [@search_start, @search_start + @search_length)
1467  *
1468  * If the path is not initialized, we will initialize the search by doing
1469  * a btrfs_search_slot().
1470  * If the path is already initialized, we will use the path as the initial
1471  * slot, to avoid duplicated btrfs_search_slot() calls.
1472  *
1473  * NOTE: If an extent item starts before @search_start, we will still
1474  * return the extent item. This is for data extent crossing stripe boundary.
1475  *
1476  * Return 0 if we found such extent item, and @path will point to the extent item.
1477  * Return >0 if no such extent item can be found, and @path will be released.
1478  * Return <0 if hit fatal error, and @path will be released.
1479  */
1480 static int find_first_extent_item(struct btrfs_root *extent_root,
1481 				  struct btrfs_path *path,
1482 				  u64 search_start, u64 search_len)
1483 {
1484 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
1485 	struct btrfs_key key;
1486 	int ret;
1487 
1488 	/* Continue using the existing path */
1489 	if (path->nodes[0])
1490 		goto search_forward;
1491 
1492 	key.objectid = search_start;
1493 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1494 		key.type = BTRFS_METADATA_ITEM_KEY;
1495 	else
1496 		key.type = BTRFS_EXTENT_ITEM_KEY;
1497 	key.offset = (u64)-1;
1498 
1499 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1500 	if (ret < 0)
1501 		return ret;
1502 	if (unlikely(ret == 0)) {
1503 		/*
1504 		 * Key with offset -1 found, there would have to exist an extent
1505 		 * item with such offset, but this is out of the valid range.
1506 		 */
1507 		btrfs_release_path(path);
1508 		return -EUCLEAN;
1509 	}
1510 
1511 	/*
1512 	 * Here we intentionally pass 0 as @min_objectid, as there could be
1513 	 * an extent item starting before @search_start.
1514 	 */
1515 	ret = btrfs_previous_extent_item(extent_root, path, 0);
1516 	if (ret < 0)
1517 		return ret;
1518 	/*
1519 	 * No matter whether we have found an extent item, the next loop will
1520 	 * properly do every check on the key.
1521 	 */
1522 search_forward:
1523 	while (true) {
1524 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1525 		if (key.objectid >= search_start + search_len)
1526 			break;
1527 		if (key.type != BTRFS_METADATA_ITEM_KEY &&
1528 		    key.type != BTRFS_EXTENT_ITEM_KEY)
1529 			goto next;
1530 
1531 		ret = compare_extent_item_range(path, search_start, search_len);
1532 		if (ret == 0)
1533 			return ret;
1534 		if (ret > 0)
1535 			break;
1536 next:
1537 		ret = btrfs_next_item(extent_root, path);
1538 		if (ret) {
1539 			/* Either no more items or a fatal error. */
1540 			btrfs_release_path(path);
1541 			return ret;
1542 		}
1543 	}
1544 	btrfs_release_path(path);
1545 	return 1;
1546 }
1547 
1548 static void get_extent_info(struct btrfs_path *path, u64 *extent_start_ret,
1549 			    u64 *size_ret, u64 *flags_ret, u64 *generation_ret)
1550 {
1551 	struct btrfs_key key;
1552 	struct btrfs_extent_item *ei;
1553 
1554 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1555 	ASSERT(key.type == BTRFS_METADATA_ITEM_KEY ||
1556 	       key.type == BTRFS_EXTENT_ITEM_KEY, "key.type=%u", key.type);
1557 	*extent_start_ret = key.objectid;
1558 	if (key.type == BTRFS_METADATA_ITEM_KEY)
1559 		*size_ret = path->nodes[0]->fs_info->nodesize;
1560 	else
1561 		*size_ret = key.offset;
1562 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_extent_item);
1563 	*flags_ret = btrfs_extent_flags(path->nodes[0], ei);
1564 	*generation_ret = btrfs_extent_generation(path->nodes[0], ei);
1565 }
1566 
1567 static int sync_write_pointer_for_zoned(struct scrub_ctx *sctx, u64 logical,
1568 					u64 physical, u64 physical_end)
1569 {
1570 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1571 	int ret = 0;
1572 
1573 	if (!btrfs_is_zoned(fs_info))
1574 		return 0;
1575 
1576 	mutex_lock(&sctx->wr_lock);
1577 	if (sctx->write_pointer < physical_end) {
1578 		ret = btrfs_sync_zone_write_pointer(sctx->wr_tgtdev, logical,
1579 						    physical,
1580 						    sctx->write_pointer);
1581 		if (ret)
1582 			btrfs_err(fs_info, "scrub: zoned: failed to recover write pointer");
1583 	}
1584 	mutex_unlock(&sctx->wr_lock);
1585 	btrfs_dev_clear_zone_empty(sctx->wr_tgtdev, physical);
1586 
1587 	return ret;
1588 }
1589 
1590 static void fill_one_extent_info(struct btrfs_fs_info *fs_info,
1591 				 struct scrub_stripe *stripe,
1592 				 u64 extent_start, u64 extent_len,
1593 				 u64 extent_flags, u64 extent_gen)
1594 {
1595 	for (u64 cur_logical = max(stripe->logical, extent_start);
1596 	     cur_logical < min(stripe->logical + BTRFS_STRIPE_LEN,
1597 			       extent_start + extent_len);
1598 	     cur_logical += fs_info->sectorsize) {
1599 		const int nr_sector = (cur_logical - stripe->logical) >>
1600 				      fs_info->sectorsize_bits;
1601 		struct scrub_sector_verification *sector =
1602 						&stripe->sectors[nr_sector];
1603 
1604 		scrub_bitmap_set_bit_has_extent(stripe, nr_sector);
1605 		if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1606 			scrub_bitmap_set_bit_is_metadata(stripe, nr_sector);
1607 			sector->generation = extent_gen;
1608 		}
1609 	}
1610 }
1611 
1612 static void scrub_stripe_reset_bitmaps(struct scrub_stripe *stripe)
1613 {
1614 	ASSERT(stripe->nr_sectors);
1615 	bitmap_zero(stripe->bitmaps, scrub_bitmap_nr_last * stripe->nr_sectors);
1616 }
1617 
1618 /*
1619  * Locate one stripe which has at least one extent in its range.
1620  *
1621  * Return 0 if found such stripe, and store its info into @stripe.
1622  * Return >0 if there is no such stripe in the specified range.
1623  * Return <0 for error.
1624  */
1625 static int scrub_find_fill_first_stripe(struct btrfs_block_group *bg,
1626 					struct btrfs_path *extent_path,
1627 					struct btrfs_path *csum_path,
1628 					struct btrfs_device *dev, u64 physical,
1629 					int mirror_num, u64 logical_start,
1630 					u32 logical_len,
1631 					struct scrub_stripe *stripe)
1632 {
1633 	struct btrfs_fs_info *fs_info = bg->fs_info;
1634 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bg->start);
1635 	struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bg->start);
1636 	const u64 logical_end = logical_start + logical_len;
1637 	u64 cur_logical = logical_start;
1638 	u64 stripe_end;
1639 	u64 extent_start;
1640 	u64 extent_len;
1641 	u64 extent_flags;
1642 	u64 extent_gen;
1643 	int ret;
1644 
1645 	if (unlikely(!extent_root || !csum_root)) {
1646 		btrfs_err(fs_info, "scrub: no valid extent or csum root found");
1647 		return -EUCLEAN;
1648 	}
1649 	memset(stripe->sectors, 0, sizeof(struct scrub_sector_verification) *
1650 				   stripe->nr_sectors);
1651 	scrub_stripe_reset_bitmaps(stripe);
1652 
1653 	/* The range must be inside the bg. */
1654 	ASSERT(logical_start >= bg->start && logical_end <= btrfs_block_group_end(bg),
1655 	       "bg->start=%llu logical_start=%llu logical_end=%llu end=%llu",
1656 	       bg->start, logical_start, logical_end, btrfs_block_group_end(bg));
1657 
1658 	ret = find_first_extent_item(extent_root, extent_path, logical_start,
1659 				     logical_len);
1660 	/* Either error or not found. */
1661 	if (ret)
1662 		return ret;
1663 	get_extent_info(extent_path, &extent_start, &extent_len, &extent_flags,
1664 			&extent_gen);
1665 	if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1666 		stripe->nr_meta_extents++;
1667 	if (extent_flags & BTRFS_EXTENT_FLAG_DATA)
1668 		stripe->nr_data_extents++;
1669 	cur_logical = max(extent_start, cur_logical);
1670 
1671 	/*
1672 	 * Round down to stripe boundary.
1673 	 *
1674 	 * The extra calculation against bg->start is to handle block groups
1675 	 * whose logical bytenr is not BTRFS_STRIPE_LEN aligned.
1676 	 */
1677 	stripe->logical = round_down(cur_logical - bg->start, BTRFS_STRIPE_LEN) +
1678 			  bg->start;
1679 	stripe->physical = physical + stripe->logical - logical_start;
1680 	stripe->dev = dev;
1681 	stripe->bg = bg;
1682 	stripe->mirror_num = mirror_num;
1683 	stripe_end = stripe->logical + BTRFS_STRIPE_LEN - 1;
1684 
1685 	/* Fill the first extent info into stripe->sectors[] array. */
1686 	fill_one_extent_info(fs_info, stripe, extent_start, extent_len,
1687 			     extent_flags, extent_gen);
1688 	cur_logical = extent_start + extent_len;
1689 
1690 	/* Fill the extent info for the remaining sectors. */
1691 	while (cur_logical <= stripe_end) {
1692 		ret = find_first_extent_item(extent_root, extent_path, cur_logical,
1693 					     stripe_end - cur_logical + 1);
1694 		if (ret < 0)
1695 			return ret;
1696 		if (ret > 0) {
1697 			ret = 0;
1698 			break;
1699 		}
1700 		get_extent_info(extent_path, &extent_start, &extent_len,
1701 				&extent_flags, &extent_gen);
1702 		if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1703 			stripe->nr_meta_extents++;
1704 		if (extent_flags & BTRFS_EXTENT_FLAG_DATA)
1705 			stripe->nr_data_extents++;
1706 		fill_one_extent_info(fs_info, stripe, extent_start, extent_len,
1707 				     extent_flags, extent_gen);
1708 		cur_logical = extent_start + extent_len;
1709 	}
1710 
1711 	/* Now fill the data csum. */
1712 	if (bg->flags & BTRFS_BLOCK_GROUP_DATA) {
1713 		int sector_nr;
1714 		unsigned long csum_bitmap = 0;
1715 
1716 		/* Csum space should have already been allocated. */
1717 		ASSERT(stripe->csums);
1718 
1719 		/*
1720 		 * Our csum bitmap should be large enough, as BTRFS_STRIPE_LEN
1721 		 * should contain at most 16 sectors.
1722 		 */
1723 		ASSERT(BITS_PER_LONG >= BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits);
1724 
1725 		ret = btrfs_lookup_csums_bitmap(csum_root, csum_path,
1726 						stripe->logical, stripe_end,
1727 						stripe->csums, &csum_bitmap);
1728 		if (ret < 0)
1729 			return ret;
1730 		if (ret > 0)
1731 			ret = 0;
1732 
1733 		for_each_set_bit(sector_nr, &csum_bitmap, stripe->nr_sectors) {
1734 			stripe->sectors[sector_nr].csum = stripe->csums +
1735 				sector_nr * fs_info->csum_size;
1736 		}
1737 	}
1738 	set_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state);
1739 
1740 	return ret;
1741 }
1742 
1743 static void scrub_reset_stripe(struct scrub_stripe *stripe)
1744 {
1745 	scrub_stripe_reset_bitmaps(stripe);
1746 
1747 	stripe->nr_meta_extents = 0;
1748 	stripe->nr_data_extents = 0;
1749 	stripe->state = 0;
1750 
1751 	for (int i = 0; i < stripe->nr_sectors; i++) {
1752 		stripe->sectors[i].csum = NULL;
1753 		stripe->sectors[i].generation = 0;
1754 	}
1755 }
1756 
1757 static u32 stripe_length(const struct scrub_stripe *stripe)
1758 {
1759 	ASSERT(stripe->bg);
1760 
1761 	return min(BTRFS_STRIPE_LEN,
1762 		   stripe->bg->start + stripe->bg->length - stripe->logical);
1763 }
1764 
1765 static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe)
1766 {
1767 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
1768 	struct btrfs_bio *bbio = NULL;
1769 	unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits;
1770 	const unsigned long has_extent = scrub_bitmap_read_has_extent(stripe);
1771 	u64 stripe_len = BTRFS_STRIPE_LEN;
1772 	int mirror = stripe->mirror_num;
1773 	int i;
1774 
1775 	atomic_inc(&stripe->pending_io);
1776 
1777 	for_each_set_bit(i, &has_extent, stripe->nr_sectors) {
1778 		/* We're beyond the chunk boundary, no need to read anymore. */
1779 		if (i >= nr_sectors)
1780 			break;
1781 
1782 		/* The current sector cannot be merged, submit the bio. */
1783 		if (bbio &&
1784 		    ((i > 0 && !test_bit(i - 1, &has_extent)) ||
1785 		     bbio->bio.bi_iter.bi_size >= stripe_len)) {
1786 			ASSERT(bbio->bio.bi_iter.bi_size);
1787 			atomic_inc(&stripe->pending_io);
1788 			btrfs_submit_bbio(bbio, mirror);
1789 			bbio = NULL;
1790 		}
1791 
1792 		if (!bbio) {
1793 			struct btrfs_io_stripe io_stripe = {};
1794 			struct btrfs_io_context *bioc = NULL;
1795 			const u64 logical = stripe->logical +
1796 					    (i << fs_info->sectorsize_bits);
1797 			int ret;
1798 
1799 			io_stripe.rst_search_commit_root = true;
1800 			stripe_len = (nr_sectors - i) << fs_info->sectorsize_bits;
1801 			/*
1802 			 * For RST cases, we need to manually split the bbio to
1803 			 * follow the RST boundary.
1804 			 */
1805 			ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
1806 					      &stripe_len, &bioc, &io_stripe, &mirror);
1807 			btrfs_put_bioc(bioc);
1808 			if (ret < 0) {
1809 				if (ret != -ENODATA) {
1810 					/*
1811 					 * Earlier btrfs_get_raid_extent_offset()
1812 					 * returned -ENODATA, which means there's
1813 					 * no entry for the corresponding range
1814 					 * in the stripe tree.  But if it's in
1815 					 * the extent tree, then it's a preallocated
1816 					 * extent and not an error.
1817 					 */
1818 					scrub_bitmap_set_bit_io_error(stripe, i);
1819 					scrub_bitmap_set_bit_error(stripe, i);
1820 				}
1821 				continue;
1822 			}
1823 
1824 			bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ,
1825 						logical, scrub_read_endio, stripe);
1826 		}
1827 
1828 		scrub_bio_add_sector(bbio, stripe, i);
1829 	}
1830 
1831 	if (bbio) {
1832 		ASSERT(bbio->bio.bi_iter.bi_size);
1833 		atomic_inc(&stripe->pending_io);
1834 		btrfs_submit_bbio(bbio, mirror);
1835 	}
1836 
1837 	if (atomic_dec_and_test(&stripe->pending_io)) {
1838 		wake_up(&stripe->io_wait);
1839 		INIT_WORK(&stripe->work, scrub_stripe_read_repair_worker);
1840 		queue_work(stripe->bg->fs_info->scrub_workers, &stripe->work);
1841 	}
1842 }
1843 
1844 static void scrub_submit_initial_read(struct scrub_ctx *sctx,
1845 				      struct scrub_stripe *stripe)
1846 {
1847 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1848 	struct btrfs_bio *bbio;
1849 	unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits;
1850 	int mirror = stripe->mirror_num;
1851 
1852 	ASSERT(stripe->bg);
1853 	ASSERT(stripe->mirror_num > 0);
1854 	ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state));
1855 
1856 	if (btrfs_need_stripe_tree_update(fs_info, stripe->bg->flags)) {
1857 		scrub_submit_extent_sector_read(stripe);
1858 		return;
1859 	}
1860 
1861 	bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ,
1862 				stripe->logical, scrub_read_endio, stripe);
1863 	/* Read the whole range inside the chunk boundary. */
1864 	for (unsigned int cur = 0; cur < nr_sectors; cur++)
1865 		scrub_bio_add_sector(bbio, stripe, cur);
1866 	atomic_inc(&stripe->pending_io);
1867 
1868 	/*
1869 	 * For dev-replace, either user asks to avoid the source dev, or
1870 	 * the device is missing, we try the next mirror instead.
1871 	 */
1872 	if (sctx->is_dev_replace &&
1873 	    (fs_info->dev_replace.cont_reading_from_srcdev_mode ==
1874 	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID ||
1875 	     !stripe->dev->bdev)) {
1876 		int num_copies = btrfs_num_copies(fs_info, stripe->bg->start,
1877 						  stripe->bg->length);
1878 
1879 		mirror = calc_next_mirror(mirror, num_copies);
1880 	}
1881 	btrfs_submit_bbio(bbio, mirror);
1882 }
1883 
1884 static bool stripe_has_metadata_error(struct scrub_stripe *stripe)
1885 {
1886 	const unsigned long error = scrub_bitmap_read_error(stripe);
1887 	int i;
1888 
1889 	for_each_set_bit(i, &error, stripe->nr_sectors) {
1890 		if (scrub_bitmap_test_bit_is_metadata(stripe, i)) {
1891 			struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
1892 
1893 			btrfs_err(fs_info,
1894 		    "scrub: stripe %llu has unrepaired metadata sector at logical %llu",
1895 				  stripe->logical,
1896 				  stripe->logical + (i << fs_info->sectorsize_bits));
1897 			return true;
1898 		}
1899 	}
1900 	return false;
1901 }
1902 
1903 static void submit_initial_group_read(struct scrub_ctx *sctx,
1904 				      unsigned int first_slot,
1905 				      unsigned int nr_stripes)
1906 {
1907 	struct blk_plug plug;
1908 
1909 	ASSERT(first_slot < SCRUB_TOTAL_STRIPES);
1910 	ASSERT(first_slot + nr_stripes <= SCRUB_TOTAL_STRIPES);
1911 
1912 	scrub_throttle_dev_io(sctx, sctx->stripes[0].dev,
1913 			      btrfs_stripe_nr_to_offset(nr_stripes));
1914 	blk_start_plug(&plug);
1915 	for (int i = 0; i < nr_stripes; i++) {
1916 		struct scrub_stripe *stripe = &sctx->stripes[first_slot + i];
1917 
1918 		/* Those stripes should be initialized. */
1919 		ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state));
1920 		scrub_submit_initial_read(sctx, stripe);
1921 	}
1922 	blk_finish_plug(&plug);
1923 }
1924 
1925 static int flush_scrub_stripes(struct scrub_ctx *sctx)
1926 {
1927 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1928 	struct scrub_stripe *stripe;
1929 	const int nr_stripes = sctx->cur_stripe;
1930 	int ret = 0;
1931 
1932 	if (!nr_stripes)
1933 		return 0;
1934 
1935 	ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &sctx->stripes[0].state));
1936 
1937 	/* Submit the stripes which are populated but not submitted. */
1938 	if (nr_stripes % SCRUB_STRIPES_PER_GROUP) {
1939 		const int first_slot = round_down(nr_stripes, SCRUB_STRIPES_PER_GROUP);
1940 
1941 		submit_initial_group_read(sctx, first_slot, nr_stripes - first_slot);
1942 	}
1943 
1944 	for (int i = 0; i < nr_stripes; i++) {
1945 		stripe = &sctx->stripes[i];
1946 
1947 		wait_event(stripe->repair_wait,
1948 			   test_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state));
1949 	}
1950 
1951 	/* Submit for dev-replace. */
1952 	if (sctx->is_dev_replace) {
1953 		/*
1954 		 * For dev-replace, if we know there is something wrong with
1955 		 * metadata, we should immediately abort.
1956 		 */
1957 		for (int i = 0; i < nr_stripes; i++) {
1958 			if (unlikely(stripe_has_metadata_error(&sctx->stripes[i]))) {
1959 				ret = -EIO;
1960 				goto out;
1961 			}
1962 		}
1963 		for (int i = 0; i < nr_stripes; i++) {
1964 			unsigned long good;
1965 			unsigned long has_extent;
1966 			unsigned long error;
1967 
1968 			stripe = &sctx->stripes[i];
1969 
1970 			ASSERT(stripe->dev == fs_info->dev_replace.srcdev);
1971 
1972 			has_extent = scrub_bitmap_read_has_extent(stripe);
1973 			error = scrub_bitmap_read_error(stripe);
1974 			bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors);
1975 			scrub_write_sectors(sctx, stripe, good, true);
1976 		}
1977 	}
1978 
1979 	/* Wait for the above writebacks to finish. */
1980 	for (int i = 0; i < nr_stripes; i++) {
1981 		stripe = &sctx->stripes[i];
1982 
1983 		wait_scrub_stripe_io(stripe);
1984 		spin_lock(&sctx->stat_lock);
1985 		sctx->stat.last_physical = stripe->physical + stripe_length(stripe);
1986 		spin_unlock(&sctx->stat_lock);
1987 		scrub_reset_stripe(stripe);
1988 	}
1989 out:
1990 	sctx->cur_stripe = 0;
1991 	return ret;
1992 }
1993 
1994 static void raid56_scrub_wait_endio(struct bio *bio)
1995 {
1996 	complete(bio->bi_private);
1997 }
1998 
1999 static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *bg,
2000 			      struct btrfs_device *dev, int mirror_num,
2001 			      u64 logical, u32 length, u64 physical,
2002 			      u64 *found_logical_ret)
2003 {
2004 	struct scrub_stripe *stripe;
2005 	int ret;
2006 
2007 	/*
2008 	 * There should always be one slot left, as caller filling the last
2009 	 * slot should flush them all.
2010 	 */
2011 	ASSERT(sctx->cur_stripe < SCRUB_TOTAL_STRIPES);
2012 
2013 	/* @found_logical_ret must be specified. */
2014 	ASSERT(found_logical_ret);
2015 
2016 	stripe = &sctx->stripes[sctx->cur_stripe];
2017 	scrub_reset_stripe(stripe);
2018 	ret = scrub_find_fill_first_stripe(bg, &sctx->extent_path,
2019 					   &sctx->csum_path, dev, physical,
2020 					   mirror_num, logical, length, stripe);
2021 	/* Either >0 as no more extents or <0 for error. */
2022 	if (ret)
2023 		return ret;
2024 	*found_logical_ret = stripe->logical;
2025 	sctx->cur_stripe++;
2026 
2027 	/* We filled one group, submit it. */
2028 	if (sctx->cur_stripe % SCRUB_STRIPES_PER_GROUP == 0) {
2029 		const int first_slot = sctx->cur_stripe - SCRUB_STRIPES_PER_GROUP;
2030 
2031 		submit_initial_group_read(sctx, first_slot, SCRUB_STRIPES_PER_GROUP);
2032 	}
2033 
2034 	/* Last slot used, flush them all. */
2035 	if (sctx->cur_stripe == SCRUB_TOTAL_STRIPES)
2036 		return flush_scrub_stripes(sctx);
2037 	return 0;
2038 }
2039 
2040 /*
2041  * Return 0 if we should not cancel the scrub.
2042  * Return <0 if we need to cancel the scrub, returned value will
2043  * indicate the reason:
2044  * - -ECANCELED - Being explicitly canceled through ioctl.
2045  * - -EINTR     - Being interrupted by signal or fs/process freezing.
2046  */
2047 static int should_cancel_scrub(const struct scrub_ctx *sctx)
2048 {
2049 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2050 
2051 	if (atomic_read(&fs_info->scrub_cancel_req) ||
2052 	    atomic_read(&sctx->cancel_req))
2053 		return -ECANCELED;
2054 
2055 	/*
2056 	 * The user (e.g. fsfreeze command) or power management (PM)
2057 	 * suspend/hibernate can freeze the fs.  And PM suspend/hibernate will
2058 	 * also freeze all user processes.
2059 	 *
2060 	 * A user process can only be frozen when it is in user space, thus we
2061 	 * have to cancel the run so that the process can return to the user
2062 	 * space.
2063 	 *
2064 	 * Furthermore we have to check both filesystem and process freezing,
2065 	 * as PM can be configured to freeze the filesystems before processes.
2066 	 *
2067 	 * If we only check fs freezing, then suspend without fs freezing
2068 	 * will timeout, as the process is still in kernel space.
2069 	 *
2070 	 * If we only check process freezing, then suspend with fs freezing
2071 	 * will timeout, as the running scrub will prevent the fs from being frozen.
2072 	 */
2073 	if (fs_info->sb->s_writers.frozen > SB_UNFROZEN ||
2074 	    freezing(current) || signal_pending(current))
2075 		return -EINTR;
2076 	return 0;
2077 }
2078 
2079 static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
2080 				      struct btrfs_device *scrub_dev,
2081 				      struct btrfs_chunk_map *map,
2082 				      u64 full_stripe_start,
2083 				      unsigned long *extent_bitmap)
2084 {
2085 	DECLARE_COMPLETION_ONSTACK(io_done);
2086 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2087 	struct btrfs_io_context *bioc = NULL;
2088 	struct btrfs_raid_bio *rbio;
2089 	struct bio bio;
2090 	const int data_stripes = nr_data_stripes(map);
2091 	u64 length = btrfs_stripe_nr_to_offset(data_stripes);
2092 	int ret;
2093 
2094 	bio_init(&bio, NULL, NULL, 0, REQ_OP_READ);
2095 	bio.bi_iter.bi_sector = full_stripe_start >> SECTOR_SHIFT;
2096 	bio.bi_private = &io_done;
2097 	bio.bi_end_io = raid56_scrub_wait_endio;
2098 
2099 	btrfs_bio_counter_inc_blocked(fs_info);
2100 	ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, full_stripe_start,
2101 			      &length, &bioc, NULL, NULL);
2102 	if (ret < 0)
2103 		goto out;
2104 	/* For RAID56 write there must be an @bioc allocated. */
2105 	ASSERT(bioc);
2106 	rbio = raid56_parity_alloc_scrub_rbio(&bio, bioc, scrub_dev, extent_bitmap,
2107 				BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits);
2108 	btrfs_put_bioc(bioc);
2109 	if (!rbio) {
2110 		ret = -ENOMEM;
2111 		goto out;
2112 	}
2113 	/* Use the recovered stripes as cache to avoid read them from disk again. */
2114 	for (int i = 0; i < data_stripes; i++) {
2115 		struct scrub_stripe *stripe = &sctx->raid56_data_stripes[i];
2116 
2117 		raid56_parity_cache_data_folios(rbio, stripe->buffer,
2118 				full_stripe_start + (i << BTRFS_STRIPE_LEN_SHIFT));
2119 	}
2120 	raid56_parity_submit_scrub_rbio(rbio);
2121 	wait_for_completion_io(&io_done);
2122 	ret = blk_status_to_errno(bio.bi_status);
2123 out:
2124 	btrfs_bio_counter_dec(fs_info);
2125 	bio_uninit(&bio);
2126 	return ret;
2127 }
2128 
2129 static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
2130 				      struct btrfs_device *scrub_dev,
2131 				      struct btrfs_block_group *bg,
2132 				      struct btrfs_chunk_map *map,
2133 				      u64 full_stripe_start)
2134 {
2135 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2136 	BTRFS_PATH_AUTO_RELEASE(extent_path);
2137 	BTRFS_PATH_AUTO_RELEASE(csum_path);
2138 	struct scrub_stripe *stripe;
2139 	bool all_empty = true;
2140 	const int data_stripes = nr_data_stripes(map);
2141 	unsigned long extent_bitmap = 0;
2142 	int ret;
2143 
2144 	ASSERT(sctx->raid56_data_stripes);
2145 
2146 	ret = should_cancel_scrub(sctx);
2147 	if (ret < 0)
2148 		return ret;
2149 
2150 	if (atomic_read(&fs_info->scrub_pause_req))
2151 		scrub_blocked_if_needed(fs_info);
2152 
2153 	spin_lock(&bg->lock);
2154 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
2155 		spin_unlock(&bg->lock);
2156 		return 0;
2157 	}
2158 	spin_unlock(&bg->lock);
2159 
2160 	/*
2161 	 * For data stripe search, we cannot reuse the same extent/csum paths,
2162 	 * as the data stripe bytenr may be smaller than previous extent.  Thus
2163 	 * we have to use our own extent/csum paths.
2164 	 */
2165 	extent_path.search_commit_root = true;
2166 	extent_path.skip_locking = true;
2167 	csum_path.search_commit_root = true;
2168 	csum_path.skip_locking = true;
2169 
2170 	for (int i = 0; i < data_stripes; i++) {
2171 		int stripe_index;
2172 		int rot;
2173 		u64 physical;
2174 
2175 		stripe = &sctx->raid56_data_stripes[i];
2176 		rot = div_u64(full_stripe_start - bg->start,
2177 			      data_stripes) >> BTRFS_STRIPE_LEN_SHIFT;
2178 		stripe_index = (i + rot) % map->num_stripes;
2179 		physical = map->stripes[stripe_index].physical +
2180 			   btrfs_stripe_nr_to_offset(rot);
2181 
2182 		scrub_reset_stripe(stripe);
2183 		set_bit(SCRUB_STRIPE_FLAG_NO_REPORT, &stripe->state);
2184 		ret = scrub_find_fill_first_stripe(bg, &extent_path, &csum_path,
2185 				map->stripes[stripe_index].dev, physical, 1,
2186 				full_stripe_start + btrfs_stripe_nr_to_offset(i),
2187 				BTRFS_STRIPE_LEN, stripe);
2188 		if (ret < 0)
2189 			return ret;
2190 		/*
2191 		 * No extent in this data stripe, need to manually mark them
2192 		 * initialized to make later read submission happy.
2193 		 */
2194 		if (ret > 0) {
2195 			stripe->logical = full_stripe_start +
2196 					  btrfs_stripe_nr_to_offset(i);
2197 			stripe->dev = map->stripes[stripe_index].dev;
2198 			stripe->mirror_num = 1;
2199 			set_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state);
2200 		}
2201 	}
2202 
2203 	/* Check if all data stripes are empty. */
2204 	for (int i = 0; i < data_stripes; i++) {
2205 		stripe = &sctx->raid56_data_stripes[i];
2206 		if (!scrub_bitmap_empty_has_extent(stripe)) {
2207 			all_empty = false;
2208 			break;
2209 		}
2210 	}
2211 	if (all_empty)
2212 		return 0;
2213 
2214 	for (int i = 0; i < data_stripes; i++) {
2215 		stripe = &sctx->raid56_data_stripes[i];
2216 		scrub_submit_initial_read(sctx, stripe);
2217 	}
2218 	for (int i = 0; i < data_stripes; i++) {
2219 		stripe = &sctx->raid56_data_stripes[i];
2220 
2221 		wait_event(stripe->repair_wait,
2222 			   test_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state));
2223 	}
2224 	/* For now, no zoned support for RAID56. */
2225 	ASSERT(!btrfs_is_zoned(sctx->fs_info));
2226 
2227 	/*
2228 	 * Now all data stripes are properly verified. Check if we have any
2229 	 * unrepaired, if so abort immediately or we could further corrupt the
2230 	 * P/Q stripes.
2231 	 *
2232 	 * During the loop, also populate extent_bitmap.
2233 	 */
2234 	for (int i = 0; i < data_stripes; i++) {
2235 		unsigned long error;
2236 		unsigned long has_extent;
2237 
2238 		stripe = &sctx->raid56_data_stripes[i];
2239 
2240 		error = scrub_bitmap_read_error(stripe);
2241 		has_extent = scrub_bitmap_read_has_extent(stripe);
2242 
2243 		/*
2244 		 * We should only check the errors where there is an extent.
2245 		 * As we may hit an empty data stripe while it's missing.
2246 		 */
2247 		bitmap_and(&error, &error, &has_extent, stripe->nr_sectors);
2248 		if (unlikely(!bitmap_empty(&error, stripe->nr_sectors))) {
2249 			btrfs_err(fs_info,
2250 "scrub: unrepaired sectors detected, full stripe %llu data stripe %u errors %*pbl",
2251 				  full_stripe_start, i, stripe->nr_sectors,
2252 				  &error);
2253 			return ret;
2254 		}
2255 		bitmap_or(&extent_bitmap, &extent_bitmap, &has_extent,
2256 			  stripe->nr_sectors);
2257 	}
2258 
2259 	/* Now we can check and regenerate the P/Q stripe. */
2260 	return scrub_raid56_cached_parity(sctx, scrub_dev, map, full_stripe_start,
2261 					  &extent_bitmap);
2262 }
2263 
2264 /*
2265  * Scrub one range which can only has simple mirror based profile.
2266  * (Including all range in SINGLE/DUP/RAID1/RAID1C*, and each stripe in
2267  *  RAID0/RAID10).
2268  *
2269  * Since we may need to handle a subset of block group, we need @logical_start
2270  * and @logical_length parameter.
2271  */
2272 static int scrub_simple_mirror(struct scrub_ctx *sctx,
2273 			       struct btrfs_block_group *bg,
2274 			       u64 logical_start, u64 logical_length,
2275 			       struct btrfs_device *device,
2276 			       u64 physical, int mirror_num)
2277 {
2278 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2279 	const u64 logical_end = logical_start + logical_length;
2280 	u64 cur_logical = logical_start;
2281 	int ret = 0;
2282 
2283 	/* The range must be inside the bg */
2284 	ASSERT(logical_start >= bg->start && logical_end <= btrfs_block_group_end(bg));
2285 
2286 	/* Go through each extent items inside the logical range */
2287 	while (cur_logical < logical_end) {
2288 		u64 found_logical = U64_MAX;
2289 		u64 cur_physical = physical + cur_logical - logical_start;
2290 
2291 		ret = should_cancel_scrub(sctx);
2292 		if (ret < 0)
2293 			break;
2294 
2295 		if (atomic_read(&fs_info->scrub_pause_req))
2296 			scrub_blocked_if_needed(fs_info);
2297 
2298 		spin_lock(&bg->lock);
2299 		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
2300 			spin_unlock(&bg->lock);
2301 			ret = 0;
2302 			break;
2303 		}
2304 		spin_unlock(&bg->lock);
2305 
2306 		ret = queue_scrub_stripe(sctx, bg, device, mirror_num,
2307 					 cur_logical, logical_end - cur_logical,
2308 					 cur_physical, &found_logical);
2309 		if (ret > 0) {
2310 			/* No more extent, just update the accounting */
2311 			spin_lock(&sctx->stat_lock);
2312 			sctx->stat.last_physical = physical + logical_length;
2313 			spin_unlock(&sctx->stat_lock);
2314 			ret = 0;
2315 			break;
2316 		}
2317 		if (ret < 0)
2318 			break;
2319 
2320 		/* queue_scrub_stripe() returned 0, @found_logical must be updated. */
2321 		ASSERT(found_logical != U64_MAX);
2322 		cur_logical = found_logical + BTRFS_STRIPE_LEN;
2323 
2324 		/* Don't hold CPU for too long time */
2325 		cond_resched();
2326 	}
2327 	return ret;
2328 }
2329 
2330 /* Calculate the full stripe length for simple stripe based profiles */
2331 static u64 simple_stripe_full_stripe_len(const struct btrfs_chunk_map *map)
2332 {
2333 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2334 			    BTRFS_BLOCK_GROUP_RAID10));
2335 
2336 	return btrfs_stripe_nr_to_offset(map->num_stripes / map->sub_stripes);
2337 }
2338 
2339 /* Get the logical bytenr for the stripe */
2340 static u64 simple_stripe_get_logical(struct btrfs_chunk_map *map,
2341 				     struct btrfs_block_group *bg,
2342 				     int stripe_index)
2343 {
2344 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2345 			    BTRFS_BLOCK_GROUP_RAID10));
2346 	ASSERT(stripe_index < map->num_stripes);
2347 
2348 	/*
2349 	 * (stripe_index / sub_stripes) gives how many data stripes we need to
2350 	 * skip.
2351 	 */
2352 	return btrfs_stripe_nr_to_offset(stripe_index / map->sub_stripes) +
2353 	       bg->start;
2354 }
2355 
2356 /* Get the mirror number for the stripe */
2357 static int simple_stripe_mirror_num(struct btrfs_chunk_map *map, int stripe_index)
2358 {
2359 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2360 			    BTRFS_BLOCK_GROUP_RAID10));
2361 	ASSERT(stripe_index < map->num_stripes);
2362 
2363 	/* For RAID0, it's fixed to 1, for RAID10 it's 0,1,0,1... */
2364 	return stripe_index % map->sub_stripes + 1;
2365 }
2366 
2367 static int scrub_simple_stripe(struct scrub_ctx *sctx,
2368 			       struct btrfs_block_group *bg,
2369 			       struct btrfs_chunk_map *map,
2370 			       struct btrfs_device *device,
2371 			       int stripe_index)
2372 {
2373 	const u64 logical_increment = simple_stripe_full_stripe_len(map);
2374 	const u64 orig_logical = simple_stripe_get_logical(map, bg, stripe_index);
2375 	const u64 orig_physical = map->stripes[stripe_index].physical;
2376 	const u64 end = btrfs_block_group_end(bg);
2377 	const int mirror_num = simple_stripe_mirror_num(map, stripe_index);
2378 	u64 cur_logical = orig_logical;
2379 	u64 cur_physical = orig_physical;
2380 	int ret = 0;
2381 
2382 	while (cur_logical < end) {
2383 		/*
2384 		 * Inside each stripe, RAID0 is just SINGLE, and RAID10 is
2385 		 * just RAID1, so we can reuse scrub_simple_mirror() to scrub
2386 		 * this stripe.
2387 		 */
2388 		ret = scrub_simple_mirror(sctx, bg, cur_logical,
2389 					  BTRFS_STRIPE_LEN, device, cur_physical,
2390 					  mirror_num);
2391 		if (ret)
2392 			return ret;
2393 		/* Skip to next stripe which belongs to the target device */
2394 		cur_logical += logical_increment;
2395 		/* For physical offset, we just go to next stripe */
2396 		cur_physical += BTRFS_STRIPE_LEN;
2397 	}
2398 	return ret;
2399 }
2400 
2401 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
2402 					   struct btrfs_block_group *bg,
2403 					   struct btrfs_chunk_map *map,
2404 					   struct btrfs_device *scrub_dev,
2405 					   int stripe_index)
2406 {
2407 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2408 	const u64 profile = map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK;
2409 	const u64 chunk_logical = bg->start;
2410 	int ret;
2411 	int ret2;
2412 	u64 physical = map->stripes[stripe_index].physical;
2413 	const u64 dev_stripe_len = btrfs_calc_stripe_length(map);
2414 	const u64 physical_end = physical + dev_stripe_len;
2415 	u64 logical;
2416 	u64 logic_end;
2417 	/* The logical increment after finishing one stripe */
2418 	u64 increment;
2419 	/* Offset inside the chunk */
2420 	u64 offset;
2421 	u64 stripe_logical;
2422 
2423 	/* Extent_path should be released by now. */
2424 	ASSERT(sctx->extent_path.nodes[0] == NULL);
2425 
2426 	scrub_blocked_if_needed(fs_info);
2427 
2428 	if (sctx->is_dev_replace &&
2429 	    btrfs_dev_is_sequential(sctx->wr_tgtdev, physical)) {
2430 		mutex_lock(&sctx->wr_lock);
2431 		sctx->write_pointer = physical;
2432 		mutex_unlock(&sctx->wr_lock);
2433 	}
2434 
2435 	/* Prepare the extra data stripes used by RAID56. */
2436 	if (profile & BTRFS_BLOCK_GROUP_RAID56_MASK) {
2437 		ASSERT(sctx->raid56_data_stripes == NULL);
2438 
2439 		sctx->raid56_data_stripes = kzalloc_objs(struct scrub_stripe,
2440 							 nr_data_stripes(map));
2441 		if (!sctx->raid56_data_stripes) {
2442 			ret = -ENOMEM;
2443 			goto out;
2444 		}
2445 		for (int i = 0; i < nr_data_stripes(map); i++) {
2446 			ret = init_scrub_stripe(fs_info,
2447 						&sctx->raid56_data_stripes[i]);
2448 			if (ret < 0)
2449 				goto out;
2450 			sctx->raid56_data_stripes[i].bg = bg;
2451 			sctx->raid56_data_stripes[i].sctx = sctx;
2452 		}
2453 	}
2454 	/*
2455 	 * There used to be a big double loop to handle all profiles using the
2456 	 * same routine, which grows larger and more gross over time.
2457 	 *
2458 	 * So here we handle each profile differently, so simpler profiles
2459 	 * have simpler scrubbing function.
2460 	 */
2461 	if (!(profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10 |
2462 			 BTRFS_BLOCK_GROUP_RAID56_MASK))) {
2463 		/*
2464 		 * Above check rules out all complex profile, the remaining
2465 		 * profiles are SINGLE|DUP|RAID1|RAID1C*, which is simple
2466 		 * mirrored duplication without stripe.
2467 		 *
2468 		 * Only @physical and @mirror_num needs to calculated using
2469 		 * @stripe_index.
2470 		 */
2471 		ret = scrub_simple_mirror(sctx, bg, bg->start, bg->length,
2472 				scrub_dev, map->stripes[stripe_index].physical,
2473 				stripe_index + 1);
2474 		offset = 0;
2475 		goto out;
2476 	}
2477 	if (profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
2478 		ret = scrub_simple_stripe(sctx, bg, map, scrub_dev, stripe_index);
2479 		offset = btrfs_stripe_nr_to_offset(stripe_index / map->sub_stripes);
2480 		goto out;
2481 	}
2482 
2483 	/* Only RAID56 goes through the old code */
2484 	ASSERT(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK);
2485 	ret = 0;
2486 
2487 	/* Calculate the logical end of the stripe */
2488 	get_raid56_logic_offset(physical_end, stripe_index,
2489 				map, &logic_end, NULL);
2490 	logic_end += chunk_logical;
2491 
2492 	/* Initialize @offset in case we need to go to out: label */
2493 	get_raid56_logic_offset(physical, stripe_index, map, &offset, NULL);
2494 	increment = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
2495 
2496 	/*
2497 	 * Due to the rotation, for RAID56 it's better to iterate each stripe
2498 	 * using their physical offset.
2499 	 */
2500 	while (physical < physical_end) {
2501 		ret = get_raid56_logic_offset(physical, stripe_index, map,
2502 					      &logical, &stripe_logical);
2503 		logical += chunk_logical;
2504 		if (ret) {
2505 			/* it is parity strip */
2506 			stripe_logical += chunk_logical;
2507 			ret = scrub_raid56_parity_stripe(sctx, scrub_dev, bg,
2508 							 map, stripe_logical);
2509 			spin_lock(&sctx->stat_lock);
2510 			sctx->stat.last_physical = min(physical + BTRFS_STRIPE_LEN,
2511 						       physical_end);
2512 			spin_unlock(&sctx->stat_lock);
2513 			if (ret)
2514 				goto out;
2515 			goto next;
2516 		}
2517 
2518 		/*
2519 		 * Now we're at a data stripe, scrub each extents in the range.
2520 		 *
2521 		 * At this stage, if we ignore the repair part, inside each data
2522 		 * stripe it is no different than SINGLE profile.
2523 		 * We can reuse scrub_simple_mirror() here, as the repair part
2524 		 * is still based on @mirror_num.
2525 		 */
2526 		ret = scrub_simple_mirror(sctx, bg, logical, BTRFS_STRIPE_LEN,
2527 					  scrub_dev, physical, 1);
2528 		if (ret < 0)
2529 			goto out;
2530 next:
2531 		logical += increment;
2532 		physical += BTRFS_STRIPE_LEN;
2533 		spin_lock(&sctx->stat_lock);
2534 		sctx->stat.last_physical = physical;
2535 		spin_unlock(&sctx->stat_lock);
2536 	}
2537 out:
2538 	ret2 = flush_scrub_stripes(sctx);
2539 	if (!ret)
2540 		ret = ret2;
2541 	btrfs_release_path(&sctx->extent_path);
2542 	btrfs_release_path(&sctx->csum_path);
2543 
2544 	if (sctx->raid56_data_stripes) {
2545 		for (int i = 0; i < nr_data_stripes(map); i++)
2546 			release_scrub_stripe(&sctx->raid56_data_stripes[i]);
2547 		kfree(sctx->raid56_data_stripes);
2548 		sctx->raid56_data_stripes = NULL;
2549 	}
2550 
2551 	if (sctx->is_dev_replace && ret >= 0) {
2552 		ret2 = sync_write_pointer_for_zoned(sctx,
2553 				chunk_logical + offset,
2554 				map->stripes[stripe_index].physical,
2555 				physical_end);
2556 		if (ret2)
2557 			ret = ret2;
2558 	}
2559 
2560 	return ret < 0 ? ret : 0;
2561 }
2562 
2563 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx,
2564 					  struct btrfs_block_group *bg,
2565 					  struct btrfs_device *scrub_dev,
2566 					  u64 dev_offset,
2567 					  u64 dev_extent_len)
2568 {
2569 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2570 	struct btrfs_chunk_map *map;
2571 	int i;
2572 	int ret = 0;
2573 
2574 	map = btrfs_find_chunk_map(fs_info, bg->start, bg->length);
2575 	if (!map) {
2576 		/*
2577 		 * Might have been an unused block group deleted by the cleaner
2578 		 * kthread or relocation.
2579 		 */
2580 		spin_lock(&bg->lock);
2581 		if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags))
2582 			ret = -EINVAL;
2583 		spin_unlock(&bg->lock);
2584 
2585 		return ret;
2586 	}
2587 	if (map->start != bg->start)
2588 		goto out;
2589 	if (map->chunk_len < dev_extent_len)
2590 		goto out;
2591 
2592 	for (i = 0; i < map->num_stripes; ++i) {
2593 		if (map->stripes[i].dev->bdev == scrub_dev->bdev &&
2594 		    map->stripes[i].physical == dev_offset) {
2595 			ret = scrub_stripe(sctx, bg, map, scrub_dev, i);
2596 			if (ret)
2597 				goto out;
2598 		}
2599 	}
2600 out:
2601 	btrfs_free_chunk_map(map);
2602 
2603 	return ret;
2604 }
2605 
2606 static int finish_extent_writes_for_zoned(struct btrfs_root *root,
2607 					  struct btrfs_block_group *cache)
2608 {
2609 	struct btrfs_fs_info *fs_info = cache->fs_info;
2610 
2611 	if (!btrfs_is_zoned(fs_info))
2612 		return 0;
2613 
2614 	btrfs_wait_block_group_reservations(cache);
2615 	btrfs_wait_nocow_writers(cache);
2616 	btrfs_wait_ordered_roots(fs_info, U64_MAX, cache);
2617 
2618 	return btrfs_commit_current_transaction(root);
2619 }
2620 
2621 static noinline_for_stack
2622 int scrub_enumerate_chunks(struct scrub_ctx *sctx,
2623 			   struct btrfs_device *scrub_dev, u64 start, u64 end)
2624 {
2625 	struct btrfs_dev_extent *dev_extent = NULL;
2626 	BTRFS_PATH_AUTO_FREE(path);
2627 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2628 	struct btrfs_root *root = fs_info->dev_root;
2629 	u64 chunk_offset;
2630 	int ret = 0;
2631 	int ro_set;
2632 	int slot;
2633 	struct extent_buffer *l;
2634 	struct btrfs_key key;
2635 	struct btrfs_key found_key;
2636 	struct btrfs_block_group *cache;
2637 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
2638 
2639 	path = btrfs_alloc_path();
2640 	if (!path)
2641 		return -ENOMEM;
2642 
2643 	path->reada = READA_FORWARD;
2644 	path->search_commit_root = true;
2645 	path->skip_locking = true;
2646 
2647 	key.objectid = scrub_dev->devid;
2648 	key.type = BTRFS_DEV_EXTENT_KEY;
2649 	key.offset = 0ull;
2650 
2651 	while (1) {
2652 		u64 dev_extent_len;
2653 
2654 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2655 		if (ret < 0)
2656 			break;
2657 		if (ret > 0) {
2658 			if (path->slots[0] >=
2659 			    btrfs_header_nritems(path->nodes[0])) {
2660 				ret = btrfs_next_leaf(root, path);
2661 				if (ret < 0)
2662 					break;
2663 				if (ret > 0) {
2664 					ret = 0;
2665 					break;
2666 				}
2667 			} else {
2668 				ret = 0;
2669 			}
2670 		}
2671 
2672 		l = path->nodes[0];
2673 		slot = path->slots[0];
2674 
2675 		btrfs_item_key_to_cpu(l, &found_key, slot);
2676 
2677 		if (found_key.objectid != scrub_dev->devid)
2678 			break;
2679 
2680 		if (found_key.type != BTRFS_DEV_EXTENT_KEY)
2681 			break;
2682 
2683 		if (found_key.offset >= end)
2684 			break;
2685 
2686 		if (found_key.offset < key.offset)
2687 			break;
2688 
2689 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2690 		dev_extent_len = btrfs_dev_extent_length(l, dev_extent);
2691 
2692 		if (found_key.offset + dev_extent_len <= start)
2693 			goto skip;
2694 
2695 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2696 
2697 		/*
2698 		 * get a reference on the corresponding block group to prevent
2699 		 * the chunk from going away while we scrub it
2700 		 */
2701 		cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2702 
2703 		/* some chunks are removed but not committed to disk yet,
2704 		 * continue scrubbing */
2705 		if (!cache)
2706 			goto skip;
2707 
2708 		ASSERT(cache->start <= chunk_offset);
2709 		/*
2710 		 * We are using the commit root to search for device extents, so
2711 		 * that means we could have found a device extent item from a
2712 		 * block group that was deleted in the current transaction. The
2713 		 * logical start offset of the deleted block group, stored at
2714 		 * @chunk_offset, might be part of the logical address range of
2715 		 * a new block group (which uses different physical extents).
2716 		 * In this case btrfs_lookup_block_group() has returned the new
2717 		 * block group, and its start address is less than @chunk_offset.
2718 		 *
2719 		 * We skip such new block groups, because it's pointless to
2720 		 * process them, as we won't find their extents because we search
2721 		 * for them using the commit root of the extent tree. For a device
2722 		 * replace it's also fine to skip it, we won't miss copying them
2723 		 * to the target device because we have the write duplication
2724 		 * setup through the regular write path (by btrfs_map_block()),
2725 		 * and we have committed a transaction when we started the device
2726 		 * replace, right after setting up the device replace state.
2727 		 */
2728 		if (cache->start < chunk_offset) {
2729 			btrfs_put_block_group(cache);
2730 			goto skip;
2731 		}
2732 
2733 		if (sctx->is_dev_replace && btrfs_is_zoned(fs_info)) {
2734 			if (!test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags)) {
2735 				btrfs_put_block_group(cache);
2736 				goto skip;
2737 			}
2738 		}
2739 
2740 		/*
2741 		 * Make sure that while we are scrubbing the corresponding block
2742 		 * group doesn't get its logical address and its device extents
2743 		 * reused for another block group, which can possibly be of a
2744 		 * different type and different profile. We do this to prevent
2745 		 * false error detections and crashes due to bogus attempts to
2746 		 * repair extents.
2747 		 */
2748 		spin_lock(&cache->lock);
2749 		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags)) {
2750 			spin_unlock(&cache->lock);
2751 			btrfs_put_block_group(cache);
2752 			goto skip;
2753 		}
2754 		btrfs_freeze_block_group(cache);
2755 		spin_unlock(&cache->lock);
2756 
2757 		/*
2758 		 * we need call btrfs_inc_block_group_ro() with scrubs_paused,
2759 		 * to avoid deadlock caused by:
2760 		 * btrfs_inc_block_group_ro()
2761 		 * -> btrfs_wait_for_commit()
2762 		 * -> btrfs_commit_transaction()
2763 		 * -> btrfs_scrub_pause()
2764 		 */
2765 		scrub_pause_on(fs_info);
2766 
2767 		/*
2768 		 * Don't do chunk preallocation for scrub.
2769 		 *
2770 		 * This is especially important for SYSTEM bgs, or we can hit
2771 		 * -EFBIG from btrfs_finish_chunk_alloc() like:
2772 		 * 1. The only SYSTEM bg is marked RO.
2773 		 *    Since SYSTEM bg is small, that's pretty common.
2774 		 * 2. New SYSTEM bg will be allocated
2775 		 *    Due to regular version will allocate new chunk.
2776 		 * 3. New SYSTEM bg is empty and will get cleaned up
2777 		 *    Before cleanup really happens, it's marked RO again.
2778 		 * 4. Empty SYSTEM bg get scrubbed
2779 		 *    We go back to 2.
2780 		 *
2781 		 * This can easily boost the amount of SYSTEM chunks if cleaner
2782 		 * thread can't be triggered fast enough, and use up all space
2783 		 * of btrfs_super_block::sys_chunk_array
2784 		 *
2785 		 * While for dev replace, we need to try our best to mark block
2786 		 * group RO, to prevent race between:
2787 		 * - Write duplication
2788 		 *   Contains latest data
2789 		 * - Scrub copy
2790 		 *   Contains data from commit tree
2791 		 *
2792 		 * If target block group is not marked RO, nocow writes can
2793 		 * be overwritten by scrub copy, causing data corruption.
2794 		 * So for dev-replace, it's not allowed to continue if a block
2795 		 * group is not RO.
2796 		 */
2797 		ret = btrfs_inc_block_group_ro(cache, sctx->is_dev_replace);
2798 		if (!ret && sctx->is_dev_replace) {
2799 			ret = finish_extent_writes_for_zoned(root, cache);
2800 			if (ret) {
2801 				btrfs_dec_block_group_ro(cache);
2802 				scrub_pause_off(fs_info);
2803 				btrfs_put_block_group(cache);
2804 				break;
2805 			}
2806 		}
2807 
2808 		if (ret == 0) {
2809 			ro_set = 1;
2810 		} else if (ret == -ENOSPC && !sctx->is_dev_replace &&
2811 			   !(cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) {
2812 			/*
2813 			 * btrfs_inc_block_group_ro return -ENOSPC when it
2814 			 * failed in creating new chunk for metadata.
2815 			 * It is not a problem for scrub, because
2816 			 * metadata are always cowed, and our scrub paused
2817 			 * commit_transactions.
2818 			 *
2819 			 * For RAID56 chunks, we have to mark them read-only
2820 			 * for scrub, as later we would use our own cache
2821 			 * out of RAID56 realm.
2822 			 * Thus we want the RAID56 bg to be marked RO to
2823 			 * prevent RMW from screwing up out cache.
2824 			 */
2825 			ro_set = 0;
2826 		} else if (ret == -ETXTBSY) {
2827 			btrfs_warn(fs_info,
2828 	     "scrub: skipping scrub of block group %llu due to active swapfile",
2829 				   cache->start);
2830 			scrub_pause_off(fs_info);
2831 			ret = 0;
2832 			goto skip_unfreeze;
2833 		} else {
2834 			btrfs_warn(fs_info, "scrub: failed setting block group ro: %d",
2835 				   ret);
2836 			btrfs_unfreeze_block_group(cache);
2837 			btrfs_put_block_group(cache);
2838 			scrub_pause_off(fs_info);
2839 			break;
2840 		}
2841 
2842 		/*
2843 		 * Now the target block is marked RO, wait for nocow writes to
2844 		 * finish before dev-replace.
2845 		 * COW is fine, as COW never overwrites extents in commit tree.
2846 		 */
2847 		if (sctx->is_dev_replace) {
2848 			btrfs_wait_nocow_writers(cache);
2849 			btrfs_wait_ordered_roots(fs_info, U64_MAX, cache);
2850 		}
2851 
2852 		scrub_pause_off(fs_info);
2853 		down_write(&dev_replace->rwsem);
2854 		dev_replace->cursor_right = found_key.offset + dev_extent_len;
2855 		dev_replace->cursor_left = found_key.offset;
2856 		dev_replace->item_needs_writeback = 1;
2857 		up_write(&dev_replace->rwsem);
2858 
2859 		ret = scrub_chunk(sctx, cache, scrub_dev, found_key.offset,
2860 				  dev_extent_len);
2861 		if (sctx->is_dev_replace &&
2862 		    !btrfs_finish_block_group_to_copy(dev_replace->srcdev,
2863 						      cache, found_key.offset))
2864 			ro_set = 0;
2865 
2866 		down_write(&dev_replace->rwsem);
2867 		dev_replace->cursor_left = dev_replace->cursor_right;
2868 		dev_replace->item_needs_writeback = 1;
2869 		up_write(&dev_replace->rwsem);
2870 
2871 		if (ro_set)
2872 			btrfs_dec_block_group_ro(cache);
2873 
2874 		/*
2875 		 * We might have prevented the cleaner kthread from deleting
2876 		 * this block group if it was already unused because we raced
2877 		 * and set it to RO mode first. So add it back to the unused
2878 		 * list, otherwise it might not ever be deleted unless a manual
2879 		 * balance is triggered or it becomes used and unused again.
2880 		 */
2881 		spin_lock(&cache->lock);
2882 		if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags) &&
2883 		    !cache->ro && cache->reserved == 0 && cache->used == 0) {
2884 			spin_unlock(&cache->lock);
2885 			if (btrfs_test_opt(fs_info, DISCARD_ASYNC))
2886 				btrfs_discard_queue_work(&fs_info->discard_ctl,
2887 							 cache);
2888 			else
2889 				btrfs_mark_bg_unused(cache);
2890 		} else {
2891 			spin_unlock(&cache->lock);
2892 		}
2893 skip_unfreeze:
2894 		btrfs_unfreeze_block_group(cache);
2895 		btrfs_put_block_group(cache);
2896 		if (ret)
2897 			break;
2898 		if (unlikely(sctx->is_dev_replace &&
2899 			     atomic64_read(&dev_replace->num_write_errors) > 0)) {
2900 			ret = -EIO;
2901 			break;
2902 		}
2903 		if (sctx->stat.malloc_errors > 0) {
2904 			ret = -ENOMEM;
2905 			break;
2906 		}
2907 skip:
2908 		key.offset = found_key.offset + dev_extent_len;
2909 		btrfs_release_path(path);
2910 	}
2911 
2912 	return ret;
2913 }
2914 
2915 static int scrub_one_super(struct scrub_ctx *sctx, struct btrfs_device *dev,
2916 			   struct page *page, u64 physical, u64 generation)
2917 {
2918 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2919 	struct btrfs_super_block *sb = page_address(page);
2920 	int ret;
2921 
2922 	ret = bdev_rw_virt(dev->bdev, physical >> SECTOR_SHIFT, sb,
2923 			BTRFS_SUPER_INFO_SIZE, REQ_OP_READ);
2924 	if (ret < 0)
2925 		return ret;
2926 	ret = btrfs_check_super_csum(fs_info, sb);
2927 	if (unlikely(ret != 0)) {
2928 		btrfs_err_rl(fs_info,
2929 		  "scrub: super block at physical %llu devid %llu has bad csum",
2930 			physical, dev->devid);
2931 		return -EIO;
2932 	}
2933 	if (unlikely(btrfs_super_generation(sb) != generation)) {
2934 		btrfs_err_rl(fs_info,
2935 "scrub: super block at physical %llu devid %llu has bad generation %llu expect %llu",
2936 			     physical, dev->devid,
2937 			     btrfs_super_generation(sb), generation);
2938 		return -EUCLEAN;
2939 	}
2940 
2941 	return btrfs_validate_super(fs_info, sb, -1);
2942 }
2943 
2944 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx,
2945 					   struct btrfs_device *scrub_dev)
2946 {
2947 	int	i;
2948 	u64	bytenr;
2949 	u64	gen;
2950 	int ret = 0;
2951 	struct page *page;
2952 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2953 
2954 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
2955 		return -EROFS;
2956 
2957 	page = alloc_page(GFP_KERNEL);
2958 	if (!page) {
2959 		spin_lock(&sctx->stat_lock);
2960 		sctx->stat.malloc_errors++;
2961 		spin_unlock(&sctx->stat_lock);
2962 		return -ENOMEM;
2963 	}
2964 
2965 	/* Seed devices of a new filesystem has their own generation. */
2966 	if (scrub_dev->fs_devices != fs_info->fs_devices)
2967 		gen = scrub_dev->generation;
2968 	else
2969 		gen = btrfs_get_last_trans_committed(fs_info);
2970 
2971 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2972 		ret = btrfs_sb_log_location(scrub_dev, i, 0, &bytenr);
2973 		if (ret == -ENOENT)
2974 			break;
2975 
2976 		if (ret) {
2977 			spin_lock(&sctx->stat_lock);
2978 			sctx->stat.super_errors++;
2979 			spin_unlock(&sctx->stat_lock);
2980 			continue;
2981 		}
2982 
2983 		if (bytenr + BTRFS_SUPER_INFO_SIZE >
2984 		    scrub_dev->commit_total_bytes)
2985 			break;
2986 		if (!btrfs_check_super_location(scrub_dev, bytenr))
2987 			continue;
2988 
2989 		ret = scrub_one_super(sctx, scrub_dev, page, bytenr, gen);
2990 		if (ret) {
2991 			spin_lock(&sctx->stat_lock);
2992 			sctx->stat.super_errors++;
2993 			spin_unlock(&sctx->stat_lock);
2994 		}
2995 	}
2996 	__free_page(page);
2997 	return 0;
2998 }
2999 
3000 static void scrub_workers_put(struct btrfs_fs_info *fs_info)
3001 {
3002 	if (refcount_dec_and_mutex_lock(&fs_info->scrub_workers_refcnt,
3003 					&fs_info->scrub_lock)) {
3004 		struct workqueue_struct *scrub_workers = fs_info->scrub_workers;
3005 
3006 		fs_info->scrub_workers = NULL;
3007 		mutex_unlock(&fs_info->scrub_lock);
3008 
3009 		if (scrub_workers)
3010 			destroy_workqueue(scrub_workers);
3011 	}
3012 }
3013 
3014 /*
3015  * get a reference count on fs_info->scrub_workers. start worker if necessary
3016  */
3017 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info)
3018 {
3019 	struct workqueue_struct *scrub_workers = NULL;
3020 	unsigned int flags = WQ_FREEZABLE | WQ_UNBOUND;
3021 	int max_active = fs_info->thread_pool_size;
3022 	int ret = -ENOMEM;
3023 
3024 	if (refcount_inc_not_zero(&fs_info->scrub_workers_refcnt))
3025 		return 0;
3026 
3027 	scrub_workers = alloc_workqueue("btrfs-scrub", flags, max_active);
3028 	if (!scrub_workers)
3029 		return -ENOMEM;
3030 
3031 	mutex_lock(&fs_info->scrub_lock);
3032 	if (refcount_read(&fs_info->scrub_workers_refcnt) == 0) {
3033 		ASSERT(fs_info->scrub_workers == NULL);
3034 		fs_info->scrub_workers = scrub_workers;
3035 		refcount_set(&fs_info->scrub_workers_refcnt, 1);
3036 		mutex_unlock(&fs_info->scrub_lock);
3037 		return 0;
3038 	}
3039 	/* Other thread raced in and created the workers for us */
3040 	refcount_inc(&fs_info->scrub_workers_refcnt);
3041 	mutex_unlock(&fs_info->scrub_lock);
3042 
3043 	ret = 0;
3044 
3045 	destroy_workqueue(scrub_workers);
3046 	return ret;
3047 }
3048 
3049 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
3050 		    u64 end, struct btrfs_scrub_progress *progress,
3051 		    bool readonly, bool is_dev_replace)
3052 {
3053 	struct btrfs_dev_lookup_args args = { .devid = devid };
3054 	struct scrub_ctx *sctx;
3055 	int ret;
3056 	struct btrfs_device *dev;
3057 	unsigned int nofs_flag;
3058 	bool need_commit = false;
3059 
3060 	/* Set the basic fallback @last_physical before we got a sctx. */
3061 	if (progress)
3062 		progress->last_physical = start;
3063 
3064 	if (btrfs_fs_closing(fs_info))
3065 		return -EAGAIN;
3066 
3067 	/* At mount time we have ensured nodesize is in the range of [4K, 64K]. */
3068 	ASSERT(fs_info->nodesize <= BTRFS_STRIPE_LEN);
3069 
3070 	/* Allocate outside of device_list_mutex */
3071 	sctx = scrub_setup_ctx(fs_info, is_dev_replace);
3072 	if (IS_ERR(sctx))
3073 		return PTR_ERR(sctx);
3074 	sctx->stat.last_physical = start;
3075 
3076 	ret = scrub_workers_get(fs_info);
3077 	if (ret)
3078 		goto out_free_ctx;
3079 
3080 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
3081 	dev = btrfs_find_device(fs_info->fs_devices, &args);
3082 	if (!dev || (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) &&
3083 		     !is_dev_replace)) {
3084 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3085 		ret = -ENODEV;
3086 		goto out;
3087 	}
3088 
3089 	if (!is_dev_replace && !readonly &&
3090 	    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
3091 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3092 		btrfs_err(fs_info,
3093 			"scrub: devid %llu: filesystem on %s is not writable",
3094 				 devid, btrfs_dev_name(dev));
3095 		ret = -EROFS;
3096 		goto out;
3097 	}
3098 
3099 	mutex_lock(&fs_info->scrub_lock);
3100 	if (unlikely(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3101 		     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &dev->dev_state))) {
3102 		mutex_unlock(&fs_info->scrub_lock);
3103 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3104 		ret = -EIO;
3105 		goto out;
3106 	}
3107 
3108 	down_read(&fs_info->dev_replace.rwsem);
3109 	if (dev->scrub_ctx ||
3110 	    (!is_dev_replace &&
3111 	     btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) {
3112 		up_read(&fs_info->dev_replace.rwsem);
3113 		mutex_unlock(&fs_info->scrub_lock);
3114 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3115 		ret = -EINPROGRESS;
3116 		goto out;
3117 	}
3118 	up_read(&fs_info->dev_replace.rwsem);
3119 
3120 	sctx->readonly = readonly;
3121 	dev->scrub_ctx = sctx;
3122 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3123 
3124 	/*
3125 	 * checking @scrub_pause_req here, we can avoid
3126 	 * race between committing transaction and scrubbing.
3127 	 */
3128 	__scrub_blocked_if_needed(fs_info);
3129 	atomic_inc(&fs_info->scrubs_running);
3130 	mutex_unlock(&fs_info->scrub_lock);
3131 
3132 	/*
3133 	 * In order to avoid deadlock with reclaim when there is a transaction
3134 	 * trying to pause scrub, make sure we use GFP_NOFS for all the
3135 	 * allocations done at btrfs_scrub_sectors() and scrub_sectors_for_parity()
3136 	 * invoked by our callees. The pausing request is done when the
3137 	 * transaction commit starts, and it blocks the transaction until scrub
3138 	 * is paused (done at specific points at scrub_stripe() or right above
3139 	 * before incrementing fs_info->scrubs_running).
3140 	 */
3141 	nofs_flag = memalloc_nofs_save();
3142 	if (!is_dev_replace) {
3143 		u64 old_super_errors;
3144 
3145 		spin_lock(&sctx->stat_lock);
3146 		old_super_errors = sctx->stat.super_errors;
3147 		spin_unlock(&sctx->stat_lock);
3148 
3149 		btrfs_info(fs_info, "scrub: started on devid %llu", devid);
3150 		/*
3151 		 * by holding device list mutex, we can
3152 		 * kick off writing super in log tree sync.
3153 		 */
3154 		mutex_lock(&fs_info->fs_devices->device_list_mutex);
3155 		ret = scrub_supers(sctx, dev);
3156 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3157 
3158 		spin_lock(&sctx->stat_lock);
3159 		/*
3160 		 * Super block errors found, but we can not commit transaction
3161 		 * at current context, since btrfs_commit_transaction() needs
3162 		 * to pause the current running scrub (hold by ourselves).
3163 		 */
3164 		if (sctx->stat.super_errors > old_super_errors && !sctx->readonly)
3165 			need_commit = true;
3166 		spin_unlock(&sctx->stat_lock);
3167 	}
3168 
3169 	if (!ret)
3170 		ret = scrub_enumerate_chunks(sctx, dev, start, end);
3171 	memalloc_nofs_restore(nofs_flag);
3172 
3173 	atomic_dec(&fs_info->scrubs_running);
3174 	wake_up(&fs_info->scrub_pause_wait);
3175 
3176 	if (progress)
3177 		memcpy(progress, &sctx->stat, sizeof(*progress));
3178 
3179 	if (!is_dev_replace)
3180 		btrfs_info(fs_info, "scrub: %s on devid %llu with status: %d",
3181 			ret ? "not finished" : "finished", devid, ret);
3182 
3183 	mutex_lock(&fs_info->scrub_lock);
3184 	dev->scrub_ctx = NULL;
3185 	mutex_unlock(&fs_info->scrub_lock);
3186 
3187 	scrub_workers_put(fs_info);
3188 	scrub_put_ctx(sctx);
3189 
3190 	/*
3191 	 * We found some super block errors before, now try to force a
3192 	 * transaction commit, as scrub has finished.
3193 	 */
3194 	if (need_commit) {
3195 		struct btrfs_trans_handle *trans;
3196 
3197 		trans = btrfs_start_transaction(fs_info->tree_root, 0);
3198 		if (IS_ERR(trans)) {
3199 			ret = PTR_ERR(trans);
3200 			btrfs_err(fs_info,
3201 	"scrub: failed to start transaction to fix super block errors: %d", ret);
3202 			return ret;
3203 		}
3204 		ret = btrfs_commit_transaction(trans);
3205 		if (ret < 0)
3206 			btrfs_err(fs_info,
3207 	"scrub: failed to commit transaction to fix super block errors: %d", ret);
3208 	}
3209 	return ret;
3210 out:
3211 	scrub_workers_put(fs_info);
3212 out_free_ctx:
3213 	scrub_free_ctx(sctx);
3214 
3215 	return ret;
3216 }
3217 
3218 void btrfs_scrub_pause(struct btrfs_fs_info *fs_info)
3219 {
3220 	mutex_lock(&fs_info->scrub_lock);
3221 	atomic_inc(&fs_info->scrub_pause_req);
3222 	while (atomic_read(&fs_info->scrubs_paused) !=
3223 	       atomic_read(&fs_info->scrubs_running)) {
3224 		mutex_unlock(&fs_info->scrub_lock);
3225 		wait_event(fs_info->scrub_pause_wait,
3226 			   atomic_read(&fs_info->scrubs_paused) ==
3227 			   atomic_read(&fs_info->scrubs_running));
3228 		mutex_lock(&fs_info->scrub_lock);
3229 	}
3230 	mutex_unlock(&fs_info->scrub_lock);
3231 }
3232 
3233 void btrfs_scrub_continue(struct btrfs_fs_info *fs_info)
3234 {
3235 	atomic_dec(&fs_info->scrub_pause_req);
3236 	wake_up(&fs_info->scrub_pause_wait);
3237 }
3238 
3239 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
3240 {
3241 	mutex_lock(&fs_info->scrub_lock);
3242 	if (!atomic_read(&fs_info->scrubs_running)) {
3243 		mutex_unlock(&fs_info->scrub_lock);
3244 		return -ENOTCONN;
3245 	}
3246 
3247 	atomic_inc(&fs_info->scrub_cancel_req);
3248 	while (atomic_read(&fs_info->scrubs_running)) {
3249 		mutex_unlock(&fs_info->scrub_lock);
3250 		wait_event(fs_info->scrub_pause_wait,
3251 			   atomic_read(&fs_info->scrubs_running) == 0);
3252 		mutex_lock(&fs_info->scrub_lock);
3253 	}
3254 	atomic_dec(&fs_info->scrub_cancel_req);
3255 	mutex_unlock(&fs_info->scrub_lock);
3256 
3257 	return 0;
3258 }
3259 
3260 int btrfs_scrub_cancel_dev(struct btrfs_device *dev)
3261 {
3262 	struct btrfs_fs_info *fs_info = dev->fs_info;
3263 	struct scrub_ctx *sctx;
3264 
3265 	mutex_lock(&fs_info->scrub_lock);
3266 	sctx = dev->scrub_ctx;
3267 	if (!sctx) {
3268 		mutex_unlock(&fs_info->scrub_lock);
3269 		return -ENOTCONN;
3270 	}
3271 	atomic_inc(&sctx->cancel_req);
3272 	while (dev->scrub_ctx) {
3273 		mutex_unlock(&fs_info->scrub_lock);
3274 		wait_event(fs_info->scrub_pause_wait,
3275 			   dev->scrub_ctx == NULL);
3276 		mutex_lock(&fs_info->scrub_lock);
3277 	}
3278 	mutex_unlock(&fs_info->scrub_lock);
3279 
3280 	return 0;
3281 }
3282 
3283 int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid,
3284 			 struct btrfs_scrub_progress *progress)
3285 {
3286 	struct btrfs_dev_lookup_args args = { .devid = devid };
3287 	struct btrfs_device *dev;
3288 	struct scrub_ctx *sctx = NULL;
3289 
3290 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
3291 	dev = btrfs_find_device(fs_info->fs_devices, &args);
3292 	if (dev)
3293 		sctx = dev->scrub_ctx;
3294 	if (sctx)
3295 		memcpy(progress, &sctx->stat, sizeof(*progress));
3296 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3297 
3298 	return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;
3299 }
3300