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