Btrfs: minor cleanup in scrub
[profile/ivi/kernel-x86-ivi.git] / fs / btrfs / scrub.c
1 /*
2  * Copyright (C) 2011 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
30 /*
31  * This is only the first step towards a full-features scrub. It reads all
32  * extent and super block and verifies the checksums. In case a bad checksum
33  * is found or the extent cannot be read, good data will be written back if
34  * any can be found.
35  *
36  * Future enhancements:
37  *  - In case an unrepairable extent is encountered, track which files are
38  *    affected and report them
39  *  - track and record media errors, throw out bad devices
40  *  - add a mode to also read unallocated space
41  */
42
43 struct scrub_dev;
44
45 #define SCRUB_PAGES_PER_BIO     16      /* 64k per bio */
46 #define SCRUB_BIOS_PER_DEV      16      /* 1 MB per device in flight */
47
48 struct scrub_page {
49         u64                     flags;  /* extent flags */
50         u64                     generation;
51         int                     mirror_num;
52         int                     have_csum;
53         u8                      csum[BTRFS_CSUM_SIZE];
54 };
55
56 struct scrub_bio {
57         int                     index;
58         struct scrub_dev        *sdev;
59         struct bio              *bio;
60         int                     err;
61         u64                     logical;
62         u64                     physical;
63         struct scrub_page       spag[SCRUB_PAGES_PER_BIO];
64         u64                     count;
65         int                     next_free;
66         struct btrfs_work       work;
67 };
68
69 struct scrub_dev {
70         struct scrub_bio        *bios[SCRUB_BIOS_PER_DEV];
71         struct btrfs_device     *dev;
72         int                     first_free;
73         int                     curr;
74         atomic_t                in_flight;
75         atomic_t                fixup_cnt;
76         spinlock_t              list_lock;
77         wait_queue_head_t       list_wait;
78         u16                     csum_size;
79         struct list_head        csum_list;
80         atomic_t                cancel_req;
81         int                     readonly;
82         /*
83          * statistics
84          */
85         struct btrfs_scrub_progress stat;
86         spinlock_t              stat_lock;
87 };
88
89 struct scrub_fixup_nodatasum {
90         struct scrub_dev        *sdev;
91         u64                     logical;
92         struct btrfs_root       *root;
93         struct btrfs_work       work;
94         int                     mirror_num;
95 };
96
97 struct scrub_warning {
98         struct btrfs_path       *path;
99         u64                     extent_item_size;
100         char                    *scratch_buf;
101         char                    *msg_buf;
102         const char              *errstr;
103         sector_t                sector;
104         u64                     logical;
105         struct btrfs_device     *dev;
106         int                     msg_bufsize;
107         int                     scratch_bufsize;
108 };
109
110 static void scrub_bio_end_io(struct bio *bio, int err);
111 static void scrub_checksum(struct btrfs_work *work);
112 static int scrub_checksum_data(struct scrub_dev *sdev,
113                                struct scrub_page *spag, void *buffer);
114 static int scrub_checksum_tree_block(struct scrub_dev *sdev,
115                                      struct scrub_page *spag, u64 logical,
116                                      void *buffer);
117 static int scrub_checksum_super(struct scrub_bio *sbio, void *buffer);
118 static int scrub_fixup_check(struct scrub_bio *sbio, int ix);
119 static void scrub_fixup_end_io(struct bio *bio, int err);
120 static int scrub_fixup_io(int rw, struct block_device *bdev, sector_t sector,
121                           struct page *page);
122 static void scrub_fixup(struct scrub_bio *sbio, int ix);
123
124
125 static void scrub_free_csums(struct scrub_dev *sdev)
126 {
127         while (!list_empty(&sdev->csum_list)) {
128                 struct btrfs_ordered_sum *sum;
129                 sum = list_first_entry(&sdev->csum_list,
130                                        struct btrfs_ordered_sum, list);
131                 list_del(&sum->list);
132                 kfree(sum);
133         }
134 }
135
136 static void scrub_free_bio(struct bio *bio)
137 {
138         int i;
139         struct page *last_page = NULL;
140
141         if (!bio)
142                 return;
143
144         for (i = 0; i < bio->bi_vcnt; ++i) {
145                 if (bio->bi_io_vec[i].bv_page == last_page)
146                         continue;
147                 last_page = bio->bi_io_vec[i].bv_page;
148                 __free_page(last_page);
149         }
150         bio_put(bio);
151 }
152
153 static noinline_for_stack void scrub_free_dev(struct scrub_dev *sdev)
154 {
155         int i;
156
157         if (!sdev)
158                 return;
159
160         for (i = 0; i < SCRUB_BIOS_PER_DEV; ++i) {
161                 struct scrub_bio *sbio = sdev->bios[i];
162
163                 if (!sbio)
164                         break;
165
166                 scrub_free_bio(sbio->bio);
167                 kfree(sbio);
168         }
169
170         scrub_free_csums(sdev);
171         kfree(sdev);
172 }
173
174 static noinline_for_stack
175 struct scrub_dev *scrub_setup_dev(struct btrfs_device *dev)
176 {
177         struct scrub_dev *sdev;
178         int             i;
179         struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
180
181         sdev = kzalloc(sizeof(*sdev), GFP_NOFS);
182         if (!sdev)
183                 goto nomem;
184         sdev->dev = dev;
185         for (i = 0; i < SCRUB_BIOS_PER_DEV; ++i) {
186                 struct scrub_bio *sbio;
187
188                 sbio = kzalloc(sizeof(*sbio), GFP_NOFS);
189                 if (!sbio)
190                         goto nomem;
191                 sdev->bios[i] = sbio;
192
193                 sbio->index = i;
194                 sbio->sdev = sdev;
195                 sbio->count = 0;
196                 sbio->work.func = scrub_checksum;
197
198                 if (i != SCRUB_BIOS_PER_DEV-1)
199                         sdev->bios[i]->next_free = i + 1;
200                 else
201                         sdev->bios[i]->next_free = -1;
202         }
203         sdev->first_free = 0;
204         sdev->curr = -1;
205         atomic_set(&sdev->in_flight, 0);
206         atomic_set(&sdev->fixup_cnt, 0);
207         atomic_set(&sdev->cancel_req, 0);
208         sdev->csum_size = btrfs_super_csum_size(fs_info->super_copy);
209         INIT_LIST_HEAD(&sdev->csum_list);
210
211         spin_lock_init(&sdev->list_lock);
212         spin_lock_init(&sdev->stat_lock);
213         init_waitqueue_head(&sdev->list_wait);
214         return sdev;
215
216 nomem:
217         scrub_free_dev(sdev);
218         return ERR_PTR(-ENOMEM);
219 }
220
221 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root, void *ctx)
222 {
223         u64 isize;
224         u32 nlink;
225         int ret;
226         int i;
227         struct extent_buffer *eb;
228         struct btrfs_inode_item *inode_item;
229         struct scrub_warning *swarn = ctx;
230         struct btrfs_fs_info *fs_info = swarn->dev->dev_root->fs_info;
231         struct inode_fs_paths *ipath = NULL;
232         struct btrfs_root *local_root;
233         struct btrfs_key root_key;
234
235         root_key.objectid = root;
236         root_key.type = BTRFS_ROOT_ITEM_KEY;
237         root_key.offset = (u64)-1;
238         local_root = btrfs_read_fs_root_no_name(fs_info, &root_key);
239         if (IS_ERR(local_root)) {
240                 ret = PTR_ERR(local_root);
241                 goto err;
242         }
243
244         ret = inode_item_info(inum, 0, local_root, swarn->path);
245         if (ret) {
246                 btrfs_release_path(swarn->path);
247                 goto err;
248         }
249
250         eb = swarn->path->nodes[0];
251         inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
252                                         struct btrfs_inode_item);
253         isize = btrfs_inode_size(eb, inode_item);
254         nlink = btrfs_inode_nlink(eb, inode_item);
255         btrfs_release_path(swarn->path);
256
257         ipath = init_ipath(4096, local_root, swarn->path);
258         if (IS_ERR(ipath)) {
259                 ret = PTR_ERR(ipath);
260                 ipath = NULL;
261                 goto err;
262         }
263         ret = paths_from_inode(inum, ipath);
264
265         if (ret < 0)
266                 goto err;
267
268         /*
269          * we deliberately ignore the bit ipath might have been too small to
270          * hold all of the paths here
271          */
272         for (i = 0; i < ipath->fspath->elem_cnt; ++i)
273                 printk(KERN_WARNING "btrfs: %s at logical %llu on dev "
274                         "%s, sector %llu, root %llu, inode %llu, offset %llu, "
275                         "length %llu, links %u (path: %s)\n", swarn->errstr,
276                         swarn->logical, swarn->dev->name,
277                         (unsigned long long)swarn->sector, root, inum, offset,
278                         min(isize - offset, (u64)PAGE_SIZE), nlink,
279                         (char *)(unsigned long)ipath->fspath->val[i]);
280
281         free_ipath(ipath);
282         return 0;
283
284 err:
285         printk(KERN_WARNING "btrfs: %s at logical %llu on dev "
286                 "%s, sector %llu, root %llu, inode %llu, offset %llu: path "
287                 "resolving failed with ret=%d\n", swarn->errstr,
288                 swarn->logical, swarn->dev->name,
289                 (unsigned long long)swarn->sector, root, inum, offset, ret);
290
291         free_ipath(ipath);
292         return 0;
293 }
294
295 static void scrub_print_warning(const char *errstr, struct scrub_bio *sbio,
296                                 int ix)
297 {
298         struct btrfs_device *dev = sbio->sdev->dev;
299         struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
300         struct btrfs_path *path;
301         struct btrfs_key found_key;
302         struct extent_buffer *eb;
303         struct btrfs_extent_item *ei;
304         struct scrub_warning swarn;
305         u32 item_size;
306         int ret;
307         u64 ref_root;
308         u8 ref_level;
309         unsigned long ptr = 0;
310         const int bufsize = 4096;
311         u64 extent_item_pos;
312
313         path = btrfs_alloc_path();
314
315         swarn.scratch_buf = kmalloc(bufsize, GFP_NOFS);
316         swarn.msg_buf = kmalloc(bufsize, GFP_NOFS);
317         swarn.sector = (sbio->physical + ix * PAGE_SIZE) >> 9;
318         swarn.logical = sbio->logical + ix * PAGE_SIZE;
319         swarn.errstr = errstr;
320         swarn.dev = dev;
321         swarn.msg_bufsize = bufsize;
322         swarn.scratch_bufsize = bufsize;
323
324         if (!path || !swarn.scratch_buf || !swarn.msg_buf)
325                 goto out;
326
327         ret = extent_from_logical(fs_info, swarn.logical, path, &found_key);
328         if (ret < 0)
329                 goto out;
330
331         extent_item_pos = swarn.logical - found_key.objectid;
332         swarn.extent_item_size = found_key.offset;
333
334         eb = path->nodes[0];
335         ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
336         item_size = btrfs_item_size_nr(eb, path->slots[0]);
337         btrfs_release_path(path);
338
339         if (ret & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
340                 do {
341                         ret = tree_backref_for_extent(&ptr, eb, ei, item_size,
342                                                         &ref_root, &ref_level);
343                         printk(KERN_WARNING
344                                 "btrfs: %s at logical %llu on dev %s, "
345                                 "sector %llu: metadata %s (level %d) in tree "
346                                 "%llu\n", errstr, swarn.logical, dev->name,
347                                 (unsigned long long)swarn.sector,
348                                 ref_level ? "node" : "leaf",
349                                 ret < 0 ? -1 : ref_level,
350                                 ret < 0 ? -1 : ref_root);
351                 } while (ret != 1);
352         } else {
353                 swarn.path = path;
354                 iterate_extent_inodes(fs_info, path, found_key.objectid,
355                                         extent_item_pos,
356                                         scrub_print_warning_inode, &swarn);
357         }
358
359 out:
360         btrfs_free_path(path);
361         kfree(swarn.scratch_buf);
362         kfree(swarn.msg_buf);
363 }
364
365 static int scrub_fixup_readpage(u64 inum, u64 offset, u64 root, void *ctx)
366 {
367         struct page *page = NULL;
368         unsigned long index;
369         struct scrub_fixup_nodatasum *fixup = ctx;
370         int ret;
371         int corrected = 0;
372         struct btrfs_key key;
373         struct inode *inode = NULL;
374         u64 end = offset + PAGE_SIZE - 1;
375         struct btrfs_root *local_root;
376
377         key.objectid = root;
378         key.type = BTRFS_ROOT_ITEM_KEY;
379         key.offset = (u64)-1;
380         local_root = btrfs_read_fs_root_no_name(fixup->root->fs_info, &key);
381         if (IS_ERR(local_root))
382                 return PTR_ERR(local_root);
383
384         key.type = BTRFS_INODE_ITEM_KEY;
385         key.objectid = inum;
386         key.offset = 0;
387         inode = btrfs_iget(fixup->root->fs_info->sb, &key, local_root, NULL);
388         if (IS_ERR(inode))
389                 return PTR_ERR(inode);
390
391         index = offset >> PAGE_CACHE_SHIFT;
392
393         page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
394         if (!page) {
395                 ret = -ENOMEM;
396                 goto out;
397         }
398
399         if (PageUptodate(page)) {
400                 struct btrfs_mapping_tree *map_tree;
401                 if (PageDirty(page)) {
402                         /*
403                          * we need to write the data to the defect sector. the
404                          * data that was in that sector is not in memory,
405                          * because the page was modified. we must not write the
406                          * modified page to that sector.
407                          *
408                          * TODO: what could be done here: wait for the delalloc
409                          *       runner to write out that page (might involve
410                          *       COW) and see whether the sector is still
411                          *       referenced afterwards.
412                          *
413                          * For the meantime, we'll treat this error
414                          * incorrectable, although there is a chance that a
415                          * later scrub will find the bad sector again and that
416                          * there's no dirty page in memory, then.
417                          */
418                         ret = -EIO;
419                         goto out;
420                 }
421                 map_tree = &BTRFS_I(inode)->root->fs_info->mapping_tree;
422                 ret = repair_io_failure(map_tree, offset, PAGE_SIZE,
423                                         fixup->logical, page,
424                                         fixup->mirror_num);
425                 unlock_page(page);
426                 corrected = !ret;
427         } else {
428                 /*
429                  * we need to get good data first. the general readpage path
430                  * will call repair_io_failure for us, we just have to make
431                  * sure we read the bad mirror.
432                  */
433                 ret = set_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
434                                         EXTENT_DAMAGED, GFP_NOFS);
435                 if (ret) {
436                         /* set_extent_bits should give proper error */
437                         WARN_ON(ret > 0);
438                         if (ret > 0)
439                                 ret = -EFAULT;
440                         goto out;
441                 }
442
443                 ret = extent_read_full_page(&BTRFS_I(inode)->io_tree, page,
444                                                 btrfs_get_extent,
445                                                 fixup->mirror_num);
446                 wait_on_page_locked(page);
447
448                 corrected = !test_range_bit(&BTRFS_I(inode)->io_tree, offset,
449                                                 end, EXTENT_DAMAGED, 0, NULL);
450                 if (!corrected)
451                         clear_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
452                                                 EXTENT_DAMAGED, GFP_NOFS);
453         }
454
455 out:
456         if (page)
457                 put_page(page);
458         if (inode)
459                 iput(inode);
460
461         if (ret < 0)
462                 return ret;
463
464         if (ret == 0 && corrected) {
465                 /*
466                  * we only need to call readpage for one of the inodes belonging
467                  * to this extent. so make iterate_extent_inodes stop
468                  */
469                 return 1;
470         }
471
472         return -EIO;
473 }
474
475 static void scrub_fixup_nodatasum(struct btrfs_work *work)
476 {
477         int ret;
478         struct scrub_fixup_nodatasum *fixup;
479         struct scrub_dev *sdev;
480         struct btrfs_trans_handle *trans = NULL;
481         struct btrfs_fs_info *fs_info;
482         struct btrfs_path *path;
483         int uncorrectable = 0;
484
485         fixup = container_of(work, struct scrub_fixup_nodatasum, work);
486         sdev = fixup->sdev;
487         fs_info = fixup->root->fs_info;
488
489         path = btrfs_alloc_path();
490         if (!path) {
491                 spin_lock(&sdev->stat_lock);
492                 ++sdev->stat.malloc_errors;
493                 spin_unlock(&sdev->stat_lock);
494                 uncorrectable = 1;
495                 goto out;
496         }
497
498         trans = btrfs_join_transaction(fixup->root);
499         if (IS_ERR(trans)) {
500                 uncorrectable = 1;
501                 goto out;
502         }
503
504         /*
505          * the idea is to trigger a regular read through the standard path. we
506          * read a page from the (failed) logical address by specifying the
507          * corresponding copynum of the failed sector. thus, that readpage is
508          * expected to fail.
509          * that is the point where on-the-fly error correction will kick in
510          * (once it's finished) and rewrite the failed sector if a good copy
511          * can be found.
512          */
513         ret = iterate_inodes_from_logical(fixup->logical, fixup->root->fs_info,
514                                                 path, scrub_fixup_readpage,
515                                                 fixup);
516         if (ret < 0) {
517                 uncorrectable = 1;
518                 goto out;
519         }
520         WARN_ON(ret != 1);
521
522         spin_lock(&sdev->stat_lock);
523         ++sdev->stat.corrected_errors;
524         spin_unlock(&sdev->stat_lock);
525
526 out:
527         if (trans && !IS_ERR(trans))
528                 btrfs_end_transaction(trans, fixup->root);
529         if (uncorrectable) {
530                 spin_lock(&sdev->stat_lock);
531                 ++sdev->stat.uncorrectable_errors;
532                 spin_unlock(&sdev->stat_lock);
533                 printk_ratelimited(KERN_ERR "btrfs: unable to fixup "
534                                         "(nodatasum) error at logical %llu\n",
535                                         fixup->logical);
536         }
537
538         btrfs_free_path(path);
539         kfree(fixup);
540
541         /* see caller why we're pretending to be paused in the scrub counters */
542         mutex_lock(&fs_info->scrub_lock);
543         atomic_dec(&fs_info->scrubs_running);
544         atomic_dec(&fs_info->scrubs_paused);
545         mutex_unlock(&fs_info->scrub_lock);
546         atomic_dec(&sdev->fixup_cnt);
547         wake_up(&fs_info->scrub_pause_wait);
548         wake_up(&sdev->list_wait);
549 }
550
551 /*
552  * scrub_recheck_error gets called when either verification of the page
553  * failed or the bio failed to read, e.g. with EIO. In the latter case,
554  * recheck_error gets called for every page in the bio, even though only
555  * one may be bad
556  */
557 static int scrub_recheck_error(struct scrub_bio *sbio, int ix)
558 {
559         struct scrub_dev *sdev = sbio->sdev;
560         u64 sector = (sbio->physical + ix * PAGE_SIZE) >> 9;
561         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
562                                         DEFAULT_RATELIMIT_BURST);
563
564         if (sbio->err) {
565                 if (scrub_fixup_io(READ, sbio->sdev->dev->bdev, sector,
566                                    sbio->bio->bi_io_vec[ix].bv_page) == 0) {
567                         if (scrub_fixup_check(sbio, ix) == 0)
568                                 return 0;
569                 }
570                 if (__ratelimit(&_rs))
571                         scrub_print_warning("i/o error", sbio, ix);
572         } else {
573                 if (__ratelimit(&_rs))
574                         scrub_print_warning("checksum error", sbio, ix);
575         }
576
577         spin_lock(&sdev->stat_lock);
578         ++sdev->stat.read_errors;
579         spin_unlock(&sdev->stat_lock);
580
581         scrub_fixup(sbio, ix);
582         return 1;
583 }
584
585 static int scrub_fixup_check(struct scrub_bio *sbio, int ix)
586 {
587         int ret = 1;
588         struct page *page;
589         void *buffer;
590         u64 flags = sbio->spag[ix].flags;
591
592         page = sbio->bio->bi_io_vec[ix].bv_page;
593         buffer = kmap_atomic(page, KM_USER0);
594         if (flags & BTRFS_EXTENT_FLAG_DATA) {
595                 ret = scrub_checksum_data(sbio->sdev,
596                                           sbio->spag + ix, buffer);
597         } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
598                 ret = scrub_checksum_tree_block(sbio->sdev,
599                                                 sbio->spag + ix,
600                                                 sbio->logical + ix * PAGE_SIZE,
601                                                 buffer);
602         } else {
603                 WARN_ON(1);
604         }
605         kunmap_atomic(buffer, KM_USER0);
606
607         return ret;
608 }
609
610 static void scrub_fixup_end_io(struct bio *bio, int err)
611 {
612         complete((struct completion *)bio->bi_private);
613 }
614
615 static void scrub_fixup(struct scrub_bio *sbio, int ix)
616 {
617         struct scrub_dev *sdev = sbio->sdev;
618         struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
619         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
620         struct btrfs_bio *bbio = NULL;
621         struct scrub_fixup_nodatasum *fixup;
622         u64 logical = sbio->logical + ix * PAGE_SIZE;
623         u64 length;
624         int i;
625         int ret;
626         DECLARE_COMPLETION_ONSTACK(complete);
627
628         if ((sbio->spag[ix].flags & BTRFS_EXTENT_FLAG_DATA) &&
629             (sbio->spag[ix].have_csum == 0)) {
630                 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
631                 if (!fixup)
632                         goto uncorrectable;
633                 fixup->sdev = sdev;
634                 fixup->logical = logical;
635                 fixup->root = fs_info->extent_root;
636                 fixup->mirror_num = sbio->spag[ix].mirror_num;
637                 /*
638                  * increment scrubs_running to prevent cancel requests from
639                  * completing as long as a fixup worker is running. we must also
640                  * increment scrubs_paused to prevent deadlocking on pause
641                  * requests used for transactions commits (as the worker uses a
642                  * transaction context). it is safe to regard the fixup worker
643                  * as paused for all matters practical. effectively, we only
644                  * avoid cancellation requests from completing.
645                  */
646                 mutex_lock(&fs_info->scrub_lock);
647                 atomic_inc(&fs_info->scrubs_running);
648                 atomic_inc(&fs_info->scrubs_paused);
649                 mutex_unlock(&fs_info->scrub_lock);
650                 atomic_inc(&sdev->fixup_cnt);
651                 fixup->work.func = scrub_fixup_nodatasum;
652                 btrfs_queue_worker(&fs_info->scrub_workers, &fixup->work);
653                 return;
654         }
655
656         length = PAGE_SIZE;
657         ret = btrfs_map_block(map_tree, REQ_WRITE, logical, &length,
658                               &bbio, 0);
659         if (ret || !bbio || length < PAGE_SIZE) {
660                 printk(KERN_ERR
661                        "scrub_fixup: btrfs_map_block failed us for %llu\n",
662                        (unsigned long long)logical);
663                 WARN_ON(1);
664                 kfree(bbio);
665                 return;
666         }
667
668         if (bbio->num_stripes == 1)
669                 /* there aren't any replicas */
670                 goto uncorrectable;
671
672         /*
673          * first find a good copy
674          */
675         for (i = 0; i < bbio->num_stripes; ++i) {
676                 if (i + 1 == sbio->spag[ix].mirror_num)
677                         continue;
678
679                 if (scrub_fixup_io(READ, bbio->stripes[i].dev->bdev,
680                                    bbio->stripes[i].physical >> 9,
681                                    sbio->bio->bi_io_vec[ix].bv_page)) {
682                         /* I/O-error, this is not a good copy */
683                         continue;
684                 }
685
686                 if (scrub_fixup_check(sbio, ix) == 0)
687                         break;
688         }
689         if (i == bbio->num_stripes)
690                 goto uncorrectable;
691
692         if (!sdev->readonly) {
693                 /*
694                  * bi_io_vec[ix].bv_page now contains good data, write it back
695                  */
696                 if (scrub_fixup_io(WRITE, sdev->dev->bdev,
697                                    (sbio->physical + ix * PAGE_SIZE) >> 9,
698                                    sbio->bio->bi_io_vec[ix].bv_page)) {
699                         /* I/O-error, writeback failed, give up */
700                         goto uncorrectable;
701                 }
702         }
703
704         kfree(bbio);
705         spin_lock(&sdev->stat_lock);
706         ++sdev->stat.corrected_errors;
707         spin_unlock(&sdev->stat_lock);
708
709         printk_ratelimited(KERN_ERR "btrfs: fixed up error at logical %llu\n",
710                                (unsigned long long)logical);
711         return;
712
713 uncorrectable:
714         kfree(bbio);
715         spin_lock(&sdev->stat_lock);
716         ++sdev->stat.uncorrectable_errors;
717         spin_unlock(&sdev->stat_lock);
718
719         printk_ratelimited(KERN_ERR "btrfs: unable to fixup (regular) error at "
720                                 "logical %llu\n", (unsigned long long)logical);
721 }
722
723 static int scrub_fixup_io(int rw, struct block_device *bdev, sector_t sector,
724                          struct page *page)
725 {
726         struct bio *bio = NULL;
727         int ret;
728         DECLARE_COMPLETION_ONSTACK(complete);
729
730         bio = bio_alloc(GFP_NOFS, 1);
731         bio->bi_bdev = bdev;
732         bio->bi_sector = sector;
733         bio_add_page(bio, page, PAGE_SIZE, 0);
734         bio->bi_end_io = scrub_fixup_end_io;
735         bio->bi_private = &complete;
736         btrfsic_submit_bio(rw, bio);
737
738         /* this will also unplug the queue */
739         wait_for_completion(&complete);
740
741         ret = !test_bit(BIO_UPTODATE, &bio->bi_flags);
742         bio_put(bio);
743         return ret;
744 }
745
746 static void scrub_bio_end_io(struct bio *bio, int err)
747 {
748         struct scrub_bio *sbio = bio->bi_private;
749         struct scrub_dev *sdev = sbio->sdev;
750         struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
751
752         sbio->err = err;
753         sbio->bio = bio;
754
755         btrfs_queue_worker(&fs_info->scrub_workers, &sbio->work);
756 }
757
758 static void scrub_checksum(struct btrfs_work *work)
759 {
760         struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
761         struct scrub_dev *sdev = sbio->sdev;
762         struct page *page;
763         void *buffer;
764         int i;
765         u64 flags;
766         u64 logical;
767         int ret;
768
769         if (sbio->err) {
770                 ret = 0;
771                 for (i = 0; i < sbio->count; ++i)
772                         ret |= scrub_recheck_error(sbio, i);
773                 if (!ret) {
774                         spin_lock(&sdev->stat_lock);
775                         ++sdev->stat.unverified_errors;
776                         spin_unlock(&sdev->stat_lock);
777                 }
778
779                 sbio->bio->bi_flags &= ~(BIO_POOL_MASK - 1);
780                 sbio->bio->bi_flags |= 1 << BIO_UPTODATE;
781                 sbio->bio->bi_phys_segments = 0;
782                 sbio->bio->bi_idx = 0;
783
784                 for (i = 0; i < sbio->count; i++) {
785                         struct bio_vec *bi;
786                         bi = &sbio->bio->bi_io_vec[i];
787                         bi->bv_offset = 0;
788                         bi->bv_len = PAGE_SIZE;
789                 }
790                 goto out;
791         }
792         for (i = 0; i < sbio->count; ++i) {
793                 page = sbio->bio->bi_io_vec[i].bv_page;
794                 buffer = kmap_atomic(page, KM_USER0);
795                 flags = sbio->spag[i].flags;
796                 logical = sbio->logical + i * PAGE_SIZE;
797                 ret = 0;
798                 if (flags & BTRFS_EXTENT_FLAG_DATA) {
799                         ret = scrub_checksum_data(sdev, sbio->spag + i, buffer);
800                 } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
801                         ret = scrub_checksum_tree_block(sdev, sbio->spag + i,
802                                                         logical, buffer);
803                 } else if (flags & BTRFS_EXTENT_FLAG_SUPER) {
804                         BUG_ON(i);
805                         (void)scrub_checksum_super(sbio, buffer);
806                 } else {
807                         WARN_ON(1);
808                 }
809                 kunmap_atomic(buffer, KM_USER0);
810                 if (ret) {
811                         ret = scrub_recheck_error(sbio, i);
812                         if (!ret) {
813                                 spin_lock(&sdev->stat_lock);
814                                 ++sdev->stat.unverified_errors;
815                                 spin_unlock(&sdev->stat_lock);
816                         }
817                 }
818         }
819
820 out:
821         scrub_free_bio(sbio->bio);
822         sbio->bio = NULL;
823         spin_lock(&sdev->list_lock);
824         sbio->next_free = sdev->first_free;
825         sdev->first_free = sbio->index;
826         spin_unlock(&sdev->list_lock);
827         atomic_dec(&sdev->in_flight);
828         wake_up(&sdev->list_wait);
829 }
830
831 static int scrub_checksum_data(struct scrub_dev *sdev,
832                                struct scrub_page *spag, void *buffer)
833 {
834         u8 csum[BTRFS_CSUM_SIZE];
835         u32 crc = ~(u32)0;
836         int fail = 0;
837         struct btrfs_root *root = sdev->dev->dev_root;
838
839         if (!spag->have_csum)
840                 return 0;
841
842         crc = btrfs_csum_data(root, buffer, crc, PAGE_SIZE);
843         btrfs_csum_final(crc, csum);
844         if (memcmp(csum, spag->csum, sdev->csum_size))
845                 fail = 1;
846
847         spin_lock(&sdev->stat_lock);
848         ++sdev->stat.data_extents_scrubbed;
849         sdev->stat.data_bytes_scrubbed += PAGE_SIZE;
850         if (fail)
851                 ++sdev->stat.csum_errors;
852         spin_unlock(&sdev->stat_lock);
853
854         return fail;
855 }
856
857 static int scrub_checksum_tree_block(struct scrub_dev *sdev,
858                                      struct scrub_page *spag, u64 logical,
859                                      void *buffer)
860 {
861         struct btrfs_header *h;
862         struct btrfs_root *root = sdev->dev->dev_root;
863         struct btrfs_fs_info *fs_info = root->fs_info;
864         u8 csum[BTRFS_CSUM_SIZE];
865         u32 crc = ~(u32)0;
866         int fail = 0;
867         int crc_fail = 0;
868
869         /*
870          * we don't use the getter functions here, as we
871          * a) don't have an extent buffer and
872          * b) the page is already kmapped
873          */
874         h = (struct btrfs_header *)buffer;
875
876         if (logical != le64_to_cpu(h->bytenr))
877                 ++fail;
878
879         if (spag->generation != le64_to_cpu(h->generation))
880                 ++fail;
881
882         if (memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
883                 ++fail;
884
885         if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
886                    BTRFS_UUID_SIZE))
887                 ++fail;
888
889         crc = btrfs_csum_data(root, buffer + BTRFS_CSUM_SIZE, crc,
890                               PAGE_SIZE - BTRFS_CSUM_SIZE);
891         btrfs_csum_final(crc, csum);
892         if (memcmp(csum, h->csum, sdev->csum_size))
893                 ++crc_fail;
894
895         spin_lock(&sdev->stat_lock);
896         ++sdev->stat.tree_extents_scrubbed;
897         sdev->stat.tree_bytes_scrubbed += PAGE_SIZE;
898         if (crc_fail)
899                 ++sdev->stat.csum_errors;
900         if (fail)
901                 ++sdev->stat.verify_errors;
902         spin_unlock(&sdev->stat_lock);
903
904         return fail || crc_fail;
905 }
906
907 static int scrub_checksum_super(struct scrub_bio *sbio, void *buffer)
908 {
909         struct btrfs_super_block *s;
910         u64 logical;
911         struct scrub_dev *sdev = sbio->sdev;
912         struct btrfs_root *root = sdev->dev->dev_root;
913         struct btrfs_fs_info *fs_info = root->fs_info;
914         u8 csum[BTRFS_CSUM_SIZE];
915         u32 crc = ~(u32)0;
916         int fail = 0;
917
918         s = (struct btrfs_super_block *)buffer;
919         logical = sbio->logical;
920
921         if (logical != le64_to_cpu(s->bytenr))
922                 ++fail;
923
924         if (sbio->spag[0].generation != le64_to_cpu(s->generation))
925                 ++fail;
926
927         if (memcmp(s->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
928                 ++fail;
929
930         crc = btrfs_csum_data(root, buffer + BTRFS_CSUM_SIZE, crc,
931                               PAGE_SIZE - BTRFS_CSUM_SIZE);
932         btrfs_csum_final(crc, csum);
933         if (memcmp(csum, s->csum, sbio->sdev->csum_size))
934                 ++fail;
935
936         if (fail) {
937                 /*
938                  * if we find an error in a super block, we just report it.
939                  * They will get written with the next transaction commit
940                  * anyway
941                  */
942                 spin_lock(&sdev->stat_lock);
943                 ++sdev->stat.super_errors;
944                 spin_unlock(&sdev->stat_lock);
945         }
946
947         return fail;
948 }
949
950 static void scrub_submit(struct scrub_dev *sdev)
951 {
952         struct scrub_bio *sbio;
953
954         if (sdev->curr == -1)
955                 return;
956
957         sbio = sdev->bios[sdev->curr];
958         sbio->err = 0;
959         sdev->curr = -1;
960         atomic_inc(&sdev->in_flight);
961
962         btrfsic_submit_bio(READ, sbio->bio);
963 }
964
965 static int scrub_page(struct scrub_dev *sdev, u64 logical, u64 len,
966                       u64 physical, u64 flags, u64 gen, int mirror_num,
967                       u8 *csum, int force)
968 {
969         struct scrub_bio *sbio;
970         struct page *page;
971         int ret;
972
973 again:
974         /*
975          * grab a fresh bio or wait for one to become available
976          */
977         while (sdev->curr == -1) {
978                 spin_lock(&sdev->list_lock);
979                 sdev->curr = sdev->first_free;
980                 if (sdev->curr != -1) {
981                         sdev->first_free = sdev->bios[sdev->curr]->next_free;
982                         sdev->bios[sdev->curr]->next_free = -1;
983                         sdev->bios[sdev->curr]->count = 0;
984                         spin_unlock(&sdev->list_lock);
985                 } else {
986                         spin_unlock(&sdev->list_lock);
987                         wait_event(sdev->list_wait, sdev->first_free != -1);
988                 }
989         }
990         sbio = sdev->bios[sdev->curr];
991         if (sbio->count == 0) {
992                 struct bio *bio;
993
994                 sbio->physical = physical;
995                 sbio->logical = logical;
996                 bio = bio_alloc(GFP_NOFS, SCRUB_PAGES_PER_BIO);
997                 if (!bio)
998                         return -ENOMEM;
999
1000                 bio->bi_private = sbio;
1001                 bio->bi_end_io = scrub_bio_end_io;
1002                 bio->bi_bdev = sdev->dev->bdev;
1003                 bio->bi_sector = sbio->physical >> 9;
1004                 sbio->err = 0;
1005                 sbio->bio = bio;
1006         } else if (sbio->physical + sbio->count * PAGE_SIZE != physical ||
1007                    sbio->logical + sbio->count * PAGE_SIZE != logical) {
1008                 scrub_submit(sdev);
1009                 goto again;
1010         }
1011         sbio->spag[sbio->count].flags = flags;
1012         sbio->spag[sbio->count].generation = gen;
1013         sbio->spag[sbio->count].have_csum = 0;
1014         sbio->spag[sbio->count].mirror_num = mirror_num;
1015
1016         page = alloc_page(GFP_NOFS);
1017         if (!page)
1018                 return -ENOMEM;
1019
1020         ret = bio_add_page(sbio->bio, page, PAGE_SIZE, 0);
1021         if (!ret) {
1022                 __free_page(page);
1023                 scrub_submit(sdev);
1024                 goto again;
1025         }
1026
1027         if (csum) {
1028                 sbio->spag[sbio->count].have_csum = 1;
1029                 memcpy(sbio->spag[sbio->count].csum, csum, sdev->csum_size);
1030         }
1031         ++sbio->count;
1032         if (sbio->count == SCRUB_PAGES_PER_BIO || force)
1033                 scrub_submit(sdev);
1034
1035         return 0;
1036 }
1037
1038 static int scrub_find_csum(struct scrub_dev *sdev, u64 logical, u64 len,
1039                            u8 *csum)
1040 {
1041         struct btrfs_ordered_sum *sum = NULL;
1042         int ret = 0;
1043         unsigned long i;
1044         unsigned long num_sectors;
1045         u32 sectorsize = sdev->dev->dev_root->sectorsize;
1046
1047         while (!list_empty(&sdev->csum_list)) {
1048                 sum = list_first_entry(&sdev->csum_list,
1049                                        struct btrfs_ordered_sum, list);
1050                 if (sum->bytenr > logical)
1051                         return 0;
1052                 if (sum->bytenr + sum->len > logical)
1053                         break;
1054
1055                 ++sdev->stat.csum_discards;
1056                 list_del(&sum->list);
1057                 kfree(sum);
1058                 sum = NULL;
1059         }
1060         if (!sum)
1061                 return 0;
1062
1063         num_sectors = sum->len / sectorsize;
1064         for (i = 0; i < num_sectors; ++i) {
1065                 if (sum->sums[i].bytenr == logical) {
1066                         memcpy(csum, &sum->sums[i].sum, sdev->csum_size);
1067                         ret = 1;
1068                         break;
1069                 }
1070         }
1071         if (ret && i == num_sectors - 1) {
1072                 list_del(&sum->list);
1073                 kfree(sum);
1074         }
1075         return ret;
1076 }
1077
1078 /* scrub extent tries to collect up to 64 kB for each bio */
1079 static int scrub_extent(struct scrub_dev *sdev, u64 logical, u64 len,
1080                         u64 physical, u64 flags, u64 gen, int mirror_num)
1081 {
1082         int ret;
1083         u8 csum[BTRFS_CSUM_SIZE];
1084
1085         while (len) {
1086                 u64 l = min_t(u64, len, PAGE_SIZE);
1087                 int have_csum = 0;
1088
1089                 if (flags & BTRFS_EXTENT_FLAG_DATA) {
1090                         /* push csums to sbio */
1091                         have_csum = scrub_find_csum(sdev, logical, l, csum);
1092                         if (have_csum == 0)
1093                                 ++sdev->stat.no_csum;
1094                 }
1095                 ret = scrub_page(sdev, logical, l, physical, flags, gen,
1096                                  mirror_num, have_csum ? csum : NULL, 0);
1097                 if (ret)
1098                         return ret;
1099                 len -= l;
1100                 logical += l;
1101                 physical += l;
1102         }
1103         return 0;
1104 }
1105
1106 static noinline_for_stack int scrub_stripe(struct scrub_dev *sdev,
1107         struct map_lookup *map, int num, u64 base, u64 length)
1108 {
1109         struct btrfs_path *path;
1110         struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
1111         struct btrfs_root *root = fs_info->extent_root;
1112         struct btrfs_root *csum_root = fs_info->csum_root;
1113         struct btrfs_extent_item *extent;
1114         struct blk_plug plug;
1115         u64 flags;
1116         int ret;
1117         int slot;
1118         int i;
1119         u64 nstripes;
1120         struct extent_buffer *l;
1121         struct btrfs_key key;
1122         u64 physical;
1123         u64 logical;
1124         u64 generation;
1125         int mirror_num;
1126         struct reada_control *reada1;
1127         struct reada_control *reada2;
1128         struct btrfs_key key_start;
1129         struct btrfs_key key_end;
1130
1131         u64 increment = map->stripe_len;
1132         u64 offset;
1133
1134         nstripes = length;
1135         offset = 0;
1136         do_div(nstripes, map->stripe_len);
1137         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1138                 offset = map->stripe_len * num;
1139                 increment = map->stripe_len * map->num_stripes;
1140                 mirror_num = 1;
1141         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1142                 int factor = map->num_stripes / map->sub_stripes;
1143                 offset = map->stripe_len * (num / map->sub_stripes);
1144                 increment = map->stripe_len * factor;
1145                 mirror_num = num % map->sub_stripes + 1;
1146         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1147                 increment = map->stripe_len;
1148                 mirror_num = num % map->num_stripes + 1;
1149         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1150                 increment = map->stripe_len;
1151                 mirror_num = num % map->num_stripes + 1;
1152         } else {
1153                 increment = map->stripe_len;
1154                 mirror_num = 1;
1155         }
1156
1157         path = btrfs_alloc_path();
1158         if (!path)
1159                 return -ENOMEM;
1160
1161         path->search_commit_root = 1;
1162         path->skip_locking = 1;
1163
1164         /*
1165          * trigger the readahead for extent tree csum tree and wait for
1166          * completion. During readahead, the scrub is officially paused
1167          * to not hold off transaction commits
1168          */
1169         logical = base + offset;
1170
1171         wait_event(sdev->list_wait,
1172                    atomic_read(&sdev->in_flight) == 0);
1173         atomic_inc(&fs_info->scrubs_paused);
1174         wake_up(&fs_info->scrub_pause_wait);
1175
1176         /* FIXME it might be better to start readahead at commit root */
1177         key_start.objectid = logical;
1178         key_start.type = BTRFS_EXTENT_ITEM_KEY;
1179         key_start.offset = (u64)0;
1180         key_end.objectid = base + offset + nstripes * increment;
1181         key_end.type = BTRFS_EXTENT_ITEM_KEY;
1182         key_end.offset = (u64)0;
1183         reada1 = btrfs_reada_add(root, &key_start, &key_end);
1184
1185         key_start.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1186         key_start.type = BTRFS_EXTENT_CSUM_KEY;
1187         key_start.offset = logical;
1188         key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1189         key_end.type = BTRFS_EXTENT_CSUM_KEY;
1190         key_end.offset = base + offset + nstripes * increment;
1191         reada2 = btrfs_reada_add(csum_root, &key_start, &key_end);
1192
1193         if (!IS_ERR(reada1))
1194                 btrfs_reada_wait(reada1);
1195         if (!IS_ERR(reada2))
1196                 btrfs_reada_wait(reada2);
1197
1198         mutex_lock(&fs_info->scrub_lock);
1199         while (atomic_read(&fs_info->scrub_pause_req)) {
1200                 mutex_unlock(&fs_info->scrub_lock);
1201                 wait_event(fs_info->scrub_pause_wait,
1202                    atomic_read(&fs_info->scrub_pause_req) == 0);
1203                 mutex_lock(&fs_info->scrub_lock);
1204         }
1205         atomic_dec(&fs_info->scrubs_paused);
1206         mutex_unlock(&fs_info->scrub_lock);
1207         wake_up(&fs_info->scrub_pause_wait);
1208
1209         /*
1210          * collect all data csums for the stripe to avoid seeking during
1211          * the scrub. This might currently (crc32) end up to be about 1MB
1212          */
1213         blk_start_plug(&plug);
1214
1215         /*
1216          * now find all extents for each stripe and scrub them
1217          */
1218         logical = base + offset;
1219         physical = map->stripes[num].physical;
1220         ret = 0;
1221         for (i = 0; i < nstripes; ++i) {
1222                 /*
1223                  * canceled?
1224                  */
1225                 if (atomic_read(&fs_info->scrub_cancel_req) ||
1226                     atomic_read(&sdev->cancel_req)) {
1227                         ret = -ECANCELED;
1228                         goto out;
1229                 }
1230                 /*
1231                  * check to see if we have to pause
1232                  */
1233                 if (atomic_read(&fs_info->scrub_pause_req)) {
1234                         /* push queued extents */
1235                         scrub_submit(sdev);
1236                         wait_event(sdev->list_wait,
1237                                    atomic_read(&sdev->in_flight) == 0);
1238                         atomic_inc(&fs_info->scrubs_paused);
1239                         wake_up(&fs_info->scrub_pause_wait);
1240                         mutex_lock(&fs_info->scrub_lock);
1241                         while (atomic_read(&fs_info->scrub_pause_req)) {
1242                                 mutex_unlock(&fs_info->scrub_lock);
1243                                 wait_event(fs_info->scrub_pause_wait,
1244                                    atomic_read(&fs_info->scrub_pause_req) == 0);
1245                                 mutex_lock(&fs_info->scrub_lock);
1246                         }
1247                         atomic_dec(&fs_info->scrubs_paused);
1248                         mutex_unlock(&fs_info->scrub_lock);
1249                         wake_up(&fs_info->scrub_pause_wait);
1250                 }
1251
1252                 ret = btrfs_lookup_csums_range(csum_root, logical,
1253                                                logical + map->stripe_len - 1,
1254                                                &sdev->csum_list, 1);
1255                 if (ret)
1256                         goto out;
1257
1258                 key.objectid = logical;
1259                 key.type = BTRFS_EXTENT_ITEM_KEY;
1260                 key.offset = (u64)0;
1261
1262                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1263                 if (ret < 0)
1264                         goto out;
1265                 if (ret > 0) {
1266                         ret = btrfs_previous_item(root, path, 0,
1267                                                   BTRFS_EXTENT_ITEM_KEY);
1268                         if (ret < 0)
1269                                 goto out;
1270                         if (ret > 0) {
1271                                 /* there's no smaller item, so stick with the
1272                                  * larger one */
1273                                 btrfs_release_path(path);
1274                                 ret = btrfs_search_slot(NULL, root, &key,
1275                                                         path, 0, 0);
1276                                 if (ret < 0)
1277                                         goto out;
1278                         }
1279                 }
1280
1281                 while (1) {
1282                         l = path->nodes[0];
1283                         slot = path->slots[0];
1284                         if (slot >= btrfs_header_nritems(l)) {
1285                                 ret = btrfs_next_leaf(root, path);
1286                                 if (ret == 0)
1287                                         continue;
1288                                 if (ret < 0)
1289                                         goto out;
1290
1291                                 break;
1292                         }
1293                         btrfs_item_key_to_cpu(l, &key, slot);
1294
1295                         if (key.objectid + key.offset <= logical)
1296                                 goto next;
1297
1298                         if (key.objectid >= logical + map->stripe_len)
1299                                 break;
1300
1301                         if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY)
1302                                 goto next;
1303
1304                         extent = btrfs_item_ptr(l, slot,
1305                                                 struct btrfs_extent_item);
1306                         flags = btrfs_extent_flags(l, extent);
1307                         generation = btrfs_extent_generation(l, extent);
1308
1309                         if (key.objectid < logical &&
1310                             (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
1311                                 printk(KERN_ERR
1312                                        "btrfs scrub: tree block %llu spanning "
1313                                        "stripes, ignored. logical=%llu\n",
1314                                        (unsigned long long)key.objectid,
1315                                        (unsigned long long)logical);
1316                                 goto next;
1317                         }
1318
1319                         /*
1320                          * trim extent to this stripe
1321                          */
1322                         if (key.objectid < logical) {
1323                                 key.offset -= logical - key.objectid;
1324                                 key.objectid = logical;
1325                         }
1326                         if (key.objectid + key.offset >
1327                             logical + map->stripe_len) {
1328                                 key.offset = logical + map->stripe_len -
1329                                              key.objectid;
1330                         }
1331
1332                         ret = scrub_extent(sdev, key.objectid, key.offset,
1333                                            key.objectid - logical + physical,
1334                                            flags, generation, mirror_num);
1335                         if (ret)
1336                                 goto out;
1337
1338 next:
1339                         path->slots[0]++;
1340                 }
1341                 btrfs_release_path(path);
1342                 logical += increment;
1343                 physical += map->stripe_len;
1344                 spin_lock(&sdev->stat_lock);
1345                 sdev->stat.last_physical = physical;
1346                 spin_unlock(&sdev->stat_lock);
1347         }
1348         /* push queued extents */
1349         scrub_submit(sdev);
1350
1351 out:
1352         blk_finish_plug(&plug);
1353         btrfs_free_path(path);
1354         return ret < 0 ? ret : 0;
1355 }
1356
1357 static noinline_for_stack int scrub_chunk(struct scrub_dev *sdev,
1358         u64 chunk_tree, u64 chunk_objectid, u64 chunk_offset, u64 length,
1359         u64 dev_offset)
1360 {
1361         struct btrfs_mapping_tree *map_tree =
1362                 &sdev->dev->dev_root->fs_info->mapping_tree;
1363         struct map_lookup *map;
1364         struct extent_map *em;
1365         int i;
1366         int ret = -EINVAL;
1367
1368         read_lock(&map_tree->map_tree.lock);
1369         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
1370         read_unlock(&map_tree->map_tree.lock);
1371
1372         if (!em)
1373                 return -EINVAL;
1374
1375         map = (struct map_lookup *)em->bdev;
1376         if (em->start != chunk_offset)
1377                 goto out;
1378
1379         if (em->len < length)
1380                 goto out;
1381
1382         for (i = 0; i < map->num_stripes; ++i) {
1383                 if (map->stripes[i].dev == sdev->dev &&
1384                     map->stripes[i].physical == dev_offset) {
1385                         ret = scrub_stripe(sdev, map, i, chunk_offset, length);
1386                         if (ret)
1387                                 goto out;
1388                 }
1389         }
1390 out:
1391         free_extent_map(em);
1392
1393         return ret;
1394 }
1395
1396 static noinline_for_stack
1397 int scrub_enumerate_chunks(struct scrub_dev *sdev, u64 start, u64 end)
1398 {
1399         struct btrfs_dev_extent *dev_extent = NULL;
1400         struct btrfs_path *path;
1401         struct btrfs_root *root = sdev->dev->dev_root;
1402         struct btrfs_fs_info *fs_info = root->fs_info;
1403         u64 length;
1404         u64 chunk_tree;
1405         u64 chunk_objectid;
1406         u64 chunk_offset;
1407         int ret;
1408         int slot;
1409         struct extent_buffer *l;
1410         struct btrfs_key key;
1411         struct btrfs_key found_key;
1412         struct btrfs_block_group_cache *cache;
1413
1414         path = btrfs_alloc_path();
1415         if (!path)
1416                 return -ENOMEM;
1417
1418         path->reada = 2;
1419         path->search_commit_root = 1;
1420         path->skip_locking = 1;
1421
1422         key.objectid = sdev->dev->devid;
1423         key.offset = 0ull;
1424         key.type = BTRFS_DEV_EXTENT_KEY;
1425
1426
1427         while (1) {
1428                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1429                 if (ret < 0)
1430                         break;
1431                 if (ret > 0) {
1432                         if (path->slots[0] >=
1433                             btrfs_header_nritems(path->nodes[0])) {
1434                                 ret = btrfs_next_leaf(root, path);
1435                                 if (ret)
1436                                         break;
1437                         }
1438                 }
1439
1440                 l = path->nodes[0];
1441                 slot = path->slots[0];
1442
1443                 btrfs_item_key_to_cpu(l, &found_key, slot);
1444
1445                 if (found_key.objectid != sdev->dev->devid)
1446                         break;
1447
1448                 if (btrfs_key_type(&found_key) != BTRFS_DEV_EXTENT_KEY)
1449                         break;
1450
1451                 if (found_key.offset >= end)
1452                         break;
1453
1454                 if (found_key.offset < key.offset)
1455                         break;
1456
1457                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1458                 length = btrfs_dev_extent_length(l, dev_extent);
1459
1460                 if (found_key.offset + length <= start) {
1461                         key.offset = found_key.offset + length;
1462                         btrfs_release_path(path);
1463                         continue;
1464                 }
1465
1466                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
1467                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
1468                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
1469
1470                 /*
1471                  * get a reference on the corresponding block group to prevent
1472                  * the chunk from going away while we scrub it
1473                  */
1474                 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
1475                 if (!cache) {
1476                         ret = -ENOENT;
1477                         break;
1478                 }
1479                 ret = scrub_chunk(sdev, chunk_tree, chunk_objectid,
1480                                   chunk_offset, length, found_key.offset);
1481                 btrfs_put_block_group(cache);
1482                 if (ret)
1483                         break;
1484
1485                 key.offset = found_key.offset + length;
1486                 btrfs_release_path(path);
1487         }
1488
1489         btrfs_free_path(path);
1490
1491         /*
1492          * ret can still be 1 from search_slot or next_leaf,
1493          * that's not an error
1494          */
1495         return ret < 0 ? ret : 0;
1496 }
1497
1498 static noinline_for_stack int scrub_supers(struct scrub_dev *sdev)
1499 {
1500         int     i;
1501         u64     bytenr;
1502         u64     gen;
1503         int     ret;
1504         struct btrfs_device *device = sdev->dev;
1505         struct btrfs_root *root = device->dev_root;
1506
1507         gen = root->fs_info->last_trans_committed;
1508
1509         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1510                 bytenr = btrfs_sb_offset(i);
1511                 if (bytenr + BTRFS_SUPER_INFO_SIZE > device->total_bytes)
1512                         break;
1513
1514                 ret = scrub_page(sdev, bytenr, PAGE_SIZE, bytenr,
1515                                  BTRFS_EXTENT_FLAG_SUPER, gen, i, NULL, 1);
1516                 if (ret)
1517                         return ret;
1518         }
1519         wait_event(sdev->list_wait, atomic_read(&sdev->in_flight) == 0);
1520
1521         return 0;
1522 }
1523
1524 /*
1525  * get a reference count on fs_info->scrub_workers. start worker if necessary
1526  */
1527 static noinline_for_stack int scrub_workers_get(struct btrfs_root *root)
1528 {
1529         struct btrfs_fs_info *fs_info = root->fs_info;
1530         int ret = 0;
1531
1532         mutex_lock(&fs_info->scrub_lock);
1533         if (fs_info->scrub_workers_refcnt == 0) {
1534                 btrfs_init_workers(&fs_info->scrub_workers, "scrub",
1535                            fs_info->thread_pool_size, &fs_info->generic_worker);
1536                 fs_info->scrub_workers.idle_thresh = 4;
1537                 ret = btrfs_start_workers(&fs_info->scrub_workers);
1538                 if (ret)
1539                         goto out;
1540         }
1541         ++fs_info->scrub_workers_refcnt;
1542 out:
1543         mutex_unlock(&fs_info->scrub_lock);
1544
1545         return ret;
1546 }
1547
1548 static noinline_for_stack void scrub_workers_put(struct btrfs_root *root)
1549 {
1550         struct btrfs_fs_info *fs_info = root->fs_info;
1551
1552         mutex_lock(&fs_info->scrub_lock);
1553         if (--fs_info->scrub_workers_refcnt == 0)
1554                 btrfs_stop_workers(&fs_info->scrub_workers);
1555         WARN_ON(fs_info->scrub_workers_refcnt < 0);
1556         mutex_unlock(&fs_info->scrub_lock);
1557 }
1558
1559
1560 int btrfs_scrub_dev(struct btrfs_root *root, u64 devid, u64 start, u64 end,
1561                     struct btrfs_scrub_progress *progress, int readonly)
1562 {
1563         struct scrub_dev *sdev;
1564         struct btrfs_fs_info *fs_info = root->fs_info;
1565         int ret;
1566         struct btrfs_device *dev;
1567
1568         if (btrfs_fs_closing(root->fs_info))
1569                 return -EINVAL;
1570
1571         /*
1572          * check some assumptions
1573          */
1574         if (root->sectorsize != PAGE_SIZE ||
1575             root->sectorsize != root->leafsize ||
1576             root->sectorsize != root->nodesize) {
1577                 printk(KERN_ERR "btrfs_scrub: size assumptions fail\n");
1578                 return -EINVAL;
1579         }
1580
1581         ret = scrub_workers_get(root);
1582         if (ret)
1583                 return ret;
1584
1585         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1586         dev = btrfs_find_device(root, devid, NULL, NULL);
1587         if (!dev || dev->missing) {
1588                 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1589                 scrub_workers_put(root);
1590                 return -ENODEV;
1591         }
1592         mutex_lock(&fs_info->scrub_lock);
1593
1594         if (!dev->in_fs_metadata) {
1595                 mutex_unlock(&fs_info->scrub_lock);
1596                 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1597                 scrub_workers_put(root);
1598                 return -ENODEV;
1599         }
1600
1601         if (dev->scrub_device) {
1602                 mutex_unlock(&fs_info->scrub_lock);
1603                 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1604                 scrub_workers_put(root);
1605                 return -EINPROGRESS;
1606         }
1607         sdev = scrub_setup_dev(dev);
1608         if (IS_ERR(sdev)) {
1609                 mutex_unlock(&fs_info->scrub_lock);
1610                 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1611                 scrub_workers_put(root);
1612                 return PTR_ERR(sdev);
1613         }
1614         sdev->readonly = readonly;
1615         dev->scrub_device = sdev;
1616
1617         atomic_inc(&fs_info->scrubs_running);
1618         mutex_unlock(&fs_info->scrub_lock);
1619         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1620
1621         down_read(&fs_info->scrub_super_lock);
1622         ret = scrub_supers(sdev);
1623         up_read(&fs_info->scrub_super_lock);
1624
1625         if (!ret)
1626                 ret = scrub_enumerate_chunks(sdev, start, end);
1627
1628         wait_event(sdev->list_wait, atomic_read(&sdev->in_flight) == 0);
1629         atomic_dec(&fs_info->scrubs_running);
1630         wake_up(&fs_info->scrub_pause_wait);
1631
1632         wait_event(sdev->list_wait, atomic_read(&sdev->fixup_cnt) == 0);
1633
1634         if (progress)
1635                 memcpy(progress, &sdev->stat, sizeof(*progress));
1636
1637         mutex_lock(&fs_info->scrub_lock);
1638         dev->scrub_device = NULL;
1639         mutex_unlock(&fs_info->scrub_lock);
1640
1641         scrub_free_dev(sdev);
1642         scrub_workers_put(root);
1643
1644         return ret;
1645 }
1646
1647 int btrfs_scrub_pause(struct btrfs_root *root)
1648 {
1649         struct btrfs_fs_info *fs_info = root->fs_info;
1650
1651         mutex_lock(&fs_info->scrub_lock);
1652         atomic_inc(&fs_info->scrub_pause_req);
1653         while (atomic_read(&fs_info->scrubs_paused) !=
1654                atomic_read(&fs_info->scrubs_running)) {
1655                 mutex_unlock(&fs_info->scrub_lock);
1656                 wait_event(fs_info->scrub_pause_wait,
1657                            atomic_read(&fs_info->scrubs_paused) ==
1658                            atomic_read(&fs_info->scrubs_running));
1659                 mutex_lock(&fs_info->scrub_lock);
1660         }
1661         mutex_unlock(&fs_info->scrub_lock);
1662
1663         return 0;
1664 }
1665
1666 int btrfs_scrub_continue(struct btrfs_root *root)
1667 {
1668         struct btrfs_fs_info *fs_info = root->fs_info;
1669
1670         atomic_dec(&fs_info->scrub_pause_req);
1671         wake_up(&fs_info->scrub_pause_wait);
1672         return 0;
1673 }
1674
1675 int btrfs_scrub_pause_super(struct btrfs_root *root)
1676 {
1677         down_write(&root->fs_info->scrub_super_lock);
1678         return 0;
1679 }
1680
1681 int btrfs_scrub_continue_super(struct btrfs_root *root)
1682 {
1683         up_write(&root->fs_info->scrub_super_lock);
1684         return 0;
1685 }
1686
1687 int btrfs_scrub_cancel(struct btrfs_root *root)
1688 {
1689         struct btrfs_fs_info *fs_info = root->fs_info;
1690
1691         mutex_lock(&fs_info->scrub_lock);
1692         if (!atomic_read(&fs_info->scrubs_running)) {
1693                 mutex_unlock(&fs_info->scrub_lock);
1694                 return -ENOTCONN;
1695         }
1696
1697         atomic_inc(&fs_info->scrub_cancel_req);
1698         while (atomic_read(&fs_info->scrubs_running)) {
1699                 mutex_unlock(&fs_info->scrub_lock);
1700                 wait_event(fs_info->scrub_pause_wait,
1701                            atomic_read(&fs_info->scrubs_running) == 0);
1702                 mutex_lock(&fs_info->scrub_lock);
1703         }
1704         atomic_dec(&fs_info->scrub_cancel_req);
1705         mutex_unlock(&fs_info->scrub_lock);
1706
1707         return 0;
1708 }
1709
1710 int btrfs_scrub_cancel_dev(struct btrfs_root *root, struct btrfs_device *dev)
1711 {
1712         struct btrfs_fs_info *fs_info = root->fs_info;
1713         struct scrub_dev *sdev;
1714
1715         mutex_lock(&fs_info->scrub_lock);
1716         sdev = dev->scrub_device;
1717         if (!sdev) {
1718                 mutex_unlock(&fs_info->scrub_lock);
1719                 return -ENOTCONN;
1720         }
1721         atomic_inc(&sdev->cancel_req);
1722         while (dev->scrub_device) {
1723                 mutex_unlock(&fs_info->scrub_lock);
1724                 wait_event(fs_info->scrub_pause_wait,
1725                            dev->scrub_device == NULL);
1726                 mutex_lock(&fs_info->scrub_lock);
1727         }
1728         mutex_unlock(&fs_info->scrub_lock);
1729
1730         return 0;
1731 }
1732
1733 int btrfs_scrub_cancel_devid(struct btrfs_root *root, u64 devid)
1734 {
1735         struct btrfs_fs_info *fs_info = root->fs_info;
1736         struct btrfs_device *dev;
1737         int ret;
1738
1739         /*
1740          * we have to hold the device_list_mutex here so the device
1741          * does not go away in cancel_dev. FIXME: find a better solution
1742          */
1743         mutex_lock(&fs_info->fs_devices->device_list_mutex);
1744         dev = btrfs_find_device(root, devid, NULL, NULL);
1745         if (!dev) {
1746                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1747                 return -ENODEV;
1748         }
1749         ret = btrfs_scrub_cancel_dev(root, dev);
1750         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1751
1752         return ret;
1753 }
1754
1755 int btrfs_scrub_progress(struct btrfs_root *root, u64 devid,
1756                          struct btrfs_scrub_progress *progress)
1757 {
1758         struct btrfs_device *dev;
1759         struct scrub_dev *sdev = NULL;
1760
1761         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1762         dev = btrfs_find_device(root, devid, NULL, NULL);
1763         if (dev)
1764                 sdev = dev->scrub_device;
1765         if (sdev)
1766                 memcpy(progress, &sdev->stat, sizeof(*progress));
1767         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1768
1769         return dev ? (sdev ? 0 : -ENOTCONN) : -ENODEV;
1770 }