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