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