xref: /openbmc/linux/fs/btrfs/scrub.c (revision 7c8ede16280586c72c36af6604985d714b84a32c)
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 <crypto/hash.h>
10 #include "ctree.h"
11 #include "discard.h"
12 #include "volumes.h"
13 #include "disk-io.h"
14 #include "ordered-data.h"
15 #include "transaction.h"
16 #include "backref.h"
17 #include "extent_io.h"
18 #include "dev-replace.h"
19 #include "check-integrity.h"
20 #include "rcu-string.h"
21 #include "raid56.h"
22 #include "block-group.h"
23 #include "zoned.h"
24 #include "fs.h"
25 #include "accessors.h"
26 #include "file-item.h"
27 
28 /*
29  * This is only the first step towards a full-features scrub. It reads all
30  * extent and super block and verifies the checksums. In case a bad checksum
31  * is found or the extent cannot be read, good data will be written back if
32  * any can be found.
33  *
34  * Future enhancements:
35  *  - In case an unrepairable extent is encountered, track which files are
36  *    affected and report them
37  *  - track and record media errors, throw out bad devices
38  *  - add a mode to also read unallocated space
39  */
40 
41 struct scrub_block;
42 struct scrub_ctx;
43 
44 /*
45  * The following three values only influence the performance.
46  *
47  * The last one configures the number of parallel and outstanding I/O
48  * operations. The first one configures an upper limit for the number
49  * of (dynamically allocated) pages that are added to a bio.
50  */
51 #define SCRUB_SECTORS_PER_BIO	32	/* 128KiB per bio for 4KiB pages */
52 #define SCRUB_BIOS_PER_SCTX	64	/* 8MiB per device in flight for 4KiB pages */
53 
54 /*
55  * The following value times PAGE_SIZE needs to be large enough to match the
56  * largest node/leaf/sector size that shall be supported.
57  */
58 #define SCRUB_MAX_SECTORS_PER_BLOCK	(BTRFS_MAX_METADATA_BLOCKSIZE / SZ_4K)
59 
60 #define SCRUB_MAX_PAGES			(DIV_ROUND_UP(BTRFS_MAX_METADATA_BLOCKSIZE, PAGE_SIZE))
61 
62 /*
63  * Maximum number of mirrors that can be available for all profiles counting
64  * the target device of dev-replace as one. During an active device replace
65  * procedure, the target device of the copy operation is a mirror for the
66  * filesystem data as well that can be used to read data in order to repair
67  * read errors on other disks.
68  *
69  * Current value is derived from RAID1C4 with 4 copies.
70  */
71 #define BTRFS_MAX_MIRRORS (4 + 1)
72 
73 struct scrub_recover {
74 	refcount_t		refs;
75 	struct btrfs_io_context	*bioc;
76 	u64			map_length;
77 };
78 
79 struct scrub_sector {
80 	struct scrub_block	*sblock;
81 	struct list_head	list;
82 	u64			flags;  /* extent flags */
83 	u64			generation;
84 	/* Offset in bytes to @sblock. */
85 	u32			offset;
86 	atomic_t		refs;
87 	unsigned int		have_csum:1;
88 	unsigned int		io_error:1;
89 	u8			csum[BTRFS_CSUM_SIZE];
90 
91 	struct scrub_recover	*recover;
92 };
93 
94 struct scrub_bio {
95 	int			index;
96 	struct scrub_ctx	*sctx;
97 	struct btrfs_device	*dev;
98 	struct bio		*bio;
99 	blk_status_t		status;
100 	u64			logical;
101 	u64			physical;
102 	struct scrub_sector	*sectors[SCRUB_SECTORS_PER_BIO];
103 	int			sector_count;
104 	int			next_free;
105 	struct work_struct	work;
106 };
107 
108 struct scrub_block {
109 	/*
110 	 * Each page will have its page::private used to record the logical
111 	 * bytenr.
112 	 */
113 	struct page		*pages[SCRUB_MAX_PAGES];
114 	struct scrub_sector	*sectors[SCRUB_MAX_SECTORS_PER_BLOCK];
115 	struct btrfs_device	*dev;
116 	/* Logical bytenr of the sblock */
117 	u64			logical;
118 	u64			physical;
119 	u64			physical_for_dev_replace;
120 	/* Length of sblock in bytes */
121 	u32			len;
122 	int			sector_count;
123 	int			mirror_num;
124 
125 	atomic_t		outstanding_sectors;
126 	refcount_t		refs; /* free mem on transition to zero */
127 	struct scrub_ctx	*sctx;
128 	struct scrub_parity	*sparity;
129 	struct {
130 		unsigned int	header_error:1;
131 		unsigned int	checksum_error:1;
132 		unsigned int	no_io_error_seen:1;
133 		unsigned int	generation_error:1; /* also sets header_error */
134 
135 		/* The following is for the data used to check parity */
136 		/* It is for the data with checksum */
137 		unsigned int	data_corrected:1;
138 	};
139 	struct work_struct	work;
140 };
141 
142 /* Used for the chunks with parity stripe such RAID5/6 */
143 struct scrub_parity {
144 	struct scrub_ctx	*sctx;
145 
146 	struct btrfs_device	*scrub_dev;
147 
148 	u64			logic_start;
149 
150 	u64			logic_end;
151 
152 	int			nsectors;
153 
154 	u32			stripe_len;
155 
156 	refcount_t		refs;
157 
158 	struct list_head	sectors_list;
159 
160 	/* Work of parity check and repair */
161 	struct work_struct	work;
162 
163 	/* Mark the parity blocks which have data */
164 	unsigned long		dbitmap;
165 
166 	/*
167 	 * Mark the parity blocks which have data, but errors happen when
168 	 * read data or check data
169 	 */
170 	unsigned long		ebitmap;
171 };
172 
173 struct scrub_ctx {
174 	struct scrub_bio	*bios[SCRUB_BIOS_PER_SCTX];
175 	struct btrfs_fs_info	*fs_info;
176 	int			first_free;
177 	int			curr;
178 	atomic_t		bios_in_flight;
179 	atomic_t		workers_pending;
180 	spinlock_t		list_lock;
181 	wait_queue_head_t	list_wait;
182 	struct list_head	csum_list;
183 	atomic_t		cancel_req;
184 	int			readonly;
185 	int			sectors_per_bio;
186 
187 	/* State of IO submission throttling affecting the associated device */
188 	ktime_t			throttle_deadline;
189 	u64			throttle_sent;
190 
191 	int			is_dev_replace;
192 	u64			write_pointer;
193 
194 	struct scrub_bio        *wr_curr_bio;
195 	struct mutex            wr_lock;
196 	struct btrfs_device     *wr_tgtdev;
197 	bool                    flush_all_writes;
198 
199 	/*
200 	 * statistics
201 	 */
202 	struct btrfs_scrub_progress stat;
203 	spinlock_t		stat_lock;
204 
205 	/*
206 	 * Use a ref counter to avoid use-after-free issues. Scrub workers
207 	 * decrement bios_in_flight and workers_pending and then do a wakeup
208 	 * on the list_wait wait queue. We must ensure the main scrub task
209 	 * doesn't free the scrub context before or while the workers are
210 	 * doing the wakeup() call.
211 	 */
212 	refcount_t              refs;
213 };
214 
215 struct scrub_warning {
216 	struct btrfs_path	*path;
217 	u64			extent_item_size;
218 	const char		*errstr;
219 	u64			physical;
220 	u64			logical;
221 	struct btrfs_device	*dev;
222 };
223 
224 struct full_stripe_lock {
225 	struct rb_node node;
226 	u64 logical;
227 	u64 refs;
228 	struct mutex mutex;
229 };
230 
231 #ifndef CONFIG_64BIT
232 /* This structure is for archtectures whose (void *) is smaller than u64 */
233 struct scrub_page_private {
234 	u64 logical;
235 };
236 #endif
237 
238 static int attach_scrub_page_private(struct page *page, u64 logical)
239 {
240 #ifdef CONFIG_64BIT
241 	attach_page_private(page, (void *)logical);
242 	return 0;
243 #else
244 	struct scrub_page_private *spp;
245 
246 	spp = kmalloc(sizeof(*spp), GFP_KERNEL);
247 	if (!spp)
248 		return -ENOMEM;
249 	spp->logical = logical;
250 	attach_page_private(page, (void *)spp);
251 	return 0;
252 #endif
253 }
254 
255 static void detach_scrub_page_private(struct page *page)
256 {
257 #ifdef CONFIG_64BIT
258 	detach_page_private(page);
259 	return;
260 #else
261 	struct scrub_page_private *spp;
262 
263 	spp = detach_page_private(page);
264 	kfree(spp);
265 	return;
266 #endif
267 }
268 
269 static struct scrub_block *alloc_scrub_block(struct scrub_ctx *sctx,
270 					     struct btrfs_device *dev,
271 					     u64 logical, u64 physical,
272 					     u64 physical_for_dev_replace,
273 					     int mirror_num)
274 {
275 	struct scrub_block *sblock;
276 
277 	sblock = kzalloc(sizeof(*sblock), GFP_KERNEL);
278 	if (!sblock)
279 		return NULL;
280 	refcount_set(&sblock->refs, 1);
281 	sblock->sctx = sctx;
282 	sblock->logical = logical;
283 	sblock->physical = physical;
284 	sblock->physical_for_dev_replace = physical_for_dev_replace;
285 	sblock->dev = dev;
286 	sblock->mirror_num = mirror_num;
287 	sblock->no_io_error_seen = 1;
288 	/*
289 	 * Scrub_block::pages will be allocated at alloc_scrub_sector() when
290 	 * the corresponding page is not allocated.
291 	 */
292 	return sblock;
293 }
294 
295 /*
296  * Allocate a new scrub sector and attach it to @sblock.
297  *
298  * Will also allocate new pages for @sblock if needed.
299  */
300 static struct scrub_sector *alloc_scrub_sector(struct scrub_block *sblock,
301 					       u64 logical)
302 {
303 	const pgoff_t page_index = (logical - sblock->logical) >> PAGE_SHIFT;
304 	struct scrub_sector *ssector;
305 
306 	/* We must never have scrub_block exceed U32_MAX in size. */
307 	ASSERT(logical - sblock->logical < U32_MAX);
308 
309 	ssector = kzalloc(sizeof(*ssector), GFP_KERNEL);
310 	if (!ssector)
311 		return NULL;
312 
313 	/* Allocate a new page if the slot is not allocated */
314 	if (!sblock->pages[page_index]) {
315 		int ret;
316 
317 		sblock->pages[page_index] = alloc_page(GFP_KERNEL);
318 		if (!sblock->pages[page_index]) {
319 			kfree(ssector);
320 			return NULL;
321 		}
322 		ret = attach_scrub_page_private(sblock->pages[page_index],
323 				sblock->logical + (page_index << PAGE_SHIFT));
324 		if (ret < 0) {
325 			kfree(ssector);
326 			__free_page(sblock->pages[page_index]);
327 			sblock->pages[page_index] = NULL;
328 			return NULL;
329 		}
330 	}
331 
332 	atomic_set(&ssector->refs, 1);
333 	ssector->sblock = sblock;
334 	/* The sector to be added should not be used */
335 	ASSERT(sblock->sectors[sblock->sector_count] == NULL);
336 	ssector->offset = logical - sblock->logical;
337 
338 	/* The sector count must be smaller than the limit */
339 	ASSERT(sblock->sector_count < SCRUB_MAX_SECTORS_PER_BLOCK);
340 
341 	sblock->sectors[sblock->sector_count] = ssector;
342 	sblock->sector_count++;
343 	sblock->len += sblock->sctx->fs_info->sectorsize;
344 
345 	return ssector;
346 }
347 
348 static struct page *scrub_sector_get_page(struct scrub_sector *ssector)
349 {
350 	struct scrub_block *sblock = ssector->sblock;
351 	pgoff_t index;
352 	/*
353 	 * When calling this function, ssector must be alreaday attached to the
354 	 * parent sblock.
355 	 */
356 	ASSERT(sblock);
357 
358 	/* The range should be inside the sblock range */
359 	ASSERT(ssector->offset < sblock->len);
360 
361 	index = ssector->offset >> PAGE_SHIFT;
362 	ASSERT(index < SCRUB_MAX_PAGES);
363 	ASSERT(sblock->pages[index]);
364 	ASSERT(PagePrivate(sblock->pages[index]));
365 	return sblock->pages[index];
366 }
367 
368 static unsigned int scrub_sector_get_page_offset(struct scrub_sector *ssector)
369 {
370 	struct scrub_block *sblock = ssector->sblock;
371 
372 	/*
373 	 * When calling this function, ssector must be already attached to the
374 	 * parent sblock.
375 	 */
376 	ASSERT(sblock);
377 
378 	/* The range should be inside the sblock range */
379 	ASSERT(ssector->offset < sblock->len);
380 
381 	return offset_in_page(ssector->offset);
382 }
383 
384 static char *scrub_sector_get_kaddr(struct scrub_sector *ssector)
385 {
386 	return page_address(scrub_sector_get_page(ssector)) +
387 	       scrub_sector_get_page_offset(ssector);
388 }
389 
390 static int bio_add_scrub_sector(struct bio *bio, struct scrub_sector *ssector,
391 				unsigned int len)
392 {
393 	return bio_add_page(bio, scrub_sector_get_page(ssector), len,
394 			    scrub_sector_get_page_offset(ssector));
395 }
396 
397 static int scrub_setup_recheck_block(struct scrub_block *original_sblock,
398 				     struct scrub_block *sblocks_for_recheck[]);
399 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
400 				struct scrub_block *sblock,
401 				int retry_failed_mirror);
402 static void scrub_recheck_block_checksum(struct scrub_block *sblock);
403 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
404 					     struct scrub_block *sblock_good);
405 static int scrub_repair_sector_from_good_copy(struct scrub_block *sblock_bad,
406 					    struct scrub_block *sblock_good,
407 					    int sector_num, int force_write);
408 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock);
409 static int scrub_write_sector_to_dev_replace(struct scrub_block *sblock,
410 					     int sector_num);
411 static int scrub_checksum_data(struct scrub_block *sblock);
412 static int scrub_checksum_tree_block(struct scrub_block *sblock);
413 static int scrub_checksum_super(struct scrub_block *sblock);
414 static void scrub_block_put(struct scrub_block *sblock);
415 static void scrub_sector_get(struct scrub_sector *sector);
416 static void scrub_sector_put(struct scrub_sector *sector);
417 static void scrub_parity_get(struct scrub_parity *sparity);
418 static void scrub_parity_put(struct scrub_parity *sparity);
419 static int scrub_sectors(struct scrub_ctx *sctx, u64 logical, u32 len,
420 			 u64 physical, struct btrfs_device *dev, u64 flags,
421 			 u64 gen, int mirror_num, u8 *csum,
422 			 u64 physical_for_dev_replace);
423 static void scrub_bio_end_io(struct bio *bio);
424 static void scrub_bio_end_io_worker(struct work_struct *work);
425 static void scrub_block_complete(struct scrub_block *sblock);
426 static void scrub_find_good_copy(struct btrfs_fs_info *fs_info,
427 				 u64 extent_logical, u32 extent_len,
428 				 u64 *extent_physical,
429 				 struct btrfs_device **extent_dev,
430 				 int *extent_mirror_num);
431 static int scrub_add_sector_to_wr_bio(struct scrub_ctx *sctx,
432 				      struct scrub_sector *sector);
433 static void scrub_wr_submit(struct scrub_ctx *sctx);
434 static void scrub_wr_bio_end_io(struct bio *bio);
435 static void scrub_wr_bio_end_io_worker(struct work_struct *work);
436 static void scrub_put_ctx(struct scrub_ctx *sctx);
437 
438 static inline int scrub_is_page_on_raid56(struct scrub_sector *sector)
439 {
440 	return sector->recover &&
441 	       (sector->recover->bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK);
442 }
443 
444 static void scrub_pending_bio_inc(struct scrub_ctx *sctx)
445 {
446 	refcount_inc(&sctx->refs);
447 	atomic_inc(&sctx->bios_in_flight);
448 }
449 
450 static void scrub_pending_bio_dec(struct scrub_ctx *sctx)
451 {
452 	atomic_dec(&sctx->bios_in_flight);
453 	wake_up(&sctx->list_wait);
454 	scrub_put_ctx(sctx);
455 }
456 
457 static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
458 {
459 	while (atomic_read(&fs_info->scrub_pause_req)) {
460 		mutex_unlock(&fs_info->scrub_lock);
461 		wait_event(fs_info->scrub_pause_wait,
462 		   atomic_read(&fs_info->scrub_pause_req) == 0);
463 		mutex_lock(&fs_info->scrub_lock);
464 	}
465 }
466 
467 static void scrub_pause_on(struct btrfs_fs_info *fs_info)
468 {
469 	atomic_inc(&fs_info->scrubs_paused);
470 	wake_up(&fs_info->scrub_pause_wait);
471 }
472 
473 static void scrub_pause_off(struct btrfs_fs_info *fs_info)
474 {
475 	mutex_lock(&fs_info->scrub_lock);
476 	__scrub_blocked_if_needed(fs_info);
477 	atomic_dec(&fs_info->scrubs_paused);
478 	mutex_unlock(&fs_info->scrub_lock);
479 
480 	wake_up(&fs_info->scrub_pause_wait);
481 }
482 
483 static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
484 {
485 	scrub_pause_on(fs_info);
486 	scrub_pause_off(fs_info);
487 }
488 
489 /*
490  * Insert new full stripe lock into full stripe locks tree
491  *
492  * Return pointer to existing or newly inserted full_stripe_lock structure if
493  * everything works well.
494  * Return ERR_PTR(-ENOMEM) if we failed to allocate memory
495  *
496  * NOTE: caller must hold full_stripe_locks_root->lock before calling this
497  * function
498  */
499 static struct full_stripe_lock *insert_full_stripe_lock(
500 		struct btrfs_full_stripe_locks_tree *locks_root,
501 		u64 fstripe_logical)
502 {
503 	struct rb_node **p;
504 	struct rb_node *parent = NULL;
505 	struct full_stripe_lock *entry;
506 	struct full_stripe_lock *ret;
507 
508 	lockdep_assert_held(&locks_root->lock);
509 
510 	p = &locks_root->root.rb_node;
511 	while (*p) {
512 		parent = *p;
513 		entry = rb_entry(parent, struct full_stripe_lock, node);
514 		if (fstripe_logical < entry->logical) {
515 			p = &(*p)->rb_left;
516 		} else if (fstripe_logical > entry->logical) {
517 			p = &(*p)->rb_right;
518 		} else {
519 			entry->refs++;
520 			return entry;
521 		}
522 	}
523 
524 	/*
525 	 * Insert new lock.
526 	 */
527 	ret = kmalloc(sizeof(*ret), GFP_KERNEL);
528 	if (!ret)
529 		return ERR_PTR(-ENOMEM);
530 	ret->logical = fstripe_logical;
531 	ret->refs = 1;
532 	mutex_init(&ret->mutex);
533 
534 	rb_link_node(&ret->node, parent, p);
535 	rb_insert_color(&ret->node, &locks_root->root);
536 	return ret;
537 }
538 
539 /*
540  * Search for a full stripe lock of a block group
541  *
542  * Return pointer to existing full stripe lock if found
543  * Return NULL if not found
544  */
545 static struct full_stripe_lock *search_full_stripe_lock(
546 		struct btrfs_full_stripe_locks_tree *locks_root,
547 		u64 fstripe_logical)
548 {
549 	struct rb_node *node;
550 	struct full_stripe_lock *entry;
551 
552 	lockdep_assert_held(&locks_root->lock);
553 
554 	node = locks_root->root.rb_node;
555 	while (node) {
556 		entry = rb_entry(node, struct full_stripe_lock, node);
557 		if (fstripe_logical < entry->logical)
558 			node = node->rb_left;
559 		else if (fstripe_logical > entry->logical)
560 			node = node->rb_right;
561 		else
562 			return entry;
563 	}
564 	return NULL;
565 }
566 
567 /*
568  * Helper to get full stripe logical from a normal bytenr.
569  *
570  * Caller must ensure @cache is a RAID56 block group.
571  */
572 static u64 get_full_stripe_logical(struct btrfs_block_group *cache, u64 bytenr)
573 {
574 	u64 ret;
575 
576 	/*
577 	 * Due to chunk item size limit, full stripe length should not be
578 	 * larger than U32_MAX. Just a sanity check here.
579 	 */
580 	WARN_ON_ONCE(cache->full_stripe_len >= U32_MAX);
581 
582 	/*
583 	 * round_down() can only handle power of 2, while RAID56 full
584 	 * stripe length can be 64KiB * n, so we need to manually round down.
585 	 */
586 	ret = div64_u64(bytenr - cache->start, cache->full_stripe_len) *
587 			cache->full_stripe_len + cache->start;
588 	return ret;
589 }
590 
591 /*
592  * Lock a full stripe to avoid concurrency of recovery and read
593  *
594  * It's only used for profiles with parities (RAID5/6), for other profiles it
595  * does nothing.
596  *
597  * Return 0 if we locked full stripe covering @bytenr, with a mutex held.
598  * So caller must call unlock_full_stripe() at the same context.
599  *
600  * Return <0 if encounters error.
601  */
602 static int lock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr,
603 			    bool *locked_ret)
604 {
605 	struct btrfs_block_group *bg_cache;
606 	struct btrfs_full_stripe_locks_tree *locks_root;
607 	struct full_stripe_lock *existing;
608 	u64 fstripe_start;
609 	int ret = 0;
610 
611 	*locked_ret = false;
612 	bg_cache = btrfs_lookup_block_group(fs_info, bytenr);
613 	if (!bg_cache) {
614 		ASSERT(0);
615 		return -ENOENT;
616 	}
617 
618 	/* Profiles not based on parity don't need full stripe lock */
619 	if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK))
620 		goto out;
621 	locks_root = &bg_cache->full_stripe_locks_root;
622 
623 	fstripe_start = get_full_stripe_logical(bg_cache, bytenr);
624 
625 	/* Now insert the full stripe lock */
626 	mutex_lock(&locks_root->lock);
627 	existing = insert_full_stripe_lock(locks_root, fstripe_start);
628 	mutex_unlock(&locks_root->lock);
629 	if (IS_ERR(existing)) {
630 		ret = PTR_ERR(existing);
631 		goto out;
632 	}
633 	mutex_lock(&existing->mutex);
634 	*locked_ret = true;
635 out:
636 	btrfs_put_block_group(bg_cache);
637 	return ret;
638 }
639 
640 /*
641  * Unlock a full stripe.
642  *
643  * NOTE: Caller must ensure it's the same context calling corresponding
644  * lock_full_stripe().
645  *
646  * Return 0 if we unlock full stripe without problem.
647  * Return <0 for error
648  */
649 static int unlock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr,
650 			      bool locked)
651 {
652 	struct btrfs_block_group *bg_cache;
653 	struct btrfs_full_stripe_locks_tree *locks_root;
654 	struct full_stripe_lock *fstripe_lock;
655 	u64 fstripe_start;
656 	bool freeit = false;
657 	int ret = 0;
658 
659 	/* If we didn't acquire full stripe lock, no need to continue */
660 	if (!locked)
661 		return 0;
662 
663 	bg_cache = btrfs_lookup_block_group(fs_info, bytenr);
664 	if (!bg_cache) {
665 		ASSERT(0);
666 		return -ENOENT;
667 	}
668 	if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK))
669 		goto out;
670 
671 	locks_root = &bg_cache->full_stripe_locks_root;
672 	fstripe_start = get_full_stripe_logical(bg_cache, bytenr);
673 
674 	mutex_lock(&locks_root->lock);
675 	fstripe_lock = search_full_stripe_lock(locks_root, fstripe_start);
676 	/* Unpaired unlock_full_stripe() detected */
677 	if (!fstripe_lock) {
678 		WARN_ON(1);
679 		ret = -ENOENT;
680 		mutex_unlock(&locks_root->lock);
681 		goto out;
682 	}
683 
684 	if (fstripe_lock->refs == 0) {
685 		WARN_ON(1);
686 		btrfs_warn(fs_info, "full stripe lock at %llu refcount underflow",
687 			fstripe_lock->logical);
688 	} else {
689 		fstripe_lock->refs--;
690 	}
691 
692 	if (fstripe_lock->refs == 0) {
693 		rb_erase(&fstripe_lock->node, &locks_root->root);
694 		freeit = true;
695 	}
696 	mutex_unlock(&locks_root->lock);
697 
698 	mutex_unlock(&fstripe_lock->mutex);
699 	if (freeit)
700 		kfree(fstripe_lock);
701 out:
702 	btrfs_put_block_group(bg_cache);
703 	return ret;
704 }
705 
706 static void scrub_free_csums(struct scrub_ctx *sctx)
707 {
708 	while (!list_empty(&sctx->csum_list)) {
709 		struct btrfs_ordered_sum *sum;
710 		sum = list_first_entry(&sctx->csum_list,
711 				       struct btrfs_ordered_sum, list);
712 		list_del(&sum->list);
713 		kfree(sum);
714 	}
715 }
716 
717 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
718 {
719 	int i;
720 
721 	if (!sctx)
722 		return;
723 
724 	/* this can happen when scrub is cancelled */
725 	if (sctx->curr != -1) {
726 		struct scrub_bio *sbio = sctx->bios[sctx->curr];
727 
728 		for (i = 0; i < sbio->sector_count; i++)
729 			scrub_block_put(sbio->sectors[i]->sblock);
730 		bio_put(sbio->bio);
731 	}
732 
733 	for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
734 		struct scrub_bio *sbio = sctx->bios[i];
735 
736 		if (!sbio)
737 			break;
738 		kfree(sbio);
739 	}
740 
741 	kfree(sctx->wr_curr_bio);
742 	scrub_free_csums(sctx);
743 	kfree(sctx);
744 }
745 
746 static void scrub_put_ctx(struct scrub_ctx *sctx)
747 {
748 	if (refcount_dec_and_test(&sctx->refs))
749 		scrub_free_ctx(sctx);
750 }
751 
752 static noinline_for_stack struct scrub_ctx *scrub_setup_ctx(
753 		struct btrfs_fs_info *fs_info, int is_dev_replace)
754 {
755 	struct scrub_ctx *sctx;
756 	int		i;
757 
758 	sctx = kzalloc(sizeof(*sctx), GFP_KERNEL);
759 	if (!sctx)
760 		goto nomem;
761 	refcount_set(&sctx->refs, 1);
762 	sctx->is_dev_replace = is_dev_replace;
763 	sctx->sectors_per_bio = SCRUB_SECTORS_PER_BIO;
764 	sctx->curr = -1;
765 	sctx->fs_info = fs_info;
766 	INIT_LIST_HEAD(&sctx->csum_list);
767 	for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
768 		struct scrub_bio *sbio;
769 
770 		sbio = kzalloc(sizeof(*sbio), GFP_KERNEL);
771 		if (!sbio)
772 			goto nomem;
773 		sctx->bios[i] = sbio;
774 
775 		sbio->index = i;
776 		sbio->sctx = sctx;
777 		sbio->sector_count = 0;
778 		INIT_WORK(&sbio->work, scrub_bio_end_io_worker);
779 
780 		if (i != SCRUB_BIOS_PER_SCTX - 1)
781 			sctx->bios[i]->next_free = i + 1;
782 		else
783 			sctx->bios[i]->next_free = -1;
784 	}
785 	sctx->first_free = 0;
786 	atomic_set(&sctx->bios_in_flight, 0);
787 	atomic_set(&sctx->workers_pending, 0);
788 	atomic_set(&sctx->cancel_req, 0);
789 
790 	spin_lock_init(&sctx->list_lock);
791 	spin_lock_init(&sctx->stat_lock);
792 	init_waitqueue_head(&sctx->list_wait);
793 	sctx->throttle_deadline = 0;
794 
795 	WARN_ON(sctx->wr_curr_bio != NULL);
796 	mutex_init(&sctx->wr_lock);
797 	sctx->wr_curr_bio = NULL;
798 	if (is_dev_replace) {
799 		WARN_ON(!fs_info->dev_replace.tgtdev);
800 		sctx->wr_tgtdev = fs_info->dev_replace.tgtdev;
801 		sctx->flush_all_writes = false;
802 	}
803 
804 	return sctx;
805 
806 nomem:
807 	scrub_free_ctx(sctx);
808 	return ERR_PTR(-ENOMEM);
809 }
810 
811 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root,
812 				     void *warn_ctx)
813 {
814 	u32 nlink;
815 	int ret;
816 	int i;
817 	unsigned nofs_flag;
818 	struct extent_buffer *eb;
819 	struct btrfs_inode_item *inode_item;
820 	struct scrub_warning *swarn = warn_ctx;
821 	struct btrfs_fs_info *fs_info = swarn->dev->fs_info;
822 	struct inode_fs_paths *ipath = NULL;
823 	struct btrfs_root *local_root;
824 	struct btrfs_key key;
825 
826 	local_root = btrfs_get_fs_root(fs_info, root, true);
827 	if (IS_ERR(local_root)) {
828 		ret = PTR_ERR(local_root);
829 		goto err;
830 	}
831 
832 	/*
833 	 * this makes the path point to (inum INODE_ITEM ioff)
834 	 */
835 	key.objectid = inum;
836 	key.type = BTRFS_INODE_ITEM_KEY;
837 	key.offset = 0;
838 
839 	ret = btrfs_search_slot(NULL, local_root, &key, swarn->path, 0, 0);
840 	if (ret) {
841 		btrfs_put_root(local_root);
842 		btrfs_release_path(swarn->path);
843 		goto err;
844 	}
845 
846 	eb = swarn->path->nodes[0];
847 	inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
848 					struct btrfs_inode_item);
849 	nlink = btrfs_inode_nlink(eb, inode_item);
850 	btrfs_release_path(swarn->path);
851 
852 	/*
853 	 * init_path might indirectly call vmalloc, or use GFP_KERNEL. Scrub
854 	 * uses GFP_NOFS in this context, so we keep it consistent but it does
855 	 * not seem to be strictly necessary.
856 	 */
857 	nofs_flag = memalloc_nofs_save();
858 	ipath = init_ipath(4096, local_root, swarn->path);
859 	memalloc_nofs_restore(nofs_flag);
860 	if (IS_ERR(ipath)) {
861 		btrfs_put_root(local_root);
862 		ret = PTR_ERR(ipath);
863 		ipath = NULL;
864 		goto err;
865 	}
866 	ret = paths_from_inode(inum, ipath);
867 
868 	if (ret < 0)
869 		goto err;
870 
871 	/*
872 	 * we deliberately ignore the bit ipath might have been too small to
873 	 * hold all of the paths here
874 	 */
875 	for (i = 0; i < ipath->fspath->elem_cnt; ++i)
876 		btrfs_warn_in_rcu(fs_info,
877 "%s at logical %llu on dev %s, physical %llu, root %llu, inode %llu, offset %llu, length %u, links %u (path: %s)",
878 				  swarn->errstr, swarn->logical,
879 				  rcu_str_deref(swarn->dev->name),
880 				  swarn->physical,
881 				  root, inum, offset,
882 				  fs_info->sectorsize, nlink,
883 				  (char *)(unsigned long)ipath->fspath->val[i]);
884 
885 	btrfs_put_root(local_root);
886 	free_ipath(ipath);
887 	return 0;
888 
889 err:
890 	btrfs_warn_in_rcu(fs_info,
891 			  "%s at logical %llu on dev %s, physical %llu, root %llu, inode %llu, offset %llu: path resolving failed with ret=%d",
892 			  swarn->errstr, swarn->logical,
893 			  rcu_str_deref(swarn->dev->name),
894 			  swarn->physical,
895 			  root, inum, offset, ret);
896 
897 	free_ipath(ipath);
898 	return 0;
899 }
900 
901 static void scrub_print_warning(const char *errstr, struct scrub_block *sblock)
902 {
903 	struct btrfs_device *dev;
904 	struct btrfs_fs_info *fs_info;
905 	struct btrfs_path *path;
906 	struct btrfs_key found_key;
907 	struct extent_buffer *eb;
908 	struct btrfs_extent_item *ei;
909 	struct scrub_warning swarn;
910 	unsigned long ptr = 0;
911 	u64 extent_item_pos;
912 	u64 flags = 0;
913 	u64 ref_root;
914 	u32 item_size;
915 	u8 ref_level = 0;
916 	int ret;
917 
918 	WARN_ON(sblock->sector_count < 1);
919 	dev = sblock->dev;
920 	fs_info = sblock->sctx->fs_info;
921 
922 	/* Super block error, no need to search extent tree. */
923 	if (sblock->sectors[0]->flags & BTRFS_EXTENT_FLAG_SUPER) {
924 		btrfs_warn_in_rcu(fs_info, "%s on device %s, physical %llu",
925 			errstr, rcu_str_deref(dev->name),
926 			sblock->physical);
927 		return;
928 	}
929 	path = btrfs_alloc_path();
930 	if (!path)
931 		return;
932 
933 	swarn.physical = sblock->physical;
934 	swarn.logical = sblock->logical;
935 	swarn.errstr = errstr;
936 	swarn.dev = NULL;
937 
938 	ret = extent_from_logical(fs_info, swarn.logical, path, &found_key,
939 				  &flags);
940 	if (ret < 0)
941 		goto out;
942 
943 	extent_item_pos = swarn.logical - found_key.objectid;
944 	swarn.extent_item_size = found_key.offset;
945 
946 	eb = path->nodes[0];
947 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
948 	item_size = btrfs_item_size(eb, path->slots[0]);
949 
950 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
951 		do {
952 			ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
953 						      item_size, &ref_root,
954 						      &ref_level);
955 			btrfs_warn_in_rcu(fs_info,
956 "%s at logical %llu on dev %s, physical %llu: metadata %s (level %d) in tree %llu",
957 				errstr, swarn.logical,
958 				rcu_str_deref(dev->name),
959 				swarn.physical,
960 				ref_level ? "node" : "leaf",
961 				ret < 0 ? -1 : ref_level,
962 				ret < 0 ? -1 : ref_root);
963 		} while (ret != 1);
964 		btrfs_release_path(path);
965 	} else {
966 		btrfs_release_path(path);
967 		swarn.path = path;
968 		swarn.dev = dev;
969 		iterate_extent_inodes(fs_info, found_key.objectid,
970 					extent_item_pos, 1,
971 					scrub_print_warning_inode, &swarn, false);
972 	}
973 
974 out:
975 	btrfs_free_path(path);
976 }
977 
978 static inline void scrub_get_recover(struct scrub_recover *recover)
979 {
980 	refcount_inc(&recover->refs);
981 }
982 
983 static inline void scrub_put_recover(struct btrfs_fs_info *fs_info,
984 				     struct scrub_recover *recover)
985 {
986 	if (refcount_dec_and_test(&recover->refs)) {
987 		btrfs_bio_counter_dec(fs_info);
988 		btrfs_put_bioc(recover->bioc);
989 		kfree(recover);
990 	}
991 }
992 
993 /*
994  * scrub_handle_errored_block gets called when either verification of the
995  * sectors failed or the bio failed to read, e.g. with EIO. In the latter
996  * case, this function handles all sectors in the bio, even though only one
997  * may be bad.
998  * The goal of this function is to repair the errored block by using the
999  * contents of one of the mirrors.
1000  */
1001 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check)
1002 {
1003 	struct scrub_ctx *sctx = sblock_to_check->sctx;
1004 	struct btrfs_device *dev = sblock_to_check->dev;
1005 	struct btrfs_fs_info *fs_info;
1006 	u64 logical;
1007 	unsigned int failed_mirror_index;
1008 	unsigned int is_metadata;
1009 	unsigned int have_csum;
1010 	/* One scrub_block for each mirror */
1011 	struct scrub_block *sblocks_for_recheck[BTRFS_MAX_MIRRORS] = { 0 };
1012 	struct scrub_block *sblock_bad;
1013 	int ret;
1014 	int mirror_index;
1015 	int sector_num;
1016 	int success;
1017 	bool full_stripe_locked;
1018 	unsigned int nofs_flag;
1019 	static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
1020 				      DEFAULT_RATELIMIT_BURST);
1021 
1022 	BUG_ON(sblock_to_check->sector_count < 1);
1023 	fs_info = sctx->fs_info;
1024 	if (sblock_to_check->sectors[0]->flags & BTRFS_EXTENT_FLAG_SUPER) {
1025 		/*
1026 		 * If we find an error in a super block, we just report it.
1027 		 * They will get written with the next transaction commit
1028 		 * anyway
1029 		 */
1030 		scrub_print_warning("super block error", sblock_to_check);
1031 		spin_lock(&sctx->stat_lock);
1032 		++sctx->stat.super_errors;
1033 		spin_unlock(&sctx->stat_lock);
1034 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
1035 		return 0;
1036 	}
1037 	logical = sblock_to_check->logical;
1038 	ASSERT(sblock_to_check->mirror_num);
1039 	failed_mirror_index = sblock_to_check->mirror_num - 1;
1040 	is_metadata = !(sblock_to_check->sectors[0]->flags &
1041 			BTRFS_EXTENT_FLAG_DATA);
1042 	have_csum = sblock_to_check->sectors[0]->have_csum;
1043 
1044 	if (!sctx->is_dev_replace && btrfs_repair_one_zone(fs_info, logical))
1045 		return 0;
1046 
1047 	/*
1048 	 * We must use GFP_NOFS because the scrub task might be waiting for a
1049 	 * worker task executing this function and in turn a transaction commit
1050 	 * might be waiting the scrub task to pause (which needs to wait for all
1051 	 * the worker tasks to complete before pausing).
1052 	 * We do allocations in the workers through insert_full_stripe_lock()
1053 	 * and scrub_add_sector_to_wr_bio(), which happens down the call chain of
1054 	 * this function.
1055 	 */
1056 	nofs_flag = memalloc_nofs_save();
1057 	/*
1058 	 * For RAID5/6, race can happen for a different device scrub thread.
1059 	 * For data corruption, Parity and Data threads will both try
1060 	 * to recovery the data.
1061 	 * Race can lead to doubly added csum error, or even unrecoverable
1062 	 * error.
1063 	 */
1064 	ret = lock_full_stripe(fs_info, logical, &full_stripe_locked);
1065 	if (ret < 0) {
1066 		memalloc_nofs_restore(nofs_flag);
1067 		spin_lock(&sctx->stat_lock);
1068 		if (ret == -ENOMEM)
1069 			sctx->stat.malloc_errors++;
1070 		sctx->stat.read_errors++;
1071 		sctx->stat.uncorrectable_errors++;
1072 		spin_unlock(&sctx->stat_lock);
1073 		return ret;
1074 	}
1075 
1076 	/*
1077 	 * read all mirrors one after the other. This includes to
1078 	 * re-read the extent or metadata block that failed (that was
1079 	 * the cause that this fixup code is called) another time,
1080 	 * sector by sector this time in order to know which sectors
1081 	 * caused I/O errors and which ones are good (for all mirrors).
1082 	 * It is the goal to handle the situation when more than one
1083 	 * mirror contains I/O errors, but the errors do not
1084 	 * overlap, i.e. the data can be repaired by selecting the
1085 	 * sectors from those mirrors without I/O error on the
1086 	 * particular sectors. One example (with blocks >= 2 * sectorsize)
1087 	 * would be that mirror #1 has an I/O error on the first sector,
1088 	 * the second sector is good, and mirror #2 has an I/O error on
1089 	 * the second sector, but the first sector is good.
1090 	 * Then the first sector of the first mirror can be repaired by
1091 	 * taking the first sector of the second mirror, and the
1092 	 * second sector of the second mirror can be repaired by
1093 	 * copying the contents of the 2nd sector of the 1st mirror.
1094 	 * One more note: if the sectors of one mirror contain I/O
1095 	 * errors, the checksum cannot be verified. In order to get
1096 	 * the best data for repairing, the first attempt is to find
1097 	 * a mirror without I/O errors and with a validated checksum.
1098 	 * Only if this is not possible, the sectors are picked from
1099 	 * mirrors with I/O errors without considering the checksum.
1100 	 * If the latter is the case, at the end, the checksum of the
1101 	 * repaired area is verified in order to correctly maintain
1102 	 * the statistics.
1103 	 */
1104 	for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS; mirror_index++) {
1105 		/*
1106 		 * Note: the two members refs and outstanding_sectors are not
1107 		 * used in the blocks that are used for the recheck procedure.
1108 		 *
1109 		 * But alloc_scrub_block() will initialize sblock::ref anyway,
1110 		 * so we can use scrub_block_put() to clean them up.
1111 		 *
1112 		 * And here we don't setup the physical/dev for the sblock yet,
1113 		 * they will be correctly initialized in scrub_setup_recheck_block().
1114 		 */
1115 		sblocks_for_recheck[mirror_index] = alloc_scrub_block(sctx, NULL,
1116 							logical, 0, 0, mirror_index);
1117 		if (!sblocks_for_recheck[mirror_index]) {
1118 			spin_lock(&sctx->stat_lock);
1119 			sctx->stat.malloc_errors++;
1120 			sctx->stat.read_errors++;
1121 			sctx->stat.uncorrectable_errors++;
1122 			spin_unlock(&sctx->stat_lock);
1123 			btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1124 			goto out;
1125 		}
1126 	}
1127 
1128 	/* Setup the context, map the logical blocks and alloc the sectors */
1129 	ret = scrub_setup_recheck_block(sblock_to_check, sblocks_for_recheck);
1130 	if (ret) {
1131 		spin_lock(&sctx->stat_lock);
1132 		sctx->stat.read_errors++;
1133 		sctx->stat.uncorrectable_errors++;
1134 		spin_unlock(&sctx->stat_lock);
1135 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1136 		goto out;
1137 	}
1138 	BUG_ON(failed_mirror_index >= BTRFS_MAX_MIRRORS);
1139 	sblock_bad = sblocks_for_recheck[failed_mirror_index];
1140 
1141 	/* build and submit the bios for the failed mirror, check checksums */
1142 	scrub_recheck_block(fs_info, sblock_bad, 1);
1143 
1144 	if (!sblock_bad->header_error && !sblock_bad->checksum_error &&
1145 	    sblock_bad->no_io_error_seen) {
1146 		/*
1147 		 * The error disappeared after reading sector by sector, or
1148 		 * the area was part of a huge bio and other parts of the
1149 		 * bio caused I/O errors, or the block layer merged several
1150 		 * read requests into one and the error is caused by a
1151 		 * different bio (usually one of the two latter cases is
1152 		 * the cause)
1153 		 */
1154 		spin_lock(&sctx->stat_lock);
1155 		sctx->stat.unverified_errors++;
1156 		sblock_to_check->data_corrected = 1;
1157 		spin_unlock(&sctx->stat_lock);
1158 
1159 		if (sctx->is_dev_replace)
1160 			scrub_write_block_to_dev_replace(sblock_bad);
1161 		goto out;
1162 	}
1163 
1164 	if (!sblock_bad->no_io_error_seen) {
1165 		spin_lock(&sctx->stat_lock);
1166 		sctx->stat.read_errors++;
1167 		spin_unlock(&sctx->stat_lock);
1168 		if (__ratelimit(&rs))
1169 			scrub_print_warning("i/o error", sblock_to_check);
1170 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1171 	} else if (sblock_bad->checksum_error) {
1172 		spin_lock(&sctx->stat_lock);
1173 		sctx->stat.csum_errors++;
1174 		spin_unlock(&sctx->stat_lock);
1175 		if (__ratelimit(&rs))
1176 			scrub_print_warning("checksum error", sblock_to_check);
1177 		btrfs_dev_stat_inc_and_print(dev,
1178 					     BTRFS_DEV_STAT_CORRUPTION_ERRS);
1179 	} else if (sblock_bad->header_error) {
1180 		spin_lock(&sctx->stat_lock);
1181 		sctx->stat.verify_errors++;
1182 		spin_unlock(&sctx->stat_lock);
1183 		if (__ratelimit(&rs))
1184 			scrub_print_warning("checksum/header error",
1185 					    sblock_to_check);
1186 		if (sblock_bad->generation_error)
1187 			btrfs_dev_stat_inc_and_print(dev,
1188 				BTRFS_DEV_STAT_GENERATION_ERRS);
1189 		else
1190 			btrfs_dev_stat_inc_and_print(dev,
1191 				BTRFS_DEV_STAT_CORRUPTION_ERRS);
1192 	}
1193 
1194 	if (sctx->readonly) {
1195 		ASSERT(!sctx->is_dev_replace);
1196 		goto out;
1197 	}
1198 
1199 	/*
1200 	 * now build and submit the bios for the other mirrors, check
1201 	 * checksums.
1202 	 * First try to pick the mirror which is completely without I/O
1203 	 * errors and also does not have a checksum error.
1204 	 * If one is found, and if a checksum is present, the full block
1205 	 * that is known to contain an error is rewritten. Afterwards
1206 	 * the block is known to be corrected.
1207 	 * If a mirror is found which is completely correct, and no
1208 	 * checksum is present, only those sectors are rewritten that had
1209 	 * an I/O error in the block to be repaired, since it cannot be
1210 	 * determined, which copy of the other sectors is better (and it
1211 	 * could happen otherwise that a correct sector would be
1212 	 * overwritten by a bad one).
1213 	 */
1214 	for (mirror_index = 0; ;mirror_index++) {
1215 		struct scrub_block *sblock_other;
1216 
1217 		if (mirror_index == failed_mirror_index)
1218 			continue;
1219 
1220 		/* raid56's mirror can be more than BTRFS_MAX_MIRRORS */
1221 		if (!scrub_is_page_on_raid56(sblock_bad->sectors[0])) {
1222 			if (mirror_index >= BTRFS_MAX_MIRRORS)
1223 				break;
1224 			if (!sblocks_for_recheck[mirror_index]->sector_count)
1225 				break;
1226 
1227 			sblock_other = sblocks_for_recheck[mirror_index];
1228 		} else {
1229 			struct scrub_recover *r = sblock_bad->sectors[0]->recover;
1230 			int max_allowed = r->bioc->num_stripes - r->bioc->num_tgtdevs;
1231 
1232 			if (mirror_index >= max_allowed)
1233 				break;
1234 			if (!sblocks_for_recheck[1]->sector_count)
1235 				break;
1236 
1237 			ASSERT(failed_mirror_index == 0);
1238 			sblock_other = sblocks_for_recheck[1];
1239 			sblock_other->mirror_num = 1 + mirror_index;
1240 		}
1241 
1242 		/* build and submit the bios, check checksums */
1243 		scrub_recheck_block(fs_info, sblock_other, 0);
1244 
1245 		if (!sblock_other->header_error &&
1246 		    !sblock_other->checksum_error &&
1247 		    sblock_other->no_io_error_seen) {
1248 			if (sctx->is_dev_replace) {
1249 				scrub_write_block_to_dev_replace(sblock_other);
1250 				goto corrected_error;
1251 			} else {
1252 				ret = scrub_repair_block_from_good_copy(
1253 						sblock_bad, sblock_other);
1254 				if (!ret)
1255 					goto corrected_error;
1256 			}
1257 		}
1258 	}
1259 
1260 	if (sblock_bad->no_io_error_seen && !sctx->is_dev_replace)
1261 		goto did_not_correct_error;
1262 
1263 	/*
1264 	 * In case of I/O errors in the area that is supposed to be
1265 	 * repaired, continue by picking good copies of those sectors.
1266 	 * Select the good sectors from mirrors to rewrite bad sectors from
1267 	 * the area to fix. Afterwards verify the checksum of the block
1268 	 * that is supposed to be repaired. This verification step is
1269 	 * only done for the purpose of statistic counting and for the
1270 	 * final scrub report, whether errors remain.
1271 	 * A perfect algorithm could make use of the checksum and try
1272 	 * all possible combinations of sectors from the different mirrors
1273 	 * until the checksum verification succeeds. For example, when
1274 	 * the 2nd sector of mirror #1 faces I/O errors, and the 2nd sector
1275 	 * of mirror #2 is readable but the final checksum test fails,
1276 	 * then the 2nd sector of mirror #3 could be tried, whether now
1277 	 * the final checksum succeeds. But this would be a rare
1278 	 * exception and is therefore not implemented. At least it is
1279 	 * avoided that the good copy is overwritten.
1280 	 * A more useful improvement would be to pick the sectors
1281 	 * without I/O error based on sector sizes (512 bytes on legacy
1282 	 * disks) instead of on sectorsize. Then maybe 512 byte of one
1283 	 * mirror could be repaired by taking 512 byte of a different
1284 	 * mirror, even if other 512 byte sectors in the same sectorsize
1285 	 * area are unreadable.
1286 	 */
1287 	success = 1;
1288 	for (sector_num = 0; sector_num < sblock_bad->sector_count;
1289 	     sector_num++) {
1290 		struct scrub_sector *sector_bad = sblock_bad->sectors[sector_num];
1291 		struct scrub_block *sblock_other = NULL;
1292 
1293 		/* Skip no-io-error sectors in scrub */
1294 		if (!sector_bad->io_error && !sctx->is_dev_replace)
1295 			continue;
1296 
1297 		if (scrub_is_page_on_raid56(sblock_bad->sectors[0])) {
1298 			/*
1299 			 * In case of dev replace, if raid56 rebuild process
1300 			 * didn't work out correct data, then copy the content
1301 			 * in sblock_bad to make sure target device is identical
1302 			 * to source device, instead of writing garbage data in
1303 			 * sblock_for_recheck array to target device.
1304 			 */
1305 			sblock_other = NULL;
1306 		} else if (sector_bad->io_error) {
1307 			/* Try to find no-io-error sector in mirrors */
1308 			for (mirror_index = 0;
1309 			     mirror_index < BTRFS_MAX_MIRRORS &&
1310 			     sblocks_for_recheck[mirror_index]->sector_count > 0;
1311 			     mirror_index++) {
1312 				if (!sblocks_for_recheck[mirror_index]->
1313 				    sectors[sector_num]->io_error) {
1314 					sblock_other = sblocks_for_recheck[mirror_index];
1315 					break;
1316 				}
1317 			}
1318 			if (!sblock_other)
1319 				success = 0;
1320 		}
1321 
1322 		if (sctx->is_dev_replace) {
1323 			/*
1324 			 * Did not find a mirror to fetch the sector from.
1325 			 * scrub_write_sector_to_dev_replace() handles this
1326 			 * case (sector->io_error), by filling the block with
1327 			 * zeros before submitting the write request
1328 			 */
1329 			if (!sblock_other)
1330 				sblock_other = sblock_bad;
1331 
1332 			if (scrub_write_sector_to_dev_replace(sblock_other,
1333 							      sector_num) != 0) {
1334 				atomic64_inc(
1335 					&fs_info->dev_replace.num_write_errors);
1336 				success = 0;
1337 			}
1338 		} else if (sblock_other) {
1339 			ret = scrub_repair_sector_from_good_copy(sblock_bad,
1340 								 sblock_other,
1341 								 sector_num, 0);
1342 			if (0 == ret)
1343 				sector_bad->io_error = 0;
1344 			else
1345 				success = 0;
1346 		}
1347 	}
1348 
1349 	if (success && !sctx->is_dev_replace) {
1350 		if (is_metadata || have_csum) {
1351 			/*
1352 			 * need to verify the checksum now that all
1353 			 * sectors on disk are repaired (the write
1354 			 * request for data to be repaired is on its way).
1355 			 * Just be lazy and use scrub_recheck_block()
1356 			 * which re-reads the data before the checksum
1357 			 * is verified, but most likely the data comes out
1358 			 * of the page cache.
1359 			 */
1360 			scrub_recheck_block(fs_info, sblock_bad, 1);
1361 			if (!sblock_bad->header_error &&
1362 			    !sblock_bad->checksum_error &&
1363 			    sblock_bad->no_io_error_seen)
1364 				goto corrected_error;
1365 			else
1366 				goto did_not_correct_error;
1367 		} else {
1368 corrected_error:
1369 			spin_lock(&sctx->stat_lock);
1370 			sctx->stat.corrected_errors++;
1371 			sblock_to_check->data_corrected = 1;
1372 			spin_unlock(&sctx->stat_lock);
1373 			btrfs_err_rl_in_rcu(fs_info,
1374 				"fixed up error at logical %llu on dev %s",
1375 				logical, rcu_str_deref(dev->name));
1376 		}
1377 	} else {
1378 did_not_correct_error:
1379 		spin_lock(&sctx->stat_lock);
1380 		sctx->stat.uncorrectable_errors++;
1381 		spin_unlock(&sctx->stat_lock);
1382 		btrfs_err_rl_in_rcu(fs_info,
1383 			"unable to fixup (regular) error at logical %llu on dev %s",
1384 			logical, rcu_str_deref(dev->name));
1385 	}
1386 
1387 out:
1388 	for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS; mirror_index++) {
1389 		struct scrub_block *sblock = sblocks_for_recheck[mirror_index];
1390 		struct scrub_recover *recover;
1391 		int sector_index;
1392 
1393 		/* Not allocated, continue checking the next mirror */
1394 		if (!sblock)
1395 			continue;
1396 
1397 		for (sector_index = 0; sector_index < sblock->sector_count;
1398 		     sector_index++) {
1399 			/*
1400 			 * Here we just cleanup the recover, each sector will be
1401 			 * properly cleaned up by later scrub_block_put()
1402 			 */
1403 			recover = sblock->sectors[sector_index]->recover;
1404 			if (recover) {
1405 				scrub_put_recover(fs_info, recover);
1406 				sblock->sectors[sector_index]->recover = NULL;
1407 			}
1408 		}
1409 		scrub_block_put(sblock);
1410 	}
1411 
1412 	ret = unlock_full_stripe(fs_info, logical, full_stripe_locked);
1413 	memalloc_nofs_restore(nofs_flag);
1414 	if (ret < 0)
1415 		return ret;
1416 	return 0;
1417 }
1418 
1419 static inline int scrub_nr_raid_mirrors(struct btrfs_io_context *bioc)
1420 {
1421 	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID5)
1422 		return 2;
1423 	else if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID6)
1424 		return 3;
1425 	else
1426 		return (int)bioc->num_stripes;
1427 }
1428 
1429 static inline void scrub_stripe_index_and_offset(u64 logical, u64 map_type,
1430 						 u64 *raid_map,
1431 						 int nstripes, int mirror,
1432 						 int *stripe_index,
1433 						 u64 *stripe_offset)
1434 {
1435 	int i;
1436 
1437 	if (map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
1438 		/* RAID5/6 */
1439 		for (i = 0; i < nstripes; i++) {
1440 			if (raid_map[i] == RAID6_Q_STRIPE ||
1441 			    raid_map[i] == RAID5_P_STRIPE)
1442 				continue;
1443 
1444 			if (logical >= raid_map[i] &&
1445 			    logical < raid_map[i] + BTRFS_STRIPE_LEN)
1446 				break;
1447 		}
1448 
1449 		*stripe_index = i;
1450 		*stripe_offset = logical - raid_map[i];
1451 	} else {
1452 		/* The other RAID type */
1453 		*stripe_index = mirror;
1454 		*stripe_offset = 0;
1455 	}
1456 }
1457 
1458 static int scrub_setup_recheck_block(struct scrub_block *original_sblock,
1459 				     struct scrub_block *sblocks_for_recheck[])
1460 {
1461 	struct scrub_ctx *sctx = original_sblock->sctx;
1462 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1463 	u64 logical = original_sblock->logical;
1464 	u64 length = original_sblock->sector_count << fs_info->sectorsize_bits;
1465 	u64 generation = original_sblock->sectors[0]->generation;
1466 	u64 flags = original_sblock->sectors[0]->flags;
1467 	u64 have_csum = original_sblock->sectors[0]->have_csum;
1468 	struct scrub_recover *recover;
1469 	struct btrfs_io_context *bioc;
1470 	u64 sublen;
1471 	u64 mapped_length;
1472 	u64 stripe_offset;
1473 	int stripe_index;
1474 	int sector_index = 0;
1475 	int mirror_index;
1476 	int nmirrors;
1477 	int ret;
1478 
1479 	while (length > 0) {
1480 		sublen = min_t(u64, length, fs_info->sectorsize);
1481 		mapped_length = sublen;
1482 		bioc = NULL;
1483 
1484 		/*
1485 		 * With a length of sectorsize, each returned stripe represents
1486 		 * one mirror
1487 		 */
1488 		btrfs_bio_counter_inc_blocked(fs_info);
1489 		ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
1490 				       logical, &mapped_length, &bioc);
1491 		if (ret || !bioc || mapped_length < sublen) {
1492 			btrfs_put_bioc(bioc);
1493 			btrfs_bio_counter_dec(fs_info);
1494 			return -EIO;
1495 		}
1496 
1497 		recover = kzalloc(sizeof(struct scrub_recover), GFP_KERNEL);
1498 		if (!recover) {
1499 			btrfs_put_bioc(bioc);
1500 			btrfs_bio_counter_dec(fs_info);
1501 			return -ENOMEM;
1502 		}
1503 
1504 		refcount_set(&recover->refs, 1);
1505 		recover->bioc = bioc;
1506 		recover->map_length = mapped_length;
1507 
1508 		ASSERT(sector_index < SCRUB_MAX_SECTORS_PER_BLOCK);
1509 
1510 		nmirrors = min(scrub_nr_raid_mirrors(bioc), BTRFS_MAX_MIRRORS);
1511 
1512 		for (mirror_index = 0; mirror_index < nmirrors;
1513 		     mirror_index++) {
1514 			struct scrub_block *sblock;
1515 			struct scrub_sector *sector;
1516 
1517 			sblock = sblocks_for_recheck[mirror_index];
1518 			sblock->sctx = sctx;
1519 
1520 			sector = alloc_scrub_sector(sblock, logical);
1521 			if (!sector) {
1522 				spin_lock(&sctx->stat_lock);
1523 				sctx->stat.malloc_errors++;
1524 				spin_unlock(&sctx->stat_lock);
1525 				scrub_put_recover(fs_info, recover);
1526 				return -ENOMEM;
1527 			}
1528 			sector->flags = flags;
1529 			sector->generation = generation;
1530 			sector->have_csum = have_csum;
1531 			if (have_csum)
1532 				memcpy(sector->csum,
1533 				       original_sblock->sectors[0]->csum,
1534 				       sctx->fs_info->csum_size);
1535 
1536 			scrub_stripe_index_and_offset(logical,
1537 						      bioc->map_type,
1538 						      bioc->raid_map,
1539 						      bioc->num_stripes -
1540 						      bioc->num_tgtdevs,
1541 						      mirror_index,
1542 						      &stripe_index,
1543 						      &stripe_offset);
1544 			/*
1545 			 * We're at the first sector, also populate @sblock
1546 			 * physical and dev.
1547 			 */
1548 			if (sector_index == 0) {
1549 				sblock->physical =
1550 					bioc->stripes[stripe_index].physical +
1551 					stripe_offset;
1552 				sblock->dev = bioc->stripes[stripe_index].dev;
1553 				sblock->physical_for_dev_replace =
1554 					original_sblock->physical_for_dev_replace;
1555 			}
1556 
1557 			BUG_ON(sector_index >= original_sblock->sector_count);
1558 			scrub_get_recover(recover);
1559 			sector->recover = recover;
1560 		}
1561 		scrub_put_recover(fs_info, recover);
1562 		length -= sublen;
1563 		logical += sublen;
1564 		sector_index++;
1565 	}
1566 
1567 	return 0;
1568 }
1569 
1570 static void scrub_bio_wait_endio(struct bio *bio)
1571 {
1572 	complete(bio->bi_private);
1573 }
1574 
1575 static int scrub_submit_raid56_bio_wait(struct btrfs_fs_info *fs_info,
1576 					struct bio *bio,
1577 					struct scrub_sector *sector)
1578 {
1579 	DECLARE_COMPLETION_ONSTACK(done);
1580 
1581 	bio->bi_iter.bi_sector = (sector->offset + sector->sblock->logical) >>
1582 				 SECTOR_SHIFT;
1583 	bio->bi_private = &done;
1584 	bio->bi_end_io = scrub_bio_wait_endio;
1585 	raid56_parity_recover(bio, sector->recover->bioc, sector->sblock->mirror_num);
1586 
1587 	wait_for_completion_io(&done);
1588 	return blk_status_to_errno(bio->bi_status);
1589 }
1590 
1591 static void scrub_recheck_block_on_raid56(struct btrfs_fs_info *fs_info,
1592 					  struct scrub_block *sblock)
1593 {
1594 	struct scrub_sector *first_sector = sblock->sectors[0];
1595 	struct bio *bio;
1596 	int i;
1597 
1598 	/* All sectors in sblock belong to the same stripe on the same device. */
1599 	ASSERT(sblock->dev);
1600 	if (!sblock->dev->bdev)
1601 		goto out;
1602 
1603 	bio = bio_alloc(sblock->dev->bdev, BIO_MAX_VECS, REQ_OP_READ, GFP_NOFS);
1604 
1605 	for (i = 0; i < sblock->sector_count; i++) {
1606 		struct scrub_sector *sector = sblock->sectors[i];
1607 
1608 		bio_add_scrub_sector(bio, sector, fs_info->sectorsize);
1609 	}
1610 
1611 	if (scrub_submit_raid56_bio_wait(fs_info, bio, first_sector)) {
1612 		bio_put(bio);
1613 		goto out;
1614 	}
1615 
1616 	bio_put(bio);
1617 
1618 	scrub_recheck_block_checksum(sblock);
1619 
1620 	return;
1621 out:
1622 	for (i = 0; i < sblock->sector_count; i++)
1623 		sblock->sectors[i]->io_error = 1;
1624 
1625 	sblock->no_io_error_seen = 0;
1626 }
1627 
1628 /*
1629  * This function will check the on disk data for checksum errors, header errors
1630  * and read I/O errors. If any I/O errors happen, the exact sectors which are
1631  * errored are marked as being bad. The goal is to enable scrub to take those
1632  * sectors that are not errored from all the mirrors so that the sectors that
1633  * are errored in the just handled mirror can be repaired.
1634  */
1635 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
1636 				struct scrub_block *sblock,
1637 				int retry_failed_mirror)
1638 {
1639 	int i;
1640 
1641 	sblock->no_io_error_seen = 1;
1642 
1643 	/* short cut for raid56 */
1644 	if (!retry_failed_mirror && scrub_is_page_on_raid56(sblock->sectors[0]))
1645 		return scrub_recheck_block_on_raid56(fs_info, sblock);
1646 
1647 	for (i = 0; i < sblock->sector_count; i++) {
1648 		struct scrub_sector *sector = sblock->sectors[i];
1649 		struct bio bio;
1650 		struct bio_vec bvec;
1651 
1652 		if (sblock->dev->bdev == NULL) {
1653 			sector->io_error = 1;
1654 			sblock->no_io_error_seen = 0;
1655 			continue;
1656 		}
1657 
1658 		bio_init(&bio, sblock->dev->bdev, &bvec, 1, REQ_OP_READ);
1659 		bio_add_scrub_sector(&bio, sector, fs_info->sectorsize);
1660 		bio.bi_iter.bi_sector = (sblock->physical + sector->offset) >>
1661 					SECTOR_SHIFT;
1662 
1663 		btrfsic_check_bio(&bio);
1664 		if (submit_bio_wait(&bio)) {
1665 			sector->io_error = 1;
1666 			sblock->no_io_error_seen = 0;
1667 		}
1668 
1669 		bio_uninit(&bio);
1670 	}
1671 
1672 	if (sblock->no_io_error_seen)
1673 		scrub_recheck_block_checksum(sblock);
1674 }
1675 
1676 static inline int scrub_check_fsid(u8 fsid[], struct scrub_sector *sector)
1677 {
1678 	struct btrfs_fs_devices *fs_devices = sector->sblock->dev->fs_devices;
1679 	int ret;
1680 
1681 	ret = memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1682 	return !ret;
1683 }
1684 
1685 static void scrub_recheck_block_checksum(struct scrub_block *sblock)
1686 {
1687 	sblock->header_error = 0;
1688 	sblock->checksum_error = 0;
1689 	sblock->generation_error = 0;
1690 
1691 	if (sblock->sectors[0]->flags & BTRFS_EXTENT_FLAG_DATA)
1692 		scrub_checksum_data(sblock);
1693 	else
1694 		scrub_checksum_tree_block(sblock);
1695 }
1696 
1697 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
1698 					     struct scrub_block *sblock_good)
1699 {
1700 	int i;
1701 	int ret = 0;
1702 
1703 	for (i = 0; i < sblock_bad->sector_count; i++) {
1704 		int ret_sub;
1705 
1706 		ret_sub = scrub_repair_sector_from_good_copy(sblock_bad,
1707 							     sblock_good, i, 1);
1708 		if (ret_sub)
1709 			ret = ret_sub;
1710 	}
1711 
1712 	return ret;
1713 }
1714 
1715 static int scrub_repair_sector_from_good_copy(struct scrub_block *sblock_bad,
1716 					      struct scrub_block *sblock_good,
1717 					      int sector_num, int force_write)
1718 {
1719 	struct scrub_sector *sector_bad = sblock_bad->sectors[sector_num];
1720 	struct scrub_sector *sector_good = sblock_good->sectors[sector_num];
1721 	struct btrfs_fs_info *fs_info = sblock_bad->sctx->fs_info;
1722 	const u32 sectorsize = fs_info->sectorsize;
1723 
1724 	if (force_write || sblock_bad->header_error ||
1725 	    sblock_bad->checksum_error || sector_bad->io_error) {
1726 		struct bio bio;
1727 		struct bio_vec bvec;
1728 		int ret;
1729 
1730 		if (!sblock_bad->dev->bdev) {
1731 			btrfs_warn_rl(fs_info,
1732 				"scrub_repair_page_from_good_copy(bdev == NULL) is unexpected");
1733 			return -EIO;
1734 		}
1735 
1736 		bio_init(&bio, sblock_bad->dev->bdev, &bvec, 1, REQ_OP_WRITE);
1737 		bio.bi_iter.bi_sector = (sblock_bad->physical +
1738 					 sector_bad->offset) >> SECTOR_SHIFT;
1739 		ret = bio_add_scrub_sector(&bio, sector_good, sectorsize);
1740 
1741 		btrfsic_check_bio(&bio);
1742 		ret = submit_bio_wait(&bio);
1743 		bio_uninit(&bio);
1744 
1745 		if (ret) {
1746 			btrfs_dev_stat_inc_and_print(sblock_bad->dev,
1747 				BTRFS_DEV_STAT_WRITE_ERRS);
1748 			atomic64_inc(&fs_info->dev_replace.num_write_errors);
1749 			return -EIO;
1750 		}
1751 	}
1752 
1753 	return 0;
1754 }
1755 
1756 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock)
1757 {
1758 	struct btrfs_fs_info *fs_info = sblock->sctx->fs_info;
1759 	int i;
1760 
1761 	/*
1762 	 * This block is used for the check of the parity on the source device,
1763 	 * so the data needn't be written into the destination device.
1764 	 */
1765 	if (sblock->sparity)
1766 		return;
1767 
1768 	for (i = 0; i < sblock->sector_count; i++) {
1769 		int ret;
1770 
1771 		ret = scrub_write_sector_to_dev_replace(sblock, i);
1772 		if (ret)
1773 			atomic64_inc(&fs_info->dev_replace.num_write_errors);
1774 	}
1775 }
1776 
1777 static int scrub_write_sector_to_dev_replace(struct scrub_block *sblock, int sector_num)
1778 {
1779 	const u32 sectorsize = sblock->sctx->fs_info->sectorsize;
1780 	struct scrub_sector *sector = sblock->sectors[sector_num];
1781 
1782 	if (sector->io_error)
1783 		memset(scrub_sector_get_kaddr(sector), 0, sectorsize);
1784 
1785 	return scrub_add_sector_to_wr_bio(sblock->sctx, sector);
1786 }
1787 
1788 static int fill_writer_pointer_gap(struct scrub_ctx *sctx, u64 physical)
1789 {
1790 	int ret = 0;
1791 	u64 length;
1792 
1793 	if (!btrfs_is_zoned(sctx->fs_info))
1794 		return 0;
1795 
1796 	if (!btrfs_dev_is_sequential(sctx->wr_tgtdev, physical))
1797 		return 0;
1798 
1799 	if (sctx->write_pointer < physical) {
1800 		length = physical - sctx->write_pointer;
1801 
1802 		ret = btrfs_zoned_issue_zeroout(sctx->wr_tgtdev,
1803 						sctx->write_pointer, length);
1804 		if (!ret)
1805 			sctx->write_pointer = physical;
1806 	}
1807 	return ret;
1808 }
1809 
1810 static void scrub_block_get(struct scrub_block *sblock)
1811 {
1812 	refcount_inc(&sblock->refs);
1813 }
1814 
1815 static int scrub_add_sector_to_wr_bio(struct scrub_ctx *sctx,
1816 				      struct scrub_sector *sector)
1817 {
1818 	struct scrub_block *sblock = sector->sblock;
1819 	struct scrub_bio *sbio;
1820 	int ret;
1821 	const u32 sectorsize = sctx->fs_info->sectorsize;
1822 
1823 	mutex_lock(&sctx->wr_lock);
1824 again:
1825 	if (!sctx->wr_curr_bio) {
1826 		sctx->wr_curr_bio = kzalloc(sizeof(*sctx->wr_curr_bio),
1827 					      GFP_KERNEL);
1828 		if (!sctx->wr_curr_bio) {
1829 			mutex_unlock(&sctx->wr_lock);
1830 			return -ENOMEM;
1831 		}
1832 		sctx->wr_curr_bio->sctx = sctx;
1833 		sctx->wr_curr_bio->sector_count = 0;
1834 	}
1835 	sbio = sctx->wr_curr_bio;
1836 	if (sbio->sector_count == 0) {
1837 		ret = fill_writer_pointer_gap(sctx, sector->offset +
1838 					      sblock->physical_for_dev_replace);
1839 		if (ret) {
1840 			mutex_unlock(&sctx->wr_lock);
1841 			return ret;
1842 		}
1843 
1844 		sbio->physical = sblock->physical_for_dev_replace + sector->offset;
1845 		sbio->logical = sblock->logical + sector->offset;
1846 		sbio->dev = sctx->wr_tgtdev;
1847 		if (!sbio->bio) {
1848 			sbio->bio = bio_alloc(sbio->dev->bdev, sctx->sectors_per_bio,
1849 					      REQ_OP_WRITE, GFP_NOFS);
1850 		}
1851 		sbio->bio->bi_private = sbio;
1852 		sbio->bio->bi_end_io = scrub_wr_bio_end_io;
1853 		sbio->bio->bi_iter.bi_sector = sbio->physical >> 9;
1854 		sbio->status = 0;
1855 	} else if (sbio->physical + sbio->sector_count * sectorsize !=
1856 		   sblock->physical_for_dev_replace + sector->offset ||
1857 		   sbio->logical + sbio->sector_count * sectorsize !=
1858 		   sblock->logical + sector->offset) {
1859 		scrub_wr_submit(sctx);
1860 		goto again;
1861 	}
1862 
1863 	ret = bio_add_scrub_sector(sbio->bio, sector, sectorsize);
1864 	if (ret != sectorsize) {
1865 		if (sbio->sector_count < 1) {
1866 			bio_put(sbio->bio);
1867 			sbio->bio = NULL;
1868 			mutex_unlock(&sctx->wr_lock);
1869 			return -EIO;
1870 		}
1871 		scrub_wr_submit(sctx);
1872 		goto again;
1873 	}
1874 
1875 	sbio->sectors[sbio->sector_count] = sector;
1876 	scrub_sector_get(sector);
1877 	/*
1878 	 * Since ssector no longer holds a page, but uses sblock::pages, we
1879 	 * have to ensure the sblock had not been freed before our write bio
1880 	 * finished.
1881 	 */
1882 	scrub_block_get(sector->sblock);
1883 
1884 	sbio->sector_count++;
1885 	if (sbio->sector_count == sctx->sectors_per_bio)
1886 		scrub_wr_submit(sctx);
1887 	mutex_unlock(&sctx->wr_lock);
1888 
1889 	return 0;
1890 }
1891 
1892 static void scrub_wr_submit(struct scrub_ctx *sctx)
1893 {
1894 	struct scrub_bio *sbio;
1895 
1896 	if (!sctx->wr_curr_bio)
1897 		return;
1898 
1899 	sbio = sctx->wr_curr_bio;
1900 	sctx->wr_curr_bio = NULL;
1901 	scrub_pending_bio_inc(sctx);
1902 	/* process all writes in a single worker thread. Then the block layer
1903 	 * orders the requests before sending them to the driver which
1904 	 * doubled the write performance on spinning disks when measured
1905 	 * with Linux 3.5 */
1906 	btrfsic_check_bio(sbio->bio);
1907 	submit_bio(sbio->bio);
1908 
1909 	if (btrfs_is_zoned(sctx->fs_info))
1910 		sctx->write_pointer = sbio->physical + sbio->sector_count *
1911 			sctx->fs_info->sectorsize;
1912 }
1913 
1914 static void scrub_wr_bio_end_io(struct bio *bio)
1915 {
1916 	struct scrub_bio *sbio = bio->bi_private;
1917 	struct btrfs_fs_info *fs_info = sbio->dev->fs_info;
1918 
1919 	sbio->status = bio->bi_status;
1920 	sbio->bio = bio;
1921 
1922 	INIT_WORK(&sbio->work, scrub_wr_bio_end_io_worker);
1923 	queue_work(fs_info->scrub_wr_completion_workers, &sbio->work);
1924 }
1925 
1926 static void scrub_wr_bio_end_io_worker(struct work_struct *work)
1927 {
1928 	struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
1929 	struct scrub_ctx *sctx = sbio->sctx;
1930 	int i;
1931 
1932 	ASSERT(sbio->sector_count <= SCRUB_SECTORS_PER_BIO);
1933 	if (sbio->status) {
1934 		struct btrfs_dev_replace *dev_replace =
1935 			&sbio->sctx->fs_info->dev_replace;
1936 
1937 		for (i = 0; i < sbio->sector_count; i++) {
1938 			struct scrub_sector *sector = sbio->sectors[i];
1939 
1940 			sector->io_error = 1;
1941 			atomic64_inc(&dev_replace->num_write_errors);
1942 		}
1943 	}
1944 
1945 	/*
1946 	 * In scrub_add_sector_to_wr_bio() we grab extra ref for sblock, now in
1947 	 * endio we should put the sblock.
1948 	 */
1949 	for (i = 0; i < sbio->sector_count; i++) {
1950 		scrub_block_put(sbio->sectors[i]->sblock);
1951 		scrub_sector_put(sbio->sectors[i]);
1952 	}
1953 
1954 	bio_put(sbio->bio);
1955 	kfree(sbio);
1956 	scrub_pending_bio_dec(sctx);
1957 }
1958 
1959 static int scrub_checksum(struct scrub_block *sblock)
1960 {
1961 	u64 flags;
1962 	int ret;
1963 
1964 	/*
1965 	 * No need to initialize these stats currently,
1966 	 * because this function only use return value
1967 	 * instead of these stats value.
1968 	 *
1969 	 * Todo:
1970 	 * always use stats
1971 	 */
1972 	sblock->header_error = 0;
1973 	sblock->generation_error = 0;
1974 	sblock->checksum_error = 0;
1975 
1976 	WARN_ON(sblock->sector_count < 1);
1977 	flags = sblock->sectors[0]->flags;
1978 	ret = 0;
1979 	if (flags & BTRFS_EXTENT_FLAG_DATA)
1980 		ret = scrub_checksum_data(sblock);
1981 	else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1982 		ret = scrub_checksum_tree_block(sblock);
1983 	else if (flags & BTRFS_EXTENT_FLAG_SUPER)
1984 		ret = scrub_checksum_super(sblock);
1985 	else
1986 		WARN_ON(1);
1987 	if (ret)
1988 		scrub_handle_errored_block(sblock);
1989 
1990 	return ret;
1991 }
1992 
1993 static int scrub_checksum_data(struct scrub_block *sblock)
1994 {
1995 	struct scrub_ctx *sctx = sblock->sctx;
1996 	struct btrfs_fs_info *fs_info = sctx->fs_info;
1997 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
1998 	u8 csum[BTRFS_CSUM_SIZE];
1999 	struct scrub_sector *sector;
2000 	char *kaddr;
2001 
2002 	BUG_ON(sblock->sector_count < 1);
2003 	sector = sblock->sectors[0];
2004 	if (!sector->have_csum)
2005 		return 0;
2006 
2007 	kaddr = scrub_sector_get_kaddr(sector);
2008 
2009 	shash->tfm = fs_info->csum_shash;
2010 	crypto_shash_init(shash);
2011 
2012 	crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
2013 
2014 	if (memcmp(csum, sector->csum, fs_info->csum_size))
2015 		sblock->checksum_error = 1;
2016 	return sblock->checksum_error;
2017 }
2018 
2019 static int scrub_checksum_tree_block(struct scrub_block *sblock)
2020 {
2021 	struct scrub_ctx *sctx = sblock->sctx;
2022 	struct btrfs_header *h;
2023 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2024 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2025 	u8 calculated_csum[BTRFS_CSUM_SIZE];
2026 	u8 on_disk_csum[BTRFS_CSUM_SIZE];
2027 	/*
2028 	 * This is done in sectorsize steps even for metadata as there's a
2029 	 * constraint for nodesize to be aligned to sectorsize. This will need
2030 	 * to change so we don't misuse data and metadata units like that.
2031 	 */
2032 	const u32 sectorsize = sctx->fs_info->sectorsize;
2033 	const int num_sectors = fs_info->nodesize >> fs_info->sectorsize_bits;
2034 	int i;
2035 	struct scrub_sector *sector;
2036 	char *kaddr;
2037 
2038 	BUG_ON(sblock->sector_count < 1);
2039 
2040 	/* Each member in sectors is just one sector */
2041 	ASSERT(sblock->sector_count == num_sectors);
2042 
2043 	sector = sblock->sectors[0];
2044 	kaddr = scrub_sector_get_kaddr(sector);
2045 	h = (struct btrfs_header *)kaddr;
2046 	memcpy(on_disk_csum, h->csum, sctx->fs_info->csum_size);
2047 
2048 	/*
2049 	 * we don't use the getter functions here, as we
2050 	 * a) don't have an extent buffer and
2051 	 * b) the page is already kmapped
2052 	 */
2053 	if (sblock->logical != btrfs_stack_header_bytenr(h))
2054 		sblock->header_error = 1;
2055 
2056 	if (sector->generation != btrfs_stack_header_generation(h)) {
2057 		sblock->header_error = 1;
2058 		sblock->generation_error = 1;
2059 	}
2060 
2061 	if (!scrub_check_fsid(h->fsid, sector))
2062 		sblock->header_error = 1;
2063 
2064 	if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
2065 		   BTRFS_UUID_SIZE))
2066 		sblock->header_error = 1;
2067 
2068 	shash->tfm = fs_info->csum_shash;
2069 	crypto_shash_init(shash);
2070 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
2071 			    sectorsize - BTRFS_CSUM_SIZE);
2072 
2073 	for (i = 1; i < num_sectors; i++) {
2074 		kaddr = scrub_sector_get_kaddr(sblock->sectors[i]);
2075 		crypto_shash_update(shash, kaddr, sectorsize);
2076 	}
2077 
2078 	crypto_shash_final(shash, calculated_csum);
2079 	if (memcmp(calculated_csum, on_disk_csum, sctx->fs_info->csum_size))
2080 		sblock->checksum_error = 1;
2081 
2082 	return sblock->header_error || sblock->checksum_error;
2083 }
2084 
2085 static int scrub_checksum_super(struct scrub_block *sblock)
2086 {
2087 	struct btrfs_super_block *s;
2088 	struct scrub_ctx *sctx = sblock->sctx;
2089 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2090 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2091 	u8 calculated_csum[BTRFS_CSUM_SIZE];
2092 	struct scrub_sector *sector;
2093 	char *kaddr;
2094 	int fail_gen = 0;
2095 	int fail_cor = 0;
2096 
2097 	BUG_ON(sblock->sector_count < 1);
2098 	sector = sblock->sectors[0];
2099 	kaddr = scrub_sector_get_kaddr(sector);
2100 	s = (struct btrfs_super_block *)kaddr;
2101 
2102 	if (sblock->logical != btrfs_super_bytenr(s))
2103 		++fail_cor;
2104 
2105 	if (sector->generation != btrfs_super_generation(s))
2106 		++fail_gen;
2107 
2108 	if (!scrub_check_fsid(s->fsid, sector))
2109 		++fail_cor;
2110 
2111 	shash->tfm = fs_info->csum_shash;
2112 	crypto_shash_init(shash);
2113 	crypto_shash_digest(shash, kaddr + BTRFS_CSUM_SIZE,
2114 			BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, calculated_csum);
2115 
2116 	if (memcmp(calculated_csum, s->csum, sctx->fs_info->csum_size))
2117 		++fail_cor;
2118 
2119 	return fail_cor + fail_gen;
2120 }
2121 
2122 static void scrub_block_put(struct scrub_block *sblock)
2123 {
2124 	if (refcount_dec_and_test(&sblock->refs)) {
2125 		int i;
2126 
2127 		if (sblock->sparity)
2128 			scrub_parity_put(sblock->sparity);
2129 
2130 		for (i = 0; i < sblock->sector_count; i++)
2131 			scrub_sector_put(sblock->sectors[i]);
2132 		for (i = 0; i < DIV_ROUND_UP(sblock->len, PAGE_SIZE); i++) {
2133 			if (sblock->pages[i]) {
2134 				detach_scrub_page_private(sblock->pages[i]);
2135 				__free_page(sblock->pages[i]);
2136 			}
2137 		}
2138 		kfree(sblock);
2139 	}
2140 }
2141 
2142 static void scrub_sector_get(struct scrub_sector *sector)
2143 {
2144 	atomic_inc(&sector->refs);
2145 }
2146 
2147 static void scrub_sector_put(struct scrub_sector *sector)
2148 {
2149 	if (atomic_dec_and_test(&sector->refs))
2150 		kfree(sector);
2151 }
2152 
2153 /*
2154  * Throttling of IO submission, bandwidth-limit based, the timeslice is 1
2155  * second.  Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max.
2156  */
2157 static void scrub_throttle(struct scrub_ctx *sctx)
2158 {
2159 	const int time_slice = 1000;
2160 	struct scrub_bio *sbio;
2161 	struct btrfs_device *device;
2162 	s64 delta;
2163 	ktime_t now;
2164 	u32 div;
2165 	u64 bwlimit;
2166 
2167 	sbio = sctx->bios[sctx->curr];
2168 	device = sbio->dev;
2169 	bwlimit = READ_ONCE(device->scrub_speed_max);
2170 	if (bwlimit == 0)
2171 		return;
2172 
2173 	/*
2174 	 * Slice is divided into intervals when the IO is submitted, adjust by
2175 	 * bwlimit and maximum of 64 intervals.
2176 	 */
2177 	div = max_t(u32, 1, (u32)(bwlimit / (16 * 1024 * 1024)));
2178 	div = min_t(u32, 64, div);
2179 
2180 	/* Start new epoch, set deadline */
2181 	now = ktime_get();
2182 	if (sctx->throttle_deadline == 0) {
2183 		sctx->throttle_deadline = ktime_add_ms(now, time_slice / div);
2184 		sctx->throttle_sent = 0;
2185 	}
2186 
2187 	/* Still in the time to send? */
2188 	if (ktime_before(now, sctx->throttle_deadline)) {
2189 		/* If current bio is within the limit, send it */
2190 		sctx->throttle_sent += sbio->bio->bi_iter.bi_size;
2191 		if (sctx->throttle_sent <= div_u64(bwlimit, div))
2192 			return;
2193 
2194 		/* We're over the limit, sleep until the rest of the slice */
2195 		delta = ktime_ms_delta(sctx->throttle_deadline, now);
2196 	} else {
2197 		/* New request after deadline, start new epoch */
2198 		delta = 0;
2199 	}
2200 
2201 	if (delta) {
2202 		long timeout;
2203 
2204 		timeout = div_u64(delta * HZ, 1000);
2205 		schedule_timeout_interruptible(timeout);
2206 	}
2207 
2208 	/* Next call will start the deadline period */
2209 	sctx->throttle_deadline = 0;
2210 }
2211 
2212 static void scrub_submit(struct scrub_ctx *sctx)
2213 {
2214 	struct scrub_bio *sbio;
2215 
2216 	if (sctx->curr == -1)
2217 		return;
2218 
2219 	scrub_throttle(sctx);
2220 
2221 	sbio = sctx->bios[sctx->curr];
2222 	sctx->curr = -1;
2223 	scrub_pending_bio_inc(sctx);
2224 	btrfsic_check_bio(sbio->bio);
2225 	submit_bio(sbio->bio);
2226 }
2227 
2228 static int scrub_add_sector_to_rd_bio(struct scrub_ctx *sctx,
2229 				      struct scrub_sector *sector)
2230 {
2231 	struct scrub_block *sblock = sector->sblock;
2232 	struct scrub_bio *sbio;
2233 	const u32 sectorsize = sctx->fs_info->sectorsize;
2234 	int ret;
2235 
2236 again:
2237 	/*
2238 	 * grab a fresh bio or wait for one to become available
2239 	 */
2240 	while (sctx->curr == -1) {
2241 		spin_lock(&sctx->list_lock);
2242 		sctx->curr = sctx->first_free;
2243 		if (sctx->curr != -1) {
2244 			sctx->first_free = sctx->bios[sctx->curr]->next_free;
2245 			sctx->bios[sctx->curr]->next_free = -1;
2246 			sctx->bios[sctx->curr]->sector_count = 0;
2247 			spin_unlock(&sctx->list_lock);
2248 		} else {
2249 			spin_unlock(&sctx->list_lock);
2250 			wait_event(sctx->list_wait, sctx->first_free != -1);
2251 		}
2252 	}
2253 	sbio = sctx->bios[sctx->curr];
2254 	if (sbio->sector_count == 0) {
2255 		sbio->physical = sblock->physical + sector->offset;
2256 		sbio->logical = sblock->logical + sector->offset;
2257 		sbio->dev = sblock->dev;
2258 		if (!sbio->bio) {
2259 			sbio->bio = bio_alloc(sbio->dev->bdev, sctx->sectors_per_bio,
2260 					      REQ_OP_READ, GFP_NOFS);
2261 		}
2262 		sbio->bio->bi_private = sbio;
2263 		sbio->bio->bi_end_io = scrub_bio_end_io;
2264 		sbio->bio->bi_iter.bi_sector = sbio->physical >> 9;
2265 		sbio->status = 0;
2266 	} else if (sbio->physical + sbio->sector_count * sectorsize !=
2267 		   sblock->physical + sector->offset ||
2268 		   sbio->logical + sbio->sector_count * sectorsize !=
2269 		   sblock->logical + sector->offset ||
2270 		   sbio->dev != sblock->dev) {
2271 		scrub_submit(sctx);
2272 		goto again;
2273 	}
2274 
2275 	sbio->sectors[sbio->sector_count] = sector;
2276 	ret = bio_add_scrub_sector(sbio->bio, sector, sectorsize);
2277 	if (ret != sectorsize) {
2278 		if (sbio->sector_count < 1) {
2279 			bio_put(sbio->bio);
2280 			sbio->bio = NULL;
2281 			return -EIO;
2282 		}
2283 		scrub_submit(sctx);
2284 		goto again;
2285 	}
2286 
2287 	scrub_block_get(sblock); /* one for the page added to the bio */
2288 	atomic_inc(&sblock->outstanding_sectors);
2289 	sbio->sector_count++;
2290 	if (sbio->sector_count == sctx->sectors_per_bio)
2291 		scrub_submit(sctx);
2292 
2293 	return 0;
2294 }
2295 
2296 static void scrub_missing_raid56_end_io(struct bio *bio)
2297 {
2298 	struct scrub_block *sblock = bio->bi_private;
2299 	struct btrfs_fs_info *fs_info = sblock->sctx->fs_info;
2300 
2301 	btrfs_bio_counter_dec(fs_info);
2302 	if (bio->bi_status)
2303 		sblock->no_io_error_seen = 0;
2304 
2305 	bio_put(bio);
2306 
2307 	queue_work(fs_info->scrub_workers, &sblock->work);
2308 }
2309 
2310 static void scrub_missing_raid56_worker(struct work_struct *work)
2311 {
2312 	struct scrub_block *sblock = container_of(work, struct scrub_block, work);
2313 	struct scrub_ctx *sctx = sblock->sctx;
2314 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2315 	u64 logical;
2316 	struct btrfs_device *dev;
2317 
2318 	logical = sblock->logical;
2319 	dev = sblock->dev;
2320 
2321 	if (sblock->no_io_error_seen)
2322 		scrub_recheck_block_checksum(sblock);
2323 
2324 	if (!sblock->no_io_error_seen) {
2325 		spin_lock(&sctx->stat_lock);
2326 		sctx->stat.read_errors++;
2327 		spin_unlock(&sctx->stat_lock);
2328 		btrfs_err_rl_in_rcu(fs_info,
2329 			"IO error rebuilding logical %llu for dev %s",
2330 			logical, rcu_str_deref(dev->name));
2331 	} else if (sblock->header_error || sblock->checksum_error) {
2332 		spin_lock(&sctx->stat_lock);
2333 		sctx->stat.uncorrectable_errors++;
2334 		spin_unlock(&sctx->stat_lock);
2335 		btrfs_err_rl_in_rcu(fs_info,
2336 			"failed to rebuild valid logical %llu for dev %s",
2337 			logical, rcu_str_deref(dev->name));
2338 	} else {
2339 		scrub_write_block_to_dev_replace(sblock);
2340 	}
2341 
2342 	if (sctx->is_dev_replace && sctx->flush_all_writes) {
2343 		mutex_lock(&sctx->wr_lock);
2344 		scrub_wr_submit(sctx);
2345 		mutex_unlock(&sctx->wr_lock);
2346 	}
2347 
2348 	scrub_block_put(sblock);
2349 	scrub_pending_bio_dec(sctx);
2350 }
2351 
2352 static void scrub_missing_raid56_pages(struct scrub_block *sblock)
2353 {
2354 	struct scrub_ctx *sctx = sblock->sctx;
2355 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2356 	u64 length = sblock->sector_count << fs_info->sectorsize_bits;
2357 	u64 logical = sblock->logical;
2358 	struct btrfs_io_context *bioc = NULL;
2359 	struct bio *bio;
2360 	struct btrfs_raid_bio *rbio;
2361 	int ret;
2362 	int i;
2363 
2364 	btrfs_bio_counter_inc_blocked(fs_info);
2365 	ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
2366 			       &length, &bioc);
2367 	if (ret || !bioc || !bioc->raid_map)
2368 		goto bioc_out;
2369 
2370 	if (WARN_ON(!sctx->is_dev_replace ||
2371 		    !(bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK))) {
2372 		/*
2373 		 * We shouldn't be scrubbing a missing device. Even for dev
2374 		 * replace, we should only get here for RAID 5/6. We either
2375 		 * managed to mount something with no mirrors remaining or
2376 		 * there's a bug in scrub_find_good_copy()/btrfs_map_block().
2377 		 */
2378 		goto bioc_out;
2379 	}
2380 
2381 	bio = bio_alloc(NULL, BIO_MAX_VECS, REQ_OP_READ, GFP_NOFS);
2382 	bio->bi_iter.bi_sector = logical >> 9;
2383 	bio->bi_private = sblock;
2384 	bio->bi_end_io = scrub_missing_raid56_end_io;
2385 
2386 	rbio = raid56_alloc_missing_rbio(bio, bioc);
2387 	if (!rbio)
2388 		goto rbio_out;
2389 
2390 	for (i = 0; i < sblock->sector_count; i++) {
2391 		struct scrub_sector *sector = sblock->sectors[i];
2392 
2393 		raid56_add_scrub_pages(rbio, scrub_sector_get_page(sector),
2394 				       scrub_sector_get_page_offset(sector),
2395 				       sector->offset + sector->sblock->logical);
2396 	}
2397 
2398 	INIT_WORK(&sblock->work, scrub_missing_raid56_worker);
2399 	scrub_block_get(sblock);
2400 	scrub_pending_bio_inc(sctx);
2401 	raid56_submit_missing_rbio(rbio);
2402 	btrfs_put_bioc(bioc);
2403 	return;
2404 
2405 rbio_out:
2406 	bio_put(bio);
2407 bioc_out:
2408 	btrfs_bio_counter_dec(fs_info);
2409 	btrfs_put_bioc(bioc);
2410 	spin_lock(&sctx->stat_lock);
2411 	sctx->stat.malloc_errors++;
2412 	spin_unlock(&sctx->stat_lock);
2413 }
2414 
2415 static int scrub_sectors(struct scrub_ctx *sctx, u64 logical, u32 len,
2416 		       u64 physical, struct btrfs_device *dev, u64 flags,
2417 		       u64 gen, int mirror_num, u8 *csum,
2418 		       u64 physical_for_dev_replace)
2419 {
2420 	struct scrub_block *sblock;
2421 	const u32 sectorsize = sctx->fs_info->sectorsize;
2422 	int index;
2423 
2424 	sblock = alloc_scrub_block(sctx, dev, logical, physical,
2425 				   physical_for_dev_replace, mirror_num);
2426 	if (!sblock) {
2427 		spin_lock(&sctx->stat_lock);
2428 		sctx->stat.malloc_errors++;
2429 		spin_unlock(&sctx->stat_lock);
2430 		return -ENOMEM;
2431 	}
2432 
2433 	for (index = 0; len > 0; index++) {
2434 		struct scrub_sector *sector;
2435 		/*
2436 		 * Here we will allocate one page for one sector to scrub.
2437 		 * This is fine if PAGE_SIZE == sectorsize, but will cost
2438 		 * more memory for PAGE_SIZE > sectorsize case.
2439 		 */
2440 		u32 l = min(sectorsize, len);
2441 
2442 		sector = alloc_scrub_sector(sblock, logical);
2443 		if (!sector) {
2444 			spin_lock(&sctx->stat_lock);
2445 			sctx->stat.malloc_errors++;
2446 			spin_unlock(&sctx->stat_lock);
2447 			scrub_block_put(sblock);
2448 			return -ENOMEM;
2449 		}
2450 		sector->flags = flags;
2451 		sector->generation = gen;
2452 		if (csum) {
2453 			sector->have_csum = 1;
2454 			memcpy(sector->csum, csum, sctx->fs_info->csum_size);
2455 		} else {
2456 			sector->have_csum = 0;
2457 		}
2458 		len -= l;
2459 		logical += l;
2460 		physical += l;
2461 		physical_for_dev_replace += l;
2462 	}
2463 
2464 	WARN_ON(sblock->sector_count == 0);
2465 	if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) {
2466 		/*
2467 		 * This case should only be hit for RAID 5/6 device replace. See
2468 		 * the comment in scrub_missing_raid56_pages() for details.
2469 		 */
2470 		scrub_missing_raid56_pages(sblock);
2471 	} else {
2472 		for (index = 0; index < sblock->sector_count; index++) {
2473 			struct scrub_sector *sector = sblock->sectors[index];
2474 			int ret;
2475 
2476 			ret = scrub_add_sector_to_rd_bio(sctx, sector);
2477 			if (ret) {
2478 				scrub_block_put(sblock);
2479 				return ret;
2480 			}
2481 		}
2482 
2483 		if (flags & BTRFS_EXTENT_FLAG_SUPER)
2484 			scrub_submit(sctx);
2485 	}
2486 
2487 	/* last one frees, either here or in bio completion for last page */
2488 	scrub_block_put(sblock);
2489 	return 0;
2490 }
2491 
2492 static void scrub_bio_end_io(struct bio *bio)
2493 {
2494 	struct scrub_bio *sbio = bio->bi_private;
2495 	struct btrfs_fs_info *fs_info = sbio->dev->fs_info;
2496 
2497 	sbio->status = bio->bi_status;
2498 	sbio->bio = bio;
2499 
2500 	queue_work(fs_info->scrub_workers, &sbio->work);
2501 }
2502 
2503 static void scrub_bio_end_io_worker(struct work_struct *work)
2504 {
2505 	struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
2506 	struct scrub_ctx *sctx = sbio->sctx;
2507 	int i;
2508 
2509 	ASSERT(sbio->sector_count <= SCRUB_SECTORS_PER_BIO);
2510 	if (sbio->status) {
2511 		for (i = 0; i < sbio->sector_count; i++) {
2512 			struct scrub_sector *sector = sbio->sectors[i];
2513 
2514 			sector->io_error = 1;
2515 			sector->sblock->no_io_error_seen = 0;
2516 		}
2517 	}
2518 
2519 	/* Now complete the scrub_block items that have all pages completed */
2520 	for (i = 0; i < sbio->sector_count; i++) {
2521 		struct scrub_sector *sector = sbio->sectors[i];
2522 		struct scrub_block *sblock = sector->sblock;
2523 
2524 		if (atomic_dec_and_test(&sblock->outstanding_sectors))
2525 			scrub_block_complete(sblock);
2526 		scrub_block_put(sblock);
2527 	}
2528 
2529 	bio_put(sbio->bio);
2530 	sbio->bio = NULL;
2531 	spin_lock(&sctx->list_lock);
2532 	sbio->next_free = sctx->first_free;
2533 	sctx->first_free = sbio->index;
2534 	spin_unlock(&sctx->list_lock);
2535 
2536 	if (sctx->is_dev_replace && sctx->flush_all_writes) {
2537 		mutex_lock(&sctx->wr_lock);
2538 		scrub_wr_submit(sctx);
2539 		mutex_unlock(&sctx->wr_lock);
2540 	}
2541 
2542 	scrub_pending_bio_dec(sctx);
2543 }
2544 
2545 static inline void __scrub_mark_bitmap(struct scrub_parity *sparity,
2546 				       unsigned long *bitmap,
2547 				       u64 start, u32 len)
2548 {
2549 	u64 offset;
2550 	u32 nsectors;
2551 	u32 sectorsize_bits = sparity->sctx->fs_info->sectorsize_bits;
2552 
2553 	if (len >= sparity->stripe_len) {
2554 		bitmap_set(bitmap, 0, sparity->nsectors);
2555 		return;
2556 	}
2557 
2558 	start -= sparity->logic_start;
2559 	start = div64_u64_rem(start, sparity->stripe_len, &offset);
2560 	offset = offset >> sectorsize_bits;
2561 	nsectors = len >> sectorsize_bits;
2562 
2563 	if (offset + nsectors <= sparity->nsectors) {
2564 		bitmap_set(bitmap, offset, nsectors);
2565 		return;
2566 	}
2567 
2568 	bitmap_set(bitmap, offset, sparity->nsectors - offset);
2569 	bitmap_set(bitmap, 0, nsectors - (sparity->nsectors - offset));
2570 }
2571 
2572 static inline void scrub_parity_mark_sectors_error(struct scrub_parity *sparity,
2573 						   u64 start, u32 len)
2574 {
2575 	__scrub_mark_bitmap(sparity, &sparity->ebitmap, start, len);
2576 }
2577 
2578 static inline void scrub_parity_mark_sectors_data(struct scrub_parity *sparity,
2579 						  u64 start, u32 len)
2580 {
2581 	__scrub_mark_bitmap(sparity, &sparity->dbitmap, start, len);
2582 }
2583 
2584 static void scrub_block_complete(struct scrub_block *sblock)
2585 {
2586 	int corrupted = 0;
2587 
2588 	if (!sblock->no_io_error_seen) {
2589 		corrupted = 1;
2590 		scrub_handle_errored_block(sblock);
2591 	} else {
2592 		/*
2593 		 * if has checksum error, write via repair mechanism in
2594 		 * dev replace case, otherwise write here in dev replace
2595 		 * case.
2596 		 */
2597 		corrupted = scrub_checksum(sblock);
2598 		if (!corrupted && sblock->sctx->is_dev_replace)
2599 			scrub_write_block_to_dev_replace(sblock);
2600 	}
2601 
2602 	if (sblock->sparity && corrupted && !sblock->data_corrected) {
2603 		u64 start = sblock->logical;
2604 		u64 end = sblock->logical +
2605 			  sblock->sectors[sblock->sector_count - 1]->offset +
2606 			  sblock->sctx->fs_info->sectorsize;
2607 
2608 		ASSERT(end - start <= U32_MAX);
2609 		scrub_parity_mark_sectors_error(sblock->sparity,
2610 						start, end - start);
2611 	}
2612 }
2613 
2614 static void drop_csum_range(struct scrub_ctx *sctx, struct btrfs_ordered_sum *sum)
2615 {
2616 	sctx->stat.csum_discards += sum->len >> sctx->fs_info->sectorsize_bits;
2617 	list_del(&sum->list);
2618 	kfree(sum);
2619 }
2620 
2621 /*
2622  * Find the desired csum for range [logical, logical + sectorsize), and store
2623  * the csum into @csum.
2624  *
2625  * The search source is sctx->csum_list, which is a pre-populated list
2626  * storing bytenr ordered csum ranges.  We're responsible to cleanup any range
2627  * that is before @logical.
2628  *
2629  * Return 0 if there is no csum for the range.
2630  * Return 1 if there is csum for the range and copied to @csum.
2631  */
2632 static int scrub_find_csum(struct scrub_ctx *sctx, u64 logical, u8 *csum)
2633 {
2634 	bool found = false;
2635 
2636 	while (!list_empty(&sctx->csum_list)) {
2637 		struct btrfs_ordered_sum *sum = NULL;
2638 		unsigned long index;
2639 		unsigned long num_sectors;
2640 
2641 		sum = list_first_entry(&sctx->csum_list,
2642 				       struct btrfs_ordered_sum, list);
2643 		/* The current csum range is beyond our range, no csum found */
2644 		if (sum->bytenr > logical)
2645 			break;
2646 
2647 		/*
2648 		 * The current sum is before our bytenr, since scrub is always
2649 		 * done in bytenr order, the csum will never be used anymore,
2650 		 * clean it up so that later calls won't bother with the range,
2651 		 * and continue search the next range.
2652 		 */
2653 		if (sum->bytenr + sum->len <= logical) {
2654 			drop_csum_range(sctx, sum);
2655 			continue;
2656 		}
2657 
2658 		/* Now the csum range covers our bytenr, copy the csum */
2659 		found = true;
2660 		index = (logical - sum->bytenr) >> sctx->fs_info->sectorsize_bits;
2661 		num_sectors = sum->len >> sctx->fs_info->sectorsize_bits;
2662 
2663 		memcpy(csum, sum->sums + index * sctx->fs_info->csum_size,
2664 		       sctx->fs_info->csum_size);
2665 
2666 		/* Cleanup the range if we're at the end of the csum range */
2667 		if (index == num_sectors - 1)
2668 			drop_csum_range(sctx, sum);
2669 		break;
2670 	}
2671 	if (!found)
2672 		return 0;
2673 	return 1;
2674 }
2675 
2676 /* scrub extent tries to collect up to 64 kB for each bio */
2677 static int scrub_extent(struct scrub_ctx *sctx, struct map_lookup *map,
2678 			u64 logical, u32 len,
2679 			u64 physical, struct btrfs_device *dev, u64 flags,
2680 			u64 gen, int mirror_num)
2681 {
2682 	struct btrfs_device *src_dev = dev;
2683 	u64 src_physical = physical;
2684 	int src_mirror = mirror_num;
2685 	int ret;
2686 	u8 csum[BTRFS_CSUM_SIZE];
2687 	u32 blocksize;
2688 
2689 	if (flags & BTRFS_EXTENT_FLAG_DATA) {
2690 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2691 			blocksize = map->stripe_len;
2692 		else
2693 			blocksize = sctx->fs_info->sectorsize;
2694 		spin_lock(&sctx->stat_lock);
2695 		sctx->stat.data_extents_scrubbed++;
2696 		sctx->stat.data_bytes_scrubbed += len;
2697 		spin_unlock(&sctx->stat_lock);
2698 	} else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2699 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2700 			blocksize = map->stripe_len;
2701 		else
2702 			blocksize = sctx->fs_info->nodesize;
2703 		spin_lock(&sctx->stat_lock);
2704 		sctx->stat.tree_extents_scrubbed++;
2705 		sctx->stat.tree_bytes_scrubbed += len;
2706 		spin_unlock(&sctx->stat_lock);
2707 	} else {
2708 		blocksize = sctx->fs_info->sectorsize;
2709 		WARN_ON(1);
2710 	}
2711 
2712 	/*
2713 	 * For dev-replace case, we can have @dev being a missing device.
2714 	 * Regular scrub will avoid its execution on missing device at all,
2715 	 * as that would trigger tons of read error.
2716 	 *
2717 	 * Reading from missing device will cause read error counts to
2718 	 * increase unnecessarily.
2719 	 * So here we change the read source to a good mirror.
2720 	 */
2721 	if (sctx->is_dev_replace && !dev->bdev)
2722 		scrub_find_good_copy(sctx->fs_info, logical, len, &src_physical,
2723 				     &src_dev, &src_mirror);
2724 	while (len) {
2725 		u32 l = min(len, blocksize);
2726 		int have_csum = 0;
2727 
2728 		if (flags & BTRFS_EXTENT_FLAG_DATA) {
2729 			/* push csums to sbio */
2730 			have_csum = scrub_find_csum(sctx, logical, csum);
2731 			if (have_csum == 0)
2732 				++sctx->stat.no_csum;
2733 		}
2734 		ret = scrub_sectors(sctx, logical, l, src_physical, src_dev,
2735 				    flags, gen, src_mirror,
2736 				    have_csum ? csum : NULL, physical);
2737 		if (ret)
2738 			return ret;
2739 		len -= l;
2740 		logical += l;
2741 		physical += l;
2742 		src_physical += l;
2743 	}
2744 	return 0;
2745 }
2746 
2747 static int scrub_sectors_for_parity(struct scrub_parity *sparity,
2748 				  u64 logical, u32 len,
2749 				  u64 physical, struct btrfs_device *dev,
2750 				  u64 flags, u64 gen, int mirror_num, u8 *csum)
2751 {
2752 	struct scrub_ctx *sctx = sparity->sctx;
2753 	struct scrub_block *sblock;
2754 	const u32 sectorsize = sctx->fs_info->sectorsize;
2755 	int index;
2756 
2757 	ASSERT(IS_ALIGNED(len, sectorsize));
2758 
2759 	sblock = alloc_scrub_block(sctx, dev, logical, physical, physical, mirror_num);
2760 	if (!sblock) {
2761 		spin_lock(&sctx->stat_lock);
2762 		sctx->stat.malloc_errors++;
2763 		spin_unlock(&sctx->stat_lock);
2764 		return -ENOMEM;
2765 	}
2766 
2767 	sblock->sparity = sparity;
2768 	scrub_parity_get(sparity);
2769 
2770 	for (index = 0; len > 0; index++) {
2771 		struct scrub_sector *sector;
2772 
2773 		sector = alloc_scrub_sector(sblock, logical);
2774 		if (!sector) {
2775 			spin_lock(&sctx->stat_lock);
2776 			sctx->stat.malloc_errors++;
2777 			spin_unlock(&sctx->stat_lock);
2778 			scrub_block_put(sblock);
2779 			return -ENOMEM;
2780 		}
2781 		sblock->sectors[index] = sector;
2782 		/* For scrub parity */
2783 		scrub_sector_get(sector);
2784 		list_add_tail(&sector->list, &sparity->sectors_list);
2785 		sector->flags = flags;
2786 		sector->generation = gen;
2787 		if (csum) {
2788 			sector->have_csum = 1;
2789 			memcpy(sector->csum, csum, sctx->fs_info->csum_size);
2790 		} else {
2791 			sector->have_csum = 0;
2792 		}
2793 
2794 		/* Iterate over the stripe range in sectorsize steps */
2795 		len -= sectorsize;
2796 		logical += sectorsize;
2797 		physical += sectorsize;
2798 	}
2799 
2800 	WARN_ON(sblock->sector_count == 0);
2801 	for (index = 0; index < sblock->sector_count; index++) {
2802 		struct scrub_sector *sector = sblock->sectors[index];
2803 		int ret;
2804 
2805 		ret = scrub_add_sector_to_rd_bio(sctx, sector);
2806 		if (ret) {
2807 			scrub_block_put(sblock);
2808 			return ret;
2809 		}
2810 	}
2811 
2812 	/* Last one frees, either here or in bio completion for last sector */
2813 	scrub_block_put(sblock);
2814 	return 0;
2815 }
2816 
2817 static int scrub_extent_for_parity(struct scrub_parity *sparity,
2818 				   u64 logical, u32 len,
2819 				   u64 physical, struct btrfs_device *dev,
2820 				   u64 flags, u64 gen, int mirror_num)
2821 {
2822 	struct scrub_ctx *sctx = sparity->sctx;
2823 	int ret;
2824 	u8 csum[BTRFS_CSUM_SIZE];
2825 	u32 blocksize;
2826 
2827 	if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) {
2828 		scrub_parity_mark_sectors_error(sparity, logical, len);
2829 		return 0;
2830 	}
2831 
2832 	if (flags & BTRFS_EXTENT_FLAG_DATA) {
2833 		blocksize = sparity->stripe_len;
2834 	} else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2835 		blocksize = sparity->stripe_len;
2836 	} else {
2837 		blocksize = sctx->fs_info->sectorsize;
2838 		WARN_ON(1);
2839 	}
2840 
2841 	while (len) {
2842 		u32 l = min(len, blocksize);
2843 		int have_csum = 0;
2844 
2845 		if (flags & BTRFS_EXTENT_FLAG_DATA) {
2846 			/* push csums to sbio */
2847 			have_csum = scrub_find_csum(sctx, logical, csum);
2848 			if (have_csum == 0)
2849 				goto skip;
2850 		}
2851 		ret = scrub_sectors_for_parity(sparity, logical, l, physical, dev,
2852 					     flags, gen, mirror_num,
2853 					     have_csum ? csum : NULL);
2854 		if (ret)
2855 			return ret;
2856 skip:
2857 		len -= l;
2858 		logical += l;
2859 		physical += l;
2860 	}
2861 	return 0;
2862 }
2863 
2864 /*
2865  * Given a physical address, this will calculate it's
2866  * logical offset. if this is a parity stripe, it will return
2867  * the most left data stripe's logical offset.
2868  *
2869  * return 0 if it is a data stripe, 1 means parity stripe.
2870  */
2871 static int get_raid56_logic_offset(u64 physical, int num,
2872 				   struct map_lookup *map, u64 *offset,
2873 				   u64 *stripe_start)
2874 {
2875 	int i;
2876 	int j = 0;
2877 	u64 stripe_nr;
2878 	u64 last_offset;
2879 	u32 stripe_index;
2880 	u32 rot;
2881 	const int data_stripes = nr_data_stripes(map);
2882 
2883 	last_offset = (physical - map->stripes[num].physical) * data_stripes;
2884 	if (stripe_start)
2885 		*stripe_start = last_offset;
2886 
2887 	*offset = last_offset;
2888 	for (i = 0; i < data_stripes; i++) {
2889 		*offset = last_offset + i * map->stripe_len;
2890 
2891 		stripe_nr = div64_u64(*offset, map->stripe_len);
2892 		stripe_nr = div_u64(stripe_nr, data_stripes);
2893 
2894 		/* Work out the disk rotation on this stripe-set */
2895 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &rot);
2896 		/* calculate which stripe this data locates */
2897 		rot += i;
2898 		stripe_index = rot % map->num_stripes;
2899 		if (stripe_index == num)
2900 			return 0;
2901 		if (stripe_index < num)
2902 			j++;
2903 	}
2904 	*offset = last_offset + j * map->stripe_len;
2905 	return 1;
2906 }
2907 
2908 static void scrub_free_parity(struct scrub_parity *sparity)
2909 {
2910 	struct scrub_ctx *sctx = sparity->sctx;
2911 	struct scrub_sector *curr, *next;
2912 	int nbits;
2913 
2914 	nbits = bitmap_weight(&sparity->ebitmap, sparity->nsectors);
2915 	if (nbits) {
2916 		spin_lock(&sctx->stat_lock);
2917 		sctx->stat.read_errors += nbits;
2918 		sctx->stat.uncorrectable_errors += nbits;
2919 		spin_unlock(&sctx->stat_lock);
2920 	}
2921 
2922 	list_for_each_entry_safe(curr, next, &sparity->sectors_list, list) {
2923 		list_del_init(&curr->list);
2924 		scrub_sector_put(curr);
2925 	}
2926 
2927 	kfree(sparity);
2928 }
2929 
2930 static void scrub_parity_bio_endio_worker(struct work_struct *work)
2931 {
2932 	struct scrub_parity *sparity = container_of(work, struct scrub_parity,
2933 						    work);
2934 	struct scrub_ctx *sctx = sparity->sctx;
2935 
2936 	btrfs_bio_counter_dec(sctx->fs_info);
2937 	scrub_free_parity(sparity);
2938 	scrub_pending_bio_dec(sctx);
2939 }
2940 
2941 static void scrub_parity_bio_endio(struct bio *bio)
2942 {
2943 	struct scrub_parity *sparity = bio->bi_private;
2944 	struct btrfs_fs_info *fs_info = sparity->sctx->fs_info;
2945 
2946 	if (bio->bi_status)
2947 		bitmap_or(&sparity->ebitmap, &sparity->ebitmap,
2948 			  &sparity->dbitmap, sparity->nsectors);
2949 
2950 	bio_put(bio);
2951 
2952 	INIT_WORK(&sparity->work, scrub_parity_bio_endio_worker);
2953 	queue_work(fs_info->scrub_parity_workers, &sparity->work);
2954 }
2955 
2956 static void scrub_parity_check_and_repair(struct scrub_parity *sparity)
2957 {
2958 	struct scrub_ctx *sctx = sparity->sctx;
2959 	struct btrfs_fs_info *fs_info = sctx->fs_info;
2960 	struct bio *bio;
2961 	struct btrfs_raid_bio *rbio;
2962 	struct btrfs_io_context *bioc = NULL;
2963 	u64 length;
2964 	int ret;
2965 
2966 	if (!bitmap_andnot(&sparity->dbitmap, &sparity->dbitmap,
2967 			   &sparity->ebitmap, sparity->nsectors))
2968 		goto out;
2969 
2970 	length = sparity->logic_end - sparity->logic_start;
2971 
2972 	btrfs_bio_counter_inc_blocked(fs_info);
2973 	ret = btrfs_map_sblock(fs_info, BTRFS_MAP_WRITE, sparity->logic_start,
2974 			       &length, &bioc);
2975 	if (ret || !bioc || !bioc->raid_map)
2976 		goto bioc_out;
2977 
2978 	bio = bio_alloc(NULL, BIO_MAX_VECS, REQ_OP_READ, GFP_NOFS);
2979 	bio->bi_iter.bi_sector = sparity->logic_start >> 9;
2980 	bio->bi_private = sparity;
2981 	bio->bi_end_io = scrub_parity_bio_endio;
2982 
2983 	rbio = raid56_parity_alloc_scrub_rbio(bio, bioc,
2984 					      sparity->scrub_dev,
2985 					      &sparity->dbitmap,
2986 					      sparity->nsectors);
2987 	btrfs_put_bioc(bioc);
2988 	if (!rbio)
2989 		goto rbio_out;
2990 
2991 	scrub_pending_bio_inc(sctx);
2992 	raid56_parity_submit_scrub_rbio(rbio);
2993 	return;
2994 
2995 rbio_out:
2996 	bio_put(bio);
2997 bioc_out:
2998 	btrfs_bio_counter_dec(fs_info);
2999 	bitmap_or(&sparity->ebitmap, &sparity->ebitmap, &sparity->dbitmap,
3000 		  sparity->nsectors);
3001 	spin_lock(&sctx->stat_lock);
3002 	sctx->stat.malloc_errors++;
3003 	spin_unlock(&sctx->stat_lock);
3004 out:
3005 	scrub_free_parity(sparity);
3006 }
3007 
3008 static void scrub_parity_get(struct scrub_parity *sparity)
3009 {
3010 	refcount_inc(&sparity->refs);
3011 }
3012 
3013 static void scrub_parity_put(struct scrub_parity *sparity)
3014 {
3015 	if (!refcount_dec_and_test(&sparity->refs))
3016 		return;
3017 
3018 	scrub_parity_check_and_repair(sparity);
3019 }
3020 
3021 /*
3022  * Return 0 if the extent item range covers any byte of the range.
3023  * Return <0 if the extent item is before @search_start.
3024  * Return >0 if the extent item is after @start_start + @search_len.
3025  */
3026 static int compare_extent_item_range(struct btrfs_path *path,
3027 				     u64 search_start, u64 search_len)
3028 {
3029 	struct btrfs_fs_info *fs_info = path->nodes[0]->fs_info;
3030 	u64 len;
3031 	struct btrfs_key key;
3032 
3033 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3034 	ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY ||
3035 	       key.type == BTRFS_METADATA_ITEM_KEY);
3036 	if (key.type == BTRFS_METADATA_ITEM_KEY)
3037 		len = fs_info->nodesize;
3038 	else
3039 		len = key.offset;
3040 
3041 	if (key.objectid + len <= search_start)
3042 		return -1;
3043 	if (key.objectid >= search_start + search_len)
3044 		return 1;
3045 	return 0;
3046 }
3047 
3048 /*
3049  * Locate one extent item which covers any byte in range
3050  * [@search_start, @search_start + @search_length)
3051  *
3052  * If the path is not initialized, we will initialize the search by doing
3053  * a btrfs_search_slot().
3054  * If the path is already initialized, we will use the path as the initial
3055  * slot, to avoid duplicated btrfs_search_slot() calls.
3056  *
3057  * NOTE: If an extent item starts before @search_start, we will still
3058  * return the extent item. This is for data extent crossing stripe boundary.
3059  *
3060  * Return 0 if we found such extent item, and @path will point to the extent item.
3061  * Return >0 if no such extent item can be found, and @path will be released.
3062  * Return <0 if hit fatal error, and @path will be released.
3063  */
3064 static int find_first_extent_item(struct btrfs_root *extent_root,
3065 				  struct btrfs_path *path,
3066 				  u64 search_start, u64 search_len)
3067 {
3068 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
3069 	struct btrfs_key key;
3070 	int ret;
3071 
3072 	/* Continue using the existing path */
3073 	if (path->nodes[0])
3074 		goto search_forward;
3075 
3076 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
3077 		key.type = BTRFS_METADATA_ITEM_KEY;
3078 	else
3079 		key.type = BTRFS_EXTENT_ITEM_KEY;
3080 	key.objectid = search_start;
3081 	key.offset = (u64)-1;
3082 
3083 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3084 	if (ret < 0)
3085 		return ret;
3086 
3087 	ASSERT(ret > 0);
3088 	/*
3089 	 * Here we intentionally pass 0 as @min_objectid, as there could be
3090 	 * an extent item starting before @search_start.
3091 	 */
3092 	ret = btrfs_previous_extent_item(extent_root, path, 0);
3093 	if (ret < 0)
3094 		return ret;
3095 	/*
3096 	 * No matter whether we have found an extent item, the next loop will
3097 	 * properly do every check on the key.
3098 	 */
3099 search_forward:
3100 	while (true) {
3101 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3102 		if (key.objectid >= search_start + search_len)
3103 			break;
3104 		if (key.type != BTRFS_METADATA_ITEM_KEY &&
3105 		    key.type != BTRFS_EXTENT_ITEM_KEY)
3106 			goto next;
3107 
3108 		ret = compare_extent_item_range(path, search_start, search_len);
3109 		if (ret == 0)
3110 			return ret;
3111 		if (ret > 0)
3112 			break;
3113 next:
3114 		path->slots[0]++;
3115 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3116 			ret = btrfs_next_leaf(extent_root, path);
3117 			if (ret) {
3118 				/* Either no more item or fatal error */
3119 				btrfs_release_path(path);
3120 				return ret;
3121 			}
3122 		}
3123 	}
3124 	btrfs_release_path(path);
3125 	return 1;
3126 }
3127 
3128 static void get_extent_info(struct btrfs_path *path, u64 *extent_start_ret,
3129 			    u64 *size_ret, u64 *flags_ret, u64 *generation_ret)
3130 {
3131 	struct btrfs_key key;
3132 	struct btrfs_extent_item *ei;
3133 
3134 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3135 	ASSERT(key.type == BTRFS_METADATA_ITEM_KEY ||
3136 	       key.type == BTRFS_EXTENT_ITEM_KEY);
3137 	*extent_start_ret = key.objectid;
3138 	if (key.type == BTRFS_METADATA_ITEM_KEY)
3139 		*size_ret = path->nodes[0]->fs_info->nodesize;
3140 	else
3141 		*size_ret = key.offset;
3142 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_extent_item);
3143 	*flags_ret = btrfs_extent_flags(path->nodes[0], ei);
3144 	*generation_ret = btrfs_extent_generation(path->nodes[0], ei);
3145 }
3146 
3147 static bool does_range_cross_boundary(u64 extent_start, u64 extent_len,
3148 				      u64 boundary_start, u64 boudary_len)
3149 {
3150 	return (extent_start < boundary_start &&
3151 		extent_start + extent_len > boundary_start) ||
3152 	       (extent_start < boundary_start + boudary_len &&
3153 		extent_start + extent_len > boundary_start + boudary_len);
3154 }
3155 
3156 static int scrub_raid56_data_stripe_for_parity(struct scrub_ctx *sctx,
3157 					       struct scrub_parity *sparity,
3158 					       struct map_lookup *map,
3159 					       struct btrfs_device *sdev,
3160 					       struct btrfs_path *path,
3161 					       u64 logical)
3162 {
3163 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3164 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
3165 	struct btrfs_root *csum_root = btrfs_csum_root(fs_info, logical);
3166 	u64 cur_logical = logical;
3167 	int ret;
3168 
3169 	ASSERT(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK);
3170 
3171 	/* Path must not be populated */
3172 	ASSERT(!path->nodes[0]);
3173 
3174 	while (cur_logical < logical + map->stripe_len) {
3175 		struct btrfs_io_context *bioc = NULL;
3176 		struct btrfs_device *extent_dev;
3177 		u64 extent_start;
3178 		u64 extent_size;
3179 		u64 mapped_length;
3180 		u64 extent_flags;
3181 		u64 extent_gen;
3182 		u64 extent_physical;
3183 		u64 extent_mirror_num;
3184 
3185 		ret = find_first_extent_item(extent_root, path, cur_logical,
3186 					     logical + map->stripe_len - cur_logical);
3187 		/* No more extent item in this data stripe */
3188 		if (ret > 0) {
3189 			ret = 0;
3190 			break;
3191 		}
3192 		if (ret < 0)
3193 			break;
3194 		get_extent_info(path, &extent_start, &extent_size, &extent_flags,
3195 				&extent_gen);
3196 
3197 		/* Metadata should not cross stripe boundaries */
3198 		if ((extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) &&
3199 		    does_range_cross_boundary(extent_start, extent_size,
3200 					      logical, map->stripe_len)) {
3201 			btrfs_err(fs_info,
3202 	"scrub: tree block %llu spanning stripes, ignored. logical=%llu",
3203 				  extent_start, logical);
3204 			spin_lock(&sctx->stat_lock);
3205 			sctx->stat.uncorrectable_errors++;
3206 			spin_unlock(&sctx->stat_lock);
3207 			cur_logical += extent_size;
3208 			continue;
3209 		}
3210 
3211 		/* Skip hole range which doesn't have any extent */
3212 		cur_logical = max(extent_start, cur_logical);
3213 
3214 		/* Truncate the range inside this data stripe */
3215 		extent_size = min(extent_start + extent_size,
3216 				  logical + map->stripe_len) - cur_logical;
3217 		extent_start = cur_logical;
3218 		ASSERT(extent_size <= U32_MAX);
3219 
3220 		scrub_parity_mark_sectors_data(sparity, extent_start, extent_size);
3221 
3222 		mapped_length = extent_size;
3223 		ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, extent_start,
3224 				      &mapped_length, &bioc, 0);
3225 		if (!ret && (!bioc || mapped_length < extent_size))
3226 			ret = -EIO;
3227 		if (ret) {
3228 			btrfs_put_bioc(bioc);
3229 			scrub_parity_mark_sectors_error(sparity, extent_start,
3230 							extent_size);
3231 			break;
3232 		}
3233 		extent_physical = bioc->stripes[0].physical;
3234 		extent_mirror_num = bioc->mirror_num;
3235 		extent_dev = bioc->stripes[0].dev;
3236 		btrfs_put_bioc(bioc);
3237 
3238 		ret = btrfs_lookup_csums_range(csum_root, extent_start,
3239 					       extent_start + extent_size - 1,
3240 					       &sctx->csum_list, 1, false);
3241 		if (ret) {
3242 			scrub_parity_mark_sectors_error(sparity, extent_start,
3243 							extent_size);
3244 			break;
3245 		}
3246 
3247 		ret = scrub_extent_for_parity(sparity, extent_start,
3248 					      extent_size, extent_physical,
3249 					      extent_dev, extent_flags,
3250 					      extent_gen, extent_mirror_num);
3251 		scrub_free_csums(sctx);
3252 
3253 		if (ret) {
3254 			scrub_parity_mark_sectors_error(sparity, extent_start,
3255 							extent_size);
3256 			break;
3257 		}
3258 
3259 		cond_resched();
3260 		cur_logical += extent_size;
3261 	}
3262 	btrfs_release_path(path);
3263 	return ret;
3264 }
3265 
3266 static noinline_for_stack int scrub_raid56_parity(struct scrub_ctx *sctx,
3267 						  struct map_lookup *map,
3268 						  struct btrfs_device *sdev,
3269 						  u64 logic_start,
3270 						  u64 logic_end)
3271 {
3272 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3273 	struct btrfs_path *path;
3274 	u64 cur_logical;
3275 	int ret;
3276 	struct scrub_parity *sparity;
3277 	int nsectors;
3278 
3279 	path = btrfs_alloc_path();
3280 	if (!path) {
3281 		spin_lock(&sctx->stat_lock);
3282 		sctx->stat.malloc_errors++;
3283 		spin_unlock(&sctx->stat_lock);
3284 		return -ENOMEM;
3285 	}
3286 	path->search_commit_root = 1;
3287 	path->skip_locking = 1;
3288 
3289 	ASSERT(map->stripe_len <= U32_MAX);
3290 	nsectors = map->stripe_len >> fs_info->sectorsize_bits;
3291 	ASSERT(nsectors <= BITS_PER_LONG);
3292 	sparity = kzalloc(sizeof(struct scrub_parity), GFP_NOFS);
3293 	if (!sparity) {
3294 		spin_lock(&sctx->stat_lock);
3295 		sctx->stat.malloc_errors++;
3296 		spin_unlock(&sctx->stat_lock);
3297 		btrfs_free_path(path);
3298 		return -ENOMEM;
3299 	}
3300 
3301 	ASSERT(map->stripe_len <= U32_MAX);
3302 	sparity->stripe_len = map->stripe_len;
3303 	sparity->nsectors = nsectors;
3304 	sparity->sctx = sctx;
3305 	sparity->scrub_dev = sdev;
3306 	sparity->logic_start = logic_start;
3307 	sparity->logic_end = logic_end;
3308 	refcount_set(&sparity->refs, 1);
3309 	INIT_LIST_HEAD(&sparity->sectors_list);
3310 
3311 	ret = 0;
3312 	for (cur_logical = logic_start; cur_logical < logic_end;
3313 	     cur_logical += map->stripe_len) {
3314 		ret = scrub_raid56_data_stripe_for_parity(sctx, sparity, map,
3315 							  sdev, path, cur_logical);
3316 		if (ret < 0)
3317 			break;
3318 	}
3319 
3320 	scrub_parity_put(sparity);
3321 	scrub_submit(sctx);
3322 	mutex_lock(&sctx->wr_lock);
3323 	scrub_wr_submit(sctx);
3324 	mutex_unlock(&sctx->wr_lock);
3325 
3326 	btrfs_free_path(path);
3327 	return ret < 0 ? ret : 0;
3328 }
3329 
3330 static void sync_replace_for_zoned(struct scrub_ctx *sctx)
3331 {
3332 	if (!btrfs_is_zoned(sctx->fs_info))
3333 		return;
3334 
3335 	sctx->flush_all_writes = true;
3336 	scrub_submit(sctx);
3337 	mutex_lock(&sctx->wr_lock);
3338 	scrub_wr_submit(sctx);
3339 	mutex_unlock(&sctx->wr_lock);
3340 
3341 	wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
3342 }
3343 
3344 static int sync_write_pointer_for_zoned(struct scrub_ctx *sctx, u64 logical,
3345 					u64 physical, u64 physical_end)
3346 {
3347 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3348 	int ret = 0;
3349 
3350 	if (!btrfs_is_zoned(fs_info))
3351 		return 0;
3352 
3353 	wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
3354 
3355 	mutex_lock(&sctx->wr_lock);
3356 	if (sctx->write_pointer < physical_end) {
3357 		ret = btrfs_sync_zone_write_pointer(sctx->wr_tgtdev, logical,
3358 						    physical,
3359 						    sctx->write_pointer);
3360 		if (ret)
3361 			btrfs_err(fs_info,
3362 				  "zoned: failed to recover write pointer");
3363 	}
3364 	mutex_unlock(&sctx->wr_lock);
3365 	btrfs_dev_clear_zone_empty(sctx->wr_tgtdev, physical);
3366 
3367 	return ret;
3368 }
3369 
3370 /*
3371  * Scrub one range which can only has simple mirror based profile.
3372  * (Including all range in SINGLE/DUP/RAID1/RAID1C*, and each stripe in
3373  *  RAID0/RAID10).
3374  *
3375  * Since we may need to handle a subset of block group, we need @logical_start
3376  * and @logical_length parameter.
3377  */
3378 static int scrub_simple_mirror(struct scrub_ctx *sctx,
3379 			       struct btrfs_root *extent_root,
3380 			       struct btrfs_root *csum_root,
3381 			       struct btrfs_block_group *bg,
3382 			       struct map_lookup *map,
3383 			       u64 logical_start, u64 logical_length,
3384 			       struct btrfs_device *device,
3385 			       u64 physical, int mirror_num)
3386 {
3387 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3388 	const u64 logical_end = logical_start + logical_length;
3389 	/* An artificial limit, inherit from old scrub behavior */
3390 	const u32 max_length = SZ_64K;
3391 	struct btrfs_path path = { 0 };
3392 	u64 cur_logical = logical_start;
3393 	int ret;
3394 
3395 	/* The range must be inside the bg */
3396 	ASSERT(logical_start >= bg->start && logical_end <= bg->start + bg->length);
3397 
3398 	path.search_commit_root = 1;
3399 	path.skip_locking = 1;
3400 	/* Go through each extent items inside the logical range */
3401 	while (cur_logical < logical_end) {
3402 		u64 extent_start;
3403 		u64 extent_len;
3404 		u64 extent_flags;
3405 		u64 extent_gen;
3406 		u64 scrub_len;
3407 
3408 		/* Canceled? */
3409 		if (atomic_read(&fs_info->scrub_cancel_req) ||
3410 		    atomic_read(&sctx->cancel_req)) {
3411 			ret = -ECANCELED;
3412 			break;
3413 		}
3414 		/* Paused? */
3415 		if (atomic_read(&fs_info->scrub_pause_req)) {
3416 			/* Push queued extents */
3417 			sctx->flush_all_writes = true;
3418 			scrub_submit(sctx);
3419 			mutex_lock(&sctx->wr_lock);
3420 			scrub_wr_submit(sctx);
3421 			mutex_unlock(&sctx->wr_lock);
3422 			wait_event(sctx->list_wait,
3423 				   atomic_read(&sctx->bios_in_flight) == 0);
3424 			sctx->flush_all_writes = false;
3425 			scrub_blocked_if_needed(fs_info);
3426 		}
3427 		/* Block group removed? */
3428 		spin_lock(&bg->lock);
3429 		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
3430 			spin_unlock(&bg->lock);
3431 			ret = 0;
3432 			break;
3433 		}
3434 		spin_unlock(&bg->lock);
3435 
3436 		ret = find_first_extent_item(extent_root, &path, cur_logical,
3437 					     logical_end - cur_logical);
3438 		if (ret > 0) {
3439 			/* No more extent, just update the accounting */
3440 			sctx->stat.last_physical = physical + logical_length;
3441 			ret = 0;
3442 			break;
3443 		}
3444 		if (ret < 0)
3445 			break;
3446 		get_extent_info(&path, &extent_start, &extent_len,
3447 				&extent_flags, &extent_gen);
3448 		/* Skip hole range which doesn't have any extent */
3449 		cur_logical = max(extent_start, cur_logical);
3450 
3451 		/*
3452 		 * Scrub len has three limits:
3453 		 * - Extent size limit
3454 		 * - Scrub range limit
3455 		 *   This is especially imporatant for RAID0/RAID10 to reuse
3456 		 *   this function
3457 		 * - Max scrub size limit
3458 		 */
3459 		scrub_len = min(min(extent_start + extent_len,
3460 				    logical_end), cur_logical + max_length) -
3461 			    cur_logical;
3462 
3463 		if (extent_flags & BTRFS_EXTENT_FLAG_DATA) {
3464 			ret = btrfs_lookup_csums_range(csum_root, cur_logical,
3465 					cur_logical + scrub_len - 1,
3466 					&sctx->csum_list, 1, false);
3467 			if (ret)
3468 				break;
3469 		}
3470 		if ((extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) &&
3471 		    does_range_cross_boundary(extent_start, extent_len,
3472 					      logical_start, logical_length)) {
3473 			btrfs_err(fs_info,
3474 "scrub: tree block %llu spanning boundaries, ignored. boundary=[%llu, %llu)",
3475 				  extent_start, logical_start, logical_end);
3476 			spin_lock(&sctx->stat_lock);
3477 			sctx->stat.uncorrectable_errors++;
3478 			spin_unlock(&sctx->stat_lock);
3479 			cur_logical += scrub_len;
3480 			continue;
3481 		}
3482 		ret = scrub_extent(sctx, map, cur_logical, scrub_len,
3483 				   cur_logical - logical_start + physical,
3484 				   device, extent_flags, extent_gen,
3485 				   mirror_num);
3486 		scrub_free_csums(sctx);
3487 		if (ret)
3488 			break;
3489 		if (sctx->is_dev_replace)
3490 			sync_replace_for_zoned(sctx);
3491 		cur_logical += scrub_len;
3492 		/* Don't hold CPU for too long time */
3493 		cond_resched();
3494 	}
3495 	btrfs_release_path(&path);
3496 	return ret;
3497 }
3498 
3499 /* Calculate the full stripe length for simple stripe based profiles */
3500 static u64 simple_stripe_full_stripe_len(const struct map_lookup *map)
3501 {
3502 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3503 			    BTRFS_BLOCK_GROUP_RAID10));
3504 
3505 	return map->num_stripes / map->sub_stripes * map->stripe_len;
3506 }
3507 
3508 /* Get the logical bytenr for the stripe */
3509 static u64 simple_stripe_get_logical(struct map_lookup *map,
3510 				     struct btrfs_block_group *bg,
3511 				     int stripe_index)
3512 {
3513 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3514 			    BTRFS_BLOCK_GROUP_RAID10));
3515 	ASSERT(stripe_index < map->num_stripes);
3516 
3517 	/*
3518 	 * (stripe_index / sub_stripes) gives how many data stripes we need to
3519 	 * skip.
3520 	 */
3521 	return (stripe_index / map->sub_stripes) * map->stripe_len + bg->start;
3522 }
3523 
3524 /* Get the mirror number for the stripe */
3525 static int simple_stripe_mirror_num(struct map_lookup *map, int stripe_index)
3526 {
3527 	ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3528 			    BTRFS_BLOCK_GROUP_RAID10));
3529 	ASSERT(stripe_index < map->num_stripes);
3530 
3531 	/* For RAID0, it's fixed to 1, for RAID10 it's 0,1,0,1... */
3532 	return stripe_index % map->sub_stripes + 1;
3533 }
3534 
3535 static int scrub_simple_stripe(struct scrub_ctx *sctx,
3536 			       struct btrfs_root *extent_root,
3537 			       struct btrfs_root *csum_root,
3538 			       struct btrfs_block_group *bg,
3539 			       struct map_lookup *map,
3540 			       struct btrfs_device *device,
3541 			       int stripe_index)
3542 {
3543 	const u64 logical_increment = simple_stripe_full_stripe_len(map);
3544 	const u64 orig_logical = simple_stripe_get_logical(map, bg, stripe_index);
3545 	const u64 orig_physical = map->stripes[stripe_index].physical;
3546 	const int mirror_num = simple_stripe_mirror_num(map, stripe_index);
3547 	u64 cur_logical = orig_logical;
3548 	u64 cur_physical = orig_physical;
3549 	int ret = 0;
3550 
3551 	while (cur_logical < bg->start + bg->length) {
3552 		/*
3553 		 * Inside each stripe, RAID0 is just SINGLE, and RAID10 is
3554 		 * just RAID1, so we can reuse scrub_simple_mirror() to scrub
3555 		 * this stripe.
3556 		 */
3557 		ret = scrub_simple_mirror(sctx, extent_root, csum_root, bg, map,
3558 					  cur_logical, map->stripe_len, device,
3559 					  cur_physical, mirror_num);
3560 		if (ret)
3561 			return ret;
3562 		/* Skip to next stripe which belongs to the target device */
3563 		cur_logical += logical_increment;
3564 		/* For physical offset, we just go to next stripe */
3565 		cur_physical += map->stripe_len;
3566 	}
3567 	return ret;
3568 }
3569 
3570 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
3571 					   struct btrfs_block_group *bg,
3572 					   struct extent_map *em,
3573 					   struct btrfs_device *scrub_dev,
3574 					   int stripe_index)
3575 {
3576 	struct btrfs_path *path;
3577 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3578 	struct btrfs_root *root;
3579 	struct btrfs_root *csum_root;
3580 	struct blk_plug plug;
3581 	struct map_lookup *map = em->map_lookup;
3582 	const u64 profile = map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK;
3583 	const u64 chunk_logical = bg->start;
3584 	int ret;
3585 	u64 physical = map->stripes[stripe_index].physical;
3586 	const u64 dev_stripe_len = btrfs_calc_stripe_length(em);
3587 	const u64 physical_end = physical + dev_stripe_len;
3588 	u64 logical;
3589 	u64 logic_end;
3590 	/* The logical increment after finishing one stripe */
3591 	u64 increment;
3592 	/* Offset inside the chunk */
3593 	u64 offset;
3594 	u64 stripe_logical;
3595 	u64 stripe_end;
3596 	int stop_loop = 0;
3597 
3598 	path = btrfs_alloc_path();
3599 	if (!path)
3600 		return -ENOMEM;
3601 
3602 	/*
3603 	 * work on commit root. The related disk blocks are static as
3604 	 * long as COW is applied. This means, it is save to rewrite
3605 	 * them to repair disk errors without any race conditions
3606 	 */
3607 	path->search_commit_root = 1;
3608 	path->skip_locking = 1;
3609 	path->reada = READA_FORWARD;
3610 
3611 	wait_event(sctx->list_wait,
3612 		   atomic_read(&sctx->bios_in_flight) == 0);
3613 	scrub_blocked_if_needed(fs_info);
3614 
3615 	root = btrfs_extent_root(fs_info, bg->start);
3616 	csum_root = btrfs_csum_root(fs_info, bg->start);
3617 
3618 	/*
3619 	 * collect all data csums for the stripe to avoid seeking during
3620 	 * the scrub. This might currently (crc32) end up to be about 1MB
3621 	 */
3622 	blk_start_plug(&plug);
3623 
3624 	if (sctx->is_dev_replace &&
3625 	    btrfs_dev_is_sequential(sctx->wr_tgtdev, physical)) {
3626 		mutex_lock(&sctx->wr_lock);
3627 		sctx->write_pointer = physical;
3628 		mutex_unlock(&sctx->wr_lock);
3629 		sctx->flush_all_writes = true;
3630 	}
3631 
3632 	/*
3633 	 * There used to be a big double loop to handle all profiles using the
3634 	 * same routine, which grows larger and more gross over time.
3635 	 *
3636 	 * So here we handle each profile differently, so simpler profiles
3637 	 * have simpler scrubbing function.
3638 	 */
3639 	if (!(profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10 |
3640 			 BTRFS_BLOCK_GROUP_RAID56_MASK))) {
3641 		/*
3642 		 * Above check rules out all complex profile, the remaining
3643 		 * profiles are SINGLE|DUP|RAID1|RAID1C*, which is simple
3644 		 * mirrored duplication without stripe.
3645 		 *
3646 		 * Only @physical and @mirror_num needs to calculated using
3647 		 * @stripe_index.
3648 		 */
3649 		ret = scrub_simple_mirror(sctx, root, csum_root, bg, map,
3650 				bg->start, bg->length, scrub_dev,
3651 				map->stripes[stripe_index].physical,
3652 				stripe_index + 1);
3653 		offset = 0;
3654 		goto out;
3655 	}
3656 	if (profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
3657 		ret = scrub_simple_stripe(sctx, root, csum_root, bg, map,
3658 					  scrub_dev, stripe_index);
3659 		offset = map->stripe_len * (stripe_index / map->sub_stripes);
3660 		goto out;
3661 	}
3662 
3663 	/* Only RAID56 goes through the old code */
3664 	ASSERT(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK);
3665 	ret = 0;
3666 
3667 	/* Calculate the logical end of the stripe */
3668 	get_raid56_logic_offset(physical_end, stripe_index,
3669 				map, &logic_end, NULL);
3670 	logic_end += chunk_logical;
3671 
3672 	/* Initialize @offset in case we need to go to out: label */
3673 	get_raid56_logic_offset(physical, stripe_index, map, &offset, NULL);
3674 	increment = map->stripe_len * nr_data_stripes(map);
3675 
3676 	/*
3677 	 * Due to the rotation, for RAID56 it's better to iterate each stripe
3678 	 * using their physical offset.
3679 	 */
3680 	while (physical < physical_end) {
3681 		ret = get_raid56_logic_offset(physical, stripe_index, map,
3682 					      &logical, &stripe_logical);
3683 		logical += chunk_logical;
3684 		if (ret) {
3685 			/* it is parity strip */
3686 			stripe_logical += chunk_logical;
3687 			stripe_end = stripe_logical + increment;
3688 			ret = scrub_raid56_parity(sctx, map, scrub_dev,
3689 						  stripe_logical,
3690 						  stripe_end);
3691 			if (ret)
3692 				goto out;
3693 			goto next;
3694 		}
3695 
3696 		/*
3697 		 * Now we're at a data stripe, scrub each extents in the range.
3698 		 *
3699 		 * At this stage, if we ignore the repair part, inside each data
3700 		 * stripe it is no different than SINGLE profile.
3701 		 * We can reuse scrub_simple_mirror() here, as the repair part
3702 		 * is still based on @mirror_num.
3703 		 */
3704 		ret = scrub_simple_mirror(sctx, root, csum_root, bg, map,
3705 					  logical, map->stripe_len,
3706 					  scrub_dev, physical, 1);
3707 		if (ret < 0)
3708 			goto out;
3709 next:
3710 		logical += increment;
3711 		physical += map->stripe_len;
3712 		spin_lock(&sctx->stat_lock);
3713 		if (stop_loop)
3714 			sctx->stat.last_physical =
3715 				map->stripes[stripe_index].physical + dev_stripe_len;
3716 		else
3717 			sctx->stat.last_physical = physical;
3718 		spin_unlock(&sctx->stat_lock);
3719 		if (stop_loop)
3720 			break;
3721 	}
3722 out:
3723 	/* push queued extents */
3724 	scrub_submit(sctx);
3725 	mutex_lock(&sctx->wr_lock);
3726 	scrub_wr_submit(sctx);
3727 	mutex_unlock(&sctx->wr_lock);
3728 
3729 	blk_finish_plug(&plug);
3730 	btrfs_free_path(path);
3731 
3732 	if (sctx->is_dev_replace && ret >= 0) {
3733 		int ret2;
3734 
3735 		ret2 = sync_write_pointer_for_zoned(sctx,
3736 				chunk_logical + offset,
3737 				map->stripes[stripe_index].physical,
3738 				physical_end);
3739 		if (ret2)
3740 			ret = ret2;
3741 	}
3742 
3743 	return ret < 0 ? ret : 0;
3744 }
3745 
3746 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx,
3747 					  struct btrfs_block_group *bg,
3748 					  struct btrfs_device *scrub_dev,
3749 					  u64 dev_offset,
3750 					  u64 dev_extent_len)
3751 {
3752 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3753 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
3754 	struct map_lookup *map;
3755 	struct extent_map *em;
3756 	int i;
3757 	int ret = 0;
3758 
3759 	read_lock(&map_tree->lock);
3760 	em = lookup_extent_mapping(map_tree, bg->start, bg->length);
3761 	read_unlock(&map_tree->lock);
3762 
3763 	if (!em) {
3764 		/*
3765 		 * Might have been an unused block group deleted by the cleaner
3766 		 * kthread or relocation.
3767 		 */
3768 		spin_lock(&bg->lock);
3769 		if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags))
3770 			ret = -EINVAL;
3771 		spin_unlock(&bg->lock);
3772 
3773 		return ret;
3774 	}
3775 	if (em->start != bg->start)
3776 		goto out;
3777 	if (em->len < dev_extent_len)
3778 		goto out;
3779 
3780 	map = em->map_lookup;
3781 	for (i = 0; i < map->num_stripes; ++i) {
3782 		if (map->stripes[i].dev->bdev == scrub_dev->bdev &&
3783 		    map->stripes[i].physical == dev_offset) {
3784 			ret = scrub_stripe(sctx, bg, em, scrub_dev, i);
3785 			if (ret)
3786 				goto out;
3787 		}
3788 	}
3789 out:
3790 	free_extent_map(em);
3791 
3792 	return ret;
3793 }
3794 
3795 static int finish_extent_writes_for_zoned(struct btrfs_root *root,
3796 					  struct btrfs_block_group *cache)
3797 {
3798 	struct btrfs_fs_info *fs_info = cache->fs_info;
3799 	struct btrfs_trans_handle *trans;
3800 
3801 	if (!btrfs_is_zoned(fs_info))
3802 		return 0;
3803 
3804 	btrfs_wait_block_group_reservations(cache);
3805 	btrfs_wait_nocow_writers(cache);
3806 	btrfs_wait_ordered_roots(fs_info, U64_MAX, cache->start, cache->length);
3807 
3808 	trans = btrfs_join_transaction(root);
3809 	if (IS_ERR(trans))
3810 		return PTR_ERR(trans);
3811 	return btrfs_commit_transaction(trans);
3812 }
3813 
3814 static noinline_for_stack
3815 int scrub_enumerate_chunks(struct scrub_ctx *sctx,
3816 			   struct btrfs_device *scrub_dev, u64 start, u64 end)
3817 {
3818 	struct btrfs_dev_extent *dev_extent = NULL;
3819 	struct btrfs_path *path;
3820 	struct btrfs_fs_info *fs_info = sctx->fs_info;
3821 	struct btrfs_root *root = fs_info->dev_root;
3822 	u64 chunk_offset;
3823 	int ret = 0;
3824 	int ro_set;
3825 	int slot;
3826 	struct extent_buffer *l;
3827 	struct btrfs_key key;
3828 	struct btrfs_key found_key;
3829 	struct btrfs_block_group *cache;
3830 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
3831 
3832 	path = btrfs_alloc_path();
3833 	if (!path)
3834 		return -ENOMEM;
3835 
3836 	path->reada = READA_FORWARD;
3837 	path->search_commit_root = 1;
3838 	path->skip_locking = 1;
3839 
3840 	key.objectid = scrub_dev->devid;
3841 	key.offset = 0ull;
3842 	key.type = BTRFS_DEV_EXTENT_KEY;
3843 
3844 	while (1) {
3845 		u64 dev_extent_len;
3846 
3847 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3848 		if (ret < 0)
3849 			break;
3850 		if (ret > 0) {
3851 			if (path->slots[0] >=
3852 			    btrfs_header_nritems(path->nodes[0])) {
3853 				ret = btrfs_next_leaf(root, path);
3854 				if (ret < 0)
3855 					break;
3856 				if (ret > 0) {
3857 					ret = 0;
3858 					break;
3859 				}
3860 			} else {
3861 				ret = 0;
3862 			}
3863 		}
3864 
3865 		l = path->nodes[0];
3866 		slot = path->slots[0];
3867 
3868 		btrfs_item_key_to_cpu(l, &found_key, slot);
3869 
3870 		if (found_key.objectid != scrub_dev->devid)
3871 			break;
3872 
3873 		if (found_key.type != BTRFS_DEV_EXTENT_KEY)
3874 			break;
3875 
3876 		if (found_key.offset >= end)
3877 			break;
3878 
3879 		if (found_key.offset < key.offset)
3880 			break;
3881 
3882 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3883 		dev_extent_len = btrfs_dev_extent_length(l, dev_extent);
3884 
3885 		if (found_key.offset + dev_extent_len <= start)
3886 			goto skip;
3887 
3888 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3889 
3890 		/*
3891 		 * get a reference on the corresponding block group to prevent
3892 		 * the chunk from going away while we scrub it
3893 		 */
3894 		cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3895 
3896 		/* some chunks are removed but not committed to disk yet,
3897 		 * continue scrubbing */
3898 		if (!cache)
3899 			goto skip;
3900 
3901 		ASSERT(cache->start <= chunk_offset);
3902 		/*
3903 		 * We are using the commit root to search for device extents, so
3904 		 * that means we could have found a device extent item from a
3905 		 * block group that was deleted in the current transaction. The
3906 		 * logical start offset of the deleted block group, stored at
3907 		 * @chunk_offset, might be part of the logical address range of
3908 		 * a new block group (which uses different physical extents).
3909 		 * In this case btrfs_lookup_block_group() has returned the new
3910 		 * block group, and its start address is less than @chunk_offset.
3911 		 *
3912 		 * We skip such new block groups, because it's pointless to
3913 		 * process them, as we won't find their extents because we search
3914 		 * for them using the commit root of the extent tree. For a device
3915 		 * replace it's also fine to skip it, we won't miss copying them
3916 		 * to the target device because we have the write duplication
3917 		 * setup through the regular write path (by btrfs_map_block()),
3918 		 * and we have committed a transaction when we started the device
3919 		 * replace, right after setting up the device replace state.
3920 		 */
3921 		if (cache->start < chunk_offset) {
3922 			btrfs_put_block_group(cache);
3923 			goto skip;
3924 		}
3925 
3926 		if (sctx->is_dev_replace && btrfs_is_zoned(fs_info)) {
3927 			if (!test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags)) {
3928 				btrfs_put_block_group(cache);
3929 				goto skip;
3930 			}
3931 		}
3932 
3933 		/*
3934 		 * Make sure that while we are scrubbing the corresponding block
3935 		 * group doesn't get its logical address and its device extents
3936 		 * reused for another block group, which can possibly be of a
3937 		 * different type and different profile. We do this to prevent
3938 		 * false error detections and crashes due to bogus attempts to
3939 		 * repair extents.
3940 		 */
3941 		spin_lock(&cache->lock);
3942 		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags)) {
3943 			spin_unlock(&cache->lock);
3944 			btrfs_put_block_group(cache);
3945 			goto skip;
3946 		}
3947 		btrfs_freeze_block_group(cache);
3948 		spin_unlock(&cache->lock);
3949 
3950 		/*
3951 		 * we need call btrfs_inc_block_group_ro() with scrubs_paused,
3952 		 * to avoid deadlock caused by:
3953 		 * btrfs_inc_block_group_ro()
3954 		 * -> btrfs_wait_for_commit()
3955 		 * -> btrfs_commit_transaction()
3956 		 * -> btrfs_scrub_pause()
3957 		 */
3958 		scrub_pause_on(fs_info);
3959 
3960 		/*
3961 		 * Don't do chunk preallocation for scrub.
3962 		 *
3963 		 * This is especially important for SYSTEM bgs, or we can hit
3964 		 * -EFBIG from btrfs_finish_chunk_alloc() like:
3965 		 * 1. The only SYSTEM bg is marked RO.
3966 		 *    Since SYSTEM bg is small, that's pretty common.
3967 		 * 2. New SYSTEM bg will be allocated
3968 		 *    Due to regular version will allocate new chunk.
3969 		 * 3. New SYSTEM bg is empty and will get cleaned up
3970 		 *    Before cleanup really happens, it's marked RO again.
3971 		 * 4. Empty SYSTEM bg get scrubbed
3972 		 *    We go back to 2.
3973 		 *
3974 		 * This can easily boost the amount of SYSTEM chunks if cleaner
3975 		 * thread can't be triggered fast enough, and use up all space
3976 		 * of btrfs_super_block::sys_chunk_array
3977 		 *
3978 		 * While for dev replace, we need to try our best to mark block
3979 		 * group RO, to prevent race between:
3980 		 * - Write duplication
3981 		 *   Contains latest data
3982 		 * - Scrub copy
3983 		 *   Contains data from commit tree
3984 		 *
3985 		 * If target block group is not marked RO, nocow writes can
3986 		 * be overwritten by scrub copy, causing data corruption.
3987 		 * So for dev-replace, it's not allowed to continue if a block
3988 		 * group is not RO.
3989 		 */
3990 		ret = btrfs_inc_block_group_ro(cache, sctx->is_dev_replace);
3991 		if (!ret && sctx->is_dev_replace) {
3992 			ret = finish_extent_writes_for_zoned(root, cache);
3993 			if (ret) {
3994 				btrfs_dec_block_group_ro(cache);
3995 				scrub_pause_off(fs_info);
3996 				btrfs_put_block_group(cache);
3997 				break;
3998 			}
3999 		}
4000 
4001 		if (ret == 0) {
4002 			ro_set = 1;
4003 		} else if (ret == -ENOSPC && !sctx->is_dev_replace) {
4004 			/*
4005 			 * btrfs_inc_block_group_ro return -ENOSPC when it
4006 			 * failed in creating new chunk for metadata.
4007 			 * It is not a problem for scrub, because
4008 			 * metadata are always cowed, and our scrub paused
4009 			 * commit_transactions.
4010 			 */
4011 			ro_set = 0;
4012 		} else if (ret == -ETXTBSY) {
4013 			btrfs_warn(fs_info,
4014 		   "skipping scrub of block group %llu due to active swapfile",
4015 				   cache->start);
4016 			scrub_pause_off(fs_info);
4017 			ret = 0;
4018 			goto skip_unfreeze;
4019 		} else {
4020 			btrfs_warn(fs_info,
4021 				   "failed setting block group ro: %d", ret);
4022 			btrfs_unfreeze_block_group(cache);
4023 			btrfs_put_block_group(cache);
4024 			scrub_pause_off(fs_info);
4025 			break;
4026 		}
4027 
4028 		/*
4029 		 * Now the target block is marked RO, wait for nocow writes to
4030 		 * finish before dev-replace.
4031 		 * COW is fine, as COW never overwrites extents in commit tree.
4032 		 */
4033 		if (sctx->is_dev_replace) {
4034 			btrfs_wait_nocow_writers(cache);
4035 			btrfs_wait_ordered_roots(fs_info, U64_MAX, cache->start,
4036 					cache->length);
4037 		}
4038 
4039 		scrub_pause_off(fs_info);
4040 		down_write(&dev_replace->rwsem);
4041 		dev_replace->cursor_right = found_key.offset + dev_extent_len;
4042 		dev_replace->cursor_left = found_key.offset;
4043 		dev_replace->item_needs_writeback = 1;
4044 		up_write(&dev_replace->rwsem);
4045 
4046 		ret = scrub_chunk(sctx, cache, scrub_dev, found_key.offset,
4047 				  dev_extent_len);
4048 
4049 		/*
4050 		 * flush, submit all pending read and write bios, afterwards
4051 		 * wait for them.
4052 		 * Note that in the dev replace case, a read request causes
4053 		 * write requests that are submitted in the read completion
4054 		 * worker. Therefore in the current situation, it is required
4055 		 * that all write requests are flushed, so that all read and
4056 		 * write requests are really completed when bios_in_flight
4057 		 * changes to 0.
4058 		 */
4059 		sctx->flush_all_writes = true;
4060 		scrub_submit(sctx);
4061 		mutex_lock(&sctx->wr_lock);
4062 		scrub_wr_submit(sctx);
4063 		mutex_unlock(&sctx->wr_lock);
4064 
4065 		wait_event(sctx->list_wait,
4066 			   atomic_read(&sctx->bios_in_flight) == 0);
4067 
4068 		scrub_pause_on(fs_info);
4069 
4070 		/*
4071 		 * must be called before we decrease @scrub_paused.
4072 		 * make sure we don't block transaction commit while
4073 		 * we are waiting pending workers finished.
4074 		 */
4075 		wait_event(sctx->list_wait,
4076 			   atomic_read(&sctx->workers_pending) == 0);
4077 		sctx->flush_all_writes = false;
4078 
4079 		scrub_pause_off(fs_info);
4080 
4081 		if (sctx->is_dev_replace &&
4082 		    !btrfs_finish_block_group_to_copy(dev_replace->srcdev,
4083 						      cache, found_key.offset))
4084 			ro_set = 0;
4085 
4086 		down_write(&dev_replace->rwsem);
4087 		dev_replace->cursor_left = dev_replace->cursor_right;
4088 		dev_replace->item_needs_writeback = 1;
4089 		up_write(&dev_replace->rwsem);
4090 
4091 		if (ro_set)
4092 			btrfs_dec_block_group_ro(cache);
4093 
4094 		/*
4095 		 * We might have prevented the cleaner kthread from deleting
4096 		 * this block group if it was already unused because we raced
4097 		 * and set it to RO mode first. So add it back to the unused
4098 		 * list, otherwise it might not ever be deleted unless a manual
4099 		 * balance is triggered or it becomes used and unused again.
4100 		 */
4101 		spin_lock(&cache->lock);
4102 		if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags) &&
4103 		    !cache->ro && cache->reserved == 0 && cache->used == 0) {
4104 			spin_unlock(&cache->lock);
4105 			if (btrfs_test_opt(fs_info, DISCARD_ASYNC))
4106 				btrfs_discard_queue_work(&fs_info->discard_ctl,
4107 							 cache);
4108 			else
4109 				btrfs_mark_bg_unused(cache);
4110 		} else {
4111 			spin_unlock(&cache->lock);
4112 		}
4113 skip_unfreeze:
4114 		btrfs_unfreeze_block_group(cache);
4115 		btrfs_put_block_group(cache);
4116 		if (ret)
4117 			break;
4118 		if (sctx->is_dev_replace &&
4119 		    atomic64_read(&dev_replace->num_write_errors) > 0) {
4120 			ret = -EIO;
4121 			break;
4122 		}
4123 		if (sctx->stat.malloc_errors > 0) {
4124 			ret = -ENOMEM;
4125 			break;
4126 		}
4127 skip:
4128 		key.offset = found_key.offset + dev_extent_len;
4129 		btrfs_release_path(path);
4130 	}
4131 
4132 	btrfs_free_path(path);
4133 
4134 	return ret;
4135 }
4136 
4137 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx,
4138 					   struct btrfs_device *scrub_dev)
4139 {
4140 	int	i;
4141 	u64	bytenr;
4142 	u64	gen;
4143 	int	ret;
4144 	struct btrfs_fs_info *fs_info = sctx->fs_info;
4145 
4146 	if (BTRFS_FS_ERROR(fs_info))
4147 		return -EROFS;
4148 
4149 	/* Seed devices of a new filesystem has their own generation. */
4150 	if (scrub_dev->fs_devices != fs_info->fs_devices)
4151 		gen = scrub_dev->generation;
4152 	else
4153 		gen = fs_info->last_trans_committed;
4154 
4155 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
4156 		bytenr = btrfs_sb_offset(i);
4157 		if (bytenr + BTRFS_SUPER_INFO_SIZE >
4158 		    scrub_dev->commit_total_bytes)
4159 			break;
4160 		if (!btrfs_check_super_location(scrub_dev, bytenr))
4161 			continue;
4162 
4163 		ret = scrub_sectors(sctx, bytenr, BTRFS_SUPER_INFO_SIZE, bytenr,
4164 				    scrub_dev, BTRFS_EXTENT_FLAG_SUPER, gen, i,
4165 				    NULL, bytenr);
4166 		if (ret)
4167 			return ret;
4168 	}
4169 	wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
4170 
4171 	return 0;
4172 }
4173 
4174 static void scrub_workers_put(struct btrfs_fs_info *fs_info)
4175 {
4176 	if (refcount_dec_and_mutex_lock(&fs_info->scrub_workers_refcnt,
4177 					&fs_info->scrub_lock)) {
4178 		struct workqueue_struct *scrub_workers = fs_info->scrub_workers;
4179 		struct workqueue_struct *scrub_wr_comp =
4180 						fs_info->scrub_wr_completion_workers;
4181 		struct workqueue_struct *scrub_parity =
4182 						fs_info->scrub_parity_workers;
4183 
4184 		fs_info->scrub_workers = NULL;
4185 		fs_info->scrub_wr_completion_workers = NULL;
4186 		fs_info->scrub_parity_workers = NULL;
4187 		mutex_unlock(&fs_info->scrub_lock);
4188 
4189 		if (scrub_workers)
4190 			destroy_workqueue(scrub_workers);
4191 		if (scrub_wr_comp)
4192 			destroy_workqueue(scrub_wr_comp);
4193 		if (scrub_parity)
4194 			destroy_workqueue(scrub_parity);
4195 	}
4196 }
4197 
4198 /*
4199  * get a reference count on fs_info->scrub_workers. start worker if necessary
4200  */
4201 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info,
4202 						int is_dev_replace)
4203 {
4204 	struct workqueue_struct *scrub_workers = NULL;
4205 	struct workqueue_struct *scrub_wr_comp = NULL;
4206 	struct workqueue_struct *scrub_parity = NULL;
4207 	unsigned int flags = WQ_FREEZABLE | WQ_UNBOUND;
4208 	int max_active = fs_info->thread_pool_size;
4209 	int ret = -ENOMEM;
4210 
4211 	if (refcount_inc_not_zero(&fs_info->scrub_workers_refcnt))
4212 		return 0;
4213 
4214 	scrub_workers = alloc_workqueue("btrfs-scrub", flags,
4215 					is_dev_replace ? 1 : max_active);
4216 	if (!scrub_workers)
4217 		goto fail_scrub_workers;
4218 
4219 	scrub_wr_comp = alloc_workqueue("btrfs-scrubwrc", flags, max_active);
4220 	if (!scrub_wr_comp)
4221 		goto fail_scrub_wr_completion_workers;
4222 
4223 	scrub_parity = alloc_workqueue("btrfs-scrubparity", flags, max_active);
4224 	if (!scrub_parity)
4225 		goto fail_scrub_parity_workers;
4226 
4227 	mutex_lock(&fs_info->scrub_lock);
4228 	if (refcount_read(&fs_info->scrub_workers_refcnt) == 0) {
4229 		ASSERT(fs_info->scrub_workers == NULL &&
4230 		       fs_info->scrub_wr_completion_workers == NULL &&
4231 		       fs_info->scrub_parity_workers == NULL);
4232 		fs_info->scrub_workers = scrub_workers;
4233 		fs_info->scrub_wr_completion_workers = scrub_wr_comp;
4234 		fs_info->scrub_parity_workers = scrub_parity;
4235 		refcount_set(&fs_info->scrub_workers_refcnt, 1);
4236 		mutex_unlock(&fs_info->scrub_lock);
4237 		return 0;
4238 	}
4239 	/* Other thread raced in and created the workers for us */
4240 	refcount_inc(&fs_info->scrub_workers_refcnt);
4241 	mutex_unlock(&fs_info->scrub_lock);
4242 
4243 	ret = 0;
4244 	destroy_workqueue(scrub_parity);
4245 fail_scrub_parity_workers:
4246 	destroy_workqueue(scrub_wr_comp);
4247 fail_scrub_wr_completion_workers:
4248 	destroy_workqueue(scrub_workers);
4249 fail_scrub_workers:
4250 	return ret;
4251 }
4252 
4253 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
4254 		    u64 end, struct btrfs_scrub_progress *progress,
4255 		    int readonly, int is_dev_replace)
4256 {
4257 	struct btrfs_dev_lookup_args args = { .devid = devid };
4258 	struct scrub_ctx *sctx;
4259 	int ret;
4260 	struct btrfs_device *dev;
4261 	unsigned int nofs_flag;
4262 	bool need_commit = false;
4263 
4264 	if (btrfs_fs_closing(fs_info))
4265 		return -EAGAIN;
4266 
4267 	/* At mount time we have ensured nodesize is in the range of [4K, 64K]. */
4268 	ASSERT(fs_info->nodesize <= BTRFS_STRIPE_LEN);
4269 
4270 	/*
4271 	 * SCRUB_MAX_SECTORS_PER_BLOCK is calculated using the largest possible
4272 	 * value (max nodesize / min sectorsize), thus nodesize should always
4273 	 * be fine.
4274 	 */
4275 	ASSERT(fs_info->nodesize <=
4276 	       SCRUB_MAX_SECTORS_PER_BLOCK << fs_info->sectorsize_bits);
4277 
4278 	/* Allocate outside of device_list_mutex */
4279 	sctx = scrub_setup_ctx(fs_info, is_dev_replace);
4280 	if (IS_ERR(sctx))
4281 		return PTR_ERR(sctx);
4282 
4283 	ret = scrub_workers_get(fs_info, is_dev_replace);
4284 	if (ret)
4285 		goto out_free_ctx;
4286 
4287 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
4288 	dev = btrfs_find_device(fs_info->fs_devices, &args);
4289 	if (!dev || (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) &&
4290 		     !is_dev_replace)) {
4291 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4292 		ret = -ENODEV;
4293 		goto out;
4294 	}
4295 
4296 	if (!is_dev_replace && !readonly &&
4297 	    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
4298 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4299 		btrfs_err_in_rcu(fs_info,
4300 			"scrub on devid %llu: filesystem on %s is not writable",
4301 				 devid, rcu_str_deref(dev->name));
4302 		ret = -EROFS;
4303 		goto out;
4304 	}
4305 
4306 	mutex_lock(&fs_info->scrub_lock);
4307 	if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4308 	    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &dev->dev_state)) {
4309 		mutex_unlock(&fs_info->scrub_lock);
4310 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4311 		ret = -EIO;
4312 		goto out;
4313 	}
4314 
4315 	down_read(&fs_info->dev_replace.rwsem);
4316 	if (dev->scrub_ctx ||
4317 	    (!is_dev_replace &&
4318 	     btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) {
4319 		up_read(&fs_info->dev_replace.rwsem);
4320 		mutex_unlock(&fs_info->scrub_lock);
4321 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4322 		ret = -EINPROGRESS;
4323 		goto out;
4324 	}
4325 	up_read(&fs_info->dev_replace.rwsem);
4326 
4327 	sctx->readonly = readonly;
4328 	dev->scrub_ctx = sctx;
4329 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4330 
4331 	/*
4332 	 * checking @scrub_pause_req here, we can avoid
4333 	 * race between committing transaction and scrubbing.
4334 	 */
4335 	__scrub_blocked_if_needed(fs_info);
4336 	atomic_inc(&fs_info->scrubs_running);
4337 	mutex_unlock(&fs_info->scrub_lock);
4338 
4339 	/*
4340 	 * In order to avoid deadlock with reclaim when there is a transaction
4341 	 * trying to pause scrub, make sure we use GFP_NOFS for all the
4342 	 * allocations done at btrfs_scrub_sectors() and scrub_sectors_for_parity()
4343 	 * invoked by our callees. The pausing request is done when the
4344 	 * transaction commit starts, and it blocks the transaction until scrub
4345 	 * is paused (done at specific points at scrub_stripe() or right above
4346 	 * before incrementing fs_info->scrubs_running).
4347 	 */
4348 	nofs_flag = memalloc_nofs_save();
4349 	if (!is_dev_replace) {
4350 		u64 old_super_errors;
4351 
4352 		spin_lock(&sctx->stat_lock);
4353 		old_super_errors = sctx->stat.super_errors;
4354 		spin_unlock(&sctx->stat_lock);
4355 
4356 		btrfs_info(fs_info, "scrub: started on devid %llu", devid);
4357 		/*
4358 		 * by holding device list mutex, we can
4359 		 * kick off writing super in log tree sync.
4360 		 */
4361 		mutex_lock(&fs_info->fs_devices->device_list_mutex);
4362 		ret = scrub_supers(sctx, dev);
4363 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4364 
4365 		spin_lock(&sctx->stat_lock);
4366 		/*
4367 		 * Super block errors found, but we can not commit transaction
4368 		 * at current context, since btrfs_commit_transaction() needs
4369 		 * to pause the current running scrub (hold by ourselves).
4370 		 */
4371 		if (sctx->stat.super_errors > old_super_errors && !sctx->readonly)
4372 			need_commit = true;
4373 		spin_unlock(&sctx->stat_lock);
4374 	}
4375 
4376 	if (!ret)
4377 		ret = scrub_enumerate_chunks(sctx, dev, start, end);
4378 	memalloc_nofs_restore(nofs_flag);
4379 
4380 	wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
4381 	atomic_dec(&fs_info->scrubs_running);
4382 	wake_up(&fs_info->scrub_pause_wait);
4383 
4384 	wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0);
4385 
4386 	if (progress)
4387 		memcpy(progress, &sctx->stat, sizeof(*progress));
4388 
4389 	if (!is_dev_replace)
4390 		btrfs_info(fs_info, "scrub: %s on devid %llu with status: %d",
4391 			ret ? "not finished" : "finished", devid, ret);
4392 
4393 	mutex_lock(&fs_info->scrub_lock);
4394 	dev->scrub_ctx = NULL;
4395 	mutex_unlock(&fs_info->scrub_lock);
4396 
4397 	scrub_workers_put(fs_info);
4398 	scrub_put_ctx(sctx);
4399 
4400 	/*
4401 	 * We found some super block errors before, now try to force a
4402 	 * transaction commit, as scrub has finished.
4403 	 */
4404 	if (need_commit) {
4405 		struct btrfs_trans_handle *trans;
4406 
4407 		trans = btrfs_start_transaction(fs_info->tree_root, 0);
4408 		if (IS_ERR(trans)) {
4409 			ret = PTR_ERR(trans);
4410 			btrfs_err(fs_info,
4411 	"scrub: failed to start transaction to fix super block errors: %d", ret);
4412 			return ret;
4413 		}
4414 		ret = btrfs_commit_transaction(trans);
4415 		if (ret < 0)
4416 			btrfs_err(fs_info,
4417 	"scrub: failed to commit transaction to fix super block errors: %d", ret);
4418 	}
4419 	return ret;
4420 out:
4421 	scrub_workers_put(fs_info);
4422 out_free_ctx:
4423 	scrub_free_ctx(sctx);
4424 
4425 	return ret;
4426 }
4427 
4428 void btrfs_scrub_pause(struct btrfs_fs_info *fs_info)
4429 {
4430 	mutex_lock(&fs_info->scrub_lock);
4431 	atomic_inc(&fs_info->scrub_pause_req);
4432 	while (atomic_read(&fs_info->scrubs_paused) !=
4433 	       atomic_read(&fs_info->scrubs_running)) {
4434 		mutex_unlock(&fs_info->scrub_lock);
4435 		wait_event(fs_info->scrub_pause_wait,
4436 			   atomic_read(&fs_info->scrubs_paused) ==
4437 			   atomic_read(&fs_info->scrubs_running));
4438 		mutex_lock(&fs_info->scrub_lock);
4439 	}
4440 	mutex_unlock(&fs_info->scrub_lock);
4441 }
4442 
4443 void btrfs_scrub_continue(struct btrfs_fs_info *fs_info)
4444 {
4445 	atomic_dec(&fs_info->scrub_pause_req);
4446 	wake_up(&fs_info->scrub_pause_wait);
4447 }
4448 
4449 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
4450 {
4451 	mutex_lock(&fs_info->scrub_lock);
4452 	if (!atomic_read(&fs_info->scrubs_running)) {
4453 		mutex_unlock(&fs_info->scrub_lock);
4454 		return -ENOTCONN;
4455 	}
4456 
4457 	atomic_inc(&fs_info->scrub_cancel_req);
4458 	while (atomic_read(&fs_info->scrubs_running)) {
4459 		mutex_unlock(&fs_info->scrub_lock);
4460 		wait_event(fs_info->scrub_pause_wait,
4461 			   atomic_read(&fs_info->scrubs_running) == 0);
4462 		mutex_lock(&fs_info->scrub_lock);
4463 	}
4464 	atomic_dec(&fs_info->scrub_cancel_req);
4465 	mutex_unlock(&fs_info->scrub_lock);
4466 
4467 	return 0;
4468 }
4469 
4470 int btrfs_scrub_cancel_dev(struct btrfs_device *dev)
4471 {
4472 	struct btrfs_fs_info *fs_info = dev->fs_info;
4473 	struct scrub_ctx *sctx;
4474 
4475 	mutex_lock(&fs_info->scrub_lock);
4476 	sctx = dev->scrub_ctx;
4477 	if (!sctx) {
4478 		mutex_unlock(&fs_info->scrub_lock);
4479 		return -ENOTCONN;
4480 	}
4481 	atomic_inc(&sctx->cancel_req);
4482 	while (dev->scrub_ctx) {
4483 		mutex_unlock(&fs_info->scrub_lock);
4484 		wait_event(fs_info->scrub_pause_wait,
4485 			   dev->scrub_ctx == NULL);
4486 		mutex_lock(&fs_info->scrub_lock);
4487 	}
4488 	mutex_unlock(&fs_info->scrub_lock);
4489 
4490 	return 0;
4491 }
4492 
4493 int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid,
4494 			 struct btrfs_scrub_progress *progress)
4495 {
4496 	struct btrfs_dev_lookup_args args = { .devid = devid };
4497 	struct btrfs_device *dev;
4498 	struct scrub_ctx *sctx = NULL;
4499 
4500 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
4501 	dev = btrfs_find_device(fs_info->fs_devices, &args);
4502 	if (dev)
4503 		sctx = dev->scrub_ctx;
4504 	if (sctx)
4505 		memcpy(progress, &sctx->stat, sizeof(*progress));
4506 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4507 
4508 	return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;
4509 }
4510 
4511 static void scrub_find_good_copy(struct btrfs_fs_info *fs_info,
4512 				 u64 extent_logical, u32 extent_len,
4513 				 u64 *extent_physical,
4514 				 struct btrfs_device **extent_dev,
4515 				 int *extent_mirror_num)
4516 {
4517 	u64 mapped_length;
4518 	struct btrfs_io_context *bioc = NULL;
4519 	int ret;
4520 
4521 	mapped_length = extent_len;
4522 	ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, extent_logical,
4523 			      &mapped_length, &bioc, 0);
4524 	if (ret || !bioc || mapped_length < extent_len ||
4525 	    !bioc->stripes[0].dev->bdev) {
4526 		btrfs_put_bioc(bioc);
4527 		return;
4528 	}
4529 
4530 	*extent_physical = bioc->stripes[0].physical;
4531 	*extent_mirror_num = bioc->mirror_num;
4532 	*extent_dev = bioc->stripes[0].dev;
4533 	btrfs_put_bioc(bioc);
4534 }
4535