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