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