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