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 {
100 struct btrfs_bio *bbio;
102 enum btrfs_compression_type compress_type;
103 u32 len_to_oe_boundary;
105 btrfs_bio_end_io_t end_io_func;
106 struct writeback_control *wbc;
109 * This is for metadata read, to provide the extra needed verification
110 * info. This has to be provided for submit_one_bio(), as
111 * submit_one_bio() can submit a bio if it ends at stripe boundary. If
112 * no such parent_check is provided, the metadata can hit false alert at
115 struct btrfs_tree_parent_check *parent_check;
118 * Tell writepage not to lock the state bits for this range, it still
119 * does the unlocking.
124 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
126 struct btrfs_bio *bbio = bio_ctrl->bbio;
127 int mirror_num = bio_ctrl->mirror_num;
132 /* Caller should ensure the bio has at least some range added */
133 ASSERT(bbio->bio.bi_iter.bi_size);
135 if (!is_data_inode(&bbio->inode->vfs_inode)) {
136 if (btrfs_op(&bbio->bio) != BTRFS_MAP_WRITE) {
138 * For metadata read, we should have the parent_check,
139 * and copy it to bbio for metadata verification.
141 ASSERT(bio_ctrl->parent_check);
142 memcpy(&bbio->parent_check,
143 bio_ctrl->parent_check,
144 sizeof(struct btrfs_tree_parent_check));
146 bbio->bio.bi_opf |= REQ_META;
149 if (btrfs_op(&bbio->bio) == BTRFS_MAP_READ &&
150 bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
151 btrfs_submit_compressed_read(bbio, mirror_num);
153 btrfs_submit_bio(bbio, mirror_num);
155 /* The bbio is owned by the end_io handler now */
156 bio_ctrl->bbio = NULL;
160 * Submit or fail the current bio in the bio_ctrl structure.
162 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
164 struct btrfs_bio *bbio = bio_ctrl->bbio;
171 btrfs_bio_end_io(bbio, errno_to_blk_status(ret));
172 /* The bio is owned by the end_io handler now */
173 bio_ctrl->bbio = NULL;
175 submit_one_bio(bio_ctrl);
179 int __init extent_buffer_init_cachep(void)
181 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
182 sizeof(struct extent_buffer), 0,
183 SLAB_MEM_SPREAD, NULL);
184 if (!extent_buffer_cache)
190 void __cold extent_buffer_free_cachep(void)
193 * Make sure all delayed rcu free are flushed before we
197 kmem_cache_destroy(extent_buffer_cache);
200 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
202 unsigned long index = start >> PAGE_SHIFT;
203 unsigned long end_index = end >> PAGE_SHIFT;
206 while (index <= end_index) {
207 page = find_get_page(inode->i_mapping, index);
208 BUG_ON(!page); /* Pages should be in the extent_io_tree */
209 clear_page_dirty_for_io(page);
215 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
217 struct address_space *mapping = inode->i_mapping;
218 unsigned long index = start >> PAGE_SHIFT;
219 unsigned long end_index = end >> PAGE_SHIFT;
222 while (index <= end_index) {
223 folio = filemap_get_folio(mapping, index);
224 filemap_dirty_folio(mapping, folio);
225 folio_account_redirty(folio);
226 index += folio_nr_pages(folio);
232 * Process one page for __process_pages_contig().
234 * Return >0 if we hit @page == @locked_page.
235 * Return 0 if we updated the page status.
236 * Return -EGAIN if the we need to try again.
237 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
239 static int process_one_page(struct btrfs_fs_info *fs_info,
240 struct address_space *mapping,
241 struct page *page, struct page *locked_page,
242 unsigned long page_ops, u64 start, u64 end)
246 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
247 len = end + 1 - start;
249 if (page_ops & PAGE_SET_ORDERED)
250 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
251 if (page_ops & PAGE_SET_ERROR)
252 btrfs_page_clamp_set_error(fs_info, page, start, len);
253 if (page_ops & PAGE_START_WRITEBACK) {
254 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
255 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
257 if (page_ops & PAGE_END_WRITEBACK)
258 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
260 if (page == locked_page)
263 if (page_ops & PAGE_LOCK) {
266 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
269 if (!PageDirty(page) || page->mapping != mapping) {
270 btrfs_page_end_writer_lock(fs_info, page, start, len);
274 if (page_ops & PAGE_UNLOCK)
275 btrfs_page_end_writer_lock(fs_info, page, start, len);
279 static int __process_pages_contig(struct address_space *mapping,
280 struct page *locked_page,
281 u64 start, u64 end, unsigned long page_ops,
284 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
285 pgoff_t start_index = start >> PAGE_SHIFT;
286 pgoff_t end_index = end >> PAGE_SHIFT;
287 pgoff_t index = start_index;
288 unsigned long pages_processed = 0;
289 struct folio_batch fbatch;
293 if (page_ops & PAGE_LOCK) {
294 ASSERT(page_ops == PAGE_LOCK);
295 ASSERT(processed_end && *processed_end == start);
298 if ((page_ops & PAGE_SET_ERROR) && start_index <= end_index)
299 mapping_set_error(mapping, -EIO);
301 folio_batch_init(&fbatch);
302 while (index <= end_index) {
305 found_folios = filemap_get_folios_contig(mapping, &index,
308 if (found_folios == 0) {
310 * Only if we're going to lock these pages, we can find
313 ASSERT(page_ops & PAGE_LOCK);
318 for (i = 0; i < found_folios; i++) {
320 struct folio *folio = fbatch.folios[i];
321 process_ret = process_one_page(fs_info, mapping,
322 &folio->page, locked_page, page_ops,
324 if (process_ret < 0) {
326 folio_batch_release(&fbatch);
329 pages_processed += folio_nr_pages(folio);
331 folio_batch_release(&fbatch);
335 if (err && processed_end) {
337 * Update @processed_end. I know this is awful since it has
338 * two different return value patterns (inclusive vs exclusive).
340 * But the exclusive pattern is necessary if @start is 0, or we
341 * underflow and check against processed_end won't work as
345 *processed_end = min(end,
346 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
348 *processed_end = start;
353 static noinline void __unlock_for_delalloc(struct inode *inode,
354 struct page *locked_page,
357 unsigned long index = start >> PAGE_SHIFT;
358 unsigned long end_index = end >> PAGE_SHIFT;
361 if (index == locked_page->index && end_index == index)
364 __process_pages_contig(inode->i_mapping, locked_page, start, end,
368 static noinline int lock_delalloc_pages(struct inode *inode,
369 struct page *locked_page,
373 unsigned long index = delalloc_start >> PAGE_SHIFT;
374 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
375 u64 processed_end = delalloc_start;
379 if (index == locked_page->index && index == end_index)
382 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
383 delalloc_end, PAGE_LOCK, &processed_end);
384 if (ret == -EAGAIN && processed_end > delalloc_start)
385 __unlock_for_delalloc(inode, locked_page, delalloc_start,
391 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
392 * more than @max_bytes.
394 * @start: The original start bytenr to search.
395 * Will store the extent range start bytenr.
396 * @end: The original end bytenr of the search range
397 * Will store the extent range end bytenr.
399 * Return true if we find a delalloc range which starts inside the original
400 * range, and @start/@end will store the delalloc range start/end.
402 * Return false if we can't find any delalloc range which starts inside the
403 * original range, and @start/@end will be the non-delalloc range start/end.
406 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
407 struct page *locked_page, u64 *start,
410 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
411 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
412 const u64 orig_start = *start;
413 const u64 orig_end = *end;
414 /* The sanity tests may not set a valid fs_info. */
415 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
419 struct extent_state *cached_state = NULL;
423 /* Caller should pass a valid @end to indicate the search range end */
424 ASSERT(orig_end > orig_start);
426 /* The range should at least cover part of the page */
427 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
428 orig_end <= page_offset(locked_page)));
430 /* step one, find a bunch of delalloc bytes starting at start */
431 delalloc_start = *start;
433 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
434 max_bytes, &cached_state);
435 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
436 *start = delalloc_start;
438 /* @delalloc_end can be -1, never go beyond @orig_end */
439 *end = min(delalloc_end, orig_end);
440 free_extent_state(cached_state);
445 * start comes from the offset of locked_page. We have to lock
446 * pages in order, so we can't process delalloc bytes before
449 if (delalloc_start < *start)
450 delalloc_start = *start;
453 * make sure to limit the number of pages we try to lock down
455 if (delalloc_end + 1 - delalloc_start > max_bytes)
456 delalloc_end = delalloc_start + max_bytes - 1;
458 /* step two, lock all the pages after the page that has start */
459 ret = lock_delalloc_pages(inode, locked_page,
460 delalloc_start, delalloc_end);
461 ASSERT(!ret || ret == -EAGAIN);
462 if (ret == -EAGAIN) {
463 /* some of the pages are gone, lets avoid looping by
464 * shortening the size of the delalloc range we're searching
466 free_extent_state(cached_state);
469 max_bytes = PAGE_SIZE;
478 /* step three, lock the state bits for the whole range */
479 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
481 /* then test to make sure it is all still delalloc */
482 ret = test_range_bit(tree, delalloc_start, delalloc_end,
483 EXTENT_DELALLOC, 1, cached_state);
485 unlock_extent(tree, delalloc_start, delalloc_end,
487 __unlock_for_delalloc(inode, locked_page,
488 delalloc_start, delalloc_end);
492 free_extent_state(cached_state);
493 *start = delalloc_start;
499 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
500 struct page *locked_page,
501 u32 clear_bits, unsigned long page_ops)
503 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
505 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
506 start, end, page_ops, NULL);
509 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
511 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
513 ASSERT(page_offset(page) <= start &&
514 start + len <= page_offset(page) + PAGE_SIZE);
517 if (fsverity_active(page->mapping->host) &&
519 !PageUptodate(page) &&
520 start < i_size_read(page->mapping->host) &&
521 !fsverity_verify_page(page)) {
522 btrfs_page_set_error(fs_info, page, start, len);
524 btrfs_page_set_uptodate(fs_info, page, start, len);
527 btrfs_page_clear_uptodate(fs_info, page, start, len);
528 btrfs_page_set_error(fs_info, page, start, len);
531 if (!btrfs_is_subpage(fs_info, page))
534 btrfs_subpage_end_reader(fs_info, page, start, len);
537 /* lots and lots of room for performance fixes in the end_bio funcs */
539 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
541 struct btrfs_inode *inode;
542 const bool uptodate = (err == 0);
545 ASSERT(page && page->mapping);
546 inode = BTRFS_I(page->mapping->host);
547 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
550 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
553 ASSERT(end + 1 - start <= U32_MAX);
554 len = end + 1 - start;
556 btrfs_page_clear_uptodate(fs_info, page, start, len);
557 btrfs_page_set_error(fs_info, page, start, len);
558 ret = err < 0 ? err : -EIO;
559 mapping_set_error(page->mapping, ret);
564 * after a writepage IO is done, we need to:
565 * clear the uptodate bits on error
566 * clear the writeback bits in the extent tree for this IO
567 * end_page_writeback if the page has no more pending IO
569 * Scheduling is not allowed, so the extent state tree is expected
570 * to have one and only one object corresponding to this IO.
572 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
574 struct bio *bio = &bbio->bio;
575 int error = blk_status_to_errno(bio->bi_status);
576 struct bio_vec *bvec;
579 struct bvec_iter_all iter_all;
581 ASSERT(!bio_flagged(bio, BIO_CLONED));
582 bio_for_each_segment_all(bvec, bio, iter_all) {
583 struct page *page = bvec->bv_page;
584 struct inode *inode = page->mapping->host;
585 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
586 const u32 sectorsize = fs_info->sectorsize;
588 /* Our read/write should always be sector aligned. */
589 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
591 "partial page write in btrfs with offset %u and length %u",
592 bvec->bv_offset, bvec->bv_len);
593 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
595 "incomplete page write with offset %u and length %u",
596 bvec->bv_offset, bvec->bv_len);
598 start = page_offset(page) + bvec->bv_offset;
599 end = start + bvec->bv_len - 1;
601 end_extent_writepage(page, error, start, end);
603 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
610 * Record previously processed extent range
612 * For endio_readpage_release_extent() to handle a full extent range, reducing
613 * the extent io operations.
615 struct processed_extent {
616 struct btrfs_inode *inode;
617 /* Start of the range in @inode */
619 /* End of the range in @inode */
625 * Try to release processed extent range
627 * May not release the extent range right now if the current range is
628 * contiguous to processed extent.
630 * Will release processed extent when any of @inode, @uptodate, the range is
631 * no longer contiguous to the processed range.
633 * Passing @inode == NULL will force processed extent to be released.
635 static void endio_readpage_release_extent(struct processed_extent *processed,
636 struct btrfs_inode *inode, u64 start, u64 end,
639 struct extent_state *cached = NULL;
640 struct extent_io_tree *tree;
642 /* The first extent, initialize @processed */
643 if (!processed->inode)
647 * Contiguous to processed extent, just uptodate the end.
649 * Several things to notice:
651 * - bio can be merged as long as on-disk bytenr is contiguous
652 * This means we can have page belonging to other inodes, thus need to
653 * check if the inode still matches.
654 * - bvec can contain range beyond current page for multi-page bvec
655 * Thus we need to do processed->end + 1 >= start check
657 if (processed->inode == inode && processed->uptodate == uptodate &&
658 processed->end + 1 >= start && end >= processed->end) {
659 processed->end = end;
663 tree = &processed->inode->io_tree;
665 * Now we don't have range contiguous to the processed range, release
666 * the processed range now.
668 unlock_extent(tree, processed->start, processed->end, &cached);
671 /* Update processed to current range */
672 processed->inode = inode;
673 processed->start = start;
674 processed->end = end;
675 processed->uptodate = uptodate;
678 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
680 ASSERT(PageLocked(page));
681 if (!btrfs_is_subpage(fs_info, page))
684 ASSERT(PagePrivate(page));
685 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
689 * Find extent buffer for a givne bytenr.
691 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
694 static struct extent_buffer *find_extent_buffer_readpage(
695 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
697 struct extent_buffer *eb;
700 * For regular sectorsize, we can use page->private to grab extent
703 if (fs_info->nodesize >= PAGE_SIZE) {
704 ASSERT(PagePrivate(page) && page->private);
705 return (struct extent_buffer *)page->private;
708 /* For subpage case, we need to lookup buffer radix tree */
710 eb = radix_tree_lookup(&fs_info->buffer_radix,
711 bytenr >> fs_info->sectorsize_bits);
718 * after a readpage IO is done, we need to:
719 * clear the uptodate bits on error
720 * set the uptodate bits if things worked
721 * set the page up to date if all extents in the tree are uptodate
722 * clear the lock bit in the extent tree
723 * unlock the page if there are no other extents locked for it
725 * Scheduling is not allowed, so the extent state tree is expected
726 * to have one and only one object corresponding to this IO.
728 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
730 struct bio *bio = &bbio->bio;
731 struct bio_vec *bvec;
732 struct processed_extent processed = { 0 };
734 * The offset to the beginning of a bio, since one bio can never be
735 * larger than UINT_MAX, u32 here is enough.
739 struct bvec_iter_all iter_all;
741 ASSERT(!bio_flagged(bio, BIO_CLONED));
742 bio_for_each_segment_all(bvec, bio, iter_all) {
743 bool uptodate = !bio->bi_status;
744 struct page *page = bvec->bv_page;
745 struct inode *inode = page->mapping->host;
746 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
747 const u32 sectorsize = fs_info->sectorsize;
753 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
754 bio->bi_iter.bi_sector, bio->bi_status,
758 * We always issue full-sector reads, but if some block in a
759 * page fails to read, blk_update_request() will advance
760 * bv_offset and adjust bv_len to compensate. Print a warning
761 * for unaligned offsets, and an error if they don't add up to
764 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
766 "partial page read in btrfs with offset %u and length %u",
767 bvec->bv_offset, bvec->bv_len);
768 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
771 "incomplete page read with offset %u and length %u",
772 bvec->bv_offset, bvec->bv_len);
774 start = page_offset(page) + bvec->bv_offset;
775 end = start + bvec->bv_len - 1;
778 mirror = bbio->mirror_num;
779 if (uptodate && !is_data_inode(inode) &&
780 btrfs_validate_metadata_buffer(bbio, page, start, end, mirror))
783 if (likely(uptodate)) {
784 loff_t i_size = i_size_read(inode);
785 pgoff_t end_index = i_size >> PAGE_SHIFT;
788 * Zero out the remaining part if this range straddles
791 * Here we should only zero the range inside the bvec,
792 * not touch anything else.
794 * NOTE: i_size is exclusive while end is inclusive.
796 if (page->index == end_index && i_size <= end) {
797 u32 zero_start = max(offset_in_page(i_size),
798 offset_in_page(start));
800 zero_user_segment(page, zero_start,
801 offset_in_page(end) + 1);
803 } else if (!is_data_inode(inode)) {
804 struct extent_buffer *eb;
806 eb = find_extent_buffer_readpage(fs_info, page, start);
807 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
808 eb->read_mirror = mirror;
809 atomic_dec(&eb->io_pages);
812 /* Update page status and unlock. */
813 end_page_read(page, uptodate, start, len);
814 endio_readpage_release_extent(&processed, BTRFS_I(inode),
815 start, end, PageUptodate(page));
817 ASSERT(bio_offset + len > bio_offset);
821 /* Release the last extent */
822 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
827 * Populate every free slot in a provided array with pages.
829 * @nr_pages: number of pages to allocate
830 * @page_array: the array to fill with pages; any existing non-null entries in
831 * the array will be skipped
833 * Return: 0 if all pages were able to be allocated;
834 * -ENOMEM otherwise, and the caller is responsible for freeing all
835 * non-null page pointers in the array.
837 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
839 unsigned int allocated;
841 for (allocated = 0; allocated < nr_pages;) {
842 unsigned int last = allocated;
844 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
846 if (allocated == nr_pages)
850 * During this iteration, no page could be allocated, even
851 * though alloc_pages_bulk_array() falls back to alloc_page()
852 * if it could not bulk-allocate. So we must be out of memory.
854 if (allocated == last)
857 memalloc_retry_wait(GFP_NOFS);
862 static bool btrfs_bio_is_contig(struct btrfs_bio_ctrl *bio_ctrl,
863 struct page *page, u64 disk_bytenr,
864 unsigned int pg_offset)
866 struct bio *bio = &bio_ctrl->bbio->bio;
867 struct bio_vec *bvec = bio_last_bvec_all(bio);
868 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
870 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
872 * For compression, all IO should have its logical bytenr set
873 * to the starting bytenr of the compressed extent.
875 return bio->bi_iter.bi_sector == sector;
879 * The contig check requires the following conditions to be met:
881 * 1) The pages are belonging to the same inode
882 * This is implied by the call chain.
884 * 2) The range has adjacent logical bytenr
886 * 3) The range has adjacent file offset
887 * This is required for the usage of btrfs_bio->file_offset.
889 return bio_end_sector(bio) == sector &&
890 page_offset(bvec->bv_page) + bvec->bv_offset + bvec->bv_len ==
891 page_offset(page) + pg_offset;
894 static void alloc_new_bio(struct btrfs_inode *inode,
895 struct btrfs_bio_ctrl *bio_ctrl,
896 u64 disk_bytenr, u64 file_offset)
898 struct btrfs_fs_info *fs_info = inode->root->fs_info;
899 struct btrfs_bio *bbio;
901 bbio = btrfs_bio_alloc(BIO_MAX_VECS, bio_ctrl->opf, fs_info,
902 bio_ctrl->end_io_func, NULL);
903 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
905 bbio->file_offset = file_offset;
906 bio_ctrl->bbio = bbio;
907 bio_ctrl->len_to_oe_boundary = U32_MAX;
910 * Limit the extent to the ordered boundary for Zone Append.
911 * Compressed bios aren't submitted directly, so it doesn't apply to
914 if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE &&
915 btrfs_use_zone_append(bbio)) {
916 struct btrfs_ordered_extent *ordered;
918 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
920 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
921 ordered->file_offset +
922 ordered->disk_num_bytes - file_offset);
923 btrfs_put_ordered_extent(ordered);
929 * Pick the last added device to support cgroup writeback. For
930 * multi-device file systems this means blk-cgroup policies have
931 * to always be set on the last added/replaced device.
932 * This is a bit odd but has been like that for a long time.
934 bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
935 wbc_init_bio(bio_ctrl->wbc, &bbio->bio);
940 * @disk_bytenr: logical bytenr where the write will be
941 * @page: page to add to the bio
942 * @size: portion of page that we want to write to
943 * @pg_offset: offset of the new bio or to check whether we are adding
944 * a contiguous page to the previous one
946 * The will either add the page into the existing @bio_ctrl->bbio, or allocate a
947 * new one in @bio_ctrl->bbio.
948 * The mirror number for this IO should already be initizlied in
949 * @bio_ctrl->mirror_num.
951 static void submit_extent_page(struct btrfs_bio_ctrl *bio_ctrl,
952 u64 disk_bytenr, struct page *page,
953 size_t size, unsigned long pg_offset)
955 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
957 ASSERT(pg_offset + size <= PAGE_SIZE);
958 ASSERT(bio_ctrl->end_io_func);
960 if (bio_ctrl->bbio &&
961 !btrfs_bio_is_contig(bio_ctrl, page, disk_bytenr, pg_offset))
962 submit_one_bio(bio_ctrl);
967 /* Allocate new bio if needed */
968 if (!bio_ctrl->bbio) {
969 alloc_new_bio(inode, bio_ctrl, disk_bytenr,
970 page_offset(page) + pg_offset);
973 /* Cap to the current ordered extent boundary if there is one. */
974 if (len > bio_ctrl->len_to_oe_boundary) {
975 ASSERT(bio_ctrl->compress_type == BTRFS_COMPRESS_NONE);
976 ASSERT(is_data_inode(&inode->vfs_inode));
977 len = bio_ctrl->len_to_oe_boundary;
980 if (bio_add_page(&bio_ctrl->bbio->bio, page, len, pg_offset) != len) {
981 /* bio full: move on to a new one */
982 submit_one_bio(bio_ctrl);
987 wbc_account_cgroup_owner(bio_ctrl->wbc, page, len);
992 bio_ctrl->len_to_oe_boundary -= len;
994 /* Ordered extent boundary: move on to a new bio. */
995 if (bio_ctrl->len_to_oe_boundary == 0)
996 submit_one_bio(bio_ctrl);
1000 static int attach_extent_buffer_page(struct extent_buffer *eb,
1002 struct btrfs_subpage *prealloc)
1004 struct btrfs_fs_info *fs_info = eb->fs_info;
1008 * If the page is mapped to btree inode, we should hold the private
1009 * lock to prevent race.
1010 * For cloned or dummy extent buffers, their pages are not mapped and
1011 * will not race with any other ebs.
1014 lockdep_assert_held(&page->mapping->private_lock);
1016 if (fs_info->nodesize >= PAGE_SIZE) {
1017 if (!PagePrivate(page))
1018 attach_page_private(page, eb);
1020 WARN_ON(page->private != (unsigned long)eb);
1024 /* Already mapped, just free prealloc */
1025 if (PagePrivate(page)) {
1026 btrfs_free_subpage(prealloc);
1031 /* Has preallocated memory for subpage */
1032 attach_page_private(page, prealloc);
1034 /* Do new allocation to attach subpage */
1035 ret = btrfs_attach_subpage(fs_info, page,
1036 BTRFS_SUBPAGE_METADATA);
1040 int set_page_extent_mapped(struct page *page)
1042 struct btrfs_fs_info *fs_info;
1044 ASSERT(page->mapping);
1046 if (PagePrivate(page))
1049 fs_info = btrfs_sb(page->mapping->host->i_sb);
1051 if (btrfs_is_subpage(fs_info, page))
1052 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1054 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1058 void clear_page_extent_mapped(struct page *page)
1060 struct btrfs_fs_info *fs_info;
1062 ASSERT(page->mapping);
1064 if (!PagePrivate(page))
1067 fs_info = btrfs_sb(page->mapping->host->i_sb);
1068 if (btrfs_is_subpage(fs_info, page))
1069 return btrfs_detach_subpage(fs_info, page);
1071 detach_page_private(page);
1074 static struct extent_map *
1075 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1076 u64 start, u64 len, struct extent_map **em_cached)
1078 struct extent_map *em;
1080 if (em_cached && *em_cached) {
1082 if (extent_map_in_tree(em) && start >= em->start &&
1083 start < extent_map_end(em)) {
1084 refcount_inc(&em->refs);
1088 free_extent_map(em);
1092 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1093 if (em_cached && !IS_ERR(em)) {
1095 refcount_inc(&em->refs);
1101 * basic readpage implementation. Locked extent state structs are inserted
1102 * into the tree that are removed when the IO is done (by the end_io
1104 * XXX JDM: This needs looking at to ensure proper page locking
1105 * return 0 on success, otherwise return error
1107 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1108 struct btrfs_bio_ctrl *bio_ctrl, u64 *prev_em_start)
1110 struct inode *inode = page->mapping->host;
1111 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1112 u64 start = page_offset(page);
1113 const u64 end = start + PAGE_SIZE - 1;
1116 u64 last_byte = i_size_read(inode);
1118 struct extent_map *em;
1120 size_t pg_offset = 0;
1122 size_t blocksize = inode->i_sb->s_blocksize;
1123 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1125 ret = set_page_extent_mapped(page);
1127 unlock_extent(tree, start, end, NULL);
1128 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1133 if (page->index == last_byte >> PAGE_SHIFT) {
1134 size_t zero_offset = offset_in_page(last_byte);
1137 iosize = PAGE_SIZE - zero_offset;
1138 memzero_page(page, zero_offset, iosize);
1141 bio_ctrl->end_io_func = end_bio_extent_readpage;
1142 begin_page_read(fs_info, page);
1143 while (cur <= end) {
1144 enum btrfs_compression_type compress_type = BTRFS_COMPRESS_NONE;
1145 bool force_bio_submit = false;
1148 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1149 if (cur >= last_byte) {
1150 iosize = PAGE_SIZE - pg_offset;
1151 memzero_page(page, pg_offset, iosize);
1152 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1153 end_page_read(page, true, cur, iosize);
1156 em = __get_extent_map(inode, page, pg_offset, cur,
1157 end - cur + 1, em_cached);
1159 unlock_extent(tree, cur, end, NULL);
1160 end_page_read(page, false, cur, end + 1 - cur);
1163 extent_offset = cur - em->start;
1164 BUG_ON(extent_map_end(em) <= cur);
1167 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1168 compress_type = em->compress_type;
1170 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1171 iosize = ALIGN(iosize, blocksize);
1172 if (compress_type != BTRFS_COMPRESS_NONE)
1173 disk_bytenr = em->block_start;
1175 disk_bytenr = em->block_start + extent_offset;
1176 block_start = em->block_start;
1177 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1178 block_start = EXTENT_MAP_HOLE;
1181 * If we have a file range that points to a compressed extent
1182 * and it's followed by a consecutive file range that points
1183 * to the same compressed extent (possibly with a different
1184 * offset and/or length, so it either points to the whole extent
1185 * or only part of it), we must make sure we do not submit a
1186 * single bio to populate the pages for the 2 ranges because
1187 * this makes the compressed extent read zero out the pages
1188 * belonging to the 2nd range. Imagine the following scenario:
1191 * [0 - 8K] [8K - 24K]
1194 * points to extent X, points to extent X,
1195 * offset 4K, length of 8K offset 0, length 16K
1197 * [extent X, compressed length = 4K uncompressed length = 16K]
1199 * If the bio to read the compressed extent covers both ranges,
1200 * it will decompress extent X into the pages belonging to the
1201 * first range and then it will stop, zeroing out the remaining
1202 * pages that belong to the other range that points to extent X.
1203 * So here we make sure we submit 2 bios, one for the first
1204 * range and another one for the third range. Both will target
1205 * the same physical extent from disk, but we can't currently
1206 * make the compressed bio endio callback populate the pages
1207 * for both ranges because each compressed bio is tightly
1208 * coupled with a single extent map, and each range can have
1209 * an extent map with a different offset value relative to the
1210 * uncompressed data of our extent and different lengths. This
1211 * is a corner case so we prioritize correctness over
1212 * non-optimal behavior (submitting 2 bios for the same extent).
1214 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1215 prev_em_start && *prev_em_start != (u64)-1 &&
1216 *prev_em_start != em->start)
1217 force_bio_submit = true;
1220 *prev_em_start = em->start;
1222 free_extent_map(em);
1225 /* we've found a hole, just zero and go on */
1226 if (block_start == EXTENT_MAP_HOLE) {
1227 memzero_page(page, pg_offset, iosize);
1229 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1230 end_page_read(page, true, cur, iosize);
1232 pg_offset += iosize;
1235 /* the get_extent function already copied into the page */
1236 if (block_start == EXTENT_MAP_INLINE) {
1237 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1238 end_page_read(page, true, cur, iosize);
1240 pg_offset += iosize;
1244 if (bio_ctrl->compress_type != compress_type) {
1245 submit_one_bio(bio_ctrl);
1246 bio_ctrl->compress_type = compress_type;
1249 if (force_bio_submit)
1250 submit_one_bio(bio_ctrl);
1251 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1254 pg_offset += iosize;
1260 int btrfs_read_folio(struct file *file, struct folio *folio)
1262 struct page *page = &folio->page;
1263 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1264 u64 start = page_offset(page);
1265 u64 end = start + PAGE_SIZE - 1;
1266 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ };
1269 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1271 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, NULL);
1273 * If btrfs_do_readpage() failed we will want to submit the assembled
1274 * bio to do the cleanup.
1276 submit_one_bio(&bio_ctrl);
1280 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1282 struct extent_map **em_cached,
1283 struct btrfs_bio_ctrl *bio_ctrl,
1286 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1289 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1291 for (index = 0; index < nr_pages; index++) {
1292 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1294 put_page(pages[index]);
1299 * helper for __extent_writepage, doing all of the delayed allocation setup.
1301 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1302 * to write the page (copy into inline extent). In this case the IO has
1303 * been started and the page is already unlocked.
1305 * This returns 0 if all went well (page still locked)
1306 * This returns < 0 if there were errors (page still locked)
1308 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1309 struct page *page, struct writeback_control *wbc)
1311 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1312 u64 delalloc_start = page_offset(page);
1313 u64 delalloc_to_write = 0;
1314 /* How many pages are started by btrfs_run_delalloc_range() */
1315 unsigned long nr_written = 0;
1317 int page_started = 0;
1319 while (delalloc_start < page_end) {
1320 u64 delalloc_end = page_end;
1323 found = find_lock_delalloc_range(&inode->vfs_inode, page,
1327 delalloc_start = delalloc_end + 1;
1330 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1331 delalloc_end, &page_started, &nr_written, wbc);
1333 btrfs_page_set_error(inode->root->fs_info, page,
1334 page_offset(page), PAGE_SIZE);
1338 * delalloc_end is already one less than the total length, so
1339 * we don't subtract one from PAGE_SIZE
1341 delalloc_to_write += (delalloc_end - delalloc_start +
1342 PAGE_SIZE) >> PAGE_SHIFT;
1343 delalloc_start = delalloc_end + 1;
1345 if (wbc->nr_to_write < delalloc_to_write) {
1348 if (delalloc_to_write < thresh * 2)
1349 thresh = delalloc_to_write;
1350 wbc->nr_to_write = min_t(u64, delalloc_to_write,
1354 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
1357 * We've unlocked the page, so we can't update the mapping's
1358 * writeback index, just update nr_to_write.
1360 wbc->nr_to_write -= nr_written;
1368 * Find the first byte we need to write.
1370 * For subpage, one page can contain several sectors, and
1371 * __extent_writepage_io() will just grab all extent maps in the page
1372 * range and try to submit all non-inline/non-compressed extents.
1374 * This is a big problem for subpage, we shouldn't re-submit already written
1376 * This function will lookup subpage dirty bit to find which range we really
1379 * Return the next dirty range in [@start, @end).
1380 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
1382 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
1383 struct page *page, u64 *start, u64 *end)
1385 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
1386 struct btrfs_subpage_info *spi = fs_info->subpage_info;
1387 u64 orig_start = *start;
1388 /* Declare as unsigned long so we can use bitmap ops */
1389 unsigned long flags;
1390 int range_start_bit;
1394 * For regular sector size == page size case, since one page only
1395 * contains one sector, we return the page offset directly.
1397 if (!btrfs_is_subpage(fs_info, page)) {
1398 *start = page_offset(page);
1399 *end = page_offset(page) + PAGE_SIZE;
1403 range_start_bit = spi->dirty_offset +
1404 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
1406 /* We should have the page locked, but just in case */
1407 spin_lock_irqsave(&subpage->lock, flags);
1408 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
1409 spi->dirty_offset + spi->bitmap_nr_bits);
1410 spin_unlock_irqrestore(&subpage->lock, flags);
1412 range_start_bit -= spi->dirty_offset;
1413 range_end_bit -= spi->dirty_offset;
1415 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
1416 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
1420 * helper for __extent_writepage. This calls the writepage start hooks,
1421 * and does the loop to map the page into extents and bios.
1423 * We return 1 if the IO is started and the page is unlocked,
1424 * 0 if all went well (page still locked)
1425 * < 0 if there were errors (page still locked)
1427 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
1429 struct btrfs_bio_ctrl *bio_ctrl,
1433 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1434 u64 cur = page_offset(page);
1435 u64 end = cur + PAGE_SIZE - 1;
1438 struct extent_map *em;
1443 ret = btrfs_writepage_cow_fixup(page);
1445 /* Fixup worker will requeue */
1446 redirty_page_for_writepage(bio_ctrl->wbc, page);
1452 * we don't want to touch the inode after unlocking the page,
1453 * so we update the mapping writeback index now
1455 bio_ctrl->wbc->nr_to_write--;
1457 bio_ctrl->end_io_func = end_bio_extent_writepage;
1458 while (cur <= end) {
1461 u64 dirty_range_start = cur;
1462 u64 dirty_range_end;
1465 if (cur >= i_size) {
1466 btrfs_writepage_endio_finish_ordered(inode, page, cur,
1469 * This range is beyond i_size, thus we don't need to
1470 * bother writing back.
1471 * But we still need to clear the dirty subpage bit, or
1472 * the next time the page gets dirtied, we will try to
1473 * writeback the sectors with subpage dirty bits,
1474 * causing writeback without ordered extent.
1476 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
1480 find_next_dirty_byte(fs_info, page, &dirty_range_start,
1482 if (cur < dirty_range_start) {
1483 cur = dirty_range_start;
1487 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
1489 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
1490 ret = PTR_ERR_OR_ZERO(em);
1494 extent_offset = cur - em->start;
1495 em_end = extent_map_end(em);
1496 ASSERT(cur <= em_end);
1498 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
1499 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
1500 block_start = em->block_start;
1501 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
1502 disk_bytenr = em->block_start + extent_offset;
1505 * Note that em_end from extent_map_end() and dirty_range_end from
1506 * find_next_dirty_byte() are all exclusive
1508 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
1509 free_extent_map(em);
1513 * compressed and inline extents are written through other
1516 if (compressed || block_start == EXTENT_MAP_HOLE ||
1517 block_start == EXTENT_MAP_INLINE) {
1521 btrfs_writepage_endio_finish_ordered(inode,
1522 page, cur, cur + iosize - 1, true);
1523 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
1528 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
1529 if (!PageWriteback(page)) {
1530 btrfs_err(inode->root->fs_info,
1531 "page %lu not writeback, cur %llu end %llu",
1532 page->index, cur, end);
1536 * Although the PageDirty bit is cleared before entering this
1537 * function, subpage dirty bit is not cleared.
1538 * So clear subpage dirty bit here so next time we won't submit
1539 * page for range already written to disk.
1541 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
1543 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1544 cur - page_offset(page));
1549 btrfs_page_assert_not_dirty(fs_info, page);
1555 * If we finish without problem, we should not only clear page dirty,
1556 * but also empty subpage dirty bits
1563 * the writepage semantics are similar to regular writepage. extent
1564 * records are inserted to lock ranges in the tree, and as dirty areas
1565 * are found, they are marked writeback. Then the lock bits are removed
1566 * and the end_io handler clears the writeback ranges
1568 * Return 0 if everything goes well.
1569 * Return <0 for error.
1571 static int __extent_writepage(struct page *page, struct btrfs_bio_ctrl *bio_ctrl)
1573 struct folio *folio = page_folio(page);
1574 struct inode *inode = page->mapping->host;
1575 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1576 const u64 page_start = page_offset(page);
1577 const u64 page_end = page_start + PAGE_SIZE - 1;
1581 loff_t i_size = i_size_read(inode);
1582 unsigned long end_index = i_size >> PAGE_SHIFT;
1584 trace___extent_writepage(page, inode, bio_ctrl->wbc);
1586 WARN_ON(!PageLocked(page));
1588 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
1589 page_offset(page), PAGE_SIZE);
1591 pg_offset = offset_in_page(i_size);
1592 if (page->index > end_index ||
1593 (page->index == end_index && !pg_offset)) {
1594 folio_invalidate(folio, 0, folio_size(folio));
1595 folio_unlock(folio);
1599 if (page->index == end_index)
1600 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
1602 ret = set_page_extent_mapped(page);
1608 if (!bio_ctrl->extent_locked) {
1609 ret = writepage_delalloc(BTRFS_I(inode), page, bio_ctrl->wbc);
1616 ret = __extent_writepage_io(BTRFS_I(inode), page, bio_ctrl, i_size, &nr);
1622 /* make sure the mapping tag for page dirty gets cleared */
1623 set_page_writeback(page);
1624 end_page_writeback(page);
1627 * Here we used to have a check for PageError() and then set @ret and
1628 * call end_extent_writepage().
1630 * But in fact setting @ret here will cause different error paths
1631 * between subpage and regular sectorsize.
1633 * For regular page size, we never submit current page, but only add
1634 * current page to current bio.
1635 * The bio submission can only happen in next page.
1636 * Thus if we hit the PageError() branch, @ret is already set to
1637 * non-zero value and will not get updated for regular sectorsize.
1639 * But for subpage case, it's possible we submit part of current page,
1640 * thus can get PageError() set by submitted bio of the same page,
1641 * while our @ret is still 0.
1643 * So here we unify the behavior and don't set @ret.
1644 * Error can still be properly passed to higher layer as page will
1645 * be set error, here we just don't handle the IO failure.
1647 * NOTE: This is just a hotfix for subpage.
1648 * The root fix will be properly ending ordered extent when we hit
1649 * an error during writeback.
1651 * But that needs a bigger refactoring, as we not only need to grab the
1652 * submitted OE, but also need to know exactly at which bytenr we hit
1654 * Currently the full page based __extent_writepage_io() is not
1657 if (PageError(page))
1658 end_extent_writepage(page, ret, page_start, page_end);
1659 if (bio_ctrl->extent_locked) {
1660 struct writeback_control *wbc = bio_ctrl->wbc;
1663 * If bio_ctrl->extent_locked, it's from extent_write_locked_range(),
1664 * the page can either be locked by lock_page() or
1665 * process_one_page().
1666 * Let btrfs_page_unlock_writer() handle both cases.
1669 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
1670 wbc->range_end + 1 - wbc->range_start);
1678 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
1680 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
1681 TASK_UNINTERRUPTIBLE);
1684 static void end_extent_buffer_writeback(struct extent_buffer *eb)
1686 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1687 smp_mb__after_atomic();
1688 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
1692 * Lock extent buffer status and pages for writeback.
1694 * May try to flush write bio if we can't get the lock.
1696 * Return 0 if the extent buffer doesn't need to be submitted.
1697 * (E.g. the extent buffer is not dirty)
1698 * Return >0 is the extent buffer is submitted to bio.
1699 * Return <0 if something went wrong, no page is locked.
1701 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
1702 struct btrfs_bio_ctrl *bio_ctrl)
1704 struct btrfs_fs_info *fs_info = eb->fs_info;
1709 if (!btrfs_try_tree_write_lock(eb)) {
1710 submit_write_bio(bio_ctrl, 0);
1712 btrfs_tree_lock(eb);
1715 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
1716 btrfs_tree_unlock(eb);
1717 if (bio_ctrl->wbc->sync_mode != WB_SYNC_ALL)
1720 submit_write_bio(bio_ctrl, 0);
1724 wait_on_extent_buffer_writeback(eb);
1725 btrfs_tree_lock(eb);
1726 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
1728 btrfs_tree_unlock(eb);
1733 * We need to do this to prevent races in people who check if the eb is
1734 * under IO since we can end up having no IO bits set for a short period
1737 spin_lock(&eb->refs_lock);
1738 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
1739 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1740 spin_unlock(&eb->refs_lock);
1741 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
1742 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1744 fs_info->dirty_metadata_batch);
1747 spin_unlock(&eb->refs_lock);
1750 btrfs_tree_unlock(eb);
1753 * Either we don't need to submit any tree block, or we're submitting
1755 * Subpage metadata doesn't use page locking at all, so we can skip
1758 if (!ret || fs_info->nodesize < PAGE_SIZE)
1761 num_pages = num_extent_pages(eb);
1762 for (i = 0; i < num_pages; i++) {
1763 struct page *p = eb->pages[i];
1765 if (!trylock_page(p)) {
1767 submit_write_bio(bio_ctrl, 0);
1777 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
1779 struct btrfs_fs_info *fs_info = eb->fs_info;
1781 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
1782 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
1786 * A read may stumble upon this buffer later, make sure that it gets an
1787 * error and knows there was an error.
1789 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
1792 * We need to set the mapping with the io error as well because a write
1793 * error will flip the file system readonly, and then syncfs() will
1794 * return a 0 because we are readonly if we don't modify the err seq for
1797 mapping_set_error(page->mapping, -EIO);
1800 * If writeback for a btree extent that doesn't belong to a log tree
1801 * failed, increment the counter transaction->eb_write_errors.
1802 * We do this because while the transaction is running and before it's
1803 * committing (when we call filemap_fdata[write|wait]_range against
1804 * the btree inode), we might have
1805 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
1806 * returns an error or an error happens during writeback, when we're
1807 * committing the transaction we wouldn't know about it, since the pages
1808 * can be no longer dirty nor marked anymore for writeback (if a
1809 * subsequent modification to the extent buffer didn't happen before the
1810 * transaction commit), which makes filemap_fdata[write|wait]_range not
1811 * able to find the pages tagged with SetPageError at transaction
1812 * commit time. So if this happens we must abort the transaction,
1813 * otherwise we commit a super block with btree roots that point to
1814 * btree nodes/leafs whose content on disk is invalid - either garbage
1815 * or the content of some node/leaf from a past generation that got
1816 * cowed or deleted and is no longer valid.
1818 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
1819 * not be enough - we need to distinguish between log tree extents vs
1820 * non-log tree extents, and the next filemap_fdatawait_range() call
1821 * will catch and clear such errors in the mapping - and that call might
1822 * be from a log sync and not from a transaction commit. Also, checking
1823 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
1824 * not done and would not be reliable - the eb might have been released
1825 * from memory and reading it back again means that flag would not be
1826 * set (since it's a runtime flag, not persisted on disk).
1828 * Using the flags below in the btree inode also makes us achieve the
1829 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
1830 * writeback for all dirty pages and before filemap_fdatawait_range()
1831 * is called, the writeback for all dirty pages had already finished
1832 * with errors - because we were not using AS_EIO/AS_ENOSPC,
1833 * filemap_fdatawait_range() would return success, as it could not know
1834 * that writeback errors happened (the pages were no longer tagged for
1837 switch (eb->log_index) {
1839 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
1842 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
1845 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
1848 BUG(); /* unexpected, logic error */
1853 * The endio specific version which won't touch any unsafe spinlock in endio
1856 static struct extent_buffer *find_extent_buffer_nolock(
1857 struct btrfs_fs_info *fs_info, u64 start)
1859 struct extent_buffer *eb;
1862 eb = radix_tree_lookup(&fs_info->buffer_radix,
1863 start >> fs_info->sectorsize_bits);
1864 if (eb && atomic_inc_not_zero(&eb->refs)) {
1873 * The endio function for subpage extent buffer write.
1875 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
1876 * after all extent buffers in the page has finished their writeback.
1878 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
1880 struct bio *bio = &bbio->bio;
1881 struct btrfs_fs_info *fs_info;
1882 struct bio_vec *bvec;
1883 struct bvec_iter_all iter_all;
1885 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
1886 ASSERT(fs_info->nodesize < PAGE_SIZE);
1888 ASSERT(!bio_flagged(bio, BIO_CLONED));
1889 bio_for_each_segment_all(bvec, bio, iter_all) {
1890 struct page *page = bvec->bv_page;
1891 u64 bvec_start = page_offset(page) + bvec->bv_offset;
1892 u64 bvec_end = bvec_start + bvec->bv_len - 1;
1893 u64 cur_bytenr = bvec_start;
1895 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
1897 /* Iterate through all extent buffers in the range */
1898 while (cur_bytenr <= bvec_end) {
1899 struct extent_buffer *eb;
1903 * Here we can't use find_extent_buffer(), as it may
1904 * try to lock eb->refs_lock, which is not safe in endio
1907 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
1910 cur_bytenr = eb->start + eb->len;
1912 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
1913 done = atomic_dec_and_test(&eb->io_pages);
1916 if (bio->bi_status ||
1917 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
1918 ClearPageUptodate(page);
1919 set_btree_ioerr(page, eb);
1922 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
1924 end_extent_buffer_writeback(eb);
1926 * free_extent_buffer() will grab spinlock which is not
1927 * safe in endio context. Thus here we manually dec
1930 atomic_dec(&eb->refs);
1936 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
1938 struct bio *bio = &bbio->bio;
1939 struct bio_vec *bvec;
1940 struct extent_buffer *eb;
1942 struct bvec_iter_all iter_all;
1944 ASSERT(!bio_flagged(bio, BIO_CLONED));
1945 bio_for_each_segment_all(bvec, bio, iter_all) {
1946 struct page *page = bvec->bv_page;
1948 eb = (struct extent_buffer *)page->private;
1950 done = atomic_dec_and_test(&eb->io_pages);
1952 if (bio->bi_status ||
1953 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
1954 ClearPageUptodate(page);
1955 set_btree_ioerr(page, eb);
1958 end_page_writeback(page);
1963 end_extent_buffer_writeback(eb);
1969 static void prepare_eb_write(struct extent_buffer *eb)
1972 unsigned long start;
1975 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1976 atomic_set(&eb->io_pages, num_extent_pages(eb));
1978 /* Set btree blocks beyond nritems with 0 to avoid stale content */
1979 nritems = btrfs_header_nritems(eb);
1980 if (btrfs_header_level(eb) > 0) {
1981 end = btrfs_node_key_ptr_offset(eb, nritems);
1982 memzero_extent_buffer(eb, end, eb->len - end);
1986 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
1988 start = btrfs_item_nr_offset(eb, nritems);
1989 end = btrfs_item_nr_offset(eb, 0);
1991 end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
1993 end += btrfs_item_offset(eb, nritems - 1);
1994 memzero_extent_buffer(eb, start, end - start);
1999 * Unlike the work in write_one_eb(), we rely completely on extent locking.
2000 * Page locking is only utilized at minimum to keep the VMM code happy.
2002 static void write_one_subpage_eb(struct extent_buffer *eb,
2003 struct btrfs_bio_ctrl *bio_ctrl)
2005 struct btrfs_fs_info *fs_info = eb->fs_info;
2006 struct page *page = eb->pages[0];
2007 bool no_dirty_ebs = false;
2009 prepare_eb_write(eb);
2011 /* clear_page_dirty_for_io() in subpage helper needs page locked */
2013 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2015 /* Check if this is the last dirty bit to update nr_written */
2016 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2017 eb->start, eb->len);
2019 clear_page_dirty_for_io(page);
2021 bio_ctrl->end_io_func = end_bio_subpage_eb_writepage;
2023 submit_extent_page(bio_ctrl, eb->start, page, eb->len,
2024 eb->start - page_offset(page));
2027 * Submission finished without problem, if no range of the page is
2028 * dirty anymore, we have submitted a page. Update nr_written in wbc.
2031 bio_ctrl->wbc->nr_to_write--;
2034 static noinline_for_stack void write_one_eb(struct extent_buffer *eb,
2035 struct btrfs_bio_ctrl *bio_ctrl)
2037 u64 disk_bytenr = eb->start;
2040 prepare_eb_write(eb);
2042 bio_ctrl->end_io_func = end_bio_extent_buffer_writepage;
2044 num_pages = num_extent_pages(eb);
2045 for (i = 0; i < num_pages; i++) {
2046 struct page *p = eb->pages[i];
2048 clear_page_dirty_for_io(p);
2049 set_page_writeback(p);
2050 submit_extent_page(bio_ctrl, disk_bytenr, p, PAGE_SIZE, 0);
2051 disk_bytenr += PAGE_SIZE;
2052 bio_ctrl->wbc->nr_to_write--;
2058 * Submit one subpage btree page.
2060 * The main difference to submit_eb_page() is:
2062 * For subpage, we don't rely on page locking at all.
2065 * We only flush bio if we may be unable to fit current extent buffers into
2068 * Return >=0 for the number of submitted extent buffers.
2069 * Return <0 for fatal error.
2071 static int submit_eb_subpage(struct page *page, struct btrfs_bio_ctrl *bio_ctrl)
2073 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2075 u64 page_start = page_offset(page);
2077 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
2080 /* Lock and write each dirty extent buffers in the range */
2081 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
2082 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2083 struct extent_buffer *eb;
2084 unsigned long flags;
2088 * Take private lock to ensure the subpage won't be detached
2091 spin_lock(&page->mapping->private_lock);
2092 if (!PagePrivate(page)) {
2093 spin_unlock(&page->mapping->private_lock);
2096 spin_lock_irqsave(&subpage->lock, flags);
2097 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
2098 subpage->bitmaps)) {
2099 spin_unlock_irqrestore(&subpage->lock, flags);
2100 spin_unlock(&page->mapping->private_lock);
2105 start = page_start + bit_start * fs_info->sectorsize;
2106 bit_start += sectors_per_node;
2109 * Here we just want to grab the eb without touching extra
2110 * spin locks, so call find_extent_buffer_nolock().
2112 eb = find_extent_buffer_nolock(fs_info, start);
2113 spin_unlock_irqrestore(&subpage->lock, flags);
2114 spin_unlock(&page->mapping->private_lock);
2117 * The eb has already reached 0 refs thus find_extent_buffer()
2118 * doesn't return it. We don't need to write back such eb
2124 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2126 free_extent_buffer(eb);
2130 free_extent_buffer(eb);
2133 write_one_subpage_eb(eb, bio_ctrl);
2134 free_extent_buffer(eb);
2140 /* We hit error, end bio for the submitted extent buffers */
2141 submit_write_bio(bio_ctrl, ret);
2146 * Submit all page(s) of one extent buffer.
2148 * @page: the page of one extent buffer
2149 * @eb_context: to determine if we need to submit this page, if current page
2150 * belongs to this eb, we don't need to submit
2152 * The caller should pass each page in their bytenr order, and here we use
2153 * @eb_context to determine if we have submitted pages of one extent buffer.
2155 * If we have, we just skip until we hit a new page that doesn't belong to
2156 * current @eb_context.
2158 * If not, we submit all the page(s) of the extent buffer.
2160 * Return >0 if we have submitted the extent buffer successfully.
2161 * Return 0 if we don't need to submit the page, as it's already submitted by
2163 * Return <0 for fatal error.
2165 static int submit_eb_page(struct page *page, struct btrfs_bio_ctrl *bio_ctrl,
2166 struct extent_buffer **eb_context)
2168 struct address_space *mapping = page->mapping;
2169 struct btrfs_block_group *cache = NULL;
2170 struct extent_buffer *eb;
2173 if (!PagePrivate(page))
2176 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
2177 return submit_eb_subpage(page, bio_ctrl);
2179 spin_lock(&mapping->private_lock);
2180 if (!PagePrivate(page)) {
2181 spin_unlock(&mapping->private_lock);
2185 eb = (struct extent_buffer *)page->private;
2188 * Shouldn't happen and normally this would be a BUG_ON but no point
2189 * crashing the machine for something we can survive anyway.
2192 spin_unlock(&mapping->private_lock);
2196 if (eb == *eb_context) {
2197 spin_unlock(&mapping->private_lock);
2200 ret = atomic_inc_not_zero(&eb->refs);
2201 spin_unlock(&mapping->private_lock);
2205 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
2207 * If for_sync, this hole will be filled with
2208 * trasnsaction commit.
2210 if (bio_ctrl->wbc->sync_mode == WB_SYNC_ALL &&
2211 !bio_ctrl->wbc->for_sync)
2215 free_extent_buffer(eb);
2221 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2223 btrfs_revert_meta_write_pointer(cache, eb);
2225 btrfs_put_block_group(cache);
2226 free_extent_buffer(eb);
2231 * Implies write in zoned mode. Mark the last eb in a block group.
2233 btrfs_schedule_zone_finish_bg(cache, eb);
2234 btrfs_put_block_group(cache);
2236 write_one_eb(eb, bio_ctrl);
2237 free_extent_buffer(eb);
2241 int btree_write_cache_pages(struct address_space *mapping,
2242 struct writeback_control *wbc)
2244 struct extent_buffer *eb_context = NULL;
2245 struct btrfs_bio_ctrl bio_ctrl = {
2247 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2250 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
2253 int nr_to_write_done = 0;
2254 struct folio_batch fbatch;
2255 unsigned int nr_folios;
2257 pgoff_t end; /* Inclusive */
2261 folio_batch_init(&fbatch);
2262 if (wbc->range_cyclic) {
2263 index = mapping->writeback_index; /* Start from prev offset */
2266 * Start from the beginning does not need to cycle over the
2267 * range, mark it as scanned.
2269 scanned = (index == 0);
2271 index = wbc->range_start >> PAGE_SHIFT;
2272 end = wbc->range_end >> PAGE_SHIFT;
2275 if (wbc->sync_mode == WB_SYNC_ALL)
2276 tag = PAGECACHE_TAG_TOWRITE;
2278 tag = PAGECACHE_TAG_DIRTY;
2279 btrfs_zoned_meta_io_lock(fs_info);
2281 if (wbc->sync_mode == WB_SYNC_ALL)
2282 tag_pages_for_writeback(mapping, index, end);
2283 while (!done && !nr_to_write_done && (index <= end) &&
2284 (nr_folios = filemap_get_folios_tag(mapping, &index, end,
2288 for (i = 0; i < nr_folios; i++) {
2289 struct folio *folio = fbatch.folios[i];
2291 ret = submit_eb_page(&folio->page, &bio_ctrl, &eb_context);
2300 * the filesystem may choose to bump up nr_to_write.
2301 * We have to make sure to honor the new nr_to_write
2304 nr_to_write_done = wbc->nr_to_write <= 0;
2306 folio_batch_release(&fbatch);
2309 if (!scanned && !done) {
2311 * We hit the last page and there is more work to be done: wrap
2312 * back to the start of the file
2319 * If something went wrong, don't allow any metadata write bio to be
2322 * This would prevent use-after-free if we had dirty pages not
2323 * cleaned up, which can still happen by fuzzed images.
2326 * Allowing existing tree block to be allocated for other trees.
2328 * - Log tree operations
2329 * Exiting tree blocks get allocated to log tree, bumps its
2330 * generation, then get cleaned in tree re-balance.
2331 * Such tree block will not be written back, since it's clean,
2332 * thus no WRITTEN flag set.
2333 * And after log writes back, this tree block is not traced by
2334 * any dirty extent_io_tree.
2336 * - Offending tree block gets re-dirtied from its original owner
2337 * Since it has bumped generation, no WRITTEN flag, it can be
2338 * reused without COWing. This tree block will not be traced
2339 * by btrfs_transaction::dirty_pages.
2341 * Now such dirty tree block will not be cleaned by any dirty
2342 * extent io tree. Thus we don't want to submit such wild eb
2343 * if the fs already has error.
2345 * We can get ret > 0 from submit_extent_page() indicating how many ebs
2346 * were submitted. Reset it to 0 to avoid false alerts for the caller.
2350 if (!ret && BTRFS_FS_ERROR(fs_info))
2352 submit_write_bio(&bio_ctrl, ret);
2354 btrfs_zoned_meta_io_unlock(fs_info);
2359 * Walk the list of dirty pages of the given address space and write all of them.
2361 * @mapping: address space structure to write
2362 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2363 * @bio_ctrl: holds context for the write, namely the bio
2365 * If a page is already under I/O, write_cache_pages() skips it, even
2366 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
2367 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
2368 * and msync() need to guarantee that all the data which was dirty at the time
2369 * the call was made get new I/O started against them. If wbc->sync_mode is
2370 * WB_SYNC_ALL then we were called for data integrity and we must wait for
2371 * existing IO to complete.
2373 static int extent_write_cache_pages(struct address_space *mapping,
2374 struct btrfs_bio_ctrl *bio_ctrl)
2376 struct writeback_control *wbc = bio_ctrl->wbc;
2377 struct inode *inode = mapping->host;
2380 int nr_to_write_done = 0;
2381 struct folio_batch fbatch;
2382 unsigned int nr_folios;
2384 pgoff_t end; /* Inclusive */
2386 int range_whole = 0;
2391 * We have to hold onto the inode so that ordered extents can do their
2392 * work when the IO finishes. The alternative to this is failing to add
2393 * an ordered extent if the igrab() fails there and that is a huge pain
2394 * to deal with, so instead just hold onto the inode throughout the
2395 * writepages operation. If it fails here we are freeing up the inode
2396 * anyway and we'd rather not waste our time writing out stuff that is
2397 * going to be truncated anyway.
2402 folio_batch_init(&fbatch);
2403 if (wbc->range_cyclic) {
2404 index = mapping->writeback_index; /* Start from prev offset */
2407 * Start from the beginning does not need to cycle over the
2408 * range, mark it as scanned.
2410 scanned = (index == 0);
2412 index = wbc->range_start >> PAGE_SHIFT;
2413 end = wbc->range_end >> PAGE_SHIFT;
2414 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2420 * We do the tagged writepage as long as the snapshot flush bit is set
2421 * and we are the first one who do the filemap_flush() on this inode.
2423 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
2424 * not race in and drop the bit.
2426 if (range_whole && wbc->nr_to_write == LONG_MAX &&
2427 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
2428 &BTRFS_I(inode)->runtime_flags))
2429 wbc->tagged_writepages = 1;
2431 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2432 tag = PAGECACHE_TAG_TOWRITE;
2434 tag = PAGECACHE_TAG_DIRTY;
2436 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2437 tag_pages_for_writeback(mapping, index, end);
2439 while (!done && !nr_to_write_done && (index <= end) &&
2440 (nr_folios = filemap_get_folios_tag(mapping, &index,
2441 end, tag, &fbatch))) {
2444 for (i = 0; i < nr_folios; i++) {
2445 struct folio *folio = fbatch.folios[i];
2447 done_index = folio->index + folio_nr_pages(folio);
2449 * At this point we hold neither the i_pages lock nor
2450 * the page lock: the page may be truncated or
2451 * invalidated (changing page->mapping to NULL),
2452 * or even swizzled back from swapper_space to
2453 * tmpfs file mapping
2455 if (!folio_trylock(folio)) {
2456 submit_write_bio(bio_ctrl, 0);
2460 if (unlikely(folio->mapping != mapping)) {
2461 folio_unlock(folio);
2465 if (wbc->sync_mode != WB_SYNC_NONE) {
2466 if (folio_test_writeback(folio))
2467 submit_write_bio(bio_ctrl, 0);
2468 folio_wait_writeback(folio);
2471 if (folio_test_writeback(folio) ||
2472 !folio_clear_dirty_for_io(folio)) {
2473 folio_unlock(folio);
2477 ret = __extent_writepage(&folio->page, bio_ctrl);
2484 * the filesystem may choose to bump up nr_to_write.
2485 * We have to make sure to honor the new nr_to_write
2488 nr_to_write_done = wbc->nr_to_write <= 0;
2490 folio_batch_release(&fbatch);
2493 if (!scanned && !done) {
2495 * We hit the last page and there is more work to be done: wrap
2496 * back to the start of the file
2502 * If we're looping we could run into a page that is locked by a
2503 * writer and that writer could be waiting on writeback for a
2504 * page in our current bio, and thus deadlock, so flush the
2507 submit_write_bio(bio_ctrl, 0);
2511 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
2512 mapping->writeback_index = done_index;
2514 btrfs_add_delayed_iput(BTRFS_I(inode));
2519 * Submit the pages in the range to bio for call sites which delalloc range has
2520 * already been ran (aka, ordered extent inserted) and all pages are still
2523 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
2525 bool found_error = false;
2526 int first_error = 0;
2528 struct address_space *mapping = inode->i_mapping;
2531 unsigned long nr_pages;
2532 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
2533 struct writeback_control wbc_writepages = {
2534 .sync_mode = WB_SYNC_ALL,
2535 .range_start = start,
2536 .range_end = end + 1,
2537 .no_cgroup_owner = 1,
2539 struct btrfs_bio_ctrl bio_ctrl = {
2540 .wbc = &wbc_writepages,
2541 /* We're called from an async helper function */
2542 .opf = REQ_OP_WRITE | REQ_BTRFS_CGROUP_PUNT |
2543 wbc_to_write_flags(&wbc_writepages),
2547 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
2548 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
2550 wbc_writepages.nr_to_write = nr_pages * 2;
2552 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
2553 while (cur <= end) {
2554 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
2556 page = find_get_page(mapping, cur >> PAGE_SHIFT);
2558 * All pages in the range are locked since
2559 * btrfs_run_delalloc_range(), thus there is no way to clear
2560 * the page dirty flag.
2562 ASSERT(PageLocked(page));
2563 ASSERT(PageDirty(page));
2564 clear_page_dirty_for_io(page);
2565 ret = __extent_writepage(page, &bio_ctrl);
2575 submit_write_bio(&bio_ctrl, found_error ? ret : 0);
2577 wbc_detach_inode(&wbc_writepages);
2583 int extent_writepages(struct address_space *mapping,
2584 struct writeback_control *wbc)
2586 struct inode *inode = mapping->host;
2588 struct btrfs_bio_ctrl bio_ctrl = {
2590 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2595 * Allow only a single thread to do the reloc work in zoned mode to
2596 * protect the write pointer updates.
2598 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
2599 ret = extent_write_cache_pages(mapping, &bio_ctrl);
2600 submit_write_bio(&bio_ctrl, ret);
2601 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
2605 void extent_readahead(struct readahead_control *rac)
2607 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ | REQ_RAHEAD };
2608 struct page *pagepool[16];
2609 struct extent_map *em_cached = NULL;
2610 u64 prev_em_start = (u64)-1;
2613 while ((nr = readahead_page_batch(rac, pagepool))) {
2614 u64 contig_start = readahead_pos(rac);
2615 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
2617 contiguous_readpages(pagepool, nr, contig_start, contig_end,
2618 &em_cached, &bio_ctrl, &prev_em_start);
2622 free_extent_map(em_cached);
2623 submit_one_bio(&bio_ctrl);
2627 * basic invalidate_folio code, this waits on any locked or writeback
2628 * ranges corresponding to the folio, and then deletes any extent state
2629 * records from the tree
2631 int extent_invalidate_folio(struct extent_io_tree *tree,
2632 struct folio *folio, size_t offset)
2634 struct extent_state *cached_state = NULL;
2635 u64 start = folio_pos(folio);
2636 u64 end = start + folio_size(folio) - 1;
2637 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
2639 /* This function is only called for the btree inode */
2640 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
2642 start += ALIGN(offset, blocksize);
2646 lock_extent(tree, start, end, &cached_state);
2647 folio_wait_writeback(folio);
2650 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
2651 * so here we only need to unlock the extent range to free any
2652 * existing extent state.
2654 unlock_extent(tree, start, end, &cached_state);
2659 * a helper for release_folio, this tests for areas of the page that
2660 * are locked or under IO and drops the related state bits if it is safe
2663 static int try_release_extent_state(struct extent_io_tree *tree,
2664 struct page *page, gfp_t mask)
2666 u64 start = page_offset(page);
2667 u64 end = start + PAGE_SIZE - 1;
2670 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
2673 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
2674 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS);
2677 * At this point we can safely clear everything except the
2678 * locked bit, the nodatasum bit and the delalloc new bit.
2679 * The delalloc new bit will be cleared by ordered extent
2682 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL,
2685 /* if clear_extent_bit failed for enomem reasons,
2686 * we can't allow the release to continue.
2697 * a helper for release_folio. As long as there are no locked extents
2698 * in the range corresponding to the page, both state records and extent
2699 * map records are removed
2701 int try_release_extent_mapping(struct page *page, gfp_t mask)
2703 struct extent_map *em;
2704 u64 start = page_offset(page);
2705 u64 end = start + PAGE_SIZE - 1;
2706 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
2707 struct extent_io_tree *tree = &btrfs_inode->io_tree;
2708 struct extent_map_tree *map = &btrfs_inode->extent_tree;
2710 if (gfpflags_allow_blocking(mask) &&
2711 page->mapping->host->i_size > SZ_16M) {
2713 while (start <= end) {
2714 struct btrfs_fs_info *fs_info;
2717 len = end - start + 1;
2718 write_lock(&map->lock);
2719 em = lookup_extent_mapping(map, start, len);
2721 write_unlock(&map->lock);
2724 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
2725 em->start != start) {
2726 write_unlock(&map->lock);
2727 free_extent_map(em);
2730 if (test_range_bit(tree, em->start,
2731 extent_map_end(em) - 1,
2732 EXTENT_LOCKED, 0, NULL))
2735 * If it's not in the list of modified extents, used
2736 * by a fast fsync, we can remove it. If it's being
2737 * logged we can safely remove it since fsync took an
2738 * extra reference on the em.
2740 if (list_empty(&em->list) ||
2741 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
2744 * If it's in the list of modified extents, remove it
2745 * only if its generation is older then the current one,
2746 * in which case we don't need it for a fast fsync.
2747 * Otherwise don't remove it, we could be racing with an
2748 * ongoing fast fsync that could miss the new extent.
2750 fs_info = btrfs_inode->root->fs_info;
2751 spin_lock(&fs_info->trans_lock);
2752 cur_gen = fs_info->generation;
2753 spin_unlock(&fs_info->trans_lock);
2754 if (em->generation >= cur_gen)
2758 * We only remove extent maps that are not in the list of
2759 * modified extents or that are in the list but with a
2760 * generation lower then the current generation, so there
2761 * is no need to set the full fsync flag on the inode (it
2762 * hurts the fsync performance for workloads with a data
2763 * size that exceeds or is close to the system's memory).
2765 remove_extent_mapping(map, em);
2766 /* once for the rb tree */
2767 free_extent_map(em);
2769 start = extent_map_end(em);
2770 write_unlock(&map->lock);
2773 free_extent_map(em);
2775 cond_resched(); /* Allow large-extent preemption. */
2778 return try_release_extent_state(tree, page, mask);
2782 * To cache previous fiemap extent
2784 * Will be used for merging fiemap extent
2786 struct fiemap_cache {
2795 * Helper to submit fiemap extent.
2797 * Will try to merge current fiemap extent specified by @offset, @phys,
2798 * @len and @flags with cached one.
2799 * And only when we fails to merge, cached one will be submitted as
2802 * Return value is the same as fiemap_fill_next_extent().
2804 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
2805 struct fiemap_cache *cache,
2806 u64 offset, u64 phys, u64 len, u32 flags)
2810 /* Set at the end of extent_fiemap(). */
2811 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
2817 * Sanity check, extent_fiemap() should have ensured that new
2818 * fiemap extent won't overlap with cached one.
2821 * NOTE: Physical address can overlap, due to compression
2823 if (cache->offset + cache->len > offset) {
2829 * Only merges fiemap extents if
2830 * 1) Their logical addresses are continuous
2832 * 2) Their physical addresses are continuous
2833 * So truly compressed (physical size smaller than logical size)
2834 * extents won't get merged with each other
2836 * 3) Share same flags
2838 if (cache->offset + cache->len == offset &&
2839 cache->phys + cache->len == phys &&
2840 cache->flags == flags) {
2845 /* Not mergeable, need to submit cached one */
2846 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
2847 cache->len, cache->flags);
2848 cache->cached = false;
2852 cache->cached = true;
2853 cache->offset = offset;
2856 cache->flags = flags;
2862 * Emit last fiemap cache
2864 * The last fiemap cache may still be cached in the following case:
2866 * |<- Fiemap range ->|
2867 * |<------------ First extent ----------->|
2869 * In this case, the first extent range will be cached but not emitted.
2870 * So we must emit it before ending extent_fiemap().
2872 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
2873 struct fiemap_cache *cache)
2880 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
2881 cache->len, cache->flags);
2882 cache->cached = false;
2888 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
2890 struct extent_buffer *clone;
2891 struct btrfs_key key;
2896 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
2899 ret = btrfs_next_leaf(inode->root, path);
2904 * Don't bother with cloning if there are no more file extent items for
2907 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2908 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
2911 /* See the comment at fiemap_search_slot() about why we clone. */
2912 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2916 slot = path->slots[0];
2917 btrfs_release_path(path);
2918 path->nodes[0] = clone;
2919 path->slots[0] = slot;
2925 * Search for the first file extent item that starts at a given file offset or
2926 * the one that starts immediately before that offset.
2927 * Returns: 0 on success, < 0 on error, 1 if not found.
2929 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
2932 const u64 ino = btrfs_ino(inode);
2933 struct btrfs_root *root = inode->root;
2934 struct extent_buffer *clone;
2935 struct btrfs_key key;
2940 key.type = BTRFS_EXTENT_DATA_KEY;
2941 key.offset = file_offset;
2943 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2947 if (ret > 0 && path->slots[0] > 0) {
2948 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
2949 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
2953 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2954 ret = btrfs_next_leaf(root, path);
2958 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2959 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
2964 * We clone the leaf and use it during fiemap. This is because while
2965 * using the leaf we do expensive things like checking if an extent is
2966 * shared, which can take a long time. In order to prevent blocking
2967 * other tasks for too long, we use a clone of the leaf. We have locked
2968 * the file range in the inode's io tree, so we know none of our file
2969 * extent items can change. This way we avoid blocking other tasks that
2970 * want to insert items for other inodes in the same leaf or b+tree
2971 * rebalance operations (triggered for example when someone is trying
2972 * to push items into this leaf when trying to insert an item in a
2974 * We also need the private clone because holding a read lock on an
2975 * extent buffer of the subvolume's b+tree will make lockdep unhappy
2976 * when we call fiemap_fill_next_extent(), because that may cause a page
2977 * fault when filling the user space buffer with fiemap data.
2979 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2983 slot = path->slots[0];
2984 btrfs_release_path(path);
2985 path->nodes[0] = clone;
2986 path->slots[0] = slot;
2992 * Process a range which is a hole or a prealloc extent in the inode's subvolume
2993 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
2994 * extent. The end offset (@end) is inclusive.
2996 static int fiemap_process_hole(struct btrfs_inode *inode,
2997 struct fiemap_extent_info *fieinfo,
2998 struct fiemap_cache *cache,
2999 struct extent_state **delalloc_cached_state,
3000 struct btrfs_backref_share_check_ctx *backref_ctx,
3001 u64 disk_bytenr, u64 extent_offset,
3005 const u64 i_size = i_size_read(&inode->vfs_inode);
3006 u64 cur_offset = start;
3007 u64 last_delalloc_end = 0;
3008 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3009 bool checked_extent_shared = false;
3013 * There can be no delalloc past i_size, so don't waste time looking for
3016 while (cur_offset < end && cur_offset < i_size) {
3020 u64 prealloc_len = 0;
3023 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3024 delalloc_cached_state,
3031 * If this is a prealloc extent we have to report every section
3032 * of it that has no delalloc.
3034 if (disk_bytenr != 0) {
3035 if (last_delalloc_end == 0) {
3036 prealloc_start = start;
3037 prealloc_len = delalloc_start - start;
3039 prealloc_start = last_delalloc_end + 1;
3040 prealloc_len = delalloc_start - prealloc_start;
3044 if (prealloc_len > 0) {
3045 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3046 ret = btrfs_is_data_extent_shared(inode,
3053 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3055 checked_extent_shared = true;
3057 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3058 disk_bytenr + extent_offset,
3059 prealloc_len, prealloc_flags);
3062 extent_offset += prealloc_len;
3065 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3066 delalloc_end + 1 - delalloc_start,
3067 FIEMAP_EXTENT_DELALLOC |
3068 FIEMAP_EXTENT_UNKNOWN);
3072 last_delalloc_end = delalloc_end;
3073 cur_offset = delalloc_end + 1;
3074 extent_offset += cur_offset - delalloc_start;
3079 * Either we found no delalloc for the whole prealloc extent or we have
3080 * a prealloc extent that spans i_size or starts at or after i_size.
3082 if (disk_bytenr != 0 && last_delalloc_end < end) {
3086 if (last_delalloc_end == 0) {
3087 prealloc_start = start;
3088 prealloc_len = end + 1 - start;
3090 prealloc_start = last_delalloc_end + 1;
3091 prealloc_len = end + 1 - prealloc_start;
3094 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3095 ret = btrfs_is_data_extent_shared(inode,
3102 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3104 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3105 disk_bytenr + extent_offset,
3106 prealloc_len, prealloc_flags);
3114 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3115 struct btrfs_path *path,
3116 u64 *last_extent_end_ret)
3118 const u64 ino = btrfs_ino(inode);
3119 struct btrfs_root *root = inode->root;
3120 struct extent_buffer *leaf;
3121 struct btrfs_file_extent_item *ei;
3122 struct btrfs_key key;
3127 * Lookup the last file extent. We're not using i_size here because
3128 * there might be preallocation past i_size.
3130 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3131 /* There can't be a file extent item at offset (u64)-1 */
3137 * For a non-existing key, btrfs_search_slot() always leaves us at a
3138 * slot > 0, except if the btree is empty, which is impossible because
3139 * at least it has the inode item for this inode and all the items for
3140 * the root inode 256.
3142 ASSERT(path->slots[0] > 0);
3144 leaf = path->nodes[0];
3145 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3146 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3147 /* No file extent items in the subvolume tree. */
3148 *last_extent_end_ret = 0;
3153 * For an inline extent, the disk_bytenr is where inline data starts at,
3154 * so first check if we have an inline extent item before checking if we
3155 * have an implicit hole (disk_bytenr == 0).
3157 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3158 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3159 *last_extent_end_ret = btrfs_file_extent_end(path);
3164 * Find the last file extent item that is not a hole (when NO_HOLES is
3165 * not enabled). This should take at most 2 iterations in the worst
3166 * case: we have one hole file extent item at slot 0 of a leaf and
3167 * another hole file extent item as the last item in the previous leaf.
3168 * This is because we merge file extent items that represent holes.
3170 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3171 while (disk_bytenr == 0) {
3172 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3175 } else if (ret > 0) {
3176 /* No file extent items that are not holes. */
3177 *last_extent_end_ret = 0;
3180 leaf = path->nodes[0];
3181 ei = btrfs_item_ptr(leaf, path->slots[0],
3182 struct btrfs_file_extent_item);
3183 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3186 *last_extent_end_ret = btrfs_file_extent_end(path);
3190 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3193 const u64 ino = btrfs_ino(inode);
3194 struct extent_state *cached_state = NULL;
3195 struct extent_state *delalloc_cached_state = NULL;
3196 struct btrfs_path *path;
3197 struct fiemap_cache cache = { 0 };
3198 struct btrfs_backref_share_check_ctx *backref_ctx;
3199 u64 last_extent_end;
3200 u64 prev_extent_end;
3203 bool stopped = false;
3206 backref_ctx = btrfs_alloc_backref_share_check_ctx();
3207 path = btrfs_alloc_path();
3208 if (!backref_ctx || !path) {
3213 lockstart = round_down(start, inode->root->fs_info->sectorsize);
3214 lockend = round_up(start + len, inode->root->fs_info->sectorsize);
3215 prev_extent_end = lockstart;
3217 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
3218 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3220 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3223 btrfs_release_path(path);
3225 path->reada = READA_FORWARD;
3226 ret = fiemap_search_slot(inode, path, lockstart);
3229 } else if (ret > 0) {
3231 * No file extent item found, but we may have delalloc between
3232 * the current offset and i_size. So check for that.
3235 goto check_eof_delalloc;
3238 while (prev_extent_end < lockend) {
3239 struct extent_buffer *leaf = path->nodes[0];
3240 struct btrfs_file_extent_item *ei;
3241 struct btrfs_key key;
3244 u64 extent_offset = 0;
3246 u64 disk_bytenr = 0;
3251 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3252 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3255 extent_end = btrfs_file_extent_end(path);
3258 * The first iteration can leave us at an extent item that ends
3259 * before our range's start. Move to the next item.
3261 if (extent_end <= lockstart)
3264 backref_ctx->curr_leaf_bytenr = leaf->start;
3266 /* We have in implicit hole (NO_HOLES feature enabled). */
3267 if (prev_extent_end < key.offset) {
3268 const u64 range_end = min(key.offset, lockend) - 1;
3270 ret = fiemap_process_hole(inode, fieinfo, &cache,
3271 &delalloc_cached_state,
3272 backref_ctx, 0, 0, 0,
3273 prev_extent_end, range_end);
3276 } else if (ret > 0) {
3277 /* fiemap_fill_next_extent() told us to stop. */
3282 /* We've reached the end of the fiemap range, stop. */
3283 if (key.offset >= lockend) {
3289 extent_len = extent_end - key.offset;
3290 ei = btrfs_item_ptr(leaf, path->slots[0],
3291 struct btrfs_file_extent_item);
3292 compression = btrfs_file_extent_compression(leaf, ei);
3293 extent_type = btrfs_file_extent_type(leaf, ei);
3294 extent_gen = btrfs_file_extent_generation(leaf, ei);
3296 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3297 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3298 if (compression == BTRFS_COMPRESS_NONE)
3299 extent_offset = btrfs_file_extent_offset(leaf, ei);
3302 if (compression != BTRFS_COMPRESS_NONE)
3303 flags |= FIEMAP_EXTENT_ENCODED;
3305 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3306 flags |= FIEMAP_EXTENT_DATA_INLINE;
3307 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
3308 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
3310 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
3311 ret = fiemap_process_hole(inode, fieinfo, &cache,
3312 &delalloc_cached_state,
3314 disk_bytenr, extent_offset,
3315 extent_gen, key.offset,
3317 } else if (disk_bytenr == 0) {
3318 /* We have an explicit hole. */
3319 ret = fiemap_process_hole(inode, fieinfo, &cache,
3320 &delalloc_cached_state,
3321 backref_ctx, 0, 0, 0,
3322 key.offset, extent_end - 1);
3324 /* We have a regular extent. */
3325 if (fieinfo->fi_extents_max) {
3326 ret = btrfs_is_data_extent_shared(inode,
3333 flags |= FIEMAP_EXTENT_SHARED;
3336 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
3337 disk_bytenr + extent_offset,
3343 } else if (ret > 0) {
3344 /* fiemap_fill_next_extent() told us to stop. */
3349 prev_extent_end = extent_end;
3351 if (fatal_signal_pending(current)) {
3356 ret = fiemap_next_leaf_item(inode, path);
3359 } else if (ret > 0) {
3360 /* No more file extent items for this inode. */
3368 * Release (and free) the path before emitting any final entries to
3369 * fiemap_fill_next_extent() to keep lockdep happy. This is because
3370 * once we find no more file extent items exist, we may have a
3371 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
3372 * faults when copying data to the user space buffer.
3374 btrfs_free_path(path);
3377 if (!stopped && prev_extent_end < lockend) {
3378 ret = fiemap_process_hole(inode, fieinfo, &cache,
3379 &delalloc_cached_state, backref_ctx,
3380 0, 0, 0, prev_extent_end, lockend - 1);
3383 prev_extent_end = lockend;
3386 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
3387 const u64 i_size = i_size_read(&inode->vfs_inode);
3389 if (prev_extent_end < i_size) {
3394 delalloc = btrfs_find_delalloc_in_range(inode,
3397 &delalloc_cached_state,
3401 cache.flags |= FIEMAP_EXTENT_LAST;
3403 cache.flags |= FIEMAP_EXTENT_LAST;
3407 ret = emit_last_fiemap_cache(fieinfo, &cache);
3410 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3411 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3413 free_extent_state(delalloc_cached_state);
3414 btrfs_free_backref_share_ctx(backref_ctx);
3415 btrfs_free_path(path);
3419 static void __free_extent_buffer(struct extent_buffer *eb)
3421 kmem_cache_free(extent_buffer_cache, eb);
3424 int extent_buffer_under_io(const struct extent_buffer *eb)
3426 return (atomic_read(&eb->io_pages) ||
3427 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
3428 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3431 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
3433 struct btrfs_subpage *subpage;
3435 lockdep_assert_held(&page->mapping->private_lock);
3437 if (PagePrivate(page)) {
3438 subpage = (struct btrfs_subpage *)page->private;
3439 if (atomic_read(&subpage->eb_refs))
3442 * Even there is no eb refs here, we may still have
3443 * end_page_read() call relying on page::private.
3445 if (atomic_read(&subpage->readers))
3451 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
3453 struct btrfs_fs_info *fs_info = eb->fs_info;
3454 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3457 * For mapped eb, we're going to change the page private, which should
3458 * be done under the private_lock.
3461 spin_lock(&page->mapping->private_lock);
3463 if (!PagePrivate(page)) {
3465 spin_unlock(&page->mapping->private_lock);
3469 if (fs_info->nodesize >= PAGE_SIZE) {
3471 * We do this since we'll remove the pages after we've
3472 * removed the eb from the radix tree, so we could race
3473 * and have this page now attached to the new eb. So
3474 * only clear page_private if it's still connected to
3477 if (PagePrivate(page) &&
3478 page->private == (unsigned long)eb) {
3479 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3480 BUG_ON(PageDirty(page));
3481 BUG_ON(PageWriteback(page));
3483 * We need to make sure we haven't be attached
3486 detach_page_private(page);
3489 spin_unlock(&page->mapping->private_lock);
3494 * For subpage, we can have dummy eb with page private. In this case,
3495 * we can directly detach the private as such page is only attached to
3496 * one dummy eb, no sharing.
3499 btrfs_detach_subpage(fs_info, page);
3503 btrfs_page_dec_eb_refs(fs_info, page);
3506 * We can only detach the page private if there are no other ebs in the
3507 * page range and no unfinished IO.
3509 if (!page_range_has_eb(fs_info, page))
3510 btrfs_detach_subpage(fs_info, page);
3512 spin_unlock(&page->mapping->private_lock);
3515 /* Release all pages attached to the extent buffer */
3516 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
3521 ASSERT(!extent_buffer_under_io(eb));
3523 num_pages = num_extent_pages(eb);
3524 for (i = 0; i < num_pages; i++) {
3525 struct page *page = eb->pages[i];
3530 detach_extent_buffer_page(eb, page);
3532 /* One for when we allocated the page */
3538 * Helper for releasing the extent buffer.
3540 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
3542 btrfs_release_extent_buffer_pages(eb);
3543 btrfs_leak_debug_del_eb(eb);
3544 __free_extent_buffer(eb);
3547 static struct extent_buffer *
3548 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
3551 struct extent_buffer *eb = NULL;
3553 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
3556 eb->fs_info = fs_info;
3557 init_rwsem(&eb->lock);
3559 btrfs_leak_debug_add_eb(eb);
3560 INIT_LIST_HEAD(&eb->release_list);
3562 spin_lock_init(&eb->refs_lock);
3563 atomic_set(&eb->refs, 1);
3564 atomic_set(&eb->io_pages, 0);
3566 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
3571 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
3574 struct extent_buffer *new;
3575 int num_pages = num_extent_pages(src);
3578 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
3583 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
3584 * btrfs_release_extent_buffer() have different behavior for
3585 * UNMAPPED subpage extent buffer.
3587 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
3589 ret = btrfs_alloc_page_array(num_pages, new->pages);
3591 btrfs_release_extent_buffer(new);
3595 for (i = 0; i < num_pages; i++) {
3597 struct page *p = new->pages[i];
3599 ret = attach_extent_buffer_page(new, p, NULL);
3601 btrfs_release_extent_buffer(new);
3604 WARN_ON(PageDirty(p));
3605 copy_page(page_address(p), page_address(src->pages[i]));
3607 set_extent_buffer_uptodate(new);
3612 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3613 u64 start, unsigned long len)
3615 struct extent_buffer *eb;
3620 eb = __alloc_extent_buffer(fs_info, start, len);
3624 num_pages = num_extent_pages(eb);
3625 ret = btrfs_alloc_page_array(num_pages, eb->pages);
3629 for (i = 0; i < num_pages; i++) {
3630 struct page *p = eb->pages[i];
3632 ret = attach_extent_buffer_page(eb, p, NULL);
3637 set_extent_buffer_uptodate(eb);
3638 btrfs_set_header_nritems(eb, 0);
3639 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3643 for (i = 0; i < num_pages; i++) {
3645 detach_extent_buffer_page(eb, eb->pages[i]);
3646 __free_page(eb->pages[i]);
3649 __free_extent_buffer(eb);
3653 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3656 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
3659 static void check_buffer_tree_ref(struct extent_buffer *eb)
3663 * The TREE_REF bit is first set when the extent_buffer is added
3664 * to the radix tree. It is also reset, if unset, when a new reference
3665 * is created by find_extent_buffer.
3667 * It is only cleared in two cases: freeing the last non-tree
3668 * reference to the extent_buffer when its STALE bit is set or
3669 * calling release_folio when the tree reference is the only reference.
3671 * In both cases, care is taken to ensure that the extent_buffer's
3672 * pages are not under io. However, release_folio can be concurrently
3673 * called with creating new references, which is prone to race
3674 * conditions between the calls to check_buffer_tree_ref in those
3675 * codepaths and clearing TREE_REF in try_release_extent_buffer.
3677 * The actual lifetime of the extent_buffer in the radix tree is
3678 * adequately protected by the refcount, but the TREE_REF bit and
3679 * its corresponding reference are not. To protect against this
3680 * class of races, we call check_buffer_tree_ref from the codepaths
3681 * which trigger io after they set eb->io_pages. Note that once io is
3682 * initiated, TREE_REF can no longer be cleared, so that is the
3683 * moment at which any such race is best fixed.
3685 refs = atomic_read(&eb->refs);
3686 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3689 spin_lock(&eb->refs_lock);
3690 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3691 atomic_inc(&eb->refs);
3692 spin_unlock(&eb->refs_lock);
3695 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
3696 struct page *accessed)
3700 check_buffer_tree_ref(eb);
3702 num_pages = num_extent_pages(eb);
3703 for (i = 0; i < num_pages; i++) {
3704 struct page *p = eb->pages[i];
3707 mark_page_accessed(p);
3711 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
3714 struct extent_buffer *eb;
3716 eb = find_extent_buffer_nolock(fs_info, start);
3720 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
3721 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
3722 * another task running free_extent_buffer() might have seen that flag
3723 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
3724 * writeback flags not set) and it's still in the tree (flag
3725 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
3726 * decrementing the extent buffer's reference count twice. So here we
3727 * could race and increment the eb's reference count, clear its stale
3728 * flag, mark it as dirty and drop our reference before the other task
3729 * finishes executing free_extent_buffer, which would later result in
3730 * an attempt to free an extent buffer that is dirty.
3732 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
3733 spin_lock(&eb->refs_lock);
3734 spin_unlock(&eb->refs_lock);
3736 mark_extent_buffer_accessed(eb, NULL);
3740 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3741 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
3744 struct extent_buffer *eb, *exists = NULL;
3747 eb = find_extent_buffer(fs_info, start);
3750 eb = alloc_dummy_extent_buffer(fs_info, start);
3752 return ERR_PTR(-ENOMEM);
3753 eb->fs_info = fs_info;
3755 ret = radix_tree_preload(GFP_NOFS);
3757 exists = ERR_PTR(ret);
3760 spin_lock(&fs_info->buffer_lock);
3761 ret = radix_tree_insert(&fs_info->buffer_radix,
3762 start >> fs_info->sectorsize_bits, eb);
3763 spin_unlock(&fs_info->buffer_lock);
3764 radix_tree_preload_end();
3765 if (ret == -EEXIST) {
3766 exists = find_extent_buffer(fs_info, start);
3772 check_buffer_tree_ref(eb);
3773 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3777 btrfs_release_extent_buffer(eb);
3782 static struct extent_buffer *grab_extent_buffer(
3783 struct btrfs_fs_info *fs_info, struct page *page)
3785 struct extent_buffer *exists;
3788 * For subpage case, we completely rely on radix tree to ensure we
3789 * don't try to insert two ebs for the same bytenr. So here we always
3790 * return NULL and just continue.
3792 if (fs_info->nodesize < PAGE_SIZE)
3795 /* Page not yet attached to an extent buffer */
3796 if (!PagePrivate(page))
3800 * We could have already allocated an eb for this page and attached one
3801 * so lets see if we can get a ref on the existing eb, and if we can we
3802 * know it's good and we can just return that one, else we know we can
3803 * just overwrite page->private.
3805 exists = (struct extent_buffer *)page->private;
3806 if (atomic_inc_not_zero(&exists->refs))
3809 WARN_ON(PageDirty(page));
3810 detach_page_private(page);
3814 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
3816 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
3817 btrfs_err(fs_info, "bad tree block start %llu", start);
3821 if (fs_info->nodesize < PAGE_SIZE &&
3822 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
3824 "tree block crosses page boundary, start %llu nodesize %u",
3825 start, fs_info->nodesize);
3828 if (fs_info->nodesize >= PAGE_SIZE &&
3829 !PAGE_ALIGNED(start)) {
3831 "tree block is not page aligned, start %llu nodesize %u",
3832 start, fs_info->nodesize);
3838 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3839 u64 start, u64 owner_root, int level)
3841 unsigned long len = fs_info->nodesize;
3844 unsigned long index = start >> PAGE_SHIFT;
3845 struct extent_buffer *eb;
3846 struct extent_buffer *exists = NULL;
3848 struct address_space *mapping = fs_info->btree_inode->i_mapping;
3849 u64 lockdep_owner = owner_root;
3853 if (check_eb_alignment(fs_info, start))
3854 return ERR_PTR(-EINVAL);
3856 #if BITS_PER_LONG == 32
3857 if (start >= MAX_LFS_FILESIZE) {
3858 btrfs_err_rl(fs_info,
3859 "extent buffer %llu is beyond 32bit page cache limit", start);
3860 btrfs_err_32bit_limit(fs_info);
3861 return ERR_PTR(-EOVERFLOW);
3863 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
3864 btrfs_warn_32bit_limit(fs_info);
3867 eb = find_extent_buffer(fs_info, start);
3871 eb = __alloc_extent_buffer(fs_info, start, len);
3873 return ERR_PTR(-ENOMEM);
3876 * The reloc trees are just snapshots, so we need them to appear to be
3877 * just like any other fs tree WRT lockdep.
3879 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
3880 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
3882 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
3884 num_pages = num_extent_pages(eb);
3885 for (i = 0; i < num_pages; i++, index++) {
3886 struct btrfs_subpage *prealloc = NULL;
3888 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
3890 exists = ERR_PTR(-ENOMEM);
3895 * Preallocate page->private for subpage case, so that we won't
3896 * allocate memory with private_lock hold. The memory will be
3897 * freed by attach_extent_buffer_page() or freed manually if
3900 * Although we have ensured one subpage eb can only have one
3901 * page, but it may change in the future for 16K page size
3902 * support, so we still preallocate the memory in the loop.
3904 if (fs_info->nodesize < PAGE_SIZE) {
3905 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
3906 if (IS_ERR(prealloc)) {
3907 ret = PTR_ERR(prealloc);
3910 exists = ERR_PTR(ret);
3915 spin_lock(&mapping->private_lock);
3916 exists = grab_extent_buffer(fs_info, p);
3918 spin_unlock(&mapping->private_lock);
3921 mark_extent_buffer_accessed(exists, p);
3922 btrfs_free_subpage(prealloc);
3925 /* Should not fail, as we have preallocated the memory */
3926 ret = attach_extent_buffer_page(eb, p, prealloc);
3929 * To inform we have extra eb under allocation, so that
3930 * detach_extent_buffer_page() won't release the page private
3931 * when the eb hasn't yet been inserted into radix tree.
3933 * The ref will be decreased when the eb released the page, in
3934 * detach_extent_buffer_page().
3935 * Thus needs no special handling in error path.
3937 btrfs_page_inc_eb_refs(fs_info, p);
3938 spin_unlock(&mapping->private_lock);
3940 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
3942 if (!PageUptodate(p))
3946 * We can't unlock the pages just yet since the extent buffer
3947 * hasn't been properly inserted in the radix tree, this
3948 * opens a race with btree_release_folio which can free a page
3949 * while we are still filling in all pages for the buffer and
3954 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3956 ret = radix_tree_preload(GFP_NOFS);
3958 exists = ERR_PTR(ret);
3962 spin_lock(&fs_info->buffer_lock);
3963 ret = radix_tree_insert(&fs_info->buffer_radix,
3964 start >> fs_info->sectorsize_bits, eb);
3965 spin_unlock(&fs_info->buffer_lock);
3966 radix_tree_preload_end();
3967 if (ret == -EEXIST) {
3968 exists = find_extent_buffer(fs_info, start);
3974 /* add one reference for the tree */
3975 check_buffer_tree_ref(eb);
3976 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3979 * Now it's safe to unlock the pages because any calls to
3980 * btree_release_folio will correctly detect that a page belongs to a
3981 * live buffer and won't free them prematurely.
3983 for (i = 0; i < num_pages; i++)
3984 unlock_page(eb->pages[i]);
3988 WARN_ON(!atomic_dec_and_test(&eb->refs));
3989 for (i = 0; i < num_pages; i++) {
3991 unlock_page(eb->pages[i]);
3994 btrfs_release_extent_buffer(eb);
3998 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4000 struct extent_buffer *eb =
4001 container_of(head, struct extent_buffer, rcu_head);
4003 __free_extent_buffer(eb);
4006 static int release_extent_buffer(struct extent_buffer *eb)
4007 __releases(&eb->refs_lock)
4009 lockdep_assert_held(&eb->refs_lock);
4011 WARN_ON(atomic_read(&eb->refs) == 0);
4012 if (atomic_dec_and_test(&eb->refs)) {
4013 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4014 struct btrfs_fs_info *fs_info = eb->fs_info;
4016 spin_unlock(&eb->refs_lock);
4018 spin_lock(&fs_info->buffer_lock);
4019 radix_tree_delete(&fs_info->buffer_radix,
4020 eb->start >> fs_info->sectorsize_bits);
4021 spin_unlock(&fs_info->buffer_lock);
4023 spin_unlock(&eb->refs_lock);
4026 btrfs_leak_debug_del_eb(eb);
4027 /* Should be safe to release our pages at this point */
4028 btrfs_release_extent_buffer_pages(eb);
4029 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4030 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4031 __free_extent_buffer(eb);
4035 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4038 spin_unlock(&eb->refs_lock);
4043 void free_extent_buffer(struct extent_buffer *eb)
4049 refs = atomic_read(&eb->refs);
4051 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4052 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4055 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4059 spin_lock(&eb->refs_lock);
4060 if (atomic_read(&eb->refs) == 2 &&
4061 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4062 !extent_buffer_under_io(eb) &&
4063 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4064 atomic_dec(&eb->refs);
4067 * I know this is terrible, but it's temporary until we stop tracking
4068 * the uptodate bits and such for the extent buffers.
4070 release_extent_buffer(eb);
4073 void free_extent_buffer_stale(struct extent_buffer *eb)
4078 spin_lock(&eb->refs_lock);
4079 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4081 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4082 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4083 atomic_dec(&eb->refs);
4084 release_extent_buffer(eb);
4087 static void btree_clear_page_dirty(struct page *page)
4089 ASSERT(PageDirty(page));
4090 ASSERT(PageLocked(page));
4091 clear_page_dirty_for_io(page);
4092 xa_lock_irq(&page->mapping->i_pages);
4093 if (!PageDirty(page))
4094 __xa_clear_mark(&page->mapping->i_pages,
4095 page_index(page), PAGECACHE_TAG_DIRTY);
4096 xa_unlock_irq(&page->mapping->i_pages);
4099 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4101 struct btrfs_fs_info *fs_info = eb->fs_info;
4102 struct page *page = eb->pages[0];
4105 /* btree_clear_page_dirty() needs page locked */
4107 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4110 btree_clear_page_dirty(page);
4112 WARN_ON(atomic_read(&eb->refs) == 0);
4115 void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
4116 struct extent_buffer *eb)
4118 struct btrfs_fs_info *fs_info = eb->fs_info;
4123 btrfs_assert_tree_write_locked(eb);
4125 if (trans && btrfs_header_generation(eb) != trans->transid)
4128 if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
4131 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
4132 fs_info->dirty_metadata_batch);
4134 if (eb->fs_info->nodesize < PAGE_SIZE)
4135 return clear_subpage_extent_buffer_dirty(eb);
4137 num_pages = num_extent_pages(eb);
4139 for (i = 0; i < num_pages; i++) {
4140 page = eb->pages[i];
4141 if (!PageDirty(page))
4144 btree_clear_page_dirty(page);
4145 ClearPageError(page);
4148 WARN_ON(atomic_read(&eb->refs) == 0);
4151 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4157 check_buffer_tree_ref(eb);
4159 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4161 num_pages = num_extent_pages(eb);
4162 WARN_ON(atomic_read(&eb->refs) == 0);
4163 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4166 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4169 * For subpage case, we can have other extent buffers in the
4170 * same page, and in clear_subpage_extent_buffer_dirty() we
4171 * have to clear page dirty without subpage lock held.
4172 * This can cause race where our page gets dirty cleared after
4175 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4176 * its page for other reasons, we can use page lock to prevent
4180 lock_page(eb->pages[0]);
4181 for (i = 0; i < num_pages; i++)
4182 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4183 eb->start, eb->len);
4185 unlock_page(eb->pages[0]);
4187 #ifdef CONFIG_BTRFS_DEBUG
4188 for (i = 0; i < num_pages; i++)
4189 ASSERT(PageDirty(eb->pages[i]));
4195 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4197 struct btrfs_fs_info *fs_info = eb->fs_info;
4202 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4203 num_pages = num_extent_pages(eb);
4204 for (i = 0; i < num_pages; i++) {
4205 page = eb->pages[i];
4210 * This is special handling for metadata subpage, as regular
4211 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4213 if (fs_info->nodesize >= PAGE_SIZE)
4214 ClearPageUptodate(page);
4216 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4221 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4223 struct btrfs_fs_info *fs_info = eb->fs_info;
4228 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4229 num_pages = num_extent_pages(eb);
4230 for (i = 0; i < num_pages; i++) {
4231 page = eb->pages[i];
4234 * This is special handling for metadata subpage, as regular
4235 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4237 if (fs_info->nodesize >= PAGE_SIZE)
4238 SetPageUptodate(page);
4240 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4245 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4247 struct btrfs_tree_parent_check *check)
4249 struct btrfs_fs_info *fs_info = eb->fs_info;
4250 struct extent_io_tree *io_tree;
4251 struct page *page = eb->pages[0];
4252 struct extent_state *cached_state = NULL;
4253 struct btrfs_bio_ctrl bio_ctrl = {
4255 .mirror_num = mirror_num,
4256 .parent_check = check,
4260 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4261 ASSERT(PagePrivate(page));
4263 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4265 if (wait == WAIT_NONE) {
4266 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4270 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4276 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4277 PageUptodate(page) ||
4278 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4279 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4280 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4285 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4286 eb->read_mirror = 0;
4287 atomic_set(&eb->io_pages, 1);
4288 check_buffer_tree_ref(eb);
4289 bio_ctrl.end_io_func = end_bio_extent_readpage;
4291 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
4293 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
4294 submit_extent_page(&bio_ctrl, eb->start, page, eb->len,
4295 eb->start - page_offset(page));
4296 submit_one_bio(&bio_ctrl);
4297 if (wait != WAIT_COMPLETE) {
4298 free_extent_state(cached_state);
4302 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1,
4303 EXTENT_LOCKED, &cached_state);
4304 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4309 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
4310 struct btrfs_tree_parent_check *check)
4314 int locked_pages = 0;
4315 int all_uptodate = 1;
4317 unsigned long num_reads = 0;
4318 struct btrfs_bio_ctrl bio_ctrl = {
4320 .mirror_num = mirror_num,
4321 .parent_check = check,
4324 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4328 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
4329 * operation, which could potentially still be in flight. In this case
4330 * we simply want to return an error.
4332 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
4335 if (eb->fs_info->nodesize < PAGE_SIZE)
4336 return read_extent_buffer_subpage(eb, wait, mirror_num, check);
4338 num_pages = num_extent_pages(eb);
4339 for (i = 0; i < num_pages; i++) {
4340 page = eb->pages[i];
4341 if (wait == WAIT_NONE) {
4343 * WAIT_NONE is only utilized by readahead. If we can't
4344 * acquire the lock atomically it means either the eb
4345 * is being read out or under modification.
4346 * Either way the eb will be or has been cached,
4347 * readahead can exit safely.
4349 if (!trylock_page(page))
4357 * We need to firstly lock all pages to make sure that
4358 * the uptodate bit of our pages won't be affected by
4359 * clear_extent_buffer_uptodate().
4361 for (i = 0; i < num_pages; i++) {
4362 page = eb->pages[i];
4363 if (!PageUptodate(page)) {
4370 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4374 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4375 eb->read_mirror = 0;
4376 atomic_set(&eb->io_pages, num_reads);
4378 * It is possible for release_folio to clear the TREE_REF bit before we
4379 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
4381 check_buffer_tree_ref(eb);
4382 bio_ctrl.end_io_func = end_bio_extent_readpage;
4383 for (i = 0; i < num_pages; i++) {
4384 page = eb->pages[i];
4386 if (!PageUptodate(page)) {
4387 ClearPageError(page);
4388 submit_extent_page(&bio_ctrl, page_offset(page), page,
4395 submit_one_bio(&bio_ctrl);
4397 if (wait != WAIT_COMPLETE)
4400 for (i = 0; i < num_pages; i++) {
4401 page = eb->pages[i];
4402 wait_on_page_locked(page);
4403 if (!PageUptodate(page))
4410 while (locked_pages > 0) {
4412 page = eb->pages[locked_pages];
4418 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
4421 btrfs_warn(eb->fs_info,
4422 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
4423 eb->start, eb->len, start, len);
4424 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4430 * Check if the [start, start + len) range is valid before reading/writing
4432 * NOTE: @start and @len are offset inside the eb, not logical address.
4434 * Caller should not touch the dst/src memory if this function returns error.
4436 static inline int check_eb_range(const struct extent_buffer *eb,
4437 unsigned long start, unsigned long len)
4439 unsigned long offset;
4441 /* start, start + len should not go beyond eb->len nor overflow */
4442 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
4443 return report_eb_range(eb, start, len);
4448 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
4449 unsigned long start, unsigned long len)
4455 char *dst = (char *)dstv;
4456 unsigned long i = get_eb_page_index(start);
4458 if (check_eb_range(eb, start, len))
4461 offset = get_eb_offset_in_page(eb, start);
4464 page = eb->pages[i];
4466 cur = min(len, (PAGE_SIZE - offset));
4467 kaddr = page_address(page);
4468 memcpy(dst, kaddr + offset, cur);
4477 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
4479 unsigned long start, unsigned long len)
4485 char __user *dst = (char __user *)dstv;
4486 unsigned long i = get_eb_page_index(start);
4489 WARN_ON(start > eb->len);
4490 WARN_ON(start + len > eb->start + eb->len);
4492 offset = get_eb_offset_in_page(eb, start);
4495 page = eb->pages[i];
4497 cur = min(len, (PAGE_SIZE - offset));
4498 kaddr = page_address(page);
4499 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
4513 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
4514 unsigned long start, unsigned long len)
4520 char *ptr = (char *)ptrv;
4521 unsigned long i = get_eb_page_index(start);
4524 if (check_eb_range(eb, start, len))
4527 offset = get_eb_offset_in_page(eb, start);
4530 page = eb->pages[i];
4532 cur = min(len, (PAGE_SIZE - offset));
4534 kaddr = page_address(page);
4535 ret = memcmp(ptr, kaddr + offset, cur);
4548 * Check that the extent buffer is uptodate.
4550 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
4551 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
4553 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
4556 struct btrfs_fs_info *fs_info = eb->fs_info;
4559 * If we are using the commit root we could potentially clear a page
4560 * Uptodate while we're using the extent buffer that we've previously
4561 * looked up. We don't want to complain in this case, as the page was
4562 * valid before, we just didn't write it out. Instead we want to catch
4563 * the case where we didn't actually read the block properly, which
4564 * would have !PageUptodate && !PageError, as we clear PageError before
4567 if (fs_info->nodesize < PAGE_SIZE) {
4568 bool uptodate, error;
4570 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
4571 eb->start, eb->len);
4572 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
4573 WARN_ON(!uptodate && !error);
4575 WARN_ON(!PageUptodate(page) && !PageError(page));
4579 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
4584 assert_eb_page_uptodate(eb, eb->pages[0]);
4585 kaddr = page_address(eb->pages[0]) +
4586 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
4588 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
4591 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
4595 assert_eb_page_uptodate(eb, eb->pages[0]);
4596 kaddr = page_address(eb->pages[0]) +
4597 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
4598 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
4601 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
4602 unsigned long start, unsigned long len)
4608 char *src = (char *)srcv;
4609 unsigned long i = get_eb_page_index(start);
4611 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
4613 if (check_eb_range(eb, start, len))
4616 offset = get_eb_offset_in_page(eb, start);
4619 page = eb->pages[i];
4620 assert_eb_page_uptodate(eb, page);
4622 cur = min(len, PAGE_SIZE - offset);
4623 kaddr = page_address(page);
4624 memcpy(kaddr + offset, src, cur);
4633 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
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];
4649 assert_eb_page_uptodate(eb, page);
4651 cur = min(len, PAGE_SIZE - offset);
4652 kaddr = page_address(page);
4653 memset(kaddr + offset, 0, cur);
4661 void copy_extent_buffer_full(const struct extent_buffer *dst,
4662 const struct extent_buffer *src)
4667 ASSERT(dst->len == src->len);
4669 if (dst->fs_info->nodesize >= PAGE_SIZE) {
4670 num_pages = num_extent_pages(dst);
4671 for (i = 0; i < num_pages; i++)
4672 copy_page(page_address(dst->pages[i]),
4673 page_address(src->pages[i]));
4675 size_t src_offset = get_eb_offset_in_page(src, 0);
4676 size_t dst_offset = get_eb_offset_in_page(dst, 0);
4678 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
4679 memcpy(page_address(dst->pages[0]) + dst_offset,
4680 page_address(src->pages[0]) + src_offset,
4685 void copy_extent_buffer(const struct extent_buffer *dst,
4686 const struct extent_buffer *src,
4687 unsigned long dst_offset, unsigned long src_offset,
4690 u64 dst_len = dst->len;
4695 unsigned long i = get_eb_page_index(dst_offset);
4697 if (check_eb_range(dst, dst_offset, len) ||
4698 check_eb_range(src, src_offset, len))
4701 WARN_ON(src->len != dst_len);
4703 offset = get_eb_offset_in_page(dst, dst_offset);
4706 page = dst->pages[i];
4707 assert_eb_page_uptodate(dst, page);
4709 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
4711 kaddr = page_address(page);
4712 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4722 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
4724 * @eb: the extent buffer
4725 * @start: offset of the bitmap item in the extent buffer
4727 * @page_index: return index of the page in the extent buffer that contains the
4729 * @page_offset: return offset into the page given by page_index
4731 * This helper hides the ugliness of finding the byte in an extent buffer which
4732 * contains a given bit.
4734 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
4735 unsigned long start, unsigned long nr,
4736 unsigned long *page_index,
4737 size_t *page_offset)
4739 size_t byte_offset = BIT_BYTE(nr);
4743 * The byte we want is the offset of the extent buffer + the offset of
4744 * the bitmap item in the extent buffer + the offset of the byte in the
4747 offset = start + offset_in_page(eb->start) + byte_offset;
4749 *page_index = offset >> PAGE_SHIFT;
4750 *page_offset = offset_in_page(offset);
4754 * Determine whether a bit in a bitmap item is set.
4756 * @eb: the extent buffer
4757 * @start: offset of the bitmap item in the extent buffer
4758 * @nr: bit number to test
4760 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
4768 eb_bitmap_offset(eb, start, nr, &i, &offset);
4769 page = eb->pages[i];
4770 assert_eb_page_uptodate(eb, page);
4771 kaddr = page_address(page);
4772 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
4776 * Set an area of a bitmap to 1.
4778 * @eb: the extent buffer
4779 * @start: offset of the bitmap item in the extent buffer
4780 * @pos: bit number of the first bit
4781 * @len: number of bits to set
4783 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
4784 unsigned long pos, unsigned long len)
4790 const unsigned int size = pos + len;
4791 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
4792 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
4794 eb_bitmap_offset(eb, start, pos, &i, &offset);
4795 page = eb->pages[i];
4796 assert_eb_page_uptodate(eb, page);
4797 kaddr = page_address(page);
4799 while (len >= bits_to_set) {
4800 kaddr[offset] |= mask_to_set;
4802 bits_to_set = BITS_PER_BYTE;
4804 if (++offset >= PAGE_SIZE && len > 0) {
4806 page = eb->pages[++i];
4807 assert_eb_page_uptodate(eb, page);
4808 kaddr = page_address(page);
4812 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
4813 kaddr[offset] |= mask_to_set;
4819 * Clear an area of a bitmap.
4821 * @eb: the extent buffer
4822 * @start: offset of the bitmap item in the extent buffer
4823 * @pos: bit number of the first bit
4824 * @len: number of bits to clear
4826 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
4827 unsigned long start, unsigned long pos,
4834 const unsigned int size = pos + len;
4835 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
4836 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
4838 eb_bitmap_offset(eb, start, pos, &i, &offset);
4839 page = eb->pages[i];
4840 assert_eb_page_uptodate(eb, page);
4841 kaddr = page_address(page);
4843 while (len >= bits_to_clear) {
4844 kaddr[offset] &= ~mask_to_clear;
4845 len -= bits_to_clear;
4846 bits_to_clear = BITS_PER_BYTE;
4848 if (++offset >= PAGE_SIZE && len > 0) {
4850 page = eb->pages[++i];
4851 assert_eb_page_uptodate(eb, page);
4852 kaddr = page_address(page);
4856 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
4857 kaddr[offset] &= ~mask_to_clear;
4861 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4863 unsigned long distance = (src > dst) ? src - dst : dst - src;
4864 return distance < len;
4867 static void copy_pages(struct page *dst_page, struct page *src_page,
4868 unsigned long dst_off, unsigned long src_off,
4871 char *dst_kaddr = page_address(dst_page);
4873 int must_memmove = 0;
4875 if (dst_page != src_page) {
4876 src_kaddr = page_address(src_page);
4878 src_kaddr = dst_kaddr;
4879 if (areas_overlap(src_off, dst_off, len))
4884 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
4886 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
4889 void memcpy_extent_buffer(const struct extent_buffer *dst,
4890 unsigned long dst_offset, unsigned long src_offset,
4894 size_t dst_off_in_page;
4895 size_t src_off_in_page;
4896 unsigned long dst_i;
4897 unsigned long src_i;
4899 if (check_eb_range(dst, dst_offset, len) ||
4900 check_eb_range(dst, src_offset, len))
4904 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
4905 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
4907 dst_i = get_eb_page_index(dst_offset);
4908 src_i = get_eb_page_index(src_offset);
4910 cur = min(len, (unsigned long)(PAGE_SIZE -
4912 cur = min_t(unsigned long, cur,
4913 (unsigned long)(PAGE_SIZE - dst_off_in_page));
4915 copy_pages(dst->pages[dst_i], dst->pages[src_i],
4916 dst_off_in_page, src_off_in_page, cur);
4924 void memmove_extent_buffer(const struct extent_buffer *dst,
4925 unsigned long dst_offset, unsigned long src_offset,
4929 size_t dst_off_in_page;
4930 size_t src_off_in_page;
4931 unsigned long dst_end = dst_offset + len - 1;
4932 unsigned long src_end = src_offset + len - 1;
4933 unsigned long dst_i;
4934 unsigned long src_i;
4936 if (check_eb_range(dst, dst_offset, len) ||
4937 check_eb_range(dst, src_offset, len))
4939 if (dst_offset < src_offset) {
4940 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
4944 dst_i = get_eb_page_index(dst_end);
4945 src_i = get_eb_page_index(src_end);
4947 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
4948 src_off_in_page = get_eb_offset_in_page(dst, src_end);
4950 cur = min_t(unsigned long, len, src_off_in_page + 1);
4951 cur = min(cur, dst_off_in_page + 1);
4952 copy_pages(dst->pages[dst_i], dst->pages[src_i],
4953 dst_off_in_page - cur + 1,
4954 src_off_in_page - cur + 1, cur);
4962 #define GANG_LOOKUP_SIZE 16
4963 static struct extent_buffer *get_next_extent_buffer(
4964 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
4966 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
4967 struct extent_buffer *found = NULL;
4968 u64 page_start = page_offset(page);
4969 u64 cur = page_start;
4971 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
4972 lockdep_assert_held(&fs_info->buffer_lock);
4974 while (cur < page_start + PAGE_SIZE) {
4978 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
4979 (void **)gang, cur >> fs_info->sectorsize_bits,
4980 min_t(unsigned int, GANG_LOOKUP_SIZE,
4981 PAGE_SIZE / fs_info->nodesize));
4984 for (i = 0; i < ret; i++) {
4985 /* Already beyond page end */
4986 if (gang[i]->start >= page_start + PAGE_SIZE)
4989 if (gang[i]->start >= bytenr) {
4994 cur = gang[ret - 1]->start + gang[ret - 1]->len;
5000 static int try_release_subpage_extent_buffer(struct page *page)
5002 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5003 u64 cur = page_offset(page);
5004 const u64 end = page_offset(page) + PAGE_SIZE;
5008 struct extent_buffer *eb = NULL;
5011 * Unlike try_release_extent_buffer() which uses page->private
5012 * to grab buffer, for subpage case we rely on radix tree, thus
5013 * we need to ensure radix tree consistency.
5015 * We also want an atomic snapshot of the radix tree, thus go
5016 * with spinlock rather than RCU.
5018 spin_lock(&fs_info->buffer_lock);
5019 eb = get_next_extent_buffer(fs_info, page, cur);
5021 /* No more eb in the page range after or at cur */
5022 spin_unlock(&fs_info->buffer_lock);
5025 cur = eb->start + eb->len;
5028 * The same as try_release_extent_buffer(), to ensure the eb
5029 * won't disappear out from under us.
5031 spin_lock(&eb->refs_lock);
5032 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5033 spin_unlock(&eb->refs_lock);
5034 spin_unlock(&fs_info->buffer_lock);
5037 spin_unlock(&fs_info->buffer_lock);
5040 * If tree ref isn't set then we know the ref on this eb is a
5041 * real ref, so just return, this eb will likely be freed soon
5044 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5045 spin_unlock(&eb->refs_lock);
5050 * Here we don't care about the return value, we will always
5051 * check the page private at the end. And
5052 * release_extent_buffer() will release the refs_lock.
5054 release_extent_buffer(eb);
5057 * Finally to check if we have cleared page private, as if we have
5058 * released all ebs in the page, the page private should be cleared now.
5060 spin_lock(&page->mapping->private_lock);
5061 if (!PagePrivate(page))
5065 spin_unlock(&page->mapping->private_lock);
5070 int try_release_extent_buffer(struct page *page)
5072 struct extent_buffer *eb;
5074 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5075 return try_release_subpage_extent_buffer(page);
5078 * We need to make sure nobody is changing page->private, as we rely on
5079 * page->private as the pointer to extent buffer.
5081 spin_lock(&page->mapping->private_lock);
5082 if (!PagePrivate(page)) {
5083 spin_unlock(&page->mapping->private_lock);
5087 eb = (struct extent_buffer *)page->private;
5091 * This is a little awful but should be ok, we need to make sure that
5092 * the eb doesn't disappear out from under us while we're looking at
5095 spin_lock(&eb->refs_lock);
5096 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5097 spin_unlock(&eb->refs_lock);
5098 spin_unlock(&page->mapping->private_lock);
5101 spin_unlock(&page->mapping->private_lock);
5104 * If tree ref isn't set then we know the ref on this eb is a real ref,
5105 * so just return, this page will likely be freed soon anyway.
5107 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5108 spin_unlock(&eb->refs_lock);
5112 return release_extent_buffer(eb);
5116 * btrfs_readahead_tree_block - attempt to readahead a child block
5117 * @fs_info: the fs_info
5118 * @bytenr: bytenr to read
5119 * @owner_root: objectid of the root that owns this eb
5120 * @gen: generation for the uptodate check, can be 0
5121 * @level: level for the eb
5123 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5124 * normal uptodate check of the eb, without checking the generation. If we have
5125 * to read the block we will not block on anything.
5127 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5128 u64 bytenr, u64 owner_root, u64 gen, int level)
5130 struct btrfs_tree_parent_check check = {
5135 struct extent_buffer *eb;
5138 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5142 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5143 free_extent_buffer(eb);
5147 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
5149 free_extent_buffer_stale(eb);
5151 free_extent_buffer(eb);
5155 * btrfs_readahead_node_child - readahead a node's child block
5156 * @node: parent node we're reading from
5157 * @slot: slot in the parent node for the child we want to read
5159 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5160 * the slot in the node provided.
5162 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5164 btrfs_readahead_tree_block(node->fs_info,
5165 btrfs_node_blockptr(node, slot),
5166 btrfs_header_owner(node),
5167 btrfs_node_ptr_generation(node, slot),
5168 btrfs_header_level(node) - 1);