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