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"
24 #include "check-integrity.h"
26 #include "rcu-string.h"
31 #include "block-group.h"
32 #include "compression.h"
34 #include "accessors.h"
35 #include "file-item.h"
37 #include "dev-replace.h"
39 #include "transaction.h"
41 static struct kmem_cache *extent_buffer_cache;
43 #ifdef CONFIG_BTRFS_DEBUG
44 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
46 struct btrfs_fs_info *fs_info = eb->fs_info;
49 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
50 list_add(&eb->leak_list, &fs_info->allocated_ebs);
51 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
54 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
56 struct btrfs_fs_info *fs_info = eb->fs_info;
59 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
60 list_del(&eb->leak_list);
61 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
64 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
66 struct extent_buffer *eb;
70 * If we didn't get into open_ctree our allocated_ebs will not be
71 * initialized, so just skip this.
73 if (!fs_info->allocated_ebs.next)
76 WARN_ON(!list_empty(&fs_info->allocated_ebs));
77 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
78 while (!list_empty(&fs_info->allocated_ebs)) {
79 eb = list_first_entry(&fs_info->allocated_ebs,
80 struct extent_buffer, leak_list);
82 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
83 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
84 btrfs_header_owner(eb));
85 list_del(&eb->leak_list);
86 kmem_cache_free(extent_buffer_cache, eb);
88 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
91 #define btrfs_leak_debug_add_eb(eb) do {} while (0)
92 #define btrfs_leak_debug_del_eb(eb) do {} while (0)
96 * Structure to record info about the bio being assembled, and other info like
97 * how many bytes are there before stripe/ordered extent boundary.
99 struct btrfs_bio_ctrl {
102 enum btrfs_compression_type compress_type;
103 u32 len_to_oe_boundary;
104 btrfs_bio_end_io_t end_io_func;
107 * This is for metadata read, to provide the extra needed verification
108 * info. This has to be provided for submit_one_bio(), as
109 * submit_one_bio() can submit a bio if it ends at stripe boundary. If
110 * no such parent_check is provided, the metadata can hit false alert at
113 struct btrfs_tree_parent_check *parent_check;
116 * Tell writepage not to lock the state bits for this range, it still
117 * does the unlocking.
121 /* Tell the submit_bio code to use REQ_SYNC */
125 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
136 bv = bio_first_bvec_all(bio);
137 inode = bv->bv_page->mapping->host;
138 mirror_num = bio_ctrl->mirror_num;
140 /* Caller should ensure the bio has at least some range added */
141 ASSERT(bio->bi_iter.bi_size);
143 if (!is_data_inode(inode)) {
144 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
146 * For metadata read, we should have the parent_check,
147 * and copy it to bbio for metadata verification.
149 ASSERT(bio_ctrl->parent_check);
150 memcpy(&btrfs_bio(bio)->parent_check,
151 bio_ctrl->parent_check,
152 sizeof(struct btrfs_tree_parent_check));
154 bio->bi_opf |= REQ_META;
157 if (btrfs_op(bio) == BTRFS_MAP_READ &&
158 bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
159 btrfs_submit_compressed_read(inode, bio, mirror_num);
161 btrfs_submit_bio(bio, mirror_num);
163 /* The bio is owned by the end_io handler now */
164 bio_ctrl->bio = NULL;
168 * Submit or fail the current bio in the bio_ctrl structure.
170 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
172 struct bio *bio = bio_ctrl->bio;
179 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
180 /* The bio is owned by the end_io handler now */
181 bio_ctrl->bio = NULL;
183 submit_one_bio(bio_ctrl);
187 int __init extent_buffer_init_cachep(void)
189 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
190 sizeof(struct extent_buffer), 0,
191 SLAB_MEM_SPREAD, NULL);
192 if (!extent_buffer_cache)
198 void __cold extent_buffer_free_cachep(void)
201 * Make sure all delayed rcu free are flushed before we
205 kmem_cache_destroy(extent_buffer_cache);
208 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
210 unsigned long index = start >> PAGE_SHIFT;
211 unsigned long end_index = end >> PAGE_SHIFT;
214 while (index <= end_index) {
215 page = find_get_page(inode->i_mapping, index);
216 BUG_ON(!page); /* Pages should be in the extent_io_tree */
217 clear_page_dirty_for_io(page);
223 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
225 struct address_space *mapping = inode->i_mapping;
226 unsigned long index = start >> PAGE_SHIFT;
227 unsigned long end_index = end >> PAGE_SHIFT;
230 while (index <= end_index) {
231 folio = filemap_get_folio(mapping, index);
232 filemap_dirty_folio(mapping, folio);
233 folio_account_redirty(folio);
234 index += folio_nr_pages(folio);
240 * Process one page for __process_pages_contig().
242 * Return >0 if we hit @page == @locked_page.
243 * Return 0 if we updated the page status.
244 * Return -EGAIN if the we need to try again.
245 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
247 static int process_one_page(struct btrfs_fs_info *fs_info,
248 struct address_space *mapping,
249 struct page *page, struct page *locked_page,
250 unsigned long page_ops, u64 start, u64 end)
254 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
255 len = end + 1 - start;
257 if (page_ops & PAGE_SET_ORDERED)
258 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
259 if (page_ops & PAGE_SET_ERROR)
260 btrfs_page_clamp_set_error(fs_info, page, start, len);
261 if (page_ops & PAGE_START_WRITEBACK) {
262 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
263 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
265 if (page_ops & PAGE_END_WRITEBACK)
266 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
268 if (page == locked_page)
271 if (page_ops & PAGE_LOCK) {
274 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
277 if (!PageDirty(page) || page->mapping != mapping) {
278 btrfs_page_end_writer_lock(fs_info, page, start, len);
282 if (page_ops & PAGE_UNLOCK)
283 btrfs_page_end_writer_lock(fs_info, page, start, len);
287 static int __process_pages_contig(struct address_space *mapping,
288 struct page *locked_page,
289 u64 start, u64 end, unsigned long page_ops,
292 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
293 pgoff_t start_index = start >> PAGE_SHIFT;
294 pgoff_t end_index = end >> PAGE_SHIFT;
295 pgoff_t index = start_index;
296 unsigned long pages_processed = 0;
297 struct folio_batch fbatch;
301 if (page_ops & PAGE_LOCK) {
302 ASSERT(page_ops == PAGE_LOCK);
303 ASSERT(processed_end && *processed_end == start);
306 if ((page_ops & PAGE_SET_ERROR) && start_index <= end_index)
307 mapping_set_error(mapping, -EIO);
309 folio_batch_init(&fbatch);
310 while (index <= end_index) {
313 found_folios = filemap_get_folios_contig(mapping, &index,
316 if (found_folios == 0) {
318 * Only if we're going to lock these pages, we can find
321 ASSERT(page_ops & PAGE_LOCK);
326 for (i = 0; i < found_folios; i++) {
328 struct folio *folio = fbatch.folios[i];
329 process_ret = process_one_page(fs_info, mapping,
330 &folio->page, locked_page, page_ops,
332 if (process_ret < 0) {
334 folio_batch_release(&fbatch);
337 pages_processed += folio_nr_pages(folio);
339 folio_batch_release(&fbatch);
343 if (err && processed_end) {
345 * Update @processed_end. I know this is awful since it has
346 * two different return value patterns (inclusive vs exclusive).
348 * But the exclusive pattern is necessary if @start is 0, or we
349 * underflow and check against processed_end won't work as
353 *processed_end = min(end,
354 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
356 *processed_end = start;
361 static noinline void __unlock_for_delalloc(struct inode *inode,
362 struct page *locked_page,
365 unsigned long index = start >> PAGE_SHIFT;
366 unsigned long end_index = end >> PAGE_SHIFT;
369 if (index == locked_page->index && end_index == index)
372 __process_pages_contig(inode->i_mapping, locked_page, start, end,
376 static noinline int lock_delalloc_pages(struct inode *inode,
377 struct page *locked_page,
381 unsigned long index = delalloc_start >> PAGE_SHIFT;
382 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
383 u64 processed_end = delalloc_start;
387 if (index == locked_page->index && index == end_index)
390 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
391 delalloc_end, PAGE_LOCK, &processed_end);
392 if (ret == -EAGAIN && processed_end > delalloc_start)
393 __unlock_for_delalloc(inode, locked_page, delalloc_start,
399 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
400 * more than @max_bytes.
402 * @start: The original start bytenr to search.
403 * Will store the extent range start bytenr.
404 * @end: The original end bytenr of the search range
405 * Will store the extent range end bytenr.
407 * Return true if we find a delalloc range which starts inside the original
408 * range, and @start/@end will store the delalloc range start/end.
410 * Return false if we can't find any delalloc range which starts inside the
411 * original range, and @start/@end will be the non-delalloc range start/end.
414 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
415 struct page *locked_page, u64 *start,
418 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
419 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
420 const u64 orig_start = *start;
421 const u64 orig_end = *end;
422 /* The sanity tests may not set a valid fs_info. */
423 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
427 struct extent_state *cached_state = NULL;
431 /* Caller should pass a valid @end to indicate the search range end */
432 ASSERT(orig_end > orig_start);
434 /* The range should at least cover part of the page */
435 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
436 orig_end <= page_offset(locked_page)));
438 /* step one, find a bunch of delalloc bytes starting at start */
439 delalloc_start = *start;
441 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
442 max_bytes, &cached_state);
443 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
444 *start = delalloc_start;
446 /* @delalloc_end can be -1, never go beyond @orig_end */
447 *end = min(delalloc_end, orig_end);
448 free_extent_state(cached_state);
453 * start comes from the offset of locked_page. We have to lock
454 * pages in order, so we can't process delalloc bytes before
457 if (delalloc_start < *start)
458 delalloc_start = *start;
461 * make sure to limit the number of pages we try to lock down
463 if (delalloc_end + 1 - delalloc_start > max_bytes)
464 delalloc_end = delalloc_start + max_bytes - 1;
466 /* step two, lock all the pages after the page that has start */
467 ret = lock_delalloc_pages(inode, locked_page,
468 delalloc_start, delalloc_end);
469 ASSERT(!ret || ret == -EAGAIN);
470 if (ret == -EAGAIN) {
471 /* some of the pages are gone, lets avoid looping by
472 * shortening the size of the delalloc range we're searching
474 free_extent_state(cached_state);
477 max_bytes = PAGE_SIZE;
486 /* step three, lock the state bits for the whole range */
487 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
489 /* then test to make sure it is all still delalloc */
490 ret = test_range_bit(tree, delalloc_start, delalloc_end,
491 EXTENT_DELALLOC, 1, cached_state);
493 unlock_extent(tree, delalloc_start, delalloc_end,
495 __unlock_for_delalloc(inode, locked_page,
496 delalloc_start, delalloc_end);
500 free_extent_state(cached_state);
501 *start = delalloc_start;
507 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
508 struct page *locked_page,
509 u32 clear_bits, unsigned long page_ops)
511 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
513 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
514 start, end, page_ops, NULL);
517 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
519 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
521 ASSERT(page_offset(page) <= start &&
522 start + len <= page_offset(page) + PAGE_SIZE);
525 if (fsverity_active(page->mapping->host) &&
527 !PageUptodate(page) &&
528 start < i_size_read(page->mapping->host) &&
529 !fsverity_verify_page(page)) {
530 btrfs_page_set_error(fs_info, page, start, len);
532 btrfs_page_set_uptodate(fs_info, page, start, len);
535 btrfs_page_clear_uptodate(fs_info, page, start, len);
536 btrfs_page_set_error(fs_info, page, start, len);
539 if (!btrfs_is_subpage(fs_info, page))
542 btrfs_subpage_end_reader(fs_info, page, start, len);
545 /* lots and lots of room for performance fixes in the end_bio funcs */
547 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
549 struct btrfs_inode *inode;
550 const bool uptodate = (err == 0);
553 ASSERT(page && page->mapping);
554 inode = BTRFS_I(page->mapping->host);
555 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
558 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
561 ASSERT(end + 1 - start <= U32_MAX);
562 len = end + 1 - start;
564 btrfs_page_clear_uptodate(fs_info, page, start, len);
565 btrfs_page_set_error(fs_info, page, start, len);
566 ret = err < 0 ? err : -EIO;
567 mapping_set_error(page->mapping, ret);
572 * after a writepage IO is done, we need to:
573 * clear the uptodate bits on error
574 * clear the writeback bits in the extent tree for this IO
575 * end_page_writeback if the page has no more pending IO
577 * Scheduling is not allowed, so the extent state tree is expected
578 * to have one and only one object corresponding to this IO.
580 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
582 struct bio *bio = &bbio->bio;
583 int error = blk_status_to_errno(bio->bi_status);
584 struct bio_vec *bvec;
587 struct bvec_iter_all iter_all;
589 ASSERT(!bio_flagged(bio, BIO_CLONED));
590 bio_for_each_segment_all(bvec, bio, iter_all) {
591 struct page *page = bvec->bv_page;
592 struct inode *inode = page->mapping->host;
593 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
594 const u32 sectorsize = fs_info->sectorsize;
596 /* Our read/write should always be sector aligned. */
597 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
599 "partial page write in btrfs with offset %u and length %u",
600 bvec->bv_offset, bvec->bv_len);
601 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
603 "incomplete page write with offset %u and length %u",
604 bvec->bv_offset, bvec->bv_len);
606 start = page_offset(page) + bvec->bv_offset;
607 end = start + bvec->bv_len - 1;
609 end_extent_writepage(page, error, start, end);
611 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
618 * Record previously processed extent range
620 * For endio_readpage_release_extent() to handle a full extent range, reducing
621 * the extent io operations.
623 struct processed_extent {
624 struct btrfs_inode *inode;
625 /* Start of the range in @inode */
627 /* End of the range in @inode */
633 * Try to release processed extent range
635 * May not release the extent range right now if the current range is
636 * contiguous to processed extent.
638 * Will release processed extent when any of @inode, @uptodate, the range is
639 * no longer contiguous to the processed range.
641 * Passing @inode == NULL will force processed extent to be released.
643 static void endio_readpage_release_extent(struct processed_extent *processed,
644 struct btrfs_inode *inode, u64 start, u64 end,
647 struct extent_state *cached = NULL;
648 struct extent_io_tree *tree;
650 /* The first extent, initialize @processed */
651 if (!processed->inode)
655 * Contiguous to processed extent, just uptodate the end.
657 * Several things to notice:
659 * - bio can be merged as long as on-disk bytenr is contiguous
660 * This means we can have page belonging to other inodes, thus need to
661 * check if the inode still matches.
662 * - bvec can contain range beyond current page for multi-page bvec
663 * Thus we need to do processed->end + 1 >= start check
665 if (processed->inode == inode && processed->uptodate == uptodate &&
666 processed->end + 1 >= start && end >= processed->end) {
667 processed->end = end;
671 tree = &processed->inode->io_tree;
673 * Now we don't have range contiguous to the processed range, release
674 * the processed range now.
676 unlock_extent(tree, processed->start, processed->end, &cached);
679 /* Update processed to current range */
680 processed->inode = inode;
681 processed->start = start;
682 processed->end = end;
683 processed->uptodate = uptodate;
686 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
688 ASSERT(PageLocked(page));
689 if (!btrfs_is_subpage(fs_info, page))
692 ASSERT(PagePrivate(page));
693 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
697 * Find extent buffer for a givne bytenr.
699 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
702 static struct extent_buffer *find_extent_buffer_readpage(
703 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
705 struct extent_buffer *eb;
708 * For regular sectorsize, we can use page->private to grab extent
711 if (fs_info->nodesize >= PAGE_SIZE) {
712 ASSERT(PagePrivate(page) && page->private);
713 return (struct extent_buffer *)page->private;
716 /* For subpage case, we need to lookup buffer radix tree */
718 eb = radix_tree_lookup(&fs_info->buffer_radix,
719 bytenr >> fs_info->sectorsize_bits);
726 * after a readpage IO is done, we need to:
727 * clear the uptodate bits on error
728 * set the uptodate bits if things worked
729 * set the page up to date if all extents in the tree are uptodate
730 * clear the lock bit in the extent tree
731 * unlock the page if there are no other extents locked for it
733 * Scheduling is not allowed, so the extent state tree is expected
734 * to have one and only one object corresponding to this IO.
736 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
738 struct bio *bio = &bbio->bio;
739 struct bio_vec *bvec;
740 struct processed_extent processed = { 0 };
742 * The offset to the beginning of a bio, since one bio can never be
743 * larger than UINT_MAX, u32 here is enough.
747 struct bvec_iter_all iter_all;
749 ASSERT(!bio_flagged(bio, BIO_CLONED));
750 bio_for_each_segment_all(bvec, bio, iter_all) {
751 bool uptodate = !bio->bi_status;
752 struct page *page = bvec->bv_page;
753 struct inode *inode = page->mapping->host;
754 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
755 const u32 sectorsize = fs_info->sectorsize;
761 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
762 bio->bi_iter.bi_sector, bio->bi_status,
766 * We always issue full-sector reads, but if some block in a
767 * page fails to read, blk_update_request() will advance
768 * bv_offset and adjust bv_len to compensate. Print a warning
769 * for unaligned offsets, and an error if they don't add up to
772 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
774 "partial page read in btrfs with offset %u and length %u",
775 bvec->bv_offset, bvec->bv_len);
776 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
779 "incomplete page read with offset %u and length %u",
780 bvec->bv_offset, bvec->bv_len);
782 start = page_offset(page) + bvec->bv_offset;
783 end = start + bvec->bv_len - 1;
786 mirror = bbio->mirror_num;
787 if (uptodate && !is_data_inode(inode) &&
788 btrfs_validate_metadata_buffer(bbio, page, start, end, mirror))
791 if (likely(uptodate)) {
792 loff_t i_size = i_size_read(inode);
793 pgoff_t end_index = i_size >> PAGE_SHIFT;
796 * Zero out the remaining part if this range straddles
799 * Here we should only zero the range inside the bvec,
800 * not touch anything else.
802 * NOTE: i_size is exclusive while end is inclusive.
804 if (page->index == end_index && i_size <= end) {
805 u32 zero_start = max(offset_in_page(i_size),
806 offset_in_page(start));
808 zero_user_segment(page, zero_start,
809 offset_in_page(end) + 1);
811 } else if (!is_data_inode(inode)) {
812 struct extent_buffer *eb;
814 eb = find_extent_buffer_readpage(fs_info, page, start);
815 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
816 eb->read_mirror = mirror;
817 atomic_dec(&eb->io_pages);
820 /* Update page status and unlock. */
821 end_page_read(page, uptodate, start, len);
822 endio_readpage_release_extent(&processed, BTRFS_I(inode),
823 start, end, PageUptodate(page));
825 ASSERT(bio_offset + len > bio_offset);
829 /* Release the last extent */
830 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
835 * Populate every free slot in a provided array with pages.
837 * @nr_pages: number of pages to allocate
838 * @page_array: the array to fill with pages; any existing non-null entries in
839 * the array will be skipped
841 * Return: 0 if all pages were able to be allocated;
842 * -ENOMEM otherwise, and the caller is responsible for freeing all
843 * non-null page pointers in the array.
845 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
847 unsigned int allocated;
849 for (allocated = 0; allocated < nr_pages;) {
850 unsigned int last = allocated;
852 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
854 if (allocated == nr_pages)
858 * During this iteration, no page could be allocated, even
859 * though alloc_pages_bulk_array() falls back to alloc_page()
860 * if it could not bulk-allocate. So we must be out of memory.
862 if (allocated == last)
865 memalloc_retry_wait(GFP_NOFS);
871 * Attempt to add a page to bio.
873 * @bio_ctrl: record both the bio, and its bio_flags
874 * @page: page to add to the bio
875 * @disk_bytenr: offset of the new bio or to check whether we are adding
876 * a contiguous page to the previous one
877 * @size: portion of page that we want to write
878 * @pg_offset: starting offset in the page
879 * @compress_type: compression type of the current bio to see if we can merge them
881 * Attempt to add a page to bio considering stripe alignment etc.
883 * Return >= 0 for the number of bytes added to the bio.
884 * Can return 0 if the current bio is already at stripe/zone boundary.
885 * Return <0 for error.
887 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
889 u64 disk_bytenr, unsigned int size,
890 unsigned int pg_offset,
891 enum btrfs_compression_type compress_type)
893 struct bio *bio = bio_ctrl->bio;
894 u32 bio_size = bio->bi_iter.bi_size;
896 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
900 /* The limit should be calculated when bio_ctrl->bio is allocated */
901 ASSERT(bio_ctrl->len_to_oe_boundary);
902 if (bio_ctrl->compress_type != compress_type)
906 if (bio->bi_iter.bi_size == 0) {
907 /* We can always add a page into an empty bio. */
909 } else if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE) {
910 struct bio_vec *bvec = bio_last_bvec_all(bio);
913 * The contig check requires the following conditions to be met:
914 * 1) The pages are belonging to the same inode
915 * This is implied by the call chain.
917 * 2) The range has adjacent logical bytenr
919 * 3) The range has adjacent file offset
920 * This is required for the usage of btrfs_bio->file_offset.
922 if (bio_end_sector(bio) == sector &&
923 page_offset(bvec->bv_page) + bvec->bv_offset +
924 bvec->bv_len == page_offset(page) + pg_offset)
928 * For compression, all IO should have its logical bytenr
929 * set to the starting bytenr of the compressed extent.
931 contig = bio->bi_iter.bi_sector == sector;
937 real_size = min(bio_ctrl->len_to_oe_boundary - bio_size, size);
940 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
941 * bio will still execute its endio function on the page!
946 return bio_add_page(bio, page, real_size, pg_offset);
949 static void calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
950 struct btrfs_inode *inode, u64 file_offset)
952 struct btrfs_ordered_extent *ordered;
955 * Limit the extent to the ordered boundary for Zone Append.
956 * Compressed bios aren't submitted directly, so it doesn't apply to
959 if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE &&
960 btrfs_use_zone_append(btrfs_bio(bio_ctrl->bio))) {
961 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
963 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
964 ordered->file_offset +
965 ordered->disk_num_bytes - file_offset);
966 btrfs_put_ordered_extent(ordered);
971 bio_ctrl->len_to_oe_boundary = U32_MAX;
974 static void alloc_new_bio(struct btrfs_inode *inode,
975 struct btrfs_bio_ctrl *bio_ctrl,
976 struct writeback_control *wbc, blk_opf_t opf,
977 u64 disk_bytenr, u32 offset, u64 file_offset,
978 enum btrfs_compression_type compress_type)
980 struct btrfs_fs_info *fs_info = inode->root->fs_info;
983 bio = btrfs_bio_alloc(BIO_MAX_VECS, opf, inode, bio_ctrl->end_io_func,
986 * For compressed page range, its disk_bytenr is always @disk_bytenr
987 * passed in, no matter if we have added any range into previous bio.
989 if (compress_type != BTRFS_COMPRESS_NONE)
990 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
992 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
993 btrfs_bio(bio)->file_offset = file_offset;
995 bio_ctrl->compress_type = compress_type;
996 calc_bio_boundaries(bio_ctrl, inode, file_offset);
1000 * Pick the last added device to support cgroup writeback. For
1001 * multi-device file systems this means blk-cgroup policies have
1002 * to always be set on the last added/replaced device.
1003 * This is a bit odd but has been like that for a long time.
1005 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
1006 wbc_init_bio(wbc, bio);
1011 * @opf: bio REQ_OP_* and REQ_* flags as one value
1012 * @wbc: optional writeback control for io accounting
1013 * @disk_bytenr: logical bytenr where the write will be
1014 * @page: page to add to the bio
1015 * @size: portion of page that we want to write to
1016 * @pg_offset: offset of the new bio or to check whether we are adding
1017 * a contiguous page to the previous one
1018 * @compress_type: compress type for current bio
1020 * The will either add the page into the existing @bio_ctrl->bio, or allocate a
1021 * new one in @bio_ctrl->bio.
1022 * The mirror number for this IO should already be initizlied in
1023 * @bio_ctrl->mirror_num.
1025 static int submit_extent_page(blk_opf_t opf,
1026 struct writeback_control *wbc,
1027 struct btrfs_bio_ctrl *bio_ctrl,
1028 u64 disk_bytenr, struct page *page,
1029 size_t size, unsigned long pg_offset,
1030 enum btrfs_compression_type compress_type,
1031 bool force_bio_submit)
1033 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1034 unsigned int cur = pg_offset;
1038 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
1039 pg_offset + size <= PAGE_SIZE);
1041 ASSERT(bio_ctrl->end_io_func);
1043 if (force_bio_submit)
1044 submit_one_bio(bio_ctrl);
1046 while (cur < pg_offset + size) {
1047 u32 offset = cur - pg_offset;
1050 /* Allocate new bio if needed */
1051 if (!bio_ctrl->bio) {
1052 alloc_new_bio(inode, bio_ctrl, wbc, opf, disk_bytenr,
1053 offset, page_offset(page) + cur,
1057 * We must go through btrfs_bio_add_page() to ensure each
1058 * page range won't cross various boundaries.
1060 if (compress_type != BTRFS_COMPRESS_NONE)
1061 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
1062 size - offset, pg_offset + offset,
1065 added = btrfs_bio_add_page(bio_ctrl, page,
1066 disk_bytenr + offset, size - offset,
1067 pg_offset + offset, compress_type);
1069 /* Metadata page range should never be split */
1070 if (!is_data_inode(&inode->vfs_inode))
1071 ASSERT(added == 0 || added == size - offset);
1073 /* At least we added some page, update the account */
1075 wbc_account_cgroup_owner(wbc, page, added);
1077 /* We have reached boundary, submit right now */
1078 if (added < size - offset) {
1079 /* The bio should contain some page(s) */
1080 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
1081 submit_one_bio(bio_ctrl);
1088 static int attach_extent_buffer_page(struct extent_buffer *eb,
1090 struct btrfs_subpage *prealloc)
1092 struct btrfs_fs_info *fs_info = eb->fs_info;
1096 * If the page is mapped to btree inode, we should hold the private
1097 * lock to prevent race.
1098 * For cloned or dummy extent buffers, their pages are not mapped and
1099 * will not race with any other ebs.
1102 lockdep_assert_held(&page->mapping->private_lock);
1104 if (fs_info->nodesize >= PAGE_SIZE) {
1105 if (!PagePrivate(page))
1106 attach_page_private(page, eb);
1108 WARN_ON(page->private != (unsigned long)eb);
1112 /* Already mapped, just free prealloc */
1113 if (PagePrivate(page)) {
1114 btrfs_free_subpage(prealloc);
1119 /* Has preallocated memory for subpage */
1120 attach_page_private(page, prealloc);
1122 /* Do new allocation to attach subpage */
1123 ret = btrfs_attach_subpage(fs_info, page,
1124 BTRFS_SUBPAGE_METADATA);
1128 int set_page_extent_mapped(struct page *page)
1130 struct btrfs_fs_info *fs_info;
1132 ASSERT(page->mapping);
1134 if (PagePrivate(page))
1137 fs_info = btrfs_sb(page->mapping->host->i_sb);
1139 if (btrfs_is_subpage(fs_info, page))
1140 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1142 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1146 void clear_page_extent_mapped(struct page *page)
1148 struct btrfs_fs_info *fs_info;
1150 ASSERT(page->mapping);
1152 if (!PagePrivate(page))
1155 fs_info = btrfs_sb(page->mapping->host->i_sb);
1156 if (btrfs_is_subpage(fs_info, page))
1157 return btrfs_detach_subpage(fs_info, page);
1159 detach_page_private(page);
1162 static struct extent_map *
1163 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1164 u64 start, u64 len, struct extent_map **em_cached)
1166 struct extent_map *em;
1168 if (em_cached && *em_cached) {
1170 if (extent_map_in_tree(em) && start >= em->start &&
1171 start < extent_map_end(em)) {
1172 refcount_inc(&em->refs);
1176 free_extent_map(em);
1180 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1181 if (em_cached && !IS_ERR(em)) {
1183 refcount_inc(&em->refs);
1189 * basic readpage implementation. Locked extent state structs are inserted
1190 * into the tree that are removed when the IO is done (by the end_io
1192 * XXX JDM: This needs looking at to ensure proper page locking
1193 * return 0 on success, otherwise return error
1195 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1196 struct btrfs_bio_ctrl *bio_ctrl,
1197 blk_opf_t read_flags, u64 *prev_em_start)
1199 struct inode *inode = page->mapping->host;
1200 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1201 u64 start = page_offset(page);
1202 const u64 end = start + PAGE_SIZE - 1;
1205 u64 last_byte = i_size_read(inode);
1207 struct extent_map *em;
1209 size_t pg_offset = 0;
1211 size_t blocksize = inode->i_sb->s_blocksize;
1212 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1214 ret = set_page_extent_mapped(page);
1216 unlock_extent(tree, start, end, NULL);
1217 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1222 if (page->index == last_byte >> PAGE_SHIFT) {
1223 size_t zero_offset = offset_in_page(last_byte);
1226 iosize = PAGE_SIZE - zero_offset;
1227 memzero_page(page, zero_offset, iosize);
1230 bio_ctrl->end_io_func = end_bio_extent_readpage;
1231 begin_page_read(fs_info, page);
1232 while (cur <= end) {
1233 unsigned long this_bio_flag = 0;
1234 bool force_bio_submit = false;
1237 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1238 if (cur >= last_byte) {
1239 iosize = PAGE_SIZE - pg_offset;
1240 memzero_page(page, pg_offset, iosize);
1241 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1242 end_page_read(page, true, cur, iosize);
1245 em = __get_extent_map(inode, page, pg_offset, cur,
1246 end - cur + 1, em_cached);
1248 unlock_extent(tree, cur, end, NULL);
1249 end_page_read(page, false, cur, end + 1 - cur);
1253 extent_offset = cur - em->start;
1254 BUG_ON(extent_map_end(em) <= cur);
1257 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1258 this_bio_flag = em->compress_type;
1260 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1261 iosize = ALIGN(iosize, blocksize);
1262 if (this_bio_flag != BTRFS_COMPRESS_NONE)
1263 disk_bytenr = em->block_start;
1265 disk_bytenr = em->block_start + extent_offset;
1266 block_start = em->block_start;
1267 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1268 block_start = EXTENT_MAP_HOLE;
1271 * If we have a file range that points to a compressed extent
1272 * and it's followed by a consecutive file range that points
1273 * to the same compressed extent (possibly with a different
1274 * offset and/or length, so it either points to the whole extent
1275 * or only part of it), we must make sure we do not submit a
1276 * single bio to populate the pages for the 2 ranges because
1277 * this makes the compressed extent read zero out the pages
1278 * belonging to the 2nd range. Imagine the following scenario:
1281 * [0 - 8K] [8K - 24K]
1284 * points to extent X, points to extent X,
1285 * offset 4K, length of 8K offset 0, length 16K
1287 * [extent X, compressed length = 4K uncompressed length = 16K]
1289 * If the bio to read the compressed extent covers both ranges,
1290 * it will decompress extent X into the pages belonging to the
1291 * first range and then it will stop, zeroing out the remaining
1292 * pages that belong to the other range that points to extent X.
1293 * So here we make sure we submit 2 bios, one for the first
1294 * range and another one for the third range. Both will target
1295 * the same physical extent from disk, but we can't currently
1296 * make the compressed bio endio callback populate the pages
1297 * for both ranges because each compressed bio is tightly
1298 * coupled with a single extent map, and each range can have
1299 * an extent map with a different offset value relative to the
1300 * uncompressed data of our extent and different lengths. This
1301 * is a corner case so we prioritize correctness over
1302 * non-optimal behavior (submitting 2 bios for the same extent).
1304 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1305 prev_em_start && *prev_em_start != (u64)-1 &&
1306 *prev_em_start != em->start)
1307 force_bio_submit = true;
1310 *prev_em_start = em->start;
1312 free_extent_map(em);
1315 /* we've found a hole, just zero and go on */
1316 if (block_start == EXTENT_MAP_HOLE) {
1317 memzero_page(page, pg_offset, iosize);
1319 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1320 end_page_read(page, true, cur, iosize);
1322 pg_offset += iosize;
1325 /* the get_extent function already copied into the page */
1326 if (block_start == EXTENT_MAP_INLINE) {
1327 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1328 end_page_read(page, true, cur, iosize);
1330 pg_offset += iosize;
1334 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
1335 bio_ctrl, disk_bytenr, page, iosize,
1336 pg_offset, this_bio_flag,
1340 * We have to unlock the remaining range, or the page
1341 * will never be unlocked.
1343 unlock_extent(tree, cur, end, NULL);
1344 end_page_read(page, false, cur, end + 1 - cur);
1348 pg_offset += iosize;
1354 int btrfs_read_folio(struct file *file, struct folio *folio)
1356 struct page *page = &folio->page;
1357 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1358 u64 start = page_offset(page);
1359 u64 end = start + PAGE_SIZE - 1;
1360 struct btrfs_bio_ctrl bio_ctrl = { 0 };
1363 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1365 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
1367 * If btrfs_do_readpage() failed we will want to submit the assembled
1368 * bio to do the cleanup.
1370 submit_one_bio(&bio_ctrl);
1374 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1376 struct extent_map **em_cached,
1377 struct btrfs_bio_ctrl *bio_ctrl,
1380 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1383 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1385 for (index = 0; index < nr_pages; index++) {
1386 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1387 REQ_RAHEAD, prev_em_start);
1388 put_page(pages[index]);
1393 * helper for __extent_writepage, doing all of the delayed allocation setup.
1395 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1396 * to write the page (copy into inline extent). In this case the IO has
1397 * been started and the page is already unlocked.
1399 * This returns 0 if all went well (page still locked)
1400 * This returns < 0 if there were errors (page still locked)
1402 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1403 struct page *page, struct writeback_control *wbc)
1405 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1406 u64 delalloc_start = page_offset(page);
1407 u64 delalloc_to_write = 0;
1408 /* How many pages are started by btrfs_run_delalloc_range() */
1409 unsigned long nr_written = 0;
1411 int page_started = 0;
1413 while (delalloc_start < page_end) {
1414 u64 delalloc_end = page_end;
1417 found = find_lock_delalloc_range(&inode->vfs_inode, page,
1421 delalloc_start = delalloc_end + 1;
1424 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1425 delalloc_end, &page_started, &nr_written, wbc);
1427 btrfs_page_set_error(inode->root->fs_info, page,
1428 page_offset(page), PAGE_SIZE);
1432 * delalloc_end is already one less than the total length, so
1433 * we don't subtract one from PAGE_SIZE
1435 delalloc_to_write += (delalloc_end - delalloc_start +
1436 PAGE_SIZE) >> PAGE_SHIFT;
1437 delalloc_start = delalloc_end + 1;
1439 if (wbc->nr_to_write < delalloc_to_write) {
1442 if (delalloc_to_write < thresh * 2)
1443 thresh = delalloc_to_write;
1444 wbc->nr_to_write = min_t(u64, delalloc_to_write,
1448 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
1451 * We've unlocked the page, so we can't update the mapping's
1452 * writeback index, just update nr_to_write.
1454 wbc->nr_to_write -= nr_written;
1462 * Find the first byte we need to write.
1464 * For subpage, one page can contain several sectors, and
1465 * __extent_writepage_io() will just grab all extent maps in the page
1466 * range and try to submit all non-inline/non-compressed extents.
1468 * This is a big problem for subpage, we shouldn't re-submit already written
1470 * This function will lookup subpage dirty bit to find which range we really
1473 * Return the next dirty range in [@start, @end).
1474 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
1476 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
1477 struct page *page, u64 *start, u64 *end)
1479 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
1480 struct btrfs_subpage_info *spi = fs_info->subpage_info;
1481 u64 orig_start = *start;
1482 /* Declare as unsigned long so we can use bitmap ops */
1483 unsigned long flags;
1484 int range_start_bit;
1488 * For regular sector size == page size case, since one page only
1489 * contains one sector, we return the page offset directly.
1491 if (!btrfs_is_subpage(fs_info, page)) {
1492 *start = page_offset(page);
1493 *end = page_offset(page) + PAGE_SIZE;
1497 range_start_bit = spi->dirty_offset +
1498 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
1500 /* We should have the page locked, but just in case */
1501 spin_lock_irqsave(&subpage->lock, flags);
1502 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
1503 spi->dirty_offset + spi->bitmap_nr_bits);
1504 spin_unlock_irqrestore(&subpage->lock, flags);
1506 range_start_bit -= spi->dirty_offset;
1507 range_end_bit -= spi->dirty_offset;
1509 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
1510 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
1514 * helper for __extent_writepage. This calls the writepage start hooks,
1515 * and does the loop to map the page into extents and bios.
1517 * We return 1 if the IO is started and the page is unlocked,
1518 * 0 if all went well (page still locked)
1519 * < 0 if there were errors (page still locked)
1521 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
1523 struct writeback_control *wbc,
1524 struct btrfs_bio_ctrl *bio_ctrl,
1528 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1529 u64 cur = page_offset(page);
1530 u64 end = cur + PAGE_SIZE - 1;
1533 struct extent_map *em;
1537 enum req_op op = REQ_OP_WRITE;
1538 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1539 bool has_error = false;
1542 ret = btrfs_writepage_cow_fixup(page);
1544 /* Fixup worker will requeue */
1545 redirty_page_for_writepage(wbc, page);
1551 * we don't want to touch the inode after unlocking the page,
1552 * so we update the mapping writeback index now
1556 bio_ctrl->end_io_func = end_bio_extent_writepage;
1557 while (cur <= end) {
1560 u64 dirty_range_start = cur;
1561 u64 dirty_range_end;
1564 if (cur >= i_size) {
1565 btrfs_writepage_endio_finish_ordered(inode, page, cur,
1568 * This range is beyond i_size, thus we don't need to
1569 * bother writing back.
1570 * But we still need to clear the dirty subpage bit, or
1571 * the next time the page gets dirtied, we will try to
1572 * writeback the sectors with subpage dirty bits,
1573 * causing writeback without ordered extent.
1575 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
1579 find_next_dirty_byte(fs_info, page, &dirty_range_start,
1581 if (cur < dirty_range_start) {
1582 cur = dirty_range_start;
1586 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
1588 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
1589 ret = PTR_ERR_OR_ZERO(em);
1596 extent_offset = cur - em->start;
1597 em_end = extent_map_end(em);
1598 ASSERT(cur <= em_end);
1600 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
1601 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
1602 block_start = em->block_start;
1603 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
1604 disk_bytenr = em->block_start + extent_offset;
1607 * Note that em_end from extent_map_end() and dirty_range_end from
1608 * find_next_dirty_byte() are all exclusive
1610 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
1611 free_extent_map(em);
1615 * compressed and inline extents are written through other
1618 if (compressed || block_start == EXTENT_MAP_HOLE ||
1619 block_start == EXTENT_MAP_INLINE) {
1623 btrfs_writepage_endio_finish_ordered(inode,
1624 page, cur, cur + iosize - 1, true);
1625 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
1630 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
1631 if (!PageWriteback(page)) {
1632 btrfs_err(inode->root->fs_info,
1633 "page %lu not writeback, cur %llu end %llu",
1634 page->index, cur, end);
1638 * Although the PageDirty bit is cleared before entering this
1639 * function, subpage dirty bit is not cleared.
1640 * So clear subpage dirty bit here so next time we won't submit
1641 * page for range already written to disk.
1643 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
1645 ret = submit_extent_page(op | write_flags, wbc,
1646 bio_ctrl, disk_bytenr,
1648 cur - page_offset(page),
1655 btrfs_page_set_error(fs_info, page, cur, iosize);
1656 if (PageWriteback(page))
1657 btrfs_page_clear_writeback(fs_info, page, cur,
1665 * If we finish without problem, we should not only clear page dirty,
1666 * but also empty subpage dirty bits
1669 btrfs_page_assert_not_dirty(fs_info, page);
1677 * the writepage semantics are similar to regular writepage. extent
1678 * records are inserted to lock ranges in the tree, and as dirty areas
1679 * are found, they are marked writeback. Then the lock bits are removed
1680 * and the end_io handler clears the writeback ranges
1682 * Return 0 if everything goes well.
1683 * Return <0 for error.
1685 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
1686 struct btrfs_bio_ctrl *bio_ctrl)
1688 struct folio *folio = page_folio(page);
1689 struct inode *inode = page->mapping->host;
1690 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1691 const u64 page_start = page_offset(page);
1692 const u64 page_end = page_start + PAGE_SIZE - 1;
1696 loff_t i_size = i_size_read(inode);
1697 unsigned long end_index = i_size >> PAGE_SHIFT;
1699 trace___extent_writepage(page, inode, wbc);
1701 WARN_ON(!PageLocked(page));
1703 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
1704 page_offset(page), PAGE_SIZE);
1706 pg_offset = offset_in_page(i_size);
1707 if (page->index > end_index ||
1708 (page->index == end_index && !pg_offset)) {
1709 folio_invalidate(folio, 0, folio_size(folio));
1710 folio_unlock(folio);
1714 if (page->index == end_index)
1715 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
1717 ret = set_page_extent_mapped(page);
1723 if (!bio_ctrl->extent_locked) {
1724 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
1731 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, bio_ctrl, i_size,
1738 /* make sure the mapping tag for page dirty gets cleared */
1739 set_page_writeback(page);
1740 end_page_writeback(page);
1743 * Here we used to have a check for PageError() and then set @ret and
1744 * call end_extent_writepage().
1746 * But in fact setting @ret here will cause different error paths
1747 * between subpage and regular sectorsize.
1749 * For regular page size, we never submit current page, but only add
1750 * current page to current bio.
1751 * The bio submission can only happen in next page.
1752 * Thus if we hit the PageError() branch, @ret is already set to
1753 * non-zero value and will not get updated for regular sectorsize.
1755 * But for subpage case, it's possible we submit part of current page,
1756 * thus can get PageError() set by submitted bio of the same page,
1757 * while our @ret is still 0.
1759 * So here we unify the behavior and don't set @ret.
1760 * Error can still be properly passed to higher layer as page will
1761 * be set error, here we just don't handle the IO failure.
1763 * NOTE: This is just a hotfix for subpage.
1764 * The root fix will be properly ending ordered extent when we hit
1765 * an error during writeback.
1767 * But that needs a bigger refactoring, as we not only need to grab the
1768 * submitted OE, but also need to know exactly at which bytenr we hit
1770 * Currently the full page based __extent_writepage_io() is not
1773 if (PageError(page))
1774 end_extent_writepage(page, ret, page_start, page_end);
1775 if (bio_ctrl->extent_locked) {
1777 * If bio_ctrl->extent_locked, it's from extent_write_locked_range(),
1778 * the page can either be locked by lock_page() or
1779 * process_one_page().
1780 * Let btrfs_page_unlock_writer() handle both cases.
1783 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
1784 wbc->range_end + 1 - wbc->range_start);
1792 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
1794 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
1795 TASK_UNINTERRUPTIBLE);
1798 static void end_extent_buffer_writeback(struct extent_buffer *eb)
1800 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1801 smp_mb__after_atomic();
1802 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
1806 * Lock extent buffer status and pages for writeback.
1808 * May try to flush write bio if we can't get the lock.
1810 * Return 0 if the extent buffer doesn't need to be submitted.
1811 * (E.g. the extent buffer is not dirty)
1812 * Return >0 is the extent buffer is submitted to bio.
1813 * Return <0 if something went wrong, no page is locked.
1815 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
1816 struct btrfs_bio_ctrl *bio_ctrl)
1818 struct btrfs_fs_info *fs_info = eb->fs_info;
1823 if (!btrfs_try_tree_write_lock(eb)) {
1824 submit_write_bio(bio_ctrl, 0);
1826 btrfs_tree_lock(eb);
1829 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
1830 btrfs_tree_unlock(eb);
1831 if (!bio_ctrl->sync_io)
1834 submit_write_bio(bio_ctrl, 0);
1838 wait_on_extent_buffer_writeback(eb);
1839 btrfs_tree_lock(eb);
1840 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
1842 btrfs_tree_unlock(eb);
1847 * We need to do this to prevent races in people who check if the eb is
1848 * under IO since we can end up having no IO bits set for a short period
1851 spin_lock(&eb->refs_lock);
1852 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
1853 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1854 spin_unlock(&eb->refs_lock);
1855 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
1856 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1858 fs_info->dirty_metadata_batch);
1861 spin_unlock(&eb->refs_lock);
1864 btrfs_tree_unlock(eb);
1867 * Either we don't need to submit any tree block, or we're submitting
1869 * Subpage metadata doesn't use page locking at all, so we can skip
1872 if (!ret || fs_info->nodesize < PAGE_SIZE)
1875 num_pages = num_extent_pages(eb);
1876 for (i = 0; i < num_pages; i++) {
1877 struct page *p = eb->pages[i];
1879 if (!trylock_page(p)) {
1881 submit_write_bio(bio_ctrl, 0);
1891 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
1893 struct btrfs_fs_info *fs_info = eb->fs_info;
1895 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
1896 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
1900 * A read may stumble upon this buffer later, make sure that it gets an
1901 * error and knows there was an error.
1903 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
1906 * We need to set the mapping with the io error as well because a write
1907 * error will flip the file system readonly, and then syncfs() will
1908 * return a 0 because we are readonly if we don't modify the err seq for
1911 mapping_set_error(page->mapping, -EIO);
1914 * If writeback for a btree extent that doesn't belong to a log tree
1915 * failed, increment the counter transaction->eb_write_errors.
1916 * We do this because while the transaction is running and before it's
1917 * committing (when we call filemap_fdata[write|wait]_range against
1918 * the btree inode), we might have
1919 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
1920 * returns an error or an error happens during writeback, when we're
1921 * committing the transaction we wouldn't know about it, since the pages
1922 * can be no longer dirty nor marked anymore for writeback (if a
1923 * subsequent modification to the extent buffer didn't happen before the
1924 * transaction commit), which makes filemap_fdata[write|wait]_range not
1925 * able to find the pages tagged with SetPageError at transaction
1926 * commit time. So if this happens we must abort the transaction,
1927 * otherwise we commit a super block with btree roots that point to
1928 * btree nodes/leafs whose content on disk is invalid - either garbage
1929 * or the content of some node/leaf from a past generation that got
1930 * cowed or deleted and is no longer valid.
1932 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
1933 * not be enough - we need to distinguish between log tree extents vs
1934 * non-log tree extents, and the next filemap_fdatawait_range() call
1935 * will catch and clear such errors in the mapping - and that call might
1936 * be from a log sync and not from a transaction commit. Also, checking
1937 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
1938 * not done and would not be reliable - the eb might have been released
1939 * from memory and reading it back again means that flag would not be
1940 * set (since it's a runtime flag, not persisted on disk).
1942 * Using the flags below in the btree inode also makes us achieve the
1943 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
1944 * writeback for all dirty pages and before filemap_fdatawait_range()
1945 * is called, the writeback for all dirty pages had already finished
1946 * with errors - because we were not using AS_EIO/AS_ENOSPC,
1947 * filemap_fdatawait_range() would return success, as it could not know
1948 * that writeback errors happened (the pages were no longer tagged for
1951 switch (eb->log_index) {
1953 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
1956 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
1959 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
1962 BUG(); /* unexpected, logic error */
1967 * The endio specific version which won't touch any unsafe spinlock in endio
1970 static struct extent_buffer *find_extent_buffer_nolock(
1971 struct btrfs_fs_info *fs_info, u64 start)
1973 struct extent_buffer *eb;
1976 eb = radix_tree_lookup(&fs_info->buffer_radix,
1977 start >> fs_info->sectorsize_bits);
1978 if (eb && atomic_inc_not_zero(&eb->refs)) {
1987 * The endio function for subpage extent buffer write.
1989 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
1990 * after all extent buffers in the page has finished their writeback.
1992 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
1994 struct bio *bio = &bbio->bio;
1995 struct btrfs_fs_info *fs_info;
1996 struct bio_vec *bvec;
1997 struct bvec_iter_all iter_all;
1999 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
2000 ASSERT(fs_info->nodesize < PAGE_SIZE);
2002 ASSERT(!bio_flagged(bio, BIO_CLONED));
2003 bio_for_each_segment_all(bvec, bio, iter_all) {
2004 struct page *page = bvec->bv_page;
2005 u64 bvec_start = page_offset(page) + bvec->bv_offset;
2006 u64 bvec_end = bvec_start + bvec->bv_len - 1;
2007 u64 cur_bytenr = bvec_start;
2009 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
2011 /* Iterate through all extent buffers in the range */
2012 while (cur_bytenr <= bvec_end) {
2013 struct extent_buffer *eb;
2017 * Here we can't use find_extent_buffer(), as it may
2018 * try to lock eb->refs_lock, which is not safe in endio
2021 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
2024 cur_bytenr = eb->start + eb->len;
2026 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
2027 done = atomic_dec_and_test(&eb->io_pages);
2030 if (bio->bi_status ||
2031 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2032 ClearPageUptodate(page);
2033 set_btree_ioerr(page, eb);
2036 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
2038 end_extent_buffer_writeback(eb);
2040 * free_extent_buffer() will grab spinlock which is not
2041 * safe in endio context. Thus here we manually dec
2044 atomic_dec(&eb->refs);
2050 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
2052 struct bio *bio = &bbio->bio;
2053 struct bio_vec *bvec;
2054 struct extent_buffer *eb;
2056 struct bvec_iter_all iter_all;
2058 ASSERT(!bio_flagged(bio, BIO_CLONED));
2059 bio_for_each_segment_all(bvec, bio, iter_all) {
2060 struct page *page = bvec->bv_page;
2062 eb = (struct extent_buffer *)page->private;
2064 done = atomic_dec_and_test(&eb->io_pages);
2066 if (bio->bi_status ||
2067 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2068 ClearPageUptodate(page);
2069 set_btree_ioerr(page, eb);
2072 end_page_writeback(page);
2077 end_extent_buffer_writeback(eb);
2083 static void prepare_eb_write(struct extent_buffer *eb)
2086 unsigned long start;
2089 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2090 atomic_set(&eb->io_pages, num_extent_pages(eb));
2092 /* Set btree blocks beyond nritems with 0 to avoid stale content */
2093 nritems = btrfs_header_nritems(eb);
2094 if (btrfs_header_level(eb) > 0) {
2095 end = btrfs_node_key_ptr_offset(eb, nritems);
2096 memzero_extent_buffer(eb, end, eb->len - end);
2100 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2102 start = btrfs_item_nr_offset(eb, nritems);
2103 end = btrfs_item_nr_offset(eb, 0);
2105 end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
2107 end += btrfs_item_offset(eb, nritems - 1);
2108 memzero_extent_buffer(eb, start, end - start);
2113 * Unlike the work in write_one_eb(), we rely completely on extent locking.
2114 * Page locking is only utilized at minimum to keep the VMM code happy.
2116 static int write_one_subpage_eb(struct extent_buffer *eb,
2117 struct writeback_control *wbc,
2118 struct btrfs_bio_ctrl *bio_ctrl)
2120 struct btrfs_fs_info *fs_info = eb->fs_info;
2121 struct page *page = eb->pages[0];
2122 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2123 bool no_dirty_ebs = false;
2126 prepare_eb_write(eb);
2128 /* clear_page_dirty_for_io() in subpage helper needs page locked */
2130 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2132 /* Check if this is the last dirty bit to update nr_written */
2133 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2134 eb->start, eb->len);
2136 clear_page_dirty_for_io(page);
2138 bio_ctrl->end_io_func = end_bio_subpage_eb_writepage;
2140 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2141 bio_ctrl, eb->start, page, eb->len,
2142 eb->start - page_offset(page), 0, false);
2144 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
2145 set_btree_ioerr(page, eb);
2148 if (atomic_dec_and_test(&eb->io_pages))
2149 end_extent_buffer_writeback(eb);
2154 * Submission finished without problem, if no range of the page is
2155 * dirty anymore, we have submitted a page. Update nr_written in wbc.
2162 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
2163 struct writeback_control *wbc,
2164 struct btrfs_bio_ctrl *bio_ctrl)
2166 u64 disk_bytenr = eb->start;
2168 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2171 prepare_eb_write(eb);
2173 bio_ctrl->end_io_func = end_bio_extent_buffer_writepage;
2175 num_pages = num_extent_pages(eb);
2176 for (i = 0; i < num_pages; i++) {
2177 struct page *p = eb->pages[i];
2179 clear_page_dirty_for_io(p);
2180 set_page_writeback(p);
2181 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2182 bio_ctrl, disk_bytenr, p,
2183 PAGE_SIZE, 0, 0, false);
2185 set_btree_ioerr(p, eb);
2186 if (PageWriteback(p))
2187 end_page_writeback(p);
2188 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
2189 end_extent_buffer_writeback(eb);
2193 disk_bytenr += PAGE_SIZE;
2198 if (unlikely(ret)) {
2199 for (; i < num_pages; i++) {
2200 struct page *p = eb->pages[i];
2201 clear_page_dirty_for_io(p);
2210 * Submit one subpage btree page.
2212 * The main difference to submit_eb_page() is:
2214 * For subpage, we don't rely on page locking at all.
2217 * We only flush bio if we may be unable to fit current extent buffers into
2220 * Return >=0 for the number of submitted extent buffers.
2221 * Return <0 for fatal error.
2223 static int submit_eb_subpage(struct page *page,
2224 struct writeback_control *wbc,
2225 struct btrfs_bio_ctrl *bio_ctrl)
2227 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2229 u64 page_start = page_offset(page);
2231 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
2234 /* Lock and write each dirty extent buffers in the range */
2235 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
2236 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2237 struct extent_buffer *eb;
2238 unsigned long flags;
2242 * Take private lock to ensure the subpage won't be detached
2245 spin_lock(&page->mapping->private_lock);
2246 if (!PagePrivate(page)) {
2247 spin_unlock(&page->mapping->private_lock);
2250 spin_lock_irqsave(&subpage->lock, flags);
2251 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
2252 subpage->bitmaps)) {
2253 spin_unlock_irqrestore(&subpage->lock, flags);
2254 spin_unlock(&page->mapping->private_lock);
2259 start = page_start + bit_start * fs_info->sectorsize;
2260 bit_start += sectors_per_node;
2263 * Here we just want to grab the eb without touching extra
2264 * spin locks, so call find_extent_buffer_nolock().
2266 eb = find_extent_buffer_nolock(fs_info, start);
2267 spin_unlock_irqrestore(&subpage->lock, flags);
2268 spin_unlock(&page->mapping->private_lock);
2271 * The eb has already reached 0 refs thus find_extent_buffer()
2272 * doesn't return it. We don't need to write back such eb
2278 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2280 free_extent_buffer(eb);
2284 free_extent_buffer(eb);
2287 ret = write_one_subpage_eb(eb, wbc, bio_ctrl);
2288 free_extent_buffer(eb);
2296 /* We hit error, end bio for the submitted extent buffers */
2297 submit_write_bio(bio_ctrl, ret);
2302 * Submit all page(s) of one extent buffer.
2304 * @page: the page of one extent buffer
2305 * @eb_context: to determine if we need to submit this page, if current page
2306 * belongs to this eb, we don't need to submit
2308 * The caller should pass each page in their bytenr order, and here we use
2309 * @eb_context to determine if we have submitted pages of one extent buffer.
2311 * If we have, we just skip until we hit a new page that doesn't belong to
2312 * current @eb_context.
2314 * If not, we submit all the page(s) of the extent buffer.
2316 * Return >0 if we have submitted the extent buffer successfully.
2317 * Return 0 if we don't need to submit the page, as it's already submitted by
2319 * Return <0 for fatal error.
2321 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
2322 struct btrfs_bio_ctrl *bio_ctrl,
2323 struct extent_buffer **eb_context)
2325 struct address_space *mapping = page->mapping;
2326 struct btrfs_block_group *cache = NULL;
2327 struct extent_buffer *eb;
2330 if (!PagePrivate(page))
2333 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
2334 return submit_eb_subpage(page, wbc, bio_ctrl);
2336 spin_lock(&mapping->private_lock);
2337 if (!PagePrivate(page)) {
2338 spin_unlock(&mapping->private_lock);
2342 eb = (struct extent_buffer *)page->private;
2345 * Shouldn't happen and normally this would be a BUG_ON but no point
2346 * crashing the machine for something we can survive anyway.
2349 spin_unlock(&mapping->private_lock);
2353 if (eb == *eb_context) {
2354 spin_unlock(&mapping->private_lock);
2357 ret = atomic_inc_not_zero(&eb->refs);
2358 spin_unlock(&mapping->private_lock);
2362 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
2364 * If for_sync, this hole will be filled with
2365 * trasnsaction commit.
2367 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
2371 free_extent_buffer(eb);
2377 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2379 btrfs_revert_meta_write_pointer(cache, eb);
2381 btrfs_put_block_group(cache);
2382 free_extent_buffer(eb);
2387 * Implies write in zoned mode. Mark the last eb in a block group.
2389 btrfs_schedule_zone_finish_bg(cache, eb);
2390 btrfs_put_block_group(cache);
2392 ret = write_one_eb(eb, wbc, bio_ctrl);
2393 free_extent_buffer(eb);
2399 int btree_write_cache_pages(struct address_space *mapping,
2400 struct writeback_control *wbc)
2402 struct extent_buffer *eb_context = NULL;
2403 struct btrfs_bio_ctrl bio_ctrl = {
2405 .sync_io = (wbc->sync_mode == WB_SYNC_ALL),
2407 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
2410 int nr_to_write_done = 0;
2411 struct folio_batch fbatch;
2412 unsigned int nr_folios;
2414 pgoff_t end; /* Inclusive */
2418 folio_batch_init(&fbatch);
2419 if (wbc->range_cyclic) {
2420 index = mapping->writeback_index; /* Start from prev offset */
2423 * Start from the beginning does not need to cycle over the
2424 * range, mark it as scanned.
2426 scanned = (index == 0);
2428 index = wbc->range_start >> PAGE_SHIFT;
2429 end = wbc->range_end >> PAGE_SHIFT;
2432 if (wbc->sync_mode == WB_SYNC_ALL)
2433 tag = PAGECACHE_TAG_TOWRITE;
2435 tag = PAGECACHE_TAG_DIRTY;
2436 btrfs_zoned_meta_io_lock(fs_info);
2438 if (wbc->sync_mode == WB_SYNC_ALL)
2439 tag_pages_for_writeback(mapping, index, end);
2440 while (!done && !nr_to_write_done && (index <= end) &&
2441 (nr_folios = filemap_get_folios_tag(mapping, &index, end,
2445 for (i = 0; i < nr_folios; i++) {
2446 struct folio *folio = fbatch.folios[i];
2448 ret = submit_eb_page(&folio->page, wbc, &bio_ctrl,
2458 * the filesystem may choose to bump up nr_to_write.
2459 * We have to make sure to honor the new nr_to_write
2462 nr_to_write_done = wbc->nr_to_write <= 0;
2464 folio_batch_release(&fbatch);
2467 if (!scanned && !done) {
2469 * We hit the last page and there is more work to be done: wrap
2470 * back to the start of the file
2477 * If something went wrong, don't allow any metadata write bio to be
2480 * This would prevent use-after-free if we had dirty pages not
2481 * cleaned up, which can still happen by fuzzed images.
2484 * Allowing existing tree block to be allocated for other trees.
2486 * - Log tree operations
2487 * Exiting tree blocks get allocated to log tree, bumps its
2488 * generation, then get cleaned in tree re-balance.
2489 * Such tree block will not be written back, since it's clean,
2490 * thus no WRITTEN flag set.
2491 * And after log writes back, this tree block is not traced by
2492 * any dirty extent_io_tree.
2494 * - Offending tree block gets re-dirtied from its original owner
2495 * Since it has bumped generation, no WRITTEN flag, it can be
2496 * reused without COWing. This tree block will not be traced
2497 * by btrfs_transaction::dirty_pages.
2499 * Now such dirty tree block will not be cleaned by any dirty
2500 * extent io tree. Thus we don't want to submit such wild eb
2501 * if the fs already has error.
2503 * We can get ret > 0 from submit_extent_page() indicating how many ebs
2504 * were submitted. Reset it to 0 to avoid false alerts for the caller.
2508 if (!ret && BTRFS_FS_ERROR(fs_info))
2510 submit_write_bio(&bio_ctrl, ret);
2512 btrfs_zoned_meta_io_unlock(fs_info);
2517 * Walk the list of dirty pages of the given address space and write all of them.
2519 * @mapping: address space structure to write
2520 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2521 * @bio_ctrl: holds context for the write, namely the bio
2523 * If a page is already under I/O, write_cache_pages() skips it, even
2524 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
2525 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
2526 * and msync() need to guarantee that all the data which was dirty at the time
2527 * the call was made get new I/O started against them. If wbc->sync_mode is
2528 * WB_SYNC_ALL then we were called for data integrity and we must wait for
2529 * existing IO to complete.
2531 static int extent_write_cache_pages(struct address_space *mapping,
2532 struct writeback_control *wbc,
2533 struct btrfs_bio_ctrl *bio_ctrl)
2535 struct inode *inode = mapping->host;
2538 int nr_to_write_done = 0;
2539 struct folio_batch fbatch;
2540 unsigned int nr_folios;
2542 pgoff_t end; /* Inclusive */
2544 int range_whole = 0;
2549 * We have to hold onto the inode so that ordered extents can do their
2550 * work when the IO finishes. The alternative to this is failing to add
2551 * an ordered extent if the igrab() fails there and that is a huge pain
2552 * to deal with, so instead just hold onto the inode throughout the
2553 * writepages operation. If it fails here we are freeing up the inode
2554 * anyway and we'd rather not waste our time writing out stuff that is
2555 * going to be truncated anyway.
2560 folio_batch_init(&fbatch);
2561 if (wbc->range_cyclic) {
2562 index = mapping->writeback_index; /* Start from prev offset */
2565 * Start from the beginning does not need to cycle over the
2566 * range, mark it as scanned.
2568 scanned = (index == 0);
2570 index = wbc->range_start >> PAGE_SHIFT;
2571 end = wbc->range_end >> PAGE_SHIFT;
2572 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2578 * We do the tagged writepage as long as the snapshot flush bit is set
2579 * and we are the first one who do the filemap_flush() on this inode.
2581 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
2582 * not race in and drop the bit.
2584 if (range_whole && wbc->nr_to_write == LONG_MAX &&
2585 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
2586 &BTRFS_I(inode)->runtime_flags))
2587 wbc->tagged_writepages = 1;
2589 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2590 tag = PAGECACHE_TAG_TOWRITE;
2592 tag = PAGECACHE_TAG_DIRTY;
2594 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2595 tag_pages_for_writeback(mapping, index, end);
2597 while (!done && !nr_to_write_done && (index <= end) &&
2598 (nr_folios = filemap_get_folios_tag(mapping, &index,
2599 end, tag, &fbatch))) {
2602 for (i = 0; i < nr_folios; i++) {
2603 struct folio *folio = fbatch.folios[i];
2605 done_index = folio->index + folio_nr_pages(folio);
2607 * At this point we hold neither the i_pages lock nor
2608 * the page lock: the page may be truncated or
2609 * invalidated (changing page->mapping to NULL),
2610 * or even swizzled back from swapper_space to
2611 * tmpfs file mapping
2613 if (!folio_trylock(folio)) {
2614 submit_write_bio(bio_ctrl, 0);
2618 if (unlikely(folio->mapping != mapping)) {
2619 folio_unlock(folio);
2623 if (wbc->sync_mode != WB_SYNC_NONE) {
2624 if (folio_test_writeback(folio))
2625 submit_write_bio(bio_ctrl, 0);
2626 folio_wait_writeback(folio);
2629 if (folio_test_writeback(folio) ||
2630 !folio_clear_dirty_for_io(folio)) {
2631 folio_unlock(folio);
2635 ret = __extent_writepage(&folio->page, wbc, bio_ctrl);
2642 * the filesystem may choose to bump up nr_to_write.
2643 * We have to make sure to honor the new nr_to_write
2646 nr_to_write_done = wbc->nr_to_write <= 0;
2648 folio_batch_release(&fbatch);
2651 if (!scanned && !done) {
2653 * We hit the last page and there is more work to be done: wrap
2654 * back to the start of the file
2660 * If we're looping we could run into a page that is locked by a
2661 * writer and that writer could be waiting on writeback for a
2662 * page in our current bio, and thus deadlock, so flush the
2665 submit_write_bio(bio_ctrl, 0);
2669 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
2670 mapping->writeback_index = done_index;
2672 btrfs_add_delayed_iput(BTRFS_I(inode));
2677 * Submit the pages in the range to bio for call sites which delalloc range has
2678 * already been ran (aka, ordered extent inserted) and all pages are still
2681 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
2683 bool found_error = false;
2684 int first_error = 0;
2686 struct address_space *mapping = inode->i_mapping;
2689 unsigned long nr_pages;
2690 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
2691 struct btrfs_bio_ctrl bio_ctrl = {
2695 struct writeback_control wbc_writepages = {
2696 .sync_mode = WB_SYNC_ALL,
2697 .range_start = start,
2698 .range_end = end + 1,
2699 /* We're called from an async helper function */
2700 .punt_to_cgroup = 1,
2701 .no_cgroup_owner = 1,
2704 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
2705 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
2707 wbc_writepages.nr_to_write = nr_pages * 2;
2709 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
2710 while (cur <= end) {
2711 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
2713 page = find_get_page(mapping, cur >> PAGE_SHIFT);
2715 * All pages in the range are locked since
2716 * btrfs_run_delalloc_range(), thus there is no way to clear
2717 * the page dirty flag.
2719 ASSERT(PageLocked(page));
2720 ASSERT(PageDirty(page));
2721 clear_page_dirty_for_io(page);
2722 ret = __extent_writepage(page, &wbc_writepages, &bio_ctrl);
2732 submit_write_bio(&bio_ctrl, found_error ? ret : 0);
2734 wbc_detach_inode(&wbc_writepages);
2740 int extent_writepages(struct address_space *mapping,
2741 struct writeback_control *wbc)
2743 struct inode *inode = mapping->host;
2745 struct btrfs_bio_ctrl bio_ctrl = {
2747 .sync_io = (wbc->sync_mode == WB_SYNC_ALL),
2751 * Allow only a single thread to do the reloc work in zoned mode to
2752 * protect the write pointer updates.
2754 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
2755 ret = extent_write_cache_pages(mapping, wbc, &bio_ctrl);
2756 submit_write_bio(&bio_ctrl, ret);
2757 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
2761 void extent_readahead(struct readahead_control *rac)
2763 struct btrfs_bio_ctrl bio_ctrl = { 0 };
2764 struct page *pagepool[16];
2765 struct extent_map *em_cached = NULL;
2766 u64 prev_em_start = (u64)-1;
2769 while ((nr = readahead_page_batch(rac, pagepool))) {
2770 u64 contig_start = readahead_pos(rac);
2771 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
2773 contiguous_readpages(pagepool, nr, contig_start, contig_end,
2774 &em_cached, &bio_ctrl, &prev_em_start);
2778 free_extent_map(em_cached);
2779 submit_one_bio(&bio_ctrl);
2783 * basic invalidate_folio code, this waits on any locked or writeback
2784 * ranges corresponding to the folio, and then deletes any extent state
2785 * records from the tree
2787 int extent_invalidate_folio(struct extent_io_tree *tree,
2788 struct folio *folio, size_t offset)
2790 struct extent_state *cached_state = NULL;
2791 u64 start = folio_pos(folio);
2792 u64 end = start + folio_size(folio) - 1;
2793 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
2795 /* This function is only called for the btree inode */
2796 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
2798 start += ALIGN(offset, blocksize);
2802 lock_extent(tree, start, end, &cached_state);
2803 folio_wait_writeback(folio);
2806 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
2807 * so here we only need to unlock the extent range to free any
2808 * existing extent state.
2810 unlock_extent(tree, start, end, &cached_state);
2815 * a helper for release_folio, this tests for areas of the page that
2816 * are locked or under IO and drops the related state bits if it is safe
2819 static int try_release_extent_state(struct extent_io_tree *tree,
2820 struct page *page, gfp_t mask)
2822 u64 start = page_offset(page);
2823 u64 end = start + PAGE_SIZE - 1;
2826 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
2829 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
2830 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS);
2833 * At this point we can safely clear everything except the
2834 * locked bit, the nodatasum bit and the delalloc new bit.
2835 * The delalloc new bit will be cleared by ordered extent
2838 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL,
2841 /* if clear_extent_bit failed for enomem reasons,
2842 * we can't allow the release to continue.
2853 * a helper for release_folio. As long as there are no locked extents
2854 * in the range corresponding to the page, both state records and extent
2855 * map records are removed
2857 int try_release_extent_mapping(struct page *page, gfp_t mask)
2859 struct extent_map *em;
2860 u64 start = page_offset(page);
2861 u64 end = start + PAGE_SIZE - 1;
2862 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
2863 struct extent_io_tree *tree = &btrfs_inode->io_tree;
2864 struct extent_map_tree *map = &btrfs_inode->extent_tree;
2866 if (gfpflags_allow_blocking(mask) &&
2867 page->mapping->host->i_size > SZ_16M) {
2869 while (start <= end) {
2870 struct btrfs_fs_info *fs_info;
2873 len = end - start + 1;
2874 write_lock(&map->lock);
2875 em = lookup_extent_mapping(map, start, len);
2877 write_unlock(&map->lock);
2880 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
2881 em->start != start) {
2882 write_unlock(&map->lock);
2883 free_extent_map(em);
2886 if (test_range_bit(tree, em->start,
2887 extent_map_end(em) - 1,
2888 EXTENT_LOCKED, 0, NULL))
2891 * If it's not in the list of modified extents, used
2892 * by a fast fsync, we can remove it. If it's being
2893 * logged we can safely remove it since fsync took an
2894 * extra reference on the em.
2896 if (list_empty(&em->list) ||
2897 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
2900 * If it's in the list of modified extents, remove it
2901 * only if its generation is older then the current one,
2902 * in which case we don't need it for a fast fsync.
2903 * Otherwise don't remove it, we could be racing with an
2904 * ongoing fast fsync that could miss the new extent.
2906 fs_info = btrfs_inode->root->fs_info;
2907 spin_lock(&fs_info->trans_lock);
2908 cur_gen = fs_info->generation;
2909 spin_unlock(&fs_info->trans_lock);
2910 if (em->generation >= cur_gen)
2914 * We only remove extent maps that are not in the list of
2915 * modified extents or that are in the list but with a
2916 * generation lower then the current generation, so there
2917 * is no need to set the full fsync flag on the inode (it
2918 * hurts the fsync performance for workloads with a data
2919 * size that exceeds or is close to the system's memory).
2921 remove_extent_mapping(map, em);
2922 /* once for the rb tree */
2923 free_extent_map(em);
2925 start = extent_map_end(em);
2926 write_unlock(&map->lock);
2929 free_extent_map(em);
2931 cond_resched(); /* Allow large-extent preemption. */
2934 return try_release_extent_state(tree, page, mask);
2938 * To cache previous fiemap extent
2940 * Will be used for merging fiemap extent
2942 struct fiemap_cache {
2951 * Helper to submit fiemap extent.
2953 * Will try to merge current fiemap extent specified by @offset, @phys,
2954 * @len and @flags with cached one.
2955 * And only when we fails to merge, cached one will be submitted as
2958 * Return value is the same as fiemap_fill_next_extent().
2960 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
2961 struct fiemap_cache *cache,
2962 u64 offset, u64 phys, u64 len, u32 flags)
2966 /* Set at the end of extent_fiemap(). */
2967 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
2973 * Sanity check, extent_fiemap() should have ensured that new
2974 * fiemap extent won't overlap with cached one.
2977 * NOTE: Physical address can overlap, due to compression
2979 if (cache->offset + cache->len > offset) {
2985 * Only merges fiemap extents if
2986 * 1) Their logical addresses are continuous
2988 * 2) Their physical addresses are continuous
2989 * So truly compressed (physical size smaller than logical size)
2990 * extents won't get merged with each other
2992 * 3) Share same flags
2994 if (cache->offset + cache->len == offset &&
2995 cache->phys + cache->len == phys &&
2996 cache->flags == flags) {
3001 /* Not mergeable, need to submit cached one */
3002 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3003 cache->len, cache->flags);
3004 cache->cached = false;
3008 cache->cached = true;
3009 cache->offset = offset;
3012 cache->flags = flags;
3018 * Emit last fiemap cache
3020 * The last fiemap cache may still be cached in the following case:
3022 * |<- Fiemap range ->|
3023 * |<------------ First extent ----------->|
3025 * In this case, the first extent range will be cached but not emitted.
3026 * So we must emit it before ending extent_fiemap().
3028 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
3029 struct fiemap_cache *cache)
3036 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3037 cache->len, cache->flags);
3038 cache->cached = false;
3044 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
3046 struct extent_buffer *clone;
3047 struct btrfs_key key;
3052 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
3055 ret = btrfs_next_leaf(inode->root, path);
3060 * Don't bother with cloning if there are no more file extent items for
3063 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3064 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
3067 /* See the comment at fiemap_search_slot() about why we clone. */
3068 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3072 slot = path->slots[0];
3073 btrfs_release_path(path);
3074 path->nodes[0] = clone;
3075 path->slots[0] = slot;
3081 * Search for the first file extent item that starts at a given file offset or
3082 * the one that starts immediately before that offset.
3083 * Returns: 0 on success, < 0 on error, 1 if not found.
3085 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
3088 const u64 ino = btrfs_ino(inode);
3089 struct btrfs_root *root = inode->root;
3090 struct extent_buffer *clone;
3091 struct btrfs_key key;
3096 key.type = BTRFS_EXTENT_DATA_KEY;
3097 key.offset = file_offset;
3099 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3103 if (ret > 0 && path->slots[0] > 0) {
3104 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3105 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3109 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3110 ret = btrfs_next_leaf(root, path);
3114 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3115 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3120 * We clone the leaf and use it during fiemap. This is because while
3121 * using the leaf we do expensive things like checking if an extent is
3122 * shared, which can take a long time. In order to prevent blocking
3123 * other tasks for too long, we use a clone of the leaf. We have locked
3124 * the file range in the inode's io tree, so we know none of our file
3125 * extent items can change. This way we avoid blocking other tasks that
3126 * want to insert items for other inodes in the same leaf or b+tree
3127 * rebalance operations (triggered for example when someone is trying
3128 * to push items into this leaf when trying to insert an item in a
3130 * We also need the private clone because holding a read lock on an
3131 * extent buffer of the subvolume's b+tree will make lockdep unhappy
3132 * when we call fiemap_fill_next_extent(), because that may cause a page
3133 * fault when filling the user space buffer with fiemap data.
3135 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3139 slot = path->slots[0];
3140 btrfs_release_path(path);
3141 path->nodes[0] = clone;
3142 path->slots[0] = slot;
3148 * Process a range which is a hole or a prealloc extent in the inode's subvolume
3149 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
3150 * extent. The end offset (@end) is inclusive.
3152 static int fiemap_process_hole(struct btrfs_inode *inode,
3153 struct fiemap_extent_info *fieinfo,
3154 struct fiemap_cache *cache,
3155 struct extent_state **delalloc_cached_state,
3156 struct btrfs_backref_share_check_ctx *backref_ctx,
3157 u64 disk_bytenr, u64 extent_offset,
3161 const u64 i_size = i_size_read(&inode->vfs_inode);
3162 u64 cur_offset = start;
3163 u64 last_delalloc_end = 0;
3164 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3165 bool checked_extent_shared = false;
3169 * There can be no delalloc past i_size, so don't waste time looking for
3172 while (cur_offset < end && cur_offset < i_size) {
3176 u64 prealloc_len = 0;
3179 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3180 delalloc_cached_state,
3187 * If this is a prealloc extent we have to report every section
3188 * of it that has no delalloc.
3190 if (disk_bytenr != 0) {
3191 if (last_delalloc_end == 0) {
3192 prealloc_start = start;
3193 prealloc_len = delalloc_start - start;
3195 prealloc_start = last_delalloc_end + 1;
3196 prealloc_len = delalloc_start - prealloc_start;
3200 if (prealloc_len > 0) {
3201 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3202 ret = btrfs_is_data_extent_shared(inode,
3209 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3211 checked_extent_shared = true;
3213 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3214 disk_bytenr + extent_offset,
3215 prealloc_len, prealloc_flags);
3218 extent_offset += prealloc_len;
3221 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3222 delalloc_end + 1 - delalloc_start,
3223 FIEMAP_EXTENT_DELALLOC |
3224 FIEMAP_EXTENT_UNKNOWN);
3228 last_delalloc_end = delalloc_end;
3229 cur_offset = delalloc_end + 1;
3230 extent_offset += cur_offset - delalloc_start;
3235 * Either we found no delalloc for the whole prealloc extent or we have
3236 * a prealloc extent that spans i_size or starts at or after i_size.
3238 if (disk_bytenr != 0 && last_delalloc_end < end) {
3242 if (last_delalloc_end == 0) {
3243 prealloc_start = start;
3244 prealloc_len = end + 1 - start;
3246 prealloc_start = last_delalloc_end + 1;
3247 prealloc_len = end + 1 - prealloc_start;
3250 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3251 ret = btrfs_is_data_extent_shared(inode,
3258 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3260 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3261 disk_bytenr + extent_offset,
3262 prealloc_len, prealloc_flags);
3270 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3271 struct btrfs_path *path,
3272 u64 *last_extent_end_ret)
3274 const u64 ino = btrfs_ino(inode);
3275 struct btrfs_root *root = inode->root;
3276 struct extent_buffer *leaf;
3277 struct btrfs_file_extent_item *ei;
3278 struct btrfs_key key;
3283 * Lookup the last file extent. We're not using i_size here because
3284 * there might be preallocation past i_size.
3286 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3287 /* There can't be a file extent item at offset (u64)-1 */
3293 * For a non-existing key, btrfs_search_slot() always leaves us at a
3294 * slot > 0, except if the btree is empty, which is impossible because
3295 * at least it has the inode item for this inode and all the items for
3296 * the root inode 256.
3298 ASSERT(path->slots[0] > 0);
3300 leaf = path->nodes[0];
3301 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3302 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3303 /* No file extent items in the subvolume tree. */
3304 *last_extent_end_ret = 0;
3309 * For an inline extent, the disk_bytenr is where inline data starts at,
3310 * so first check if we have an inline extent item before checking if we
3311 * have an implicit hole (disk_bytenr == 0).
3313 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3314 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3315 *last_extent_end_ret = btrfs_file_extent_end(path);
3320 * Find the last file extent item that is not a hole (when NO_HOLES is
3321 * not enabled). This should take at most 2 iterations in the worst
3322 * case: we have one hole file extent item at slot 0 of a leaf and
3323 * another hole file extent item as the last item in the previous leaf.
3324 * This is because we merge file extent items that represent holes.
3326 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3327 while (disk_bytenr == 0) {
3328 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3331 } else if (ret > 0) {
3332 /* No file extent items that are not holes. */
3333 *last_extent_end_ret = 0;
3336 leaf = path->nodes[0];
3337 ei = btrfs_item_ptr(leaf, path->slots[0],
3338 struct btrfs_file_extent_item);
3339 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3342 *last_extent_end_ret = btrfs_file_extent_end(path);
3346 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3349 const u64 ino = btrfs_ino(inode);
3350 struct extent_state *cached_state = NULL;
3351 struct extent_state *delalloc_cached_state = NULL;
3352 struct btrfs_path *path;
3353 struct fiemap_cache cache = { 0 };
3354 struct btrfs_backref_share_check_ctx *backref_ctx;
3355 u64 last_extent_end;
3356 u64 prev_extent_end;
3359 bool stopped = false;
3362 backref_ctx = btrfs_alloc_backref_share_check_ctx();
3363 path = btrfs_alloc_path();
3364 if (!backref_ctx || !path) {
3369 lockstart = round_down(start, inode->root->fs_info->sectorsize);
3370 lockend = round_up(start + len, inode->root->fs_info->sectorsize);
3371 prev_extent_end = lockstart;
3373 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
3374 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3376 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3379 btrfs_release_path(path);
3381 path->reada = READA_FORWARD;
3382 ret = fiemap_search_slot(inode, path, lockstart);
3385 } else if (ret > 0) {
3387 * No file extent item found, but we may have delalloc between
3388 * the current offset and i_size. So check for that.
3391 goto check_eof_delalloc;
3394 while (prev_extent_end < lockend) {
3395 struct extent_buffer *leaf = path->nodes[0];
3396 struct btrfs_file_extent_item *ei;
3397 struct btrfs_key key;
3400 u64 extent_offset = 0;
3402 u64 disk_bytenr = 0;
3407 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3408 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3411 extent_end = btrfs_file_extent_end(path);
3414 * The first iteration can leave us at an extent item that ends
3415 * before our range's start. Move to the next item.
3417 if (extent_end <= lockstart)
3420 backref_ctx->curr_leaf_bytenr = leaf->start;
3422 /* We have in implicit hole (NO_HOLES feature enabled). */
3423 if (prev_extent_end < key.offset) {
3424 const u64 range_end = min(key.offset, lockend) - 1;
3426 ret = fiemap_process_hole(inode, fieinfo, &cache,
3427 &delalloc_cached_state,
3428 backref_ctx, 0, 0, 0,
3429 prev_extent_end, range_end);
3432 } else if (ret > 0) {
3433 /* fiemap_fill_next_extent() told us to stop. */
3438 /* We've reached the end of the fiemap range, stop. */
3439 if (key.offset >= lockend) {
3445 extent_len = extent_end - key.offset;
3446 ei = btrfs_item_ptr(leaf, path->slots[0],
3447 struct btrfs_file_extent_item);
3448 compression = btrfs_file_extent_compression(leaf, ei);
3449 extent_type = btrfs_file_extent_type(leaf, ei);
3450 extent_gen = btrfs_file_extent_generation(leaf, ei);
3452 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3453 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3454 if (compression == BTRFS_COMPRESS_NONE)
3455 extent_offset = btrfs_file_extent_offset(leaf, ei);
3458 if (compression != BTRFS_COMPRESS_NONE)
3459 flags |= FIEMAP_EXTENT_ENCODED;
3461 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3462 flags |= FIEMAP_EXTENT_DATA_INLINE;
3463 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
3464 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
3466 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
3467 ret = fiemap_process_hole(inode, fieinfo, &cache,
3468 &delalloc_cached_state,
3470 disk_bytenr, extent_offset,
3471 extent_gen, key.offset,
3473 } else if (disk_bytenr == 0) {
3474 /* We have an explicit hole. */
3475 ret = fiemap_process_hole(inode, fieinfo, &cache,
3476 &delalloc_cached_state,
3477 backref_ctx, 0, 0, 0,
3478 key.offset, extent_end - 1);
3480 /* We have a regular extent. */
3481 if (fieinfo->fi_extents_max) {
3482 ret = btrfs_is_data_extent_shared(inode,
3489 flags |= FIEMAP_EXTENT_SHARED;
3492 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
3493 disk_bytenr + extent_offset,
3499 } else if (ret > 0) {
3500 /* fiemap_fill_next_extent() told us to stop. */
3505 prev_extent_end = extent_end;
3507 if (fatal_signal_pending(current)) {
3512 ret = fiemap_next_leaf_item(inode, path);
3515 } else if (ret > 0) {
3516 /* No more file extent items for this inode. */
3524 * Release (and free) the path before emitting any final entries to
3525 * fiemap_fill_next_extent() to keep lockdep happy. This is because
3526 * once we find no more file extent items exist, we may have a
3527 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
3528 * faults when copying data to the user space buffer.
3530 btrfs_free_path(path);
3533 if (!stopped && prev_extent_end < lockend) {
3534 ret = fiemap_process_hole(inode, fieinfo, &cache,
3535 &delalloc_cached_state, backref_ctx,
3536 0, 0, 0, prev_extent_end, lockend - 1);
3539 prev_extent_end = lockend;
3542 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
3543 const u64 i_size = i_size_read(&inode->vfs_inode);
3545 if (prev_extent_end < i_size) {
3550 delalloc = btrfs_find_delalloc_in_range(inode,
3553 &delalloc_cached_state,
3557 cache.flags |= FIEMAP_EXTENT_LAST;
3559 cache.flags |= FIEMAP_EXTENT_LAST;
3563 ret = emit_last_fiemap_cache(fieinfo, &cache);
3566 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3567 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3569 free_extent_state(delalloc_cached_state);
3570 btrfs_free_backref_share_ctx(backref_ctx);
3571 btrfs_free_path(path);
3575 static void __free_extent_buffer(struct extent_buffer *eb)
3577 kmem_cache_free(extent_buffer_cache, eb);
3580 int extent_buffer_under_io(const struct extent_buffer *eb)
3582 return (atomic_read(&eb->io_pages) ||
3583 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
3584 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3587 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
3589 struct btrfs_subpage *subpage;
3591 lockdep_assert_held(&page->mapping->private_lock);
3593 if (PagePrivate(page)) {
3594 subpage = (struct btrfs_subpage *)page->private;
3595 if (atomic_read(&subpage->eb_refs))
3598 * Even there is no eb refs here, we may still have
3599 * end_page_read() call relying on page::private.
3601 if (atomic_read(&subpage->readers))
3607 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
3609 struct btrfs_fs_info *fs_info = eb->fs_info;
3610 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3613 * For mapped eb, we're going to change the page private, which should
3614 * be done under the private_lock.
3617 spin_lock(&page->mapping->private_lock);
3619 if (!PagePrivate(page)) {
3621 spin_unlock(&page->mapping->private_lock);
3625 if (fs_info->nodesize >= PAGE_SIZE) {
3627 * We do this since we'll remove the pages after we've
3628 * removed the eb from the radix tree, so we could race
3629 * and have this page now attached to the new eb. So
3630 * only clear page_private if it's still connected to
3633 if (PagePrivate(page) &&
3634 page->private == (unsigned long)eb) {
3635 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3636 BUG_ON(PageDirty(page));
3637 BUG_ON(PageWriteback(page));
3639 * We need to make sure we haven't be attached
3642 detach_page_private(page);
3645 spin_unlock(&page->mapping->private_lock);
3650 * For subpage, we can have dummy eb with page private. In this case,
3651 * we can directly detach the private as such page is only attached to
3652 * one dummy eb, no sharing.
3655 btrfs_detach_subpage(fs_info, page);
3659 btrfs_page_dec_eb_refs(fs_info, page);
3662 * We can only detach the page private if there are no other ebs in the
3663 * page range and no unfinished IO.
3665 if (!page_range_has_eb(fs_info, page))
3666 btrfs_detach_subpage(fs_info, page);
3668 spin_unlock(&page->mapping->private_lock);
3671 /* Release all pages attached to the extent buffer */
3672 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
3677 ASSERT(!extent_buffer_under_io(eb));
3679 num_pages = num_extent_pages(eb);
3680 for (i = 0; i < num_pages; i++) {
3681 struct page *page = eb->pages[i];
3686 detach_extent_buffer_page(eb, page);
3688 /* One for when we allocated the page */
3694 * Helper for releasing the extent buffer.
3696 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
3698 btrfs_release_extent_buffer_pages(eb);
3699 btrfs_leak_debug_del_eb(eb);
3700 __free_extent_buffer(eb);
3703 static struct extent_buffer *
3704 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
3707 struct extent_buffer *eb = NULL;
3709 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
3712 eb->fs_info = fs_info;
3713 init_rwsem(&eb->lock);
3715 btrfs_leak_debug_add_eb(eb);
3716 INIT_LIST_HEAD(&eb->release_list);
3718 spin_lock_init(&eb->refs_lock);
3719 atomic_set(&eb->refs, 1);
3720 atomic_set(&eb->io_pages, 0);
3722 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
3727 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
3730 struct extent_buffer *new;
3731 int num_pages = num_extent_pages(src);
3734 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
3739 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
3740 * btrfs_release_extent_buffer() have different behavior for
3741 * UNMAPPED subpage extent buffer.
3743 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
3745 ret = btrfs_alloc_page_array(num_pages, new->pages);
3747 btrfs_release_extent_buffer(new);
3751 for (i = 0; i < num_pages; i++) {
3753 struct page *p = new->pages[i];
3755 ret = attach_extent_buffer_page(new, p, NULL);
3757 btrfs_release_extent_buffer(new);
3760 WARN_ON(PageDirty(p));
3761 copy_page(page_address(p), page_address(src->pages[i]));
3763 set_extent_buffer_uptodate(new);
3768 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3769 u64 start, unsigned long len)
3771 struct extent_buffer *eb;
3776 eb = __alloc_extent_buffer(fs_info, start, len);
3780 num_pages = num_extent_pages(eb);
3781 ret = btrfs_alloc_page_array(num_pages, eb->pages);
3785 for (i = 0; i < num_pages; i++) {
3786 struct page *p = eb->pages[i];
3788 ret = attach_extent_buffer_page(eb, p, NULL);
3793 set_extent_buffer_uptodate(eb);
3794 btrfs_set_header_nritems(eb, 0);
3795 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3799 for (i = 0; i < num_pages; i++) {
3801 detach_extent_buffer_page(eb, eb->pages[i]);
3802 __free_page(eb->pages[i]);
3805 __free_extent_buffer(eb);
3809 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3812 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
3815 static void check_buffer_tree_ref(struct extent_buffer *eb)
3819 * The TREE_REF bit is first set when the extent_buffer is added
3820 * to the radix tree. It is also reset, if unset, when a new reference
3821 * is created by find_extent_buffer.
3823 * It is only cleared in two cases: freeing the last non-tree
3824 * reference to the extent_buffer when its STALE bit is set or
3825 * calling release_folio when the tree reference is the only reference.
3827 * In both cases, care is taken to ensure that the extent_buffer's
3828 * pages are not under io. However, release_folio can be concurrently
3829 * called with creating new references, which is prone to race
3830 * conditions between the calls to check_buffer_tree_ref in those
3831 * codepaths and clearing TREE_REF in try_release_extent_buffer.
3833 * The actual lifetime of the extent_buffer in the radix tree is
3834 * adequately protected by the refcount, but the TREE_REF bit and
3835 * its corresponding reference are not. To protect against this
3836 * class of races, we call check_buffer_tree_ref from the codepaths
3837 * which trigger io after they set eb->io_pages. Note that once io is
3838 * initiated, TREE_REF can no longer be cleared, so that is the
3839 * moment at which any such race is best fixed.
3841 refs = atomic_read(&eb->refs);
3842 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3845 spin_lock(&eb->refs_lock);
3846 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3847 atomic_inc(&eb->refs);
3848 spin_unlock(&eb->refs_lock);
3851 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
3852 struct page *accessed)
3856 check_buffer_tree_ref(eb);
3858 num_pages = num_extent_pages(eb);
3859 for (i = 0; i < num_pages; i++) {
3860 struct page *p = eb->pages[i];
3863 mark_page_accessed(p);
3867 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
3870 struct extent_buffer *eb;
3872 eb = find_extent_buffer_nolock(fs_info, start);
3876 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
3877 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
3878 * another task running free_extent_buffer() might have seen that flag
3879 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
3880 * writeback flags not set) and it's still in the tree (flag
3881 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
3882 * decrementing the extent buffer's reference count twice. So here we
3883 * could race and increment the eb's reference count, clear its stale
3884 * flag, mark it as dirty and drop our reference before the other task
3885 * finishes executing free_extent_buffer, which would later result in
3886 * an attempt to free an extent buffer that is dirty.
3888 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
3889 spin_lock(&eb->refs_lock);
3890 spin_unlock(&eb->refs_lock);
3892 mark_extent_buffer_accessed(eb, NULL);
3896 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3897 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
3900 struct extent_buffer *eb, *exists = NULL;
3903 eb = find_extent_buffer(fs_info, start);
3906 eb = alloc_dummy_extent_buffer(fs_info, start);
3908 return ERR_PTR(-ENOMEM);
3909 eb->fs_info = fs_info;
3911 ret = radix_tree_preload(GFP_NOFS);
3913 exists = ERR_PTR(ret);
3916 spin_lock(&fs_info->buffer_lock);
3917 ret = radix_tree_insert(&fs_info->buffer_radix,
3918 start >> fs_info->sectorsize_bits, eb);
3919 spin_unlock(&fs_info->buffer_lock);
3920 radix_tree_preload_end();
3921 if (ret == -EEXIST) {
3922 exists = find_extent_buffer(fs_info, start);
3928 check_buffer_tree_ref(eb);
3929 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3933 btrfs_release_extent_buffer(eb);
3938 static struct extent_buffer *grab_extent_buffer(
3939 struct btrfs_fs_info *fs_info, struct page *page)
3941 struct extent_buffer *exists;
3944 * For subpage case, we completely rely on radix tree to ensure we
3945 * don't try to insert two ebs for the same bytenr. So here we always
3946 * return NULL and just continue.
3948 if (fs_info->nodesize < PAGE_SIZE)
3951 /* Page not yet attached to an extent buffer */
3952 if (!PagePrivate(page))
3956 * We could have already allocated an eb for this page and attached one
3957 * so lets see if we can get a ref on the existing eb, and if we can we
3958 * know it's good and we can just return that one, else we know we can
3959 * just overwrite page->private.
3961 exists = (struct extent_buffer *)page->private;
3962 if (atomic_inc_not_zero(&exists->refs))
3965 WARN_ON(PageDirty(page));
3966 detach_page_private(page);
3970 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
3972 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
3973 btrfs_err(fs_info, "bad tree block start %llu", start);
3977 if (fs_info->nodesize < PAGE_SIZE &&
3978 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
3980 "tree block crosses page boundary, start %llu nodesize %u",
3981 start, fs_info->nodesize);
3984 if (fs_info->nodesize >= PAGE_SIZE &&
3985 !PAGE_ALIGNED(start)) {
3987 "tree block is not page aligned, start %llu nodesize %u",
3988 start, fs_info->nodesize);
3994 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3995 u64 start, u64 owner_root, int level)
3997 unsigned long len = fs_info->nodesize;
4000 unsigned long index = start >> PAGE_SHIFT;
4001 struct extent_buffer *eb;
4002 struct extent_buffer *exists = NULL;
4004 struct address_space *mapping = fs_info->btree_inode->i_mapping;
4005 u64 lockdep_owner = owner_root;
4009 if (check_eb_alignment(fs_info, start))
4010 return ERR_PTR(-EINVAL);
4012 #if BITS_PER_LONG == 32
4013 if (start >= MAX_LFS_FILESIZE) {
4014 btrfs_err_rl(fs_info,
4015 "extent buffer %llu is beyond 32bit page cache limit", start);
4016 btrfs_err_32bit_limit(fs_info);
4017 return ERR_PTR(-EOVERFLOW);
4019 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
4020 btrfs_warn_32bit_limit(fs_info);
4023 eb = find_extent_buffer(fs_info, start);
4027 eb = __alloc_extent_buffer(fs_info, start, len);
4029 return ERR_PTR(-ENOMEM);
4032 * The reloc trees are just snapshots, so we need them to appear to be
4033 * just like any other fs tree WRT lockdep.
4035 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
4036 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4038 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
4040 num_pages = num_extent_pages(eb);
4041 for (i = 0; i < num_pages; i++, index++) {
4042 struct btrfs_subpage *prealloc = NULL;
4044 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
4046 exists = ERR_PTR(-ENOMEM);
4051 * Preallocate page->private for subpage case, so that we won't
4052 * allocate memory with private_lock hold. The memory will be
4053 * freed by attach_extent_buffer_page() or freed manually if
4056 * Although we have ensured one subpage eb can only have one
4057 * page, but it may change in the future for 16K page size
4058 * support, so we still preallocate the memory in the loop.
4060 if (fs_info->nodesize < PAGE_SIZE) {
4061 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
4062 if (IS_ERR(prealloc)) {
4063 ret = PTR_ERR(prealloc);
4066 exists = ERR_PTR(ret);
4071 spin_lock(&mapping->private_lock);
4072 exists = grab_extent_buffer(fs_info, p);
4074 spin_unlock(&mapping->private_lock);
4077 mark_extent_buffer_accessed(exists, p);
4078 btrfs_free_subpage(prealloc);
4081 /* Should not fail, as we have preallocated the memory */
4082 ret = attach_extent_buffer_page(eb, p, prealloc);
4085 * To inform we have extra eb under allocation, so that
4086 * detach_extent_buffer_page() won't release the page private
4087 * when the eb hasn't yet been inserted into radix tree.
4089 * The ref will be decreased when the eb released the page, in
4090 * detach_extent_buffer_page().
4091 * Thus needs no special handling in error path.
4093 btrfs_page_inc_eb_refs(fs_info, p);
4094 spin_unlock(&mapping->private_lock);
4096 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
4098 if (!PageUptodate(p))
4102 * We can't unlock the pages just yet since the extent buffer
4103 * hasn't been properly inserted in the radix tree, this
4104 * opens a race with btree_release_folio which can free a page
4105 * while we are still filling in all pages for the buffer and
4110 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4112 ret = radix_tree_preload(GFP_NOFS);
4114 exists = ERR_PTR(ret);
4118 spin_lock(&fs_info->buffer_lock);
4119 ret = radix_tree_insert(&fs_info->buffer_radix,
4120 start >> fs_info->sectorsize_bits, eb);
4121 spin_unlock(&fs_info->buffer_lock);
4122 radix_tree_preload_end();
4123 if (ret == -EEXIST) {
4124 exists = find_extent_buffer(fs_info, start);
4130 /* add one reference for the tree */
4131 check_buffer_tree_ref(eb);
4132 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4135 * Now it's safe to unlock the pages because any calls to
4136 * btree_release_folio will correctly detect that a page belongs to a
4137 * live buffer and won't free them prematurely.
4139 for (i = 0; i < num_pages; i++)
4140 unlock_page(eb->pages[i]);
4144 WARN_ON(!atomic_dec_and_test(&eb->refs));
4145 for (i = 0; i < num_pages; i++) {
4147 unlock_page(eb->pages[i]);
4150 btrfs_release_extent_buffer(eb);
4154 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4156 struct extent_buffer *eb =
4157 container_of(head, struct extent_buffer, rcu_head);
4159 __free_extent_buffer(eb);
4162 static int release_extent_buffer(struct extent_buffer *eb)
4163 __releases(&eb->refs_lock)
4165 lockdep_assert_held(&eb->refs_lock);
4167 WARN_ON(atomic_read(&eb->refs) == 0);
4168 if (atomic_dec_and_test(&eb->refs)) {
4169 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4170 struct btrfs_fs_info *fs_info = eb->fs_info;
4172 spin_unlock(&eb->refs_lock);
4174 spin_lock(&fs_info->buffer_lock);
4175 radix_tree_delete(&fs_info->buffer_radix,
4176 eb->start >> fs_info->sectorsize_bits);
4177 spin_unlock(&fs_info->buffer_lock);
4179 spin_unlock(&eb->refs_lock);
4182 btrfs_leak_debug_del_eb(eb);
4183 /* Should be safe to release our pages at this point */
4184 btrfs_release_extent_buffer_pages(eb);
4185 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4186 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4187 __free_extent_buffer(eb);
4191 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4194 spin_unlock(&eb->refs_lock);
4199 void free_extent_buffer(struct extent_buffer *eb)
4205 refs = atomic_read(&eb->refs);
4207 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4208 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4211 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4215 spin_lock(&eb->refs_lock);
4216 if (atomic_read(&eb->refs) == 2 &&
4217 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4218 !extent_buffer_under_io(eb) &&
4219 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4220 atomic_dec(&eb->refs);
4223 * I know this is terrible, but it's temporary until we stop tracking
4224 * the uptodate bits and such for the extent buffers.
4226 release_extent_buffer(eb);
4229 void free_extent_buffer_stale(struct extent_buffer *eb)
4234 spin_lock(&eb->refs_lock);
4235 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4237 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4238 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4239 atomic_dec(&eb->refs);
4240 release_extent_buffer(eb);
4243 static void btree_clear_page_dirty(struct page *page)
4245 ASSERT(PageDirty(page));
4246 ASSERT(PageLocked(page));
4247 clear_page_dirty_for_io(page);
4248 xa_lock_irq(&page->mapping->i_pages);
4249 if (!PageDirty(page))
4250 __xa_clear_mark(&page->mapping->i_pages,
4251 page_index(page), PAGECACHE_TAG_DIRTY);
4252 xa_unlock_irq(&page->mapping->i_pages);
4255 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4257 struct btrfs_fs_info *fs_info = eb->fs_info;
4258 struct page *page = eb->pages[0];
4261 /* btree_clear_page_dirty() needs page locked */
4263 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4266 btree_clear_page_dirty(page);
4268 WARN_ON(atomic_read(&eb->refs) == 0);
4271 void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
4272 struct extent_buffer *eb)
4274 struct btrfs_fs_info *fs_info = eb->fs_info;
4279 btrfs_assert_tree_write_locked(eb);
4281 if (trans && btrfs_header_generation(eb) != trans->transid)
4284 if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
4287 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
4288 fs_info->dirty_metadata_batch);
4290 if (eb->fs_info->nodesize < PAGE_SIZE)
4291 return clear_subpage_extent_buffer_dirty(eb);
4293 num_pages = num_extent_pages(eb);
4295 for (i = 0; i < num_pages; i++) {
4296 page = eb->pages[i];
4297 if (!PageDirty(page))
4300 btree_clear_page_dirty(page);
4301 ClearPageError(page);
4304 WARN_ON(atomic_read(&eb->refs) == 0);
4307 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4313 check_buffer_tree_ref(eb);
4315 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4317 num_pages = num_extent_pages(eb);
4318 WARN_ON(atomic_read(&eb->refs) == 0);
4319 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4322 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4325 * For subpage case, we can have other extent buffers in the
4326 * same page, and in clear_subpage_extent_buffer_dirty() we
4327 * have to clear page dirty without subpage lock held.
4328 * This can cause race where our page gets dirty cleared after
4331 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4332 * its page for other reasons, we can use page lock to prevent
4336 lock_page(eb->pages[0]);
4337 for (i = 0; i < num_pages; i++)
4338 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4339 eb->start, eb->len);
4341 unlock_page(eb->pages[0]);
4343 #ifdef CONFIG_BTRFS_DEBUG
4344 for (i = 0; i < num_pages; i++)
4345 ASSERT(PageDirty(eb->pages[i]));
4351 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4353 struct btrfs_fs_info *fs_info = eb->fs_info;
4358 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4359 num_pages = num_extent_pages(eb);
4360 for (i = 0; i < num_pages; i++) {
4361 page = eb->pages[i];
4366 * This is special handling for metadata subpage, as regular
4367 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4369 if (fs_info->nodesize >= PAGE_SIZE)
4370 ClearPageUptodate(page);
4372 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4377 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4379 struct btrfs_fs_info *fs_info = eb->fs_info;
4384 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4385 num_pages = num_extent_pages(eb);
4386 for (i = 0; i < num_pages; i++) {
4387 page = eb->pages[i];
4390 * This is special handling for metadata subpage, as regular
4391 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4393 if (fs_info->nodesize >= PAGE_SIZE)
4394 SetPageUptodate(page);
4396 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4401 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4403 struct btrfs_tree_parent_check *check)
4405 struct btrfs_fs_info *fs_info = eb->fs_info;
4406 struct extent_io_tree *io_tree;
4407 struct page *page = eb->pages[0];
4408 struct extent_state *cached_state = NULL;
4409 struct btrfs_bio_ctrl bio_ctrl = {
4410 .mirror_num = mirror_num,
4411 .parent_check = check,
4415 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4416 ASSERT(PagePrivate(page));
4418 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4420 if (wait == WAIT_NONE) {
4421 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4425 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4432 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4433 PageUptodate(page) ||
4434 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4435 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4436 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4441 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4442 eb->read_mirror = 0;
4443 atomic_set(&eb->io_pages, 1);
4444 check_buffer_tree_ref(eb);
4445 bio_ctrl.end_io_func = end_bio_extent_readpage;
4447 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
4449 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
4450 ret = submit_extent_page(REQ_OP_READ, NULL, &bio_ctrl,
4451 eb->start, page, eb->len,
4452 eb->start - page_offset(page), 0, true);
4455 * In the endio function, if we hit something wrong we will
4456 * increase the io_pages, so here we need to decrease it for
4459 atomic_dec(&eb->io_pages);
4461 submit_one_bio(&bio_ctrl);
4462 if (ret || wait != WAIT_COMPLETE) {
4463 free_extent_state(cached_state);
4467 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1,
4468 EXTENT_LOCKED, &cached_state);
4469 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4474 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
4475 struct btrfs_tree_parent_check *check)
4481 int locked_pages = 0;
4482 int all_uptodate = 1;
4484 unsigned long num_reads = 0;
4485 struct btrfs_bio_ctrl bio_ctrl = {
4486 .mirror_num = mirror_num,
4487 .parent_check = check,
4490 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4494 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
4495 * operation, which could potentially still be in flight. In this case
4496 * we simply want to return an error.
4498 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
4501 if (eb->fs_info->nodesize < PAGE_SIZE)
4502 return read_extent_buffer_subpage(eb, wait, mirror_num, check);
4504 num_pages = num_extent_pages(eb);
4505 for (i = 0; i < num_pages; i++) {
4506 page = eb->pages[i];
4507 if (wait == WAIT_NONE) {
4509 * WAIT_NONE is only utilized by readahead. If we can't
4510 * acquire the lock atomically it means either the eb
4511 * is being read out or under modification.
4512 * Either way the eb will be or has been cached,
4513 * readahead can exit safely.
4515 if (!trylock_page(page))
4523 * We need to firstly lock all pages to make sure that
4524 * the uptodate bit of our pages won't be affected by
4525 * clear_extent_buffer_uptodate().
4527 for (i = 0; i < num_pages; i++) {
4528 page = eb->pages[i];
4529 if (!PageUptodate(page)) {
4536 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4540 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4541 eb->read_mirror = 0;
4542 atomic_set(&eb->io_pages, num_reads);
4544 * It is possible for release_folio to clear the TREE_REF bit before we
4545 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
4547 check_buffer_tree_ref(eb);
4548 bio_ctrl.end_io_func = end_bio_extent_readpage;
4549 for (i = 0; i < num_pages; i++) {
4550 page = eb->pages[i];
4552 if (!PageUptodate(page)) {
4554 atomic_dec(&eb->io_pages);
4559 ClearPageError(page);
4560 err = submit_extent_page(REQ_OP_READ, NULL,
4561 &bio_ctrl, page_offset(page), page,
4562 PAGE_SIZE, 0, 0, false);
4565 * We failed to submit the bio so it's the
4566 * caller's responsibility to perform cleanup
4567 * i.e unlock page/set error bit.
4572 atomic_dec(&eb->io_pages);
4579 submit_one_bio(&bio_ctrl);
4581 if (ret || wait != WAIT_COMPLETE)
4584 for (i = 0; i < num_pages; i++) {
4585 page = eb->pages[i];
4586 wait_on_page_locked(page);
4587 if (!PageUptodate(page))
4594 while (locked_pages > 0) {
4596 page = eb->pages[locked_pages];
4602 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
4605 btrfs_warn(eb->fs_info,
4606 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
4607 eb->start, eb->len, start, len);
4608 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4614 * Check if the [start, start + len) range is valid before reading/writing
4616 * NOTE: @start and @len are offset inside the eb, not logical address.
4618 * Caller should not touch the dst/src memory if this function returns error.
4620 static inline int check_eb_range(const struct extent_buffer *eb,
4621 unsigned long start, unsigned long len)
4623 unsigned long offset;
4625 /* start, start + len should not go beyond eb->len nor overflow */
4626 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
4627 return report_eb_range(eb, start, len);
4632 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
4633 unsigned long start, unsigned long len)
4639 char *dst = (char *)dstv;
4640 unsigned long i = get_eb_page_index(start);
4642 if (check_eb_range(eb, start, len))
4645 offset = get_eb_offset_in_page(eb, start);
4648 page = eb->pages[i];
4650 cur = min(len, (PAGE_SIZE - offset));
4651 kaddr = page_address(page);
4652 memcpy(dst, kaddr + offset, cur);
4661 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
4663 unsigned long start, unsigned long len)
4669 char __user *dst = (char __user *)dstv;
4670 unsigned long i = get_eb_page_index(start);
4673 WARN_ON(start > eb->len);
4674 WARN_ON(start + len > eb->start + eb->len);
4676 offset = get_eb_offset_in_page(eb, start);
4679 page = eb->pages[i];
4681 cur = min(len, (PAGE_SIZE - offset));
4682 kaddr = page_address(page);
4683 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
4697 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
4698 unsigned long start, unsigned long len)
4704 char *ptr = (char *)ptrv;
4705 unsigned long i = get_eb_page_index(start);
4708 if (check_eb_range(eb, start, len))
4711 offset = get_eb_offset_in_page(eb, start);
4714 page = eb->pages[i];
4716 cur = min(len, (PAGE_SIZE - offset));
4718 kaddr = page_address(page);
4719 ret = memcmp(ptr, kaddr + offset, cur);
4732 * Check that the extent buffer is uptodate.
4734 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
4735 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
4737 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
4740 struct btrfs_fs_info *fs_info = eb->fs_info;
4743 * If we are using the commit root we could potentially clear a page
4744 * Uptodate while we're using the extent buffer that we've previously
4745 * looked up. We don't want to complain in this case, as the page was
4746 * valid before, we just didn't write it out. Instead we want to catch
4747 * the case where we didn't actually read the block properly, which
4748 * would have !PageUptodate && !PageError, as we clear PageError before
4751 if (fs_info->nodesize < PAGE_SIZE) {
4752 bool uptodate, error;
4754 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
4755 eb->start, eb->len);
4756 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
4757 WARN_ON(!uptodate && !error);
4759 WARN_ON(!PageUptodate(page) && !PageError(page));
4763 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
4768 assert_eb_page_uptodate(eb, eb->pages[0]);
4769 kaddr = page_address(eb->pages[0]) +
4770 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
4772 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
4775 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
4779 assert_eb_page_uptodate(eb, eb->pages[0]);
4780 kaddr = page_address(eb->pages[0]) +
4781 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
4782 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
4785 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
4786 unsigned long start, unsigned long len)
4792 char *src = (char *)srcv;
4793 unsigned long i = get_eb_page_index(start);
4795 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
4797 if (check_eb_range(eb, start, len))
4800 offset = get_eb_offset_in_page(eb, start);
4803 page = eb->pages[i];
4804 assert_eb_page_uptodate(eb, page);
4806 cur = min(len, PAGE_SIZE - offset);
4807 kaddr = page_address(page);
4808 memcpy(kaddr + offset, src, cur);
4817 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
4824 unsigned long i = get_eb_page_index(start);
4826 if (check_eb_range(eb, start, len))
4829 offset = get_eb_offset_in_page(eb, start);
4832 page = eb->pages[i];
4833 assert_eb_page_uptodate(eb, page);
4835 cur = min(len, PAGE_SIZE - offset);
4836 kaddr = page_address(page);
4837 memset(kaddr + offset, 0, cur);
4845 void copy_extent_buffer_full(const struct extent_buffer *dst,
4846 const struct extent_buffer *src)
4851 ASSERT(dst->len == src->len);
4853 if (dst->fs_info->nodesize >= PAGE_SIZE) {
4854 num_pages = num_extent_pages(dst);
4855 for (i = 0; i < num_pages; i++)
4856 copy_page(page_address(dst->pages[i]),
4857 page_address(src->pages[i]));
4859 size_t src_offset = get_eb_offset_in_page(src, 0);
4860 size_t dst_offset = get_eb_offset_in_page(dst, 0);
4862 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
4863 memcpy(page_address(dst->pages[0]) + dst_offset,
4864 page_address(src->pages[0]) + src_offset,
4869 void copy_extent_buffer(const struct extent_buffer *dst,
4870 const struct extent_buffer *src,
4871 unsigned long dst_offset, unsigned long src_offset,
4874 u64 dst_len = dst->len;
4879 unsigned long i = get_eb_page_index(dst_offset);
4881 if (check_eb_range(dst, dst_offset, len) ||
4882 check_eb_range(src, src_offset, len))
4885 WARN_ON(src->len != dst_len);
4887 offset = get_eb_offset_in_page(dst, dst_offset);
4890 page = dst->pages[i];
4891 assert_eb_page_uptodate(dst, page);
4893 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
4895 kaddr = page_address(page);
4896 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4906 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
4908 * @eb: the extent buffer
4909 * @start: offset of the bitmap item in the extent buffer
4911 * @page_index: return index of the page in the extent buffer that contains the
4913 * @page_offset: return offset into the page given by page_index
4915 * This helper hides the ugliness of finding the byte in an extent buffer which
4916 * contains a given bit.
4918 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
4919 unsigned long start, unsigned long nr,
4920 unsigned long *page_index,
4921 size_t *page_offset)
4923 size_t byte_offset = BIT_BYTE(nr);
4927 * The byte we want is the offset of the extent buffer + the offset of
4928 * the bitmap item in the extent buffer + the offset of the byte in the
4931 offset = start + offset_in_page(eb->start) + byte_offset;
4933 *page_index = offset >> PAGE_SHIFT;
4934 *page_offset = offset_in_page(offset);
4938 * Determine whether a bit in a bitmap item is set.
4940 * @eb: the extent buffer
4941 * @start: offset of the bitmap item in the extent buffer
4942 * @nr: bit number to test
4944 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
4952 eb_bitmap_offset(eb, start, nr, &i, &offset);
4953 page = eb->pages[i];
4954 assert_eb_page_uptodate(eb, page);
4955 kaddr = page_address(page);
4956 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
4960 * Set an area of a bitmap to 1.
4962 * @eb: the extent buffer
4963 * @start: offset of the bitmap item in the extent buffer
4964 * @pos: bit number of the first bit
4965 * @len: number of bits to set
4967 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
4968 unsigned long pos, unsigned long len)
4974 const unsigned int size = pos + len;
4975 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
4976 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
4978 eb_bitmap_offset(eb, start, pos, &i, &offset);
4979 page = eb->pages[i];
4980 assert_eb_page_uptodate(eb, page);
4981 kaddr = page_address(page);
4983 while (len >= bits_to_set) {
4984 kaddr[offset] |= mask_to_set;
4986 bits_to_set = BITS_PER_BYTE;
4988 if (++offset >= PAGE_SIZE && len > 0) {
4990 page = eb->pages[++i];
4991 assert_eb_page_uptodate(eb, page);
4992 kaddr = page_address(page);
4996 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
4997 kaddr[offset] |= mask_to_set;
5003 * Clear an area of a bitmap.
5005 * @eb: the extent buffer
5006 * @start: offset of the bitmap item in the extent buffer
5007 * @pos: bit number of the first bit
5008 * @len: number of bits to clear
5010 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
5011 unsigned long start, unsigned long pos,
5018 const unsigned int size = pos + len;
5019 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5020 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5022 eb_bitmap_offset(eb, start, pos, &i, &offset);
5023 page = eb->pages[i];
5024 assert_eb_page_uptodate(eb, page);
5025 kaddr = page_address(page);
5027 while (len >= bits_to_clear) {
5028 kaddr[offset] &= ~mask_to_clear;
5029 len -= bits_to_clear;
5030 bits_to_clear = BITS_PER_BYTE;
5032 if (++offset >= PAGE_SIZE && len > 0) {
5034 page = eb->pages[++i];
5035 assert_eb_page_uptodate(eb, page);
5036 kaddr = page_address(page);
5040 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5041 kaddr[offset] &= ~mask_to_clear;
5045 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5047 unsigned long distance = (src > dst) ? src - dst : dst - src;
5048 return distance < len;
5051 static void copy_pages(struct page *dst_page, struct page *src_page,
5052 unsigned long dst_off, unsigned long src_off,
5055 char *dst_kaddr = page_address(dst_page);
5057 int must_memmove = 0;
5059 if (dst_page != src_page) {
5060 src_kaddr = page_address(src_page);
5062 src_kaddr = dst_kaddr;
5063 if (areas_overlap(src_off, dst_off, len))
5068 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5070 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5073 void memcpy_extent_buffer(const struct extent_buffer *dst,
5074 unsigned long dst_offset, unsigned long src_offset,
5078 size_t dst_off_in_page;
5079 size_t src_off_in_page;
5080 unsigned long dst_i;
5081 unsigned long src_i;
5083 if (check_eb_range(dst, dst_offset, len) ||
5084 check_eb_range(dst, src_offset, len))
5088 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
5089 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
5091 dst_i = get_eb_page_index(dst_offset);
5092 src_i = get_eb_page_index(src_offset);
5094 cur = min(len, (unsigned long)(PAGE_SIZE -
5096 cur = min_t(unsigned long, cur,
5097 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5099 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5100 dst_off_in_page, src_off_in_page, cur);
5108 void memmove_extent_buffer(const struct extent_buffer *dst,
5109 unsigned long dst_offset, unsigned long src_offset,
5113 size_t dst_off_in_page;
5114 size_t src_off_in_page;
5115 unsigned long dst_end = dst_offset + len - 1;
5116 unsigned long src_end = src_offset + len - 1;
5117 unsigned long dst_i;
5118 unsigned long src_i;
5120 if (check_eb_range(dst, dst_offset, len) ||
5121 check_eb_range(dst, src_offset, len))
5123 if (dst_offset < src_offset) {
5124 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5128 dst_i = get_eb_page_index(dst_end);
5129 src_i = get_eb_page_index(src_end);
5131 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
5132 src_off_in_page = get_eb_offset_in_page(dst, src_end);
5134 cur = min_t(unsigned long, len, src_off_in_page + 1);
5135 cur = min(cur, dst_off_in_page + 1);
5136 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5137 dst_off_in_page - cur + 1,
5138 src_off_in_page - cur + 1, cur);
5146 #define GANG_LOOKUP_SIZE 16
5147 static struct extent_buffer *get_next_extent_buffer(
5148 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
5150 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
5151 struct extent_buffer *found = NULL;
5152 u64 page_start = page_offset(page);
5153 u64 cur = page_start;
5155 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
5156 lockdep_assert_held(&fs_info->buffer_lock);
5158 while (cur < page_start + PAGE_SIZE) {
5162 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
5163 (void **)gang, cur >> fs_info->sectorsize_bits,
5164 min_t(unsigned int, GANG_LOOKUP_SIZE,
5165 PAGE_SIZE / fs_info->nodesize));
5168 for (i = 0; i < ret; i++) {
5169 /* Already beyond page end */
5170 if (gang[i]->start >= page_start + PAGE_SIZE)
5173 if (gang[i]->start >= bytenr) {
5178 cur = gang[ret - 1]->start + gang[ret - 1]->len;
5184 static int try_release_subpage_extent_buffer(struct page *page)
5186 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5187 u64 cur = page_offset(page);
5188 const u64 end = page_offset(page) + PAGE_SIZE;
5192 struct extent_buffer *eb = NULL;
5195 * Unlike try_release_extent_buffer() which uses page->private
5196 * to grab buffer, for subpage case we rely on radix tree, thus
5197 * we need to ensure radix tree consistency.
5199 * We also want an atomic snapshot of the radix tree, thus go
5200 * with spinlock rather than RCU.
5202 spin_lock(&fs_info->buffer_lock);
5203 eb = get_next_extent_buffer(fs_info, page, cur);
5205 /* No more eb in the page range after or at cur */
5206 spin_unlock(&fs_info->buffer_lock);
5209 cur = eb->start + eb->len;
5212 * The same as try_release_extent_buffer(), to ensure the eb
5213 * won't disappear out from under us.
5215 spin_lock(&eb->refs_lock);
5216 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5217 spin_unlock(&eb->refs_lock);
5218 spin_unlock(&fs_info->buffer_lock);
5221 spin_unlock(&fs_info->buffer_lock);
5224 * If tree ref isn't set then we know the ref on this eb is a
5225 * real ref, so just return, this eb will likely be freed soon
5228 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5229 spin_unlock(&eb->refs_lock);
5234 * Here we don't care about the return value, we will always
5235 * check the page private at the end. And
5236 * release_extent_buffer() will release the refs_lock.
5238 release_extent_buffer(eb);
5241 * Finally to check if we have cleared page private, as if we have
5242 * released all ebs in the page, the page private should be cleared now.
5244 spin_lock(&page->mapping->private_lock);
5245 if (!PagePrivate(page))
5249 spin_unlock(&page->mapping->private_lock);
5254 int try_release_extent_buffer(struct page *page)
5256 struct extent_buffer *eb;
5258 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5259 return try_release_subpage_extent_buffer(page);
5262 * We need to make sure nobody is changing page->private, as we rely on
5263 * page->private as the pointer to extent buffer.
5265 spin_lock(&page->mapping->private_lock);
5266 if (!PagePrivate(page)) {
5267 spin_unlock(&page->mapping->private_lock);
5271 eb = (struct extent_buffer *)page->private;
5275 * This is a little awful but should be ok, we need to make sure that
5276 * the eb doesn't disappear out from under us while we're looking at
5279 spin_lock(&eb->refs_lock);
5280 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5281 spin_unlock(&eb->refs_lock);
5282 spin_unlock(&page->mapping->private_lock);
5285 spin_unlock(&page->mapping->private_lock);
5288 * If tree ref isn't set then we know the ref on this eb is a real ref,
5289 * so just return, this page will likely be freed soon anyway.
5291 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5292 spin_unlock(&eb->refs_lock);
5296 return release_extent_buffer(eb);
5300 * btrfs_readahead_tree_block - attempt to readahead a child block
5301 * @fs_info: the fs_info
5302 * @bytenr: bytenr to read
5303 * @owner_root: objectid of the root that owns this eb
5304 * @gen: generation for the uptodate check, can be 0
5305 * @level: level for the eb
5307 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5308 * normal uptodate check of the eb, without checking the generation. If we have
5309 * to read the block we will not block on anything.
5311 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5312 u64 bytenr, u64 owner_root, u64 gen, int level)
5314 struct btrfs_tree_parent_check check = {
5319 struct extent_buffer *eb;
5322 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5326 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5327 free_extent_buffer(eb);
5331 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
5333 free_extent_buffer_stale(eb);
5335 free_extent_buffer(eb);
5339 * btrfs_readahead_node_child - readahead a node's child block
5340 * @node: parent node we're reading from
5341 * @slot: slot in the parent node for the child we want to read
5343 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5344 * the slot in the node provided.
5346 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5348 btrfs_readahead_tree_block(node->fs_info,
5349 btrfs_node_blockptr(node, slot),
5350 btrfs_header_owner(node),
5351 btrfs_node_ptr_generation(node, slot),
5352 btrfs_header_level(node) - 1);