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