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