1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.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>
18 #include "extent_io.h"
19 #include "extent-io-tree.h"
20 #include "extent_map.h"
22 #include "btrfs_inode.h"
25 #include "rcu-string.h"
30 #include "block-group.h"
31 #include "compression.h"
33 #include "accessors.h"
34 #include "file-item.h"
36 #include "dev-replace.h"
38 #include "transaction.h"
40 static struct kmem_cache *extent_buffer_cache;
42 #ifdef CONFIG_BTRFS_DEBUG
43 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
45 struct btrfs_fs_info *fs_info = eb->fs_info;
48 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
49 list_add(&eb->leak_list, &fs_info->allocated_ebs);
50 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
53 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
55 struct btrfs_fs_info *fs_info = eb->fs_info;
58 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
59 list_del(&eb->leak_list);
60 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
63 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
65 struct extent_buffer *eb;
69 * If we didn't get into open_ctree our allocated_ebs will not be
70 * initialized, so just skip this.
72 if (!fs_info->allocated_ebs.next)
75 WARN_ON(!list_empty(&fs_info->allocated_ebs));
76 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
77 while (!list_empty(&fs_info->allocated_ebs)) {
78 eb = list_first_entry(&fs_info->allocated_ebs,
79 struct extent_buffer, leak_list);
81 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
82 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
83 btrfs_header_owner(eb));
84 list_del(&eb->leak_list);
85 kmem_cache_free(extent_buffer_cache, eb);
87 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
90 #define btrfs_leak_debug_add_eb(eb) do {} while (0)
91 #define btrfs_leak_debug_del_eb(eb) do {} while (0)
95 * Structure to record info about the bio being assembled, and other info like
96 * how many bytes are there before stripe/ordered extent boundary.
98 struct btrfs_bio_ctrl {
99 struct btrfs_bio *bbio;
100 enum btrfs_compression_type compress_type;
101 u32 len_to_oe_boundary;
103 btrfs_bio_end_io_t end_io_func;
104 struct writeback_control *wbc;
107 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
109 struct btrfs_bio *bbio = bio_ctrl->bbio;
114 /* Caller should ensure the bio has at least some range added */
115 ASSERT(bbio->bio.bi_iter.bi_size);
117 if (btrfs_op(&bbio->bio) == BTRFS_MAP_READ &&
118 bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
119 btrfs_submit_compressed_read(bbio);
121 btrfs_submit_bio(bbio, 0);
123 /* The bbio is owned by the end_io handler now */
124 bio_ctrl->bbio = NULL;
128 * Submit or fail the current bio in the bio_ctrl structure.
130 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
132 struct btrfs_bio *bbio = bio_ctrl->bbio;
139 btrfs_bio_end_io(bbio, errno_to_blk_status(ret));
140 /* The bio is owned by the end_io handler now */
141 bio_ctrl->bbio = NULL;
143 submit_one_bio(bio_ctrl);
147 int __init extent_buffer_init_cachep(void)
149 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
150 sizeof(struct extent_buffer), 0,
151 SLAB_MEM_SPREAD, NULL);
152 if (!extent_buffer_cache)
158 void __cold extent_buffer_free_cachep(void)
161 * Make sure all delayed rcu free are flushed before we
165 kmem_cache_destroy(extent_buffer_cache);
168 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
170 unsigned long index = start >> PAGE_SHIFT;
171 unsigned long end_index = end >> PAGE_SHIFT;
174 while (index <= end_index) {
175 page = find_get_page(inode->i_mapping, index);
176 BUG_ON(!page); /* Pages should be in the extent_io_tree */
177 clear_page_dirty_for_io(page);
183 static void process_one_page(struct btrfs_fs_info *fs_info,
184 struct page *page, struct page *locked_page,
185 unsigned long page_ops, u64 start, u64 end)
187 struct folio *folio = page_folio(page);
190 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
191 len = end + 1 - start;
193 if (page_ops & PAGE_SET_ORDERED)
194 btrfs_folio_clamp_set_ordered(fs_info, folio, start, len);
195 if (page_ops & PAGE_START_WRITEBACK) {
196 btrfs_folio_clamp_clear_dirty(fs_info, folio, start, len);
197 btrfs_folio_clamp_set_writeback(fs_info, folio, start, len);
199 if (page_ops & PAGE_END_WRITEBACK)
200 btrfs_folio_clamp_clear_writeback(fs_info, folio, start, len);
202 if (page != locked_page && (page_ops & PAGE_UNLOCK))
203 btrfs_folio_end_writer_lock(fs_info, folio, start, len);
206 static void __process_pages_contig(struct address_space *mapping,
207 struct page *locked_page, u64 start, u64 end,
208 unsigned long page_ops)
210 struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
211 pgoff_t start_index = start >> PAGE_SHIFT;
212 pgoff_t end_index = end >> PAGE_SHIFT;
213 pgoff_t index = start_index;
214 struct folio_batch fbatch;
217 folio_batch_init(&fbatch);
218 while (index <= end_index) {
221 found_folios = filemap_get_folios_contig(mapping, &index,
223 for (i = 0; i < found_folios; i++) {
224 struct folio *folio = fbatch.folios[i];
226 process_one_page(fs_info, &folio->page, locked_page,
227 page_ops, start, end);
229 folio_batch_release(&fbatch);
234 static noinline void __unlock_for_delalloc(struct inode *inode,
235 struct page *locked_page,
238 unsigned long index = start >> PAGE_SHIFT;
239 unsigned long end_index = end >> PAGE_SHIFT;
242 if (index == locked_page->index && end_index == index)
245 __process_pages_contig(inode->i_mapping, locked_page, start, end,
249 static noinline int lock_delalloc_pages(struct inode *inode,
250 struct page *locked_page,
254 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
255 struct address_space *mapping = inode->i_mapping;
256 pgoff_t start_index = start >> PAGE_SHIFT;
257 pgoff_t end_index = end >> PAGE_SHIFT;
258 pgoff_t index = start_index;
259 u64 processed_end = start;
260 struct folio_batch fbatch;
262 if (index == locked_page->index && index == end_index)
265 folio_batch_init(&fbatch);
266 while (index <= end_index) {
267 unsigned int found_folios, i;
269 found_folios = filemap_get_folios_contig(mapping, &index,
271 if (found_folios == 0)
274 for (i = 0; i < found_folios; i++) {
275 struct folio *folio = fbatch.folios[i];
276 struct page *page = folio_page(folio, 0);
277 u32 len = end + 1 - start;
279 if (page == locked_page)
282 if (btrfs_folio_start_writer_lock(fs_info, folio, start,
286 if (!PageDirty(page) || page->mapping != mapping) {
287 btrfs_folio_end_writer_lock(fs_info, folio, start,
292 processed_end = page_offset(page) + PAGE_SIZE - 1;
294 folio_batch_release(&fbatch);
300 folio_batch_release(&fbatch);
301 if (processed_end > start)
302 __unlock_for_delalloc(inode, locked_page, start, processed_end);
307 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
308 * more than @max_bytes.
310 * @start: The original start bytenr to search.
311 * Will store the extent range start bytenr.
312 * @end: The original end bytenr of the search range
313 * Will store the extent range end bytenr.
315 * Return true if we find a delalloc range which starts inside the original
316 * range, and @start/@end will store the delalloc range start/end.
318 * Return false if we can't find any delalloc range which starts inside the
319 * original range, and @start/@end will be the non-delalloc range start/end.
322 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
323 struct page *locked_page, u64 *start,
326 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
327 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
328 const u64 orig_start = *start;
329 const u64 orig_end = *end;
330 /* The sanity tests may not set a valid fs_info. */
331 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
335 struct extent_state *cached_state = NULL;
339 /* Caller should pass a valid @end to indicate the search range end */
340 ASSERT(orig_end > orig_start);
342 /* The range should at least cover part of the page */
343 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
344 orig_end <= page_offset(locked_page)));
346 /* step one, find a bunch of delalloc bytes starting at start */
347 delalloc_start = *start;
349 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
350 max_bytes, &cached_state);
351 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
352 *start = delalloc_start;
354 /* @delalloc_end can be -1, never go beyond @orig_end */
355 *end = min(delalloc_end, orig_end);
356 free_extent_state(cached_state);
361 * start comes from the offset of locked_page. We have to lock
362 * pages in order, so we can't process delalloc bytes before
365 if (delalloc_start < *start)
366 delalloc_start = *start;
369 * make sure to limit the number of pages we try to lock down
371 if (delalloc_end + 1 - delalloc_start > max_bytes)
372 delalloc_end = delalloc_start + max_bytes - 1;
374 /* step two, lock all the pages after the page that has start */
375 ret = lock_delalloc_pages(inode, locked_page,
376 delalloc_start, delalloc_end);
377 ASSERT(!ret || ret == -EAGAIN);
378 if (ret == -EAGAIN) {
379 /* some of the pages are gone, lets avoid looping by
380 * shortening the size of the delalloc range we're searching
382 free_extent_state(cached_state);
385 max_bytes = PAGE_SIZE;
394 /* step three, lock the state bits for the whole range */
395 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
397 /* then test to make sure it is all still delalloc */
398 ret = test_range_bit(tree, delalloc_start, delalloc_end,
399 EXTENT_DELALLOC, cached_state);
401 unlock_extent(tree, delalloc_start, delalloc_end,
403 __unlock_for_delalloc(inode, locked_page,
404 delalloc_start, delalloc_end);
408 free_extent_state(cached_state);
409 *start = delalloc_start;
415 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
416 struct page *locked_page,
417 u32 clear_bits, unsigned long page_ops)
419 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
421 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
422 start, end, page_ops);
425 static bool btrfs_verify_page(struct page *page, u64 start)
427 if (!fsverity_active(page->mapping->host) ||
428 PageUptodate(page) ||
429 start >= i_size_read(page->mapping->host))
431 return fsverity_verify_page(page);
434 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
436 struct btrfs_fs_info *fs_info = page_to_fs_info(page);
437 struct folio *folio = page_folio(page);
439 ASSERT(page_offset(page) <= start &&
440 start + len <= page_offset(page) + PAGE_SIZE);
442 if (uptodate && btrfs_verify_page(page, start))
443 btrfs_folio_set_uptodate(fs_info, folio, start, len);
445 btrfs_folio_clear_uptodate(fs_info, folio, start, len);
447 if (!btrfs_is_subpage(fs_info, page->mapping))
450 btrfs_subpage_end_reader(fs_info, folio, start, len);
454 * After a write IO is done, we need to:
456 * - clear the uptodate bits on error
457 * - clear the writeback bits in the extent tree for the range
458 * - filio_end_writeback() if there is no more pending io for the folio
460 * Scheduling is not allowed, so the extent state tree is expected
461 * to have one and only one object corresponding to this IO.
463 static void end_bbio_data_write(struct btrfs_bio *bbio)
465 struct bio *bio = &bbio->bio;
466 int error = blk_status_to_errno(bio->bi_status);
467 struct folio_iter fi;
469 ASSERT(!bio_flagged(bio, BIO_CLONED));
470 bio_for_each_folio_all(fi, bio) {
471 struct folio *folio = fi.folio;
472 struct inode *inode = folio->mapping->host;
473 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
474 const u32 sectorsize = fs_info->sectorsize;
475 u64 start = folio_pos(folio) + fi.offset;
478 /* Only order 0 (single page) folios are allowed for data. */
479 ASSERT(folio_order(folio) == 0);
481 /* Our read/write should always be sector aligned. */
482 if (!IS_ALIGNED(fi.offset, sectorsize))
484 "partial page write in btrfs with offset %zu and length %zu",
485 fi.offset, fi.length);
486 else if (!IS_ALIGNED(fi.length, sectorsize))
488 "incomplete page write with offset %zu and length %zu",
489 fi.offset, fi.length);
491 btrfs_finish_ordered_extent(bbio->ordered,
492 folio_page(folio, 0), start, len, !error);
494 mapping_set_error(folio->mapping, error);
495 btrfs_folio_clear_writeback(fs_info, folio, start, len);
502 * Record previously processed extent range
504 * For endio_readpage_release_extent() to handle a full extent range, reducing
505 * the extent io operations.
507 struct processed_extent {
508 struct btrfs_inode *inode;
509 /* Start of the range in @inode */
511 /* End of the range in @inode */
517 * Try to release processed extent range
519 * May not release the extent range right now if the current range is
520 * contiguous to processed extent.
522 * Will release processed extent when any of @inode, @uptodate, the range is
523 * no longer contiguous to the processed range.
525 * Passing @inode == NULL will force processed extent to be released.
527 static void endio_readpage_release_extent(struct processed_extent *processed,
528 struct btrfs_inode *inode, u64 start, u64 end,
531 struct extent_state *cached = NULL;
532 struct extent_io_tree *tree;
534 /* The first extent, initialize @processed */
535 if (!processed->inode)
539 * Contiguous to processed extent, just uptodate the end.
541 * Several things to notice:
543 * - bio can be merged as long as on-disk bytenr is contiguous
544 * This means we can have page belonging to other inodes, thus need to
545 * check if the inode still matches.
546 * - bvec can contain range beyond current page for multi-page bvec
547 * Thus we need to do processed->end + 1 >= start check
549 if (processed->inode == inode && processed->uptodate == uptodate &&
550 processed->end + 1 >= start && end >= processed->end) {
551 processed->end = end;
555 tree = &processed->inode->io_tree;
557 * Now we don't have range contiguous to the processed range, release
558 * the processed range now.
560 unlock_extent(tree, processed->start, processed->end, &cached);
563 /* Update processed to current range */
564 processed->inode = inode;
565 processed->start = start;
566 processed->end = end;
567 processed->uptodate = uptodate;
570 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
572 struct folio *folio = page_folio(page);
574 ASSERT(folio_test_locked(folio));
575 if (!btrfs_is_subpage(fs_info, folio->mapping))
578 ASSERT(folio_test_private(folio));
579 btrfs_subpage_start_reader(fs_info, folio, page_offset(page), PAGE_SIZE);
583 * After a data read IO is done, we need to:
585 * - clear the uptodate bits on error
586 * - set the uptodate bits if things worked
587 * - set the folio up to date if all extents in the tree are uptodate
588 * - clear the lock bit in the extent tree
589 * - unlock the folio if there are no other extents locked for it
591 * Scheduling is not allowed, so the extent state tree is expected
592 * to have one and only one object corresponding to this IO.
594 static void end_bbio_data_read(struct btrfs_bio *bbio)
596 struct bio *bio = &bbio->bio;
597 struct processed_extent processed = { 0 };
598 struct folio_iter fi;
600 * The offset to the beginning of a bio, since one bio can never be
601 * larger than UINT_MAX, u32 here is enough.
605 ASSERT(!bio_flagged(bio, BIO_CLONED));
606 bio_for_each_folio_all(fi, &bbio->bio) {
607 bool uptodate = !bio->bi_status;
608 struct folio *folio = fi.folio;
609 struct inode *inode = folio->mapping->host;
610 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
611 const u32 sectorsize = fs_info->sectorsize;
616 /* For now only order 0 folios are supported for data. */
617 ASSERT(folio_order(folio) == 0);
619 "%s: bi_sector=%llu, err=%d, mirror=%u",
620 __func__, bio->bi_iter.bi_sector, bio->bi_status,
624 * We always issue full-sector reads, but if some block in a
625 * folio fails to read, blk_update_request() will advance
626 * bv_offset and adjust bv_len to compensate. Print a warning
627 * for unaligned offsets, and an error if they don't add up to
630 if (!IS_ALIGNED(fi.offset, sectorsize))
632 "partial page read in btrfs with offset %zu and length %zu",
633 fi.offset, fi.length);
634 else if (!IS_ALIGNED(fi.offset + fi.length, sectorsize))
636 "incomplete page read with offset %zu and length %zu",
637 fi.offset, fi.length);
639 start = folio_pos(folio) + fi.offset;
640 end = start + fi.length - 1;
643 if (likely(uptodate)) {
644 loff_t i_size = i_size_read(inode);
645 pgoff_t end_index = i_size >> folio_shift(folio);
648 * Zero out the remaining part if this range straddles
651 * Here we should only zero the range inside the folio,
652 * not touch anything else.
654 * NOTE: i_size is exclusive while end is inclusive.
656 if (folio_index(folio) == end_index && i_size <= end) {
657 u32 zero_start = max(offset_in_folio(folio, i_size),
658 offset_in_folio(folio, start));
659 u32 zero_len = offset_in_folio(folio, end) + 1 -
662 folio_zero_range(folio, zero_start, zero_len);
666 /* Update page status and unlock. */
667 end_page_read(folio_page(folio, 0), uptodate, start, len);
668 endio_readpage_release_extent(&processed, BTRFS_I(inode),
669 start, end, uptodate);
671 ASSERT(bio_offset + len > bio_offset);
675 /* Release the last extent */
676 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
681 * Populate every free slot in a provided array with pages.
683 * @nr_pages: number of pages to allocate
684 * @page_array: the array to fill with pages; any existing non-null entries in
685 * the array will be skipped
686 * @extra_gfp: the extra GFP flags for the allocation.
688 * Return: 0 if all pages were able to be allocated;
689 * -ENOMEM otherwise, the partially allocated pages would be freed and
690 * the array slots zeroed
692 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
695 const gfp_t gfp = GFP_NOFS | extra_gfp;
696 unsigned int allocated;
698 for (allocated = 0; allocated < nr_pages;) {
699 unsigned int last = allocated;
701 allocated = alloc_pages_bulk_array(gfp, nr_pages, page_array);
702 if (unlikely(allocated == last)) {
703 /* No progress, fail and do cleanup. */
704 for (int i = 0; i < allocated; i++) {
705 __free_page(page_array[i]);
706 page_array[i] = NULL;
715 * Populate needed folios for the extent buffer.
717 * For now, the folios populated are always in order 0 (aka, single page).
719 static int alloc_eb_folio_array(struct extent_buffer *eb, gfp_t extra_gfp)
721 struct page *page_array[INLINE_EXTENT_BUFFER_PAGES] = { 0 };
722 int num_pages = num_extent_pages(eb);
725 ret = btrfs_alloc_page_array(num_pages, page_array, extra_gfp);
729 for (int i = 0; i < num_pages; i++)
730 eb->folios[i] = page_folio(page_array[i]);
734 static bool btrfs_bio_is_contig(struct btrfs_bio_ctrl *bio_ctrl,
735 struct page *page, u64 disk_bytenr,
736 unsigned int pg_offset)
738 struct bio *bio = &bio_ctrl->bbio->bio;
739 struct bio_vec *bvec = bio_last_bvec_all(bio);
740 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
742 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
744 * For compression, all IO should have its logical bytenr set
745 * to the starting bytenr of the compressed extent.
747 return bio->bi_iter.bi_sector == sector;
751 * The contig check requires the following conditions to be met:
753 * 1) The pages are belonging to the same inode
754 * This is implied by the call chain.
756 * 2) The range has adjacent logical bytenr
758 * 3) The range has adjacent file offset
759 * This is required for the usage of btrfs_bio->file_offset.
761 return bio_end_sector(bio) == sector &&
762 page_offset(bvec->bv_page) + bvec->bv_offset + bvec->bv_len ==
763 page_offset(page) + pg_offset;
766 static void alloc_new_bio(struct btrfs_inode *inode,
767 struct btrfs_bio_ctrl *bio_ctrl,
768 u64 disk_bytenr, u64 file_offset)
770 struct btrfs_fs_info *fs_info = inode->root->fs_info;
771 struct btrfs_bio *bbio;
773 bbio = btrfs_bio_alloc(BIO_MAX_VECS, bio_ctrl->opf, fs_info,
774 bio_ctrl->end_io_func, NULL);
775 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
777 bbio->file_offset = file_offset;
778 bio_ctrl->bbio = bbio;
779 bio_ctrl->len_to_oe_boundary = U32_MAX;
781 /* Limit data write bios to the ordered boundary. */
783 struct btrfs_ordered_extent *ordered;
785 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
787 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
788 ordered->file_offset +
789 ordered->disk_num_bytes - file_offset);
790 bbio->ordered = ordered;
794 * Pick the last added device to support cgroup writeback. For
795 * multi-device file systems this means blk-cgroup policies have
796 * to always be set on the last added/replaced device.
797 * This is a bit odd but has been like that for a long time.
799 bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
800 wbc_init_bio(bio_ctrl->wbc, &bbio->bio);
805 * @disk_bytenr: logical bytenr where the write will be
806 * @page: page to add to the bio
807 * @size: portion of page that we want to write to
808 * @pg_offset: offset of the new bio or to check whether we are adding
809 * a contiguous page to the previous one
811 * The will either add the page into the existing @bio_ctrl->bbio, or allocate a
812 * new one in @bio_ctrl->bbio.
813 * The mirror number for this IO should already be initizlied in
814 * @bio_ctrl->mirror_num.
816 static void submit_extent_page(struct btrfs_bio_ctrl *bio_ctrl,
817 u64 disk_bytenr, struct page *page,
818 size_t size, unsigned long pg_offset)
820 struct btrfs_inode *inode = page_to_inode(page);
822 ASSERT(pg_offset + size <= PAGE_SIZE);
823 ASSERT(bio_ctrl->end_io_func);
825 if (bio_ctrl->bbio &&
826 !btrfs_bio_is_contig(bio_ctrl, page, disk_bytenr, pg_offset))
827 submit_one_bio(bio_ctrl);
832 /* Allocate new bio if needed */
833 if (!bio_ctrl->bbio) {
834 alloc_new_bio(inode, bio_ctrl, disk_bytenr,
835 page_offset(page) + pg_offset);
838 /* Cap to the current ordered extent boundary if there is one. */
839 if (len > bio_ctrl->len_to_oe_boundary) {
840 ASSERT(bio_ctrl->compress_type == BTRFS_COMPRESS_NONE);
841 ASSERT(is_data_inode(&inode->vfs_inode));
842 len = bio_ctrl->len_to_oe_boundary;
845 if (bio_add_page(&bio_ctrl->bbio->bio, page, len, pg_offset) != len) {
846 /* bio full: move on to a new one */
847 submit_one_bio(bio_ctrl);
852 wbc_account_cgroup_owner(bio_ctrl->wbc, page, len);
859 * len_to_oe_boundary defaults to U32_MAX, which isn't page or
860 * sector aligned. alloc_new_bio() then sets it to the end of
861 * our ordered extent for writes into zoned devices.
863 * When len_to_oe_boundary is tracking an ordered extent, we
864 * trust the ordered extent code to align things properly, and
865 * the check above to cap our write to the ordered extent
866 * boundary is correct.
868 * When len_to_oe_boundary is U32_MAX, the cap above would
869 * result in a 4095 byte IO for the last page right before
870 * we hit the bio limit of UINT_MAX. bio_add_page() has all
871 * the checks required to make sure we don't overflow the bio,
872 * and we should just ignore len_to_oe_boundary completely
873 * unless we're using it to track an ordered extent.
875 * It's pretty hard to make a bio sized U32_MAX, but it can
876 * happen when the page cache is able to feed us contiguous
877 * pages for large extents.
879 if (bio_ctrl->len_to_oe_boundary != U32_MAX)
880 bio_ctrl->len_to_oe_boundary -= len;
882 /* Ordered extent boundary: move on to a new bio. */
883 if (bio_ctrl->len_to_oe_boundary == 0)
884 submit_one_bio(bio_ctrl);
888 static int attach_extent_buffer_folio(struct extent_buffer *eb,
890 struct btrfs_subpage *prealloc)
892 struct btrfs_fs_info *fs_info = eb->fs_info;
896 * If the page is mapped to btree inode, we should hold the private
897 * lock to prevent race.
898 * For cloned or dummy extent buffers, their pages are not mapped and
899 * will not race with any other ebs.
902 lockdep_assert_held(&folio->mapping->i_private_lock);
904 if (fs_info->nodesize >= PAGE_SIZE) {
905 if (!folio_test_private(folio))
906 folio_attach_private(folio, eb);
908 WARN_ON(folio_get_private(folio) != eb);
912 /* Already mapped, just free prealloc */
913 if (folio_test_private(folio)) {
914 btrfs_free_subpage(prealloc);
919 /* Has preallocated memory for subpage */
920 folio_attach_private(folio, prealloc);
922 /* Do new allocation to attach subpage */
923 ret = btrfs_attach_subpage(fs_info, folio, BTRFS_SUBPAGE_METADATA);
927 int set_page_extent_mapped(struct page *page)
929 return set_folio_extent_mapped(page_folio(page));
932 int set_folio_extent_mapped(struct folio *folio)
934 struct btrfs_fs_info *fs_info;
936 ASSERT(folio->mapping);
938 if (folio_test_private(folio))
941 fs_info = folio_to_fs_info(folio);
943 if (btrfs_is_subpage(fs_info, folio->mapping))
944 return btrfs_attach_subpage(fs_info, folio, BTRFS_SUBPAGE_DATA);
946 folio_attach_private(folio, (void *)EXTENT_FOLIO_PRIVATE);
950 void clear_page_extent_mapped(struct page *page)
952 struct folio *folio = page_folio(page);
953 struct btrfs_fs_info *fs_info;
955 ASSERT(page->mapping);
957 if (!folio_test_private(folio))
960 fs_info = page_to_fs_info(page);
961 if (btrfs_is_subpage(fs_info, page->mapping))
962 return btrfs_detach_subpage(fs_info, folio);
964 folio_detach_private(folio);
967 static struct extent_map *
968 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
969 u64 start, u64 len, struct extent_map **em_cached)
971 struct extent_map *em;
973 if (em_cached && *em_cached) {
975 if (extent_map_in_tree(em) && start >= em->start &&
976 start < extent_map_end(em)) {
977 refcount_inc(&em->refs);
985 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
986 if (em_cached && !IS_ERR(em)) {
988 refcount_inc(&em->refs);
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
997 * XXX JDM: This needs looking at to ensure proper page locking
998 * return 0 on success, otherwise return error
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)
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;
1009 u64 last_byte = i_size_read(inode);
1011 struct extent_map *em;
1013 size_t pg_offset = 0;
1015 size_t blocksize = fs_info->sectorsize;
1016 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1018 ret = set_page_extent_mapped(page);
1020 unlock_extent(tree, start, end, NULL);
1025 if (page->index == last_byte >> PAGE_SHIFT) {
1026 size_t zero_offset = offset_in_page(last_byte);
1029 iosize = PAGE_SIZE - zero_offset;
1030 memzero_page(page, zero_offset, iosize);
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;
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);
1048 em = __get_extent_map(inode, page, pg_offset, cur,
1049 end - cur + 1, em_cached);
1051 unlock_extent(tree, cur, end, NULL);
1052 end_page_read(page, false, cur, end + 1 - cur);
1055 extent_offset = cur - em->start;
1056 BUG_ON(extent_map_end(em) <= cur);
1059 compress_type = extent_map_compression(em);
1061 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1062 iosize = ALIGN(iosize, blocksize);
1063 if (compress_type != BTRFS_COMPRESS_NONE)
1064 disk_bytenr = em->block_start;
1066 disk_bytenr = em->block_start + extent_offset;
1067 block_start = em->block_start;
1068 if (em->flags & EXTENT_FLAG_PREALLOC)
1069 block_start = EXTENT_MAP_HOLE;
1072 * If we have a file range that points to a compressed extent
1073 * and it's followed by a consecutive file range that points
1074 * to the same compressed extent (possibly with a different
1075 * offset and/or length, so it either points to the whole extent
1076 * or only part of it), we must make sure we do not submit a
1077 * single bio to populate the pages for the 2 ranges because
1078 * this makes the compressed extent read zero out the pages
1079 * belonging to the 2nd range. Imagine the following scenario:
1082 * [0 - 8K] [8K - 24K]
1085 * points to extent X, points to extent X,
1086 * offset 4K, length of 8K offset 0, length 16K
1088 * [extent X, compressed length = 4K uncompressed length = 16K]
1090 * If the bio to read the compressed extent covers both ranges,
1091 * it will decompress extent X into the pages belonging to the
1092 * first range and then it will stop, zeroing out the remaining
1093 * pages that belong to the other range that points to extent X.
1094 * So here we make sure we submit 2 bios, one for the first
1095 * range and another one for the third range. Both will target
1096 * the same physical extent from disk, but we can't currently
1097 * make the compressed bio endio callback populate the pages
1098 * for both ranges because each compressed bio is tightly
1099 * coupled with a single extent map, and each range can have
1100 * an extent map with a different offset value relative to the
1101 * uncompressed data of our extent and different lengths. This
1102 * is a corner case so we prioritize correctness over
1103 * non-optimal behavior (submitting 2 bios for the same extent).
1105 if (compress_type != BTRFS_COMPRESS_NONE &&
1106 prev_em_start && *prev_em_start != (u64)-1 &&
1107 *prev_em_start != em->start)
1108 force_bio_submit = true;
1111 *prev_em_start = em->start;
1113 free_extent_map(em);
1116 /* we've found a hole, just zero and go on */
1117 if (block_start == EXTENT_MAP_HOLE) {
1118 memzero_page(page, pg_offset, iosize);
1120 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1121 end_page_read(page, true, cur, iosize);
1123 pg_offset += iosize;
1126 /* the get_extent function already copied into the page */
1127 if (block_start == EXTENT_MAP_INLINE) {
1128 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1129 end_page_read(page, true, cur, iosize);
1131 pg_offset += iosize;
1135 if (bio_ctrl->compress_type != compress_type) {
1136 submit_one_bio(bio_ctrl);
1137 bio_ctrl->compress_type = compress_type;
1140 if (force_bio_submit)
1141 submit_one_bio(bio_ctrl);
1142 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1145 pg_offset += iosize;
1151 int btrfs_read_folio(struct file *file, struct folio *folio)
1153 struct page *page = &folio->page;
1154 struct btrfs_inode *inode = page_to_inode(page);
1155 u64 start = page_offset(page);
1156 u64 end = start + PAGE_SIZE - 1;
1157 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ };
1160 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1162 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, NULL);
1164 * If btrfs_do_readpage() failed we will want to submit the assembled
1165 * bio to do the cleanup.
1167 submit_one_bio(&bio_ctrl);
1171 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1173 struct extent_map **em_cached,
1174 struct btrfs_bio_ctrl *bio_ctrl,
1177 struct btrfs_inode *inode = page_to_inode(pages[0]);
1180 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1182 for (index = 0; index < nr_pages; index++) {
1183 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1185 put_page(pages[index]);
1190 * helper for __extent_writepage, doing all of the delayed allocation setup.
1192 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1193 * to write the page (copy into inline extent). In this case the IO has
1194 * been started and the page is already unlocked.
1196 * This returns 0 if all went well (page still locked)
1197 * This returns < 0 if there were errors (page still locked)
1199 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1200 struct page *page, struct writeback_control *wbc)
1202 const u64 page_start = page_offset(page);
1203 const u64 page_end = page_start + PAGE_SIZE - 1;
1204 u64 delalloc_start = page_start;
1205 u64 delalloc_end = page_end;
1206 u64 delalloc_to_write = 0;
1209 while (delalloc_start < page_end) {
1210 delalloc_end = page_end;
1211 if (!find_lock_delalloc_range(&inode->vfs_inode, page,
1212 &delalloc_start, &delalloc_end)) {
1213 delalloc_start = delalloc_end + 1;
1217 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1222 delalloc_start = delalloc_end + 1;
1226 * delalloc_end is already one less than the total length, so
1227 * we don't subtract one from PAGE_SIZE
1229 delalloc_to_write +=
1230 DIV_ROUND_UP(delalloc_end + 1 - page_start, PAGE_SIZE);
1233 * If btrfs_run_dealloc_range() already started I/O and unlocked
1234 * the pages, we just need to account for them here.
1237 wbc->nr_to_write -= delalloc_to_write;
1241 if (wbc->nr_to_write < delalloc_to_write) {
1244 if (delalloc_to_write < thresh * 2)
1245 thresh = delalloc_to_write;
1246 wbc->nr_to_write = min_t(u64, delalloc_to_write,
1254 * Find the first byte we need to write.
1256 * For subpage, one page can contain several sectors, and
1257 * __extent_writepage_io() will just grab all extent maps in the page
1258 * range and try to submit all non-inline/non-compressed extents.
1260 * This is a big problem for subpage, we shouldn't re-submit already written
1262 * This function will lookup subpage dirty bit to find which range we really
1265 * Return the next dirty range in [@start, @end).
1266 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
1268 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
1269 struct page *page, u64 *start, u64 *end)
1271 struct folio *folio = page_folio(page);
1272 struct btrfs_subpage *subpage = folio_get_private(folio);
1273 struct btrfs_subpage_info *spi = fs_info->subpage_info;
1274 u64 orig_start = *start;
1275 /* Declare as unsigned long so we can use bitmap ops */
1276 unsigned long flags;
1277 int range_start_bit;
1281 * For regular sector size == page size case, since one page only
1282 * contains one sector, we return the page offset directly.
1284 if (!btrfs_is_subpage(fs_info, page->mapping)) {
1285 *start = page_offset(page);
1286 *end = page_offset(page) + PAGE_SIZE;
1290 range_start_bit = spi->dirty_offset +
1291 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
1293 /* We should have the page locked, but just in case */
1294 spin_lock_irqsave(&subpage->lock, flags);
1295 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
1296 spi->dirty_offset + spi->bitmap_nr_bits);
1297 spin_unlock_irqrestore(&subpage->lock, flags);
1299 range_start_bit -= spi->dirty_offset;
1300 range_end_bit -= spi->dirty_offset;
1302 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
1303 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
1307 * helper for __extent_writepage. This calls the writepage start hooks,
1308 * and does the loop to map the page into extents and bios.
1310 * We return 1 if the IO is started and the page is unlocked,
1311 * 0 if all went well (page still locked)
1312 * < 0 if there were errors (page still locked)
1314 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
1316 struct btrfs_bio_ctrl *bio_ctrl,
1320 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1321 u64 cur = page_offset(page);
1322 u64 end = cur + PAGE_SIZE - 1;
1325 struct extent_map *em;
1329 ret = btrfs_writepage_cow_fixup(page);
1331 /* Fixup worker will requeue */
1332 redirty_page_for_writepage(bio_ctrl->wbc, page);
1337 bio_ctrl->end_io_func = end_bbio_data_write;
1338 while (cur <= end) {
1339 u32 len = end - cur + 1;
1342 u64 dirty_range_start = cur;
1343 u64 dirty_range_end;
1346 if (cur >= i_size) {
1347 btrfs_mark_ordered_io_finished(inode, page, cur, len,
1350 * This range is beyond i_size, thus we don't need to
1351 * bother writing back.
1352 * But we still need to clear the dirty subpage bit, or
1353 * the next time the page gets dirtied, we will try to
1354 * writeback the sectors with subpage dirty bits,
1355 * causing writeback without ordered extent.
1357 btrfs_folio_clear_dirty(fs_info, page_folio(page), cur, len);
1361 find_next_dirty_byte(fs_info, page, &dirty_range_start,
1363 if (cur < dirty_range_start) {
1364 cur = dirty_range_start;
1368 em = btrfs_get_extent(inode, NULL, 0, cur, len);
1370 ret = PTR_ERR_OR_ZERO(em);
1374 extent_offset = cur - em->start;
1375 em_end = extent_map_end(em);
1376 ASSERT(cur <= em_end);
1378 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
1379 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
1381 block_start = em->block_start;
1382 disk_bytenr = em->block_start + extent_offset;
1384 ASSERT(!extent_map_is_compressed(em));
1385 ASSERT(block_start != EXTENT_MAP_HOLE);
1386 ASSERT(block_start != EXTENT_MAP_INLINE);
1389 * Note that em_end from extent_map_end() and dirty_range_end from
1390 * find_next_dirty_byte() are all exclusive
1392 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
1393 free_extent_map(em);
1396 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
1397 if (!PageWriteback(page)) {
1398 btrfs_err(inode->root->fs_info,
1399 "page %lu not writeback, cur %llu end %llu",
1400 page->index, cur, end);
1404 * Although the PageDirty bit is cleared before entering this
1405 * function, subpage dirty bit is not cleared.
1406 * So clear subpage dirty bit here so next time we won't submit
1407 * page for range already written to disk.
1409 btrfs_folio_clear_dirty(fs_info, page_folio(page), cur, iosize);
1411 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1412 cur - page_offset(page));
1417 btrfs_folio_assert_not_dirty(fs_info, page_folio(page));
1423 * If we finish without problem, we should not only clear page dirty,
1424 * but also empty subpage dirty bits
1431 * the writepage semantics are similar to regular writepage. extent
1432 * records are inserted to lock ranges in the tree, and as dirty areas
1433 * are found, they are marked writeback. Then the lock bits are removed
1434 * and the end_io handler clears the writeback ranges
1436 * Return 0 if everything goes well.
1437 * Return <0 for error.
1439 static int __extent_writepage(struct page *page, struct btrfs_bio_ctrl *bio_ctrl)
1441 struct folio *folio = page_folio(page);
1442 struct inode *inode = page->mapping->host;
1443 const u64 page_start = page_offset(page);
1447 loff_t i_size = i_size_read(inode);
1448 unsigned long end_index = i_size >> PAGE_SHIFT;
1450 trace___extent_writepage(page, inode, bio_ctrl->wbc);
1452 WARN_ON(!PageLocked(page));
1454 pg_offset = offset_in_page(i_size);
1455 if (page->index > end_index ||
1456 (page->index == end_index && !pg_offset)) {
1457 folio_invalidate(folio, 0, folio_size(folio));
1458 folio_unlock(folio);
1462 if (page->index == end_index)
1463 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
1465 ret = set_page_extent_mapped(page);
1469 ret = writepage_delalloc(BTRFS_I(inode), page, bio_ctrl->wbc);
1475 ret = __extent_writepage_io(BTRFS_I(inode), page, bio_ctrl, i_size, &nr);
1479 bio_ctrl->wbc->nr_to_write--;
1483 /* make sure the mapping tag for page dirty gets cleared */
1484 set_page_writeback(page);
1485 end_page_writeback(page);
1488 btrfs_mark_ordered_io_finished(BTRFS_I(inode), page, page_start,
1490 mapping_set_error(page->mapping, ret);
1497 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
1499 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
1500 TASK_UNINTERRUPTIBLE);
1504 * Lock extent buffer status and pages for writeback.
1506 * Return %false if the extent buffer doesn't need to be submitted (e.g. the
1507 * extent buffer is not dirty)
1508 * Return %true is the extent buffer is submitted to bio.
1510 static noinline_for_stack bool lock_extent_buffer_for_io(struct extent_buffer *eb,
1511 struct writeback_control *wbc)
1513 struct btrfs_fs_info *fs_info = eb->fs_info;
1516 btrfs_tree_lock(eb);
1517 while (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
1518 btrfs_tree_unlock(eb);
1519 if (wbc->sync_mode != WB_SYNC_ALL)
1521 wait_on_extent_buffer_writeback(eb);
1522 btrfs_tree_lock(eb);
1526 * We need to do this to prevent races in people who check if the eb is
1527 * under IO since we can end up having no IO bits set for a short period
1530 spin_lock(&eb->refs_lock);
1531 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
1532 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1533 spin_unlock(&eb->refs_lock);
1534 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
1535 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1537 fs_info->dirty_metadata_batch);
1540 spin_unlock(&eb->refs_lock);
1542 btrfs_tree_unlock(eb);
1546 static void set_btree_ioerr(struct extent_buffer *eb)
1548 struct btrfs_fs_info *fs_info = eb->fs_info;
1550 set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1553 * A read may stumble upon this buffer later, make sure that it gets an
1554 * error and knows there was an error.
1556 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
1559 * We need to set the mapping with the io error as well because a write
1560 * error will flip the file system readonly, and then syncfs() will
1561 * return a 0 because we are readonly if we don't modify the err seq for
1564 mapping_set_error(eb->fs_info->btree_inode->i_mapping, -EIO);
1567 * If writeback for a btree extent that doesn't belong to a log tree
1568 * failed, increment the counter transaction->eb_write_errors.
1569 * We do this because while the transaction is running and before it's
1570 * committing (when we call filemap_fdata[write|wait]_range against
1571 * the btree inode), we might have
1572 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
1573 * returns an error or an error happens during writeback, when we're
1574 * committing the transaction we wouldn't know about it, since the pages
1575 * can be no longer dirty nor marked anymore for writeback (if a
1576 * subsequent modification to the extent buffer didn't happen before the
1577 * transaction commit), which makes filemap_fdata[write|wait]_range not
1578 * able to find the pages tagged with SetPageError at transaction
1579 * commit time. So if this happens we must abort the transaction,
1580 * otherwise we commit a super block with btree roots that point to
1581 * btree nodes/leafs whose content on disk is invalid - either garbage
1582 * or the content of some node/leaf from a past generation that got
1583 * cowed or deleted and is no longer valid.
1585 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
1586 * not be enough - we need to distinguish between log tree extents vs
1587 * non-log tree extents, and the next filemap_fdatawait_range() call
1588 * will catch and clear such errors in the mapping - and that call might
1589 * be from a log sync and not from a transaction commit. Also, checking
1590 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
1591 * not done and would not be reliable - the eb might have been released
1592 * from memory and reading it back again means that flag would not be
1593 * set (since it's a runtime flag, not persisted on disk).
1595 * Using the flags below in the btree inode also makes us achieve the
1596 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
1597 * writeback for all dirty pages and before filemap_fdatawait_range()
1598 * is called, the writeback for all dirty pages had already finished
1599 * with errors - because we were not using AS_EIO/AS_ENOSPC,
1600 * filemap_fdatawait_range() would return success, as it could not know
1601 * that writeback errors happened (the pages were no longer tagged for
1604 switch (eb->log_index) {
1606 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
1609 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
1612 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
1615 BUG(); /* unexpected, logic error */
1620 * The endio specific version which won't touch any unsafe spinlock in endio
1623 static struct extent_buffer *find_extent_buffer_nolock(
1624 struct btrfs_fs_info *fs_info, u64 start)
1626 struct extent_buffer *eb;
1629 eb = radix_tree_lookup(&fs_info->buffer_radix,
1630 start >> fs_info->sectorsize_bits);
1631 if (eb && atomic_inc_not_zero(&eb->refs)) {
1639 static void end_bbio_meta_write(struct btrfs_bio *bbio)
1641 struct extent_buffer *eb = bbio->private;
1642 struct btrfs_fs_info *fs_info = eb->fs_info;
1643 bool uptodate = !bbio->bio.bi_status;
1644 struct folio_iter fi;
1648 set_btree_ioerr(eb);
1650 bio_for_each_folio_all(fi, &bbio->bio) {
1651 u64 start = eb->start + bio_offset;
1652 struct folio *folio = fi.folio;
1653 u32 len = fi.length;
1655 btrfs_folio_clear_writeback(fs_info, folio, start, len);
1659 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1660 smp_mb__after_atomic();
1661 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
1663 bio_put(&bbio->bio);
1666 static void prepare_eb_write(struct extent_buffer *eb)
1669 unsigned long start;
1672 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1674 /* Set btree blocks beyond nritems with 0 to avoid stale content */
1675 nritems = btrfs_header_nritems(eb);
1676 if (btrfs_header_level(eb) > 0) {
1677 end = btrfs_node_key_ptr_offset(eb, nritems);
1678 memzero_extent_buffer(eb, end, eb->len - end);
1682 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
1684 start = btrfs_item_nr_offset(eb, nritems);
1685 end = btrfs_item_nr_offset(eb, 0);
1687 end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
1689 end += btrfs_item_offset(eb, nritems - 1);
1690 memzero_extent_buffer(eb, start, end - start);
1694 static noinline_for_stack void write_one_eb(struct extent_buffer *eb,
1695 struct writeback_control *wbc)
1697 struct btrfs_fs_info *fs_info = eb->fs_info;
1698 struct btrfs_bio *bbio;
1700 prepare_eb_write(eb);
1702 bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
1703 REQ_OP_WRITE | REQ_META | wbc_to_write_flags(wbc),
1704 eb->fs_info, end_bbio_meta_write, eb);
1705 bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
1706 bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
1707 wbc_init_bio(wbc, &bbio->bio);
1708 bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
1709 bbio->file_offset = eb->start;
1710 if (fs_info->nodesize < PAGE_SIZE) {
1711 struct folio *folio = eb->folios[0];
1715 btrfs_subpage_set_writeback(fs_info, folio, eb->start, eb->len);
1716 if (btrfs_subpage_clear_and_test_dirty(fs_info, folio, eb->start,
1718 folio_clear_dirty_for_io(folio);
1721 ret = bio_add_folio(&bbio->bio, folio, eb->len,
1722 eb->start - folio_pos(folio));
1724 wbc_account_cgroup_owner(wbc, folio_page(folio, 0), eb->len);
1725 folio_unlock(folio);
1727 int num_folios = num_extent_folios(eb);
1729 for (int i = 0; i < num_folios; i++) {
1730 struct folio *folio = eb->folios[i];
1734 folio_clear_dirty_for_io(folio);
1735 folio_start_writeback(folio);
1736 ret = bio_add_folio(&bbio->bio, folio, folio_size(folio), 0);
1738 wbc_account_cgroup_owner(wbc, folio_page(folio, 0),
1740 wbc->nr_to_write -= folio_nr_pages(folio);
1741 folio_unlock(folio);
1744 btrfs_submit_bio(bbio, 0);
1748 * Submit one subpage btree page.
1750 * The main difference to submit_eb_page() is:
1752 * For subpage, we don't rely on page locking at all.
1755 * We only flush bio if we may be unable to fit current extent buffers into
1758 * Return >=0 for the number of submitted extent buffers.
1759 * Return <0 for fatal error.
1761 static int submit_eb_subpage(struct page *page, struct writeback_control *wbc)
1763 struct btrfs_fs_info *fs_info = page_to_fs_info(page);
1764 struct folio *folio = page_folio(page);
1766 u64 page_start = page_offset(page);
1768 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
1770 /* Lock and write each dirty extent buffers in the range */
1771 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
1772 struct btrfs_subpage *subpage = folio_get_private(folio);
1773 struct extent_buffer *eb;
1774 unsigned long flags;
1778 * Take private lock to ensure the subpage won't be detached
1781 spin_lock(&page->mapping->i_private_lock);
1782 if (!folio_test_private(folio)) {
1783 spin_unlock(&page->mapping->i_private_lock);
1786 spin_lock_irqsave(&subpage->lock, flags);
1787 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
1788 subpage->bitmaps)) {
1789 spin_unlock_irqrestore(&subpage->lock, flags);
1790 spin_unlock(&page->mapping->i_private_lock);
1795 start = page_start + bit_start * fs_info->sectorsize;
1796 bit_start += sectors_per_node;
1799 * Here we just want to grab the eb without touching extra
1800 * spin locks, so call find_extent_buffer_nolock().
1802 eb = find_extent_buffer_nolock(fs_info, start);
1803 spin_unlock_irqrestore(&subpage->lock, flags);
1804 spin_unlock(&page->mapping->i_private_lock);
1807 * The eb has already reached 0 refs thus find_extent_buffer()
1808 * doesn't return it. We don't need to write back such eb
1814 if (lock_extent_buffer_for_io(eb, wbc)) {
1815 write_one_eb(eb, wbc);
1818 free_extent_buffer(eb);
1824 * Submit all page(s) of one extent buffer.
1826 * @page: the page of one extent buffer
1827 * @eb_context: to determine if we need to submit this page, if current page
1828 * belongs to this eb, we don't need to submit
1830 * The caller should pass each page in their bytenr order, and here we use
1831 * @eb_context to determine if we have submitted pages of one extent buffer.
1833 * If we have, we just skip until we hit a new page that doesn't belong to
1834 * current @eb_context.
1836 * If not, we submit all the page(s) of the extent buffer.
1838 * Return >0 if we have submitted the extent buffer successfully.
1839 * Return 0 if we don't need to submit the page, as it's already submitted by
1841 * Return <0 for fatal error.
1843 static int submit_eb_page(struct page *page, struct btrfs_eb_write_context *ctx)
1845 struct writeback_control *wbc = ctx->wbc;
1846 struct address_space *mapping = page->mapping;
1847 struct folio *folio = page_folio(page);
1848 struct extent_buffer *eb;
1851 if (!folio_test_private(folio))
1854 if (page_to_fs_info(page)->nodesize < PAGE_SIZE)
1855 return submit_eb_subpage(page, wbc);
1857 spin_lock(&mapping->i_private_lock);
1858 if (!folio_test_private(folio)) {
1859 spin_unlock(&mapping->i_private_lock);
1863 eb = folio_get_private(folio);
1866 * Shouldn't happen and normally this would be a BUG_ON but no point
1867 * crashing the machine for something we can survive anyway.
1870 spin_unlock(&mapping->i_private_lock);
1874 if (eb == ctx->eb) {
1875 spin_unlock(&mapping->i_private_lock);
1878 ret = atomic_inc_not_zero(&eb->refs);
1879 spin_unlock(&mapping->i_private_lock);
1885 ret = btrfs_check_meta_write_pointer(eb->fs_info, ctx);
1889 free_extent_buffer(eb);
1893 if (!lock_extent_buffer_for_io(eb, wbc)) {
1894 free_extent_buffer(eb);
1897 /* Implies write in zoned mode. */
1898 if (ctx->zoned_bg) {
1899 /* Mark the last eb in the block group. */
1900 btrfs_schedule_zone_finish_bg(ctx->zoned_bg, eb);
1901 ctx->zoned_bg->meta_write_pointer += eb->len;
1903 write_one_eb(eb, wbc);
1904 free_extent_buffer(eb);
1908 int btree_write_cache_pages(struct address_space *mapping,
1909 struct writeback_control *wbc)
1911 struct btrfs_eb_write_context ctx = { .wbc = wbc };
1912 struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
1915 int nr_to_write_done = 0;
1916 struct folio_batch fbatch;
1917 unsigned int nr_folios;
1919 pgoff_t end; /* Inclusive */
1923 folio_batch_init(&fbatch);
1924 if (wbc->range_cyclic) {
1925 index = mapping->writeback_index; /* Start from prev offset */
1928 * Start from the beginning does not need to cycle over the
1929 * range, mark it as scanned.
1931 scanned = (index == 0);
1933 index = wbc->range_start >> PAGE_SHIFT;
1934 end = wbc->range_end >> PAGE_SHIFT;
1937 if (wbc->sync_mode == WB_SYNC_ALL)
1938 tag = PAGECACHE_TAG_TOWRITE;
1940 tag = PAGECACHE_TAG_DIRTY;
1941 btrfs_zoned_meta_io_lock(fs_info);
1943 if (wbc->sync_mode == WB_SYNC_ALL)
1944 tag_pages_for_writeback(mapping, index, end);
1945 while (!done && !nr_to_write_done && (index <= end) &&
1946 (nr_folios = filemap_get_folios_tag(mapping, &index, end,
1950 for (i = 0; i < nr_folios; i++) {
1951 struct folio *folio = fbatch.folios[i];
1953 ret = submit_eb_page(&folio->page, &ctx);
1962 * the filesystem may choose to bump up nr_to_write.
1963 * We have to make sure to honor the new nr_to_write
1966 nr_to_write_done = wbc->nr_to_write <= 0;
1968 folio_batch_release(&fbatch);
1971 if (!scanned && !done) {
1973 * We hit the last page and there is more work to be done: wrap
1974 * back to the start of the file
1981 * If something went wrong, don't allow any metadata write bio to be
1984 * This would prevent use-after-free if we had dirty pages not
1985 * cleaned up, which can still happen by fuzzed images.
1988 * Allowing existing tree block to be allocated for other trees.
1990 * - Log tree operations
1991 * Exiting tree blocks get allocated to log tree, bumps its
1992 * generation, then get cleaned in tree re-balance.
1993 * Such tree block will not be written back, since it's clean,
1994 * thus no WRITTEN flag set.
1995 * And after log writes back, this tree block is not traced by
1996 * any dirty extent_io_tree.
1998 * - Offending tree block gets re-dirtied from its original owner
1999 * Since it has bumped generation, no WRITTEN flag, it can be
2000 * reused without COWing. This tree block will not be traced
2001 * by btrfs_transaction::dirty_pages.
2003 * Now such dirty tree block will not be cleaned by any dirty
2004 * extent io tree. Thus we don't want to submit such wild eb
2005 * if the fs already has error.
2007 * We can get ret > 0 from submit_extent_page() indicating how many ebs
2008 * were submitted. Reset it to 0 to avoid false alerts for the caller.
2012 if (!ret && BTRFS_FS_ERROR(fs_info))
2016 btrfs_put_block_group(ctx.zoned_bg);
2017 btrfs_zoned_meta_io_unlock(fs_info);
2022 * Walk the list of dirty pages of the given address space and write all of them.
2024 * @mapping: address space structure to write
2025 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2026 * @bio_ctrl: holds context for the write, namely the bio
2028 * If a page is already under I/O, write_cache_pages() skips it, even
2029 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
2030 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
2031 * and msync() need to guarantee that all the data which was dirty at the time
2032 * the call was made get new I/O started against them. If wbc->sync_mode is
2033 * WB_SYNC_ALL then we were called for data integrity and we must wait for
2034 * existing IO to complete.
2036 static int extent_write_cache_pages(struct address_space *mapping,
2037 struct btrfs_bio_ctrl *bio_ctrl)
2039 struct writeback_control *wbc = bio_ctrl->wbc;
2040 struct inode *inode = mapping->host;
2043 int nr_to_write_done = 0;
2044 struct folio_batch fbatch;
2045 unsigned int nr_folios;
2047 pgoff_t end; /* Inclusive */
2049 int range_whole = 0;
2054 * We have to hold onto the inode so that ordered extents can do their
2055 * work when the IO finishes. The alternative to this is failing to add
2056 * an ordered extent if the igrab() fails there and that is a huge pain
2057 * to deal with, so instead just hold onto the inode throughout the
2058 * writepages operation. If it fails here we are freeing up the inode
2059 * anyway and we'd rather not waste our time writing out stuff that is
2060 * going to be truncated anyway.
2065 folio_batch_init(&fbatch);
2066 if (wbc->range_cyclic) {
2067 index = mapping->writeback_index; /* Start from prev offset */
2070 * Start from the beginning does not need to cycle over the
2071 * range, mark it as scanned.
2073 scanned = (index == 0);
2075 index = wbc->range_start >> PAGE_SHIFT;
2076 end = wbc->range_end >> PAGE_SHIFT;
2077 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2083 * We do the tagged writepage as long as the snapshot flush bit is set
2084 * and we are the first one who do the filemap_flush() on this inode.
2086 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
2087 * not race in and drop the bit.
2089 if (range_whole && wbc->nr_to_write == LONG_MAX &&
2090 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
2091 &BTRFS_I(inode)->runtime_flags))
2092 wbc->tagged_writepages = 1;
2094 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2095 tag = PAGECACHE_TAG_TOWRITE;
2097 tag = PAGECACHE_TAG_DIRTY;
2099 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2100 tag_pages_for_writeback(mapping, index, end);
2102 while (!done && !nr_to_write_done && (index <= end) &&
2103 (nr_folios = filemap_get_folios_tag(mapping, &index,
2104 end, tag, &fbatch))) {
2107 for (i = 0; i < nr_folios; i++) {
2108 struct folio *folio = fbatch.folios[i];
2110 done_index = folio_next_index(folio);
2112 * At this point we hold neither the i_pages lock nor
2113 * the page lock: the page may be truncated or
2114 * invalidated (changing page->mapping to NULL),
2115 * or even swizzled back from swapper_space to
2116 * tmpfs file mapping
2118 if (!folio_trylock(folio)) {
2119 submit_write_bio(bio_ctrl, 0);
2123 if (unlikely(folio->mapping != mapping)) {
2124 folio_unlock(folio);
2128 if (!folio_test_dirty(folio)) {
2129 /* Someone wrote it for us. */
2130 folio_unlock(folio);
2134 if (wbc->sync_mode != WB_SYNC_NONE) {
2135 if (folio_test_writeback(folio))
2136 submit_write_bio(bio_ctrl, 0);
2137 folio_wait_writeback(folio);
2140 if (folio_test_writeback(folio) ||
2141 !folio_clear_dirty_for_io(folio)) {
2142 folio_unlock(folio);
2146 ret = __extent_writepage(&folio->page, bio_ctrl);
2153 * The filesystem may choose to bump up nr_to_write.
2154 * We have to make sure to honor the new nr_to_write
2157 nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
2158 wbc->nr_to_write <= 0);
2160 folio_batch_release(&fbatch);
2163 if (!scanned && !done) {
2165 * We hit the last page and there is more work to be done: wrap
2166 * back to the start of the file
2172 * If we're looping we could run into a page that is locked by a
2173 * writer and that writer could be waiting on writeback for a
2174 * page in our current bio, and thus deadlock, so flush the
2177 submit_write_bio(bio_ctrl, 0);
2181 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
2182 mapping->writeback_index = done_index;
2184 btrfs_add_delayed_iput(BTRFS_I(inode));
2189 * Submit the pages in the range to bio for call sites which delalloc range has
2190 * already been ran (aka, ordered extent inserted) and all pages are still
2193 void extent_write_locked_range(struct inode *inode, struct page *locked_page,
2194 u64 start, u64 end, struct writeback_control *wbc,
2197 bool found_error = false;
2199 struct address_space *mapping = inode->i_mapping;
2200 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2201 const u32 sectorsize = fs_info->sectorsize;
2202 loff_t i_size = i_size_read(inode);
2204 struct btrfs_bio_ctrl bio_ctrl = {
2206 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2209 if (wbc->no_cgroup_owner)
2210 bio_ctrl.opf |= REQ_BTRFS_CGROUP_PUNT;
2212 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
2214 while (cur <= end) {
2215 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
2216 u32 cur_len = cur_end + 1 - cur;
2220 page = find_get_page(mapping, cur >> PAGE_SHIFT);
2221 ASSERT(PageLocked(page));
2222 if (pages_dirty && page != locked_page) {
2223 ASSERT(PageDirty(page));
2224 clear_page_dirty_for_io(page);
2227 ret = __extent_writepage_io(BTRFS_I(inode), page, &bio_ctrl,
2232 /* Make sure the mapping tag for page dirty gets cleared. */
2234 set_page_writeback(page);
2235 end_page_writeback(page);
2238 btrfs_mark_ordered_io_finished(BTRFS_I(inode), page,
2239 cur, cur_len, !ret);
2240 mapping_set_error(page->mapping, ret);
2242 btrfs_folio_unlock_writer(fs_info, page_folio(page), cur, cur_len);
2250 submit_write_bio(&bio_ctrl, found_error ? ret : 0);
2253 int extent_writepages(struct address_space *mapping,
2254 struct writeback_control *wbc)
2256 struct inode *inode = mapping->host;
2258 struct btrfs_bio_ctrl bio_ctrl = {
2260 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2264 * Allow only a single thread to do the reloc work in zoned mode to
2265 * protect the write pointer updates.
2267 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
2268 ret = extent_write_cache_pages(mapping, &bio_ctrl);
2269 submit_write_bio(&bio_ctrl, ret);
2270 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
2274 void extent_readahead(struct readahead_control *rac)
2276 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ | REQ_RAHEAD };
2277 struct page *pagepool[16];
2278 struct extent_map *em_cached = NULL;
2279 u64 prev_em_start = (u64)-1;
2282 while ((nr = readahead_page_batch(rac, pagepool))) {
2283 u64 contig_start = readahead_pos(rac);
2284 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
2286 contiguous_readpages(pagepool, nr, contig_start, contig_end,
2287 &em_cached, &bio_ctrl, &prev_em_start);
2291 free_extent_map(em_cached);
2292 submit_one_bio(&bio_ctrl);
2296 * basic invalidate_folio code, this waits on any locked or writeback
2297 * ranges corresponding to the folio, and then deletes any extent state
2298 * records from the tree
2300 int extent_invalidate_folio(struct extent_io_tree *tree,
2301 struct folio *folio, size_t offset)
2303 struct extent_state *cached_state = NULL;
2304 u64 start = folio_pos(folio);
2305 u64 end = start + folio_size(folio) - 1;
2306 size_t blocksize = folio_to_fs_info(folio)->sectorsize;
2308 /* This function is only called for the btree inode */
2309 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
2311 start += ALIGN(offset, blocksize);
2315 lock_extent(tree, start, end, &cached_state);
2316 folio_wait_writeback(folio);
2319 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
2320 * so here we only need to unlock the extent range to free any
2321 * existing extent state.
2323 unlock_extent(tree, start, end, &cached_state);
2328 * a helper for release_folio, this tests for areas of the page that
2329 * are locked or under IO and drops the related state bits if it is safe
2332 static int try_release_extent_state(struct extent_io_tree *tree,
2333 struct page *page, gfp_t mask)
2335 u64 start = page_offset(page);
2336 u64 end = start + PAGE_SIZE - 1;
2339 if (test_range_bit_exists(tree, start, end, EXTENT_LOCKED)) {
2342 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
2343 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS |
2344 EXTENT_QGROUP_RESERVED);
2347 * At this point we can safely clear everything except the
2348 * locked bit, the nodatasum bit and the delalloc new bit.
2349 * The delalloc new bit will be cleared by ordered extent
2352 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL, NULL);
2354 /* if clear_extent_bit failed for enomem reasons,
2355 * we can't allow the release to continue.
2366 * a helper for release_folio. As long as there are no locked extents
2367 * in the range corresponding to the page, both state records and extent
2368 * map records are removed
2370 int try_release_extent_mapping(struct page *page, gfp_t mask)
2372 struct extent_map *em;
2373 u64 start = page_offset(page);
2374 u64 end = start + PAGE_SIZE - 1;
2375 struct btrfs_inode *btrfs_inode = page_to_inode(page);
2376 struct extent_io_tree *tree = &btrfs_inode->io_tree;
2377 struct extent_map_tree *map = &btrfs_inode->extent_tree;
2379 if (gfpflags_allow_blocking(mask) &&
2380 page->mapping->host->i_size > SZ_16M) {
2382 while (start <= end) {
2383 struct btrfs_fs_info *fs_info;
2386 len = end - start + 1;
2387 write_lock(&map->lock);
2388 em = lookup_extent_mapping(map, start, len);
2390 write_unlock(&map->lock);
2393 if ((em->flags & EXTENT_FLAG_PINNED) ||
2394 em->start != start) {
2395 write_unlock(&map->lock);
2396 free_extent_map(em);
2399 if (test_range_bit_exists(tree, em->start,
2400 extent_map_end(em) - 1,
2404 * If it's not in the list of modified extents, used
2405 * by a fast fsync, we can remove it. If it's being
2406 * logged we can safely remove it since fsync took an
2407 * extra reference on the em.
2409 if (list_empty(&em->list) ||
2410 (em->flags & EXTENT_FLAG_LOGGING))
2413 * If it's in the list of modified extents, remove it
2414 * only if its generation is older then the current one,
2415 * in which case we don't need it for a fast fsync.
2416 * Otherwise don't remove it, we could be racing with an
2417 * ongoing fast fsync that could miss the new extent.
2419 fs_info = btrfs_inode->root->fs_info;
2420 spin_lock(&fs_info->trans_lock);
2421 cur_gen = fs_info->generation;
2422 spin_unlock(&fs_info->trans_lock);
2423 if (em->generation >= cur_gen)
2427 * We only remove extent maps that are not in the list of
2428 * modified extents or that are in the list but with a
2429 * generation lower then the current generation, so there
2430 * is no need to set the full fsync flag on the inode (it
2431 * hurts the fsync performance for workloads with a data
2432 * size that exceeds or is close to the system's memory).
2434 remove_extent_mapping(map, em);
2435 /* once for the rb tree */
2436 free_extent_map(em);
2438 start = extent_map_end(em);
2439 write_unlock(&map->lock);
2442 free_extent_map(em);
2444 cond_resched(); /* Allow large-extent preemption. */
2447 return try_release_extent_state(tree, page, mask);
2450 struct btrfs_fiemap_entry {
2458 * Indicate the caller of emit_fiemap_extent() that it needs to unlock the file
2459 * range from the inode's io tree, unlock the subvolume tree search path, flush
2460 * the fiemap cache and relock the file range and research the subvolume tree.
2461 * The value here is something negative that can't be confused with a valid
2462 * errno value and different from 1 because that's also a return value from
2463 * fiemap_fill_next_extent() and also it's often used to mean some btree search
2464 * did not find a key, so make it some distinct negative value.
2466 #define BTRFS_FIEMAP_FLUSH_CACHE (-(MAX_ERRNO + 1))
2471 * - Cache the next entry to be emitted to the fiemap buffer, so that we can
2472 * merge extents that are contiguous and can be grouped as a single one;
2474 * - Store extents ready to be written to the fiemap buffer in an intermediary
2475 * buffer. This intermediary buffer is to ensure that in case the fiemap
2476 * buffer is memory mapped to the fiemap target file, we don't deadlock
2477 * during btrfs_page_mkwrite(). This is because during fiemap we are locking
2478 * an extent range in order to prevent races with delalloc flushing and
2479 * ordered extent completion, which is needed in order to reliably detect
2480 * delalloc in holes and prealloc extents. And this can lead to a deadlock
2481 * if the fiemap buffer is memory mapped to the file we are running fiemap
2482 * against (a silly, useless in practice scenario, but possible) because
2483 * btrfs_page_mkwrite() will try to lock the same extent range.
2485 struct fiemap_cache {
2486 /* An array of ready fiemap entries. */
2487 struct btrfs_fiemap_entry *entries;
2488 /* Number of entries in the entries array. */
2490 /* Index of the next entry in the entries array to write to. */
2493 * Once the entries array is full, this indicates what's the offset for
2494 * the next file extent item we must search for in the inode's subvolume
2495 * tree after unlocking the extent range in the inode's io tree and
2496 * releasing the search path.
2498 u64 next_search_offset;
2500 * This matches struct fiemap_extent_info::fi_mapped_extents, we use it
2501 * to count ourselves emitted extents and stop instead of relying on
2502 * fiemap_fill_next_extent() because we buffer ready fiemap entries at
2503 * the @entries array, and we want to stop as soon as we hit the max
2504 * amount of extents to map, not just to save time but also to make the
2505 * logic at extent_fiemap() simpler.
2507 unsigned int extents_mapped;
2508 /* Fields for the cached extent (unsubmitted, not ready, extent). */
2516 static int flush_fiemap_cache(struct fiemap_extent_info *fieinfo,
2517 struct fiemap_cache *cache)
2519 for (int i = 0; i < cache->entries_pos; i++) {
2520 struct btrfs_fiemap_entry *entry = &cache->entries[i];
2523 ret = fiemap_fill_next_extent(fieinfo, entry->offset,
2524 entry->phys, entry->len,
2527 * Ignore 1 (reached max entries) because we keep track of that
2528 * ourselves in emit_fiemap_extent().
2533 cache->entries_pos = 0;
2539 * Helper to submit fiemap extent.
2541 * Will try to merge current fiemap extent specified by @offset, @phys,
2542 * @len and @flags with cached one.
2543 * And only when we fails to merge, cached one will be submitted as
2546 * Return value is the same as fiemap_fill_next_extent().
2548 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
2549 struct fiemap_cache *cache,
2550 u64 offset, u64 phys, u64 len, u32 flags)
2552 struct btrfs_fiemap_entry *entry;
2555 /* Set at the end of extent_fiemap(). */
2556 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
2562 * When iterating the extents of the inode, at extent_fiemap(), we may
2563 * find an extent that starts at an offset behind the end offset of the
2564 * previous extent we processed. This happens if fiemap is called
2565 * without FIEMAP_FLAG_SYNC and there are ordered extents completing
2566 * after we had to unlock the file range, release the search path, emit
2567 * the fiemap extents stored in the buffer (cache->entries array) and
2568 * the lock the remainder of the range and re-search the btree.
2570 * For example we are in leaf X processing its last item, which is the
2571 * file extent item for file range [512K, 1M[, and after
2572 * btrfs_next_leaf() releases the path, there's an ordered extent that
2573 * completes for the file range [768K, 2M[, and that results in trimming
2574 * the file extent item so that it now corresponds to the file range
2575 * [512K, 768K[ and a new file extent item is inserted for the file
2576 * range [768K, 2M[, which may end up as the last item of leaf X or as
2577 * the first item of the next leaf - in either case btrfs_next_leaf()
2578 * will leave us with a path pointing to the new extent item, for the
2579 * file range [768K, 2M[, since that's the first key that follows the
2580 * last one we processed. So in order not to report overlapping extents
2581 * to user space, we trim the length of the previously cached extent and
2584 * Upon calling btrfs_next_leaf() we may also find an extent with an
2585 * offset smaller than or equals to cache->offset, and this happens
2586 * when we had a hole or prealloc extent with several delalloc ranges in
2587 * it, but after btrfs_next_leaf() released the path, delalloc was
2588 * flushed and the resulting ordered extents were completed, so we can
2589 * now have found a file extent item for an offset that is smaller than
2590 * or equals to what we have in cache->offset. We deal with this as
2593 cache_end = cache->offset + cache->len;
2594 if (cache_end > offset) {
2595 if (offset == cache->offset) {
2597 * We cached a dealloc range (found in the io tree) for
2598 * a hole or prealloc extent and we have now found a
2599 * file extent item for the same offset. What we have
2600 * now is more recent and up to date, so discard what
2601 * we had in the cache and use what we have just found.
2604 } else if (offset > cache->offset) {
2606 * The extent range we previously found ends after the
2607 * offset of the file extent item we found and that
2608 * offset falls somewhere in the middle of that previous
2609 * extent range. So adjust the range we previously found
2610 * to end at the offset of the file extent item we have
2611 * just found, since this extent is more up to date.
2612 * Emit that adjusted range and cache the file extent
2613 * item we have just found. This corresponds to the case
2614 * where a previously found file extent item was split
2615 * due to an ordered extent completing.
2617 cache->len = offset - cache->offset;
2620 const u64 range_end = offset + len;
2623 * The offset of the file extent item we have just found
2624 * is behind the cached offset. This means we were
2625 * processing a hole or prealloc extent for which we
2626 * have found delalloc ranges (in the io tree), so what
2627 * we have in the cache is the last delalloc range we
2628 * found while the file extent item we found can be
2629 * either for a whole delalloc range we previously
2630 * emmitted or only a part of that range.
2632 * We have two cases here:
2634 * 1) The file extent item's range ends at or behind the
2635 * cached extent's end. In this case just ignore the
2636 * current file extent item because we don't want to
2637 * overlap with previous ranges that may have been
2640 * 2) The file extent item starts behind the currently
2641 * cached extent but its end offset goes beyond the
2642 * end offset of the cached extent. We don't want to
2643 * overlap with a previous range that may have been
2644 * emmitted already, so we emit the currently cached
2645 * extent and then partially store the current file
2646 * extent item's range in the cache, for the subrange
2647 * going the cached extent's end to the end of the
2650 if (range_end <= cache_end)
2653 if (!(flags & (FIEMAP_EXTENT_ENCODED | FIEMAP_EXTENT_DELALLOC)))
2654 phys += cache_end - offset;
2657 len = range_end - cache_end;
2663 * Only merges fiemap extents if
2664 * 1) Their logical addresses are continuous
2666 * 2) Their physical addresses are continuous
2667 * So truly compressed (physical size smaller than logical size)
2668 * extents won't get merged with each other
2670 * 3) Share same flags
2672 if (cache->offset + cache->len == offset &&
2673 cache->phys + cache->len == phys &&
2674 cache->flags == flags) {
2680 /* Not mergeable, need to submit cached one */
2682 if (cache->entries_pos == cache->entries_size) {
2684 * We will need to research for the end offset of the last
2685 * stored extent and not from the current offset, because after
2686 * unlocking the range and releasing the path, if there's a hole
2687 * between that end offset and this current offset, a new extent
2688 * may have been inserted due to a new write, so we don't want
2691 entry = &cache->entries[cache->entries_size - 1];
2692 cache->next_search_offset = entry->offset + entry->len;
2693 cache->cached = false;
2695 return BTRFS_FIEMAP_FLUSH_CACHE;
2698 entry = &cache->entries[cache->entries_pos];
2699 entry->offset = cache->offset;
2700 entry->phys = cache->phys;
2701 entry->len = cache->len;
2702 entry->flags = cache->flags;
2703 cache->entries_pos++;
2704 cache->extents_mapped++;
2706 if (cache->extents_mapped == fieinfo->fi_extents_max) {
2707 cache->cached = false;
2711 cache->cached = true;
2712 cache->offset = offset;
2715 cache->flags = flags;
2721 * Emit last fiemap cache
2723 * The last fiemap cache may still be cached in the following case:
2725 * |<- Fiemap range ->|
2726 * |<------------ First extent ----------->|
2728 * In this case, the first extent range will be cached but not emitted.
2729 * So we must emit it before ending extent_fiemap().
2731 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
2732 struct fiemap_cache *cache)
2739 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
2740 cache->len, cache->flags);
2741 cache->cached = false;
2747 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
2749 struct extent_buffer *clone;
2750 struct btrfs_key key;
2755 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
2758 ret = btrfs_next_leaf(inode->root, path);
2763 * Don't bother with cloning if there are no more file extent items for
2766 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2767 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
2770 /* See the comment at fiemap_search_slot() about why we clone. */
2771 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2775 slot = path->slots[0];
2776 btrfs_release_path(path);
2777 path->nodes[0] = clone;
2778 path->slots[0] = slot;
2784 * Search for the first file extent item that starts at a given file offset or
2785 * the one that starts immediately before that offset.
2786 * Returns: 0 on success, < 0 on error, 1 if not found.
2788 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
2791 const u64 ino = btrfs_ino(inode);
2792 struct btrfs_root *root = inode->root;
2793 struct extent_buffer *clone;
2794 struct btrfs_key key;
2799 key.type = BTRFS_EXTENT_DATA_KEY;
2800 key.offset = file_offset;
2802 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2806 if (ret > 0 && path->slots[0] > 0) {
2807 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
2808 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
2812 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2813 ret = btrfs_next_leaf(root, path);
2817 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2818 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
2823 * We clone the leaf and use it during fiemap. This is because while
2824 * using the leaf we do expensive things like checking if an extent is
2825 * shared, which can take a long time. In order to prevent blocking
2826 * other tasks for too long, we use a clone of the leaf. We have locked
2827 * the file range in the inode's io tree, so we know none of our file
2828 * extent items can change. This way we avoid blocking other tasks that
2829 * want to insert items for other inodes in the same leaf or b+tree
2830 * rebalance operations (triggered for example when someone is trying
2831 * to push items into this leaf when trying to insert an item in a
2833 * We also need the private clone because holding a read lock on an
2834 * extent buffer of the subvolume's b+tree will make lockdep unhappy
2835 * when we check if extents are shared, as backref walking may need to
2836 * lock the same leaf we are processing.
2838 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2842 slot = path->slots[0];
2843 btrfs_release_path(path);
2844 path->nodes[0] = clone;
2845 path->slots[0] = slot;
2851 * Process a range which is a hole or a prealloc extent in the inode's subvolume
2852 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
2853 * extent. The end offset (@end) is inclusive.
2855 static int fiemap_process_hole(struct btrfs_inode *inode,
2856 struct fiemap_extent_info *fieinfo,
2857 struct fiemap_cache *cache,
2858 struct extent_state **delalloc_cached_state,
2859 struct btrfs_backref_share_check_ctx *backref_ctx,
2860 u64 disk_bytenr, u64 extent_offset,
2864 const u64 i_size = i_size_read(&inode->vfs_inode);
2865 u64 cur_offset = start;
2866 u64 last_delalloc_end = 0;
2867 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
2868 bool checked_extent_shared = false;
2872 * There can be no delalloc past i_size, so don't waste time looking for
2875 while (cur_offset < end && cur_offset < i_size) {
2879 u64 prealloc_len = 0;
2882 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
2883 delalloc_cached_state,
2890 * If this is a prealloc extent we have to report every section
2891 * of it that has no delalloc.
2893 if (disk_bytenr != 0) {
2894 if (last_delalloc_end == 0) {
2895 prealloc_start = start;
2896 prealloc_len = delalloc_start - start;
2898 prealloc_start = last_delalloc_end + 1;
2899 prealloc_len = delalloc_start - prealloc_start;
2903 if (prealloc_len > 0) {
2904 if (!checked_extent_shared && fieinfo->fi_extents_max) {
2905 ret = btrfs_is_data_extent_shared(inode,
2912 prealloc_flags |= FIEMAP_EXTENT_SHARED;
2914 checked_extent_shared = true;
2916 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
2917 disk_bytenr + extent_offset,
2918 prealloc_len, prealloc_flags);
2921 extent_offset += prealloc_len;
2924 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
2925 delalloc_end + 1 - delalloc_start,
2926 FIEMAP_EXTENT_DELALLOC |
2927 FIEMAP_EXTENT_UNKNOWN);
2931 last_delalloc_end = delalloc_end;
2932 cur_offset = delalloc_end + 1;
2933 extent_offset += cur_offset - delalloc_start;
2938 * Either we found no delalloc for the whole prealloc extent or we have
2939 * a prealloc extent that spans i_size or starts at or after i_size.
2941 if (disk_bytenr != 0 && last_delalloc_end < end) {
2945 if (last_delalloc_end == 0) {
2946 prealloc_start = start;
2947 prealloc_len = end + 1 - start;
2949 prealloc_start = last_delalloc_end + 1;
2950 prealloc_len = end + 1 - prealloc_start;
2953 if (!checked_extent_shared && fieinfo->fi_extents_max) {
2954 ret = btrfs_is_data_extent_shared(inode,
2961 prealloc_flags |= FIEMAP_EXTENT_SHARED;
2963 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
2964 disk_bytenr + extent_offset,
2965 prealloc_len, prealloc_flags);
2973 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
2974 struct btrfs_path *path,
2975 u64 *last_extent_end_ret)
2977 const u64 ino = btrfs_ino(inode);
2978 struct btrfs_root *root = inode->root;
2979 struct extent_buffer *leaf;
2980 struct btrfs_file_extent_item *ei;
2981 struct btrfs_key key;
2986 * Lookup the last file extent. We're not using i_size here because
2987 * there might be preallocation past i_size.
2989 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
2990 /* There can't be a file extent item at offset (u64)-1 */
2996 * For a non-existing key, btrfs_search_slot() always leaves us at a
2997 * slot > 0, except if the btree is empty, which is impossible because
2998 * at least it has the inode item for this inode and all the items for
2999 * the root inode 256.
3001 ASSERT(path->slots[0] > 0);
3003 leaf = path->nodes[0];
3004 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3005 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3006 /* No file extent items in the subvolume tree. */
3007 *last_extent_end_ret = 0;
3012 * For an inline extent, the disk_bytenr is where inline data starts at,
3013 * so first check if we have an inline extent item before checking if we
3014 * have an implicit hole (disk_bytenr == 0).
3016 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3017 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3018 *last_extent_end_ret = btrfs_file_extent_end(path);
3023 * Find the last file extent item that is not a hole (when NO_HOLES is
3024 * not enabled). This should take at most 2 iterations in the worst
3025 * case: we have one hole file extent item at slot 0 of a leaf and
3026 * another hole file extent item as the last item in the previous leaf.
3027 * This is because we merge file extent items that represent holes.
3029 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3030 while (disk_bytenr == 0) {
3031 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3034 } else if (ret > 0) {
3035 /* No file extent items that are not holes. */
3036 *last_extent_end_ret = 0;
3039 leaf = path->nodes[0];
3040 ei = btrfs_item_ptr(leaf, path->slots[0],
3041 struct btrfs_file_extent_item);
3042 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3045 *last_extent_end_ret = btrfs_file_extent_end(path);
3049 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3052 const u64 ino = btrfs_ino(inode);
3053 struct extent_state *cached_state = NULL;
3054 struct extent_state *delalloc_cached_state = NULL;
3055 struct btrfs_path *path;
3056 struct fiemap_cache cache = { 0 };
3057 struct btrfs_backref_share_check_ctx *backref_ctx;
3058 u64 last_extent_end;
3059 u64 prev_extent_end;
3062 const u64 sectorsize = inode->root->fs_info->sectorsize;
3063 bool stopped = false;
3066 cache.entries_size = PAGE_SIZE / sizeof(struct btrfs_fiemap_entry);
3067 cache.entries = kmalloc_array(cache.entries_size,
3068 sizeof(struct btrfs_fiemap_entry),
3070 backref_ctx = btrfs_alloc_backref_share_check_ctx();
3071 path = btrfs_alloc_path();
3072 if (!cache.entries || !backref_ctx || !path) {
3078 range_start = round_down(start, sectorsize);
3079 range_end = round_up(start + len, sectorsize);
3080 prev_extent_end = range_start;
3082 lock_extent(&inode->io_tree, range_start, range_end, &cached_state);
3084 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3087 btrfs_release_path(path);
3089 path->reada = READA_FORWARD;
3090 ret = fiemap_search_slot(inode, path, range_start);
3093 } else if (ret > 0) {
3095 * No file extent item found, but we may have delalloc between
3096 * the current offset and i_size. So check for that.
3099 goto check_eof_delalloc;
3102 while (prev_extent_end < range_end) {
3103 struct extent_buffer *leaf = path->nodes[0];
3104 struct btrfs_file_extent_item *ei;
3105 struct btrfs_key key;
3108 u64 extent_offset = 0;
3110 u64 disk_bytenr = 0;
3115 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3116 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3119 extent_end = btrfs_file_extent_end(path);
3122 * The first iteration can leave us at an extent item that ends
3123 * before our range's start. Move to the next item.
3125 if (extent_end <= range_start)
3128 backref_ctx->curr_leaf_bytenr = leaf->start;
3130 /* We have in implicit hole (NO_HOLES feature enabled). */
3131 if (prev_extent_end < key.offset) {
3132 const u64 hole_end = min(key.offset, range_end) - 1;
3134 ret = fiemap_process_hole(inode, fieinfo, &cache,
3135 &delalloc_cached_state,
3136 backref_ctx, 0, 0, 0,
3137 prev_extent_end, hole_end);
3140 } else if (ret > 0) {
3141 /* fiemap_fill_next_extent() told us to stop. */
3146 /* We've reached the end of the fiemap range, stop. */
3147 if (key.offset >= range_end) {
3153 extent_len = extent_end - key.offset;
3154 ei = btrfs_item_ptr(leaf, path->slots[0],
3155 struct btrfs_file_extent_item);
3156 compression = btrfs_file_extent_compression(leaf, ei);
3157 extent_type = btrfs_file_extent_type(leaf, ei);
3158 extent_gen = btrfs_file_extent_generation(leaf, ei);
3160 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3161 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3162 if (compression == BTRFS_COMPRESS_NONE)
3163 extent_offset = btrfs_file_extent_offset(leaf, ei);
3166 if (compression != BTRFS_COMPRESS_NONE)
3167 flags |= FIEMAP_EXTENT_ENCODED;
3169 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3170 flags |= FIEMAP_EXTENT_DATA_INLINE;
3171 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
3172 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
3174 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
3175 ret = fiemap_process_hole(inode, fieinfo, &cache,
3176 &delalloc_cached_state,
3178 disk_bytenr, extent_offset,
3179 extent_gen, key.offset,
3181 } else if (disk_bytenr == 0) {
3182 /* We have an explicit hole. */
3183 ret = fiemap_process_hole(inode, fieinfo, &cache,
3184 &delalloc_cached_state,
3185 backref_ctx, 0, 0, 0,
3186 key.offset, extent_end - 1);
3188 /* We have a regular extent. */
3189 if (fieinfo->fi_extents_max) {
3190 ret = btrfs_is_data_extent_shared(inode,
3197 flags |= FIEMAP_EXTENT_SHARED;
3200 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
3201 disk_bytenr + extent_offset,
3207 } else if (ret > 0) {
3208 /* emit_fiemap_extent() told us to stop. */
3213 prev_extent_end = extent_end;
3215 if (fatal_signal_pending(current)) {
3220 ret = fiemap_next_leaf_item(inode, path);
3223 } else if (ret > 0) {
3224 /* No more file extent items for this inode. */
3231 if (!stopped && prev_extent_end < range_end) {
3232 ret = fiemap_process_hole(inode, fieinfo, &cache,
3233 &delalloc_cached_state, backref_ctx,
3234 0, 0, 0, prev_extent_end, range_end - 1);
3237 prev_extent_end = range_end;
3240 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
3241 const u64 i_size = i_size_read(&inode->vfs_inode);
3243 if (prev_extent_end < i_size) {
3248 delalloc = btrfs_find_delalloc_in_range(inode,
3251 &delalloc_cached_state,
3255 cache.flags |= FIEMAP_EXTENT_LAST;
3257 cache.flags |= FIEMAP_EXTENT_LAST;
3262 unlock_extent(&inode->io_tree, range_start, range_end, &cached_state);
3264 if (ret == BTRFS_FIEMAP_FLUSH_CACHE) {
3265 btrfs_release_path(path);
3266 ret = flush_fiemap_cache(fieinfo, &cache);
3269 len -= cache.next_search_offset - start;
3270 start = cache.next_search_offset;
3272 } else if (ret < 0) {
3277 * Must free the path before emitting to the fiemap buffer because we
3278 * may have a non-cloned leaf and if the fiemap buffer is memory mapped
3279 * to a file, a write into it (through btrfs_page_mkwrite()) may trigger
3280 * waiting for an ordered extent that in order to complete needs to
3281 * modify that leaf, therefore leading to a deadlock.
3283 btrfs_free_path(path);
3286 ret = flush_fiemap_cache(fieinfo, &cache);
3290 ret = emit_last_fiemap_cache(fieinfo, &cache);
3292 free_extent_state(delalloc_cached_state);
3293 kfree(cache.entries);
3294 btrfs_free_backref_share_ctx(backref_ctx);
3295 btrfs_free_path(path);
3299 static void __free_extent_buffer(struct extent_buffer *eb)
3301 kmem_cache_free(extent_buffer_cache, eb);
3304 static int extent_buffer_under_io(const struct extent_buffer *eb)
3306 return (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
3307 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3310 static bool folio_range_has_eb(struct btrfs_fs_info *fs_info, struct folio *folio)
3312 struct btrfs_subpage *subpage;
3314 lockdep_assert_held(&folio->mapping->i_private_lock);
3316 if (folio_test_private(folio)) {
3317 subpage = folio_get_private(folio);
3318 if (atomic_read(&subpage->eb_refs))
3321 * Even there is no eb refs here, we may still have
3322 * end_page_read() call relying on page::private.
3324 if (atomic_read(&subpage->readers))
3330 static void detach_extent_buffer_folio(struct extent_buffer *eb, struct folio *folio)
3332 struct btrfs_fs_info *fs_info = eb->fs_info;
3333 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3336 * For mapped eb, we're going to change the folio private, which should
3337 * be done under the i_private_lock.
3340 spin_lock(&folio->mapping->i_private_lock);
3342 if (!folio_test_private(folio)) {
3344 spin_unlock(&folio->mapping->i_private_lock);
3348 if (fs_info->nodesize >= PAGE_SIZE) {
3350 * We do this since we'll remove the pages after we've
3351 * removed the eb from the radix tree, so we could race
3352 * and have this page now attached to the new eb. So
3353 * only clear folio if it's still connected to
3356 if (folio_test_private(folio) && folio_get_private(folio) == eb) {
3357 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3358 BUG_ON(folio_test_dirty(folio));
3359 BUG_ON(folio_test_writeback(folio));
3360 /* We need to make sure we haven't be attached to a new eb. */
3361 folio_detach_private(folio);
3364 spin_unlock(&folio->mapping->i_private_lock);
3369 * For subpage, we can have dummy eb with folio private attached. In
3370 * this case, we can directly detach the private as such folio is only
3371 * attached to one dummy eb, no sharing.
3374 btrfs_detach_subpage(fs_info, folio);
3378 btrfs_folio_dec_eb_refs(fs_info, folio);
3381 * We can only detach the folio private if there are no other ebs in the
3382 * page range and no unfinished IO.
3384 if (!folio_range_has_eb(fs_info, folio))
3385 btrfs_detach_subpage(fs_info, folio);
3387 spin_unlock(&folio->mapping->i_private_lock);
3390 /* Release all pages attached to the extent buffer */
3391 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
3393 ASSERT(!extent_buffer_under_io(eb));
3395 for (int i = 0; i < INLINE_EXTENT_BUFFER_PAGES; i++) {
3396 struct folio *folio = eb->folios[i];
3401 detach_extent_buffer_folio(eb, folio);
3403 /* One for when we allocated the folio. */
3409 * Helper for releasing the extent buffer.
3411 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
3413 btrfs_release_extent_buffer_pages(eb);
3414 btrfs_leak_debug_del_eb(eb);
3415 __free_extent_buffer(eb);
3418 static struct extent_buffer *
3419 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
3422 struct extent_buffer *eb = NULL;
3424 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
3427 eb->fs_info = fs_info;
3428 init_rwsem(&eb->lock);
3430 btrfs_leak_debug_add_eb(eb);
3432 spin_lock_init(&eb->refs_lock);
3433 atomic_set(&eb->refs, 1);
3435 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
3440 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
3442 struct extent_buffer *new;
3443 int num_folios = num_extent_folios(src);
3446 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
3451 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
3452 * btrfs_release_extent_buffer() have different behavior for
3453 * UNMAPPED subpage extent buffer.
3455 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
3457 ret = alloc_eb_folio_array(new, 0);
3459 btrfs_release_extent_buffer(new);
3463 for (int i = 0; i < num_folios; i++) {
3464 struct folio *folio = new->folios[i];
3467 ret = attach_extent_buffer_folio(new, folio, NULL);
3469 btrfs_release_extent_buffer(new);
3472 WARN_ON(folio_test_dirty(folio));
3474 copy_extent_buffer_full(new, src);
3475 set_extent_buffer_uptodate(new);
3480 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3481 u64 start, unsigned long len)
3483 struct extent_buffer *eb;
3487 eb = __alloc_extent_buffer(fs_info, start, len);
3491 ret = alloc_eb_folio_array(eb, 0);
3495 num_folios = num_extent_folios(eb);
3496 for (int i = 0; i < num_folios; i++) {
3497 ret = attach_extent_buffer_folio(eb, eb->folios[i], NULL);
3502 set_extent_buffer_uptodate(eb);
3503 btrfs_set_header_nritems(eb, 0);
3504 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3508 for (int i = 0; i < num_folios; i++) {
3509 if (eb->folios[i]) {
3510 detach_extent_buffer_folio(eb, eb->folios[i]);
3511 __folio_put(eb->folios[i]);
3514 __free_extent_buffer(eb);
3518 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3521 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
3524 static void check_buffer_tree_ref(struct extent_buffer *eb)
3528 * The TREE_REF bit is first set when the extent_buffer is added
3529 * to the radix tree. It is also reset, if unset, when a new reference
3530 * is created by find_extent_buffer.
3532 * It is only cleared in two cases: freeing the last non-tree
3533 * reference to the extent_buffer when its STALE bit is set or
3534 * calling release_folio when the tree reference is the only reference.
3536 * In both cases, care is taken to ensure that the extent_buffer's
3537 * pages are not under io. However, release_folio can be concurrently
3538 * called with creating new references, which is prone to race
3539 * conditions between the calls to check_buffer_tree_ref in those
3540 * codepaths and clearing TREE_REF in try_release_extent_buffer.
3542 * The actual lifetime of the extent_buffer in the radix tree is
3543 * adequately protected by the refcount, but the TREE_REF bit and
3544 * its corresponding reference are not. To protect against this
3545 * class of races, we call check_buffer_tree_ref from the codepaths
3546 * which trigger io. Note that once io is initiated, TREE_REF can no
3547 * longer be cleared, so that is the moment at which any such race is
3550 refs = atomic_read(&eb->refs);
3551 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3554 spin_lock(&eb->refs_lock);
3555 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3556 atomic_inc(&eb->refs);
3557 spin_unlock(&eb->refs_lock);
3560 static void mark_extent_buffer_accessed(struct extent_buffer *eb)
3562 int num_folios= num_extent_folios(eb);
3564 check_buffer_tree_ref(eb);
3566 for (int i = 0; i < num_folios; i++)
3567 folio_mark_accessed(eb->folios[i]);
3570 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
3573 struct extent_buffer *eb;
3575 eb = find_extent_buffer_nolock(fs_info, start);
3579 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
3580 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
3581 * another task running free_extent_buffer() might have seen that flag
3582 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
3583 * writeback flags not set) and it's still in the tree (flag
3584 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
3585 * decrementing the extent buffer's reference count twice. So here we
3586 * could race and increment the eb's reference count, clear its stale
3587 * flag, mark it as dirty and drop our reference before the other task
3588 * finishes executing free_extent_buffer, which would later result in
3589 * an attempt to free an extent buffer that is dirty.
3591 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
3592 spin_lock(&eb->refs_lock);
3593 spin_unlock(&eb->refs_lock);
3595 mark_extent_buffer_accessed(eb);
3599 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3600 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
3603 struct extent_buffer *eb, *exists = NULL;
3606 eb = find_extent_buffer(fs_info, start);
3609 eb = alloc_dummy_extent_buffer(fs_info, start);
3611 return ERR_PTR(-ENOMEM);
3612 eb->fs_info = fs_info;
3614 ret = radix_tree_preload(GFP_NOFS);
3616 exists = ERR_PTR(ret);
3619 spin_lock(&fs_info->buffer_lock);
3620 ret = radix_tree_insert(&fs_info->buffer_radix,
3621 start >> fs_info->sectorsize_bits, eb);
3622 spin_unlock(&fs_info->buffer_lock);
3623 radix_tree_preload_end();
3624 if (ret == -EEXIST) {
3625 exists = find_extent_buffer(fs_info, start);
3631 check_buffer_tree_ref(eb);
3632 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3636 btrfs_release_extent_buffer(eb);
3641 static struct extent_buffer *grab_extent_buffer(
3642 struct btrfs_fs_info *fs_info, struct page *page)
3644 struct folio *folio = page_folio(page);
3645 struct extent_buffer *exists;
3648 * For subpage case, we completely rely on radix tree to ensure we
3649 * don't try to insert two ebs for the same bytenr. So here we always
3650 * return NULL and just continue.
3652 if (fs_info->nodesize < PAGE_SIZE)
3655 /* Page not yet attached to an extent buffer */
3656 if (!folio_test_private(folio))
3660 * We could have already allocated an eb for this page and attached one
3661 * so lets see if we can get a ref on the existing eb, and if we can we
3662 * know it's good and we can just return that one, else we know we can
3663 * just overwrite folio private.
3665 exists = folio_get_private(folio);
3666 if (atomic_inc_not_zero(&exists->refs))
3669 WARN_ON(PageDirty(page));
3670 folio_detach_private(folio);
3674 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
3676 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
3677 btrfs_err(fs_info, "bad tree block start %llu", start);
3681 if (fs_info->nodesize < PAGE_SIZE &&
3682 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
3684 "tree block crosses page boundary, start %llu nodesize %u",
3685 start, fs_info->nodesize);
3688 if (fs_info->nodesize >= PAGE_SIZE &&
3689 !PAGE_ALIGNED(start)) {
3691 "tree block is not page aligned, start %llu nodesize %u",
3692 start, fs_info->nodesize);
3695 if (!IS_ALIGNED(start, fs_info->nodesize) &&
3696 !test_and_set_bit(BTRFS_FS_UNALIGNED_TREE_BLOCK, &fs_info->flags)) {
3698 "tree block not nodesize aligned, start %llu nodesize %u, can be resolved by a full metadata balance",
3699 start, fs_info->nodesize);
3706 * Return 0 if eb->folios[i] is attached to btree inode successfully.
3707 * Return >0 if there is already another extent buffer for the range,
3708 * and @found_eb_ret would be updated.
3709 * Return -EAGAIN if the filemap has an existing folio but with different size
3711 * The caller needs to free the existing folios and retry using the same order.
3713 static int attach_eb_folio_to_filemap(struct extent_buffer *eb, int i,
3714 struct extent_buffer **found_eb_ret)
3717 struct btrfs_fs_info *fs_info = eb->fs_info;
3718 struct address_space *mapping = fs_info->btree_inode->i_mapping;
3719 const unsigned long index = eb->start >> PAGE_SHIFT;
3720 struct folio *existing_folio;
3723 ASSERT(found_eb_ret);
3725 /* Caller should ensure the folio exists. */
3726 ASSERT(eb->folios[i]);
3729 ret = filemap_add_folio(mapping, eb->folios[i], index + i,
3730 GFP_NOFS | __GFP_NOFAIL);
3734 existing_folio = filemap_lock_folio(mapping, index + i);
3735 /* The page cache only exists for a very short time, just retry. */
3736 if (IS_ERR(existing_folio))
3739 /* For now, we should only have single-page folios for btree inode. */
3740 ASSERT(folio_nr_pages(existing_folio) == 1);
3742 if (folio_size(existing_folio) != folio_size(eb->folios[0])) {
3743 folio_unlock(existing_folio);
3744 folio_put(existing_folio);
3748 if (fs_info->nodesize < PAGE_SIZE) {
3750 * We're going to reuse the existing page, can drop our page
3751 * and subpage structure now.
3753 __free_page(folio_page(eb->folios[i], 0));
3754 eb->folios[i] = existing_folio;
3756 struct extent_buffer *existing_eb;
3758 existing_eb = grab_extent_buffer(fs_info,
3759 folio_page(existing_folio, 0));
3761 /* The extent buffer still exists, we can use it directly. */
3762 *found_eb_ret = existing_eb;
3763 folio_unlock(existing_folio);
3764 folio_put(existing_folio);
3767 /* The extent buffer no longer exists, we can reuse the folio. */
3768 __free_page(folio_page(eb->folios[i], 0));
3769 eb->folios[i] = existing_folio;
3774 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3775 u64 start, u64 owner_root, int level)
3777 unsigned long len = fs_info->nodesize;
3780 struct extent_buffer *eb;
3781 struct extent_buffer *existing_eb = NULL;
3782 struct address_space *mapping = fs_info->btree_inode->i_mapping;
3783 struct btrfs_subpage *prealloc = NULL;
3784 u64 lockdep_owner = owner_root;
3785 bool page_contig = true;
3789 if (check_eb_alignment(fs_info, start))
3790 return ERR_PTR(-EINVAL);
3792 #if BITS_PER_LONG == 32
3793 if (start >= MAX_LFS_FILESIZE) {
3794 btrfs_err_rl(fs_info,
3795 "extent buffer %llu is beyond 32bit page cache limit", start);
3796 btrfs_err_32bit_limit(fs_info);
3797 return ERR_PTR(-EOVERFLOW);
3799 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
3800 btrfs_warn_32bit_limit(fs_info);
3803 eb = find_extent_buffer(fs_info, start);
3807 eb = __alloc_extent_buffer(fs_info, start, len);
3809 return ERR_PTR(-ENOMEM);
3812 * The reloc trees are just snapshots, so we need them to appear to be
3813 * just like any other fs tree WRT lockdep.
3815 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
3816 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
3818 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
3821 * Preallocate folio private for subpage case, so that we won't
3822 * allocate memory with i_private_lock nor page lock hold.
3824 * The memory will be freed by attach_extent_buffer_page() or freed
3825 * manually if we exit earlier.
3827 if (fs_info->nodesize < PAGE_SIZE) {
3828 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
3829 if (IS_ERR(prealloc)) {
3830 ret = PTR_ERR(prealloc);
3836 /* Allocate all pages first. */
3837 ret = alloc_eb_folio_array(eb, __GFP_NOFAIL);
3839 btrfs_free_subpage(prealloc);
3843 num_folios = num_extent_folios(eb);
3844 /* Attach all pages to the filemap. */
3845 for (int i = 0; i < num_folios; i++) {
3846 struct folio *folio;
3848 ret = attach_eb_folio_to_filemap(eb, i, &existing_eb);
3850 ASSERT(existing_eb);
3855 * TODO: Special handling for a corner case where the order of
3856 * folios mismatch between the new eb and filemap.
3858 * This happens when:
3860 * - the new eb is using higher order folio
3862 * - the filemap is still using 0-order folios for the range
3863 * This can happen at the previous eb allocation, and we don't
3864 * have higher order folio for the call.
3866 * - the existing eb has already been freed
3868 * In this case, we have to free the existing folios first, and
3869 * re-allocate using the same order.
3870 * Thankfully this is not going to happen yet, as we're still
3871 * using 0-order folios.
3873 if (unlikely(ret == -EAGAIN)) {
3880 * Only after attach_eb_folio_to_filemap(), eb->folios[] is
3881 * reliable, as we may choose to reuse the existing page cache
3882 * and free the allocated page.
3884 folio = eb->folios[i];
3885 spin_lock(&mapping->i_private_lock);
3886 /* Should not fail, as we have preallocated the memory */
3887 ret = attach_extent_buffer_folio(eb, folio, prealloc);
3890 * To inform we have extra eb under allocation, so that
3891 * detach_extent_buffer_page() won't release the folio private
3892 * when the eb hasn't yet been inserted into radix tree.
3894 * The ref will be decreased when the eb released the page, in
3895 * detach_extent_buffer_page().
3896 * Thus needs no special handling in error path.
3898 btrfs_folio_inc_eb_refs(fs_info, folio);
3899 spin_unlock(&mapping->i_private_lock);
3901 WARN_ON(btrfs_folio_test_dirty(fs_info, folio, eb->start, eb->len));
3904 * Check if the current page is physically contiguous with previous eb
3906 * At this stage, either we allocated a large folio, thus @i
3907 * would only be 0, or we fall back to per-page allocation.
3909 if (i && folio_page(eb->folios[i - 1], 0) + 1 != folio_page(folio, 0))
3910 page_contig = false;
3912 if (!btrfs_folio_test_uptodate(fs_info, folio, eb->start, eb->len))
3916 * We can't unlock the pages just yet since the extent buffer
3917 * hasn't been properly inserted in the radix tree, this
3918 * opens a race with btree_release_folio which can free a page
3919 * while we are still filling in all pages for the buffer and
3924 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3925 /* All pages are physically contiguous, can skip cross page handling. */
3927 eb->addr = folio_address(eb->folios[0]) + offset_in_page(eb->start);
3929 ret = radix_tree_preload(GFP_NOFS);
3933 spin_lock(&fs_info->buffer_lock);
3934 ret = radix_tree_insert(&fs_info->buffer_radix,
3935 start >> fs_info->sectorsize_bits, eb);
3936 spin_unlock(&fs_info->buffer_lock);
3937 radix_tree_preload_end();
3938 if (ret == -EEXIST) {
3940 existing_eb = find_extent_buffer(fs_info, start);
3946 /* add one reference for the tree */
3947 check_buffer_tree_ref(eb);
3948 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3951 * Now it's safe to unlock the pages because any calls to
3952 * btree_release_folio will correctly detect that a page belongs to a
3953 * live buffer and won't free them prematurely.
3955 for (int i = 0; i < num_folios; i++)
3956 unlock_page(folio_page(eb->folios[i], 0));
3960 WARN_ON(!atomic_dec_and_test(&eb->refs));
3963 * Any attached folios need to be detached before we unlock them. This
3964 * is because when we're inserting our new folios into the mapping, and
3965 * then attaching our eb to that folio. If we fail to insert our folio
3966 * we'll lookup the folio for that index, and grab that EB. We do not
3967 * want that to grab this eb, as we're getting ready to free it. So we
3968 * have to detach it first and then unlock it.
3970 * We have to drop our reference and NULL it out here because in the
3971 * subpage case detaching does a btrfs_folio_dec_eb_refs() for our eb.
3972 * Below when we call btrfs_release_extent_buffer() we will call
3973 * detach_extent_buffer_folio() on our remaining pages in the !subpage
3974 * case. If we left eb->folios[i] populated in the subpage case we'd
3975 * double put our reference and be super sad.
3977 for (int i = 0; i < attached; i++) {
3978 ASSERT(eb->folios[i]);
3979 detach_extent_buffer_folio(eb, eb->folios[i]);
3980 unlock_page(folio_page(eb->folios[i], 0));
3981 folio_put(eb->folios[i]);
3982 eb->folios[i] = NULL;
3985 * Now all pages of that extent buffer is unmapped, set UNMAPPED flag,
3986 * so it can be cleaned up without utlizing page->mapping.
3988 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3990 btrfs_release_extent_buffer(eb);
3992 return ERR_PTR(ret);
3993 ASSERT(existing_eb);
3997 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
3999 struct extent_buffer *eb =
4000 container_of(head, struct extent_buffer, rcu_head);
4002 __free_extent_buffer(eb);
4005 static int release_extent_buffer(struct extent_buffer *eb)
4006 __releases(&eb->refs_lock)
4008 lockdep_assert_held(&eb->refs_lock);
4010 WARN_ON(atomic_read(&eb->refs) == 0);
4011 if (atomic_dec_and_test(&eb->refs)) {
4012 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4013 struct btrfs_fs_info *fs_info = eb->fs_info;
4015 spin_unlock(&eb->refs_lock);
4017 spin_lock(&fs_info->buffer_lock);
4018 radix_tree_delete(&fs_info->buffer_radix,
4019 eb->start >> fs_info->sectorsize_bits);
4020 spin_unlock(&fs_info->buffer_lock);
4022 spin_unlock(&eb->refs_lock);
4025 btrfs_leak_debug_del_eb(eb);
4026 /* Should be safe to release our pages at this point */
4027 btrfs_release_extent_buffer_pages(eb);
4028 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4029 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4030 __free_extent_buffer(eb);
4034 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4037 spin_unlock(&eb->refs_lock);
4042 void free_extent_buffer(struct extent_buffer *eb)
4048 refs = atomic_read(&eb->refs);
4050 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4051 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4054 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4058 spin_lock(&eb->refs_lock);
4059 if (atomic_read(&eb->refs) == 2 &&
4060 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4061 !extent_buffer_under_io(eb) &&
4062 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4063 atomic_dec(&eb->refs);
4066 * I know this is terrible, but it's temporary until we stop tracking
4067 * the uptodate bits and such for the extent buffers.
4069 release_extent_buffer(eb);
4072 void free_extent_buffer_stale(struct extent_buffer *eb)
4077 spin_lock(&eb->refs_lock);
4078 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4080 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4081 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4082 atomic_dec(&eb->refs);
4083 release_extent_buffer(eb);
4086 static void btree_clear_folio_dirty(struct folio *folio)
4088 ASSERT(folio_test_dirty(folio));
4089 ASSERT(folio_test_locked(folio));
4090 folio_clear_dirty_for_io(folio);
4091 xa_lock_irq(&folio->mapping->i_pages);
4092 if (!folio_test_dirty(folio))
4093 __xa_clear_mark(&folio->mapping->i_pages,
4094 folio_index(folio), PAGECACHE_TAG_DIRTY);
4095 xa_unlock_irq(&folio->mapping->i_pages);
4098 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4100 struct btrfs_fs_info *fs_info = eb->fs_info;
4101 struct folio *folio = eb->folios[0];
4104 /* btree_clear_folio_dirty() needs page locked. */
4106 last = btrfs_subpage_clear_and_test_dirty(fs_info, folio, eb->start, eb->len);
4108 btree_clear_folio_dirty(folio);
4109 folio_unlock(folio);
4110 WARN_ON(atomic_read(&eb->refs) == 0);
4113 void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
4114 struct extent_buffer *eb)
4116 struct btrfs_fs_info *fs_info = eb->fs_info;
4119 btrfs_assert_tree_write_locked(eb);
4121 if (trans && btrfs_header_generation(eb) != trans->transid)
4125 * Instead of clearing the dirty flag off of the buffer, mark it as
4126 * EXTENT_BUFFER_ZONED_ZEROOUT. This allows us to preserve
4127 * write-ordering in zoned mode, without the need to later re-dirty
4128 * the extent_buffer.
4130 * The actual zeroout of the buffer will happen later in
4131 * btree_csum_one_bio.
4133 if (btrfs_is_zoned(fs_info) && test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4134 set_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags);
4138 if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
4141 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
4142 fs_info->dirty_metadata_batch);
4144 if (eb->fs_info->nodesize < PAGE_SIZE)
4145 return clear_subpage_extent_buffer_dirty(eb);
4147 num_folios = num_extent_folios(eb);
4148 for (int i = 0; i < num_folios; i++) {
4149 struct folio *folio = eb->folios[i];
4151 if (!folio_test_dirty(folio))
4154 btree_clear_folio_dirty(folio);
4155 folio_unlock(folio);
4157 WARN_ON(atomic_read(&eb->refs) == 0);
4160 void set_extent_buffer_dirty(struct extent_buffer *eb)
4165 check_buffer_tree_ref(eb);
4167 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4169 num_folios = num_extent_folios(eb);
4170 WARN_ON(atomic_read(&eb->refs) == 0);
4171 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4174 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4177 * For subpage case, we can have other extent buffers in the
4178 * same page, and in clear_subpage_extent_buffer_dirty() we
4179 * have to clear page dirty without subpage lock held.
4180 * This can cause race where our page gets dirty cleared after
4183 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4184 * its page for other reasons, we can use page lock to prevent
4188 lock_page(folio_page(eb->folios[0], 0));
4189 for (int i = 0; i < num_folios; i++)
4190 btrfs_folio_set_dirty(eb->fs_info, eb->folios[i],
4191 eb->start, eb->len);
4193 unlock_page(folio_page(eb->folios[0], 0));
4194 percpu_counter_add_batch(&eb->fs_info->dirty_metadata_bytes,
4196 eb->fs_info->dirty_metadata_batch);
4198 #ifdef CONFIG_BTRFS_DEBUG
4199 for (int i = 0; i < num_folios; i++)
4200 ASSERT(folio_test_dirty(eb->folios[i]));
4204 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4206 struct btrfs_fs_info *fs_info = eb->fs_info;
4207 int num_folios = num_extent_folios(eb);
4209 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4210 for (int i = 0; i < num_folios; i++) {
4211 struct folio *folio = eb->folios[i];
4217 * This is special handling for metadata subpage, as regular
4218 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4220 if (fs_info->nodesize >= PAGE_SIZE)
4221 folio_clear_uptodate(folio);
4223 btrfs_subpage_clear_uptodate(fs_info, folio,
4224 eb->start, eb->len);
4228 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4230 struct btrfs_fs_info *fs_info = eb->fs_info;
4231 int num_folios = num_extent_folios(eb);
4233 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4234 for (int i = 0; i < num_folios; i++) {
4235 struct folio *folio = eb->folios[i];
4238 * This is special handling for metadata subpage, as regular
4239 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4241 if (fs_info->nodesize >= PAGE_SIZE)
4242 folio_mark_uptodate(folio);
4244 btrfs_subpage_set_uptodate(fs_info, folio,
4245 eb->start, eb->len);
4249 static void end_bbio_meta_read(struct btrfs_bio *bbio)
4251 struct extent_buffer *eb = bbio->private;
4252 struct btrfs_fs_info *fs_info = eb->fs_info;
4253 bool uptodate = !bbio->bio.bi_status;
4254 struct folio_iter fi;
4257 eb->read_mirror = bbio->mirror_num;
4260 btrfs_validate_extent_buffer(eb, &bbio->parent_check) < 0)
4264 set_extent_buffer_uptodate(eb);
4266 clear_extent_buffer_uptodate(eb);
4267 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4270 bio_for_each_folio_all(fi, &bbio->bio) {
4271 struct folio *folio = fi.folio;
4272 u64 start = eb->start + bio_offset;
4273 u32 len = fi.length;
4276 btrfs_folio_set_uptodate(fs_info, folio, start, len);
4278 btrfs_folio_clear_uptodate(fs_info, folio, start, len);
4283 clear_bit(EXTENT_BUFFER_READING, &eb->bflags);
4284 smp_mb__after_atomic();
4285 wake_up_bit(&eb->bflags, EXTENT_BUFFER_READING);
4286 free_extent_buffer(eb);
4288 bio_put(&bbio->bio);
4291 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
4292 struct btrfs_tree_parent_check *check)
4294 struct btrfs_bio *bbio;
4297 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4301 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
4302 * operation, which could potentially still be in flight. In this case
4303 * we simply want to return an error.
4305 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
4308 /* Someone else is already reading the buffer, just wait for it. */
4309 if (test_and_set_bit(EXTENT_BUFFER_READING, &eb->bflags))
4313 * Between the initial test_bit(EXTENT_BUFFER_UPTODATE) and the above
4314 * test_and_set_bit(EXTENT_BUFFER_READING), someone else could have
4315 * started and finished reading the same eb. In this case, UPTODATE
4316 * will now be set, and we shouldn't read it in again.
4318 if (unlikely(test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))) {
4319 clear_bit(EXTENT_BUFFER_READING, &eb->bflags);
4320 smp_mb__after_atomic();
4321 wake_up_bit(&eb->bflags, EXTENT_BUFFER_READING);
4325 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4326 eb->read_mirror = 0;
4327 check_buffer_tree_ref(eb);
4328 atomic_inc(&eb->refs);
4330 bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
4331 REQ_OP_READ | REQ_META, eb->fs_info,
4332 end_bbio_meta_read, eb);
4333 bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
4334 bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
4335 bbio->file_offset = eb->start;
4336 memcpy(&bbio->parent_check, check, sizeof(*check));
4337 if (eb->fs_info->nodesize < PAGE_SIZE) {
4338 ret = bio_add_folio(&bbio->bio, eb->folios[0], eb->len,
4339 eb->start - folio_pos(eb->folios[0]));
4342 int num_folios = num_extent_folios(eb);
4344 for (int i = 0; i < num_folios; i++) {
4345 struct folio *folio = eb->folios[i];
4347 ret = bio_add_folio(&bbio->bio, folio, folio_size(folio), 0);
4351 btrfs_submit_bio(bbio, mirror_num);
4354 if (wait == WAIT_COMPLETE) {
4355 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_READING, TASK_UNINTERRUPTIBLE);
4356 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4363 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
4366 btrfs_warn(eb->fs_info,
4367 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
4368 eb->start, eb->len, start, len);
4369 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4375 * Check if the [start, start + len) range is valid before reading/writing
4377 * NOTE: @start and @len are offset inside the eb, not logical address.
4379 * Caller should not touch the dst/src memory if this function returns error.
4381 static inline int check_eb_range(const struct extent_buffer *eb,
4382 unsigned long start, unsigned long len)
4384 unsigned long offset;
4386 /* start, start + len should not go beyond eb->len nor overflow */
4387 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
4388 return report_eb_range(eb, start, len);
4393 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
4394 unsigned long start, unsigned long len)
4396 const int unit_size = folio_size(eb->folios[0]);
4399 char *dst = (char *)dstv;
4400 unsigned long i = get_eb_folio_index(eb, start);
4402 if (check_eb_range(eb, start, len)) {
4404 * Invalid range hit, reset the memory, so callers won't get
4405 * some random garbage for their uninitialized memory.
4407 memset(dstv, 0, len);
4412 memcpy(dstv, eb->addr + start, len);
4416 offset = get_eb_offset_in_folio(eb, start);
4421 cur = min(len, unit_size - offset);
4422 kaddr = folio_address(eb->folios[i]);
4423 memcpy(dst, kaddr + offset, cur);
4432 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
4434 unsigned long start, unsigned long len)
4436 const int unit_size = folio_size(eb->folios[0]);
4439 char __user *dst = (char __user *)dstv;
4440 unsigned long i = get_eb_folio_index(eb, start);
4443 WARN_ON(start > eb->len);
4444 WARN_ON(start + len > eb->start + eb->len);
4447 if (copy_to_user_nofault(dstv, eb->addr + start, len))
4452 offset = get_eb_offset_in_folio(eb, start);
4457 cur = min(len, unit_size - offset);
4458 kaddr = folio_address(eb->folios[i]);
4459 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
4473 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
4474 unsigned long start, unsigned long len)
4476 const int unit_size = folio_size(eb->folios[0]);
4480 char *ptr = (char *)ptrv;
4481 unsigned long i = get_eb_folio_index(eb, start);
4484 if (check_eb_range(eb, start, len))
4488 return memcmp(ptrv, eb->addr + start, len);
4490 offset = get_eb_offset_in_folio(eb, start);
4493 cur = min(len, unit_size - offset);
4494 kaddr = folio_address(eb->folios[i]);
4495 ret = memcmp(ptr, kaddr + offset, cur);
4508 * Check that the extent buffer is uptodate.
4510 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
4511 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
4513 static void assert_eb_folio_uptodate(const struct extent_buffer *eb, int i)
4515 struct btrfs_fs_info *fs_info = eb->fs_info;
4516 struct folio *folio = eb->folios[i];
4521 * If we are using the commit root we could potentially clear a page
4522 * Uptodate while we're using the extent buffer that we've previously
4523 * looked up. We don't want to complain in this case, as the page was
4524 * valid before, we just didn't write it out. Instead we want to catch
4525 * the case where we didn't actually read the block properly, which
4526 * would have !PageUptodate and !EXTENT_BUFFER_WRITE_ERR.
4528 if (test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4531 if (fs_info->nodesize < PAGE_SIZE) {
4532 struct folio *folio = eb->folios[0];
4535 if (WARN_ON(!btrfs_subpage_test_uptodate(fs_info, folio,
4536 eb->start, eb->len)))
4537 btrfs_subpage_dump_bitmap(fs_info, folio, eb->start, eb->len);
4539 WARN_ON(!folio_test_uptodate(folio));
4543 static void __write_extent_buffer(const struct extent_buffer *eb,
4544 const void *srcv, unsigned long start,
4545 unsigned long len, bool use_memmove)
4547 const int unit_size = folio_size(eb->folios[0]);
4551 char *src = (char *)srcv;
4552 unsigned long i = get_eb_folio_index(eb, start);
4553 /* For unmapped (dummy) ebs, no need to check their uptodate status. */
4554 const bool check_uptodate = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4556 if (check_eb_range(eb, start, len))
4561 memmove(eb->addr + start, srcv, len);
4563 memcpy(eb->addr + start, srcv, len);
4567 offset = get_eb_offset_in_folio(eb, start);
4571 assert_eb_folio_uptodate(eb, i);
4573 cur = min(len, unit_size - offset);
4574 kaddr = folio_address(eb->folios[i]);
4576 memmove(kaddr + offset, src, cur);
4578 memcpy(kaddr + offset, src, cur);
4587 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
4588 unsigned long start, unsigned long len)
4590 return __write_extent_buffer(eb, srcv, start, len, false);
4593 static void memset_extent_buffer(const struct extent_buffer *eb, int c,
4594 unsigned long start, unsigned long len)
4596 const int unit_size = folio_size(eb->folios[0]);
4597 unsigned long cur = start;
4600 memset(eb->addr + start, c, len);
4604 while (cur < start + len) {
4605 unsigned long index = get_eb_folio_index(eb, cur);
4606 unsigned int offset = get_eb_offset_in_folio(eb, cur);
4607 unsigned int cur_len = min(start + len - cur, unit_size - offset);
4609 assert_eb_folio_uptodate(eb, index);
4610 memset(folio_address(eb->folios[index]) + offset, c, cur_len);
4616 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
4619 if (check_eb_range(eb, start, len))
4621 return memset_extent_buffer(eb, 0, start, len);
4624 void copy_extent_buffer_full(const struct extent_buffer *dst,
4625 const struct extent_buffer *src)
4627 const int unit_size = folio_size(src->folios[0]);
4628 unsigned long cur = 0;
4630 ASSERT(dst->len == src->len);
4632 while (cur < src->len) {
4633 unsigned long index = get_eb_folio_index(src, cur);
4634 unsigned long offset = get_eb_offset_in_folio(src, cur);
4635 unsigned long cur_len = min(src->len, unit_size - offset);
4636 void *addr = folio_address(src->folios[index]) + offset;
4638 write_extent_buffer(dst, addr, cur, cur_len);
4644 void copy_extent_buffer(const struct extent_buffer *dst,
4645 const struct extent_buffer *src,
4646 unsigned long dst_offset, unsigned long src_offset,
4649 const int unit_size = folio_size(dst->folios[0]);
4650 u64 dst_len = dst->len;
4654 unsigned long i = get_eb_folio_index(dst, dst_offset);
4656 if (check_eb_range(dst, dst_offset, len) ||
4657 check_eb_range(src, src_offset, len))
4660 WARN_ON(src->len != dst_len);
4662 offset = get_eb_offset_in_folio(dst, dst_offset);
4665 assert_eb_folio_uptodate(dst, i);
4667 cur = min(len, (unsigned long)(unit_size - offset));
4669 kaddr = folio_address(dst->folios[i]);
4670 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4680 * Calculate the folio and offset of the byte containing the given bit number.
4682 * @eb: the extent buffer
4683 * @start: offset of the bitmap item in the extent buffer
4685 * @folio_index: return index of the folio in the extent buffer that contains
4686 * the given bit number
4687 * @folio_offset: return offset into the folio given by folio_index
4689 * This helper hides the ugliness of finding the byte in an extent buffer which
4690 * contains a given bit.
4692 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
4693 unsigned long start, unsigned long nr,
4694 unsigned long *folio_index,
4695 size_t *folio_offset)
4697 size_t byte_offset = BIT_BYTE(nr);
4701 * The byte we want is the offset of the extent buffer + the offset of
4702 * the bitmap item in the extent buffer + the offset of the byte in the
4705 offset = start + offset_in_folio(eb->folios[0], eb->start) + byte_offset;
4707 *folio_index = offset >> folio_shift(eb->folios[0]);
4708 *folio_offset = offset_in_folio(eb->folios[0], offset);
4712 * Determine whether a bit in a bitmap item is set.
4714 * @eb: the extent buffer
4715 * @start: offset of the bitmap item in the extent buffer
4716 * @nr: bit number to test
4718 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
4725 eb_bitmap_offset(eb, start, nr, &i, &offset);
4726 assert_eb_folio_uptodate(eb, i);
4727 kaddr = folio_address(eb->folios[i]);
4728 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
4731 static u8 *extent_buffer_get_byte(const struct extent_buffer *eb, unsigned long bytenr)
4733 unsigned long index = get_eb_folio_index(eb, bytenr);
4735 if (check_eb_range(eb, bytenr, 1))
4737 return folio_address(eb->folios[index]) + get_eb_offset_in_folio(eb, bytenr);
4741 * Set an area of a bitmap to 1.
4743 * @eb: the extent buffer
4744 * @start: offset of the bitmap item in the extent buffer
4745 * @pos: bit number of the first bit
4746 * @len: number of bits to set
4748 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
4749 unsigned long pos, unsigned long len)
4751 unsigned int first_byte = start + BIT_BYTE(pos);
4752 unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4753 const bool same_byte = (first_byte == last_byte);
4754 u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4758 mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4760 /* Handle the first byte. */
4761 kaddr = extent_buffer_get_byte(eb, first_byte);
4766 /* Handle the byte aligned part. */
4767 ASSERT(first_byte + 1 <= last_byte);
4768 memset_extent_buffer(eb, 0xff, first_byte + 1, last_byte - first_byte - 1);
4770 /* Handle the last byte. */
4771 kaddr = extent_buffer_get_byte(eb, last_byte);
4772 *kaddr |= BITMAP_LAST_BYTE_MASK(pos + len);
4777 * Clear an area of a bitmap.
4779 * @eb: the extent buffer
4780 * @start: offset of the bitmap item in the extent buffer
4781 * @pos: bit number of the first bit
4782 * @len: number of bits to clear
4784 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
4785 unsigned long start, unsigned long pos,
4788 unsigned int first_byte = start + BIT_BYTE(pos);
4789 unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4790 const bool same_byte = (first_byte == last_byte);
4791 u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4795 mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4797 /* Handle the first byte. */
4798 kaddr = extent_buffer_get_byte(eb, first_byte);
4803 /* Handle the byte aligned part. */
4804 ASSERT(first_byte + 1 <= last_byte);
4805 memset_extent_buffer(eb, 0, first_byte + 1, last_byte - first_byte - 1);
4807 /* Handle the last byte. */
4808 kaddr = extent_buffer_get_byte(eb, last_byte);
4809 *kaddr &= ~BITMAP_LAST_BYTE_MASK(pos + len);
4812 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4814 unsigned long distance = (src > dst) ? src - dst : dst - src;
4815 return distance < len;
4818 void memcpy_extent_buffer(const struct extent_buffer *dst,
4819 unsigned long dst_offset, unsigned long src_offset,
4822 const int unit_size = folio_size(dst->folios[0]);
4823 unsigned long cur_off = 0;
4825 if (check_eb_range(dst, dst_offset, len) ||
4826 check_eb_range(dst, src_offset, len))
4830 const bool use_memmove = areas_overlap(src_offset, dst_offset, len);
4833 memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
4835 memcpy(dst->addr + dst_offset, dst->addr + src_offset, len);
4839 while (cur_off < len) {
4840 unsigned long cur_src = cur_off + src_offset;
4841 unsigned long folio_index = get_eb_folio_index(dst, cur_src);
4842 unsigned long folio_off = get_eb_offset_in_folio(dst, cur_src);
4843 unsigned long cur_len = min(src_offset + len - cur_src,
4844 unit_size - folio_off);
4845 void *src_addr = folio_address(dst->folios[folio_index]) + folio_off;
4846 const bool use_memmove = areas_overlap(src_offset + cur_off,
4847 dst_offset + cur_off, cur_len);
4849 __write_extent_buffer(dst, src_addr, dst_offset + cur_off, cur_len,
4855 void memmove_extent_buffer(const struct extent_buffer *dst,
4856 unsigned long dst_offset, unsigned long src_offset,
4859 unsigned long dst_end = dst_offset + len - 1;
4860 unsigned long src_end = src_offset + len - 1;
4862 if (check_eb_range(dst, dst_offset, len) ||
4863 check_eb_range(dst, src_offset, len))
4866 if (dst_offset < src_offset) {
4867 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
4872 memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
4877 unsigned long src_i;
4879 size_t dst_off_in_folio;
4880 size_t src_off_in_folio;
4884 src_i = get_eb_folio_index(dst, src_end);
4886 dst_off_in_folio = get_eb_offset_in_folio(dst, dst_end);
4887 src_off_in_folio = get_eb_offset_in_folio(dst, src_end);
4889 cur = min_t(unsigned long, len, src_off_in_folio + 1);
4890 cur = min(cur, dst_off_in_folio + 1);
4892 src_addr = folio_address(dst->folios[src_i]) + src_off_in_folio -
4894 use_memmove = areas_overlap(src_end - cur + 1, dst_end - cur + 1,
4897 __write_extent_buffer(dst, src_addr, dst_end - cur + 1, cur,
4906 #define GANG_LOOKUP_SIZE 16
4907 static struct extent_buffer *get_next_extent_buffer(
4908 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
4910 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
4911 struct extent_buffer *found = NULL;
4912 u64 page_start = page_offset(page);
4913 u64 cur = page_start;
4915 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
4916 lockdep_assert_held(&fs_info->buffer_lock);
4918 while (cur < page_start + PAGE_SIZE) {
4922 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
4923 (void **)gang, cur >> fs_info->sectorsize_bits,
4924 min_t(unsigned int, GANG_LOOKUP_SIZE,
4925 PAGE_SIZE / fs_info->nodesize));
4928 for (i = 0; i < ret; i++) {
4929 /* Already beyond page end */
4930 if (gang[i]->start >= page_start + PAGE_SIZE)
4933 if (gang[i]->start >= bytenr) {
4938 cur = gang[ret - 1]->start + gang[ret - 1]->len;
4944 static int try_release_subpage_extent_buffer(struct page *page)
4946 struct btrfs_fs_info *fs_info = page_to_fs_info(page);
4947 u64 cur = page_offset(page);
4948 const u64 end = page_offset(page) + PAGE_SIZE;
4952 struct extent_buffer *eb = NULL;
4955 * Unlike try_release_extent_buffer() which uses folio private
4956 * to grab buffer, for subpage case we rely on radix tree, thus
4957 * we need to ensure radix tree consistency.
4959 * We also want an atomic snapshot of the radix tree, thus go
4960 * with spinlock rather than RCU.
4962 spin_lock(&fs_info->buffer_lock);
4963 eb = get_next_extent_buffer(fs_info, page, cur);
4965 /* No more eb in the page range after or at cur */
4966 spin_unlock(&fs_info->buffer_lock);
4969 cur = eb->start + eb->len;
4972 * The same as try_release_extent_buffer(), to ensure the eb
4973 * won't disappear out from under us.
4975 spin_lock(&eb->refs_lock);
4976 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4977 spin_unlock(&eb->refs_lock);
4978 spin_unlock(&fs_info->buffer_lock);
4981 spin_unlock(&fs_info->buffer_lock);
4984 * If tree ref isn't set then we know the ref on this eb is a
4985 * real ref, so just return, this eb will likely be freed soon
4988 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4989 spin_unlock(&eb->refs_lock);
4994 * Here we don't care about the return value, we will always
4995 * check the folio private at the end. And
4996 * release_extent_buffer() will release the refs_lock.
4998 release_extent_buffer(eb);
5001 * Finally to check if we have cleared folio private, as if we have
5002 * released all ebs in the page, the folio private should be cleared now.
5004 spin_lock(&page->mapping->i_private_lock);
5005 if (!folio_test_private(page_folio(page)))
5009 spin_unlock(&page->mapping->i_private_lock);
5014 int try_release_extent_buffer(struct page *page)
5016 struct folio *folio = page_folio(page);
5017 struct extent_buffer *eb;
5019 if (page_to_fs_info(page)->nodesize < PAGE_SIZE)
5020 return try_release_subpage_extent_buffer(page);
5023 * We need to make sure nobody is changing folio private, as we rely on
5024 * folio private as the pointer to extent buffer.
5026 spin_lock(&page->mapping->i_private_lock);
5027 if (!folio_test_private(folio)) {
5028 spin_unlock(&page->mapping->i_private_lock);
5032 eb = folio_get_private(folio);
5036 * This is a little awful but should be ok, we need to make sure that
5037 * the eb doesn't disappear out from under us while we're looking at
5040 spin_lock(&eb->refs_lock);
5041 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5042 spin_unlock(&eb->refs_lock);
5043 spin_unlock(&page->mapping->i_private_lock);
5046 spin_unlock(&page->mapping->i_private_lock);
5049 * If tree ref isn't set then we know the ref on this eb is a real ref,
5050 * so just return, this page will likely be freed soon anyway.
5052 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5053 spin_unlock(&eb->refs_lock);
5057 return release_extent_buffer(eb);
5061 * Attempt to readahead a child block.
5063 * @fs_info: the fs_info
5064 * @bytenr: bytenr to read
5065 * @owner_root: objectid of the root that owns this eb
5066 * @gen: generation for the uptodate check, can be 0
5067 * @level: level for the eb
5069 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5070 * normal uptodate check of the eb, without checking the generation. If we have
5071 * to read the block we will not block on anything.
5073 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5074 u64 bytenr, u64 owner_root, u64 gen, int level)
5076 struct btrfs_tree_parent_check check = {
5081 struct extent_buffer *eb;
5084 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5088 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5089 free_extent_buffer(eb);
5093 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
5095 free_extent_buffer_stale(eb);
5097 free_extent_buffer(eb);
5101 * Readahead a node's child block.
5103 * @node: parent node we're reading from
5104 * @slot: slot in the parent node for the child we want to read
5106 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5107 * the slot in the node provided.
5109 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5111 btrfs_readahead_tree_block(node->fs_info,
5112 btrfs_node_blockptr(node, slot),
5113 btrfs_header_owner(node),
5114 btrfs_node_ptr_generation(node, slot),
5115 btrfs_header_level(node) - 1);