GNU Linux-libre 4.19.211-gnu1
[releases.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         if (tree->ops && tree->ops->check_extent_io_range)
93                 tree->ops->check_extent_io_range(tree->private_data, caller,
94                                                  start, end);
95 }
96 #else
97 #define btrfs_leak_debug_add(new, head) do {} while (0)
98 #define btrfs_leak_debug_del(entry)     do {} while (0)
99 #define btrfs_leak_debug_check()        do {} while (0)
100 #define btrfs_debug_check_extent_io_range(c, s, e)      do {} while (0)
101 #endif
102
103 #define BUFFER_LRU_MAX 64
104
105 struct tree_entry {
106         u64 start;
107         u64 end;
108         struct rb_node rb_node;
109 };
110
111 struct extent_page_data {
112         struct bio *bio;
113         struct extent_io_tree *tree;
114         /* tells writepage not to lock the state bits for this range
115          * it still does the unlocking
116          */
117         unsigned int extent_locked:1;
118
119         /* tells the submit_bio code to use REQ_SYNC */
120         unsigned int sync_io:1;
121 };
122
123 static int add_extent_changeset(struct extent_state *state, unsigned bits,
124                                  struct extent_changeset *changeset,
125                                  int set)
126 {
127         int ret;
128
129         if (!changeset)
130                 return 0;
131         if (set && (state->state & bits) == bits)
132                 return 0;
133         if (!set && (state->state & bits) == 0)
134                 return 0;
135         changeset->bytes_changed += state->end - state->start + 1;
136         ret = ulist_add(&changeset->range_changed, state->start, state->end,
137                         GFP_ATOMIC);
138         return ret;
139 }
140
141 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
142                                        unsigned long bio_flags)
143 {
144         blk_status_t ret = 0;
145         struct bio_vec *bvec = bio_last_bvec_all(bio);
146         struct page *page = bvec->bv_page;
147         struct extent_io_tree *tree = bio->bi_private;
148         u64 start;
149
150         start = page_offset(page) + bvec->bv_offset;
151
152         bio->bi_private = NULL;
153
154         if (tree->ops)
155                 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
156                                            mirror_num, bio_flags, start);
157         else
158                 btrfsic_submit_bio(bio);
159
160         return blk_status_to_errno(ret);
161 }
162
163 /* Cleanup unsubmitted bios */
164 static void end_write_bio(struct extent_page_data *epd, int ret)
165 {
166         if (epd->bio) {
167                 epd->bio->bi_status = errno_to_blk_status(ret);
168                 bio_endio(epd->bio);
169                 epd->bio = NULL;
170         }
171 }
172
173 /*
174  * Submit bio from extent page data via submit_one_bio
175  *
176  * Return 0 if everything is OK.
177  * Return <0 for error.
178  */
179 static int __must_check flush_write_bio(struct extent_page_data *epd)
180 {
181         int ret = 0;
182
183         if (epd->bio) {
184                 ret = submit_one_bio(epd->bio, 0, 0);
185                 /*
186                  * Clean up of epd->bio is handled by its endio function.
187                  * And endio is either triggered by successful bio execution
188                  * or the error handler of submit bio hook.
189                  * So at this point, no matter what happened, we don't need
190                  * to clean up epd->bio.
191                  */
192                 epd->bio = NULL;
193         }
194         return ret;
195 }
196
197 int __init extent_io_init(void)
198 {
199         extent_state_cache = kmem_cache_create("btrfs_extent_state",
200                         sizeof(struct extent_state), 0,
201                         SLAB_MEM_SPREAD, NULL);
202         if (!extent_state_cache)
203                 return -ENOMEM;
204
205         extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
206                         sizeof(struct extent_buffer), 0,
207                         SLAB_MEM_SPREAD, NULL);
208         if (!extent_buffer_cache)
209                 goto free_state_cache;
210
211         if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
212                         offsetof(struct btrfs_io_bio, bio),
213                         BIOSET_NEED_BVECS))
214                 goto free_buffer_cache;
215
216         if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
217                 goto free_bioset;
218
219         return 0;
220
221 free_bioset:
222         bioset_exit(&btrfs_bioset);
223
224 free_buffer_cache:
225         kmem_cache_destroy(extent_buffer_cache);
226         extent_buffer_cache = NULL;
227
228 free_state_cache:
229         kmem_cache_destroy(extent_state_cache);
230         extent_state_cache = NULL;
231         return -ENOMEM;
232 }
233
234 void __cold extent_io_exit(void)
235 {
236         btrfs_leak_debug_check();
237
238         /*
239          * Make sure all delayed rcu free are flushed before we
240          * destroy caches.
241          */
242         rcu_barrier();
243         kmem_cache_destroy(extent_state_cache);
244         kmem_cache_destroy(extent_buffer_cache);
245         bioset_exit(&btrfs_bioset);
246 }
247
248 void extent_io_tree_init(struct extent_io_tree *tree,
249                          void *private_data)
250 {
251         tree->state = RB_ROOT;
252         tree->ops = NULL;
253         tree->dirty_bytes = 0;
254         spin_lock_init(&tree->lock);
255         tree->private_data = private_data;
256 }
257
258 static struct extent_state *alloc_extent_state(gfp_t mask)
259 {
260         struct extent_state *state;
261
262         /*
263          * The given mask might be not appropriate for the slab allocator,
264          * drop the unsupported bits
265          */
266         mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
267         state = kmem_cache_alloc(extent_state_cache, mask);
268         if (!state)
269                 return state;
270         state->state = 0;
271         state->failrec = NULL;
272         RB_CLEAR_NODE(&state->rb_node);
273         btrfs_leak_debug_add(&state->leak_list, &states);
274         refcount_set(&state->refs, 1);
275         init_waitqueue_head(&state->wq);
276         trace_alloc_extent_state(state, mask, _RET_IP_);
277         return state;
278 }
279
280 void free_extent_state(struct extent_state *state)
281 {
282         if (!state)
283                 return;
284         if (refcount_dec_and_test(&state->refs)) {
285                 WARN_ON(extent_state_in_tree(state));
286                 btrfs_leak_debug_del(&state->leak_list);
287                 trace_free_extent_state(state, _RET_IP_);
288                 kmem_cache_free(extent_state_cache, state);
289         }
290 }
291
292 static struct rb_node *tree_insert(struct rb_root *root,
293                                    struct rb_node *search_start,
294                                    u64 offset,
295                                    struct rb_node *node,
296                                    struct rb_node ***p_in,
297                                    struct rb_node **parent_in)
298 {
299         struct rb_node **p;
300         struct rb_node *parent = NULL;
301         struct tree_entry *entry;
302
303         if (p_in && parent_in) {
304                 p = *p_in;
305                 parent = *parent_in;
306                 goto do_insert;
307         }
308
309         p = search_start ? &search_start : &root->rb_node;
310         while (*p) {
311                 parent = *p;
312                 entry = rb_entry(parent, struct tree_entry, rb_node);
313
314                 if (offset < entry->start)
315                         p = &(*p)->rb_left;
316                 else if (offset > entry->end)
317                         p = &(*p)->rb_right;
318                 else
319                         return parent;
320         }
321
322 do_insert:
323         rb_link_node(node, parent, p);
324         rb_insert_color(node, root);
325         return NULL;
326 }
327
328 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
329                                       struct rb_node **prev_ret,
330                                       struct rb_node **next_ret,
331                                       struct rb_node ***p_ret,
332                                       struct rb_node **parent_ret)
333 {
334         struct rb_root *root = &tree->state;
335         struct rb_node **n = &root->rb_node;
336         struct rb_node *prev = NULL;
337         struct rb_node *orig_prev = NULL;
338         struct tree_entry *entry;
339         struct tree_entry *prev_entry = NULL;
340
341         while (*n) {
342                 prev = *n;
343                 entry = rb_entry(prev, struct tree_entry, rb_node);
344                 prev_entry = entry;
345
346                 if (offset < entry->start)
347                         n = &(*n)->rb_left;
348                 else if (offset > entry->end)
349                         n = &(*n)->rb_right;
350                 else
351                         return *n;
352         }
353
354         if (p_ret)
355                 *p_ret = n;
356         if (parent_ret)
357                 *parent_ret = prev;
358
359         if (prev_ret) {
360                 orig_prev = prev;
361                 while (prev && offset > prev_entry->end) {
362                         prev = rb_next(prev);
363                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
364                 }
365                 *prev_ret = prev;
366                 prev = orig_prev;
367         }
368
369         if (next_ret) {
370                 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
371                 while (prev && offset < prev_entry->start) {
372                         prev = rb_prev(prev);
373                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
374                 }
375                 *next_ret = prev;
376         }
377         return NULL;
378 }
379
380 static inline struct rb_node *
381 tree_search_for_insert(struct extent_io_tree *tree,
382                        u64 offset,
383                        struct rb_node ***p_ret,
384                        struct rb_node **parent_ret)
385 {
386         struct rb_node *prev = NULL;
387         struct rb_node *ret;
388
389         ret = __etree_search(tree, offset, &prev, NULL, p_ret, parent_ret);
390         if (!ret)
391                 return prev;
392         return ret;
393 }
394
395 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
396                                           u64 offset)
397 {
398         return tree_search_for_insert(tree, offset, NULL, NULL);
399 }
400
401 static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
402                      struct extent_state *other)
403 {
404         if (tree->ops && tree->ops->merge_extent_hook)
405                 tree->ops->merge_extent_hook(tree->private_data, new, other);
406 }
407
408 /*
409  * utility function to look for merge candidates inside a given range.
410  * Any extents with matching state are merged together into a single
411  * extent in the tree.  Extents with EXTENT_IO in their state field
412  * are not merged because the end_io handlers need to be able to do
413  * operations on them without sleeping (or doing allocations/splits).
414  *
415  * This should be called with the tree lock held.
416  */
417 static void merge_state(struct extent_io_tree *tree,
418                         struct extent_state *state)
419 {
420         struct extent_state *other;
421         struct rb_node *other_node;
422
423         if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
424                 return;
425
426         other_node = rb_prev(&state->rb_node);
427         if (other_node) {
428                 other = rb_entry(other_node, struct extent_state, rb_node);
429                 if (other->end == state->start - 1 &&
430                     other->state == state->state) {
431                         merge_cb(tree, state, other);
432                         state->start = other->start;
433                         rb_erase(&other->rb_node, &tree->state);
434                         RB_CLEAR_NODE(&other->rb_node);
435                         free_extent_state(other);
436                 }
437         }
438         other_node = rb_next(&state->rb_node);
439         if (other_node) {
440                 other = rb_entry(other_node, struct extent_state, rb_node);
441                 if (other->start == state->end + 1 &&
442                     other->state == state->state) {
443                         merge_cb(tree, state, other);
444                         state->end = other->end;
445                         rb_erase(&other->rb_node, &tree->state);
446                         RB_CLEAR_NODE(&other->rb_node);
447                         free_extent_state(other);
448                 }
449         }
450 }
451
452 static void set_state_cb(struct extent_io_tree *tree,
453                          struct extent_state *state, unsigned *bits)
454 {
455         if (tree->ops && tree->ops->set_bit_hook)
456                 tree->ops->set_bit_hook(tree->private_data, state, bits);
457 }
458
459 static void clear_state_cb(struct extent_io_tree *tree,
460                            struct extent_state *state, unsigned *bits)
461 {
462         if (tree->ops && tree->ops->clear_bit_hook)
463                 tree->ops->clear_bit_hook(tree->private_data, state, bits);
464 }
465
466 static void set_state_bits(struct extent_io_tree *tree,
467                            struct extent_state *state, unsigned *bits,
468                            struct extent_changeset *changeset);
469
470 /*
471  * insert an extent_state struct into the tree.  'bits' are set on the
472  * struct before it is inserted.
473  *
474  * This may return -EEXIST if the extent is already there, in which case the
475  * state struct is freed.
476  *
477  * The tree lock is not taken internally.  This is a utility function and
478  * probably isn't what you want to call (see set/clear_extent_bit).
479  */
480 static int insert_state(struct extent_io_tree *tree,
481                         struct extent_state *state, u64 start, u64 end,
482                         struct rb_node ***p,
483                         struct rb_node **parent,
484                         unsigned *bits, struct extent_changeset *changeset)
485 {
486         struct rb_node *node;
487
488         if (end < start)
489                 WARN(1, KERN_ERR "BTRFS: end < start %llu %llu\n",
490                        end, start);
491         state->start = start;
492         state->end = end;
493
494         set_state_bits(tree, state, bits, changeset);
495
496         node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
497         if (node) {
498                 struct extent_state *found;
499                 found = rb_entry(node, struct extent_state, rb_node);
500                 pr_err("BTRFS: found node %llu %llu on insert of %llu %llu\n",
501                        found->start, found->end, start, end);
502                 return -EEXIST;
503         }
504         merge_state(tree, state);
505         return 0;
506 }
507
508 static void split_cb(struct extent_io_tree *tree, struct extent_state *orig,
509                      u64 split)
510 {
511         if (tree->ops && tree->ops->split_extent_hook)
512                 tree->ops->split_extent_hook(tree->private_data, orig, split);
513 }
514
515 /*
516  * split a given extent state struct in two, inserting the preallocated
517  * struct 'prealloc' as the newly created second half.  'split' indicates an
518  * offset inside 'orig' where it should be split.
519  *
520  * Before calling,
521  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
522  * are two extent state structs in the tree:
523  * prealloc: [orig->start, split - 1]
524  * orig: [ split, orig->end ]
525  *
526  * The tree locks are not taken by this function. They need to be held
527  * by the caller.
528  */
529 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
530                        struct extent_state *prealloc, u64 split)
531 {
532         struct rb_node *node;
533
534         split_cb(tree, orig, split);
535
536         prealloc->start = orig->start;
537         prealloc->end = split - 1;
538         prealloc->state = orig->state;
539         orig->start = split;
540
541         node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
542                            &prealloc->rb_node, NULL, NULL);
543         if (node) {
544                 free_extent_state(prealloc);
545                 return -EEXIST;
546         }
547         return 0;
548 }
549
550 static struct extent_state *next_state(struct extent_state *state)
551 {
552         struct rb_node *next = rb_next(&state->rb_node);
553         if (next)
554                 return rb_entry(next, struct extent_state, rb_node);
555         else
556                 return NULL;
557 }
558
559 /*
560  * utility function to clear some bits in an extent state struct.
561  * it will optionally wake up any one waiting on this state (wake == 1).
562  *
563  * If no bits are set on the state struct after clearing things, the
564  * struct is freed and removed from the tree
565  */
566 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
567                                             struct extent_state *state,
568                                             unsigned *bits, int wake,
569                                             struct extent_changeset *changeset)
570 {
571         struct extent_state *next;
572         unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
573         int ret;
574
575         if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
576                 u64 range = state->end - state->start + 1;
577                 WARN_ON(range > tree->dirty_bytes);
578                 tree->dirty_bytes -= range;
579         }
580         clear_state_cb(tree, state, bits);
581         ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
582         BUG_ON(ret < 0);
583         state->state &= ~bits_to_clear;
584         if (wake)
585                 wake_up(&state->wq);
586         if (state->state == 0) {
587                 next = next_state(state);
588                 if (extent_state_in_tree(state)) {
589                         rb_erase(&state->rb_node, &tree->state);
590                         RB_CLEAR_NODE(&state->rb_node);
591                         free_extent_state(state);
592                 } else {
593                         WARN_ON(1);
594                 }
595         } else {
596                 merge_state(tree, state);
597                 next = next_state(state);
598         }
599         return next;
600 }
601
602 static struct extent_state *
603 alloc_extent_state_atomic(struct extent_state *prealloc)
604 {
605         if (!prealloc)
606                 prealloc = alloc_extent_state(GFP_ATOMIC);
607
608         return prealloc;
609 }
610
611 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
612 {
613         struct inode *inode = tree->private_data;
614
615         btrfs_panic(btrfs_sb(inode->i_sb), err,
616         "locking error: extent tree was modified by another thread while locked");
617 }
618
619 /*
620  * clear some bits on a range in the tree.  This may require splitting
621  * or inserting elements in the tree, so the gfp mask is used to
622  * indicate which allocations or sleeping are allowed.
623  *
624  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
625  * the given range from the tree regardless of state (ie for truncate).
626  *
627  * the range [start, end] is inclusive.
628  *
629  * This takes the tree lock, and returns 0 on success and < 0 on error.
630  */
631 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
632                               unsigned bits, int wake, int delete,
633                               struct extent_state **cached_state,
634                               gfp_t mask, struct extent_changeset *changeset)
635 {
636         struct extent_state *state;
637         struct extent_state *cached;
638         struct extent_state *prealloc = NULL;
639         struct rb_node *node;
640         u64 last_end;
641         int err;
642         int clear = 0;
643
644         btrfs_debug_check_extent_io_range(tree, start, end);
645
646         if (bits & EXTENT_DELALLOC)
647                 bits |= EXTENT_NORESERVE;
648
649         if (delete)
650                 bits |= ~EXTENT_CTLBITS;
651         bits |= EXTENT_FIRST_DELALLOC;
652
653         if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
654                 clear = 1;
655 again:
656         if (!prealloc && gfpflags_allow_blocking(mask)) {
657                 /*
658                  * Don't care for allocation failure here because we might end
659                  * up not needing the pre-allocated extent state at all, which
660                  * is the case if we only have in the tree extent states that
661                  * cover our input range and don't cover too any other range.
662                  * If we end up needing a new extent state we allocate it later.
663                  */
664                 prealloc = alloc_extent_state(mask);
665         }
666
667         spin_lock(&tree->lock);
668         if (cached_state) {
669                 cached = *cached_state;
670
671                 if (clear) {
672                         *cached_state = NULL;
673                         cached_state = NULL;
674                 }
675
676                 if (cached && extent_state_in_tree(cached) &&
677                     cached->start <= start && cached->end > start) {
678                         if (clear)
679                                 refcount_dec(&cached->refs);
680                         state = cached;
681                         goto hit_next;
682                 }
683                 if (clear)
684                         free_extent_state(cached);
685         }
686         /*
687          * this search will find the extents that end after
688          * our range starts
689          */
690         node = tree_search(tree, start);
691         if (!node)
692                 goto out;
693         state = rb_entry(node, struct extent_state, rb_node);
694 hit_next:
695         if (state->start > end)
696                 goto out;
697         WARN_ON(state->end < start);
698         last_end = state->end;
699
700         /* the state doesn't have the wanted bits, go ahead */
701         if (!(state->state & bits)) {
702                 state = next_state(state);
703                 goto next;
704         }
705
706         /*
707          *     | ---- desired range ---- |
708          *  | state | or
709          *  | ------------- state -------------- |
710          *
711          * We need to split the extent we found, and may flip
712          * bits on second half.
713          *
714          * If the extent we found extends past our range, we
715          * just split and search again.  It'll get split again
716          * the next time though.
717          *
718          * If the extent we found is inside our range, we clear
719          * the desired bit on it.
720          */
721
722         if (state->start < start) {
723                 prealloc = alloc_extent_state_atomic(prealloc);
724                 BUG_ON(!prealloc);
725                 err = split_state(tree, state, prealloc, start);
726                 if (err)
727                         extent_io_tree_panic(tree, err);
728
729                 prealloc = NULL;
730                 if (err)
731                         goto out;
732                 if (state->end <= end) {
733                         state = clear_state_bit(tree, state, &bits, wake,
734                                                 changeset);
735                         goto next;
736                 }
737                 goto search_again;
738         }
739         /*
740          * | ---- desired range ---- |
741          *                        | state |
742          * We need to split the extent, and clear the bit
743          * on the first half
744          */
745         if (state->start <= end && state->end > end) {
746                 prealloc = alloc_extent_state_atomic(prealloc);
747                 BUG_ON(!prealloc);
748                 err = split_state(tree, state, prealloc, end + 1);
749                 if (err)
750                         extent_io_tree_panic(tree, err);
751
752                 if (wake)
753                         wake_up(&state->wq);
754
755                 clear_state_bit(tree, prealloc, &bits, wake, changeset);
756
757                 prealloc = NULL;
758                 goto out;
759         }
760
761         state = clear_state_bit(tree, state, &bits, wake, changeset);
762 next:
763         if (last_end == (u64)-1)
764                 goto out;
765         start = last_end + 1;
766         if (start <= end && state && !need_resched())
767                 goto hit_next;
768
769 search_again:
770         if (start > end)
771                 goto out;
772         spin_unlock(&tree->lock);
773         if (gfpflags_allow_blocking(mask))
774                 cond_resched();
775         goto again;
776
777 out:
778         spin_unlock(&tree->lock);
779         if (prealloc)
780                 free_extent_state(prealloc);
781
782         return 0;
783
784 }
785
786 static void wait_on_state(struct extent_io_tree *tree,
787                           struct extent_state *state)
788                 __releases(tree->lock)
789                 __acquires(tree->lock)
790 {
791         DEFINE_WAIT(wait);
792         prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
793         spin_unlock(&tree->lock);
794         schedule();
795         spin_lock(&tree->lock);
796         finish_wait(&state->wq, &wait);
797 }
798
799 /*
800  * waits for one or more bits to clear on a range in the state tree.
801  * The range [start, end] is inclusive.
802  * The tree lock is taken by this function
803  */
804 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
805                             unsigned long bits)
806 {
807         struct extent_state *state;
808         struct rb_node *node;
809
810         btrfs_debug_check_extent_io_range(tree, start, end);
811
812         spin_lock(&tree->lock);
813 again:
814         while (1) {
815                 /*
816                  * this search will find all the extents that end after
817                  * our range starts
818                  */
819                 node = tree_search(tree, start);
820 process_node:
821                 if (!node)
822                         break;
823
824                 state = rb_entry(node, struct extent_state, rb_node);
825
826                 if (state->start > end)
827                         goto out;
828
829                 if (state->state & bits) {
830                         start = state->start;
831                         refcount_inc(&state->refs);
832                         wait_on_state(tree, state);
833                         free_extent_state(state);
834                         goto again;
835                 }
836                 start = state->end + 1;
837
838                 if (start > end)
839                         break;
840
841                 if (!cond_resched_lock(&tree->lock)) {
842                         node = rb_next(node);
843                         goto process_node;
844                 }
845         }
846 out:
847         spin_unlock(&tree->lock);
848 }
849
850 static void set_state_bits(struct extent_io_tree *tree,
851                            struct extent_state *state,
852                            unsigned *bits, struct extent_changeset *changeset)
853 {
854         unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
855         int ret;
856
857         set_state_cb(tree, state, bits);
858         if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
859                 u64 range = state->end - state->start + 1;
860                 tree->dirty_bytes += range;
861         }
862         ret = add_extent_changeset(state, bits_to_set, changeset, 1);
863         BUG_ON(ret < 0);
864         state->state |= bits_to_set;
865 }
866
867 static void cache_state_if_flags(struct extent_state *state,
868                                  struct extent_state **cached_ptr,
869                                  unsigned flags)
870 {
871         if (cached_ptr && !(*cached_ptr)) {
872                 if (!flags || (state->state & flags)) {
873                         *cached_ptr = state;
874                         refcount_inc(&state->refs);
875                 }
876         }
877 }
878
879 static void cache_state(struct extent_state *state,
880                         struct extent_state **cached_ptr)
881 {
882         return cache_state_if_flags(state, cached_ptr,
883                                     EXTENT_IOBITS | EXTENT_BOUNDARY);
884 }
885
886 /*
887  * set some bits on a range in the tree.  This may require allocations or
888  * sleeping, so the gfp mask is used to indicate what is allowed.
889  *
890  * If any of the exclusive bits are set, this will fail with -EEXIST if some
891  * part of the range already has the desired bits set.  The start of the
892  * existing range is returned in failed_start in this case.
893  *
894  * [start, end] is inclusive This takes the tree lock.
895  */
896
897 static int __must_check
898 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
899                  unsigned bits, unsigned exclusive_bits,
900                  u64 *failed_start, struct extent_state **cached_state,
901                  gfp_t mask, struct extent_changeset *changeset)
902 {
903         struct extent_state *state;
904         struct extent_state *prealloc = NULL;
905         struct rb_node *node;
906         struct rb_node **p;
907         struct rb_node *parent;
908         int err = 0;
909         u64 last_start;
910         u64 last_end;
911
912         btrfs_debug_check_extent_io_range(tree, start, end);
913
914         bits |= EXTENT_FIRST_DELALLOC;
915 again:
916         if (!prealloc && gfpflags_allow_blocking(mask)) {
917                 /*
918                  * Don't care for allocation failure here because we might end
919                  * up not needing the pre-allocated extent state at all, which
920                  * is the case if we only have in the tree extent states that
921                  * cover our input range and don't cover too any other range.
922                  * If we end up needing a new extent state we allocate it later.
923                  */
924                 prealloc = alloc_extent_state(mask);
925         }
926
927         spin_lock(&tree->lock);
928         if (cached_state && *cached_state) {
929                 state = *cached_state;
930                 if (state->start <= start && state->end > start &&
931                     extent_state_in_tree(state)) {
932                         node = &state->rb_node;
933                         goto hit_next;
934                 }
935         }
936         /*
937          * this search will find all the extents that end after
938          * our range starts.
939          */
940         node = tree_search_for_insert(tree, start, &p, &parent);
941         if (!node) {
942                 prealloc = alloc_extent_state_atomic(prealloc);
943                 BUG_ON(!prealloc);
944                 err = insert_state(tree, prealloc, start, end,
945                                    &p, &parent, &bits, changeset);
946                 if (err)
947                         extent_io_tree_panic(tree, err);
948
949                 cache_state(prealloc, cached_state);
950                 prealloc = NULL;
951                 goto out;
952         }
953         state = rb_entry(node, struct extent_state, rb_node);
954 hit_next:
955         last_start = state->start;
956         last_end = state->end;
957
958         /*
959          * | ---- desired range ---- |
960          * | state |
961          *
962          * Just lock what we found and keep going
963          */
964         if (state->start == start && state->end <= end) {
965                 if (state->state & exclusive_bits) {
966                         *failed_start = state->start;
967                         err = -EEXIST;
968                         goto out;
969                 }
970
971                 set_state_bits(tree, state, &bits, changeset);
972                 cache_state(state, cached_state);
973                 merge_state(tree, state);
974                 if (last_end == (u64)-1)
975                         goto out;
976                 start = last_end + 1;
977                 state = next_state(state);
978                 if (start < end && state && state->start == start &&
979                     !need_resched())
980                         goto hit_next;
981                 goto search_again;
982         }
983
984         /*
985          *     | ---- desired range ---- |
986          * | state |
987          *   or
988          * | ------------- state -------------- |
989          *
990          * We need to split the extent we found, and may flip bits on
991          * second half.
992          *
993          * If the extent we found extends past our
994          * range, we just split and search again.  It'll get split
995          * again the next time though.
996          *
997          * If the extent we found is inside our range, we set the
998          * desired bit on it.
999          */
1000         if (state->start < start) {
1001                 if (state->state & exclusive_bits) {
1002                         *failed_start = start;
1003                         err = -EEXIST;
1004                         goto out;
1005                 }
1006
1007                 prealloc = alloc_extent_state_atomic(prealloc);
1008                 BUG_ON(!prealloc);
1009                 err = split_state(tree, state, prealloc, start);
1010                 if (err)
1011                         extent_io_tree_panic(tree, err);
1012
1013                 prealloc = NULL;
1014                 if (err)
1015                         goto out;
1016                 if (state->end <= end) {
1017                         set_state_bits(tree, state, &bits, changeset);
1018                         cache_state(state, cached_state);
1019                         merge_state(tree, state);
1020                         if (last_end == (u64)-1)
1021                                 goto out;
1022                         start = last_end + 1;
1023                         state = next_state(state);
1024                         if (start < end && state && state->start == start &&
1025                             !need_resched())
1026                                 goto hit_next;
1027                 }
1028                 goto search_again;
1029         }
1030         /*
1031          * | ---- desired range ---- |
1032          *     | state | or               | state |
1033          *
1034          * There's a hole, we need to insert something in it and
1035          * ignore the extent we found.
1036          */
1037         if (state->start > start) {
1038                 u64 this_end;
1039                 if (end < last_start)
1040                         this_end = end;
1041                 else
1042                         this_end = last_start - 1;
1043
1044                 prealloc = alloc_extent_state_atomic(prealloc);
1045                 BUG_ON(!prealloc);
1046
1047                 /*
1048                  * Avoid to free 'prealloc' if it can be merged with
1049                  * the later extent.
1050                  */
1051                 err = insert_state(tree, prealloc, start, this_end,
1052                                    NULL, NULL, &bits, changeset);
1053                 if (err)
1054                         extent_io_tree_panic(tree, err);
1055
1056                 cache_state(prealloc, cached_state);
1057                 prealloc = NULL;
1058                 start = this_end + 1;
1059                 goto search_again;
1060         }
1061         /*
1062          * | ---- desired range ---- |
1063          *                        | state |
1064          * We need to split the extent, and set the bit
1065          * on the first half
1066          */
1067         if (state->start <= end && state->end > end) {
1068                 if (state->state & exclusive_bits) {
1069                         *failed_start = start;
1070                         err = -EEXIST;
1071                         goto out;
1072                 }
1073
1074                 prealloc = alloc_extent_state_atomic(prealloc);
1075                 BUG_ON(!prealloc);
1076                 err = split_state(tree, state, prealloc, end + 1);
1077                 if (err)
1078                         extent_io_tree_panic(tree, err);
1079
1080                 set_state_bits(tree, prealloc, &bits, changeset);
1081                 cache_state(prealloc, cached_state);
1082                 merge_state(tree, prealloc);
1083                 prealloc = NULL;
1084                 goto out;
1085         }
1086
1087 search_again:
1088         if (start > end)
1089                 goto out;
1090         spin_unlock(&tree->lock);
1091         if (gfpflags_allow_blocking(mask))
1092                 cond_resched();
1093         goto again;
1094
1095 out:
1096         spin_unlock(&tree->lock);
1097         if (prealloc)
1098                 free_extent_state(prealloc);
1099
1100         return err;
1101
1102 }
1103
1104 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1105                    unsigned bits, u64 * failed_start,
1106                    struct extent_state **cached_state, gfp_t mask)
1107 {
1108         return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1109                                 cached_state, mask, NULL);
1110 }
1111
1112
1113 /**
1114  * convert_extent_bit - convert all bits in a given range from one bit to
1115  *                      another
1116  * @tree:       the io tree to search
1117  * @start:      the start offset in bytes
1118  * @end:        the end offset in bytes (inclusive)
1119  * @bits:       the bits to set in this range
1120  * @clear_bits: the bits to clear in this range
1121  * @cached_state:       state that we're going to cache
1122  *
1123  * This will go through and set bits for the given range.  If any states exist
1124  * already in this range they are set with the given bit and cleared of the
1125  * clear_bits.  This is only meant to be used by things that are mergeable, ie
1126  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
1127  * boundary bits like LOCK.
1128  *
1129  * All allocations are done with GFP_NOFS.
1130  */
1131 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1132                        unsigned bits, unsigned clear_bits,
1133                        struct extent_state **cached_state)
1134 {
1135         struct extent_state *state;
1136         struct extent_state *prealloc = NULL;
1137         struct rb_node *node;
1138         struct rb_node **p;
1139         struct rb_node *parent;
1140         int err = 0;
1141         u64 last_start;
1142         u64 last_end;
1143         bool first_iteration = true;
1144
1145         btrfs_debug_check_extent_io_range(tree, start, end);
1146
1147 again:
1148         if (!prealloc) {
1149                 /*
1150                  * Best effort, don't worry if extent state allocation fails
1151                  * here for the first iteration. We might have a cached state
1152                  * that matches exactly the target range, in which case no
1153                  * extent state allocations are needed. We'll only know this
1154                  * after locking the tree.
1155                  */
1156                 prealloc = alloc_extent_state(GFP_NOFS);
1157                 if (!prealloc && !first_iteration)
1158                         return -ENOMEM;
1159         }
1160
1161         spin_lock(&tree->lock);
1162         if (cached_state && *cached_state) {
1163                 state = *cached_state;
1164                 if (state->start <= start && state->end > start &&
1165                     extent_state_in_tree(state)) {
1166                         node = &state->rb_node;
1167                         goto hit_next;
1168                 }
1169         }
1170
1171         /*
1172          * this search will find all the extents that end after
1173          * our range starts.
1174          */
1175         node = tree_search_for_insert(tree, start, &p, &parent);
1176         if (!node) {
1177                 prealloc = alloc_extent_state_atomic(prealloc);
1178                 if (!prealloc) {
1179                         err = -ENOMEM;
1180                         goto out;
1181                 }
1182                 err = insert_state(tree, prealloc, start, end,
1183                                    &p, &parent, &bits, NULL);
1184                 if (err)
1185                         extent_io_tree_panic(tree, err);
1186                 cache_state(prealloc, cached_state);
1187                 prealloc = NULL;
1188                 goto out;
1189         }
1190         state = rb_entry(node, struct extent_state, rb_node);
1191 hit_next:
1192         last_start = state->start;
1193         last_end = state->end;
1194
1195         /*
1196          * | ---- desired range ---- |
1197          * | state |
1198          *
1199          * Just lock what we found and keep going
1200          */
1201         if (state->start == start && state->end <= end) {
1202                 set_state_bits(tree, state, &bits, NULL);
1203                 cache_state(state, cached_state);
1204                 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1205                 if (last_end == (u64)-1)
1206                         goto out;
1207                 start = last_end + 1;
1208                 if (start < end && state && state->start == start &&
1209                     !need_resched())
1210                         goto hit_next;
1211                 goto search_again;
1212         }
1213
1214         /*
1215          *     | ---- desired range ---- |
1216          * | state |
1217          *   or
1218          * | ------------- state -------------- |
1219          *
1220          * We need to split the extent we found, and may flip bits on
1221          * second half.
1222          *
1223          * If the extent we found extends past our
1224          * range, we just split and search again.  It'll get split
1225          * again the next time though.
1226          *
1227          * If the extent we found is inside our range, we set the
1228          * desired bit on it.
1229          */
1230         if (state->start < start) {
1231                 prealloc = alloc_extent_state_atomic(prealloc);
1232                 if (!prealloc) {
1233                         err = -ENOMEM;
1234                         goto out;
1235                 }
1236                 err = split_state(tree, state, prealloc, start);
1237                 if (err)
1238                         extent_io_tree_panic(tree, err);
1239                 prealloc = NULL;
1240                 if (err)
1241                         goto out;
1242                 if (state->end <= end) {
1243                         set_state_bits(tree, state, &bits, NULL);
1244                         cache_state(state, cached_state);
1245                         state = clear_state_bit(tree, state, &clear_bits, 0,
1246                                                 NULL);
1247                         if (last_end == (u64)-1)
1248                                 goto out;
1249                         start = last_end + 1;
1250                         if (start < end && state && state->start == start &&
1251                             !need_resched())
1252                                 goto hit_next;
1253                 }
1254                 goto search_again;
1255         }
1256         /*
1257          * | ---- desired range ---- |
1258          *     | state | or               | state |
1259          *
1260          * There's a hole, we need to insert something in it and
1261          * ignore the extent we found.
1262          */
1263         if (state->start > start) {
1264                 u64 this_end;
1265                 if (end < last_start)
1266                         this_end = end;
1267                 else
1268                         this_end = last_start - 1;
1269
1270                 prealloc = alloc_extent_state_atomic(prealloc);
1271                 if (!prealloc) {
1272                         err = -ENOMEM;
1273                         goto out;
1274                 }
1275
1276                 /*
1277                  * Avoid to free 'prealloc' if it can be merged with
1278                  * the later extent.
1279                  */
1280                 err = insert_state(tree, prealloc, start, this_end,
1281                                    NULL, NULL, &bits, NULL);
1282                 if (err)
1283                         extent_io_tree_panic(tree, err);
1284                 cache_state(prealloc, cached_state);
1285                 prealloc = NULL;
1286                 start = this_end + 1;
1287                 goto search_again;
1288         }
1289         /*
1290          * | ---- desired range ---- |
1291          *                        | state |
1292          * We need to split the extent, and set the bit
1293          * on the first half
1294          */
1295         if (state->start <= end && state->end > end) {
1296                 prealloc = alloc_extent_state_atomic(prealloc);
1297                 if (!prealloc) {
1298                         err = -ENOMEM;
1299                         goto out;
1300                 }
1301
1302                 err = split_state(tree, state, prealloc, end + 1);
1303                 if (err)
1304                         extent_io_tree_panic(tree, err);
1305
1306                 set_state_bits(tree, prealloc, &bits, NULL);
1307                 cache_state(prealloc, cached_state);
1308                 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1309                 prealloc = NULL;
1310                 goto out;
1311         }
1312
1313 search_again:
1314         if (start > end)
1315                 goto out;
1316         spin_unlock(&tree->lock);
1317         cond_resched();
1318         first_iteration = false;
1319         goto again;
1320
1321 out:
1322         spin_unlock(&tree->lock);
1323         if (prealloc)
1324                 free_extent_state(prealloc);
1325
1326         return err;
1327 }
1328
1329 /* wrappers around set/clear extent bit */
1330 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1331                            unsigned bits, struct extent_changeset *changeset)
1332 {
1333         /*
1334          * We don't support EXTENT_LOCKED yet, as current changeset will
1335          * record any bits changed, so for EXTENT_LOCKED case, it will
1336          * either fail with -EEXIST or changeset will record the whole
1337          * range.
1338          */
1339         BUG_ON(bits & EXTENT_LOCKED);
1340
1341         return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1342                                 changeset);
1343 }
1344
1345 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1346                      unsigned bits, int wake, int delete,
1347                      struct extent_state **cached)
1348 {
1349         return __clear_extent_bit(tree, start, end, bits, wake, delete,
1350                                   cached, GFP_NOFS, NULL);
1351 }
1352
1353 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1354                 unsigned bits, struct extent_changeset *changeset)
1355 {
1356         /*
1357          * Don't support EXTENT_LOCKED case, same reason as
1358          * set_record_extent_bits().
1359          */
1360         BUG_ON(bits & EXTENT_LOCKED);
1361
1362         return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1363                                   changeset);
1364 }
1365
1366 /*
1367  * either insert or lock state struct between start and end use mask to tell
1368  * us if waiting is desired.
1369  */
1370 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1371                      struct extent_state **cached_state)
1372 {
1373         int err;
1374         u64 failed_start;
1375
1376         while (1) {
1377                 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1378                                        EXTENT_LOCKED, &failed_start,
1379                                        cached_state, GFP_NOFS, NULL);
1380                 if (err == -EEXIST) {
1381                         wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1382                         start = failed_start;
1383                 } else
1384                         break;
1385                 WARN_ON(start > end);
1386         }
1387         return err;
1388 }
1389
1390 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1391 {
1392         int err;
1393         u64 failed_start;
1394
1395         err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1396                                &failed_start, NULL, GFP_NOFS, NULL);
1397         if (err == -EEXIST) {
1398                 if (failed_start > start)
1399                         clear_extent_bit(tree, start, failed_start - 1,
1400                                          EXTENT_LOCKED, 1, 0, NULL);
1401                 return 0;
1402         }
1403         return 1;
1404 }
1405
1406 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1407 {
1408         unsigned long index = start >> PAGE_SHIFT;
1409         unsigned long end_index = end >> PAGE_SHIFT;
1410         struct page *page;
1411
1412         while (index <= end_index) {
1413                 page = find_get_page(inode->i_mapping, index);
1414                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1415                 clear_page_dirty_for_io(page);
1416                 put_page(page);
1417                 index++;
1418         }
1419 }
1420
1421 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1422 {
1423         unsigned long index = start >> PAGE_SHIFT;
1424         unsigned long end_index = end >> PAGE_SHIFT;
1425         struct page *page;
1426
1427         while (index <= end_index) {
1428                 page = find_get_page(inode->i_mapping, index);
1429                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1430                 __set_page_dirty_nobuffers(page);
1431                 account_page_redirty(page);
1432                 put_page(page);
1433                 index++;
1434         }
1435 }
1436
1437 /* find the first state struct with 'bits' set after 'start', and
1438  * return it.  tree->lock must be held.  NULL will returned if
1439  * nothing was found after 'start'
1440  */
1441 static struct extent_state *
1442 find_first_extent_bit_state(struct extent_io_tree *tree,
1443                             u64 start, unsigned bits)
1444 {
1445         struct rb_node *node;
1446         struct extent_state *state;
1447
1448         /*
1449          * this search will find all the extents that end after
1450          * our range starts.
1451          */
1452         node = tree_search(tree, start);
1453         if (!node)
1454                 goto out;
1455
1456         while (1) {
1457                 state = rb_entry(node, struct extent_state, rb_node);
1458                 if (state->end >= start && (state->state & bits))
1459                         return state;
1460
1461                 node = rb_next(node);
1462                 if (!node)
1463                         break;
1464         }
1465 out:
1466         return NULL;
1467 }
1468
1469 /*
1470  * find the first offset in the io tree with 'bits' set. zero is
1471  * returned if we find something, and *start_ret and *end_ret are
1472  * set to reflect the state struct that was found.
1473  *
1474  * If nothing was found, 1 is returned. If found something, return 0.
1475  */
1476 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1477                           u64 *start_ret, u64 *end_ret, unsigned bits,
1478                           struct extent_state **cached_state)
1479 {
1480         struct extent_state *state;
1481         struct rb_node *n;
1482         int ret = 1;
1483
1484         spin_lock(&tree->lock);
1485         if (cached_state && *cached_state) {
1486                 state = *cached_state;
1487                 if (state->end == start - 1 && extent_state_in_tree(state)) {
1488                         n = rb_next(&state->rb_node);
1489                         while (n) {
1490                                 state = rb_entry(n, struct extent_state,
1491                                                  rb_node);
1492                                 if (state->state & bits)
1493                                         goto got_it;
1494                                 n = rb_next(n);
1495                         }
1496                         free_extent_state(*cached_state);
1497                         *cached_state = NULL;
1498                         goto out;
1499                 }
1500                 free_extent_state(*cached_state);
1501                 *cached_state = NULL;
1502         }
1503
1504         state = find_first_extent_bit_state(tree, start, bits);
1505 got_it:
1506         if (state) {
1507                 cache_state_if_flags(state, cached_state, 0);
1508                 *start_ret = state->start;
1509                 *end_ret = state->end;
1510                 ret = 0;
1511         }
1512 out:
1513         spin_unlock(&tree->lock);
1514         return ret;
1515 }
1516
1517 /*
1518  * find a contiguous range of bytes in the file marked as delalloc, not
1519  * more than 'max_bytes'.  start and end are used to return the range,
1520  *
1521  * 1 is returned if we find something, 0 if nothing was in the tree
1522  */
1523 static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
1524                                         u64 *start, u64 *end, u64 max_bytes,
1525                                         struct extent_state **cached_state)
1526 {
1527         struct rb_node *node;
1528         struct extent_state *state;
1529         u64 cur_start = *start;
1530         u64 found = 0;
1531         u64 total_bytes = 0;
1532
1533         spin_lock(&tree->lock);
1534
1535         /*
1536          * this search will find all the extents that end after
1537          * our range starts.
1538          */
1539         node = tree_search(tree, cur_start);
1540         if (!node) {
1541                 if (!found)
1542                         *end = (u64)-1;
1543                 goto out;
1544         }
1545
1546         while (1) {
1547                 state = rb_entry(node, struct extent_state, rb_node);
1548                 if (found && (state->start != cur_start ||
1549                               (state->state & EXTENT_BOUNDARY))) {
1550                         goto out;
1551                 }
1552                 if (!(state->state & EXTENT_DELALLOC)) {
1553                         if (!found)
1554                                 *end = state->end;
1555                         goto out;
1556                 }
1557                 if (!found) {
1558                         *start = state->start;
1559                         *cached_state = state;
1560                         refcount_inc(&state->refs);
1561                 }
1562                 found++;
1563                 *end = state->end;
1564                 cur_start = state->end + 1;
1565                 node = rb_next(node);
1566                 total_bytes += state->end - state->start + 1;
1567                 if (total_bytes >= max_bytes)
1568                         break;
1569                 if (!node)
1570                         break;
1571         }
1572 out:
1573         spin_unlock(&tree->lock);
1574         return found;
1575 }
1576
1577 static int __process_pages_contig(struct address_space *mapping,
1578                                   struct page *locked_page,
1579                                   pgoff_t start_index, pgoff_t end_index,
1580                                   unsigned long page_ops, pgoff_t *index_ret);
1581
1582 static noinline void __unlock_for_delalloc(struct inode *inode,
1583                                            struct page *locked_page,
1584                                            u64 start, u64 end)
1585 {
1586         unsigned long index = start >> PAGE_SHIFT;
1587         unsigned long end_index = end >> PAGE_SHIFT;
1588
1589         ASSERT(locked_page);
1590         if (index == locked_page->index && end_index == index)
1591                 return;
1592
1593         __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1594                                PAGE_UNLOCK, NULL);
1595 }
1596
1597 static noinline int lock_delalloc_pages(struct inode *inode,
1598                                         struct page *locked_page,
1599                                         u64 delalloc_start,
1600                                         u64 delalloc_end)
1601 {
1602         unsigned long index = delalloc_start >> PAGE_SHIFT;
1603         unsigned long index_ret = index;
1604         unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1605         int ret;
1606
1607         ASSERT(locked_page);
1608         if (index == locked_page->index && index == end_index)
1609                 return 0;
1610
1611         ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1612                                      end_index, PAGE_LOCK, &index_ret);
1613         if (ret == -EAGAIN)
1614                 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1615                                       (u64)index_ret << PAGE_SHIFT);
1616         return ret;
1617 }
1618
1619 /*
1620  * find a contiguous range of bytes in the file marked as delalloc, not
1621  * more than 'max_bytes'.  start and end are used to return the range,
1622  *
1623  * 1 is returned if we find something, 0 if nothing was in the tree
1624  */
1625 STATIC u64 find_lock_delalloc_range(struct inode *inode,
1626                                     struct extent_io_tree *tree,
1627                                     struct page *locked_page, u64 *start,
1628                                     u64 *end, u64 max_bytes)
1629 {
1630         u64 delalloc_start;
1631         u64 delalloc_end;
1632         u64 found;
1633         struct extent_state *cached_state = NULL;
1634         int ret;
1635         int loops = 0;
1636
1637 again:
1638         /* step one, find a bunch of delalloc bytes starting at start */
1639         delalloc_start = *start;
1640         delalloc_end = 0;
1641         found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1642                                     max_bytes, &cached_state);
1643         if (!found || delalloc_end <= *start) {
1644                 *start = delalloc_start;
1645                 *end = delalloc_end;
1646                 free_extent_state(cached_state);
1647                 return 0;
1648         }
1649
1650         /*
1651          * start comes from the offset of locked_page.  We have to lock
1652          * pages in order, so we can't process delalloc bytes before
1653          * locked_page
1654          */
1655         if (delalloc_start < *start)
1656                 delalloc_start = *start;
1657
1658         /*
1659          * make sure to limit the number of pages we try to lock down
1660          */
1661         if (delalloc_end + 1 - delalloc_start > max_bytes)
1662                 delalloc_end = delalloc_start + max_bytes - 1;
1663
1664         /* step two, lock all the pages after the page that has start */
1665         ret = lock_delalloc_pages(inode, locked_page,
1666                                   delalloc_start, delalloc_end);
1667         if (ret == -EAGAIN) {
1668                 /* some of the pages are gone, lets avoid looping by
1669                  * shortening the size of the delalloc range we're searching
1670                  */
1671                 free_extent_state(cached_state);
1672                 cached_state = NULL;
1673                 if (!loops) {
1674                         max_bytes = PAGE_SIZE;
1675                         loops = 1;
1676                         goto again;
1677                 } else {
1678                         found = 0;
1679                         goto out_failed;
1680                 }
1681         }
1682         BUG_ON(ret); /* Only valid values are 0 and -EAGAIN */
1683
1684         /* step three, lock the state bits for the whole range */
1685         lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1686
1687         /* then test to make sure it is all still delalloc */
1688         ret = test_range_bit(tree, delalloc_start, delalloc_end,
1689                              EXTENT_DELALLOC, 1, cached_state);
1690         if (!ret) {
1691                 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1692                                      &cached_state);
1693                 __unlock_for_delalloc(inode, locked_page,
1694                               delalloc_start, delalloc_end);
1695                 cond_resched();
1696                 goto again;
1697         }
1698         free_extent_state(cached_state);
1699         *start = delalloc_start;
1700         *end = delalloc_end;
1701 out_failed:
1702         return found;
1703 }
1704
1705 static int __process_pages_contig(struct address_space *mapping,
1706                                   struct page *locked_page,
1707                                   pgoff_t start_index, pgoff_t end_index,
1708                                   unsigned long page_ops, pgoff_t *index_ret)
1709 {
1710         unsigned long nr_pages = end_index - start_index + 1;
1711         unsigned long pages_locked = 0;
1712         pgoff_t index = start_index;
1713         struct page *pages[16];
1714         unsigned ret;
1715         int err = 0;
1716         int i;
1717
1718         if (page_ops & PAGE_LOCK) {
1719                 ASSERT(page_ops == PAGE_LOCK);
1720                 ASSERT(index_ret && *index_ret == start_index);
1721         }
1722
1723         if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1724                 mapping_set_error(mapping, -EIO);
1725
1726         while (nr_pages > 0) {
1727                 ret = find_get_pages_contig(mapping, index,
1728                                      min_t(unsigned long,
1729                                      nr_pages, ARRAY_SIZE(pages)), pages);
1730                 if (ret == 0) {
1731                         /*
1732                          * Only if we're going to lock these pages,
1733                          * can we find nothing at @index.
1734                          */
1735                         ASSERT(page_ops & PAGE_LOCK);
1736                         err = -EAGAIN;
1737                         goto out;
1738                 }
1739
1740                 for (i = 0; i < ret; i++) {
1741                         if (page_ops & PAGE_SET_PRIVATE2)
1742                                 SetPagePrivate2(pages[i]);
1743
1744                         if (pages[i] == locked_page) {
1745                                 put_page(pages[i]);
1746                                 pages_locked++;
1747                                 continue;
1748                         }
1749                         if (page_ops & PAGE_CLEAR_DIRTY)
1750                                 clear_page_dirty_for_io(pages[i]);
1751                         if (page_ops & PAGE_SET_WRITEBACK)
1752                                 set_page_writeback(pages[i]);
1753                         if (page_ops & PAGE_SET_ERROR)
1754                                 SetPageError(pages[i]);
1755                         if (page_ops & PAGE_END_WRITEBACK)
1756                                 end_page_writeback(pages[i]);
1757                         if (page_ops & PAGE_UNLOCK)
1758                                 unlock_page(pages[i]);
1759                         if (page_ops & PAGE_LOCK) {
1760                                 lock_page(pages[i]);
1761                                 if (!PageDirty(pages[i]) ||
1762                                     pages[i]->mapping != mapping) {
1763                                         unlock_page(pages[i]);
1764                                         for (; i < ret; i++)
1765                                                 put_page(pages[i]);
1766                                         err = -EAGAIN;
1767                                         goto out;
1768                                 }
1769                         }
1770                         put_page(pages[i]);
1771                         pages_locked++;
1772                 }
1773                 nr_pages -= ret;
1774                 index += ret;
1775                 cond_resched();
1776         }
1777 out:
1778         if (err && index_ret)
1779                 *index_ret = start_index + pages_locked - 1;
1780         return err;
1781 }
1782
1783 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1784                                  u64 delalloc_end, struct page *locked_page,
1785                                  unsigned clear_bits,
1786                                  unsigned long page_ops)
1787 {
1788         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1789                          NULL);
1790
1791         __process_pages_contig(inode->i_mapping, locked_page,
1792                                start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1793                                page_ops, NULL);
1794 }
1795
1796 /*
1797  * count the number of bytes in the tree that have a given bit(s)
1798  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
1799  * cached.  The total number found is returned.
1800  */
1801 u64 count_range_bits(struct extent_io_tree *tree,
1802                      u64 *start, u64 search_end, u64 max_bytes,
1803                      unsigned bits, int contig)
1804 {
1805         struct rb_node *node;
1806         struct extent_state *state;
1807         u64 cur_start = *start;
1808         u64 total_bytes = 0;
1809         u64 last = 0;
1810         int found = 0;
1811
1812         if (WARN_ON(search_end <= cur_start))
1813                 return 0;
1814
1815         spin_lock(&tree->lock);
1816         if (cur_start == 0 && bits == EXTENT_DIRTY) {
1817                 total_bytes = tree->dirty_bytes;
1818                 goto out;
1819         }
1820         /*
1821          * this search will find all the extents that end after
1822          * our range starts.
1823          */
1824         node = tree_search(tree, cur_start);
1825         if (!node)
1826                 goto out;
1827
1828         while (1) {
1829                 state = rb_entry(node, struct extent_state, rb_node);
1830                 if (state->start > search_end)
1831                         break;
1832                 if (contig && found && state->start > last + 1)
1833                         break;
1834                 if (state->end >= cur_start && (state->state & bits) == bits) {
1835                         total_bytes += min(search_end, state->end) + 1 -
1836                                        max(cur_start, state->start);
1837                         if (total_bytes >= max_bytes)
1838                                 break;
1839                         if (!found) {
1840                                 *start = max(cur_start, state->start);
1841                                 found = 1;
1842                         }
1843                         last = state->end;
1844                 } else if (contig && found) {
1845                         break;
1846                 }
1847                 node = rb_next(node);
1848                 if (!node)
1849                         break;
1850         }
1851 out:
1852         spin_unlock(&tree->lock);
1853         return total_bytes;
1854 }
1855
1856 /*
1857  * set the private field for a given byte offset in the tree.  If there isn't
1858  * an extent_state there already, this does nothing.
1859  */
1860 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
1861                 struct io_failure_record *failrec)
1862 {
1863         struct rb_node *node;
1864         struct extent_state *state;
1865         int ret = 0;
1866
1867         spin_lock(&tree->lock);
1868         /*
1869          * this search will find all the extents that end after
1870          * our range starts.
1871          */
1872         node = tree_search(tree, start);
1873         if (!node) {
1874                 ret = -ENOENT;
1875                 goto out;
1876         }
1877         state = rb_entry(node, struct extent_state, rb_node);
1878         if (state->start != start) {
1879                 ret = -ENOENT;
1880                 goto out;
1881         }
1882         state->failrec = failrec;
1883 out:
1884         spin_unlock(&tree->lock);
1885         return ret;
1886 }
1887
1888 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
1889                 struct io_failure_record **failrec)
1890 {
1891         struct rb_node *node;
1892         struct extent_state *state;
1893         int ret = 0;
1894
1895         spin_lock(&tree->lock);
1896         /*
1897          * this search will find all the extents that end after
1898          * our range starts.
1899          */
1900         node = tree_search(tree, start);
1901         if (!node) {
1902                 ret = -ENOENT;
1903                 goto out;
1904         }
1905         state = rb_entry(node, struct extent_state, rb_node);
1906         if (state->start != start) {
1907                 ret = -ENOENT;
1908                 goto out;
1909         }
1910         *failrec = state->failrec;
1911 out:
1912         spin_unlock(&tree->lock);
1913         return ret;
1914 }
1915
1916 /*
1917  * searches a range in the state tree for a given mask.
1918  * If 'filled' == 1, this returns 1 only if every extent in the tree
1919  * has the bits set.  Otherwise, 1 is returned if any bit in the
1920  * range is found set.
1921  */
1922 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1923                    unsigned bits, int filled, struct extent_state *cached)
1924 {
1925         struct extent_state *state = NULL;
1926         struct rb_node *node;
1927         int bitset = 0;
1928
1929         spin_lock(&tree->lock);
1930         if (cached && extent_state_in_tree(cached) && cached->start <= start &&
1931             cached->end > start)
1932                 node = &cached->rb_node;
1933         else
1934                 node = tree_search(tree, start);
1935         while (node && start <= end) {
1936                 state = rb_entry(node, struct extent_state, rb_node);
1937
1938                 if (filled && state->start > start) {
1939                         bitset = 0;
1940                         break;
1941                 }
1942
1943                 if (state->start > end)
1944                         break;
1945
1946                 if (state->state & bits) {
1947                         bitset = 1;
1948                         if (!filled)
1949                                 break;
1950                 } else if (filled) {
1951                         bitset = 0;
1952                         break;
1953                 }
1954
1955                 if (state->end == (u64)-1)
1956                         break;
1957
1958                 start = state->end + 1;
1959                 if (start > end)
1960                         break;
1961                 node = rb_next(node);
1962                 if (!node) {
1963                         if (filled)
1964                                 bitset = 0;
1965                         break;
1966                 }
1967         }
1968         spin_unlock(&tree->lock);
1969         return bitset;
1970 }
1971
1972 /*
1973  * helper function to set a given page up to date if all the
1974  * extents in the tree for that page are up to date
1975  */
1976 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1977 {
1978         u64 start = page_offset(page);
1979         u64 end = start + PAGE_SIZE - 1;
1980         if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1981                 SetPageUptodate(page);
1982 }
1983
1984 int free_io_failure(struct extent_io_tree *failure_tree,
1985                     struct extent_io_tree *io_tree,
1986                     struct io_failure_record *rec)
1987 {
1988         int ret;
1989         int err = 0;
1990
1991         set_state_failrec(failure_tree, rec->start, NULL);
1992         ret = clear_extent_bits(failure_tree, rec->start,
1993                                 rec->start + rec->len - 1,
1994                                 EXTENT_LOCKED | EXTENT_DIRTY);
1995         if (ret)
1996                 err = ret;
1997
1998         ret = clear_extent_bits(io_tree, rec->start,
1999                                 rec->start + rec->len - 1,
2000                                 EXTENT_DAMAGED);
2001         if (ret && !err)
2002                 err = ret;
2003
2004         kfree(rec);
2005         return err;
2006 }
2007
2008 /*
2009  * this bypasses the standard btrfs submit functions deliberately, as
2010  * the standard behavior is to write all copies in a raid setup. here we only
2011  * want to write the one bad copy. so we do the mapping for ourselves and issue
2012  * submit_bio directly.
2013  * to avoid any synchronization issues, wait for the data after writing, which
2014  * actually prevents the read that triggered the error from finishing.
2015  * currently, there can be no more than two copies of every data bit. thus,
2016  * exactly one rewrite is required.
2017  */
2018 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2019                       u64 length, u64 logical, struct page *page,
2020                       unsigned int pg_offset, int mirror_num)
2021 {
2022         struct bio *bio;
2023         struct btrfs_device *dev;
2024         u64 map_length = 0;
2025         u64 sector;
2026         struct btrfs_bio *bbio = NULL;
2027         int ret;
2028
2029         ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2030         BUG_ON(!mirror_num);
2031
2032         bio = btrfs_io_bio_alloc(1);
2033         bio->bi_iter.bi_size = 0;
2034         map_length = length;
2035
2036         /*
2037          * Avoid races with device replace and make sure our bbio has devices
2038          * associated to its stripes that don't go away while we are doing the
2039          * read repair operation.
2040          */
2041         btrfs_bio_counter_inc_blocked(fs_info);
2042         if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2043                 /*
2044                  * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2045                  * to update all raid stripes, but here we just want to correct
2046                  * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2047                  * stripe's dev and sector.
2048                  */
2049                 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2050                                       &map_length, &bbio, 0);
2051                 if (ret) {
2052                         btrfs_bio_counter_dec(fs_info);
2053                         bio_put(bio);
2054                         return -EIO;
2055                 }
2056                 ASSERT(bbio->mirror_num == 1);
2057         } else {
2058                 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2059                                       &map_length, &bbio, mirror_num);
2060                 if (ret) {
2061                         btrfs_bio_counter_dec(fs_info);
2062                         bio_put(bio);
2063                         return -EIO;
2064                 }
2065                 BUG_ON(mirror_num != bbio->mirror_num);
2066         }
2067
2068         sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2069         bio->bi_iter.bi_sector = sector;
2070         dev = bbio->stripes[bbio->mirror_num - 1].dev;
2071         btrfs_put_bbio(bbio);
2072         if (!dev || !dev->bdev ||
2073             !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2074                 btrfs_bio_counter_dec(fs_info);
2075                 bio_put(bio);
2076                 return -EIO;
2077         }
2078         bio_set_dev(bio, dev->bdev);
2079         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2080         bio_add_page(bio, page, length, pg_offset);
2081
2082         if (btrfsic_submit_bio_wait(bio)) {
2083                 /* try to remap that extent elsewhere? */
2084                 btrfs_bio_counter_dec(fs_info);
2085                 bio_put(bio);
2086                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2087                 return -EIO;
2088         }
2089
2090         btrfs_info_rl_in_rcu(fs_info,
2091                 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2092                                   ino, start,
2093                                   rcu_str_deref(dev->name), sector);
2094         btrfs_bio_counter_dec(fs_info);
2095         bio_put(bio);
2096         return 0;
2097 }
2098
2099 int repair_eb_io_failure(struct btrfs_fs_info *fs_info,
2100                          struct extent_buffer *eb, int mirror_num)
2101 {
2102         u64 start = eb->start;
2103         int i, num_pages = num_extent_pages(eb);
2104         int ret = 0;
2105
2106         if (sb_rdonly(fs_info->sb))
2107                 return -EROFS;
2108
2109         for (i = 0; i < num_pages; i++) {
2110                 struct page *p = eb->pages[i];
2111
2112                 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2113                                         start - page_offset(p), mirror_num);
2114                 if (ret)
2115                         break;
2116                 start += PAGE_SIZE;
2117         }
2118
2119         return ret;
2120 }
2121
2122 /*
2123  * each time an IO finishes, we do a fast check in the IO failure tree
2124  * to see if we need to process or clean up an io_failure_record
2125  */
2126 int clean_io_failure(struct btrfs_fs_info *fs_info,
2127                      struct extent_io_tree *failure_tree,
2128                      struct extent_io_tree *io_tree, u64 start,
2129                      struct page *page, u64 ino, unsigned int pg_offset)
2130 {
2131         u64 private;
2132         struct io_failure_record *failrec;
2133         struct extent_state *state;
2134         int num_copies;
2135         int ret;
2136
2137         private = 0;
2138         ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2139                                EXTENT_DIRTY, 0);
2140         if (!ret)
2141                 return 0;
2142
2143         ret = get_state_failrec(failure_tree, start, &failrec);
2144         if (ret)
2145                 return 0;
2146
2147         BUG_ON(!failrec->this_mirror);
2148
2149         if (failrec->in_validation) {
2150                 /* there was no real error, just free the record */
2151                 btrfs_debug(fs_info,
2152                         "clean_io_failure: freeing dummy error at %llu",
2153                         failrec->start);
2154                 goto out;
2155         }
2156         if (sb_rdonly(fs_info->sb))
2157                 goto out;
2158
2159         spin_lock(&io_tree->lock);
2160         state = find_first_extent_bit_state(io_tree,
2161                                             failrec->start,
2162                                             EXTENT_LOCKED);
2163         spin_unlock(&io_tree->lock);
2164
2165         if (state && state->start <= failrec->start &&
2166             state->end >= failrec->start + failrec->len - 1) {
2167                 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2168                                               failrec->len);
2169                 if (num_copies > 1)  {
2170                         repair_io_failure(fs_info, ino, start, failrec->len,
2171                                           failrec->logical, page, pg_offset,
2172                                           failrec->failed_mirror);
2173                 }
2174         }
2175
2176 out:
2177         free_io_failure(failure_tree, io_tree, failrec);
2178
2179         return 0;
2180 }
2181
2182 /*
2183  * Can be called when
2184  * - hold extent lock
2185  * - under ordered extent
2186  * - the inode is freeing
2187  */
2188 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2189 {
2190         struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2191         struct io_failure_record *failrec;
2192         struct extent_state *state, *next;
2193
2194         if (RB_EMPTY_ROOT(&failure_tree->state))
2195                 return;
2196
2197         spin_lock(&failure_tree->lock);
2198         state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2199         while (state) {
2200                 if (state->start > end)
2201                         break;
2202
2203                 ASSERT(state->end <= end);
2204
2205                 next = next_state(state);
2206
2207                 failrec = state->failrec;
2208                 free_extent_state(state);
2209                 kfree(failrec);
2210
2211                 state = next;
2212         }
2213         spin_unlock(&failure_tree->lock);
2214 }
2215
2216 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2217                 struct io_failure_record **failrec_ret)
2218 {
2219         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2220         struct io_failure_record *failrec;
2221         struct extent_map *em;
2222         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2223         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2224         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2225         int ret;
2226         u64 logical;
2227
2228         ret = get_state_failrec(failure_tree, start, &failrec);
2229         if (ret) {
2230                 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2231                 if (!failrec)
2232                         return -ENOMEM;
2233
2234                 failrec->start = start;
2235                 failrec->len = end - start + 1;
2236                 failrec->this_mirror = 0;
2237                 failrec->bio_flags = 0;
2238                 failrec->in_validation = 0;
2239
2240                 read_lock(&em_tree->lock);
2241                 em = lookup_extent_mapping(em_tree, start, failrec->len);
2242                 if (!em) {
2243                         read_unlock(&em_tree->lock);
2244                         kfree(failrec);
2245                         return -EIO;
2246                 }
2247
2248                 if (em->start > start || em->start + em->len <= start) {
2249                         free_extent_map(em);
2250                         em = NULL;
2251                 }
2252                 read_unlock(&em_tree->lock);
2253                 if (!em) {
2254                         kfree(failrec);
2255                         return -EIO;
2256                 }
2257
2258                 logical = start - em->start;
2259                 logical = em->block_start + logical;
2260                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2261                         logical = em->block_start;
2262                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2263                         extent_set_compress_type(&failrec->bio_flags,
2264                                                  em->compress_type);
2265                 }
2266
2267                 btrfs_debug(fs_info,
2268                         "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2269                         logical, start, failrec->len);
2270
2271                 failrec->logical = logical;
2272                 free_extent_map(em);
2273
2274                 /* set the bits in the private failure tree */
2275                 ret = set_extent_bits(failure_tree, start, end,
2276                                         EXTENT_LOCKED | EXTENT_DIRTY);
2277                 if (ret >= 0)
2278                         ret = set_state_failrec(failure_tree, start, failrec);
2279                 /* set the bits in the inode's tree */
2280                 if (ret >= 0)
2281                         ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2282                 if (ret < 0) {
2283                         kfree(failrec);
2284                         return ret;
2285                 }
2286         } else {
2287                 btrfs_debug(fs_info,
2288                         "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2289                         failrec->logical, failrec->start, failrec->len,
2290                         failrec->in_validation);
2291                 /*
2292                  * when data can be on disk more than twice, add to failrec here
2293                  * (e.g. with a list for failed_mirror) to make
2294                  * clean_io_failure() clean all those errors at once.
2295                  */
2296         }
2297
2298         *failrec_ret = failrec;
2299
2300         return 0;
2301 }
2302
2303 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2304                            struct io_failure_record *failrec, int failed_mirror)
2305 {
2306         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2307         int num_copies;
2308
2309         num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2310         if (num_copies == 1) {
2311                 /*
2312                  * we only have a single copy of the data, so don't bother with
2313                  * all the retry and error correction code that follows. no
2314                  * matter what the error is, it is very likely to persist.
2315                  */
2316                 btrfs_debug(fs_info,
2317                         "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2318                         num_copies, failrec->this_mirror, failed_mirror);
2319                 return false;
2320         }
2321
2322         /*
2323          * there are two premises:
2324          *      a) deliver good data to the caller
2325          *      b) correct the bad sectors on disk
2326          */
2327         if (failed_bio_pages > 1) {
2328                 /*
2329                  * to fulfill b), we need to know the exact failing sectors, as
2330                  * we don't want to rewrite any more than the failed ones. thus,
2331                  * we need separate read requests for the failed bio
2332                  *
2333                  * if the following BUG_ON triggers, our validation request got
2334                  * merged. we need separate requests for our algorithm to work.
2335                  */
2336                 BUG_ON(failrec->in_validation);
2337                 failrec->in_validation = 1;
2338                 failrec->this_mirror = failed_mirror;
2339         } else {
2340                 /*
2341                  * we're ready to fulfill a) and b) alongside. get a good copy
2342                  * of the failed sector and if we succeed, we have setup
2343                  * everything for repair_io_failure to do the rest for us.
2344                  */
2345                 if (failrec->in_validation) {
2346                         BUG_ON(failrec->this_mirror != failed_mirror);
2347                         failrec->in_validation = 0;
2348                         failrec->this_mirror = 0;
2349                 }
2350                 failrec->failed_mirror = failed_mirror;
2351                 failrec->this_mirror++;
2352                 if (failrec->this_mirror == failed_mirror)
2353                         failrec->this_mirror++;
2354         }
2355
2356         if (failrec->this_mirror > num_copies) {
2357                 btrfs_debug(fs_info,
2358                         "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2359                         num_copies, failrec->this_mirror, failed_mirror);
2360                 return false;
2361         }
2362
2363         return true;
2364 }
2365
2366
2367 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2368                                     struct io_failure_record *failrec,
2369                                     struct page *page, int pg_offset, int icsum,
2370                                     bio_end_io_t *endio_func, void *data)
2371 {
2372         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2373         struct bio *bio;
2374         struct btrfs_io_bio *btrfs_failed_bio;
2375         struct btrfs_io_bio *btrfs_bio;
2376
2377         bio = btrfs_io_bio_alloc(1);
2378         bio->bi_end_io = endio_func;
2379         bio->bi_iter.bi_sector = failrec->logical >> 9;
2380         bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2381         bio->bi_iter.bi_size = 0;
2382         bio->bi_private = data;
2383
2384         btrfs_failed_bio = btrfs_io_bio(failed_bio);
2385         if (btrfs_failed_bio->csum) {
2386                 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2387
2388                 btrfs_bio = btrfs_io_bio(bio);
2389                 btrfs_bio->csum = btrfs_bio->csum_inline;
2390                 icsum *= csum_size;
2391                 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2392                        csum_size);
2393         }
2394
2395         bio_add_page(bio, page, failrec->len, pg_offset);
2396
2397         return bio;
2398 }
2399
2400 /*
2401  * this is a generic handler for readpage errors (default
2402  * readpage_io_failed_hook). if other copies exist, read those and write back
2403  * good data to the failed position. does not investigate in remapping the
2404  * failed extent elsewhere, hoping the device will be smart enough to do this as
2405  * needed
2406  */
2407
2408 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2409                               struct page *page, u64 start, u64 end,
2410                               int failed_mirror)
2411 {
2412         struct io_failure_record *failrec;
2413         struct inode *inode = page->mapping->host;
2414         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2415         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2416         struct bio *bio;
2417         int read_mode = 0;
2418         blk_status_t status;
2419         int ret;
2420         unsigned failed_bio_pages = bio_pages_all(failed_bio);
2421
2422         BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2423
2424         ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2425         if (ret)
2426                 return ret;
2427
2428         if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2429                                     failed_mirror)) {
2430                 free_io_failure(failure_tree, tree, failrec);
2431                 return -EIO;
2432         }
2433
2434         if (failed_bio_pages > 1)
2435                 read_mode |= REQ_FAILFAST_DEV;
2436
2437         phy_offset >>= inode->i_sb->s_blocksize_bits;
2438         bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2439                                       start - page_offset(page),
2440                                       (int)phy_offset, failed_bio->bi_end_io,
2441                                       NULL);
2442         bio->bi_opf = REQ_OP_READ | read_mode;
2443
2444         btrfs_debug(btrfs_sb(inode->i_sb),
2445                 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2446                 read_mode, failrec->this_mirror, failrec->in_validation);
2447
2448         status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2449                                          failrec->bio_flags, 0);
2450         if (status) {
2451                 free_io_failure(failure_tree, tree, failrec);
2452                 bio_put(bio);
2453                 ret = blk_status_to_errno(status);
2454         }
2455
2456         return ret;
2457 }
2458
2459 /* lots and lots of room for performance fixes in the end_bio funcs */
2460
2461 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2462 {
2463         int uptodate = (err == 0);
2464         struct extent_io_tree *tree;
2465         int ret = 0;
2466
2467         tree = &BTRFS_I(page->mapping->host)->io_tree;
2468
2469         if (tree->ops && tree->ops->writepage_end_io_hook)
2470                 tree->ops->writepage_end_io_hook(page, start, end, NULL,
2471                                 uptodate);
2472
2473         if (!uptodate) {
2474                 ClearPageUptodate(page);
2475                 SetPageError(page);
2476                 ret = err < 0 ? err : -EIO;
2477                 mapping_set_error(page->mapping, ret);
2478         }
2479 }
2480
2481 /*
2482  * after a writepage IO is done, we need to:
2483  * clear the uptodate bits on error
2484  * clear the writeback bits in the extent tree for this IO
2485  * end_page_writeback if the page has no more pending IO
2486  *
2487  * Scheduling is not allowed, so the extent state tree is expected
2488  * to have one and only one object corresponding to this IO.
2489  */
2490 static void end_bio_extent_writepage(struct bio *bio)
2491 {
2492         int error = blk_status_to_errno(bio->bi_status);
2493         struct bio_vec *bvec;
2494         u64 start;
2495         u64 end;
2496         int i;
2497
2498         ASSERT(!bio_flagged(bio, BIO_CLONED));
2499         bio_for_each_segment_all(bvec, bio, i) {
2500                 struct page *page = bvec->bv_page;
2501                 struct inode *inode = page->mapping->host;
2502                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2503
2504                 /* We always issue full-page reads, but if some block
2505                  * in a page fails to read, blk_update_request() will
2506                  * advance bv_offset and adjust bv_len to compensate.
2507                  * Print a warning for nonzero offsets, and an error
2508                  * if they don't add up to a full page.  */
2509                 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2510                         if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2511                                 btrfs_err(fs_info,
2512                                    "partial page write in btrfs with offset %u and length %u",
2513                                         bvec->bv_offset, bvec->bv_len);
2514                         else
2515                                 btrfs_info(fs_info,
2516                                    "incomplete page write in btrfs with offset %u and length %u",
2517                                         bvec->bv_offset, bvec->bv_len);
2518                 }
2519
2520                 start = page_offset(page);
2521                 end = start + bvec->bv_offset + bvec->bv_len - 1;
2522
2523                 end_extent_writepage(page, error, start, end);
2524                 end_page_writeback(page);
2525         }
2526
2527         bio_put(bio);
2528 }
2529
2530 static void
2531 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2532                               int uptodate)
2533 {
2534         struct extent_state *cached = NULL;
2535         u64 end = start + len - 1;
2536
2537         if (uptodate && tree->track_uptodate)
2538                 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2539         unlock_extent_cached_atomic(tree, start, end, &cached);
2540 }
2541
2542 /*
2543  * after a readpage IO is done, we need to:
2544  * clear the uptodate bits on error
2545  * set the uptodate bits if things worked
2546  * set the page up to date if all extents in the tree are uptodate
2547  * clear the lock bit in the extent tree
2548  * unlock the page if there are no other extents locked for it
2549  *
2550  * Scheduling is not allowed, so the extent state tree is expected
2551  * to have one and only one object corresponding to this IO.
2552  */
2553 static void end_bio_extent_readpage(struct bio *bio)
2554 {
2555         struct bio_vec *bvec;
2556         int uptodate = !bio->bi_status;
2557         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2558         struct extent_io_tree *tree, *failure_tree;
2559         u64 offset = 0;
2560         u64 start;
2561         u64 end;
2562         u64 len;
2563         u64 extent_start = 0;
2564         u64 extent_len = 0;
2565         int mirror;
2566         int ret;
2567         int i;
2568
2569         ASSERT(!bio_flagged(bio, BIO_CLONED));
2570         bio_for_each_segment_all(bvec, bio, i) {
2571                 struct page *page = bvec->bv_page;
2572                 struct inode *inode = page->mapping->host;
2573                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2574
2575                 btrfs_debug(fs_info,
2576                         "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2577                         (u64)bio->bi_iter.bi_sector, bio->bi_status,
2578                         io_bio->mirror_num);
2579                 tree = &BTRFS_I(inode)->io_tree;
2580                 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2581
2582                 /* We always issue full-page reads, but if some block
2583                  * in a page fails to read, blk_update_request() will
2584                  * advance bv_offset and adjust bv_len to compensate.
2585                  * Print a warning for nonzero offsets, and an error
2586                  * if they don't add up to a full page.  */
2587                 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2588                         if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2589                                 btrfs_err(fs_info,
2590                                         "partial page read in btrfs with offset %u and length %u",
2591                                         bvec->bv_offset, bvec->bv_len);
2592                         else
2593                                 btrfs_info(fs_info,
2594                                         "incomplete page read in btrfs with offset %u and length %u",
2595                                         bvec->bv_offset, bvec->bv_len);
2596                 }
2597
2598                 start = page_offset(page);
2599                 end = start + bvec->bv_offset + bvec->bv_len - 1;
2600                 len = bvec->bv_len;
2601
2602                 mirror = io_bio->mirror_num;
2603                 if (likely(uptodate && tree->ops)) {
2604                         ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2605                                                               page, start, end,
2606                                                               mirror);
2607                         if (ret)
2608                                 uptodate = 0;
2609                         else
2610                                 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2611                                                  failure_tree, tree, start,
2612                                                  page,
2613                                                  btrfs_ino(BTRFS_I(inode)), 0);
2614                 }
2615
2616                 if (likely(uptodate))
2617                         goto readpage_ok;
2618
2619                 if (tree->ops) {
2620                         ret = tree->ops->readpage_io_failed_hook(page, mirror);
2621                         if (ret == -EAGAIN) {
2622                                 /*
2623                                  * Data inode's readpage_io_failed_hook() always
2624                                  * returns -EAGAIN.
2625                                  *
2626                                  * The generic bio_readpage_error handles errors
2627                                  * the following way: If possible, new read
2628                                  * requests are created and submitted and will
2629                                  * end up in end_bio_extent_readpage as well (if
2630                                  * we're lucky, not in the !uptodate case). In
2631                                  * that case it returns 0 and we just go on with
2632                                  * the next page in our bio. If it can't handle
2633                                  * the error it will return -EIO and we remain
2634                                  * responsible for that page.
2635                                  */
2636                                 ret = bio_readpage_error(bio, offset, page,
2637                                                          start, end, mirror);
2638                                 if (ret == 0) {
2639                                         uptodate = !bio->bi_status;
2640                                         offset += len;
2641                                         continue;
2642                                 }
2643                         }
2644
2645                         /*
2646                          * metadata's readpage_io_failed_hook() always returns
2647                          * -EIO and fixes nothing.  -EIO is also returned if
2648                          * data inode error could not be fixed.
2649                          */
2650                         ASSERT(ret == -EIO);
2651                 }
2652 readpage_ok:
2653                 if (likely(uptodate)) {
2654                         loff_t i_size = i_size_read(inode);
2655                         pgoff_t end_index = i_size >> PAGE_SHIFT;
2656                         unsigned off;
2657
2658                         /* Zero out the end if this page straddles i_size */
2659                         off = i_size & (PAGE_SIZE-1);
2660                         if (page->index == end_index && off)
2661                                 zero_user_segment(page, off, PAGE_SIZE);
2662                         SetPageUptodate(page);
2663                 } else {
2664                         ClearPageUptodate(page);
2665                         SetPageError(page);
2666                 }
2667                 unlock_page(page);
2668                 offset += len;
2669
2670                 if (unlikely(!uptodate)) {
2671                         if (extent_len) {
2672                                 endio_readpage_release_extent(tree,
2673                                                               extent_start,
2674                                                               extent_len, 1);
2675                                 extent_start = 0;
2676                                 extent_len = 0;
2677                         }
2678                         endio_readpage_release_extent(tree, start,
2679                                                       end - start + 1, 0);
2680                 } else if (!extent_len) {
2681                         extent_start = start;
2682                         extent_len = end + 1 - start;
2683                 } else if (extent_start + extent_len == start) {
2684                         extent_len += end + 1 - start;
2685                 } else {
2686                         endio_readpage_release_extent(tree, extent_start,
2687                                                       extent_len, uptodate);
2688                         extent_start = start;
2689                         extent_len = end + 1 - start;
2690                 }
2691         }
2692
2693         if (extent_len)
2694                 endio_readpage_release_extent(tree, extent_start, extent_len,
2695                                               uptodate);
2696         if (io_bio->end_io)
2697                 io_bio->end_io(io_bio, blk_status_to_errno(bio->bi_status));
2698         bio_put(bio);
2699 }
2700
2701 /*
2702  * Initialize the members up to but not including 'bio'. Use after allocating a
2703  * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2704  * 'bio' because use of __GFP_ZERO is not supported.
2705  */
2706 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2707 {
2708         memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2709 }
2710
2711 /*
2712  * The following helpers allocate a bio. As it's backed by a bioset, it'll
2713  * never fail.  We're returning a bio right now but you can call btrfs_io_bio
2714  * for the appropriate container_of magic
2715  */
2716 struct bio *btrfs_bio_alloc(struct block_device *bdev, u64 first_byte)
2717 {
2718         struct bio *bio;
2719
2720         bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2721         bio_set_dev(bio, bdev);
2722         bio->bi_iter.bi_sector = first_byte >> 9;
2723         btrfs_io_bio_init(btrfs_io_bio(bio));
2724         return bio;
2725 }
2726
2727 struct bio *btrfs_bio_clone(struct bio *bio)
2728 {
2729         struct btrfs_io_bio *btrfs_bio;
2730         struct bio *new;
2731
2732         /* Bio allocation backed by a bioset does not fail */
2733         new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2734         btrfs_bio = btrfs_io_bio(new);
2735         btrfs_io_bio_init(btrfs_bio);
2736         btrfs_bio->iter = bio->bi_iter;
2737         return new;
2738 }
2739
2740 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2741 {
2742         struct bio *bio;
2743
2744         /* Bio allocation backed by a bioset does not fail */
2745         bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2746         btrfs_io_bio_init(btrfs_io_bio(bio));
2747         return bio;
2748 }
2749
2750 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2751 {
2752         struct bio *bio;
2753         struct btrfs_io_bio *btrfs_bio;
2754
2755         /* this will never fail when it's backed by a bioset */
2756         bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2757         ASSERT(bio);
2758
2759         btrfs_bio = btrfs_io_bio(bio);
2760         btrfs_io_bio_init(btrfs_bio);
2761
2762         bio_trim(bio, offset >> 9, size >> 9);
2763         btrfs_bio->iter = bio->bi_iter;
2764         return bio;
2765 }
2766
2767 /*
2768  * @opf:        bio REQ_OP_* and REQ_* flags as one value
2769  * @tree:       tree so we can call our merge_bio hook
2770  * @wbc:        optional writeback control for io accounting
2771  * @page:       page to add to the bio
2772  * @pg_offset:  offset of the new bio or to check whether we are adding
2773  *              a contiguous page to the previous one
2774  * @size:       portion of page that we want to write
2775  * @offset:     starting offset in the page
2776  * @bdev:       attach newly created bios to this bdev
2777  * @bio_ret:    must be valid pointer, newly allocated bio will be stored there
2778  * @end_io_func:     end_io callback for new bio
2779  * @mirror_num:      desired mirror to read/write
2780  * @prev_bio_flags:  flags of previous bio to see if we can merge the current one
2781  * @bio_flags:  flags of the current bio to see if we can merge them
2782  */
2783 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2784                               struct writeback_control *wbc,
2785                               struct page *page, u64 offset,
2786                               size_t size, unsigned long pg_offset,
2787                               struct block_device *bdev,
2788                               struct bio **bio_ret,
2789                               bio_end_io_t end_io_func,
2790                               int mirror_num,
2791                               unsigned long prev_bio_flags,
2792                               unsigned long bio_flags,
2793                               bool force_bio_submit)
2794 {
2795         int ret = 0;
2796         struct bio *bio;
2797         size_t page_size = min_t(size_t, size, PAGE_SIZE);
2798         sector_t sector = offset >> 9;
2799
2800         ASSERT(bio_ret);
2801
2802         if (*bio_ret) {
2803                 bool contig;
2804                 bool can_merge = true;
2805
2806                 bio = *bio_ret;
2807                 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2808                         contig = bio->bi_iter.bi_sector == sector;
2809                 else
2810                         contig = bio_end_sector(bio) == sector;
2811
2812                 if (tree->ops && btrfs_merge_bio_hook(page, offset, page_size,
2813                                                       bio, bio_flags))
2814                         can_merge = false;
2815
2816                 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2817                     force_bio_submit ||
2818                     bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2819                         ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2820                         if (ret < 0) {
2821                                 *bio_ret = NULL;
2822                                 return ret;
2823                         }
2824                         bio = NULL;
2825                 } else {
2826                         if (wbc)
2827                                 wbc_account_io(wbc, page, page_size);
2828                         return 0;
2829                 }
2830         }
2831
2832         bio = btrfs_bio_alloc(bdev, offset);
2833         bio_add_page(bio, page, page_size, pg_offset);
2834         bio->bi_end_io = end_io_func;
2835         bio->bi_private = tree;
2836         bio->bi_write_hint = page->mapping->host->i_write_hint;
2837         bio->bi_opf = opf;
2838         if (wbc) {
2839                 wbc_init_bio(wbc, bio);
2840                 wbc_account_io(wbc, page, page_size);
2841         }
2842
2843         *bio_ret = bio;
2844
2845         return ret;
2846 }
2847
2848 static void attach_extent_buffer_page(struct extent_buffer *eb,
2849                                       struct page *page)
2850 {
2851         if (!PagePrivate(page)) {
2852                 SetPagePrivate(page);
2853                 get_page(page);
2854                 set_page_private(page, (unsigned long)eb);
2855         } else {
2856                 WARN_ON(page->private != (unsigned long)eb);
2857         }
2858 }
2859
2860 void set_page_extent_mapped(struct page *page)
2861 {
2862         if (!PagePrivate(page)) {
2863                 SetPagePrivate(page);
2864                 get_page(page);
2865                 set_page_private(page, EXTENT_PAGE_PRIVATE);
2866         }
2867 }
2868
2869 static struct extent_map *
2870 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
2871                  u64 start, u64 len, get_extent_t *get_extent,
2872                  struct extent_map **em_cached)
2873 {
2874         struct extent_map *em;
2875
2876         if (em_cached && *em_cached) {
2877                 em = *em_cached;
2878                 if (extent_map_in_tree(em) && start >= em->start &&
2879                     start < extent_map_end(em)) {
2880                         refcount_inc(&em->refs);
2881                         return em;
2882                 }
2883
2884                 free_extent_map(em);
2885                 *em_cached = NULL;
2886         }
2887
2888         em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
2889         if (em_cached && !IS_ERR_OR_NULL(em)) {
2890                 BUG_ON(*em_cached);
2891                 refcount_inc(&em->refs);
2892                 *em_cached = em;
2893         }
2894         return em;
2895 }
2896 /*
2897  * basic readpage implementation.  Locked extent state structs are inserted
2898  * into the tree that are removed when the IO is done (by the end_io
2899  * handlers)
2900  * XXX JDM: This needs looking at to ensure proper page locking
2901  * return 0 on success, otherwise return error
2902  */
2903 static int __do_readpage(struct extent_io_tree *tree,
2904                          struct page *page,
2905                          get_extent_t *get_extent,
2906                          struct extent_map **em_cached,
2907                          struct bio **bio, int mirror_num,
2908                          unsigned long *bio_flags, unsigned int read_flags,
2909                          u64 *prev_em_start)
2910 {
2911         struct inode *inode = page->mapping->host;
2912         u64 start = page_offset(page);
2913         const u64 end = start + PAGE_SIZE - 1;
2914         u64 cur = start;
2915         u64 extent_offset;
2916         u64 last_byte = i_size_read(inode);
2917         u64 block_start;
2918         u64 cur_end;
2919         struct extent_map *em;
2920         struct block_device *bdev;
2921         int ret = 0;
2922         int nr = 0;
2923         size_t pg_offset = 0;
2924         size_t iosize;
2925         size_t disk_io_size;
2926         size_t blocksize = inode->i_sb->s_blocksize;
2927         unsigned long this_bio_flag = 0;
2928
2929         set_page_extent_mapped(page);
2930
2931         if (!PageUptodate(page)) {
2932                 if (cleancache_get_page(page) == 0) {
2933                         BUG_ON(blocksize != PAGE_SIZE);
2934                         unlock_extent(tree, start, end);
2935                         goto out;
2936                 }
2937         }
2938
2939         if (page->index == last_byte >> PAGE_SHIFT) {
2940                 char *userpage;
2941                 size_t zero_offset = last_byte & (PAGE_SIZE - 1);
2942
2943                 if (zero_offset) {
2944                         iosize = PAGE_SIZE - zero_offset;
2945                         userpage = kmap_atomic(page);
2946                         memset(userpage + zero_offset, 0, iosize);
2947                         flush_dcache_page(page);
2948                         kunmap_atomic(userpage);
2949                 }
2950         }
2951         while (cur <= end) {
2952                 bool force_bio_submit = false;
2953                 u64 offset;
2954
2955                 if (cur >= last_byte) {
2956                         char *userpage;
2957                         struct extent_state *cached = NULL;
2958
2959                         iosize = PAGE_SIZE - pg_offset;
2960                         userpage = kmap_atomic(page);
2961                         memset(userpage + pg_offset, 0, iosize);
2962                         flush_dcache_page(page);
2963                         kunmap_atomic(userpage);
2964                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2965                                             &cached, GFP_NOFS);
2966                         unlock_extent_cached(tree, cur,
2967                                              cur + iosize - 1, &cached);
2968                         break;
2969                 }
2970                 em = __get_extent_map(inode, page, pg_offset, cur,
2971                                       end - cur + 1, get_extent, em_cached);
2972                 if (IS_ERR_OR_NULL(em)) {
2973                         SetPageError(page);
2974                         unlock_extent(tree, cur, end);
2975                         break;
2976                 }
2977                 extent_offset = cur - em->start;
2978                 BUG_ON(extent_map_end(em) <= cur);
2979                 BUG_ON(end < cur);
2980
2981                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2982                         this_bio_flag |= EXTENT_BIO_COMPRESSED;
2983                         extent_set_compress_type(&this_bio_flag,
2984                                                  em->compress_type);
2985                 }
2986
2987                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2988                 cur_end = min(extent_map_end(em) - 1, end);
2989                 iosize = ALIGN(iosize, blocksize);
2990                 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2991                         disk_io_size = em->block_len;
2992                         offset = em->block_start;
2993                 } else {
2994                         offset = em->block_start + extent_offset;
2995                         disk_io_size = iosize;
2996                 }
2997                 bdev = em->bdev;
2998                 block_start = em->block_start;
2999                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3000                         block_start = EXTENT_MAP_HOLE;
3001
3002                 /*
3003                  * If we have a file range that points to a compressed extent
3004                  * and it's followed by a consecutive file range that points to
3005                  * to the same compressed extent (possibly with a different
3006                  * offset and/or length, so it either points to the whole extent
3007                  * or only part of it), we must make sure we do not submit a
3008                  * single bio to populate the pages for the 2 ranges because
3009                  * this makes the compressed extent read zero out the pages
3010                  * belonging to the 2nd range. Imagine the following scenario:
3011                  *
3012                  *  File layout
3013                  *  [0 - 8K]                     [8K - 24K]
3014                  *    |                               |
3015                  *    |                               |
3016                  * points to extent X,         points to extent X,
3017                  * offset 4K, length of 8K     offset 0, length 16K
3018                  *
3019                  * [extent X, compressed length = 4K uncompressed length = 16K]
3020                  *
3021                  * If the bio to read the compressed extent covers both ranges,
3022                  * it will decompress extent X into the pages belonging to the
3023                  * first range and then it will stop, zeroing out the remaining
3024                  * pages that belong to the other range that points to extent X.
3025                  * So here we make sure we submit 2 bios, one for the first
3026                  * range and another one for the third range. Both will target
3027                  * the same physical extent from disk, but we can't currently
3028                  * make the compressed bio endio callback populate the pages
3029                  * for both ranges because each compressed bio is tightly
3030                  * coupled with a single extent map, and each range can have
3031                  * an extent map with a different offset value relative to the
3032                  * uncompressed data of our extent and different lengths. This
3033                  * is a corner case so we prioritize correctness over
3034                  * non-optimal behavior (submitting 2 bios for the same extent).
3035                  */
3036                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3037                     prev_em_start && *prev_em_start != (u64)-1 &&
3038                     *prev_em_start != em->start)
3039                         force_bio_submit = true;
3040
3041                 if (prev_em_start)
3042                         *prev_em_start = em->start;
3043
3044                 free_extent_map(em);
3045                 em = NULL;
3046
3047                 /* we've found a hole, just zero and go on */
3048                 if (block_start == EXTENT_MAP_HOLE) {
3049                         char *userpage;
3050                         struct extent_state *cached = NULL;
3051
3052                         userpage = kmap_atomic(page);
3053                         memset(userpage + pg_offset, 0, iosize);
3054                         flush_dcache_page(page);
3055                         kunmap_atomic(userpage);
3056
3057                         set_extent_uptodate(tree, cur, cur + iosize - 1,
3058                                             &cached, GFP_NOFS);
3059                         unlock_extent_cached(tree, cur,
3060                                              cur + iosize - 1, &cached);
3061                         cur = cur + iosize;
3062                         pg_offset += iosize;
3063                         continue;
3064                 }
3065                 /* the get_extent function already copied into the page */
3066                 if (test_range_bit(tree, cur, cur_end,
3067                                    EXTENT_UPTODATE, 1, NULL)) {
3068                         check_page_uptodate(tree, page);
3069                         unlock_extent(tree, cur, cur + iosize - 1);
3070                         cur = cur + iosize;
3071                         pg_offset += iosize;
3072                         continue;
3073                 }
3074                 /* we have an inline extent but it didn't get marked up
3075                  * to date.  Error out
3076                  */
3077                 if (block_start == EXTENT_MAP_INLINE) {
3078                         SetPageError(page);
3079                         unlock_extent(tree, cur, cur + iosize - 1);
3080                         cur = cur + iosize;
3081                         pg_offset += iosize;
3082                         continue;
3083                 }
3084
3085                 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3086                                          page, offset, disk_io_size,
3087                                          pg_offset, bdev, bio,
3088                                          end_bio_extent_readpage, mirror_num,
3089                                          *bio_flags,
3090                                          this_bio_flag,
3091                                          force_bio_submit);
3092                 if (!ret) {
3093                         nr++;
3094                         *bio_flags = this_bio_flag;
3095                 } else {
3096                         SetPageError(page);
3097                         unlock_extent(tree, cur, cur + iosize - 1);
3098                         goto out;
3099                 }
3100                 cur = cur + iosize;
3101                 pg_offset += iosize;
3102         }
3103 out:
3104         if (!nr) {
3105                 if (!PageError(page))
3106                         SetPageUptodate(page);
3107                 unlock_page(page);
3108         }
3109         return ret;
3110 }
3111
3112 static inline void __do_contiguous_readpages(struct extent_io_tree *tree,
3113                                              struct page *pages[], int nr_pages,
3114                                              u64 start, u64 end,
3115                                              struct extent_map **em_cached,
3116                                              struct bio **bio,
3117                                              unsigned long *bio_flags,
3118                                              u64 *prev_em_start)
3119 {
3120         struct inode *inode;
3121         struct btrfs_ordered_extent *ordered;
3122         int index;
3123
3124         inode = pages[0]->mapping->host;
3125         while (1) {
3126                 lock_extent(tree, start, end);
3127                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3128                                                      end - start + 1);
3129                 if (!ordered)
3130                         break;
3131                 unlock_extent(tree, start, end);
3132                 btrfs_start_ordered_extent(inode, ordered, 1);
3133                 btrfs_put_ordered_extent(ordered);
3134         }
3135
3136         for (index = 0; index < nr_pages; index++) {
3137                 __do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3138                                 bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3139                 put_page(pages[index]);
3140         }
3141 }
3142
3143 static void __extent_readpages(struct extent_io_tree *tree,
3144                                struct page *pages[],
3145                                int nr_pages,
3146                                struct extent_map **em_cached,
3147                                struct bio **bio, unsigned long *bio_flags,
3148                                u64 *prev_em_start)
3149 {
3150         u64 start = 0;
3151         u64 end = 0;
3152         u64 page_start;
3153         int index;
3154         int first_index = 0;
3155
3156         for (index = 0; index < nr_pages; index++) {
3157                 page_start = page_offset(pages[index]);
3158                 if (!end) {
3159                         start = page_start;
3160                         end = start + PAGE_SIZE - 1;
3161                         first_index = index;
3162                 } else if (end + 1 == page_start) {
3163                         end += PAGE_SIZE;
3164                 } else {
3165                         __do_contiguous_readpages(tree, &pages[first_index],
3166                                                   index - first_index, start,
3167                                                   end, em_cached,
3168                                                   bio, bio_flags,
3169                                                   prev_em_start);
3170                         start = page_start;
3171                         end = start + PAGE_SIZE - 1;
3172                         first_index = index;
3173                 }
3174         }
3175
3176         if (end)
3177                 __do_contiguous_readpages(tree, &pages[first_index],
3178                                           index - first_index, start,
3179                                           end, em_cached, bio,
3180                                           bio_flags, prev_em_start);
3181 }
3182
3183 static int __extent_read_full_page(struct extent_io_tree *tree,
3184                                    struct page *page,
3185                                    get_extent_t *get_extent,
3186                                    struct bio **bio, int mirror_num,
3187                                    unsigned long *bio_flags,
3188                                    unsigned int read_flags)
3189 {
3190         struct inode *inode = page->mapping->host;
3191         struct btrfs_ordered_extent *ordered;
3192         u64 start = page_offset(page);
3193         u64 end = start + PAGE_SIZE - 1;
3194         int ret;
3195
3196         while (1) {
3197                 lock_extent(tree, start, end);
3198                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3199                                                 PAGE_SIZE);
3200                 if (!ordered)
3201                         break;
3202                 unlock_extent(tree, start, end);
3203                 btrfs_start_ordered_extent(inode, ordered, 1);
3204                 btrfs_put_ordered_extent(ordered);
3205         }
3206
3207         ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3208                             bio_flags, read_flags, NULL);
3209         return ret;
3210 }
3211
3212 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3213                             get_extent_t *get_extent, int mirror_num)
3214 {
3215         struct bio *bio = NULL;
3216         unsigned long bio_flags = 0;
3217         int ret;
3218
3219         ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3220                                       &bio_flags, 0);
3221         if (bio)
3222                 ret = submit_one_bio(bio, mirror_num, bio_flags);
3223         return ret;
3224 }
3225
3226 static void update_nr_written(struct writeback_control *wbc,
3227                               unsigned long nr_written)
3228 {
3229         wbc->nr_to_write -= nr_written;
3230 }
3231
3232 /*
3233  * helper for __extent_writepage, doing all of the delayed allocation setup.
3234  *
3235  * This returns 1 if btrfs_run_delalloc_range function did all the work required
3236  * to write the page (copy into inline extent).  In this case the IO has
3237  * been started and the page is already unlocked.
3238  *
3239  * This returns 0 if all went well (page still locked)
3240  * This returns < 0 if there were errors (page still locked)
3241  */
3242 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3243                               struct page *page, struct writeback_control *wbc,
3244                               struct extent_page_data *epd,
3245                               u64 delalloc_start,
3246                               unsigned long *nr_written)
3247 {
3248         struct extent_io_tree *tree = epd->tree;
3249         u64 page_end = delalloc_start + PAGE_SIZE - 1;
3250         u64 nr_delalloc;
3251         u64 delalloc_to_write = 0;
3252         u64 delalloc_end = 0;
3253         int ret;
3254         int page_started = 0;
3255
3256         if (epd->extent_locked)
3257                 return 0;
3258
3259         while (delalloc_end < page_end) {
3260                 nr_delalloc = find_lock_delalloc_range(inode, tree,
3261                                                page,
3262                                                &delalloc_start,
3263                                                &delalloc_end,
3264                                                BTRFS_MAX_EXTENT_SIZE);
3265                 if (nr_delalloc == 0) {
3266                         delalloc_start = delalloc_end + 1;
3267                         continue;
3268                 }
3269                 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3270                                 delalloc_end, &page_started, nr_written, wbc);
3271                 /* File system has been set read-only */
3272                 if (ret) {
3273                         SetPageError(page);
3274                         /*
3275                          * btrfs_run_delalloc_range should return < 0 for error
3276                          * but just in case, we use > 0 here meaning the IO is
3277                          * started, so we don't want to return > 0 unless
3278                          * things are going well.
3279                          */
3280                         ret = ret < 0 ? ret : -EIO;
3281                         goto done;
3282                 }
3283                 /*
3284                  * delalloc_end is already one less than the total length, so
3285                  * we don't subtract one from PAGE_SIZE
3286                  */
3287                 delalloc_to_write += (delalloc_end - delalloc_start +
3288                                       PAGE_SIZE) >> PAGE_SHIFT;
3289                 delalloc_start = delalloc_end + 1;
3290         }
3291         if (wbc->nr_to_write < delalloc_to_write) {
3292                 int thresh = 8192;
3293
3294                 if (delalloc_to_write < thresh * 2)
3295                         thresh = delalloc_to_write;
3296                 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3297                                          thresh);
3298         }
3299
3300         /* did the fill delalloc function already unlock and start
3301          * the IO?
3302          */
3303         if (page_started) {
3304                 /*
3305                  * we've unlocked the page, so we can't update
3306                  * the mapping's writeback index, just update
3307                  * nr_to_write.
3308                  */
3309                 wbc->nr_to_write -= *nr_written;
3310                 return 1;
3311         }
3312
3313         ret = 0;
3314
3315 done:
3316         return ret;
3317 }
3318
3319 /*
3320  * helper for __extent_writepage.  This calls the writepage start hooks,
3321  * and does the loop to map the page into extents and bios.
3322  *
3323  * We return 1 if the IO is started and the page is unlocked,
3324  * 0 if all went well (page still locked)
3325  * < 0 if there were errors (page still locked)
3326  */
3327 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3328                                  struct page *page,
3329                                  struct writeback_control *wbc,
3330                                  struct extent_page_data *epd,
3331                                  loff_t i_size,
3332                                  unsigned long nr_written,
3333                                  unsigned int write_flags, int *nr_ret)
3334 {
3335         struct extent_io_tree *tree = epd->tree;
3336         u64 start = page_offset(page);
3337         u64 page_end = start + PAGE_SIZE - 1;
3338         u64 end;
3339         u64 cur = start;
3340         u64 extent_offset;
3341         u64 block_start;
3342         u64 iosize;
3343         struct extent_map *em;
3344         struct block_device *bdev;
3345         size_t pg_offset = 0;
3346         size_t blocksize;
3347         int ret = 0;
3348         int nr = 0;
3349         bool compressed;
3350
3351         if (tree->ops && tree->ops->writepage_start_hook) {
3352                 ret = tree->ops->writepage_start_hook(page, start,
3353                                                       page_end);
3354                 if (ret) {
3355                         /* Fixup worker will requeue */
3356                         if (ret == -EBUSY)
3357                                 wbc->pages_skipped++;
3358                         else
3359                                 redirty_page_for_writepage(wbc, page);
3360
3361                         update_nr_written(wbc, nr_written);
3362                         unlock_page(page);
3363                         return 1;
3364                 }
3365         }
3366
3367         /*
3368          * we don't want to touch the inode after unlocking the page,
3369          * so we update the mapping writeback index now
3370          */
3371         update_nr_written(wbc, nr_written + 1);
3372
3373         end = page_end;
3374         if (i_size <= start) {
3375                 if (tree->ops && tree->ops->writepage_end_io_hook)
3376                         tree->ops->writepage_end_io_hook(page, start,
3377                                                          page_end, NULL, 1);
3378                 goto done;
3379         }
3380
3381         blocksize = inode->i_sb->s_blocksize;
3382
3383         while (cur <= end) {
3384                 u64 em_end;
3385                 u64 offset;
3386
3387                 if (cur >= i_size) {
3388                         if (tree->ops && tree->ops->writepage_end_io_hook)
3389                                 tree->ops->writepage_end_io_hook(page, cur,
3390                                                          page_end, NULL, 1);
3391                         break;
3392                 }
3393                 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3394                                      end - cur + 1, 1);
3395                 if (IS_ERR_OR_NULL(em)) {
3396                         SetPageError(page);
3397                         ret = PTR_ERR_OR_ZERO(em);
3398                         break;
3399                 }
3400
3401                 extent_offset = cur - em->start;
3402                 em_end = extent_map_end(em);
3403                 BUG_ON(em_end <= cur);
3404                 BUG_ON(end < cur);
3405                 iosize = min(em_end - cur, end - cur + 1);
3406                 iosize = ALIGN(iosize, blocksize);
3407                 offset = em->block_start + extent_offset;
3408                 bdev = em->bdev;
3409                 block_start = em->block_start;
3410                 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3411                 free_extent_map(em);
3412                 em = NULL;
3413
3414                 /*
3415                  * compressed and inline extents are written through other
3416                  * paths in the FS
3417                  */
3418                 if (compressed || block_start == EXTENT_MAP_HOLE ||
3419                     block_start == EXTENT_MAP_INLINE) {
3420                         /*
3421                          * end_io notification does not happen here for
3422                          * compressed extents
3423                          */
3424                         if (!compressed && tree->ops &&
3425                             tree->ops->writepage_end_io_hook)
3426                                 tree->ops->writepage_end_io_hook(page, cur,
3427                                                          cur + iosize - 1,
3428                                                          NULL, 1);
3429                         else if (compressed) {
3430                                 /* we don't want to end_page_writeback on
3431                                  * a compressed extent.  this happens
3432                                  * elsewhere
3433                                  */
3434                                 nr++;
3435                         }
3436
3437                         cur += iosize;
3438                         pg_offset += iosize;
3439                         continue;
3440                 }
3441
3442                 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3443                 if (!PageWriteback(page)) {
3444                         btrfs_err(BTRFS_I(inode)->root->fs_info,
3445                                    "page %lu not writeback, cur %llu end %llu",
3446                                page->index, cur, end);
3447                 }
3448
3449                 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3450                                          page, offset, iosize, pg_offset,
3451                                          bdev, &epd->bio,
3452                                          end_bio_extent_writepage,
3453                                          0, 0, 0, false);
3454                 if (ret) {
3455                         SetPageError(page);
3456                         if (PageWriteback(page))
3457                                 end_page_writeback(page);
3458                 }
3459
3460                 cur = cur + iosize;
3461                 pg_offset += iosize;
3462                 nr++;
3463         }
3464 done:
3465         *nr_ret = nr;
3466         return ret;
3467 }
3468
3469 /*
3470  * the writepage semantics are similar to regular writepage.  extent
3471  * records are inserted to lock ranges in the tree, and as dirty areas
3472  * are found, they are marked writeback.  Then the lock bits are removed
3473  * and the end_io handler clears the writeback ranges
3474  *
3475  * Return 0 if everything goes well.
3476  * Return <0 for error.
3477  */
3478 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3479                               struct extent_page_data *epd)
3480 {
3481         struct inode *inode = page->mapping->host;
3482         u64 start = page_offset(page);
3483         u64 page_end = start + PAGE_SIZE - 1;
3484         int ret;
3485         int nr = 0;
3486         size_t pg_offset = 0;
3487         loff_t i_size = i_size_read(inode);
3488         unsigned long end_index = i_size >> PAGE_SHIFT;
3489         unsigned int write_flags = 0;
3490         unsigned long nr_written = 0;
3491
3492         write_flags = wbc_to_write_flags(wbc);
3493
3494         trace___extent_writepage(page, inode, wbc);
3495
3496         WARN_ON(!PageLocked(page));
3497
3498         ClearPageError(page);
3499
3500         pg_offset = i_size & (PAGE_SIZE - 1);
3501         if (page->index > end_index ||
3502            (page->index == end_index && !pg_offset)) {
3503                 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3504                 unlock_page(page);
3505                 return 0;
3506         }
3507
3508         if (page->index == end_index) {
3509                 char *userpage;
3510
3511                 userpage = kmap_atomic(page);
3512                 memset(userpage + pg_offset, 0,
3513                        PAGE_SIZE - pg_offset);
3514                 kunmap_atomic(userpage);
3515                 flush_dcache_page(page);
3516         }
3517
3518         pg_offset = 0;
3519
3520         set_page_extent_mapped(page);
3521
3522         ret = writepage_delalloc(inode, page, wbc, epd, start, &nr_written);
3523         if (ret == 1)
3524                 goto done_unlocked;
3525         if (ret)
3526                 goto done;
3527
3528         ret = __extent_writepage_io(inode, page, wbc, epd,
3529                                     i_size, nr_written, write_flags, &nr);
3530         if (ret == 1)
3531                 goto done_unlocked;
3532
3533 done:
3534         if (nr == 0) {
3535                 /* make sure the mapping tag for page dirty gets cleared */
3536                 set_page_writeback(page);
3537                 end_page_writeback(page);
3538         }
3539         if (PageError(page)) {
3540                 ret = ret < 0 ? ret : -EIO;
3541                 end_extent_writepage(page, ret, start, page_end);
3542         }
3543         unlock_page(page);
3544         ASSERT(ret <= 0);
3545         return ret;
3546
3547 done_unlocked:
3548         return 0;
3549 }
3550
3551 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3552 {
3553         wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3554                        TASK_UNINTERRUPTIBLE);
3555 }
3556
3557 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3558 {
3559         clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3560         smp_mb__after_atomic();
3561         wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3562 }
3563
3564 /*
3565  * Lock eb pages and flush the bio if we can't the locks
3566  *
3567  * Return  0 if nothing went wrong
3568  * Return >0 is same as 0, except bio is not submitted
3569  * Return <0 if something went wrong, no page is locked
3570  */
3571 static noinline_for_stack int
3572 lock_extent_buffer_for_io(struct extent_buffer *eb,
3573                           struct btrfs_fs_info *fs_info,
3574                           struct extent_page_data *epd)
3575 {
3576         int i, num_pages, failed_page_nr;
3577         int flush = 0;
3578         int ret = 0;
3579
3580         if (!btrfs_try_tree_write_lock(eb)) {
3581                 ret = flush_write_bio(epd);
3582                 if (ret < 0)
3583                         return ret;
3584                 flush = 1;
3585                 btrfs_tree_lock(eb);
3586         }
3587
3588         if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3589                 btrfs_tree_unlock(eb);
3590                 if (!epd->sync_io)
3591                         return 0;
3592                 if (!flush) {
3593                         ret = flush_write_bio(epd);
3594                         if (ret < 0)
3595                                 return ret;
3596                         flush = 1;
3597                 }
3598                 while (1) {
3599                         wait_on_extent_buffer_writeback(eb);
3600                         btrfs_tree_lock(eb);
3601                         if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3602                                 break;
3603                         btrfs_tree_unlock(eb);
3604                 }
3605         }
3606
3607         /*
3608          * We need to do this to prevent races in people who check if the eb is
3609          * under IO since we can end up having no IO bits set for a short period
3610          * of time.
3611          */
3612         spin_lock(&eb->refs_lock);
3613         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3614                 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3615                 spin_unlock(&eb->refs_lock);
3616                 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3617                 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3618                                          -eb->len,
3619                                          fs_info->dirty_metadata_batch);
3620                 ret = 1;
3621         } else {
3622                 spin_unlock(&eb->refs_lock);
3623         }
3624
3625         btrfs_tree_unlock(eb);
3626
3627         if (!ret)
3628                 return ret;
3629
3630         num_pages = num_extent_pages(eb);
3631         for (i = 0; i < num_pages; i++) {
3632                 struct page *p = eb->pages[i];
3633
3634                 if (!trylock_page(p)) {
3635                         if (!flush) {
3636                                 int err;
3637
3638                                 err = flush_write_bio(epd);
3639                                 if (err < 0) {
3640                                         ret = err;
3641                                         failed_page_nr = i;
3642                                         goto err_unlock;
3643                                 }
3644                                 flush = 1;
3645                         }
3646                         lock_page(p);
3647                 }
3648         }
3649
3650         return ret;
3651 err_unlock:
3652         /* Unlock already locked pages */
3653         for (i = 0; i < failed_page_nr; i++)
3654                 unlock_page(eb->pages[i]);
3655         /*
3656          * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3657          * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3658          * be made and undo everything done before.
3659          */
3660         btrfs_tree_lock(eb);
3661         spin_lock(&eb->refs_lock);
3662         set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3663         end_extent_buffer_writeback(eb);
3664         spin_unlock(&eb->refs_lock);
3665         percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3666                                  fs_info->dirty_metadata_batch);
3667         btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3668         btrfs_tree_unlock(eb);
3669         return ret;
3670 }
3671
3672 static void set_btree_ioerr(struct page *page)
3673 {
3674         struct extent_buffer *eb = (struct extent_buffer *)page->private;
3675
3676         SetPageError(page);
3677         if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3678                 return;
3679
3680         /*
3681          * If writeback for a btree extent that doesn't belong to a log tree
3682          * failed, increment the counter transaction->eb_write_errors.
3683          * We do this because while the transaction is running and before it's
3684          * committing (when we call filemap_fdata[write|wait]_range against
3685          * the btree inode), we might have
3686          * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3687          * returns an error or an error happens during writeback, when we're
3688          * committing the transaction we wouldn't know about it, since the pages
3689          * can be no longer dirty nor marked anymore for writeback (if a
3690          * subsequent modification to the extent buffer didn't happen before the
3691          * transaction commit), which makes filemap_fdata[write|wait]_range not
3692          * able to find the pages tagged with SetPageError at transaction
3693          * commit time. So if this happens we must abort the transaction,
3694          * otherwise we commit a super block with btree roots that point to
3695          * btree nodes/leafs whose content on disk is invalid - either garbage
3696          * or the content of some node/leaf from a past generation that got
3697          * cowed or deleted and is no longer valid.
3698          *
3699          * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3700          * not be enough - we need to distinguish between log tree extents vs
3701          * non-log tree extents, and the next filemap_fdatawait_range() call
3702          * will catch and clear such errors in the mapping - and that call might
3703          * be from a log sync and not from a transaction commit. Also, checking
3704          * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3705          * not done and would not be reliable - the eb might have been released
3706          * from memory and reading it back again means that flag would not be
3707          * set (since it's a runtime flag, not persisted on disk).
3708          *
3709          * Using the flags below in the btree inode also makes us achieve the
3710          * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3711          * writeback for all dirty pages and before filemap_fdatawait_range()
3712          * is called, the writeback for all dirty pages had already finished
3713          * with errors - because we were not using AS_EIO/AS_ENOSPC,
3714          * filemap_fdatawait_range() would return success, as it could not know
3715          * that writeback errors happened (the pages were no longer tagged for
3716          * writeback).
3717          */
3718         switch (eb->log_index) {
3719         case -1:
3720                 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3721                 break;
3722         case 0:
3723                 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3724                 break;
3725         case 1:
3726                 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3727                 break;
3728         default:
3729                 BUG(); /* unexpected, logic error */
3730         }
3731 }
3732
3733 static void end_bio_extent_buffer_writepage(struct bio *bio)
3734 {
3735         struct bio_vec *bvec;
3736         struct extent_buffer *eb;
3737         int i, done;
3738
3739         ASSERT(!bio_flagged(bio, BIO_CLONED));
3740         bio_for_each_segment_all(bvec, bio, i) {
3741                 struct page *page = bvec->bv_page;
3742
3743                 eb = (struct extent_buffer *)page->private;
3744                 BUG_ON(!eb);
3745                 done = atomic_dec_and_test(&eb->io_pages);
3746
3747                 if (bio->bi_status ||
3748                     test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3749                         ClearPageUptodate(page);
3750                         set_btree_ioerr(page);
3751                 }
3752
3753                 end_page_writeback(page);
3754
3755                 if (!done)
3756                         continue;
3757
3758                 end_extent_buffer_writeback(eb);
3759         }
3760
3761         bio_put(bio);
3762 }
3763
3764 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3765                         struct btrfs_fs_info *fs_info,
3766                         struct writeback_control *wbc,
3767                         struct extent_page_data *epd)
3768 {
3769         struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3770         struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3771         u64 offset = eb->start;
3772         u32 nritems;
3773         int i, num_pages;
3774         unsigned long start, end;
3775         unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3776         int ret = 0;
3777
3778         clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3779         num_pages = num_extent_pages(eb);
3780         atomic_set(&eb->io_pages, num_pages);
3781
3782         /* set btree blocks beyond nritems with 0 to avoid stale content. */
3783         nritems = btrfs_header_nritems(eb);
3784         if (btrfs_header_level(eb) > 0) {
3785                 end = btrfs_node_key_ptr_offset(nritems);
3786
3787                 memzero_extent_buffer(eb, end, eb->len - end);
3788         } else {
3789                 /*
3790                  * leaf:
3791                  * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3792                  */
3793                 start = btrfs_item_nr_offset(nritems);
3794                 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, eb);
3795                 memzero_extent_buffer(eb, start, end - start);
3796         }
3797
3798         for (i = 0; i < num_pages; i++) {
3799                 struct page *p = eb->pages[i];
3800
3801                 clear_page_dirty_for_io(p);
3802                 set_page_writeback(p);
3803                 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3804                                          p, offset, PAGE_SIZE, 0, bdev,
3805                                          &epd->bio,
3806                                          end_bio_extent_buffer_writepage,
3807                                          0, 0, 0, false);
3808                 if (ret) {
3809                         set_btree_ioerr(p);
3810                         if (PageWriteback(p))
3811                                 end_page_writeback(p);
3812                         if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3813                                 end_extent_buffer_writeback(eb);
3814                         ret = -EIO;
3815                         break;
3816                 }
3817                 offset += PAGE_SIZE;
3818                 update_nr_written(wbc, 1);
3819                 unlock_page(p);
3820         }
3821
3822         if (unlikely(ret)) {
3823                 for (; i < num_pages; i++) {
3824                         struct page *p = eb->pages[i];
3825                         clear_page_dirty_for_io(p);
3826                         unlock_page(p);
3827                 }
3828         }
3829
3830         return ret;
3831 }
3832
3833 int btree_write_cache_pages(struct address_space *mapping,
3834                                    struct writeback_control *wbc)
3835 {
3836         struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3837         struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3838         struct extent_buffer *eb, *prev_eb = NULL;
3839         struct extent_page_data epd = {
3840                 .bio = NULL,
3841                 .tree = tree,
3842                 .extent_locked = 0,
3843                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3844         };
3845         int ret = 0;
3846         int done = 0;
3847         int nr_to_write_done = 0;
3848         struct pagevec pvec;
3849         int nr_pages;
3850         pgoff_t index;
3851         pgoff_t end;            /* Inclusive */
3852         int scanned = 0;
3853         int tag;
3854
3855         pagevec_init(&pvec);
3856         if (wbc->range_cyclic) {
3857                 index = mapping->writeback_index; /* Start from prev offset */
3858                 end = -1;
3859         } else {
3860                 index = wbc->range_start >> PAGE_SHIFT;
3861                 end = wbc->range_end >> PAGE_SHIFT;
3862                 scanned = 1;
3863         }
3864         if (wbc->sync_mode == WB_SYNC_ALL)
3865                 tag = PAGECACHE_TAG_TOWRITE;
3866         else
3867                 tag = PAGECACHE_TAG_DIRTY;
3868 retry:
3869         if (wbc->sync_mode == WB_SYNC_ALL)
3870                 tag_pages_for_writeback(mapping, index, end);
3871         while (!done && !nr_to_write_done && (index <= end) &&
3872                (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3873                         tag))) {
3874                 unsigned i;
3875
3876                 scanned = 1;
3877                 for (i = 0; i < nr_pages; i++) {
3878                         struct page *page = pvec.pages[i];
3879
3880                         if (!PagePrivate(page))
3881                                 continue;
3882
3883                         spin_lock(&mapping->private_lock);
3884                         if (!PagePrivate(page)) {
3885                                 spin_unlock(&mapping->private_lock);
3886                                 continue;
3887                         }
3888
3889                         eb = (struct extent_buffer *)page->private;
3890
3891                         /*
3892                          * Shouldn't happen and normally this would be a BUG_ON
3893                          * but no sense in crashing the users box for something
3894                          * we can survive anyway.
3895                          */
3896                         if (WARN_ON(!eb)) {
3897                                 spin_unlock(&mapping->private_lock);
3898                                 continue;
3899                         }
3900
3901                         if (eb == prev_eb) {
3902                                 spin_unlock(&mapping->private_lock);
3903                                 continue;
3904                         }
3905
3906                         ret = atomic_inc_not_zero(&eb->refs);
3907                         spin_unlock(&mapping->private_lock);
3908                         if (!ret)
3909                                 continue;
3910
3911                         prev_eb = eb;
3912                         ret = lock_extent_buffer_for_io(eb, fs_info, &epd);
3913                         if (!ret) {
3914                                 free_extent_buffer(eb);
3915                                 continue;
3916                         } else if (ret < 0) {
3917                                 done = 1;
3918                                 free_extent_buffer(eb);
3919                                 break;
3920                         }
3921
3922                         ret = write_one_eb(eb, fs_info, wbc, &epd);
3923                         if (ret) {
3924                                 done = 1;
3925                                 free_extent_buffer(eb);
3926                                 break;
3927                         }
3928                         free_extent_buffer(eb);
3929
3930                         /*
3931                          * the filesystem may choose to bump up nr_to_write.
3932                          * We have to make sure to honor the new nr_to_write
3933                          * at any time
3934                          */
3935                         nr_to_write_done = wbc->nr_to_write <= 0;
3936                 }
3937                 pagevec_release(&pvec);
3938                 cond_resched();
3939         }
3940         if (!scanned && !done) {
3941                 /*
3942                  * We hit the last page and there is more work to be done: wrap
3943                  * back to the start of the file
3944                  */
3945                 scanned = 1;
3946                 index = 0;
3947                 goto retry;
3948         }
3949         ASSERT(ret <= 0);
3950         if (ret < 0) {
3951                 end_write_bio(&epd, ret);
3952                 return ret;
3953         }
3954         /*
3955          * If something went wrong, don't allow any metadata write bio to be
3956          * submitted.
3957          *
3958          * This would prevent use-after-free if we had dirty pages not
3959          * cleaned up, which can still happen by fuzzed images.
3960          *
3961          * - Bad extent tree
3962          *   Allowing existing tree block to be allocated for other trees.
3963          *
3964          * - Log tree operations
3965          *   Exiting tree blocks get allocated to log tree, bumps its
3966          *   generation, then get cleaned in tree re-balance.
3967          *   Such tree block will not be written back, since it's clean,
3968          *   thus no WRITTEN flag set.
3969          *   And after log writes back, this tree block is not traced by
3970          *   any dirty extent_io_tree.
3971          *
3972          * - Offending tree block gets re-dirtied from its original owner
3973          *   Since it has bumped generation, no WRITTEN flag, it can be
3974          *   reused without COWing. This tree block will not be traced
3975          *   by btrfs_transaction::dirty_pages.
3976          *
3977          *   Now such dirty tree block will not be cleaned by any dirty
3978          *   extent io tree. Thus we don't want to submit such wild eb
3979          *   if the fs already has error.
3980          */
3981         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3982                 ret = flush_write_bio(&epd);
3983         } else {
3984                 ret = -EUCLEAN;
3985                 end_write_bio(&epd, ret);
3986         }
3987         return ret;
3988 }
3989
3990 /**
3991  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
3992  * @mapping: address space structure to write
3993  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3994  * @data: data passed to __extent_writepage function
3995  *
3996  * If a page is already under I/O, write_cache_pages() skips it, even
3997  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
3998  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
3999  * and msync() need to guarantee that all the data which was dirty at the time
4000  * the call was made get new I/O started against them.  If wbc->sync_mode is
4001  * WB_SYNC_ALL then we were called for data integrity and we must wait for
4002  * existing IO to complete.
4003  */
4004 static int extent_write_cache_pages(struct address_space *mapping,
4005                              struct writeback_control *wbc,
4006                              struct extent_page_data *epd)
4007 {
4008         struct inode *inode = mapping->host;
4009         int ret = 0;
4010         int done = 0;
4011         int nr_to_write_done = 0;
4012         struct pagevec pvec;
4013         int nr_pages;
4014         pgoff_t index;
4015         pgoff_t end;            /* Inclusive */
4016         pgoff_t done_index;
4017         int range_whole = 0;
4018         int scanned = 0;
4019         int tag;
4020
4021         /*
4022          * We have to hold onto the inode so that ordered extents can do their
4023          * work when the IO finishes.  The alternative to this is failing to add
4024          * an ordered extent if the igrab() fails there and that is a huge pain
4025          * to deal with, so instead just hold onto the inode throughout the
4026          * writepages operation.  If it fails here we are freeing up the inode
4027          * anyway and we'd rather not waste our time writing out stuff that is
4028          * going to be truncated anyway.
4029          */
4030         if (!igrab(inode))
4031                 return 0;
4032
4033         pagevec_init(&pvec);
4034         if (wbc->range_cyclic) {
4035                 index = mapping->writeback_index; /* Start from prev offset */
4036                 end = -1;
4037         } else {
4038                 index = wbc->range_start >> PAGE_SHIFT;
4039                 end = wbc->range_end >> PAGE_SHIFT;
4040                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4041                         range_whole = 1;
4042                 scanned = 1;
4043         }
4044
4045         /*
4046          * We do the tagged writepage as long as the snapshot flush bit is set
4047          * and we are the first one who do the filemap_flush() on this inode.
4048          *
4049          * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4050          * not race in and drop the bit.
4051          */
4052         if (range_whole && wbc->nr_to_write == LONG_MAX &&
4053             test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4054                                &BTRFS_I(inode)->runtime_flags))
4055                 wbc->tagged_writepages = 1;
4056
4057         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4058                 tag = PAGECACHE_TAG_TOWRITE;
4059         else
4060                 tag = PAGECACHE_TAG_DIRTY;
4061 retry:
4062         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4063                 tag_pages_for_writeback(mapping, index, end);
4064         done_index = index;
4065         while (!done && !nr_to_write_done && (index <= end) &&
4066                         (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4067                                                 &index, end, tag))) {
4068                 unsigned i;
4069
4070                 scanned = 1;
4071                 for (i = 0; i < nr_pages; i++) {
4072                         struct page *page = pvec.pages[i];
4073
4074                         done_index = page->index + 1;
4075                         /*
4076                          * At this point we hold neither the i_pages lock nor
4077                          * the page lock: the page may be truncated or
4078                          * invalidated (changing page->mapping to NULL),
4079                          * or even swizzled back from swapper_space to
4080                          * tmpfs file mapping
4081                          */
4082                         if (!trylock_page(page)) {
4083                                 ret = flush_write_bio(epd);
4084                                 BUG_ON(ret < 0);
4085                                 lock_page(page);
4086                         }
4087
4088                         if (unlikely(page->mapping != mapping)) {
4089                                 unlock_page(page);
4090                                 continue;
4091                         }
4092
4093                         if (wbc->sync_mode != WB_SYNC_NONE) {
4094                                 if (PageWriteback(page)) {
4095                                         ret = flush_write_bio(epd);
4096                                         BUG_ON(ret < 0);
4097                                 }
4098                                 wait_on_page_writeback(page);
4099                         }
4100
4101                         if (PageWriteback(page) ||
4102                             !clear_page_dirty_for_io(page)) {
4103                                 unlock_page(page);
4104                                 continue;
4105                         }
4106
4107                         ret = __extent_writepage(page, wbc, epd);
4108
4109                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
4110                                 unlock_page(page);
4111                                 ret = 0;
4112                         }
4113                         if (ret < 0) {
4114                                 done = 1;
4115                                 break;
4116                         }
4117
4118                         /*
4119                          * the filesystem may choose to bump up nr_to_write.
4120                          * We have to make sure to honor the new nr_to_write
4121                          * at any time
4122                          */
4123                         nr_to_write_done = wbc->nr_to_write <= 0;
4124                 }
4125                 pagevec_release(&pvec);
4126                 cond_resched();
4127         }
4128         if (!scanned && !done) {
4129                 /*
4130                  * We hit the last page and there is more work to be done: wrap
4131                  * back to the start of the file
4132                  */
4133                 scanned = 1;
4134                 index = 0;
4135
4136                 /*
4137                  * If we're looping we could run into a page that is locked by a
4138                  * writer and that writer could be waiting on writeback for a
4139                  * page in our current bio, and thus deadlock, so flush the
4140                  * write bio here.
4141                  */
4142                 ret = flush_write_bio(epd);
4143                 if (!ret)
4144                         goto retry;
4145         }
4146
4147         if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4148                 mapping->writeback_index = done_index;
4149
4150         btrfs_add_delayed_iput(inode);
4151         return ret;
4152 }
4153
4154 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4155 {
4156         int ret;
4157         struct extent_page_data epd = {
4158                 .bio = NULL,
4159                 .tree = &BTRFS_I(page->mapping->host)->io_tree,
4160                 .extent_locked = 0,
4161                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4162         };
4163
4164         ret = __extent_writepage(page, wbc, &epd);
4165         ASSERT(ret <= 0);
4166         if (ret < 0) {
4167                 end_write_bio(&epd, ret);
4168                 return ret;
4169         }
4170
4171         ret = flush_write_bio(&epd);
4172         ASSERT(ret <= 0);
4173         return ret;
4174 }
4175
4176 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4177                               int mode)
4178 {
4179         int ret = 0;
4180         int flush_ret;
4181         struct address_space *mapping = inode->i_mapping;
4182         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4183         struct page *page;
4184         unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4185                 PAGE_SHIFT;
4186
4187         struct extent_page_data epd = {
4188                 .bio = NULL,
4189                 .tree = tree,
4190                 .extent_locked = 1,
4191                 .sync_io = mode == WB_SYNC_ALL,
4192         };
4193         struct writeback_control wbc_writepages = {
4194                 .sync_mode      = mode,
4195                 .nr_to_write    = nr_pages * 2,
4196                 .range_start    = start,
4197                 .range_end      = end + 1,
4198         };
4199
4200         while (start <= end) {
4201                 page = find_get_page(mapping, start >> PAGE_SHIFT);
4202                 if (clear_page_dirty_for_io(page))
4203                         ret = __extent_writepage(page, &wbc_writepages, &epd);
4204                 else {
4205                         if (tree->ops && tree->ops->writepage_end_io_hook)
4206                                 tree->ops->writepage_end_io_hook(page, start,
4207                                                  start + PAGE_SIZE - 1,
4208                                                  NULL, 1);
4209                         unlock_page(page);
4210                 }
4211                 put_page(page);
4212                 start += PAGE_SIZE;
4213         }
4214
4215         flush_ret = flush_write_bio(&epd);
4216         BUG_ON(flush_ret < 0);
4217         return ret;
4218 }
4219
4220 int extent_writepages(struct address_space *mapping,
4221                       struct writeback_control *wbc)
4222 {
4223         int ret = 0;
4224         int flush_ret;
4225         struct extent_page_data epd = {
4226                 .bio = NULL,
4227                 .tree = &BTRFS_I(mapping->host)->io_tree,
4228                 .extent_locked = 0,
4229                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4230         };
4231
4232         ret = extent_write_cache_pages(mapping, wbc, &epd);
4233         flush_ret = flush_write_bio(&epd);
4234         BUG_ON(flush_ret < 0);
4235         return ret;
4236 }
4237
4238 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4239                      unsigned nr_pages)
4240 {
4241         struct bio *bio = NULL;
4242         unsigned page_idx;
4243         unsigned long bio_flags = 0;
4244         struct page *pagepool[16];
4245         struct page *page;
4246         struct extent_map *em_cached = NULL;
4247         struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4248         int nr = 0;
4249         u64 prev_em_start = (u64)-1;
4250
4251         for (page_idx = 0; page_idx < nr_pages; page_idx++) {
4252                 page = list_entry(pages->prev, struct page, lru);
4253
4254                 prefetchw(&page->flags);
4255                 list_del(&page->lru);
4256                 if (add_to_page_cache_lru(page, mapping,
4257                                         page->index,
4258                                         readahead_gfp_mask(mapping))) {
4259                         put_page(page);
4260                         continue;
4261                 }
4262
4263                 pagepool[nr++] = page;
4264                 if (nr < ARRAY_SIZE(pagepool))
4265                         continue;
4266                 __extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4267                                 &bio_flags, &prev_em_start);
4268                 nr = 0;
4269         }
4270         if (nr)
4271                 __extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4272                                 &bio_flags, &prev_em_start);
4273
4274         if (em_cached)
4275                 free_extent_map(em_cached);
4276
4277         BUG_ON(!list_empty(pages));
4278         if (bio)
4279                 return submit_one_bio(bio, 0, bio_flags);
4280         return 0;
4281 }
4282
4283 /*
4284  * basic invalidatepage code, this waits on any locked or writeback
4285  * ranges corresponding to the page, and then deletes any extent state
4286  * records from the tree
4287  */
4288 int extent_invalidatepage(struct extent_io_tree *tree,
4289                           struct page *page, unsigned long offset)
4290 {
4291         struct extent_state *cached_state = NULL;
4292         u64 start = page_offset(page);
4293         u64 end = start + PAGE_SIZE - 1;
4294         size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4295
4296         start += ALIGN(offset, blocksize);
4297         if (start > end)
4298                 return 0;
4299
4300         lock_extent_bits(tree, start, end, &cached_state);
4301         wait_on_page_writeback(page);
4302         clear_extent_bit(tree, start, end,
4303                          EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
4304                          EXTENT_DO_ACCOUNTING,
4305                          1, 1, &cached_state);
4306         return 0;
4307 }
4308
4309 /*
4310  * a helper for releasepage, this tests for areas of the page that
4311  * are locked or under IO and drops the related state bits if it is safe
4312  * to drop the page.
4313  */
4314 static int try_release_extent_state(struct extent_io_tree *tree,
4315                                     struct page *page, gfp_t mask)
4316 {
4317         u64 start = page_offset(page);
4318         u64 end = start + PAGE_SIZE - 1;
4319         int ret = 1;
4320
4321         if (test_range_bit(tree, start, end,
4322                            EXTENT_IOBITS, 0, NULL))
4323                 ret = 0;
4324         else {
4325                 /*
4326                  * at this point we can safely clear everything except the
4327                  * locked bit and the nodatasum bit
4328                  */
4329                 ret = __clear_extent_bit(tree, start, end,
4330                                  ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4331                                  0, 0, NULL, mask, NULL);
4332
4333                 /* if clear_extent_bit failed for enomem reasons,
4334                  * we can't allow the release to continue.
4335                  */
4336                 if (ret < 0)
4337                         ret = 0;
4338                 else
4339                         ret = 1;
4340         }
4341         return ret;
4342 }
4343
4344 /*
4345  * a helper for releasepage.  As long as there are no locked extents
4346  * in the range corresponding to the page, both state records and extent
4347  * map records are removed
4348  */
4349 int try_release_extent_mapping(struct page *page, gfp_t mask)
4350 {
4351         struct extent_map *em;
4352         u64 start = page_offset(page);
4353         u64 end = start + PAGE_SIZE - 1;
4354         struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4355         struct extent_io_tree *tree = &btrfs_inode->io_tree;
4356         struct extent_map_tree *map = &btrfs_inode->extent_tree;
4357
4358         if (gfpflags_allow_blocking(mask) &&
4359             page->mapping->host->i_size > SZ_16M) {
4360                 u64 len;
4361                 while (start <= end) {
4362                         len = end - start + 1;
4363                         write_lock(&map->lock);
4364                         em = lookup_extent_mapping(map, start, len);
4365                         if (!em) {
4366                                 write_unlock(&map->lock);
4367                                 break;
4368                         }
4369                         if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4370                             em->start != start) {
4371                                 write_unlock(&map->lock);
4372                                 free_extent_map(em);
4373                                 break;
4374                         }
4375                         if (!test_range_bit(tree, em->start,
4376                                             extent_map_end(em) - 1,
4377                                             EXTENT_LOCKED | EXTENT_WRITEBACK,
4378                                             0, NULL)) {
4379                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4380                                         &btrfs_inode->runtime_flags);
4381                                 remove_extent_mapping(map, em);
4382                                 /* once for the rb tree */
4383                                 free_extent_map(em);
4384                         }
4385                         start = extent_map_end(em);
4386                         write_unlock(&map->lock);
4387
4388                         /* once for us */
4389                         free_extent_map(em);
4390
4391                         cond_resched(); /* Allow large-extent preemption. */
4392                 }
4393         }
4394         return try_release_extent_state(tree, page, mask);
4395 }
4396
4397 /*
4398  * helper function for fiemap, which doesn't want to see any holes.
4399  * This maps until we find something past 'last'
4400  */
4401 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4402                                                 u64 offset, u64 last)
4403 {
4404         u64 sectorsize = btrfs_inode_sectorsize(inode);
4405         struct extent_map *em;
4406         u64 len;
4407
4408         if (offset >= last)
4409                 return NULL;
4410
4411         while (1) {
4412                 len = last - offset;
4413                 if (len == 0)
4414                         break;
4415                 len = ALIGN(len, sectorsize);
4416                 em = btrfs_get_extent_fiemap(BTRFS_I(inode), NULL, 0, offset,
4417                                 len, 0);
4418                 if (IS_ERR_OR_NULL(em))
4419                         return em;
4420
4421                 /* if this isn't a hole return it */
4422                 if (em->block_start != EXTENT_MAP_HOLE)
4423                         return em;
4424
4425                 /* this is a hole, advance to the next extent */
4426                 offset = extent_map_end(em);
4427                 free_extent_map(em);
4428                 if (offset >= last)
4429                         break;
4430         }
4431         return NULL;
4432 }
4433
4434 /*
4435  * To cache previous fiemap extent
4436  *
4437  * Will be used for merging fiemap extent
4438  */
4439 struct fiemap_cache {
4440         u64 offset;
4441         u64 phys;
4442         u64 len;
4443         u32 flags;
4444         bool cached;
4445 };
4446
4447 /*
4448  * Helper to submit fiemap extent.
4449  *
4450  * Will try to merge current fiemap extent specified by @offset, @phys,
4451  * @len and @flags with cached one.
4452  * And only when we fails to merge, cached one will be submitted as
4453  * fiemap extent.
4454  *
4455  * Return value is the same as fiemap_fill_next_extent().
4456  */
4457 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4458                                 struct fiemap_cache *cache,
4459                                 u64 offset, u64 phys, u64 len, u32 flags)
4460 {
4461         int ret = 0;
4462
4463         if (!cache->cached)
4464                 goto assign;
4465
4466         /*
4467          * Sanity check, extent_fiemap() should have ensured that new
4468          * fiemap extent won't overlap with cahced one.
4469          * Not recoverable.
4470          *
4471          * NOTE: Physical address can overlap, due to compression
4472          */
4473         if (cache->offset + cache->len > offset) {
4474                 WARN_ON(1);
4475                 return -EINVAL;
4476         }
4477
4478         /*
4479          * Only merges fiemap extents if
4480          * 1) Their logical addresses are continuous
4481          *
4482          * 2) Their physical addresses are continuous
4483          *    So truly compressed (physical size smaller than logical size)
4484          *    extents won't get merged with each other
4485          *
4486          * 3) Share same flags except FIEMAP_EXTENT_LAST
4487          *    So regular extent won't get merged with prealloc extent
4488          */
4489         if (cache->offset + cache->len  == offset &&
4490             cache->phys + cache->len == phys  &&
4491             (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4492                         (flags & ~FIEMAP_EXTENT_LAST)) {
4493                 cache->len += len;
4494                 cache->flags |= flags;
4495                 goto try_submit_last;
4496         }
4497
4498         /* Not mergeable, need to submit cached one */
4499         ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4500                                       cache->len, cache->flags);
4501         cache->cached = false;
4502         if (ret)
4503                 return ret;
4504 assign:
4505         cache->cached = true;
4506         cache->offset = offset;
4507         cache->phys = phys;
4508         cache->len = len;
4509         cache->flags = flags;
4510 try_submit_last:
4511         if (cache->flags & FIEMAP_EXTENT_LAST) {
4512                 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4513                                 cache->phys, cache->len, cache->flags);
4514                 cache->cached = false;
4515         }
4516         return ret;
4517 }
4518
4519 /*
4520  * Emit last fiemap cache
4521  *
4522  * The last fiemap cache may still be cached in the following case:
4523  * 0                  4k                    8k
4524  * |<- Fiemap range ->|
4525  * |<------------  First extent ----------->|
4526  *
4527  * In this case, the first extent range will be cached but not emitted.
4528  * So we must emit it before ending extent_fiemap().
4529  */
4530 static int emit_last_fiemap_cache(struct btrfs_fs_info *fs_info,
4531                                   struct fiemap_extent_info *fieinfo,
4532                                   struct fiemap_cache *cache)
4533 {
4534         int ret;
4535
4536         if (!cache->cached)
4537                 return 0;
4538
4539         ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4540                                       cache->len, cache->flags);
4541         cache->cached = false;
4542         if (ret > 0)
4543                 ret = 0;
4544         return ret;
4545 }
4546
4547 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4548                 __u64 start, __u64 len)
4549 {
4550         int ret = 0;
4551         u64 off = start;
4552         u64 max = start + len;
4553         u32 flags = 0;
4554         u32 found_type;
4555         u64 last;
4556         u64 last_for_get_extent = 0;
4557         u64 disko = 0;
4558         u64 isize = i_size_read(inode);
4559         struct btrfs_key found_key;
4560         struct extent_map *em = NULL;
4561         struct extent_state *cached_state = NULL;
4562         struct btrfs_path *path;
4563         struct btrfs_root *root = BTRFS_I(inode)->root;
4564         struct fiemap_cache cache = { 0 };
4565         int end = 0;
4566         u64 em_start = 0;
4567         u64 em_len = 0;
4568         u64 em_end = 0;
4569
4570         if (len == 0)
4571                 return -EINVAL;
4572
4573         path = btrfs_alloc_path();
4574         if (!path)
4575                 return -ENOMEM;
4576         path->leave_spinning = 1;
4577
4578         start = round_down(start, btrfs_inode_sectorsize(inode));
4579         len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4580
4581         /*
4582          * lookup the last file extent.  We're not using i_size here
4583          * because there might be preallocation past i_size
4584          */
4585         ret = btrfs_lookup_file_extent(NULL, root, path,
4586                         btrfs_ino(BTRFS_I(inode)), -1, 0);
4587         if (ret < 0) {
4588                 btrfs_free_path(path);
4589                 return ret;
4590         } else {
4591                 WARN_ON(!ret);
4592                 if (ret == 1)
4593                         ret = 0;
4594         }
4595
4596         path->slots[0]--;
4597         btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4598         found_type = found_key.type;
4599
4600         /* No extents, but there might be delalloc bits */
4601         if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4602             found_type != BTRFS_EXTENT_DATA_KEY) {
4603                 /* have to trust i_size as the end */
4604                 last = (u64)-1;
4605                 last_for_get_extent = isize;
4606         } else {
4607                 /*
4608                  * remember the start of the last extent.  There are a
4609                  * bunch of different factors that go into the length of the
4610                  * extent, so its much less complex to remember where it started
4611                  */
4612                 last = found_key.offset;
4613                 last_for_get_extent = last + 1;
4614         }
4615         btrfs_release_path(path);
4616
4617         /*
4618          * we might have some extents allocated but more delalloc past those
4619          * extents.  so, we trust isize unless the start of the last extent is
4620          * beyond isize
4621          */
4622         if (last < isize) {
4623                 last = (u64)-1;
4624                 last_for_get_extent = isize;
4625         }
4626
4627         lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4628                          &cached_state);
4629
4630         em = get_extent_skip_holes(inode, start, last_for_get_extent);
4631         if (!em)
4632                 goto out;
4633         if (IS_ERR(em)) {
4634                 ret = PTR_ERR(em);
4635                 goto out;
4636         }
4637
4638         while (!end) {
4639                 u64 offset_in_extent = 0;
4640
4641                 /* break if the extent we found is outside the range */
4642                 if (em->start >= max || extent_map_end(em) < off)
4643                         break;
4644
4645                 /*
4646                  * get_extent may return an extent that starts before our
4647                  * requested range.  We have to make sure the ranges
4648                  * we return to fiemap always move forward and don't
4649                  * overlap, so adjust the offsets here
4650                  */
4651                 em_start = max(em->start, off);
4652
4653                 /*
4654                  * record the offset from the start of the extent
4655                  * for adjusting the disk offset below.  Only do this if the
4656                  * extent isn't compressed since our in ram offset may be past
4657                  * what we have actually allocated on disk.
4658                  */
4659                 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4660                         offset_in_extent = em_start - em->start;
4661                 em_end = extent_map_end(em);
4662                 em_len = em_end - em_start;
4663                 flags = 0;
4664                 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4665                         disko = em->block_start + offset_in_extent;
4666                 else
4667                         disko = 0;
4668
4669                 /*
4670                  * bump off for our next call to get_extent
4671                  */
4672                 off = extent_map_end(em);
4673                 if (off >= max)
4674                         end = 1;
4675
4676                 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4677                         end = 1;
4678                         flags |= FIEMAP_EXTENT_LAST;
4679                 } else if (em->block_start == EXTENT_MAP_INLINE) {
4680                         flags |= (FIEMAP_EXTENT_DATA_INLINE |
4681                                   FIEMAP_EXTENT_NOT_ALIGNED);
4682                 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4683                         flags |= (FIEMAP_EXTENT_DELALLOC |
4684                                   FIEMAP_EXTENT_UNKNOWN);
4685                 } else if (fieinfo->fi_extents_max) {
4686                         u64 bytenr = em->block_start -
4687                                 (em->start - em->orig_start);
4688
4689                         /*
4690                          * As btrfs supports shared space, this information
4691                          * can be exported to userspace tools via
4692                          * flag FIEMAP_EXTENT_SHARED.  If fi_extents_max == 0
4693                          * then we're just getting a count and we can skip the
4694                          * lookup stuff.
4695                          */
4696                         ret = btrfs_check_shared(root,
4697                                                  btrfs_ino(BTRFS_I(inode)),
4698                                                  bytenr);
4699                         if (ret < 0)
4700                                 goto out_free;
4701                         if (ret)
4702                                 flags |= FIEMAP_EXTENT_SHARED;
4703                         ret = 0;
4704                 }
4705                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4706                         flags |= FIEMAP_EXTENT_ENCODED;
4707                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4708                         flags |= FIEMAP_EXTENT_UNWRITTEN;
4709
4710                 free_extent_map(em);
4711                 em = NULL;
4712                 if ((em_start >= last) || em_len == (u64)-1 ||
4713                    (last == (u64)-1 && isize <= em_end)) {
4714                         flags |= FIEMAP_EXTENT_LAST;
4715                         end = 1;
4716                 }
4717
4718                 /* now scan forward to see if this is really the last extent. */
4719                 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4720                 if (IS_ERR(em)) {
4721                         ret = PTR_ERR(em);
4722                         goto out;
4723                 }
4724                 if (!em) {
4725                         flags |= FIEMAP_EXTENT_LAST;
4726                         end = 1;
4727                 }
4728                 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4729                                            em_len, flags);
4730                 if (ret) {
4731                         if (ret == 1)
4732                                 ret = 0;
4733                         goto out_free;
4734                 }
4735         }
4736 out_free:
4737         if (!ret)
4738                 ret = emit_last_fiemap_cache(root->fs_info, fieinfo, &cache);
4739         free_extent_map(em);
4740 out:
4741         btrfs_free_path(path);
4742         unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4743                              &cached_state);
4744         return ret;
4745 }
4746
4747 static void __free_extent_buffer(struct extent_buffer *eb)
4748 {
4749         btrfs_leak_debug_del(&eb->leak_list);
4750         kmem_cache_free(extent_buffer_cache, eb);
4751 }
4752
4753 int extent_buffer_under_io(struct extent_buffer *eb)
4754 {
4755         return (atomic_read(&eb->io_pages) ||
4756                 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4757                 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4758 }
4759
4760 /*
4761  * Release all pages attached to the extent buffer.
4762  */
4763 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4764 {
4765         int i;
4766         int num_pages;
4767         int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4768
4769         BUG_ON(extent_buffer_under_io(eb));
4770
4771         num_pages = num_extent_pages(eb);
4772         for (i = 0; i < num_pages; i++) {
4773                 struct page *page = eb->pages[i];
4774
4775                 if (!page)
4776                         continue;
4777                 if (mapped)
4778                         spin_lock(&page->mapping->private_lock);
4779                 /*
4780                  * We do this since we'll remove the pages after we've
4781                  * removed the eb from the radix tree, so we could race
4782                  * and have this page now attached to the new eb.  So
4783                  * only clear page_private if it's still connected to
4784                  * this eb.
4785                  */
4786                 if (PagePrivate(page) &&
4787                     page->private == (unsigned long)eb) {
4788                         BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4789                         BUG_ON(PageDirty(page));
4790                         BUG_ON(PageWriteback(page));
4791                         /*
4792                          * We need to make sure we haven't be attached
4793                          * to a new eb.
4794                          */
4795                         ClearPagePrivate(page);
4796                         set_page_private(page, 0);
4797                         /* One for the page private */
4798                         put_page(page);
4799                 }
4800
4801                 if (mapped)
4802                         spin_unlock(&page->mapping->private_lock);
4803
4804                 /* One for when we allocated the page */
4805                 put_page(page);
4806         }
4807 }
4808
4809 /*
4810  * Helper for releasing the extent buffer.
4811  */
4812 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4813 {
4814         btrfs_release_extent_buffer_pages(eb);
4815         __free_extent_buffer(eb);
4816 }
4817
4818 static struct extent_buffer *
4819 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4820                       unsigned long len)
4821 {
4822         struct extent_buffer *eb = NULL;
4823
4824         eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4825         eb->start = start;
4826         eb->len = len;
4827         eb->fs_info = fs_info;
4828         eb->bflags = 0;
4829         rwlock_init(&eb->lock);
4830         atomic_set(&eb->write_locks, 0);
4831         atomic_set(&eb->read_locks, 0);
4832         atomic_set(&eb->blocking_readers, 0);
4833         atomic_set(&eb->blocking_writers, 0);
4834         atomic_set(&eb->spinning_readers, 0);
4835         atomic_set(&eb->spinning_writers, 0);
4836         eb->lock_nested = 0;
4837         init_waitqueue_head(&eb->write_lock_wq);
4838         init_waitqueue_head(&eb->read_lock_wq);
4839
4840         btrfs_leak_debug_add(&eb->leak_list, &buffers);
4841
4842         spin_lock_init(&eb->refs_lock);
4843         atomic_set(&eb->refs, 1);
4844         atomic_set(&eb->io_pages, 0);
4845
4846         /*
4847          * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4848          */
4849         BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4850                 > MAX_INLINE_EXTENT_BUFFER_SIZE);
4851         BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4852
4853         return eb;
4854 }
4855
4856 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4857 {
4858         int i;
4859         struct page *p;
4860         struct extent_buffer *new;
4861         int num_pages = num_extent_pages(src);
4862
4863         new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4864         if (new == NULL)
4865                 return NULL;
4866
4867         for (i = 0; i < num_pages; i++) {
4868                 p = alloc_page(GFP_NOFS);
4869                 if (!p) {
4870                         btrfs_release_extent_buffer(new);
4871                         return NULL;
4872                 }
4873                 attach_extent_buffer_page(new, p);
4874                 WARN_ON(PageDirty(p));
4875                 SetPageUptodate(p);
4876                 new->pages[i] = p;
4877                 copy_page(page_address(p), page_address(src->pages[i]));
4878         }
4879
4880         set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4881         set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4882
4883         return new;
4884 }
4885
4886 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4887                                                   u64 start, unsigned long len)
4888 {
4889         struct extent_buffer *eb;
4890         int num_pages;
4891         int i;
4892
4893         eb = __alloc_extent_buffer(fs_info, start, len);
4894         if (!eb)
4895                 return NULL;
4896
4897         num_pages = num_extent_pages(eb);
4898         for (i = 0; i < num_pages; i++) {
4899                 eb->pages[i] = alloc_page(GFP_NOFS);
4900                 if (!eb->pages[i])
4901                         goto err;
4902         }
4903         set_extent_buffer_uptodate(eb);
4904         btrfs_set_header_nritems(eb, 0);
4905         set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4906
4907         return eb;
4908 err:
4909         for (; i > 0; i--)
4910                 __free_page(eb->pages[i - 1]);
4911         __free_extent_buffer(eb);
4912         return NULL;
4913 }
4914
4915 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4916                                                 u64 start)
4917 {
4918         return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4919 }
4920
4921 static void check_buffer_tree_ref(struct extent_buffer *eb)
4922 {
4923         int refs;
4924         /*
4925          * The TREE_REF bit is first set when the extent_buffer is added
4926          * to the radix tree. It is also reset, if unset, when a new reference
4927          * is created by find_extent_buffer.
4928          *
4929          * It is only cleared in two cases: freeing the last non-tree
4930          * reference to the extent_buffer when its STALE bit is set or
4931          * calling releasepage when the tree reference is the only reference.
4932          *
4933          * In both cases, care is taken to ensure that the extent_buffer's
4934          * pages are not under io. However, releasepage can be concurrently
4935          * called with creating new references, which is prone to race
4936          * conditions between the calls to check_buffer_tree_ref in those
4937          * codepaths and clearing TREE_REF in try_release_extent_buffer.
4938          *
4939          * The actual lifetime of the extent_buffer in the radix tree is
4940          * adequately protected by the refcount, but the TREE_REF bit and
4941          * its corresponding reference are not. To protect against this
4942          * class of races, we call check_buffer_tree_ref from the codepaths
4943          * which trigger io after they set eb->io_pages. Note that once io is
4944          * initiated, TREE_REF can no longer be cleared, so that is the
4945          * moment at which any such race is best fixed.
4946          */
4947         refs = atomic_read(&eb->refs);
4948         if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4949                 return;
4950
4951         spin_lock(&eb->refs_lock);
4952         if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4953                 atomic_inc(&eb->refs);
4954         spin_unlock(&eb->refs_lock);
4955 }
4956
4957 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4958                 struct page *accessed)
4959 {
4960         int num_pages, i;
4961
4962         check_buffer_tree_ref(eb);
4963
4964         num_pages = num_extent_pages(eb);
4965         for (i = 0; i < num_pages; i++) {
4966                 struct page *p = eb->pages[i];
4967
4968                 if (p != accessed)
4969                         mark_page_accessed(p);
4970         }
4971 }
4972
4973 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4974                                          u64 start)
4975 {
4976         struct extent_buffer *eb;
4977
4978         rcu_read_lock();
4979         eb = radix_tree_lookup(&fs_info->buffer_radix,
4980                                start >> PAGE_SHIFT);
4981         if (eb && atomic_inc_not_zero(&eb->refs)) {
4982                 rcu_read_unlock();
4983                 /*
4984                  * Lock our eb's refs_lock to avoid races with
4985                  * free_extent_buffer. When we get our eb it might be flagged
4986                  * with EXTENT_BUFFER_STALE and another task running
4987                  * free_extent_buffer might have seen that flag set,
4988                  * eb->refs == 2, that the buffer isn't under IO (dirty and
4989                  * writeback flags not set) and it's still in the tree (flag
4990                  * EXTENT_BUFFER_TREE_REF set), therefore being in the process
4991                  * of decrementing the extent buffer's reference count twice.
4992                  * So here we could race and increment the eb's reference count,
4993                  * clear its stale flag, mark it as dirty and drop our reference
4994                  * before the other task finishes executing free_extent_buffer,
4995                  * which would later result in an attempt to free an extent
4996                  * buffer that is dirty.
4997                  */
4998                 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4999                         spin_lock(&eb->refs_lock);
5000                         spin_unlock(&eb->refs_lock);
5001                 }
5002                 mark_extent_buffer_accessed(eb, NULL);
5003                 return eb;
5004         }
5005         rcu_read_unlock();
5006
5007         return NULL;
5008 }
5009
5010 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5011 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5012                                         u64 start)
5013 {
5014         struct extent_buffer *eb, *exists = NULL;
5015         int ret;
5016
5017         eb = find_extent_buffer(fs_info, start);
5018         if (eb)
5019                 return eb;
5020         eb = alloc_dummy_extent_buffer(fs_info, start);
5021         if (!eb)
5022                 return ERR_PTR(-ENOMEM);
5023         eb->fs_info = fs_info;
5024 again:
5025         ret = radix_tree_preload(GFP_NOFS);
5026         if (ret) {
5027                 exists = ERR_PTR(ret);
5028                 goto free_eb;
5029         }
5030         spin_lock(&fs_info->buffer_lock);
5031         ret = radix_tree_insert(&fs_info->buffer_radix,
5032                                 start >> PAGE_SHIFT, eb);
5033         spin_unlock(&fs_info->buffer_lock);
5034         radix_tree_preload_end();
5035         if (ret == -EEXIST) {
5036                 exists = find_extent_buffer(fs_info, start);
5037                 if (exists)
5038                         goto free_eb;
5039                 else
5040                         goto again;
5041         }
5042         check_buffer_tree_ref(eb);
5043         set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5044
5045         /*
5046          * We will free dummy extent buffer's if they come into
5047          * free_extent_buffer with a ref count of 2, but if we are using this we
5048          * want the buffers to stay in memory until we're done with them, so
5049          * bump the ref count again.
5050          */
5051         atomic_inc(&eb->refs);
5052         return eb;
5053 free_eb:
5054         btrfs_release_extent_buffer(eb);
5055         return exists;
5056 }
5057 #endif
5058
5059 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5060                                           u64 start)
5061 {
5062         unsigned long len = fs_info->nodesize;
5063         int num_pages;
5064         int i;
5065         unsigned long index = start >> PAGE_SHIFT;
5066         struct extent_buffer *eb;
5067         struct extent_buffer *exists = NULL;
5068         struct page *p;
5069         struct address_space *mapping = fs_info->btree_inode->i_mapping;
5070         int uptodate = 1;
5071         int ret;
5072
5073         if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5074                 btrfs_err(fs_info, "bad tree block start %llu", start);
5075                 return ERR_PTR(-EINVAL);
5076         }
5077
5078         eb = find_extent_buffer(fs_info, start);
5079         if (eb)
5080                 return eb;
5081
5082         eb = __alloc_extent_buffer(fs_info, start, len);
5083         if (!eb)
5084                 return ERR_PTR(-ENOMEM);
5085
5086         num_pages = num_extent_pages(eb);
5087         for (i = 0; i < num_pages; i++, index++) {
5088                 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5089                 if (!p) {
5090                         exists = ERR_PTR(-ENOMEM);
5091                         goto free_eb;
5092                 }
5093
5094                 spin_lock(&mapping->private_lock);
5095                 if (PagePrivate(p)) {
5096                         /*
5097                          * We could have already allocated an eb for this page
5098                          * and attached one so lets see if we can get a ref on
5099                          * the existing eb, and if we can we know it's good and
5100                          * we can just return that one, else we know we can just
5101                          * overwrite page->private.
5102                          */
5103                         exists = (struct extent_buffer *)p->private;
5104                         if (atomic_inc_not_zero(&exists->refs)) {
5105                                 spin_unlock(&mapping->private_lock);
5106                                 unlock_page(p);
5107                                 put_page(p);
5108                                 mark_extent_buffer_accessed(exists, p);
5109                                 goto free_eb;
5110                         }
5111                         exists = NULL;
5112
5113                         /*
5114                          * Do this so attach doesn't complain and we need to
5115                          * drop the ref the old guy had.
5116                          */
5117                         ClearPagePrivate(p);
5118                         WARN_ON(PageDirty(p));
5119                         put_page(p);
5120                 }
5121                 attach_extent_buffer_page(eb, p);
5122                 spin_unlock(&mapping->private_lock);
5123                 WARN_ON(PageDirty(p));
5124                 eb->pages[i] = p;
5125                 if (!PageUptodate(p))
5126                         uptodate = 0;
5127
5128                 /*
5129                  * We can't unlock the pages just yet since the extent buffer
5130                  * hasn't been properly inserted in the radix tree, this
5131                  * opens a race with btree_releasepage which can free a page
5132                  * while we are still filling in all pages for the buffer and
5133                  * we could crash.
5134                  */
5135         }
5136         if (uptodate)
5137                 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5138 again:
5139         ret = radix_tree_preload(GFP_NOFS);
5140         if (ret) {
5141                 exists = ERR_PTR(ret);
5142                 goto free_eb;
5143         }
5144
5145         spin_lock(&fs_info->buffer_lock);
5146         ret = radix_tree_insert(&fs_info->buffer_radix,
5147                                 start >> PAGE_SHIFT, eb);
5148         spin_unlock(&fs_info->buffer_lock);
5149         radix_tree_preload_end();
5150         if (ret == -EEXIST) {
5151                 exists = find_extent_buffer(fs_info, start);
5152                 if (exists)
5153                         goto free_eb;
5154                 else
5155                         goto again;
5156         }
5157         /* add one reference for the tree */
5158         check_buffer_tree_ref(eb);
5159         set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5160
5161         /*
5162          * Now it's safe to unlock the pages because any calls to
5163          * btree_releasepage will correctly detect that a page belongs to a
5164          * live buffer and won't free them prematurely.
5165          */
5166         for (i = 0; i < num_pages; i++)
5167                 unlock_page(eb->pages[i]);
5168         return eb;
5169
5170 free_eb:
5171         WARN_ON(!atomic_dec_and_test(&eb->refs));
5172         for (i = 0; i < num_pages; i++) {
5173                 if (eb->pages[i])
5174                         unlock_page(eb->pages[i]);
5175         }
5176
5177         btrfs_release_extent_buffer(eb);
5178         return exists;
5179 }
5180
5181 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5182 {
5183         struct extent_buffer *eb =
5184                         container_of(head, struct extent_buffer, rcu_head);
5185
5186         __free_extent_buffer(eb);
5187 }
5188
5189 static int release_extent_buffer(struct extent_buffer *eb)
5190 {
5191         lockdep_assert_held(&eb->refs_lock);
5192
5193         WARN_ON(atomic_read(&eb->refs) == 0);
5194         if (atomic_dec_and_test(&eb->refs)) {
5195                 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5196                         struct btrfs_fs_info *fs_info = eb->fs_info;
5197
5198                         spin_unlock(&eb->refs_lock);
5199
5200                         spin_lock(&fs_info->buffer_lock);
5201                         radix_tree_delete(&fs_info->buffer_radix,
5202                                           eb->start >> PAGE_SHIFT);
5203                         spin_unlock(&fs_info->buffer_lock);
5204                 } else {
5205                         spin_unlock(&eb->refs_lock);
5206                 }
5207
5208                 /* Should be safe to release our pages at this point */
5209                 btrfs_release_extent_buffer_pages(eb);
5210 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5211                 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5212                         __free_extent_buffer(eb);
5213                         return 1;
5214                 }
5215 #endif
5216                 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5217                 return 1;
5218         }
5219         spin_unlock(&eb->refs_lock);
5220
5221         return 0;
5222 }
5223
5224 void free_extent_buffer(struct extent_buffer *eb)
5225 {
5226         int refs;
5227         int old;
5228         if (!eb)
5229                 return;
5230
5231         while (1) {
5232                 refs = atomic_read(&eb->refs);
5233                 if (refs <= 3)
5234                         break;
5235                 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5236                 if (old == refs)
5237                         return;
5238         }
5239
5240         spin_lock(&eb->refs_lock);
5241         if (atomic_read(&eb->refs) == 2 &&
5242             test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))
5243                 atomic_dec(&eb->refs);
5244
5245         if (atomic_read(&eb->refs) == 2 &&
5246             test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5247             !extent_buffer_under_io(eb) &&
5248             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5249                 atomic_dec(&eb->refs);
5250
5251         /*
5252          * I know this is terrible, but it's temporary until we stop tracking
5253          * the uptodate bits and such for the extent buffers.
5254          */
5255         release_extent_buffer(eb);
5256 }
5257
5258 void free_extent_buffer_stale(struct extent_buffer *eb)
5259 {
5260         if (!eb)
5261                 return;
5262
5263         spin_lock(&eb->refs_lock);
5264         set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5265
5266         if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5267             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5268                 atomic_dec(&eb->refs);
5269         release_extent_buffer(eb);
5270 }
5271
5272 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5273 {
5274         int i;
5275         int num_pages;
5276         struct page *page;
5277
5278         num_pages = num_extent_pages(eb);
5279
5280         for (i = 0; i < num_pages; i++) {
5281                 page = eb->pages[i];
5282                 if (!PageDirty(page))
5283                         continue;
5284
5285                 lock_page(page);
5286                 WARN_ON(!PagePrivate(page));
5287
5288                 clear_page_dirty_for_io(page);
5289                 xa_lock_irq(&page->mapping->i_pages);
5290                 if (!PageDirty(page)) {
5291                         radix_tree_tag_clear(&page->mapping->i_pages,
5292                                                 page_index(page),
5293                                                 PAGECACHE_TAG_DIRTY);
5294                 }
5295                 xa_unlock_irq(&page->mapping->i_pages);
5296                 ClearPageError(page);
5297                 unlock_page(page);
5298         }
5299         WARN_ON(atomic_read(&eb->refs) == 0);
5300 }
5301
5302 int set_extent_buffer_dirty(struct extent_buffer *eb)
5303 {
5304         int i;
5305         int num_pages;
5306         int was_dirty = 0;
5307
5308         check_buffer_tree_ref(eb);
5309
5310         was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5311
5312         num_pages = num_extent_pages(eb);
5313         WARN_ON(atomic_read(&eb->refs) == 0);
5314         WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5315
5316         for (i = 0; i < num_pages; i++)
5317                 set_page_dirty(eb->pages[i]);
5318         return was_dirty;
5319 }
5320
5321 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5322 {
5323         int i;
5324         struct page *page;
5325         int num_pages;
5326
5327         clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5328         num_pages = num_extent_pages(eb);
5329         for (i = 0; i < num_pages; i++) {
5330                 page = eb->pages[i];
5331                 if (page)
5332                         ClearPageUptodate(page);
5333         }
5334 }
5335
5336 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5337 {
5338         int i;
5339         struct page *page;
5340         int num_pages;
5341
5342         set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5343         num_pages = num_extent_pages(eb);
5344         for (i = 0; i < num_pages; i++) {
5345                 page = eb->pages[i];
5346                 SetPageUptodate(page);
5347         }
5348 }
5349
5350 int read_extent_buffer_pages(struct extent_io_tree *tree,
5351                              struct extent_buffer *eb, int wait, int mirror_num)
5352 {
5353         int i;
5354         struct page *page;
5355         int err;
5356         int ret = 0;
5357         int locked_pages = 0;
5358         int all_uptodate = 1;
5359         int num_pages;
5360         unsigned long num_reads = 0;
5361         struct bio *bio = NULL;
5362         unsigned long bio_flags = 0;
5363
5364         if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5365                 return 0;
5366
5367         num_pages = num_extent_pages(eb);
5368         for (i = 0; i < num_pages; i++) {
5369                 page = eb->pages[i];
5370                 if (wait == WAIT_NONE) {
5371                         if (!trylock_page(page))
5372                                 goto unlock_exit;
5373                 } else {
5374                         lock_page(page);
5375                 }
5376                 locked_pages++;
5377         }
5378         /*
5379          * We need to firstly lock all pages to make sure that
5380          * the uptodate bit of our pages won't be affected by
5381          * clear_extent_buffer_uptodate().
5382          */
5383         for (i = 0; i < num_pages; i++) {
5384                 page = eb->pages[i];
5385                 if (!PageUptodate(page)) {
5386                         num_reads++;
5387                         all_uptodate = 0;
5388                 }
5389         }
5390
5391         if (all_uptodate) {
5392                 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5393                 goto unlock_exit;
5394         }
5395
5396         clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5397         eb->read_mirror = 0;
5398         atomic_set(&eb->io_pages, num_reads);
5399         /*
5400          * It is possible for releasepage to clear the TREE_REF bit before we
5401          * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5402          */
5403         check_buffer_tree_ref(eb);
5404         for (i = 0; i < num_pages; i++) {
5405                 page = eb->pages[i];
5406
5407                 if (!PageUptodate(page)) {
5408                         if (ret) {
5409                                 atomic_dec(&eb->io_pages);
5410                                 unlock_page(page);
5411                                 continue;
5412                         }
5413
5414                         ClearPageError(page);
5415                         err = __extent_read_full_page(tree, page,
5416                                                       btree_get_extent, &bio,
5417                                                       mirror_num, &bio_flags,
5418                                                       REQ_META);
5419                         if (err) {
5420                                 ret = err;
5421                                 /*
5422                                  * We use &bio in above __extent_read_full_page,
5423                                  * so we ensure that if it returns error, the
5424                                  * current page fails to add itself to bio and
5425                                  * it's been unlocked.
5426                                  *
5427                                  * We must dec io_pages by ourselves.
5428                                  */
5429                                 atomic_dec(&eb->io_pages);
5430                         }
5431                 } else {
5432                         unlock_page(page);
5433                 }
5434         }
5435
5436         if (bio) {
5437                 err = submit_one_bio(bio, mirror_num, bio_flags);
5438                 if (err)
5439                         return err;
5440         }
5441
5442         if (ret || wait != WAIT_COMPLETE)
5443                 return ret;
5444
5445         for (i = 0; i < num_pages; i++) {
5446                 page = eb->pages[i];
5447                 wait_on_page_locked(page);
5448                 if (!PageUptodate(page))
5449                         ret = -EIO;
5450         }
5451
5452         return ret;
5453
5454 unlock_exit:
5455         while (locked_pages > 0) {
5456                 locked_pages--;
5457                 page = eb->pages[locked_pages];
5458                 unlock_page(page);
5459         }
5460         return ret;
5461 }
5462
5463 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5464                         unsigned long start, unsigned long len)
5465 {
5466         size_t cur;
5467         size_t offset;
5468         struct page *page;
5469         char *kaddr;
5470         char *dst = (char *)dstv;
5471         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5472         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5473
5474         if (start + len > eb->len) {
5475                 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5476                      eb->start, eb->len, start, len);
5477                 memset(dst, 0, len);
5478                 return;
5479         }
5480
5481         offset = (start_offset + start) & (PAGE_SIZE - 1);
5482
5483         while (len > 0) {
5484                 page = eb->pages[i];
5485
5486                 cur = min(len, (PAGE_SIZE - offset));
5487                 kaddr = page_address(page);
5488                 memcpy(dst, kaddr + offset, cur);
5489
5490                 dst += cur;
5491                 len -= cur;
5492                 offset = 0;
5493                 i++;
5494         }
5495 }
5496
5497 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5498                                        void __user *dstv,
5499                                        unsigned long start, unsigned long len)
5500 {
5501         size_t cur;
5502         size_t offset;
5503         struct page *page;
5504         char *kaddr;
5505         char __user *dst = (char __user *)dstv;
5506         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5507         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5508         int ret = 0;
5509
5510         WARN_ON(start > eb->len);
5511         WARN_ON(start + len > eb->start + eb->len);
5512
5513         offset = (start_offset + start) & (PAGE_SIZE - 1);
5514
5515         while (len > 0) {
5516                 page = eb->pages[i];
5517
5518                 cur = min(len, (PAGE_SIZE - offset));
5519                 kaddr = page_address(page);
5520                 if (probe_user_write(dst, kaddr + offset, cur)) {
5521                         ret = -EFAULT;
5522                         break;
5523                 }
5524
5525                 dst += cur;
5526                 len -= cur;
5527                 offset = 0;
5528                 i++;
5529         }
5530
5531         return ret;
5532 }
5533
5534 /*
5535  * return 0 if the item is found within a page.
5536  * return 1 if the item spans two pages.
5537  * return -EINVAL otherwise.
5538  */
5539 int map_private_extent_buffer(const struct extent_buffer *eb,
5540                               unsigned long start, unsigned long min_len,
5541                               char **map, unsigned long *map_start,
5542                               unsigned long *map_len)
5543 {
5544         size_t offset = start & (PAGE_SIZE - 1);
5545         char *kaddr;
5546         struct page *p;
5547         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5548         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5549         unsigned long end_i = (start_offset + start + min_len - 1) >>
5550                 PAGE_SHIFT;
5551
5552         if (start + min_len > eb->len) {
5553                 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5554                        eb->start, eb->len, start, min_len);
5555                 return -EINVAL;
5556         }
5557
5558         if (i != end_i)
5559                 return 1;
5560
5561         if (i == 0) {
5562                 offset = start_offset;
5563                 *map_start = 0;
5564         } else {
5565                 offset = 0;
5566                 *map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5567         }
5568
5569         p = eb->pages[i];
5570         kaddr = page_address(p);
5571         *map = kaddr + offset;
5572         *map_len = PAGE_SIZE - offset;
5573         return 0;
5574 }
5575
5576 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5577                          unsigned long start, unsigned long len)
5578 {
5579         size_t cur;
5580         size_t offset;
5581         struct page *page;
5582         char *kaddr;
5583         char *ptr = (char *)ptrv;
5584         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5585         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5586         int ret = 0;
5587
5588         WARN_ON(start > eb->len);
5589         WARN_ON(start + len > eb->start + eb->len);
5590
5591         offset = (start_offset + start) & (PAGE_SIZE - 1);
5592
5593         while (len > 0) {
5594                 page = eb->pages[i];
5595
5596                 cur = min(len, (PAGE_SIZE - offset));
5597
5598                 kaddr = page_address(page);
5599                 ret = memcmp(ptr, kaddr + offset, cur);
5600                 if (ret)
5601                         break;
5602
5603                 ptr += cur;
5604                 len -= cur;
5605                 offset = 0;
5606                 i++;
5607         }
5608         return ret;
5609 }
5610
5611 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5612                 const void *srcv)
5613 {
5614         char *kaddr;
5615
5616         WARN_ON(!PageUptodate(eb->pages[0]));
5617         kaddr = page_address(eb->pages[0]);
5618         memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5619                         BTRFS_FSID_SIZE);
5620 }
5621
5622 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5623 {
5624         char *kaddr;
5625
5626         WARN_ON(!PageUptodate(eb->pages[0]));
5627         kaddr = page_address(eb->pages[0]);
5628         memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5629                         BTRFS_FSID_SIZE);
5630 }
5631
5632 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5633                          unsigned long start, unsigned long len)
5634 {
5635         size_t cur;
5636         size_t offset;
5637         struct page *page;
5638         char *kaddr;
5639         char *src = (char *)srcv;
5640         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5641         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5642
5643         WARN_ON(start > eb->len);
5644         WARN_ON(start + len > eb->start + eb->len);
5645
5646         offset = (start_offset + start) & (PAGE_SIZE - 1);
5647
5648         while (len > 0) {
5649                 page = eb->pages[i];
5650                 WARN_ON(!PageUptodate(page));
5651
5652                 cur = min(len, PAGE_SIZE - offset);
5653                 kaddr = page_address(page);
5654                 memcpy(kaddr + offset, src, cur);
5655
5656                 src += cur;
5657                 len -= cur;
5658                 offset = 0;
5659                 i++;
5660         }
5661 }
5662
5663 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5664                 unsigned long len)
5665 {
5666         size_t cur;
5667         size_t offset;
5668         struct page *page;
5669         char *kaddr;
5670         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5671         unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5672
5673         WARN_ON(start > eb->len);
5674         WARN_ON(start + len > eb->start + eb->len);
5675
5676         offset = (start_offset + start) & (PAGE_SIZE - 1);
5677
5678         while (len > 0) {
5679                 page = eb->pages[i];
5680                 WARN_ON(!PageUptodate(page));
5681
5682                 cur = min(len, PAGE_SIZE - offset);
5683                 kaddr = page_address(page);
5684                 memset(kaddr + offset, 0, cur);
5685
5686                 len -= cur;
5687                 offset = 0;
5688                 i++;
5689         }
5690 }
5691
5692 void copy_extent_buffer_full(struct extent_buffer *dst,
5693                              struct extent_buffer *src)
5694 {
5695         int i;
5696         int num_pages;
5697
5698         ASSERT(dst->len == src->len);
5699
5700         num_pages = num_extent_pages(dst);
5701         for (i = 0; i < num_pages; i++)
5702                 copy_page(page_address(dst->pages[i]),
5703                                 page_address(src->pages[i]));
5704 }
5705
5706 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5707                         unsigned long dst_offset, unsigned long src_offset,
5708                         unsigned long len)
5709 {
5710         u64 dst_len = dst->len;
5711         size_t cur;
5712         size_t offset;
5713         struct page *page;
5714         char *kaddr;
5715         size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5716         unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5717
5718         WARN_ON(src->len != dst_len);
5719
5720         offset = (start_offset + dst_offset) &
5721                 (PAGE_SIZE - 1);
5722
5723         while (len > 0) {
5724                 page = dst->pages[i];
5725                 WARN_ON(!PageUptodate(page));
5726
5727                 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5728
5729                 kaddr = page_address(page);
5730                 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5731
5732                 src_offset += cur;
5733                 len -= cur;
5734                 offset = 0;
5735                 i++;
5736         }
5737 }
5738
5739 /*
5740  * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5741  * given bit number
5742  * @eb: the extent buffer
5743  * @start: offset of the bitmap item in the extent buffer
5744  * @nr: bit number
5745  * @page_index: return index of the page in the extent buffer that contains the
5746  * given bit number
5747  * @page_offset: return offset into the page given by page_index
5748  *
5749  * This helper hides the ugliness of finding the byte in an extent buffer which
5750  * contains a given bit.
5751  */
5752 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5753                                     unsigned long start, unsigned long nr,
5754                                     unsigned long *page_index,
5755                                     size_t *page_offset)
5756 {
5757         size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5758         size_t byte_offset = BIT_BYTE(nr);
5759         size_t offset;
5760
5761         /*
5762          * The byte we want is the offset of the extent buffer + the offset of
5763          * the bitmap item in the extent buffer + the offset of the byte in the
5764          * bitmap item.
5765          */
5766         offset = start_offset + start + byte_offset;
5767
5768         *page_index = offset >> PAGE_SHIFT;
5769         *page_offset = offset & (PAGE_SIZE - 1);
5770 }
5771
5772 /**
5773  * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5774  * @eb: the extent buffer
5775  * @start: offset of the bitmap item in the extent buffer
5776  * @nr: bit number to test
5777  */
5778 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5779                            unsigned long nr)
5780 {
5781         u8 *kaddr;
5782         struct page *page;
5783         unsigned long i;
5784         size_t offset;
5785
5786         eb_bitmap_offset(eb, start, nr, &i, &offset);
5787         page = eb->pages[i];
5788         WARN_ON(!PageUptodate(page));
5789         kaddr = page_address(page);
5790         return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5791 }
5792
5793 /**
5794  * extent_buffer_bitmap_set - set an area of a bitmap
5795  * @eb: the extent buffer
5796  * @start: offset of the bitmap item in the extent buffer
5797  * @pos: bit number of the first bit
5798  * @len: number of bits to set
5799  */
5800 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5801                               unsigned long pos, unsigned long len)
5802 {
5803         u8 *kaddr;
5804         struct page *page;
5805         unsigned long i;
5806         size_t offset;
5807         const unsigned int size = pos + len;
5808         int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5809         u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5810
5811         eb_bitmap_offset(eb, start, pos, &i, &offset);
5812         page = eb->pages[i];
5813         WARN_ON(!PageUptodate(page));
5814         kaddr = page_address(page);
5815
5816         while (len >= bits_to_set) {
5817                 kaddr[offset] |= mask_to_set;
5818                 len -= bits_to_set;
5819                 bits_to_set = BITS_PER_BYTE;
5820                 mask_to_set = ~0;
5821                 if (++offset >= PAGE_SIZE && len > 0) {
5822                         offset = 0;
5823                         page = eb->pages[++i];
5824                         WARN_ON(!PageUptodate(page));
5825                         kaddr = page_address(page);
5826                 }
5827         }
5828         if (len) {
5829                 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5830                 kaddr[offset] |= mask_to_set;
5831         }
5832 }
5833
5834
5835 /**
5836  * extent_buffer_bitmap_clear - clear an area of a bitmap
5837  * @eb: the extent buffer
5838  * @start: offset of the bitmap item in the extent buffer
5839  * @pos: bit number of the first bit
5840  * @len: number of bits to clear
5841  */
5842 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5843                                 unsigned long pos, unsigned long len)
5844 {
5845         u8 *kaddr;
5846         struct page *page;
5847         unsigned long i;
5848         size_t offset;
5849         const unsigned int size = pos + len;
5850         int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5851         u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5852
5853         eb_bitmap_offset(eb, start, pos, &i, &offset);
5854         page = eb->pages[i];
5855         WARN_ON(!PageUptodate(page));
5856         kaddr = page_address(page);
5857
5858         while (len >= bits_to_clear) {
5859                 kaddr[offset] &= ~mask_to_clear;
5860                 len -= bits_to_clear;
5861                 bits_to_clear = BITS_PER_BYTE;
5862                 mask_to_clear = ~0;
5863                 if (++offset >= PAGE_SIZE && len > 0) {
5864                         offset = 0;
5865                         page = eb->pages[++i];
5866                         WARN_ON(!PageUptodate(page));
5867                         kaddr = page_address(page);
5868                 }
5869         }
5870         if (len) {
5871                 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5872                 kaddr[offset] &= ~mask_to_clear;
5873         }
5874 }
5875
5876 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5877 {
5878         unsigned long distance = (src > dst) ? src - dst : dst - src;
5879         return distance < len;
5880 }
5881
5882 static void copy_pages(struct page *dst_page, struct page *src_page,
5883                        unsigned long dst_off, unsigned long src_off,
5884                        unsigned long len)
5885 {
5886         char *dst_kaddr = page_address(dst_page);
5887         char *src_kaddr;
5888         int must_memmove = 0;
5889
5890         if (dst_page != src_page) {
5891                 src_kaddr = page_address(src_page);
5892         } else {
5893                 src_kaddr = dst_kaddr;
5894                 if (areas_overlap(src_off, dst_off, len))
5895                         must_memmove = 1;
5896         }
5897
5898         if (must_memmove)
5899                 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5900         else
5901                 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5902 }
5903
5904 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5905                            unsigned long src_offset, unsigned long len)
5906 {
5907         struct btrfs_fs_info *fs_info = dst->fs_info;
5908         size_t cur;
5909         size_t dst_off_in_page;
5910         size_t src_off_in_page;
5911         size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5912         unsigned long dst_i;
5913         unsigned long src_i;
5914
5915         if (src_offset + len > dst->len) {
5916                 btrfs_err(fs_info,
5917                         "memmove bogus src_offset %lu move len %lu dst len %lu",
5918                          src_offset, len, dst->len);
5919                 BUG_ON(1);
5920         }
5921         if (dst_offset + len > dst->len) {
5922                 btrfs_err(fs_info,
5923                         "memmove bogus dst_offset %lu move len %lu dst len %lu",
5924                          dst_offset, len, dst->len);
5925                 BUG_ON(1);
5926         }
5927
5928         while (len > 0) {
5929                 dst_off_in_page = (start_offset + dst_offset) &
5930                         (PAGE_SIZE - 1);
5931                 src_off_in_page = (start_offset + src_offset) &
5932                         (PAGE_SIZE - 1);
5933
5934                 dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
5935                 src_i = (start_offset + src_offset) >> PAGE_SHIFT;
5936
5937                 cur = min(len, (unsigned long)(PAGE_SIZE -
5938                                                src_off_in_page));
5939                 cur = min_t(unsigned long, cur,
5940                         (unsigned long)(PAGE_SIZE - dst_off_in_page));
5941
5942                 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5943                            dst_off_in_page, src_off_in_page, cur);
5944
5945                 src_offset += cur;
5946                 dst_offset += cur;
5947                 len -= cur;
5948         }
5949 }
5950
5951 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5952                            unsigned long src_offset, unsigned long len)
5953 {
5954         struct btrfs_fs_info *fs_info = dst->fs_info;
5955         size_t cur;
5956         size_t dst_off_in_page;
5957         size_t src_off_in_page;
5958         unsigned long dst_end = dst_offset + len - 1;
5959         unsigned long src_end = src_offset + len - 1;
5960         size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5961         unsigned long dst_i;
5962         unsigned long src_i;
5963
5964         if (src_offset + len > dst->len) {
5965                 btrfs_err(fs_info,
5966                           "memmove bogus src_offset %lu move len %lu len %lu",
5967                           src_offset, len, dst->len);
5968                 BUG_ON(1);
5969         }
5970         if (dst_offset + len > dst->len) {
5971                 btrfs_err(fs_info,
5972                           "memmove bogus dst_offset %lu move len %lu len %lu",
5973                           dst_offset, len, dst->len);
5974                 BUG_ON(1);
5975         }
5976         if (dst_offset < src_offset) {
5977                 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5978                 return;
5979         }
5980         while (len > 0) {
5981                 dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
5982                 src_i = (start_offset + src_end) >> PAGE_SHIFT;
5983
5984                 dst_off_in_page = (start_offset + dst_end) &
5985                         (PAGE_SIZE - 1);
5986                 src_off_in_page = (start_offset + src_end) &
5987                         (PAGE_SIZE - 1);
5988
5989                 cur = min_t(unsigned long, len, src_off_in_page + 1);
5990                 cur = min(cur, dst_off_in_page + 1);
5991                 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5992                            dst_off_in_page - cur + 1,
5993                            src_off_in_page - cur + 1, cur);
5994
5995                 dst_end -= cur;
5996                 src_end -= cur;
5997                 len -= cur;
5998         }
5999 }
6000
6001 int try_release_extent_buffer(struct page *page)
6002 {
6003         struct extent_buffer *eb;
6004
6005         /*
6006          * We need to make sure nobody is attaching this page to an eb right
6007          * now.
6008          */
6009         spin_lock(&page->mapping->private_lock);
6010         if (!PagePrivate(page)) {
6011                 spin_unlock(&page->mapping->private_lock);
6012                 return 1;
6013         }
6014
6015         eb = (struct extent_buffer *)page->private;
6016         BUG_ON(!eb);
6017
6018         /*
6019          * This is a little awful but should be ok, we need to make sure that
6020          * the eb doesn't disappear out from under us while we're looking at
6021          * this page.
6022          */
6023         spin_lock(&eb->refs_lock);
6024         if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6025                 spin_unlock(&eb->refs_lock);
6026                 spin_unlock(&page->mapping->private_lock);
6027                 return 0;
6028         }
6029         spin_unlock(&page->mapping->private_lock);
6030
6031         /*
6032          * If tree ref isn't set then we know the ref on this eb is a real ref,
6033          * so just return, this page will likely be freed soon anyway.
6034          */
6035         if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6036                 spin_unlock(&eb->refs_lock);
6037                 return 0;
6038         }
6039
6040         return release_extent_buffer(eb);
6041 }