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