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