Btrfs: RAID5 and RAID6
[linux-2.6-block.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 "dev-replace.h"
29 #include "check-integrity.h"
30 #include "rcu-string.h"
31 #include "raid56.h"
32
33 /*
34  * This is only the first step towards a full-features scrub. It reads all
35  * extent and super block and verifies the checksums. In case a bad checksum
36  * is found or the extent cannot be read, good data will be written back if
37  * any can be found.
38  *
39  * Future enhancements:
40  *  - In case an unrepairable extent is encountered, track which files are
41  *    affected and report them
42  *  - track and record media errors, throw out bad devices
43  *  - add a mode to also read unallocated space
44  */
45
46 struct scrub_block;
47 struct scrub_ctx;
48
49 /*
50  * the following three values only influence the performance.
51  * The last one configures the number of parallel and outstanding I/O
52  * operations. The first two values configure an upper limit for the number
53  * of (dynamically allocated) pages that are added to a bio.
54  */
55 #define SCRUB_PAGES_PER_RD_BIO  32      /* 128k per bio */
56 #define SCRUB_PAGES_PER_WR_BIO  32      /* 128k per bio */
57 #define SCRUB_BIOS_PER_SCTX     64      /* 8MB per device in flight */
58
59 /*
60  * the following value times PAGE_SIZE needs to be large enough to match the
61  * largest node/leaf/sector size that shall be supported.
62  * Values larger than BTRFS_STRIPE_LEN are not supported.
63  */
64 #define SCRUB_MAX_PAGES_PER_BLOCK       16      /* 64k per node/leaf/sector */
65
66 struct scrub_page {
67         struct scrub_block      *sblock;
68         struct page             *page;
69         struct btrfs_device     *dev;
70         u64                     flags;  /* extent flags */
71         u64                     generation;
72         u64                     logical;
73         u64                     physical;
74         u64                     physical_for_dev_replace;
75         atomic_t                ref_count;
76         struct {
77                 unsigned int    mirror_num:8;
78                 unsigned int    have_csum:1;
79                 unsigned int    io_error:1;
80         };
81         u8                      csum[BTRFS_CSUM_SIZE];
82 };
83
84 struct scrub_bio {
85         int                     index;
86         struct scrub_ctx        *sctx;
87         struct btrfs_device     *dev;
88         struct bio              *bio;
89         int                     err;
90         u64                     logical;
91         u64                     physical;
92 #if SCRUB_PAGES_PER_WR_BIO >= SCRUB_PAGES_PER_RD_BIO
93         struct scrub_page       *pagev[SCRUB_PAGES_PER_WR_BIO];
94 #else
95         struct scrub_page       *pagev[SCRUB_PAGES_PER_RD_BIO];
96 #endif
97         int                     page_count;
98         int                     next_free;
99         struct btrfs_work       work;
100 };
101
102 struct scrub_block {
103         struct scrub_page       *pagev[SCRUB_MAX_PAGES_PER_BLOCK];
104         int                     page_count;
105         atomic_t                outstanding_pages;
106         atomic_t                ref_count; /* free mem on transition to zero */
107         struct scrub_ctx        *sctx;
108         struct {
109                 unsigned int    header_error:1;
110                 unsigned int    checksum_error:1;
111                 unsigned int    no_io_error_seen:1;
112                 unsigned int    generation_error:1; /* also sets header_error */
113         };
114 };
115
116 struct scrub_wr_ctx {
117         struct scrub_bio *wr_curr_bio;
118         struct btrfs_device *tgtdev;
119         int pages_per_wr_bio; /* <= SCRUB_PAGES_PER_WR_BIO */
120         atomic_t flush_all_writes;
121         struct mutex wr_lock;
122 };
123
124 struct scrub_ctx {
125         struct scrub_bio        *bios[SCRUB_BIOS_PER_SCTX];
126         struct btrfs_root       *dev_root;
127         int                     first_free;
128         int                     curr;
129         atomic_t                bios_in_flight;
130         atomic_t                workers_pending;
131         spinlock_t              list_lock;
132         wait_queue_head_t       list_wait;
133         u16                     csum_size;
134         struct list_head        csum_list;
135         atomic_t                cancel_req;
136         int                     readonly;
137         int                     pages_per_rd_bio;
138         u32                     sectorsize;
139         u32                     nodesize;
140         u32                     leafsize;
141
142         int                     is_dev_replace;
143         struct scrub_wr_ctx     wr_ctx;
144
145         /*
146          * statistics
147          */
148         struct btrfs_scrub_progress stat;
149         spinlock_t              stat_lock;
150 };
151
152 struct scrub_fixup_nodatasum {
153         struct scrub_ctx        *sctx;
154         struct btrfs_device     *dev;
155         u64                     logical;
156         struct btrfs_root       *root;
157         struct btrfs_work       work;
158         int                     mirror_num;
159 };
160
161 struct scrub_copy_nocow_ctx {
162         struct scrub_ctx        *sctx;
163         u64                     logical;
164         u64                     len;
165         int                     mirror_num;
166         u64                     physical_for_dev_replace;
167         struct btrfs_work       work;
168 };
169
170 struct scrub_warning {
171         struct btrfs_path       *path;
172         u64                     extent_item_size;
173         char                    *scratch_buf;
174         char                    *msg_buf;
175         const char              *errstr;
176         sector_t                sector;
177         u64                     logical;
178         struct btrfs_device     *dev;
179         int                     msg_bufsize;
180         int                     scratch_bufsize;
181 };
182
183
184 static void scrub_pending_bio_inc(struct scrub_ctx *sctx);
185 static void scrub_pending_bio_dec(struct scrub_ctx *sctx);
186 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx);
187 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx);
188 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check);
189 static int scrub_setup_recheck_block(struct scrub_ctx *sctx,
190                                      struct btrfs_fs_info *fs_info,
191                                      struct scrub_block *original_sblock,
192                                      u64 length, u64 logical,
193                                      struct scrub_block *sblocks_for_recheck);
194 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
195                                 struct scrub_block *sblock, int is_metadata,
196                                 int have_csum, u8 *csum, u64 generation,
197                                 u16 csum_size);
198 static void scrub_recheck_block_checksum(struct btrfs_fs_info *fs_info,
199                                          struct scrub_block *sblock,
200                                          int is_metadata, int have_csum,
201                                          const u8 *csum, u64 generation,
202                                          u16 csum_size);
203 static void scrub_complete_bio_end_io(struct bio *bio, int err);
204 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
205                                              struct scrub_block *sblock_good,
206                                              int force_write);
207 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
208                                             struct scrub_block *sblock_good,
209                                             int page_num, int force_write);
210 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock);
211 static int scrub_write_page_to_dev_replace(struct scrub_block *sblock,
212                                            int page_num);
213 static int scrub_checksum_data(struct scrub_block *sblock);
214 static int scrub_checksum_tree_block(struct scrub_block *sblock);
215 static int scrub_checksum_super(struct scrub_block *sblock);
216 static void scrub_block_get(struct scrub_block *sblock);
217 static void scrub_block_put(struct scrub_block *sblock);
218 static void scrub_page_get(struct scrub_page *spage);
219 static void scrub_page_put(struct scrub_page *spage);
220 static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx,
221                                     struct scrub_page *spage);
222 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
223                        u64 physical, struct btrfs_device *dev, u64 flags,
224                        u64 gen, int mirror_num, u8 *csum, int force,
225                        u64 physical_for_dev_replace);
226 static void scrub_bio_end_io(struct bio *bio, int err);
227 static void scrub_bio_end_io_worker(struct btrfs_work *work);
228 static void scrub_block_complete(struct scrub_block *sblock);
229 static void scrub_remap_extent(struct btrfs_fs_info *fs_info,
230                                u64 extent_logical, u64 extent_len,
231                                u64 *extent_physical,
232                                struct btrfs_device **extent_dev,
233                                int *extent_mirror_num);
234 static int scrub_setup_wr_ctx(struct scrub_ctx *sctx,
235                               struct scrub_wr_ctx *wr_ctx,
236                               struct btrfs_fs_info *fs_info,
237                               struct btrfs_device *dev,
238                               int is_dev_replace);
239 static void scrub_free_wr_ctx(struct scrub_wr_ctx *wr_ctx);
240 static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx,
241                                     struct scrub_page *spage);
242 static void scrub_wr_submit(struct scrub_ctx *sctx);
243 static void scrub_wr_bio_end_io(struct bio *bio, int err);
244 static void scrub_wr_bio_end_io_worker(struct btrfs_work *work);
245 static int write_page_nocow(struct scrub_ctx *sctx,
246                             u64 physical_for_dev_replace, struct page *page);
247 static int copy_nocow_pages_for_inode(u64 inum, u64 offset, u64 root,
248                                       void *ctx);
249 static int copy_nocow_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
250                             int mirror_num, u64 physical_for_dev_replace);
251 static void copy_nocow_pages_worker(struct btrfs_work *work);
252
253
254 static void scrub_pending_bio_inc(struct scrub_ctx *sctx)
255 {
256         atomic_inc(&sctx->bios_in_flight);
257 }
258
259 static void scrub_pending_bio_dec(struct scrub_ctx *sctx)
260 {
261         atomic_dec(&sctx->bios_in_flight);
262         wake_up(&sctx->list_wait);
263 }
264
265 /*
266  * used for workers that require transaction commits (i.e., for the
267  * NOCOW case)
268  */
269 static void scrub_pending_trans_workers_inc(struct scrub_ctx *sctx)
270 {
271         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
272
273         /*
274          * increment scrubs_running to prevent cancel requests from
275          * completing as long as a worker is running. we must also
276          * increment scrubs_paused to prevent deadlocking on pause
277          * requests used for transactions commits (as the worker uses a
278          * transaction context). it is safe to regard the worker
279          * as paused for all matters practical. effectively, we only
280          * avoid cancellation requests from completing.
281          */
282         mutex_lock(&fs_info->scrub_lock);
283         atomic_inc(&fs_info->scrubs_running);
284         atomic_inc(&fs_info->scrubs_paused);
285         mutex_unlock(&fs_info->scrub_lock);
286         atomic_inc(&sctx->workers_pending);
287 }
288
289 /* used for workers that require transaction commits */
290 static void scrub_pending_trans_workers_dec(struct scrub_ctx *sctx)
291 {
292         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
293
294         /*
295          * see scrub_pending_trans_workers_inc() why we're pretending
296          * to be paused in the scrub counters
297          */
298         mutex_lock(&fs_info->scrub_lock);
299         atomic_dec(&fs_info->scrubs_running);
300         atomic_dec(&fs_info->scrubs_paused);
301         mutex_unlock(&fs_info->scrub_lock);
302         atomic_dec(&sctx->workers_pending);
303         wake_up(&fs_info->scrub_pause_wait);
304         wake_up(&sctx->list_wait);
305 }
306
307 static void scrub_free_csums(struct scrub_ctx *sctx)
308 {
309         while (!list_empty(&sctx->csum_list)) {
310                 struct btrfs_ordered_sum *sum;
311                 sum = list_first_entry(&sctx->csum_list,
312                                        struct btrfs_ordered_sum, list);
313                 list_del(&sum->list);
314                 kfree(sum);
315         }
316 }
317
318 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
319 {
320         int i;
321
322         if (!sctx)
323                 return;
324
325         scrub_free_wr_ctx(&sctx->wr_ctx);
326
327         /* this can happen when scrub is cancelled */
328         if (sctx->curr != -1) {
329                 struct scrub_bio *sbio = sctx->bios[sctx->curr];
330
331                 for (i = 0; i < sbio->page_count; i++) {
332                         WARN_ON(!sbio->pagev[i]->page);
333                         scrub_block_put(sbio->pagev[i]->sblock);
334                 }
335                 bio_put(sbio->bio);
336         }
337
338         for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
339                 struct scrub_bio *sbio = sctx->bios[i];
340
341                 if (!sbio)
342                         break;
343                 kfree(sbio);
344         }
345
346         scrub_free_csums(sctx);
347         kfree(sctx);
348 }
349
350 static noinline_for_stack
351 struct scrub_ctx *scrub_setup_ctx(struct btrfs_device *dev, int is_dev_replace)
352 {
353         struct scrub_ctx *sctx;
354         int             i;
355         struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
356         int pages_per_rd_bio;
357         int ret;
358
359         /*
360          * the setting of pages_per_rd_bio is correct for scrub but might
361          * be wrong for the dev_replace code where we might read from
362          * different devices in the initial huge bios. However, that
363          * code is able to correctly handle the case when adding a page
364          * to a bio fails.
365          */
366         if (dev->bdev)
367                 pages_per_rd_bio = min_t(int, SCRUB_PAGES_PER_RD_BIO,
368                                          bio_get_nr_vecs(dev->bdev));
369         else
370                 pages_per_rd_bio = SCRUB_PAGES_PER_RD_BIO;
371         sctx = kzalloc(sizeof(*sctx), GFP_NOFS);
372         if (!sctx)
373                 goto nomem;
374         sctx->is_dev_replace = is_dev_replace;
375         sctx->pages_per_rd_bio = pages_per_rd_bio;
376         sctx->curr = -1;
377         sctx->dev_root = dev->dev_root;
378         for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) {
379                 struct scrub_bio *sbio;
380
381                 sbio = kzalloc(sizeof(*sbio), GFP_NOFS);
382                 if (!sbio)
383                         goto nomem;
384                 sctx->bios[i] = sbio;
385
386                 sbio->index = i;
387                 sbio->sctx = sctx;
388                 sbio->page_count = 0;
389                 sbio->work.func = scrub_bio_end_io_worker;
390
391                 if (i != SCRUB_BIOS_PER_SCTX - 1)
392                         sctx->bios[i]->next_free = i + 1;
393                 else
394                         sctx->bios[i]->next_free = -1;
395         }
396         sctx->first_free = 0;
397         sctx->nodesize = dev->dev_root->nodesize;
398         sctx->leafsize = dev->dev_root->leafsize;
399         sctx->sectorsize = dev->dev_root->sectorsize;
400         atomic_set(&sctx->bios_in_flight, 0);
401         atomic_set(&sctx->workers_pending, 0);
402         atomic_set(&sctx->cancel_req, 0);
403         sctx->csum_size = btrfs_super_csum_size(fs_info->super_copy);
404         INIT_LIST_HEAD(&sctx->csum_list);
405
406         spin_lock_init(&sctx->list_lock);
407         spin_lock_init(&sctx->stat_lock);
408         init_waitqueue_head(&sctx->list_wait);
409
410         ret = scrub_setup_wr_ctx(sctx, &sctx->wr_ctx, fs_info,
411                                  fs_info->dev_replace.tgtdev, is_dev_replace);
412         if (ret) {
413                 scrub_free_ctx(sctx);
414                 return ERR_PTR(ret);
415         }
416         return sctx;
417
418 nomem:
419         scrub_free_ctx(sctx);
420         return ERR_PTR(-ENOMEM);
421 }
422
423 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root,
424                                      void *warn_ctx)
425 {
426         u64 isize;
427         u32 nlink;
428         int ret;
429         int i;
430         struct extent_buffer *eb;
431         struct btrfs_inode_item *inode_item;
432         struct scrub_warning *swarn = warn_ctx;
433         struct btrfs_fs_info *fs_info = swarn->dev->dev_root->fs_info;
434         struct inode_fs_paths *ipath = NULL;
435         struct btrfs_root *local_root;
436         struct btrfs_key root_key;
437
438         root_key.objectid = root;
439         root_key.type = BTRFS_ROOT_ITEM_KEY;
440         root_key.offset = (u64)-1;
441         local_root = btrfs_read_fs_root_no_name(fs_info, &root_key);
442         if (IS_ERR(local_root)) {
443                 ret = PTR_ERR(local_root);
444                 goto err;
445         }
446
447         ret = inode_item_info(inum, 0, local_root, swarn->path);
448         if (ret) {
449                 btrfs_release_path(swarn->path);
450                 goto err;
451         }
452
453         eb = swarn->path->nodes[0];
454         inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
455                                         struct btrfs_inode_item);
456         isize = btrfs_inode_size(eb, inode_item);
457         nlink = btrfs_inode_nlink(eb, inode_item);
458         btrfs_release_path(swarn->path);
459
460         ipath = init_ipath(4096, local_root, swarn->path);
461         if (IS_ERR(ipath)) {
462                 ret = PTR_ERR(ipath);
463                 ipath = NULL;
464                 goto err;
465         }
466         ret = paths_from_inode(inum, ipath);
467
468         if (ret < 0)
469                 goto err;
470
471         /*
472          * we deliberately ignore the bit ipath might have been too small to
473          * hold all of the paths here
474          */
475         for (i = 0; i < ipath->fspath->elem_cnt; ++i)
476                 printk_in_rcu(KERN_WARNING "btrfs: %s at logical %llu on dev "
477                         "%s, sector %llu, root %llu, inode %llu, offset %llu, "
478                         "length %llu, links %u (path: %s)\n", swarn->errstr,
479                         swarn->logical, rcu_str_deref(swarn->dev->name),
480                         (unsigned long long)swarn->sector, root, inum, offset,
481                         min(isize - offset, (u64)PAGE_SIZE), nlink,
482                         (char *)(unsigned long)ipath->fspath->val[i]);
483
484         free_ipath(ipath);
485         return 0;
486
487 err:
488         printk_in_rcu(KERN_WARNING "btrfs: %s at logical %llu on dev "
489                 "%s, sector %llu, root %llu, inode %llu, offset %llu: path "
490                 "resolving failed with ret=%d\n", swarn->errstr,
491                 swarn->logical, rcu_str_deref(swarn->dev->name),
492                 (unsigned long long)swarn->sector, root, inum, offset, ret);
493
494         free_ipath(ipath);
495         return 0;
496 }
497
498 static void scrub_print_warning(const char *errstr, struct scrub_block *sblock)
499 {
500         struct btrfs_device *dev;
501         struct btrfs_fs_info *fs_info;
502         struct btrfs_path *path;
503         struct btrfs_key found_key;
504         struct extent_buffer *eb;
505         struct btrfs_extent_item *ei;
506         struct scrub_warning swarn;
507         unsigned long ptr = 0;
508         u64 extent_item_pos;
509         u64 flags = 0;
510         u64 ref_root;
511         u32 item_size;
512         u8 ref_level;
513         const int bufsize = 4096;
514         int ret;
515
516         WARN_ON(sblock->page_count < 1);
517         dev = sblock->pagev[0]->dev;
518         fs_info = sblock->sctx->dev_root->fs_info;
519
520         path = btrfs_alloc_path();
521
522         swarn.scratch_buf = kmalloc(bufsize, GFP_NOFS);
523         swarn.msg_buf = kmalloc(bufsize, GFP_NOFS);
524         swarn.sector = (sblock->pagev[0]->physical) >> 9;
525         swarn.logical = sblock->pagev[0]->logical;
526         swarn.errstr = errstr;
527         swarn.dev = NULL;
528         swarn.msg_bufsize = bufsize;
529         swarn.scratch_bufsize = bufsize;
530
531         if (!path || !swarn.scratch_buf || !swarn.msg_buf)
532                 goto out;
533
534         ret = extent_from_logical(fs_info, swarn.logical, path, &found_key,
535                                   &flags);
536         if (ret < 0)
537                 goto out;
538
539         extent_item_pos = swarn.logical - found_key.objectid;
540         swarn.extent_item_size = found_key.offset;
541
542         eb = path->nodes[0];
543         ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
544         item_size = btrfs_item_size_nr(eb, path->slots[0]);
545         btrfs_release_path(path);
546
547         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
548                 do {
549                         ret = tree_backref_for_extent(&ptr, eb, ei, item_size,
550                                                         &ref_root, &ref_level);
551                         printk_in_rcu(KERN_WARNING
552                                 "btrfs: %s at logical %llu on dev %s, "
553                                 "sector %llu: metadata %s (level %d) in tree "
554                                 "%llu\n", errstr, swarn.logical,
555                                 rcu_str_deref(dev->name),
556                                 (unsigned long long)swarn.sector,
557                                 ref_level ? "node" : "leaf",
558                                 ret < 0 ? -1 : ref_level,
559                                 ret < 0 ? -1 : ref_root);
560                 } while (ret != 1);
561         } else {
562                 swarn.path = path;
563                 swarn.dev = dev;
564                 iterate_extent_inodes(fs_info, found_key.objectid,
565                                         extent_item_pos, 1,
566                                         scrub_print_warning_inode, &swarn);
567         }
568
569 out:
570         btrfs_free_path(path);
571         kfree(swarn.scratch_buf);
572         kfree(swarn.msg_buf);
573 }
574
575 static int scrub_fixup_readpage(u64 inum, u64 offset, u64 root, void *fixup_ctx)
576 {
577         struct page *page = NULL;
578         unsigned long index;
579         struct scrub_fixup_nodatasum *fixup = fixup_ctx;
580         int ret;
581         int corrected = 0;
582         struct btrfs_key key;
583         struct inode *inode = NULL;
584         u64 end = offset + PAGE_SIZE - 1;
585         struct btrfs_root *local_root;
586
587         key.objectid = root;
588         key.type = BTRFS_ROOT_ITEM_KEY;
589         key.offset = (u64)-1;
590         local_root = btrfs_read_fs_root_no_name(fixup->root->fs_info, &key);
591         if (IS_ERR(local_root))
592                 return PTR_ERR(local_root);
593
594         key.type = BTRFS_INODE_ITEM_KEY;
595         key.objectid = inum;
596         key.offset = 0;
597         inode = btrfs_iget(fixup->root->fs_info->sb, &key, local_root, NULL);
598         if (IS_ERR(inode))
599                 return PTR_ERR(inode);
600
601         index = offset >> PAGE_CACHE_SHIFT;
602
603         page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
604         if (!page) {
605                 ret = -ENOMEM;
606                 goto out;
607         }
608
609         if (PageUptodate(page)) {
610                 struct btrfs_fs_info *fs_info;
611                 if (PageDirty(page)) {
612                         /*
613                          * we need to write the data to the defect sector. the
614                          * data that was in that sector is not in memory,
615                          * because the page was modified. we must not write the
616                          * modified page to that sector.
617                          *
618                          * TODO: what could be done here: wait for the delalloc
619                          *       runner to write out that page (might involve
620                          *       COW) and see whether the sector is still
621                          *       referenced afterwards.
622                          *
623                          * For the meantime, we'll treat this error
624                          * incorrectable, although there is a chance that a
625                          * later scrub will find the bad sector again and that
626                          * there's no dirty page in memory, then.
627                          */
628                         ret = -EIO;
629                         goto out;
630                 }
631                 fs_info = BTRFS_I(inode)->root->fs_info;
632                 ret = repair_io_failure(fs_info, offset, PAGE_SIZE,
633                                         fixup->logical, page,
634                                         fixup->mirror_num);
635                 unlock_page(page);
636                 corrected = !ret;
637         } else {
638                 /*
639                  * we need to get good data first. the general readpage path
640                  * will call repair_io_failure for us, we just have to make
641                  * sure we read the bad mirror.
642                  */
643                 ret = set_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
644                                         EXTENT_DAMAGED, GFP_NOFS);
645                 if (ret) {
646                         /* set_extent_bits should give proper error */
647                         WARN_ON(ret > 0);
648                         if (ret > 0)
649                                 ret = -EFAULT;
650                         goto out;
651                 }
652
653                 ret = extent_read_full_page(&BTRFS_I(inode)->io_tree, page,
654                                                 btrfs_get_extent,
655                                                 fixup->mirror_num);
656                 wait_on_page_locked(page);
657
658                 corrected = !test_range_bit(&BTRFS_I(inode)->io_tree, offset,
659                                                 end, EXTENT_DAMAGED, 0, NULL);
660                 if (!corrected)
661                         clear_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
662                                                 EXTENT_DAMAGED, GFP_NOFS);
663         }
664
665 out:
666         if (page)
667                 put_page(page);
668         if (inode)
669                 iput(inode);
670
671         if (ret < 0)
672                 return ret;
673
674         if (ret == 0 && corrected) {
675                 /*
676                  * we only need to call readpage for one of the inodes belonging
677                  * to this extent. so make iterate_extent_inodes stop
678                  */
679                 return 1;
680         }
681
682         return -EIO;
683 }
684
685 static void scrub_fixup_nodatasum(struct btrfs_work *work)
686 {
687         int ret;
688         struct scrub_fixup_nodatasum *fixup;
689         struct scrub_ctx *sctx;
690         struct btrfs_trans_handle *trans = NULL;
691         struct btrfs_fs_info *fs_info;
692         struct btrfs_path *path;
693         int uncorrectable = 0;
694
695         fixup = container_of(work, struct scrub_fixup_nodatasum, work);
696         sctx = fixup->sctx;
697         fs_info = fixup->root->fs_info;
698
699         path = btrfs_alloc_path();
700         if (!path) {
701                 spin_lock(&sctx->stat_lock);
702                 ++sctx->stat.malloc_errors;
703                 spin_unlock(&sctx->stat_lock);
704                 uncorrectable = 1;
705                 goto out;
706         }
707
708         trans = btrfs_join_transaction(fixup->root);
709         if (IS_ERR(trans)) {
710                 uncorrectable = 1;
711                 goto out;
712         }
713
714         /*
715          * the idea is to trigger a regular read through the standard path. we
716          * read a page from the (failed) logical address by specifying the
717          * corresponding copynum of the failed sector. thus, that readpage is
718          * expected to fail.
719          * that is the point where on-the-fly error correction will kick in
720          * (once it's finished) and rewrite the failed sector if a good copy
721          * can be found.
722          */
723         ret = iterate_inodes_from_logical(fixup->logical, fixup->root->fs_info,
724                                                 path, scrub_fixup_readpage,
725                                                 fixup);
726         if (ret < 0) {
727                 uncorrectable = 1;
728                 goto out;
729         }
730         WARN_ON(ret != 1);
731
732         spin_lock(&sctx->stat_lock);
733         ++sctx->stat.corrected_errors;
734         spin_unlock(&sctx->stat_lock);
735
736 out:
737         if (trans && !IS_ERR(trans))
738                 btrfs_end_transaction(trans, fixup->root);
739         if (uncorrectable) {
740                 spin_lock(&sctx->stat_lock);
741                 ++sctx->stat.uncorrectable_errors;
742                 spin_unlock(&sctx->stat_lock);
743                 btrfs_dev_replace_stats_inc(
744                         &sctx->dev_root->fs_info->dev_replace.
745                         num_uncorrectable_read_errors);
746                 printk_ratelimited_in_rcu(KERN_ERR
747                         "btrfs: unable to fixup (nodatasum) error at logical %llu on dev %s\n",
748                         (unsigned long long)fixup->logical,
749                         rcu_str_deref(fixup->dev->name));
750         }
751
752         btrfs_free_path(path);
753         kfree(fixup);
754
755         scrub_pending_trans_workers_dec(sctx);
756 }
757
758 /*
759  * scrub_handle_errored_block gets called when either verification of the
760  * pages failed or the bio failed to read, e.g. with EIO. In the latter
761  * case, this function handles all pages in the bio, even though only one
762  * may be bad.
763  * The goal of this function is to repair the errored block by using the
764  * contents of one of the mirrors.
765  */
766 static int scrub_handle_errored_block(struct scrub_block *sblock_to_check)
767 {
768         struct scrub_ctx *sctx = sblock_to_check->sctx;
769         struct btrfs_device *dev;
770         struct btrfs_fs_info *fs_info;
771         u64 length;
772         u64 logical;
773         u64 generation;
774         unsigned int failed_mirror_index;
775         unsigned int is_metadata;
776         unsigned int have_csum;
777         u8 *csum;
778         struct scrub_block *sblocks_for_recheck; /* holds one for each mirror */
779         struct scrub_block *sblock_bad;
780         int ret;
781         int mirror_index;
782         int page_num;
783         int success;
784         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
785                                       DEFAULT_RATELIMIT_BURST);
786
787         BUG_ON(sblock_to_check->page_count < 1);
788         fs_info = sctx->dev_root->fs_info;
789         if (sblock_to_check->pagev[0]->flags & BTRFS_EXTENT_FLAG_SUPER) {
790                 /*
791                  * if we find an error in a super block, we just report it.
792                  * They will get written with the next transaction commit
793                  * anyway
794                  */
795                 spin_lock(&sctx->stat_lock);
796                 ++sctx->stat.super_errors;
797                 spin_unlock(&sctx->stat_lock);
798                 return 0;
799         }
800         length = sblock_to_check->page_count * PAGE_SIZE;
801         logical = sblock_to_check->pagev[0]->logical;
802         generation = sblock_to_check->pagev[0]->generation;
803         BUG_ON(sblock_to_check->pagev[0]->mirror_num < 1);
804         failed_mirror_index = sblock_to_check->pagev[0]->mirror_num - 1;
805         is_metadata = !(sblock_to_check->pagev[0]->flags &
806                         BTRFS_EXTENT_FLAG_DATA);
807         have_csum = sblock_to_check->pagev[0]->have_csum;
808         csum = sblock_to_check->pagev[0]->csum;
809         dev = sblock_to_check->pagev[0]->dev;
810
811         if (sctx->is_dev_replace && !is_metadata && !have_csum) {
812                 sblocks_for_recheck = NULL;
813                 goto nodatasum_case;
814         }
815
816         /*
817          * read all mirrors one after the other. This includes to
818          * re-read the extent or metadata block that failed (that was
819          * the cause that this fixup code is called) another time,
820          * page by page this time in order to know which pages
821          * caused I/O errors and which ones are good (for all mirrors).
822          * It is the goal to handle the situation when more than one
823          * mirror contains I/O errors, but the errors do not
824          * overlap, i.e. the data can be repaired by selecting the
825          * pages from those mirrors without I/O error on the
826          * particular pages. One example (with blocks >= 2 * PAGE_SIZE)
827          * would be that mirror #1 has an I/O error on the first page,
828          * the second page is good, and mirror #2 has an I/O error on
829          * the second page, but the first page is good.
830          * Then the first page of the first mirror can be repaired by
831          * taking the first page of the second mirror, and the
832          * second page of the second mirror can be repaired by
833          * copying the contents of the 2nd page of the 1st mirror.
834          * One more note: if the pages of one mirror contain I/O
835          * errors, the checksum cannot be verified. In order to get
836          * the best data for repairing, the first attempt is to find
837          * a mirror without I/O errors and with a validated checksum.
838          * Only if this is not possible, the pages are picked from
839          * mirrors with I/O errors without considering the checksum.
840          * If the latter is the case, at the end, the checksum of the
841          * repaired area is verified in order to correctly maintain
842          * the statistics.
843          */
844
845         sblocks_for_recheck = kzalloc(BTRFS_MAX_MIRRORS *
846                                      sizeof(*sblocks_for_recheck),
847                                      GFP_NOFS);
848         if (!sblocks_for_recheck) {
849                 spin_lock(&sctx->stat_lock);
850                 sctx->stat.malloc_errors++;
851                 sctx->stat.read_errors++;
852                 sctx->stat.uncorrectable_errors++;
853                 spin_unlock(&sctx->stat_lock);
854                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
855                 goto out;
856         }
857
858         /* setup the context, map the logical blocks and alloc the pages */
859         ret = scrub_setup_recheck_block(sctx, fs_info, sblock_to_check, length,
860                                         logical, sblocks_for_recheck);
861         if (ret) {
862                 spin_lock(&sctx->stat_lock);
863                 sctx->stat.read_errors++;
864                 sctx->stat.uncorrectable_errors++;
865                 spin_unlock(&sctx->stat_lock);
866                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
867                 goto out;
868         }
869         BUG_ON(failed_mirror_index >= BTRFS_MAX_MIRRORS);
870         sblock_bad = sblocks_for_recheck + failed_mirror_index;
871
872         /* build and submit the bios for the failed mirror, check checksums */
873         scrub_recheck_block(fs_info, sblock_bad, is_metadata, have_csum,
874                             csum, generation, sctx->csum_size);
875
876         if (!sblock_bad->header_error && !sblock_bad->checksum_error &&
877             sblock_bad->no_io_error_seen) {
878                 /*
879                  * the error disappeared after reading page by page, or
880                  * the area was part of a huge bio and other parts of the
881                  * bio caused I/O errors, or the block layer merged several
882                  * read requests into one and the error is caused by a
883                  * different bio (usually one of the two latter cases is
884                  * the cause)
885                  */
886                 spin_lock(&sctx->stat_lock);
887                 sctx->stat.unverified_errors++;
888                 spin_unlock(&sctx->stat_lock);
889
890                 if (sctx->is_dev_replace)
891                         scrub_write_block_to_dev_replace(sblock_bad);
892                 goto out;
893         }
894
895         if (!sblock_bad->no_io_error_seen) {
896                 spin_lock(&sctx->stat_lock);
897                 sctx->stat.read_errors++;
898                 spin_unlock(&sctx->stat_lock);
899                 if (__ratelimit(&_rs))
900                         scrub_print_warning("i/o error", sblock_to_check);
901                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
902         } else if (sblock_bad->checksum_error) {
903                 spin_lock(&sctx->stat_lock);
904                 sctx->stat.csum_errors++;
905                 spin_unlock(&sctx->stat_lock);
906                 if (__ratelimit(&_rs))
907                         scrub_print_warning("checksum error", sblock_to_check);
908                 btrfs_dev_stat_inc_and_print(dev,
909                                              BTRFS_DEV_STAT_CORRUPTION_ERRS);
910         } else if (sblock_bad->header_error) {
911                 spin_lock(&sctx->stat_lock);
912                 sctx->stat.verify_errors++;
913                 spin_unlock(&sctx->stat_lock);
914                 if (__ratelimit(&_rs))
915                         scrub_print_warning("checksum/header error",
916                                             sblock_to_check);
917                 if (sblock_bad->generation_error)
918                         btrfs_dev_stat_inc_and_print(dev,
919                                 BTRFS_DEV_STAT_GENERATION_ERRS);
920                 else
921                         btrfs_dev_stat_inc_and_print(dev,
922                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
923         }
924
925         if (sctx->readonly && !sctx->is_dev_replace)
926                 goto did_not_correct_error;
927
928         if (!is_metadata && !have_csum) {
929                 struct scrub_fixup_nodatasum *fixup_nodatasum;
930
931 nodatasum_case:
932                 WARN_ON(sctx->is_dev_replace);
933
934                 /*
935                  * !is_metadata and !have_csum, this means that the data
936                  * might not be COW'ed, that it might be modified
937                  * concurrently. The general strategy to work on the
938                  * commit root does not help in the case when COW is not
939                  * used.
940                  */
941                 fixup_nodatasum = kzalloc(sizeof(*fixup_nodatasum), GFP_NOFS);
942                 if (!fixup_nodatasum)
943                         goto did_not_correct_error;
944                 fixup_nodatasum->sctx = sctx;
945                 fixup_nodatasum->dev = dev;
946                 fixup_nodatasum->logical = logical;
947                 fixup_nodatasum->root = fs_info->extent_root;
948                 fixup_nodatasum->mirror_num = failed_mirror_index + 1;
949                 scrub_pending_trans_workers_inc(sctx);
950                 fixup_nodatasum->work.func = scrub_fixup_nodatasum;
951                 btrfs_queue_worker(&fs_info->scrub_workers,
952                                    &fixup_nodatasum->work);
953                 goto out;
954         }
955
956         /*
957          * now build and submit the bios for the other mirrors, check
958          * checksums.
959          * First try to pick the mirror which is completely without I/O
960          * errors and also does not have a checksum error.
961          * If one is found, and if a checksum is present, the full block
962          * that is known to contain an error is rewritten. Afterwards
963          * the block is known to be corrected.
964          * If a mirror is found which is completely correct, and no
965          * checksum is present, only those pages are rewritten that had
966          * an I/O error in the block to be repaired, since it cannot be
967          * determined, which copy of the other pages is better (and it
968          * could happen otherwise that a correct page would be
969          * overwritten by a bad one).
970          */
971         for (mirror_index = 0;
972              mirror_index < BTRFS_MAX_MIRRORS &&
973              sblocks_for_recheck[mirror_index].page_count > 0;
974              mirror_index++) {
975                 struct scrub_block *sblock_other;
976
977                 if (mirror_index == failed_mirror_index)
978                         continue;
979                 sblock_other = sblocks_for_recheck + mirror_index;
980
981                 /* build and submit the bios, check checksums */
982                 scrub_recheck_block(fs_info, sblock_other, is_metadata,
983                                     have_csum, csum, generation,
984                                     sctx->csum_size);
985
986                 if (!sblock_other->header_error &&
987                     !sblock_other->checksum_error &&
988                     sblock_other->no_io_error_seen) {
989                         if (sctx->is_dev_replace) {
990                                 scrub_write_block_to_dev_replace(sblock_other);
991                         } else {
992                                 int force_write = is_metadata || have_csum;
993
994                                 ret = scrub_repair_block_from_good_copy(
995                                                 sblock_bad, sblock_other,
996                                                 force_write);
997                         }
998                         if (0 == ret)
999                                 goto corrected_error;
1000                 }
1001         }
1002
1003         /*
1004          * for dev_replace, pick good pages and write to the target device.
1005          */
1006         if (sctx->is_dev_replace) {
1007                 success = 1;
1008                 for (page_num = 0; page_num < sblock_bad->page_count;
1009                      page_num++) {
1010                         int sub_success;
1011
1012                         sub_success = 0;
1013                         for (mirror_index = 0;
1014                              mirror_index < BTRFS_MAX_MIRRORS &&
1015                              sblocks_for_recheck[mirror_index].page_count > 0;
1016                              mirror_index++) {
1017                                 struct scrub_block *sblock_other =
1018                                         sblocks_for_recheck + mirror_index;
1019                                 struct scrub_page *page_other =
1020                                         sblock_other->pagev[page_num];
1021
1022                                 if (!page_other->io_error) {
1023                                         ret = scrub_write_page_to_dev_replace(
1024                                                         sblock_other, page_num);
1025                                         if (ret == 0) {
1026                                                 /* succeeded for this page */
1027                                                 sub_success = 1;
1028                                                 break;
1029                                         } else {
1030                                                 btrfs_dev_replace_stats_inc(
1031                                                         &sctx->dev_root->
1032                                                         fs_info->dev_replace.
1033                                                         num_write_errors);
1034                                         }
1035                                 }
1036                         }
1037
1038                         if (!sub_success) {
1039                                 /*
1040                                  * did not find a mirror to fetch the page
1041                                  * from. scrub_write_page_to_dev_replace()
1042                                  * handles this case (page->io_error), by
1043                                  * filling the block with zeros before
1044                                  * submitting the write request
1045                                  */
1046                                 success = 0;
1047                                 ret = scrub_write_page_to_dev_replace(
1048                                                 sblock_bad, page_num);
1049                                 if (ret)
1050                                         btrfs_dev_replace_stats_inc(
1051                                                 &sctx->dev_root->fs_info->
1052                                                 dev_replace.num_write_errors);
1053                         }
1054                 }
1055
1056                 goto out;
1057         }
1058
1059         /*
1060          * for regular scrub, repair those pages that are errored.
1061          * In case of I/O errors in the area that is supposed to be
1062          * repaired, continue by picking good copies of those pages.
1063          * Select the good pages from mirrors to rewrite bad pages from
1064          * the area to fix. Afterwards verify the checksum of the block
1065          * that is supposed to be repaired. This verification step is
1066          * only done for the purpose of statistic counting and for the
1067          * final scrub report, whether errors remain.
1068          * A perfect algorithm could make use of the checksum and try
1069          * all possible combinations of pages from the different mirrors
1070          * until the checksum verification succeeds. For example, when
1071          * the 2nd page of mirror #1 faces I/O errors, and the 2nd page
1072          * of mirror #2 is readable but the final checksum test fails,
1073          * then the 2nd page of mirror #3 could be tried, whether now
1074          * the final checksum succeedes. But this would be a rare
1075          * exception and is therefore not implemented. At least it is
1076          * avoided that the good copy is overwritten.
1077          * A more useful improvement would be to pick the sectors
1078          * without I/O error based on sector sizes (512 bytes on legacy
1079          * disks) instead of on PAGE_SIZE. Then maybe 512 byte of one
1080          * mirror could be repaired by taking 512 byte of a different
1081          * mirror, even if other 512 byte sectors in the same PAGE_SIZE
1082          * area are unreadable.
1083          */
1084
1085         /* can only fix I/O errors from here on */
1086         if (sblock_bad->no_io_error_seen)
1087                 goto did_not_correct_error;
1088
1089         success = 1;
1090         for (page_num = 0; page_num < sblock_bad->page_count; page_num++) {
1091                 struct scrub_page *page_bad = sblock_bad->pagev[page_num];
1092
1093                 if (!page_bad->io_error)
1094                         continue;
1095
1096                 for (mirror_index = 0;
1097                      mirror_index < BTRFS_MAX_MIRRORS &&
1098                      sblocks_for_recheck[mirror_index].page_count > 0;
1099                      mirror_index++) {
1100                         struct scrub_block *sblock_other = sblocks_for_recheck +
1101                                                            mirror_index;
1102                         struct scrub_page *page_other = sblock_other->pagev[
1103                                                         page_num];
1104
1105                         if (!page_other->io_error) {
1106                                 ret = scrub_repair_page_from_good_copy(
1107                                         sblock_bad, sblock_other, page_num, 0);
1108                                 if (0 == ret) {
1109                                         page_bad->io_error = 0;
1110                                         break; /* succeeded for this page */
1111                                 }
1112                         }
1113                 }
1114
1115                 if (page_bad->io_error) {
1116                         /* did not find a mirror to copy the page from */
1117                         success = 0;
1118                 }
1119         }
1120
1121         if (success) {
1122                 if (is_metadata || have_csum) {
1123                         /*
1124                          * need to verify the checksum now that all
1125                          * sectors on disk are repaired (the write
1126                          * request for data to be repaired is on its way).
1127                          * Just be lazy and use scrub_recheck_block()
1128                          * which re-reads the data before the checksum
1129                          * is verified, but most likely the data comes out
1130                          * of the page cache.
1131                          */
1132                         scrub_recheck_block(fs_info, sblock_bad,
1133                                             is_metadata, have_csum, csum,
1134                                             generation, sctx->csum_size);
1135                         if (!sblock_bad->header_error &&
1136                             !sblock_bad->checksum_error &&
1137                             sblock_bad->no_io_error_seen)
1138                                 goto corrected_error;
1139                         else
1140                                 goto did_not_correct_error;
1141                 } else {
1142 corrected_error:
1143                         spin_lock(&sctx->stat_lock);
1144                         sctx->stat.corrected_errors++;
1145                         spin_unlock(&sctx->stat_lock);
1146                         printk_ratelimited_in_rcu(KERN_ERR
1147                                 "btrfs: fixed up error at logical %llu on dev %s\n",
1148                                 (unsigned long long)logical,
1149                                 rcu_str_deref(dev->name));
1150                 }
1151         } else {
1152 did_not_correct_error:
1153                 spin_lock(&sctx->stat_lock);
1154                 sctx->stat.uncorrectable_errors++;
1155                 spin_unlock(&sctx->stat_lock);
1156                 printk_ratelimited_in_rcu(KERN_ERR
1157                         "btrfs: unable to fixup (regular) error at logical %llu on dev %s\n",
1158                         (unsigned long long)logical,
1159                         rcu_str_deref(dev->name));
1160         }
1161
1162 out:
1163         if (sblocks_for_recheck) {
1164                 for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS;
1165                      mirror_index++) {
1166                         struct scrub_block *sblock = sblocks_for_recheck +
1167                                                      mirror_index;
1168                         int page_index;
1169
1170                         for (page_index = 0; page_index < sblock->page_count;
1171                              page_index++) {
1172                                 sblock->pagev[page_index]->sblock = NULL;
1173                                 scrub_page_put(sblock->pagev[page_index]);
1174                         }
1175                 }
1176                 kfree(sblocks_for_recheck);
1177         }
1178
1179         return 0;
1180 }
1181
1182 static int scrub_setup_recheck_block(struct scrub_ctx *sctx,
1183                                      struct btrfs_fs_info *fs_info,
1184                                      struct scrub_block *original_sblock,
1185                                      u64 length, u64 logical,
1186                                      struct scrub_block *sblocks_for_recheck)
1187 {
1188         int page_index;
1189         int mirror_index;
1190         int ret;
1191
1192         /*
1193          * note: the two members ref_count and outstanding_pages
1194          * are not used (and not set) in the blocks that are used for
1195          * the recheck procedure
1196          */
1197
1198         page_index = 0;
1199         while (length > 0) {
1200                 u64 sublen = min_t(u64, length, PAGE_SIZE);
1201                 u64 mapped_length = sublen;
1202                 struct btrfs_bio *bbio = NULL;
1203
1204                 /*
1205                  * with a length of PAGE_SIZE, each returned stripe
1206                  * represents one mirror
1207                  */
1208                 ret = btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS, logical,
1209                                       &mapped_length, &bbio, 0);
1210                 if (ret || !bbio || mapped_length < sublen) {
1211                         kfree(bbio);
1212                         return -EIO;
1213                 }
1214
1215                 BUG_ON(page_index >= SCRUB_PAGES_PER_RD_BIO);
1216                 for (mirror_index = 0; mirror_index < (int)bbio->num_stripes;
1217                      mirror_index++) {
1218                         struct scrub_block *sblock;
1219                         struct scrub_page *page;
1220
1221                         if (mirror_index >= BTRFS_MAX_MIRRORS)
1222                                 continue;
1223
1224                         sblock = sblocks_for_recheck + mirror_index;
1225                         sblock->sctx = sctx;
1226                         page = kzalloc(sizeof(*page), GFP_NOFS);
1227                         if (!page) {
1228 leave_nomem:
1229                                 spin_lock(&sctx->stat_lock);
1230                                 sctx->stat.malloc_errors++;
1231                                 spin_unlock(&sctx->stat_lock);
1232                                 kfree(bbio);
1233                                 return -ENOMEM;
1234                         }
1235                         scrub_page_get(page);
1236                         sblock->pagev[page_index] = page;
1237                         page->logical = logical;
1238                         page->physical = bbio->stripes[mirror_index].physical;
1239                         BUG_ON(page_index >= original_sblock->page_count);
1240                         page->physical_for_dev_replace =
1241                                 original_sblock->pagev[page_index]->
1242                                 physical_for_dev_replace;
1243                         /* for missing devices, dev->bdev is NULL */
1244                         page->dev = bbio->stripes[mirror_index].dev;
1245                         page->mirror_num = mirror_index + 1;
1246                         sblock->page_count++;
1247                         page->page = alloc_page(GFP_NOFS);
1248                         if (!page->page)
1249                                 goto leave_nomem;
1250                 }
1251                 kfree(bbio);
1252                 length -= sublen;
1253                 logical += sublen;
1254                 page_index++;
1255         }
1256
1257         return 0;
1258 }
1259
1260 /*
1261  * this function will check the on disk data for checksum errors, header
1262  * errors and read I/O errors. If any I/O errors happen, the exact pages
1263  * which are errored are marked as being bad. The goal is to enable scrub
1264  * to take those pages that are not errored from all the mirrors so that
1265  * the pages that are errored in the just handled mirror can be repaired.
1266  */
1267 static void scrub_recheck_block(struct btrfs_fs_info *fs_info,
1268                                 struct scrub_block *sblock, int is_metadata,
1269                                 int have_csum, u8 *csum, u64 generation,
1270                                 u16 csum_size)
1271 {
1272         int page_num;
1273
1274         sblock->no_io_error_seen = 1;
1275         sblock->header_error = 0;
1276         sblock->checksum_error = 0;
1277
1278         for (page_num = 0; page_num < sblock->page_count; page_num++) {
1279                 struct bio *bio;
1280                 struct scrub_page *page = sblock->pagev[page_num];
1281                 DECLARE_COMPLETION_ONSTACK(complete);
1282
1283                 if (page->dev->bdev == NULL) {
1284                         page->io_error = 1;
1285                         sblock->no_io_error_seen = 0;
1286                         continue;
1287                 }
1288
1289                 WARN_ON(!page->page);
1290                 bio = bio_alloc(GFP_NOFS, 1);
1291                 if (!bio) {
1292                         page->io_error = 1;
1293                         sblock->no_io_error_seen = 0;
1294                         continue;
1295                 }
1296                 bio->bi_bdev = page->dev->bdev;
1297                 bio->bi_sector = page->physical >> 9;
1298                 bio->bi_end_io = scrub_complete_bio_end_io;
1299                 bio->bi_private = &complete;
1300
1301                 bio_add_page(bio, page->page, PAGE_SIZE, 0);
1302                 btrfsic_submit_bio(READ, bio);
1303
1304                 /* this will also unplug the queue */
1305                 wait_for_completion(&complete);
1306
1307                 page->io_error = !test_bit(BIO_UPTODATE, &bio->bi_flags);
1308                 if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
1309                         sblock->no_io_error_seen = 0;
1310                 bio_put(bio);
1311         }
1312
1313         if (sblock->no_io_error_seen)
1314                 scrub_recheck_block_checksum(fs_info, sblock, is_metadata,
1315                                              have_csum, csum, generation,
1316                                              csum_size);
1317
1318         return;
1319 }
1320
1321 static void scrub_recheck_block_checksum(struct btrfs_fs_info *fs_info,
1322                                          struct scrub_block *sblock,
1323                                          int is_metadata, int have_csum,
1324                                          const u8 *csum, u64 generation,
1325                                          u16 csum_size)
1326 {
1327         int page_num;
1328         u8 calculated_csum[BTRFS_CSUM_SIZE];
1329         u32 crc = ~(u32)0;
1330         struct btrfs_root *root = fs_info->extent_root;
1331         void *mapped_buffer;
1332
1333         WARN_ON(!sblock->pagev[0]->page);
1334         if (is_metadata) {
1335                 struct btrfs_header *h;
1336
1337                 mapped_buffer = kmap_atomic(sblock->pagev[0]->page);
1338                 h = (struct btrfs_header *)mapped_buffer;
1339
1340                 if (sblock->pagev[0]->logical != le64_to_cpu(h->bytenr) ||
1341                     memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE) ||
1342                     memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
1343                            BTRFS_UUID_SIZE)) {
1344                         sblock->header_error = 1;
1345                 } else if (generation != le64_to_cpu(h->generation)) {
1346                         sblock->header_error = 1;
1347                         sblock->generation_error = 1;
1348                 }
1349                 csum = h->csum;
1350         } else {
1351                 if (!have_csum)
1352                         return;
1353
1354                 mapped_buffer = kmap_atomic(sblock->pagev[0]->page);
1355         }
1356
1357         for (page_num = 0;;) {
1358                 if (page_num == 0 && is_metadata)
1359                         crc = btrfs_csum_data(root,
1360                                 ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE,
1361                                 crc, PAGE_SIZE - BTRFS_CSUM_SIZE);
1362                 else
1363                         crc = btrfs_csum_data(root, mapped_buffer, crc,
1364                                               PAGE_SIZE);
1365
1366                 kunmap_atomic(mapped_buffer);
1367                 page_num++;
1368                 if (page_num >= sblock->page_count)
1369                         break;
1370                 WARN_ON(!sblock->pagev[page_num]->page);
1371
1372                 mapped_buffer = kmap_atomic(sblock->pagev[page_num]->page);
1373         }
1374
1375         btrfs_csum_final(crc, calculated_csum);
1376         if (memcmp(calculated_csum, csum, csum_size))
1377                 sblock->checksum_error = 1;
1378 }
1379
1380 static void scrub_complete_bio_end_io(struct bio *bio, int err)
1381 {
1382         complete((struct completion *)bio->bi_private);
1383 }
1384
1385 static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad,
1386                                              struct scrub_block *sblock_good,
1387                                              int force_write)
1388 {
1389         int page_num;
1390         int ret = 0;
1391
1392         for (page_num = 0; page_num < sblock_bad->page_count; page_num++) {
1393                 int ret_sub;
1394
1395                 ret_sub = scrub_repair_page_from_good_copy(sblock_bad,
1396                                                            sblock_good,
1397                                                            page_num,
1398                                                            force_write);
1399                 if (ret_sub)
1400                         ret = ret_sub;
1401         }
1402
1403         return ret;
1404 }
1405
1406 static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad,
1407                                             struct scrub_block *sblock_good,
1408                                             int page_num, int force_write)
1409 {
1410         struct scrub_page *page_bad = sblock_bad->pagev[page_num];
1411         struct scrub_page *page_good = sblock_good->pagev[page_num];
1412
1413         BUG_ON(page_bad->page == NULL);
1414         BUG_ON(page_good->page == NULL);
1415         if (force_write || sblock_bad->header_error ||
1416             sblock_bad->checksum_error || page_bad->io_error) {
1417                 struct bio *bio;
1418                 int ret;
1419                 DECLARE_COMPLETION_ONSTACK(complete);
1420
1421                 if (!page_bad->dev->bdev) {
1422                         printk_ratelimited(KERN_WARNING
1423                                 "btrfs: scrub_repair_page_from_good_copy(bdev == NULL) is unexpected!\n");
1424                         return -EIO;
1425                 }
1426
1427                 bio = bio_alloc(GFP_NOFS, 1);
1428                 if (!bio)
1429                         return -EIO;
1430                 bio->bi_bdev = page_bad->dev->bdev;
1431                 bio->bi_sector = page_bad->physical >> 9;
1432                 bio->bi_end_io = scrub_complete_bio_end_io;
1433                 bio->bi_private = &complete;
1434
1435                 ret = bio_add_page(bio, page_good->page, PAGE_SIZE, 0);
1436                 if (PAGE_SIZE != ret) {
1437                         bio_put(bio);
1438                         return -EIO;
1439                 }
1440                 btrfsic_submit_bio(WRITE, bio);
1441
1442                 /* this will also unplug the queue */
1443                 wait_for_completion(&complete);
1444                 if (!bio_flagged(bio, BIO_UPTODATE)) {
1445                         btrfs_dev_stat_inc_and_print(page_bad->dev,
1446                                 BTRFS_DEV_STAT_WRITE_ERRS);
1447                         btrfs_dev_replace_stats_inc(
1448                                 &sblock_bad->sctx->dev_root->fs_info->
1449                                 dev_replace.num_write_errors);
1450                         bio_put(bio);
1451                         return -EIO;
1452                 }
1453                 bio_put(bio);
1454         }
1455
1456         return 0;
1457 }
1458
1459 static void scrub_write_block_to_dev_replace(struct scrub_block *sblock)
1460 {
1461         int page_num;
1462
1463         for (page_num = 0; page_num < sblock->page_count; page_num++) {
1464                 int ret;
1465
1466                 ret = scrub_write_page_to_dev_replace(sblock, page_num);
1467                 if (ret)
1468                         btrfs_dev_replace_stats_inc(
1469                                 &sblock->sctx->dev_root->fs_info->dev_replace.
1470                                 num_write_errors);
1471         }
1472 }
1473
1474 static int scrub_write_page_to_dev_replace(struct scrub_block *sblock,
1475                                            int page_num)
1476 {
1477         struct scrub_page *spage = sblock->pagev[page_num];
1478
1479         BUG_ON(spage->page == NULL);
1480         if (spage->io_error) {
1481                 void *mapped_buffer = kmap_atomic(spage->page);
1482
1483                 memset(mapped_buffer, 0, PAGE_CACHE_SIZE);
1484                 flush_dcache_page(spage->page);
1485                 kunmap_atomic(mapped_buffer);
1486         }
1487         return scrub_add_page_to_wr_bio(sblock->sctx, spage);
1488 }
1489
1490 static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx,
1491                                     struct scrub_page *spage)
1492 {
1493         struct scrub_wr_ctx *wr_ctx = &sctx->wr_ctx;
1494         struct scrub_bio *sbio;
1495         int ret;
1496
1497         mutex_lock(&wr_ctx->wr_lock);
1498 again:
1499         if (!wr_ctx->wr_curr_bio) {
1500                 wr_ctx->wr_curr_bio = kzalloc(sizeof(*wr_ctx->wr_curr_bio),
1501                                               GFP_NOFS);
1502                 if (!wr_ctx->wr_curr_bio) {
1503                         mutex_unlock(&wr_ctx->wr_lock);
1504                         return -ENOMEM;
1505                 }
1506                 wr_ctx->wr_curr_bio->sctx = sctx;
1507                 wr_ctx->wr_curr_bio->page_count = 0;
1508         }
1509         sbio = wr_ctx->wr_curr_bio;
1510         if (sbio->page_count == 0) {
1511                 struct bio *bio;
1512
1513                 sbio->physical = spage->physical_for_dev_replace;
1514                 sbio->logical = spage->logical;
1515                 sbio->dev = wr_ctx->tgtdev;
1516                 bio = sbio->bio;
1517                 if (!bio) {
1518                         bio = bio_alloc(GFP_NOFS, wr_ctx->pages_per_wr_bio);
1519                         if (!bio) {
1520                                 mutex_unlock(&wr_ctx->wr_lock);
1521                                 return -ENOMEM;
1522                         }
1523                         sbio->bio = bio;
1524                 }
1525
1526                 bio->bi_private = sbio;
1527                 bio->bi_end_io = scrub_wr_bio_end_io;
1528                 bio->bi_bdev = sbio->dev->bdev;
1529                 bio->bi_sector = sbio->physical >> 9;
1530                 sbio->err = 0;
1531         } else if (sbio->physical + sbio->page_count * PAGE_SIZE !=
1532                    spage->physical_for_dev_replace ||
1533                    sbio->logical + sbio->page_count * PAGE_SIZE !=
1534                    spage->logical) {
1535                 scrub_wr_submit(sctx);
1536                 goto again;
1537         }
1538
1539         ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0);
1540         if (ret != PAGE_SIZE) {
1541                 if (sbio->page_count < 1) {
1542                         bio_put(sbio->bio);
1543                         sbio->bio = NULL;
1544                         mutex_unlock(&wr_ctx->wr_lock);
1545                         return -EIO;
1546                 }
1547                 scrub_wr_submit(sctx);
1548                 goto again;
1549         }
1550
1551         sbio->pagev[sbio->page_count] = spage;
1552         scrub_page_get(spage);
1553         sbio->page_count++;
1554         if (sbio->page_count == wr_ctx->pages_per_wr_bio)
1555                 scrub_wr_submit(sctx);
1556         mutex_unlock(&wr_ctx->wr_lock);
1557
1558         return 0;
1559 }
1560
1561 static void scrub_wr_submit(struct scrub_ctx *sctx)
1562 {
1563         struct scrub_wr_ctx *wr_ctx = &sctx->wr_ctx;
1564         struct scrub_bio *sbio;
1565
1566         if (!wr_ctx->wr_curr_bio)
1567                 return;
1568
1569         sbio = wr_ctx->wr_curr_bio;
1570         wr_ctx->wr_curr_bio = NULL;
1571         WARN_ON(!sbio->bio->bi_bdev);
1572         scrub_pending_bio_inc(sctx);
1573         /* process all writes in a single worker thread. Then the block layer
1574          * orders the requests before sending them to the driver which
1575          * doubled the write performance on spinning disks when measured
1576          * with Linux 3.5 */
1577         btrfsic_submit_bio(WRITE, sbio->bio);
1578 }
1579
1580 static void scrub_wr_bio_end_io(struct bio *bio, int err)
1581 {
1582         struct scrub_bio *sbio = bio->bi_private;
1583         struct btrfs_fs_info *fs_info = sbio->dev->dev_root->fs_info;
1584
1585         sbio->err = err;
1586         sbio->bio = bio;
1587
1588         sbio->work.func = scrub_wr_bio_end_io_worker;
1589         btrfs_queue_worker(&fs_info->scrub_wr_completion_workers, &sbio->work);
1590 }
1591
1592 static void scrub_wr_bio_end_io_worker(struct btrfs_work *work)
1593 {
1594         struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
1595         struct scrub_ctx *sctx = sbio->sctx;
1596         int i;
1597
1598         WARN_ON(sbio->page_count > SCRUB_PAGES_PER_WR_BIO);
1599         if (sbio->err) {
1600                 struct btrfs_dev_replace *dev_replace =
1601                         &sbio->sctx->dev_root->fs_info->dev_replace;
1602
1603                 for (i = 0; i < sbio->page_count; i++) {
1604                         struct scrub_page *spage = sbio->pagev[i];
1605
1606                         spage->io_error = 1;
1607                         btrfs_dev_replace_stats_inc(&dev_replace->
1608                                                     num_write_errors);
1609                 }
1610         }
1611
1612         for (i = 0; i < sbio->page_count; i++)
1613                 scrub_page_put(sbio->pagev[i]);
1614
1615         bio_put(sbio->bio);
1616         kfree(sbio);
1617         scrub_pending_bio_dec(sctx);
1618 }
1619
1620 static int scrub_checksum(struct scrub_block *sblock)
1621 {
1622         u64 flags;
1623         int ret;
1624
1625         WARN_ON(sblock->page_count < 1);
1626         flags = sblock->pagev[0]->flags;
1627         ret = 0;
1628         if (flags & BTRFS_EXTENT_FLAG_DATA)
1629                 ret = scrub_checksum_data(sblock);
1630         else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1631                 ret = scrub_checksum_tree_block(sblock);
1632         else if (flags & BTRFS_EXTENT_FLAG_SUPER)
1633                 (void)scrub_checksum_super(sblock);
1634         else
1635                 WARN_ON(1);
1636         if (ret)
1637                 scrub_handle_errored_block(sblock);
1638
1639         return ret;
1640 }
1641
1642 static int scrub_checksum_data(struct scrub_block *sblock)
1643 {
1644         struct scrub_ctx *sctx = sblock->sctx;
1645         u8 csum[BTRFS_CSUM_SIZE];
1646         u8 *on_disk_csum;
1647         struct page *page;
1648         void *buffer;
1649         u32 crc = ~(u32)0;
1650         int fail = 0;
1651         struct btrfs_root *root = sctx->dev_root;
1652         u64 len;
1653         int index;
1654
1655         BUG_ON(sblock->page_count < 1);
1656         if (!sblock->pagev[0]->have_csum)
1657                 return 0;
1658
1659         on_disk_csum = sblock->pagev[0]->csum;
1660         page = sblock->pagev[0]->page;
1661         buffer = kmap_atomic(page);
1662
1663         len = sctx->sectorsize;
1664         index = 0;
1665         for (;;) {
1666                 u64 l = min_t(u64, len, PAGE_SIZE);
1667
1668                 crc = btrfs_csum_data(root, buffer, crc, l);
1669                 kunmap_atomic(buffer);
1670                 len -= l;
1671                 if (len == 0)
1672                         break;
1673                 index++;
1674                 BUG_ON(index >= sblock->page_count);
1675                 BUG_ON(!sblock->pagev[index]->page);
1676                 page = sblock->pagev[index]->page;
1677                 buffer = kmap_atomic(page);
1678         }
1679
1680         btrfs_csum_final(crc, csum);
1681         if (memcmp(csum, on_disk_csum, sctx->csum_size))
1682                 fail = 1;
1683
1684         return fail;
1685 }
1686
1687 static int scrub_checksum_tree_block(struct scrub_block *sblock)
1688 {
1689         struct scrub_ctx *sctx = sblock->sctx;
1690         struct btrfs_header *h;
1691         struct btrfs_root *root = sctx->dev_root;
1692         struct btrfs_fs_info *fs_info = root->fs_info;
1693         u8 calculated_csum[BTRFS_CSUM_SIZE];
1694         u8 on_disk_csum[BTRFS_CSUM_SIZE];
1695         struct page *page;
1696         void *mapped_buffer;
1697         u64 mapped_size;
1698         void *p;
1699         u32 crc = ~(u32)0;
1700         int fail = 0;
1701         int crc_fail = 0;
1702         u64 len;
1703         int index;
1704
1705         BUG_ON(sblock->page_count < 1);
1706         page = sblock->pagev[0]->page;
1707         mapped_buffer = kmap_atomic(page);
1708         h = (struct btrfs_header *)mapped_buffer;
1709         memcpy(on_disk_csum, h->csum, sctx->csum_size);
1710
1711         /*
1712          * we don't use the getter functions here, as we
1713          * a) don't have an extent buffer and
1714          * b) the page is already kmapped
1715          */
1716
1717         if (sblock->pagev[0]->logical != le64_to_cpu(h->bytenr))
1718                 ++fail;
1719
1720         if (sblock->pagev[0]->generation != le64_to_cpu(h->generation))
1721                 ++fail;
1722
1723         if (memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
1724                 ++fail;
1725
1726         if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
1727                    BTRFS_UUID_SIZE))
1728                 ++fail;
1729
1730         WARN_ON(sctx->nodesize != sctx->leafsize);
1731         len = sctx->nodesize - BTRFS_CSUM_SIZE;
1732         mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
1733         p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
1734         index = 0;
1735         for (;;) {
1736                 u64 l = min_t(u64, len, mapped_size);
1737
1738                 crc = btrfs_csum_data(root, p, crc, l);
1739                 kunmap_atomic(mapped_buffer);
1740                 len -= l;
1741                 if (len == 0)
1742                         break;
1743                 index++;
1744                 BUG_ON(index >= sblock->page_count);
1745                 BUG_ON(!sblock->pagev[index]->page);
1746                 page = sblock->pagev[index]->page;
1747                 mapped_buffer = kmap_atomic(page);
1748                 mapped_size = PAGE_SIZE;
1749                 p = mapped_buffer;
1750         }
1751
1752         btrfs_csum_final(crc, calculated_csum);
1753         if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
1754                 ++crc_fail;
1755
1756         return fail || crc_fail;
1757 }
1758
1759 static int scrub_checksum_super(struct scrub_block *sblock)
1760 {
1761         struct btrfs_super_block *s;
1762         struct scrub_ctx *sctx = sblock->sctx;
1763         struct btrfs_root *root = sctx->dev_root;
1764         struct btrfs_fs_info *fs_info = root->fs_info;
1765         u8 calculated_csum[BTRFS_CSUM_SIZE];
1766         u8 on_disk_csum[BTRFS_CSUM_SIZE];
1767         struct page *page;
1768         void *mapped_buffer;
1769         u64 mapped_size;
1770         void *p;
1771         u32 crc = ~(u32)0;
1772         int fail_gen = 0;
1773         int fail_cor = 0;
1774         u64 len;
1775         int index;
1776
1777         BUG_ON(sblock->page_count < 1);
1778         page = sblock->pagev[0]->page;
1779         mapped_buffer = kmap_atomic(page);
1780         s = (struct btrfs_super_block *)mapped_buffer;
1781         memcpy(on_disk_csum, s->csum, sctx->csum_size);
1782
1783         if (sblock->pagev[0]->logical != le64_to_cpu(s->bytenr))
1784                 ++fail_cor;
1785
1786         if (sblock->pagev[0]->generation != le64_to_cpu(s->generation))
1787                 ++fail_gen;
1788
1789         if (memcmp(s->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
1790                 ++fail_cor;
1791
1792         len = BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE;
1793         mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE;
1794         p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE;
1795         index = 0;
1796         for (;;) {
1797                 u64 l = min_t(u64, len, mapped_size);
1798
1799                 crc = btrfs_csum_data(root, p, crc, l);
1800                 kunmap_atomic(mapped_buffer);
1801                 len -= l;
1802                 if (len == 0)
1803                         break;
1804                 index++;
1805                 BUG_ON(index >= sblock->page_count);
1806                 BUG_ON(!sblock->pagev[index]->page);
1807                 page = sblock->pagev[index]->page;
1808                 mapped_buffer = kmap_atomic(page);
1809                 mapped_size = PAGE_SIZE;
1810                 p = mapped_buffer;
1811         }
1812
1813         btrfs_csum_final(crc, calculated_csum);
1814         if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size))
1815                 ++fail_cor;
1816
1817         if (fail_cor + fail_gen) {
1818                 /*
1819                  * if we find an error in a super block, we just report it.
1820                  * They will get written with the next transaction commit
1821                  * anyway
1822                  */
1823                 spin_lock(&sctx->stat_lock);
1824                 ++sctx->stat.super_errors;
1825                 spin_unlock(&sctx->stat_lock);
1826                 if (fail_cor)
1827                         btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
1828                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
1829                 else
1830                         btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev,
1831                                 BTRFS_DEV_STAT_GENERATION_ERRS);
1832         }
1833
1834         return fail_cor + fail_gen;
1835 }
1836
1837 static void scrub_block_get(struct scrub_block *sblock)
1838 {
1839         atomic_inc(&sblock->ref_count);
1840 }
1841
1842 static void scrub_block_put(struct scrub_block *sblock)
1843 {
1844         if (atomic_dec_and_test(&sblock->ref_count)) {
1845                 int i;
1846
1847                 for (i = 0; i < sblock->page_count; i++)
1848                         scrub_page_put(sblock->pagev[i]);
1849                 kfree(sblock);
1850         }
1851 }
1852
1853 static void scrub_page_get(struct scrub_page *spage)
1854 {
1855         atomic_inc(&spage->ref_count);
1856 }
1857
1858 static void scrub_page_put(struct scrub_page *spage)
1859 {
1860         if (atomic_dec_and_test(&spage->ref_count)) {
1861                 if (spage->page)
1862                         __free_page(spage->page);
1863                 kfree(spage);
1864         }
1865 }
1866
1867 static void scrub_submit(struct scrub_ctx *sctx)
1868 {
1869         struct scrub_bio *sbio;
1870
1871         if (sctx->curr == -1)
1872                 return;
1873
1874         sbio = sctx->bios[sctx->curr];
1875         sctx->curr = -1;
1876         scrub_pending_bio_inc(sctx);
1877
1878         if (!sbio->bio->bi_bdev) {
1879                 /*
1880                  * this case should not happen. If btrfs_map_block() is
1881                  * wrong, it could happen for dev-replace operations on
1882                  * missing devices when no mirrors are available, but in
1883                  * this case it should already fail the mount.
1884                  * This case is handled correctly (but _very_ slowly).
1885                  */
1886                 printk_ratelimited(KERN_WARNING
1887                         "btrfs: scrub_submit(bio bdev == NULL) is unexpected!\n");
1888                 bio_endio(sbio->bio, -EIO);
1889         } else {
1890                 btrfsic_submit_bio(READ, sbio->bio);
1891         }
1892 }
1893
1894 static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx,
1895                                     struct scrub_page *spage)
1896 {
1897         struct scrub_block *sblock = spage->sblock;
1898         struct scrub_bio *sbio;
1899         int ret;
1900
1901 again:
1902         /*
1903          * grab a fresh bio or wait for one to become available
1904          */
1905         while (sctx->curr == -1) {
1906                 spin_lock(&sctx->list_lock);
1907                 sctx->curr = sctx->first_free;
1908                 if (sctx->curr != -1) {
1909                         sctx->first_free = sctx->bios[sctx->curr]->next_free;
1910                         sctx->bios[sctx->curr]->next_free = -1;
1911                         sctx->bios[sctx->curr]->page_count = 0;
1912                         spin_unlock(&sctx->list_lock);
1913                 } else {
1914                         spin_unlock(&sctx->list_lock);
1915                         wait_event(sctx->list_wait, sctx->first_free != -1);
1916                 }
1917         }
1918         sbio = sctx->bios[sctx->curr];
1919         if (sbio->page_count == 0) {
1920                 struct bio *bio;
1921
1922                 sbio->physical = spage->physical;
1923                 sbio->logical = spage->logical;
1924                 sbio->dev = spage->dev;
1925                 bio = sbio->bio;
1926                 if (!bio) {
1927                         bio = bio_alloc(GFP_NOFS, sctx->pages_per_rd_bio);
1928                         if (!bio)
1929                                 return -ENOMEM;
1930                         sbio->bio = bio;
1931                 }
1932
1933                 bio->bi_private = sbio;
1934                 bio->bi_end_io = scrub_bio_end_io;
1935                 bio->bi_bdev = sbio->dev->bdev;
1936                 bio->bi_sector = sbio->physical >> 9;
1937                 sbio->err = 0;
1938         } else if (sbio->physical + sbio->page_count * PAGE_SIZE !=
1939                    spage->physical ||
1940                    sbio->logical + sbio->page_count * PAGE_SIZE !=
1941                    spage->logical ||
1942                    sbio->dev != spage->dev) {
1943                 scrub_submit(sctx);
1944                 goto again;
1945         }
1946
1947         sbio->pagev[sbio->page_count] = spage;
1948         ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0);
1949         if (ret != PAGE_SIZE) {
1950                 if (sbio->page_count < 1) {
1951                         bio_put(sbio->bio);
1952                         sbio->bio = NULL;
1953                         return -EIO;
1954                 }
1955                 scrub_submit(sctx);
1956                 goto again;
1957         }
1958
1959         scrub_block_get(sblock); /* one for the page added to the bio */
1960         atomic_inc(&sblock->outstanding_pages);
1961         sbio->page_count++;
1962         if (sbio->page_count == sctx->pages_per_rd_bio)
1963                 scrub_submit(sctx);
1964
1965         return 0;
1966 }
1967
1968 static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
1969                        u64 physical, struct btrfs_device *dev, u64 flags,
1970                        u64 gen, int mirror_num, u8 *csum, int force,
1971                        u64 physical_for_dev_replace)
1972 {
1973         struct scrub_block *sblock;
1974         int index;
1975
1976         sblock = kzalloc(sizeof(*sblock), GFP_NOFS);
1977         if (!sblock) {
1978                 spin_lock(&sctx->stat_lock);
1979                 sctx->stat.malloc_errors++;
1980                 spin_unlock(&sctx->stat_lock);
1981                 return -ENOMEM;
1982         }
1983
1984         /* one ref inside this function, plus one for each page added to
1985          * a bio later on */
1986         atomic_set(&sblock->ref_count, 1);
1987         sblock->sctx = sctx;
1988         sblock->no_io_error_seen = 1;
1989
1990         for (index = 0; len > 0; index++) {
1991                 struct scrub_page *spage;
1992                 u64 l = min_t(u64, len, PAGE_SIZE);
1993
1994                 spage = kzalloc(sizeof(*spage), GFP_NOFS);
1995                 if (!spage) {
1996 leave_nomem:
1997                         spin_lock(&sctx->stat_lock);
1998                         sctx->stat.malloc_errors++;
1999                         spin_unlock(&sctx->stat_lock);
2000                         scrub_block_put(sblock);
2001                         return -ENOMEM;
2002                 }
2003                 BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK);
2004                 scrub_page_get(spage);
2005                 sblock->pagev[index] = spage;
2006                 spage->sblock = sblock;
2007                 spage->dev = dev;
2008                 spage->flags = flags;
2009                 spage->generation = gen;
2010                 spage->logical = logical;
2011                 spage->physical = physical;
2012                 spage->physical_for_dev_replace = physical_for_dev_replace;
2013                 spage->mirror_num = mirror_num;
2014                 if (csum) {
2015                         spage->have_csum = 1;
2016                         memcpy(spage->csum, csum, sctx->csum_size);
2017                 } else {
2018                         spage->have_csum = 0;
2019                 }
2020                 sblock->page_count++;
2021                 spage->page = alloc_page(GFP_NOFS);
2022                 if (!spage->page)
2023                         goto leave_nomem;
2024                 len -= l;
2025                 logical += l;
2026                 physical += l;
2027                 physical_for_dev_replace += l;
2028         }
2029
2030         WARN_ON(sblock->page_count == 0);
2031         for (index = 0; index < sblock->page_count; index++) {
2032                 struct scrub_page *spage = sblock->pagev[index];
2033                 int ret;
2034
2035                 ret = scrub_add_page_to_rd_bio(sctx, spage);
2036                 if (ret) {
2037                         scrub_block_put(sblock);
2038                         return ret;
2039                 }
2040         }
2041
2042         if (force)
2043                 scrub_submit(sctx);
2044
2045         /* last one frees, either here or in bio completion for last page */
2046         scrub_block_put(sblock);
2047         return 0;
2048 }
2049
2050 static void scrub_bio_end_io(struct bio *bio, int err)
2051 {
2052         struct scrub_bio *sbio = bio->bi_private;
2053         struct btrfs_fs_info *fs_info = sbio->dev->dev_root->fs_info;
2054
2055         sbio->err = err;
2056         sbio->bio = bio;
2057
2058         btrfs_queue_worker(&fs_info->scrub_workers, &sbio->work);
2059 }
2060
2061 static void scrub_bio_end_io_worker(struct btrfs_work *work)
2062 {
2063         struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
2064         struct scrub_ctx *sctx = sbio->sctx;
2065         int i;
2066
2067         BUG_ON(sbio->page_count > SCRUB_PAGES_PER_RD_BIO);
2068         if (sbio->err) {
2069                 for (i = 0; i < sbio->page_count; i++) {
2070                         struct scrub_page *spage = sbio->pagev[i];
2071
2072                         spage->io_error = 1;
2073                         spage->sblock->no_io_error_seen = 0;
2074                 }
2075         }
2076
2077         /* now complete the scrub_block items that have all pages completed */
2078         for (i = 0; i < sbio->page_count; i++) {
2079                 struct scrub_page *spage = sbio->pagev[i];
2080                 struct scrub_block *sblock = spage->sblock;
2081
2082                 if (atomic_dec_and_test(&sblock->outstanding_pages))
2083                         scrub_block_complete(sblock);
2084                 scrub_block_put(sblock);
2085         }
2086
2087         bio_put(sbio->bio);
2088         sbio->bio = NULL;
2089         spin_lock(&sctx->list_lock);
2090         sbio->next_free = sctx->first_free;
2091         sctx->first_free = sbio->index;
2092         spin_unlock(&sctx->list_lock);
2093
2094         if (sctx->is_dev_replace &&
2095             atomic_read(&sctx->wr_ctx.flush_all_writes)) {
2096                 mutex_lock(&sctx->wr_ctx.wr_lock);
2097                 scrub_wr_submit(sctx);
2098                 mutex_unlock(&sctx->wr_ctx.wr_lock);
2099         }
2100
2101         scrub_pending_bio_dec(sctx);
2102 }
2103
2104 static void scrub_block_complete(struct scrub_block *sblock)
2105 {
2106         if (!sblock->no_io_error_seen) {
2107                 scrub_handle_errored_block(sblock);
2108         } else {
2109                 /*
2110                  * if has checksum error, write via repair mechanism in
2111                  * dev replace case, otherwise write here in dev replace
2112                  * case.
2113                  */
2114                 if (!scrub_checksum(sblock) && sblock->sctx->is_dev_replace)
2115                         scrub_write_block_to_dev_replace(sblock);
2116         }
2117 }
2118
2119 static int scrub_find_csum(struct scrub_ctx *sctx, u64 logical, u64 len,
2120                            u8 *csum)
2121 {
2122         struct btrfs_ordered_sum *sum = NULL;
2123         int ret = 0;
2124         unsigned long i;
2125         unsigned long num_sectors;
2126
2127         while (!list_empty(&sctx->csum_list)) {
2128                 sum = list_first_entry(&sctx->csum_list,
2129                                        struct btrfs_ordered_sum, list);
2130                 if (sum->bytenr > logical)
2131                         return 0;
2132                 if (sum->bytenr + sum->len > logical)
2133                         break;
2134
2135                 ++sctx->stat.csum_discards;
2136                 list_del(&sum->list);
2137                 kfree(sum);
2138                 sum = NULL;
2139         }
2140         if (!sum)
2141                 return 0;
2142
2143         num_sectors = sum->len / sctx->sectorsize;
2144         for (i = 0; i < num_sectors; ++i) {
2145                 if (sum->sums[i].bytenr == logical) {
2146                         memcpy(csum, &sum->sums[i].sum, sctx->csum_size);
2147                         ret = 1;
2148                         break;
2149                 }
2150         }
2151         if (ret && i == num_sectors - 1) {
2152                 list_del(&sum->list);
2153                 kfree(sum);
2154         }
2155         return ret;
2156 }
2157
2158 /* scrub extent tries to collect up to 64 kB for each bio */
2159 static int scrub_extent(struct scrub_ctx *sctx, u64 logical, u64 len,
2160                         u64 physical, struct btrfs_device *dev, u64 flags,
2161                         u64 gen, int mirror_num, u64 physical_for_dev_replace)
2162 {
2163         int ret;
2164         u8 csum[BTRFS_CSUM_SIZE];
2165         u32 blocksize;
2166
2167         if (flags & BTRFS_EXTENT_FLAG_DATA) {
2168                 blocksize = sctx->sectorsize;
2169                 spin_lock(&sctx->stat_lock);
2170                 sctx->stat.data_extents_scrubbed++;
2171                 sctx->stat.data_bytes_scrubbed += len;
2172                 spin_unlock(&sctx->stat_lock);
2173         } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2174                 WARN_ON(sctx->nodesize != sctx->leafsize);
2175                 blocksize = sctx->nodesize;
2176                 spin_lock(&sctx->stat_lock);
2177                 sctx->stat.tree_extents_scrubbed++;
2178                 sctx->stat.tree_bytes_scrubbed += len;
2179                 spin_unlock(&sctx->stat_lock);
2180         } else {
2181                 blocksize = sctx->sectorsize;
2182                 WARN_ON(1);
2183         }
2184
2185         while (len) {
2186                 u64 l = min_t(u64, len, blocksize);
2187                 int have_csum = 0;
2188
2189                 if (flags & BTRFS_EXTENT_FLAG_DATA) {
2190                         /* push csums to sbio */
2191                         have_csum = scrub_find_csum(sctx, logical, l, csum);
2192                         if (have_csum == 0)
2193                                 ++sctx->stat.no_csum;
2194                         if (sctx->is_dev_replace && !have_csum) {
2195                                 ret = copy_nocow_pages(sctx, logical, l,
2196                                                        mirror_num,
2197                                                       physical_for_dev_replace);
2198                                 goto behind_scrub_pages;
2199                         }
2200                 }
2201                 ret = scrub_pages(sctx, logical, l, physical, dev, flags, gen,
2202                                   mirror_num, have_csum ? csum : NULL, 0,
2203                                   physical_for_dev_replace);
2204 behind_scrub_pages:
2205                 if (ret)
2206                         return ret;
2207                 len -= l;
2208                 logical += l;
2209                 physical += l;
2210                 physical_for_dev_replace += l;
2211         }
2212         return 0;
2213 }
2214
2215 static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
2216                                            struct map_lookup *map,
2217                                            struct btrfs_device *scrub_dev,
2218                                            int num, u64 base, u64 length,
2219                                            int is_dev_replace)
2220 {
2221         struct btrfs_path *path;
2222         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
2223         struct btrfs_root *root = fs_info->extent_root;
2224         struct btrfs_root *csum_root = fs_info->csum_root;
2225         struct btrfs_extent_item *extent;
2226         struct blk_plug plug;
2227         u64 flags;
2228         int ret;
2229         int slot;
2230         int i;
2231         u64 nstripes;
2232         struct extent_buffer *l;
2233         struct btrfs_key key;
2234         u64 physical;
2235         u64 logical;
2236         u64 generation;
2237         int mirror_num;
2238         struct reada_control *reada1;
2239         struct reada_control *reada2;
2240         struct btrfs_key key_start;
2241         struct btrfs_key key_end;
2242         u64 increment = map->stripe_len;
2243         u64 offset;
2244         u64 extent_logical;
2245         u64 extent_physical;
2246         u64 extent_len;
2247         struct btrfs_device *extent_dev;
2248         int extent_mirror_num;
2249
2250         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
2251                          BTRFS_BLOCK_GROUP_RAID6)) {
2252                 if (num >= nr_data_stripes(map)) {
2253                         return 0;
2254                 }
2255         }
2256
2257         nstripes = length;
2258         offset = 0;
2259         do_div(nstripes, map->stripe_len);
2260         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
2261                 offset = map->stripe_len * num;
2262                 increment = map->stripe_len * map->num_stripes;
2263                 mirror_num = 1;
2264         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2265                 int factor = map->num_stripes / map->sub_stripes;
2266                 offset = map->stripe_len * (num / map->sub_stripes);
2267                 increment = map->stripe_len * factor;
2268                 mirror_num = num % map->sub_stripes + 1;
2269         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
2270                 increment = map->stripe_len;
2271                 mirror_num = num % map->num_stripes + 1;
2272         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
2273                 increment = map->stripe_len;
2274                 mirror_num = num % map->num_stripes + 1;
2275         } else {
2276                 increment = map->stripe_len;
2277                 mirror_num = 1;
2278         }
2279
2280         path = btrfs_alloc_path();
2281         if (!path)
2282                 return -ENOMEM;
2283
2284         /*
2285          * work on commit root. The related disk blocks are static as
2286          * long as COW is applied. This means, it is save to rewrite
2287          * them to repair disk errors without any race conditions
2288          */
2289         path->search_commit_root = 1;
2290         path->skip_locking = 1;
2291
2292         /*
2293          * trigger the readahead for extent tree csum tree and wait for
2294          * completion. During readahead, the scrub is officially paused
2295          * to not hold off transaction commits
2296          */
2297         logical = base + offset;
2298
2299         wait_event(sctx->list_wait,
2300                    atomic_read(&sctx->bios_in_flight) == 0);
2301         atomic_inc(&fs_info->scrubs_paused);
2302         wake_up(&fs_info->scrub_pause_wait);
2303
2304         /* FIXME it might be better to start readahead at commit root */
2305         key_start.objectid = logical;
2306         key_start.type = BTRFS_EXTENT_ITEM_KEY;
2307         key_start.offset = (u64)0;
2308         key_end.objectid = base + offset + nstripes * increment;
2309         key_end.type = BTRFS_EXTENT_ITEM_KEY;
2310         key_end.offset = (u64)0;
2311         reada1 = btrfs_reada_add(root, &key_start, &key_end);
2312
2313         key_start.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
2314         key_start.type = BTRFS_EXTENT_CSUM_KEY;
2315         key_start.offset = logical;
2316         key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
2317         key_end.type = BTRFS_EXTENT_CSUM_KEY;
2318         key_end.offset = base + offset + nstripes * increment;
2319         reada2 = btrfs_reada_add(csum_root, &key_start, &key_end);
2320
2321         if (!IS_ERR(reada1))
2322                 btrfs_reada_wait(reada1);
2323         if (!IS_ERR(reada2))
2324                 btrfs_reada_wait(reada2);
2325
2326         mutex_lock(&fs_info->scrub_lock);
2327         while (atomic_read(&fs_info->scrub_pause_req)) {
2328                 mutex_unlock(&fs_info->scrub_lock);
2329                 wait_event(fs_info->scrub_pause_wait,
2330                    atomic_read(&fs_info->scrub_pause_req) == 0);
2331                 mutex_lock(&fs_info->scrub_lock);
2332         }
2333         atomic_dec(&fs_info->scrubs_paused);
2334         mutex_unlock(&fs_info->scrub_lock);
2335         wake_up(&fs_info->scrub_pause_wait);
2336
2337         /*
2338          * collect all data csums for the stripe to avoid seeking during
2339          * the scrub. This might currently (crc32) end up to be about 1MB
2340          */
2341         blk_start_plug(&plug);
2342
2343         /*
2344          * now find all extents for each stripe and scrub them
2345          */
2346         logical = base + offset;
2347         physical = map->stripes[num].physical;
2348         ret = 0;
2349         for (i = 0; i < nstripes; ++i) {
2350                 /*
2351                  * canceled?
2352                  */
2353                 if (atomic_read(&fs_info->scrub_cancel_req) ||
2354                     atomic_read(&sctx->cancel_req)) {
2355                         ret = -ECANCELED;
2356                         goto out;
2357                 }
2358                 /*
2359                  * check to see if we have to pause
2360                  */
2361                 if (atomic_read(&fs_info->scrub_pause_req)) {
2362                         /* push queued extents */
2363                         atomic_set(&sctx->wr_ctx.flush_all_writes, 1);
2364                         scrub_submit(sctx);
2365                         mutex_lock(&sctx->wr_ctx.wr_lock);
2366                         scrub_wr_submit(sctx);
2367                         mutex_unlock(&sctx->wr_ctx.wr_lock);
2368                         wait_event(sctx->list_wait,
2369                                    atomic_read(&sctx->bios_in_flight) == 0);
2370                         atomic_set(&sctx->wr_ctx.flush_all_writes, 0);
2371                         atomic_inc(&fs_info->scrubs_paused);
2372                         wake_up(&fs_info->scrub_pause_wait);
2373                         mutex_lock(&fs_info->scrub_lock);
2374                         while (atomic_read(&fs_info->scrub_pause_req)) {
2375                                 mutex_unlock(&fs_info->scrub_lock);
2376                                 wait_event(fs_info->scrub_pause_wait,
2377                                    atomic_read(&fs_info->scrub_pause_req) == 0);
2378                                 mutex_lock(&fs_info->scrub_lock);
2379                         }
2380                         atomic_dec(&fs_info->scrubs_paused);
2381                         mutex_unlock(&fs_info->scrub_lock);
2382                         wake_up(&fs_info->scrub_pause_wait);
2383                 }
2384
2385                 ret = btrfs_lookup_csums_range(csum_root, logical,
2386                                                logical + map->stripe_len - 1,
2387                                                &sctx->csum_list, 1);
2388                 if (ret)
2389                         goto out;
2390
2391                 key.objectid = logical;
2392                 key.type = BTRFS_EXTENT_ITEM_KEY;
2393                 key.offset = (u64)0;
2394
2395                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2396                 if (ret < 0)
2397                         goto out;
2398                 if (ret > 0) {
2399                         ret = btrfs_previous_item(root, path, 0,
2400                                                   BTRFS_EXTENT_ITEM_KEY);
2401                         if (ret < 0)
2402                                 goto out;
2403                         if (ret > 0) {
2404                                 /* there's no smaller item, so stick with the
2405                                  * larger one */
2406                                 btrfs_release_path(path);
2407                                 ret = btrfs_search_slot(NULL, root, &key,
2408                                                         path, 0, 0);
2409                                 if (ret < 0)
2410                                         goto out;
2411                         }
2412                 }
2413
2414                 while (1) {
2415                         l = path->nodes[0];
2416                         slot = path->slots[0];
2417                         if (slot >= btrfs_header_nritems(l)) {
2418                                 ret = btrfs_next_leaf(root, path);
2419                                 if (ret == 0)
2420                                         continue;
2421                                 if (ret < 0)
2422                                         goto out;
2423
2424                                 break;
2425                         }
2426                         btrfs_item_key_to_cpu(l, &key, slot);
2427
2428                         if (key.objectid + key.offset <= logical)
2429                                 goto next;
2430
2431                         if (key.objectid >= logical + map->stripe_len)
2432                                 break;
2433
2434                         if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY)
2435                                 goto next;
2436
2437                         extent = btrfs_item_ptr(l, slot,
2438                                                 struct btrfs_extent_item);
2439                         flags = btrfs_extent_flags(l, extent);
2440                         generation = btrfs_extent_generation(l, extent);
2441
2442                         if (key.objectid < logical &&
2443                             (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
2444                                 printk(KERN_ERR
2445                                        "btrfs scrub: tree block %llu spanning "
2446                                        "stripes, ignored. logical=%llu\n",
2447                                        (unsigned long long)key.objectid,
2448                                        (unsigned long long)logical);
2449                                 goto next;
2450                         }
2451
2452                         /*
2453                          * trim extent to this stripe
2454                          */
2455                         if (key.objectid < logical) {
2456                                 key.offset -= logical - key.objectid;
2457                                 key.objectid = logical;
2458                         }
2459                         if (key.objectid + key.offset >
2460                             logical + map->stripe_len) {
2461                                 key.offset = logical + map->stripe_len -
2462                                              key.objectid;
2463                         }
2464
2465                         extent_logical = key.objectid;
2466                         extent_physical = key.objectid - logical + physical;
2467                         extent_len = key.offset;
2468                         extent_dev = scrub_dev;
2469                         extent_mirror_num = mirror_num;
2470                         if (is_dev_replace)
2471                                 scrub_remap_extent(fs_info, extent_logical,
2472                                                    extent_len, &extent_physical,
2473                                                    &extent_dev,
2474                                                    &extent_mirror_num);
2475                         ret = scrub_extent(sctx, extent_logical, extent_len,
2476                                            extent_physical, extent_dev, flags,
2477                                            generation, extent_mirror_num,
2478                                            key.objectid - logical + physical);
2479                         if (ret)
2480                                 goto out;
2481
2482 next:
2483                         path->slots[0]++;
2484                 }
2485                 btrfs_release_path(path);
2486                 logical += increment;
2487                 physical += map->stripe_len;
2488                 spin_lock(&sctx->stat_lock);
2489                 sctx->stat.last_physical = physical;
2490                 spin_unlock(&sctx->stat_lock);
2491         }
2492 out:
2493         /* push queued extents */
2494         scrub_submit(sctx);
2495         mutex_lock(&sctx->wr_ctx.wr_lock);
2496         scrub_wr_submit(sctx);
2497         mutex_unlock(&sctx->wr_ctx.wr_lock);
2498
2499         blk_finish_plug(&plug);
2500         btrfs_free_path(path);
2501         return ret < 0 ? ret : 0;
2502 }
2503
2504 static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx,
2505                                           struct btrfs_device *scrub_dev,
2506                                           u64 chunk_tree, u64 chunk_objectid,
2507                                           u64 chunk_offset, u64 length,
2508                                           u64 dev_offset, int is_dev_replace)
2509 {
2510         struct btrfs_mapping_tree *map_tree =
2511                 &sctx->dev_root->fs_info->mapping_tree;
2512         struct map_lookup *map;
2513         struct extent_map *em;
2514         int i;
2515         int ret = 0;
2516
2517         read_lock(&map_tree->map_tree.lock);
2518         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
2519         read_unlock(&map_tree->map_tree.lock);
2520
2521         if (!em)
2522                 return -EINVAL;
2523
2524         map = (struct map_lookup *)em->bdev;
2525         if (em->start != chunk_offset)
2526                 goto out;
2527
2528         if (em->len < length)
2529                 goto out;
2530
2531         for (i = 0; i < map->num_stripes; ++i) {
2532                 if (map->stripes[i].dev->bdev == scrub_dev->bdev &&
2533                     map->stripes[i].physical == dev_offset) {
2534                         ret = scrub_stripe(sctx, map, scrub_dev, i,
2535                                            chunk_offset, length,
2536                                            is_dev_replace);
2537                         if (ret)
2538                                 goto out;
2539                 }
2540         }
2541 out:
2542         free_extent_map(em);
2543
2544         return ret;
2545 }
2546
2547 static noinline_for_stack
2548 int scrub_enumerate_chunks(struct scrub_ctx *sctx,
2549                            struct btrfs_device *scrub_dev, u64 start, u64 end,
2550                            int is_dev_replace)
2551 {
2552         struct btrfs_dev_extent *dev_extent = NULL;
2553         struct btrfs_path *path;
2554         struct btrfs_root *root = sctx->dev_root;
2555         struct btrfs_fs_info *fs_info = root->fs_info;
2556         u64 length;
2557         u64 chunk_tree;
2558         u64 chunk_objectid;
2559         u64 chunk_offset;
2560         int ret;
2561         int slot;
2562         struct extent_buffer *l;
2563         struct btrfs_key key;
2564         struct btrfs_key found_key;
2565         struct btrfs_block_group_cache *cache;
2566         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
2567
2568         path = btrfs_alloc_path();
2569         if (!path)
2570                 return -ENOMEM;
2571
2572         path->reada = 2;
2573         path->search_commit_root = 1;
2574         path->skip_locking = 1;
2575
2576         key.objectid = scrub_dev->devid;
2577         key.offset = 0ull;
2578         key.type = BTRFS_DEV_EXTENT_KEY;
2579
2580         while (1) {
2581                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2582                 if (ret < 0)
2583                         break;
2584                 if (ret > 0) {
2585                         if (path->slots[0] >=
2586                             btrfs_header_nritems(path->nodes[0])) {
2587                                 ret = btrfs_next_leaf(root, path);
2588                                 if (ret)
2589                                         break;
2590                         }
2591                 }
2592
2593                 l = path->nodes[0];
2594                 slot = path->slots[0];
2595
2596                 btrfs_item_key_to_cpu(l, &found_key, slot);
2597
2598                 if (found_key.objectid != scrub_dev->devid)
2599                         break;
2600
2601                 if (btrfs_key_type(&found_key) != BTRFS_DEV_EXTENT_KEY)
2602                         break;
2603
2604                 if (found_key.offset >= end)
2605                         break;
2606
2607                 if (found_key.offset < key.offset)
2608                         break;
2609
2610                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2611                 length = btrfs_dev_extent_length(l, dev_extent);
2612
2613                 if (found_key.offset + length <= start) {
2614                         key.offset = found_key.offset + length;
2615                         btrfs_release_path(path);
2616                         continue;
2617                 }
2618
2619                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2620                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
2621                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2622
2623                 /*
2624                  * get a reference on the corresponding block group to prevent
2625                  * the chunk from going away while we scrub it
2626                  */
2627                 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2628                 if (!cache) {
2629                         ret = -ENOENT;
2630                         break;
2631                 }
2632                 dev_replace->cursor_right = found_key.offset + length;
2633                 dev_replace->cursor_left = found_key.offset;
2634                 dev_replace->item_needs_writeback = 1;
2635                 ret = scrub_chunk(sctx, scrub_dev, chunk_tree, chunk_objectid,
2636                                   chunk_offset, length, found_key.offset,
2637                                   is_dev_replace);
2638
2639                 /*
2640                  * flush, submit all pending read and write bios, afterwards
2641                  * wait for them.
2642                  * Note that in the dev replace case, a read request causes
2643                  * write requests that are submitted in the read completion
2644                  * worker. Therefore in the current situation, it is required
2645                  * that all write requests are flushed, so that all read and
2646                  * write requests are really completed when bios_in_flight
2647                  * changes to 0.
2648                  */
2649                 atomic_set(&sctx->wr_ctx.flush_all_writes, 1);
2650                 scrub_submit(sctx);
2651                 mutex_lock(&sctx->wr_ctx.wr_lock);
2652                 scrub_wr_submit(sctx);
2653                 mutex_unlock(&sctx->wr_ctx.wr_lock);
2654
2655                 wait_event(sctx->list_wait,
2656                            atomic_read(&sctx->bios_in_flight) == 0);
2657                 atomic_set(&sctx->wr_ctx.flush_all_writes, 0);
2658                 atomic_inc(&fs_info->scrubs_paused);
2659                 wake_up(&fs_info->scrub_pause_wait);
2660                 wait_event(sctx->list_wait,
2661                            atomic_read(&sctx->workers_pending) == 0);
2662
2663                 mutex_lock(&fs_info->scrub_lock);
2664                 while (atomic_read(&fs_info->scrub_pause_req)) {
2665                         mutex_unlock(&fs_info->scrub_lock);
2666                         wait_event(fs_info->scrub_pause_wait,
2667                            atomic_read(&fs_info->scrub_pause_req) == 0);
2668                         mutex_lock(&fs_info->scrub_lock);
2669                 }
2670                 atomic_dec(&fs_info->scrubs_paused);
2671                 mutex_unlock(&fs_info->scrub_lock);
2672                 wake_up(&fs_info->scrub_pause_wait);
2673
2674                 dev_replace->cursor_left = dev_replace->cursor_right;
2675                 dev_replace->item_needs_writeback = 1;
2676                 btrfs_put_block_group(cache);
2677                 if (ret)
2678                         break;
2679                 if (is_dev_replace &&
2680                     atomic64_read(&dev_replace->num_write_errors) > 0) {
2681                         ret = -EIO;
2682                         break;
2683                 }
2684                 if (sctx->stat.malloc_errors > 0) {
2685                         ret = -ENOMEM;
2686                         break;
2687                 }
2688
2689                 key.offset = found_key.offset + length;
2690                 btrfs_release_path(path);
2691         }
2692
2693         btrfs_free_path(path);
2694
2695         /*
2696          * ret can still be 1 from search_slot or next_leaf,
2697          * that's not an error
2698          */
2699         return ret < 0 ? ret : 0;
2700 }
2701
2702 static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx,
2703                                            struct btrfs_device *scrub_dev)
2704 {
2705         int     i;
2706         u64     bytenr;
2707         u64     gen;
2708         int     ret;
2709         struct btrfs_root *root = sctx->dev_root;
2710
2711         if (root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)
2712                 return -EIO;
2713
2714         gen = root->fs_info->last_trans_committed;
2715
2716         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2717                 bytenr = btrfs_sb_offset(i);
2718                 if (bytenr + BTRFS_SUPER_INFO_SIZE > scrub_dev->total_bytes)
2719                         break;
2720
2721                 ret = scrub_pages(sctx, bytenr, BTRFS_SUPER_INFO_SIZE, bytenr,
2722                                   scrub_dev, BTRFS_EXTENT_FLAG_SUPER, gen, i,
2723                                   NULL, 1, bytenr);
2724                 if (ret)
2725                         return ret;
2726         }
2727         wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
2728
2729         return 0;
2730 }
2731
2732 /*
2733  * get a reference count on fs_info->scrub_workers. start worker if necessary
2734  */
2735 static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info,
2736                                                 int is_dev_replace)
2737 {
2738         int ret = 0;
2739
2740         mutex_lock(&fs_info->scrub_lock);
2741         if (fs_info->scrub_workers_refcnt == 0) {
2742                 if (is_dev_replace)
2743                         btrfs_init_workers(&fs_info->scrub_workers, "scrub", 1,
2744                                         &fs_info->generic_worker);
2745                 else
2746                         btrfs_init_workers(&fs_info->scrub_workers, "scrub",
2747                                         fs_info->thread_pool_size,
2748                                         &fs_info->generic_worker);
2749                 fs_info->scrub_workers.idle_thresh = 4;
2750                 ret = btrfs_start_workers(&fs_info->scrub_workers);
2751                 if (ret)
2752                         goto out;
2753                 btrfs_init_workers(&fs_info->scrub_wr_completion_workers,
2754                                    "scrubwrc",
2755                                    fs_info->thread_pool_size,
2756                                    &fs_info->generic_worker);
2757                 fs_info->scrub_wr_completion_workers.idle_thresh = 2;
2758                 ret = btrfs_start_workers(
2759                                 &fs_info->scrub_wr_completion_workers);
2760                 if (ret)
2761                         goto out;
2762                 btrfs_init_workers(&fs_info->scrub_nocow_workers, "scrubnc", 1,
2763                                    &fs_info->generic_worker);
2764                 ret = btrfs_start_workers(&fs_info->scrub_nocow_workers);
2765                 if (ret)
2766                         goto out;
2767         }
2768         ++fs_info->scrub_workers_refcnt;
2769 out:
2770         mutex_unlock(&fs_info->scrub_lock);
2771
2772         return ret;
2773 }
2774
2775 static noinline_for_stack void scrub_workers_put(struct btrfs_fs_info *fs_info)
2776 {
2777         mutex_lock(&fs_info->scrub_lock);
2778         if (--fs_info->scrub_workers_refcnt == 0) {
2779                 btrfs_stop_workers(&fs_info->scrub_workers);
2780                 btrfs_stop_workers(&fs_info->scrub_wr_completion_workers);
2781                 btrfs_stop_workers(&fs_info->scrub_nocow_workers);
2782         }
2783         WARN_ON(fs_info->scrub_workers_refcnt < 0);
2784         mutex_unlock(&fs_info->scrub_lock);
2785 }
2786
2787 int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
2788                     u64 end, struct btrfs_scrub_progress *progress,
2789                     int readonly, int is_dev_replace)
2790 {
2791         struct scrub_ctx *sctx;
2792         int ret;
2793         struct btrfs_device *dev;
2794
2795         if (btrfs_fs_closing(fs_info))
2796                 return -EINVAL;
2797
2798         /*
2799          * check some assumptions
2800          */
2801         if (fs_info->chunk_root->nodesize != fs_info->chunk_root->leafsize) {
2802                 printk(KERN_ERR
2803                        "btrfs_scrub: size assumption nodesize == leafsize (%d == %d) fails\n",
2804                        fs_info->chunk_root->nodesize,
2805                        fs_info->chunk_root->leafsize);
2806                 return -EINVAL;
2807         }
2808
2809         if (fs_info->chunk_root->nodesize > BTRFS_STRIPE_LEN) {
2810                 /*
2811                  * in this case scrub is unable to calculate the checksum
2812                  * the way scrub is implemented. Do not handle this
2813                  * situation at all because it won't ever happen.
2814                  */
2815                 printk(KERN_ERR
2816                        "btrfs_scrub: size assumption nodesize <= BTRFS_STRIPE_LEN (%d <= %d) fails\n",
2817                        fs_info->chunk_root->nodesize, BTRFS_STRIPE_LEN);
2818                 return -EINVAL;
2819         }
2820
2821         if (fs_info->chunk_root->sectorsize != PAGE_SIZE) {
2822                 /* not supported for data w/o checksums */
2823                 printk(KERN_ERR
2824                        "btrfs_scrub: size assumption sectorsize != PAGE_SIZE (%d != %lld) fails\n",
2825                        fs_info->chunk_root->sectorsize,
2826                        (unsigned long long)PAGE_SIZE);
2827                 return -EINVAL;
2828         }
2829
2830         if (fs_info->chunk_root->nodesize >
2831             PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK ||
2832             fs_info->chunk_root->sectorsize >
2833             PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK) {
2834                 /*
2835                  * would exhaust the array bounds of pagev member in
2836                  * struct scrub_block
2837                  */
2838                 pr_err("btrfs_scrub: size assumption nodesize and sectorsize <= SCRUB_MAX_PAGES_PER_BLOCK (%d <= %d && %d <= %d) fails\n",
2839                        fs_info->chunk_root->nodesize,
2840                        SCRUB_MAX_PAGES_PER_BLOCK,
2841                        fs_info->chunk_root->sectorsize,
2842                        SCRUB_MAX_PAGES_PER_BLOCK);
2843                 return -EINVAL;
2844         }
2845
2846         ret = scrub_workers_get(fs_info, is_dev_replace);
2847         if (ret)
2848                 return ret;
2849
2850         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2851         dev = btrfs_find_device(fs_info, devid, NULL, NULL);
2852         if (!dev || (dev->missing && !is_dev_replace)) {
2853                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2854                 scrub_workers_put(fs_info);
2855                 return -ENODEV;
2856         }
2857         mutex_lock(&fs_info->scrub_lock);
2858
2859         if (!dev->in_fs_metadata || dev->is_tgtdev_for_dev_replace) {
2860                 mutex_unlock(&fs_info->scrub_lock);
2861                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2862                 scrub_workers_put(fs_info);
2863                 return -EIO;
2864         }
2865
2866         btrfs_dev_replace_lock(&fs_info->dev_replace);
2867         if (dev->scrub_device ||
2868             (!is_dev_replace &&
2869              btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) {
2870                 btrfs_dev_replace_unlock(&fs_info->dev_replace);
2871                 mutex_unlock(&fs_info->scrub_lock);
2872                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2873                 scrub_workers_put(fs_info);
2874                 return -EINPROGRESS;
2875         }
2876         btrfs_dev_replace_unlock(&fs_info->dev_replace);
2877         sctx = scrub_setup_ctx(dev, is_dev_replace);
2878         if (IS_ERR(sctx)) {
2879                 mutex_unlock(&fs_info->scrub_lock);
2880                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2881                 scrub_workers_put(fs_info);
2882                 return PTR_ERR(sctx);
2883         }
2884         sctx->readonly = readonly;
2885         dev->scrub_device = sctx;
2886
2887         atomic_inc(&fs_info->scrubs_running);
2888         mutex_unlock(&fs_info->scrub_lock);
2889         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2890
2891         if (!is_dev_replace) {
2892                 down_read(&fs_info->scrub_super_lock);
2893                 ret = scrub_supers(sctx, dev);
2894                 up_read(&fs_info->scrub_super_lock);
2895         }
2896
2897         if (!ret)
2898                 ret = scrub_enumerate_chunks(sctx, dev, start, end,
2899                                              is_dev_replace);
2900
2901         wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0);
2902         atomic_dec(&fs_info->scrubs_running);
2903         wake_up(&fs_info->scrub_pause_wait);
2904
2905         wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0);
2906
2907         if (progress)
2908                 memcpy(progress, &sctx->stat, sizeof(*progress));
2909
2910         mutex_lock(&fs_info->scrub_lock);
2911         dev->scrub_device = NULL;
2912         mutex_unlock(&fs_info->scrub_lock);
2913
2914         scrub_free_ctx(sctx);
2915         scrub_workers_put(fs_info);
2916
2917         return ret;
2918 }
2919
2920 void btrfs_scrub_pause(struct btrfs_root *root)
2921 {
2922         struct btrfs_fs_info *fs_info = root->fs_info;
2923
2924         mutex_lock(&fs_info->scrub_lock);
2925         atomic_inc(&fs_info->scrub_pause_req);
2926         while (atomic_read(&fs_info->scrubs_paused) !=
2927                atomic_read(&fs_info->scrubs_running)) {
2928                 mutex_unlock(&fs_info->scrub_lock);
2929                 wait_event(fs_info->scrub_pause_wait,
2930                            atomic_read(&fs_info->scrubs_paused) ==
2931                            atomic_read(&fs_info->scrubs_running));
2932                 mutex_lock(&fs_info->scrub_lock);
2933         }
2934         mutex_unlock(&fs_info->scrub_lock);
2935 }
2936
2937 void btrfs_scrub_continue(struct btrfs_root *root)
2938 {
2939         struct btrfs_fs_info *fs_info = root->fs_info;
2940
2941         atomic_dec(&fs_info->scrub_pause_req);
2942         wake_up(&fs_info->scrub_pause_wait);
2943 }
2944
2945 void btrfs_scrub_pause_super(struct btrfs_root *root)
2946 {
2947         down_write(&root->fs_info->scrub_super_lock);
2948 }
2949
2950 void btrfs_scrub_continue_super(struct btrfs_root *root)
2951 {
2952         up_write(&root->fs_info->scrub_super_lock);
2953 }
2954
2955 int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
2956 {
2957         mutex_lock(&fs_info->scrub_lock);
2958         if (!atomic_read(&fs_info->scrubs_running)) {
2959                 mutex_unlock(&fs_info->scrub_lock);
2960                 return -ENOTCONN;
2961         }
2962
2963         atomic_inc(&fs_info->scrub_cancel_req);
2964         while (atomic_read(&fs_info->scrubs_running)) {
2965                 mutex_unlock(&fs_info->scrub_lock);
2966                 wait_event(fs_info->scrub_pause_wait,
2967                            atomic_read(&fs_info->scrubs_running) == 0);
2968                 mutex_lock(&fs_info->scrub_lock);
2969         }
2970         atomic_dec(&fs_info->scrub_cancel_req);
2971         mutex_unlock(&fs_info->scrub_lock);
2972
2973         return 0;
2974 }
2975
2976 int btrfs_scrub_cancel_dev(struct btrfs_fs_info *fs_info,
2977                            struct btrfs_device *dev)
2978 {
2979         struct scrub_ctx *sctx;
2980
2981         mutex_lock(&fs_info->scrub_lock);
2982         sctx = dev->scrub_device;
2983         if (!sctx) {
2984                 mutex_unlock(&fs_info->scrub_lock);
2985                 return -ENOTCONN;
2986         }
2987         atomic_inc(&sctx->cancel_req);
2988         while (dev->scrub_device) {
2989                 mutex_unlock(&fs_info->scrub_lock);
2990                 wait_event(fs_info->scrub_pause_wait,
2991                            dev->scrub_device == NULL);
2992                 mutex_lock(&fs_info->scrub_lock);
2993         }
2994         mutex_unlock(&fs_info->scrub_lock);
2995
2996         return 0;
2997 }
2998
2999 int btrfs_scrub_cancel_devid(struct btrfs_root *root, u64 devid)
3000 {
3001         struct btrfs_fs_info *fs_info = root->fs_info;
3002         struct btrfs_device *dev;
3003         int ret;
3004
3005         /*
3006          * we have to hold the device_list_mutex here so the device
3007          * does not go away in cancel_dev. FIXME: find a better solution
3008          */
3009         mutex_lock(&fs_info->fs_devices->device_list_mutex);
3010         dev = btrfs_find_device(fs_info, devid, NULL, NULL);
3011         if (!dev) {
3012                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3013                 return -ENODEV;
3014         }
3015         ret = btrfs_scrub_cancel_dev(fs_info, dev);
3016         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3017
3018         return ret;
3019 }
3020
3021 int btrfs_scrub_progress(struct btrfs_root *root, u64 devid,
3022                          struct btrfs_scrub_progress *progress)
3023 {
3024         struct btrfs_device *dev;
3025         struct scrub_ctx *sctx = NULL;
3026
3027         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
3028         dev = btrfs_find_device(root->fs_info, devid, NULL, NULL);
3029         if (dev)
3030                 sctx = dev->scrub_device;
3031         if (sctx)
3032                 memcpy(progress, &sctx->stat, sizeof(*progress));
3033         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
3034
3035         return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;
3036 }
3037
3038 static void scrub_remap_extent(struct btrfs_fs_info *fs_info,
3039                                u64 extent_logical, u64 extent_len,
3040                                u64 *extent_physical,
3041                                struct btrfs_device **extent_dev,
3042                                int *extent_mirror_num)
3043 {
3044         u64 mapped_length;
3045         struct btrfs_bio *bbio = NULL;
3046         int ret;
3047
3048         mapped_length = extent_len;
3049         ret = btrfs_map_block(fs_info, READ, extent_logical,
3050                               &mapped_length, &bbio, 0);
3051         if (ret || !bbio || mapped_length < extent_len ||
3052             !bbio->stripes[0].dev->bdev) {
3053                 kfree(bbio);
3054                 return;
3055         }
3056
3057         *extent_physical = bbio->stripes[0].physical;
3058         *extent_mirror_num = bbio->mirror_num;
3059         *extent_dev = bbio->stripes[0].dev;
3060         kfree(bbio);
3061 }
3062
3063 static int scrub_setup_wr_ctx(struct scrub_ctx *sctx,
3064                               struct scrub_wr_ctx *wr_ctx,
3065                               struct btrfs_fs_info *fs_info,
3066                               struct btrfs_device *dev,
3067                               int is_dev_replace)
3068 {
3069         WARN_ON(wr_ctx->wr_curr_bio != NULL);
3070
3071         mutex_init(&wr_ctx->wr_lock);
3072         wr_ctx->wr_curr_bio = NULL;
3073         if (!is_dev_replace)
3074                 return 0;
3075
3076         WARN_ON(!dev->bdev);
3077         wr_ctx->pages_per_wr_bio = min_t(int, SCRUB_PAGES_PER_WR_BIO,
3078                                          bio_get_nr_vecs(dev->bdev));
3079         wr_ctx->tgtdev = dev;
3080         atomic_set(&wr_ctx->flush_all_writes, 0);
3081         return 0;
3082 }
3083
3084 static void scrub_free_wr_ctx(struct scrub_wr_ctx *wr_ctx)
3085 {
3086         mutex_lock(&wr_ctx->wr_lock);
3087         kfree(wr_ctx->wr_curr_bio);
3088         wr_ctx->wr_curr_bio = NULL;
3089         mutex_unlock(&wr_ctx->wr_lock);
3090 }
3091
3092 static int copy_nocow_pages(struct scrub_ctx *sctx, u64 logical, u64 len,
3093                             int mirror_num, u64 physical_for_dev_replace)
3094 {
3095         struct scrub_copy_nocow_ctx *nocow_ctx;
3096         struct btrfs_fs_info *fs_info = sctx->dev_root->fs_info;
3097
3098         nocow_ctx = kzalloc(sizeof(*nocow_ctx), GFP_NOFS);
3099         if (!nocow_ctx) {
3100                 spin_lock(&sctx->stat_lock);
3101                 sctx->stat.malloc_errors++;
3102                 spin_unlock(&sctx->stat_lock);
3103                 return -ENOMEM;
3104         }
3105
3106         scrub_pending_trans_workers_inc(sctx);
3107
3108         nocow_ctx->sctx = sctx;
3109         nocow_ctx->logical = logical;
3110         nocow_ctx->len = len;
3111         nocow_ctx->mirror_num = mirror_num;
3112         nocow_ctx->physical_for_dev_replace = physical_for_dev_replace;
3113         nocow_ctx->work.func = copy_nocow_pages_worker;
3114         btrfs_queue_worker(&fs_info->scrub_nocow_workers,
3115                            &nocow_ctx->work);
3116
3117         return 0;
3118 }
3119
3120 static void copy_nocow_pages_worker(struct btrfs_work *work)
3121 {
3122         struct scrub_copy_nocow_ctx *nocow_ctx =
3123                 container_of(work, struct scrub_copy_nocow_ctx, work);
3124         struct scrub_ctx *sctx = nocow_ctx->sctx;
3125         u64 logical = nocow_ctx->logical;
3126         u64 len = nocow_ctx->len;
3127         int mirror_num = nocow_ctx->mirror_num;
3128         u64 physical_for_dev_replace = nocow_ctx->physical_for_dev_replace;
3129         int ret;
3130         struct btrfs_trans_handle *trans = NULL;
3131         struct btrfs_fs_info *fs_info;
3132         struct btrfs_path *path;
3133         struct btrfs_root *root;
3134         int not_written = 0;
3135
3136         fs_info = sctx->dev_root->fs_info;
3137         root = fs_info->extent_root;
3138
3139         path = btrfs_alloc_path();
3140         if (!path) {
3141                 spin_lock(&sctx->stat_lock);
3142                 sctx->stat.malloc_errors++;
3143                 spin_unlock(&sctx->stat_lock);
3144                 not_written = 1;
3145                 goto out;
3146         }
3147
3148         trans = btrfs_join_transaction(root);
3149         if (IS_ERR(trans)) {
3150                 not_written = 1;
3151                 goto out;
3152         }
3153
3154         ret = iterate_inodes_from_logical(logical, fs_info, path,
3155                                           copy_nocow_pages_for_inode,
3156                                           nocow_ctx);
3157         if (ret != 0 && ret != -ENOENT) {
3158                 pr_warn("iterate_inodes_from_logical() failed: log %llu, phys %llu, len %llu, mir %llu, ret %d\n",
3159                         (unsigned long long)logical,
3160                         (unsigned long long)physical_for_dev_replace,
3161                         (unsigned long long)len,
3162                         (unsigned long long)mirror_num, ret);
3163                 not_written = 1;
3164                 goto out;
3165         }
3166
3167 out:
3168         if (trans && !IS_ERR(trans))
3169                 btrfs_end_transaction(trans, root);
3170         if (not_written)
3171                 btrfs_dev_replace_stats_inc(&fs_info->dev_replace.
3172                                             num_uncorrectable_read_errors);
3173
3174         btrfs_free_path(path);
3175         kfree(nocow_ctx);
3176
3177         scrub_pending_trans_workers_dec(sctx);
3178 }
3179
3180 static int copy_nocow_pages_for_inode(u64 inum, u64 offset, u64 root, void *ctx)
3181 {
3182         unsigned long index;
3183         struct scrub_copy_nocow_ctx *nocow_ctx = ctx;
3184         int ret = 0;
3185         struct btrfs_key key;
3186         struct inode *inode = NULL;
3187         struct btrfs_root *local_root;
3188         u64 physical_for_dev_replace;
3189         u64 len;
3190         struct btrfs_fs_info *fs_info = nocow_ctx->sctx->dev_root->fs_info;
3191
3192         key.objectid = root;
3193         key.type = BTRFS_ROOT_ITEM_KEY;
3194         key.offset = (u64)-1;
3195         local_root = btrfs_read_fs_root_no_name(fs_info, &key);
3196         if (IS_ERR(local_root))
3197                 return PTR_ERR(local_root);
3198
3199         key.type = BTRFS_INODE_ITEM_KEY;
3200         key.objectid = inum;
3201         key.offset = 0;
3202         inode = btrfs_iget(fs_info->sb, &key, local_root, NULL);
3203         if (IS_ERR(inode))
3204                 return PTR_ERR(inode);
3205
3206         physical_for_dev_replace = nocow_ctx->physical_for_dev_replace;
3207         len = nocow_ctx->len;
3208         while (len >= PAGE_CACHE_SIZE) {
3209                 struct page *page = NULL;
3210                 int ret_sub;
3211
3212                 index = offset >> PAGE_CACHE_SHIFT;
3213
3214                 page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
3215                 if (!page) {
3216                         pr_err("find_or_create_page() failed\n");
3217                         ret = -ENOMEM;
3218                         goto next_page;
3219                 }
3220
3221                 if (PageUptodate(page)) {
3222                         if (PageDirty(page))
3223                                 goto next_page;
3224                 } else {
3225                         ClearPageError(page);
3226                         ret_sub = extent_read_full_page(&BTRFS_I(inode)->
3227                                                          io_tree,
3228                                                         page, btrfs_get_extent,
3229                                                         nocow_ctx->mirror_num);
3230                         if (ret_sub) {
3231                                 ret = ret_sub;
3232                                 goto next_page;
3233                         }
3234                         wait_on_page_locked(page);
3235                         if (!PageUptodate(page)) {
3236                                 ret = -EIO;
3237                                 goto next_page;
3238                         }
3239                 }
3240                 ret_sub = write_page_nocow(nocow_ctx->sctx,
3241                                            physical_for_dev_replace, page);
3242                 if (ret_sub) {
3243                         ret = ret_sub;
3244                         goto next_page;
3245                 }
3246
3247 next_page:
3248                 if (page) {
3249                         unlock_page(page);
3250                         put_page(page);
3251                 }
3252                 offset += PAGE_CACHE_SIZE;
3253                 physical_for_dev_replace += PAGE_CACHE_SIZE;
3254                 len -= PAGE_CACHE_SIZE;
3255         }
3256
3257         if (inode)
3258                 iput(inode);
3259         return ret;
3260 }
3261
3262 static int write_page_nocow(struct scrub_ctx *sctx,
3263                             u64 physical_for_dev_replace, struct page *page)
3264 {
3265         struct bio *bio;
3266         struct btrfs_device *dev;
3267         int ret;
3268         DECLARE_COMPLETION_ONSTACK(compl);
3269
3270         dev = sctx->wr_ctx.tgtdev;
3271         if (!dev)
3272                 return -EIO;
3273         if (!dev->bdev) {
3274                 printk_ratelimited(KERN_WARNING
3275                         "btrfs: scrub write_page_nocow(bdev == NULL) is unexpected!\n");
3276                 return -EIO;
3277         }
3278         bio = bio_alloc(GFP_NOFS, 1);
3279         if (!bio) {
3280                 spin_lock(&sctx->stat_lock);
3281                 sctx->stat.malloc_errors++;
3282                 spin_unlock(&sctx->stat_lock);
3283                 return -ENOMEM;
3284         }
3285         bio->bi_private = &compl;
3286         bio->bi_end_io = scrub_complete_bio_end_io;
3287         bio->bi_size = 0;
3288         bio->bi_sector = physical_for_dev_replace >> 9;
3289         bio->bi_bdev = dev->bdev;
3290         ret = bio_add_page(bio, page, PAGE_CACHE_SIZE, 0);
3291         if (ret != PAGE_CACHE_SIZE) {
3292 leave_with_eio:
3293                 bio_put(bio);
3294                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
3295                 return -EIO;
3296         }
3297         btrfsic_submit_bio(WRITE_SYNC, bio);
3298         wait_for_completion(&compl);
3299
3300         if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
3301                 goto leave_with_eio;
3302
3303         bio_put(bio);
3304         return 0;
3305 }