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