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