]> git.openfabrics.org - ~shefty/rdma-dev.git/blob - fs/btrfs/scrub.c
460e30bb1884d75358eea71b1c207833c182fbd7
[~shefty/rdma-dev.git] / fs / btrfs / scrub.c
1 /*
2  * Copyright (C) 2011, 2012 STRATO.  All rights reserved.
3  *
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.
7  *
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.
12  *
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.
17  */
18
19 #include <linux/blkdev.h>
20 #include <linux/ratelimit.h>
21 #include "ctree.h"
22 #include "volumes.h"
23 #include "disk-io.h"
24 #include "ordered-data.h"
25 #include "transaction.h"
26 #include "backref.h"
27 #include "extent_io.h"
28 #include "check-integrity.h"
29 #include "rcu-string.h"
30
31 /*
32  * This is only the first step towards a full-features scrub. It reads all
33  * extent and super block and verifies the checksums. In case a bad checksum
34  * is found or the extent cannot be read, good data will be written back if
35  * any can be found.
36  *
37  * Future enhancements:
38  *  - In case an unrepairable extent is encountered, track which files are
39  *    affected and report them
40  *  - track and record media errors, throw out bad devices
41  *  - add a mode to also read unallocated space
42  */
43
44 struct scrub_block;
45 struct scrub_ctx;
46
47 #define SCRUB_PAGES_PER_BIO     16      /* 64k per bio */
48 #define SCRUB_BIOS_PER_CTX      16      /* 1 MB per device in flight */
49
50 /*
51  * the following value times PAGE_SIZE needs to be large enough to match the
52  * largest node/leaf/sector size that shall be supported.
53  * Values larger than BTRFS_STRIPE_LEN are not supported.
54  */
55 #define SCRUB_MAX_PAGES_PER_BLOCK       16      /* 64k per node/leaf/sector */
56
57 struct scrub_page {
58         struct scrub_block      *sblock;
59         struct page             *page;
60         struct btrfs_device     *dev;
61         u64                     flags;  /* extent flags */
62         u64                     generation;
63         u64                     logical;
64         u64                     physical;
65         atomic_t                ref_count;
66         struct {
67                 unsigned int    mirror_num:8;
68                 unsigned int    have_csum:1;
69                 unsigned int    io_error:1;
70         };
71         u8                      csum[BTRFS_CSUM_SIZE];
72 };
73
74 struct scrub_bio {
75         int                     index;
76         struct scrub_ctx        *sctx;
77         struct btrfs_device     *dev;
78         struct bio              *bio;
79         int                     err;
80         u64                     logical;
81         u64                     physical;
82         struct scrub_page       *pagev[SCRUB_PAGES_PER_BIO];
83         int                     page_count;
84         int                     next_free;
85         struct btrfs_work       work;
86 };
87
88 struct scrub_block {
89         struct scrub_page       *pagev[SCRUB_MAX_PAGES_PER_BLOCK];
90         int                     page_count;
91         atomic_t                outstanding_pages;
92         atomic_t                ref_count; /* free mem on transition to zero */
93         struct scrub_ctx        *sctx;
94         struct {
95                 unsigned int    header_error:1;
96                 unsigned int    checksum_error:1;
97                 unsigned int    no_io_error_seen:1;
98                 unsigned int    generation_error:1; /* also sets header_error */
99         };
100 };
101
102 struct scrub_ctx {
103         struct scrub_bio        *bios[SCRUB_BIOS_PER_CTX];
104         struct btrfs_root       *dev_root;
105         int                     first_free;
106         int                     curr;
107         atomic_t                bios_in_flight;
108         atomic_t                workers_pending;
109         spinlock_t              list_lock;
110         wait_queue_head_t       list_wait;
111         u16                     csum_size;
112         struct list_head        csum_list;
113         atomic_t                cancel_req;
114         int                     readonly;
115         int                     pages_per_bio; /* <= SCRUB_PAGES_PER_BIO */
116         u32                     sectorsize;
117         u32                     nodesize;
118         u32                     leafsize;
119
120         int                     is_dev_replace;
121
122         /*
123          * statistics
124          */
125         struct btrfs_scrub_progress stat;
126         spinlock_t              stat_lock;
127 };
128
129 struct scrub_fixup_nodatasum {
130         struct scrub_ctx        *sctx;
131         struct btrfs_device     *dev;
132         u64                     logical;
133         struct btrfs_root       *root;
134         struct btrfs_work       work;
135         int                     mirror_num;
136 };
137
138 struct scrub_warning {
139         struct btrfs_path       *path;
140         u64                     extent_item_size;
141         char                    *scratch_buf;
142         char                    *msg_buf;
143         const char              *errstr;
144         sector_t                sector;
145         u64                     logical;
146         struct btrfs_device     *dev;
147         int                     msg_bufsize;
148         int                     scratch_bufsize;
149 };
150
151
152 static void scrub_pending_bio_inc(struct scrub_ctx *sctx);
153 static void scrub_pending_bio_dec(struct scrub_ctx *sctx);
154 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx);
155 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx);
156 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check);
157 static int scrub_setup_recheck_block(struct scrub_ctx *sctx,
158                                      struct btrfs_fs_info *fs_info,
159                                      u64 length, u64 logical,
160                                      struct scrub_block *sblock);
161 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
162                                 struct scrub_block *sblock, int is_metadata,
163                                 int have_csum, u8 *csum, u64 generation,
164                                 u16 csum_size);
165 static void scrub_recheck_block_checksum(struct btrfs_fs_info *fs_info,
166                                          struct scrub_block *sblock,
167                                          int is_metadata, int have_csum,
168                                          const u8 *csum, u64 generation,
169                                          u16 csum_size);
170 static void scrub_complete_bio_end_io(struct bio *bio, int err);
171 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
172                                              struct scrub_block *sblock_good,
173                                              int force_write);
174 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
175                                             struct scrub_block *sblock_good,
176                                             int page_num, int force_write);
177 static int scrub_checksum_data(struct scrub_block *sblock);
178 static int scrub_checksum_tree_block(struct scrub_block *sblock);
179 static int scrub_checksum_super(struct scrub_block *sblock);
180 static void scrub_block_get(struct scrub_block *sblock);
181 static void scrub_block_put(struct scrub_block *sblock);
182 static void scrub_page_get(struct scrub_page *spage);
183 static void scrub_page_put(struct scrub_page *spage);
184 static int scrub_add_page_to_bio(struct scrub_ctx *sctx,
185                                  struct scrub_page *spage);
186 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
187                        u64 physical, struct btrfs_device *dev, u64 flags,
188                        u64 gen, int mirror_num, u8 *csum, int force);
189 static void scrub_bio_end_io(struct bio *bio, int err);
190 static void scrub_bio_end_io_worker(struct btrfs_work *work);
191 static void scrub_block_complete(struct scrub_block *sblock);
192
193
194 static void scrub_pending_bio_inc(struct scrub_ctx *sctx)
195 {
196         atomic_inc(&sctx->bios_in_flight);
197 }
198
199 static void scrub_pending_bio_dec(struct scrub_ctx *sctx)
200 {
201         atomic_dec(&sctx->bios_in_flight);
202         wake_up(&sctx->list_wait);
203 }
204
205 /*
206  * used for workers that require transaction commits (i.e., for the
207  * NOCOW case)
208  */
209 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx)
210 {
211         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
212
213         /*
214          * increment scrubs_running to prevent cancel requests from
215          * completing as long as a worker is running. we must also
216          * increment scrubs_paused to prevent deadlocking on pause
217          * requests used for transactions commits (as the worker uses a
218          * transaction context). it is safe to regard the worker
219          * as paused for all matters practical. effectively, we only
220          * avoid cancellation requests from completing.
221          */
222         mutex_lock(&fs_info->scrub_lock);
223         atomic_inc(&fs_info->scrubs_running);
224         atomic_inc(&fs_info->scrubs_paused);
225         mutex_unlock(&fs_info->scrub_lock);
226         atomic_inc(&sctx->workers_pending);
227 }
228
229 /* used for workers that require transaction commits */
230 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx)
231 {
232         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
233
234         /*
235          * see scrub_pending_trans_workers_inc() why we're pretending
236          * to be paused in the scrub counters
237          */
238         mutex_lock(&fs_info->scrub_lock);
239         atomic_dec(&fs_info->scrubs_running);
240         atomic_dec(&fs_info->scrubs_paused);
241         mutex_unlock(&fs_info->scrub_lock);
242         atomic_dec(&sctx->workers_pending);
243         wake_up(&fs_info->scrub_pause_wait);
244         wake_up(&sctx->list_wait);
245 }
246
247 static void scrub_free_csums(struct scrub_ctx *sctx)
248 {
249         while (!list_empty(&sctx->csum_list)) {
250                 struct btrfs_ordered_sum *sum;
251                 sum = list_first_entry(&sctx->csum_list,
252                                        struct btrfs_ordered_sum, list);
253                 list_del(&sum->list);
254                 kfree(sum);
255         }
256 }
257
258 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
259 {
260         int i;
261
262         if (!sctx)
263                 return;
264
265         /* this can happen when scrub is cancelled */
266         if (sctx->curr != -1) {
267                 struct scrub_bio *sbio = sctx->bios[sctx->curr];
268
269                 for (i = 0; i < sbio->page_count; i++) {
270                         BUG_ON(!sbio->pagev[i]);
271                         BUG_ON(!sbio->pagev[i]->page);
272                         scrub_block_put(sbio->pagev[i]->sblock);
273                 }
274                 bio_put(sbio->bio);
275         }
276
277         for (i = 0; i < SCRUB_BIOS_PER_CTX; ++i) {
278                 struct scrub_bio *sbio = sctx->bios[i];
279
280                 if (!sbio)
281                         break;
282                 kfree(sbio);
283         }
284
285         scrub_free_csums(sctx);
286         kfree(sctx);
287 }
288
289 static noinline_for_stack
290 struct scrub_ctx *scrub_setup_ctx(struct btrfs_device *dev, int is_dev_replace)
291 {
292         struct scrub_ctx *sctx;
293         int             i;
294         struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
295         int pages_per_bio;
296
297         pages_per_bio = min_t(int, SCRUB_PAGES_PER_BIO,
298                               bio_get_nr_vecs(dev->bdev));
299         sctx = kzalloc(sizeof(*sctx), GFP_NOFS);
300         if (!sctx)
301                 goto nomem;
302         sctx->is_dev_replace = is_dev_replace;
303         sctx->pages_per_bio = pages_per_bio;
304         sctx->curr = -1;
305         sctx->dev_root = dev->dev_root;
306         for (i = 0; i < SCRUB_BIOS_PER_CTX; ++i) {
307                 struct scrub_bio *sbio;
308
309                 sbio = kzalloc(sizeof(*sbio), GFP_NOFS);
310                 if (!sbio)
311                         goto nomem;
312                 sctx->bios[i] = sbio;
313
314                 sbio->index = i;
315                 sbio->sctx = sctx;
316                 sbio->page_count = 0;
317                 sbio->work.func = scrub_bio_end_io_worker;
318
319                 if (i != SCRUB_BIOS_PER_CTX - 1)
320                         sctx->bios[i]->next_free = i + 1;
321                 else
322                         sctx->bios[i]->next_free = -1;
323         }
324         sctx->first_free = 0;
325         sctx->nodesize = dev->dev_root->nodesize;
326         sctx->leafsize = dev->dev_root->leafsize;
327         sctx->sectorsize = dev->dev_root->sectorsize;
328         atomic_set(&sctx->bios_in_flight, 0);
329         atomic_set(&sctx->workers_pending, 0);
330         atomic_set(&sctx->cancel_req, 0);
331         sctx->csum_size = btrfs_super_csum_size(fs_info->super_copy);
332         INIT_LIST_HEAD(&sctx->csum_list);
333
334         spin_lock_init(&sctx->list_lock);
335         spin_lock_init(&sctx->stat_lock);
336         init_waitqueue_head(&sctx->list_wait);
337         return sctx;
338
339 nomem:
340         scrub_free_ctx(sctx);
341         return ERR_PTR(-ENOMEM);
342 }
343
344 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root, void *ctx)
345 {
346         u64 isize;
347         u32 nlink;
348         int ret;
349         int i;
350         struct extent_buffer *eb;
351         struct btrfs_inode_item *inode_item;
352         struct scrub_warning *swarn = ctx;
353         struct btrfs_fs_info *fs_info = swarn->dev->dev_root->fs_info;
354         struct inode_fs_paths *ipath = NULL;
355         struct btrfs_root *local_root;
356         struct btrfs_key root_key;
357
358         root_key.objectid = root;
359         root_key.type = BTRFS_ROOT_ITEM_KEY;
360         root_key.offset = (u64)-1;
361         local_root = btrfs_read_fs_root_no_name(fs_info, &root_key);
362         if (IS_ERR(local_root)) {
363                 ret = PTR_ERR(local_root);
364                 goto err;
365         }
366
367         ret = inode_item_info(inum, 0, local_root, swarn->path);
368         if (ret) {
369                 btrfs_release_path(swarn->path);
370                 goto err;
371         }
372
373         eb = swarn->path->nodes[0];
374         inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
375                                         struct btrfs_inode_item);
376         isize = btrfs_inode_size(eb, inode_item);
377         nlink = btrfs_inode_nlink(eb, inode_item);
378         btrfs_release_path(swarn->path);
379
380         ipath = init_ipath(4096, local_root, swarn->path);
381         if (IS_ERR(ipath)) {
382                 ret = PTR_ERR(ipath);
383                 ipath = NULL;
384                 goto err;
385         }
386         ret = paths_from_inode(inum, ipath);
387
388         if (ret < 0)
389                 goto err;
390
391         /*
392          * we deliberately ignore the bit ipath might have been too small to
393          * hold all of the paths here
394          */
395         for (i = 0; i < ipath->fspath->elem_cnt; ++i)
396                 printk_in_rcu(KERN_WARNING "btrfs: %s at logical %llu on dev "
397                         "%s, sector %llu, root %llu, inode %llu, offset %llu, "
398                         "length %llu, links %u (path: %s)\n", swarn->errstr,
399                         swarn->logical, rcu_str_deref(swarn->dev->name),
400                         (unsigned long long)swarn->sector, root, inum, offset,
401                         min(isize - offset, (u64)PAGE_SIZE), nlink,
402                         (char *)(unsigned long)ipath->fspath->val[i]);
403
404         free_ipath(ipath);
405         return 0;
406
407 err:
408         printk_in_rcu(KERN_WARNING "btrfs: %s at logical %llu on dev "
409                 "%s, sector %llu, root %llu, inode %llu, offset %llu: path "
410                 "resolving failed with ret=%d\n", swarn->errstr,
411                 swarn->logical, rcu_str_deref(swarn->dev->name),
412                 (unsigned long long)swarn->sector, root, inum, offset, ret);
413
414         free_ipath(ipath);
415         return 0;
416 }
417
418 static void scrub_print_warning(const char *errstr, struct scrub_block *sblock)
419 {
420         struct btrfs_device *dev;
421         struct btrfs_fs_info *fs_info;
422         struct btrfs_path *path;
423         struct btrfs_key found_key;
424         struct extent_buffer *eb;
425         struct btrfs_extent_item *ei;
426         struct scrub_warning swarn;
427         unsigned long ptr = 0;
428         u64 extent_item_pos;
429         u64 flags = 0;
430         u64 ref_root;
431         u32 item_size;
432         u8 ref_level;
433         const int bufsize = 4096;
434         int ret;
435
436         WARN_ON(sblock->page_count < 1);
437         dev = sblock->pagev[0]->dev;
438         fs_info = sblock->sctx->dev_root->fs_info;
439
440         path = btrfs_alloc_path();
441
442         swarn.scratch_buf = kmalloc(bufsize, GFP_NOFS);
443         swarn.msg_buf = kmalloc(bufsize, GFP_NOFS);
444         swarn.sector = (sblock->pagev[0]->physical) >> 9;
445         swarn.logical = sblock->pagev[0]->logical;
446         swarn.errstr = errstr;
447         swarn.dev = NULL;
448         swarn.msg_bufsize = bufsize;
449         swarn.scratch_bufsize = bufsize;
450
451         if (!path || !swarn.scratch_buf || !swarn.msg_buf)
452                 goto out;
453
454         ret = extent_from_logical(fs_info, swarn.logical, path, &found_key,
455                                   &flags);
456         if (ret < 0)
457                 goto out;
458
459         extent_item_pos = swarn.logical - found_key.objectid;
460         swarn.extent_item_size = found_key.offset;
461
462         eb = path->nodes[0];
463         ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
464         item_size = btrfs_item_size_nr(eb, path->slots[0]);
465         btrfs_release_path(path);
466
467         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
468                 do {
469                         ret = tree_backref_for_extent(&ptr, eb, ei, item_size,
470                                                         &ref_root, &ref_level);
471                         printk_in_rcu(KERN_WARNING
472                                 "btrfs: %s at logical %llu on dev %s, "
473                                 "sector %llu: metadata %s (level %d) in tree "
474                                 "%llu\n", errstr, swarn.logical,
475                                 rcu_str_deref(dev->name),
476                                 (unsigned long long)swarn.sector,
477                                 ref_level ? "node" : "leaf",
478                                 ret < 0 ? -1 : ref_level,
479                                 ret < 0 ? -1 : ref_root);
480                 } while (ret != 1);
481         } else {
482                 swarn.path = path;
483                 swarn.dev = dev;
484                 iterate_extent_inodes(fs_info, found_key.objectid,
485                                         extent_item_pos, 1,
486                                         scrub_print_warning_inode, &swarn);
487         }
488
489 out:
490         btrfs_free_path(path);
491         kfree(swarn.scratch_buf);
492         kfree(swarn.msg_buf);
493 }
494
495 static int scrub_fixup_readpage(u64 inum, u64 offset, u64 root, void *ctx)
496 {
497         struct page *page = NULL;
498         unsigned long index;
499         struct scrub_fixup_nodatasum *fixup = ctx;
500         int ret;
501         int corrected = 0;
502         struct btrfs_key key;
503         struct inode *inode = NULL;
504         u64 end = offset + PAGE_SIZE - 1;
505         struct btrfs_root *local_root;
506
507         key.objectid = root;
508         key.type = BTRFS_ROOT_ITEM_KEY;
509         key.offset = (u64)-1;
510         local_root = btrfs_read_fs_root_no_name(fixup->root->fs_info, &key);
511         if (IS_ERR(local_root))
512                 return PTR_ERR(local_root);
513
514         key.type = BTRFS_INODE_ITEM_KEY;
515         key.objectid = inum;
516         key.offset = 0;
517         inode = btrfs_iget(fixup->root->fs_info->sb, &key, local_root, NULL);
518         if (IS_ERR(inode))
519                 return PTR_ERR(inode);
520
521         index = offset >> PAGE_CACHE_SHIFT;
522
523         page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
524         if (!page) {
525                 ret = -ENOMEM;
526                 goto out;
527         }
528
529         if (PageUptodate(page)) {
530                 struct btrfs_fs_info *fs_info;
531                 if (PageDirty(page)) {
532                         /*
533                          * we need to write the data to the defect sector. the
534                          * data that was in that sector is not in memory,
535                          * because the page was modified. we must not write the
536                          * modified page to that sector.
537                          *
538                          * TODO: what could be done here: wait for the delalloc
539                          *       runner to write out that page (might involve
540                          *       COW) and see whether the sector is still
541                          *       referenced afterwards.
542                          *
543                          * For the meantime, we'll treat this error
544                          * incorrectable, although there is a chance that a
545                          * later scrub will find the bad sector again and that
546                          * there's no dirty page in memory, then.
547                          */
548                         ret = -EIO;
549                         goto out;
550                 }
551                 fs_info = BTRFS_I(inode)->root->fs_info;
552                 ret = repair_io_failure(fs_info, offset, PAGE_SIZE,
553                                         fixup->logical, page,
554                                         fixup->mirror_num);
555                 unlock_page(page);
556                 corrected = !ret;
557         } else {
558                 /*
559                  * we need to get good data first. the general readpage path
560                  * will call repair_io_failure for us, we just have to make
561                  * sure we read the bad mirror.
562                  */
563                 ret = set_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
564                                         EXTENT_DAMAGED, GFP_NOFS);
565                 if (ret) {
566                         /* set_extent_bits should give proper error */
567                         WARN_ON(ret > 0);
568                         if (ret > 0)
569                                 ret = -EFAULT;
570                         goto out;
571                 }
572
573                 ret = extent_read_full_page(&BTRFS_I(inode)->io_tree, page,
574                                                 btrfs_get_extent,
575                                                 fixup->mirror_num);
576                 wait_on_page_locked(page);
577
578                 corrected = !test_range_bit(&BTRFS_I(inode)->io_tree, offset,
579                                                 end, EXTENT_DAMAGED, 0, NULL);
580                 if (!corrected)
581                         clear_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
582                                                 EXTENT_DAMAGED, GFP_NOFS);
583         }
584
585 out:
586         if (page)
587                 put_page(page);
588         if (inode)
589                 iput(inode);
590
591         if (ret < 0)
592                 return ret;
593
594         if (ret == 0 && corrected) {
595                 /*
596                  * we only need to call readpage for one of the inodes belonging
597                  * to this extent. so make iterate_extent_inodes stop
598                  */
599                 return 1;
600         }
601
602         return -EIO;
603 }
604
605 static void scrub_fixup_nodatasum(struct btrfs_work *work)
606 {
607         int ret;
608         struct scrub_fixup_nodatasum *fixup;
609         struct scrub_ctx *sctx;
610         struct btrfs_trans_handle *trans = NULL;
611         struct btrfs_fs_info *fs_info;
612         struct btrfs_path *path;
613         int uncorrectable = 0;
614
615         fixup = container_of(work, struct scrub_fixup_nodatasum, work);
616         sctx = fixup->sctx;
617         fs_info = fixup->root->fs_info;
618
619         path = btrfs_alloc_path();
620         if (!path) {
621                 spin_lock(&sctx->stat_lock);
622                 ++sctx->stat.malloc_errors;
623                 spin_unlock(&sctx->stat_lock);
624                 uncorrectable = 1;
625                 goto out;
626         }
627
628         trans = btrfs_join_transaction(fixup->root);
629         if (IS_ERR(trans)) {
630                 uncorrectable = 1;
631                 goto out;
632         }
633
634         /*
635          * the idea is to trigger a regular read through the standard path. we
636          * read a page from the (failed) logical address by specifying the
637          * corresponding copynum of the failed sector. thus, that readpage is
638          * expected to fail.
639          * that is the point where on-the-fly error correction will kick in
640          * (once it's finished) and rewrite the failed sector if a good copy
641          * can be found.
642          */
643         ret = iterate_inodes_from_logical(fixup->logical, fixup->root->fs_info,
644                                                 path, scrub_fixup_readpage,
645                                                 fixup);
646         if (ret < 0) {
647                 uncorrectable = 1;
648                 goto out;
649         }
650         WARN_ON(ret != 1);
651
652         spin_lock(&sctx->stat_lock);
653         ++sctx->stat.corrected_errors;
654         spin_unlock(&sctx->stat_lock);
655
656 out:
657         if (trans && !IS_ERR(trans))
658                 btrfs_end_transaction(trans, fixup->root);
659         if (uncorrectable) {
660                 spin_lock(&sctx->stat_lock);
661                 ++sctx->stat.uncorrectable_errors;
662                 spin_unlock(&sctx->stat_lock);
663
664                 printk_ratelimited_in_rcu(KERN_ERR
665                         "btrfs: unable to fixup (nodatasum) error at logical %llu on dev %s\n",
666                         (unsigned long long)fixup->logical,
667                         rcu_str_deref(fixup->dev->name));
668         }
669
670         btrfs_free_path(path);
671         kfree(fixup);
672
673         scrub_pending_trans_workers_dec(sctx);
674 }
675
676 /*
677  * scrub_handle_errored_block gets called when either verification of the
678  * pages failed or the bio failed to read, e.g. with EIO. In the latter
679  * case, this function handles all pages in the bio, even though only one
680  * may be bad.
681  * The goal of this function is to repair the errored block by using the
682  * contents of one of the mirrors.
683  */
684 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check)
685 {
686         struct scrub_ctx *sctx = sblock_to_check->sctx;
687         struct btrfs_device *dev;
688         struct btrfs_fs_info *fs_info;
689         u64 length;
690         u64 logical;
691         u64 generation;
692         unsigned int failed_mirror_index;
693         unsigned int is_metadata;
694         unsigned int have_csum;
695         u8 *csum;
696         struct scrub_block *sblocks_for_recheck; /* holds one for each mirror */
697         struct scrub_block *sblock_bad;
698         int ret;
699         int mirror_index;
700         int page_num;
701         int success;
702         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
703                                       DEFAULT_RATELIMIT_BURST);
704
705         BUG_ON(sblock_to_check->page_count < 1);
706         fs_info = sctx->dev_root->fs_info;
707         length = sblock_to_check->page_count * PAGE_SIZE;
708         logical = sblock_to_check->pagev[0]->logical;
709         generation = sblock_to_check->pagev[0]->generation;
710         BUG_ON(sblock_to_check->pagev[0]->mirror_num < 1);
711         failed_mirror_index = sblock_to_check->pagev[0]->mirror_num - 1;
712         is_metadata = !(sblock_to_check->pagev[0]->flags &
713                         BTRFS_EXTENT_FLAG_DATA);
714         have_csum = sblock_to_check->pagev[0]->have_csum;
715         csum = sblock_to_check->pagev[0]->csum;
716         dev = sblock_to_check->pagev[0]->dev;
717
718         /*
719          * read all mirrors one after the other. This includes to
720          * re-read the extent or metadata block that failed (that was
721          * the cause that this fixup code is called) another time,
722          * page by page this time in order to know which pages
723          * caused I/O errors and which ones are good (for all mirrors).
724          * It is the goal to handle the situation when more than one
725          * mirror contains I/O errors, but the errors do not
726          * overlap, i.e. the data can be repaired by selecting the
727          * pages from those mirrors without I/O error on the
728          * particular pages. One example (with blocks >= 2 * PAGE_SIZE)
729          * would be that mirror #1 has an I/O error on the first page,
730          * the second page is good, and mirror #2 has an I/O error on
731          * the second page, but the first page is good.
732          * Then the first page of the first mirror can be repaired by
733          * taking the first page of the second mirror, and the
734          * second page of the second mirror can be repaired by
735          * copying the contents of the 2nd page of the 1st mirror.
736          * One more note: if the pages of one mirror contain I/O
737          * errors, the checksum cannot be verified. In order to get
738          * the best data for repairing, the first attempt is to find
739          * a mirror without I/O errors and with a validated checksum.
740          * Only if this is not possible, the pages are picked from
741          * mirrors with I/O errors without considering the checksum.
742          * If the latter is the case, at the end, the checksum of the
743          * repaired area is verified in order to correctly maintain
744          * the statistics.
745          */
746
747         sblocks_for_recheck = kzalloc(BTRFS_MAX_MIRRORS *
748                                      sizeof(*sblocks_for_recheck),
749                                      GFP_NOFS);
750         if (!sblocks_for_recheck) {
751                 spin_lock(&sctx->stat_lock);
752                 sctx->stat.malloc_errors++;
753                 sctx->stat.read_errors++;
754                 sctx->stat.uncorrectable_errors++;
755                 spin_unlock(&sctx->stat_lock);
756                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
757                 goto out;
758         }
759
760         /* setup the context, map the logical blocks and alloc the pages */
761         ret = scrub_setup_recheck_block(sctx, fs_info, length,
762                                         logical, sblocks_for_recheck);
763         if (ret) {
764                 spin_lock(&sctx->stat_lock);
765                 sctx->stat.read_errors++;
766                 sctx->stat.uncorrectable_errors++;
767                 spin_unlock(&sctx->stat_lock);
768                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
769                 goto out;
770         }
771         BUG_ON(failed_mirror_index >= BTRFS_MAX_MIRRORS);
772         sblock_bad = sblocks_for_recheck + failed_mirror_index;
773
774         /* build and submit the bios for the failed mirror, check checksums */
775         scrub_recheck_block(fs_info, sblock_bad, is_metadata, have_csum,
776                             csum, generation, sctx->csum_size);
777
778         if (!sblock_bad->header_error && !sblock_bad->checksum_error &&
779             sblock_bad->no_io_error_seen) {
780                 /*
781                  * the error disappeared after reading page by page, or
782                  * the area was part of a huge bio and other parts of the
783                  * bio caused I/O errors, or the block layer merged several
784                  * read requests into one and the error is caused by a
785                  * different bio (usually one of the two latter cases is
786                  * the cause)
787                  */
788                 spin_lock(&sctx->stat_lock);
789                 sctx->stat.unverified_errors++;
790                 spin_unlock(&sctx->stat_lock);
791
792                 goto out;
793         }
794
795         if (!sblock_bad->no_io_error_seen) {
796                 spin_lock(&sctx->stat_lock);
797                 sctx->stat.read_errors++;
798                 spin_unlock(&sctx->stat_lock);
799                 if (__ratelimit(&_rs))
800                         scrub_print_warning("i/o error", sblock_to_check);
801                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
802         } else if (sblock_bad->checksum_error) {
803                 spin_lock(&sctx->stat_lock);
804                 sctx->stat.csum_errors++;
805                 spin_unlock(&sctx->stat_lock);
806                 if (__ratelimit(&_rs))
807                         scrub_print_warning("checksum error", sblock_to_check);
808                 btrfs_dev_stat_inc_and_print(dev,
809                                              BTRFS_DEV_STAT_CORRUPTION_ERRS);
810         } else if (sblock_bad->header_error) {
811                 spin_lock(&sctx->stat_lock);
812                 sctx->stat.verify_errors++;
813                 spin_unlock(&sctx->stat_lock);
814                 if (__ratelimit(&_rs))
815                         scrub_print_warning("checksum/header error",
816                                             sblock_to_check);
817                 if (sblock_bad->generation_error)
818                         btrfs_dev_stat_inc_and_print(dev,
819                                 BTRFS_DEV_STAT_GENERATION_ERRS);
820                 else
821                         btrfs_dev_stat_inc_and_print(dev,
822                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
823         }
824
825         if (sctx->readonly)
826                 goto did_not_correct_error;
827
828         if (!is_metadata && !have_csum) {
829                 struct scrub_fixup_nodatasum *fixup_nodatasum;
830
831                 /*
832                  * !is_metadata and !have_csum, this means that the data
833                  * might not be COW'ed, that it might be modified
834                  * concurrently. The general strategy to work on the
835                  * commit root does not help in the case when COW is not
836                  * used.
837                  */
838                 fixup_nodatasum = kzalloc(sizeof(*fixup_nodatasum), GFP_NOFS);
839                 if (!fixup_nodatasum)
840                         goto did_not_correct_error;
841                 fixup_nodatasum->sctx = sctx;
842                 fixup_nodatasum->dev = dev;
843                 fixup_nodatasum->logical = logical;
844                 fixup_nodatasum->root = fs_info->extent_root;
845                 fixup_nodatasum->mirror_num = failed_mirror_index + 1;
846                 scrub_pending_trans_workers_inc(sctx);
847                 fixup_nodatasum->work.func = scrub_fixup_nodatasum;
848                 btrfs_queue_worker(&fs_info->scrub_workers,
849                                    &fixup_nodatasum->work);
850                 goto out;
851         }
852
853         /*
854          * now build and submit the bios for the other mirrors, check
855          * checksums.
856          * First try to pick the mirror which is completely without I/O
857          * errors and also does not have a checksum error.
858          * If one is found, and if a checksum is present, the full block
859          * that is known to contain an error is rewritten. Afterwards
860          * the block is known to be corrected.
861          * If a mirror is found which is completely correct, and no
862          * checksum is present, only those pages are rewritten that had
863          * an I/O error in the block to be repaired, since it cannot be
864          * determined, which copy of the other pages is better (and it
865          * could happen otherwise that a correct page would be
866          * overwritten by a bad one).
867          */
868         for (mirror_index = 0;
869              mirror_index < BTRFS_MAX_MIRRORS &&
870              sblocks_for_recheck[mirror_index].page_count > 0;
871              mirror_index++) {
872                 struct scrub_block *sblock_other;
873
874                 if (mirror_index == failed_mirror_index)
875                         continue;
876                 sblock_other = sblocks_for_recheck + mirror_index;
877
878                 /* build and submit the bios, check checksums */
879                 scrub_recheck_block(fs_info, sblock_other, is_metadata,
880                                     have_csum, csum, generation,
881                                     sctx->csum_size);
882
883                 if (!sblock_other->header_error &&
884                     !sblock_other->checksum_error &&
885                     sblock_other->no_io_error_seen) {
886                         int force_write = is_metadata || have_csum;
887
888                         ret = scrub_repair_block_from_good_copy(sblock_bad,
889                                                                 sblock_other,
890                                                                 force_write);
891                         if (0 == ret)
892                                 goto corrected_error;
893                 }
894         }
895
896         /*
897          * in case of I/O errors in the area that is supposed to be
898          * repaired, continue by picking good copies of those pages.
899          * Select the good pages from mirrors to rewrite bad pages from
900          * the area to fix. Afterwards verify the checksum of the block
901          * that is supposed to be repaired. This verification step is
902          * only done for the purpose of statistic counting and for the
903          * final scrub report, whether errors remain.
904          * A perfect algorithm could make use of the checksum and try
905          * all possible combinations of pages from the different mirrors
906          * until the checksum verification succeeds. For example, when
907          * the 2nd page of mirror #1 faces I/O errors, and the 2nd page
908          * of mirror #2 is readable but the final checksum test fails,
909          * then the 2nd page of mirror #3 could be tried, whether now
910          * the final checksum succeedes. But this would be a rare
911          * exception and is therefore not implemented. At least it is
912          * avoided that the good copy is overwritten.
913          * A more useful improvement would be to pick the sectors
914          * without I/O error based on sector sizes (512 bytes on legacy
915          * disks) instead of on PAGE_SIZE. Then maybe 512 byte of one
916          * mirror could be repaired by taking 512 byte of a different
917          * mirror, even if other 512 byte sectors in the same PAGE_SIZE
918          * area are unreadable.
919          */
920
921         /* can only fix I/O errors from here on */
922         if (sblock_bad->no_io_error_seen)
923                 goto did_not_correct_error;
924
925         success = 1;
926         for (page_num = 0; page_num < sblock_bad->page_count; page_num++) {
927                 struct scrub_page *page_bad = sblock_bad->pagev[page_num];
928
929                 if (!page_bad->io_error)
930                         continue;
931
932                 for (mirror_index = 0;
933                      mirror_index < BTRFS_MAX_MIRRORS &&
934                      sblocks_for_recheck[mirror_index].page_count > 0;
935                      mirror_index++) {
936                         struct scrub_block *sblock_other = sblocks_for_recheck +
937                                                            mirror_index;
938                         struct scrub_page *page_other = sblock_other->pagev[
939                                                         page_num];
940
941                         if (!page_other->io_error) {
942                                 ret = scrub_repair_page_from_good_copy(
943                                         sblock_bad, sblock_other, page_num, 0);
944                                 if (0 == ret) {
945                                         page_bad->io_error = 0;
946                                         break; /* succeeded for this page */
947                                 }
948                         }
949                 }
950
951                 if (page_bad->io_error) {
952                         /* did not find a mirror to copy the page from */
953                         success = 0;
954                 }
955         }
956
957         if (success) {
958                 if (is_metadata || have_csum) {
959                         /*
960                          * need to verify the checksum now that all
961                          * sectors on disk are repaired (the write
962                          * request for data to be repaired is on its way).
963                          * Just be lazy and use scrub_recheck_block()
964                          * which re-reads the data before the checksum
965                          * is verified, but most likely the data comes out
966                          * of the page cache.
967                          */
968                         scrub_recheck_block(fs_info, sblock_bad,
969                                             is_metadata, have_csum, csum,
970                                             generation, sctx->csum_size);
971                         if (!sblock_bad->header_error &&
972                             !sblock_bad->checksum_error &&
973                             sblock_bad->no_io_error_seen)
974                                 goto corrected_error;
975                         else
976                                 goto did_not_correct_error;
977                 } else {
978 corrected_error:
979                         spin_lock(&sctx->stat_lock);
980                         sctx->stat.corrected_errors++;
981                         spin_unlock(&sctx->stat_lock);
982                         printk_ratelimited_in_rcu(KERN_ERR
983                                 "btrfs: fixed up error at logical %llu on dev %s\n",
984                                 (unsigned long long)logical,
985                                 rcu_str_deref(dev->name));
986                 }
987         } else {
988 did_not_correct_error:
989                 spin_lock(&sctx->stat_lock);
990                 sctx->stat.uncorrectable_errors++;
991                 spin_unlock(&sctx->stat_lock);
992                 printk_ratelimited_in_rcu(KERN_ERR
993                         "btrfs: unable to fixup (regular) error at logical %llu on dev %s\n",
994                         (unsigned long long)logical,
995                         rcu_str_deref(dev->name));
996         }
997
998 out:
999         if (sblocks_for_recheck) {
1000                 for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS;
1001                      mirror_index++) {
1002                         struct scrub_block *sblock = sblocks_for_recheck +
1003                                                      mirror_index;
1004                         int page_index;
1005
1006                         for (page_index = 0; page_index < sblock->page_count;
1007                              page_index++) {
1008                                 sblock->pagev[page_index]->sblock = NULL;
1009                                 scrub_page_put(sblock->pagev[page_index]);
1010                         }
1011                 }
1012                 kfree(sblocks_for_recheck);
1013         }
1014
1015         return 0;
1016 }
1017
1018 static int scrub_setup_recheck_block(struct scrub_ctx *sctx,
1019                                      struct btrfs_fs_info *fs_info,
1020                                      u64 length, u64 logical,
1021                                      struct scrub_block *sblocks_for_recheck)
1022 {
1023         int page_index;
1024         int mirror_index;
1025         int ret;
1026
1027         /*
1028          * note: the two members ref_count and outstanding_pages
1029          * are not used (and not set) in the blocks that are used for
1030          * the recheck procedure
1031          */
1032
1033         page_index = 0;
1034         while (length > 0) {
1035                 u64 sublen = min_t(u64, length, PAGE_SIZE);
1036                 u64 mapped_length = sublen;
1037                 struct btrfs_bio *bbio = NULL;
1038
1039                 /*
1040                  * with a length of PAGE_SIZE, each returned stripe
1041                  * represents one mirror
1042                  */
1043                 ret = btrfs_map_block(fs_info, WRITE, logical, &mapped_length,
1044                                       &bbio, 0);
1045                 if (ret || !bbio || mapped_length < sublen) {
1046                         kfree(bbio);
1047                         return -EIO;
1048                 }
1049
1050                 BUG_ON(page_index >= SCRUB_PAGES_PER_BIO);
1051                 for (mirror_index = 0; mirror_index < (int)bbio->num_stripes;
1052                      mirror_index++) {
1053                         struct scrub_block *sblock;
1054                         struct scrub_page *page;
1055
1056                         if (mirror_index >= BTRFS_MAX_MIRRORS)
1057                                 continue;
1058
1059                         sblock = sblocks_for_recheck + mirror_index;
1060                         sblock->sctx = sctx;
1061                         page = kzalloc(sizeof(*page), GFP_NOFS);
1062                         if (!page) {
1063 leave_nomem:
1064                                 spin_lock(&sctx->stat_lock);
1065                                 sctx->stat.malloc_errors++;
1066                                 spin_unlock(&sctx->stat_lock);
1067                                 kfree(bbio);
1068                                 return -ENOMEM;
1069                         }
1070                         scrub_page_get(page);
1071                         sblock->pagev[page_index] = page;
1072                         page->logical = logical;
1073                         page->physical = bbio->stripes[mirror_index].physical;
1074                         /* for missing devices, dev->bdev is NULL */
1075                         page->dev = bbio->stripes[mirror_index].dev;
1076                         page->mirror_num = mirror_index + 1;
1077                         sblock->page_count++;
1078                         page->page = alloc_page(GFP_NOFS);
1079                         if (!page->page)
1080                                 goto leave_nomem;
1081                 }
1082                 kfree(bbio);
1083                 length -= sublen;
1084                 logical += sublen;
1085                 page_index++;
1086         }
1087
1088         return 0;
1089 }
1090
1091 /*
1092  * this function will check the on disk data for checksum errors, header
1093  * errors and read I/O errors. If any I/O errors happen, the exact pages
1094  * which are errored are marked as being bad. The goal is to enable scrub
1095  * to take those pages that are not errored from all the mirrors so that
1096  * the pages that are errored in the just handled mirror can be repaired.
1097  */
1098 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
1099                                 struct scrub_block *sblock, int is_metadata,
1100                                 int have_csum, u8 *csum, u64 generation,
1101                                 u16 csum_size)
1102 {
1103         int page_num;
1104
1105         sblock->no_io_error_seen = 1;
1106         sblock->header_error = 0;
1107         sblock->checksum_error = 0;
1108
1109         for (page_num = 0; page_num < sblock->page_count; page_num++) {
1110                 struct bio *bio;
1111                 struct scrub_page *page = sblock->pagev[page_num];
1112                 DECLARE_COMPLETION_ONSTACK(complete);
1113
1114                 if (page->dev->bdev == NULL) {
1115                         page->io_error = 1;
1116                         sblock->no_io_error_seen = 0;
1117                         continue;
1118                 }
1119
1120                 WARN_ON(!page->page);
1121                 bio = bio_alloc(GFP_NOFS, 1);
1122                 if (!bio) {
1123                         page->io_error = 1;
1124                         sblock->no_io_error_seen = 0;
1125                         continue;
1126                 }
1127                 bio->bi_bdev = page->dev->bdev;
1128                 bio->bi_sector = page->physical >> 9;
1129                 bio->bi_end_io = scrub_complete_bio_end_io;
1130                 bio->bi_private = &complete;
1131
1132                 bio_add_page(bio, page->page, PAGE_SIZE, 0);
1133                 btrfsic_submit_bio(READ, bio);
1134
1135                 /* this will also unplug the queue */
1136                 wait_for_completion(&complete);
1137
1138                 page->io_error = !test_bit(BIO_UPTODATE, &bio->bi_flags);
1139                 if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
1140                         sblock->no_io_error_seen = 0;
1141                 bio_put(bio);
1142         }
1143
1144         if (sblock->no_io_error_seen)
1145                 scrub_recheck_block_checksum(fs_info, sblock, is_metadata,
1146                                              have_csum, csum, generation,
1147                                              csum_size);
1148
1149         return;
1150 }
1151
1152 static void scrub_recheck_block_checksum(struct btrfs_fs_info *fs_info,
1153                                          struct scrub_block *sblock,
1154                                          int is_metadata, int have_csum,
1155                                          const u8 *csum, u64 generation,
1156                                          u16 csum_size)
1157 {
1158         int page_num;
1159         u8 calculated_csum[BTRFS_CSUM_SIZE];
1160         u32 crc = ~(u32)0;
1161         struct btrfs_root *root = fs_info->extent_root;
1162         void *mapped_buffer;
1163
1164         WARN_ON(!sblock->pagev[0]->page);
1165         if (is_metadata) {
1166                 struct btrfs_header *h;
1167
1168                 mapped_buffer = kmap_atomic(sblock->pagev[0]->page);
1169                 h = (struct btrfs_header *)mapped_buffer;
1170
1171                 if (sblock->pagev[0]->logical != le64_to_cpu(h->bytenr) ||
1172                     memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE) ||
1173                     memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
1174                            BTRFS_UUID_SIZE)) {
1175                         sblock->header_error = 1;
1176                 } else if (generation != le64_to_cpu(h->generation)) {
1177                         sblock->header_error = 1;
1178                         sblock->generation_error = 1;
1179                 }
1180                 csum = h->csum;
1181         } else {
1182                 if (!have_csum)
1183                         return;
1184
1185                 mapped_buffer = kmap_atomic(sblock->pagev[0]->page);
1186         }
1187
1188         for (page_num = 0;;) {
1189                 if (page_num == 0 && is_metadata)
1190                         crc = btrfs_csum_data(root,
1191                                 ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE,
1192                                 crc, PAGE_SIZE - BTRFS_CSUM_SIZE);
1193                 else
1194                         crc = btrfs_csum_data(root, mapped_buffer, crc,
1195                                               PAGE_SIZE);
1196
1197                 kunmap_atomic(mapped_buffer);
1198                 page_num++;
1199                 if (page_num >= sblock->page_count)
1200                         break;
1201                 WARN_ON(!sblock->pagev[page_num]->page);
1202
1203                 mapped_buffer = kmap_atomic(sblock->pagev[page_num]->page);
1204         }
1205
1206         btrfs_csum_final(crc, calculated_csum);
1207         if (memcmp(calculated_csum, csum, csum_size))
1208                 sblock->checksum_error = 1;
1209 }
1210
1211 static void scrub_complete_bio_end_io(struct bio *bio, int err)
1212 {
1213         complete((struct completion *)bio->bi_private);
1214 }
1215
1216 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
1217                                              struct scrub_block *sblock_good,
1218                                              int force_write)
1219 {
1220         int page_num;
1221         int ret = 0;
1222
1223         for (page_num = 0; page_num < sblock_bad->page_count; page_num++) {
1224                 int ret_sub;
1225
1226                 ret_sub = scrub_repair_page_from_good_copy(sblock_bad,
1227                                                            sblock_good,
1228                                                            page_num,
1229                                                            force_write);
1230                 if (ret_sub)
1231                         ret = ret_sub;
1232         }
1233
1234         return ret;
1235 }
1236
1237 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
1238                                             struct scrub_block *sblock_good,
1239                                             int page_num, int force_write)
1240 {
1241         struct scrub_page *page_bad = sblock_bad->pagev[page_num];
1242         struct scrub_page *page_good = sblock_good->pagev[page_num];
1243
1244         BUG_ON(page_bad->page == NULL);
1245         BUG_ON(page_good->page == NULL);
1246         if (force_write || sblock_bad->header_error ||
1247             sblock_bad->checksum_error || page_bad->io_error) {
1248                 struct bio *bio;
1249                 int ret;
1250                 DECLARE_COMPLETION_ONSTACK(complete);
1251
1252                 bio = bio_alloc(GFP_NOFS, 1);
1253                 if (!bio)
1254                         return -EIO;
1255                 bio->bi_bdev = page_bad->dev->bdev;
1256                 bio->bi_sector = page_bad->physical >> 9;
1257                 bio->bi_end_io = scrub_complete_bio_end_io;
1258                 bio->bi_private = &complete;
1259
1260                 ret = bio_add_page(bio, page_good->page, PAGE_SIZE, 0);
1261                 if (PAGE_SIZE != ret) {
1262                         bio_put(bio);
1263                         return -EIO;
1264                 }
1265                 btrfsic_submit_bio(WRITE, bio);
1266
1267                 /* this will also unplug the queue */
1268                 wait_for_completion(&complete);
1269                 if (!bio_flagged(bio, BIO_UPTODATE)) {
1270                         btrfs_dev_stat_inc_and_print(page_bad->dev,
1271                                 BTRFS_DEV_STAT_WRITE_ERRS);
1272                         bio_put(bio);
1273                         return -EIO;
1274                 }
1275                 bio_put(bio);
1276         }
1277
1278         return 0;
1279 }
1280
1281 static void scrub_checksum(struct scrub_block *sblock)
1282 {
1283         u64 flags;
1284         int ret;
1285
1286         WARN_ON(sblock->page_count < 1);
1287         flags = sblock->pagev[0]->flags;
1288         ret = 0;
1289         if (flags & BTRFS_EXTENT_FLAG_DATA)
1290                 ret = scrub_checksum_data(sblock);
1291         else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1292                 ret = scrub_checksum_tree_block(sblock);
1293         else if (flags & BTRFS_EXTENT_FLAG_SUPER)
1294                 (void)scrub_checksum_super(sblock);
1295         else
1296                 WARN_ON(1);
1297         if (ret)
1298                 scrub_handle_errored_block(sblock);
1299 }
1300
1301 static int scrub_checksum_data(struct scrub_block *sblock)
1302 {
1303         struct scrub_ctx *sctx = sblock->sctx;
1304         u8 csum[BTRFS_CSUM_SIZE];
1305         u8 *on_disk_csum;
1306         struct page *page;
1307         void *buffer;
1308         u32 crc = ~(u32)0;
1309         int fail = 0;
1310         struct btrfs_root *root = sctx->dev_root;
1311         u64 len;
1312         int index;
1313
1314         BUG_ON(sblock->page_count < 1);
1315         if (!sblock->pagev[0]->have_csum)
1316                 return 0;
1317
1318         on_disk_csum = sblock->pagev[0]->csum;
1319         page = sblock->pagev[0]->page;
1320         buffer = kmap_atomic(page);
1321
1322         len = sctx->sectorsize;
1323         index = 0;
1324         for (;;) {
1325                 u64 l = min_t(u64, len, PAGE_SIZE);
1326
1327                 crc = btrfs_csum_data(root, buffer, crc, l);
1328                 kunmap_atomic(buffer);
1329                 len -= l;
1330                 if (len == 0)
1331                         break;
1332                 index++;
1333                 BUG_ON(index >= sblock->page_count);
1334                 BUG_ON(!sblock->pagev[index]->page);
1335                 page = sblock->pagev[index]->page;
1336                 buffer = kmap_atomic(page);
1337         }
1338
1339         btrfs_csum_final(crc, csum);
1340         if (memcmp(csum, on_disk_csum, sctx->csum_size))
1341                 fail = 1;
1342
1343         return fail;
1344 }
1345
1346 static int scrub_checksum_tree_block(struct scrub_block *sblock)
1347 {
1348         struct scrub_ctx *sctx = sblock->sctx;
1349         struct btrfs_header *h;
1350         struct btrfs_root *root = sctx->dev_root;
1351         struct btrfs_fs_info *fs_info = root->fs_info;
1352         u8 calculated_csum[BTRFS_CSUM_SIZE];
1353         u8 on_disk_csum[BTRFS_CSUM_SIZE];
1354         struct page *page;
1355         void *mapped_buffer;
1356         u64 mapped_size;
1357         void *p;
1358         u32 crc = ~(u32)0;
1359         int fail = 0;
1360         int crc_fail = 0;
1361         u64 len;
1362         int index;
1363
1364         BUG_ON(sblock->page_count < 1);
1365         page = sblock->pagev[0]->page;
1366         mapped_buffer = kmap_atomic(page);
1367         h = (struct btrfs_header *)mapped_buffer;
1368         memcpy(on_disk_csum, h->csum, sctx->csum_size);
1369
1370         /*
1371          * we don't use the getter functions here, as we
1372          * a) don't have an extent buffer and
1373          * b) the page is already kmapped
1374          */
1375
1376         if (sblock->pagev[0]->logical != le64_to_cpu(h->bytenr))
1377                 ++fail;
1378
1379         if (sblock->pagev[0]->generation != le64_to_cpu(h->generation))
1380                 ++fail;
1381
1382         if (memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
1383                 ++fail;
1384
1385         if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
1386                    BTRFS_UUID_SIZE))
1387                 ++fail;
1388
1389         BUG_ON(sctx->nodesize != sctx->leafsize);
1390         len = sctx->nodesize - BTRFS_CSUM_SIZE;
1391         mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
1392         p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
1393         index = 0;
1394         for (;;) {
1395                 u64 l = min_t(u64, len, mapped_size);
1396
1397                 crc = btrfs_csum_data(root, p, crc, l);
1398                 kunmap_atomic(mapped_buffer);
1399                 len -= l;
1400                 if (len == 0)
1401                         break;
1402                 index++;
1403                 BUG_ON(index >= sblock->page_count);
1404                 BUG_ON(!sblock->pagev[index]->page);
1405                 page = sblock->pagev[index]->page;
1406                 mapped_buffer = kmap_atomic(page);
1407                 mapped_size = PAGE_SIZE;
1408                 p = mapped_buffer;
1409         }
1410
1411         btrfs_csum_final(crc, calculated_csum);
1412         if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
1413                 ++crc_fail;
1414
1415         return fail || crc_fail;
1416 }
1417
1418 static int scrub_checksum_super(struct scrub_block *sblock)
1419 {
1420         struct btrfs_super_block *s;
1421         struct scrub_ctx *sctx = sblock->sctx;
1422         struct btrfs_root *root = sctx->dev_root;
1423         struct btrfs_fs_info *fs_info = root->fs_info;
1424         u8 calculated_csum[BTRFS_CSUM_SIZE];
1425         u8 on_disk_csum[BTRFS_CSUM_SIZE];
1426         struct page *page;
1427         void *mapped_buffer;
1428         u64 mapped_size;
1429         void *p;
1430         u32 crc = ~(u32)0;
1431         int fail_gen = 0;
1432         int fail_cor = 0;
1433         u64 len;
1434         int index;
1435
1436         BUG_ON(sblock->page_count < 1);
1437         page = sblock->pagev[0]->page;
1438         mapped_buffer = kmap_atomic(page);
1439         s = (struct btrfs_super_block *)mapped_buffer;
1440         memcpy(on_disk_csum, s->csum, sctx->csum_size);
1441
1442         if (sblock->pagev[0]->logical != le64_to_cpu(s->bytenr))
1443                 ++fail_cor;
1444
1445         if (sblock->pagev[0]->generation != le64_to_cpu(s->generation))
1446                 ++fail_gen;
1447
1448         if (memcmp(s->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
1449                 ++fail_cor;
1450
1451         len = BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE;
1452         mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
1453         p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
1454         index = 0;
1455         for (;;) {
1456                 u64 l = min_t(u64, len, mapped_size);
1457
1458                 crc = btrfs_csum_data(root, p, crc, l);
1459                 kunmap_atomic(mapped_buffer);
1460                 len -= l;
1461                 if (len == 0)
1462                         break;
1463                 index++;
1464                 BUG_ON(index >= sblock->page_count);
1465                 BUG_ON(!sblock->pagev[index]->page);
1466                 page = sblock->pagev[index]->page;
1467                 mapped_buffer = kmap_atomic(page);
1468                 mapped_size = PAGE_SIZE;
1469                 p = mapped_buffer;
1470         }
1471
1472         btrfs_csum_final(crc, calculated_csum);
1473         if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
1474                 ++fail_cor;
1475
1476         if (fail_cor + fail_gen) {
1477                 /*
1478                  * if we find an error in a super block, we just report it.
1479                  * They will get written with the next transaction commit
1480                  * anyway
1481                  */
1482                 spin_lock(&sctx->stat_lock);
1483                 ++sctx->stat.super_errors;
1484                 spin_unlock(&sctx->stat_lock);
1485                 if (fail_cor)
1486                         btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
1487                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
1488                 else
1489                         btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
1490                                 BTRFS_DEV_STAT_GENERATION_ERRS);
1491         }
1492
1493         return fail_cor + fail_gen;
1494 }
1495
1496 static void scrub_block_get(struct scrub_block *sblock)
1497 {
1498         atomic_inc(&sblock->ref_count);
1499 }
1500
1501 static void scrub_block_put(struct scrub_block *sblock)
1502 {
1503         if (atomic_dec_and_test(&sblock->ref_count)) {
1504                 int i;
1505
1506                 for (i = 0; i < sblock->page_count; i++)
1507                         scrub_page_put(sblock->pagev[i]);
1508                 kfree(sblock);
1509         }
1510 }
1511
1512 static void scrub_page_get(struct scrub_page *spage)
1513 {
1514         atomic_inc(&spage->ref_count);
1515 }
1516
1517 static void scrub_page_put(struct scrub_page *spage)
1518 {
1519         if (atomic_dec_and_test(&spage->ref_count)) {
1520                 if (spage->page)
1521                         __free_page(spage->page);
1522                 kfree(spage);
1523         }
1524 }
1525
1526 static void scrub_submit(struct scrub_ctx *sctx)
1527 {
1528         struct scrub_bio *sbio;
1529
1530         if (sctx->curr == -1)
1531                 return;
1532
1533         sbio = sctx->bios[sctx->curr];
1534         sctx->curr = -1;
1535         scrub_pending_bio_inc(sctx);
1536
1537         btrfsic_submit_bio(READ, sbio->bio);
1538 }
1539
1540 static int scrub_add_page_to_bio(struct scrub_ctx *sctx,
1541                                  struct scrub_page *spage)
1542 {
1543         struct scrub_block *sblock = spage->sblock;
1544         struct scrub_bio *sbio;
1545         int ret;
1546
1547 again:
1548         /*
1549          * grab a fresh bio or wait for one to become available
1550          */
1551         while (sctx->curr == -1) {
1552                 spin_lock(&sctx->list_lock);
1553                 sctx->curr = sctx->first_free;
1554                 if (sctx->curr != -1) {
1555                         sctx->first_free = sctx->bios[sctx->curr]->next_free;
1556                         sctx->bios[sctx->curr]->next_free = -1;
1557                         sctx->bios[sctx->curr]->page_count = 0;
1558                         spin_unlock(&sctx->list_lock);
1559                 } else {
1560                         spin_unlock(&sctx->list_lock);
1561                         wait_event(sctx->list_wait, sctx->first_free != -1);
1562                 }
1563         }
1564         sbio = sctx->bios[sctx->curr];
1565         if (sbio->page_count == 0) {
1566                 struct bio *bio;
1567
1568                 sbio->physical = spage->physical;
1569                 sbio->logical = spage->logical;
1570                 sbio->dev = spage->dev;
1571                 bio = sbio->bio;
1572                 if (!bio) {
1573                         bio = bio_alloc(GFP_NOFS, sctx->pages_per_bio);
1574                         if (!bio)
1575                                 return -ENOMEM;
1576                         sbio->bio = bio;
1577                 }
1578
1579                 bio->bi_private = sbio;
1580                 bio->bi_end_io = scrub_bio_end_io;
1581                 bio->bi_bdev = sbio->dev->bdev;
1582                 bio->bi_sector = sbio->physical >> 9;
1583                 sbio->err = 0;
1584         } else if (sbio->physical + sbio->page_count * PAGE_SIZE !=
1585                    spage->physical ||
1586                    sbio->logical + sbio->page_count * PAGE_SIZE !=
1587                    spage->logical ||
1588                    sbio->dev != spage->dev) {
1589                 scrub_submit(sctx);
1590                 goto again;
1591         }
1592
1593         sbio->pagev[sbio->page_count] = spage;
1594         ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0);
1595         if (ret != PAGE_SIZE) {
1596                 if (sbio->page_count < 1) {
1597                         bio_put(sbio->bio);
1598                         sbio->bio = NULL;
1599                         return -EIO;
1600                 }
1601                 scrub_submit(sctx);
1602                 goto again;
1603         }
1604
1605         scrub_block_get(sblock); /* one for the added page */
1606         atomic_inc(&sblock->outstanding_pages);
1607         sbio->page_count++;
1608         if (sbio->page_count == sctx->pages_per_bio)
1609                 scrub_submit(sctx);
1610
1611         return 0;
1612 }
1613
1614 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
1615                        u64 physical, struct btrfs_device *dev, u64 flags,
1616                        u64 gen, int mirror_num, u8 *csum, int force)
1617 {
1618         struct scrub_block *sblock;
1619         int index;
1620
1621         sblock = kzalloc(sizeof(*sblock), GFP_NOFS);
1622         if (!sblock) {
1623                 spin_lock(&sctx->stat_lock);
1624                 sctx->stat.malloc_errors++;
1625                 spin_unlock(&sctx->stat_lock);
1626                 return -ENOMEM;
1627         }
1628
1629         /* one ref inside this function, plus one for each page added to
1630          * a bio later on */
1631         atomic_set(&sblock->ref_count, 1);
1632         sblock->sctx = sctx;
1633         sblock->no_io_error_seen = 1;
1634
1635         for (index = 0; len > 0; index++) {
1636                 struct scrub_page *spage;
1637                 u64 l = min_t(u64, len, PAGE_SIZE);
1638
1639                 spage = kzalloc(sizeof(*spage), GFP_NOFS);
1640                 if (!spage) {
1641 leave_nomem:
1642                         spin_lock(&sctx->stat_lock);
1643                         sctx->stat.malloc_errors++;
1644                         spin_unlock(&sctx->stat_lock);
1645                         scrub_block_put(sblock);
1646                         return -ENOMEM;
1647                 }
1648                 BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK);
1649                 scrub_page_get(spage);
1650                 sblock->pagev[index] = spage;
1651                 spage->sblock = sblock;
1652                 spage->dev = dev;
1653                 spage->flags = flags;
1654                 spage->generation = gen;
1655                 spage->logical = logical;
1656                 spage->physical = physical;
1657                 spage->mirror_num = mirror_num;
1658                 if (csum) {
1659                         spage->have_csum = 1;
1660                         memcpy(spage->csum, csum, sctx->csum_size);
1661                 } else {
1662                         spage->have_csum = 0;
1663                 }
1664                 sblock->page_count++;
1665                 spage->page = alloc_page(GFP_NOFS);
1666                 if (!spage->page)
1667                         goto leave_nomem;
1668                 len -= l;
1669                 logical += l;
1670                 physical += l;
1671         }
1672
1673         WARN_ON(sblock->page_count == 0);
1674         for (index = 0; index < sblock->page_count; index++) {
1675                 struct scrub_page *spage = sblock->pagev[index];
1676                 int ret;
1677
1678                 ret = scrub_add_page_to_bio(sctx, spage);
1679                 if (ret) {
1680                         scrub_block_put(sblock);
1681                         return ret;
1682                 }
1683         }
1684
1685         if (force)
1686                 scrub_submit(sctx);
1687
1688         /* last one frees, either here or in bio completion for last page */
1689         scrub_block_put(sblock);
1690         return 0;
1691 }
1692
1693 static void scrub_bio_end_io(struct bio *bio, int err)
1694 {
1695         struct scrub_bio *sbio = bio->bi_private;
1696         struct btrfs_fs_info *fs_info = sbio->dev->dev_root->fs_info;
1697
1698         sbio->err = err;
1699         sbio->bio = bio;
1700
1701         btrfs_queue_worker(&fs_info->scrub_workers, &sbio->work);
1702 }
1703
1704 static void scrub_bio_end_io_worker(struct btrfs_work *work)
1705 {
1706         struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
1707         struct scrub_ctx *sctx = sbio->sctx;
1708         int i;
1709
1710         BUG_ON(sbio->page_count > SCRUB_PAGES_PER_BIO);
1711         if (sbio->err) {
1712                 for (i = 0; i < sbio->page_count; i++) {
1713                         struct scrub_page *spage = sbio->pagev[i];
1714
1715                         spage->io_error = 1;
1716                         spage->sblock->no_io_error_seen = 0;
1717                 }
1718         }
1719
1720         /* now complete the scrub_block items that have all pages completed */
1721         for (i = 0; i < sbio->page_count; i++) {
1722                 struct scrub_page *spage = sbio->pagev[i];
1723                 struct scrub_block *sblock = spage->sblock;
1724
1725                 if (atomic_dec_and_test(&sblock->outstanding_pages))
1726                         scrub_block_complete(sblock);
1727                 scrub_block_put(sblock);
1728         }
1729
1730         bio_put(sbio->bio);
1731         sbio->bio = NULL;
1732         spin_lock(&sctx->list_lock);
1733         sbio->next_free = sctx->first_free;
1734         sctx->first_free = sbio->index;
1735         spin_unlock(&sctx->list_lock);
1736         scrub_pending_bio_dec(sctx);
1737 }
1738
1739 static void scrub_block_complete(struct scrub_block *sblock)
1740 {
1741         if (!sblock->no_io_error_seen)
1742                 scrub_handle_errored_block(sblock);
1743         else
1744                 scrub_checksum(sblock);
1745 }
1746
1747 static int scrub_find_csum(struct scrub_ctx *sctx, u64 logical, u64 len,
1748                            u8 *csum)
1749 {
1750         struct btrfs_ordered_sum *sum = NULL;
1751         int ret = 0;
1752         unsigned long i;
1753         unsigned long num_sectors;
1754
1755         while (!list_empty(&sctx->csum_list)) {
1756                 sum = list_first_entry(&sctx->csum_list,
1757                                        struct btrfs_ordered_sum, list);
1758                 if (sum->bytenr > logical)
1759                         return 0;
1760                 if (sum->bytenr + sum->len > logical)
1761                         break;
1762
1763                 ++sctx->stat.csum_discards;
1764                 list_del(&sum->list);
1765                 kfree(sum);
1766                 sum = NULL;
1767         }
1768         if (!sum)
1769                 return 0;
1770
1771         num_sectors = sum->len / sctx->sectorsize;
1772         for (i = 0; i < num_sectors; ++i) {
1773                 if (sum->sums[i].bytenr == logical) {
1774                         memcpy(csum, &sum->sums[i].sum, sctx->csum_size);
1775                         ret = 1;
1776                         break;
1777                 }
1778         }
1779         if (ret && i == num_sectors - 1) {
1780                 list_del(&sum->list);
1781                 kfree(sum);
1782         }
1783         return ret;
1784 }
1785
1786 /* scrub extent tries to collect up to 64 kB for each bio */
1787 static int scrub_extent(struct scrub_ctx *sctx, u64 logical, u64 len,
1788                         u64 physical, struct btrfs_device *dev, u64 flags,
1789                         u64 gen, int mirror_num)
1790 {
1791         int ret;
1792         u8 csum[BTRFS_CSUM_SIZE];
1793         u32 blocksize;
1794
1795         if (flags & BTRFS_EXTENT_FLAG_DATA) {
1796                 blocksize = sctx->sectorsize;
1797                 spin_lock(&sctx->stat_lock);
1798                 sctx->stat.data_extents_scrubbed++;
1799                 sctx->stat.data_bytes_scrubbed += len;
1800                 spin_unlock(&sctx->stat_lock);
1801         } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1802                 BUG_ON(sctx->nodesize != sctx->leafsize);
1803                 blocksize = sctx->nodesize;
1804                 spin_lock(&sctx->stat_lock);
1805                 sctx->stat.tree_extents_scrubbed++;
1806                 sctx->stat.tree_bytes_scrubbed += len;
1807                 spin_unlock(&sctx->stat_lock);
1808         } else {
1809                 blocksize = sctx->sectorsize;
1810                 BUG_ON(1);
1811         }
1812
1813         while (len) {
1814                 u64 l = min_t(u64, len, blocksize);
1815                 int have_csum = 0;
1816
1817                 if (flags & BTRFS_EXTENT_FLAG_DATA) {
1818                         /* push csums to sbio */
1819                         have_csum = scrub_find_csum(sctx, logical, l, csum);
1820                         if (have_csum == 0)
1821                                 ++sctx->stat.no_csum;
1822                 }
1823                 ret = scrub_pages(sctx, logical, l, physical, dev, flags, gen,
1824                                   mirror_num, have_csum ? csum : NULL, 0);
1825                 if (ret)
1826                         return ret;
1827                 len -= l;
1828                 logical += l;
1829                 physical += l;
1830         }
1831         return 0;
1832 }
1833
1834 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
1835                                            struct map_lookup *map,
1836                                            struct btrfs_device *scrub_dev,
1837                                            int num, u64 base, u64 length)
1838 {
1839         struct btrfs_path *path;
1840         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
1841         struct btrfs_root *root = fs_info->extent_root;
1842         struct btrfs_root *csum_root = fs_info->csum_root;
1843         struct btrfs_extent_item *extent;
1844         struct blk_plug plug;
1845         u64 flags;
1846         int ret;
1847         int slot;
1848         int i;
1849         u64 nstripes;
1850         struct extent_buffer *l;
1851         struct btrfs_key key;
1852         u64 physical;
1853         u64 logical;
1854         u64 generation;
1855         int mirror_num;
1856         struct reada_control *reada1;
1857         struct reada_control *reada2;
1858         struct btrfs_key key_start;
1859         struct btrfs_key key_end;
1860         u64 increment = map->stripe_len;
1861         u64 offset;
1862
1863         nstripes = length;
1864         offset = 0;
1865         do_div(nstripes, map->stripe_len);
1866         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1867                 offset = map->stripe_len * num;
1868                 increment = map->stripe_len * map->num_stripes;
1869                 mirror_num = 1;
1870         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1871                 int factor = map->num_stripes / map->sub_stripes;
1872                 offset = map->stripe_len * (num / map->sub_stripes);
1873                 increment = map->stripe_len * factor;
1874                 mirror_num = num % map->sub_stripes + 1;
1875         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1876                 increment = map->stripe_len;
1877                 mirror_num = num % map->num_stripes + 1;
1878         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1879                 increment = map->stripe_len;
1880                 mirror_num = num % map->num_stripes + 1;
1881         } else {
1882                 increment = map->stripe_len;
1883                 mirror_num = 1;
1884         }
1885
1886         path = btrfs_alloc_path();
1887         if (!path)
1888                 return -ENOMEM;
1889
1890         /*
1891          * work on commit root. The related disk blocks are static as
1892          * long as COW is applied. This means, it is save to rewrite
1893          * them to repair disk errors without any race conditions
1894          */
1895         path->search_commit_root = 1;
1896         path->skip_locking = 1;
1897
1898         /*
1899          * trigger the readahead for extent tree csum tree and wait for
1900          * completion. During readahead, the scrub is officially paused
1901          * to not hold off transaction commits
1902          */
1903         logical = base + offset;
1904
1905         wait_event(sctx->list_wait,
1906                    atomic_read(&sctx->bios_in_flight) == 0);
1907         atomic_inc(&fs_info->scrubs_paused);
1908         wake_up(&fs_info->scrub_pause_wait);
1909
1910         /* FIXME it might be better to start readahead at commit root */
1911         key_start.objectid = logical;
1912         key_start.type = BTRFS_EXTENT_ITEM_KEY;
1913         key_start.offset = (u64)0;
1914         key_end.objectid = base + offset + nstripes * increment;
1915         key_end.type = BTRFS_EXTENT_ITEM_KEY;
1916         key_end.offset = (u64)0;
1917         reada1 = btrfs_reada_add(root, &key_start, &key_end);
1918
1919         key_start.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1920         key_start.type = BTRFS_EXTENT_CSUM_KEY;
1921         key_start.offset = logical;
1922         key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1923         key_end.type = BTRFS_EXTENT_CSUM_KEY;
1924         key_end.offset = base + offset + nstripes * increment;
1925         reada2 = btrfs_reada_add(csum_root, &key_start, &key_end);
1926
1927         if (!IS_ERR(reada1))
1928                 btrfs_reada_wait(reada1);
1929         if (!IS_ERR(reada2))
1930                 btrfs_reada_wait(reada2);
1931
1932         mutex_lock(&fs_info->scrub_lock);
1933         while (atomic_read(&fs_info->scrub_pause_req)) {
1934                 mutex_unlock(&fs_info->scrub_lock);
1935                 wait_event(fs_info->scrub_pause_wait,
1936                    atomic_read(&fs_info->scrub_pause_req) == 0);
1937                 mutex_lock(&fs_info->scrub_lock);
1938         }
1939         atomic_dec(&fs_info->scrubs_paused);
1940         mutex_unlock(&fs_info->scrub_lock);
1941         wake_up(&fs_info->scrub_pause_wait);
1942
1943         /*
1944          * collect all data csums for the stripe to avoid seeking during
1945          * the scrub. This might currently (crc32) end up to be about 1MB
1946          */
1947         blk_start_plug(&plug);
1948
1949         /*
1950          * now find all extents for each stripe and scrub them
1951          */
1952         logical = base + offset;
1953         physical = map->stripes[num].physical;
1954         ret = 0;
1955         for (i = 0; i < nstripes; ++i) {
1956                 /*
1957                  * canceled?
1958                  */
1959                 if (atomic_read(&fs_info->scrub_cancel_req) ||
1960                     atomic_read(&sctx->cancel_req)) {
1961                         ret = -ECANCELED;
1962                         goto out;
1963                 }
1964                 /*
1965                  * check to see if we have to pause
1966                  */
1967                 if (atomic_read(&fs_info->scrub_pause_req)) {
1968                         /* push queued extents */
1969                         scrub_submit(sctx);
1970                         wait_event(sctx->list_wait,
1971                                    atomic_read(&sctx->bios_in_flight) == 0);
1972                         atomic_inc(&fs_info->scrubs_paused);
1973                         wake_up(&fs_info->scrub_pause_wait);
1974                         mutex_lock(&fs_info->scrub_lock);
1975                         while (atomic_read(&fs_info->scrub_pause_req)) {
1976                                 mutex_unlock(&fs_info->scrub_lock);
1977                                 wait_event(fs_info->scrub_pause_wait,
1978                                    atomic_read(&fs_info->scrub_pause_req) == 0);
1979                                 mutex_lock(&fs_info->scrub_lock);
1980                         }
1981                         atomic_dec(&fs_info->scrubs_paused);
1982                         mutex_unlock(&fs_info->scrub_lock);
1983                         wake_up(&fs_info->scrub_pause_wait);
1984                 }
1985
1986                 ret = btrfs_lookup_csums_range(csum_root, logical,
1987                                                logical + map->stripe_len - 1,
1988                                                &sctx->csum_list, 1);
1989                 if (ret)
1990                         goto out;
1991
1992                 key.objectid = logical;
1993                 key.type = BTRFS_EXTENT_ITEM_KEY;
1994                 key.offset = (u64)0;
1995
1996                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1997                 if (ret < 0)
1998                         goto out;
1999                 if (ret > 0) {
2000                         ret = btrfs_previous_item(root, path, 0,
2001                                                   BTRFS_EXTENT_ITEM_KEY);
2002                         if (ret < 0)
2003                                 goto out;
2004                         if (ret > 0) {
2005                                 /* there's no smaller item, so stick with the
2006                                  * larger one */
2007                                 btrfs_release_path(path);
2008                                 ret = btrfs_search_slot(NULL, root, &key,
2009                                                         path, 0, 0);
2010                                 if (ret < 0)
2011                                         goto out;
2012                         }
2013                 }
2014
2015                 while (1) {
2016                         l = path->nodes[0];
2017                         slot = path->slots[0];
2018                         if (slot >= btrfs_header_nritems(l)) {
2019                                 ret = btrfs_next_leaf(root, path);
2020                                 if (ret == 0)
2021                                         continue;
2022                                 if (ret < 0)
2023                                         goto out;
2024
2025                                 break;
2026                         }
2027                         btrfs_item_key_to_cpu(l, &key, slot);
2028
2029                         if (key.objectid + key.offset <= logical)
2030                                 goto next;
2031
2032                         if (key.objectid >= logical + map->stripe_len)
2033                                 break;
2034
2035                         if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY)
2036                                 goto next;
2037
2038                         extent = btrfs_item_ptr(l, slot,
2039                                                 struct btrfs_extent_item);
2040                         flags = btrfs_extent_flags(l, extent);
2041                         generation = btrfs_extent_generation(l, extent);
2042
2043                         if (key.objectid < logical &&
2044                             (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
2045                                 printk(KERN_ERR
2046                                        "btrfs scrub: tree block %llu spanning "
2047                                        "stripes, ignored. logical=%llu\n",
2048                                        (unsigned long long)key.objectid,
2049                                        (unsigned long long)logical);
2050                                 goto next;
2051                         }
2052
2053                         /*
2054                          * trim extent to this stripe
2055                          */
2056                         if (key.objectid < logical) {
2057                                 key.offset -= logical - key.objectid;
2058                                 key.objectid = logical;
2059                         }
2060                         if (key.objectid + key.offset >
2061                             logical + map->stripe_len) {
2062                                 key.offset = logical + map->stripe_len -
2063                                              key.objectid;
2064                         }
2065
2066                         ret = scrub_extent(sctx, key.objectid, key.offset,
2067                                            key.objectid - logical + physical,
2068                                            scrub_dev, flags, generation,
2069                                            mirror_num);
2070                         if (ret)
2071                                 goto out;
2072
2073 next:
2074                         path->slots[0]++;
2075                 }
2076                 btrfs_release_path(path);
2077                 logical += increment;
2078                 physical += map->stripe_len;
2079                 spin_lock(&sctx->stat_lock);
2080                 sctx->stat.last_physical = physical;
2081                 spin_unlock(&sctx->stat_lock);
2082         }
2083         /* push queued extents */
2084         scrub_submit(sctx);
2085
2086 out:
2087         blk_finish_plug(&plug);
2088         btrfs_free_path(path);
2089         return ret < 0 ? ret : 0;
2090 }
2091
2092 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx,
2093                                           struct btrfs_device *scrub_dev,
2094                                           u64 chunk_tree, u64 chunk_objectid,
2095                                           u64 chunk_offset, u64 length,
2096                                           u64 dev_offset)
2097 {
2098         struct btrfs_mapping_tree *map_tree =
2099                 &sctx->dev_root->fs_info->mapping_tree;
2100         struct map_lookup *map;
2101         struct extent_map *em;
2102         int i;
2103         int ret = -EINVAL;
2104
2105         read_lock(&map_tree->map_tree.lock);
2106         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
2107         read_unlock(&map_tree->map_tree.lock);
2108
2109         if (!em)
2110                 return -EINVAL;
2111
2112         map = (struct map_lookup *)em->bdev;
2113         if (em->start != chunk_offset)
2114                 goto out;
2115
2116         if (em->len < length)
2117                 goto out;
2118
2119         for (i = 0; i < map->num_stripes; ++i) {
2120                 if (map->stripes[i].dev->bdev == scrub_dev->bdev &&
2121                     map->stripes[i].physical == dev_offset) {
2122                         ret = scrub_stripe(sctx, map, scrub_dev, i,
2123                                            chunk_offset, length);
2124                         if (ret)
2125                                 goto out;
2126                 }
2127         }
2128 out:
2129         free_extent_map(em);
2130
2131         return ret;
2132 }
2133
2134 static noinline_for_stack
2135 int scrub_enumerate_chunks(struct scrub_ctx *sctx,
2136                            struct btrfs_device *scrub_dev, u64 start, u64 end)
2137 {
2138         struct btrfs_dev_extent *dev_extent = NULL;
2139         struct btrfs_path *path;
2140         struct btrfs_root *root = sctx->dev_root;
2141         struct btrfs_fs_info *fs_info = root->fs_info;
2142         u64 length;
2143         u64 chunk_tree;
2144         u64 chunk_objectid;
2145         u64 chunk_offset;
2146         int ret;
2147         int slot;
2148         struct extent_buffer *l;
2149         struct btrfs_key key;
2150         struct btrfs_key found_key;
2151         struct btrfs_block_group_cache *cache;
2152
2153         path = btrfs_alloc_path();
2154         if (!path)
2155                 return -ENOMEM;
2156
2157         path->reada = 2;
2158         path->search_commit_root = 1;
2159         path->skip_locking = 1;
2160
2161         key.objectid = scrub_dev->devid;
2162         key.offset = 0ull;
2163         key.type = BTRFS_DEV_EXTENT_KEY;
2164
2165         while (1) {
2166                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2167                 if (ret < 0)
2168                         break;
2169                 if (ret > 0) {
2170                         if (path->slots[0] >=
2171                             btrfs_header_nritems(path->nodes[0])) {
2172                                 ret = btrfs_next_leaf(root, path);
2173                                 if (ret)
2174                                         break;
2175                         }
2176                 }
2177
2178                 l = path->nodes[0];
2179                 slot = path->slots[0];
2180
2181                 btrfs_item_key_to_cpu(l, &found_key, slot);
2182
2183                 if (found_key.objectid != scrub_dev->devid)
2184                         break;
2185
2186                 if (btrfs_key_type(&found_key) != BTRFS_DEV_EXTENT_KEY)
2187                         break;
2188
2189                 if (found_key.offset >= end)
2190                         break;
2191
2192                 if (found_key.offset < key.offset)
2193                         break;
2194
2195                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2196                 length = btrfs_dev_extent_length(l, dev_extent);
2197
2198                 if (found_key.offset + length <= start) {
2199                         key.offset = found_key.offset + length;
2200                         btrfs_release_path(path);
2201                         continue;
2202                 }
2203
2204                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2205                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
2206                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2207
2208                 /*
2209                  * get a reference on the corresponding block group to prevent
2210                  * the chunk from going away while we scrub it
2211                  */
2212                 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2213                 if (!cache) {
2214                         ret = -ENOENT;
2215                         break;
2216                 }
2217                 ret = scrub_chunk(sctx, scrub_dev, chunk_tree, chunk_objectid,
2218                                   chunk_offset, length, found_key.offset);
2219                 btrfs_put_block_group(cache);
2220                 if (ret)
2221                         break;
2222
2223                 key.offset = found_key.offset + length;
2224                 btrfs_release_path(path);
2225         }
2226
2227         btrfs_free_path(path);
2228
2229         /*
2230          * ret can still be 1 from search_slot or next_leaf,
2231          * that's not an error
2232          */
2233         return ret < 0 ? ret : 0;
2234 }
2235
2236 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx,
2237                                            struct btrfs_device *scrub_dev)
2238 {
2239         int     i;
2240         u64     bytenr;
2241         u64     gen;
2242         int     ret;
2243         struct btrfs_root *root = sctx->dev_root;
2244
2245         if (root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)
2246                 return -EIO;
2247
2248         gen = root->fs_info->last_trans_committed;
2249
2250         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2251                 bytenr = btrfs_sb_offset(i);
2252                 if (bytenr + BTRFS_SUPER_INFO_SIZE > scrub_dev->total_bytes)
2253                         break;
2254
2255                 ret = scrub_pages(sctx, bytenr, BTRFS_SUPER_INFO_SIZE, bytenr,
2256                                   scrub_dev, BTRFS_EXTENT_FLAG_SUPER, gen, i,
2257                                   NULL, 1);
2258                 if (ret)
2259                         return ret;
2260         }
2261         wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
2262
2263         return 0;
2264 }
2265
2266 /*
2267  * get a reference count on fs_info->scrub_workers. start worker if necessary
2268  */
2269 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info)
2270 {
2271         int ret = 0;
2272
2273         mutex_lock(&fs_info->scrub_lock);
2274         if (fs_info->scrub_workers_refcnt == 0) {
2275                 btrfs_init_workers(&fs_info->scrub_workers, "scrub",
2276                            fs_info->thread_pool_size, &fs_info->generic_worker);
2277                 fs_info->scrub_workers.idle_thresh = 4;
2278                 ret = btrfs_start_workers(&fs_info->scrub_workers);
2279                 if (ret)
2280                         goto out;
2281         }
2282         ++fs_info->scrub_workers_refcnt;
2283 out:
2284         mutex_unlock(&fs_info->scrub_lock);
2285
2286         return ret;
2287 }
2288
2289 static noinline_for_stack void scrub_workers_put(struct btrfs_fs_info *fs_info)
2290 {
2291         mutex_lock(&fs_info->scrub_lock);
2292         if (--fs_info->scrub_workers_refcnt == 0)
2293                 btrfs_stop_workers(&fs_info->scrub_workers);
2294         WARN_ON(fs_info->scrub_workers_refcnt < 0);
2295         mutex_unlock(&fs_info->scrub_lock);
2296 }
2297
2298 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
2299                     u64 end, struct btrfs_scrub_progress *progress,
2300                     int readonly, int is_dev_replace)
2301 {
2302         struct scrub_ctx *sctx;
2303         int ret;
2304         struct btrfs_device *dev;
2305
2306         if (btrfs_fs_closing(fs_info))
2307                 return -EINVAL;
2308
2309         /*
2310          * check some assumptions
2311          */
2312         if (fs_info->chunk_root->nodesize != fs_info->chunk_root->leafsize) {
2313                 printk(KERN_ERR
2314                        "btrfs_scrub: size assumption nodesize == leafsize (%d == %d) fails\n",
2315                        fs_info->chunk_root->nodesize,
2316                        fs_info->chunk_root->leafsize);
2317                 return -EINVAL;
2318         }
2319
2320         if (fs_info->chunk_root->nodesize > BTRFS_STRIPE_LEN) {
2321                 /*
2322                  * in this case scrub is unable to calculate the checksum
2323                  * the way scrub is implemented. Do not handle this
2324                  * situation at all because it won't ever happen.
2325                  */
2326                 printk(KERN_ERR
2327                        "btrfs_scrub: size assumption nodesize <= BTRFS_STRIPE_LEN (%d <= %d) fails\n",
2328                        fs_info->chunk_root->nodesize, BTRFS_STRIPE_LEN);
2329                 return -EINVAL;
2330         }
2331
2332         if (fs_info->chunk_root->sectorsize != PAGE_SIZE) {
2333                 /* not supported for data w/o checksums */
2334                 printk(KERN_ERR
2335                        "btrfs_scrub: size assumption sectorsize != PAGE_SIZE (%d != %lld) fails\n",
2336                        fs_info->chunk_root->sectorsize,
2337                        (unsigned long long)PAGE_SIZE);
2338                 return -EINVAL;
2339         }
2340
2341         if (fs_info->chunk_root->nodesize >
2342             PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK ||
2343             fs_info->chunk_root->sectorsize >
2344             PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK) {
2345                 /*
2346                  * would exhaust the array bounds of pagev member in
2347                  * struct scrub_block
2348                  */
2349                 pr_err("btrfs_scrub: size assumption nodesize and sectorsize <= SCRUB_MAX_PAGES_PER_BLOCK (%d <= %d && %d <= %d) fails\n",
2350                        fs_info->chunk_root->nodesize,
2351                        SCRUB_MAX_PAGES_PER_BLOCK,
2352                        fs_info->chunk_root->sectorsize,
2353                        SCRUB_MAX_PAGES_PER_BLOCK);
2354                 return -EINVAL;
2355         }
2356
2357         ret = scrub_workers_get(fs_info);
2358         if (ret)
2359                 return ret;
2360
2361         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2362         dev = btrfs_find_device(fs_info, devid, NULL, NULL);
2363         if (!dev || (dev->missing && !is_dev_replace)) {
2364                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2365                 scrub_workers_put(fs_info);
2366                 return -ENODEV;
2367         }
2368         mutex_lock(&fs_info->scrub_lock);
2369
2370         if (!dev->in_fs_metadata || dev->is_tgtdev_for_dev_replace) {
2371                 mutex_unlock(&fs_info->scrub_lock);
2372                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2373                 scrub_workers_put(fs_info);
2374                 return -EIO;
2375         }
2376
2377         if (dev->scrub_device) {
2378                 mutex_unlock(&fs_info->scrub_lock);
2379                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2380                 scrub_workers_put(fs_info);
2381                 return -EINPROGRESS;
2382         }
2383         sctx = scrub_setup_ctx(dev, is_dev_replace);
2384         if (IS_ERR(sctx)) {
2385                 mutex_unlock(&fs_info->scrub_lock);
2386                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2387                 scrub_workers_put(fs_info);
2388                 return PTR_ERR(sctx);
2389         }
2390         sctx->readonly = readonly;
2391         dev->scrub_device = sctx;
2392
2393         atomic_inc(&fs_info->scrubs_running);
2394         mutex_unlock(&fs_info->scrub_lock);
2395         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2396
2397         down_read(&fs_info->scrub_super_lock);
2398         ret = scrub_supers(sctx, dev);
2399         up_read(&fs_info->scrub_super_lock);
2400
2401         if (!ret)
2402                 ret = scrub_enumerate_chunks(sctx, dev, start, end);
2403
2404         wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
2405         atomic_dec(&fs_info->scrubs_running);
2406         wake_up(&fs_info->scrub_pause_wait);
2407
2408         wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0);
2409
2410         if (progress)
2411                 memcpy(progress, &sctx->stat, sizeof(*progress));
2412
2413         mutex_lock(&fs_info->scrub_lock);
2414         dev->scrub_device = NULL;
2415         mutex_unlock(&fs_info->scrub_lock);
2416
2417         scrub_free_ctx(sctx);
2418         scrub_workers_put(fs_info);
2419
2420         return ret;
2421 }
2422
2423 void btrfs_scrub_pause(struct btrfs_root *root)
2424 {
2425         struct btrfs_fs_info *fs_info = root->fs_info;
2426
2427         mutex_lock(&fs_info->scrub_lock);
2428         atomic_inc(&fs_info->scrub_pause_req);
2429         while (atomic_read(&fs_info->scrubs_paused) !=
2430                atomic_read(&fs_info->scrubs_running)) {
2431                 mutex_unlock(&fs_info->scrub_lock);
2432                 wait_event(fs_info->scrub_pause_wait,
2433                            atomic_read(&fs_info->scrubs_paused) ==
2434                            atomic_read(&fs_info->scrubs_running));
2435                 mutex_lock(&fs_info->scrub_lock);
2436         }
2437         mutex_unlock(&fs_info->scrub_lock);
2438 }
2439
2440 void btrfs_scrub_continue(struct btrfs_root *root)
2441 {
2442         struct btrfs_fs_info *fs_info = root->fs_info;
2443
2444         atomic_dec(&fs_info->scrub_pause_req);
2445         wake_up(&fs_info->scrub_pause_wait);
2446 }
2447
2448 void btrfs_scrub_pause_super(struct btrfs_root *root)
2449 {
2450         down_write(&root->fs_info->scrub_super_lock);
2451 }
2452
2453 void btrfs_scrub_continue_super(struct btrfs_root *root)
2454 {
2455         up_write(&root->fs_info->scrub_super_lock);
2456 }
2457
2458 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
2459 {
2460         mutex_lock(&fs_info->scrub_lock);
2461         if (!atomic_read(&fs_info->scrubs_running)) {
2462                 mutex_unlock(&fs_info->scrub_lock);
2463                 return -ENOTCONN;
2464         }
2465
2466         atomic_inc(&fs_info->scrub_cancel_req);
2467         while (atomic_read(&fs_info->scrubs_running)) {
2468                 mutex_unlock(&fs_info->scrub_lock);
2469                 wait_event(fs_info->scrub_pause_wait,
2470                            atomic_read(&fs_info->scrubs_running) == 0);
2471                 mutex_lock(&fs_info->scrub_lock);
2472         }
2473         atomic_dec(&fs_info->scrub_cancel_req);
2474         mutex_unlock(&fs_info->scrub_lock);
2475
2476         return 0;
2477 }
2478
2479 int btrfs_scrub_cancel_dev(struct btrfs_fs_info *fs_info,
2480                            struct btrfs_device *dev)
2481 {
2482         struct scrub_ctx *sctx;
2483
2484         mutex_lock(&fs_info->scrub_lock);
2485         sctx = dev->scrub_device;
2486         if (!sctx) {
2487                 mutex_unlock(&fs_info->scrub_lock);
2488                 return -ENOTCONN;
2489         }
2490         atomic_inc(&sctx->cancel_req);
2491         while (dev->scrub_device) {
2492                 mutex_unlock(&fs_info->scrub_lock);
2493                 wait_event(fs_info->scrub_pause_wait,
2494                            dev->scrub_device == NULL);
2495                 mutex_lock(&fs_info->scrub_lock);
2496         }
2497         mutex_unlock(&fs_info->scrub_lock);
2498
2499         return 0;
2500 }
2501
2502 int btrfs_scrub_cancel_devid(struct btrfs_root *root, u64 devid)
2503 {
2504         struct btrfs_fs_info *fs_info = root->fs_info;
2505         struct btrfs_device *dev;
2506         int ret;
2507
2508         /*
2509          * we have to hold the device_list_mutex here so the device
2510          * does not go away in cancel_dev. FIXME: find a better solution
2511          */
2512         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2513         dev = btrfs_find_device(fs_info, devid, NULL, NULL);
2514         if (!dev) {
2515                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2516                 return -ENODEV;
2517         }
2518         ret = btrfs_scrub_cancel_dev(fs_info, dev);
2519         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2520
2521         return ret;
2522 }
2523
2524 int btrfs_scrub_progress(struct btrfs_root *root, u64 devid,
2525                          struct btrfs_scrub_progress *progress)
2526 {
2527         struct btrfs_device *dev;
2528         struct scrub_ctx *sctx = NULL;
2529
2530         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2531         dev = btrfs_find_device(root->fs_info, devid, NULL, NULL);
2532         if (dev)
2533                 sctx = dev->scrub_device;
2534         if (sctx)
2535                 memcpy(progress, &sctx->stat, sizeof(*progress));
2536         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2537
2538         return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;
2539 }