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