2 * Copyright (C) 2011, 2012 STRATO. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/blkdev.h>
20 #include <linux/ratelimit.h>
21 #include <linux/sched/mm.h>
25 #include "ordered-data.h"
26 #include "transaction.h"
28 #include "extent_io.h"
29 #include "dev-replace.h"
30 #include "check-integrity.h"
31 #include "rcu-string.h"
35 * This is only the first step towards a full-features scrub. It reads all
36 * extent and super block and verifies the checksums. In case a bad checksum
37 * is found or the extent cannot be read, good data will be written back if
40 * Future enhancements:
41 * - In case an unrepairable extent is encountered, track which files are
42 * affected and report them
43 * - track and record media errors, throw out bad devices
44 * - add a mode to also read unallocated space
51 * the following three values only influence the performance.
52 * The last one configures the number of parallel and outstanding I/O
53 * operations. The first two values configure an upper limit for the number
54 * of (dynamically allocated) pages that are added to a bio.
56 #define SCRUB_PAGES_PER_RD_BIO 32 /* 128k per bio */
57 #define SCRUB_PAGES_PER_WR_BIO 32 /* 128k per bio */
58 #define SCRUB_BIOS_PER_SCTX 64 /* 8MB per device in flight */
61 * the following value times PAGE_SIZE needs to be large enough to match the
62 * largest node/leaf/sector size that shall be supported.
63 * Values larger than BTRFS_STRIPE_LEN are not supported.
65 #define SCRUB_MAX_PAGES_PER_BLOCK 16 /* 64k per node/leaf/sector */
67 struct scrub_recover {
69 struct btrfs_bio *bbio;
74 struct scrub_block *sblock;
76 struct btrfs_device *dev;
77 struct list_head list;
78 u64 flags; /* extent flags */
82 u64 physical_for_dev_replace;
85 unsigned int mirror_num:8;
86 unsigned int have_csum:1;
87 unsigned int io_error:1;
89 u8 csum[BTRFS_CSUM_SIZE];
91 struct scrub_recover *recover;
96 struct scrub_ctx *sctx;
97 struct btrfs_device *dev;
102 #if SCRUB_PAGES_PER_WR_BIO >= SCRUB_PAGES_PER_RD_BIO
103 struct scrub_page *pagev[SCRUB_PAGES_PER_WR_BIO];
105 struct scrub_page *pagev[SCRUB_PAGES_PER_RD_BIO];
109 struct btrfs_work work;
113 struct scrub_page *pagev[SCRUB_MAX_PAGES_PER_BLOCK];
115 atomic_t outstanding_pages;
116 refcount_t refs; /* free mem on transition to zero */
117 struct scrub_ctx *sctx;
118 struct scrub_parity *sparity;
120 unsigned int header_error:1;
121 unsigned int checksum_error:1;
122 unsigned int no_io_error_seen:1;
123 unsigned int generation_error:1; /* also sets header_error */
125 /* The following is for the data used to check parity */
126 /* It is for the data with checksum */
127 unsigned int data_corrected:1;
129 struct btrfs_work work;
132 /* Used for the chunks with parity stripe such RAID5/6 */
133 struct scrub_parity {
134 struct scrub_ctx *sctx;
136 struct btrfs_device *scrub_dev;
148 struct list_head spages;
150 /* Work of parity check and repair */
151 struct btrfs_work work;
153 /* Mark the parity blocks which have data */
154 unsigned long *dbitmap;
157 * Mark the parity blocks which have data, but errors happen when
158 * read data or check data
160 unsigned long *ebitmap;
162 unsigned long bitmap[0];
166 struct scrub_bio *bios[SCRUB_BIOS_PER_SCTX];
167 struct btrfs_fs_info *fs_info;
170 atomic_t bios_in_flight;
171 atomic_t workers_pending;
172 spinlock_t list_lock;
173 wait_queue_head_t list_wait;
175 struct list_head csum_list;
178 int pages_per_rd_bio;
182 struct scrub_bio *wr_curr_bio;
183 struct mutex wr_lock;
184 int pages_per_wr_bio; /* <= SCRUB_PAGES_PER_WR_BIO */
185 struct btrfs_device *wr_tgtdev;
186 bool flush_all_writes;
191 struct btrfs_scrub_progress stat;
192 spinlock_t stat_lock;
195 * Use a ref counter to avoid use-after-free issues. Scrub workers
196 * decrement bios_in_flight and workers_pending and then do a wakeup
197 * on the list_wait wait queue. We must ensure the main scrub task
198 * doesn't free the scrub context before or while the workers are
199 * doing the wakeup() call.
204 struct scrub_fixup_nodatasum {
205 struct scrub_ctx *sctx;
206 struct btrfs_device *dev;
208 struct btrfs_root *root;
209 struct btrfs_work work;
213 struct scrub_nocow_inode {
217 struct list_head list;
220 struct scrub_copy_nocow_ctx {
221 struct scrub_ctx *sctx;
225 u64 physical_for_dev_replace;
226 struct list_head inodes;
227 struct btrfs_work work;
230 struct scrub_warning {
231 struct btrfs_path *path;
232 u64 extent_item_size;
236 struct btrfs_device *dev;
239 struct full_stripe_lock {
246 static void scrub_pending_bio_inc(struct scrub_ctx *sctx);
247 static void scrub_pending_bio_dec(struct scrub_ctx *sctx);
248 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx);
249 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx);
250 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check);
251 static int scrub_setup_recheck_block(struct scrub_block *original_sblock,
252 struct scrub_block *sblocks_for_recheck);
253 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
254 struct scrub_block *sblock,
255 int retry_failed_mirror);
256 static void scrub_recheck_block_checksum(struct scrub_block *sblock);
257 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
258 struct scrub_block *sblock_good);
259 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
260 struct scrub_block *sblock_good,
261 int page_num, int force_write);
262 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock);
263 static int scrub_write_page_to_dev_replace(struct scrub_block *sblock,
265 static int scrub_checksum_data(struct scrub_block *sblock);
266 static int scrub_checksum_tree_block(struct scrub_block *sblock);
267 static int scrub_checksum_super(struct scrub_block *sblock);
268 static void scrub_block_get(struct scrub_block *sblock);
269 static void scrub_block_put(struct scrub_block *sblock);
270 static void scrub_page_get(struct scrub_page *spage);
271 static void scrub_page_put(struct scrub_page *spage);
272 static void scrub_parity_get(struct scrub_parity *sparity);
273 static void scrub_parity_put(struct scrub_parity *sparity);
274 static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx,
275 struct scrub_page *spage);
276 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
277 u64 physical, struct btrfs_device *dev, u64 flags,
278 u64 gen, int mirror_num, u8 *csum, int force,
279 u64 physical_for_dev_replace);
280 static void scrub_bio_end_io(struct bio *bio);
281 static void scrub_bio_end_io_worker(struct btrfs_work *work);
282 static void scrub_block_complete(struct scrub_block *sblock);
283 static void scrub_remap_extent(struct btrfs_fs_info *fs_info,
284 u64 extent_logical, u64 extent_len,
285 u64 *extent_physical,
286 struct btrfs_device **extent_dev,
287 int *extent_mirror_num);
288 static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx,
289 struct scrub_page *spage);
290 static void scrub_wr_submit(struct scrub_ctx *sctx);
291 static void scrub_wr_bio_end_io(struct bio *bio);
292 static void scrub_wr_bio_end_io_worker(struct btrfs_work *work);
293 static int write_page_nocow(struct scrub_ctx *sctx,
294 u64 physical_for_dev_replace, struct page *page);
295 static int copy_nocow_pages_for_inode(u64 inum, u64 offset, u64 root,
296 struct scrub_copy_nocow_ctx *ctx);
297 static int copy_nocow_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
298 int mirror_num, u64 physical_for_dev_replace);
299 static void copy_nocow_pages_worker(struct btrfs_work *work);
300 static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info);
301 static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info);
302 static void scrub_put_ctx(struct scrub_ctx *sctx);
304 static inline int scrub_is_page_on_raid56(struct scrub_page *page)
306 return page->recover &&
307 (page->recover->bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK);
310 static void scrub_pending_bio_inc(struct scrub_ctx *sctx)
312 refcount_inc(&sctx->refs);
313 atomic_inc(&sctx->bios_in_flight);
316 static void scrub_pending_bio_dec(struct scrub_ctx *sctx)
318 atomic_dec(&sctx->bios_in_flight);
319 wake_up(&sctx->list_wait);
323 static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
325 while (atomic_read(&fs_info->scrub_pause_req)) {
326 mutex_unlock(&fs_info->scrub_lock);
327 wait_event(fs_info->scrub_pause_wait,
328 atomic_read(&fs_info->scrub_pause_req) == 0);
329 mutex_lock(&fs_info->scrub_lock);
333 static void scrub_pause_on(struct btrfs_fs_info *fs_info)
335 atomic_inc(&fs_info->scrubs_paused);
336 wake_up(&fs_info->scrub_pause_wait);
339 static void scrub_pause_off(struct btrfs_fs_info *fs_info)
341 mutex_lock(&fs_info->scrub_lock);
342 __scrub_blocked_if_needed(fs_info);
343 atomic_dec(&fs_info->scrubs_paused);
344 mutex_unlock(&fs_info->scrub_lock);
346 wake_up(&fs_info->scrub_pause_wait);
349 static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
351 scrub_pause_on(fs_info);
352 scrub_pause_off(fs_info);
356 * Insert new full stripe lock into full stripe locks tree
358 * Return pointer to existing or newly inserted full_stripe_lock structure if
359 * everything works well.
360 * Return ERR_PTR(-ENOMEM) if we failed to allocate memory
362 * NOTE: caller must hold full_stripe_locks_root->lock before calling this
365 static struct full_stripe_lock *insert_full_stripe_lock(
366 struct btrfs_full_stripe_locks_tree *locks_root,
370 struct rb_node *parent = NULL;
371 struct full_stripe_lock *entry;
372 struct full_stripe_lock *ret;
374 WARN_ON(!mutex_is_locked(&locks_root->lock));
376 p = &locks_root->root.rb_node;
379 entry = rb_entry(parent, struct full_stripe_lock, node);
380 if (fstripe_logical < entry->logical) {
382 } else if (fstripe_logical > entry->logical) {
390 /* Insert new lock */
391 ret = kmalloc(sizeof(*ret), GFP_KERNEL);
393 return ERR_PTR(-ENOMEM);
394 ret->logical = fstripe_logical;
396 mutex_init(&ret->mutex);
398 rb_link_node(&ret->node, parent, p);
399 rb_insert_color(&ret->node, &locks_root->root);
404 * Search for a full stripe lock of a block group
406 * Return pointer to existing full stripe lock if found
407 * Return NULL if not found
409 static struct full_stripe_lock *search_full_stripe_lock(
410 struct btrfs_full_stripe_locks_tree *locks_root,
413 struct rb_node *node;
414 struct full_stripe_lock *entry;
416 WARN_ON(!mutex_is_locked(&locks_root->lock));
418 node = locks_root->root.rb_node;
420 entry = rb_entry(node, struct full_stripe_lock, node);
421 if (fstripe_logical < entry->logical)
422 node = node->rb_left;
423 else if (fstripe_logical > entry->logical)
424 node = node->rb_right;
432 * Helper to get full stripe logical from a normal bytenr.
434 * Caller must ensure @cache is a RAID56 block group.
436 static u64 get_full_stripe_logical(struct btrfs_block_group_cache *cache,
442 * Due to chunk item size limit, full stripe length should not be
443 * larger than U32_MAX. Just a sanity check here.
445 WARN_ON_ONCE(cache->full_stripe_len >= U32_MAX);
448 * round_down() can only handle power of 2, while RAID56 full
449 * stripe length can be 64KiB * n, so we need to manually round down.
451 ret = div64_u64(bytenr - cache->key.objectid, cache->full_stripe_len) *
452 cache->full_stripe_len + cache->key.objectid;
457 * Lock a full stripe to avoid concurrency of recovery and read
459 * It's only used for profiles with parities (RAID5/6), for other profiles it
462 * Return 0 if we locked full stripe covering @bytenr, with a mutex held.
463 * So caller must call unlock_full_stripe() at the same context.
465 * Return <0 if encounters error.
467 static int lock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr,
470 struct btrfs_block_group_cache *bg_cache;
471 struct btrfs_full_stripe_locks_tree *locks_root;
472 struct full_stripe_lock *existing;
477 bg_cache = btrfs_lookup_block_group(fs_info, bytenr);
483 /* Profiles not based on parity don't need full stripe lock */
484 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK))
486 locks_root = &bg_cache->full_stripe_locks_root;
488 fstripe_start = get_full_stripe_logical(bg_cache, bytenr);
490 /* Now insert the full stripe lock */
491 mutex_lock(&locks_root->lock);
492 existing = insert_full_stripe_lock(locks_root, fstripe_start);
493 mutex_unlock(&locks_root->lock);
494 if (IS_ERR(existing)) {
495 ret = PTR_ERR(existing);
498 mutex_lock(&existing->mutex);
501 btrfs_put_block_group(bg_cache);
506 * Unlock a full stripe.
508 * NOTE: Caller must ensure it's the same context calling corresponding
509 * lock_full_stripe().
511 * Return 0 if we unlock full stripe without problem.
512 * Return <0 for error
514 static int unlock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr,
517 struct btrfs_block_group_cache *bg_cache;
518 struct btrfs_full_stripe_locks_tree *locks_root;
519 struct full_stripe_lock *fstripe_lock;
524 /* If we didn't acquire full stripe lock, no need to continue */
528 bg_cache = btrfs_lookup_block_group(fs_info, bytenr);
533 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK))
536 locks_root = &bg_cache->full_stripe_locks_root;
537 fstripe_start = get_full_stripe_logical(bg_cache, bytenr);
539 mutex_lock(&locks_root->lock);
540 fstripe_lock = search_full_stripe_lock(locks_root, fstripe_start);
541 /* Unpaired unlock_full_stripe() detected */
545 mutex_unlock(&locks_root->lock);
549 if (fstripe_lock->refs == 0) {
551 btrfs_warn(fs_info, "full stripe lock at %llu refcount underflow",
552 fstripe_lock->logical);
554 fstripe_lock->refs--;
557 if (fstripe_lock->refs == 0) {
558 rb_erase(&fstripe_lock->node, &locks_root->root);
561 mutex_unlock(&locks_root->lock);
563 mutex_unlock(&fstripe_lock->mutex);
567 btrfs_put_block_group(bg_cache);
572 * used for workers that require transaction commits (i.e., for the
575 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx)
577 struct btrfs_fs_info *fs_info = sctx->fs_info;
579 refcount_inc(&sctx->refs);
581 * increment scrubs_running to prevent cancel requests from
582 * completing as long as a worker is running. we must also
583 * increment scrubs_paused to prevent deadlocking on pause
584 * requests used for transactions commits (as the worker uses a
585 * transaction context). it is safe to regard the worker
586 * as paused for all matters practical. effectively, we only
587 * avoid cancellation requests from completing.
589 mutex_lock(&fs_info->scrub_lock);
590 atomic_inc(&fs_info->scrubs_running);
591 atomic_inc(&fs_info->scrubs_paused);
592 mutex_unlock(&fs_info->scrub_lock);
595 * check if @scrubs_running=@scrubs_paused condition
596 * inside wait_event() is not an atomic operation.
597 * which means we may inc/dec @scrub_running/paused
598 * at any time. Let's wake up @scrub_pause_wait as
599 * much as we can to let commit transaction blocked less.
601 wake_up(&fs_info->scrub_pause_wait);
603 atomic_inc(&sctx->workers_pending);
606 /* used for workers that require transaction commits */
607 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx)
609 struct btrfs_fs_info *fs_info = sctx->fs_info;
612 * see scrub_pending_trans_workers_inc() why we're pretending
613 * to be paused in the scrub counters
615 mutex_lock(&fs_info->scrub_lock);
616 atomic_dec(&fs_info->scrubs_running);
617 atomic_dec(&fs_info->scrubs_paused);
618 mutex_unlock(&fs_info->scrub_lock);
619 atomic_dec(&sctx->workers_pending);
620 wake_up(&fs_info->scrub_pause_wait);
621 wake_up(&sctx->list_wait);
625 static void scrub_free_csums(struct scrub_ctx *sctx)
627 while (!list_empty(&sctx->csum_list)) {
628 struct btrfs_ordered_sum *sum;
629 sum = list_first_entry(&sctx->csum_list,
630 struct btrfs_ordered_sum, list);
631 list_del(&sum->list);
636 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
643 /* this can happen when scrub is cancelled */
644 if (sctx->curr != -1) {
645 struct scrub_bio *sbio = sctx->bios[sctx->curr];
647 for (i = 0; i < sbio->page_count; i++) {
648 WARN_ON(!sbio->pagev[i]->page);
649 scrub_block_put(sbio->pagev[i]->sblock);
654 for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
655 struct scrub_bio *sbio = sctx->bios[i];
662 kfree(sctx->wr_curr_bio);
663 scrub_free_csums(sctx);
667 static void scrub_put_ctx(struct scrub_ctx *sctx)
669 if (refcount_dec_and_test(&sctx->refs))
670 scrub_free_ctx(sctx);
673 static noinline_for_stack
674 struct scrub_ctx *scrub_setup_ctx(struct btrfs_device *dev, int is_dev_replace)
676 struct scrub_ctx *sctx;
678 struct btrfs_fs_info *fs_info = dev->fs_info;
680 sctx = kzalloc(sizeof(*sctx), GFP_KERNEL);
683 refcount_set(&sctx->refs, 1);
684 sctx->is_dev_replace = is_dev_replace;
685 sctx->pages_per_rd_bio = SCRUB_PAGES_PER_RD_BIO;
687 sctx->fs_info = dev->fs_info;
688 for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
689 struct scrub_bio *sbio;
691 sbio = kzalloc(sizeof(*sbio), GFP_KERNEL);
694 sctx->bios[i] = sbio;
698 sbio->page_count = 0;
699 btrfs_init_work(&sbio->work, btrfs_scrub_helper,
700 scrub_bio_end_io_worker, NULL, NULL);
702 if (i != SCRUB_BIOS_PER_SCTX - 1)
703 sctx->bios[i]->next_free = i + 1;
705 sctx->bios[i]->next_free = -1;
707 sctx->first_free = 0;
708 atomic_set(&sctx->bios_in_flight, 0);
709 atomic_set(&sctx->workers_pending, 0);
710 atomic_set(&sctx->cancel_req, 0);
711 sctx->csum_size = btrfs_super_csum_size(fs_info->super_copy);
712 INIT_LIST_HEAD(&sctx->csum_list);
714 spin_lock_init(&sctx->list_lock);
715 spin_lock_init(&sctx->stat_lock);
716 init_waitqueue_head(&sctx->list_wait);
718 WARN_ON(sctx->wr_curr_bio != NULL);
719 mutex_init(&sctx->wr_lock);
720 sctx->wr_curr_bio = NULL;
721 if (is_dev_replace) {
722 WARN_ON(!fs_info->dev_replace.tgtdev);
723 sctx->pages_per_wr_bio = SCRUB_PAGES_PER_WR_BIO;
724 sctx->wr_tgtdev = fs_info->dev_replace.tgtdev;
725 sctx->flush_all_writes = false;
731 scrub_free_ctx(sctx);
732 return ERR_PTR(-ENOMEM);
735 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root,
743 struct extent_buffer *eb;
744 struct btrfs_inode_item *inode_item;
745 struct scrub_warning *swarn = warn_ctx;
746 struct btrfs_fs_info *fs_info = swarn->dev->fs_info;
747 struct inode_fs_paths *ipath = NULL;
748 struct btrfs_root *local_root;
749 struct btrfs_key root_key;
750 struct btrfs_key key;
752 root_key.objectid = root;
753 root_key.type = BTRFS_ROOT_ITEM_KEY;
754 root_key.offset = (u64)-1;
755 local_root = btrfs_read_fs_root_no_name(fs_info, &root_key);
756 if (IS_ERR(local_root)) {
757 ret = PTR_ERR(local_root);
762 * this makes the path point to (inum INODE_ITEM ioff)
765 key.type = BTRFS_INODE_ITEM_KEY;
768 ret = btrfs_search_slot(NULL, local_root, &key, swarn->path, 0, 0);
770 btrfs_release_path(swarn->path);
774 eb = swarn->path->nodes[0];
775 inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
776 struct btrfs_inode_item);
777 isize = btrfs_inode_size(eb, inode_item);
778 nlink = btrfs_inode_nlink(eb, inode_item);
779 btrfs_release_path(swarn->path);
782 * init_path might indirectly call vmalloc, or use GFP_KERNEL. Scrub
783 * uses GFP_NOFS in this context, so we keep it consistent but it does
784 * not seem to be strictly necessary.
786 nofs_flag = memalloc_nofs_save();
787 ipath = init_ipath(4096, local_root, swarn->path);
788 memalloc_nofs_restore(nofs_flag);
790 ret = PTR_ERR(ipath);
794 ret = paths_from_inode(inum, ipath);
800 * we deliberately ignore the bit ipath might have been too small to
801 * hold all of the paths here
803 for (i = 0; i < ipath->fspath->elem_cnt; ++i)
804 btrfs_warn_in_rcu(fs_info,
805 "%s at logical %llu on dev %s, sector %llu, root %llu, inode %llu, offset %llu, length %llu, links %u (path: %s)",
806 swarn->errstr, swarn->logical,
807 rcu_str_deref(swarn->dev->name),
808 (unsigned long long)swarn->sector,
810 min(isize - offset, (u64)PAGE_SIZE), nlink,
811 (char *)(unsigned long)ipath->fspath->val[i]);
817 btrfs_warn_in_rcu(fs_info,
818 "%s at logical %llu on dev %s, sector %llu, root %llu, inode %llu, offset %llu: path resolving failed with ret=%d",
819 swarn->errstr, swarn->logical,
820 rcu_str_deref(swarn->dev->name),
821 (unsigned long long)swarn->sector,
822 root, inum, offset, ret);
828 static void scrub_print_warning(const char *errstr, struct scrub_block *sblock)
830 struct btrfs_device *dev;
831 struct btrfs_fs_info *fs_info;
832 struct btrfs_path *path;
833 struct btrfs_key found_key;
834 struct extent_buffer *eb;
835 struct btrfs_extent_item *ei;
836 struct scrub_warning swarn;
837 unsigned long ptr = 0;
845 WARN_ON(sblock->page_count < 1);
846 dev = sblock->pagev[0]->dev;
847 fs_info = sblock->sctx->fs_info;
849 path = btrfs_alloc_path();
853 swarn.sector = (sblock->pagev[0]->physical) >> 9;
854 swarn.logical = sblock->pagev[0]->logical;
855 swarn.errstr = errstr;
858 ret = extent_from_logical(fs_info, swarn.logical, path, &found_key,
863 extent_item_pos = swarn.logical - found_key.objectid;
864 swarn.extent_item_size = found_key.offset;
867 ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
868 item_size = btrfs_item_size_nr(eb, path->slots[0]);
870 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
872 ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
873 item_size, &ref_root,
875 btrfs_warn_in_rcu(fs_info,
876 "%s at logical %llu on dev %s, sector %llu: metadata %s (level %d) in tree %llu",
877 errstr, swarn.logical,
878 rcu_str_deref(dev->name),
879 (unsigned long long)swarn.sector,
880 ref_level ? "node" : "leaf",
881 ret < 0 ? -1 : ref_level,
882 ret < 0 ? -1 : ref_root);
884 btrfs_release_path(path);
886 btrfs_release_path(path);
889 iterate_extent_inodes(fs_info, found_key.objectid,
891 scrub_print_warning_inode, &swarn);
895 btrfs_free_path(path);
898 static int scrub_fixup_readpage(u64 inum, u64 offset, u64 root, void *fixup_ctx)
900 struct page *page = NULL;
902 struct scrub_fixup_nodatasum *fixup = fixup_ctx;
905 struct btrfs_key key;
906 struct inode *inode = NULL;
907 struct btrfs_fs_info *fs_info;
908 u64 end = offset + PAGE_SIZE - 1;
909 struct btrfs_root *local_root;
913 key.type = BTRFS_ROOT_ITEM_KEY;
914 key.offset = (u64)-1;
916 fs_info = fixup->root->fs_info;
917 srcu_index = srcu_read_lock(&fs_info->subvol_srcu);
919 local_root = btrfs_read_fs_root_no_name(fs_info, &key);
920 if (IS_ERR(local_root)) {
921 srcu_read_unlock(&fs_info->subvol_srcu, srcu_index);
922 return PTR_ERR(local_root);
925 key.type = BTRFS_INODE_ITEM_KEY;
928 inode = btrfs_iget(fs_info->sb, &key, local_root, NULL);
929 srcu_read_unlock(&fs_info->subvol_srcu, srcu_index);
931 return PTR_ERR(inode);
933 index = offset >> PAGE_SHIFT;
935 page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
941 if (PageUptodate(page)) {
942 if (PageDirty(page)) {
944 * we need to write the data to the defect sector. the
945 * data that was in that sector is not in memory,
946 * because the page was modified. we must not write the
947 * modified page to that sector.
949 * TODO: what could be done here: wait for the delalloc
950 * runner to write out that page (might involve
951 * COW) and see whether the sector is still
952 * referenced afterwards.
954 * For the meantime, we'll treat this error
955 * incorrectable, although there is a chance that a
956 * later scrub will find the bad sector again and that
957 * there's no dirty page in memory, then.
962 ret = repair_io_failure(fs_info, inum, offset, PAGE_SIZE,
963 fixup->logical, page,
964 offset - page_offset(page),
970 * we need to get good data first. the general readpage path
971 * will call repair_io_failure for us, we just have to make
972 * sure we read the bad mirror.
974 ret = set_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
977 /* set_extent_bits should give proper error */
984 ret = extent_read_full_page(&BTRFS_I(inode)->io_tree, page,
987 wait_on_page_locked(page);
989 corrected = !test_range_bit(&BTRFS_I(inode)->io_tree, offset,
990 end, EXTENT_DAMAGED, 0, NULL);
992 clear_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
1005 if (ret == 0 && corrected) {
1007 * we only need to call readpage for one of the inodes belonging
1008 * to this extent. so make iterate_extent_inodes stop
1016 static void scrub_fixup_nodatasum(struct btrfs_work *work)
1018 struct btrfs_fs_info *fs_info;
1020 struct scrub_fixup_nodatasum *fixup;
1021 struct scrub_ctx *sctx;
1022 struct btrfs_trans_handle *trans = NULL;
1023 struct btrfs_path *path;
1024 int uncorrectable = 0;
1026 fixup = container_of(work, struct scrub_fixup_nodatasum, work);
1028 fs_info = fixup->root->fs_info;
1030 path = btrfs_alloc_path();
1032 spin_lock(&sctx->stat_lock);
1033 ++sctx->stat.malloc_errors;
1034 spin_unlock(&sctx->stat_lock);
1039 trans = btrfs_join_transaction(fixup->root);
1040 if (IS_ERR(trans)) {
1046 * the idea is to trigger a regular read through the standard path. we
1047 * read a page from the (failed) logical address by specifying the
1048 * corresponding copynum of the failed sector. thus, that readpage is
1050 * that is the point where on-the-fly error correction will kick in
1051 * (once it's finished) and rewrite the failed sector if a good copy
1054 ret = iterate_inodes_from_logical(fixup->logical, fs_info, path,
1055 scrub_fixup_readpage, fixup);
1062 spin_lock(&sctx->stat_lock);
1063 ++sctx->stat.corrected_errors;
1064 spin_unlock(&sctx->stat_lock);
1067 if (trans && !IS_ERR(trans))
1068 btrfs_end_transaction(trans);
1069 if (uncorrectable) {
1070 spin_lock(&sctx->stat_lock);
1071 ++sctx->stat.uncorrectable_errors;
1072 spin_unlock(&sctx->stat_lock);
1073 btrfs_dev_replace_stats_inc(
1074 &fs_info->dev_replace.num_uncorrectable_read_errors);
1075 btrfs_err_rl_in_rcu(fs_info,
1076 "unable to fixup (nodatasum) error at logical %llu on dev %s",
1077 fixup->logical, rcu_str_deref(fixup->dev->name));
1080 btrfs_free_path(path);
1083 scrub_pending_trans_workers_dec(sctx);
1086 static inline void scrub_get_recover(struct scrub_recover *recover)
1088 refcount_inc(&recover->refs);
1091 static inline void scrub_put_recover(struct btrfs_fs_info *fs_info,
1092 struct scrub_recover *recover)
1094 if (refcount_dec_and_test(&recover->refs)) {
1095 btrfs_bio_counter_dec(fs_info);
1096 btrfs_put_bbio(recover->bbio);
1102 * scrub_handle_errored_block gets called when either verification of the
1103 * pages failed or the bio failed to read, e.g. with EIO. In the latter
1104 * case, this function handles all pages in the bio, even though only one
1106 * The goal of this function is to repair the errored block by using the
1107 * contents of one of the mirrors.
1109 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check)
1111 struct scrub_ctx *sctx = sblock_to_check->sctx;
1112 struct btrfs_device *dev;
1113 struct btrfs_fs_info *fs_info;
1116 unsigned int failed_mirror_index;
1117 unsigned int is_metadata;
1118 unsigned int have_csum;
1119 struct scrub_block *sblocks_for_recheck; /* holds one for each mirror */
1120 struct scrub_block *sblock_bad;
1125 bool full_stripe_locked;
1126 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
1127 DEFAULT_RATELIMIT_BURST);
1129 BUG_ON(sblock_to_check->page_count < 1);
1130 fs_info = sctx->fs_info;
1131 if (sblock_to_check->pagev[0]->flags & BTRFS_EXTENT_FLAG_SUPER) {
1133 * if we find an error in a super block, we just report it.
1134 * They will get written with the next transaction commit
1137 spin_lock(&sctx->stat_lock);
1138 ++sctx->stat.super_errors;
1139 spin_unlock(&sctx->stat_lock);
1142 length = sblock_to_check->page_count * PAGE_SIZE;
1143 logical = sblock_to_check->pagev[0]->logical;
1144 BUG_ON(sblock_to_check->pagev[0]->mirror_num < 1);
1145 failed_mirror_index = sblock_to_check->pagev[0]->mirror_num - 1;
1146 is_metadata = !(sblock_to_check->pagev[0]->flags &
1147 BTRFS_EXTENT_FLAG_DATA);
1148 have_csum = sblock_to_check->pagev[0]->have_csum;
1149 dev = sblock_to_check->pagev[0]->dev;
1152 * For RAID5/6, race can happen for a different device scrub thread.
1153 * For data corruption, Parity and Data threads will both try
1154 * to recovery the data.
1155 * Race can lead to doubly added csum error, or even unrecoverable
1158 ret = lock_full_stripe(fs_info, logical, &full_stripe_locked);
1160 spin_lock(&sctx->stat_lock);
1162 sctx->stat.malloc_errors++;
1163 sctx->stat.read_errors++;
1164 sctx->stat.uncorrectable_errors++;
1165 spin_unlock(&sctx->stat_lock);
1170 * read all mirrors one after the other. This includes to
1171 * re-read the extent or metadata block that failed (that was
1172 * the cause that this fixup code is called) another time,
1173 * page by page this time in order to know which pages
1174 * caused I/O errors and which ones are good (for all mirrors).
1175 * It is the goal to handle the situation when more than one
1176 * mirror contains I/O errors, but the errors do not
1177 * overlap, i.e. the data can be repaired by selecting the
1178 * pages from those mirrors without I/O error on the
1179 * particular pages. One example (with blocks >= 2 * PAGE_SIZE)
1180 * would be that mirror #1 has an I/O error on the first page,
1181 * the second page is good, and mirror #2 has an I/O error on
1182 * the second page, but the first page is good.
1183 * Then the first page of the first mirror can be repaired by
1184 * taking the first page of the second mirror, and the
1185 * second page of the second mirror can be repaired by
1186 * copying the contents of the 2nd page of the 1st mirror.
1187 * One more note: if the pages of one mirror contain I/O
1188 * errors, the checksum cannot be verified. In order to get
1189 * the best data for repairing, the first attempt is to find
1190 * a mirror without I/O errors and with a validated checksum.
1191 * Only if this is not possible, the pages are picked from
1192 * mirrors with I/O errors without considering the checksum.
1193 * If the latter is the case, at the end, the checksum of the
1194 * repaired area is verified in order to correctly maintain
1198 sblocks_for_recheck = kcalloc(BTRFS_MAX_MIRRORS,
1199 sizeof(*sblocks_for_recheck), GFP_NOFS);
1200 if (!sblocks_for_recheck) {
1201 spin_lock(&sctx->stat_lock);
1202 sctx->stat.malloc_errors++;
1203 sctx->stat.read_errors++;
1204 sctx->stat.uncorrectable_errors++;
1205 spin_unlock(&sctx->stat_lock);
1206 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1210 /* setup the context, map the logical blocks and alloc the pages */
1211 ret = scrub_setup_recheck_block(sblock_to_check, sblocks_for_recheck);
1213 spin_lock(&sctx->stat_lock);
1214 sctx->stat.read_errors++;
1215 sctx->stat.uncorrectable_errors++;
1216 spin_unlock(&sctx->stat_lock);
1217 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1220 BUG_ON(failed_mirror_index >= BTRFS_MAX_MIRRORS);
1221 sblock_bad = sblocks_for_recheck + failed_mirror_index;
1223 /* build and submit the bios for the failed mirror, check checksums */
1224 scrub_recheck_block(fs_info, sblock_bad, 1);
1226 if (!sblock_bad->header_error && !sblock_bad->checksum_error &&
1227 sblock_bad->no_io_error_seen) {
1229 * the error disappeared after reading page by page, or
1230 * the area was part of a huge bio and other parts of the
1231 * bio caused I/O errors, or the block layer merged several
1232 * read requests into one and the error is caused by a
1233 * different bio (usually one of the two latter cases is
1236 spin_lock(&sctx->stat_lock);
1237 sctx->stat.unverified_errors++;
1238 sblock_to_check->data_corrected = 1;
1239 spin_unlock(&sctx->stat_lock);
1241 if (sctx->is_dev_replace)
1242 scrub_write_block_to_dev_replace(sblock_bad);
1246 if (!sblock_bad->no_io_error_seen) {
1247 spin_lock(&sctx->stat_lock);
1248 sctx->stat.read_errors++;
1249 spin_unlock(&sctx->stat_lock);
1250 if (__ratelimit(&_rs))
1251 scrub_print_warning("i/o error", sblock_to_check);
1252 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
1253 } else if (sblock_bad->checksum_error) {
1254 spin_lock(&sctx->stat_lock);
1255 sctx->stat.csum_errors++;
1256 spin_unlock(&sctx->stat_lock);
1257 if (__ratelimit(&_rs))
1258 scrub_print_warning("checksum error", sblock_to_check);
1259 btrfs_dev_stat_inc_and_print(dev,
1260 BTRFS_DEV_STAT_CORRUPTION_ERRS);
1261 } else if (sblock_bad->header_error) {
1262 spin_lock(&sctx->stat_lock);
1263 sctx->stat.verify_errors++;
1264 spin_unlock(&sctx->stat_lock);
1265 if (__ratelimit(&_rs))
1266 scrub_print_warning("checksum/header error",
1268 if (sblock_bad->generation_error)
1269 btrfs_dev_stat_inc_and_print(dev,
1270 BTRFS_DEV_STAT_GENERATION_ERRS);
1272 btrfs_dev_stat_inc_and_print(dev,
1273 BTRFS_DEV_STAT_CORRUPTION_ERRS);
1276 if (sctx->readonly) {
1277 ASSERT(!sctx->is_dev_replace);
1282 * NOTE: Even for nodatasum case, it's still possible that it's a
1283 * compressed data extent, thus scrub_fixup_nodatasum(), which write
1284 * inode page cache onto disk, could cause serious data corruption.
1286 * So here we could only read from disk, and hope our recovery could
1287 * reach disk before the newer write.
1289 if (0 && !is_metadata && !have_csum) {
1290 struct scrub_fixup_nodatasum *fixup_nodatasum;
1292 WARN_ON(sctx->is_dev_replace);
1295 * !is_metadata and !have_csum, this means that the data
1296 * might not be COWed, that it might be modified
1297 * concurrently. The general strategy to work on the
1298 * commit root does not help in the case when COW is not
1301 fixup_nodatasum = kzalloc(sizeof(*fixup_nodatasum), GFP_NOFS);
1302 if (!fixup_nodatasum)
1303 goto did_not_correct_error;
1304 fixup_nodatasum->sctx = sctx;
1305 fixup_nodatasum->dev = dev;
1306 fixup_nodatasum->logical = logical;
1307 fixup_nodatasum->root = fs_info->extent_root;
1308 fixup_nodatasum->mirror_num = failed_mirror_index + 1;
1309 scrub_pending_trans_workers_inc(sctx);
1310 btrfs_init_work(&fixup_nodatasum->work, btrfs_scrub_helper,
1311 scrub_fixup_nodatasum, NULL, NULL);
1312 btrfs_queue_work(fs_info->scrub_workers,
1313 &fixup_nodatasum->work);
1318 * now build and submit the bios for the other mirrors, check
1320 * First try to pick the mirror which is completely without I/O
1321 * errors and also does not have a checksum error.
1322 * If one is found, and if a checksum is present, the full block
1323 * that is known to contain an error is rewritten. Afterwards
1324 * the block is known to be corrected.
1325 * If a mirror is found which is completely correct, and no
1326 * checksum is present, only those pages are rewritten that had
1327 * an I/O error in the block to be repaired, since it cannot be
1328 * determined, which copy of the other pages is better (and it
1329 * could happen otherwise that a correct page would be
1330 * overwritten by a bad one).
1332 for (mirror_index = 0; ;mirror_index++) {
1333 struct scrub_block *sblock_other;
1335 if (mirror_index == failed_mirror_index)
1338 /* raid56's mirror can be more than BTRFS_MAX_MIRRORS */
1339 if (!scrub_is_page_on_raid56(sblock_bad->pagev[0])) {
1340 if (mirror_index >= BTRFS_MAX_MIRRORS)
1342 if (!sblocks_for_recheck[mirror_index].page_count)
1345 sblock_other = sblocks_for_recheck + mirror_index;
1347 struct scrub_recover *r = sblock_bad->pagev[0]->recover;
1348 int max_allowed = r->bbio->num_stripes -
1349 r->bbio->num_tgtdevs;
1351 if (mirror_index >= max_allowed)
1353 if (!sblocks_for_recheck[1].page_count)
1356 ASSERT(failed_mirror_index == 0);
1357 sblock_other = sblocks_for_recheck + 1;
1358 sblock_other->pagev[0]->mirror_num = 1 + mirror_index;
1361 /* build and submit the bios, check checksums */
1362 scrub_recheck_block(fs_info, sblock_other, 0);
1364 if (!sblock_other->header_error &&
1365 !sblock_other->checksum_error &&
1366 sblock_other->no_io_error_seen) {
1367 if (sctx->is_dev_replace) {
1368 scrub_write_block_to_dev_replace(sblock_other);
1369 goto corrected_error;
1371 ret = scrub_repair_block_from_good_copy(
1372 sblock_bad, sblock_other);
1374 goto corrected_error;
1379 if (sblock_bad->no_io_error_seen && !sctx->is_dev_replace)
1380 goto did_not_correct_error;
1383 * In case of I/O errors in the area that is supposed to be
1384 * repaired, continue by picking good copies of those pages.
1385 * Select the good pages from mirrors to rewrite bad pages from
1386 * the area to fix. Afterwards verify the checksum of the block
1387 * that is supposed to be repaired. This verification step is
1388 * only done for the purpose of statistic counting and for the
1389 * final scrub report, whether errors remain.
1390 * A perfect algorithm could make use of the checksum and try
1391 * all possible combinations of pages from the different mirrors
1392 * until the checksum verification succeeds. For example, when
1393 * the 2nd page of mirror #1 faces I/O errors, and the 2nd page
1394 * of mirror #2 is readable but the final checksum test fails,
1395 * then the 2nd page of mirror #3 could be tried, whether now
1396 * the final checksum succeeds. But this would be a rare
1397 * exception and is therefore not implemented. At least it is
1398 * avoided that the good copy is overwritten.
1399 * A more useful improvement would be to pick the sectors
1400 * without I/O error based on sector sizes (512 bytes on legacy
1401 * disks) instead of on PAGE_SIZE. Then maybe 512 byte of one
1402 * mirror could be repaired by taking 512 byte of a different
1403 * mirror, even if other 512 byte sectors in the same PAGE_SIZE
1404 * area are unreadable.
1407 for (page_num = 0; page_num < sblock_bad->page_count;
1409 struct scrub_page *page_bad = sblock_bad->pagev[page_num];
1410 struct scrub_block *sblock_other = NULL;
1412 /* skip no-io-error page in scrub */
1413 if (!page_bad->io_error && !sctx->is_dev_replace)
1416 /* try to find no-io-error page in mirrors */
1417 if (page_bad->io_error) {
1418 for (mirror_index = 0;
1419 mirror_index < BTRFS_MAX_MIRRORS &&
1420 sblocks_for_recheck[mirror_index].page_count > 0;
1422 if (!sblocks_for_recheck[mirror_index].
1423 pagev[page_num]->io_error) {
1424 sblock_other = sblocks_for_recheck +
1433 if (sctx->is_dev_replace) {
1435 * did not find a mirror to fetch the page
1436 * from. scrub_write_page_to_dev_replace()
1437 * handles this case (page->io_error), by
1438 * filling the block with zeros before
1439 * submitting the write request
1442 sblock_other = sblock_bad;
1444 if (scrub_write_page_to_dev_replace(sblock_other,
1446 btrfs_dev_replace_stats_inc(
1447 &fs_info->dev_replace.num_write_errors);
1450 } else if (sblock_other) {
1451 ret = scrub_repair_page_from_good_copy(sblock_bad,
1455 page_bad->io_error = 0;
1461 if (success && !sctx->is_dev_replace) {
1462 if (is_metadata || have_csum) {
1464 * need to verify the checksum now that all
1465 * sectors on disk are repaired (the write
1466 * request for data to be repaired is on its way).
1467 * Just be lazy and use scrub_recheck_block()
1468 * which re-reads the data before the checksum
1469 * is verified, but most likely the data comes out
1470 * of the page cache.
1472 scrub_recheck_block(fs_info, sblock_bad, 1);
1473 if (!sblock_bad->header_error &&
1474 !sblock_bad->checksum_error &&
1475 sblock_bad->no_io_error_seen)
1476 goto corrected_error;
1478 goto did_not_correct_error;
1481 spin_lock(&sctx->stat_lock);
1482 sctx->stat.corrected_errors++;
1483 sblock_to_check->data_corrected = 1;
1484 spin_unlock(&sctx->stat_lock);
1485 btrfs_err_rl_in_rcu(fs_info,
1486 "fixed up error at logical %llu on dev %s",
1487 logical, rcu_str_deref(dev->name));
1490 did_not_correct_error:
1491 spin_lock(&sctx->stat_lock);
1492 sctx->stat.uncorrectable_errors++;
1493 spin_unlock(&sctx->stat_lock);
1494 btrfs_err_rl_in_rcu(fs_info,
1495 "unable to fixup (regular) error at logical %llu on dev %s",
1496 logical, rcu_str_deref(dev->name));
1500 if (sblocks_for_recheck) {
1501 for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS;
1503 struct scrub_block *sblock = sblocks_for_recheck +
1505 struct scrub_recover *recover;
1508 for (page_index = 0; page_index < sblock->page_count;
1510 sblock->pagev[page_index]->sblock = NULL;
1511 recover = sblock->pagev[page_index]->recover;
1513 scrub_put_recover(fs_info, recover);
1514 sblock->pagev[page_index]->recover =
1517 scrub_page_put(sblock->pagev[page_index]);
1520 kfree(sblocks_for_recheck);
1523 ret = unlock_full_stripe(fs_info, logical, full_stripe_locked);
1529 static inline int scrub_nr_raid_mirrors(struct btrfs_bio *bbio)
1531 if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID5)
1533 else if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID6)
1536 return (int)bbio->num_stripes;
1539 static inline void scrub_stripe_index_and_offset(u64 logical, u64 map_type,
1542 int nstripes, int mirror,
1548 if (map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
1550 for (i = 0; i < nstripes; i++) {
1551 if (raid_map[i] == RAID6_Q_STRIPE ||
1552 raid_map[i] == RAID5_P_STRIPE)
1555 if (logical >= raid_map[i] &&
1556 logical < raid_map[i] + mapped_length)
1561 *stripe_offset = logical - raid_map[i];
1563 /* The other RAID type */
1564 *stripe_index = mirror;
1569 static int scrub_setup_recheck_block(struct scrub_block *original_sblock,
1570 struct scrub_block *sblocks_for_recheck)
1572 struct scrub_ctx *sctx = original_sblock->sctx;
1573 struct btrfs_fs_info *fs_info = sctx->fs_info;
1574 u64 length = original_sblock->page_count * PAGE_SIZE;
1575 u64 logical = original_sblock->pagev[0]->logical;
1576 u64 generation = original_sblock->pagev[0]->generation;
1577 u64 flags = original_sblock->pagev[0]->flags;
1578 u64 have_csum = original_sblock->pagev[0]->have_csum;
1579 struct scrub_recover *recover;
1580 struct btrfs_bio *bbio;
1591 * note: the two members refs and outstanding_pages
1592 * are not used (and not set) in the blocks that are used for
1593 * the recheck procedure
1596 while (length > 0) {
1597 sublen = min_t(u64, length, PAGE_SIZE);
1598 mapped_length = sublen;
1602 * with a length of PAGE_SIZE, each returned stripe
1603 * represents one mirror
1605 btrfs_bio_counter_inc_blocked(fs_info);
1606 ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
1607 logical, &mapped_length, &bbio);
1608 if (ret || !bbio || mapped_length < sublen) {
1609 btrfs_put_bbio(bbio);
1610 btrfs_bio_counter_dec(fs_info);
1614 recover = kzalloc(sizeof(struct scrub_recover), GFP_NOFS);
1616 btrfs_put_bbio(bbio);
1617 btrfs_bio_counter_dec(fs_info);
1621 refcount_set(&recover->refs, 1);
1622 recover->bbio = bbio;
1623 recover->map_length = mapped_length;
1625 BUG_ON(page_index >= SCRUB_MAX_PAGES_PER_BLOCK);
1627 nmirrors = min(scrub_nr_raid_mirrors(bbio), BTRFS_MAX_MIRRORS);
1629 for (mirror_index = 0; mirror_index < nmirrors;
1631 struct scrub_block *sblock;
1632 struct scrub_page *page;
1634 sblock = sblocks_for_recheck + mirror_index;
1635 sblock->sctx = sctx;
1637 page = kzalloc(sizeof(*page), GFP_NOFS);
1640 spin_lock(&sctx->stat_lock);
1641 sctx->stat.malloc_errors++;
1642 spin_unlock(&sctx->stat_lock);
1643 scrub_put_recover(fs_info, recover);
1646 scrub_page_get(page);
1647 sblock->pagev[page_index] = page;
1648 page->sblock = sblock;
1649 page->flags = flags;
1650 page->generation = generation;
1651 page->logical = logical;
1652 page->have_csum = have_csum;
1655 original_sblock->pagev[0]->csum,
1658 scrub_stripe_index_and_offset(logical,
1667 page->physical = bbio->stripes[stripe_index].physical +
1669 page->dev = bbio->stripes[stripe_index].dev;
1671 BUG_ON(page_index >= original_sblock->page_count);
1672 page->physical_for_dev_replace =
1673 original_sblock->pagev[page_index]->
1674 physical_for_dev_replace;
1675 /* for missing devices, dev->bdev is NULL */
1676 page->mirror_num = mirror_index + 1;
1677 sblock->page_count++;
1678 page->page = alloc_page(GFP_NOFS);
1682 scrub_get_recover(recover);
1683 page->recover = recover;
1685 scrub_put_recover(fs_info, recover);
1694 struct scrub_bio_ret {
1695 struct completion event;
1696 blk_status_t status;
1699 static void scrub_bio_wait_endio(struct bio *bio)
1701 struct scrub_bio_ret *ret = bio->bi_private;
1703 ret->status = bio->bi_status;
1704 complete(&ret->event);
1707 static int scrub_submit_raid56_bio_wait(struct btrfs_fs_info *fs_info,
1709 struct scrub_page *page)
1711 struct scrub_bio_ret done;
1715 init_completion(&done.event);
1717 bio->bi_iter.bi_sector = page->logical >> 9;
1718 bio->bi_private = &done;
1719 bio->bi_end_io = scrub_bio_wait_endio;
1721 mirror_num = page->sblock->pagev[0]->mirror_num;
1722 ret = raid56_parity_recover(fs_info, bio, page->recover->bbio,
1723 page->recover->map_length,
1728 wait_for_completion_io(&done.event);
1736 * this function will check the on disk data for checksum errors, header
1737 * errors and read I/O errors. If any I/O errors happen, the exact pages
1738 * which are errored are marked as being bad. The goal is to enable scrub
1739 * to take those pages that are not errored from all the mirrors so that
1740 * the pages that are errored in the just handled mirror can be repaired.
1742 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
1743 struct scrub_block *sblock,
1744 int retry_failed_mirror)
1748 sblock->no_io_error_seen = 1;
1750 for (page_num = 0; page_num < sblock->page_count; page_num++) {
1752 struct scrub_page *page = sblock->pagev[page_num];
1754 if (page->dev->bdev == NULL) {
1756 sblock->no_io_error_seen = 0;
1760 WARN_ON(!page->page);
1761 bio = btrfs_io_bio_alloc(1);
1762 bio_set_dev(bio, page->dev->bdev);
1764 bio_add_page(bio, page->page, PAGE_SIZE, 0);
1765 if (!retry_failed_mirror && scrub_is_page_on_raid56(page)) {
1766 if (scrub_submit_raid56_bio_wait(fs_info, bio, page)) {
1768 sblock->no_io_error_seen = 0;
1771 bio->bi_iter.bi_sector = page->physical >> 9;
1772 bio_set_op_attrs(bio, REQ_OP_READ, 0);
1774 if (btrfsic_submit_bio_wait(bio)) {
1776 sblock->no_io_error_seen = 0;
1783 if (sblock->no_io_error_seen)
1784 scrub_recheck_block_checksum(sblock);
1787 static inline int scrub_check_fsid(u8 fsid[],
1788 struct scrub_page *spage)
1790 struct btrfs_fs_devices *fs_devices = spage->dev->fs_devices;
1793 ret = memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1797 static void scrub_recheck_block_checksum(struct scrub_block *sblock)
1799 sblock->header_error = 0;
1800 sblock->checksum_error = 0;
1801 sblock->generation_error = 0;
1803 if (sblock->pagev[0]->flags & BTRFS_EXTENT_FLAG_DATA)
1804 scrub_checksum_data(sblock);
1806 scrub_checksum_tree_block(sblock);
1809 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
1810 struct scrub_block *sblock_good)
1815 for (page_num = 0; page_num < sblock_bad->page_count; page_num++) {
1818 ret_sub = scrub_repair_page_from_good_copy(sblock_bad,
1828 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
1829 struct scrub_block *sblock_good,
1830 int page_num, int force_write)
1832 struct scrub_page *page_bad = sblock_bad->pagev[page_num];
1833 struct scrub_page *page_good = sblock_good->pagev[page_num];
1834 struct btrfs_fs_info *fs_info = sblock_bad->sctx->fs_info;
1836 BUG_ON(page_bad->page == NULL);
1837 BUG_ON(page_good->page == NULL);
1838 if (force_write || sblock_bad->header_error ||
1839 sblock_bad->checksum_error || page_bad->io_error) {
1843 if (!page_bad->dev->bdev) {
1844 btrfs_warn_rl(fs_info,
1845 "scrub_repair_page_from_good_copy(bdev == NULL) is unexpected");
1849 bio = btrfs_io_bio_alloc(1);
1850 bio_set_dev(bio, page_bad->dev->bdev);
1851 bio->bi_iter.bi_sector = page_bad->physical >> 9;
1852 bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
1854 ret = bio_add_page(bio, page_good->page, PAGE_SIZE, 0);
1855 if (PAGE_SIZE != ret) {
1860 if (btrfsic_submit_bio_wait(bio)) {
1861 btrfs_dev_stat_inc_and_print(page_bad->dev,
1862 BTRFS_DEV_STAT_WRITE_ERRS);
1863 btrfs_dev_replace_stats_inc(
1864 &fs_info->dev_replace.num_write_errors);
1874 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock)
1876 struct btrfs_fs_info *fs_info = sblock->sctx->fs_info;
1880 * This block is used for the check of the parity on the source device,
1881 * so the data needn't be written into the destination device.
1883 if (sblock->sparity)
1886 for (page_num = 0; page_num < sblock->page_count; page_num++) {
1889 ret = scrub_write_page_to_dev_replace(sblock, page_num);
1891 btrfs_dev_replace_stats_inc(
1892 &fs_info->dev_replace.num_write_errors);
1896 static int scrub_write_page_to_dev_replace(struct scrub_block *sblock,
1899 struct scrub_page *spage = sblock->pagev[page_num];
1901 BUG_ON(spage->page == NULL);
1902 if (spage->io_error) {
1903 void *mapped_buffer = kmap_atomic(spage->page);
1905 clear_page(mapped_buffer);
1906 flush_dcache_page(spage->page);
1907 kunmap_atomic(mapped_buffer);
1909 return scrub_add_page_to_wr_bio(sblock->sctx, spage);
1912 static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx,
1913 struct scrub_page *spage)
1915 struct scrub_bio *sbio;
1918 mutex_lock(&sctx->wr_lock);
1920 if (!sctx->wr_curr_bio) {
1921 sctx->wr_curr_bio = kzalloc(sizeof(*sctx->wr_curr_bio),
1923 if (!sctx->wr_curr_bio) {
1924 mutex_unlock(&sctx->wr_lock);
1927 sctx->wr_curr_bio->sctx = sctx;
1928 sctx->wr_curr_bio->page_count = 0;
1930 sbio = sctx->wr_curr_bio;
1931 if (sbio->page_count == 0) {
1934 sbio->physical = spage->physical_for_dev_replace;
1935 sbio->logical = spage->logical;
1936 sbio->dev = sctx->wr_tgtdev;
1939 bio = btrfs_io_bio_alloc(sctx->pages_per_wr_bio);
1943 bio->bi_private = sbio;
1944 bio->bi_end_io = scrub_wr_bio_end_io;
1945 bio_set_dev(bio, sbio->dev->bdev);
1946 bio->bi_iter.bi_sector = sbio->physical >> 9;
1947 bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
1949 } else if (sbio->physical + sbio->page_count * PAGE_SIZE !=
1950 spage->physical_for_dev_replace ||
1951 sbio->logical + sbio->page_count * PAGE_SIZE !=
1953 scrub_wr_submit(sctx);
1957 ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0);
1958 if (ret != PAGE_SIZE) {
1959 if (sbio->page_count < 1) {
1962 mutex_unlock(&sctx->wr_lock);
1965 scrub_wr_submit(sctx);
1969 sbio->pagev[sbio->page_count] = spage;
1970 scrub_page_get(spage);
1972 if (sbio->page_count == sctx->pages_per_wr_bio)
1973 scrub_wr_submit(sctx);
1974 mutex_unlock(&sctx->wr_lock);
1979 static void scrub_wr_submit(struct scrub_ctx *sctx)
1981 struct scrub_bio *sbio;
1983 if (!sctx->wr_curr_bio)
1986 sbio = sctx->wr_curr_bio;
1987 sctx->wr_curr_bio = NULL;
1988 WARN_ON(!sbio->bio->bi_disk);
1989 scrub_pending_bio_inc(sctx);
1990 /* process all writes in a single worker thread. Then the block layer
1991 * orders the requests before sending them to the driver which
1992 * doubled the write performance on spinning disks when measured
1994 btrfsic_submit_bio(sbio->bio);
1997 static void scrub_wr_bio_end_io(struct bio *bio)
1999 struct scrub_bio *sbio = bio->bi_private;
2000 struct btrfs_fs_info *fs_info = sbio->dev->fs_info;
2002 sbio->status = bio->bi_status;
2005 btrfs_init_work(&sbio->work, btrfs_scrubwrc_helper,
2006 scrub_wr_bio_end_io_worker, NULL, NULL);
2007 btrfs_queue_work(fs_info->scrub_wr_completion_workers, &sbio->work);
2010 static void scrub_wr_bio_end_io_worker(struct btrfs_work *work)
2012 struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
2013 struct scrub_ctx *sctx = sbio->sctx;
2016 WARN_ON(sbio->page_count > SCRUB_PAGES_PER_WR_BIO);
2018 struct btrfs_dev_replace *dev_replace =
2019 &sbio->sctx->fs_info->dev_replace;
2021 for (i = 0; i < sbio->page_count; i++) {
2022 struct scrub_page *spage = sbio->pagev[i];
2024 spage->io_error = 1;
2025 btrfs_dev_replace_stats_inc(&dev_replace->
2030 for (i = 0; i < sbio->page_count; i++)
2031 scrub_page_put(sbio->pagev[i]);
2035 scrub_pending_bio_dec(sctx);
2038 static int scrub_checksum(struct scrub_block *sblock)
2044 * No need to initialize these stats currently,
2045 * because this function only use return value
2046 * instead of these stats value.
2051 sblock->header_error = 0;
2052 sblock->generation_error = 0;
2053 sblock->checksum_error = 0;
2055 WARN_ON(sblock->page_count < 1);
2056 flags = sblock->pagev[0]->flags;
2058 if (flags & BTRFS_EXTENT_FLAG_DATA)
2059 ret = scrub_checksum_data(sblock);
2060 else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2061 ret = scrub_checksum_tree_block(sblock);
2062 else if (flags & BTRFS_EXTENT_FLAG_SUPER)
2063 (void)scrub_checksum_super(sblock);
2067 scrub_handle_errored_block(sblock);
2072 static int scrub_checksum_data(struct scrub_block *sblock)
2074 struct scrub_ctx *sctx = sblock->sctx;
2075 u8 csum[BTRFS_CSUM_SIZE];
2083 BUG_ON(sblock->page_count < 1);
2084 if (!sblock->pagev[0]->have_csum)
2087 on_disk_csum = sblock->pagev[0]->csum;
2088 page = sblock->pagev[0]->page;
2089 buffer = kmap_atomic(page);
2091 len = sctx->fs_info->sectorsize;
2094 u64 l = min_t(u64, len, PAGE_SIZE);
2096 crc = btrfs_csum_data(buffer, crc, l);
2097 kunmap_atomic(buffer);
2102 BUG_ON(index >= sblock->page_count);
2103 BUG_ON(!sblock->pagev[index]->page);
2104 page = sblock->pagev[index]->page;
2105 buffer = kmap_atomic(page);
2108 btrfs_csum_final(crc, csum);
2109 if (memcmp(csum, on_disk_csum, sctx->csum_size))
2110 sblock->checksum_error = 1;
2112 return sblock->checksum_error;
2115 static int scrub_checksum_tree_block(struct scrub_block *sblock)
2117 struct scrub_ctx *sctx = sblock->sctx;
2118 struct btrfs_header *h;
2119 struct btrfs_fs_info *fs_info = sctx->fs_info;
2120 u8 calculated_csum[BTRFS_CSUM_SIZE];
2121 u8 on_disk_csum[BTRFS_CSUM_SIZE];
2123 void *mapped_buffer;
2130 BUG_ON(sblock->page_count < 1);
2131 page = sblock->pagev[0]->page;
2132 mapped_buffer = kmap_atomic(page);
2133 h = (struct btrfs_header *)mapped_buffer;
2134 memcpy(on_disk_csum, h->csum, sctx->csum_size);
2137 * we don't use the getter functions here, as we
2138 * a) don't have an extent buffer and
2139 * b) the page is already kmapped
2141 if (sblock->pagev[0]->logical != btrfs_stack_header_bytenr(h))
2142 sblock->header_error = 1;
2144 if (sblock->pagev[0]->generation != btrfs_stack_header_generation(h)) {
2145 sblock->header_error = 1;
2146 sblock->generation_error = 1;
2149 if (!scrub_check_fsid(h->fsid, sblock->pagev[0]))
2150 sblock->header_error = 1;
2152 if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
2154 sblock->header_error = 1;
2156 len = sctx->fs_info->nodesize - BTRFS_CSUM_SIZE;
2157 mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
2158 p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
2161 u64 l = min_t(u64, len, mapped_size);
2163 crc = btrfs_csum_data(p, crc, l);
2164 kunmap_atomic(mapped_buffer);
2169 BUG_ON(index >= sblock->page_count);
2170 BUG_ON(!sblock->pagev[index]->page);
2171 page = sblock->pagev[index]->page;
2172 mapped_buffer = kmap_atomic(page);
2173 mapped_size = PAGE_SIZE;
2177 btrfs_csum_final(crc, calculated_csum);
2178 if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
2179 sblock->checksum_error = 1;
2181 return sblock->header_error || sblock->checksum_error;
2184 static int scrub_checksum_super(struct scrub_block *sblock)
2186 struct btrfs_super_block *s;
2187 struct scrub_ctx *sctx = sblock->sctx;
2188 u8 calculated_csum[BTRFS_CSUM_SIZE];
2189 u8 on_disk_csum[BTRFS_CSUM_SIZE];
2191 void *mapped_buffer;
2200 BUG_ON(sblock->page_count < 1);
2201 page = sblock->pagev[0]->page;
2202 mapped_buffer = kmap_atomic(page);
2203 s = (struct btrfs_super_block *)mapped_buffer;
2204 memcpy(on_disk_csum, s->csum, sctx->csum_size);
2206 if (sblock->pagev[0]->logical != btrfs_super_bytenr(s))
2209 if (sblock->pagev[0]->generation != btrfs_super_generation(s))
2212 if (!scrub_check_fsid(s->fsid, sblock->pagev[0]))
2215 len = BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE;
2216 mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
2217 p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
2220 u64 l = min_t(u64, len, mapped_size);
2222 crc = btrfs_csum_data(p, crc, l);
2223 kunmap_atomic(mapped_buffer);
2228 BUG_ON(index >= sblock->page_count);
2229 BUG_ON(!sblock->pagev[index]->page);
2230 page = sblock->pagev[index]->page;
2231 mapped_buffer = kmap_atomic(page);
2232 mapped_size = PAGE_SIZE;
2236 btrfs_csum_final(crc, calculated_csum);
2237 if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
2240 if (fail_cor + fail_gen) {
2242 * if we find an error in a super block, we just report it.
2243 * They will get written with the next transaction commit
2246 spin_lock(&sctx->stat_lock);
2247 ++sctx->stat.super_errors;
2248 spin_unlock(&sctx->stat_lock);
2250 btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
2251 BTRFS_DEV_STAT_CORRUPTION_ERRS);
2253 btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
2254 BTRFS_DEV_STAT_GENERATION_ERRS);
2257 return fail_cor + fail_gen;
2260 static void scrub_block_get(struct scrub_block *sblock)
2262 refcount_inc(&sblock->refs);
2265 static void scrub_block_put(struct scrub_block *sblock)
2267 if (refcount_dec_and_test(&sblock->refs)) {
2270 if (sblock->sparity)
2271 scrub_parity_put(sblock->sparity);
2273 for (i = 0; i < sblock->page_count; i++)
2274 scrub_page_put(sblock->pagev[i]);
2279 static void scrub_page_get(struct scrub_page *spage)
2281 atomic_inc(&spage->refs);
2284 static void scrub_page_put(struct scrub_page *spage)
2286 if (atomic_dec_and_test(&spage->refs)) {
2288 __free_page(spage->page);
2293 static void scrub_submit(struct scrub_ctx *sctx)
2295 struct scrub_bio *sbio;
2297 if (sctx->curr == -1)
2300 sbio = sctx->bios[sctx->curr];
2302 scrub_pending_bio_inc(sctx);
2303 btrfsic_submit_bio(sbio->bio);
2306 static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx,
2307 struct scrub_page *spage)
2309 struct scrub_block *sblock = spage->sblock;
2310 struct scrub_bio *sbio;
2315 * grab a fresh bio or wait for one to become available
2317 while (sctx->curr == -1) {
2318 spin_lock(&sctx->list_lock);
2319 sctx->curr = sctx->first_free;
2320 if (sctx->curr != -1) {
2321 sctx->first_free = sctx->bios[sctx->curr]->next_free;
2322 sctx->bios[sctx->curr]->next_free = -1;
2323 sctx->bios[sctx->curr]->page_count = 0;
2324 spin_unlock(&sctx->list_lock);
2326 spin_unlock(&sctx->list_lock);
2327 wait_event(sctx->list_wait, sctx->first_free != -1);
2330 sbio = sctx->bios[sctx->curr];
2331 if (sbio->page_count == 0) {
2334 sbio->physical = spage->physical;
2335 sbio->logical = spage->logical;
2336 sbio->dev = spage->dev;
2339 bio = btrfs_io_bio_alloc(sctx->pages_per_rd_bio);
2343 bio->bi_private = sbio;
2344 bio->bi_end_io = scrub_bio_end_io;
2345 bio_set_dev(bio, sbio->dev->bdev);
2346 bio->bi_iter.bi_sector = sbio->physical >> 9;
2347 bio_set_op_attrs(bio, REQ_OP_READ, 0);
2349 } else if (sbio->physical + sbio->page_count * PAGE_SIZE !=
2351 sbio->logical + sbio->page_count * PAGE_SIZE !=
2353 sbio->dev != spage->dev) {
2358 sbio->pagev[sbio->page_count] = spage;
2359 ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0);
2360 if (ret != PAGE_SIZE) {
2361 if (sbio->page_count < 1) {
2370 scrub_block_get(sblock); /* one for the page added to the bio */
2371 atomic_inc(&sblock->outstanding_pages);
2373 if (sbio->page_count == sctx->pages_per_rd_bio)
2379 static void scrub_missing_raid56_end_io(struct bio *bio)
2381 struct scrub_block *sblock = bio->bi_private;
2382 struct btrfs_fs_info *fs_info = sblock->sctx->fs_info;
2385 sblock->no_io_error_seen = 0;
2389 btrfs_queue_work(fs_info->scrub_workers, &sblock->work);
2392 static void scrub_missing_raid56_worker(struct btrfs_work *work)
2394 struct scrub_block *sblock = container_of(work, struct scrub_block, work);
2395 struct scrub_ctx *sctx = sblock->sctx;
2396 struct btrfs_fs_info *fs_info = sctx->fs_info;
2398 struct btrfs_device *dev;
2400 logical = sblock->pagev[0]->logical;
2401 dev = sblock->pagev[0]->dev;
2403 if (sblock->no_io_error_seen)
2404 scrub_recheck_block_checksum(sblock);
2406 if (!sblock->no_io_error_seen) {
2407 spin_lock(&sctx->stat_lock);
2408 sctx->stat.read_errors++;
2409 spin_unlock(&sctx->stat_lock);
2410 btrfs_err_rl_in_rcu(fs_info,
2411 "IO error rebuilding logical %llu for dev %s",
2412 logical, rcu_str_deref(dev->name));
2413 } else if (sblock->header_error || sblock->checksum_error) {
2414 spin_lock(&sctx->stat_lock);
2415 sctx->stat.uncorrectable_errors++;
2416 spin_unlock(&sctx->stat_lock);
2417 btrfs_err_rl_in_rcu(fs_info,
2418 "failed to rebuild valid logical %llu for dev %s",
2419 logical, rcu_str_deref(dev->name));
2421 scrub_write_block_to_dev_replace(sblock);
2424 scrub_block_put(sblock);
2426 if (sctx->is_dev_replace && sctx->flush_all_writes) {
2427 mutex_lock(&sctx->wr_lock);
2428 scrub_wr_submit(sctx);
2429 mutex_unlock(&sctx->wr_lock);
2432 scrub_pending_bio_dec(sctx);
2435 static void scrub_missing_raid56_pages(struct scrub_block *sblock)
2437 struct scrub_ctx *sctx = sblock->sctx;
2438 struct btrfs_fs_info *fs_info = sctx->fs_info;
2439 u64 length = sblock->page_count * PAGE_SIZE;
2440 u64 logical = sblock->pagev[0]->logical;
2441 struct btrfs_bio *bbio = NULL;
2443 struct btrfs_raid_bio *rbio;
2447 btrfs_bio_counter_inc_blocked(fs_info);
2448 ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
2450 if (ret || !bbio || !bbio->raid_map)
2453 if (WARN_ON(!sctx->is_dev_replace ||
2454 !(bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK))) {
2456 * We shouldn't be scrubbing a missing device. Even for dev
2457 * replace, we should only get here for RAID 5/6. We either
2458 * managed to mount something with no mirrors remaining or
2459 * there's a bug in scrub_remap_extent()/btrfs_map_block().
2464 bio = btrfs_io_bio_alloc(0);
2465 bio->bi_iter.bi_sector = logical >> 9;
2466 bio->bi_private = sblock;
2467 bio->bi_end_io = scrub_missing_raid56_end_io;
2469 rbio = raid56_alloc_missing_rbio(fs_info, bio, bbio, length);
2473 for (i = 0; i < sblock->page_count; i++) {
2474 struct scrub_page *spage = sblock->pagev[i];
2476 raid56_add_scrub_pages(rbio, spage->page, spage->logical);
2479 btrfs_init_work(&sblock->work, btrfs_scrub_helper,
2480 scrub_missing_raid56_worker, NULL, NULL);
2481 scrub_block_get(sblock);
2482 scrub_pending_bio_inc(sctx);
2483 raid56_submit_missing_rbio(rbio);
2489 btrfs_bio_counter_dec(fs_info);
2490 btrfs_put_bbio(bbio);
2491 spin_lock(&sctx->stat_lock);
2492 sctx->stat.malloc_errors++;
2493 spin_unlock(&sctx->stat_lock);
2496 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
2497 u64 physical, struct btrfs_device *dev, u64 flags,
2498 u64 gen, int mirror_num, u8 *csum, int force,
2499 u64 physical_for_dev_replace)
2501 struct scrub_block *sblock;
2504 sblock = kzalloc(sizeof(*sblock), GFP_KERNEL);
2506 spin_lock(&sctx->stat_lock);
2507 sctx->stat.malloc_errors++;
2508 spin_unlock(&sctx->stat_lock);
2512 /* one ref inside this function, plus one for each page added to
2514 refcount_set(&sblock->refs, 1);
2515 sblock->sctx = sctx;
2516 sblock->no_io_error_seen = 1;
2518 for (index = 0; len > 0; index++) {
2519 struct scrub_page *spage;
2520 u64 l = min_t(u64, len, PAGE_SIZE);
2522 spage = kzalloc(sizeof(*spage), GFP_KERNEL);
2525 spin_lock(&sctx->stat_lock);
2526 sctx->stat.malloc_errors++;
2527 spin_unlock(&sctx->stat_lock);
2528 scrub_block_put(sblock);
2531 BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK);
2532 scrub_page_get(spage);
2533 sblock->pagev[index] = spage;
2534 spage->sblock = sblock;
2536 spage->flags = flags;
2537 spage->generation = gen;
2538 spage->logical = logical;
2539 spage->physical = physical;
2540 spage->physical_for_dev_replace = physical_for_dev_replace;
2541 spage->mirror_num = mirror_num;
2543 spage->have_csum = 1;
2544 memcpy(spage->csum, csum, sctx->csum_size);
2546 spage->have_csum = 0;
2548 sblock->page_count++;
2549 spage->page = alloc_page(GFP_KERNEL);
2555 physical_for_dev_replace += l;
2558 WARN_ON(sblock->page_count == 0);
2561 * This case should only be hit for RAID 5/6 device replace. See
2562 * the comment in scrub_missing_raid56_pages() for details.
2564 scrub_missing_raid56_pages(sblock);
2566 for (index = 0; index < sblock->page_count; index++) {
2567 struct scrub_page *spage = sblock->pagev[index];
2570 ret = scrub_add_page_to_rd_bio(sctx, spage);
2572 scrub_block_put(sblock);
2581 /* last one frees, either here or in bio completion for last page */
2582 scrub_block_put(sblock);
2586 static void scrub_bio_end_io(struct bio *bio)
2588 struct scrub_bio *sbio = bio->bi_private;
2589 struct btrfs_fs_info *fs_info = sbio->dev->fs_info;
2591 sbio->status = bio->bi_status;
2594 btrfs_queue_work(fs_info->scrub_workers, &sbio->work);
2597 static void scrub_bio_end_io_worker(struct btrfs_work *work)
2599 struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
2600 struct scrub_ctx *sctx = sbio->sctx;
2603 BUG_ON(sbio->page_count > SCRUB_PAGES_PER_RD_BIO);
2605 for (i = 0; i < sbio->page_count; i++) {
2606 struct scrub_page *spage = sbio->pagev[i];
2608 spage->io_error = 1;
2609 spage->sblock->no_io_error_seen = 0;
2613 /* now complete the scrub_block items that have all pages completed */
2614 for (i = 0; i < sbio->page_count; i++) {
2615 struct scrub_page *spage = sbio->pagev[i];
2616 struct scrub_block *sblock = spage->sblock;
2618 if (atomic_dec_and_test(&sblock->outstanding_pages))
2619 scrub_block_complete(sblock);
2620 scrub_block_put(sblock);
2625 spin_lock(&sctx->list_lock);
2626 sbio->next_free = sctx->first_free;
2627 sctx->first_free = sbio->index;
2628 spin_unlock(&sctx->list_lock);
2630 if (sctx->is_dev_replace && sctx->flush_all_writes) {
2631 mutex_lock(&sctx->wr_lock);
2632 scrub_wr_submit(sctx);
2633 mutex_unlock(&sctx->wr_lock);
2636 scrub_pending_bio_dec(sctx);
2639 static inline void __scrub_mark_bitmap(struct scrub_parity *sparity,
2640 unsigned long *bitmap,
2646 int sectorsize = sparity->sctx->fs_info->sectorsize;
2648 if (len >= sparity->stripe_len) {
2649 bitmap_set(bitmap, 0, sparity->nsectors);
2653 start -= sparity->logic_start;
2654 start = div64_u64_rem(start, sparity->stripe_len, &offset);
2655 offset = div_u64(offset, sectorsize);
2656 nsectors64 = div_u64(len, sectorsize);
2658 ASSERT(nsectors64 < UINT_MAX);
2659 nsectors = (u32)nsectors64;
2661 if (offset + nsectors <= sparity->nsectors) {
2662 bitmap_set(bitmap, offset, nsectors);
2666 bitmap_set(bitmap, offset, sparity->nsectors - offset);
2667 bitmap_set(bitmap, 0, nsectors - (sparity->nsectors - offset));
2670 static inline void scrub_parity_mark_sectors_error(struct scrub_parity *sparity,
2673 __scrub_mark_bitmap(sparity, sparity->ebitmap, start, len);
2676 static inline void scrub_parity_mark_sectors_data(struct scrub_parity *sparity,
2679 __scrub_mark_bitmap(sparity, sparity->dbitmap, start, len);
2682 static void scrub_block_complete(struct scrub_block *sblock)
2686 if (!sblock->no_io_error_seen) {
2688 scrub_handle_errored_block(sblock);
2691 * if has checksum error, write via repair mechanism in
2692 * dev replace case, otherwise write here in dev replace
2695 corrupted = scrub_checksum(sblock);
2696 if (!corrupted && sblock->sctx->is_dev_replace)
2697 scrub_write_block_to_dev_replace(sblock);
2700 if (sblock->sparity && corrupted && !sblock->data_corrected) {
2701 u64 start = sblock->pagev[0]->logical;
2702 u64 end = sblock->pagev[sblock->page_count - 1]->logical +
2705 scrub_parity_mark_sectors_error(sblock->sparity,
2706 start, end - start);
2710 static int scrub_find_csum(struct scrub_ctx *sctx, u64 logical, u8 *csum)
2712 struct btrfs_ordered_sum *sum = NULL;
2713 unsigned long index;
2714 unsigned long num_sectors;
2716 while (!list_empty(&sctx->csum_list)) {
2717 sum = list_first_entry(&sctx->csum_list,
2718 struct btrfs_ordered_sum, list);
2719 if (sum->bytenr > logical)
2721 if (sum->bytenr + sum->len > logical)
2724 ++sctx->stat.csum_discards;
2725 list_del(&sum->list);
2732 index = div_u64(logical - sum->bytenr, sctx->fs_info->sectorsize);
2733 ASSERT(index < UINT_MAX);
2735 num_sectors = sum->len / sctx->fs_info->sectorsize;
2736 memcpy(csum, sum->sums + index, sctx->csum_size);
2737 if (index == num_sectors - 1) {
2738 list_del(&sum->list);
2744 /* scrub extent tries to collect up to 64 kB for each bio */
2745 static int scrub_extent(struct scrub_ctx *sctx, u64 logical, u64 len,
2746 u64 physical, struct btrfs_device *dev, u64 flags,
2747 u64 gen, int mirror_num, u64 physical_for_dev_replace)
2750 u8 csum[BTRFS_CSUM_SIZE];
2753 if (flags & BTRFS_EXTENT_FLAG_DATA) {
2754 blocksize = sctx->fs_info->sectorsize;
2755 spin_lock(&sctx->stat_lock);
2756 sctx->stat.data_extents_scrubbed++;
2757 sctx->stat.data_bytes_scrubbed += len;
2758 spin_unlock(&sctx->stat_lock);
2759 } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2760 blocksize = sctx->fs_info->nodesize;
2761 spin_lock(&sctx->stat_lock);
2762 sctx->stat.tree_extents_scrubbed++;
2763 sctx->stat.tree_bytes_scrubbed += len;
2764 spin_unlock(&sctx->stat_lock);
2766 blocksize = sctx->fs_info->sectorsize;
2771 u64 l = min_t(u64, len, blocksize);
2774 if (flags & BTRFS_EXTENT_FLAG_DATA) {
2775 /* push csums to sbio */
2776 have_csum = scrub_find_csum(sctx, logical, csum);
2778 ++sctx->stat.no_csum;
2779 if (0 && sctx->is_dev_replace && !have_csum) {
2780 ret = copy_nocow_pages(sctx, logical, l,
2782 physical_for_dev_replace);
2783 goto behind_scrub_pages;
2786 ret = scrub_pages(sctx, logical, l, physical, dev, flags, gen,
2787 mirror_num, have_csum ? csum : NULL, 0,
2788 physical_for_dev_replace);
2795 physical_for_dev_replace += l;
2800 static int scrub_pages_for_parity(struct scrub_parity *sparity,
2801 u64 logical, u64 len,
2802 u64 physical, struct btrfs_device *dev,
2803 u64 flags, u64 gen, int mirror_num, u8 *csum)
2805 struct scrub_ctx *sctx = sparity->sctx;
2806 struct scrub_block *sblock;
2809 sblock = kzalloc(sizeof(*sblock), GFP_KERNEL);
2811 spin_lock(&sctx->stat_lock);
2812 sctx->stat.malloc_errors++;
2813 spin_unlock(&sctx->stat_lock);
2817 /* one ref inside this function, plus one for each page added to
2819 refcount_set(&sblock->refs, 1);
2820 sblock->sctx = sctx;
2821 sblock->no_io_error_seen = 1;
2822 sblock->sparity = sparity;
2823 scrub_parity_get(sparity);
2825 for (index = 0; len > 0; index++) {
2826 struct scrub_page *spage;
2827 u64 l = min_t(u64, len, PAGE_SIZE);
2829 spage = kzalloc(sizeof(*spage), GFP_KERNEL);
2832 spin_lock(&sctx->stat_lock);
2833 sctx->stat.malloc_errors++;
2834 spin_unlock(&sctx->stat_lock);
2835 scrub_block_put(sblock);
2838 BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK);
2839 /* For scrub block */
2840 scrub_page_get(spage);
2841 sblock->pagev[index] = spage;
2842 /* For scrub parity */
2843 scrub_page_get(spage);
2844 list_add_tail(&spage->list, &sparity->spages);
2845 spage->sblock = sblock;
2847 spage->flags = flags;
2848 spage->generation = gen;
2849 spage->logical = logical;
2850 spage->physical = physical;
2851 spage->mirror_num = mirror_num;
2853 spage->have_csum = 1;
2854 memcpy(spage->csum, csum, sctx->csum_size);
2856 spage->have_csum = 0;
2858 sblock->page_count++;
2859 spage->page = alloc_page(GFP_KERNEL);
2867 WARN_ON(sblock->page_count == 0);
2868 for (index = 0; index < sblock->page_count; index++) {
2869 struct scrub_page *spage = sblock->pagev[index];
2872 ret = scrub_add_page_to_rd_bio(sctx, spage);
2874 scrub_block_put(sblock);
2879 /* last one frees, either here or in bio completion for last page */
2880 scrub_block_put(sblock);
2884 static int scrub_extent_for_parity(struct scrub_parity *sparity,
2885 u64 logical, u64 len,
2886 u64 physical, struct btrfs_device *dev,
2887 u64 flags, u64 gen, int mirror_num)
2889 struct scrub_ctx *sctx = sparity->sctx;
2891 u8 csum[BTRFS_CSUM_SIZE];
2895 scrub_parity_mark_sectors_error(sparity, logical, len);
2899 if (flags & BTRFS_EXTENT_FLAG_DATA) {
2900 blocksize = sctx->fs_info->sectorsize;
2901 } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2902 blocksize = sctx->fs_info->nodesize;
2904 blocksize = sctx->fs_info->sectorsize;
2909 u64 l = min_t(u64, len, blocksize);
2912 if (flags & BTRFS_EXTENT_FLAG_DATA) {
2913 /* push csums to sbio */
2914 have_csum = scrub_find_csum(sctx, logical, csum);
2918 ret = scrub_pages_for_parity(sparity, logical, l, physical, dev,
2919 flags, gen, mirror_num,
2920 have_csum ? csum : NULL);
2932 * Given a physical address, this will calculate it's
2933 * logical offset. if this is a parity stripe, it will return
2934 * the most left data stripe's logical offset.
2936 * return 0 if it is a data stripe, 1 means parity stripe.
2938 static int get_raid56_logic_offset(u64 physical, int num,
2939 struct map_lookup *map, u64 *offset,
2949 last_offset = (physical - map->stripes[num].physical) *
2950 nr_data_stripes(map);
2952 *stripe_start = last_offset;
2954 *offset = last_offset;
2955 for (i = 0; i < nr_data_stripes(map); i++) {
2956 *offset = last_offset + i * map->stripe_len;
2958 stripe_nr = div64_u64(*offset, map->stripe_len);
2959 stripe_nr = div_u64(stripe_nr, nr_data_stripes(map));
2961 /* Work out the disk rotation on this stripe-set */
2962 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &rot);
2963 /* calculate which stripe this data locates */
2965 stripe_index = rot % map->num_stripes;
2966 if (stripe_index == num)
2968 if (stripe_index < num)
2971 *offset = last_offset + j * map->stripe_len;
2975 static void scrub_free_parity(struct scrub_parity *sparity)
2977 struct scrub_ctx *sctx = sparity->sctx;
2978 struct scrub_page *curr, *next;
2981 nbits = bitmap_weight(sparity->ebitmap, sparity->nsectors);
2983 spin_lock(&sctx->stat_lock);
2984 sctx->stat.read_errors += nbits;
2985 sctx->stat.uncorrectable_errors += nbits;
2986 spin_unlock(&sctx->stat_lock);
2989 list_for_each_entry_safe(curr, next, &sparity->spages, list) {
2990 list_del_init(&curr->list);
2991 scrub_page_put(curr);
2997 static void scrub_parity_bio_endio_worker(struct btrfs_work *work)
2999 struct scrub_parity *sparity = container_of(work, struct scrub_parity,
3001 struct scrub_ctx *sctx = sparity->sctx;
3003 scrub_free_parity(sparity);
3004 scrub_pending_bio_dec(sctx);
3007 static void scrub_parity_bio_endio(struct bio *bio)
3009 struct scrub_parity *sparity = (struct scrub_parity *)bio->bi_private;
3010 struct btrfs_fs_info *fs_info = sparity->sctx->fs_info;
3013 bitmap_or(sparity->ebitmap, sparity->ebitmap, sparity->dbitmap,
3018 btrfs_init_work(&sparity->work, btrfs_scrubparity_helper,
3019 scrub_parity_bio_endio_worker, NULL, NULL);
3020 btrfs_queue_work(fs_info->scrub_parity_workers, &sparity->work);
3023 static void scrub_parity_check_and_repair(struct scrub_parity *sparity)
3025 struct scrub_ctx *sctx = sparity->sctx;
3026 struct btrfs_fs_info *fs_info = sctx->fs_info;
3028 struct btrfs_raid_bio *rbio;
3029 struct btrfs_bio *bbio = NULL;
3033 if (!bitmap_andnot(sparity->dbitmap, sparity->dbitmap, sparity->ebitmap,
3037 length = sparity->logic_end - sparity->logic_start;
3039 btrfs_bio_counter_inc_blocked(fs_info);
3040 ret = btrfs_map_sblock(fs_info, BTRFS_MAP_WRITE, sparity->logic_start,
3042 if (ret || !bbio || !bbio->raid_map)
3045 bio = btrfs_io_bio_alloc(0);
3046 bio->bi_iter.bi_sector = sparity->logic_start >> 9;
3047 bio->bi_private = sparity;
3048 bio->bi_end_io = scrub_parity_bio_endio;
3050 rbio = raid56_parity_alloc_scrub_rbio(fs_info, bio, bbio,
3051 length, sparity->scrub_dev,
3057 scrub_pending_bio_inc(sctx);
3058 raid56_parity_submit_scrub_rbio(rbio);
3064 btrfs_bio_counter_dec(fs_info);
3065 btrfs_put_bbio(bbio);
3066 bitmap_or(sparity->ebitmap, sparity->ebitmap, sparity->dbitmap,
3068 spin_lock(&sctx->stat_lock);
3069 sctx->stat.malloc_errors++;
3070 spin_unlock(&sctx->stat_lock);
3072 scrub_free_parity(sparity);
3075 static inline int scrub_calc_parity_bitmap_len(int nsectors)
3077 return DIV_ROUND_UP(nsectors, BITS_PER_LONG) * sizeof(long);
3080 static void scrub_parity_get(struct scrub_parity *sparity)
3082 refcount_inc(&sparity->refs);
3085 static void scrub_parity_put(struct scrub_parity *sparity)
3087 if (!refcount_dec_and_test(&sparity->refs))
3090 scrub_parity_check_and_repair(sparity);
3093 static noinline_for_stack int scrub_raid56_parity(struct scrub_ctx *sctx,
3094 struct map_lookup *map,
3095 struct btrfs_device *sdev,
3096 struct btrfs_path *path,
3100 struct btrfs_fs_info *fs_info = sctx->fs_info;
3101 struct btrfs_root *root = fs_info->extent_root;
3102 struct btrfs_root *csum_root = fs_info->csum_root;
3103 struct btrfs_extent_item *extent;
3104 struct btrfs_bio *bbio = NULL;
3108 struct extent_buffer *l;
3109 struct btrfs_key key;
3112 u64 extent_physical;
3115 struct btrfs_device *extent_dev;
3116 struct scrub_parity *sparity;
3119 int extent_mirror_num;
3122 nsectors = div_u64(map->stripe_len, fs_info->sectorsize);
3123 bitmap_len = scrub_calc_parity_bitmap_len(nsectors);
3124 sparity = kzalloc(sizeof(struct scrub_parity) + 2 * bitmap_len,
3127 spin_lock(&sctx->stat_lock);
3128 sctx->stat.malloc_errors++;
3129 spin_unlock(&sctx->stat_lock);
3133 sparity->stripe_len = map->stripe_len;
3134 sparity->nsectors = nsectors;
3135 sparity->sctx = sctx;
3136 sparity->scrub_dev = sdev;
3137 sparity->logic_start = logic_start;
3138 sparity->logic_end = logic_end;
3139 refcount_set(&sparity->refs, 1);
3140 INIT_LIST_HEAD(&sparity->spages);
3141 sparity->dbitmap = sparity->bitmap;
3142 sparity->ebitmap = (void *)sparity->bitmap + bitmap_len;
3145 while (logic_start < logic_end) {
3146 if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
3147 key.type = BTRFS_METADATA_ITEM_KEY;
3149 key.type = BTRFS_EXTENT_ITEM_KEY;
3150 key.objectid = logic_start;
3151 key.offset = (u64)-1;
3153 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3158 ret = btrfs_previous_extent_item(root, path, 0);
3162 btrfs_release_path(path);
3163 ret = btrfs_search_slot(NULL, root, &key,
3175 slot = path->slots[0];
3176 if (slot >= btrfs_header_nritems(l)) {
3177 ret = btrfs_next_leaf(root, path);
3186 btrfs_item_key_to_cpu(l, &key, slot);
3188 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3189 key.type != BTRFS_METADATA_ITEM_KEY)
3192 if (key.type == BTRFS_METADATA_ITEM_KEY)
3193 bytes = fs_info->nodesize;
3197 if (key.objectid + bytes <= logic_start)
3200 if (key.objectid >= logic_end) {
3205 while (key.objectid >= logic_start + map->stripe_len)
3206 logic_start += map->stripe_len;
3208 extent = btrfs_item_ptr(l, slot,
3209 struct btrfs_extent_item);
3210 flags = btrfs_extent_flags(l, extent);
3211 generation = btrfs_extent_generation(l, extent);
3213 if ((flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) &&
3214 (key.objectid < logic_start ||
3215 key.objectid + bytes >
3216 logic_start + map->stripe_len)) {
3218 "scrub: tree block %llu spanning stripes, ignored. logical=%llu",
3219 key.objectid, logic_start);
3220 spin_lock(&sctx->stat_lock);
3221 sctx->stat.uncorrectable_errors++;
3222 spin_unlock(&sctx->stat_lock);
3226 extent_logical = key.objectid;
3229 if (extent_logical < logic_start) {
3230 extent_len -= logic_start - extent_logical;
3231 extent_logical = logic_start;
3234 if (extent_logical + extent_len >
3235 logic_start + map->stripe_len)
3236 extent_len = logic_start + map->stripe_len -
3239 scrub_parity_mark_sectors_data(sparity, extent_logical,
3242 mapped_length = extent_len;
3244 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ,
3245 extent_logical, &mapped_length, &bbio,
3248 if (!bbio || mapped_length < extent_len)
3252 btrfs_put_bbio(bbio);
3255 extent_physical = bbio->stripes[0].physical;
3256 extent_mirror_num = bbio->mirror_num;
3257 extent_dev = bbio->stripes[0].dev;
3258 btrfs_put_bbio(bbio);
3260 ret = btrfs_lookup_csums_range(csum_root,
3262 extent_logical + extent_len - 1,
3263 &sctx->csum_list, 1);
3267 ret = scrub_extent_for_parity(sparity, extent_logical,
3274 scrub_free_csums(sctx);
3279 if (extent_logical + extent_len <
3280 key.objectid + bytes) {
3281 logic_start += map->stripe_len;
3283 if (logic_start >= logic_end) {
3288 if (logic_start < key.objectid + bytes) {
3297 btrfs_release_path(path);
3302 logic_start += map->stripe_len;
3306 scrub_parity_mark_sectors_error(sparity, logic_start,
3307 logic_end - logic_start);
3308 scrub_parity_put(sparity);
3310 mutex_lock(&sctx->wr_lock);
3311 scrub_wr_submit(sctx);
3312 mutex_unlock(&sctx->wr_lock);
3314 btrfs_release_path(path);
3315 return ret < 0 ? ret : 0;
3318 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
3319 struct map_lookup *map,
3320 struct btrfs_device *scrub_dev,
3321 int num, u64 base, u64 length,
3324 struct btrfs_path *path, *ppath;
3325 struct btrfs_fs_info *fs_info = sctx->fs_info;
3326 struct btrfs_root *root = fs_info->extent_root;
3327 struct btrfs_root *csum_root = fs_info->csum_root;
3328 struct btrfs_extent_item *extent;
3329 struct blk_plug plug;
3334 struct extent_buffer *l;
3341 struct reada_control *reada1;
3342 struct reada_control *reada2;
3343 struct btrfs_key key;
3344 struct btrfs_key key_end;
3345 u64 increment = map->stripe_len;
3348 u64 extent_physical;
3352 struct btrfs_device *extent_dev;
3353 int extent_mirror_num;
3356 physical = map->stripes[num].physical;
3358 nstripes = div64_u64(length, map->stripe_len);
3359 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3360 offset = map->stripe_len * num;
3361 increment = map->stripe_len * map->num_stripes;
3363 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3364 int factor = map->num_stripes / map->sub_stripes;
3365 offset = map->stripe_len * (num / map->sub_stripes);
3366 increment = map->stripe_len * factor;
3367 mirror_num = num % map->sub_stripes + 1;
3368 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
3369 increment = map->stripe_len;
3370 mirror_num = num % map->num_stripes + 1;
3371 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
3372 increment = map->stripe_len;
3373 mirror_num = num % map->num_stripes + 1;
3374 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
3375 get_raid56_logic_offset(physical, num, map, &offset, NULL);
3376 increment = map->stripe_len * nr_data_stripes(map);
3379 increment = map->stripe_len;
3383 path = btrfs_alloc_path();
3387 ppath = btrfs_alloc_path();
3389 btrfs_free_path(path);
3394 * work on commit root. The related disk blocks are static as
3395 * long as COW is applied. This means, it is save to rewrite
3396 * them to repair disk errors without any race conditions
3398 path->search_commit_root = 1;
3399 path->skip_locking = 1;
3401 ppath->search_commit_root = 1;
3402 ppath->skip_locking = 1;
3404 * trigger the readahead for extent tree csum tree and wait for
3405 * completion. During readahead, the scrub is officially paused
3406 * to not hold off transaction commits
3408 logical = base + offset;
3409 physical_end = physical + nstripes * map->stripe_len;
3410 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
3411 get_raid56_logic_offset(physical_end, num,
3412 map, &logic_end, NULL);
3415 logic_end = logical + increment * nstripes;
3417 wait_event(sctx->list_wait,
3418 atomic_read(&sctx->bios_in_flight) == 0);
3419 scrub_blocked_if_needed(fs_info);
3421 /* FIXME it might be better to start readahead at commit root */
3422 key.objectid = logical;
3423 key.type = BTRFS_EXTENT_ITEM_KEY;
3424 key.offset = (u64)0;
3425 key_end.objectid = logic_end;
3426 key_end.type = BTRFS_METADATA_ITEM_KEY;
3427 key_end.offset = (u64)-1;
3428 reada1 = btrfs_reada_add(root, &key, &key_end);
3430 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3431 key.type = BTRFS_EXTENT_CSUM_KEY;
3432 key.offset = logical;
3433 key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3434 key_end.type = BTRFS_EXTENT_CSUM_KEY;
3435 key_end.offset = logic_end;
3436 reada2 = btrfs_reada_add(csum_root, &key, &key_end);
3438 if (!IS_ERR(reada1))
3439 btrfs_reada_wait(reada1);
3440 if (!IS_ERR(reada2))
3441 btrfs_reada_wait(reada2);
3445 * collect all data csums for the stripe to avoid seeking during
3446 * the scrub. This might currently (crc32) end up to be about 1MB
3448 blk_start_plug(&plug);
3451 * now find all extents for each stripe and scrub them
3454 while (physical < physical_end) {
3458 if (atomic_read(&fs_info->scrub_cancel_req) ||
3459 atomic_read(&sctx->cancel_req)) {
3464 * check to see if we have to pause
3466 if (atomic_read(&fs_info->scrub_pause_req)) {
3467 /* push queued extents */
3468 sctx->flush_all_writes = true;
3470 mutex_lock(&sctx->wr_lock);
3471 scrub_wr_submit(sctx);
3472 mutex_unlock(&sctx->wr_lock);
3473 wait_event(sctx->list_wait,
3474 atomic_read(&sctx->bios_in_flight) == 0);
3475 sctx->flush_all_writes = false;
3476 scrub_blocked_if_needed(fs_info);
3479 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
3480 ret = get_raid56_logic_offset(physical, num, map,
3485 /* it is parity strip */
3486 stripe_logical += base;
3487 stripe_end = stripe_logical + increment;
3488 ret = scrub_raid56_parity(sctx, map, scrub_dev,
3489 ppath, stripe_logical,
3497 if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
3498 key.type = BTRFS_METADATA_ITEM_KEY;
3500 key.type = BTRFS_EXTENT_ITEM_KEY;
3501 key.objectid = logical;
3502 key.offset = (u64)-1;
3504 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3509 ret = btrfs_previous_extent_item(root, path, 0);
3513 /* there's no smaller item, so stick with the
3515 btrfs_release_path(path);
3516 ret = btrfs_search_slot(NULL, root, &key,
3528 slot = path->slots[0];
3529 if (slot >= btrfs_header_nritems(l)) {
3530 ret = btrfs_next_leaf(root, path);
3539 btrfs_item_key_to_cpu(l, &key, slot);
3541 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3542 key.type != BTRFS_METADATA_ITEM_KEY)
3545 if (key.type == BTRFS_METADATA_ITEM_KEY)
3546 bytes = fs_info->nodesize;
3550 if (key.objectid + bytes <= logical)
3553 if (key.objectid >= logical + map->stripe_len) {
3554 /* out of this device extent */
3555 if (key.objectid >= logic_end)
3560 extent = btrfs_item_ptr(l, slot,
3561 struct btrfs_extent_item);
3562 flags = btrfs_extent_flags(l, extent);
3563 generation = btrfs_extent_generation(l, extent);
3565 if ((flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) &&
3566 (key.objectid < logical ||
3567 key.objectid + bytes >
3568 logical + map->stripe_len)) {
3570 "scrub: tree block %llu spanning stripes, ignored. logical=%llu",
3571 key.objectid, logical);
3572 spin_lock(&sctx->stat_lock);
3573 sctx->stat.uncorrectable_errors++;
3574 spin_unlock(&sctx->stat_lock);
3579 extent_logical = key.objectid;
3583 * trim extent to this stripe
3585 if (extent_logical < logical) {
3586 extent_len -= logical - extent_logical;
3587 extent_logical = logical;
3589 if (extent_logical + extent_len >
3590 logical + map->stripe_len) {
3591 extent_len = logical + map->stripe_len -
3595 extent_physical = extent_logical - logical + physical;
3596 extent_dev = scrub_dev;
3597 extent_mirror_num = mirror_num;
3599 scrub_remap_extent(fs_info, extent_logical,
3600 extent_len, &extent_physical,
3602 &extent_mirror_num);
3604 ret = btrfs_lookup_csums_range(csum_root,
3608 &sctx->csum_list, 1);
3612 ret = scrub_extent(sctx, extent_logical, extent_len,
3613 extent_physical, extent_dev, flags,
3614 generation, extent_mirror_num,
3615 extent_logical - logical + physical);
3617 scrub_free_csums(sctx);
3622 if (extent_logical + extent_len <
3623 key.objectid + bytes) {
3624 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
3626 * loop until we find next data stripe
3627 * or we have finished all stripes.
3630 physical += map->stripe_len;
3631 ret = get_raid56_logic_offset(physical,
3636 if (ret && physical < physical_end) {
3637 stripe_logical += base;
3638 stripe_end = stripe_logical +
3640 ret = scrub_raid56_parity(sctx,
3641 map, scrub_dev, ppath,
3649 physical += map->stripe_len;
3650 logical += increment;
3652 if (logical < key.objectid + bytes) {
3657 if (physical >= physical_end) {
3665 btrfs_release_path(path);
3667 logical += increment;
3668 physical += map->stripe_len;
3669 spin_lock(&sctx->stat_lock);
3671 sctx->stat.last_physical = map->stripes[num].physical +
3674 sctx->stat.last_physical = physical;
3675 spin_unlock(&sctx->stat_lock);
3680 /* push queued extents */
3682 mutex_lock(&sctx->wr_lock);
3683 scrub_wr_submit(sctx);
3684 mutex_unlock(&sctx->wr_lock);
3686 blk_finish_plug(&plug);
3687 btrfs_free_path(path);
3688 btrfs_free_path(ppath);
3689 return ret < 0 ? ret : 0;
3692 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx,
3693 struct btrfs_device *scrub_dev,
3694 u64 chunk_offset, u64 length,
3696 struct btrfs_block_group_cache *cache,
3699 struct btrfs_fs_info *fs_info = sctx->fs_info;
3700 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
3701 struct map_lookup *map;
3702 struct extent_map *em;
3706 read_lock(&map_tree->map_tree.lock);
3707 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
3708 read_unlock(&map_tree->map_tree.lock);
3712 * Might have been an unused block group deleted by the cleaner
3713 * kthread or relocation.
3715 spin_lock(&cache->lock);
3716 if (!cache->removed)
3718 spin_unlock(&cache->lock);
3723 map = em->map_lookup;
3724 if (em->start != chunk_offset)
3727 if (em->len < length)
3730 for (i = 0; i < map->num_stripes; ++i) {
3731 if (map->stripes[i].dev->bdev == scrub_dev->bdev &&
3732 map->stripes[i].physical == dev_offset) {
3733 ret = scrub_stripe(sctx, map, scrub_dev, i,
3734 chunk_offset, length,
3741 free_extent_map(em);
3746 static noinline_for_stack
3747 int scrub_enumerate_chunks(struct scrub_ctx *sctx,
3748 struct btrfs_device *scrub_dev, u64 start, u64 end,
3751 struct btrfs_dev_extent *dev_extent = NULL;
3752 struct btrfs_path *path;
3753 struct btrfs_fs_info *fs_info = sctx->fs_info;
3754 struct btrfs_root *root = fs_info->dev_root;
3760 struct extent_buffer *l;
3761 struct btrfs_key key;
3762 struct btrfs_key found_key;
3763 struct btrfs_block_group_cache *cache;
3764 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
3766 path = btrfs_alloc_path();
3770 path->reada = READA_FORWARD;
3771 path->search_commit_root = 1;
3772 path->skip_locking = 1;
3774 key.objectid = scrub_dev->devid;
3776 key.type = BTRFS_DEV_EXTENT_KEY;
3779 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3783 if (path->slots[0] >=
3784 btrfs_header_nritems(path->nodes[0])) {
3785 ret = btrfs_next_leaf(root, path);
3798 slot = path->slots[0];
3800 btrfs_item_key_to_cpu(l, &found_key, slot);
3802 if (found_key.objectid != scrub_dev->devid)
3805 if (found_key.type != BTRFS_DEV_EXTENT_KEY)
3808 if (found_key.offset >= end)
3811 if (found_key.offset < key.offset)
3814 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3815 length = btrfs_dev_extent_length(l, dev_extent);
3817 if (found_key.offset + length <= start)
3820 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3823 * get a reference on the corresponding block group to prevent
3824 * the chunk from going away while we scrub it
3826 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3828 /* some chunks are removed but not committed to disk yet,
3829 * continue scrubbing */
3834 * we need call btrfs_inc_block_group_ro() with scrubs_paused,
3835 * to avoid deadlock caused by:
3836 * btrfs_inc_block_group_ro()
3837 * -> btrfs_wait_for_commit()
3838 * -> btrfs_commit_transaction()
3839 * -> btrfs_scrub_pause()
3841 scrub_pause_on(fs_info);
3842 ret = btrfs_inc_block_group_ro(fs_info, cache);
3843 if (!ret && is_dev_replace) {
3845 * If we are doing a device replace wait for any tasks
3846 * that started dellaloc right before we set the block
3847 * group to RO mode, as they might have just allocated
3848 * an extent from it or decided they could do a nocow
3849 * write. And if any such tasks did that, wait for their
3850 * ordered extents to complete and then commit the
3851 * current transaction, so that we can later see the new
3852 * extent items in the extent tree - the ordered extents
3853 * create delayed data references (for cow writes) when
3854 * they complete, which will be run and insert the
3855 * corresponding extent items into the extent tree when
3856 * we commit the transaction they used when running
3857 * inode.c:btrfs_finish_ordered_io(). We later use
3858 * the commit root of the extent tree to find extents
3859 * to copy from the srcdev into the tgtdev, and we don't
3860 * want to miss any new extents.
3862 btrfs_wait_block_group_reservations(cache);
3863 btrfs_wait_nocow_writers(cache);
3864 ret = btrfs_wait_ordered_roots(fs_info, U64_MAX,
3865 cache->key.objectid,
3868 struct btrfs_trans_handle *trans;
3870 trans = btrfs_join_transaction(root);
3872 ret = PTR_ERR(trans);
3874 ret = btrfs_commit_transaction(trans);
3876 scrub_pause_off(fs_info);
3877 btrfs_put_block_group(cache);
3882 scrub_pause_off(fs_info);
3886 } else if (ret == -ENOSPC) {
3888 * btrfs_inc_block_group_ro return -ENOSPC when it
3889 * failed in creating new chunk for metadata.
3890 * It is not a problem for scrub/replace, because
3891 * metadata are always cowed, and our scrub paused
3892 * commit_transactions.
3897 "failed setting block group ro: %d", ret);
3898 btrfs_put_block_group(cache);
3902 btrfs_dev_replace_lock(&fs_info->dev_replace, 1);
3903 dev_replace->cursor_right = found_key.offset + length;
3904 dev_replace->cursor_left = found_key.offset;
3905 dev_replace->item_needs_writeback = 1;
3906 btrfs_dev_replace_unlock(&fs_info->dev_replace, 1);
3907 ret = scrub_chunk(sctx, scrub_dev, chunk_offset, length,
3908 found_key.offset, cache, is_dev_replace);
3911 * flush, submit all pending read and write bios, afterwards
3913 * Note that in the dev replace case, a read request causes
3914 * write requests that are submitted in the read completion
3915 * worker. Therefore in the current situation, it is required
3916 * that all write requests are flushed, so that all read and
3917 * write requests are really completed when bios_in_flight
3920 sctx->flush_all_writes = true;
3922 mutex_lock(&sctx->wr_lock);
3923 scrub_wr_submit(sctx);
3924 mutex_unlock(&sctx->wr_lock);
3926 wait_event(sctx->list_wait,
3927 atomic_read(&sctx->bios_in_flight) == 0);
3929 scrub_pause_on(fs_info);
3932 * must be called before we decrease @scrub_paused.
3933 * make sure we don't block transaction commit while
3934 * we are waiting pending workers finished.
3936 wait_event(sctx->list_wait,
3937 atomic_read(&sctx->workers_pending) == 0);
3938 sctx->flush_all_writes = false;
3940 scrub_pause_off(fs_info);
3942 btrfs_dev_replace_lock(&fs_info->dev_replace, 1);
3943 dev_replace->cursor_left = dev_replace->cursor_right;
3944 dev_replace->item_needs_writeback = 1;
3945 btrfs_dev_replace_unlock(&fs_info->dev_replace, 1);
3948 btrfs_dec_block_group_ro(cache);
3951 * We might have prevented the cleaner kthread from deleting
3952 * this block group if it was already unused because we raced
3953 * and set it to RO mode first. So add it back to the unused
3954 * list, otherwise it might not ever be deleted unless a manual
3955 * balance is triggered or it becomes used and unused again.
3957 spin_lock(&cache->lock);
3958 if (!cache->removed && !cache->ro && cache->reserved == 0 &&
3959 btrfs_block_group_used(&cache->item) == 0) {
3960 spin_unlock(&cache->lock);
3961 spin_lock(&fs_info->unused_bgs_lock);
3962 if (list_empty(&cache->bg_list)) {
3963 btrfs_get_block_group(cache);
3964 list_add_tail(&cache->bg_list,
3965 &fs_info->unused_bgs);
3967 spin_unlock(&fs_info->unused_bgs_lock);
3969 spin_unlock(&cache->lock);
3972 btrfs_put_block_group(cache);
3975 if (is_dev_replace &&
3976 atomic64_read(&dev_replace->num_write_errors) > 0) {
3980 if (sctx->stat.malloc_errors > 0) {
3985 key.offset = found_key.offset + length;
3986 btrfs_release_path(path);
3989 btrfs_free_path(path);
3994 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx,
3995 struct btrfs_device *scrub_dev)
4001 struct btrfs_fs_info *fs_info = sctx->fs_info;
4003 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4006 /* Seed devices of a new filesystem has their own generation. */
4007 if (scrub_dev->fs_devices != fs_info->fs_devices)
4008 gen = scrub_dev->generation;
4010 gen = fs_info->last_trans_committed;
4012 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
4013 bytenr = btrfs_sb_offset(i);
4014 if (bytenr + BTRFS_SUPER_INFO_SIZE >
4015 scrub_dev->commit_total_bytes)
4018 ret = scrub_pages(sctx, bytenr, BTRFS_SUPER_INFO_SIZE, bytenr,
4019 scrub_dev, BTRFS_EXTENT_FLAG_SUPER, gen, i,
4024 wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
4030 * get a reference count on fs_info->scrub_workers. start worker if necessary
4032 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info,
4035 unsigned int flags = WQ_FREEZABLE | WQ_UNBOUND;
4036 int max_active = fs_info->thread_pool_size;
4038 if (fs_info->scrub_workers_refcnt == 0) {
4039 fs_info->scrub_workers = btrfs_alloc_workqueue(fs_info, "scrub",
4040 flags, is_dev_replace ? 1 : max_active, 4);
4041 if (!fs_info->scrub_workers)
4042 goto fail_scrub_workers;
4044 fs_info->scrub_wr_completion_workers =
4045 btrfs_alloc_workqueue(fs_info, "scrubwrc", flags,
4047 if (!fs_info->scrub_wr_completion_workers)
4048 goto fail_scrub_wr_completion_workers;
4050 fs_info->scrub_nocow_workers =
4051 btrfs_alloc_workqueue(fs_info, "scrubnc", flags, 1, 0);
4052 if (!fs_info->scrub_nocow_workers)
4053 goto fail_scrub_nocow_workers;
4054 fs_info->scrub_parity_workers =
4055 btrfs_alloc_workqueue(fs_info, "scrubparity", flags,
4057 if (!fs_info->scrub_parity_workers)
4058 goto fail_scrub_parity_workers;
4060 ++fs_info->scrub_workers_refcnt;
4063 fail_scrub_parity_workers:
4064 btrfs_destroy_workqueue(fs_info->scrub_nocow_workers);
4065 fail_scrub_nocow_workers:
4066 btrfs_destroy_workqueue(fs_info->scrub_wr_completion_workers);
4067 fail_scrub_wr_completion_workers:
4068 btrfs_destroy_workqueue(fs_info->scrub_workers);
4073 static noinline_for_stack void scrub_workers_put(struct btrfs_fs_info *fs_info)
4075 if (--fs_info->scrub_workers_refcnt == 0) {
4076 btrfs_destroy_workqueue(fs_info->scrub_workers);
4077 btrfs_destroy_workqueue(fs_info->scrub_wr_completion_workers);
4078 btrfs_destroy_workqueue(fs_info->scrub_nocow_workers);
4079 btrfs_destroy_workqueue(fs_info->scrub_parity_workers);
4081 WARN_ON(fs_info->scrub_workers_refcnt < 0);
4084 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
4085 u64 end, struct btrfs_scrub_progress *progress,
4086 int readonly, int is_dev_replace)
4088 struct scrub_ctx *sctx;
4090 struct btrfs_device *dev;
4091 struct rcu_string *name;
4093 if (btrfs_fs_closing(fs_info))
4096 if (fs_info->nodesize > BTRFS_STRIPE_LEN) {
4098 * in this case scrub is unable to calculate the checksum
4099 * the way scrub is implemented. Do not handle this
4100 * situation at all because it won't ever happen.
4103 "scrub: size assumption nodesize <= BTRFS_STRIPE_LEN (%d <= %d) fails",
4109 if (fs_info->sectorsize != PAGE_SIZE) {
4110 /* not supported for data w/o checksums */
4111 btrfs_err_rl(fs_info,
4112 "scrub: size assumption sectorsize != PAGE_SIZE (%d != %lu) fails",
4113 fs_info->sectorsize, PAGE_SIZE);
4117 if (fs_info->nodesize >
4118 PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK ||
4119 fs_info->sectorsize > PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK) {
4121 * would exhaust the array bounds of pagev member in
4122 * struct scrub_block
4125 "scrub: size assumption nodesize and sectorsize <= SCRUB_MAX_PAGES_PER_BLOCK (%d <= %d && %d <= %d) fails",
4127 SCRUB_MAX_PAGES_PER_BLOCK,
4128 fs_info->sectorsize,
4129 SCRUB_MAX_PAGES_PER_BLOCK);
4134 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4135 dev = btrfs_find_device(fs_info, devid, NULL, NULL);
4136 if (!dev || (dev->missing && !is_dev_replace)) {
4137 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4141 if (!is_dev_replace && !readonly && !dev->writeable) {
4142 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4144 name = rcu_dereference(dev->name);
4145 btrfs_err(fs_info, "scrub: device %s is not writable",
4151 mutex_lock(&fs_info->scrub_lock);
4152 if (!dev->in_fs_metadata || dev->is_tgtdev_for_dev_replace) {
4153 mutex_unlock(&fs_info->scrub_lock);
4154 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4158 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
4159 if (dev->scrub_device ||
4161 btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) {
4162 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
4163 mutex_unlock(&fs_info->scrub_lock);
4164 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4165 return -EINPROGRESS;
4167 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
4169 ret = scrub_workers_get(fs_info, is_dev_replace);
4171 mutex_unlock(&fs_info->scrub_lock);
4172 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4176 sctx = scrub_setup_ctx(dev, is_dev_replace);
4178 mutex_unlock(&fs_info->scrub_lock);
4179 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4180 scrub_workers_put(fs_info);
4181 return PTR_ERR(sctx);
4183 sctx->readonly = readonly;
4184 dev->scrub_device = sctx;
4185 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4188 * checking @scrub_pause_req here, we can avoid
4189 * race between committing transaction and scrubbing.
4191 __scrub_blocked_if_needed(fs_info);
4192 atomic_inc(&fs_info->scrubs_running);
4193 mutex_unlock(&fs_info->scrub_lock);
4195 if (!is_dev_replace) {
4197 * by holding device list mutex, we can
4198 * kick off writing super in log tree sync.
4200 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4201 ret = scrub_supers(sctx, dev);
4202 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4206 ret = scrub_enumerate_chunks(sctx, dev, start, end,
4209 wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
4210 atomic_dec(&fs_info->scrubs_running);
4211 wake_up(&fs_info->scrub_pause_wait);
4213 wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0);
4216 memcpy(progress, &sctx->stat, sizeof(*progress));
4218 mutex_lock(&fs_info->scrub_lock);
4219 dev->scrub_device = NULL;
4220 scrub_workers_put(fs_info);
4221 mutex_unlock(&fs_info->scrub_lock);
4223 scrub_put_ctx(sctx);
4228 void btrfs_scrub_pause(struct btrfs_fs_info *fs_info)
4230 mutex_lock(&fs_info->scrub_lock);
4231 atomic_inc(&fs_info->scrub_pause_req);
4232 while (atomic_read(&fs_info->scrubs_paused) !=
4233 atomic_read(&fs_info->scrubs_running)) {
4234 mutex_unlock(&fs_info->scrub_lock);
4235 wait_event(fs_info->scrub_pause_wait,
4236 atomic_read(&fs_info->scrubs_paused) ==
4237 atomic_read(&fs_info->scrubs_running));
4238 mutex_lock(&fs_info->scrub_lock);
4240 mutex_unlock(&fs_info->scrub_lock);
4243 void btrfs_scrub_continue(struct btrfs_fs_info *fs_info)
4245 atomic_dec(&fs_info->scrub_pause_req);
4246 wake_up(&fs_info->scrub_pause_wait);
4249 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
4251 mutex_lock(&fs_info->scrub_lock);
4252 if (!atomic_read(&fs_info->scrubs_running)) {
4253 mutex_unlock(&fs_info->scrub_lock);
4257 atomic_inc(&fs_info->scrub_cancel_req);
4258 while (atomic_read(&fs_info->scrubs_running)) {
4259 mutex_unlock(&fs_info->scrub_lock);
4260 wait_event(fs_info->scrub_pause_wait,
4261 atomic_read(&fs_info->scrubs_running) == 0);
4262 mutex_lock(&fs_info->scrub_lock);
4264 atomic_dec(&fs_info->scrub_cancel_req);
4265 mutex_unlock(&fs_info->scrub_lock);
4270 int btrfs_scrub_cancel_dev(struct btrfs_fs_info *fs_info,
4271 struct btrfs_device *dev)
4273 struct scrub_ctx *sctx;
4275 mutex_lock(&fs_info->scrub_lock);
4276 sctx = dev->scrub_device;
4278 mutex_unlock(&fs_info->scrub_lock);
4281 atomic_inc(&sctx->cancel_req);
4282 while (dev->scrub_device) {
4283 mutex_unlock(&fs_info->scrub_lock);
4284 wait_event(fs_info->scrub_pause_wait,
4285 dev->scrub_device == NULL);
4286 mutex_lock(&fs_info->scrub_lock);
4288 mutex_unlock(&fs_info->scrub_lock);
4293 int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid,
4294 struct btrfs_scrub_progress *progress)
4296 struct btrfs_device *dev;
4297 struct scrub_ctx *sctx = NULL;
4299 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4300 dev = btrfs_find_device(fs_info, devid, NULL, NULL);
4302 sctx = dev->scrub_device;
4304 memcpy(progress, &sctx->stat, sizeof(*progress));
4305 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4307 return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;
4310 static void scrub_remap_extent(struct btrfs_fs_info *fs_info,
4311 u64 extent_logical, u64 extent_len,
4312 u64 *extent_physical,
4313 struct btrfs_device **extent_dev,
4314 int *extent_mirror_num)
4317 struct btrfs_bio *bbio = NULL;
4320 mapped_length = extent_len;
4321 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, extent_logical,
4322 &mapped_length, &bbio, 0);
4323 if (ret || !bbio || mapped_length < extent_len ||
4324 !bbio->stripes[0].dev->bdev) {
4325 btrfs_put_bbio(bbio);
4329 *extent_physical = bbio->stripes[0].physical;
4330 *extent_mirror_num = bbio->mirror_num;
4331 *extent_dev = bbio->stripes[0].dev;
4332 btrfs_put_bbio(bbio);
4335 static int copy_nocow_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
4336 int mirror_num, u64 physical_for_dev_replace)
4338 struct scrub_copy_nocow_ctx *nocow_ctx;
4339 struct btrfs_fs_info *fs_info = sctx->fs_info;
4341 nocow_ctx = kzalloc(sizeof(*nocow_ctx), GFP_NOFS);
4343 spin_lock(&sctx->stat_lock);
4344 sctx->stat.malloc_errors++;
4345 spin_unlock(&sctx->stat_lock);
4349 scrub_pending_trans_workers_inc(sctx);
4351 nocow_ctx->sctx = sctx;
4352 nocow_ctx->logical = logical;
4353 nocow_ctx->len = len;
4354 nocow_ctx->mirror_num = mirror_num;
4355 nocow_ctx->physical_for_dev_replace = physical_for_dev_replace;
4356 btrfs_init_work(&nocow_ctx->work, btrfs_scrubnc_helper,
4357 copy_nocow_pages_worker, NULL, NULL);
4358 INIT_LIST_HEAD(&nocow_ctx->inodes);
4359 btrfs_queue_work(fs_info->scrub_nocow_workers,
4365 static int record_inode_for_nocow(u64 inum, u64 offset, u64 root, void *ctx)
4367 struct scrub_copy_nocow_ctx *nocow_ctx = ctx;
4368 struct scrub_nocow_inode *nocow_inode;
4370 nocow_inode = kzalloc(sizeof(*nocow_inode), GFP_NOFS);
4373 nocow_inode->inum = inum;
4374 nocow_inode->offset = offset;
4375 nocow_inode->root = root;
4376 list_add_tail(&nocow_inode->list, &nocow_ctx->inodes);
4380 #define COPY_COMPLETE 1
4382 static void copy_nocow_pages_worker(struct btrfs_work *work)
4384 struct scrub_copy_nocow_ctx *nocow_ctx =
4385 container_of(work, struct scrub_copy_nocow_ctx, work);
4386 struct scrub_ctx *sctx = nocow_ctx->sctx;
4387 struct btrfs_fs_info *fs_info = sctx->fs_info;
4388 struct btrfs_root *root = fs_info->extent_root;
4389 u64 logical = nocow_ctx->logical;
4390 u64 len = nocow_ctx->len;
4391 int mirror_num = nocow_ctx->mirror_num;
4392 u64 physical_for_dev_replace = nocow_ctx->physical_for_dev_replace;
4394 struct btrfs_trans_handle *trans = NULL;
4395 struct btrfs_path *path;
4396 int not_written = 0;
4398 path = btrfs_alloc_path();
4400 spin_lock(&sctx->stat_lock);
4401 sctx->stat.malloc_errors++;
4402 spin_unlock(&sctx->stat_lock);
4407 trans = btrfs_join_transaction(root);
4408 if (IS_ERR(trans)) {
4413 ret = iterate_inodes_from_logical(logical, fs_info, path,
4414 record_inode_for_nocow, nocow_ctx);
4415 if (ret != 0 && ret != -ENOENT) {
4417 "iterate_inodes_from_logical() failed: log %llu, phys %llu, len %llu, mir %u, ret %d",
4418 logical, physical_for_dev_replace, len, mirror_num,
4424 btrfs_end_transaction(trans);
4426 while (!list_empty(&nocow_ctx->inodes)) {
4427 struct scrub_nocow_inode *entry;
4428 entry = list_first_entry(&nocow_ctx->inodes,
4429 struct scrub_nocow_inode,
4431 list_del_init(&entry->list);
4432 ret = copy_nocow_pages_for_inode(entry->inum, entry->offset,
4433 entry->root, nocow_ctx);
4435 if (ret == COPY_COMPLETE) {
4443 while (!list_empty(&nocow_ctx->inodes)) {
4444 struct scrub_nocow_inode *entry;
4445 entry = list_first_entry(&nocow_ctx->inodes,
4446 struct scrub_nocow_inode,
4448 list_del_init(&entry->list);
4451 if (trans && !IS_ERR(trans))
4452 btrfs_end_transaction(trans);
4454 btrfs_dev_replace_stats_inc(&fs_info->dev_replace.
4455 num_uncorrectable_read_errors);
4457 btrfs_free_path(path);
4460 scrub_pending_trans_workers_dec(sctx);
4463 static int check_extent_to_block(struct btrfs_inode *inode, u64 start, u64 len,
4466 struct extent_state *cached_state = NULL;
4467 struct btrfs_ordered_extent *ordered;
4468 struct extent_io_tree *io_tree;
4469 struct extent_map *em;
4470 u64 lockstart = start, lockend = start + len - 1;
4473 io_tree = &inode->io_tree;
4475 lock_extent_bits(io_tree, lockstart, lockend, &cached_state);
4476 ordered = btrfs_lookup_ordered_range(inode, lockstart, len);
4478 btrfs_put_ordered_extent(ordered);
4483 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
4490 * This extent does not actually cover the logical extent anymore,
4491 * move on to the next inode.
4493 if (em->block_start > logical ||
4494 em->block_start + em->block_len < logical + len) {
4495 free_extent_map(em);
4499 free_extent_map(em);
4502 unlock_extent_cached(io_tree, lockstart, lockend, &cached_state,
4507 static int copy_nocow_pages_for_inode(u64 inum, u64 offset, u64 root,
4508 struct scrub_copy_nocow_ctx *nocow_ctx)
4510 struct btrfs_fs_info *fs_info = nocow_ctx->sctx->fs_info;
4511 struct btrfs_key key;
4512 struct inode *inode;
4514 struct btrfs_root *local_root;
4515 struct extent_io_tree *io_tree;
4516 u64 physical_for_dev_replace;
4517 u64 nocow_ctx_logical;
4518 u64 len = nocow_ctx->len;
4519 unsigned long index;
4524 key.objectid = root;
4525 key.type = BTRFS_ROOT_ITEM_KEY;
4526 key.offset = (u64)-1;
4528 srcu_index = srcu_read_lock(&fs_info->subvol_srcu);
4530 local_root = btrfs_read_fs_root_no_name(fs_info, &key);
4531 if (IS_ERR(local_root)) {
4532 srcu_read_unlock(&fs_info->subvol_srcu, srcu_index);
4533 return PTR_ERR(local_root);
4536 key.type = BTRFS_INODE_ITEM_KEY;
4537 key.objectid = inum;
4539 inode = btrfs_iget(fs_info->sb, &key, local_root, NULL);
4540 srcu_read_unlock(&fs_info->subvol_srcu, srcu_index);
4542 return PTR_ERR(inode);
4544 /* Avoid truncate/dio/punch hole.. */
4546 inode_dio_wait(inode);
4548 physical_for_dev_replace = nocow_ctx->physical_for_dev_replace;
4549 io_tree = &BTRFS_I(inode)->io_tree;
4550 nocow_ctx_logical = nocow_ctx->logical;
4552 ret = check_extent_to_block(BTRFS_I(inode), offset, len,
4555 ret = ret > 0 ? 0 : ret;
4559 while (len >= PAGE_SIZE) {
4560 index = offset >> PAGE_SHIFT;
4562 page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
4564 btrfs_err(fs_info, "find_or_create_page() failed");
4569 if (PageUptodate(page)) {
4570 if (PageDirty(page))
4573 ClearPageError(page);
4574 err = extent_read_full_page(io_tree, page,
4576 nocow_ctx->mirror_num);
4584 * If the page has been remove from the page cache,
4585 * the data on it is meaningless, because it may be
4586 * old one, the new data may be written into the new
4587 * page in the page cache.
4589 if (page->mapping != inode->i_mapping) {
4594 if (!PageUptodate(page)) {
4600 ret = check_extent_to_block(BTRFS_I(inode), offset, len,
4603 ret = ret > 0 ? 0 : ret;
4607 err = write_page_nocow(nocow_ctx->sctx,
4608 physical_for_dev_replace, page);
4618 offset += PAGE_SIZE;
4619 physical_for_dev_replace += PAGE_SIZE;
4620 nocow_ctx_logical += PAGE_SIZE;
4623 ret = COPY_COMPLETE;
4625 inode_unlock(inode);
4630 static int write_page_nocow(struct scrub_ctx *sctx,
4631 u64 physical_for_dev_replace, struct page *page)
4634 struct btrfs_device *dev;
4637 dev = sctx->wr_tgtdev;
4641 btrfs_warn_rl(dev->fs_info,
4642 "scrub write_page_nocow(bdev == NULL) is unexpected");
4645 bio = btrfs_io_bio_alloc(1);
4646 bio->bi_iter.bi_size = 0;
4647 bio->bi_iter.bi_sector = physical_for_dev_replace >> 9;
4648 bio_set_dev(bio, dev->bdev);
4649 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
4650 ret = bio_add_page(bio, page, PAGE_SIZE, 0);
4651 if (ret != PAGE_SIZE) {
4654 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
4658 if (btrfsic_submit_bio_wait(bio))
4659 goto leave_with_eio;