btrfs: extent_io: Handle errors better in btree_write_cache_pages()
[sfrench/cifs-2.6.git] / fs / btrfs / extent_io.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
5 #include <linux/bio.h>
6 #include <linux/mm.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/cleancache.h>
16 #include "extent_io.h"
17 #include "extent_map.h"
18 #include "ctree.h"
19 #include "btrfs_inode.h"
20 #include "volumes.h"
21 #include "check-integrity.h"
22 #include "locking.h"
23 #include "rcu-string.h"
24 #include "backref.h"
25 #include "disk-io.h"
26
27 static struct kmem_cache *extent_state_cache;
28 static struct kmem_cache *extent_buffer_cache;
29 static struct bio_set btrfs_bioset;
30
31 static inline bool extent_state_in_tree(const struct extent_state *state)
32 {
33         return !RB_EMPTY_NODE(&state->rb_node);
34 }
35
36 #ifdef CONFIG_BTRFS_DEBUG
37 static LIST_HEAD(buffers);
38 static LIST_HEAD(states);
39
40 static DEFINE_SPINLOCK(leak_lock);
41
42 static inline
43 void btrfs_leak_debug_add(struct list_head *new, struct list_head *head)
44 {
45         unsigned long flags;
46
47         spin_lock_irqsave(&leak_lock, flags);
48         list_add(new, head);
49         spin_unlock_irqrestore(&leak_lock, flags);
50 }
51
52 static inline
53 void btrfs_leak_debug_del(struct list_head *entry)
54 {
55         unsigned long flags;
56
57         spin_lock_irqsave(&leak_lock, flags);
58         list_del(entry);
59         spin_unlock_irqrestore(&leak_lock, flags);
60 }
61
62 static inline
63 void btrfs_leak_debug_check(void)
64 {
65         struct extent_state *state;
66         struct extent_buffer *eb;
67
68         while (!list_empty(&states)) {
69                 state = list_entry(states.next, struct extent_state, leak_list);
70                 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
71                        state->start, state->end, state->state,
72                        extent_state_in_tree(state),
73                        refcount_read(&state->refs));
74                 list_del(&state->leak_list);
75                 kmem_cache_free(extent_state_cache, state);
76         }
77
78         while (!list_empty(&buffers)) {
79                 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
80                 pr_err("BTRFS: buffer leak start %llu len %lu refs %d bflags %lu\n",
81                        eb->start, eb->len, atomic_read(&eb->refs), eb->bflags);
82                 list_del(&eb->leak_list);
83                 kmem_cache_free(extent_buffer_cache, eb);
84         }
85 }
86
87 #define btrfs_debug_check_extent_io_range(tree, start, end)             \
88         __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
89 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
90                 struct extent_io_tree *tree, u64 start, u64 end)
91 {
92         struct inode *inode = tree->private_data;
93         u64 isize;
94
95         if (!inode || !is_data_inode(inode))
96                 return;
97
98         isize = i_size_read(inode);
99         if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
100                 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
101                     "%s: ino %llu isize %llu odd range [%llu,%llu]",
102                         caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
103         }
104 }
105 #else
106 #define btrfs_leak_debug_add(new, head) do {} while (0)
107 #define btrfs_leak_debug_del(entry)     do {} while (0)
108 #define btrfs_leak_debug_check()        do {} while (0)
109 #define btrfs_debug_check_extent_io_range(c, s, e)      do {} while (0)
110 #endif
111
112 #define BUFFER_LRU_MAX 64
113
114 struct tree_entry {
115         u64 start;
116         u64 end;
117         struct rb_node rb_node;
118 };
119
120 struct extent_page_data {
121         struct bio *bio;
122         struct extent_io_tree *tree;
123         /* tells writepage not to lock the state bits for this range
124          * it still does the unlocking
125          */
126         unsigned int extent_locked:1;
127
128         /* tells the submit_bio code to use REQ_SYNC */
129         unsigned int sync_io:1;
130 };
131
132 static int add_extent_changeset(struct extent_state *state, unsigned bits,
133                                  struct extent_changeset *changeset,
134                                  int set)
135 {
136         int ret;
137
138         if (!changeset)
139                 return 0;
140         if (set && (state->state & bits) == bits)
141                 return 0;
142         if (!set && (state->state & bits) == 0)
143                 return 0;
144         changeset->bytes_changed += state->end - state->start + 1;
145         ret = ulist_add(&changeset->range_changed, state->start, state->end,
146                         GFP_ATOMIC);
147         return ret;
148 }
149
150 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
151                                        unsigned long bio_flags)
152 {
153         blk_status_t ret = 0;
154         struct bio_vec *bvec = bio_last_bvec_all(bio);
155         struct bio_vec bv;
156         struct extent_io_tree *tree = bio->bi_private;
157         u64 start;
158
159         mp_bvec_last_segment(bvec, &bv);
160         start = page_offset(bv.bv_page) + bv.bv_offset;
161
162         bio->bi_private = NULL;
163
164         if (tree->ops)
165                 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
166                                            mirror_num, bio_flags, start);
167         else
168                 btrfsic_submit_bio(bio);
169
170         return blk_status_to_errno(ret);
171 }
172
173 /* Cleanup unsubmitted bios */
174 static void end_write_bio(struct extent_page_data *epd, int ret)
175 {
176         if (epd->bio) {
177                 epd->bio->bi_status = errno_to_blk_status(ret);
178                 bio_endio(epd->bio);
179                 epd->bio = NULL;
180         }
181 }
182
183 /*
184  * Submit bio from extent page data via submit_one_bio
185  *
186  * Return 0 if everything is OK.
187  * Return <0 for error.
188  */
189 static int __must_check flush_write_bio(struct extent_page_data *epd)
190 {
191         int ret = 0;
192
193         if (epd->bio) {
194                 ret = submit_one_bio(epd->bio, 0, 0);
195                 /*
196                  * Clean up of epd->bio is handled by its endio function.
197                  * And endio is either triggered by successful bio execution
198                  * or the error handler of submit bio hook.
199                  * So at this point, no matter what happened, we don't need
200                  * to clean up epd->bio.
201                  */
202                 epd->bio = NULL;
203         }
204         return ret;
205 }
206
207 int __init extent_io_init(void)
208 {
209         extent_state_cache = kmem_cache_create("btrfs_extent_state",
210                         sizeof(struct extent_state), 0,
211                         SLAB_MEM_SPREAD, NULL);
212         if (!extent_state_cache)
213                 return -ENOMEM;
214
215         extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
216                         sizeof(struct extent_buffer), 0,
217                         SLAB_MEM_SPREAD, NULL);
218         if (!extent_buffer_cache)
219                 goto free_state_cache;
220
221         if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
222                         offsetof(struct btrfs_io_bio, bio),
223                         BIOSET_NEED_BVECS))
224                 goto free_buffer_cache;
225
226         if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
227                 goto free_bioset;
228
229         return 0;
230
231 free_bioset:
232         bioset_exit(&btrfs_bioset);
233
234 free_buffer_cache:
235         kmem_cache_destroy(extent_buffer_cache);
236         extent_buffer_cache = NULL;
237
238 free_state_cache:
239         kmem_cache_destroy(extent_state_cache);
240         extent_state_cache = NULL;
241         return -ENOMEM;
242 }
243
244 void __cold extent_io_exit(void)
245 {
246         btrfs_leak_debug_check();
247
248         /*
249          * Make sure all delayed rcu free are flushed before we
250          * destroy caches.
251          */
252         rcu_barrier();
253         kmem_cache_destroy(extent_state_cache);
254         kmem_cache_destroy(extent_buffer_cache);
255         bioset_exit(&btrfs_bioset);
256 }
257
258 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
259                          struct extent_io_tree *tree, unsigned int owner,
260                          void *private_data)
261 {
262         tree->fs_info = fs_info;
263         tree->state = RB_ROOT;
264         tree->ops = NULL;
265         tree->dirty_bytes = 0;
266         spin_lock_init(&tree->lock);
267         tree->private_data = private_data;
268         tree->owner = owner;
269 }
270
271 static struct extent_state *alloc_extent_state(gfp_t mask)
272 {
273         struct extent_state *state;
274
275         /*
276          * The given mask might be not appropriate for the slab allocator,
277          * drop the unsupported bits
278          */
279         mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
280         state = kmem_cache_alloc(extent_state_cache, mask);
281         if (!state)
282                 return state;
283         state->state = 0;
284         state->failrec = NULL;
285         RB_CLEAR_NODE(&state->rb_node);
286         btrfs_leak_debug_add(&state->leak_list, &states);
287         refcount_set(&state->refs, 1);
288         init_waitqueue_head(&state->wq);
289         trace_alloc_extent_state(state, mask, _RET_IP_);
290         return state;
291 }
292
293 void free_extent_state(struct extent_state *state)
294 {
295         if (!state)
296                 return;
297         if (refcount_dec_and_test(&state->refs)) {
298                 WARN_ON(extent_state_in_tree(state));
299                 btrfs_leak_debug_del(&state->leak_list);
300                 trace_free_extent_state(state, _RET_IP_);
301                 kmem_cache_free(extent_state_cache, state);
302         }
303 }
304
305 static struct rb_node *tree_insert(struct rb_root *root,
306                                    struct rb_node *search_start,
307                                    u64 offset,
308                                    struct rb_node *node,
309                                    struct rb_node ***p_in,
310                                    struct rb_node **parent_in)
311 {
312         struct rb_node **p;
313         struct rb_node *parent = NULL;
314         struct tree_entry *entry;
315
316         if (p_in && parent_in) {
317                 p = *p_in;
318                 parent = *parent_in;
319                 goto do_insert;
320         }
321
322         p = search_start ? &search_start : &root->rb_node;
323         while (*p) {
324                 parent = *p;
325                 entry = rb_entry(parent, struct tree_entry, rb_node);
326
327                 if (offset < entry->start)
328                         p = &(*p)->rb_left;
329                 else if (offset > entry->end)
330                         p = &(*p)->rb_right;
331                 else
332                         return parent;
333         }
334
335 do_insert:
336         rb_link_node(node, parent, p);
337         rb_insert_color(node, root);
338         return NULL;
339 }
340
341 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
342                                       struct rb_node **next_ret,
343                                       struct rb_node **prev_ret,
344                                       struct rb_node ***p_ret,
345                                       struct rb_node **parent_ret)
346 {
347         struct rb_root *root = &tree->state;
348         struct rb_node **n = &root->rb_node;
349         struct rb_node *prev = NULL;
350         struct rb_node *orig_prev = NULL;
351         struct tree_entry *entry;
352         struct tree_entry *prev_entry = NULL;
353
354         while (*n) {
355                 prev = *n;
356                 entry = rb_entry(prev, struct tree_entry, rb_node);
357                 prev_entry = entry;
358
359                 if (offset < entry->start)
360                         n = &(*n)->rb_left;
361                 else if (offset > entry->end)
362                         n = &(*n)->rb_right;
363                 else
364                         return *n;
365         }
366
367         if (p_ret)
368                 *p_ret = n;
369         if (parent_ret)
370                 *parent_ret = prev;
371
372         if (next_ret) {
373                 orig_prev = prev;
374                 while (prev && offset > prev_entry->end) {
375                         prev = rb_next(prev);
376                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
377                 }
378                 *next_ret = prev;
379                 prev = orig_prev;
380         }
381
382         if (prev_ret) {
383                 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
384                 while (prev && offset < prev_entry->start) {
385                         prev = rb_prev(prev);
386                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
387                 }
388                 *prev_ret = prev;
389         }
390         return NULL;
391 }
392
393 static inline struct rb_node *
394 tree_search_for_insert(struct extent_io_tree *tree,
395                        u64 offset,
396                        struct rb_node ***p_ret,
397                        struct rb_node **parent_ret)
398 {
399         struct rb_node *next= NULL;
400         struct rb_node *ret;
401
402         ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
403         if (!ret)
404                 return next;
405         return ret;
406 }
407
408 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
409                                           u64 offset)
410 {
411         return tree_search_for_insert(tree, offset, NULL, NULL);
412 }
413
414 /*
415  * utility function to look for merge candidates inside a given range.
416  * Any extents with matching state are merged together into a single
417  * extent in the tree.  Extents with EXTENT_IO in their state field
418  * are not merged because the end_io handlers need to be able to do
419  * operations on them without sleeping (or doing allocations/splits).
420  *
421  * This should be called with the tree lock held.
422  */
423 static void merge_state(struct extent_io_tree *tree,
424                         struct extent_state *state)
425 {
426         struct extent_state *other;
427         struct rb_node *other_node;
428
429         if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
430                 return;
431
432         other_node = rb_prev(&state->rb_node);
433         if (other_node) {
434                 other = rb_entry(other_node, struct extent_state, rb_node);
435                 if (other->end == state->start - 1 &&
436                     other->state == state->state) {
437                         if (tree->private_data &&
438                             is_data_inode(tree->private_data))
439                                 btrfs_merge_delalloc_extent(tree->private_data,
440                                                             state, other);
441                         state->start = other->start;
442                         rb_erase(&other->rb_node, &tree->state);
443                         RB_CLEAR_NODE(&other->rb_node);
444                         free_extent_state(other);
445                 }
446         }
447         other_node = rb_next(&state->rb_node);
448         if (other_node) {
449                 other = rb_entry(other_node, struct extent_state, rb_node);
450                 if (other->start == state->end + 1 &&
451                     other->state == state->state) {
452                         if (tree->private_data &&
453                             is_data_inode(tree->private_data))
454                                 btrfs_merge_delalloc_extent(tree->private_data,
455                                                             state, other);
456                         state->end = other->end;
457                         rb_erase(&other->rb_node, &tree->state);
458                         RB_CLEAR_NODE(&other->rb_node);
459                         free_extent_state(other);
460                 }
461         }
462 }
463
464 static void set_state_bits(struct extent_io_tree *tree,
465                            struct extent_state *state, unsigned *bits,
466                            struct extent_changeset *changeset);
467
468 /*
469  * insert an extent_state struct into the tree.  'bits' are set on the
470  * struct before it is inserted.
471  *
472  * This may return -EEXIST if the extent is already there, in which case the
473  * state struct is freed.
474  *
475  * The tree lock is not taken internally.  This is a utility function and
476  * probably isn't what you want to call (see set/clear_extent_bit).
477  */
478 static int insert_state(struct extent_io_tree *tree,
479                         struct extent_state *state, u64 start, u64 end,
480                         struct rb_node ***p,
481                         struct rb_node **parent,
482                         unsigned *bits, struct extent_changeset *changeset)
483 {
484         struct rb_node *node;
485
486         if (end < start)
487                 WARN(1, KERN_ERR "BTRFS: end < start %llu %llu\n",
488                        end, start);
489         state->start = start;
490         state->end = end;
491
492         set_state_bits(tree, state, bits, changeset);
493
494         node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
495         if (node) {
496                 struct extent_state *found;
497                 found = rb_entry(node, struct extent_state, rb_node);
498                 pr_err("BTRFS: found node %llu %llu on insert of %llu %llu\n",
499                        found->start, found->end, start, end);
500                 return -EEXIST;
501         }
502         merge_state(tree, state);
503         return 0;
504 }
505
506 /*
507  * split a given extent state struct in two, inserting the preallocated
508  * struct 'prealloc' as the newly created second half.  'split' indicates an
509  * offset inside 'orig' where it should be split.
510  *
511  * Before calling,
512  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
513  * are two extent state structs in the tree:
514  * prealloc: [orig->start, split - 1]
515  * orig: [ split, orig->end ]
516  *
517  * The tree locks are not taken by this function. They need to be held
518  * by the caller.
519  */
520 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
521                        struct extent_state *prealloc, u64 split)
522 {
523         struct rb_node *node;
524
525         if (tree->private_data && is_data_inode(tree->private_data))
526                 btrfs_split_delalloc_extent(tree->private_data, orig, split);
527
528         prealloc->start = orig->start;
529         prealloc->end = split - 1;
530         prealloc->state = orig->state;
531         orig->start = split;
532
533         node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
534                            &prealloc->rb_node, NULL, NULL);
535         if (node) {
536                 free_extent_state(prealloc);
537                 return -EEXIST;
538         }
539         return 0;
540 }
541
542 static struct extent_state *next_state(struct extent_state *state)
543 {
544         struct rb_node *next = rb_next(&state->rb_node);
545         if (next)
546                 return rb_entry(next, struct extent_state, rb_node);
547         else
548                 return NULL;
549 }
550
551 /*
552  * utility function to clear some bits in an extent state struct.
553  * it will optionally wake up anyone waiting on this state (wake == 1).
554  *
555  * If no bits are set on the state struct after clearing things, the
556  * struct is freed and removed from the tree
557  */
558 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
559                                             struct extent_state *state,
560                                             unsigned *bits, int wake,
561                                             struct extent_changeset *changeset)
562 {
563         struct extent_state *next;
564         unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
565         int ret;
566
567         if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
568                 u64 range = state->end - state->start + 1;
569                 WARN_ON(range > tree->dirty_bytes);
570                 tree->dirty_bytes -= range;
571         }
572
573         if (tree->private_data && is_data_inode(tree->private_data))
574                 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
575
576         ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
577         BUG_ON(ret < 0);
578         state->state &= ~bits_to_clear;
579         if (wake)
580                 wake_up(&state->wq);
581         if (state->state == 0) {
582                 next = next_state(state);
583                 if (extent_state_in_tree(state)) {
584                         rb_erase(&state->rb_node, &tree->state);
585                         RB_CLEAR_NODE(&state->rb_node);
586                         free_extent_state(state);
587                 } else {
588                         WARN_ON(1);
589                 }
590         } else {
591                 merge_state(tree, state);
592                 next = next_state(state);
593         }
594         return next;
595 }
596
597 static struct extent_state *
598 alloc_extent_state_atomic(struct extent_state *prealloc)
599 {
600         if (!prealloc)
601                 prealloc = alloc_extent_state(GFP_ATOMIC);
602
603         return prealloc;
604 }
605
606 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
607 {
608         struct inode *inode = tree->private_data;
609
610         btrfs_panic(btrfs_sb(inode->i_sb), err,
611         "locking error: extent tree was modified by another thread while locked");
612 }
613
614 /*
615  * clear some bits on a range in the tree.  This may require splitting
616  * or inserting elements in the tree, so the gfp mask is used to
617  * indicate which allocations or sleeping are allowed.
618  *
619  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
620  * the given range from the tree regardless of state (ie for truncate).
621  *
622  * the range [start, end] is inclusive.
623  *
624  * This takes the tree lock, and returns 0 on success and < 0 on error.
625  */
626 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
627                               unsigned bits, int wake, int delete,
628                               struct extent_state **cached_state,
629                               gfp_t mask, struct extent_changeset *changeset)
630 {
631         struct extent_state *state;
632         struct extent_state *cached;
633         struct extent_state *prealloc = NULL;
634         struct rb_node *node;
635         u64 last_end;
636         int err;
637         int clear = 0;
638
639         btrfs_debug_check_extent_io_range(tree, start, end);
640         trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
641
642         if (bits & EXTENT_DELALLOC)
643                 bits |= EXTENT_NORESERVE;
644
645         if (delete)
646                 bits |= ~EXTENT_CTLBITS;
647
648         if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
649                 clear = 1;
650 again:
651         if (!prealloc && gfpflags_allow_blocking(mask)) {
652                 /*
653                  * Don't care for allocation failure here because we might end
654                  * up not needing the pre-allocated extent state at all, which
655                  * is the case if we only have in the tree extent states that
656                  * cover our input range and don't cover too any other range.
657                  * If we end up needing a new extent state we allocate it later.
658                  */
659                 prealloc = alloc_extent_state(mask);
660         }
661
662         spin_lock(&tree->lock);
663         if (cached_state) {
664                 cached = *cached_state;
665
666                 if (clear) {
667                         *cached_state = NULL;
668                         cached_state = NULL;
669                 }
670
671                 if (cached && extent_state_in_tree(cached) &&
672                     cached->start <= start && cached->end > start) {
673                         if (clear)
674                                 refcount_dec(&cached->refs);
675                         state = cached;
676                         goto hit_next;
677                 }
678                 if (clear)
679                         free_extent_state(cached);
680         }
681         /*
682          * this search will find the extents that end after
683          * our range starts
684          */
685         node = tree_search(tree, start);
686         if (!node)
687                 goto out;
688         state = rb_entry(node, struct extent_state, rb_node);
689 hit_next:
690         if (state->start > end)
691                 goto out;
692         WARN_ON(state->end < start);
693         last_end = state->end;
694
695         /* the state doesn't have the wanted bits, go ahead */
696         if (!(state->state & bits)) {
697                 state = next_state(state);
698                 goto next;
699         }
700
701         /*
702          *     | ---- desired range ---- |
703          *  | state | or
704          *  | ------------- state -------------- |
705          *
706          * We need to split the extent we found, and may flip
707          * bits on second half.
708          *
709          * If the extent we found extends past our range, we
710          * just split and search again.  It'll get split again
711          * the next time though.
712          *
713          * If the extent we found is inside our range, we clear
714          * the desired bit on it.
715          */
716
717         if (state->start < start) {
718                 prealloc = alloc_extent_state_atomic(prealloc);
719                 BUG_ON(!prealloc);
720                 err = split_state(tree, state, prealloc, start);
721                 if (err)
722                         extent_io_tree_panic(tree, err);
723
724                 prealloc = NULL;
725                 if (err)
726                         goto out;
727                 if (state->end <= end) {
728                         state = clear_state_bit(tree, state, &bits, wake,
729                                                 changeset);
730                         goto next;
731                 }
732                 goto search_again;
733         }
734         /*
735          * | ---- desired range ---- |
736          *                        | state |
737          * We need to split the extent, and clear the bit
738          * on the first half
739          */
740         if (state->start <= end && state->end > end) {
741                 prealloc = alloc_extent_state_atomic(prealloc);
742                 BUG_ON(!prealloc);
743                 err = split_state(tree, state, prealloc, end + 1);
744                 if (err)
745                         extent_io_tree_panic(tree, err);
746
747                 if (wake)
748                         wake_up(&state->wq);
749
750                 clear_state_bit(tree, prealloc, &bits, wake, changeset);
751
752                 prealloc = NULL;
753                 goto out;
754         }
755
756         state = clear_state_bit(tree, state, &bits, wake, changeset);
757 next:
758         if (last_end == (u64)-1)
759                 goto out;
760         start = last_end + 1;
761         if (start <= end && state && !need_resched())
762                 goto hit_next;
763
764 search_again:
765         if (start > end)
766                 goto out;
767         spin_unlock(&tree->lock);
768         if (gfpflags_allow_blocking(mask))
769                 cond_resched();
770         goto again;
771
772 out:
773         spin_unlock(&tree->lock);
774         if (prealloc)
775                 free_extent_state(prealloc);
776
777         return 0;
778
779 }
780
781 static void wait_on_state(struct extent_io_tree *tree,
782                           struct extent_state *state)
783                 __releases(tree->lock)
784                 __acquires(tree->lock)
785 {
786         DEFINE_WAIT(wait);
787         prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
788         spin_unlock(&tree->lock);
789         schedule();
790         spin_lock(&tree->lock);
791         finish_wait(&state->wq, &wait);
792 }
793
794 /*
795  * waits for one or more bits to clear on a range in the state tree.
796  * The range [start, end] is inclusive.
797  * The tree lock is taken by this function
798  */
799 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
800                             unsigned long bits)
801 {
802         struct extent_state *state;
803         struct rb_node *node;
804
805         btrfs_debug_check_extent_io_range(tree, start, end);
806
807         spin_lock(&tree->lock);
808 again:
809         while (1) {
810                 /*
811                  * this search will find all the extents that end after
812                  * our range starts
813                  */
814                 node = tree_search(tree, start);
815 process_node:
816                 if (!node)
817                         break;
818
819                 state = rb_entry(node, struct extent_state, rb_node);
820
821                 if (state->start > end)
822                         goto out;
823
824                 if (state->state & bits) {
825                         start = state->start;
826                         refcount_inc(&state->refs);
827                         wait_on_state(tree, state);
828                         free_extent_state(state);
829                         goto again;
830                 }
831                 start = state->end + 1;
832
833                 if (start > end)
834                         break;
835
836                 if (!cond_resched_lock(&tree->lock)) {
837                         node = rb_next(node);
838                         goto process_node;
839                 }
840         }
841 out:
842         spin_unlock(&tree->lock);
843 }
844
845 static void set_state_bits(struct extent_io_tree *tree,
846                            struct extent_state *state,
847                            unsigned *bits, struct extent_changeset *changeset)
848 {
849         unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
850         int ret;
851
852         if (tree->private_data && is_data_inode(tree->private_data))
853                 btrfs_set_delalloc_extent(tree->private_data, state, bits);
854
855         if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
856                 u64 range = state->end - state->start + 1;
857                 tree->dirty_bytes += range;
858         }
859         ret = add_extent_changeset(state, bits_to_set, changeset, 1);
860         BUG_ON(ret < 0);
861         state->state |= bits_to_set;
862 }
863
864 static void cache_state_if_flags(struct extent_state *state,
865                                  struct extent_state **cached_ptr,
866                                  unsigned flags)
867 {
868         if (cached_ptr && !(*cached_ptr)) {
869                 if (!flags || (state->state & flags)) {
870                         *cached_ptr = state;
871                         refcount_inc(&state->refs);
872                 }
873         }
874 }
875
876 static void cache_state(struct extent_state *state,
877                         struct extent_state **cached_ptr)
878 {
879         return cache_state_if_flags(state, cached_ptr,
880                                     EXTENT_LOCKED | EXTENT_BOUNDARY);
881 }
882
883 /*
884  * set some bits on a range in the tree.  This may require allocations or
885  * sleeping, so the gfp mask is used to indicate what is allowed.
886  *
887  * If any of the exclusive bits are set, this will fail with -EEXIST if some
888  * part of the range already has the desired bits set.  The start of the
889  * existing range is returned in failed_start in this case.
890  *
891  * [start, end] is inclusive This takes the tree lock.
892  */
893
894 static int __must_check
895 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
896                  unsigned bits, unsigned exclusive_bits,
897                  u64 *failed_start, struct extent_state **cached_state,
898                  gfp_t mask, struct extent_changeset *changeset)
899 {
900         struct extent_state *state;
901         struct extent_state *prealloc = NULL;
902         struct rb_node *node;
903         struct rb_node **p;
904         struct rb_node *parent;
905         int err = 0;
906         u64 last_start;
907         u64 last_end;
908
909         btrfs_debug_check_extent_io_range(tree, start, end);
910         trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
911
912 again:
913         if (!prealloc && gfpflags_allow_blocking(mask)) {
914                 /*
915                  * Don't care for allocation failure here because we might end
916                  * up not needing the pre-allocated extent state at all, which
917                  * is the case if we only have in the tree extent states that
918                  * cover our input range and don't cover too any other range.
919                  * If we end up needing a new extent state we allocate it later.
920                  */
921                 prealloc = alloc_extent_state(mask);
922         }
923
924         spin_lock(&tree->lock);
925         if (cached_state && *cached_state) {
926                 state = *cached_state;
927                 if (state->start <= start && state->end > start &&
928                     extent_state_in_tree(state)) {
929                         node = &state->rb_node;
930                         goto hit_next;
931                 }
932         }
933         /*
934          * this search will find all the extents that end after
935          * our range starts.
936          */
937         node = tree_search_for_insert(tree, start, &p, &parent);
938         if (!node) {
939                 prealloc = alloc_extent_state_atomic(prealloc);
940                 BUG_ON(!prealloc);
941                 err = insert_state(tree, prealloc, start, end,
942                                    &p, &parent, &bits, changeset);
943                 if (err)
944                         extent_io_tree_panic(tree, err);
945
946                 cache_state(prealloc, cached_state);
947                 prealloc = NULL;
948                 goto out;
949         }
950         state = rb_entry(node, struct extent_state, rb_node);
951 hit_next:
952         last_start = state->start;
953         last_end = state->end;
954
955         /*
956          * | ---- desired range ---- |
957          * | state |
958          *
959          * Just lock what we found and keep going
960          */
961         if (state->start == start && state->end <= end) {
962                 if (state->state & exclusive_bits) {
963                         *failed_start = state->start;
964                         err = -EEXIST;
965                         goto out;
966                 }
967
968                 set_state_bits(tree, state, &bits, changeset);
969                 cache_state(state, cached_state);
970                 merge_state(tree, state);
971                 if (last_end == (u64)-1)
972                         goto out;
973                 start = last_end + 1;
974                 state = next_state(state);
975                 if (start < end && state && state->start == start &&
976                     !need_resched())
977                         goto hit_next;
978                 goto search_again;
979         }
980
981         /*
982          *     | ---- desired range ---- |
983          * | state |
984          *   or
985          * | ------------- state -------------- |
986          *
987          * We need to split the extent we found, and may flip bits on
988          * second half.
989          *
990          * If the extent we found extends past our
991          * range, we just split and search again.  It'll get split
992          * again the next time though.
993          *
994          * If the extent we found is inside our range, we set the
995          * desired bit on it.
996          */
997         if (state->start < start) {
998                 if (state->state & exclusive_bits) {
999                         *failed_start = start;
1000                         err = -EEXIST;
1001                         goto out;
1002                 }
1003
1004                 prealloc = alloc_extent_state_atomic(prealloc);
1005                 BUG_ON(!prealloc);
1006                 err = split_state(tree, state, prealloc, start);
1007                 if (err)
1008                         extent_io_tree_panic(tree, err);
1009
1010                 prealloc = NULL;
1011                 if (err)
1012                         goto out;
1013                 if (state->end <= end) {
1014                         set_state_bits(tree, state, &bits, changeset);
1015                         cache_state(state, cached_state);
1016                         merge_state(tree, state);
1017                         if (last_end == (u64)-1)
1018                                 goto out;
1019                         start = last_end + 1;
1020                         state = next_state(state);
1021                         if (start < end && state && state->start == start &&
1022                             !need_resched())
1023                                 goto hit_next;
1024                 }
1025                 goto search_again;
1026         }
1027         /*
1028          * | ---- desired range ---- |
1029          *     | state | or               | state |
1030          *
1031          * There's a hole, we need to insert something in it and
1032          * ignore the extent we found.
1033          */
1034         if (state->start > start) {
1035                 u64 this_end;
1036                 if (end < last_start)
1037                         this_end = end;
1038                 else
1039                         this_end = last_start - 1;
1040
1041                 prealloc = alloc_extent_state_atomic(prealloc);
1042                 BUG_ON(!prealloc);
1043
1044                 /*
1045                  * Avoid to free 'prealloc' if it can be merged with
1046                  * the later extent.
1047                  */
1048                 err = insert_state(tree, prealloc, start, this_end,
1049                                    NULL, NULL, &bits, changeset);
1050                 if (err)
1051                         extent_io_tree_panic(tree, err);
1052
1053                 cache_state(prealloc, cached_state);
1054                 prealloc = NULL;
1055                 start = this_end + 1;
1056                 goto search_again;
1057         }
1058         /*
1059          * | ---- desired range ---- |
1060          *                        | state |
1061          * We need to split the extent, and set the bit
1062          * on the first half
1063          */
1064         if (state->start <= end && state->end > end) {
1065                 if (state->state & exclusive_bits) {
1066                         *failed_start = start;
1067                         err = -EEXIST;
1068                         goto out;
1069                 }
1070
1071                 prealloc = alloc_extent_state_atomic(prealloc);
1072                 BUG_ON(!prealloc);
1073                 err = split_state(tree, state, prealloc, end + 1);
1074                 if (err)
1075                         extent_io_tree_panic(tree, err);
1076
1077                 set_state_bits(tree, prealloc, &bits, changeset);
1078                 cache_state(prealloc, cached_state);
1079                 merge_state(tree, prealloc);
1080                 prealloc = NULL;
1081                 goto out;
1082         }
1083
1084 search_again:
1085         if (start > end)
1086                 goto out;
1087         spin_unlock(&tree->lock);
1088         if (gfpflags_allow_blocking(mask))
1089                 cond_resched();
1090         goto again;
1091
1092 out:
1093         spin_unlock(&tree->lock);
1094         if (prealloc)
1095                 free_extent_state(prealloc);
1096
1097         return err;
1098
1099 }
1100
1101 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1102                    unsigned bits, u64 * failed_start,
1103                    struct extent_state **cached_state, gfp_t mask)
1104 {
1105         return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1106                                 cached_state, mask, NULL);
1107 }
1108
1109
1110 /**
1111  * convert_extent_bit - convert all bits in a given range from one bit to
1112  *                      another
1113  * @tree:       the io tree to search
1114  * @start:      the start offset in bytes
1115  * @end:        the end offset in bytes (inclusive)
1116  * @bits:       the bits to set in this range
1117  * @clear_bits: the bits to clear in this range
1118  * @cached_state:       state that we're going to cache
1119  *
1120  * This will go through and set bits for the given range.  If any states exist
1121  * already in this range they are set with the given bit and cleared of the
1122  * clear_bits.  This is only meant to be used by things that are mergeable, ie
1123  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
1124  * boundary bits like LOCK.
1125  *
1126  * All allocations are done with GFP_NOFS.
1127  */
1128 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1129                        unsigned bits, unsigned clear_bits,
1130                        struct extent_state **cached_state)
1131 {
1132         struct extent_state *state;
1133         struct extent_state *prealloc = NULL;
1134         struct rb_node *node;
1135         struct rb_node **p;
1136         struct rb_node *parent;
1137         int err = 0;
1138         u64 last_start;
1139         u64 last_end;
1140         bool first_iteration = true;
1141
1142         btrfs_debug_check_extent_io_range(tree, start, end);
1143         trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1144                                        clear_bits);
1145
1146 again:
1147         if (!prealloc) {
1148                 /*
1149                  * Best effort, don't worry if extent state allocation fails
1150                  * here for the first iteration. We might have a cached state
1151                  * that matches exactly the target range, in which case no
1152                  * extent state allocations are needed. We'll only know this
1153                  * after locking the tree.
1154                  */
1155                 prealloc = alloc_extent_state(GFP_NOFS);
1156                 if (!prealloc && !first_iteration)
1157                         return -ENOMEM;
1158         }
1159
1160         spin_lock(&tree->lock);
1161         if (cached_state && *cached_state) {
1162                 state = *cached_state;
1163                 if (state->start <= start && state->end > start &&
1164                     extent_state_in_tree(state)) {
1165                         node = &state->rb_node;
1166                         goto hit_next;
1167                 }
1168         }
1169
1170         /*
1171          * this search will find all the extents that end after
1172          * our range starts.
1173          */
1174         node = tree_search_for_insert(tree, start, &p, &parent);
1175         if (!node) {
1176                 prealloc = alloc_extent_state_atomic(prealloc);
1177                 if (!prealloc) {
1178                         err = -ENOMEM;
1179                         goto out;
1180                 }
1181                 err = insert_state(tree, prealloc, start, end,
1182                                    &p, &parent, &bits, NULL);
1183                 if (err)
1184                         extent_io_tree_panic(tree, err);
1185                 cache_state(prealloc, cached_state);
1186                 prealloc = NULL;
1187                 goto out;
1188         }
1189         state = rb_entry(node, struct extent_state, rb_node);
1190 hit_next:
1191         last_start = state->start;
1192         last_end = state->end;
1193
1194         /*
1195          * | ---- desired range ---- |
1196          * | state |
1197          *
1198          * Just lock what we found and keep going
1199          */
1200         if (state->start == start && state->end <= end) {
1201                 set_state_bits(tree, state, &bits, NULL);
1202                 cache_state(state, cached_state);
1203                 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1204                 if (last_end == (u64)-1)
1205                         goto out;
1206                 start = last_end + 1;
1207                 if (start < end && state && state->start == start &&
1208                     !need_resched())
1209                         goto hit_next;
1210                 goto search_again;
1211         }
1212
1213         /*
1214          *     | ---- desired range ---- |
1215          * | state |
1216          *   or
1217          * | ------------- state -------------- |
1218          *
1219          * We need to split the extent we found, and may flip bits on
1220          * second half.
1221          *
1222          * If the extent we found extends past our
1223          * range, we just split and search again.  It'll get split
1224          * again the next time though.
1225          *
1226          * If the extent we found is inside our range, we set the
1227          * desired bit on it.
1228          */
1229         if (state->start < start) {
1230                 prealloc = alloc_extent_state_atomic(prealloc);
1231                 if (!prealloc) {
1232                         err = -ENOMEM;
1233                         goto out;
1234                 }
1235                 err = split_state(tree, state, prealloc, start);
1236                 if (err)
1237                         extent_io_tree_panic(tree, err);
1238                 prealloc = NULL;
1239                 if (err)
1240                         goto out;
1241                 if (state->end <= end) {
1242                         set_state_bits(tree, state, &bits, NULL);
1243                         cache_state(state, cached_state);
1244                         state = clear_state_bit(tree, state, &clear_bits, 0,
1245                                                 NULL);
1246                         if (last_end == (u64)-1)
1247                                 goto out;
1248                         start = last_end + 1;
1249                         if (start < end && state && state->start == start &&
1250                             !need_resched())
1251                                 goto hit_next;
1252                 }
1253                 goto search_again;
1254         }
1255         /*
1256          * | ---- desired range ---- |
1257          *     | state | or               | state |
1258          *
1259          * There's a hole, we need to insert something in it and
1260          * ignore the extent we found.
1261          */
1262         if (state->start > start) {
1263                 u64 this_end;
1264                 if (end < last_start)
1265                         this_end = end;
1266                 else
1267                         this_end = last_start - 1;
1268
1269                 prealloc = alloc_extent_state_atomic(prealloc);
1270                 if (!prealloc) {
1271                         err = -ENOMEM;
1272                         goto out;
1273                 }
1274
1275                 /*
1276                  * Avoid to free 'prealloc' if it can be merged with
1277                  * the later extent.
1278                  */
1279                 err = insert_state(tree, prealloc, start, this_end,
1280                                    NULL, NULL, &bits, NULL);
1281                 if (err)
1282                         extent_io_tree_panic(tree, err);
1283                 cache_state(prealloc, cached_state);
1284                 prealloc = NULL;
1285                 start = this_end + 1;
1286                 goto search_again;
1287         }
1288         /*
1289          * | ---- desired range ---- |
1290          *                        | state |
1291          * We need to split the extent, and set the bit
1292          * on the first half
1293          */
1294         if (state->start <= end && state->end > end) {
1295                 prealloc = alloc_extent_state_atomic(prealloc);
1296                 if (!prealloc) {
1297                         err = -ENOMEM;
1298                         goto out;
1299                 }
1300
1301                 err = split_state(tree, state, prealloc, end + 1);
1302                 if (err)
1303                         extent_io_tree_panic(tree, err);
1304
1305                 set_state_bits(tree, prealloc, &bits, NULL);
1306                 cache_state(prealloc, cached_state);
1307                 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1308                 prealloc = NULL;
1309                 goto out;
1310         }
1311
1312 search_again:
1313         if (start > end)
1314                 goto out;
1315         spin_unlock(&tree->lock);
1316         cond_resched();
1317         first_iteration = false;
1318         goto again;
1319
1320 out:
1321         spin_unlock(&tree->lock);
1322         if (prealloc)
1323                 free_extent_state(prealloc);
1324
1325         return err;
1326 }
1327
1328 /* wrappers around set/clear extent bit */
1329 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1330                            unsigned bits, struct extent_changeset *changeset)
1331 {
1332         /*
1333          * We don't support EXTENT_LOCKED yet, as current changeset will
1334          * record any bits changed, so for EXTENT_LOCKED case, it will
1335          * either fail with -EEXIST or changeset will record the whole
1336          * range.
1337          */
1338         BUG_ON(bits & EXTENT_LOCKED);
1339
1340         return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1341                                 changeset);
1342 }
1343
1344 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1345                      unsigned bits, int wake, int delete,
1346                      struct extent_state **cached)
1347 {
1348         return __clear_extent_bit(tree, start, end, bits, wake, delete,
1349                                   cached, GFP_NOFS, NULL);
1350 }
1351
1352 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1353                 unsigned bits, struct extent_changeset *changeset)
1354 {
1355         /*
1356          * Don't support EXTENT_LOCKED case, same reason as
1357          * set_record_extent_bits().
1358          */
1359         BUG_ON(bits & EXTENT_LOCKED);
1360
1361         return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1362                                   changeset);
1363 }
1364
1365 /*
1366  * either insert or lock state struct between start and end use mask to tell
1367  * us if waiting is desired.
1368  */
1369 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1370                      struct extent_state **cached_state)
1371 {
1372         int err;
1373         u64 failed_start;
1374
1375         while (1) {
1376                 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1377                                        EXTENT_LOCKED, &failed_start,
1378                                        cached_state, GFP_NOFS, NULL);
1379                 if (err == -EEXIST) {
1380                         wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1381                         start = failed_start;
1382                 } else
1383                         break;
1384                 WARN_ON(start > end);
1385         }
1386         return err;
1387 }
1388
1389 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1390 {
1391         int err;
1392         u64 failed_start;
1393
1394         err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1395                                &failed_start, NULL, GFP_NOFS, NULL);
1396         if (err == -EEXIST) {
1397                 if (failed_start > start)
1398                         clear_extent_bit(tree, start, failed_start - 1,
1399                                          EXTENT_LOCKED, 1, 0, NULL);
1400                 return 0;
1401         }
1402         return 1;
1403 }
1404
1405 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1406 {
1407         unsigned long index = start >> PAGE_SHIFT;
1408         unsigned long end_index = end >> PAGE_SHIFT;
1409         struct page *page;
1410
1411         while (index <= end_index) {
1412                 page = find_get_page(inode->i_mapping, index);
1413                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1414                 clear_page_dirty_for_io(page);
1415                 put_page(page);
1416                 index++;
1417         }
1418 }
1419
1420 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1421 {
1422         unsigned long index = start >> PAGE_SHIFT;
1423         unsigned long end_index = end >> PAGE_SHIFT;
1424         struct page *page;
1425
1426         while (index <= end_index) {
1427                 page = find_get_page(inode->i_mapping, index);
1428                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1429                 __set_page_dirty_nobuffers(page);
1430                 account_page_redirty(page);
1431                 put_page(page);
1432                 index++;
1433         }
1434 }
1435
1436 /* find the first state struct with 'bits' set after 'start', and
1437  * return it.  tree->lock must be held.  NULL will returned if
1438  * nothing was found after 'start'
1439  */
1440 static struct extent_state *
1441 find_first_extent_bit_state(struct extent_io_tree *tree,
1442                             u64 start, unsigned bits)
1443 {
1444         struct rb_node *node;
1445         struct extent_state *state;
1446
1447         /*
1448          * this search will find all the extents that end after
1449          * our range starts.
1450          */
1451         node = tree_search(tree, start);
1452         if (!node)
1453                 goto out;
1454
1455         while (1) {
1456                 state = rb_entry(node, struct extent_state, rb_node);
1457                 if (state->end >= start && (state->state & bits))
1458                         return state;
1459
1460                 node = rb_next(node);
1461                 if (!node)
1462                         break;
1463         }
1464 out:
1465         return NULL;
1466 }
1467
1468 /*
1469  * find the first offset in the io tree with 'bits' set. zero is
1470  * returned if we find something, and *start_ret and *end_ret are
1471  * set to reflect the state struct that was found.
1472  *
1473  * If nothing was found, 1 is returned. If found something, return 0.
1474  */
1475 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1476                           u64 *start_ret, u64 *end_ret, unsigned bits,
1477                           struct extent_state **cached_state)
1478 {
1479         struct extent_state *state;
1480         int ret = 1;
1481
1482         spin_lock(&tree->lock);
1483         if (cached_state && *cached_state) {
1484                 state = *cached_state;
1485                 if (state->end == start - 1 && extent_state_in_tree(state)) {
1486                         while ((state = next_state(state)) != NULL) {
1487                                 if (state->state & bits)
1488                                         goto got_it;
1489                         }
1490                         free_extent_state(*cached_state);
1491                         *cached_state = NULL;
1492                         goto out;
1493                 }
1494                 free_extent_state(*cached_state);
1495                 *cached_state = NULL;
1496         }
1497
1498         state = find_first_extent_bit_state(tree, start, bits);
1499 got_it:
1500         if (state) {
1501                 cache_state_if_flags(state, cached_state, 0);
1502                 *start_ret = state->start;
1503                 *end_ret = state->end;
1504                 ret = 0;
1505         }
1506 out:
1507         spin_unlock(&tree->lock);
1508         return ret;
1509 }
1510
1511 /*
1512  * find a contiguous range of bytes in the file marked as delalloc, not
1513  * more than 'max_bytes'.  start and end are used to return the range,
1514  *
1515  * true is returned if we find something, false if nothing was in the tree
1516  */
1517 static noinline bool find_delalloc_range(struct extent_io_tree *tree,
1518                                         u64 *start, u64 *end, u64 max_bytes,
1519                                         struct extent_state **cached_state)
1520 {
1521         struct rb_node *node;
1522         struct extent_state *state;
1523         u64 cur_start = *start;
1524         bool found = false;
1525         u64 total_bytes = 0;
1526
1527         spin_lock(&tree->lock);
1528
1529         /*
1530          * this search will find all the extents that end after
1531          * our range starts.
1532          */
1533         node = tree_search(tree, cur_start);
1534         if (!node) {
1535                 *end = (u64)-1;
1536                 goto out;
1537         }
1538
1539         while (1) {
1540                 state = rb_entry(node, struct extent_state, rb_node);
1541                 if (found && (state->start != cur_start ||
1542                               (state->state & EXTENT_BOUNDARY))) {
1543                         goto out;
1544                 }
1545                 if (!(state->state & EXTENT_DELALLOC)) {
1546                         if (!found)
1547                                 *end = state->end;
1548                         goto out;
1549                 }
1550                 if (!found) {
1551                         *start = state->start;
1552                         *cached_state = state;
1553                         refcount_inc(&state->refs);
1554                 }
1555                 found = true;
1556                 *end = state->end;
1557                 cur_start = state->end + 1;
1558                 node = rb_next(node);
1559                 total_bytes += state->end - state->start + 1;
1560                 if (total_bytes >= max_bytes)
1561                         break;
1562                 if (!node)
1563                         break;
1564         }
1565 out:
1566         spin_unlock(&tree->lock);
1567         return found;
1568 }
1569
1570 static int __process_pages_contig(struct address_space *mapping,
1571                                   struct page *locked_page,
1572                                   pgoff_t start_index, pgoff_t end_index,
1573                                   unsigned long page_ops, pgoff_t *index_ret);
1574
1575 static noinline void __unlock_for_delalloc(struct inode *inode,
1576                                            struct page *locked_page,
1577                                            u64 start, u64 end)
1578 {
1579         unsigned long index = start >> PAGE_SHIFT;
1580         unsigned long end_index = end >> PAGE_SHIFT;
1581
1582         ASSERT(locked_page);
1583         if (index == locked_page->index && end_index == index)
1584                 return;
1585
1586         __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1587                                PAGE_UNLOCK, NULL);
1588 }
1589
1590 static noinline int lock_delalloc_pages(struct inode *inode,
1591                                         struct page *locked_page,
1592                                         u64 delalloc_start,
1593                                         u64 delalloc_end)
1594 {
1595         unsigned long index = delalloc_start >> PAGE_SHIFT;
1596         unsigned long index_ret = index;
1597         unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1598         int ret;
1599
1600         ASSERT(locked_page);
1601         if (index == locked_page->index && index == end_index)
1602                 return 0;
1603
1604         ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1605                                      end_index, PAGE_LOCK, &index_ret);
1606         if (ret == -EAGAIN)
1607                 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1608                                       (u64)index_ret << PAGE_SHIFT);
1609         return ret;
1610 }
1611
1612 /*
1613  * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1614  * more than @max_bytes.  @Start and @end are used to return the range,
1615  *
1616  * Return: true if we find something
1617  *         false if nothing was in the tree
1618  */
1619 EXPORT_FOR_TESTS
1620 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1621                                     struct extent_io_tree *tree,
1622                                     struct page *locked_page, u64 *start,
1623                                     u64 *end)
1624 {
1625         u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1626         u64 delalloc_start;
1627         u64 delalloc_end;
1628         bool found;
1629         struct extent_state *cached_state = NULL;
1630         int ret;
1631         int loops = 0;
1632
1633 again:
1634         /* step one, find a bunch of delalloc bytes starting at start */
1635         delalloc_start = *start;
1636         delalloc_end = 0;
1637         found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1638                                     max_bytes, &cached_state);
1639         if (!found || delalloc_end <= *start) {
1640                 *start = delalloc_start;
1641                 *end = delalloc_end;
1642                 free_extent_state(cached_state);
1643                 return false;
1644         }
1645
1646         /*
1647          * start comes from the offset of locked_page.  We have to lock
1648          * pages in order, so we can't process delalloc bytes before
1649          * locked_page
1650          */
1651         if (delalloc_start < *start)
1652                 delalloc_start = *start;
1653
1654         /*
1655          * make sure to limit the number of pages we try to lock down
1656          */
1657         if (delalloc_end + 1 - delalloc_start > max_bytes)
1658                 delalloc_end = delalloc_start + max_bytes - 1;
1659
1660         /* step two, lock all the pages after the page that has start */
1661         ret = lock_delalloc_pages(inode, locked_page,
1662                                   delalloc_start, delalloc_end);
1663         ASSERT(!ret || ret == -EAGAIN);
1664         if (ret == -EAGAIN) {
1665                 /* some of the pages are gone, lets avoid looping by
1666                  * shortening the size of the delalloc range we're searching
1667                  */
1668                 free_extent_state(cached_state);
1669                 cached_state = NULL;
1670                 if (!loops) {
1671                         max_bytes = PAGE_SIZE;
1672                         loops = 1;
1673                         goto again;
1674                 } else {
1675                         found = false;
1676                         goto out_failed;
1677                 }
1678         }
1679
1680         /* step three, lock the state bits for the whole range */
1681         lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1682
1683         /* then test to make sure it is all still delalloc */
1684         ret = test_range_bit(tree, delalloc_start, delalloc_end,
1685                              EXTENT_DELALLOC, 1, cached_state);
1686         if (!ret) {
1687                 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1688                                      &cached_state);
1689                 __unlock_for_delalloc(inode, locked_page,
1690                               delalloc_start, delalloc_end);
1691                 cond_resched();
1692                 goto again;
1693         }
1694         free_extent_state(cached_state);
1695         *start = delalloc_start;
1696         *end = delalloc_end;
1697 out_failed:
1698         return found;
1699 }
1700
1701 static int __process_pages_contig(struct address_space *mapping,
1702                                   struct page *locked_page,
1703                                   pgoff_t start_index, pgoff_t end_index,
1704                                   unsigned long page_ops, pgoff_t *index_ret)
1705 {
1706         unsigned long nr_pages = end_index - start_index + 1;
1707         unsigned long pages_locked = 0;
1708         pgoff_t index = start_index;
1709         struct page *pages[16];
1710         unsigned ret;
1711         int err = 0;
1712         int i;
1713
1714         if (page_ops & PAGE_LOCK) {
1715                 ASSERT(page_ops == PAGE_LOCK);
1716                 ASSERT(index_ret && *index_ret == start_index);
1717         }
1718
1719         if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1720                 mapping_set_error(mapping, -EIO);
1721
1722         while (nr_pages > 0) {
1723                 ret = find_get_pages_contig(mapping, index,
1724                                      min_t(unsigned long,
1725                                      nr_pages, ARRAY_SIZE(pages)), pages);
1726                 if (ret == 0) {
1727                         /*
1728                          * Only if we're going to lock these pages,
1729                          * can we find nothing at @index.
1730                          */
1731                         ASSERT(page_ops & PAGE_LOCK);
1732                         err = -EAGAIN;
1733                         goto out;
1734                 }
1735
1736                 for (i = 0; i < ret; i++) {
1737                         if (page_ops & PAGE_SET_PRIVATE2)
1738                                 SetPagePrivate2(pages[i]);
1739
1740                         if (pages[i] == locked_page) {
1741                                 put_page(pages[i]);
1742                                 pages_locked++;
1743                                 continue;
1744                         }
1745                         if (page_ops & PAGE_CLEAR_DIRTY)
1746                                 clear_page_dirty_for_io(pages[i]);
1747                         if (page_ops & PAGE_SET_WRITEBACK)
1748                                 set_page_writeback(pages[i]);
1749                         if (page_ops & PAGE_SET_ERROR)
1750                                 SetPageError(pages[i]);
1751                         if (page_ops & PAGE_END_WRITEBACK)
1752                                 end_page_writeback(pages[i]);
1753                         if (page_ops & PAGE_UNLOCK)
1754                                 unlock_page(pages[i]);
1755                         if (page_ops & PAGE_LOCK) {
1756                                 lock_page(pages[i]);
1757                                 if (!PageDirty(pages[i]) ||
1758                                     pages[i]->mapping != mapping) {
1759                                         unlock_page(pages[i]);
1760                                         put_page(pages[i]);
1761                                         err = -EAGAIN;
1762                                         goto out;
1763                                 }
1764                         }
1765                         put_page(pages[i]);
1766                         pages_locked++;
1767                 }
1768                 nr_pages -= ret;
1769                 index += ret;
1770                 cond_resched();
1771         }
1772 out:
1773         if (err && index_ret)
1774                 *index_ret = start_index + pages_locked - 1;
1775         return err;
1776 }
1777
1778 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1779                                  u64 delalloc_end, struct page *locked_page,
1780                                  unsigned clear_bits,
1781                                  unsigned long page_ops)
1782 {
1783         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1784                          NULL);
1785
1786         __process_pages_contig(inode->i_mapping, locked_page,
1787                                start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1788                                page_ops, NULL);
1789 }
1790
1791 /*
1792  * count the number of bytes in the tree that have a given bit(s)
1793  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
1794  * cached.  The total number found is returned.
1795  */
1796 u64 count_range_bits(struct extent_io_tree *tree,
1797                      u64 *start, u64 search_end, u64 max_bytes,
1798                      unsigned bits, int contig)
1799 {
1800         struct rb_node *node;
1801         struct extent_state *state;
1802         u64 cur_start = *start;
1803         u64 total_bytes = 0;
1804         u64 last = 0;
1805         int found = 0;
1806
1807         if (WARN_ON(search_end <= cur_start))
1808                 return 0;
1809
1810         spin_lock(&tree->lock);
1811         if (cur_start == 0 && bits == EXTENT_DIRTY) {
1812                 total_bytes = tree->dirty_bytes;
1813                 goto out;
1814         }
1815         /*
1816          * this search will find all the extents that end after
1817          * our range starts.
1818          */
1819         node = tree_search(tree, cur_start);
1820         if (!node)
1821                 goto out;
1822
1823         while (1) {
1824                 state = rb_entry(node, struct extent_state, rb_node);
1825                 if (state->start > search_end)
1826                         break;
1827                 if (contig && found && state->start > last + 1)
1828                         break;
1829                 if (state->end >= cur_start && (state->state & bits) == bits) {
1830                         total_bytes += min(search_end, state->end) + 1 -
1831                                        max(cur_start, state->start);
1832                         if (total_bytes >= max_bytes)
1833                                 break;
1834                         if (!found) {
1835                                 *start = max(cur_start, state->start);
1836                                 found = 1;
1837                         }
1838                         last = state->end;
1839                 } else if (contig && found) {
1840                         break;
1841                 }
1842                 node = rb_next(node);
1843                 if (!node)
1844                         break;
1845         }
1846 out:
1847         spin_unlock(&tree->lock);
1848         return total_bytes;
1849 }
1850
1851 /*
1852  * set the private field for a given byte offset in the tree.  If there isn't
1853  * an extent_state there already, this does nothing.
1854  */
1855 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
1856                 struct io_failure_record *failrec)
1857 {
1858         struct rb_node *node;
1859         struct extent_state *state;
1860         int ret = 0;
1861
1862         spin_lock(&tree->lock);
1863         /*
1864          * this search will find all the extents that end after
1865          * our range starts.
1866          */
1867         node = tree_search(tree, start);
1868         if (!node) {
1869                 ret = -ENOENT;
1870                 goto out;
1871         }
1872         state = rb_entry(node, struct extent_state, rb_node);
1873         if (state->start != start) {
1874                 ret = -ENOENT;
1875                 goto out;
1876         }
1877         state->failrec = failrec;
1878 out:
1879         spin_unlock(&tree->lock);
1880         return ret;
1881 }
1882
1883 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
1884                 struct io_failure_record **failrec)
1885 {
1886         struct rb_node *node;
1887         struct extent_state *state;
1888         int ret = 0;
1889
1890         spin_lock(&tree->lock);
1891         /*
1892          * this search will find all the extents that end after
1893          * our range starts.
1894          */
1895         node = tree_search(tree, start);
1896         if (!node) {
1897                 ret = -ENOENT;
1898                 goto out;
1899         }
1900         state = rb_entry(node, struct extent_state, rb_node);
1901         if (state->start != start) {
1902                 ret = -ENOENT;
1903                 goto out;
1904         }
1905         *failrec = state->failrec;
1906 out:
1907         spin_unlock(&tree->lock);
1908         return ret;
1909 }
1910
1911 /*
1912  * searches a range in the state tree for a given mask.
1913  * If 'filled' == 1, this returns 1 only if every extent in the tree
1914  * has the bits set.  Otherwise, 1 is returned if any bit in the
1915  * range is found set.
1916  */
1917 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1918                    unsigned bits, int filled, struct extent_state *cached)
1919 {
1920         struct extent_state *state = NULL;
1921         struct rb_node *node;
1922         int bitset = 0;
1923
1924         spin_lock(&tree->lock);
1925         if (cached && extent_state_in_tree(cached) && cached->start <= start &&
1926             cached->end > start)
1927                 node = &cached->rb_node;
1928         else
1929                 node = tree_search(tree, start);
1930         while (node && start <= end) {
1931                 state = rb_entry(node, struct extent_state, rb_node);
1932
1933                 if (filled && state->start > start) {
1934                         bitset = 0;
1935                         break;
1936                 }
1937
1938                 if (state->start > end)
1939                         break;
1940
1941                 if (state->state & bits) {
1942                         bitset = 1;
1943                         if (!filled)
1944                                 break;
1945                 } else if (filled) {
1946                         bitset = 0;
1947                         break;
1948                 }
1949
1950                 if (state->end == (u64)-1)
1951                         break;
1952
1953                 start = state->end + 1;
1954                 if (start > end)
1955                         break;
1956                 node = rb_next(node);
1957                 if (!node) {
1958                         if (filled)
1959                                 bitset = 0;
1960                         break;
1961                 }
1962         }
1963         spin_unlock(&tree->lock);
1964         return bitset;
1965 }
1966
1967 /*
1968  * helper function to set a given page up to date if all the
1969  * extents in the tree for that page are up to date
1970  */
1971 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1972 {
1973         u64 start = page_offset(page);
1974         u64 end = start + PAGE_SIZE - 1;
1975         if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1976                 SetPageUptodate(page);
1977 }
1978
1979 int free_io_failure(struct extent_io_tree *failure_tree,
1980                     struct extent_io_tree *io_tree,
1981                     struct io_failure_record *rec)
1982 {
1983         int ret;
1984         int err = 0;
1985
1986         set_state_failrec(failure_tree, rec->start, NULL);
1987         ret = clear_extent_bits(failure_tree, rec->start,
1988                                 rec->start + rec->len - 1,
1989                                 EXTENT_LOCKED | EXTENT_DIRTY);
1990         if (ret)
1991                 err = ret;
1992
1993         ret = clear_extent_bits(io_tree, rec->start,
1994                                 rec->start + rec->len - 1,
1995                                 EXTENT_DAMAGED);
1996         if (ret && !err)
1997                 err = ret;
1998
1999         kfree(rec);
2000         return err;
2001 }
2002
2003 /*
2004  * this bypasses the standard btrfs submit functions deliberately, as
2005  * the standard behavior is to write all copies in a raid setup. here we only
2006  * want to write the one bad copy. so we do the mapping for ourselves and issue
2007  * submit_bio directly.
2008  * to avoid any synchronization issues, wait for the data after writing, which
2009  * actually prevents the read that triggered the error from finishing.
2010  * currently, there can be no more than two copies of every data bit. thus,
2011  * exactly one rewrite is required.
2012  */
2013 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2014                       u64 length, u64 logical, struct page *page,
2015                       unsigned int pg_offset, int mirror_num)
2016 {
2017         struct bio *bio;
2018         struct btrfs_device *dev;
2019         u64 map_length = 0;
2020         u64 sector;
2021         struct btrfs_bio *bbio = NULL;
2022         int ret;
2023
2024         ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2025         BUG_ON(!mirror_num);
2026
2027         bio = btrfs_io_bio_alloc(1);
2028         bio->bi_iter.bi_size = 0;
2029         map_length = length;
2030
2031         /*
2032          * Avoid races with device replace and make sure our bbio has devices
2033          * associated to its stripes that don't go away while we are doing the
2034          * read repair operation.
2035          */
2036         btrfs_bio_counter_inc_blocked(fs_info);
2037         if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2038                 /*
2039                  * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2040                  * to update all raid stripes, but here we just want to correct
2041                  * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2042                  * stripe's dev and sector.
2043                  */
2044                 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2045                                       &map_length, &bbio, 0);
2046                 if (ret) {
2047                         btrfs_bio_counter_dec(fs_info);
2048                         bio_put(bio);
2049                         return -EIO;
2050                 }
2051                 ASSERT(bbio->mirror_num == 1);
2052         } else {
2053                 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2054                                       &map_length, &bbio, mirror_num);
2055                 if (ret) {
2056                         btrfs_bio_counter_dec(fs_info);
2057                         bio_put(bio);
2058                         return -EIO;
2059                 }
2060                 BUG_ON(mirror_num != bbio->mirror_num);
2061         }
2062
2063         sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2064         bio->bi_iter.bi_sector = sector;
2065         dev = bbio->stripes[bbio->mirror_num - 1].dev;
2066         btrfs_put_bbio(bbio);
2067         if (!dev || !dev->bdev ||
2068             !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2069                 btrfs_bio_counter_dec(fs_info);
2070                 bio_put(bio);
2071                 return -EIO;
2072         }
2073         bio_set_dev(bio, dev->bdev);
2074         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2075         bio_add_page(bio, page, length, pg_offset);
2076
2077         if (btrfsic_submit_bio_wait(bio)) {
2078                 /* try to remap that extent elsewhere? */
2079                 btrfs_bio_counter_dec(fs_info);
2080                 bio_put(bio);
2081                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2082                 return -EIO;
2083         }
2084
2085         btrfs_info_rl_in_rcu(fs_info,
2086                 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2087                                   ino, start,
2088                                   rcu_str_deref(dev->name), sector);
2089         btrfs_bio_counter_dec(fs_info);
2090         bio_put(bio);
2091         return 0;
2092 }
2093
2094 int repair_eb_io_failure(struct btrfs_fs_info *fs_info,
2095                          struct extent_buffer *eb, int mirror_num)
2096 {
2097         u64 start = eb->start;
2098         int i, num_pages = num_extent_pages(eb);
2099         int ret = 0;
2100
2101         if (sb_rdonly(fs_info->sb))
2102                 return -EROFS;
2103
2104         for (i = 0; i < num_pages; i++) {
2105                 struct page *p = eb->pages[i];
2106
2107                 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2108                                         start - page_offset(p), mirror_num);
2109                 if (ret)
2110                         break;
2111                 start += PAGE_SIZE;
2112         }
2113
2114         return ret;
2115 }
2116
2117 /*
2118  * each time an IO finishes, we do a fast check in the IO failure tree
2119  * to see if we need to process or clean up an io_failure_record
2120  */
2121 int clean_io_failure(struct btrfs_fs_info *fs_info,
2122                      struct extent_io_tree *failure_tree,
2123                      struct extent_io_tree *io_tree, u64 start,
2124                      struct page *page, u64 ino, unsigned int pg_offset)
2125 {
2126         u64 private;
2127         struct io_failure_record *failrec;
2128         struct extent_state *state;
2129         int num_copies;
2130         int ret;
2131
2132         private = 0;
2133         ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2134                                EXTENT_DIRTY, 0);
2135         if (!ret)
2136                 return 0;
2137
2138         ret = get_state_failrec(failure_tree, start, &failrec);
2139         if (ret)
2140                 return 0;
2141
2142         BUG_ON(!failrec->this_mirror);
2143
2144         if (failrec->in_validation) {
2145                 /* there was no real error, just free the record */
2146                 btrfs_debug(fs_info,
2147                         "clean_io_failure: freeing dummy error at %llu",
2148                         failrec->start);
2149                 goto out;
2150         }
2151         if (sb_rdonly(fs_info->sb))
2152                 goto out;
2153
2154         spin_lock(&io_tree->lock);
2155         state = find_first_extent_bit_state(io_tree,
2156                                             failrec->start,
2157                                             EXTENT_LOCKED);
2158         spin_unlock(&io_tree->lock);
2159
2160         if (state && state->start <= failrec->start &&
2161             state->end >= failrec->start + failrec->len - 1) {
2162                 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2163                                               failrec->len);
2164                 if (num_copies > 1)  {
2165                         repair_io_failure(fs_info, ino, start, failrec->len,
2166                                           failrec->logical, page, pg_offset,
2167                                           failrec->failed_mirror);
2168                 }
2169         }
2170
2171 out:
2172         free_io_failure(failure_tree, io_tree, failrec);
2173
2174         return 0;
2175 }
2176
2177 /*
2178  * Can be called when
2179  * - hold extent lock
2180  * - under ordered extent
2181  * - the inode is freeing
2182  */
2183 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2184 {
2185         struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2186         struct io_failure_record *failrec;
2187         struct extent_state *state, *next;
2188
2189         if (RB_EMPTY_ROOT(&failure_tree->state))
2190                 return;
2191
2192         spin_lock(&failure_tree->lock);
2193         state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2194         while (state) {
2195                 if (state->start > end)
2196                         break;
2197
2198                 ASSERT(state->end <= end);
2199
2200                 next = next_state(state);
2201
2202                 failrec = state->failrec;
2203                 free_extent_state(state);
2204                 kfree(failrec);
2205
2206                 state = next;
2207         }
2208         spin_unlock(&failure_tree->lock);
2209 }
2210
2211 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2212                 struct io_failure_record **failrec_ret)
2213 {
2214         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2215         struct io_failure_record *failrec;
2216         struct extent_map *em;
2217         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2218         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2219         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2220         int ret;
2221         u64 logical;
2222
2223         ret = get_state_failrec(failure_tree, start, &failrec);
2224         if (ret) {
2225                 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2226                 if (!failrec)
2227                         return -ENOMEM;
2228
2229                 failrec->start = start;
2230                 failrec->len = end - start + 1;
2231                 failrec->this_mirror = 0;
2232                 failrec->bio_flags = 0;
2233                 failrec->in_validation = 0;
2234
2235                 read_lock(&em_tree->lock);
2236                 em = lookup_extent_mapping(em_tree, start, failrec->len);
2237                 if (!em) {
2238                         read_unlock(&em_tree->lock);
2239                         kfree(failrec);
2240                         return -EIO;
2241                 }
2242
2243                 if (em->start > start || em->start + em->len <= start) {
2244                         free_extent_map(em);
2245                         em = NULL;
2246                 }
2247                 read_unlock(&em_tree->lock);
2248                 if (!em) {
2249                         kfree(failrec);
2250                         return -EIO;
2251                 }
2252
2253                 logical = start - em->start;
2254                 logical = em->block_start + logical;
2255                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2256                         logical = em->block_start;
2257                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2258                         extent_set_compress_type(&failrec->bio_flags,
2259                                                  em->compress_type);
2260                 }
2261
2262                 btrfs_debug(fs_info,
2263                         "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2264                         logical, start, failrec->len);
2265
2266                 failrec->logical = logical;
2267                 free_extent_map(em);
2268
2269                 /* set the bits in the private failure tree */
2270                 ret = set_extent_bits(failure_tree, start, end,
2271                                         EXTENT_LOCKED | EXTENT_DIRTY);
2272                 if (ret >= 0)
2273                         ret = set_state_failrec(failure_tree, start, failrec);
2274                 /* set the bits in the inode's tree */
2275                 if (ret >= 0)
2276                         ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2277                 if (ret < 0) {
2278                         kfree(failrec);
2279                         return ret;
2280                 }
2281         } else {
2282                 btrfs_debug(fs_info,
2283                         "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2284                         failrec->logical, failrec->start, failrec->len,
2285                         failrec->in_validation);
2286                 /*
2287                  * when data can be on disk more than twice, add to failrec here
2288                  * (e.g. with a list for failed_mirror) to make
2289                  * clean_io_failure() clean all those errors at once.
2290                  */
2291         }
2292
2293         *failrec_ret = failrec;
2294
2295         return 0;
2296 }
2297
2298 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2299                            struct io_failure_record *failrec, int failed_mirror)
2300 {
2301         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2302         int num_copies;
2303
2304         num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2305         if (num_copies == 1) {
2306                 /*
2307                  * we only have a single copy of the data, so don't bother with
2308                  * all the retry and error correction code that follows. no
2309                  * matter what the error is, it is very likely to persist.
2310                  */
2311                 btrfs_debug(fs_info,
2312                         "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2313                         num_copies, failrec->this_mirror, failed_mirror);
2314                 return false;
2315         }
2316
2317         /*
2318          * there are two premises:
2319          *      a) deliver good data to the caller
2320          *      b) correct the bad sectors on disk
2321          */
2322         if (failed_bio_pages > 1) {
2323                 /*
2324                  * to fulfill b), we need to know the exact failing sectors, as
2325                  * we don't want to rewrite any more than the failed ones. thus,
2326                  * we need separate read requests for the failed bio
2327                  *
2328                  * if the following BUG_ON triggers, our validation request got
2329                  * merged. we need separate requests for our algorithm to work.
2330                  */
2331                 BUG_ON(failrec->in_validation);
2332                 failrec->in_validation = 1;
2333                 failrec->this_mirror = failed_mirror;
2334         } else {
2335                 /*
2336                  * we're ready to fulfill a) and b) alongside. get a good copy
2337                  * of the failed sector and if we succeed, we have setup
2338                  * everything for repair_io_failure to do the rest for us.
2339                  */
2340                 if (failrec->in_validation) {
2341                         BUG_ON(failrec->this_mirror != failed_mirror);
2342                         failrec->in_validation = 0;
2343                         failrec->this_mirror = 0;
2344                 }
2345                 failrec->failed_mirror = failed_mirror;
2346                 failrec->this_mirror++;
2347                 if (failrec->this_mirror == failed_mirror)
2348                         failrec->this_mirror++;
2349         }
2350
2351         if (failrec->this_mirror > num_copies) {
2352                 btrfs_debug(fs_info,
2353                         "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2354                         num_copies, failrec->this_mirror, failed_mirror);
2355                 return false;
2356         }
2357
2358         return true;
2359 }
2360
2361
2362 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2363                                     struct io_failure_record *failrec,
2364                                     struct page *page, int pg_offset, int icsum,
2365                                     bio_end_io_t *endio_func, void *data)
2366 {
2367         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2368         struct bio *bio;
2369         struct btrfs_io_bio *btrfs_failed_bio;
2370         struct btrfs_io_bio *btrfs_bio;
2371
2372         bio = btrfs_io_bio_alloc(1);
2373         bio->bi_end_io = endio_func;
2374         bio->bi_iter.bi_sector = failrec->logical >> 9;
2375         bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2376         bio->bi_iter.bi_size = 0;
2377         bio->bi_private = data;
2378
2379         btrfs_failed_bio = btrfs_io_bio(failed_bio);
2380         if (btrfs_failed_bio->csum) {
2381                 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2382
2383                 btrfs_bio = btrfs_io_bio(bio);
2384                 btrfs_bio->csum = btrfs_bio->csum_inline;
2385                 icsum *= csum_size;
2386                 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2387                        csum_size);
2388         }
2389
2390         bio_add_page(bio, page, failrec->len, pg_offset);
2391
2392         return bio;
2393 }
2394
2395 /*
2396  * This is a generic handler for readpage errors. If other copies exist, read
2397  * those and write back good data to the failed position. Does not investigate
2398  * in remapping the failed extent elsewhere, hoping the device will be smart
2399  * enough to do this as needed
2400  */
2401 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2402                               struct page *page, u64 start, u64 end,
2403                               int failed_mirror)
2404 {
2405         struct io_failure_record *failrec;
2406         struct inode *inode = page->mapping->host;
2407         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2408         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2409         struct bio *bio;
2410         int read_mode = 0;
2411         blk_status_t status;
2412         int ret;
2413         unsigned failed_bio_pages = failed_bio->bi_iter.bi_size >> PAGE_SHIFT;
2414
2415         BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2416
2417         ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2418         if (ret)
2419                 return ret;
2420
2421         if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2422                                     failed_mirror)) {
2423                 free_io_failure(failure_tree, tree, failrec);
2424                 return -EIO;
2425         }
2426
2427         if (failed_bio_pages > 1)
2428                 read_mode |= REQ_FAILFAST_DEV;
2429
2430         phy_offset >>= inode->i_sb->s_blocksize_bits;
2431         bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2432                                       start - page_offset(page),
2433                                       (int)phy_offset, failed_bio->bi_end_io,
2434                                       NULL);
2435         bio->bi_opf = REQ_OP_READ | read_mode;
2436
2437         btrfs_debug(btrfs_sb(inode->i_sb),
2438                 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2439                 read_mode, failrec->this_mirror, failrec->in_validation);
2440
2441         status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2442                                          failrec->bio_flags, 0);
2443         if (status) {
2444                 free_io_failure(failure_tree, tree, failrec);
2445                 bio_put(bio);
2446                 ret = blk_status_to_errno(status);
2447         }
2448
2449         return ret;
2450 }
2451
2452 /* lots and lots of room for performance fixes in the end_bio funcs */
2453
2454 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2455 {
2456         int uptodate = (err == 0);
2457         int ret = 0;
2458
2459         btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2460
2461         if (!uptodate) {
2462                 ClearPageUptodate(page);
2463                 SetPageError(page);
2464                 ret = err < 0 ? err : -EIO;
2465                 mapping_set_error(page->mapping, ret);
2466         }
2467 }
2468
2469 /*
2470  * after a writepage IO is done, we need to:
2471  * clear the uptodate bits on error
2472  * clear the writeback bits in the extent tree for this IO
2473  * end_page_writeback if the page has no more pending IO
2474  *
2475  * Scheduling is not allowed, so the extent state tree is expected
2476  * to have one and only one object corresponding to this IO.
2477  */
2478 static void end_bio_extent_writepage(struct bio *bio)
2479 {
2480         int error = blk_status_to_errno(bio->bi_status);
2481         struct bio_vec *bvec;
2482         u64 start;
2483         u64 end;
2484         int i;
2485         struct bvec_iter_all iter_all;
2486
2487         ASSERT(!bio_flagged(bio, BIO_CLONED));
2488         bio_for_each_segment_all(bvec, bio, i, iter_all) {
2489                 struct page *page = bvec->bv_page;
2490                 struct inode *inode = page->mapping->host;
2491                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2492
2493                 /* We always issue full-page reads, but if some block
2494                  * in a page fails to read, blk_update_request() will
2495                  * advance bv_offset and adjust bv_len to compensate.
2496                  * Print a warning for nonzero offsets, and an error
2497                  * if they don't add up to a full page.  */
2498                 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2499                         if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2500                                 btrfs_err(fs_info,
2501                                    "partial page write in btrfs with offset %u and length %u",
2502                                         bvec->bv_offset, bvec->bv_len);
2503                         else
2504                                 btrfs_info(fs_info,
2505                                    "incomplete page write in btrfs with offset %u and length %u",
2506                                         bvec->bv_offset, bvec->bv_len);
2507                 }
2508
2509                 start = page_offset(page);
2510                 end = start + bvec->bv_offset + bvec->bv_len - 1;
2511
2512                 end_extent_writepage(page, error, start, end);
2513                 end_page_writeback(page);
2514         }
2515
2516         bio_put(bio);
2517 }
2518
2519 static void
2520 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2521                               int uptodate)
2522 {
2523         struct extent_state *cached = NULL;
2524         u64 end = start + len - 1;
2525
2526         if (uptodate && tree->track_uptodate)
2527                 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2528         unlock_extent_cached_atomic(tree, start, end, &cached);
2529 }
2530
2531 /*
2532  * after a readpage IO is done, we need to:
2533  * clear the uptodate bits on error
2534  * set the uptodate bits if things worked
2535  * set the page up to date if all extents in the tree are uptodate
2536  * clear the lock bit in the extent tree
2537  * unlock the page if there are no other extents locked for it
2538  *
2539  * Scheduling is not allowed, so the extent state tree is expected
2540  * to have one and only one object corresponding to this IO.
2541  */
2542 static void end_bio_extent_readpage(struct bio *bio)
2543 {
2544         struct bio_vec *bvec;
2545         int uptodate = !bio->bi_status;
2546         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2547         struct extent_io_tree *tree, *failure_tree;
2548         u64 offset = 0;
2549         u64 start;
2550         u64 end;
2551         u64 len;
2552         u64 extent_start = 0;
2553         u64 extent_len = 0;
2554         int mirror;
2555         int ret;
2556         int i;
2557         struct bvec_iter_all iter_all;
2558
2559         ASSERT(!bio_flagged(bio, BIO_CLONED));
2560         bio_for_each_segment_all(bvec, bio, i, iter_all) {
2561                 struct page *page = bvec->bv_page;
2562                 struct inode *inode = page->mapping->host;
2563                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2564                 bool data_inode = btrfs_ino(BTRFS_I(inode))
2565                         != BTRFS_BTREE_INODE_OBJECTID;
2566
2567                 btrfs_debug(fs_info,
2568                         "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2569                         (u64)bio->bi_iter.bi_sector, bio->bi_status,
2570                         io_bio->mirror_num);
2571                 tree = &BTRFS_I(inode)->io_tree;
2572                 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2573
2574                 /* We always issue full-page reads, but if some block
2575                  * in a page fails to read, blk_update_request() will
2576                  * advance bv_offset and adjust bv_len to compensate.
2577                  * Print a warning for nonzero offsets, and an error
2578                  * if they don't add up to a full page.  */
2579                 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2580                         if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2581                                 btrfs_err(fs_info,
2582                                         "partial page read in btrfs with offset %u and length %u",
2583                                         bvec->bv_offset, bvec->bv_len);
2584                         else
2585                                 btrfs_info(fs_info,
2586                                         "incomplete page read in btrfs with offset %u and length %u",
2587                                         bvec->bv_offset, bvec->bv_len);
2588                 }
2589
2590                 start = page_offset(page);
2591                 end = start + bvec->bv_offset + bvec->bv_len - 1;
2592                 len = bvec->bv_len;
2593
2594                 mirror = io_bio->mirror_num;
2595                 if (likely(uptodate)) {
2596                         ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2597                                                               page, start, end,
2598                                                               mirror);
2599                         if (ret)
2600                                 uptodate = 0;
2601                         else
2602                                 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2603                                                  failure_tree, tree, start,
2604                                                  page,
2605                                                  btrfs_ino(BTRFS_I(inode)), 0);
2606                 }
2607
2608                 if (likely(uptodate))
2609                         goto readpage_ok;
2610
2611                 if (data_inode) {
2612
2613                         /*
2614                          * The generic bio_readpage_error handles errors the
2615                          * following way: If possible, new read requests are
2616                          * created and submitted and will end up in
2617                          * end_bio_extent_readpage as well (if we're lucky,
2618                          * not in the !uptodate case). In that case it returns
2619                          * 0 and we just go on with the next page in our bio.
2620                          * If it can't handle the error it will return -EIO and
2621                          * we remain responsible for that page.
2622                          */
2623                         ret = bio_readpage_error(bio, offset, page, start, end,
2624                                                  mirror);
2625                         if (ret == 0) {
2626                                 uptodate = !bio->bi_status;
2627                                 offset += len;
2628                                 continue;
2629                         }
2630                 } else {
2631                         struct extent_buffer *eb;
2632
2633                         eb = (struct extent_buffer *)page->private;
2634                         set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2635                         eb->read_mirror = mirror;
2636                         atomic_dec(&eb->io_pages);
2637                         if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2638                                                &eb->bflags))
2639                                 btree_readahead_hook(eb, -EIO);
2640                 }
2641 readpage_ok:
2642                 if (likely(uptodate)) {
2643                         loff_t i_size = i_size_read(inode);
2644                         pgoff_t end_index = i_size >> PAGE_SHIFT;
2645                         unsigned off;
2646
2647                         /* Zero out the end if this page straddles i_size */
2648                         off = offset_in_page(i_size);
2649                         if (page->index == end_index && off)
2650                                 zero_user_segment(page, off, PAGE_SIZE);
2651                         SetPageUptodate(page);
2652                 } else {
2653                         ClearPageUptodate(page);
2654                         SetPageError(page);
2655                 }
2656                 unlock_page(page);
2657                 offset += len;
2658
2659                 if (unlikely(!uptodate)) {
2660                         if (extent_len) {
2661                                 endio_readpage_release_extent(tree,
2662                                                               extent_start,
2663                                                               extent_len, 1);
2664                                 extent_start = 0;
2665                                 extent_len = 0;
2666                         }
2667                         endio_readpage_release_extent(tree, start,
2668                                                       end - start + 1, 0);
2669                 } else if (!extent_len) {
2670                         extent_start = start;
2671                         extent_len = end + 1 - start;
2672                 } else if (extent_start + extent_len == start) {
2673                         extent_len += end + 1 - start;
2674                 } else {
2675                         endio_readpage_release_extent(tree, extent_start,
2676                                                       extent_len, uptodate);
2677                         extent_start = start;
2678                         extent_len = end + 1 - start;
2679                 }
2680         }
2681
2682         if (extent_len)
2683                 endio_readpage_release_extent(tree, extent_start, extent_len,
2684                                               uptodate);
2685         btrfs_io_bio_free_csum(io_bio);
2686         bio_put(bio);
2687 }
2688
2689 /*
2690  * Initialize the members up to but not including 'bio'. Use after allocating a
2691  * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2692  * 'bio' because use of __GFP_ZERO is not supported.
2693  */
2694 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2695 {
2696         memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2697 }
2698
2699 /*
2700  * The following helpers allocate a bio. As it's backed by a bioset, it'll
2701  * never fail.  We're returning a bio right now but you can call btrfs_io_bio
2702  * for the appropriate container_of magic
2703  */
2704 struct bio *btrfs_bio_alloc(struct block_device *bdev, u64 first_byte)
2705 {
2706         struct bio *bio;
2707
2708         bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2709         bio_set_dev(bio, bdev);
2710         bio->bi_iter.bi_sector = first_byte >> 9;
2711         btrfs_io_bio_init(btrfs_io_bio(bio));
2712         return bio;
2713 }
2714
2715 struct bio *btrfs_bio_clone(struct bio *bio)
2716 {
2717         struct btrfs_io_bio *btrfs_bio;
2718         struct bio *new;
2719
2720         /* Bio allocation backed by a bioset does not fail */
2721         new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2722         btrfs_bio = btrfs_io_bio(new);
2723         btrfs_io_bio_init(btrfs_bio);
2724         btrfs_bio->iter = bio->bi_iter;
2725         return new;
2726 }
2727
2728 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2729 {
2730         struct bio *bio;
2731
2732         /* Bio allocation backed by a bioset does not fail */
2733         bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2734         btrfs_io_bio_init(btrfs_io_bio(bio));
2735         return bio;
2736 }
2737
2738 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2739 {
2740         struct bio *bio;
2741         struct btrfs_io_bio *btrfs_bio;
2742
2743         /* this will never fail when it's backed by a bioset */
2744         bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2745         ASSERT(bio);
2746
2747         btrfs_bio = btrfs_io_bio(bio);
2748         btrfs_io_bio_init(btrfs_bio);
2749
2750         bio_trim(bio, offset >> 9, size >> 9);
2751         btrfs_bio->iter = bio->bi_iter;
2752         return bio;
2753 }
2754
2755 /*
2756  * @opf:        bio REQ_OP_* and REQ_* flags as one value
2757  * @tree:       tree so we can call our merge_bio hook
2758  * @wbc:        optional writeback control for io accounting
2759  * @page:       page to add to the bio
2760  * @pg_offset:  offset of the new bio or to check whether we are adding
2761  *              a contiguous page to the previous one
2762  * @size:       portion of page that we want to write
2763  * @offset:     starting offset in the page
2764  * @bdev:       attach newly created bios to this bdev
2765  * @bio_ret:    must be valid pointer, newly allocated bio will be stored there
2766  * @end_io_func:     end_io callback for new bio
2767  * @mirror_num:      desired mirror to read/write
2768  * @prev_bio_flags:  flags of previous bio to see if we can merge the current one
2769  * @bio_flags:  flags of the current bio to see if we can merge them
2770  */
2771 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2772                               struct writeback_control *wbc,
2773                               struct page *page, u64 offset,
2774                               size_t size, unsigned long pg_offset,
2775                               struct block_device *bdev,
2776                               struct bio **bio_ret,
2777                               bio_end_io_t end_io_func,
2778                               int mirror_num,
2779                               unsigned long prev_bio_flags,
2780                               unsigned long bio_flags,
2781                               bool force_bio_submit)
2782 {
2783         int ret = 0;
2784         struct bio *bio;
2785         size_t page_size = min_t(size_t, size, PAGE_SIZE);
2786         sector_t sector = offset >> 9;
2787
2788         ASSERT(bio_ret);
2789
2790         if (*bio_ret) {
2791                 bool contig;
2792                 bool can_merge = true;
2793
2794                 bio = *bio_ret;
2795                 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2796                         contig = bio->bi_iter.bi_sector == sector;
2797                 else
2798                         contig = bio_end_sector(bio) == sector;
2799
2800                 ASSERT(tree->ops);
2801                 if (btrfs_bio_fits_in_stripe(page, page_size, bio, bio_flags))
2802                         can_merge = false;
2803
2804                 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2805                     force_bio_submit ||
2806                     bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2807                         ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2808                         if (ret < 0) {
2809                                 *bio_ret = NULL;
2810                                 return ret;
2811                         }
2812                         bio = NULL;
2813                 } else {
2814                         if (wbc)
2815                                 wbc_account_io(wbc, page, page_size);
2816                         return 0;
2817                 }
2818         }
2819
2820         bio = btrfs_bio_alloc(bdev, offset);
2821         bio_add_page(bio, page, page_size, pg_offset);
2822         bio->bi_end_io = end_io_func;
2823         bio->bi_private = tree;
2824         bio->bi_write_hint = page->mapping->host->i_write_hint;
2825         bio->bi_opf = opf;
2826         if (wbc) {
2827                 wbc_init_bio(wbc, bio);
2828                 wbc_account_io(wbc, page, page_size);
2829         }
2830
2831         *bio_ret = bio;
2832
2833         return ret;
2834 }
2835
2836 static void attach_extent_buffer_page(struct extent_buffer *eb,
2837                                       struct page *page)
2838 {
2839         if (!PagePrivate(page)) {
2840                 SetPagePrivate(page);
2841                 get_page(page);
2842                 set_page_private(page, (unsigned long)eb);
2843         } else {
2844                 WARN_ON(page->private != (unsigned long)eb);
2845         }
2846 }
2847
2848 void set_page_extent_mapped(struct page *page)
2849 {
2850         if (!PagePrivate(page)) {
2851                 SetPagePrivate(page);
2852                 get_page(page);
2853                 set_page_private(page, EXTENT_PAGE_PRIVATE);
2854         }
2855 }
2856
2857 static struct extent_map *
2858 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
2859                  u64 start, u64 len, get_extent_t *get_extent,
2860                  struct extent_map **em_cached)
2861 {
2862         struct extent_map *em;
2863
2864         if (em_cached && *em_cached) {
2865                 em = *em_cached;
2866                 if (extent_map_in_tree(em) && start >= em->start &&
2867                     start < extent_map_end(em)) {
2868                         refcount_inc(&em->refs);
2869                         return em;
2870                 }
2871
2872                 free_extent_map(em);
2873                 *em_cached = NULL;
2874         }
2875
2876         em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
2877         if (em_cached && !IS_ERR_OR_NULL(em)) {
2878                 BUG_ON(*em_cached);
2879                 refcount_inc(&em->refs);
2880                 *em_cached = em;
2881         }
2882         return em;
2883 }
2884 /*
2885  * basic readpage implementation.  Locked extent state structs are inserted
2886  * into the tree that are removed when the IO is done (by the end_io
2887  * handlers)
2888  * XXX JDM: This needs looking at to ensure proper page locking
2889  * return 0 on success, otherwise return error
2890  */
2891 static int __do_readpage(struct extent_io_tree *tree,
2892                          struct page *page,
2893                          get_extent_t *get_extent,
2894                          struct extent_map **em_cached,
2895                          struct bio **bio, int mirror_num,
2896                          unsigned long *bio_flags, unsigned int read_flags,
2897                          u64 *prev_em_start)
2898 {
2899         struct inode *inode = page->mapping->host;
2900         u64 start = page_offset(page);
2901         const u64 end = start + PAGE_SIZE - 1;
2902         u64 cur = start;
2903         u64 extent_offset;
2904         u64 last_byte = i_size_read(inode);
2905         u64 block_start;
2906         u64 cur_end;
2907         struct extent_map *em;
2908         struct block_device *bdev;
2909         int ret = 0;
2910         int nr = 0;
2911         size_t pg_offset = 0;
2912         size_t iosize;
2913         size_t disk_io_size;
2914         size_t blocksize = inode->i_sb->s_blocksize;
2915         unsigned long this_bio_flag = 0;
2916
2917         set_page_extent_mapped(page);
2918
2919         if (!PageUptodate(page)) {
2920                 if (cleancache_get_page(page) == 0) {
2921                         BUG_ON(blocksize != PAGE_SIZE);
2922                         unlock_extent(tree, start, end);
2923                         goto out;
2924                 }
2925         }
2926
2927         if (page->index == last_byte >> PAGE_SHIFT) {
2928                 char *userpage;
2929                 size_t zero_offset = offset_in_page(last_byte);
2930
2931                 if (zero_offset) {
2932                         iosize = PAGE_SIZE - zero_offset;
2933                         userpage = kmap_atomic(page);
2934                         memset(userpage + zero_offset, 0, iosize);
2935                         flush_dcache_page(page);
2936                         kunmap_atomic(userpage);
2937                 }
2938         }
2939         while (cur <= end) {
2940                 bool force_bio_submit = false;
2941                 u64 offset;
2942
2943                 if (cur >= last_byte) {
2944                         char *userpage;
2945                         struct extent_state *cached = NULL;
2946
2947                         iosize = PAGE_SIZE - pg_offset;
2948                         userpage = kmap_atomic(page);
2949                         memset(userpage + pg_offset, 0, iosize);
2950                         flush_dcache_page(page);
2951                         kunmap_atomic(userpage);
2952                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2953                                             &cached, GFP_NOFS);
2954                         unlock_extent_cached(tree, cur,
2955                                              cur + iosize - 1, &cached);
2956                         break;
2957                 }
2958                 em = __get_extent_map(inode, page, pg_offset, cur,
2959                                       end - cur + 1, get_extent, em_cached);
2960                 if (IS_ERR_OR_NULL(em)) {
2961                         SetPageError(page);
2962                         unlock_extent(tree, cur, end);
2963                         break;
2964                 }
2965                 extent_offset = cur - em->start;
2966                 BUG_ON(extent_map_end(em) <= cur);
2967                 BUG_ON(end < cur);
2968
2969                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2970                         this_bio_flag |= EXTENT_BIO_COMPRESSED;
2971                         extent_set_compress_type(&this_bio_flag,
2972                                                  em->compress_type);
2973                 }
2974
2975                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2976                 cur_end = min(extent_map_end(em) - 1, end);
2977                 iosize = ALIGN(iosize, blocksize);
2978                 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2979                         disk_io_size = em->block_len;
2980                         offset = em->block_start;
2981                 } else {
2982                         offset = em->block_start + extent_offset;
2983                         disk_io_size = iosize;
2984                 }
2985                 bdev = em->bdev;
2986                 block_start = em->block_start;
2987                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
2988                         block_start = EXTENT_MAP_HOLE;
2989
2990                 /*
2991                  * If we have a file range that points to a compressed extent
2992                  * and it's followed by a consecutive file range that points to
2993                  * to the same compressed extent (possibly with a different
2994                  * offset and/or length, so it either points to the whole extent
2995                  * or only part of it), we must make sure we do not submit a
2996                  * single bio to populate the pages for the 2 ranges because
2997                  * this makes the compressed extent read zero out the pages
2998                  * belonging to the 2nd range. Imagine the following scenario:
2999                  *
3000                  *  File layout
3001                  *  [0 - 8K]                     [8K - 24K]
3002                  *    |                               |
3003                  *    |                               |
3004                  * points to extent X,         points to extent X,
3005                  * offset 4K, length of 8K     offset 0, length 16K
3006                  *
3007                  * [extent X, compressed length = 4K uncompressed length = 16K]
3008                  *
3009                  * If the bio to read the compressed extent covers both ranges,
3010                  * it will decompress extent X into the pages belonging to the
3011                  * first range and then it will stop, zeroing out the remaining
3012                  * pages that belong to the other range that points to extent X.
3013                  * So here we make sure we submit 2 bios, one for the first
3014                  * range and another one for the third range. Both will target
3015                  * the same physical extent from disk, but we can't currently
3016                  * make the compressed bio endio callback populate the pages
3017                  * for both ranges because each compressed bio is tightly
3018                  * coupled with a single extent map, and each range can have
3019                  * an extent map with a different offset value relative to the
3020                  * uncompressed data of our extent and different lengths. This
3021                  * is a corner case so we prioritize correctness over
3022                  * non-optimal behavior (submitting 2 bios for the same extent).
3023                  */
3024                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3025                     prev_em_start && *prev_em_start != (u64)-1 &&
3026                     *prev_em_start != em->start)
3027                         force_bio_submit = true;
3028
3029                 if (prev_em_start)
3030                         *prev_em_start = em->start;
3031
3032                 free_extent_map(em);
3033                 em = NULL;
3034
3035                 /* we've found a hole, just zero and go on */
3036                 if (block_start == EXTENT_MAP_HOLE) {
3037                         char *userpage;
3038                         struct extent_state *cached = NULL;
3039
3040                         userpage = kmap_atomic(page);
3041                         memset(userpage + pg_offset, 0, iosize);
3042                         flush_dcache_page(page);
3043                         kunmap_atomic(userpage);
3044
3045                         set_extent_uptodate(tree, cur, cur + iosize - 1,
3046                                             &cached, GFP_NOFS);
3047                         unlock_extent_cached(tree, cur,
3048                                              cur + iosize - 1, &cached);
3049                         cur = cur + iosize;
3050                         pg_offset += iosize;
3051                         continue;
3052                 }
3053                 /* the get_extent function already copied into the page */
3054                 if (test_range_bit(tree, cur, cur_end,
3055                                    EXTENT_UPTODATE, 1, NULL)) {
3056                         check_page_uptodate(tree, page);
3057                         unlock_extent(tree, cur, cur + iosize - 1);
3058                         cur = cur + iosize;
3059                         pg_offset += iosize;
3060                         continue;
3061                 }
3062                 /* we have an inline extent but it didn't get marked up
3063                  * to date.  Error out
3064                  */
3065                 if (block_start == EXTENT_MAP_INLINE) {
3066                         SetPageError(page);
3067                         unlock_extent(tree, cur, cur + iosize - 1);
3068                         cur = cur + iosize;
3069                         pg_offset += iosize;
3070                         continue;
3071                 }
3072
3073                 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3074                                          page, offset, disk_io_size,
3075                                          pg_offset, bdev, bio,
3076                                          end_bio_extent_readpage, mirror_num,
3077                                          *bio_flags,
3078                                          this_bio_flag,
3079                                          force_bio_submit);
3080                 if (!ret) {
3081                         nr++;
3082                         *bio_flags = this_bio_flag;
3083                 } else {
3084                         SetPageError(page);
3085                         unlock_extent(tree, cur, cur + iosize - 1);
3086                         goto out;
3087                 }
3088                 cur = cur + iosize;
3089                 pg_offset += iosize;
3090         }
3091 out:
3092         if (!nr) {
3093                 if (!PageError(page))
3094                         SetPageUptodate(page);
3095                 unlock_page(page);
3096         }
3097         return ret;
3098 }
3099
3100 static inline void contiguous_readpages(struct extent_io_tree *tree,
3101                                              struct page *pages[], int nr_pages,
3102                                              u64 start, u64 end,
3103                                              struct extent_map **em_cached,
3104                                              struct bio **bio,
3105                                              unsigned long *bio_flags,
3106                                              u64 *prev_em_start)
3107 {
3108         struct inode *inode;
3109         struct btrfs_ordered_extent *ordered;
3110         int index;
3111
3112         inode = pages[0]->mapping->host;
3113         while (1) {
3114                 lock_extent(tree, start, end);
3115                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3116                                                      end - start + 1);
3117                 if (!ordered)
3118                         break;
3119                 unlock_extent(tree, start, end);
3120                 btrfs_start_ordered_extent(inode, ordered, 1);
3121                 btrfs_put_ordered_extent(ordered);
3122         }
3123
3124         for (index = 0; index < nr_pages; index++) {
312