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