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;
101 enum btrfs_compression_type compress_type;
102 u32 len_to_oe_boundary;
104 btrfs_bio_end_io_t end_io_func;
105 struct writeback_control *wbc;
108 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
110 struct btrfs_bio *bbio = bio_ctrl->bbio;
115 /* Caller should ensure the bio has at least some range added */
116 ASSERT(bbio->bio.bi_iter.bi_size);
118 if (btrfs_op(&bbio->bio) == BTRFS_MAP_READ &&
119 bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
120 btrfs_submit_compressed_read(bbio);
122 btrfs_submit_bio(bbio, 0);
124 /* The bbio is owned by the end_io handler now */
125 bio_ctrl->bbio = NULL;
129 * Submit or fail the current bio in the bio_ctrl structure.
131 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
133 struct btrfs_bio *bbio = bio_ctrl->bbio;
140 btrfs_bio_end_io(bbio, errno_to_blk_status(ret));
141 /* The bio is owned by the end_io handler now */
142 bio_ctrl->bbio = NULL;
144 submit_one_bio(bio_ctrl);
148 int __init extent_buffer_init_cachep(void)
150 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
151 sizeof(struct extent_buffer), 0,
152 SLAB_MEM_SPREAD, NULL);
153 if (!extent_buffer_cache)
159 void __cold extent_buffer_free_cachep(void)
162 * Make sure all delayed rcu free are flushed before we
166 kmem_cache_destroy(extent_buffer_cache);
169 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
171 unsigned long index = start >> PAGE_SHIFT;
172 unsigned long end_index = end >> PAGE_SHIFT;
175 while (index <= end_index) {
176 page = find_get_page(inode->i_mapping, index);
177 BUG_ON(!page); /* Pages should be in the extent_io_tree */
178 clear_page_dirty_for_io(page);
184 static void process_one_page(struct btrfs_fs_info *fs_info,
185 struct page *page, struct page *locked_page,
186 unsigned long page_ops, u64 start, u64 end)
190 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
191 len = end + 1 - start;
193 if (page_ops & PAGE_SET_ORDERED)
194 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
195 if (page_ops & PAGE_START_WRITEBACK) {
196 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
197 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
199 if (page_ops & PAGE_END_WRITEBACK)
200 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
202 if (page != locked_page && (page_ops & PAGE_UNLOCK))
203 btrfs_page_end_writer_lock(fs_info, page, start, len);
206 static void __process_pages_contig(struct address_space *mapping,
207 struct page *locked_page, u64 start, u64 end,
208 unsigned long page_ops)
210 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
211 pgoff_t start_index = start >> PAGE_SHIFT;
212 pgoff_t end_index = end >> PAGE_SHIFT;
213 pgoff_t index = start_index;
214 struct folio_batch fbatch;
217 folio_batch_init(&fbatch);
218 while (index <= end_index) {
221 found_folios = filemap_get_folios_contig(mapping, &index,
223 for (i = 0; i < found_folios; i++) {
224 struct folio *folio = fbatch.folios[i];
226 process_one_page(fs_info, &folio->page, locked_page,
227 page_ops, start, end);
229 folio_batch_release(&fbatch);
234 static noinline void __unlock_for_delalloc(struct inode *inode,
235 struct page *locked_page,
238 unsigned long index = start >> PAGE_SHIFT;
239 unsigned long end_index = end >> PAGE_SHIFT;
242 if (index == locked_page->index && end_index == index)
245 __process_pages_contig(inode->i_mapping, locked_page, start, end,
249 static noinline int lock_delalloc_pages(struct inode *inode,
250 struct page *locked_page,
254 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
255 struct address_space *mapping = inode->i_mapping;
256 pgoff_t start_index = start >> PAGE_SHIFT;
257 pgoff_t end_index = end >> PAGE_SHIFT;
258 pgoff_t index = start_index;
259 u64 processed_end = start;
260 struct folio_batch fbatch;
262 if (index == locked_page->index && index == end_index)
265 folio_batch_init(&fbatch);
266 while (index <= end_index) {
267 unsigned int found_folios, i;
269 found_folios = filemap_get_folios_contig(mapping, &index,
271 if (found_folios == 0)
274 for (i = 0; i < found_folios; i++) {
275 struct page *page = &fbatch.folios[i]->page;
276 u32 len = end + 1 - start;
278 if (page == locked_page)
281 if (btrfs_page_start_writer_lock(fs_info, page, start,
285 if (!PageDirty(page) || page->mapping != mapping) {
286 btrfs_page_end_writer_lock(fs_info, page, start,
291 processed_end = page_offset(page) + PAGE_SIZE - 1;
293 folio_batch_release(&fbatch);
299 folio_batch_release(&fbatch);
300 if (processed_end > start)
301 __unlock_for_delalloc(inode, locked_page, start, processed_end);
306 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
307 * more than @max_bytes.
309 * @start: The original start bytenr to search.
310 * Will store the extent range start bytenr.
311 * @end: The original end bytenr of the search range
312 * Will store the extent range end bytenr.
314 * Return true if we find a delalloc range which starts inside the original
315 * range, and @start/@end will store the delalloc range start/end.
317 * Return false if we can't find any delalloc range which starts inside the
318 * original range, and @start/@end will be the non-delalloc range start/end.
321 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
322 struct page *locked_page, u64 *start,
325 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
326 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
327 const u64 orig_start = *start;
328 const u64 orig_end = *end;
329 /* The sanity tests may not set a valid fs_info. */
330 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
334 struct extent_state *cached_state = NULL;
338 /* Caller should pass a valid @end to indicate the search range end */
339 ASSERT(orig_end > orig_start);
341 /* The range should at least cover part of the page */
342 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
343 orig_end <= page_offset(locked_page)));
345 /* step one, find a bunch of delalloc bytes starting at start */
346 delalloc_start = *start;
348 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
349 max_bytes, &cached_state);
350 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
351 *start = delalloc_start;
353 /* @delalloc_end can be -1, never go beyond @orig_end */
354 *end = min(delalloc_end, orig_end);
355 free_extent_state(cached_state);
360 * start comes from the offset of locked_page. We have to lock
361 * pages in order, so we can't process delalloc bytes before
364 if (delalloc_start < *start)
365 delalloc_start = *start;
368 * make sure to limit the number of pages we try to lock down
370 if (delalloc_end + 1 - delalloc_start > max_bytes)
371 delalloc_end = delalloc_start + max_bytes - 1;
373 /* step two, lock all the pages after the page that has start */
374 ret = lock_delalloc_pages(inode, locked_page,
375 delalloc_start, delalloc_end);
376 ASSERT(!ret || ret == -EAGAIN);
377 if (ret == -EAGAIN) {
378 /* some of the pages are gone, lets avoid looping by
379 * shortening the size of the delalloc range we're searching
381 free_extent_state(cached_state);
384 max_bytes = PAGE_SIZE;
393 /* step three, lock the state bits for the whole range */
394 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
396 /* then test to make sure it is all still delalloc */
397 ret = test_range_bit(tree, delalloc_start, delalloc_end,
398 EXTENT_DELALLOC, 1, cached_state);
400 unlock_extent(tree, delalloc_start, delalloc_end,
402 __unlock_for_delalloc(inode, locked_page,
403 delalloc_start, delalloc_end);
407 free_extent_state(cached_state);
408 *start = delalloc_start;
414 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
415 struct page *locked_page,
416 u32 clear_bits, unsigned long page_ops)
418 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
420 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
421 start, end, page_ops);
424 static bool btrfs_verify_page(struct page *page, u64 start)
426 if (!fsverity_active(page->mapping->host) ||
427 PageUptodate(page) ||
428 start >= i_size_read(page->mapping->host))
430 return fsverity_verify_page(page);
433 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
435 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
437 ASSERT(page_offset(page) <= start &&
438 start + len <= page_offset(page) + PAGE_SIZE);
440 if (uptodate && btrfs_verify_page(page, start))
441 btrfs_page_set_uptodate(fs_info, page, start, len);
443 btrfs_page_clear_uptodate(fs_info, page, start, len);
445 if (!btrfs_is_subpage(fs_info, page))
448 btrfs_subpage_end_reader(fs_info, page, start, len);
452 * after a writepage IO is done, we need to:
453 * clear the uptodate bits on error
454 * clear the writeback bits in the extent tree for this IO
455 * end_page_writeback if the page has no more pending IO
457 * Scheduling is not allowed, so the extent state tree is expected
458 * to have one and only one object corresponding to this IO.
460 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
462 struct bio *bio = &bbio->bio;
463 int error = blk_status_to_errno(bio->bi_status);
464 struct bio_vec *bvec;
465 struct bvec_iter_all iter_all;
467 ASSERT(!bio_flagged(bio, BIO_CLONED));
468 bio_for_each_segment_all(bvec, bio, iter_all) {
469 struct page *page = bvec->bv_page;
470 struct inode *inode = page->mapping->host;
471 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
472 const u32 sectorsize = fs_info->sectorsize;
473 u64 start = page_offset(page) + bvec->bv_offset;
474 u32 len = bvec->bv_len;
476 /* Our read/write should always be sector aligned. */
477 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
479 "partial page write in btrfs with offset %u and length %u",
480 bvec->bv_offset, bvec->bv_len);
481 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
483 "incomplete page write with offset %u and length %u",
484 bvec->bv_offset, bvec->bv_len);
486 btrfs_finish_ordered_extent(bbio->ordered, page, start, len, !error);
488 mapping_set_error(page->mapping, error);
489 btrfs_page_clear_writeback(fs_info, page, start, len);
496 * Record previously processed extent range
498 * For endio_readpage_release_extent() to handle a full extent range, reducing
499 * the extent io operations.
501 struct processed_extent {
502 struct btrfs_inode *inode;
503 /* Start of the range in @inode */
505 /* End of the range in @inode */
511 * Try to release processed extent range
513 * May not release the extent range right now if the current range is
514 * contiguous to processed extent.
516 * Will release processed extent when any of @inode, @uptodate, the range is
517 * no longer contiguous to the processed range.
519 * Passing @inode == NULL will force processed extent to be released.
521 static void endio_readpage_release_extent(struct processed_extent *processed,
522 struct btrfs_inode *inode, u64 start, u64 end,
525 struct extent_state *cached = NULL;
526 struct extent_io_tree *tree;
528 /* The first extent, initialize @processed */
529 if (!processed->inode)
533 * Contiguous to processed extent, just uptodate the end.
535 * Several things to notice:
537 * - bio can be merged as long as on-disk bytenr is contiguous
538 * This means we can have page belonging to other inodes, thus need to
539 * check if the inode still matches.
540 * - bvec can contain range beyond current page for multi-page bvec
541 * Thus we need to do processed->end + 1 >= start check
543 if (processed->inode == inode && processed->uptodate == uptodate &&
544 processed->end + 1 >= start && end >= processed->end) {
545 processed->end = end;
549 tree = &processed->inode->io_tree;
551 * Now we don't have range contiguous to the processed range, release
552 * the processed range now.
554 unlock_extent(tree, processed->start, processed->end, &cached);
557 /* Update processed to current range */
558 processed->inode = inode;
559 processed->start = start;
560 processed->end = end;
561 processed->uptodate = uptodate;
564 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
566 ASSERT(PageLocked(page));
567 if (!btrfs_is_subpage(fs_info, page))
570 ASSERT(PagePrivate(page));
571 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
575 * after a readpage IO is done, we need to:
576 * clear the uptodate bits on error
577 * set the uptodate bits if things worked
578 * set the page up to date if all extents in the tree are uptodate
579 * clear the lock bit in the extent tree
580 * unlock the page if there are no other extents locked for it
582 * Scheduling is not allowed, so the extent state tree is expected
583 * to have one and only one object corresponding to this IO.
585 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
587 struct bio *bio = &bbio->bio;
588 struct bio_vec *bvec;
589 struct processed_extent processed = { 0 };
591 * The offset to the beginning of a bio, since one bio can never be
592 * larger than UINT_MAX, u32 here is enough.
595 struct bvec_iter_all iter_all;
597 ASSERT(!bio_flagged(bio, BIO_CLONED));
598 bio_for_each_segment_all(bvec, bio, iter_all) {
599 bool uptodate = !bio->bi_status;
600 struct page *page = bvec->bv_page;
601 struct inode *inode = page->mapping->host;
602 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
603 const u32 sectorsize = fs_info->sectorsize;
609 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
610 bio->bi_iter.bi_sector, bio->bi_status,
614 * We always issue full-sector reads, but if some block in a
615 * page fails to read, blk_update_request() will advance
616 * bv_offset and adjust bv_len to compensate. Print a warning
617 * for unaligned offsets, and an error if they don't add up to
620 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
622 "partial page read in btrfs with offset %u and length %u",
623 bvec->bv_offset, bvec->bv_len);
624 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
627 "incomplete page read with offset %u and length %u",
628 bvec->bv_offset, bvec->bv_len);
630 start = page_offset(page) + bvec->bv_offset;
631 end = start + bvec->bv_len - 1;
634 if (likely(uptodate)) {
635 loff_t i_size = i_size_read(inode);
636 pgoff_t end_index = i_size >> PAGE_SHIFT;
639 * Zero out the remaining part if this range straddles
642 * Here we should only zero the range inside the bvec,
643 * not touch anything else.
645 * NOTE: i_size is exclusive while end is inclusive.
647 if (page->index == end_index && i_size <= end) {
648 u32 zero_start = max(offset_in_page(i_size),
649 offset_in_page(start));
651 zero_user_segment(page, zero_start,
652 offset_in_page(end) + 1);
656 /* Update page status and unlock. */
657 end_page_read(page, uptodate, start, len);
658 endio_readpage_release_extent(&processed, BTRFS_I(inode),
659 start, end, uptodate);
661 ASSERT(bio_offset + len > bio_offset);
665 /* Release the last extent */
666 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
671 * Populate every free slot in a provided array with pages.
673 * @nr_pages: number of pages to allocate
674 * @page_array: the array to fill with pages; any existing non-null entries in
675 * the array will be skipped
677 * Return: 0 if all pages were able to be allocated;
678 * -ENOMEM otherwise, the partially allocated pages would be freed and
679 * the array slots zeroed
681 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
683 unsigned int allocated;
685 for (allocated = 0; allocated < nr_pages;) {
686 unsigned int last = allocated;
688 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
690 if (allocated == nr_pages)
694 * During this iteration, no page could be allocated, even
695 * though alloc_pages_bulk_array() falls back to alloc_page()
696 * if it could not bulk-allocate. So we must be out of memory.
698 if (allocated == last) {
699 for (int i = 0; i < allocated; i++) {
700 __free_page(page_array[i]);
701 page_array[i] = NULL;
706 memalloc_retry_wait(GFP_NOFS);
711 static bool btrfs_bio_is_contig(struct btrfs_bio_ctrl *bio_ctrl,
712 struct page *page, u64 disk_bytenr,
713 unsigned int pg_offset)
715 struct bio *bio = &bio_ctrl->bbio->bio;
716 struct bio_vec *bvec = bio_last_bvec_all(bio);
717 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
719 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
721 * For compression, all IO should have its logical bytenr set
722 * to the starting bytenr of the compressed extent.
724 return bio->bi_iter.bi_sector == sector;
728 * The contig check requires the following conditions to be met:
730 * 1) The pages are belonging to the same inode
731 * This is implied by the call chain.
733 * 2) The range has adjacent logical bytenr
735 * 3) The range has adjacent file offset
736 * This is required for the usage of btrfs_bio->file_offset.
738 return bio_end_sector(bio) == sector &&
739 page_offset(bvec->bv_page) + bvec->bv_offset + bvec->bv_len ==
740 page_offset(page) + pg_offset;
743 static void alloc_new_bio(struct btrfs_inode *inode,
744 struct btrfs_bio_ctrl *bio_ctrl,
745 u64 disk_bytenr, u64 file_offset)
747 struct btrfs_fs_info *fs_info = inode->root->fs_info;
748 struct btrfs_bio *bbio;
750 bbio = btrfs_bio_alloc(BIO_MAX_VECS, bio_ctrl->opf, fs_info,
751 bio_ctrl->end_io_func, NULL);
752 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
754 bbio->file_offset = file_offset;
755 bio_ctrl->bbio = bbio;
756 bio_ctrl->len_to_oe_boundary = U32_MAX;
758 /* Limit data write bios to the ordered boundary. */
760 struct btrfs_ordered_extent *ordered;
762 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
764 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
765 ordered->file_offset +
766 ordered->disk_num_bytes - file_offset);
767 bbio->ordered = ordered;
771 * Pick the last added device to support cgroup writeback. For
772 * multi-device file systems this means blk-cgroup policies have
773 * to always be set on the last added/replaced device.
774 * This is a bit odd but has been like that for a long time.
776 bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
777 wbc_init_bio(bio_ctrl->wbc, &bbio->bio);
782 * @disk_bytenr: logical bytenr where the write will be
783 * @page: page to add to the bio
784 * @size: portion of page that we want to write to
785 * @pg_offset: offset of the new bio or to check whether we are adding
786 * a contiguous page to the previous one
788 * The will either add the page into the existing @bio_ctrl->bbio, or allocate a
789 * new one in @bio_ctrl->bbio.
790 * The mirror number for this IO should already be initizlied in
791 * @bio_ctrl->mirror_num.
793 static void submit_extent_page(struct btrfs_bio_ctrl *bio_ctrl,
794 u64 disk_bytenr, struct page *page,
795 size_t size, unsigned long pg_offset)
797 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
799 ASSERT(pg_offset + size <= PAGE_SIZE);
800 ASSERT(bio_ctrl->end_io_func);
802 if (bio_ctrl->bbio &&
803 !btrfs_bio_is_contig(bio_ctrl, page, disk_bytenr, pg_offset))
804 submit_one_bio(bio_ctrl);
809 /* Allocate new bio if needed */
810 if (!bio_ctrl->bbio) {
811 alloc_new_bio(inode, bio_ctrl, disk_bytenr,
812 page_offset(page) + pg_offset);
815 /* Cap to the current ordered extent boundary if there is one. */
816 if (len > bio_ctrl->len_to_oe_boundary) {
817 ASSERT(bio_ctrl->compress_type == BTRFS_COMPRESS_NONE);
818 ASSERT(is_data_inode(&inode->vfs_inode));
819 len = bio_ctrl->len_to_oe_boundary;
822 if (bio_add_page(&bio_ctrl->bbio->bio, page, len, pg_offset) != len) {
823 /* bio full: move on to a new one */
824 submit_one_bio(bio_ctrl);
829 wbc_account_cgroup_owner(bio_ctrl->wbc, page, len);
836 * len_to_oe_boundary defaults to U32_MAX, which isn't page or
837 * sector aligned. alloc_new_bio() then sets it to the end of
838 * our ordered extent for writes into zoned devices.
840 * When len_to_oe_boundary is tracking an ordered extent, we
841 * trust the ordered extent code to align things properly, and
842 * the check above to cap our write to the ordered extent
843 * boundary is correct.
845 * When len_to_oe_boundary is U32_MAX, the cap above would
846 * result in a 4095 byte IO for the last page right before
847 * we hit the bio limit of UINT_MAX. bio_add_page() has all
848 * the checks required to make sure we don't overflow the bio,
849 * and we should just ignore len_to_oe_boundary completely
850 * unless we're using it to track an ordered extent.
852 * It's pretty hard to make a bio sized U32_MAX, but it can
853 * happen when the page cache is able to feed us contiguous
854 * pages for large extents.
856 if (bio_ctrl->len_to_oe_boundary != U32_MAX)
857 bio_ctrl->len_to_oe_boundary -= len;
859 /* Ordered extent boundary: move on to a new bio. */
860 if (bio_ctrl->len_to_oe_boundary == 0)
861 submit_one_bio(bio_ctrl);
865 static int attach_extent_buffer_page(struct extent_buffer *eb,
867 struct btrfs_subpage *prealloc)
869 struct btrfs_fs_info *fs_info = eb->fs_info;
873 * If the page is mapped to btree inode, we should hold the private
874 * lock to prevent race.
875 * For cloned or dummy extent buffers, their pages are not mapped and
876 * will not race with any other ebs.
879 lockdep_assert_held(&page->mapping->private_lock);
881 if (fs_info->nodesize >= PAGE_SIZE) {
882 if (!PagePrivate(page))
883 attach_page_private(page, eb);
885 WARN_ON(page->private != (unsigned long)eb);
889 /* Already mapped, just free prealloc */
890 if (PagePrivate(page)) {
891 btrfs_free_subpage(prealloc);
896 /* Has preallocated memory for subpage */
897 attach_page_private(page, prealloc);
899 /* Do new allocation to attach subpage */
900 ret = btrfs_attach_subpage(fs_info, page,
901 BTRFS_SUBPAGE_METADATA);
905 int set_page_extent_mapped(struct page *page)
907 struct btrfs_fs_info *fs_info;
909 ASSERT(page->mapping);
911 if (PagePrivate(page))
914 fs_info = btrfs_sb(page->mapping->host->i_sb);
916 if (btrfs_is_subpage(fs_info, page))
917 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
919 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
923 void clear_page_extent_mapped(struct page *page)
925 struct btrfs_fs_info *fs_info;
927 ASSERT(page->mapping);
929 if (!PagePrivate(page))
932 fs_info = btrfs_sb(page->mapping->host->i_sb);
933 if (btrfs_is_subpage(fs_info, page))
934 return btrfs_detach_subpage(fs_info, page);
936 detach_page_private(page);
939 static struct extent_map *
940 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
941 u64 start, u64 len, struct extent_map **em_cached)
943 struct extent_map *em;
945 if (em_cached && *em_cached) {
947 if (extent_map_in_tree(em) && start >= em->start &&
948 start < extent_map_end(em)) {
949 refcount_inc(&em->refs);
957 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
958 if (em_cached && !IS_ERR(em)) {
960 refcount_inc(&em->refs);
966 * basic readpage implementation. Locked extent state structs are inserted
967 * into the tree that are removed when the IO is done (by the end_io
969 * XXX JDM: This needs looking at to ensure proper page locking
970 * return 0 on success, otherwise return error
972 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
973 struct btrfs_bio_ctrl *bio_ctrl, u64 *prev_em_start)
975 struct inode *inode = page->mapping->host;
976 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
977 u64 start = page_offset(page);
978 const u64 end = start + PAGE_SIZE - 1;
981 u64 last_byte = i_size_read(inode);
983 struct extent_map *em;
985 size_t pg_offset = 0;
987 size_t blocksize = inode->i_sb->s_blocksize;
988 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
990 ret = set_page_extent_mapped(page);
992 unlock_extent(tree, start, end, NULL);
997 if (page->index == last_byte >> PAGE_SHIFT) {
998 size_t zero_offset = offset_in_page(last_byte);
1001 iosize = PAGE_SIZE - zero_offset;
1002 memzero_page(page, zero_offset, iosize);
1005 bio_ctrl->end_io_func = end_bio_extent_readpage;
1006 begin_page_read(fs_info, page);
1007 while (cur <= end) {
1008 enum btrfs_compression_type compress_type = BTRFS_COMPRESS_NONE;
1009 bool force_bio_submit = false;
1012 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1013 if (cur >= last_byte) {
1014 iosize = PAGE_SIZE - pg_offset;
1015 memzero_page(page, pg_offset, iosize);
1016 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1017 end_page_read(page, true, cur, iosize);
1020 em = __get_extent_map(inode, page, pg_offset, cur,
1021 end - cur + 1, em_cached);
1023 unlock_extent(tree, cur, end, NULL);
1024 end_page_read(page, false, cur, end + 1 - cur);
1027 extent_offset = cur - em->start;
1028 BUG_ON(extent_map_end(em) <= cur);
1031 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1032 compress_type = em->compress_type;
1034 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1035 iosize = ALIGN(iosize, blocksize);
1036 if (compress_type != BTRFS_COMPRESS_NONE)
1037 disk_bytenr = em->block_start;
1039 disk_bytenr = em->block_start + extent_offset;
1040 block_start = em->block_start;
1041 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1042 block_start = EXTENT_MAP_HOLE;
1045 * If we have a file range that points to a compressed extent
1046 * and it's followed by a consecutive file range that points
1047 * to the same compressed extent (possibly with a different
1048 * offset and/or length, so it either points to the whole extent
1049 * or only part of it), we must make sure we do not submit a
1050 * single bio to populate the pages for the 2 ranges because
1051 * this makes the compressed extent read zero out the pages
1052 * belonging to the 2nd range. Imagine the following scenario:
1055 * [0 - 8K] [8K - 24K]
1058 * points to extent X, points to extent X,
1059 * offset 4K, length of 8K offset 0, length 16K
1061 * [extent X, compressed length = 4K uncompressed length = 16K]
1063 * If the bio to read the compressed extent covers both ranges,
1064 * it will decompress extent X into the pages belonging to the
1065 * first range and then it will stop, zeroing out the remaining
1066 * pages that belong to the other range that points to extent X.
1067 * So here we make sure we submit 2 bios, one for the first
1068 * range and another one for the third range. Both will target
1069 * the same physical extent from disk, but we can't currently
1070 * make the compressed bio endio callback populate the pages
1071 * for both ranges because each compressed bio is tightly
1072 * coupled with a single extent map, and each range can have
1073 * an extent map with a different offset value relative to the
1074 * uncompressed data of our extent and different lengths. This
1075 * is a corner case so we prioritize correctness over
1076 * non-optimal behavior (submitting 2 bios for the same extent).
1078 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1079 prev_em_start && *prev_em_start != (u64)-1 &&
1080 *prev_em_start != em->start)
1081 force_bio_submit = true;
1084 *prev_em_start = em->start;
1086 free_extent_map(em);
1089 /* we've found a hole, just zero and go on */
1090 if (block_start == EXTENT_MAP_HOLE) {
1091 memzero_page(page, pg_offset, iosize);
1093 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1094 end_page_read(page, true, cur, iosize);
1096 pg_offset += iosize;
1099 /* the get_extent function already copied into the page */
1100 if (block_start == EXTENT_MAP_INLINE) {
1101 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1102 end_page_read(page, true, cur, iosize);
1104 pg_offset += iosize;
1108 if (bio_ctrl->compress_type != compress_type) {
1109 submit_one_bio(bio_ctrl);
1110 bio_ctrl->compress_type = compress_type;
1113 if (force_bio_submit)
1114 submit_one_bio(bio_ctrl);
1115 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1118 pg_offset += iosize;
1124 int btrfs_read_folio(struct file *file, struct folio *folio)
1126 struct page *page = &folio->page;
1127 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1128 u64 start = page_offset(page);
1129 u64 end = start + PAGE_SIZE - 1;
1130 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ };
1133 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1135 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, NULL);
1137 * If btrfs_do_readpage() failed we will want to submit the assembled
1138 * bio to do the cleanup.
1140 submit_one_bio(&bio_ctrl);
1144 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1146 struct extent_map **em_cached,
1147 struct btrfs_bio_ctrl *bio_ctrl,
1150 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1153 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1155 for (index = 0; index < nr_pages; index++) {
1156 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1158 put_page(pages[index]);
1163 * helper for __extent_writepage, doing all of the delayed allocation setup.
1165 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1166 * to write the page (copy into inline extent). In this case the IO has
1167 * been started and the page is already unlocked.
1169 * This returns 0 if all went well (page still locked)
1170 * This returns < 0 if there were errors (page still locked)
1172 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1173 struct page *page, struct writeback_control *wbc)
1175 const u64 page_start = page_offset(page);
1176 const u64 page_end = page_start + PAGE_SIZE - 1;
1177 u64 delalloc_start = page_start;
1178 u64 delalloc_end = page_end;
1179 u64 delalloc_to_write = 0;
1182 while (delalloc_start < page_end) {
1183 delalloc_end = page_end;
1184 if (!find_lock_delalloc_range(&inode->vfs_inode, page,
1185 &delalloc_start, &delalloc_end)) {
1186 delalloc_start = delalloc_end + 1;
1190 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1195 delalloc_start = delalloc_end + 1;
1199 * delalloc_end is already one less than the total length, so
1200 * we don't subtract one from PAGE_SIZE
1202 delalloc_to_write +=
1203 DIV_ROUND_UP(delalloc_end + 1 - page_start, PAGE_SIZE);
1206 * If btrfs_run_dealloc_range() already started I/O and unlocked
1207 * the pages, we just need to account for them here.
1210 wbc->nr_to_write -= delalloc_to_write;
1214 if (wbc->nr_to_write < delalloc_to_write) {
1217 if (delalloc_to_write < thresh * 2)
1218 thresh = delalloc_to_write;
1219 wbc->nr_to_write = min_t(u64, delalloc_to_write,
1227 * Find the first byte we need to write.
1229 * For subpage, one page can contain several sectors, and
1230 * __extent_writepage_io() will just grab all extent maps in the page
1231 * range and try to submit all non-inline/non-compressed extents.
1233 * This is a big problem for subpage, we shouldn't re-submit already written
1235 * This function will lookup subpage dirty bit to find which range we really
1238 * Return the next dirty range in [@start, @end).
1239 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
1241 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
1242 struct page *page, u64 *start, u64 *end)
1244 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
1245 struct btrfs_subpage_info *spi = fs_info->subpage_info;
1246 u64 orig_start = *start;
1247 /* Declare as unsigned long so we can use bitmap ops */
1248 unsigned long flags;
1249 int range_start_bit;
1253 * For regular sector size == page size case, since one page only
1254 * contains one sector, we return the page offset directly.
1256 if (!btrfs_is_subpage(fs_info, page)) {
1257 *start = page_offset(page);
1258 *end = page_offset(page) + PAGE_SIZE;
1262 range_start_bit = spi->dirty_offset +
1263 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
1265 /* We should have the page locked, but just in case */
1266 spin_lock_irqsave(&subpage->lock, flags);
1267 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
1268 spi->dirty_offset + spi->bitmap_nr_bits);
1269 spin_unlock_irqrestore(&subpage->lock, flags);
1271 range_start_bit -= spi->dirty_offset;
1272 range_end_bit -= spi->dirty_offset;
1274 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
1275 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
1279 * helper for __extent_writepage. This calls the writepage start hooks,
1280 * and does the loop to map the page into extents and bios.
1282 * We return 1 if the IO is started and the page is unlocked,
1283 * 0 if all went well (page still locked)
1284 * < 0 if there were errors (page still locked)
1286 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
1288 struct btrfs_bio_ctrl *bio_ctrl,
1292 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1293 u64 cur = page_offset(page);
1294 u64 end = cur + PAGE_SIZE - 1;
1297 struct extent_map *em;
1301 ret = btrfs_writepage_cow_fixup(page);
1303 /* Fixup worker will requeue */
1304 redirty_page_for_writepage(bio_ctrl->wbc, page);
1309 bio_ctrl->end_io_func = end_bio_extent_writepage;
1310 while (cur <= end) {
1311 u32 len = end - cur + 1;
1314 u64 dirty_range_start = cur;
1315 u64 dirty_range_end;
1318 if (cur >= i_size) {
1319 btrfs_mark_ordered_io_finished(inode, page, cur, len,
1322 * This range is beyond i_size, thus we don't need to
1323 * bother writing back.
1324 * But we still need to clear the dirty subpage bit, or
1325 * the next time the page gets dirtied, we will try to
1326 * writeback the sectors with subpage dirty bits,
1327 * causing writeback without ordered extent.
1329 btrfs_page_clear_dirty(fs_info, page, cur, len);
1333 find_next_dirty_byte(fs_info, page, &dirty_range_start,
1335 if (cur < dirty_range_start) {
1336 cur = dirty_range_start;
1340 em = btrfs_get_extent(inode, NULL, 0, cur, len);
1342 ret = PTR_ERR_OR_ZERO(em);
1346 extent_offset = cur - em->start;
1347 em_end = extent_map_end(em);
1348 ASSERT(cur <= em_end);
1350 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
1351 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
1353 block_start = em->block_start;
1354 disk_bytenr = em->block_start + extent_offset;
1356 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
1357 ASSERT(block_start != EXTENT_MAP_HOLE);
1358 ASSERT(block_start != EXTENT_MAP_INLINE);
1361 * Note that em_end from extent_map_end() and dirty_range_end from
1362 * find_next_dirty_byte() are all exclusive
1364 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
1365 free_extent_map(em);
1368 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
1369 if (!PageWriteback(page)) {
1370 btrfs_err(inode->root->fs_info,
1371 "page %lu not writeback, cur %llu end %llu",
1372 page->index, cur, end);
1376 * Although the PageDirty bit is cleared before entering this
1377 * function, subpage dirty bit is not cleared.
1378 * So clear subpage dirty bit here so next time we won't submit
1379 * page for range already written to disk.
1381 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
1383 submit_extent_page(bio_ctrl, disk_bytenr, page, iosize,
1384 cur - page_offset(page));
1389 btrfs_page_assert_not_dirty(fs_info, page);
1395 * If we finish without problem, we should not only clear page dirty,
1396 * but also empty subpage dirty bits
1403 * the writepage semantics are similar to regular writepage. extent
1404 * records are inserted to lock ranges in the tree, and as dirty areas
1405 * are found, they are marked writeback. Then the lock bits are removed
1406 * and the end_io handler clears the writeback ranges
1408 * Return 0 if everything goes well.
1409 * Return <0 for error.
1411 static int __extent_writepage(struct page *page, struct btrfs_bio_ctrl *bio_ctrl)
1413 struct folio *folio = page_folio(page);
1414 struct inode *inode = page->mapping->host;
1415 const u64 page_start = page_offset(page);
1419 loff_t i_size = i_size_read(inode);
1420 unsigned long end_index = i_size >> PAGE_SHIFT;
1422 trace___extent_writepage(page, inode, bio_ctrl->wbc);
1424 WARN_ON(!PageLocked(page));
1426 pg_offset = offset_in_page(i_size);
1427 if (page->index > end_index ||
1428 (page->index == end_index && !pg_offset)) {
1429 folio_invalidate(folio, 0, folio_size(folio));
1430 folio_unlock(folio);
1434 if (page->index == end_index)
1435 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
1437 ret = set_page_extent_mapped(page);
1441 ret = writepage_delalloc(BTRFS_I(inode), page, bio_ctrl->wbc);
1447 ret = __extent_writepage_io(BTRFS_I(inode), page, bio_ctrl, i_size, &nr);
1451 bio_ctrl->wbc->nr_to_write--;
1455 /* make sure the mapping tag for page dirty gets cleared */
1456 set_page_writeback(page);
1457 end_page_writeback(page);
1460 btrfs_mark_ordered_io_finished(BTRFS_I(inode), page, page_start,
1462 mapping_set_error(page->mapping, ret);
1469 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
1471 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
1472 TASK_UNINTERRUPTIBLE);
1476 * Lock extent buffer status and pages for writeback.
1478 * Return %false if the extent buffer doesn't need to be submitted (e.g. the
1479 * extent buffer is not dirty)
1480 * Return %true is the extent buffer is submitted to bio.
1482 static noinline_for_stack bool lock_extent_buffer_for_io(struct extent_buffer *eb,
1483 struct writeback_control *wbc)
1485 struct btrfs_fs_info *fs_info = eb->fs_info;
1488 btrfs_tree_lock(eb);
1489 while (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
1490 btrfs_tree_unlock(eb);
1491 if (wbc->sync_mode != WB_SYNC_ALL)
1493 wait_on_extent_buffer_writeback(eb);
1494 btrfs_tree_lock(eb);
1498 * We need to do this to prevent races in people who check if the eb is
1499 * under IO since we can end up having no IO bits set for a short period
1502 spin_lock(&eb->refs_lock);
1503 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
1504 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1505 spin_unlock(&eb->refs_lock);
1506 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
1507 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1509 fs_info->dirty_metadata_batch);
1512 spin_unlock(&eb->refs_lock);
1514 btrfs_tree_unlock(eb);
1518 static void set_btree_ioerr(struct extent_buffer *eb)
1520 struct btrfs_fs_info *fs_info = eb->fs_info;
1522 set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1525 * A read may stumble upon this buffer later, make sure that it gets an
1526 * error and knows there was an error.
1528 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
1531 * We need to set the mapping with the io error as well because a write
1532 * error will flip the file system readonly, and then syncfs() will
1533 * return a 0 because we are readonly if we don't modify the err seq for
1536 mapping_set_error(eb->fs_info->btree_inode->i_mapping, -EIO);
1539 * If writeback for a btree extent that doesn't belong to a log tree
1540 * failed, increment the counter transaction->eb_write_errors.
1541 * We do this because while the transaction is running and before it's
1542 * committing (when we call filemap_fdata[write|wait]_range against
1543 * the btree inode), we might have
1544 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
1545 * returns an error or an error happens during writeback, when we're
1546 * committing the transaction we wouldn't know about it, since the pages
1547 * can be no longer dirty nor marked anymore for writeback (if a
1548 * subsequent modification to the extent buffer didn't happen before the
1549 * transaction commit), which makes filemap_fdata[write|wait]_range not
1550 * able to find the pages tagged with SetPageError at transaction
1551 * commit time. So if this happens we must abort the transaction,
1552 * otherwise we commit a super block with btree roots that point to
1553 * btree nodes/leafs whose content on disk is invalid - either garbage
1554 * or the content of some node/leaf from a past generation that got
1555 * cowed or deleted and is no longer valid.
1557 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
1558 * not be enough - we need to distinguish between log tree extents vs
1559 * non-log tree extents, and the next filemap_fdatawait_range() call
1560 * will catch and clear such errors in the mapping - and that call might
1561 * be from a log sync and not from a transaction commit. Also, checking
1562 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
1563 * not done and would not be reliable - the eb might have been released
1564 * from memory and reading it back again means that flag would not be
1565 * set (since it's a runtime flag, not persisted on disk).
1567 * Using the flags below in the btree inode also makes us achieve the
1568 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
1569 * writeback for all dirty pages and before filemap_fdatawait_range()
1570 * is called, the writeback for all dirty pages had already finished
1571 * with errors - because we were not using AS_EIO/AS_ENOSPC,
1572 * filemap_fdatawait_range() would return success, as it could not know
1573 * that writeback errors happened (the pages were no longer tagged for
1576 switch (eb->log_index) {
1578 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
1581 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
1584 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
1587 BUG(); /* unexpected, logic error */
1592 * The endio specific version which won't touch any unsafe spinlock in endio
1595 static struct extent_buffer *find_extent_buffer_nolock(
1596 struct btrfs_fs_info *fs_info, u64 start)
1598 struct extent_buffer *eb;
1601 eb = radix_tree_lookup(&fs_info->buffer_radix,
1602 start >> fs_info->sectorsize_bits);
1603 if (eb && atomic_inc_not_zero(&eb->refs)) {
1611 static void extent_buffer_write_end_io(struct btrfs_bio *bbio)
1613 struct extent_buffer *eb = bbio->private;
1614 struct btrfs_fs_info *fs_info = eb->fs_info;
1615 bool uptodate = !bbio->bio.bi_status;
1616 struct bvec_iter_all iter_all;
1617 struct bio_vec *bvec;
1621 set_btree_ioerr(eb);
1623 bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
1624 u64 start = eb->start + bio_offset;
1625 struct page *page = bvec->bv_page;
1626 u32 len = bvec->bv_len;
1628 btrfs_page_clear_writeback(fs_info, page, start, len);
1632 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1633 smp_mb__after_atomic();
1634 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
1636 bio_put(&bbio->bio);
1639 static void prepare_eb_write(struct extent_buffer *eb)
1642 unsigned long start;
1645 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1647 /* Set btree blocks beyond nritems with 0 to avoid stale content */
1648 nritems = btrfs_header_nritems(eb);
1649 if (btrfs_header_level(eb) > 0) {
1650 end = btrfs_node_key_ptr_offset(eb, nritems);
1651 memzero_extent_buffer(eb, end, eb->len - end);
1655 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
1657 start = btrfs_item_nr_offset(eb, nritems);
1658 end = btrfs_item_nr_offset(eb, 0);
1660 end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
1662 end += btrfs_item_offset(eb, nritems - 1);
1663 memzero_extent_buffer(eb, start, end - start);
1667 static noinline_for_stack void write_one_eb(struct extent_buffer *eb,
1668 struct writeback_control *wbc)
1670 struct btrfs_fs_info *fs_info = eb->fs_info;
1671 struct btrfs_bio *bbio;
1673 prepare_eb_write(eb);
1675 bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
1676 REQ_OP_WRITE | REQ_META | wbc_to_write_flags(wbc),
1677 eb->fs_info, extent_buffer_write_end_io, eb);
1678 bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
1679 bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
1680 wbc_init_bio(wbc, &bbio->bio);
1681 bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
1682 bbio->file_offset = eb->start;
1683 if (fs_info->nodesize < PAGE_SIZE) {
1684 struct page *p = eb->pages[0];
1687 btrfs_subpage_set_writeback(fs_info, p, eb->start, eb->len);
1688 if (btrfs_subpage_clear_and_test_dirty(fs_info, p, eb->start,
1690 clear_page_dirty_for_io(p);
1693 __bio_add_page(&bbio->bio, p, eb->len, eb->start - page_offset(p));
1694 wbc_account_cgroup_owner(wbc, p, eb->len);
1697 for (int i = 0; i < num_extent_pages(eb); i++) {
1698 struct page *p = eb->pages[i];
1701 clear_page_dirty_for_io(p);
1702 set_page_writeback(p);
1703 __bio_add_page(&bbio->bio, p, PAGE_SIZE, 0);
1704 wbc_account_cgroup_owner(wbc, p, PAGE_SIZE);
1709 btrfs_submit_bio(bbio, 0);
1713 * Submit one subpage btree page.
1715 * The main difference to submit_eb_page() is:
1717 * For subpage, we don't rely on page locking at all.
1720 * We only flush bio if we may be unable to fit current extent buffers into
1723 * Return >=0 for the number of submitted extent buffers.
1724 * Return <0 for fatal error.
1726 static int submit_eb_subpage(struct page *page, struct writeback_control *wbc)
1728 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
1730 u64 page_start = page_offset(page);
1732 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
1734 /* Lock and write each dirty extent buffers in the range */
1735 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
1736 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
1737 struct extent_buffer *eb;
1738 unsigned long flags;
1742 * Take private lock to ensure the subpage won't be detached
1745 spin_lock(&page->mapping->private_lock);
1746 if (!PagePrivate(page)) {
1747 spin_unlock(&page->mapping->private_lock);
1750 spin_lock_irqsave(&subpage->lock, flags);
1751 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
1752 subpage->bitmaps)) {
1753 spin_unlock_irqrestore(&subpage->lock, flags);
1754 spin_unlock(&page->mapping->private_lock);
1759 start = page_start + bit_start * fs_info->sectorsize;
1760 bit_start += sectors_per_node;
1763 * Here we just want to grab the eb without touching extra
1764 * spin locks, so call find_extent_buffer_nolock().
1766 eb = find_extent_buffer_nolock(fs_info, start);
1767 spin_unlock_irqrestore(&subpage->lock, flags);
1768 spin_unlock(&page->mapping->private_lock);
1771 * The eb has already reached 0 refs thus find_extent_buffer()
1772 * doesn't return it. We don't need to write back such eb
1778 if (lock_extent_buffer_for_io(eb, wbc)) {
1779 write_one_eb(eb, wbc);
1782 free_extent_buffer(eb);
1788 * Submit all page(s) of one extent buffer.
1790 * @page: the page of one extent buffer
1791 * @eb_context: to determine if we need to submit this page, if current page
1792 * belongs to this eb, we don't need to submit
1794 * The caller should pass each page in their bytenr order, and here we use
1795 * @eb_context to determine if we have submitted pages of one extent buffer.
1797 * If we have, we just skip until we hit a new page that doesn't belong to
1798 * current @eb_context.
1800 * If not, we submit all the page(s) of the extent buffer.
1802 * Return >0 if we have submitted the extent buffer successfully.
1803 * Return 0 if we don't need to submit the page, as it's already submitted by
1805 * Return <0 for fatal error.
1807 static int submit_eb_page(struct page *page, struct btrfs_eb_write_context *ctx)
1809 struct writeback_control *wbc = ctx->wbc;
1810 struct address_space *mapping = page->mapping;
1811 struct extent_buffer *eb;
1814 if (!PagePrivate(page))
1817 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
1818 return submit_eb_subpage(page, wbc);
1820 spin_lock(&mapping->private_lock);
1821 if (!PagePrivate(page)) {
1822 spin_unlock(&mapping->private_lock);
1826 eb = (struct extent_buffer *)page->private;
1829 * Shouldn't happen and normally this would be a BUG_ON but no point
1830 * crashing the machine for something we can survive anyway.
1833 spin_unlock(&mapping->private_lock);
1837 if (eb == ctx->eb) {
1838 spin_unlock(&mapping->private_lock);
1841 ret = atomic_inc_not_zero(&eb->refs);
1842 spin_unlock(&mapping->private_lock);
1848 ret = btrfs_check_meta_write_pointer(eb->fs_info, ctx);
1852 free_extent_buffer(eb);
1856 if (!lock_extent_buffer_for_io(eb, wbc)) {
1857 free_extent_buffer(eb);
1860 /* Implies write in zoned mode. */
1861 if (ctx->zoned_bg) {
1862 /* Mark the last eb in the block group. */
1863 btrfs_schedule_zone_finish_bg(ctx->zoned_bg, eb);
1864 ctx->zoned_bg->meta_write_pointer += eb->len;
1866 write_one_eb(eb, wbc);
1867 free_extent_buffer(eb);
1871 int btree_write_cache_pages(struct address_space *mapping,
1872 struct writeback_control *wbc)
1874 struct btrfs_eb_write_context ctx = { .wbc = wbc };
1875 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
1878 int nr_to_write_done = 0;
1879 struct folio_batch fbatch;
1880 unsigned int nr_folios;
1882 pgoff_t end; /* Inclusive */
1886 folio_batch_init(&fbatch);
1887 if (wbc->range_cyclic) {
1888 index = mapping->writeback_index; /* Start from prev offset */
1891 * Start from the beginning does not need to cycle over the
1892 * range, mark it as scanned.
1894 scanned = (index == 0);
1896 index = wbc->range_start >> PAGE_SHIFT;
1897 end = wbc->range_end >> PAGE_SHIFT;
1900 if (wbc->sync_mode == WB_SYNC_ALL)
1901 tag = PAGECACHE_TAG_TOWRITE;
1903 tag = PAGECACHE_TAG_DIRTY;
1904 btrfs_zoned_meta_io_lock(fs_info);
1906 if (wbc->sync_mode == WB_SYNC_ALL)
1907 tag_pages_for_writeback(mapping, index, end);
1908 while (!done && !nr_to_write_done && (index <= end) &&
1909 (nr_folios = filemap_get_folios_tag(mapping, &index, end,
1913 for (i = 0; i < nr_folios; i++) {
1914 struct folio *folio = fbatch.folios[i];
1916 ret = submit_eb_page(&folio->page, &ctx);
1925 * the filesystem may choose to bump up nr_to_write.
1926 * We have to make sure to honor the new nr_to_write
1929 nr_to_write_done = wbc->nr_to_write <= 0;
1931 folio_batch_release(&fbatch);
1934 if (!scanned && !done) {
1936 * We hit the last page and there is more work to be done: wrap
1937 * back to the start of the file
1944 * If something went wrong, don't allow any metadata write bio to be
1947 * This would prevent use-after-free if we had dirty pages not
1948 * cleaned up, which can still happen by fuzzed images.
1951 * Allowing existing tree block to be allocated for other trees.
1953 * - Log tree operations
1954 * Exiting tree blocks get allocated to log tree, bumps its
1955 * generation, then get cleaned in tree re-balance.
1956 * Such tree block will not be written back, since it's clean,
1957 * thus no WRITTEN flag set.
1958 * And after log writes back, this tree block is not traced by
1959 * any dirty extent_io_tree.
1961 * - Offending tree block gets re-dirtied from its original owner
1962 * Since it has bumped generation, no WRITTEN flag, it can be
1963 * reused without COWing. This tree block will not be traced
1964 * by btrfs_transaction::dirty_pages.
1966 * Now such dirty tree block will not be cleaned by any dirty
1967 * extent io tree. Thus we don't want to submit such wild eb
1968 * if the fs already has error.
1970 * We can get ret > 0 from submit_extent_page() indicating how many ebs
1971 * were submitted. Reset it to 0 to avoid false alerts for the caller.
1975 if (!ret && BTRFS_FS_ERROR(fs_info))
1979 btrfs_put_block_group(ctx.zoned_bg);
1980 btrfs_zoned_meta_io_unlock(fs_info);
1985 * Walk the list of dirty pages of the given address space and write all of them.
1987 * @mapping: address space structure to write
1988 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
1989 * @bio_ctrl: holds context for the write, namely the bio
1991 * If a page is already under I/O, write_cache_pages() skips it, even
1992 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
1993 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
1994 * and msync() need to guarantee that all the data which was dirty at the time
1995 * the call was made get new I/O started against them. If wbc->sync_mode is
1996 * WB_SYNC_ALL then we were called for data integrity and we must wait for
1997 * existing IO to complete.
1999 static int extent_write_cache_pages(struct address_space *mapping,
2000 struct btrfs_bio_ctrl *bio_ctrl)
2002 struct writeback_control *wbc = bio_ctrl->wbc;
2003 struct inode *inode = mapping->host;
2006 int nr_to_write_done = 0;
2007 struct folio_batch fbatch;
2008 unsigned int nr_folios;
2010 pgoff_t end; /* Inclusive */
2012 int range_whole = 0;
2017 * We have to hold onto the inode so that ordered extents can do their
2018 * work when the IO finishes. The alternative to this is failing to add
2019 * an ordered extent if the igrab() fails there and that is a huge pain
2020 * to deal with, so instead just hold onto the inode throughout the
2021 * writepages operation. If it fails here we are freeing up the inode
2022 * anyway and we'd rather not waste our time writing out stuff that is
2023 * going to be truncated anyway.
2028 folio_batch_init(&fbatch);
2029 if (wbc->range_cyclic) {
2030 index = mapping->writeback_index; /* Start from prev offset */
2033 * Start from the beginning does not need to cycle over the
2034 * range, mark it as scanned.
2036 scanned = (index == 0);
2038 index = wbc->range_start >> PAGE_SHIFT;
2039 end = wbc->range_end >> PAGE_SHIFT;
2040 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2046 * We do the tagged writepage as long as the snapshot flush bit is set
2047 * and we are the first one who do the filemap_flush() on this inode.
2049 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
2050 * not race in and drop the bit.
2052 if (range_whole && wbc->nr_to_write == LONG_MAX &&
2053 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
2054 &BTRFS_I(inode)->runtime_flags))
2055 wbc->tagged_writepages = 1;
2057 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2058 tag = PAGECACHE_TAG_TOWRITE;
2060 tag = PAGECACHE_TAG_DIRTY;
2062 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2063 tag_pages_for_writeback(mapping, index, end);
2065 while (!done && !nr_to_write_done && (index <= end) &&
2066 (nr_folios = filemap_get_folios_tag(mapping, &index,
2067 end, tag, &fbatch))) {
2070 for (i = 0; i < nr_folios; i++) {
2071 struct folio *folio = fbatch.folios[i];
2073 done_index = folio_next_index(folio);
2075 * At this point we hold neither the i_pages lock nor
2076 * the page lock: the page may be truncated or
2077 * invalidated (changing page->mapping to NULL),
2078 * or even swizzled back from swapper_space to
2079 * tmpfs file mapping
2081 if (!folio_trylock(folio)) {
2082 submit_write_bio(bio_ctrl, 0);
2086 if (unlikely(folio->mapping != mapping)) {
2087 folio_unlock(folio);
2091 if (!folio_test_dirty(folio)) {
2092 /* Someone wrote it for us. */
2093 folio_unlock(folio);
2097 if (wbc->sync_mode != WB_SYNC_NONE) {
2098 if (folio_test_writeback(folio))
2099 submit_write_bio(bio_ctrl, 0);
2100 folio_wait_writeback(folio);
2103 if (folio_test_writeback(folio) ||
2104 !folio_clear_dirty_for_io(folio)) {
2105 folio_unlock(folio);
2109 ret = __extent_writepage(&folio->page, bio_ctrl);
2116 * The filesystem may choose to bump up nr_to_write.
2117 * We have to make sure to honor the new nr_to_write
2120 nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
2121 wbc->nr_to_write <= 0);
2123 folio_batch_release(&fbatch);
2126 if (!scanned && !done) {
2128 * We hit the last page and there is more work to be done: wrap
2129 * back to the start of the file
2135 * If we're looping we could run into a page that is locked by a
2136 * writer and that writer could be waiting on writeback for a
2137 * page in our current bio, and thus deadlock, so flush the
2140 submit_write_bio(bio_ctrl, 0);
2144 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
2145 mapping->writeback_index = done_index;
2147 btrfs_add_delayed_iput(BTRFS_I(inode));
2152 * Submit the pages in the range to bio for call sites which delalloc range has
2153 * already been ran (aka, ordered extent inserted) and all pages are still
2156 void extent_write_locked_range(struct inode *inode, struct page *locked_page,
2157 u64 start, u64 end, struct writeback_control *wbc,
2160 bool found_error = false;
2162 struct address_space *mapping = inode->i_mapping;
2163 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2164 const u32 sectorsize = fs_info->sectorsize;
2165 loff_t i_size = i_size_read(inode);
2167 struct btrfs_bio_ctrl bio_ctrl = {
2169 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2172 if (wbc->no_cgroup_owner)
2173 bio_ctrl.opf |= REQ_BTRFS_CGROUP_PUNT;
2175 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
2177 while (cur <= end) {
2178 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
2179 u32 cur_len = cur_end + 1 - cur;
2183 page = find_get_page(mapping, cur >> PAGE_SHIFT);
2184 ASSERT(PageLocked(page));
2185 if (pages_dirty && page != locked_page) {
2186 ASSERT(PageDirty(page));
2187 clear_page_dirty_for_io(page);
2190 ret = __extent_writepage_io(BTRFS_I(inode), page, &bio_ctrl,
2195 /* Make sure the mapping tag for page dirty gets cleared. */
2197 set_page_writeback(page);
2198 end_page_writeback(page);
2201 btrfs_mark_ordered_io_finished(BTRFS_I(inode), page,
2202 cur, cur_len, !ret);
2203 mapping_set_error(page->mapping, ret);
2205 btrfs_page_unlock_writer(fs_info, page, cur, cur_len);
2213 submit_write_bio(&bio_ctrl, found_error ? ret : 0);
2216 int extent_writepages(struct address_space *mapping,
2217 struct writeback_control *wbc)
2219 struct inode *inode = mapping->host;
2221 struct btrfs_bio_ctrl bio_ctrl = {
2223 .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2227 * Allow only a single thread to do the reloc work in zoned mode to
2228 * protect the write pointer updates.
2230 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
2231 ret = extent_write_cache_pages(mapping, &bio_ctrl);
2232 submit_write_bio(&bio_ctrl, ret);
2233 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
2237 void extent_readahead(struct readahead_control *rac)
2239 struct btrfs_bio_ctrl bio_ctrl = { .opf = REQ_OP_READ | REQ_RAHEAD };
2240 struct page *pagepool[16];
2241 struct extent_map *em_cached = NULL;
2242 u64 prev_em_start = (u64)-1;
2245 while ((nr = readahead_page_batch(rac, pagepool))) {
2246 u64 contig_start = readahead_pos(rac);
2247 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
2249 contiguous_readpages(pagepool, nr, contig_start, contig_end,
2250 &em_cached, &bio_ctrl, &prev_em_start);
2254 free_extent_map(em_cached);
2255 submit_one_bio(&bio_ctrl);
2259 * basic invalidate_folio code, this waits on any locked or writeback
2260 * ranges corresponding to the folio, and then deletes any extent state
2261 * records from the tree
2263 int extent_invalidate_folio(struct extent_io_tree *tree,
2264 struct folio *folio, size_t offset)
2266 struct extent_state *cached_state = NULL;
2267 u64 start = folio_pos(folio);
2268 u64 end = start + folio_size(folio) - 1;
2269 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
2271 /* This function is only called for the btree inode */
2272 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
2274 start += ALIGN(offset, blocksize);
2278 lock_extent(tree, start, end, &cached_state);
2279 folio_wait_writeback(folio);
2282 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
2283 * so here we only need to unlock the extent range to free any
2284 * existing extent state.
2286 unlock_extent(tree, start, end, &cached_state);
2291 * a helper for release_folio, this tests for areas of the page that
2292 * are locked or under IO and drops the related state bits if it is safe
2295 static int try_release_extent_state(struct extent_io_tree *tree,
2296 struct page *page, gfp_t mask)
2298 u64 start = page_offset(page);
2299 u64 end = start + PAGE_SIZE - 1;
2302 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
2305 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
2306 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS |
2307 EXTENT_QGROUP_RESERVED);
2310 * At this point we can safely clear everything except the
2311 * locked bit, the nodatasum bit and the delalloc new bit.
2312 * The delalloc new bit will be cleared by ordered extent
2315 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL, NULL);
2317 /* if clear_extent_bit failed for enomem reasons,
2318 * we can't allow the release to continue.
2329 * a helper for release_folio. As long as there are no locked extents
2330 * in the range corresponding to the page, both state records and extent
2331 * map records are removed
2333 int try_release_extent_mapping(struct page *page, gfp_t mask)
2335 struct extent_map *em;
2336 u64 start = page_offset(page);
2337 u64 end = start + PAGE_SIZE - 1;
2338 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
2339 struct extent_io_tree *tree = &btrfs_inode->io_tree;
2340 struct extent_map_tree *map = &btrfs_inode->extent_tree;
2342 if (gfpflags_allow_blocking(mask) &&
2343 page->mapping->host->i_size > SZ_16M) {
2345 while (start <= end) {
2346 struct btrfs_fs_info *fs_info;
2349 len = end - start + 1;
2350 write_lock(&map->lock);
2351 em = lookup_extent_mapping(map, start, len);
2353 write_unlock(&map->lock);
2356 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
2357 em->start != start) {
2358 write_unlock(&map->lock);
2359 free_extent_map(em);
2362 if (test_range_bit(tree, em->start,
2363 extent_map_end(em) - 1,
2364 EXTENT_LOCKED, 0, NULL))
2367 * If it's not in the list of modified extents, used
2368 * by a fast fsync, we can remove it. If it's being
2369 * logged we can safely remove it since fsync took an
2370 * extra reference on the em.
2372 if (list_empty(&em->list) ||
2373 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
2376 * If it's in the list of modified extents, remove it
2377 * only if its generation is older then the current one,
2378 * in which case we don't need it for a fast fsync.
2379 * Otherwise don't remove it, we could be racing with an
2380 * ongoing fast fsync that could miss the new extent.
2382 fs_info = btrfs_inode->root->fs_info;
2383 spin_lock(&fs_info->trans_lock);
2384 cur_gen = fs_info->generation;
2385 spin_unlock(&fs_info->trans_lock);
2386 if (em->generation >= cur_gen)
2390 * We only remove extent maps that are not in the list of
2391 * modified extents or that are in the list but with a
2392 * generation lower then the current generation, so there
2393 * is no need to set the full fsync flag on the inode (it
2394 * hurts the fsync performance for workloads with a data
2395 * size that exceeds or is close to the system's memory).
2397 remove_extent_mapping(map, em);
2398 /* once for the rb tree */
2399 free_extent_map(em);
2401 start = extent_map_end(em);
2402 write_unlock(&map->lock);
2405 free_extent_map(em);
2407 cond_resched(); /* Allow large-extent preemption. */
2410 return try_release_extent_state(tree, page, mask);
2414 * To cache previous fiemap extent
2416 * Will be used for merging fiemap extent
2418 struct fiemap_cache {
2427 * Helper to submit fiemap extent.
2429 * Will try to merge current fiemap extent specified by @offset, @phys,
2430 * @len and @flags with cached one.
2431 * And only when we fails to merge, cached one will be submitted as
2434 * Return value is the same as fiemap_fill_next_extent().
2436 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
2437 struct fiemap_cache *cache,
2438 u64 offset, u64 phys, u64 len, u32 flags)
2442 /* Set at the end of extent_fiemap(). */
2443 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
2449 * Sanity check, extent_fiemap() should have ensured that new
2450 * fiemap extent won't overlap with cached one.
2453 * NOTE: Physical address can overlap, due to compression
2455 if (cache->offset + cache->len > offset) {
2461 * Only merges fiemap extents if
2462 * 1) Their logical addresses are continuous
2464 * 2) Their physical addresses are continuous
2465 * So truly compressed (physical size smaller than logical size)
2466 * extents won't get merged with each other
2468 * 3) Share same flags
2470 if (cache->offset + cache->len == offset &&
2471 cache->phys + cache->len == phys &&
2472 cache->flags == flags) {
2477 /* Not mergeable, need to submit cached one */
2478 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
2479 cache->len, cache->flags);
2480 cache->cached = false;
2484 cache->cached = true;
2485 cache->offset = offset;
2488 cache->flags = flags;
2494 * Emit last fiemap cache
2496 * The last fiemap cache may still be cached in the following case:
2498 * |<- Fiemap range ->|
2499 * |<------------ First extent ----------->|
2501 * In this case, the first extent range will be cached but not emitted.
2502 * So we must emit it before ending extent_fiemap().
2504 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
2505 struct fiemap_cache *cache)
2512 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
2513 cache->len, cache->flags);
2514 cache->cached = false;
2520 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
2522 struct extent_buffer *clone;
2523 struct btrfs_key key;
2528 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
2531 ret = btrfs_next_leaf(inode->root, path);
2536 * Don't bother with cloning if there are no more file extent items for
2539 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2540 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
2543 /* See the comment at fiemap_search_slot() about why we clone. */
2544 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2548 slot = path->slots[0];
2549 btrfs_release_path(path);
2550 path->nodes[0] = clone;
2551 path->slots[0] = slot;
2557 * Search for the first file extent item that starts at a given file offset or
2558 * the one that starts immediately before that offset.
2559 * Returns: 0 on success, < 0 on error, 1 if not found.
2561 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
2564 const u64 ino = btrfs_ino(inode);
2565 struct btrfs_root *root = inode->root;
2566 struct extent_buffer *clone;
2567 struct btrfs_key key;
2572 key.type = BTRFS_EXTENT_DATA_KEY;
2573 key.offset = file_offset;
2575 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2579 if (ret > 0 && path->slots[0] > 0) {
2580 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
2581 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
2585 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2586 ret = btrfs_next_leaf(root, path);
2590 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2591 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
2596 * We clone the leaf and use it during fiemap. This is because while
2597 * using the leaf we do expensive things like checking if an extent is
2598 * shared, which can take a long time. In order to prevent blocking
2599 * other tasks for too long, we use a clone of the leaf. We have locked
2600 * the file range in the inode's io tree, so we know none of our file
2601 * extent items can change. This way we avoid blocking other tasks that
2602 * want to insert items for other inodes in the same leaf or b+tree
2603 * rebalance operations (triggered for example when someone is trying
2604 * to push items into this leaf when trying to insert an item in a
2606 * We also need the private clone because holding a read lock on an
2607 * extent buffer of the subvolume's b+tree will make lockdep unhappy
2608 * when we call fiemap_fill_next_extent(), because that may cause a page
2609 * fault when filling the user space buffer with fiemap data.
2611 clone = btrfs_clone_extent_buffer(path->nodes[0]);
2615 slot = path->slots[0];
2616 btrfs_release_path(path);
2617 path->nodes[0] = clone;
2618 path->slots[0] = slot;
2624 * Process a range which is a hole or a prealloc extent in the inode's subvolume
2625 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
2626 * extent. The end offset (@end) is inclusive.
2628 static int fiemap_process_hole(struct btrfs_inode *inode,
2629 struct fiemap_extent_info *fieinfo,
2630 struct fiemap_cache *cache,
2631 struct extent_state **delalloc_cached_state,
2632 struct btrfs_backref_share_check_ctx *backref_ctx,
2633 u64 disk_bytenr, u64 extent_offset,
2637 const u64 i_size = i_size_read(&inode->vfs_inode);
2638 u64 cur_offset = start;
2639 u64 last_delalloc_end = 0;
2640 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
2641 bool checked_extent_shared = false;
2645 * There can be no delalloc past i_size, so don't waste time looking for
2648 while (cur_offset < end && cur_offset < i_size) {
2652 u64 prealloc_len = 0;
2655 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
2656 delalloc_cached_state,
2663 * If this is a prealloc extent we have to report every section
2664 * of it that has no delalloc.
2666 if (disk_bytenr != 0) {
2667 if (last_delalloc_end == 0) {
2668 prealloc_start = start;
2669 prealloc_len = delalloc_start - start;
2671 prealloc_start = last_delalloc_end + 1;
2672 prealloc_len = delalloc_start - prealloc_start;
2676 if (prealloc_len > 0) {
2677 if (!checked_extent_shared && fieinfo->fi_extents_max) {
2678 ret = btrfs_is_data_extent_shared(inode,
2685 prealloc_flags |= FIEMAP_EXTENT_SHARED;
2687 checked_extent_shared = true;
2689 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
2690 disk_bytenr + extent_offset,
2691 prealloc_len, prealloc_flags);
2694 extent_offset += prealloc_len;
2697 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
2698 delalloc_end + 1 - delalloc_start,
2699 FIEMAP_EXTENT_DELALLOC |
2700 FIEMAP_EXTENT_UNKNOWN);
2704 last_delalloc_end = delalloc_end;
2705 cur_offset = delalloc_end + 1;
2706 extent_offset += cur_offset - delalloc_start;
2711 * Either we found no delalloc for the whole prealloc extent or we have
2712 * a prealloc extent that spans i_size or starts at or after i_size.
2714 if (disk_bytenr != 0 && last_delalloc_end < end) {
2718 if (last_delalloc_end == 0) {
2719 prealloc_start = start;
2720 prealloc_len = end + 1 - start;
2722 prealloc_start = last_delalloc_end + 1;
2723 prealloc_len = end + 1 - prealloc_start;
2726 if (!checked_extent_shared && fieinfo->fi_extents_max) {
2727 ret = btrfs_is_data_extent_shared(inode,
2734 prealloc_flags |= FIEMAP_EXTENT_SHARED;
2736 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
2737 disk_bytenr + extent_offset,
2738 prealloc_len, prealloc_flags);
2746 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
2747 struct btrfs_path *path,
2748 u64 *last_extent_end_ret)
2750 const u64 ino = btrfs_ino(inode);
2751 struct btrfs_root *root = inode->root;
2752 struct extent_buffer *leaf;
2753 struct btrfs_file_extent_item *ei;
2754 struct btrfs_key key;
2759 * Lookup the last file extent. We're not using i_size here because
2760 * there might be preallocation past i_size.
2762 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
2763 /* There can't be a file extent item at offset (u64)-1 */
2769 * For a non-existing key, btrfs_search_slot() always leaves us at a
2770 * slot > 0, except if the btree is empty, which is impossible because
2771 * at least it has the inode item for this inode and all the items for
2772 * the root inode 256.
2774 ASSERT(path->slots[0] > 0);
2776 leaf = path->nodes[0];
2777 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2778 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
2779 /* No file extent items in the subvolume tree. */
2780 *last_extent_end_ret = 0;
2785 * For an inline extent, the disk_bytenr is where inline data starts at,
2786 * so first check if we have an inline extent item before checking if we
2787 * have an implicit hole (disk_bytenr == 0).
2789 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
2790 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
2791 *last_extent_end_ret = btrfs_file_extent_end(path);
2796 * Find the last file extent item that is not a hole (when NO_HOLES is
2797 * not enabled). This should take at most 2 iterations in the worst
2798 * case: we have one hole file extent item at slot 0 of a leaf and
2799 * another hole file extent item as the last item in the previous leaf.
2800 * This is because we merge file extent items that represent holes.
2802 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
2803 while (disk_bytenr == 0) {
2804 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
2807 } else if (ret > 0) {
2808 /* No file extent items that are not holes. */
2809 *last_extent_end_ret = 0;
2812 leaf = path->nodes[0];
2813 ei = btrfs_item_ptr(leaf, path->slots[0],
2814 struct btrfs_file_extent_item);
2815 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
2818 *last_extent_end_ret = btrfs_file_extent_end(path);
2822 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
2825 const u64 ino = btrfs_ino(inode);
2826 struct extent_state *cached_state = NULL;
2827 struct extent_state *delalloc_cached_state = NULL;
2828 struct btrfs_path *path;
2829 struct fiemap_cache cache = { 0 };
2830 struct btrfs_backref_share_check_ctx *backref_ctx;
2831 u64 last_extent_end;
2832 u64 prev_extent_end;
2835 bool stopped = false;
2838 backref_ctx = btrfs_alloc_backref_share_check_ctx();
2839 path = btrfs_alloc_path();
2840 if (!backref_ctx || !path) {
2845 lockstart = round_down(start, inode->root->fs_info->sectorsize);
2846 lockend = round_up(start + len, inode->root->fs_info->sectorsize);
2847 prev_extent_end = lockstart;
2849 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
2850 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
2852 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
2855 btrfs_release_path(path);
2857 path->reada = READA_FORWARD;
2858 ret = fiemap_search_slot(inode, path, lockstart);
2861 } else if (ret > 0) {
2863 * No file extent item found, but we may have delalloc between
2864 * the current offset and i_size. So check for that.
2867 goto check_eof_delalloc;
2870 while (prev_extent_end < lockend) {
2871 struct extent_buffer *leaf = path->nodes[0];
2872 struct btrfs_file_extent_item *ei;
2873 struct btrfs_key key;
2876 u64 extent_offset = 0;
2878 u64 disk_bytenr = 0;
2883 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2884 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
2887 extent_end = btrfs_file_extent_end(path);
2890 * The first iteration can leave us at an extent item that ends
2891 * before our range's start. Move to the next item.
2893 if (extent_end <= lockstart)
2896 backref_ctx->curr_leaf_bytenr = leaf->start;
2898 /* We have in implicit hole (NO_HOLES feature enabled). */
2899 if (prev_extent_end < key.offset) {
2900 const u64 range_end = min(key.offset, lockend) - 1;
2902 ret = fiemap_process_hole(inode, fieinfo, &cache,
2903 &delalloc_cached_state,
2904 backref_ctx, 0, 0, 0,
2905 prev_extent_end, range_end);
2908 } else if (ret > 0) {
2909 /* fiemap_fill_next_extent() told us to stop. */
2914 /* We've reached the end of the fiemap range, stop. */
2915 if (key.offset >= lockend) {
2921 extent_len = extent_end - key.offset;
2922 ei = btrfs_item_ptr(leaf, path->slots[0],
2923 struct btrfs_file_extent_item);
2924 compression = btrfs_file_extent_compression(leaf, ei);
2925 extent_type = btrfs_file_extent_type(leaf, ei);
2926 extent_gen = btrfs_file_extent_generation(leaf, ei);
2928 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
2929 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
2930 if (compression == BTRFS_COMPRESS_NONE)
2931 extent_offset = btrfs_file_extent_offset(leaf, ei);
2934 if (compression != BTRFS_COMPRESS_NONE)
2935 flags |= FIEMAP_EXTENT_ENCODED;
2937 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
2938 flags |= FIEMAP_EXTENT_DATA_INLINE;
2939 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
2940 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
2942 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
2943 ret = fiemap_process_hole(inode, fieinfo, &cache,
2944 &delalloc_cached_state,
2946 disk_bytenr, extent_offset,
2947 extent_gen, key.offset,
2949 } else if (disk_bytenr == 0) {
2950 /* We have an explicit hole. */
2951 ret = fiemap_process_hole(inode, fieinfo, &cache,
2952 &delalloc_cached_state,
2953 backref_ctx, 0, 0, 0,
2954 key.offset, extent_end - 1);
2956 /* We have a regular extent. */
2957 if (fieinfo->fi_extents_max) {
2958 ret = btrfs_is_data_extent_shared(inode,
2965 flags |= FIEMAP_EXTENT_SHARED;
2968 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
2969 disk_bytenr + extent_offset,
2975 } else if (ret > 0) {
2976 /* fiemap_fill_next_extent() told us to stop. */
2981 prev_extent_end = extent_end;
2983 if (fatal_signal_pending(current)) {
2988 ret = fiemap_next_leaf_item(inode, path);
2991 } else if (ret > 0) {
2992 /* No more file extent items for this inode. */
3000 * Release (and free) the path before emitting any final entries to
3001 * fiemap_fill_next_extent() to keep lockdep happy. This is because
3002 * once we find no more file extent items exist, we may have a
3003 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
3004 * faults when copying data to the user space buffer.
3006 btrfs_free_path(path);
3009 if (!stopped && prev_extent_end < lockend) {
3010 ret = fiemap_process_hole(inode, fieinfo, &cache,
3011 &delalloc_cached_state, backref_ctx,
3012 0, 0, 0, prev_extent_end, lockend - 1);
3015 prev_extent_end = lockend;
3018 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
3019 const u64 i_size = i_size_read(&inode->vfs_inode);
3021 if (prev_extent_end < i_size) {
3026 delalloc = btrfs_find_delalloc_in_range(inode,
3029 &delalloc_cached_state,
3033 cache.flags |= FIEMAP_EXTENT_LAST;
3035 cache.flags |= FIEMAP_EXTENT_LAST;
3039 ret = emit_last_fiemap_cache(fieinfo, &cache);
3042 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3043 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
3045 free_extent_state(delalloc_cached_state);
3046 btrfs_free_backref_share_ctx(backref_ctx);
3047 btrfs_free_path(path);
3051 static void __free_extent_buffer(struct extent_buffer *eb)
3053 kmem_cache_free(extent_buffer_cache, eb);
3056 static int extent_buffer_under_io(const struct extent_buffer *eb)
3058 return (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
3059 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3062 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
3064 struct btrfs_subpage *subpage;
3066 lockdep_assert_held(&page->mapping->private_lock);
3068 if (PagePrivate(page)) {
3069 subpage = (struct btrfs_subpage *)page->private;
3070 if (atomic_read(&subpage->eb_refs))
3073 * Even there is no eb refs here, we may still have
3074 * end_page_read() call relying on page::private.
3076 if (atomic_read(&subpage->readers))
3082 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
3084 struct btrfs_fs_info *fs_info = eb->fs_info;
3085 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3088 * For mapped eb, we're going to change the page private, which should
3089 * be done under the private_lock.
3092 spin_lock(&page->mapping->private_lock);
3094 if (!PagePrivate(page)) {
3096 spin_unlock(&page->mapping->private_lock);
3100 if (fs_info->nodesize >= PAGE_SIZE) {
3102 * We do this since we'll remove the pages after we've
3103 * removed the eb from the radix tree, so we could race
3104 * and have this page now attached to the new eb. So
3105 * only clear page_private if it's still connected to
3108 if (PagePrivate(page) &&
3109 page->private == (unsigned long)eb) {
3110 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
3111 BUG_ON(PageDirty(page));
3112 BUG_ON(PageWriteback(page));
3114 * We need to make sure we haven't be attached
3117 detach_page_private(page);
3120 spin_unlock(&page->mapping->private_lock);
3125 * For subpage, we can have dummy eb with page private. In this case,
3126 * we can directly detach the private as such page is only attached to
3127 * one dummy eb, no sharing.
3130 btrfs_detach_subpage(fs_info, page);
3134 btrfs_page_dec_eb_refs(fs_info, page);
3137 * We can only detach the page private if there are no other ebs in the
3138 * page range and no unfinished IO.
3140 if (!page_range_has_eb(fs_info, page))
3141 btrfs_detach_subpage(fs_info, page);
3143 spin_unlock(&page->mapping->private_lock);
3146 /* Release all pages attached to the extent buffer */
3147 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
3152 ASSERT(!extent_buffer_under_io(eb));
3154 num_pages = num_extent_pages(eb);
3155 for (i = 0; i < num_pages; i++) {
3156 struct page *page = eb->pages[i];
3161 detach_extent_buffer_page(eb, page);
3163 /* One for when we allocated the page */
3169 * Helper for releasing the extent buffer.
3171 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
3173 btrfs_release_extent_buffer_pages(eb);
3174 btrfs_leak_debug_del_eb(eb);
3175 __free_extent_buffer(eb);
3178 static struct extent_buffer *
3179 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
3182 struct extent_buffer *eb = NULL;
3184 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
3187 eb->fs_info = fs_info;
3188 init_rwsem(&eb->lock);
3190 btrfs_leak_debug_add_eb(eb);
3192 spin_lock_init(&eb->refs_lock);
3193 atomic_set(&eb->refs, 1);
3195 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
3200 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
3203 struct extent_buffer *new;
3204 int num_pages = num_extent_pages(src);
3207 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
3212 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
3213 * btrfs_release_extent_buffer() have different behavior for
3214 * UNMAPPED subpage extent buffer.
3216 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
3218 ret = btrfs_alloc_page_array(num_pages, new->pages);
3220 btrfs_release_extent_buffer(new);
3224 for (i = 0; i < num_pages; i++) {
3226 struct page *p = new->pages[i];
3228 ret = attach_extent_buffer_page(new, p, NULL);
3230 btrfs_release_extent_buffer(new);
3233 WARN_ON(PageDirty(p));
3235 copy_extent_buffer_full(new, src);
3236 set_extent_buffer_uptodate(new);
3241 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3242 u64 start, unsigned long len)
3244 struct extent_buffer *eb;
3249 eb = __alloc_extent_buffer(fs_info, start, len);
3253 num_pages = num_extent_pages(eb);
3254 ret = btrfs_alloc_page_array(num_pages, eb->pages);
3258 for (i = 0; i < num_pages; i++) {
3259 struct page *p = eb->pages[i];
3261 ret = attach_extent_buffer_page(eb, p, NULL);
3266 set_extent_buffer_uptodate(eb);
3267 btrfs_set_header_nritems(eb, 0);
3268 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3272 for (i = 0; i < num_pages; i++) {
3274 detach_extent_buffer_page(eb, eb->pages[i]);
3275 __free_page(eb->pages[i]);
3278 __free_extent_buffer(eb);
3282 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3285 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
3288 static void check_buffer_tree_ref(struct extent_buffer *eb)
3292 * The TREE_REF bit is first set when the extent_buffer is added
3293 * to the radix tree. It is also reset, if unset, when a new reference
3294 * is created by find_extent_buffer.
3296 * It is only cleared in two cases: freeing the last non-tree
3297 * reference to the extent_buffer when its STALE bit is set or
3298 * calling release_folio when the tree reference is the only reference.
3300 * In both cases, care is taken to ensure that the extent_buffer's
3301 * pages are not under io. However, release_folio can be concurrently
3302 * called with creating new references, which is prone to race
3303 * conditions between the calls to check_buffer_tree_ref in those
3304 * codepaths and clearing TREE_REF in try_release_extent_buffer.
3306 * The actual lifetime of the extent_buffer in the radix tree is
3307 * adequately protected by the refcount, but the TREE_REF bit and
3308 * its corresponding reference are not. To protect against this
3309 * class of races, we call check_buffer_tree_ref from the codepaths
3310 * which trigger io. Note that once io is initiated, TREE_REF can no
3311 * longer be cleared, so that is the moment at which any such race is
3314 refs = atomic_read(&eb->refs);
3315 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3318 spin_lock(&eb->refs_lock);
3319 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3320 atomic_inc(&eb->refs);
3321 spin_unlock(&eb->refs_lock);
3324 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
3325 struct page *accessed)
3329 check_buffer_tree_ref(eb);
3331 num_pages = num_extent_pages(eb);
3332 for (i = 0; i < num_pages; i++) {
3333 struct page *p = eb->pages[i];
3336 mark_page_accessed(p);
3340 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
3343 struct extent_buffer *eb;
3345 eb = find_extent_buffer_nolock(fs_info, start);
3349 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
3350 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
3351 * another task running free_extent_buffer() might have seen that flag
3352 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
3353 * writeback flags not set) and it's still in the tree (flag
3354 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
3355 * decrementing the extent buffer's reference count twice. So here we
3356 * could race and increment the eb's reference count, clear its stale
3357 * flag, mark it as dirty and drop our reference before the other task
3358 * finishes executing free_extent_buffer, which would later result in
3359 * an attempt to free an extent buffer that is dirty.
3361 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
3362 spin_lock(&eb->refs_lock);
3363 spin_unlock(&eb->refs_lock);
3365 mark_extent_buffer_accessed(eb, NULL);
3369 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3370 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
3373 struct extent_buffer *eb, *exists = NULL;
3376 eb = find_extent_buffer(fs_info, start);
3379 eb = alloc_dummy_extent_buffer(fs_info, start);
3381 return ERR_PTR(-ENOMEM);
3382 eb->fs_info = fs_info;
3384 ret = radix_tree_preload(GFP_NOFS);
3386 exists = ERR_PTR(ret);
3389 spin_lock(&fs_info->buffer_lock);
3390 ret = radix_tree_insert(&fs_info->buffer_radix,
3391 start >> fs_info->sectorsize_bits, eb);
3392 spin_unlock(&fs_info->buffer_lock);
3393 radix_tree_preload_end();
3394 if (ret == -EEXIST) {
3395 exists = find_extent_buffer(fs_info, start);
3401 check_buffer_tree_ref(eb);
3402 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3406 btrfs_release_extent_buffer(eb);
3411 static struct extent_buffer *grab_extent_buffer(
3412 struct btrfs_fs_info *fs_info, struct page *page)
3414 struct extent_buffer *exists;
3417 * For subpage case, we completely rely on radix tree to ensure we
3418 * don't try to insert two ebs for the same bytenr. So here we always
3419 * return NULL and just continue.
3421 if (fs_info->nodesize < PAGE_SIZE)
3424 /* Page not yet attached to an extent buffer */
3425 if (!PagePrivate(page))
3429 * We could have already allocated an eb for this page and attached one
3430 * so lets see if we can get a ref on the existing eb, and if we can we
3431 * know it's good and we can just return that one, else we know we can
3432 * just overwrite page->private.
3434 exists = (struct extent_buffer *)page->private;
3435 if (atomic_inc_not_zero(&exists->refs))
3438 WARN_ON(PageDirty(page));
3439 detach_page_private(page);
3443 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
3445 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
3446 btrfs_err(fs_info, "bad tree block start %llu", start);
3450 if (fs_info->nodesize < PAGE_SIZE &&
3451 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
3453 "tree block crosses page boundary, start %llu nodesize %u",
3454 start, fs_info->nodesize);
3457 if (fs_info->nodesize >= PAGE_SIZE &&
3458 !PAGE_ALIGNED(start)) {
3460 "tree block is not page aligned, start %llu nodesize %u",
3461 start, fs_info->nodesize);
3467 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3468 u64 start, u64 owner_root, int level)
3470 unsigned long len = fs_info->nodesize;
3473 unsigned long index = start >> PAGE_SHIFT;
3474 struct extent_buffer *eb;
3475 struct extent_buffer *exists = NULL;
3477 struct address_space *mapping = fs_info->btree_inode->i_mapping;
3478 struct btrfs_subpage *prealloc = NULL;
3479 u64 lockdep_owner = owner_root;
3483 if (check_eb_alignment(fs_info, start))
3484 return ERR_PTR(-EINVAL);
3486 #if BITS_PER_LONG == 32
3487 if (start >= MAX_LFS_FILESIZE) {
3488 btrfs_err_rl(fs_info,
3489 "extent buffer %llu is beyond 32bit page cache limit", start);
3490 btrfs_err_32bit_limit(fs_info);
3491 return ERR_PTR(-EOVERFLOW);
3493 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
3494 btrfs_warn_32bit_limit(fs_info);
3497 eb = find_extent_buffer(fs_info, start);
3501 eb = __alloc_extent_buffer(fs_info, start, len);
3503 return ERR_PTR(-ENOMEM);
3506 * The reloc trees are just snapshots, so we need them to appear to be
3507 * just like any other fs tree WRT lockdep.
3509 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
3510 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
3512 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
3514 num_pages = num_extent_pages(eb);
3517 * Preallocate page->private for subpage case, so that we won't
3518 * allocate memory with private_lock nor page lock hold.
3520 * The memory will be freed by attach_extent_buffer_page() or freed
3521 * manually if we exit earlier.
3523 if (fs_info->nodesize < PAGE_SIZE) {
3524 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
3525 if (IS_ERR(prealloc)) {
3526 exists = ERR_CAST(prealloc);
3531 for (i = 0; i < num_pages; i++, index++) {
3532 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
3534 exists = ERR_PTR(-ENOMEM);
3535 btrfs_free_subpage(prealloc);
3539 spin_lock(&mapping->private_lock);
3540 exists = grab_extent_buffer(fs_info, p);
3542 spin_unlock(&mapping->private_lock);
3545 mark_extent_buffer_accessed(exists, p);
3546 btrfs_free_subpage(prealloc);
3549 /* Should not fail, as we have preallocated the memory */
3550 ret = attach_extent_buffer_page(eb, p, prealloc);
3553 * To inform we have extra eb under allocation, so that
3554 * detach_extent_buffer_page() won't release the page private
3555 * when the eb hasn't yet been inserted into radix tree.
3557 * The ref will be decreased when the eb released the page, in
3558 * detach_extent_buffer_page().
3559 * Thus needs no special handling in error path.
3561 btrfs_page_inc_eb_refs(fs_info, p);
3562 spin_unlock(&mapping->private_lock);
3564 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
3566 if (!btrfs_page_test_uptodate(fs_info, p, eb->start, eb->len))
3570 * We can't unlock the pages just yet since the extent buffer
3571 * hasn't been properly inserted in the radix tree, this
3572 * opens a race with btree_release_folio which can free a page
3573 * while we are still filling in all pages for the buffer and
3578 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3580 ret = radix_tree_preload(GFP_NOFS);
3582 exists = ERR_PTR(ret);
3586 spin_lock(&fs_info->buffer_lock);
3587 ret = radix_tree_insert(&fs_info->buffer_radix,
3588 start >> fs_info->sectorsize_bits, eb);
3589 spin_unlock(&fs_info->buffer_lock);
3590 radix_tree_preload_end();
3591 if (ret == -EEXIST) {
3592 exists = find_extent_buffer(fs_info, start);
3598 /* add one reference for the tree */
3599 check_buffer_tree_ref(eb);
3600 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
3603 * Now it's safe to unlock the pages because any calls to
3604 * btree_release_folio will correctly detect that a page belongs to a
3605 * live buffer and won't free them prematurely.
3607 for (i = 0; i < num_pages; i++)
3608 unlock_page(eb->pages[i]);
3612 WARN_ON(!atomic_dec_and_test(&eb->refs));
3613 for (i = 0; i < num_pages; i++) {
3615 unlock_page(eb->pages[i]);
3618 btrfs_release_extent_buffer(eb);
3622 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
3624 struct extent_buffer *eb =
3625 container_of(head, struct extent_buffer, rcu_head);
3627 __free_extent_buffer(eb);
3630 static int release_extent_buffer(struct extent_buffer *eb)
3631 __releases(&eb->refs_lock)
3633 lockdep_assert_held(&eb->refs_lock);
3635 WARN_ON(atomic_read(&eb->refs) == 0);
3636 if (atomic_dec_and_test(&eb->refs)) {
3637 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
3638 struct btrfs_fs_info *fs_info = eb->fs_info;
3640 spin_unlock(&eb->refs_lock);
3642 spin_lock(&fs_info->buffer_lock);
3643 radix_tree_delete(&fs_info->buffer_radix,
3644 eb->start >> fs_info->sectorsize_bits);
3645 spin_unlock(&fs_info->buffer_lock);
3647 spin_unlock(&eb->refs_lock);
3650 btrfs_leak_debug_del_eb(eb);
3651 /* Should be safe to release our pages at this point */
3652 btrfs_release_extent_buffer_pages(eb);
3653 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3654 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
3655 __free_extent_buffer(eb);
3659 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
3662 spin_unlock(&eb->refs_lock);
3667 void free_extent_buffer(struct extent_buffer *eb)
3673 refs = atomic_read(&eb->refs);
3675 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
3676 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
3679 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
3683 spin_lock(&eb->refs_lock);
3684 if (atomic_read(&eb->refs) == 2 &&
3685 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
3686 !extent_buffer_under_io(eb) &&
3687 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3688 atomic_dec(&eb->refs);
3691 * I know this is terrible, but it's temporary until we stop tracking
3692 * the uptodate bits and such for the extent buffers.
3694 release_extent_buffer(eb);
3697 void free_extent_buffer_stale(struct extent_buffer *eb)
3702 spin_lock(&eb->refs_lock);
3703 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
3705 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
3706 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3707 atomic_dec(&eb->refs);
3708 release_extent_buffer(eb);
3711 static void btree_clear_page_dirty(struct page *page)
3713 ASSERT(PageDirty(page));
3714 ASSERT(PageLocked(page));
3715 clear_page_dirty_for_io(page);
3716 xa_lock_irq(&page->mapping->i_pages);
3717 if (!PageDirty(page))
3718 __xa_clear_mark(&page->mapping->i_pages,
3719 page_index(page), PAGECACHE_TAG_DIRTY);
3720 xa_unlock_irq(&page->mapping->i_pages);
3723 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
3725 struct btrfs_fs_info *fs_info = eb->fs_info;
3726 struct page *page = eb->pages[0];
3729 /* btree_clear_page_dirty() needs page locked */
3731 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
3734 btree_clear_page_dirty(page);
3736 WARN_ON(atomic_read(&eb->refs) == 0);
3739 void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
3740 struct extent_buffer *eb)
3742 struct btrfs_fs_info *fs_info = eb->fs_info;
3747 btrfs_assert_tree_write_locked(eb);
3749 if (trans && btrfs_header_generation(eb) != trans->transid)
3752 if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
3755 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
3756 fs_info->dirty_metadata_batch);
3758 if (eb->fs_info->nodesize < PAGE_SIZE)
3759 return clear_subpage_extent_buffer_dirty(eb);
3761 num_pages = num_extent_pages(eb);
3763 for (i = 0; i < num_pages; i++) {
3764 page = eb->pages[i];
3765 if (!PageDirty(page))
3768 btree_clear_page_dirty(page);
3771 WARN_ON(atomic_read(&eb->refs) == 0);
3774 void set_extent_buffer_dirty(struct extent_buffer *eb)
3780 check_buffer_tree_ref(eb);
3782 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3784 num_pages = num_extent_pages(eb);
3785 WARN_ON(atomic_read(&eb->refs) == 0);
3786 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
3789 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
3792 * For subpage case, we can have other extent buffers in the
3793 * same page, and in clear_subpage_extent_buffer_dirty() we
3794 * have to clear page dirty without subpage lock held.
3795 * This can cause race where our page gets dirty cleared after
3798 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
3799 * its page for other reasons, we can use page lock to prevent
3803 lock_page(eb->pages[0]);
3804 for (i = 0; i < num_pages; i++)
3805 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
3806 eb->start, eb->len);
3808 unlock_page(eb->pages[0]);
3809 percpu_counter_add_batch(&eb->fs_info->dirty_metadata_bytes,
3811 eb->fs_info->dirty_metadata_batch);
3813 #ifdef CONFIG_BTRFS_DEBUG
3814 for (i = 0; i < num_pages; i++)
3815 ASSERT(PageDirty(eb->pages[i]));
3819 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
3821 struct btrfs_fs_info *fs_info = eb->fs_info;
3826 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3827 num_pages = num_extent_pages(eb);
3828 for (i = 0; i < num_pages; i++) {
3829 page = eb->pages[i];
3834 * This is special handling for metadata subpage, as regular
3835 * btrfs_is_subpage() can not handle cloned/dummy metadata.
3837 if (fs_info->nodesize >= PAGE_SIZE)
3838 ClearPageUptodate(page);
3840 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
3845 void set_extent_buffer_uptodate(struct extent_buffer *eb)
3847 struct btrfs_fs_info *fs_info = eb->fs_info;
3852 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3853 num_pages = num_extent_pages(eb);
3854 for (i = 0; i < num_pages; i++) {
3855 page = eb->pages[i];
3858 * This is special handling for metadata subpage, as regular
3859 * btrfs_is_subpage() can not handle cloned/dummy metadata.
3861 if (fs_info->nodesize >= PAGE_SIZE)
3862 SetPageUptodate(page);
3864 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
3869 static void extent_buffer_read_end_io(struct btrfs_bio *bbio)
3871 struct extent_buffer *eb = bbio->private;
3872 struct btrfs_fs_info *fs_info = eb->fs_info;
3873 bool uptodate = !bbio->bio.bi_status;
3874 struct bvec_iter_all iter_all;
3875 struct bio_vec *bvec;
3878 eb->read_mirror = bbio->mirror_num;
3881 btrfs_validate_extent_buffer(eb, &bbio->parent_check) < 0)
3885 set_extent_buffer_uptodate(eb);
3887 clear_extent_buffer_uptodate(eb);
3888 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3891 bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
3892 u64 start = eb->start + bio_offset;
3893 struct page *page = bvec->bv_page;
3894 u32 len = bvec->bv_len;
3897 btrfs_page_set_uptodate(fs_info, page, start, len);
3899 btrfs_page_clear_uptodate(fs_info, page, start, len);
3904 clear_bit(EXTENT_BUFFER_READING, &eb->bflags);
3905 smp_mb__after_atomic();
3906 wake_up_bit(&eb->bflags, EXTENT_BUFFER_READING);
3907 free_extent_buffer(eb);
3909 bio_put(&bbio->bio);
3912 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
3913 struct btrfs_tree_parent_check *check)
3915 int num_pages = num_extent_pages(eb), i;
3916 struct btrfs_bio *bbio;
3918 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
3922 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
3923 * operation, which could potentially still be in flight. In this case
3924 * we simply want to return an error.
3926 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
3929 /* Someone else is already reading the buffer, just wait for it. */
3930 if (test_and_set_bit(EXTENT_BUFFER_READING, &eb->bflags))
3933 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3934 eb->read_mirror = 0;
3935 check_buffer_tree_ref(eb);
3936 atomic_inc(&eb->refs);
3938 bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
3939 REQ_OP_READ | REQ_META, eb->fs_info,
3940 extent_buffer_read_end_io, eb);
3941 bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
3942 bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
3943 bbio->file_offset = eb->start;
3944 memcpy(&bbio->parent_check, check, sizeof(*check));
3945 if (eb->fs_info->nodesize < PAGE_SIZE) {
3946 __bio_add_page(&bbio->bio, eb->pages[0], eb->len,
3947 eb->start - page_offset(eb->pages[0]));
3949 for (i = 0; i < num_pages; i++)
3950 __bio_add_page(&bbio->bio, eb->pages[i], PAGE_SIZE, 0);
3952 btrfs_submit_bio(bbio, mirror_num);
3955 if (wait == WAIT_COMPLETE) {
3956 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_READING, TASK_UNINTERRUPTIBLE);
3957 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
3964 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
3967 btrfs_warn(eb->fs_info,
3968 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
3969 eb->start, eb->len, start, len);
3970 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
3976 * Check if the [start, start + len) range is valid before reading/writing
3978 * NOTE: @start and @len are offset inside the eb, not logical address.
3980 * Caller should not touch the dst/src memory if this function returns error.
3982 static inline int check_eb_range(const struct extent_buffer *eb,
3983 unsigned long start, unsigned long len)
3985 unsigned long offset;
3987 /* start, start + len should not go beyond eb->len nor overflow */
3988 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
3989 return report_eb_range(eb, start, len);
3994 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
3995 unsigned long start, unsigned long len)
4001 char *dst = (char *)dstv;
4002 unsigned long i = get_eb_page_index(start);
4004 if (check_eb_range(eb, start, len)) {
4006 * Invalid range hit, reset the memory, so callers won't get
4007 * some random garbage for their uninitialzed memory.
4009 memset(dstv, 0, len);
4013 offset = get_eb_offset_in_page(eb, start);
4016 page = eb->pages[i];
4018 cur = min(len, (PAGE_SIZE - offset));
4019 kaddr = page_address(page);
4020 memcpy(dst, kaddr + offset, cur);
4029 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
4031 unsigned long start, unsigned long len)
4037 char __user *dst = (char __user *)dstv;
4038 unsigned long i = get_eb_page_index(start);
4041 WARN_ON(start > eb->len);
4042 WARN_ON(start + len > eb->start + eb->len);
4044 offset = get_eb_offset_in_page(eb, start);
4047 page = eb->pages[i];
4049 cur = min(len, (PAGE_SIZE - offset));
4050 kaddr = page_address(page);
4051 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
4065 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
4066 unsigned long start, unsigned long len)
4072 char *ptr = (char *)ptrv;
4073 unsigned long i = get_eb_page_index(start);
4076 if (check_eb_range(eb, start, len))
4079 offset = get_eb_offset_in_page(eb, start);
4082 page = eb->pages[i];
4084 cur = min(len, (PAGE_SIZE - offset));
4086 kaddr = page_address(page);
4087 ret = memcmp(ptr, kaddr + offset, cur);
4100 * Check that the extent buffer is uptodate.
4102 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
4103 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
4105 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
4108 struct btrfs_fs_info *fs_info = eb->fs_info;
4111 * If we are using the commit root we could potentially clear a page
4112 * Uptodate while we're using the extent buffer that we've previously
4113 * looked up. We don't want to complain in this case, as the page was
4114 * valid before, we just didn't write it out. Instead we want to catch
4115 * the case where we didn't actually read the block properly, which
4116 * would have !PageUptodate and !EXTENT_BUFFER_WRITE_ERR.
4118 if (test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4121 if (fs_info->nodesize < PAGE_SIZE) {
4122 if (WARN_ON(!btrfs_subpage_test_uptodate(fs_info, page,
4123 eb->start, eb->len)))
4124 btrfs_subpage_dump_bitmap(fs_info, page, eb->start, eb->len);
4126 WARN_ON(!PageUptodate(page));
4130 static void __write_extent_buffer(const struct extent_buffer *eb,
4131 const void *srcv, unsigned long start,
4132 unsigned long len, bool use_memmove)
4138 char *src = (char *)srcv;
4139 unsigned long i = get_eb_page_index(start);
4140 /* For unmapped (dummy) ebs, no need to check their uptodate status. */
4141 const bool check_uptodate = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4143 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
4145 if (check_eb_range(eb, start, len))
4148 offset = get_eb_offset_in_page(eb, start);
4151 page = eb->pages[i];
4153 assert_eb_page_uptodate(eb, page);
4155 cur = min(len, PAGE_SIZE - offset);
4156 kaddr = page_address(page);
4158 memmove(kaddr + offset, src, cur);
4160 memcpy(kaddr + offset, src, cur);
4169 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
4170 unsigned long start, unsigned long len)
4172 return __write_extent_buffer(eb, srcv, start, len, false);
4175 static void memset_extent_buffer(const struct extent_buffer *eb, int c,
4176 unsigned long start, unsigned long len)
4178 unsigned long cur = start;
4180 while (cur < start + len) {
4181 unsigned long index = get_eb_page_index(cur);
4182 unsigned int offset = get_eb_offset_in_page(eb, cur);
4183 unsigned int cur_len = min(start + len - cur, PAGE_SIZE - offset);
4184 struct page *page = eb->pages[index];
4186 assert_eb_page_uptodate(eb, page);
4187 memset(page_address(page) + offset, c, cur_len);
4193 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
4196 if (check_eb_range(eb, start, len))
4198 return memset_extent_buffer(eb, 0, start, len);
4201 void copy_extent_buffer_full(const struct extent_buffer *dst,
4202 const struct extent_buffer *src)
4204 unsigned long cur = 0;
4206 ASSERT(dst->len == src->len);
4208 while (cur < src->len) {
4209 unsigned long index = get_eb_page_index(cur);
4210 unsigned long offset = get_eb_offset_in_page(src, cur);
4211 unsigned long cur_len = min(src->len, PAGE_SIZE - offset);
4212 void *addr = page_address(src->pages[index]) + offset;
4214 write_extent_buffer(dst, addr, cur, cur_len);
4220 void copy_extent_buffer(const struct extent_buffer *dst,
4221 const struct extent_buffer *src,
4222 unsigned long dst_offset, unsigned long src_offset,
4225 u64 dst_len = dst->len;
4230 unsigned long i = get_eb_page_index(dst_offset);
4232 if (check_eb_range(dst, dst_offset, len) ||
4233 check_eb_range(src, src_offset, len))
4236 WARN_ON(src->len != dst_len);
4238 offset = get_eb_offset_in_page(dst, dst_offset);
4241 page = dst->pages[i];
4242 assert_eb_page_uptodate(dst, page);
4244 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
4246 kaddr = page_address(page);
4247 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4257 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
4259 * @eb: the extent buffer
4260 * @start: offset of the bitmap item in the extent buffer
4262 * @page_index: return index of the page in the extent buffer that contains the
4264 * @page_offset: return offset into the page given by page_index
4266 * This helper hides the ugliness of finding the byte in an extent buffer which
4267 * contains a given bit.
4269 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
4270 unsigned long start, unsigned long nr,
4271 unsigned long *page_index,
4272 size_t *page_offset)
4274 size_t byte_offset = BIT_BYTE(nr);
4278 * The byte we want is the offset of the extent buffer + the offset of
4279 * the bitmap item in the extent buffer + the offset of the byte in the
4282 offset = start + offset_in_page(eb->start) + byte_offset;
4284 *page_index = offset >> PAGE_SHIFT;
4285 *page_offset = offset_in_page(offset);
4289 * Determine whether a bit in a bitmap item is set.
4291 * @eb: the extent buffer
4292 * @start: offset of the bitmap item in the extent buffer
4293 * @nr: bit number to test
4295 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
4303 eb_bitmap_offset(eb, start, nr, &i, &offset);
4304 page = eb->pages[i];
4305 assert_eb_page_uptodate(eb, page);
4306 kaddr = page_address(page);
4307 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
4310 static u8 *extent_buffer_get_byte(const struct extent_buffer *eb, unsigned long bytenr)
4312 unsigned long index = get_eb_page_index(bytenr);
4314 if (check_eb_range(eb, bytenr, 1))
4316 return page_address(eb->pages[index]) + get_eb_offset_in_page(eb, bytenr);
4320 * Set an area of a bitmap to 1.
4322 * @eb: the extent buffer
4323 * @start: offset of the bitmap item in the extent buffer
4324 * @pos: bit number of the first bit
4325 * @len: number of bits to set
4327 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
4328 unsigned long pos, unsigned long len)
4330 unsigned int first_byte = start + BIT_BYTE(pos);
4331 unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4332 const bool same_byte = (first_byte == last_byte);
4333 u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4337 mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4339 /* Handle the first byte. */
4340 kaddr = extent_buffer_get_byte(eb, first_byte);
4345 /* Handle the byte aligned part. */
4346 ASSERT(first_byte + 1 <= last_byte);
4347 memset_extent_buffer(eb, 0xff, first_byte + 1, last_byte - first_byte - 1);
4349 /* Handle the last byte. */
4350 kaddr = extent_buffer_get_byte(eb, last_byte);
4351 *kaddr |= BITMAP_LAST_BYTE_MASK(pos + len);
4356 * Clear an area of a bitmap.
4358 * @eb: the extent buffer
4359 * @start: offset of the bitmap item in the extent buffer
4360 * @pos: bit number of the first bit
4361 * @len: number of bits to clear
4363 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
4364 unsigned long start, unsigned long pos,
4367 unsigned int first_byte = start + BIT_BYTE(pos);
4368 unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4369 const bool same_byte = (first_byte == last_byte);
4370 u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4374 mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4376 /* Handle the first byte. */
4377 kaddr = extent_buffer_get_byte(eb, first_byte);
4382 /* Handle the byte aligned part. */
4383 ASSERT(first_byte + 1 <= last_byte);
4384 memset_extent_buffer(eb, 0, first_byte + 1, last_byte - first_byte - 1);
4386 /* Handle the last byte. */
4387 kaddr = extent_buffer_get_byte(eb, last_byte);
4388 *kaddr &= ~BITMAP_LAST_BYTE_MASK(pos + len);
4391 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4393 unsigned long distance = (src > dst) ? src - dst : dst - src;
4394 return distance < len;
4397 void memcpy_extent_buffer(const struct extent_buffer *dst,
4398 unsigned long dst_offset, unsigned long src_offset,
4401 unsigned long cur_off = 0;
4403 if (check_eb_range(dst, dst_offset, len) ||
4404 check_eb_range(dst, src_offset, len))
4407 while (cur_off < len) {
4408 unsigned long cur_src = cur_off + src_offset;
4409 unsigned long pg_index = get_eb_page_index(cur_src);
4410 unsigned long pg_off = get_eb_offset_in_page(dst, cur_src);
4411 unsigned long cur_len = min(src_offset + len - cur_src,
4412 PAGE_SIZE - pg_off);
4413 void *src_addr = page_address(dst->pages[pg_index]) + pg_off;
4414 const bool use_memmove = areas_overlap(src_offset + cur_off,
4415 dst_offset + cur_off, cur_len);
4417 __write_extent_buffer(dst, src_addr, dst_offset + cur_off, cur_len,
4423 void memmove_extent_buffer(const struct extent_buffer *dst,
4424 unsigned long dst_offset, unsigned long src_offset,
4427 unsigned long dst_end = dst_offset + len - 1;
4428 unsigned long src_end = src_offset + len - 1;
4430 if (check_eb_range(dst, dst_offset, len) ||
4431 check_eb_range(dst, src_offset, len))
4434 if (dst_offset < src_offset) {
4435 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
4440 unsigned long src_i;
4442 size_t dst_off_in_page;
4443 size_t src_off_in_page;
4447 src_i = get_eb_page_index(src_end);
4449 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
4450 src_off_in_page = get_eb_offset_in_page(dst, src_end);
4452 cur = min_t(unsigned long, len, src_off_in_page + 1);
4453 cur = min(cur, dst_off_in_page + 1);
4455 src_addr = page_address(dst->pages[src_i]) + src_off_in_page -
4457 use_memmove = areas_overlap(src_end - cur + 1, dst_end - cur + 1,
4460 __write_extent_buffer(dst, src_addr, dst_end - cur + 1, cur,
4469 #define GANG_LOOKUP_SIZE 16
4470 static struct extent_buffer *get_next_extent_buffer(
4471 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
4473 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
4474 struct extent_buffer *found = NULL;
4475 u64 page_start = page_offset(page);
4476 u64 cur = page_start;
4478 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
4479 lockdep_assert_held(&fs_info->buffer_lock);
4481 while (cur < page_start + PAGE_SIZE) {
4485 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
4486 (void **)gang, cur >> fs_info->sectorsize_bits,
4487 min_t(unsigned int, GANG_LOOKUP_SIZE,
4488 PAGE_SIZE / fs_info->nodesize));
4491 for (i = 0; i < ret; i++) {
4492 /* Already beyond page end */
4493 if (gang[i]->start >= page_start + PAGE_SIZE)
4496 if (gang[i]->start >= bytenr) {
4501 cur = gang[ret - 1]->start + gang[ret - 1]->len;
4507 static int try_release_subpage_extent_buffer(struct page *page)
4509 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4510 u64 cur = page_offset(page);
4511 const u64 end = page_offset(page) + PAGE_SIZE;
4515 struct extent_buffer *eb = NULL;
4518 * Unlike try_release_extent_buffer() which uses page->private
4519 * to grab buffer, for subpage case we rely on radix tree, thus
4520 * we need to ensure radix tree consistency.
4522 * We also want an atomic snapshot of the radix tree, thus go
4523 * with spinlock rather than RCU.
4525 spin_lock(&fs_info->buffer_lock);
4526 eb = get_next_extent_buffer(fs_info, page, cur);
4528 /* No more eb in the page range after or at cur */
4529 spin_unlock(&fs_info->buffer_lock);
4532 cur = eb->start + eb->len;
4535 * The same as try_release_extent_buffer(), to ensure the eb
4536 * won't disappear out from under us.
4538 spin_lock(&eb->refs_lock);
4539 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4540 spin_unlock(&eb->refs_lock);
4541 spin_unlock(&fs_info->buffer_lock);
4544 spin_unlock(&fs_info->buffer_lock);
4547 * If tree ref isn't set then we know the ref on this eb is a
4548 * real ref, so just return, this eb will likely be freed soon
4551 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4552 spin_unlock(&eb->refs_lock);
4557 * Here we don't care about the return value, we will always
4558 * check the page private at the end. And
4559 * release_extent_buffer() will release the refs_lock.
4561 release_extent_buffer(eb);
4564 * Finally to check if we have cleared page private, as if we have
4565 * released all ebs in the page, the page private should be cleared now.
4567 spin_lock(&page->mapping->private_lock);
4568 if (!PagePrivate(page))
4572 spin_unlock(&page->mapping->private_lock);
4577 int try_release_extent_buffer(struct page *page)
4579 struct extent_buffer *eb;
4581 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
4582 return try_release_subpage_extent_buffer(page);
4585 * We need to make sure nobody is changing page->private, as we rely on
4586 * page->private as the pointer to extent buffer.
4588 spin_lock(&page->mapping->private_lock);
4589 if (!PagePrivate(page)) {
4590 spin_unlock(&page->mapping->private_lock);
4594 eb = (struct extent_buffer *)page->private;
4598 * This is a little awful but should be ok, we need to make sure that
4599 * the eb doesn't disappear out from under us while we're looking at
4602 spin_lock(&eb->refs_lock);
4603 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4604 spin_unlock(&eb->refs_lock);
4605 spin_unlock(&page->mapping->private_lock);
4608 spin_unlock(&page->mapping->private_lock);
4611 * If tree ref isn't set then we know the ref on this eb is a real ref,
4612 * so just return, this page will likely be freed soon anyway.
4614 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4615 spin_unlock(&eb->refs_lock);
4619 return release_extent_buffer(eb);
4623 * btrfs_readahead_tree_block - attempt to readahead a child block
4624 * @fs_info: the fs_info
4625 * @bytenr: bytenr to read
4626 * @owner_root: objectid of the root that owns this eb
4627 * @gen: generation for the uptodate check, can be 0
4628 * @level: level for the eb
4630 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
4631 * normal uptodate check of the eb, without checking the generation. If we have
4632 * to read the block we will not block on anything.
4634 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
4635 u64 bytenr, u64 owner_root, u64 gen, int level)
4637 struct btrfs_tree_parent_check check = {
4642 struct extent_buffer *eb;
4645 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
4649 if (btrfs_buffer_uptodate(eb, gen, 1)) {
4650 free_extent_buffer(eb);
4654 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
4656 free_extent_buffer_stale(eb);
4658 free_extent_buffer(eb);
4662 * btrfs_readahead_node_child - readahead a node's child block
4663 * @node: parent node we're reading from
4664 * @slot: slot in the parent node for the child we want to read
4666 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
4667 * the slot in the node provided.
4669 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
4671 btrfs_readahead_tree_block(node->fs_info,
4672 btrfs_node_blockptr(node, slot),
4673 btrfs_header_owner(node),
4674 btrfs_node_ptr_generation(node, slot),
4675 btrfs_header_level(node) - 1);