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