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