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 static struct kmem_cache *extent_buffer_cache;
36 #ifdef CONFIG_BTRFS_DEBUG
37 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
39 struct btrfs_fs_info *fs_info = eb->fs_info;
42 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
43 list_add(&eb->leak_list, &fs_info->allocated_ebs);
44 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
47 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
49 struct btrfs_fs_info *fs_info = eb->fs_info;
52 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
53 list_del(&eb->leak_list);
54 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
57 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
59 struct extent_buffer *eb;
63 * If we didn't get into open_ctree our allocated_ebs will not be
64 * initialized, so just skip this.
66 if (!fs_info->allocated_ebs.next)
69 WARN_ON(!list_empty(&fs_info->allocated_ebs));
70 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
71 while (!list_empty(&fs_info->allocated_ebs)) {
72 eb = list_first_entry(&fs_info->allocated_ebs,
73 struct extent_buffer, leak_list);
75 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
76 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
77 btrfs_header_owner(eb));
78 list_del(&eb->leak_list);
79 kmem_cache_free(extent_buffer_cache, eb);
81 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
84 #define btrfs_leak_debug_add_eb(eb) do {} while (0)
85 #define btrfs_leak_debug_del_eb(eb) do {} while (0)
89 * Structure to record info about the bio being assembled, and other info like
90 * how many bytes are there before stripe/ordered extent boundary.
92 struct btrfs_bio_ctrl {
95 enum btrfs_compression_type compress_type;
96 u32 len_to_stripe_boundary;
97 u32 len_to_oe_boundary;
100 struct extent_page_data {
101 struct btrfs_bio_ctrl bio_ctrl;
102 /* tells writepage not to lock the state bits for this range
103 * it still does the unlocking
105 unsigned int extent_locked:1;
107 /* tells the submit_bio code to use REQ_SYNC */
108 unsigned int sync_io:1;
111 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
122 bv = bio_first_bvec_all(bio);
123 inode = bv->bv_page->mapping->host;
124 mirror_num = bio_ctrl->mirror_num;
126 /* Caller should ensure the bio has at least some range added */
127 ASSERT(bio->bi_iter.bi_size);
129 btrfs_bio(bio)->file_offset = page_offset(bv->bv_page) + bv->bv_offset;
131 if (!is_data_inode(inode))
132 btrfs_submit_metadata_bio(inode, bio, mirror_num);
133 else if (btrfs_op(bio) == BTRFS_MAP_WRITE)
134 btrfs_submit_data_write_bio(inode, bio, mirror_num);
136 btrfs_submit_data_read_bio(inode, bio, mirror_num,
137 bio_ctrl->compress_type);
139 /* The bio is owned by the end_io handler now */
140 bio_ctrl->bio = NULL;
144 * Submit or fail the current bio in an extent_page_data structure.
146 static void submit_write_bio(struct extent_page_data *epd, int ret)
148 struct bio *bio = epd->bio_ctrl.bio;
155 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
156 /* The bio is owned by the end_io handler now */
157 epd->bio_ctrl.bio = NULL;
159 submit_one_bio(&epd->bio_ctrl);
163 int __init extent_buffer_init_cachep(void)
165 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
166 sizeof(struct extent_buffer), 0,
167 SLAB_MEM_SPREAD, NULL);
168 if (!extent_buffer_cache)
174 void __cold extent_buffer_free_cachep(void)
177 * Make sure all delayed rcu free are flushed before we
181 kmem_cache_destroy(extent_buffer_cache);
184 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
186 unsigned long index = start >> PAGE_SHIFT;
187 unsigned long end_index = end >> PAGE_SHIFT;
190 while (index <= end_index) {
191 page = find_get_page(inode->i_mapping, index);
192 BUG_ON(!page); /* Pages should be in the extent_io_tree */
193 clear_page_dirty_for_io(page);
199 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
201 struct address_space *mapping = inode->i_mapping;
202 unsigned long index = start >> PAGE_SHIFT;
203 unsigned long end_index = end >> PAGE_SHIFT;
206 while (index <= end_index) {
207 folio = filemap_get_folio(mapping, index);
208 filemap_dirty_folio(mapping, folio);
209 folio_account_redirty(folio);
210 index += folio_nr_pages(folio);
216 * Process one page for __process_pages_contig().
218 * Return >0 if we hit @page == @locked_page.
219 * Return 0 if we updated the page status.
220 * Return -EGAIN if the we need to try again.
221 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
223 static int process_one_page(struct btrfs_fs_info *fs_info,
224 struct address_space *mapping,
225 struct page *page, struct page *locked_page,
226 unsigned long page_ops, u64 start, u64 end)
230 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
231 len = end + 1 - start;
233 if (page_ops & PAGE_SET_ORDERED)
234 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
235 if (page_ops & PAGE_SET_ERROR)
236 btrfs_page_clamp_set_error(fs_info, page, start, len);
237 if (page_ops & PAGE_START_WRITEBACK) {
238 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
239 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
241 if (page_ops & PAGE_END_WRITEBACK)
242 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
244 if (page == locked_page)
247 if (page_ops & PAGE_LOCK) {
250 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
253 if (!PageDirty(page) || page->mapping != mapping) {
254 btrfs_page_end_writer_lock(fs_info, page, start, len);
258 if (page_ops & PAGE_UNLOCK)
259 btrfs_page_end_writer_lock(fs_info, page, start, len);
263 static int __process_pages_contig(struct address_space *mapping,
264 struct page *locked_page,
265 u64 start, u64 end, unsigned long page_ops,
268 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
269 pgoff_t start_index = start >> PAGE_SHIFT;
270 pgoff_t end_index = end >> PAGE_SHIFT;
271 pgoff_t index = start_index;
272 unsigned long nr_pages = end_index - start_index + 1;
273 unsigned long pages_processed = 0;
274 struct page *pages[16];
278 if (page_ops & PAGE_LOCK) {
279 ASSERT(page_ops == PAGE_LOCK);
280 ASSERT(processed_end && *processed_end == start);
283 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
284 mapping_set_error(mapping, -EIO);
286 while (nr_pages > 0) {
289 found_pages = find_get_pages_contig(mapping, index,
291 nr_pages, ARRAY_SIZE(pages)), pages);
292 if (found_pages == 0) {
294 * Only if we're going to lock these pages, we can find
297 ASSERT(page_ops & PAGE_LOCK);
302 for (i = 0; i < found_pages; i++) {
305 process_ret = process_one_page(fs_info, mapping,
306 pages[i], locked_page, page_ops,
308 if (process_ret < 0) {
309 for (; i < found_pages; i++)
317 nr_pages -= found_pages;
318 index += found_pages;
322 if (err && processed_end) {
324 * Update @processed_end. I know this is awful since it has
325 * two different return value patterns (inclusive vs exclusive).
327 * But the exclusive pattern is necessary if @start is 0, or we
328 * underflow and check against processed_end won't work as
332 *processed_end = min(end,
333 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
335 *processed_end = start;
340 static noinline void __unlock_for_delalloc(struct inode *inode,
341 struct page *locked_page,
344 unsigned long index = start >> PAGE_SHIFT;
345 unsigned long end_index = end >> PAGE_SHIFT;
348 if (index == locked_page->index && end_index == index)
351 __process_pages_contig(inode->i_mapping, locked_page, start, end,
355 static noinline int lock_delalloc_pages(struct inode *inode,
356 struct page *locked_page,
360 unsigned long index = delalloc_start >> PAGE_SHIFT;
361 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
362 u64 processed_end = delalloc_start;
366 if (index == locked_page->index && index == end_index)
369 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
370 delalloc_end, PAGE_LOCK, &processed_end);
371 if (ret == -EAGAIN && processed_end > delalloc_start)
372 __unlock_for_delalloc(inode, locked_page, delalloc_start,
378 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
379 * more than @max_bytes.
381 * @start: The original start bytenr to search.
382 * Will store the extent range start bytenr.
383 * @end: The original end bytenr of the search range
384 * Will store the extent range end bytenr.
386 * Return true if we find a delalloc range which starts inside the original
387 * range, and @start/@end will store the delalloc range start/end.
389 * Return false if we can't find any delalloc range which starts inside the
390 * original range, and @start/@end will be the non-delalloc range start/end.
393 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
394 struct page *locked_page, u64 *start,
397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
398 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
399 const u64 orig_start = *start;
400 const u64 orig_end = *end;
401 /* The sanity tests may not set a valid fs_info. */
402 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
406 struct extent_state *cached_state = NULL;
410 /* Caller should pass a valid @end to indicate the search range end */
411 ASSERT(orig_end > orig_start);
413 /* The range should at least cover part of the page */
414 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
415 orig_end <= page_offset(locked_page)));
417 /* step one, find a bunch of delalloc bytes starting at start */
418 delalloc_start = *start;
420 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
421 max_bytes, &cached_state);
422 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
423 *start = delalloc_start;
425 /* @delalloc_end can be -1, never go beyond @orig_end */
426 *end = min(delalloc_end, orig_end);
427 free_extent_state(cached_state);
432 * start comes from the offset of locked_page. We have to lock
433 * pages in order, so we can't process delalloc bytes before
436 if (delalloc_start < *start)
437 delalloc_start = *start;
440 * make sure to limit the number of pages we try to lock down
442 if (delalloc_end + 1 - delalloc_start > max_bytes)
443 delalloc_end = delalloc_start + max_bytes - 1;
445 /* step two, lock all the pages after the page that has start */
446 ret = lock_delalloc_pages(inode, locked_page,
447 delalloc_start, delalloc_end);
448 ASSERT(!ret || ret == -EAGAIN);
449 if (ret == -EAGAIN) {
450 /* some of the pages are gone, lets avoid looping by
451 * shortening the size of the delalloc range we're searching
453 free_extent_state(cached_state);
456 max_bytes = PAGE_SIZE;
465 /* step three, lock the state bits for the whole range */
466 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
468 /* then test to make sure it is all still delalloc */
469 ret = test_range_bit(tree, delalloc_start, delalloc_end,
470 EXTENT_DELALLOC, 1, cached_state);
472 unlock_extent(tree, delalloc_start, delalloc_end,
474 __unlock_for_delalloc(inode, locked_page,
475 delalloc_start, delalloc_end);
479 free_extent_state(cached_state);
480 *start = delalloc_start;
486 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
487 struct page *locked_page,
488 u32 clear_bits, unsigned long page_ops)
490 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 0, NULL);
492 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
493 start, end, page_ops, NULL);
496 static int insert_failrec(struct btrfs_inode *inode,
497 struct io_failure_record *failrec)
499 struct rb_node *exist;
501 spin_lock(&inode->io_failure_lock);
502 exist = rb_simple_insert(&inode->io_failure_tree, failrec->bytenr,
504 spin_unlock(&inode->io_failure_lock);
506 return (exist == NULL) ? 0 : -EEXIST;
509 static struct io_failure_record *get_failrec(struct btrfs_inode *inode, u64 start)
511 struct rb_node *node;
512 struct io_failure_record *failrec = ERR_PTR(-ENOENT);
514 spin_lock(&inode->io_failure_lock);
515 node = rb_simple_search(&inode->io_failure_tree, start);
517 failrec = rb_entry(node, struct io_failure_record, rb_node);
518 spin_unlock(&inode->io_failure_lock);
522 static int free_io_failure(struct btrfs_inode *inode,
523 struct io_failure_record *rec)
527 spin_lock(&inode->io_failure_lock);
528 rb_erase(&rec->rb_node, &inode->io_failure_tree);
529 spin_unlock(&inode->io_failure_lock);
531 ret = clear_extent_bits(&inode->io_tree, rec->bytenr,
532 rec->bytenr + rec->len - 1,
539 * this bypasses the standard btrfs submit functions deliberately, as
540 * the standard behavior is to write all copies in a raid setup. here we only
541 * want to write the one bad copy. so we do the mapping for ourselves and issue
542 * submit_bio directly.
543 * to avoid any synchronization issues, wait for the data after writing, which
544 * actually prevents the read that triggered the error from finishing.
545 * currently, there can be no more than two copies of every data bit. thus,
546 * exactly one rewrite is required.
548 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
549 u64 length, u64 logical, struct page *page,
550 unsigned int pg_offset, int mirror_num)
552 struct btrfs_device *dev;
557 struct btrfs_io_context *bioc = NULL;
560 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
563 if (btrfs_repair_one_zone(fs_info, logical))
569 * Avoid races with device replace and make sure our bioc has devices
570 * associated to its stripes that don't go away while we are doing the
571 * read repair operation.
573 btrfs_bio_counter_inc_blocked(fs_info);
574 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
576 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
577 * to update all raid stripes, but here we just want to correct
578 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
579 * stripe's dev and sector.
581 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
582 &map_length, &bioc, 0);
584 goto out_counter_dec;
585 ASSERT(bioc->mirror_num == 1);
587 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
588 &map_length, &bioc, mirror_num);
590 goto out_counter_dec;
591 BUG_ON(mirror_num != bioc->mirror_num);
594 sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
595 dev = bioc->stripes[bioc->mirror_num - 1].dev;
596 btrfs_put_bioc(bioc);
598 if (!dev || !dev->bdev ||
599 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
601 goto out_counter_dec;
604 bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
605 bio.bi_iter.bi_sector = sector;
606 __bio_add_page(&bio, page, length, pg_offset);
608 btrfsic_check_bio(&bio);
609 ret = submit_bio_wait(&bio);
611 /* try to remap that extent elsewhere? */
612 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
616 btrfs_info_rl_in_rcu(fs_info,
617 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
619 rcu_str_deref(dev->name), sector);
625 btrfs_bio_counter_dec(fs_info);
629 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
631 struct btrfs_fs_info *fs_info = eb->fs_info;
632 u64 start = eb->start;
633 int i, num_pages = num_extent_pages(eb);
636 if (sb_rdonly(fs_info->sb))
639 for (i = 0; i < num_pages; i++) {
640 struct page *p = eb->pages[i];
642 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
643 start - page_offset(p), mirror_num);
652 static int next_mirror(const struct io_failure_record *failrec, int cur_mirror)
654 if (cur_mirror == failrec->num_copies)
655 return cur_mirror + 1 - failrec->num_copies;
656 return cur_mirror + 1;
659 static int prev_mirror(const struct io_failure_record *failrec, int cur_mirror)
662 return failrec->num_copies;
663 return cur_mirror - 1;
667 * each time an IO finishes, we do a fast check in the IO failure tree
668 * to see if we need to process or clean up an io_failure_record
670 int btrfs_clean_io_failure(struct btrfs_inode *inode, u64 start,
671 struct page *page, unsigned int pg_offset)
673 struct btrfs_fs_info *fs_info = inode->root->fs_info;
674 struct extent_io_tree *io_tree = &inode->io_tree;
675 u64 ino = btrfs_ino(inode);
676 u64 locked_start, locked_end;
677 struct io_failure_record *failrec;
681 failrec = get_failrec(inode, start);
685 BUG_ON(!failrec->this_mirror);
687 if (sb_rdonly(fs_info->sb))
690 ret = find_first_extent_bit(io_tree, failrec->bytenr, &locked_start,
691 &locked_end, EXTENT_LOCKED, NULL);
692 if (ret || locked_start > failrec->bytenr ||
693 locked_end < failrec->bytenr + failrec->len - 1)
696 mirror = failrec->this_mirror;
698 mirror = prev_mirror(failrec, mirror);
699 repair_io_failure(fs_info, ino, start, failrec->len,
700 failrec->logical, page, pg_offset, mirror);
701 } while (mirror != failrec->failed_mirror);
704 free_io_failure(inode, failrec);
711 * - under ordered extent
712 * - the inode is freeing
714 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
716 struct io_failure_record *failrec;
717 struct rb_node *node, *next;
719 if (RB_EMPTY_ROOT(&inode->io_failure_tree))
722 spin_lock(&inode->io_failure_lock);
723 node = rb_simple_search_first(&inode->io_failure_tree, start);
725 failrec = rb_entry(node, struct io_failure_record, rb_node);
726 if (failrec->bytenr > end)
729 next = rb_next(node);
730 rb_erase(&failrec->rb_node, &inode->io_failure_tree);
735 spin_unlock(&inode->io_failure_lock);
738 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
739 struct btrfs_bio *bbio,
740 unsigned int bio_offset)
742 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
743 u64 start = bbio->file_offset + bio_offset;
744 struct io_failure_record *failrec;
745 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
746 const u32 sectorsize = fs_info->sectorsize;
749 failrec = get_failrec(BTRFS_I(inode), start);
750 if (!IS_ERR(failrec)) {
752 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
753 failrec->logical, failrec->bytenr, failrec->len);
755 * when data can be on disk more than twice, add to failrec here
756 * (e.g. with a list for failed_mirror) to make
757 * clean_io_failure() clean all those errors at once.
759 ASSERT(failrec->this_mirror == bbio->mirror_num);
760 ASSERT(failrec->len == fs_info->sectorsize);
764 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
766 return ERR_PTR(-ENOMEM);
768 RB_CLEAR_NODE(&failrec->rb_node);
769 failrec->bytenr = start;
770 failrec->len = sectorsize;
771 failrec->failed_mirror = bbio->mirror_num;
772 failrec->this_mirror = bbio->mirror_num;
773 failrec->logical = (bbio->iter.bi_sector << SECTOR_SHIFT) + bio_offset;
776 "new io failure record logical %llu start %llu",
777 failrec->logical, start);
779 failrec->num_copies = btrfs_num_copies(fs_info, failrec->logical, sectorsize);
780 if (failrec->num_copies == 1) {
782 * We only have a single copy of the data, so don't bother with
783 * all the retry and error correction code that follows. No
784 * matter what the error is, it is very likely to persist.
787 "cannot repair logical %llu num_copies %d",
788 failrec->logical, failrec->num_copies);
790 return ERR_PTR(-EIO);
793 /* Set the bits in the private failure tree */
794 ret = insert_failrec(BTRFS_I(inode), failrec);
799 ret = set_extent_bits(tree, start, start + sectorsize - 1,
802 free_io_failure(BTRFS_I(inode), failrec);
809 int btrfs_repair_one_sector(struct inode *inode, struct btrfs_bio *failed_bbio,
810 u32 bio_offset, struct page *page, unsigned int pgoff,
811 submit_bio_hook_t *submit_bio_hook)
813 u64 start = failed_bbio->file_offset + bio_offset;
814 struct io_failure_record *failrec;
815 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
816 struct bio *failed_bio = &failed_bbio->bio;
817 const int icsum = bio_offset >> fs_info->sectorsize_bits;
818 struct bio *repair_bio;
819 struct btrfs_bio *repair_bbio;
822 "repair read error: read error at %llu", start);
824 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
826 failrec = btrfs_get_io_failure_record(inode, failed_bbio, bio_offset);
828 return PTR_ERR(failrec);
831 * There are two premises:
832 * a) deliver good data to the caller
833 * b) correct the bad sectors on disk
835 * Since we're only doing repair for one sector, we only need to get
836 * a good copy of the failed sector and if we succeed, we have setup
837 * everything for repair_io_failure to do the rest for us.
839 failrec->this_mirror = next_mirror(failrec, failrec->this_mirror);
840 if (failrec->this_mirror == failrec->failed_mirror) {
842 "failed to repair num_copies %d this_mirror %d failed_mirror %d",
843 failrec->num_copies, failrec->this_mirror, failrec->failed_mirror);
844 free_io_failure(BTRFS_I(inode), failrec);
848 repair_bio = btrfs_bio_alloc(1, REQ_OP_READ, failed_bbio->end_io,
849 failed_bbio->private);
850 repair_bbio = btrfs_bio(repair_bio);
851 repair_bbio->file_offset = start;
852 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
854 if (failed_bbio->csum) {
855 const u32 csum_size = fs_info->csum_size;
857 repair_bbio->csum = repair_bbio->csum_inline;
858 memcpy(repair_bbio->csum,
859 failed_bbio->csum + csum_size * icsum, csum_size);
862 bio_add_page(repair_bio, page, failrec->len, pgoff);
863 repair_bbio->iter = repair_bio->bi_iter;
865 btrfs_debug(btrfs_sb(inode->i_sb),
866 "repair read error: submitting new read to mirror %d",
867 failrec->this_mirror);
870 * At this point we have a bio, so any errors from submit_bio_hook()
871 * will be handled by the endio on the repair_bio, so we can't return an
874 submit_bio_hook(inode, repair_bio, failrec->this_mirror, 0);
878 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
880 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
882 ASSERT(page_offset(page) <= start &&
883 start + len <= page_offset(page) + PAGE_SIZE);
886 if (fsverity_active(page->mapping->host) &&
888 !PageUptodate(page) &&
889 start < i_size_read(page->mapping->host) &&
890 !fsverity_verify_page(page)) {
891 btrfs_page_set_error(fs_info, page, start, len);
893 btrfs_page_set_uptodate(fs_info, page, start, len);
896 btrfs_page_clear_uptodate(fs_info, page, start, len);
897 btrfs_page_set_error(fs_info, page, start, len);
900 if (!btrfs_is_subpage(fs_info, page))
903 btrfs_subpage_end_reader(fs_info, page, start, len);
906 static void end_sector_io(struct page *page, u64 offset, bool uptodate)
908 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
909 const u32 sectorsize = inode->root->fs_info->sectorsize;
910 struct extent_state *cached = NULL;
912 end_page_read(page, uptodate, offset, sectorsize);
914 set_extent_uptodate(&inode->io_tree, offset,
915 offset + sectorsize - 1, &cached, GFP_ATOMIC);
916 unlock_extent_atomic(&inode->io_tree, offset, offset + sectorsize - 1,
920 static void submit_data_read_repair(struct inode *inode,
921 struct btrfs_bio *failed_bbio,
922 u32 bio_offset, const struct bio_vec *bvec,
923 unsigned int error_bitmap)
925 const unsigned int pgoff = bvec->bv_offset;
926 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
927 struct page *page = bvec->bv_page;
928 const u64 start = page_offset(bvec->bv_page) + bvec->bv_offset;
929 const u64 end = start + bvec->bv_len - 1;
930 const u32 sectorsize = fs_info->sectorsize;
931 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
934 BUG_ON(bio_op(&failed_bbio->bio) == REQ_OP_WRITE);
936 /* This repair is only for data */
937 ASSERT(is_data_inode(inode));
939 /* We're here because we had some read errors or csum mismatch */
940 ASSERT(error_bitmap);
943 * We only get called on buffered IO, thus page must be mapped and bio
944 * must not be cloned.
946 ASSERT(page->mapping && !bio_flagged(&failed_bbio->bio, BIO_CLONED));
948 /* Iterate through all the sectors in the range */
949 for (i = 0; i < nr_bits; i++) {
950 const unsigned int offset = i * sectorsize;
951 bool uptodate = false;
954 if (!(error_bitmap & (1U << i))) {
956 * This sector has no error, just end the page read
957 * and unlock the range.
963 ret = btrfs_repair_one_sector(inode, failed_bbio,
964 bio_offset + offset, page, pgoff + offset,
965 btrfs_submit_data_read_bio);
968 * We have submitted the read repair, the page release
969 * will be handled by the endio function of the
970 * submitted repair bio.
971 * Thus we don't need to do any thing here.
976 * Continue on failed repair, otherwise the remaining sectors
977 * will not be properly unlocked.
980 end_sector_io(page, start + offset, uptodate);
984 /* lots and lots of room for performance fixes in the end_bio funcs */
986 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
988 struct btrfs_inode *inode;
989 const bool uptodate = (err == 0);
992 ASSERT(page && page->mapping);
993 inode = BTRFS_I(page->mapping->host);
994 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
997 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
1000 ASSERT(end + 1 - start <= U32_MAX);
1001 len = end + 1 - start;
1003 btrfs_page_clear_uptodate(fs_info, page, start, len);
1004 btrfs_page_set_error(fs_info, page, start, len);
1005 ret = err < 0 ? err : -EIO;
1006 mapping_set_error(page->mapping, ret);
1011 * after a writepage IO is done, we need to:
1012 * clear the uptodate bits on error
1013 * clear the writeback bits in the extent tree for this IO
1014 * end_page_writeback if the page has no more pending IO
1016 * Scheduling is not allowed, so the extent state tree is expected
1017 * to have one and only one object corresponding to this IO.
1019 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
1021 struct bio *bio = &bbio->bio;
1022 int error = blk_status_to_errno(bio->bi_status);
1023 struct bio_vec *bvec;
1026 struct bvec_iter_all iter_all;
1027 bool first_bvec = true;
1029 ASSERT(!bio_flagged(bio, BIO_CLONED));
1030 bio_for_each_segment_all(bvec, bio, iter_all) {
1031 struct page *page = bvec->bv_page;
1032 struct inode *inode = page->mapping->host;
1033 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1034 const u32 sectorsize = fs_info->sectorsize;
1036 /* Our read/write should always be sector aligned. */
1037 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1039 "partial page write in btrfs with offset %u and length %u",
1040 bvec->bv_offset, bvec->bv_len);
1041 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
1043 "incomplete page write with offset %u and length %u",
1044 bvec->bv_offset, bvec->bv_len);
1046 start = page_offset(page) + bvec->bv_offset;
1047 end = start + bvec->bv_len - 1;
1050 btrfs_record_physical_zoned(inode, start, bio);
1054 end_extent_writepage(page, error, start, end);
1056 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
1063 * Record previously processed extent range
1065 * For endio_readpage_release_extent() to handle a full extent range, reducing
1066 * the extent io operations.
1068 struct processed_extent {
1069 struct btrfs_inode *inode;
1070 /* Start of the range in @inode */
1072 /* End of the range in @inode */
1078 * Try to release processed extent range
1080 * May not release the extent range right now if the current range is
1081 * contiguous to processed extent.
1083 * Will release processed extent when any of @inode, @uptodate, the range is
1084 * no longer contiguous to the processed range.
1086 * Passing @inode == NULL will force processed extent to be released.
1088 static void endio_readpage_release_extent(struct processed_extent *processed,
1089 struct btrfs_inode *inode, u64 start, u64 end,
1092 struct extent_state *cached = NULL;
1093 struct extent_io_tree *tree;
1095 /* The first extent, initialize @processed */
1096 if (!processed->inode)
1100 * Contiguous to processed extent, just uptodate the end.
1102 * Several things to notice:
1104 * - bio can be merged as long as on-disk bytenr is contiguous
1105 * This means we can have page belonging to other inodes, thus need to
1106 * check if the inode still matches.
1107 * - bvec can contain range beyond current page for multi-page bvec
1108 * Thus we need to do processed->end + 1 >= start check
1110 if (processed->inode == inode && processed->uptodate == uptodate &&
1111 processed->end + 1 >= start && end >= processed->end) {
1112 processed->end = end;
1116 tree = &processed->inode->io_tree;
1118 * Now we don't have range contiguous to the processed range, release
1119 * the processed range now.
1121 unlock_extent_atomic(tree, processed->start, processed->end, &cached);
1124 /* Update processed to current range */
1125 processed->inode = inode;
1126 processed->start = start;
1127 processed->end = end;
1128 processed->uptodate = uptodate;
1131 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
1133 ASSERT(PageLocked(page));
1134 if (!btrfs_is_subpage(fs_info, page))
1137 ASSERT(PagePrivate(page));
1138 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
1142 * Find extent buffer for a givne bytenr.
1144 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
1147 static struct extent_buffer *find_extent_buffer_readpage(
1148 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
1150 struct extent_buffer *eb;
1153 * For regular sectorsize, we can use page->private to grab extent
1156 if (fs_info->nodesize >= PAGE_SIZE) {
1157 ASSERT(PagePrivate(page) && page->private);
1158 return (struct extent_buffer *)page->private;
1161 /* For subpage case, we need to lookup buffer radix tree */
1163 eb = radix_tree_lookup(&fs_info->buffer_radix,
1164 bytenr >> fs_info->sectorsize_bits);
1171 * after a readpage IO is done, we need to:
1172 * clear the uptodate bits on error
1173 * set the uptodate bits if things worked
1174 * set the page up to date if all extents in the tree are uptodate
1175 * clear the lock bit in the extent tree
1176 * unlock the page if there are no other extents locked for it
1178 * Scheduling is not allowed, so the extent state tree is expected
1179 * to have one and only one object corresponding to this IO.
1181 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
1183 struct bio *bio = &bbio->bio;
1184 struct bio_vec *bvec;
1185 struct processed_extent processed = { 0 };
1187 * The offset to the beginning of a bio, since one bio can never be
1188 * larger than UINT_MAX, u32 here is enough.
1192 struct bvec_iter_all iter_all;
1194 ASSERT(!bio_flagged(bio, BIO_CLONED));
1195 bio_for_each_segment_all(bvec, bio, iter_all) {
1196 bool uptodate = !bio->bi_status;
1197 struct page *page = bvec->bv_page;
1198 struct inode *inode = page->mapping->host;
1199 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1200 const u32 sectorsize = fs_info->sectorsize;
1201 unsigned int error_bitmap = (unsigned int)-1;
1202 bool repair = false;
1207 btrfs_debug(fs_info,
1208 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
1209 bio->bi_iter.bi_sector, bio->bi_status,
1213 * We always issue full-sector reads, but if some block in a
1214 * page fails to read, blk_update_request() will advance
1215 * bv_offset and adjust bv_len to compensate. Print a warning
1216 * for unaligned offsets, and an error if they don't add up to
1219 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1221 "partial page read in btrfs with offset %u and length %u",
1222 bvec->bv_offset, bvec->bv_len);
1223 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
1226 "incomplete page read with offset %u and length %u",
1227 bvec->bv_offset, bvec->bv_len);
1229 start = page_offset(page) + bvec->bv_offset;
1230 end = start + bvec->bv_len - 1;
1233 mirror = bbio->mirror_num;
1234 if (likely(uptodate)) {
1235 if (is_data_inode(inode)) {
1236 error_bitmap = btrfs_verify_data_csum(bbio,
1237 bio_offset, page, start, end);
1241 if (btrfs_validate_metadata_buffer(bbio,
1242 page, start, end, mirror))
1247 if (likely(uptodate)) {
1248 loff_t i_size = i_size_read(inode);
1249 pgoff_t end_index = i_size >> PAGE_SHIFT;
1251 btrfs_clean_io_failure(BTRFS_I(inode), start, page, 0);
1254 * Zero out the remaining part if this range straddles
1257 * Here we should only zero the range inside the bvec,
1258 * not touch anything else.
1260 * NOTE: i_size is exclusive while end is inclusive.
1262 if (page->index == end_index && i_size <= end) {
1263 u32 zero_start = max(offset_in_page(i_size),
1264 offset_in_page(start));
1266 zero_user_segment(page, zero_start,
1267 offset_in_page(end) + 1);
1269 } else if (is_data_inode(inode)) {
1271 * Only try to repair bios that actually made it to a
1272 * device. If the bio failed to be submitted mirror
1273 * is 0 and we need to fail it without retrying.
1275 * This also includes the high level bios for compressed
1276 * extents - these never make it to a device and repair
1277 * is already handled on the lower compressed bio.
1282 struct extent_buffer *eb;
1284 eb = find_extent_buffer_readpage(fs_info, page, start);
1285 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
1286 eb->read_mirror = mirror;
1287 atomic_dec(&eb->io_pages);
1292 * submit_data_read_repair() will handle all the good
1293 * and bad sectors, we just continue to the next bvec.
1295 submit_data_read_repair(inode, bbio, bio_offset, bvec,
1298 /* Update page status and unlock */
1299 end_page_read(page, uptodate, start, len);
1300 endio_readpage_release_extent(&processed, BTRFS_I(inode),
1301 start, end, PageUptodate(page));
1304 ASSERT(bio_offset + len > bio_offset);
1308 /* Release the last extent */
1309 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
1310 btrfs_bio_free_csum(bbio);
1315 * Populate every free slot in a provided array with pages.
1317 * @nr_pages: number of pages to allocate
1318 * @page_array: the array to fill with pages; any existing non-null entries in
1319 * the array will be skipped
1321 * Return: 0 if all pages were able to be allocated;
1322 * -ENOMEM otherwise, and the caller is responsible for freeing all
1323 * non-null page pointers in the array.
1325 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
1327 unsigned int allocated;
1329 for (allocated = 0; allocated < nr_pages;) {
1330 unsigned int last = allocated;
1332 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
1334 if (allocated == nr_pages)
1338 * During this iteration, no page could be allocated, even
1339 * though alloc_pages_bulk_array() falls back to alloc_page()
1340 * if it could not bulk-allocate. So we must be out of memory.
1342 if (allocated == last)
1345 memalloc_retry_wait(GFP_NOFS);
1351 * Attempt to add a page to bio
1353 * @bio_ctrl: record both the bio, and its bio_flags
1354 * @page: page to add to the bio
1355 * @disk_bytenr: offset of the new bio or to check whether we are adding
1356 * a contiguous page to the previous one
1357 * @size: portion of page that we want to write
1358 * @pg_offset: starting offset in the page
1359 * @compress_type: compression type of the current bio to see if we can merge them
1361 * Attempt to add a page to bio considering stripe alignment etc.
1363 * Return >= 0 for the number of bytes added to the bio.
1364 * Can return 0 if the current bio is already at stripe/zone boundary.
1365 * Return <0 for error.
1367 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
1369 u64 disk_bytenr, unsigned int size,
1370 unsigned int pg_offset,
1371 enum btrfs_compression_type compress_type)
1373 struct bio *bio = bio_ctrl->bio;
1374 u32 bio_size = bio->bi_iter.bi_size;
1376 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
1377 bool contig = false;
1381 /* The limit should be calculated when bio_ctrl->bio is allocated */
1382 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
1383 if (bio_ctrl->compress_type != compress_type)
1387 if (bio->bi_iter.bi_size == 0) {
1388 /* We can always add a page into an empty bio. */
1390 } else if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE) {
1391 struct bio_vec *bvec = bio_last_bvec_all(bio);
1394 * The contig check requires the following conditions to be met:
1395 * 1) The pages are belonging to the same inode
1396 * This is implied by the call chain.
1398 * 2) The range has adjacent logical bytenr
1400 * 3) The range has adjacent file offset
1401 * This is required for the usage of btrfs_bio->file_offset.
1403 if (bio_end_sector(bio) == sector &&
1404 page_offset(bvec->bv_page) + bvec->bv_offset +
1405 bvec->bv_len == page_offset(page) + pg_offset)
1409 * For compression, all IO should have its logical bytenr
1410 * set to the starting bytenr of the compressed extent.
1412 contig = bio->bi_iter.bi_sector == sector;
1418 real_size = min(bio_ctrl->len_to_oe_boundary,
1419 bio_ctrl->len_to_stripe_boundary) - bio_size;
1420 real_size = min(real_size, size);
1423 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
1424 * bio will still execute its endio function on the page!
1429 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
1430 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
1432 ret = bio_add_page(bio, page, real_size, pg_offset);
1437 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
1438 struct btrfs_inode *inode, u64 file_offset)
1440 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1441 struct btrfs_io_geometry geom;
1442 struct btrfs_ordered_extent *ordered;
1443 struct extent_map *em;
1444 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
1448 * Pages for compressed extent are never submitted to disk directly,
1449 * thus it has no real boundary, just set them to U32_MAX.
1451 * The split happens for real compressed bio, which happens in
1452 * btrfs_submit_compressed_read/write().
1454 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
1455 bio_ctrl->len_to_oe_boundary = U32_MAX;
1456 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1459 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
1462 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
1464 free_extent_map(em);
1468 if (geom.len > U32_MAX)
1469 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1471 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
1473 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
1474 bio_ctrl->len_to_oe_boundary = U32_MAX;
1478 /* Ordered extent not yet created, so we're good */
1479 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
1481 bio_ctrl->len_to_oe_boundary = U32_MAX;
1485 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
1486 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
1487 btrfs_put_ordered_extent(ordered);
1491 static int alloc_new_bio(struct btrfs_inode *inode,
1492 struct btrfs_bio_ctrl *bio_ctrl,
1493 struct writeback_control *wbc,
1495 btrfs_bio_end_io_t end_io_func,
1496 u64 disk_bytenr, u32 offset, u64 file_offset,
1497 enum btrfs_compression_type compress_type)
1499 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1503 bio = btrfs_bio_alloc(BIO_MAX_VECS, opf, end_io_func, NULL);
1505 * For compressed page range, its disk_bytenr is always @disk_bytenr
1506 * passed in, no matter if we have added any range into previous bio.
1508 if (compress_type != BTRFS_COMPRESS_NONE)
1509 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
1511 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
1512 bio_ctrl->bio = bio;
1513 bio_ctrl->compress_type = compress_type;
1514 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
1520 * For Zone append we need the correct block_device that we are
1521 * going to write to set in the bio to be able to respect the
1522 * hardware limitation. Look it up here:
1524 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
1525 struct btrfs_device *dev;
1527 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
1528 fs_info->sectorsize);
1534 bio_set_dev(bio, dev->bdev);
1537 * Otherwise pick the last added device to support
1538 * cgroup writeback. For multi-device file systems this
1539 * means blk-cgroup policies have to always be set on the
1540 * last added/replaced device. This is a bit odd but has
1541 * been like that for a long time.
1543 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
1545 wbc_init_bio(wbc, bio);
1547 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
1551 bio_ctrl->bio = NULL;
1552 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
1557 * @opf: bio REQ_OP_* and REQ_* flags as one value
1558 * @wbc: optional writeback control for io accounting
1559 * @page: page to add to the bio
1560 * @disk_bytenr: logical bytenr where the write will be
1561 * @size: portion of page that we want to write to
1562 * @pg_offset: offset of the new bio or to check whether we are adding
1563 * a contiguous page to the previous one
1564 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
1565 * @end_io_func: end_io callback for new bio
1566 * @mirror_num: desired mirror to read/write
1567 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
1568 * @compress_type: compress type for current bio
1570 static int submit_extent_page(blk_opf_t opf,
1571 struct writeback_control *wbc,
1572 struct btrfs_bio_ctrl *bio_ctrl,
1573 struct page *page, u64 disk_bytenr,
1574 size_t size, unsigned long pg_offset,
1575 btrfs_bio_end_io_t end_io_func,
1576 enum btrfs_compression_type compress_type,
1577 bool force_bio_submit)
1580 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1581 unsigned int cur = pg_offset;
1585 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
1586 pg_offset + size <= PAGE_SIZE);
1587 if (force_bio_submit)
1588 submit_one_bio(bio_ctrl);
1590 while (cur < pg_offset + size) {
1591 u32 offset = cur - pg_offset;
1594 /* Allocate new bio if needed */
1595 if (!bio_ctrl->bio) {
1596 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
1597 end_io_func, disk_bytenr, offset,
1598 page_offset(page) + cur,
1604 * We must go through btrfs_bio_add_page() to ensure each
1605 * page range won't cross various boundaries.
1607 if (compress_type != BTRFS_COMPRESS_NONE)
1608 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
1609 size - offset, pg_offset + offset,
1612 added = btrfs_bio_add_page(bio_ctrl, page,
1613 disk_bytenr + offset, size - offset,
1614 pg_offset + offset, compress_type);
1616 /* Metadata page range should never be split */
1617 if (!is_data_inode(&inode->vfs_inode))
1618 ASSERT(added == 0 || added == size - offset);
1620 /* At least we added some page, update the account */
1622 wbc_account_cgroup_owner(wbc, page, added);
1624 /* We have reached boundary, submit right now */
1625 if (added < size - offset) {
1626 /* The bio should contain some page(s) */
1627 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
1628 submit_one_bio(bio_ctrl);
1635 static int attach_extent_buffer_page(struct extent_buffer *eb,
1637 struct btrfs_subpage *prealloc)
1639 struct btrfs_fs_info *fs_info = eb->fs_info;
1643 * If the page is mapped to btree inode, we should hold the private
1644 * lock to prevent race.
1645 * For cloned or dummy extent buffers, their pages are not mapped and
1646 * will not race with any other ebs.
1649 lockdep_assert_held(&page->mapping->private_lock);
1651 if (fs_info->nodesize >= PAGE_SIZE) {
1652 if (!PagePrivate(page))
1653 attach_page_private(page, eb);
1655 WARN_ON(page->private != (unsigned long)eb);
1659 /* Already mapped, just free prealloc */
1660 if (PagePrivate(page)) {
1661 btrfs_free_subpage(prealloc);
1666 /* Has preallocated memory for subpage */
1667 attach_page_private(page, prealloc);
1669 /* Do new allocation to attach subpage */
1670 ret = btrfs_attach_subpage(fs_info, page,
1671 BTRFS_SUBPAGE_METADATA);
1675 int set_page_extent_mapped(struct page *page)
1677 struct btrfs_fs_info *fs_info;
1679 ASSERT(page->mapping);
1681 if (PagePrivate(page))
1684 fs_info = btrfs_sb(page->mapping->host->i_sb);
1686 if (btrfs_is_subpage(fs_info, page))
1687 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1689 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1693 void clear_page_extent_mapped(struct page *page)
1695 struct btrfs_fs_info *fs_info;
1697 ASSERT(page->mapping);
1699 if (!PagePrivate(page))
1702 fs_info = btrfs_sb(page->mapping->host->i_sb);
1703 if (btrfs_is_subpage(fs_info, page))
1704 return btrfs_detach_subpage(fs_info, page);
1706 detach_page_private(page);
1709 static struct extent_map *
1710 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1711 u64 start, u64 len, struct extent_map **em_cached)
1713 struct extent_map *em;
1715 if (em_cached && *em_cached) {
1717 if (extent_map_in_tree(em) && start >= em->start &&
1718 start < extent_map_end(em)) {
1719 refcount_inc(&em->refs);
1723 free_extent_map(em);
1727 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1728 if (em_cached && !IS_ERR(em)) {
1730 refcount_inc(&em->refs);
1736 * basic readpage implementation. Locked extent state structs are inserted
1737 * into the tree that are removed when the IO is done (by the end_io
1739 * XXX JDM: This needs looking at to ensure proper page locking
1740 * return 0 on success, otherwise return error
1742 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1743 struct btrfs_bio_ctrl *bio_ctrl,
1744 blk_opf_t read_flags, u64 *prev_em_start)
1746 struct inode *inode = page->mapping->host;
1747 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1748 u64 start = page_offset(page);
1749 const u64 end = start + PAGE_SIZE - 1;
1752 u64 last_byte = i_size_read(inode);
1754 struct extent_map *em;
1756 size_t pg_offset = 0;
1758 size_t blocksize = inode->i_sb->s_blocksize;
1759 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1761 ret = set_page_extent_mapped(page);
1763 unlock_extent(tree, start, end, NULL);
1764 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1769 if (page->index == last_byte >> PAGE_SHIFT) {
1770 size_t zero_offset = offset_in_page(last_byte);
1773 iosize = PAGE_SIZE - zero_offset;
1774 memzero_page(page, zero_offset, iosize);
1777 begin_page_read(fs_info, page);
1778 while (cur <= end) {
1779 unsigned long this_bio_flag = 0;
1780 bool force_bio_submit = false;
1783 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1784 if (cur >= last_byte) {
1785 struct extent_state *cached = NULL;
1787 iosize = PAGE_SIZE - pg_offset;
1788 memzero_page(page, pg_offset, iosize);
1789 set_extent_uptodate(tree, cur, cur + iosize - 1,
1791 unlock_extent(tree, cur, cur + iosize - 1, &cached);
1792 end_page_read(page, true, cur, iosize);
1795 em = __get_extent_map(inode, page, pg_offset, cur,
1796 end - cur + 1, em_cached);
1798 unlock_extent(tree, cur, end, NULL);
1799 end_page_read(page, false, cur, end + 1 - cur);
1803 extent_offset = cur - em->start;
1804 BUG_ON(extent_map_end(em) <= cur);
1807 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1808 this_bio_flag = em->compress_type;
1810 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1811 iosize = ALIGN(iosize, blocksize);
1812 if (this_bio_flag != BTRFS_COMPRESS_NONE)
1813 disk_bytenr = em->block_start;
1815 disk_bytenr = em->block_start + extent_offset;
1816 block_start = em->block_start;
1817 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1818 block_start = EXTENT_MAP_HOLE;
1821 * If we have a file range that points to a compressed extent
1822 * and it's followed by a consecutive file range that points
1823 * to the same compressed extent (possibly with a different
1824 * offset and/or length, so it either points to the whole extent
1825 * or only part of it), we must make sure we do not submit a
1826 * single bio to populate the pages for the 2 ranges because
1827 * this makes the compressed extent read zero out the pages
1828 * belonging to the 2nd range. Imagine the following scenario:
1831 * [0 - 8K] [8K - 24K]
1834 * points to extent X, points to extent X,
1835 * offset 4K, length of 8K offset 0, length 16K
1837 * [extent X, compressed length = 4K uncompressed length = 16K]
1839 * If the bio to read the compressed extent covers both ranges,
1840 * it will decompress extent X into the pages belonging to the
1841 * first range and then it will stop, zeroing out the remaining
1842 * pages that belong to the other range that points to extent X.
1843 * So here we make sure we submit 2 bios, one for the first
1844 * range and another one for the third range. Both will target
1845 * the same physical extent from disk, but we can't currently
1846 * make the compressed bio endio callback populate the pages
1847 * for both ranges because each compressed bio is tightly
1848 * coupled with a single extent map, and each range can have
1849 * an extent map with a different offset value relative to the
1850 * uncompressed data of our extent and different lengths. This
1851 * is a corner case so we prioritize correctness over
1852 * non-optimal behavior (submitting 2 bios for the same extent).
1854 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1855 prev_em_start && *prev_em_start != (u64)-1 &&
1856 *prev_em_start != em->start)
1857 force_bio_submit = true;
1860 *prev_em_start = em->start;
1862 free_extent_map(em);
1865 /* we've found a hole, just zero and go on */
1866 if (block_start == EXTENT_MAP_HOLE) {
1867 struct extent_state *cached = NULL;
1869 memzero_page(page, pg_offset, iosize);
1871 set_extent_uptodate(tree, cur, cur + iosize - 1,
1873 unlock_extent(tree, cur, cur + iosize - 1, &cached);
1874 end_page_read(page, true, cur, iosize);
1876 pg_offset += iosize;
1879 /* the get_extent function already copied into the page */
1880 if (block_start == EXTENT_MAP_INLINE) {
1881 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1882 end_page_read(page, true, cur, iosize);
1884 pg_offset += iosize;
1888 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
1889 bio_ctrl, page, disk_bytenr, iosize,
1890 pg_offset, end_bio_extent_readpage,
1891 this_bio_flag, force_bio_submit);
1894 * We have to unlock the remaining range, or the page
1895 * will never be unlocked.
1897 unlock_extent(tree, cur, end, NULL);
1898 end_page_read(page, false, cur, end + 1 - cur);
1902 pg_offset += iosize;
1908 int btrfs_read_folio(struct file *file, struct folio *folio)
1910 struct page *page = &folio->page;
1911 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1912 u64 start = page_offset(page);
1913 u64 end = start + PAGE_SIZE - 1;
1914 struct btrfs_bio_ctrl bio_ctrl = { 0 };
1917 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1919 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
1921 * If btrfs_do_readpage() failed we will want to submit the assembled
1922 * bio to do the cleanup.
1924 submit_one_bio(&bio_ctrl);
1928 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1930 struct extent_map **em_cached,
1931 struct btrfs_bio_ctrl *bio_ctrl,
1934 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1937 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1939 for (index = 0; index < nr_pages; index++) {
1940 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1941 REQ_RAHEAD, prev_em_start);
1942 put_page(pages[index]);
1947 * helper for __extent_writepage, doing all of the delayed allocation setup.
1949 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1950 * to write the page (copy into inline extent). In this case the IO has
1951 * been started and the page is already unlocked.
1953 * This returns 0 if all went well (page still locked)
1954 * This returns < 0 if there were errors (page still locked)
1956 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1957 struct page *page, struct writeback_control *wbc)
1959 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1960 u64 delalloc_start = page_offset(page);
1961 u64 delalloc_to_write = 0;
1962 /* How many pages are started by btrfs_run_delalloc_range() */
1963 unsigned long nr_written = 0;
1965 int page_started = 0;
1967 while (delalloc_start < page_end) {
1968 u64 delalloc_end = page_end;
1971 found = find_lock_delalloc_range(&inode->vfs_inode, page,
1975 delalloc_start = delalloc_end + 1;
1978 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1979 delalloc_end, &page_started, &nr_written, wbc);
1981 btrfs_page_set_error(inode->root->fs_info, page,
1982 page_offset(page), PAGE_SIZE);
1986 * delalloc_end is already one less than the total length, so
1987 * we don't subtract one from PAGE_SIZE
1989 delalloc_to_write += (delalloc_end - delalloc_start +
1990 PAGE_SIZE) >> PAGE_SHIFT;
1991 delalloc_start = delalloc_end + 1;
1993 if (wbc->nr_to_write < delalloc_to_write) {
1996 if (delalloc_to_write < thresh * 2)
1997 thresh = delalloc_to_write;
1998 wbc->nr_to_write = min_t(u64, delalloc_to_write,
2002 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
2005 * We've unlocked the page, so we can't update the mapping's
2006 * writeback index, just update nr_to_write.
2008 wbc->nr_to_write -= nr_written;
2016 * Find the first byte we need to write.
2018 * For subpage, one page can contain several sectors, and
2019 * __extent_writepage_io() will just grab all extent maps in the page
2020 * range and try to submit all non-inline/non-compressed extents.
2022 * This is a big problem for subpage, we shouldn't re-submit already written
2024 * This function will lookup subpage dirty bit to find which range we really
2027 * Return the next dirty range in [@start, @end).
2028 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
2030 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
2031 struct page *page, u64 *start, u64 *end)
2033 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2034 struct btrfs_subpage_info *spi = fs_info->subpage_info;
2035 u64 orig_start = *start;
2036 /* Declare as unsigned long so we can use bitmap ops */
2037 unsigned long flags;
2038 int range_start_bit;
2042 * For regular sector size == page size case, since one page only
2043 * contains one sector, we return the page offset directly.
2045 if (!btrfs_is_subpage(fs_info, page)) {
2046 *start = page_offset(page);
2047 *end = page_offset(page) + PAGE_SIZE;
2051 range_start_bit = spi->dirty_offset +
2052 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
2054 /* We should have the page locked, but just in case */
2055 spin_lock_irqsave(&subpage->lock, flags);
2056 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
2057 spi->dirty_offset + spi->bitmap_nr_bits);
2058 spin_unlock_irqrestore(&subpage->lock, flags);
2060 range_start_bit -= spi->dirty_offset;
2061 range_end_bit -= spi->dirty_offset;
2063 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
2064 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
2068 * helper for __extent_writepage. This calls the writepage start hooks,
2069 * and does the loop to map the page into extents and bios.
2071 * We return 1 if the IO is started and the page is unlocked,
2072 * 0 if all went well (page still locked)
2073 * < 0 if there were errors (page still locked)
2075 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
2077 struct writeback_control *wbc,
2078 struct extent_page_data *epd,
2082 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2083 u64 cur = page_offset(page);
2084 u64 end = cur + PAGE_SIZE - 1;
2087 struct extent_map *em;
2091 enum req_op op = REQ_OP_WRITE;
2092 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
2093 bool has_error = false;
2096 ret = btrfs_writepage_cow_fixup(page);
2098 /* Fixup worker will requeue */
2099 redirty_page_for_writepage(wbc, page);
2105 * we don't want to touch the inode after unlocking the page,
2106 * so we update the mapping writeback index now
2110 while (cur <= end) {
2113 u64 dirty_range_start = cur;
2114 u64 dirty_range_end;
2117 if (cur >= i_size) {
2118 btrfs_writepage_endio_finish_ordered(inode, page, cur,
2121 * This range is beyond i_size, thus we don't need to
2122 * bother writing back.
2123 * But we still need to clear the dirty subpage bit, or
2124 * the next time the page gets dirtied, we will try to
2125 * writeback the sectors with subpage dirty bits,
2126 * causing writeback without ordered extent.
2128 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
2132 find_next_dirty_byte(fs_info, page, &dirty_range_start,
2134 if (cur < dirty_range_start) {
2135 cur = dirty_range_start;
2139 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
2141 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
2142 ret = PTR_ERR_OR_ZERO(em);
2149 extent_offset = cur - em->start;
2150 em_end = extent_map_end(em);
2151 ASSERT(cur <= em_end);
2153 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
2154 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
2155 block_start = em->block_start;
2156 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
2157 disk_bytenr = em->block_start + extent_offset;
2160 * Note that em_end from extent_map_end() and dirty_range_end from
2161 * find_next_dirty_byte() are all exclusive
2163 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
2165 if (btrfs_use_zone_append(inode, em->block_start))
2166 op = REQ_OP_ZONE_APPEND;
2168 free_extent_map(em);
2172 * compressed and inline extents are written through other
2175 if (compressed || block_start == EXTENT_MAP_HOLE ||
2176 block_start == EXTENT_MAP_INLINE) {
2180 btrfs_writepage_endio_finish_ordered(inode,
2181 page, cur, cur + iosize - 1, true);
2182 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2187 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
2188 if (!PageWriteback(page)) {
2189 btrfs_err(inode->root->fs_info,
2190 "page %lu not writeback, cur %llu end %llu",
2191 page->index, cur, end);
2195 * Although the PageDirty bit is cleared before entering this
2196 * function, subpage dirty bit is not cleared.
2197 * So clear subpage dirty bit here so next time we won't submit
2198 * page for range already written to disk.
2200 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2202 ret = submit_extent_page(op | write_flags, wbc,
2203 &epd->bio_ctrl, page,
2204 disk_bytenr, iosize,
2205 cur - page_offset(page),
2206 end_bio_extent_writepage,
2213 btrfs_page_set_error(fs_info, page, cur, iosize);
2214 if (PageWriteback(page))
2215 btrfs_page_clear_writeback(fs_info, page, cur,
2223 * If we finish without problem, we should not only clear page dirty,
2224 * but also empty subpage dirty bits
2227 btrfs_page_assert_not_dirty(fs_info, page);
2235 * the writepage semantics are similar to regular writepage. extent
2236 * records are inserted to lock ranges in the tree, and as dirty areas
2237 * are found, they are marked writeback. Then the lock bits are removed
2238 * and the end_io handler clears the writeback ranges
2240 * Return 0 if everything goes well.
2241 * Return <0 for error.
2243 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2244 struct extent_page_data *epd)
2246 struct folio *folio = page_folio(page);
2247 struct inode *inode = page->mapping->host;
2248 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2249 const u64 page_start = page_offset(page);
2250 const u64 page_end = page_start + PAGE_SIZE - 1;
2254 loff_t i_size = i_size_read(inode);
2255 unsigned long end_index = i_size >> PAGE_SHIFT;
2257 trace___extent_writepage(page, inode, wbc);
2259 WARN_ON(!PageLocked(page));
2261 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
2262 page_offset(page), PAGE_SIZE);
2264 pg_offset = offset_in_page(i_size);
2265 if (page->index > end_index ||
2266 (page->index == end_index && !pg_offset)) {
2267 folio_invalidate(folio, 0, folio_size(folio));
2268 folio_unlock(folio);
2272 if (page->index == end_index)
2273 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
2275 ret = set_page_extent_mapped(page);
2281 if (!epd->extent_locked) {
2282 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
2289 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
2296 /* make sure the mapping tag for page dirty gets cleared */
2297 set_page_writeback(page);
2298 end_page_writeback(page);
2301 * Here we used to have a check for PageError() and then set @ret and
2302 * call end_extent_writepage().
2304 * But in fact setting @ret here will cause different error paths
2305 * between subpage and regular sectorsize.
2307 * For regular page size, we never submit current page, but only add
2308 * current page to current bio.
2309 * The bio submission can only happen in next page.
2310 * Thus if we hit the PageError() branch, @ret is already set to
2311 * non-zero value and will not get updated for regular sectorsize.
2313 * But for subpage case, it's possible we submit part of current page,
2314 * thus can get PageError() set by submitted bio of the same page,
2315 * while our @ret is still 0.
2317 * So here we unify the behavior and don't set @ret.
2318 * Error can still be properly passed to higher layer as page will
2319 * be set error, here we just don't handle the IO failure.
2321 * NOTE: This is just a hotfix for subpage.
2322 * The root fix will be properly ending ordered extent when we hit
2323 * an error during writeback.
2325 * But that needs a bigger refactoring, as we not only need to grab the
2326 * submitted OE, but also need to know exactly at which bytenr we hit
2328 * Currently the full page based __extent_writepage_io() is not
2331 if (PageError(page))
2332 end_extent_writepage(page, ret, page_start, page_end);
2333 if (epd->extent_locked) {
2335 * If epd->extent_locked, it's from extent_write_locked_range(),
2336 * the page can either be locked by lock_page() or
2337 * process_one_page().
2338 * Let btrfs_page_unlock_writer() handle both cases.
2341 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
2342 wbc->range_end + 1 - wbc->range_start);
2350 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
2352 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
2353 TASK_UNINTERRUPTIBLE);
2356 static void end_extent_buffer_writeback(struct extent_buffer *eb)
2358 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2359 smp_mb__after_atomic();
2360 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
2364 * Lock extent buffer status and pages for writeback.
2366 * May try to flush write bio if we can't get the lock.
2368 * Return 0 if the extent buffer doesn't need to be submitted.
2369 * (E.g. the extent buffer is not dirty)
2370 * Return >0 is the extent buffer is submitted to bio.
2371 * Return <0 if something went wrong, no page is locked.
2373 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
2374 struct extent_page_data *epd)
2376 struct btrfs_fs_info *fs_info = eb->fs_info;
2381 if (!btrfs_try_tree_write_lock(eb)) {
2382 submit_write_bio(epd, 0);
2384 btrfs_tree_lock(eb);
2387 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
2388 btrfs_tree_unlock(eb);
2392 submit_write_bio(epd, 0);
2396 wait_on_extent_buffer_writeback(eb);
2397 btrfs_tree_lock(eb);
2398 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
2400 btrfs_tree_unlock(eb);
2405 * We need to do this to prevent races in people who check if the eb is
2406 * under IO since we can end up having no IO bits set for a short period
2409 spin_lock(&eb->refs_lock);
2410 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
2411 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2412 spin_unlock(&eb->refs_lock);
2413 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
2414 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2416 fs_info->dirty_metadata_batch);
2419 spin_unlock(&eb->refs_lock);
2422 btrfs_tree_unlock(eb);
2425 * Either we don't need to submit any tree block, or we're submitting
2427 * Subpage metadata doesn't use page locking at all, so we can skip
2430 if (!ret || fs_info->nodesize < PAGE_SIZE)
2433 num_pages = num_extent_pages(eb);
2434 for (i = 0; i < num_pages; i++) {
2435 struct page *p = eb->pages[i];
2437 if (!trylock_page(p)) {
2439 submit_write_bio(epd, 0);
2449 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
2451 struct btrfs_fs_info *fs_info = eb->fs_info;
2453 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
2454 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
2458 * A read may stumble upon this buffer later, make sure that it gets an
2459 * error and knows there was an error.
2461 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
2464 * We need to set the mapping with the io error as well because a write
2465 * error will flip the file system readonly, and then syncfs() will
2466 * return a 0 because we are readonly if we don't modify the err seq for
2469 mapping_set_error(page->mapping, -EIO);
2472 * If we error out, we should add back the dirty_metadata_bytes
2473 * to make it consistent.
2475 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2476 eb->len, fs_info->dirty_metadata_batch);
2479 * If writeback for a btree extent that doesn't belong to a log tree
2480 * failed, increment the counter transaction->eb_write_errors.
2481 * We do this because while the transaction is running and before it's
2482 * committing (when we call filemap_fdata[write|wait]_range against
2483 * the btree inode), we might have
2484 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
2485 * returns an error or an error happens during writeback, when we're
2486 * committing the transaction we wouldn't know about it, since the pages
2487 * can be no longer dirty nor marked anymore for writeback (if a
2488 * subsequent modification to the extent buffer didn't happen before the
2489 * transaction commit), which makes filemap_fdata[write|wait]_range not
2490 * able to find the pages tagged with SetPageError at transaction
2491 * commit time. So if this happens we must abort the transaction,
2492 * otherwise we commit a super block with btree roots that point to
2493 * btree nodes/leafs whose content on disk is invalid - either garbage
2494 * or the content of some node/leaf from a past generation that got
2495 * cowed or deleted and is no longer valid.
2497 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
2498 * not be enough - we need to distinguish between log tree extents vs
2499 * non-log tree extents, and the next filemap_fdatawait_range() call
2500 * will catch and clear such errors in the mapping - and that call might
2501 * be from a log sync and not from a transaction commit. Also, checking
2502 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
2503 * not done and would not be reliable - the eb might have been released
2504 * from memory and reading it back again means that flag would not be
2505 * set (since it's a runtime flag, not persisted on disk).
2507 * Using the flags below in the btree inode also makes us achieve the
2508 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
2509 * writeback for all dirty pages and before filemap_fdatawait_range()
2510 * is called, the writeback for all dirty pages had already finished
2511 * with errors - because we were not using AS_EIO/AS_ENOSPC,
2512 * filemap_fdatawait_range() would return success, as it could not know
2513 * that writeback errors happened (the pages were no longer tagged for
2516 switch (eb->log_index) {
2518 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
2521 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2524 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2527 BUG(); /* unexpected, logic error */
2532 * The endio specific version which won't touch any unsafe spinlock in endio
2535 static struct extent_buffer *find_extent_buffer_nolock(
2536 struct btrfs_fs_info *fs_info, u64 start)
2538 struct extent_buffer *eb;
2541 eb = radix_tree_lookup(&fs_info->buffer_radix,
2542 start >> fs_info->sectorsize_bits);
2543 if (eb && atomic_inc_not_zero(&eb->refs)) {
2552 * The endio function for subpage extent buffer write.
2554 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
2555 * after all extent buffers in the page has finished their writeback.
2557 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
2559 struct bio *bio = &bbio->bio;
2560 struct btrfs_fs_info *fs_info;
2561 struct bio_vec *bvec;
2562 struct bvec_iter_all iter_all;
2564 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
2565 ASSERT(fs_info->nodesize < PAGE_SIZE);
2567 ASSERT(!bio_flagged(bio, BIO_CLONED));
2568 bio_for_each_segment_all(bvec, bio, iter_all) {
2569 struct page *page = bvec->bv_page;
2570 u64 bvec_start = page_offset(page) + bvec->bv_offset;
2571 u64 bvec_end = bvec_start + bvec->bv_len - 1;
2572 u64 cur_bytenr = bvec_start;
2574 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
2576 /* Iterate through all extent buffers in the range */
2577 while (cur_bytenr <= bvec_end) {
2578 struct extent_buffer *eb;
2582 * Here we can't use find_extent_buffer(), as it may
2583 * try to lock eb->refs_lock, which is not safe in endio
2586 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
2589 cur_bytenr = eb->start + eb->len;
2591 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
2592 done = atomic_dec_and_test(&eb->io_pages);
2595 if (bio->bi_status ||
2596 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2597 ClearPageUptodate(page);
2598 set_btree_ioerr(page, eb);
2601 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
2603 end_extent_buffer_writeback(eb);
2605 * free_extent_buffer() will grab spinlock which is not
2606 * safe in endio context. Thus here we manually dec
2609 atomic_dec(&eb->refs);
2615 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
2617 struct bio *bio = &bbio->bio;
2618 struct bio_vec *bvec;
2619 struct extent_buffer *eb;
2621 struct bvec_iter_all iter_all;
2623 ASSERT(!bio_flagged(bio, BIO_CLONED));
2624 bio_for_each_segment_all(bvec, bio, iter_all) {
2625 struct page *page = bvec->bv_page;
2627 eb = (struct extent_buffer *)page->private;
2629 done = atomic_dec_and_test(&eb->io_pages);
2631 if (bio->bi_status ||
2632 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2633 ClearPageUptodate(page);
2634 set_btree_ioerr(page, eb);
2637 end_page_writeback(page);
2642 end_extent_buffer_writeback(eb);
2648 static void prepare_eb_write(struct extent_buffer *eb)
2651 unsigned long start;
2654 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2655 atomic_set(&eb->io_pages, num_extent_pages(eb));
2657 /* Set btree blocks beyond nritems with 0 to avoid stale content */
2658 nritems = btrfs_header_nritems(eb);
2659 if (btrfs_header_level(eb) > 0) {
2660 end = btrfs_node_key_ptr_offset(nritems);
2661 memzero_extent_buffer(eb, end, eb->len - end);
2665 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2667 start = btrfs_item_nr_offset(nritems);
2668 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
2669 memzero_extent_buffer(eb, start, end - start);
2674 * Unlike the work in write_one_eb(), we rely completely on extent locking.
2675 * Page locking is only utilized at minimum to keep the VMM code happy.
2677 static int write_one_subpage_eb(struct extent_buffer *eb,
2678 struct writeback_control *wbc,
2679 struct extent_page_data *epd)
2681 struct btrfs_fs_info *fs_info = eb->fs_info;
2682 struct page *page = eb->pages[0];
2683 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2684 bool no_dirty_ebs = false;
2687 prepare_eb_write(eb);
2689 /* clear_page_dirty_for_io() in subpage helper needs page locked */
2691 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2693 /* Check if this is the last dirty bit to update nr_written */
2694 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2695 eb->start, eb->len);
2697 clear_page_dirty_for_io(page);
2699 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2700 &epd->bio_ctrl, page, eb->start, eb->len,
2701 eb->start - page_offset(page),
2702 end_bio_subpage_eb_writepage, 0, false);
2704 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
2705 set_btree_ioerr(page, eb);
2708 if (atomic_dec_and_test(&eb->io_pages))
2709 end_extent_buffer_writeback(eb);
2714 * Submission finished without problem, if no range of the page is
2715 * dirty anymore, we have submitted a page. Update nr_written in wbc.
2722 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
2723 struct writeback_control *wbc,
2724 struct extent_page_data *epd)
2726 u64 disk_bytenr = eb->start;
2728 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2731 prepare_eb_write(eb);
2733 num_pages = num_extent_pages(eb);
2734 for (i = 0; i < num_pages; i++) {
2735 struct page *p = eb->pages[i];
2737 clear_page_dirty_for_io(p);
2738 set_page_writeback(p);
2739 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2740 &epd->bio_ctrl, p, disk_bytenr,
2742 end_bio_extent_buffer_writepage,
2745 set_btree_ioerr(p, eb);
2746 if (PageWriteback(p))
2747 end_page_writeback(p);
2748 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
2749 end_extent_buffer_writeback(eb);
2753 disk_bytenr += PAGE_SIZE;
2758 if (unlikely(ret)) {
2759 for (; i < num_pages; i++) {
2760 struct page *p = eb->pages[i];
2761 clear_page_dirty_for_io(p);
2770 * Submit one subpage btree page.
2772 * The main difference to submit_eb_page() is:
2774 * For subpage, we don't rely on page locking at all.
2777 * We only flush bio if we may be unable to fit current extent buffers into
2780 * Return >=0 for the number of submitted extent buffers.
2781 * Return <0 for fatal error.
2783 static int submit_eb_subpage(struct page *page,
2784 struct writeback_control *wbc,
2785 struct extent_page_data *epd)
2787 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2789 u64 page_start = page_offset(page);
2791 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
2794 /* Lock and write each dirty extent buffers in the range */
2795 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
2796 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2797 struct extent_buffer *eb;
2798 unsigned long flags;
2802 * Take private lock to ensure the subpage won't be detached
2805 spin_lock(&page->mapping->private_lock);
2806 if (!PagePrivate(page)) {
2807 spin_unlock(&page->mapping->private_lock);
2810 spin_lock_irqsave(&subpage->lock, flags);
2811 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
2812 subpage->bitmaps)) {
2813 spin_unlock_irqrestore(&subpage->lock, flags);
2814 spin_unlock(&page->mapping->private_lock);
2819 start = page_start + bit_start * fs_info->sectorsize;
2820 bit_start += sectors_per_node;
2823 * Here we just want to grab the eb without touching extra
2824 * spin locks, so call find_extent_buffer_nolock().
2826 eb = find_extent_buffer_nolock(fs_info, start);
2827 spin_unlock_irqrestore(&subpage->lock, flags);
2828 spin_unlock(&page->mapping->private_lock);
2831 * The eb has already reached 0 refs thus find_extent_buffer()
2832 * doesn't return it. We don't need to write back such eb
2838 ret = lock_extent_buffer_for_io(eb, epd);
2840 free_extent_buffer(eb);
2844 free_extent_buffer(eb);
2847 ret = write_one_subpage_eb(eb, wbc, epd);
2848 free_extent_buffer(eb);
2856 /* We hit error, end bio for the submitted extent buffers */
2857 submit_write_bio(epd, ret);
2862 * Submit all page(s) of one extent buffer.
2864 * @page: the page of one extent buffer
2865 * @eb_context: to determine if we need to submit this page, if current page
2866 * belongs to this eb, we don't need to submit
2868 * The caller should pass each page in their bytenr order, and here we use
2869 * @eb_context to determine if we have submitted pages of one extent buffer.
2871 * If we have, we just skip until we hit a new page that doesn't belong to
2872 * current @eb_context.
2874 * If not, we submit all the page(s) of the extent buffer.
2876 * Return >0 if we have submitted the extent buffer successfully.
2877 * Return 0 if we don't need to submit the page, as it's already submitted by
2879 * Return <0 for fatal error.
2881 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
2882 struct extent_page_data *epd,
2883 struct extent_buffer **eb_context)
2885 struct address_space *mapping = page->mapping;
2886 struct btrfs_block_group *cache = NULL;
2887 struct extent_buffer *eb;
2890 if (!PagePrivate(page))
2893 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
2894 return submit_eb_subpage(page, wbc, epd);
2896 spin_lock(&mapping->private_lock);
2897 if (!PagePrivate(page)) {
2898 spin_unlock(&mapping->private_lock);
2902 eb = (struct extent_buffer *)page->private;
2905 * Shouldn't happen and normally this would be a BUG_ON but no point
2906 * crashing the machine for something we can survive anyway.
2909 spin_unlock(&mapping->private_lock);
2913 if (eb == *eb_context) {
2914 spin_unlock(&mapping->private_lock);
2917 ret = atomic_inc_not_zero(&eb->refs);
2918 spin_unlock(&mapping->private_lock);
2922 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
2924 * If for_sync, this hole will be filled with
2925 * trasnsaction commit.
2927 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
2931 free_extent_buffer(eb);
2937 ret = lock_extent_buffer_for_io(eb, epd);
2939 btrfs_revert_meta_write_pointer(cache, eb);
2941 btrfs_put_block_group(cache);
2942 free_extent_buffer(eb);
2947 * Implies write in zoned mode. Mark the last eb in a block group.
2949 btrfs_schedule_zone_finish_bg(cache, eb);
2950 btrfs_put_block_group(cache);
2952 ret = write_one_eb(eb, wbc, epd);
2953 free_extent_buffer(eb);
2959 int btree_write_cache_pages(struct address_space *mapping,
2960 struct writeback_control *wbc)
2962 struct extent_buffer *eb_context = NULL;
2963 struct extent_page_data epd = {
2966 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
2968 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
2971 int nr_to_write_done = 0;
2972 struct pagevec pvec;
2975 pgoff_t end; /* Inclusive */
2979 pagevec_init(&pvec);
2980 if (wbc->range_cyclic) {
2981 index = mapping->writeback_index; /* Start from prev offset */
2984 * Start from the beginning does not need to cycle over the
2985 * range, mark it as scanned.
2987 scanned = (index == 0);
2989 index = wbc->range_start >> PAGE_SHIFT;
2990 end = wbc->range_end >> PAGE_SHIFT;
2993 if (wbc->sync_mode == WB_SYNC_ALL)
2994 tag = PAGECACHE_TAG_TOWRITE;
2996 tag = PAGECACHE_TAG_DIRTY;
2997 btrfs_zoned_meta_io_lock(fs_info);
2999 if (wbc->sync_mode == WB_SYNC_ALL)
3000 tag_pages_for_writeback(mapping, index, end);
3001 while (!done && !nr_to_write_done && (index <= end) &&
3002 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3006 for (i = 0; i < nr_pages; i++) {
3007 struct page *page = pvec.pages[i];
3009 ret = submit_eb_page(page, wbc, &epd, &eb_context);
3018 * the filesystem may choose to bump up nr_to_write.
3019 * We have to make sure to honor the new nr_to_write
3022 nr_to_write_done = wbc->nr_to_write <= 0;
3024 pagevec_release(&pvec);
3027 if (!scanned && !done) {
3029 * We hit the last page and there is more work to be done: wrap
3030 * back to the start of the file
3037 * If something went wrong, don't allow any metadata write bio to be
3040 * This would prevent use-after-free if we had dirty pages not
3041 * cleaned up, which can still happen by fuzzed images.
3044 * Allowing existing tree block to be allocated for other trees.
3046 * - Log tree operations
3047 * Exiting tree blocks get allocated to log tree, bumps its
3048 * generation, then get cleaned in tree re-balance.
3049 * Such tree block will not be written back, since it's clean,
3050 * thus no WRITTEN flag set.
3051 * And after log writes back, this tree block is not traced by
3052 * any dirty extent_io_tree.
3054 * - Offending tree block gets re-dirtied from its original owner
3055 * Since it has bumped generation, no WRITTEN flag, it can be
3056 * reused without COWing. This tree block will not be traced
3057 * by btrfs_transaction::dirty_pages.
3059 * Now such dirty tree block will not be cleaned by any dirty
3060 * extent io tree. Thus we don't want to submit such wild eb
3061 * if the fs already has error.
3063 * We can get ret > 0 from submit_extent_page() indicating how many ebs
3064 * were submitted. Reset it to 0 to avoid false alerts for the caller.
3068 if (!ret && BTRFS_FS_ERROR(fs_info))
3070 submit_write_bio(&epd, ret);
3072 btrfs_zoned_meta_io_unlock(fs_info);
3077 * Walk the list of dirty pages of the given address space and write all of them.
3079 * @mapping: address space structure to write
3080 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3081 * @epd: holds context for the write, namely the bio
3083 * If a page is already under I/O, write_cache_pages() skips it, even
3084 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
3085 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
3086 * and msync() need to guarantee that all the data which was dirty at the time
3087 * the call was made get new I/O started against them. If wbc->sync_mode is
3088 * WB_SYNC_ALL then we were called for data integrity and we must wait for
3089 * existing IO to complete.
3091 static int extent_write_cache_pages(struct address_space *mapping,
3092 struct writeback_control *wbc,
3093 struct extent_page_data *epd)
3095 struct inode *inode = mapping->host;
3098 int nr_to_write_done = 0;
3099 struct pagevec pvec;
3102 pgoff_t end; /* Inclusive */
3104 int range_whole = 0;
3109 * We have to hold onto the inode so that ordered extents can do their
3110 * work when the IO finishes. The alternative to this is failing to add
3111 * an ordered extent if the igrab() fails there and that is a huge pain
3112 * to deal with, so instead just hold onto the inode throughout the
3113 * writepages operation. If it fails here we are freeing up the inode
3114 * anyway and we'd rather not waste our time writing out stuff that is
3115 * going to be truncated anyway.
3120 pagevec_init(&pvec);
3121 if (wbc->range_cyclic) {
3122 index = mapping->writeback_index; /* Start from prev offset */
3125 * Start from the beginning does not need to cycle over the
3126 * range, mark it as scanned.
3128 scanned = (index == 0);
3130 index = wbc->range_start >> PAGE_SHIFT;
3131 end = wbc->range_end >> PAGE_SHIFT;
3132 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3138 * We do the tagged writepage as long as the snapshot flush bit is set
3139 * and we are the first one who do the filemap_flush() on this inode.
3141 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
3142 * not race in and drop the bit.
3144 if (range_whole && wbc->nr_to_write == LONG_MAX &&
3145 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
3146 &BTRFS_I(inode)->runtime_flags))
3147 wbc->tagged_writepages = 1;
3149 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3150 tag = PAGECACHE_TAG_TOWRITE;
3152 tag = PAGECACHE_TAG_DIRTY;
3154 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3155 tag_pages_for_writeback(mapping, index, end);
3157 while (!done && !nr_to_write_done && (index <= end) &&
3158 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
3159 &index, end, tag))) {
3162 for (i = 0; i < nr_pages; i++) {
3163 struct page *page = pvec.pages[i];
3165 done_index = page->index + 1;
3167 * At this point we hold neither the i_pages lock nor
3168 * the page lock: the page may be truncated or
3169 * invalidated (changing page->mapping to NULL),
3170 * or even swizzled back from swapper_space to
3171 * tmpfs file mapping
3173 if (!trylock_page(page)) {
3174 submit_write_bio(epd, 0);
3178 if (unlikely(page->mapping != mapping)) {
3183 if (wbc->sync_mode != WB_SYNC_NONE) {
3184 if (PageWriteback(page))
3185 submit_write_bio(epd, 0);
3186 wait_on_page_writeback(page);
3189 if (PageWriteback(page) ||
3190 !clear_page_dirty_for_io(page)) {
3195 ret = __extent_writepage(page, wbc, epd);
3202 * the filesystem may choose to bump up nr_to_write.
3203 * We have to make sure to honor the new nr_to_write
3206 nr_to_write_done = wbc->nr_to_write <= 0;
3208 pagevec_release(&pvec);
3211 if (!scanned && !done) {
3213 * We hit the last page and there is more work to be done: wrap
3214 * back to the start of the file
3220 * If we're looping we could run into a page that is locked by a
3221 * writer and that writer could be waiting on writeback for a
3222 * page in our current bio, and thus deadlock, so flush the
3225 submit_write_bio(epd, 0);
3229 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
3230 mapping->writeback_index = done_index;
3232 btrfs_add_delayed_iput(inode);
3237 * Submit the pages in the range to bio for call sites which delalloc range has
3238 * already been ran (aka, ordered extent inserted) and all pages are still
3241 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
3243 bool found_error = false;
3244 int first_error = 0;
3246 struct address_space *mapping = inode->i_mapping;
3249 unsigned long nr_pages;
3250 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
3251 struct extent_page_data epd = {
3256 struct writeback_control wbc_writepages = {
3257 .sync_mode = WB_SYNC_ALL,
3258 .range_start = start,
3259 .range_end = end + 1,
3260 /* We're called from an async helper function */
3261 .punt_to_cgroup = 1,
3262 .no_cgroup_owner = 1,
3265 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
3266 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
3268 wbc_writepages.nr_to_write = nr_pages * 2;
3270 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
3271 while (cur <= end) {
3272 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
3274 page = find_get_page(mapping, cur >> PAGE_SHIFT);
3276 * All pages in the range are locked since
3277 * btrfs_run_delalloc_range(), thus there is no way to clear
3278 * the page dirty flag.
3280 ASSERT(PageLocked(page));
3281 ASSERT(PageDirty(page));
3282 clear_page_dirty_for_io(page);
3283 ret = __extent_writepage(page, &wbc_writepages, &epd);
3293 submit_write_bio(&epd, found_error ? ret : 0);
3295 wbc_detach_inode(&wbc_writepages);
3301 int extent_writepages(struct address_space *mapping,
3302 struct writeback_control *wbc)
3304 struct inode *inode = mapping->host;
3306 struct extent_page_data epd = {
3309 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3313 * Allow only a single thread to do the reloc work in zoned mode to
3314 * protect the write pointer updates.
3316 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
3317 ret = extent_write_cache_pages(mapping, wbc, &epd);
3318 submit_write_bio(&epd, ret);
3319 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
3323 void extent_readahead(struct readahead_control *rac)
3325 struct btrfs_bio_ctrl bio_ctrl = { 0 };
3326 struct page *pagepool[16];
3327 struct extent_map *em_cached = NULL;
3328 u64 prev_em_start = (u64)-1;
3331 while ((nr = readahead_page_batch(rac, pagepool))) {
3332 u64 contig_start = readahead_pos(rac);
3333 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
3335 contiguous_readpages(pagepool, nr, contig_start, contig_end,
3336 &em_cached, &bio_ctrl, &prev_em_start);
3340 free_extent_map(em_cached);
3341 submit_one_bio(&bio_ctrl);
3345 * basic invalidate_folio code, this waits on any locked or writeback
3346 * ranges corresponding to the folio, and then deletes any extent state
3347 * records from the tree
3349 int extent_invalidate_folio(struct extent_io_tree *tree,
3350 struct folio *folio, size_t offset)
3352 struct extent_state *cached_state = NULL;
3353 u64 start = folio_pos(folio);
3354 u64 end = start + folio_size(folio) - 1;
3355 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
3357 /* This function is only called for the btree inode */
3358 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
3360 start += ALIGN(offset, blocksize);
3364 lock_extent(tree, start, end, &cached_state);
3365 folio_wait_writeback(folio);
3368 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
3369 * so here we only need to unlock the extent range to free any
3370 * existing extent state.
3372 unlock_extent(tree, start, end, &cached_state);
3377 * a helper for release_folio, this tests for areas of the page that
3378 * are locked or under IO and drops the related state bits if it is safe
3381 static int try_release_extent_state(struct extent_io_tree *tree,
3382 struct page *page, gfp_t mask)
3384 u64 start = page_offset(page);
3385 u64 end = start + PAGE_SIZE - 1;
3388 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
3392 * At this point we can safely clear everything except the
3393 * locked bit, the nodatasum bit and the delalloc new bit.
3394 * The delalloc new bit will be cleared by ordered extent
3397 ret = __clear_extent_bit(tree, start, end,
3398 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
3399 0, NULL, mask, NULL);
3401 /* if clear_extent_bit failed for enomem reasons,
3402 * we can't allow the release to continue.
3413 * a helper for release_folio. As long as there are no locked extents
3414 * in the range corresponding to the page, both state records and extent
3415 * map records are removed
3417 int try_release_extent_mapping(struct page *page, gfp_t mask)
3419 struct extent_map *em;
3420 u64 start = page_offset(page);
3421 u64 end = start + PAGE_SIZE - 1;
3422 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
3423 struct extent_io_tree *tree = &btrfs_inode->io_tree;
3424 struct extent_map_tree *map = &btrfs_inode->extent_tree;
3426 if (gfpflags_allow_blocking(mask) &&
3427 page->mapping->host->i_size > SZ_16M) {
3429 while (start <= end) {
3430 struct btrfs_fs_info *fs_info;
3433 len = end - start + 1;
3434 write_lock(&map->lock);
3435 em = lookup_extent_mapping(map, start, len);
3437 write_unlock(&map->lock);
3440 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3441 em->start != start) {
3442 write_unlock(&map->lock);
3443 free_extent_map(em);
3446 if (test_range_bit(tree, em->start,
3447 extent_map_end(em) - 1,
3448 EXTENT_LOCKED, 0, NULL))
3451 * If it's not in the list of modified extents, used
3452 * by a fast fsync, we can remove it. If it's being
3453 * logged we can safely remove it since fsync took an
3454 * extra reference on the em.
3456 if (list_empty(&em->list) ||
3457 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
3460 * If it's in the list of modified extents, remove it
3461 * only if its generation is older then the current one,
3462 * in which case we don't need it for a fast fsync.
3463 * Otherwise don't remove it, we could be racing with an
3464 * ongoing fast fsync that could miss the new extent.
3466 fs_info = btrfs_inode->root->fs_info;
3467 spin_lock(&fs_info->trans_lock);
3468 cur_gen = fs_info->generation;
3469 spin_unlock(&fs_info->trans_lock);
3470 if (em->generation >= cur_gen)
3474 * We only remove extent maps that are not in the list of
3475 * modified extents or that are in the list but with a
3476 * generation lower then the current generation, so there
3477 * is no need to set the full fsync flag on the inode (it
3478 * hurts the fsync performance for workloads with a data
3479 * size that exceeds or is close to the system's memory).
3481 remove_extent_mapping(map, em);
3482 /* once for the rb tree */
3483 free_extent_map(em);
3485 start = extent_map_end(em);
3486 write_unlock(&map->lock);
3489 free_extent_map(em);
3491 cond_resched(); /* Allow large-extent preemption. */
3494 return try_release_extent_state(tree, page, mask);
3498 * To cache previous fiemap extent
3500 * Will be used for merging fiemap extent
3502 struct fiemap_cache {
3511 * Helper to submit fiemap extent.
3513 * Will try to merge current fiemap extent specified by @offset, @phys,
3514 * @len and @flags with cached one.
3515 * And only when we fails to merge, cached one will be submitted as
3518 * Return value is the same as fiemap_fill_next_extent().
3520 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
3521 struct fiemap_cache *cache,
3522 u64 offset, u64 phys, u64 len, u32 flags)
3526 /* Set at the end of extent_fiemap(). */
3527 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
3533 * Sanity check, extent_fiemap() should have ensured that new
3534 * fiemap extent won't overlap with cached one.
3537 * NOTE: Physical address can overlap, due to compression
3539 if (cache->offset + cache->len > offset) {
3545 * Only merges fiemap extents if
3546 * 1) Their logical addresses are continuous
3548 * 2) Their physical addresses are continuous
3549 * So truly compressed (physical size smaller than logical size)
3550 * extents won't get merged with each other
3552 * 3) Share same flags
3554 if (cache->offset + cache->len == offset &&
3555 cache->phys + cache->len == phys &&
3556 cache->flags == flags) {
3561 /* Not mergeable, need to submit cached one */
3562 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3563 cache->len, cache->flags);
3564 cache->cached = false;
3568 cache->cached = true;
3569 cache->offset = offset;
3572 cache->flags = flags;
3578 * Emit last fiemap cache
3580 * The last fiemap cache may still be cached in the following case:
3582 * |<- Fiemap range ->|
3583 * |<------------ First extent ----------->|
3585 * In this case, the first extent range will be cached but not emitted.
3586 * So we must emit it before ending extent_fiemap().
3588 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
3589 struct fiemap_cache *cache)
3596 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3597 cache->len, cache->flags);
3598 cache->cached = false;
3604 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
3606 struct extent_buffer *clone;
3607 struct btrfs_key key;
3612 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
3615 ret = btrfs_next_leaf(inode->root, path);
3620 * Don't bother with cloning if there are no more file extent items for
3623 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3624 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
3627 /* See the comment at fiemap_search_slot() about why we clone. */
3628 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3632 slot = path->slots[0];
3633 btrfs_release_path(path);
3634 path->nodes[0] = clone;
3635 path->slots[0] = slot;
3641 * Search for the first file extent item that starts at a given file offset or
3642 * the one that starts immediately before that offset.
3643 * Returns: 0 on success, < 0 on error, 1 if not found.
3645 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
3648 const u64 ino = btrfs_ino(inode);
3649 struct btrfs_root *root = inode->root;
3650 struct extent_buffer *clone;
3651 struct btrfs_key key;
3656 key.type = BTRFS_EXTENT_DATA_KEY;
3657 key.offset = file_offset;
3659 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3663 if (ret > 0 && path->slots[0] > 0) {
3664 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3665 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3669 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3670 ret = btrfs_next_leaf(root, path);
3674 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3675 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3680 * We clone the leaf and use it during fiemap. This is because while
3681 * using the leaf we do expensive things like checking if an extent is
3682 * shared, which can take a long time. In order to prevent blocking
3683 * other tasks for too long, we use a clone of the leaf. We have locked
3684 * the file range in the inode's io tree, so we know none of our file
3685 * extent items can change. This way we avoid blocking other tasks that
3686 * want to insert items for other inodes in the same leaf or b+tree
3687 * rebalance operations (triggered for example when someone is trying
3688 * to push items into this leaf when trying to insert an item in a
3690 * We also need the private clone because holding a read lock on an
3691 * extent buffer of the subvolume's b+tree will make lockdep unhappy
3692 * when we call fiemap_fill_next_extent(), because that may cause a page
3693 * fault when filling the user space buffer with fiemap data.
3695 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3699 slot = path->slots[0];
3700 btrfs_release_path(path);
3701 path->nodes[0] = clone;
3702 path->slots[0] = slot;
3708 * Process a range which is a hole or a prealloc extent in the inode's subvolume
3709 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
3710 * extent. The end offset (@end) is inclusive.
3712 static int fiemap_process_hole(struct btrfs_inode *inode,
3713 struct fiemap_extent_info *fieinfo,
3714 struct fiemap_cache *cache,
3715 struct btrfs_backref_shared_cache *backref_cache,
3716 u64 disk_bytenr, u64 extent_offset,
3718 struct ulist *roots, struct ulist *tmp_ulist,
3721 const u64 i_size = i_size_read(&inode->vfs_inode);
3722 const u64 ino = btrfs_ino(inode);
3723 u64 cur_offset = start;
3724 u64 last_delalloc_end = 0;
3725 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3726 bool checked_extent_shared = false;
3730 * There can be no delalloc past i_size, so don't waste time looking for
3733 while (cur_offset < end && cur_offset < i_size) {
3737 u64 prealloc_len = 0;
3740 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3747 * If this is a prealloc extent we have to report every section
3748 * of it that has no delalloc.
3750 if (disk_bytenr != 0) {
3751 if (last_delalloc_end == 0) {
3752 prealloc_start = start;
3753 prealloc_len = delalloc_start - start;
3755 prealloc_start = last_delalloc_end + 1;
3756 prealloc_len = delalloc_start - prealloc_start;
3760 if (prealloc_len > 0) {
3761 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3762 ret = btrfs_is_data_extent_shared(inode->root,
3770 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3772 checked_extent_shared = true;
3774 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3775 disk_bytenr + extent_offset,
3776 prealloc_len, prealloc_flags);
3779 extent_offset += prealloc_len;
3782 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3783 delalloc_end + 1 - delalloc_start,
3784 FIEMAP_EXTENT_DELALLOC |
3785 FIEMAP_EXTENT_UNKNOWN);
3789 last_delalloc_end = delalloc_end;
3790 cur_offset = delalloc_end + 1;
3791 extent_offset += cur_offset - delalloc_start;
3796 * Either we found no delalloc for the whole prealloc extent or we have
3797 * a prealloc extent that spans i_size or starts at or after i_size.
3799 if (disk_bytenr != 0 && last_delalloc_end < end) {
3803 if (last_delalloc_end == 0) {
3804 prealloc_start = start;
3805 prealloc_len = end + 1 - start;
3807 prealloc_start = last_delalloc_end + 1;
3808 prealloc_len = end + 1 - prealloc_start;
3811 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3812 ret = btrfs_is_data_extent_shared(inode->root,
3820 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3822 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3823 disk_bytenr + extent_offset,
3824 prealloc_len, prealloc_flags);
3832 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3833 struct btrfs_path *path,
3834 u64 *last_extent_end_ret)
3836 const u64 ino = btrfs_ino(inode);
3837 struct btrfs_root *root = inode->root;
3838 struct extent_buffer *leaf;
3839 struct btrfs_file_extent_item *ei;
3840 struct btrfs_key key;
3845 * Lookup the last file extent. We're not using i_size here because
3846 * there might be preallocation past i_size.
3848 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3849 /* There can't be a file extent item at offset (u64)-1 */
3855 * For a non-existing key, btrfs_search_slot() always leaves us at a
3856 * slot > 0, except if the btree is empty, which is impossible because
3857 * at least it has the inode item for this inode and all the items for
3858 * the root inode 256.
3860 ASSERT(path->slots[0] > 0);
3862 leaf = path->nodes[0];
3863 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3864 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3865 /* No file extent items in the subvolume tree. */
3866 *last_extent_end_ret = 0;
3871 * For an inline extent, the disk_bytenr is where inline data starts at,
3872 * so first check if we have an inline extent item before checking if we
3873 * have an implicit hole (disk_bytenr == 0).
3875 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3876 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3877 *last_extent_end_ret = btrfs_file_extent_end(path);
3882 * Find the last file extent item that is not a hole (when NO_HOLES is
3883 * not enabled). This should take at most 2 iterations in the worst
3884 * case: we have one hole file extent item at slot 0 of a leaf and
3885 * another hole file extent item as the last item in the previous leaf.
3886 * This is because we merge file extent items that represent holes.
3888 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3889 while (disk_bytenr == 0) {
3890 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3893 } else if (ret > 0) {
3894 /* No file extent items that are not holes. */
3895 *last_extent_end_ret = 0;
3898 leaf = path->nodes[0];
3899 ei = btrfs_item_ptr(leaf, path->slots[0],
3900 struct btrfs_file_extent_item);
3901 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3904 *last_extent_end_ret = btrfs_file_extent_end(path);
3908 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3911 const u64 ino = btrfs_ino(inode);
3912 struct extent_state *cached_state = NULL;
3913 struct btrfs_path *path;
3914 struct btrfs_root *root = inode->root;
3915 struct fiemap_cache cache = { 0 };
3916 struct btrfs_backref_shared_cache *backref_cache;
3917 struct ulist *roots;
3918 struct ulist *tmp_ulist;
3919 u64 last_extent_end;
3920 u64 prev_extent_end;
3923 bool stopped = false;
3926 backref_cache = kzalloc(sizeof(*backref_cache), GFP_KERNEL);
3927 path = btrfs_alloc_path();
3928 roots = ulist_alloc(GFP_KERNEL);
3929 tmp_ulist = ulist_alloc(GFP_KERNEL);
3930 if (!backref_cache || !path || !roots || !tmp_ulist) {
3935 lockstart = round_down(start, btrfs_inode_sectorsize(inode));
3936 lockend = round_up(start + len, btrfs_inode_sectorsize(inode));
3937 prev_extent_end = lockstart;
3939 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3941 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3944 btrfs_release_path(path);
3946 path->reada = READA_FORWARD;
3947 ret = fiemap_search_slot(inode, path, lockstart);
3950 } else if (ret > 0) {
3952 * No file extent item found, but we may have delalloc between
3953 * the current offset and i_size. So check for that.
3956 goto check_eof_delalloc;
3959 while (prev_extent_end < lockend) {
3960 struct extent_buffer *leaf = path->nodes[0];
3961 struct btrfs_file_extent_item *ei;
3962 struct btrfs_key key;
3965 u64 extent_offset = 0;
3967 u64 disk_bytenr = 0;
3972 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3973 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3976 extent_end = btrfs_file_extent_end(path);
3979 * The first iteration can leave us at an extent item that ends
3980 * before our range's start. Move to the next item.
3982 if (extent_end <= lockstart)
3985 /* We have in implicit hole (NO_HOLES feature enabled). */
3986 if (prev_extent_end < key.offset) {
3987 const u64 range_end = min(key.offset, lockend) - 1;
3989 ret = fiemap_process_hole(inode, fieinfo, &cache,
3990 backref_cache, 0, 0, 0,
3992 prev_extent_end, range_end);
3995 } else if (ret > 0) {
3996 /* fiemap_fill_next_extent() told us to stop. */
4001 /* We've reached the end of the fiemap range, stop. */
4002 if (key.offset >= lockend) {
4008 extent_len = extent_end - key.offset;
4009 ei = btrfs_item_ptr(leaf, path->slots[0],
4010 struct btrfs_file_extent_item);
4011 compression = btrfs_file_extent_compression(leaf, ei);
4012 extent_type = btrfs_file_extent_type(leaf, ei);
4013 extent_gen = btrfs_file_extent_generation(leaf, ei);
4015 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4016 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
4017 if (compression == BTRFS_COMPRESS_NONE)
4018 extent_offset = btrfs_file_extent_offset(leaf, ei);
4021 if (compression != BTRFS_COMPRESS_NONE)
4022 flags |= FIEMAP_EXTENT_ENCODED;
4024 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4025 flags |= FIEMAP_EXTENT_DATA_INLINE;
4026 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
4027 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
4029 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
4030 ret = fiemap_process_hole(inode, fieinfo, &cache,
4032 disk_bytenr, extent_offset,
4033 extent_gen, roots, tmp_ulist,
4034 key.offset, extent_end - 1);
4035 } else if (disk_bytenr == 0) {
4036 /* We have an explicit hole. */
4037 ret = fiemap_process_hole(inode, fieinfo, &cache,
4038 backref_cache, 0, 0, 0,
4040 key.offset, extent_end - 1);
4042 /* We have a regular extent. */
4043 if (fieinfo->fi_extents_max) {
4044 ret = btrfs_is_data_extent_shared(root, ino,
4053 flags |= FIEMAP_EXTENT_SHARED;
4056 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
4057 disk_bytenr + extent_offset,
4063 } else if (ret > 0) {
4064 /* fiemap_fill_next_extent() told us to stop. */
4069 prev_extent_end = extent_end;
4071 if (fatal_signal_pending(current)) {
4076 ret = fiemap_next_leaf_item(inode, path);
4079 } else if (ret > 0) {
4080 /* No more file extent items for this inode. */
4088 * Release (and free) the path before emitting any final entries to
4089 * fiemap_fill_next_extent() to keep lockdep happy. This is because
4090 * once we find no more file extent items exist, we may have a
4091 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
4092 * faults when copying data to the user space buffer.
4094 btrfs_free_path(path);
4097 if (!stopped && prev_extent_end < lockend) {
4098 ret = fiemap_process_hole(inode, fieinfo, &cache, backref_cache,
4099 0, 0, 0, roots, tmp_ulist,
4100 prev_extent_end, lockend - 1);
4103 prev_extent_end = lockend;
4106 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
4107 const u64 i_size = i_size_read(&inode->vfs_inode);
4109 if (prev_extent_end < i_size) {
4114 delalloc = btrfs_find_delalloc_in_range(inode,
4120 cache.flags |= FIEMAP_EXTENT_LAST;
4122 cache.flags |= FIEMAP_EXTENT_LAST;
4126 ret = emit_last_fiemap_cache(fieinfo, &cache);
4129 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
4131 kfree(backref_cache);
4132 btrfs_free_path(path);
4134 ulist_free(tmp_ulist);
4138 static void __free_extent_buffer(struct extent_buffer *eb)
4140 kmem_cache_free(extent_buffer_cache, eb);
4143 int extent_buffer_under_io(const struct extent_buffer *eb)
4145 return (atomic_read(&eb->io_pages) ||
4146 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4147 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4150 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
4152 struct btrfs_subpage *subpage;
4154 lockdep_assert_held(&page->mapping->private_lock);
4156 if (PagePrivate(page)) {
4157 subpage = (struct btrfs_subpage *)page->private;
4158 if (atomic_read(&subpage->eb_refs))
4161 * Even there is no eb refs here, we may still have
4162 * end_page_read() call relying on page::private.
4164 if (atomic_read(&subpage->readers))
4170 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
4172 struct btrfs_fs_info *fs_info = eb->fs_info;
4173 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4176 * For mapped eb, we're going to change the page private, which should
4177 * be done under the private_lock.
4180 spin_lock(&page->mapping->private_lock);
4182 if (!PagePrivate(page)) {
4184 spin_unlock(&page->mapping->private_lock);
4188 if (fs_info->nodesize >= PAGE_SIZE) {
4190 * We do this since we'll remove the pages after we've
4191 * removed the eb from the radix tree, so we could race
4192 * and have this page now attached to the new eb. So
4193 * only clear page_private if it's still connected to
4196 if (PagePrivate(page) &&
4197 page->private == (unsigned long)eb) {
4198 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4199 BUG_ON(PageDirty(page));
4200 BUG_ON(PageWriteback(page));
4202 * We need to make sure we haven't be attached
4205 detach_page_private(page);
4208 spin_unlock(&page->mapping->private_lock);
4213 * For subpage, we can have dummy eb with page private. In this case,
4214 * we can directly detach the private as such page is only attached to
4215 * one dummy eb, no sharing.
4218 btrfs_detach_subpage(fs_info, page);
4222 btrfs_page_dec_eb_refs(fs_info, page);
4225 * We can only detach the page private if there are no other ebs in the
4226 * page range and no unfinished IO.
4228 if (!page_range_has_eb(fs_info, page))
4229 btrfs_detach_subpage(fs_info, page);
4231 spin_unlock(&page->mapping->private_lock);
4234 /* Release all pages attached to the extent buffer */
4235 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4240 ASSERT(!extent_buffer_under_io(eb));
4242 num_pages = num_extent_pages(eb);
4243 for (i = 0; i < num_pages; i++) {
4244 struct page *page = eb->pages[i];
4249 detach_extent_buffer_page(eb, page);
4251 /* One for when we allocated the page */
4257 * Helper for releasing the extent buffer.
4259 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4261 btrfs_release_extent_buffer_pages(eb);
4262 btrfs_leak_debug_del_eb(eb);
4263 __free_extent_buffer(eb);
4266 static struct extent_buffer *
4267 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4270 struct extent_buffer *eb = NULL;
4272 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4275 eb->fs_info = fs_info;
4277 init_rwsem(&eb->lock);
4279 btrfs_leak_debug_add_eb(eb);
4280 INIT_LIST_HEAD(&eb->release_list);
4282 spin_lock_init(&eb->refs_lock);
4283 atomic_set(&eb->refs, 1);
4284 atomic_set(&eb->io_pages, 0);
4286 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
4291 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
4294 struct extent_buffer *new;
4295 int num_pages = num_extent_pages(src);
4298 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4303 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
4304 * btrfs_release_extent_buffer() have different behavior for
4305 * UNMAPPED subpage extent buffer.
4307 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4309 memset(new->pages, 0, sizeof(*new->pages) * num_pages);
4310 ret = btrfs_alloc_page_array(num_pages, new->pages);
4312 btrfs_release_extent_buffer(new);
4316 for (i = 0; i < num_pages; i++) {
4318 struct page *p = new->pages[i];
4320 ret = attach_extent_buffer_page(new, p, NULL);
4322 btrfs_release_extent_buffer(new);
4325 WARN_ON(PageDirty(p));
4326 copy_page(page_address(p), page_address(src->pages[i]));
4328 set_extent_buffer_uptodate(new);
4333 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4334 u64 start, unsigned long len)
4336 struct extent_buffer *eb;
4341 eb = __alloc_extent_buffer(fs_info, start, len);
4345 num_pages = num_extent_pages(eb);
4346 ret = btrfs_alloc_page_array(num_pages, eb->pages);
4350 for (i = 0; i < num_pages; i++) {
4351 struct page *p = eb->pages[i];
4353 ret = attach_extent_buffer_page(eb, p, NULL);
4358 set_extent_buffer_uptodate(eb);
4359 btrfs_set_header_nritems(eb, 0);
4360 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4364 for (i = 0; i < num_pages; i++) {
4366 detach_extent_buffer_page(eb, eb->pages[i]);
4367 __free_page(eb->pages[i]);
4370 __free_extent_buffer(eb);
4374 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4377 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4380 static void check_buffer_tree_ref(struct extent_buffer *eb)
4384 * The TREE_REF bit is first set when the extent_buffer is added
4385 * to the radix tree. It is also reset, if unset, when a new reference
4386 * is created by find_extent_buffer.
4388 * It is only cleared in two cases: freeing the last non-tree
4389 * reference to the extent_buffer when its STALE bit is set or
4390 * calling release_folio when the tree reference is the only reference.
4392 * In both cases, care is taken to ensure that the extent_buffer's
4393 * pages are not under io. However, release_folio can be concurrently
4394 * called with creating new references, which is prone to race
4395 * conditions between the calls to check_buffer_tree_ref in those
4396 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4398 * The actual lifetime of the extent_buffer in the radix tree is
4399 * adequately protected by the refcount, but the TREE_REF bit and
4400 * its corresponding reference are not. To protect against this
4401 * class of races, we call check_buffer_tree_ref from the codepaths
4402 * which trigger io after they set eb->io_pages. Note that once io is
4403 * initiated, TREE_REF can no longer be cleared, so that is the
4404 * moment at which any such race is best fixed.
4406 refs = atomic_read(&eb->refs);
4407 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4410 spin_lock(&eb->refs_lock);
4411 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4412 atomic_inc(&eb->refs);
4413 spin_unlock(&eb->refs_lock);
4416 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4417 struct page *accessed)
4421 check_buffer_tree_ref(eb);
4423 num_pages = num_extent_pages(eb);
4424 for (i = 0; i < num_pages; i++) {
4425 struct page *p = eb->pages[i];
4428 mark_page_accessed(p);
4432 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4435 struct extent_buffer *eb;
4437 eb = find_extent_buffer_nolock(fs_info, start);
4441 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
4442 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
4443 * another task running free_extent_buffer() might have seen that flag
4444 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
4445 * writeback flags not set) and it's still in the tree (flag
4446 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
4447 * decrementing the extent buffer's reference count twice. So here we
4448 * could race and increment the eb's reference count, clear its stale
4449 * flag, mark it as dirty and drop our reference before the other task
4450 * finishes executing free_extent_buffer, which would later result in
4451 * an attempt to free an extent buffer that is dirty.
4453 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4454 spin_lock(&eb->refs_lock);
4455 spin_unlock(&eb->refs_lock);
4457 mark_extent_buffer_accessed(eb, NULL);
4461 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4462 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
4465 struct extent_buffer *eb, *exists = NULL;
4468 eb = find_extent_buffer(fs_info, start);
4471 eb = alloc_dummy_extent_buffer(fs_info, start);
4473 return ERR_PTR(-ENOMEM);
4474 eb->fs_info = fs_info;
4476 ret = radix_tree_preload(GFP_NOFS);
4478 exists = ERR_PTR(ret);
4481 spin_lock(&fs_info->buffer_lock);
4482 ret = radix_tree_insert(&fs_info->buffer_radix,
4483 start >> fs_info->sectorsize_bits, eb);
4484 spin_unlock(&fs_info->buffer_lock);
4485 radix_tree_preload_end();
4486 if (ret == -EEXIST) {
4487 exists = find_extent_buffer(fs_info, start);
4493 check_buffer_tree_ref(eb);
4494 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4498 btrfs_release_extent_buffer(eb);
4503 static struct extent_buffer *grab_extent_buffer(
4504 struct btrfs_fs_info *fs_info, struct page *page)
4506 struct extent_buffer *exists;
4509 * For subpage case, we completely rely on radix tree to ensure we
4510 * don't try to insert two ebs for the same bytenr. So here we always
4511 * return NULL and just continue.
4513 if (fs_info->nodesize < PAGE_SIZE)
4516 /* Page not yet attached to an extent buffer */
4517 if (!PagePrivate(page))
4521 * We could have already allocated an eb for this page and attached one
4522 * so lets see if we can get a ref on the existing eb, and if we can we
4523 * know it's good and we can just return that one, else we know we can
4524 * just overwrite page->private.
4526 exists = (struct extent_buffer *)page->private;
4527 if (atomic_inc_not_zero(&exists->refs))
4530 WARN_ON(PageDirty(page));
4531 detach_page_private(page);
4535 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
4537 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
4538 btrfs_err(fs_info, "bad tree block start %llu", start);
4542 if (fs_info->nodesize < PAGE_SIZE &&
4543 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
4545 "tree block crosses page boundary, start %llu nodesize %u",
4546 start, fs_info->nodesize);
4549 if (fs_info->nodesize >= PAGE_SIZE &&
4550 !PAGE_ALIGNED(start)) {
4552 "tree block is not page aligned, start %llu nodesize %u",
4553 start, fs_info->nodesize);
4559 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
4560 u64 start, u64 owner_root, int level)
4562 unsigned long len = fs_info->nodesize;
4565 unsigned long index = start >> PAGE_SHIFT;
4566 struct extent_buffer *eb;
4567 struct extent_buffer *exists = NULL;
4569 struct address_space *mapping = fs_info->btree_inode->i_mapping;
4570 u64 lockdep_owner = owner_root;
4574 if (check_eb_alignment(fs_info, start))
4575 return ERR_PTR(-EINVAL);
4577 #if BITS_PER_LONG == 32
4578 if (start >= MAX_LFS_FILESIZE) {
4579 btrfs_err_rl(fs_info,
4580 "extent buffer %llu is beyond 32bit page cache limit", start);
4581 btrfs_err_32bit_limit(fs_info);
4582 return ERR_PTR(-EOVERFLOW);
4584 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
4585 btrfs_warn_32bit_limit(fs_info);
4588 eb = find_extent_buffer(fs_info, start);
4592 eb = __alloc_extent_buffer(fs_info, start, len);
4594 return ERR_PTR(-ENOMEM);
4597 * The reloc trees are just snapshots, so we need them to appear to be
4598 * just like any other fs tree WRT lockdep.
4600 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
4601 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4603 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
4605 num_pages = num_extent_pages(eb);
4606 for (i = 0; i < num_pages; i++, index++) {
4607 struct btrfs_subpage *prealloc = NULL;
4609 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
4611 exists = ERR_PTR(-ENOMEM);
4616 * Preallocate page->private for subpage case, so that we won't
4617 * allocate memory with private_lock hold. The memory will be
4618 * freed by attach_extent_buffer_page() or freed manually if
4621 * Although we have ensured one subpage eb can only have one
4622 * page, but it may change in the future for 16K page size
4623 * support, so we still preallocate the memory in the loop.
4625 if (fs_info->nodesize < PAGE_SIZE) {
4626 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
4627 if (IS_ERR(prealloc)) {
4628 ret = PTR_ERR(prealloc);
4631 exists = ERR_PTR(ret);
4636 spin_lock(&mapping->private_lock);
4637 exists = grab_extent_buffer(fs_info, p);
4639 spin_unlock(&mapping->private_lock);
4642 mark_extent_buffer_accessed(exists, p);
4643 btrfs_free_subpage(prealloc);
4646 /* Should not fail, as we have preallocated the memory */
4647 ret = attach_extent_buffer_page(eb, p, prealloc);
4650 * To inform we have extra eb under allocation, so that
4651 * detach_extent_buffer_page() won't release the page private
4652 * when the eb hasn't yet been inserted into radix tree.
4654 * The ref will be decreased when the eb released the page, in
4655 * detach_extent_buffer_page().
4656 * Thus needs no special handling in error path.
4658 btrfs_page_inc_eb_refs(fs_info, p);
4659 spin_unlock(&mapping->private_lock);
4661 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
4663 if (!PageUptodate(p))
4667 * We can't unlock the pages just yet since the extent buffer
4668 * hasn't been properly inserted in the radix tree, this
4669 * opens a race with btree_release_folio which can free a page
4670 * while we are still filling in all pages for the buffer and
4675 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4677 ret = radix_tree_preload(GFP_NOFS);
4679 exists = ERR_PTR(ret);
4683 spin_lock(&fs_info->buffer_lock);
4684 ret = radix_tree_insert(&fs_info->buffer_radix,
4685 start >> fs_info->sectorsize_bits, eb);
4686 spin_unlock(&fs_info->buffer_lock);
4687 radix_tree_preload_end();
4688 if (ret == -EEXIST) {
4689 exists = find_extent_buffer(fs_info, start);
4695 /* add one reference for the tree */
4696 check_buffer_tree_ref(eb);
4697 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4700 * Now it's safe to unlock the pages because any calls to
4701 * btree_release_folio will correctly detect that a page belongs to a
4702 * live buffer and won't free them prematurely.
4704 for (i = 0; i < num_pages; i++)
4705 unlock_page(eb->pages[i]);
4709 WARN_ON(!atomic_dec_and_test(&eb->refs));
4710 for (i = 0; i < num_pages; i++) {
4712 unlock_page(eb->pages[i]);
4715 btrfs_release_extent_buffer(eb);
4719 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4721 struct extent_buffer *eb =
4722 container_of(head, struct extent_buffer, rcu_head);
4724 __free_extent_buffer(eb);
4727 static int release_extent_buffer(struct extent_buffer *eb)
4728 __releases(&eb->refs_lock)
4730 lockdep_assert_held(&eb->refs_lock);
4732 WARN_ON(atomic_read(&eb->refs) == 0);
4733 if (atomic_dec_and_test(&eb->refs)) {
4734 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4735 struct btrfs_fs_info *fs_info = eb->fs_info;
4737 spin_unlock(&eb->refs_lock);
4739 spin_lock(&fs_info->buffer_lock);
4740 radix_tree_delete(&fs_info->buffer_radix,
4741 eb->start >> fs_info->sectorsize_bits);
4742 spin_unlock(&fs_info->buffer_lock);
4744 spin_unlock(&eb->refs_lock);
4747 btrfs_leak_debug_del_eb(eb);
4748 /* Should be safe to release our pages at this point */
4749 btrfs_release_extent_buffer_pages(eb);
4750 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4751 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4752 __free_extent_buffer(eb);
4756 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4759 spin_unlock(&eb->refs_lock);
4764 void free_extent_buffer(struct extent_buffer *eb)
4770 refs = atomic_read(&eb->refs);
4772 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4773 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4776 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4780 spin_lock(&eb->refs_lock);
4781 if (atomic_read(&eb->refs) == 2 &&
4782 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4783 !extent_buffer_under_io(eb) &&
4784 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4785 atomic_dec(&eb->refs);
4788 * I know this is terrible, but it's temporary until we stop tracking
4789 * the uptodate bits and such for the extent buffers.
4791 release_extent_buffer(eb);
4794 void free_extent_buffer_stale(struct extent_buffer *eb)
4799 spin_lock(&eb->refs_lock);
4800 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4802 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4803 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4804 atomic_dec(&eb->refs);
4805 release_extent_buffer(eb);
4808 static void btree_clear_page_dirty(struct page *page)
4810 ASSERT(PageDirty(page));
4811 ASSERT(PageLocked(page));
4812 clear_page_dirty_for_io(page);
4813 xa_lock_irq(&page->mapping->i_pages);
4814 if (!PageDirty(page))
4815 __xa_clear_mark(&page->mapping->i_pages,
4816 page_index(page), PAGECACHE_TAG_DIRTY);
4817 xa_unlock_irq(&page->mapping->i_pages);
4820 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4822 struct btrfs_fs_info *fs_info = eb->fs_info;
4823 struct page *page = eb->pages[0];
4826 /* btree_clear_page_dirty() needs page locked */
4828 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4831 btree_clear_page_dirty(page);
4833 WARN_ON(atomic_read(&eb->refs) == 0);
4836 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
4842 if (eb->fs_info->nodesize < PAGE_SIZE)
4843 return clear_subpage_extent_buffer_dirty(eb);
4845 num_pages = num_extent_pages(eb);
4847 for (i = 0; i < num_pages; i++) {
4848 page = eb->pages[i];
4849 if (!PageDirty(page))
4852 btree_clear_page_dirty(page);
4853 ClearPageError(page);
4856 WARN_ON(atomic_read(&eb->refs) == 0);
4859 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4865 check_buffer_tree_ref(eb);
4867 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4869 num_pages = num_extent_pages(eb);
4870 WARN_ON(atomic_read(&eb->refs) == 0);
4871 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4874 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4877 * For subpage case, we can have other extent buffers in the
4878 * same page, and in clear_subpage_extent_buffer_dirty() we
4879 * have to clear page dirty without subpage lock held.
4880 * This can cause race where our page gets dirty cleared after
4883 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4884 * its page for other reasons, we can use page lock to prevent
4888 lock_page(eb->pages[0]);
4889 for (i = 0; i < num_pages; i++)
4890 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4891 eb->start, eb->len);
4893 unlock_page(eb->pages[0]);
4895 #ifdef CONFIG_BTRFS_DEBUG
4896 for (i = 0; i < num_pages; i++)
4897 ASSERT(PageDirty(eb->pages[i]));
4903 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4905 struct btrfs_fs_info *fs_info = eb->fs_info;
4910 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4911 num_pages = num_extent_pages(eb);
4912 for (i = 0; i < num_pages; i++) {
4913 page = eb->pages[i];
4918 * This is special handling for metadata subpage, as regular
4919 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4921 if (fs_info->nodesize >= PAGE_SIZE)
4922 ClearPageUptodate(page);
4924 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4929 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4931 struct btrfs_fs_info *fs_info = eb->fs_info;
4936 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4937 num_pages = num_extent_pages(eb);
4938 for (i = 0; i < num_pages; i++) {
4939 page = eb->pages[i];
4942 * This is special handling for metadata subpage, as regular
4943 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4945 if (fs_info->nodesize >= PAGE_SIZE)
4946 SetPageUptodate(page);
4948 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4953 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4956 struct btrfs_fs_info *fs_info = eb->fs_info;
4957 struct extent_io_tree *io_tree;
4958 struct page *page = eb->pages[0];
4959 struct btrfs_bio_ctrl bio_ctrl = {
4960 .mirror_num = mirror_num,
4964 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4965 ASSERT(PagePrivate(page));
4966 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4968 if (wait == WAIT_NONE) {
4969 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
4972 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4978 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4979 PageUptodate(page) ||
4980 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4981 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4982 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4986 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4987 eb->read_mirror = 0;
4988 atomic_set(&eb->io_pages, 1);
4989 check_buffer_tree_ref(eb);
4990 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
4992 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
4993 ret = submit_extent_page(REQ_OP_READ, NULL, &bio_ctrl,
4994 page, eb->start, eb->len,
4995 eb->start - page_offset(page),
4996 end_bio_extent_readpage, 0, true);
4999 * In the endio function, if we hit something wrong we will
5000 * increase the io_pages, so here we need to decrease it for
5003 atomic_dec(&eb->io_pages);
5005 submit_one_bio(&bio_ctrl);
5006 if (ret || wait != WAIT_COMPLETE)
5009 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
5010 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5015 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5021 int locked_pages = 0;
5022 int all_uptodate = 1;
5024 unsigned long num_reads = 0;
5025 struct btrfs_bio_ctrl bio_ctrl = {
5026 .mirror_num = mirror_num,
5029 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5033 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
5034 * operation, which could potentially still be in flight. In this case
5035 * we simply want to return an error.
5037 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
5040 if (eb->fs_info->nodesize < PAGE_SIZE)
5041 return read_extent_buffer_subpage(eb, wait, mirror_num);
5043 num_pages = num_extent_pages(eb);
5044 for (i = 0; i < num_pages; i++) {
5045 page = eb->pages[i];
5046 if (wait == WAIT_NONE) {
5048 * WAIT_NONE is only utilized by readahead. If we can't
5049 * acquire the lock atomically it means either the eb
5050 * is being read out or under modification.
5051 * Either way the eb will be or has been cached,
5052 * readahead can exit safely.
5054 if (!trylock_page(page))
5062 * We need to firstly lock all pages to make sure that
5063 * the uptodate bit of our pages won't be affected by
5064 * clear_extent_buffer_uptodate().
5066 for (i = 0; i < num_pages; i++) {
5067 page = eb->pages[i];
5068 if (!PageUptodate(page)) {
5075 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5079 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5080 eb->read_mirror = 0;
5081 atomic_set(&eb->io_pages, num_reads);
5083 * It is possible for release_folio to clear the TREE_REF bit before we
5084 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5086 check_buffer_tree_ref(eb);
5087 for (i = 0; i < num_pages; i++) {
5088 page = eb->pages[i];
5090 if (!PageUptodate(page)) {
5092 atomic_dec(&eb->io_pages);
5097 ClearPageError(page);
5098 err = submit_extent_page(REQ_OP_READ, NULL,
5099 &bio_ctrl, page, page_offset(page),
5100 PAGE_SIZE, 0, end_bio_extent_readpage,
5104 * We failed to submit the bio so it's the
5105 * caller's responsibility to perform cleanup
5106 * i.e unlock page/set error bit.
5111 atomic_dec(&eb->io_pages);
5118 submit_one_bio(&bio_ctrl);
5120 if (ret || wait != WAIT_COMPLETE)
5123 for (i = 0; i < num_pages; i++) {
5124 page = eb->pages[i];
5125 wait_on_page_locked(page);
5126 if (!PageUptodate(page))
5133 while (locked_pages > 0) {
5135 page = eb->pages[locked_pages];
5141 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5144 btrfs_warn(eb->fs_info,
5145 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
5146 eb->start, eb->len, start, len);
5147 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5153 * Check if the [start, start + len) range is valid before reading/writing
5155 * NOTE: @start and @len are offset inside the eb, not logical address.
5157 * Caller should not touch the dst/src memory if this function returns error.
5159 static inline int check_eb_range(const struct extent_buffer *eb,
5160 unsigned long start, unsigned long len)
5162 unsigned long offset;
5164 /* start, start + len should not go beyond eb->len nor overflow */
5165 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5166 return report_eb_range(eb, start, len);
5171 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5172 unsigned long start, unsigned long len)
5178 char *dst = (char *)dstv;
5179 unsigned long i = get_eb_page_index(start);
5181 if (check_eb_range(eb, start, len))
5184 offset = get_eb_offset_in_page(eb, start);
5187 page = eb->pages[i];
5189 cur = min(len, (PAGE_SIZE - offset));
5190 kaddr = page_address(page);
5191 memcpy(dst, kaddr + offset, cur);
5200 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5202 unsigned long start, unsigned long len)
5208 char __user *dst = (char __user *)dstv;
5209 unsigned long i = get_eb_page_index(start);
5212 WARN_ON(start > eb->len);
5213 WARN_ON(start + len > eb->start + eb->len);
5215 offset = get_eb_offset_in_page(eb, start);
5218 page = eb->pages[i];
5220 cur = min(len, (PAGE_SIZE - offset));
5221 kaddr = page_address(page);
5222 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
5236 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5237 unsigned long start, unsigned long len)
5243 char *ptr = (char *)ptrv;
5244 unsigned long i = get_eb_page_index(start);
5247 if (check_eb_range(eb, start, len))
5250 offset = get_eb_offset_in_page(eb, start);
5253 page = eb->pages[i];
5255 cur = min(len, (PAGE_SIZE - offset));
5257 kaddr = page_address(page);
5258 ret = memcmp(ptr, kaddr + offset, cur);
5271 * Check that the extent buffer is uptodate.
5273 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
5274 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
5276 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
5279 struct btrfs_fs_info *fs_info = eb->fs_info;
5282 * If we are using the commit root we could potentially clear a page
5283 * Uptodate while we're using the extent buffer that we've previously
5284 * looked up. We don't want to complain in this case, as the page was
5285 * valid before, we just didn't write it out. Instead we want to catch
5286 * the case where we didn't actually read the block properly, which
5287 * would have !PageUptodate && !PageError, as we clear PageError before
5290 if (fs_info->nodesize < PAGE_SIZE) {
5291 bool uptodate, error;
5293 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
5294 eb->start, eb->len);
5295 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
5296 WARN_ON(!uptodate && !error);
5298 WARN_ON(!PageUptodate(page) && !PageError(page));
5302 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
5307 assert_eb_page_uptodate(eb, eb->pages[0]);
5308 kaddr = page_address(eb->pages[0]) +
5309 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
5311 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5314 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
5318 assert_eb_page_uptodate(eb, eb->pages[0]);
5319 kaddr = page_address(eb->pages[0]) +
5320 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
5321 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5324 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
5325 unsigned long start, unsigned long len)
5331 char *src = (char *)srcv;
5332 unsigned long i = get_eb_page_index(start);
5334 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
5336 if (check_eb_range(eb, start, len))
5339 offset = get_eb_offset_in_page(eb, start);
5342 page = eb->pages[i];
5343 assert_eb_page_uptodate(eb, page);
5345 cur = min(len, PAGE_SIZE - offset);
5346 kaddr = page_address(page);
5347 memcpy(kaddr + offset, src, cur);
5356 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
5363 unsigned long i = get_eb_page_index(start);
5365 if (check_eb_range(eb, start, len))
5368 offset = get_eb_offset_in_page(eb, start);
5371 page = eb->pages[i];
5372 assert_eb_page_uptodate(eb, page);
5374 cur = min(len, PAGE_SIZE - offset);
5375 kaddr = page_address(page);
5376 memset(kaddr + offset, 0, cur);
5384 void copy_extent_buffer_full(const struct extent_buffer *dst,
5385 const struct extent_buffer *src)
5390 ASSERT(dst->len == src->len);
5392 if (dst->fs_info->nodesize >= PAGE_SIZE) {
5393 num_pages = num_extent_pages(dst);
5394 for (i = 0; i < num_pages; i++)
5395 copy_page(page_address(dst->pages[i]),
5396 page_address(src->pages[i]));
5398 size_t src_offset = get_eb_offset_in_page(src, 0);
5399 size_t dst_offset = get_eb_offset_in_page(dst, 0);
5401 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
5402 memcpy(page_address(dst->pages[0]) + dst_offset,
5403 page_address(src->pages[0]) + src_offset,
5408 void copy_extent_buffer(const struct extent_buffer *dst,
5409 const struct extent_buffer *src,
5410 unsigned long dst_offset, unsigned long src_offset,
5413 u64 dst_len = dst->len;
5418 unsigned long i = get_eb_page_index(dst_offset);
5420 if (check_eb_range(dst, dst_offset, len) ||
5421 check_eb_range(src, src_offset, len))
5424 WARN_ON(src->len != dst_len);
5426 offset = get_eb_offset_in_page(dst, dst_offset);
5429 page = dst->pages[i];
5430 assert_eb_page_uptodate(dst, page);
5432 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5434 kaddr = page_address(page);
5435 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5445 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5447 * @eb: the extent buffer
5448 * @start: offset of the bitmap item in the extent buffer
5450 * @page_index: return index of the page in the extent buffer that contains the
5452 * @page_offset: return offset into the page given by page_index
5454 * This helper hides the ugliness of finding the byte in an extent buffer which
5455 * contains a given bit.
5457 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
5458 unsigned long start, unsigned long nr,
5459 unsigned long *page_index,
5460 size_t *page_offset)
5462 size_t byte_offset = BIT_BYTE(nr);
5466 * The byte we want is the offset of the extent buffer + the offset of
5467 * the bitmap item in the extent buffer + the offset of the byte in the
5470 offset = start + offset_in_page(eb->start) + byte_offset;
5472 *page_index = offset >> PAGE_SHIFT;
5473 *page_offset = offset_in_page(offset);
5477 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5478 * @eb: the extent buffer
5479 * @start: offset of the bitmap item in the extent buffer
5480 * @nr: bit number to test
5482 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
5490 eb_bitmap_offset(eb, start, nr, &i, &offset);
5491 page = eb->pages[i];
5492 assert_eb_page_uptodate(eb, page);
5493 kaddr = page_address(page);
5494 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5498 * extent_buffer_bitmap_set - set an area of a bitmap
5499 * @eb: the extent buffer
5500 * @start: offset of the bitmap item in the extent buffer
5501 * @pos: bit number of the first bit
5502 * @len: number of bits to set
5504 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
5505 unsigned long pos, unsigned long len)
5511 const unsigned int size = pos + len;
5512 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5513 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5515 eb_bitmap_offset(eb, start, pos, &i, &offset);
5516 page = eb->pages[i];
5517 assert_eb_page_uptodate(eb, page);
5518 kaddr = page_address(page);
5520 while (len >= bits_to_set) {
5521 kaddr[offset] |= mask_to_set;
5523 bits_to_set = BITS_PER_BYTE;
5525 if (++offset >= PAGE_SIZE && len > 0) {
5527 page = eb->pages[++i];
5528 assert_eb_page_uptodate(eb, page);
5529 kaddr = page_address(page);
5533 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5534 kaddr[offset] |= mask_to_set;
5540 * extent_buffer_bitmap_clear - clear an area of a bitmap
5541 * @eb: the extent buffer
5542 * @start: offset of the bitmap item in the extent buffer
5543 * @pos: bit number of the first bit
5544 * @len: number of bits to clear
5546 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
5547 unsigned long start, unsigned long pos,
5554 const unsigned int size = pos + len;
5555 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5556 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5558 eb_bitmap_offset(eb, start, pos, &i, &offset);
5559 page = eb->pages[i];
5560 assert_eb_page_uptodate(eb, page);
5561 kaddr = page_address(page);
5563 while (len >= bits_to_clear) {
5564 kaddr[offset] &= ~mask_to_clear;
5565 len -= bits_to_clear;
5566 bits_to_clear = BITS_PER_BYTE;
5568 if (++offset >= PAGE_SIZE && len > 0) {
5570 page = eb->pages[++i];
5571 assert_eb_page_uptodate(eb, page);
5572 kaddr = page_address(page);
5576 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5577 kaddr[offset] &= ~mask_to_clear;
5581 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5583 unsigned long distance = (src > dst) ? src - dst : dst - src;
5584 return distance < len;
5587 static void copy_pages(struct page *dst_page, struct page *src_page,
5588 unsigned long dst_off, unsigned long src_off,
5591 char *dst_kaddr = page_address(dst_page);
5593 int must_memmove = 0;
5595 if (dst_page != src_page) {
5596 src_kaddr = page_address(src_page);
5598 src_kaddr = dst_kaddr;
5599 if (areas_overlap(src_off, dst_off, len))
5604 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5606 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5609 void memcpy_extent_buffer(const struct extent_buffer *dst,
5610 unsigned long dst_offset, unsigned long src_offset,
5614 size_t dst_off_in_page;
5615 size_t src_off_in_page;
5616 unsigned long dst_i;
5617 unsigned long src_i;
5619 if (check_eb_range(dst, dst_offset, len) ||
5620 check_eb_range(dst, src_offset, len))
5624 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
5625 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
5627 dst_i = get_eb_page_index(dst_offset);
5628 src_i = get_eb_page_index(src_offset);
5630 cur = min(len, (unsigned long)(PAGE_SIZE -
5632 cur = min_t(unsigned long, cur,
5633 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5635 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5636 dst_off_in_page, src_off_in_page, cur);
5644 void memmove_extent_buffer(const struct extent_buffer *dst,
5645 unsigned long dst_offset, unsigned long src_offset,
5649 size_t dst_off_in_page;
5650 size_t src_off_in_page;
5651 unsigned long dst_end = dst_offset + len - 1;
5652 unsigned long src_end = src_offset + len - 1;
5653 unsigned long dst_i;
5654 unsigned long src_i;
5656 if (check_eb_range(dst, dst_offset, len) ||
5657 check_eb_range(dst, src_offset, len))
5659 if (dst_offset < src_offset) {
5660 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5664 dst_i = get_eb_page_index(dst_end);
5665 src_i = get_eb_page_index(src_end);
5667 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
5668 src_off_in_page = get_eb_offset_in_page(dst, src_end);
5670 cur = min_t(unsigned long, len, src_off_in_page + 1);
5671 cur = min(cur, dst_off_in_page + 1);
5672 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5673 dst_off_in_page - cur + 1,
5674 src_off_in_page - cur + 1, cur);
5682 #define GANG_LOOKUP_SIZE 16
5683 static struct extent_buffer *get_next_extent_buffer(
5684 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
5686 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
5687 struct extent_buffer *found = NULL;
5688 u64 page_start = page_offset(page);
5689 u64 cur = page_start;
5691 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
5692 lockdep_assert_held(&fs_info->buffer_lock);
5694 while (cur < page_start + PAGE_SIZE) {
5698 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
5699 (void **)gang, cur >> fs_info->sectorsize_bits,
5700 min_t(unsigned int, GANG_LOOKUP_SIZE,
5701 PAGE_SIZE / fs_info->nodesize));
5704 for (i = 0; i < ret; i++) {
5705 /* Already beyond page end */
5706 if (gang[i]->start >= page_start + PAGE_SIZE)
5709 if (gang[i]->start >= bytenr) {
5714 cur = gang[ret - 1]->start + gang[ret - 1]->len;
5720 static int try_release_subpage_extent_buffer(struct page *page)
5722 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5723 u64 cur = page_offset(page);
5724 const u64 end = page_offset(page) + PAGE_SIZE;
5728 struct extent_buffer *eb = NULL;
5731 * Unlike try_release_extent_buffer() which uses page->private
5732 * to grab buffer, for subpage case we rely on radix tree, thus
5733 * we need to ensure radix tree consistency.
5735 * We also want an atomic snapshot of the radix tree, thus go
5736 * with spinlock rather than RCU.
5738 spin_lock(&fs_info->buffer_lock);
5739 eb = get_next_extent_buffer(fs_info, page, cur);
5741 /* No more eb in the page range after or at cur */
5742 spin_unlock(&fs_info->buffer_lock);
5745 cur = eb->start + eb->len;
5748 * The same as try_release_extent_buffer(), to ensure the eb
5749 * won't disappear out from under us.
5751 spin_lock(&eb->refs_lock);
5752 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5753 spin_unlock(&eb->refs_lock);
5754 spin_unlock(&fs_info->buffer_lock);
5757 spin_unlock(&fs_info->buffer_lock);
5760 * If tree ref isn't set then we know the ref on this eb is a
5761 * real ref, so just return, this eb will likely be freed soon
5764 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5765 spin_unlock(&eb->refs_lock);
5770 * Here we don't care about the return value, we will always
5771 * check the page private at the end. And
5772 * release_extent_buffer() will release the refs_lock.
5774 release_extent_buffer(eb);
5777 * Finally to check if we have cleared page private, as if we have
5778 * released all ebs in the page, the page private should be cleared now.
5780 spin_lock(&page->mapping->private_lock);
5781 if (!PagePrivate(page))
5785 spin_unlock(&page->mapping->private_lock);
5790 int try_release_extent_buffer(struct page *page)
5792 struct extent_buffer *eb;
5794 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5795 return try_release_subpage_extent_buffer(page);
5798 * We need to make sure nobody is changing page->private, as we rely on
5799 * page->private as the pointer to extent buffer.
5801 spin_lock(&page->mapping->private_lock);
5802 if (!PagePrivate(page)) {
5803 spin_unlock(&page->mapping->private_lock);
5807 eb = (struct extent_buffer *)page->private;
5811 * This is a little awful but should be ok, we need to make sure that
5812 * the eb doesn't disappear out from under us while we're looking at
5815 spin_lock(&eb->refs_lock);
5816 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5817 spin_unlock(&eb->refs_lock);
5818 spin_unlock(&page->mapping->private_lock);
5821 spin_unlock(&page->mapping->private_lock);
5824 * If tree ref isn't set then we know the ref on this eb is a real ref,
5825 * so just return, this page will likely be freed soon anyway.
5827 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5828 spin_unlock(&eb->refs_lock);
5832 return release_extent_buffer(eb);
5836 * btrfs_readahead_tree_block - attempt to readahead a child block
5837 * @fs_info: the fs_info
5838 * @bytenr: bytenr to read
5839 * @owner_root: objectid of the root that owns this eb
5840 * @gen: generation for the uptodate check, can be 0
5841 * @level: level for the eb
5843 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5844 * normal uptodate check of the eb, without checking the generation. If we have
5845 * to read the block we will not block on anything.
5847 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5848 u64 bytenr, u64 owner_root, u64 gen, int level)
5850 struct extent_buffer *eb;
5853 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5857 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5858 free_extent_buffer(eb);
5862 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
5864 free_extent_buffer_stale(eb);
5866 free_extent_buffer(eb);
5870 * btrfs_readahead_node_child - readahead a node's child block
5871 * @node: parent node we're reading from
5872 * @slot: slot in the parent node for the child we want to read
5874 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5875 * the slot in the node provided.
5877 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5879 btrfs_readahead_tree_block(node->fs_info,
5880 btrfs_node_blockptr(node, slot),
5881 btrfs_header_owner(node),
5882 btrfs_node_ptr_generation(node, slot),
5883 btrfs_header_level(node) - 1);