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