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 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 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 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 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 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 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 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 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 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 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 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 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 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 */ 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 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 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. */ 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 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 */ 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 */ 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 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 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 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 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 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 const u64 sector_logical = stripe->logical + 1027 ((u64)sector_nr << fs_info->sectorsize_bits); 1028 const u64 sector_physical = physical + 1029 ((u64)sector_nr << fs_info->sectorsize_bits); 1030 bool repaired = false; 1031 1032 if (scrub_bitmap_test_bit_is_metadata(stripe, sector_nr)) { 1033 nr_meta_sectors++; 1034 } else { 1035 nr_data_sectors++; 1036 if (!stripe->sectors[sector_nr].csum) 1037 nr_nodatacsum_sectors++; 1038 } 1039 1040 if (test_bit(sector_nr, &errors->init_error_bitmap) && 1041 !test_bit(sector_nr, &error_bitmap)) { 1042 nr_repaired_sectors++; 1043 repaired = true; 1044 } 1045 1046 /* Good sector from the beginning, nothing need to be done. */ 1047 if (!test_bit(sector_nr, &errors->init_error_bitmap)) 1048 continue; 1049 1050 /* 1051 * Report error for the corrupted sectors. If repaired, just 1052 * output the message of repaired message. 1053 */ 1054 if (repaired) { 1055 if (dev) { 1056 btrfs_err_rl(fs_info, 1057 "scrub: fixed up error at logical %llu on dev %s physical %llu", 1058 sector_logical, btrfs_dev_name(dev), 1059 sector_physical); 1060 } else { 1061 btrfs_err_rl(fs_info, 1062 "scrub: fixed up error at logical %llu on mirror %u", 1063 sector_logical, stripe->mirror_num); 1064 } 1065 continue; 1066 } 1067 1068 /* The remaining are all for unrepaired. */ 1069 if (dev) { 1070 btrfs_err_rl(fs_info, 1071 "scrub: unable to fixup (regular) error at logical %llu on dev %s physical %llu", 1072 sector_logical, btrfs_dev_name(dev), 1073 sector_physical); 1074 } else { 1075 btrfs_err_rl(fs_info, 1076 "scrub: unable to fixup (regular) error at logical %llu on mirror %u", 1077 sector_logical, stripe->mirror_num); 1078 } 1079 1080 if (scrub_bitmap_test_bit_io_error(stripe, sector_nr)) 1081 if (__ratelimit(&rs) && dev) 1082 scrub_print_common_warning("i/o error", dev, false, 1083 sector_logical, sector_physical); 1084 if (scrub_bitmap_test_bit_csum_error(stripe, sector_nr)) 1085 if (__ratelimit(&rs) && dev) 1086 scrub_print_common_warning("checksum error", dev, false, 1087 sector_logical, sector_physical); 1088 if (scrub_bitmap_test_bit_meta_error(stripe, sector_nr)) 1089 if (__ratelimit(&rs) && dev) 1090 scrub_print_common_warning("header error", dev, false, 1091 sector_logical, sector_physical); 1092 if (scrub_bitmap_test_bit_meta_gen_error(stripe, sector_nr)) 1093 if (__ratelimit(&rs) && dev) 1094 scrub_print_common_warning("generation error", dev, false, 1095 sector_logical, sector_physical); 1096 } 1097 1098 /* Update the device stats. */ 1099 for (int i = 0; i < errors->nr_io_errors; i++) 1100 btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_READ_ERRS); 1101 for (int i = 0; i < errors->nr_csum_errors; i++) 1102 btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_CORRUPTION_ERRS); 1103 /* Generation mismatch error is based on each metadata, not each block. */ 1104 for (int i = 0; i < errors->nr_meta_gen_errors; 1105 i += (fs_info->nodesize >> fs_info->sectorsize_bits)) 1106 btrfs_dev_stat_inc_and_print(stripe->dev, BTRFS_DEV_STAT_GENERATION_ERRS); 1107 1108 spin_lock(&sctx->stat_lock); 1109 sctx->stat.data_extents_scrubbed += stripe->nr_data_extents; 1110 sctx->stat.tree_extents_scrubbed += stripe->nr_meta_extents; 1111 sctx->stat.data_bytes_scrubbed += nr_data_sectors << fs_info->sectorsize_bits; 1112 sctx->stat.tree_bytes_scrubbed += nr_meta_sectors << fs_info->sectorsize_bits; 1113 sctx->stat.no_csum += nr_nodatacsum_sectors; 1114 sctx->stat.read_errors += errors->nr_io_errors; 1115 sctx->stat.csum_errors += errors->nr_csum_errors; 1116 sctx->stat.verify_errors += errors->nr_meta_errors + 1117 errors->nr_meta_gen_errors; 1118 sctx->stat.uncorrectable_errors += 1119 bitmap_weight(&error_bitmap, stripe->nr_sectors); 1120 sctx->stat.corrected_errors += nr_repaired_sectors; 1121 spin_unlock(&sctx->stat_lock); 1122 } 1123 1124 static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *stripe, 1125 unsigned long write_bitmap, bool dev_replace); 1126 1127 /* 1128 * The main entrance for all read related scrub work, including: 1129 * 1130 * - Wait for the initial read to finish 1131 * - Verify and locate any bad sectors 1132 * - Go through the remaining mirrors and try to read as large blocksize as 1133 * possible 1134 * - Go through all mirrors (including the failed mirror) sector-by-sector 1135 * - Submit writeback for repaired sectors 1136 * 1137 * Writeback for dev-replace does not happen here, it needs extra 1138 * synchronization for zoned devices. 1139 */ 1140 static void scrub_stripe_read_repair_worker(struct work_struct *work) 1141 { 1142 struct scrub_stripe *stripe = container_of(work, struct scrub_stripe, work); 1143 struct scrub_ctx *sctx = stripe->sctx; 1144 struct btrfs_fs_info *fs_info = sctx->fs_info; 1145 struct scrub_error_records errors = { 0 }; 1146 int num_copies = btrfs_num_copies(fs_info, stripe->bg->start, 1147 stripe->bg->length); 1148 unsigned long repaired; 1149 unsigned long error; 1150 int mirror; 1151 int i; 1152 1153 ASSERT(stripe->mirror_num >= 1, "stripe->mirror_num=%d", stripe->mirror_num); 1154 1155 wait_scrub_stripe_io(stripe); 1156 scrub_verify_one_stripe(stripe, scrub_bitmap_read_has_extent(stripe)); 1157 /* Save the initial failed bitmap for later repair and report usage. */ 1158 errors.init_error_bitmap = scrub_bitmap_read_error(stripe); 1159 errors.nr_io_errors = scrub_bitmap_weight_io_error(stripe); 1160 errors.nr_csum_errors = scrub_bitmap_weight_csum_error(stripe); 1161 errors.nr_meta_errors = scrub_bitmap_weight_meta_error(stripe); 1162 errors.nr_meta_gen_errors = scrub_bitmap_weight_meta_gen_error(stripe); 1163 1164 if (bitmap_empty(&errors.init_error_bitmap, stripe->nr_sectors)) 1165 goto out; 1166 1167 /* 1168 * Try all remaining mirrors. 1169 * 1170 * Here we still try to read as large block as possible, as this is 1171 * faster and we have extra safety nets to rely on. 1172 */ 1173 for (mirror = calc_next_mirror(stripe->mirror_num, num_copies); 1174 mirror != stripe->mirror_num; 1175 mirror = calc_next_mirror(mirror, num_copies)) { 1176 const unsigned long old_error_bitmap = scrub_bitmap_read_error(stripe); 1177 1178 scrub_stripe_submit_repair_read(stripe, mirror, 1179 BTRFS_STRIPE_LEN, false); 1180 wait_scrub_stripe_io(stripe); 1181 scrub_verify_one_stripe(stripe, old_error_bitmap); 1182 if (scrub_bitmap_empty_error(stripe)) 1183 goto out; 1184 } 1185 1186 /* 1187 * Last safety net, try re-checking all mirrors, including the failed 1188 * one, sector-by-sector. 1189 * 1190 * As if one sector failed the drive's internal csum, the whole read 1191 * containing the offending sector would be marked as error. 1192 * Thus here we do sector-by-sector read. 1193 * 1194 * This can be slow, thus we only try it as the last resort. 1195 */ 1196 1197 for (i = 0, mirror = stripe->mirror_num; 1198 i < num_copies; 1199 i++, mirror = calc_next_mirror(mirror, num_copies)) { 1200 const unsigned long old_error_bitmap = scrub_bitmap_read_error(stripe); 1201 1202 scrub_stripe_submit_repair_read(stripe, mirror, 1203 fs_info->sectorsize, true); 1204 wait_scrub_stripe_io(stripe); 1205 scrub_verify_one_stripe(stripe, old_error_bitmap); 1206 if (scrub_bitmap_empty_error(stripe)) 1207 goto out; 1208 } 1209 out: 1210 error = scrub_bitmap_read_error(stripe); 1211 /* 1212 * Submit the repaired sectors. For zoned case, we cannot do repair 1213 * in-place, but queue the bg to be relocated. 1214 */ 1215 bitmap_andnot(&repaired, &errors.init_error_bitmap, &error, 1216 stripe->nr_sectors); 1217 if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors)) { 1218 if (btrfs_is_zoned(fs_info)) { 1219 btrfs_repair_one_zone(fs_info, sctx->stripes[0].bg->start); 1220 } else { 1221 scrub_write_sectors(sctx, stripe, repaired, false); 1222 wait_scrub_stripe_io(stripe); 1223 } 1224 } 1225 1226 scrub_stripe_report_errors(sctx, stripe, &errors); 1227 set_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state); 1228 wake_up(&stripe->repair_wait); 1229 } 1230 1231 static void scrub_read_endio(struct btrfs_bio *bbio) 1232 { 1233 struct scrub_stripe *stripe = bbio->private; 1234 1235 scrub_read_endio_common(bbio); 1236 1237 if (atomic_dec_and_test(&stripe->pending_io)) { 1238 wake_up(&stripe->io_wait); 1239 INIT_WORK(&stripe->work, scrub_stripe_read_repair_worker); 1240 queue_work(stripe->bg->fs_info->scrub_workers, &stripe->work); 1241 } 1242 } 1243 1244 static void scrub_write_endio(struct btrfs_bio *bbio) 1245 { 1246 struct scrub_stripe *stripe = bbio->private; 1247 struct btrfs_fs_info *fs_info = stripe->bg->fs_info; 1248 unsigned int sector_nr = calc_sector_number(bbio); 1249 const u32 bio_size = bio_get_size(&bbio->bio); 1250 1251 if (bbio->bio.bi_status) { 1252 unsigned long flags; 1253 1254 spin_lock_irqsave(&stripe->write_error_lock, flags); 1255 bitmap_set(&stripe->write_error_bitmap, sector_nr, 1256 bio_size >> fs_info->sectorsize_bits); 1257 spin_unlock_irqrestore(&stripe->write_error_lock, flags); 1258 for (int i = 0; i < (bio_size >> fs_info->sectorsize_bits); i++) 1259 btrfs_dev_stat_inc_and_print(stripe->dev, 1260 BTRFS_DEV_STAT_WRITE_ERRS); 1261 } 1262 bio_put(&bbio->bio); 1263 1264 if (atomic_dec_and_test(&stripe->pending_io)) 1265 wake_up(&stripe->io_wait); 1266 } 1267 1268 static void scrub_submit_write_bio(struct scrub_ctx *sctx, 1269 struct scrub_stripe *stripe, 1270 struct btrfs_bio *bbio, bool dev_replace) 1271 { 1272 struct btrfs_fs_info *fs_info = sctx->fs_info; 1273 u32 bio_len = bbio->bio.bi_iter.bi_size; 1274 u32 bio_off = (bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT) - 1275 stripe->logical; 1276 1277 fill_writer_pointer_gap(sctx, stripe->physical + bio_off); 1278 atomic_inc(&stripe->pending_io); 1279 btrfs_submit_repair_write(bbio, stripe->mirror_num, dev_replace); 1280 if (!btrfs_is_zoned(fs_info)) 1281 return; 1282 /* 1283 * For zoned writeback, queue depth must be 1, thus we must wait for 1284 * the write to finish before the next write. 1285 */ 1286 wait_scrub_stripe_io(stripe); 1287 1288 /* 1289 * And also need to update the write pointer if write finished 1290 * successfully. 1291 */ 1292 if (!test_bit(bio_off >> fs_info->sectorsize_bits, 1293 &stripe->write_error_bitmap)) 1294 sctx->write_pointer += bio_len; 1295 } 1296 1297 /* 1298 * Submit the write bio(s) for the sectors specified by @write_bitmap. 1299 * 1300 * Here we utilize btrfs_submit_repair_write(), which has some extra benefits: 1301 * 1302 * - Only needs logical bytenr and mirror_num 1303 * Just like the scrub read path 1304 * 1305 * - Would only result in writes to the specified mirror 1306 * Unlike the regular writeback path, which would write back to all stripes 1307 * 1308 * - Handle dev-replace and read-repair writeback differently 1309 */ 1310 static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *stripe, 1311 unsigned long write_bitmap, bool dev_replace) 1312 { 1313 struct btrfs_fs_info *fs_info = stripe->bg->fs_info; 1314 struct btrfs_bio *bbio = NULL; 1315 int sector_nr; 1316 1317 for_each_set_bit(sector_nr, &write_bitmap, stripe->nr_sectors) { 1318 /* We should only writeback sectors covered by an extent. */ 1319 ASSERT(scrub_bitmap_test_bit_has_extent(stripe, sector_nr)); 1320 1321 /* Cannot merge with previous sector, submit the current one. */ 1322 if (bbio && sector_nr && !test_bit(sector_nr - 1, &write_bitmap)) { 1323 scrub_submit_write_bio(sctx, stripe, bbio, dev_replace); 1324 bbio = NULL; 1325 } 1326 if (!bbio) 1327 bbio = alloc_scrub_bbio(fs_info, REQ_OP_WRITE, 1328 stripe->logical + (sector_nr << fs_info->sectorsize_bits), 1329 scrub_write_endio, stripe); 1330 scrub_bio_add_sector(bbio, stripe, sector_nr); 1331 } 1332 if (bbio) 1333 scrub_submit_write_bio(sctx, stripe, bbio, dev_replace); 1334 } 1335 1336 /* 1337 * Throttling of IO submission, bandwidth-limit based, the timeslice is 1 1338 * second. Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max. 1339 */ 1340 static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *device, 1341 unsigned int bio_size) 1342 { 1343 const int time_slice = 1000; 1344 s64 delta; 1345 ktime_t now; 1346 u32 div; 1347 u64 bwlimit; 1348 1349 bwlimit = READ_ONCE(device->scrub_speed_max); 1350 if (bwlimit == 0) 1351 return; 1352 1353 /* 1354 * Slice is divided into intervals when the IO is submitted, adjust by 1355 * bwlimit and maximum of 64 intervals. 1356 */ 1357 div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64); 1358 1359 /* Start new epoch, set deadline */ 1360 now = ktime_get(); 1361 if (sctx->throttle_deadline == 0) { 1362 sctx->throttle_deadline = ktime_add_ms(now, time_slice / div); 1363 sctx->throttle_sent = 0; 1364 } 1365 1366 /* Still in the time to send? */ 1367 if (ktime_before(now, sctx->throttle_deadline)) { 1368 /* If current bio is within the limit, send it */ 1369 sctx->throttle_sent += bio_size; 1370 if (sctx->throttle_sent <= div_u64(bwlimit, div)) 1371 return; 1372 1373 /* We're over the limit, sleep until the rest of the slice */ 1374 delta = ktime_ms_delta(sctx->throttle_deadline, now); 1375 } else { 1376 /* New request after deadline, start new epoch */ 1377 delta = 0; 1378 } 1379 1380 if (delta) { 1381 long timeout; 1382 1383 timeout = div_u64(delta * HZ, 1000); 1384 schedule_timeout_interruptible(timeout); 1385 } 1386 1387 /* Next call will start the deadline period */ 1388 sctx->throttle_deadline = 0; 1389 } 1390 1391 /* 1392 * Given a physical address, this will calculate it's 1393 * logical offset. if this is a parity stripe, it will return 1394 * the most left data stripe's logical offset. 1395 * 1396 * return 0 if it is a data stripe, 1 means parity stripe. 1397 */ 1398 static int get_raid56_logic_offset(u64 physical, int num, 1399 struct btrfs_chunk_map *map, u64 *offset, 1400 u64 *stripe_start) 1401 { 1402 int i; 1403 int j = 0; 1404 u64 last_offset; 1405 const int data_stripes = nr_data_stripes(map); 1406 1407 last_offset = (physical - map->stripes[num].physical) * data_stripes; 1408 if (stripe_start) 1409 *stripe_start = last_offset; 1410 1411 *offset = last_offset; 1412 for (i = 0; i < data_stripes; i++) { 1413 u32 stripe_nr; 1414 u32 stripe_index; 1415 u32 rot; 1416 1417 *offset = last_offset + btrfs_stripe_nr_to_offset(i); 1418 1419 stripe_nr = (u32)(*offset >> BTRFS_STRIPE_LEN_SHIFT) / data_stripes; 1420 1421 /* Work out the disk rotation on this stripe-set */ 1422 rot = stripe_nr % map->num_stripes; 1423 /* calculate which stripe this data locates */ 1424 rot += i; 1425 stripe_index = rot % map->num_stripes; 1426 if (stripe_index == num) 1427 return 0; 1428 if (stripe_index < num) 1429 j++; 1430 } 1431 *offset = last_offset + btrfs_stripe_nr_to_offset(j); 1432 return 1; 1433 } 1434 1435 /* 1436 * Return 0 if the extent item range covers any byte of the range. 1437 * Return <0 if the extent item is before @search_start. 1438 * Return >0 if the extent item is after @start_start + @search_len. 1439 */ 1440 static int compare_extent_item_range(struct btrfs_path *path, 1441 u64 search_start, u64 search_len) 1442 { 1443 struct btrfs_fs_info *fs_info = path->nodes[0]->fs_info; 1444 u64 len; 1445 struct btrfs_key key; 1446 1447 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); 1448 ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY || 1449 key.type == BTRFS_METADATA_ITEM_KEY, "key.type=%u", key.type); 1450 if (key.type == BTRFS_METADATA_ITEM_KEY) 1451 len = fs_info->nodesize; 1452 else 1453 len = key.offset; 1454 1455 if (key.objectid + len <= search_start) 1456 return -1; 1457 if (key.objectid >= search_start + search_len) 1458 return 1; 1459 return 0; 1460 } 1461 1462 /* 1463 * Locate one extent item which covers any byte in range 1464 * [@search_start, @search_start + @search_length) 1465 * 1466 * If the path is not initialized, we will initialize the search by doing 1467 * a btrfs_search_slot(). 1468 * If the path is already initialized, we will use the path as the initial 1469 * slot, to avoid duplicated btrfs_search_slot() calls. 1470 * 1471 * NOTE: If an extent item starts before @search_start, we will still 1472 * return the extent item. This is for data extent crossing stripe boundary. 1473 * 1474 * Return 0 if we found such extent item, and @path will point to the extent item. 1475 * Return >0 if no such extent item can be found, and @path will be released. 1476 * Return <0 if hit fatal error, and @path will be released. 1477 */ 1478 static int find_first_extent_item(struct btrfs_root *extent_root, 1479 struct btrfs_path *path, 1480 u64 search_start, u64 search_len) 1481 { 1482 struct btrfs_fs_info *fs_info = extent_root->fs_info; 1483 struct btrfs_key key; 1484 int ret; 1485 1486 /* Continue using the existing path */ 1487 if (path->nodes[0]) 1488 goto search_forward; 1489 1490 key.objectid = search_start; 1491 if (btrfs_fs_incompat(fs_info, SKINNY_METADATA)) 1492 key.type = BTRFS_METADATA_ITEM_KEY; 1493 else 1494 key.type = BTRFS_EXTENT_ITEM_KEY; 1495 key.offset = (u64)-1; 1496 1497 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0); 1498 if (ret < 0) 1499 return ret; 1500 if (unlikely(ret == 0)) { 1501 /* 1502 * Key with offset -1 found, there would have to exist an extent 1503 * item with such offset, but this is out of the valid range. 1504 */ 1505 btrfs_release_path(path); 1506 return -EUCLEAN; 1507 } 1508 1509 /* 1510 * Here we intentionally pass 0 as @min_objectid, as there could be 1511 * an extent item starting before @search_start. 1512 */ 1513 ret = btrfs_previous_extent_item(extent_root, path, 0); 1514 if (ret < 0) 1515 return ret; 1516 /* 1517 * No matter whether we have found an extent item, the next loop will 1518 * properly do every check on the key. 1519 */ 1520 search_forward: 1521 while (true) { 1522 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); 1523 if (key.objectid >= search_start + search_len) 1524 break; 1525 if (key.type != BTRFS_METADATA_ITEM_KEY && 1526 key.type != BTRFS_EXTENT_ITEM_KEY) 1527 goto next; 1528 1529 ret = compare_extent_item_range(path, search_start, search_len); 1530 if (ret == 0) 1531 return ret; 1532 if (ret > 0) 1533 break; 1534 next: 1535 ret = btrfs_next_item(extent_root, path); 1536 if (ret) { 1537 /* Either no more items or a fatal error. */ 1538 btrfs_release_path(path); 1539 return ret; 1540 } 1541 } 1542 btrfs_release_path(path); 1543 return 1; 1544 } 1545 1546 static void get_extent_info(struct btrfs_path *path, u64 *extent_start_ret, 1547 u64 *size_ret, u64 *flags_ret, u64 *generation_ret) 1548 { 1549 struct btrfs_key key; 1550 struct btrfs_extent_item *ei; 1551 1552 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); 1553 ASSERT(key.type == BTRFS_METADATA_ITEM_KEY || 1554 key.type == BTRFS_EXTENT_ITEM_KEY, "key.type=%u", key.type); 1555 *extent_start_ret = key.objectid; 1556 if (key.type == BTRFS_METADATA_ITEM_KEY) 1557 *size_ret = path->nodes[0]->fs_info->nodesize; 1558 else 1559 *size_ret = key.offset; 1560 ei = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_extent_item); 1561 *flags_ret = btrfs_extent_flags(path->nodes[0], ei); 1562 *generation_ret = btrfs_extent_generation(path->nodes[0], ei); 1563 } 1564 1565 static int sync_write_pointer_for_zoned(struct scrub_ctx *sctx, u64 logical, 1566 u64 physical, u64 physical_end) 1567 { 1568 struct btrfs_fs_info *fs_info = sctx->fs_info; 1569 int ret = 0; 1570 1571 if (!btrfs_is_zoned(fs_info)) 1572 return 0; 1573 1574 mutex_lock(&sctx->wr_lock); 1575 if (sctx->write_pointer < physical_end) { 1576 ret = btrfs_sync_zone_write_pointer(sctx->wr_tgtdev, logical, 1577 physical, 1578 sctx->write_pointer); 1579 if (ret) 1580 btrfs_err(fs_info, "scrub: zoned: failed to recover write pointer"); 1581 } 1582 mutex_unlock(&sctx->wr_lock); 1583 btrfs_dev_clear_zone_empty(sctx->wr_tgtdev, physical); 1584 1585 return ret; 1586 } 1587 1588 static void fill_one_extent_info(struct btrfs_fs_info *fs_info, 1589 struct scrub_stripe *stripe, 1590 u64 extent_start, u64 extent_len, 1591 u64 extent_flags, u64 extent_gen) 1592 { 1593 for (u64 cur_logical = max(stripe->logical, extent_start); 1594 cur_logical < min(stripe->logical + BTRFS_STRIPE_LEN, 1595 extent_start + extent_len); 1596 cur_logical += fs_info->sectorsize) { 1597 const int nr_sector = (cur_logical - stripe->logical) >> 1598 fs_info->sectorsize_bits; 1599 struct scrub_sector_verification *sector = 1600 &stripe->sectors[nr_sector]; 1601 1602 scrub_bitmap_set_bit_has_extent(stripe, nr_sector); 1603 if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) { 1604 scrub_bitmap_set_bit_is_metadata(stripe, nr_sector); 1605 sector->generation = extent_gen; 1606 } 1607 } 1608 } 1609 1610 static void scrub_stripe_reset_bitmaps(struct scrub_stripe *stripe) 1611 { 1612 ASSERT(stripe->nr_sectors); 1613 bitmap_zero(stripe->bitmaps, scrub_bitmap_nr_last * stripe->nr_sectors); 1614 } 1615 1616 /* 1617 * Locate one stripe which has at least one extent in its range. 1618 * 1619 * Return 0 if found such stripe, and store its info into @stripe. 1620 * Return >0 if there is no such stripe in the specified range. 1621 * Return <0 for error. 1622 */ 1623 static int scrub_find_fill_first_stripe(struct btrfs_block_group *bg, 1624 struct btrfs_path *extent_path, 1625 struct btrfs_path *csum_path, 1626 struct btrfs_device *dev, u64 physical, 1627 int mirror_num, u64 logical_start, 1628 u32 logical_len, 1629 struct scrub_stripe *stripe) 1630 { 1631 struct btrfs_fs_info *fs_info = bg->fs_info; 1632 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bg->start); 1633 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bg->start); 1634 const u64 logical_end = logical_start + logical_len; 1635 u64 cur_logical = logical_start; 1636 u64 stripe_end; 1637 u64 extent_start; 1638 u64 extent_len; 1639 u64 extent_flags; 1640 u64 extent_gen; 1641 int ret; 1642 1643 if (unlikely(!extent_root || !csum_root)) { 1644 btrfs_err(fs_info, "scrub: no valid extent or csum root found"); 1645 return -EUCLEAN; 1646 } 1647 memset(stripe->sectors, 0, sizeof(struct scrub_sector_verification) * 1648 stripe->nr_sectors); 1649 scrub_stripe_reset_bitmaps(stripe); 1650 1651 /* The range must be inside the bg. */ 1652 ASSERT(logical_start >= bg->start && logical_end <= btrfs_block_group_end(bg), 1653 "bg->start=%llu logical_start=%llu logical_end=%llu end=%llu", 1654 bg->start, logical_start, logical_end, btrfs_block_group_end(bg)); 1655 1656 ret = find_first_extent_item(extent_root, extent_path, logical_start, 1657 logical_len); 1658 /* Either error or not found. */ 1659 if (ret) 1660 return ret; 1661 get_extent_info(extent_path, &extent_start, &extent_len, &extent_flags, 1662 &extent_gen); 1663 if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) 1664 stripe->nr_meta_extents++; 1665 if (extent_flags & BTRFS_EXTENT_FLAG_DATA) 1666 stripe->nr_data_extents++; 1667 cur_logical = max(extent_start, cur_logical); 1668 1669 /* 1670 * Round down to stripe boundary. 1671 * 1672 * The extra calculation against bg->start is to handle block groups 1673 * whose logical bytenr is not BTRFS_STRIPE_LEN aligned. 1674 */ 1675 stripe->logical = round_down(cur_logical - bg->start, BTRFS_STRIPE_LEN) + 1676 bg->start; 1677 stripe->physical = physical + stripe->logical - logical_start; 1678 stripe->dev = dev; 1679 stripe->bg = bg; 1680 stripe->mirror_num = mirror_num; 1681 stripe_end = stripe->logical + BTRFS_STRIPE_LEN - 1; 1682 1683 /* Fill the first extent info into stripe->sectors[] array. */ 1684 fill_one_extent_info(fs_info, stripe, extent_start, extent_len, 1685 extent_flags, extent_gen); 1686 cur_logical = extent_start + extent_len; 1687 1688 /* Fill the extent info for the remaining sectors. */ 1689 while (cur_logical <= stripe_end) { 1690 ret = find_first_extent_item(extent_root, extent_path, cur_logical, 1691 stripe_end - cur_logical + 1); 1692 if (ret < 0) 1693 return ret; 1694 if (ret > 0) { 1695 ret = 0; 1696 break; 1697 } 1698 get_extent_info(extent_path, &extent_start, &extent_len, 1699 &extent_flags, &extent_gen); 1700 if (extent_flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) 1701 stripe->nr_meta_extents++; 1702 if (extent_flags & BTRFS_EXTENT_FLAG_DATA) 1703 stripe->nr_data_extents++; 1704 fill_one_extent_info(fs_info, stripe, extent_start, extent_len, 1705 extent_flags, extent_gen); 1706 cur_logical = extent_start + extent_len; 1707 } 1708 1709 /* Now fill the data csum. */ 1710 if (bg->flags & BTRFS_BLOCK_GROUP_DATA) { 1711 int sector_nr; 1712 unsigned long csum_bitmap = 0; 1713 1714 /* Csum space should have already been allocated. */ 1715 ASSERT(stripe->csums); 1716 1717 /* 1718 * Our csum bitmap should be large enough, as BTRFS_STRIPE_LEN 1719 * should contain at most 16 sectors. 1720 */ 1721 ASSERT(BITS_PER_LONG >= BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits); 1722 1723 ret = btrfs_lookup_csums_bitmap(csum_root, csum_path, 1724 stripe->logical, stripe_end, 1725 stripe->csums, &csum_bitmap); 1726 if (ret < 0) 1727 return ret; 1728 if (ret > 0) 1729 ret = 0; 1730 1731 for_each_set_bit(sector_nr, &csum_bitmap, stripe->nr_sectors) { 1732 stripe->sectors[sector_nr].csum = stripe->csums + 1733 sector_nr * fs_info->csum_size; 1734 } 1735 } 1736 set_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state); 1737 1738 return ret; 1739 } 1740 1741 static void scrub_reset_stripe(struct scrub_stripe *stripe) 1742 { 1743 scrub_stripe_reset_bitmaps(stripe); 1744 1745 stripe->nr_meta_extents = 0; 1746 stripe->nr_data_extents = 0; 1747 stripe->state = 0; 1748 1749 for (int i = 0; i < stripe->nr_sectors; i++) { 1750 stripe->sectors[i].csum = NULL; 1751 stripe->sectors[i].generation = 0; 1752 } 1753 } 1754 1755 static u32 stripe_length(const struct scrub_stripe *stripe) 1756 { 1757 ASSERT(stripe->bg); 1758 1759 return min(BTRFS_STRIPE_LEN, 1760 stripe->bg->start + stripe->bg->length - stripe->logical); 1761 } 1762 1763 static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe) 1764 { 1765 struct btrfs_fs_info *fs_info = stripe->bg->fs_info; 1766 struct btrfs_bio *bbio = NULL; 1767 unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits; 1768 const unsigned long has_extent = scrub_bitmap_read_has_extent(stripe); 1769 u64 stripe_len = BTRFS_STRIPE_LEN; 1770 int mirror = stripe->mirror_num; 1771 int i; 1772 1773 atomic_inc(&stripe->pending_io); 1774 1775 for_each_set_bit(i, &has_extent, stripe->nr_sectors) { 1776 /* We're beyond the chunk boundary, no need to read anymore. */ 1777 if (i >= nr_sectors) 1778 break; 1779 1780 /* The current sector cannot be merged, submit the bio. */ 1781 if (bbio && 1782 ((i > 0 && !test_bit(i - 1, &has_extent)) || 1783 bbio->bio.bi_iter.bi_size >= stripe_len)) { 1784 ASSERT(bbio->bio.bi_iter.bi_size); 1785 atomic_inc(&stripe->pending_io); 1786 btrfs_submit_bbio(bbio, mirror); 1787 bbio = NULL; 1788 } 1789 1790 if (!bbio) { 1791 struct btrfs_io_stripe io_stripe = {}; 1792 struct btrfs_io_context *bioc = NULL; 1793 const u64 logical = stripe->logical + 1794 (i << fs_info->sectorsize_bits); 1795 int ret; 1796 1797 io_stripe.rst_search_commit_root = true; 1798 stripe_len = (nr_sectors - i) << fs_info->sectorsize_bits; 1799 /* 1800 * For RST cases, we need to manually split the bbio to 1801 * follow the RST boundary. 1802 */ 1803 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical, 1804 &stripe_len, &bioc, &io_stripe, &mirror); 1805 btrfs_put_bioc(bioc); 1806 if (ret < 0) { 1807 if (ret != -ENODATA) { 1808 /* 1809 * Earlier btrfs_get_raid_extent_offset() 1810 * returned -ENODATA, which means there's 1811 * no entry for the corresponding range 1812 * in the stripe tree. But if it's in 1813 * the extent tree, then it's a preallocated 1814 * extent and not an error. 1815 */ 1816 scrub_bitmap_set_bit_io_error(stripe, i); 1817 scrub_bitmap_set_bit_error(stripe, i); 1818 } 1819 continue; 1820 } 1821 1822 bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ, 1823 logical, scrub_read_endio, stripe); 1824 } 1825 1826 scrub_bio_add_sector(bbio, stripe, i); 1827 } 1828 1829 if (bbio) { 1830 ASSERT(bbio->bio.bi_iter.bi_size); 1831 atomic_inc(&stripe->pending_io); 1832 btrfs_submit_bbio(bbio, mirror); 1833 } 1834 1835 if (atomic_dec_and_test(&stripe->pending_io)) { 1836 wake_up(&stripe->io_wait); 1837 INIT_WORK(&stripe->work, scrub_stripe_read_repair_worker); 1838 queue_work(stripe->bg->fs_info->scrub_workers, &stripe->work); 1839 } 1840 } 1841 1842 static void scrub_submit_initial_read(struct scrub_ctx *sctx, 1843 struct scrub_stripe *stripe) 1844 { 1845 struct btrfs_fs_info *fs_info = sctx->fs_info; 1846 struct btrfs_bio *bbio; 1847 unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits; 1848 int mirror = stripe->mirror_num; 1849 1850 ASSERT(stripe->bg); 1851 ASSERT(stripe->mirror_num > 0); 1852 ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state)); 1853 1854 if (btrfs_need_stripe_tree_update(fs_info, stripe->bg->flags)) { 1855 scrub_submit_extent_sector_read(stripe); 1856 return; 1857 } 1858 1859 bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ, 1860 stripe->logical, scrub_read_endio, stripe); 1861 /* Read the whole range inside the chunk boundary. */ 1862 for (unsigned int cur = 0; cur < nr_sectors; cur++) 1863 scrub_bio_add_sector(bbio, stripe, cur); 1864 atomic_inc(&stripe->pending_io); 1865 1866 /* 1867 * For dev-replace, either user asks to avoid the source dev, or 1868 * the device is missing, we try the next mirror instead. 1869 */ 1870 if (sctx->is_dev_replace && 1871 (fs_info->dev_replace.cont_reading_from_srcdev_mode == 1872 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID || 1873 !stripe->dev->bdev)) { 1874 int num_copies = btrfs_num_copies(fs_info, stripe->bg->start, 1875 stripe->bg->length); 1876 1877 mirror = calc_next_mirror(mirror, num_copies); 1878 } 1879 btrfs_submit_bbio(bbio, mirror); 1880 } 1881 1882 static bool stripe_has_metadata_error(struct scrub_stripe *stripe) 1883 { 1884 const unsigned long error = scrub_bitmap_read_error(stripe); 1885 int i; 1886 1887 for_each_set_bit(i, &error, stripe->nr_sectors) { 1888 if (scrub_bitmap_test_bit_is_metadata(stripe, i)) { 1889 struct btrfs_fs_info *fs_info = stripe->bg->fs_info; 1890 1891 btrfs_err(fs_info, 1892 "scrub: stripe %llu has unrepaired metadata sector at logical %llu", 1893 stripe->logical, 1894 stripe->logical + (i << fs_info->sectorsize_bits)); 1895 return true; 1896 } 1897 } 1898 return false; 1899 } 1900 1901 static void submit_initial_group_read(struct scrub_ctx *sctx, 1902 unsigned int first_slot, 1903 unsigned int nr_stripes) 1904 { 1905 struct blk_plug plug; 1906 1907 ASSERT(first_slot < SCRUB_TOTAL_STRIPES); 1908 ASSERT(first_slot + nr_stripes <= SCRUB_TOTAL_STRIPES); 1909 1910 scrub_throttle_dev_io(sctx, sctx->stripes[0].dev, 1911 btrfs_stripe_nr_to_offset(nr_stripes)); 1912 blk_start_plug(&plug); 1913 for (int i = 0; i < nr_stripes; i++) { 1914 struct scrub_stripe *stripe = &sctx->stripes[first_slot + i]; 1915 1916 /* Those stripes should be initialized. */ 1917 ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state)); 1918 scrub_submit_initial_read(sctx, stripe); 1919 } 1920 blk_finish_plug(&plug); 1921 } 1922 1923 static int flush_scrub_stripes(struct scrub_ctx *sctx) 1924 { 1925 struct btrfs_fs_info *fs_info = sctx->fs_info; 1926 struct scrub_stripe *stripe; 1927 const int nr_stripes = sctx->cur_stripe; 1928 int ret = 0; 1929 1930 if (!nr_stripes) 1931 return 0; 1932 1933 ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &sctx->stripes[0].state)); 1934 1935 /* Submit the stripes which are populated but not submitted. */ 1936 if (nr_stripes % SCRUB_STRIPES_PER_GROUP) { 1937 const int first_slot = round_down(nr_stripes, SCRUB_STRIPES_PER_GROUP); 1938 1939 submit_initial_group_read(sctx, first_slot, nr_stripes - first_slot); 1940 } 1941 1942 for (int i = 0; i < nr_stripes; i++) { 1943 stripe = &sctx->stripes[i]; 1944 1945 wait_event(stripe->repair_wait, 1946 test_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state)); 1947 } 1948 1949 /* Submit for dev-replace. */ 1950 if (sctx->is_dev_replace) { 1951 /* 1952 * For dev-replace, if we know there is something wrong with 1953 * metadata, we should immediately abort. 1954 */ 1955 for (int i = 0; i < nr_stripes; i++) { 1956 if (unlikely(stripe_has_metadata_error(&sctx->stripes[i]))) { 1957 ret = -EIO; 1958 goto out; 1959 } 1960 } 1961 for (int i = 0; i < nr_stripes; i++) { 1962 unsigned long good; 1963 unsigned long has_extent; 1964 unsigned long error; 1965 1966 stripe = &sctx->stripes[i]; 1967 1968 ASSERT(stripe->dev == fs_info->dev_replace.srcdev); 1969 1970 has_extent = scrub_bitmap_read_has_extent(stripe); 1971 error = scrub_bitmap_read_error(stripe); 1972 bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors); 1973 scrub_write_sectors(sctx, stripe, good, true); 1974 } 1975 } 1976 1977 /* Wait for the above writebacks to finish. */ 1978 for (int i = 0; i < nr_stripes; i++) { 1979 stripe = &sctx->stripes[i]; 1980 1981 wait_scrub_stripe_io(stripe); 1982 spin_lock(&sctx->stat_lock); 1983 sctx->stat.last_physical = stripe->physical + stripe_length(stripe); 1984 spin_unlock(&sctx->stat_lock); 1985 scrub_reset_stripe(stripe); 1986 } 1987 out: 1988 sctx->cur_stripe = 0; 1989 return ret; 1990 } 1991 1992 static void raid56_scrub_wait_endio(struct bio *bio) 1993 { 1994 complete(bio->bi_private); 1995 } 1996 1997 static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *bg, 1998 struct btrfs_device *dev, int mirror_num, 1999 u64 logical, u32 length, u64 physical, 2000 u64 *found_logical_ret) 2001 { 2002 struct scrub_stripe *stripe; 2003 int ret; 2004 2005 /* 2006 * There should always be one slot left, as caller filling the last 2007 * slot should flush them all. 2008 */ 2009 ASSERT(sctx->cur_stripe < SCRUB_TOTAL_STRIPES); 2010 2011 /* @found_logical_ret must be specified. */ 2012 ASSERT(found_logical_ret); 2013 2014 stripe = &sctx->stripes[sctx->cur_stripe]; 2015 scrub_reset_stripe(stripe); 2016 ret = scrub_find_fill_first_stripe(bg, &sctx->extent_path, 2017 &sctx->csum_path, dev, physical, 2018 mirror_num, logical, length, stripe); 2019 /* Either >0 as no more extents or <0 for error. */ 2020 if (ret) 2021 return ret; 2022 *found_logical_ret = stripe->logical; 2023 sctx->cur_stripe++; 2024 2025 /* We filled one group, submit it. */ 2026 if (sctx->cur_stripe % SCRUB_STRIPES_PER_GROUP == 0) { 2027 const int first_slot = sctx->cur_stripe - SCRUB_STRIPES_PER_GROUP; 2028 2029 submit_initial_group_read(sctx, first_slot, SCRUB_STRIPES_PER_GROUP); 2030 } 2031 2032 /* Last slot used, flush them all. */ 2033 if (sctx->cur_stripe == SCRUB_TOTAL_STRIPES) 2034 return flush_scrub_stripes(sctx); 2035 return 0; 2036 } 2037 2038 /* 2039 * Return 0 if we should not cancel the scrub. 2040 * Return <0 if we need to cancel the scrub, returned value will 2041 * indicate the reason: 2042 * - -ECANCELED - Being explicitly canceled through ioctl. 2043 * - -EINTR - Being interrupted by signal or fs/process freezing. 2044 */ 2045 static int should_cancel_scrub(const struct scrub_ctx *sctx) 2046 { 2047 struct btrfs_fs_info *fs_info = sctx->fs_info; 2048 2049 if (atomic_read(&fs_info->scrub_cancel_req) || 2050 atomic_read(&sctx->cancel_req)) 2051 return -ECANCELED; 2052 2053 /* 2054 * The user (e.g. fsfreeze command) or power management (PM) 2055 * suspend/hibernate can freeze the fs. And PM suspend/hibernate will 2056 * also freeze all user processes. 2057 * 2058 * A user process can only be frozen when it is in user space, thus we 2059 * have to cancel the run so that the process can return to the user 2060 * space. 2061 * 2062 * Furthermore we have to check both filesystem and process freezing, 2063 * as PM can be configured to freeze the filesystems before processes. 2064 * 2065 * If we only check fs freezing, then suspend without fs freezing 2066 * will timeout, as the process is still in kernel space. 2067 * 2068 * If we only check process freezing, then suspend with fs freezing 2069 * will timeout, as the running scrub will prevent the fs from being frozen. 2070 */ 2071 if (fs_info->sb->s_writers.frozen > SB_UNFROZEN || 2072 freezing(current) || signal_pending(current)) 2073 return -EINTR; 2074 return 0; 2075 } 2076 2077 static int scrub_raid56_cached_parity(struct scrub_ctx *sctx, 2078 struct btrfs_device *scrub_dev, 2079 struct btrfs_chunk_map *map, 2080 u64 full_stripe_start, 2081 unsigned long *extent_bitmap) 2082 { 2083 DECLARE_COMPLETION_ONSTACK(io_done); 2084 struct btrfs_fs_info *fs_info = sctx->fs_info; 2085 struct btrfs_io_context *bioc = NULL; 2086 struct btrfs_raid_bio *rbio; 2087 struct bio bio; 2088 const int data_stripes = nr_data_stripes(map); 2089 u64 length = btrfs_stripe_nr_to_offset(data_stripes); 2090 int ret; 2091 2092 bio_init(&bio, NULL, NULL, 0, REQ_OP_READ); 2093 bio.bi_iter.bi_sector = full_stripe_start >> SECTOR_SHIFT; 2094 bio.bi_private = &io_done; 2095 bio.bi_end_io = raid56_scrub_wait_endio; 2096 2097 btrfs_bio_counter_inc_blocked(fs_info); 2098 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, full_stripe_start, 2099 &length, &bioc, NULL, NULL); 2100 if (ret < 0) 2101 goto out; 2102 /* For RAID56 write there must be an @bioc allocated. */ 2103 ASSERT(bioc); 2104 rbio = raid56_parity_alloc_scrub_rbio(&bio, bioc, scrub_dev, extent_bitmap, 2105 BTRFS_STRIPE_LEN >> fs_info->sectorsize_bits); 2106 btrfs_put_bioc(bioc); 2107 if (!rbio) { 2108 ret = -ENOMEM; 2109 goto out; 2110 } 2111 /* Use the recovered stripes as cache to avoid read them from disk again. */ 2112 for (int i = 0; i < data_stripes; i++) { 2113 struct scrub_stripe *stripe = &sctx->raid56_data_stripes[i]; 2114 2115 raid56_parity_cache_data_folios(rbio, stripe->buffer, 2116 full_stripe_start + (i << BTRFS_STRIPE_LEN_SHIFT)); 2117 } 2118 raid56_parity_submit_scrub_rbio(rbio); 2119 wait_for_completion_io(&io_done); 2120 ret = blk_status_to_errno(bio.bi_status); 2121 out: 2122 btrfs_bio_counter_dec(fs_info); 2123 bio_uninit(&bio); 2124 return ret; 2125 } 2126 2127 static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx, 2128 struct btrfs_device *scrub_dev, 2129 struct btrfs_block_group *bg, 2130 struct btrfs_chunk_map *map, 2131 u64 full_stripe_start) 2132 { 2133 struct btrfs_fs_info *fs_info = sctx->fs_info; 2134 BTRFS_PATH_AUTO_RELEASE(extent_path); 2135 BTRFS_PATH_AUTO_RELEASE(csum_path); 2136 struct scrub_stripe *stripe; 2137 bool all_empty = true; 2138 const int data_stripes = nr_data_stripes(map); 2139 unsigned long extent_bitmap = 0; 2140 int ret; 2141 2142 ASSERT(sctx->raid56_data_stripes); 2143 2144 ret = should_cancel_scrub(sctx); 2145 if (ret < 0) 2146 return ret; 2147 2148 if (atomic_read(&fs_info->scrub_pause_req)) 2149 scrub_blocked_if_needed(fs_info); 2150 2151 spin_lock(&bg->lock); 2152 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) { 2153 spin_unlock(&bg->lock); 2154 return 0; 2155 } 2156 spin_unlock(&bg->lock); 2157 2158 /* 2159 * For data stripe search, we cannot reuse the same extent/csum paths, 2160 * as the data stripe bytenr may be smaller than previous extent. Thus 2161 * we have to use our own extent/csum paths. 2162 */ 2163 extent_path.search_commit_root = true; 2164 extent_path.skip_locking = true; 2165 csum_path.search_commit_root = true; 2166 csum_path.skip_locking = true; 2167 2168 for (int i = 0; i < data_stripes; i++) { 2169 int stripe_index; 2170 int rot; 2171 u64 physical; 2172 2173 stripe = &sctx->raid56_data_stripes[i]; 2174 rot = div_u64(full_stripe_start - bg->start, 2175 data_stripes) >> BTRFS_STRIPE_LEN_SHIFT; 2176 stripe_index = (i + rot) % map->num_stripes; 2177 physical = map->stripes[stripe_index].physical + 2178 btrfs_stripe_nr_to_offset(rot); 2179 2180 scrub_reset_stripe(stripe); 2181 set_bit(SCRUB_STRIPE_FLAG_NO_REPORT, &stripe->state); 2182 ret = scrub_find_fill_first_stripe(bg, &extent_path, &csum_path, 2183 map->stripes[stripe_index].dev, physical, 1, 2184 full_stripe_start + btrfs_stripe_nr_to_offset(i), 2185 BTRFS_STRIPE_LEN, stripe); 2186 if (ret < 0) 2187 return ret; 2188 /* 2189 * No extent in this data stripe, need to manually mark them 2190 * initialized to make later read submission happy. 2191 */ 2192 if (ret > 0) { 2193 stripe->logical = full_stripe_start + 2194 btrfs_stripe_nr_to_offset(i); 2195 stripe->dev = map->stripes[stripe_index].dev; 2196 stripe->mirror_num = 1; 2197 set_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state); 2198 } 2199 } 2200 2201 /* Check if all data stripes are empty. */ 2202 for (int i = 0; i < data_stripes; i++) { 2203 stripe = &sctx->raid56_data_stripes[i]; 2204 if (!scrub_bitmap_empty_has_extent(stripe)) { 2205 all_empty = false; 2206 break; 2207 } 2208 } 2209 if (all_empty) 2210 return 0; 2211 2212 for (int i = 0; i < data_stripes; i++) { 2213 stripe = &sctx->raid56_data_stripes[i]; 2214 scrub_submit_initial_read(sctx, stripe); 2215 } 2216 for (int i = 0; i < data_stripes; i++) { 2217 stripe = &sctx->raid56_data_stripes[i]; 2218 2219 wait_event(stripe->repair_wait, 2220 test_bit(SCRUB_STRIPE_FLAG_REPAIR_DONE, &stripe->state)); 2221 } 2222 /* For now, no zoned support for RAID56. */ 2223 ASSERT(!btrfs_is_zoned(sctx->fs_info)); 2224 2225 /* 2226 * Now all data stripes are properly verified. Check if we have any 2227 * unrepaired, if so abort immediately or we could further corrupt the 2228 * P/Q stripes. 2229 * 2230 * During the loop, also populate extent_bitmap. 2231 */ 2232 for (int i = 0; i < data_stripes; i++) { 2233 unsigned long error; 2234 unsigned long has_extent; 2235 2236 stripe = &sctx->raid56_data_stripes[i]; 2237 2238 error = scrub_bitmap_read_error(stripe); 2239 has_extent = scrub_bitmap_read_has_extent(stripe); 2240 2241 /* 2242 * We should only check the errors where there is an extent. 2243 * As we may hit an empty data stripe while it's missing. 2244 */ 2245 bitmap_and(&error, &error, &has_extent, stripe->nr_sectors); 2246 if (unlikely(!bitmap_empty(&error, stripe->nr_sectors))) { 2247 btrfs_err(fs_info, 2248 "scrub: unrepaired sectors detected, full stripe %llu data stripe %u errors %*pbl", 2249 full_stripe_start, i, stripe->nr_sectors, 2250 &error); 2251 return ret; 2252 } 2253 bitmap_or(&extent_bitmap, &extent_bitmap, &has_extent, 2254 stripe->nr_sectors); 2255 } 2256 2257 /* Now we can check and regenerate the P/Q stripe. */ 2258 return scrub_raid56_cached_parity(sctx, scrub_dev, map, full_stripe_start, 2259 &extent_bitmap); 2260 } 2261 2262 /* 2263 * Scrub one range which can only has simple mirror based profile. 2264 * (Including all range in SINGLE/DUP/RAID1/RAID1C*, and each stripe in 2265 * RAID0/RAID10). 2266 * 2267 * Since we may need to handle a subset of block group, we need @logical_start 2268 * and @logical_length parameter. 2269 */ 2270 static int scrub_simple_mirror(struct scrub_ctx *sctx, 2271 struct btrfs_block_group *bg, 2272 u64 logical_start, u64 logical_length, 2273 struct btrfs_device *device, 2274 u64 physical, int mirror_num) 2275 { 2276 struct btrfs_fs_info *fs_info = sctx->fs_info; 2277 const u64 logical_end = logical_start + logical_length; 2278 u64 cur_logical = logical_start; 2279 int ret = 0; 2280 2281 /* The range must be inside the bg */ 2282 ASSERT(logical_start >= bg->start && logical_end <= btrfs_block_group_end(bg)); 2283 2284 /* Go through each extent items inside the logical range */ 2285 while (cur_logical < logical_end) { 2286 u64 found_logical = U64_MAX; 2287 u64 cur_physical = physical + cur_logical - logical_start; 2288 2289 ret = should_cancel_scrub(sctx); 2290 if (ret < 0) 2291 break; 2292 2293 if (atomic_read(&fs_info->scrub_pause_req)) 2294 scrub_blocked_if_needed(fs_info); 2295 2296 spin_lock(&bg->lock); 2297 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) { 2298 spin_unlock(&bg->lock); 2299 ret = 0; 2300 break; 2301 } 2302 spin_unlock(&bg->lock); 2303 2304 ret = queue_scrub_stripe(sctx, bg, device, mirror_num, 2305 cur_logical, logical_end - cur_logical, 2306 cur_physical, &found_logical); 2307 if (ret > 0) { 2308 /* No more extent, just update the accounting */ 2309 spin_lock(&sctx->stat_lock); 2310 sctx->stat.last_physical = physical + logical_length; 2311 spin_unlock(&sctx->stat_lock); 2312 ret = 0; 2313 break; 2314 } 2315 if (ret < 0) 2316 break; 2317 2318 /* queue_scrub_stripe() returned 0, @found_logical must be updated. */ 2319 ASSERT(found_logical != U64_MAX); 2320 cur_logical = found_logical + BTRFS_STRIPE_LEN; 2321 2322 /* Don't hold CPU for too long time */ 2323 cond_resched(); 2324 } 2325 return ret; 2326 } 2327 2328 /* Calculate the full stripe length for simple stripe based profiles */ 2329 static u64 simple_stripe_full_stripe_len(const struct btrfs_chunk_map *map) 2330 { 2331 ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 | 2332 BTRFS_BLOCK_GROUP_RAID10)); 2333 2334 return btrfs_stripe_nr_to_offset(map->num_stripes / map->sub_stripes); 2335 } 2336 2337 /* Get the logical bytenr for the stripe */ 2338 static u64 simple_stripe_get_logical(struct btrfs_chunk_map *map, 2339 struct btrfs_block_group *bg, 2340 int stripe_index) 2341 { 2342 ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 | 2343 BTRFS_BLOCK_GROUP_RAID10)); 2344 ASSERT(stripe_index < map->num_stripes); 2345 2346 /* 2347 * (stripe_index / sub_stripes) gives how many data stripes we need to 2348 * skip. 2349 */ 2350 return btrfs_stripe_nr_to_offset(stripe_index / map->sub_stripes) + 2351 bg->start; 2352 } 2353 2354 /* Get the mirror number for the stripe */ 2355 static int simple_stripe_mirror_num(struct btrfs_chunk_map *map, int stripe_index) 2356 { 2357 ASSERT(map->type & (BTRFS_BLOCK_GROUP_RAID0 | 2358 BTRFS_BLOCK_GROUP_RAID10)); 2359 ASSERT(stripe_index < map->num_stripes); 2360 2361 /* For RAID0, it's fixed to 1, for RAID10 it's 0,1,0,1... */ 2362 return stripe_index % map->sub_stripes + 1; 2363 } 2364 2365 static int scrub_simple_stripe(struct scrub_ctx *sctx, 2366 struct btrfs_block_group *bg, 2367 struct btrfs_chunk_map *map, 2368 struct btrfs_device *device, 2369 int stripe_index) 2370 { 2371 const u64 logical_increment = simple_stripe_full_stripe_len(map); 2372 const u64 orig_logical = simple_stripe_get_logical(map, bg, stripe_index); 2373 const u64 orig_physical = map->stripes[stripe_index].physical; 2374 const u64 end = btrfs_block_group_end(bg); 2375 const int mirror_num = simple_stripe_mirror_num(map, stripe_index); 2376 u64 cur_logical = orig_logical; 2377 u64 cur_physical = orig_physical; 2378 int ret = 0; 2379 2380 while (cur_logical < end) { 2381 /* 2382 * Inside each stripe, RAID0 is just SINGLE, and RAID10 is 2383 * just RAID1, so we can reuse scrub_simple_mirror() to scrub 2384 * this stripe. 2385 */ 2386 ret = scrub_simple_mirror(sctx, bg, cur_logical, 2387 BTRFS_STRIPE_LEN, device, cur_physical, 2388 mirror_num); 2389 if (ret) 2390 return ret; 2391 /* Skip to next stripe which belongs to the target device */ 2392 cur_logical += logical_increment; 2393 /* For physical offset, we just go to next stripe */ 2394 cur_physical += BTRFS_STRIPE_LEN; 2395 } 2396 return ret; 2397 } 2398 2399 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx, 2400 struct btrfs_block_group *bg, 2401 struct btrfs_chunk_map *map, 2402 struct btrfs_device *scrub_dev, 2403 int stripe_index) 2404 { 2405 struct btrfs_fs_info *fs_info = sctx->fs_info; 2406 const u64 profile = map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK; 2407 const u64 chunk_logical = bg->start; 2408 int ret; 2409 int ret2; 2410 u64 physical = map->stripes[stripe_index].physical; 2411 const u64 dev_stripe_len = btrfs_calc_stripe_length(map); 2412 const u64 physical_end = physical + dev_stripe_len; 2413 u64 logical; 2414 u64 logic_end; 2415 /* The logical increment after finishing one stripe */ 2416 u64 increment; 2417 /* Offset inside the chunk */ 2418 u64 offset; 2419 u64 stripe_logical; 2420 2421 /* Extent_path should be released by now. */ 2422 ASSERT(sctx->extent_path.nodes[0] == NULL); 2423 2424 scrub_blocked_if_needed(fs_info); 2425 2426 if (sctx->is_dev_replace && 2427 btrfs_dev_is_sequential(sctx->wr_tgtdev, physical)) { 2428 mutex_lock(&sctx->wr_lock); 2429 sctx->write_pointer = physical; 2430 mutex_unlock(&sctx->wr_lock); 2431 } 2432 2433 /* Prepare the extra data stripes used by RAID56. */ 2434 if (profile & BTRFS_BLOCK_GROUP_RAID56_MASK) { 2435 ASSERT(sctx->raid56_data_stripes == NULL); 2436 2437 sctx->raid56_data_stripes = kzalloc_objs(struct scrub_stripe, 2438 nr_data_stripes(map)); 2439 if (!sctx->raid56_data_stripes) { 2440 ret = -ENOMEM; 2441 goto out; 2442 } 2443 for (int i = 0; i < nr_data_stripes(map); i++) { 2444 ret = init_scrub_stripe(fs_info, 2445 &sctx->raid56_data_stripes[i]); 2446 if (ret < 0) 2447 goto out; 2448 sctx->raid56_data_stripes[i].bg = bg; 2449 sctx->raid56_data_stripes[i].sctx = sctx; 2450 } 2451 } 2452 /* 2453 * There used to be a big double loop to handle all profiles using the 2454 * same routine, which grows larger and more gross over time. 2455 * 2456 * So here we handle each profile differently, so simpler profiles 2457 * have simpler scrubbing function. 2458 */ 2459 if (!(profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10 | 2460 BTRFS_BLOCK_GROUP_RAID56_MASK))) { 2461 /* 2462 * Above check rules out all complex profile, the remaining 2463 * profiles are SINGLE|DUP|RAID1|RAID1C*, which is simple 2464 * mirrored duplication without stripe. 2465 * 2466 * Only @physical and @mirror_num needs to calculated using 2467 * @stripe_index. 2468 */ 2469 ret = scrub_simple_mirror(sctx, bg, bg->start, bg->length, 2470 scrub_dev, map->stripes[stripe_index].physical, 2471 stripe_index + 1); 2472 offset = 0; 2473 goto out; 2474 } 2475 if (profile & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) { 2476 ret = scrub_simple_stripe(sctx, bg, map, scrub_dev, stripe_index); 2477 offset = btrfs_stripe_nr_to_offset(stripe_index / map->sub_stripes); 2478 goto out; 2479 } 2480 2481 /* Only RAID56 goes through the old code */ 2482 ASSERT(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK); 2483 ret = 0; 2484 2485 /* Calculate the logical end of the stripe */ 2486 get_raid56_logic_offset(physical_end, stripe_index, 2487 map, &logic_end, NULL); 2488 logic_end += chunk_logical; 2489 2490 /* Initialize @offset in case we need to go to out: label */ 2491 get_raid56_logic_offset(physical, stripe_index, map, &offset, NULL); 2492 increment = btrfs_stripe_nr_to_offset(nr_data_stripes(map)); 2493 2494 /* 2495 * Due to the rotation, for RAID56 it's better to iterate each stripe 2496 * using their physical offset. 2497 */ 2498 while (physical < physical_end) { 2499 ret = get_raid56_logic_offset(physical, stripe_index, map, 2500 &logical, &stripe_logical); 2501 logical += chunk_logical; 2502 if (ret) { 2503 /* it is parity strip */ 2504 stripe_logical += chunk_logical; 2505 ret = scrub_raid56_parity_stripe(sctx, scrub_dev, bg, 2506 map, stripe_logical); 2507 spin_lock(&sctx->stat_lock); 2508 sctx->stat.last_physical = min(physical + BTRFS_STRIPE_LEN, 2509 physical_end); 2510 spin_unlock(&sctx->stat_lock); 2511 if (ret) 2512 goto out; 2513 goto next; 2514 } 2515 2516 /* 2517 * Now we're at a data stripe, scrub each extents in the range. 2518 * 2519 * At this stage, if we ignore the repair part, inside each data 2520 * stripe it is no different than SINGLE profile. 2521 * We can reuse scrub_simple_mirror() here, as the repair part 2522 * is still based on @mirror_num. 2523 */ 2524 ret = scrub_simple_mirror(sctx, bg, logical, BTRFS_STRIPE_LEN, 2525 scrub_dev, physical, 1); 2526 if (ret < 0) 2527 goto out; 2528 next: 2529 logical += increment; 2530 physical += BTRFS_STRIPE_LEN; 2531 spin_lock(&sctx->stat_lock); 2532 sctx->stat.last_physical = physical; 2533 spin_unlock(&sctx->stat_lock); 2534 } 2535 out: 2536 ret2 = flush_scrub_stripes(sctx); 2537 if (!ret) 2538 ret = ret2; 2539 btrfs_release_path(&sctx->extent_path); 2540 btrfs_release_path(&sctx->csum_path); 2541 2542 if (sctx->raid56_data_stripes) { 2543 for (int i = 0; i < nr_data_stripes(map); i++) 2544 release_scrub_stripe(&sctx->raid56_data_stripes[i]); 2545 kfree(sctx->raid56_data_stripes); 2546 sctx->raid56_data_stripes = NULL; 2547 } 2548 2549 if (sctx->is_dev_replace && ret >= 0) { 2550 ret2 = sync_write_pointer_for_zoned(sctx, 2551 chunk_logical + offset, 2552 map->stripes[stripe_index].physical, 2553 physical_end); 2554 if (ret2) 2555 ret = ret2; 2556 } 2557 2558 return ret < 0 ? ret : 0; 2559 } 2560 2561 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx, 2562 struct btrfs_block_group *bg, 2563 struct btrfs_device *scrub_dev, 2564 u64 dev_offset, 2565 u64 dev_extent_len) 2566 { 2567 struct btrfs_fs_info *fs_info = sctx->fs_info; 2568 struct btrfs_chunk_map *map; 2569 int i; 2570 int ret = 0; 2571 2572 map = btrfs_find_chunk_map(fs_info, bg->start, bg->length); 2573 if (!map) { 2574 /* 2575 * Might have been an unused block group deleted by the cleaner 2576 * kthread or relocation. 2577 */ 2578 spin_lock(&bg->lock); 2579 if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) 2580 ret = -EINVAL; 2581 spin_unlock(&bg->lock); 2582 2583 return ret; 2584 } 2585 if (map->start != bg->start) 2586 goto out; 2587 if (map->chunk_len < dev_extent_len) 2588 goto out; 2589 2590 for (i = 0; i < map->num_stripes; ++i) { 2591 if (map->stripes[i].dev->bdev == scrub_dev->bdev && 2592 map->stripes[i].physical == dev_offset) { 2593 ret = scrub_stripe(sctx, bg, map, scrub_dev, i); 2594 if (ret) 2595 goto out; 2596 } 2597 } 2598 out: 2599 btrfs_free_chunk_map(map); 2600 2601 return ret; 2602 } 2603 2604 static int finish_extent_writes_for_zoned(struct btrfs_root *root, 2605 struct btrfs_block_group *cache) 2606 { 2607 struct btrfs_fs_info *fs_info = cache->fs_info; 2608 2609 if (!btrfs_is_zoned(fs_info)) 2610 return 0; 2611 2612 btrfs_wait_block_group_reservations(cache); 2613 btrfs_wait_nocow_writers(cache); 2614 btrfs_wait_ordered_roots(fs_info, U64_MAX, cache); 2615 2616 return btrfs_commit_current_transaction(root); 2617 } 2618 2619 static noinline_for_stack 2620 int scrub_enumerate_chunks(struct scrub_ctx *sctx, 2621 struct btrfs_device *scrub_dev, u64 start, u64 end) 2622 { 2623 struct btrfs_dev_extent *dev_extent = NULL; 2624 BTRFS_PATH_AUTO_FREE(path); 2625 struct btrfs_fs_info *fs_info = sctx->fs_info; 2626 struct btrfs_root *root = fs_info->dev_root; 2627 u64 chunk_offset; 2628 int ret = 0; 2629 int ro_set; 2630 int slot; 2631 struct extent_buffer *l; 2632 struct btrfs_key key; 2633 struct btrfs_key found_key; 2634 struct btrfs_block_group *cache; 2635 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; 2636 2637 path = btrfs_alloc_path(); 2638 if (!path) 2639 return -ENOMEM; 2640 2641 path->reada = READA_FORWARD; 2642 path->search_commit_root = true; 2643 path->skip_locking = true; 2644 2645 key.objectid = scrub_dev->devid; 2646 key.type = BTRFS_DEV_EXTENT_KEY; 2647 key.offset = 0ull; 2648 2649 while (1) { 2650 u64 dev_extent_len; 2651 2652 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 2653 if (ret < 0) 2654 break; 2655 if (ret > 0) { 2656 if (path->slots[0] >= 2657 btrfs_header_nritems(path->nodes[0])) { 2658 ret = btrfs_next_leaf(root, path); 2659 if (ret < 0) 2660 break; 2661 if (ret > 0) { 2662 ret = 0; 2663 break; 2664 } 2665 } else { 2666 ret = 0; 2667 } 2668 } 2669 2670 l = path->nodes[0]; 2671 slot = path->slots[0]; 2672 2673 btrfs_item_key_to_cpu(l, &found_key, slot); 2674 2675 if (found_key.objectid != scrub_dev->devid) 2676 break; 2677 2678 if (found_key.type != BTRFS_DEV_EXTENT_KEY) 2679 break; 2680 2681 if (found_key.offset >= end) 2682 break; 2683 2684 if (found_key.offset < key.offset) 2685 break; 2686 2687 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); 2688 dev_extent_len = btrfs_dev_extent_length(l, dev_extent); 2689 2690 if (found_key.offset + dev_extent_len <= start) 2691 goto skip; 2692 2693 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent); 2694 2695 /* 2696 * get a reference on the corresponding block group to prevent 2697 * the chunk from going away while we scrub it 2698 */ 2699 cache = btrfs_lookup_block_group(fs_info, chunk_offset); 2700 2701 /* some chunks are removed but not committed to disk yet, 2702 * continue scrubbing */ 2703 if (!cache) 2704 goto skip; 2705 2706 ASSERT(cache->start <= chunk_offset); 2707 /* 2708 * We are using the commit root to search for device extents, so 2709 * that means we could have found a device extent item from a 2710 * block group that was deleted in the current transaction. The 2711 * logical start offset of the deleted block group, stored at 2712 * @chunk_offset, might be part of the logical address range of 2713 * a new block group (which uses different physical extents). 2714 * In this case btrfs_lookup_block_group() has returned the new 2715 * block group, and its start address is less than @chunk_offset. 2716 * 2717 * We skip such new block groups, because it's pointless to 2718 * process them, as we won't find their extents because we search 2719 * for them using the commit root of the extent tree. For a device 2720 * replace it's also fine to skip it, we won't miss copying them 2721 * to the target device because we have the write duplication 2722 * setup through the regular write path (by btrfs_map_block()), 2723 * and we have committed a transaction when we started the device 2724 * replace, right after setting up the device replace state. 2725 */ 2726 if (cache->start < chunk_offset) { 2727 btrfs_put_block_group(cache); 2728 goto skip; 2729 } 2730 2731 if (sctx->is_dev_replace && btrfs_is_zoned(fs_info)) { 2732 if (!test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags)) { 2733 btrfs_put_block_group(cache); 2734 goto skip; 2735 } 2736 } 2737 2738 /* 2739 * Make sure that while we are scrubbing the corresponding block 2740 * group doesn't get its logical address and its device extents 2741 * reused for another block group, which can possibly be of a 2742 * different type and different profile. We do this to prevent 2743 * false error detections and crashes due to bogus attempts to 2744 * repair extents. 2745 */ 2746 spin_lock(&cache->lock); 2747 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags)) { 2748 spin_unlock(&cache->lock); 2749 btrfs_put_block_group(cache); 2750 goto skip; 2751 } 2752 btrfs_freeze_block_group(cache); 2753 spin_unlock(&cache->lock); 2754 2755 /* 2756 * we need call btrfs_inc_block_group_ro() with scrubs_paused, 2757 * to avoid deadlock caused by: 2758 * btrfs_inc_block_group_ro() 2759 * -> btrfs_wait_for_commit() 2760 * -> btrfs_commit_transaction() 2761 * -> btrfs_scrub_pause() 2762 */ 2763 scrub_pause_on(fs_info); 2764 2765 /* 2766 * Don't do chunk preallocation for scrub. 2767 * 2768 * This is especially important for SYSTEM bgs, or we can hit 2769 * -EFBIG from btrfs_finish_chunk_alloc() like: 2770 * 1. The only SYSTEM bg is marked RO. 2771 * Since SYSTEM bg is small, that's pretty common. 2772 * 2. New SYSTEM bg will be allocated 2773 * Due to regular version will allocate new chunk. 2774 * 3. New SYSTEM bg is empty and will get cleaned up 2775 * Before cleanup really happens, it's marked RO again. 2776 * 4. Empty SYSTEM bg get scrubbed 2777 * We go back to 2. 2778 * 2779 * This can easily boost the amount of SYSTEM chunks if cleaner 2780 * thread can't be triggered fast enough, and use up all space 2781 * of btrfs_super_block::sys_chunk_array 2782 * 2783 * While for dev replace, we need to try our best to mark block 2784 * group RO, to prevent race between: 2785 * - Write duplication 2786 * Contains latest data 2787 * - Scrub copy 2788 * Contains data from commit tree 2789 * 2790 * If target block group is not marked RO, nocow writes can 2791 * be overwritten by scrub copy, causing data corruption. 2792 * So for dev-replace, it's not allowed to continue if a block 2793 * group is not RO. 2794 */ 2795 ret = btrfs_inc_block_group_ro(cache, sctx->is_dev_replace); 2796 if (!ret && sctx->is_dev_replace) { 2797 ret = finish_extent_writes_for_zoned(root, cache); 2798 if (ret) { 2799 btrfs_dec_block_group_ro(cache); 2800 scrub_pause_off(fs_info); 2801 btrfs_put_block_group(cache); 2802 break; 2803 } 2804 } 2805 2806 if (ret == 0) { 2807 ro_set = 1; 2808 } else if (ret == -ENOSPC && !sctx->is_dev_replace && 2809 !(cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) { 2810 /* 2811 * btrfs_inc_block_group_ro return -ENOSPC when it 2812 * failed in creating new chunk for metadata. 2813 * It is not a problem for scrub, because 2814 * metadata are always cowed, and our scrub paused 2815 * commit_transactions. 2816 * 2817 * For RAID56 chunks, we have to mark them read-only 2818 * for scrub, as later we would use our own cache 2819 * out of RAID56 realm. 2820 * Thus we want the RAID56 bg to be marked RO to 2821 * prevent RMW from screwing up out cache. 2822 */ 2823 ro_set = 0; 2824 } else if (ret == -ETXTBSY) { 2825 btrfs_warn(fs_info, 2826 "scrub: skipping scrub of block group %llu due to active swapfile", 2827 cache->start); 2828 scrub_pause_off(fs_info); 2829 ret = 0; 2830 goto skip_unfreeze; 2831 } else { 2832 btrfs_warn(fs_info, "scrub: failed setting block group ro: %d", 2833 ret); 2834 btrfs_unfreeze_block_group(cache); 2835 btrfs_put_block_group(cache); 2836 scrub_pause_off(fs_info); 2837 break; 2838 } 2839 2840 /* 2841 * Now the target block is marked RO, wait for nocow writes to 2842 * finish before dev-replace. 2843 * COW is fine, as COW never overwrites extents in commit tree. 2844 */ 2845 if (sctx->is_dev_replace) { 2846 btrfs_wait_nocow_writers(cache); 2847 btrfs_wait_ordered_roots(fs_info, U64_MAX, cache); 2848 } 2849 2850 scrub_pause_off(fs_info); 2851 down_write(&dev_replace->rwsem); 2852 dev_replace->cursor_right = found_key.offset + dev_extent_len; 2853 dev_replace->cursor_left = found_key.offset; 2854 dev_replace->item_needs_writeback = 1; 2855 up_write(&dev_replace->rwsem); 2856 2857 ret = scrub_chunk(sctx, cache, scrub_dev, found_key.offset, 2858 dev_extent_len); 2859 if (sctx->is_dev_replace && 2860 !btrfs_finish_block_group_to_copy(dev_replace->srcdev, 2861 cache, found_key.offset)) 2862 ro_set = 0; 2863 2864 down_write(&dev_replace->rwsem); 2865 dev_replace->cursor_left = dev_replace->cursor_right; 2866 dev_replace->item_needs_writeback = 1; 2867 up_write(&dev_replace->rwsem); 2868 2869 if (ro_set) 2870 btrfs_dec_block_group_ro(cache); 2871 2872 /* 2873 * We might have prevented the cleaner kthread from deleting 2874 * this block group if it was already unused because we raced 2875 * and set it to RO mode first. So add it back to the unused 2876 * list, otherwise it might not ever be deleted unless a manual 2877 * balance is triggered or it becomes used and unused again. 2878 */ 2879 spin_lock(&cache->lock); 2880 if (!test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags) && 2881 !cache->ro && cache->reserved == 0 && cache->used == 0) { 2882 spin_unlock(&cache->lock); 2883 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) 2884 btrfs_discard_queue_work(&fs_info->discard_ctl, 2885 cache); 2886 else 2887 btrfs_mark_bg_unused(cache); 2888 } else { 2889 spin_unlock(&cache->lock); 2890 } 2891 skip_unfreeze: 2892 btrfs_unfreeze_block_group(cache); 2893 btrfs_put_block_group(cache); 2894 if (ret) 2895 break; 2896 if (unlikely(sctx->is_dev_replace && 2897 atomic64_read(&dev_replace->num_write_errors) > 0)) { 2898 ret = -EIO; 2899 break; 2900 } 2901 if (sctx->stat.malloc_errors > 0) { 2902 ret = -ENOMEM; 2903 break; 2904 } 2905 skip: 2906 key.offset = found_key.offset + dev_extent_len; 2907 btrfs_release_path(path); 2908 } 2909 2910 return ret; 2911 } 2912 2913 static int scrub_one_super(struct scrub_ctx *sctx, struct btrfs_device *dev, 2914 struct page *page, u64 physical, u64 generation) 2915 { 2916 struct btrfs_fs_info *fs_info = sctx->fs_info; 2917 struct btrfs_super_block *sb = page_address(page); 2918 int ret; 2919 2920 ret = bdev_rw_virt(dev->bdev, physical >> SECTOR_SHIFT, sb, 2921 BTRFS_SUPER_INFO_SIZE, REQ_OP_READ); 2922 if (ret < 0) 2923 return ret; 2924 ret = btrfs_check_super_csum(fs_info, sb); 2925 if (unlikely(ret != 0)) { 2926 btrfs_err_rl(fs_info, 2927 "scrub: super block at physical %llu devid %llu has bad csum", 2928 physical, dev->devid); 2929 return -EIO; 2930 } 2931 if (unlikely(btrfs_super_generation(sb) != generation)) { 2932 btrfs_err_rl(fs_info, 2933 "scrub: super block at physical %llu devid %llu has bad generation %llu expect %llu", 2934 physical, dev->devid, 2935 btrfs_super_generation(sb), generation); 2936 return -EUCLEAN; 2937 } 2938 2939 return btrfs_validate_super(fs_info, sb, -1); 2940 } 2941 2942 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx, 2943 struct btrfs_device *scrub_dev) 2944 { 2945 int i; 2946 u64 bytenr; 2947 u64 gen; 2948 int ret = 0; 2949 struct page *page; 2950 struct btrfs_fs_info *fs_info = sctx->fs_info; 2951 2952 if (unlikely(BTRFS_FS_ERROR(fs_info))) 2953 return -EROFS; 2954 2955 page = alloc_page(GFP_KERNEL); 2956 if (!page) { 2957 spin_lock(&sctx->stat_lock); 2958 sctx->stat.malloc_errors++; 2959 spin_unlock(&sctx->stat_lock); 2960 return -ENOMEM; 2961 } 2962 2963 /* Seed devices of a new filesystem has their own generation. */ 2964 if (scrub_dev->fs_devices != fs_info->fs_devices) 2965 gen = scrub_dev->generation; 2966 else 2967 gen = btrfs_get_last_trans_committed(fs_info); 2968 2969 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) { 2970 ret = btrfs_sb_log_location(scrub_dev, i, 0, &bytenr); 2971 if (ret == -ENOENT) 2972 break; 2973 2974 if (ret) { 2975 spin_lock(&sctx->stat_lock); 2976 sctx->stat.super_errors++; 2977 spin_unlock(&sctx->stat_lock); 2978 continue; 2979 } 2980 2981 if (bytenr + BTRFS_SUPER_INFO_SIZE > 2982 scrub_dev->commit_total_bytes) 2983 break; 2984 if (!btrfs_check_super_location(scrub_dev, bytenr)) 2985 continue; 2986 2987 ret = scrub_one_super(sctx, scrub_dev, page, bytenr, gen); 2988 if (ret) { 2989 spin_lock(&sctx->stat_lock); 2990 sctx->stat.super_errors++; 2991 spin_unlock(&sctx->stat_lock); 2992 } 2993 } 2994 __free_page(page); 2995 return 0; 2996 } 2997 2998 static void scrub_workers_put(struct btrfs_fs_info *fs_info) 2999 { 3000 if (refcount_dec_and_mutex_lock(&fs_info->scrub_workers_refcnt, 3001 &fs_info->scrub_lock)) { 3002 struct workqueue_struct *scrub_workers = fs_info->scrub_workers; 3003 3004 fs_info->scrub_workers = NULL; 3005 mutex_unlock(&fs_info->scrub_lock); 3006 3007 if (scrub_workers) 3008 destroy_workqueue(scrub_workers); 3009 } 3010 } 3011 3012 /* 3013 * get a reference count on fs_info->scrub_workers. start worker if necessary 3014 */ 3015 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info) 3016 { 3017 struct workqueue_struct *scrub_workers = NULL; 3018 unsigned int flags = WQ_FREEZABLE | WQ_UNBOUND; 3019 int max_active = fs_info->thread_pool_size; 3020 int ret = -ENOMEM; 3021 3022 if (refcount_inc_not_zero(&fs_info->scrub_workers_refcnt)) 3023 return 0; 3024 3025 scrub_workers = alloc_workqueue("btrfs-scrub", flags, max_active); 3026 if (!scrub_workers) 3027 return -ENOMEM; 3028 3029 mutex_lock(&fs_info->scrub_lock); 3030 if (refcount_read(&fs_info->scrub_workers_refcnt) == 0) { 3031 ASSERT(fs_info->scrub_workers == NULL); 3032 fs_info->scrub_workers = scrub_workers; 3033 refcount_set(&fs_info->scrub_workers_refcnt, 1); 3034 mutex_unlock(&fs_info->scrub_lock); 3035 return 0; 3036 } 3037 /* Other thread raced in and created the workers for us */ 3038 refcount_inc(&fs_info->scrub_workers_refcnt); 3039 mutex_unlock(&fs_info->scrub_lock); 3040 3041 ret = 0; 3042 3043 destroy_workqueue(scrub_workers); 3044 return ret; 3045 } 3046 3047 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, 3048 u64 end, struct btrfs_scrub_progress *progress, 3049 bool readonly, bool is_dev_replace) 3050 { 3051 struct btrfs_dev_lookup_args args = { .devid = devid }; 3052 struct scrub_ctx *sctx; 3053 int ret; 3054 struct btrfs_device *dev; 3055 unsigned int nofs_flag; 3056 bool need_commit = false; 3057 3058 /* Set the basic fallback @last_physical before we got a sctx. */ 3059 if (progress) 3060 progress->last_physical = start; 3061 3062 if (btrfs_fs_closing(fs_info)) 3063 return -EAGAIN; 3064 3065 /* At mount time we have ensured nodesize is in the range of [4K, 64K]. */ 3066 ASSERT(fs_info->nodesize <= BTRFS_STRIPE_LEN); 3067 3068 /* Allocate outside of device_list_mutex */ 3069 sctx = scrub_setup_ctx(fs_info, is_dev_replace); 3070 if (IS_ERR(sctx)) 3071 return PTR_ERR(sctx); 3072 sctx->stat.last_physical = start; 3073 3074 ret = scrub_workers_get(fs_info); 3075 if (ret) 3076 goto out_free_ctx; 3077 3078 mutex_lock(&fs_info->fs_devices->device_list_mutex); 3079 dev = btrfs_find_device(fs_info->fs_devices, &args); 3080 if (!dev || (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) && 3081 !is_dev_replace)) { 3082 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3083 ret = -ENODEV; 3084 goto out; 3085 } 3086 3087 if (!is_dev_replace && !readonly && 3088 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) { 3089 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3090 btrfs_err(fs_info, 3091 "scrub: devid %llu: filesystem on %s is not writable", 3092 devid, btrfs_dev_name(dev)); 3093 ret = -EROFS; 3094 goto out; 3095 } 3096 3097 mutex_lock(&fs_info->scrub_lock); 3098 if (unlikely(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) || 3099 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &dev->dev_state))) { 3100 mutex_unlock(&fs_info->scrub_lock); 3101 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3102 ret = -EIO; 3103 goto out; 3104 } 3105 3106 down_read(&fs_info->dev_replace.rwsem); 3107 if (dev->scrub_ctx || 3108 (!is_dev_replace && 3109 btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) { 3110 up_read(&fs_info->dev_replace.rwsem); 3111 mutex_unlock(&fs_info->scrub_lock); 3112 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3113 ret = -EINPROGRESS; 3114 goto out; 3115 } 3116 up_read(&fs_info->dev_replace.rwsem); 3117 3118 sctx->readonly = readonly; 3119 dev->scrub_ctx = sctx; 3120 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3121 3122 /* 3123 * checking @scrub_pause_req here, we can avoid 3124 * race between committing transaction and scrubbing. 3125 */ 3126 __scrub_blocked_if_needed(fs_info); 3127 atomic_inc(&fs_info->scrubs_running); 3128 mutex_unlock(&fs_info->scrub_lock); 3129 3130 /* 3131 * In order to avoid deadlock with reclaim when there is a transaction 3132 * trying to pause scrub, make sure we use GFP_NOFS for all the 3133 * allocations done at btrfs_scrub_sectors() and scrub_sectors_for_parity() 3134 * invoked by our callees. The pausing request is done when the 3135 * transaction commit starts, and it blocks the transaction until scrub 3136 * is paused (done at specific points at scrub_stripe() or right above 3137 * before incrementing fs_info->scrubs_running). 3138 */ 3139 nofs_flag = memalloc_nofs_save(); 3140 if (!is_dev_replace) { 3141 u64 old_super_errors; 3142 3143 spin_lock(&sctx->stat_lock); 3144 old_super_errors = sctx->stat.super_errors; 3145 spin_unlock(&sctx->stat_lock); 3146 3147 btrfs_info(fs_info, "scrub: started on devid %llu", devid); 3148 /* 3149 * by holding device list mutex, we can 3150 * kick off writing super in log tree sync. 3151 */ 3152 mutex_lock(&fs_info->fs_devices->device_list_mutex); 3153 ret = scrub_supers(sctx, dev); 3154 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3155 3156 spin_lock(&sctx->stat_lock); 3157 /* 3158 * Super block errors found, but we can not commit transaction 3159 * at current context, since btrfs_commit_transaction() needs 3160 * to pause the current running scrub (hold by ourselves). 3161 */ 3162 if (sctx->stat.super_errors > old_super_errors && !sctx->readonly) 3163 need_commit = true; 3164 spin_unlock(&sctx->stat_lock); 3165 } 3166 3167 if (!ret) 3168 ret = scrub_enumerate_chunks(sctx, dev, start, end); 3169 memalloc_nofs_restore(nofs_flag); 3170 3171 atomic_dec(&fs_info->scrubs_running); 3172 wake_up(&fs_info->scrub_pause_wait); 3173 3174 if (progress) 3175 memcpy(progress, &sctx->stat, sizeof(*progress)); 3176 3177 if (!is_dev_replace) 3178 btrfs_info(fs_info, "scrub: %s on devid %llu with status: %d", 3179 ret ? "not finished" : "finished", devid, ret); 3180 3181 mutex_lock(&fs_info->scrub_lock); 3182 dev->scrub_ctx = NULL; 3183 mutex_unlock(&fs_info->scrub_lock); 3184 3185 scrub_workers_put(fs_info); 3186 scrub_put_ctx(sctx); 3187 3188 /* 3189 * We found some super block errors before, now try to force a 3190 * transaction commit, as scrub has finished. 3191 */ 3192 if (need_commit) { 3193 struct btrfs_trans_handle *trans; 3194 3195 trans = btrfs_start_transaction(fs_info->tree_root, 0); 3196 if (IS_ERR(trans)) { 3197 ret = PTR_ERR(trans); 3198 btrfs_err(fs_info, 3199 "scrub: failed to start transaction to fix super block errors: %d", ret); 3200 return ret; 3201 } 3202 ret = btrfs_commit_transaction(trans); 3203 if (ret < 0) 3204 btrfs_err(fs_info, 3205 "scrub: failed to commit transaction to fix super block errors: %d", ret); 3206 } 3207 return ret; 3208 out: 3209 scrub_workers_put(fs_info); 3210 out_free_ctx: 3211 scrub_free_ctx(sctx); 3212 3213 return ret; 3214 } 3215 3216 void btrfs_scrub_pause(struct btrfs_fs_info *fs_info) 3217 { 3218 mutex_lock(&fs_info->scrub_lock); 3219 atomic_inc(&fs_info->scrub_pause_req); 3220 while (atomic_read(&fs_info->scrubs_paused) != 3221 atomic_read(&fs_info->scrubs_running)) { 3222 mutex_unlock(&fs_info->scrub_lock); 3223 wait_event(fs_info->scrub_pause_wait, 3224 atomic_read(&fs_info->scrubs_paused) == 3225 atomic_read(&fs_info->scrubs_running)); 3226 mutex_lock(&fs_info->scrub_lock); 3227 } 3228 mutex_unlock(&fs_info->scrub_lock); 3229 } 3230 3231 void btrfs_scrub_continue(struct btrfs_fs_info *fs_info) 3232 { 3233 atomic_dec(&fs_info->scrub_pause_req); 3234 wake_up(&fs_info->scrub_pause_wait); 3235 } 3236 3237 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info) 3238 { 3239 mutex_lock(&fs_info->scrub_lock); 3240 if (!atomic_read(&fs_info->scrubs_running)) { 3241 mutex_unlock(&fs_info->scrub_lock); 3242 return -ENOTCONN; 3243 } 3244 3245 atomic_inc(&fs_info->scrub_cancel_req); 3246 while (atomic_read(&fs_info->scrubs_running)) { 3247 mutex_unlock(&fs_info->scrub_lock); 3248 wait_event(fs_info->scrub_pause_wait, 3249 atomic_read(&fs_info->scrubs_running) == 0); 3250 mutex_lock(&fs_info->scrub_lock); 3251 } 3252 atomic_dec(&fs_info->scrub_cancel_req); 3253 mutex_unlock(&fs_info->scrub_lock); 3254 3255 return 0; 3256 } 3257 3258 int btrfs_scrub_cancel_dev(struct btrfs_device *dev) 3259 { 3260 struct btrfs_fs_info *fs_info = dev->fs_info; 3261 struct scrub_ctx *sctx; 3262 3263 mutex_lock(&fs_info->scrub_lock); 3264 sctx = dev->scrub_ctx; 3265 if (!sctx) { 3266 mutex_unlock(&fs_info->scrub_lock); 3267 return -ENOTCONN; 3268 } 3269 atomic_inc(&sctx->cancel_req); 3270 while (dev->scrub_ctx) { 3271 mutex_unlock(&fs_info->scrub_lock); 3272 wait_event(fs_info->scrub_pause_wait, 3273 dev->scrub_ctx == NULL); 3274 mutex_lock(&fs_info->scrub_lock); 3275 } 3276 mutex_unlock(&fs_info->scrub_lock); 3277 3278 return 0; 3279 } 3280 3281 int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid, 3282 struct btrfs_scrub_progress *progress) 3283 { 3284 struct btrfs_dev_lookup_args args = { .devid = devid }; 3285 struct btrfs_device *dev; 3286 struct scrub_ctx *sctx = NULL; 3287 3288 mutex_lock(&fs_info->fs_devices->device_list_mutex); 3289 dev = btrfs_find_device(fs_info->fs_devices, &args); 3290 if (dev) 3291 sctx = dev->scrub_ctx; 3292 if (sctx) 3293 memcpy(progress, &sctx->stat, sizeof(*progress)); 3294 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 3295 3296 return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV; 3297 } 3298