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