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;
98 btrfs_bio_end_io_t end_io_func;
101 struct extent_page_data {
102 struct btrfs_bio_ctrl bio_ctrl;
103 /* tells writepage not to lock the state bits for this range
104 * it still does the unlocking
106 unsigned int extent_locked:1;
108 /* tells the submit_bio code to use REQ_SYNC */
109 unsigned int sync_io:1;
112 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
123 bv = bio_first_bvec_all(bio);
124 inode = bv->bv_page->mapping->host;
125 mirror_num = bio_ctrl->mirror_num;
127 /* Caller should ensure the bio has at least some range added */
128 ASSERT(bio->bi_iter.bi_size);
130 btrfs_bio(bio)->file_offset = page_offset(bv->bv_page) + bv->bv_offset;
132 if (!is_data_inode(inode))
133 btrfs_submit_metadata_bio(inode, bio, mirror_num);
134 else if (btrfs_op(bio) == BTRFS_MAP_WRITE)
135 btrfs_submit_data_write_bio(inode, bio, mirror_num);
137 btrfs_submit_data_read_bio(inode, bio, mirror_num,
138 bio_ctrl->compress_type);
140 /* The bio is owned by the end_io handler now */
141 bio_ctrl->bio = NULL;
145 * Submit or fail the current bio in an extent_page_data structure.
147 static void submit_write_bio(struct extent_page_data *epd, int ret)
149 struct bio *bio = epd->bio_ctrl.bio;
156 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
157 /* The bio is owned by the end_io handler now */
158 epd->bio_ctrl.bio = NULL;
160 submit_one_bio(&epd->bio_ctrl);
164 int __init extent_buffer_init_cachep(void)
166 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
167 sizeof(struct extent_buffer), 0,
168 SLAB_MEM_SPREAD, NULL);
169 if (!extent_buffer_cache)
175 void __cold extent_buffer_free_cachep(void)
178 * Make sure all delayed rcu free are flushed before we
182 kmem_cache_destroy(extent_buffer_cache);
185 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
187 unsigned long index = start >> PAGE_SHIFT;
188 unsigned long end_index = end >> PAGE_SHIFT;
191 while (index <= end_index) {
192 page = find_get_page(inode->i_mapping, index);
193 BUG_ON(!page); /* Pages should be in the extent_io_tree */
194 clear_page_dirty_for_io(page);
200 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
202 struct address_space *mapping = inode->i_mapping;
203 unsigned long index = start >> PAGE_SHIFT;
204 unsigned long end_index = end >> PAGE_SHIFT;
207 while (index <= end_index) {
208 folio = filemap_get_folio(mapping, index);
209 filemap_dirty_folio(mapping, folio);
210 folio_account_redirty(folio);
211 index += folio_nr_pages(folio);
217 * Process one page for __process_pages_contig().
219 * Return >0 if we hit @page == @locked_page.
220 * Return 0 if we updated the page status.
221 * Return -EGAIN if the we need to try again.
222 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
224 static int process_one_page(struct btrfs_fs_info *fs_info,
225 struct address_space *mapping,
226 struct page *page, struct page *locked_page,
227 unsigned long page_ops, u64 start, u64 end)
231 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
232 len = end + 1 - start;
234 if (page_ops & PAGE_SET_ORDERED)
235 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
236 if (page_ops & PAGE_SET_ERROR)
237 btrfs_page_clamp_set_error(fs_info, page, start, len);
238 if (page_ops & PAGE_START_WRITEBACK) {
239 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
240 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
242 if (page_ops & PAGE_END_WRITEBACK)
243 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
245 if (page == locked_page)
248 if (page_ops & PAGE_LOCK) {
251 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
254 if (!PageDirty(page) || page->mapping != mapping) {
255 btrfs_page_end_writer_lock(fs_info, page, start, len);
259 if (page_ops & PAGE_UNLOCK)
260 btrfs_page_end_writer_lock(fs_info, page, start, len);
264 static int __process_pages_contig(struct address_space *mapping,
265 struct page *locked_page,
266 u64 start, u64 end, unsigned long page_ops,
269 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
270 pgoff_t start_index = start >> PAGE_SHIFT;
271 pgoff_t end_index = end >> PAGE_SHIFT;
272 pgoff_t index = start_index;
273 unsigned long pages_processed = 0;
274 struct folio_batch fbatch;
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) && start_index <= end_index)
284 mapping_set_error(mapping, -EIO);
286 folio_batch_init(&fbatch);
287 while (index <= end_index) {
290 found_folios = filemap_get_folios_contig(mapping, &index,
293 if (found_folios == 0) {
295 * Only if we're going to lock these pages, we can find
298 ASSERT(page_ops & PAGE_LOCK);
303 for (i = 0; i < found_folios; i++) {
305 struct folio *folio = fbatch.folios[i];
306 process_ret = process_one_page(fs_info, mapping,
307 &folio->page, locked_page, page_ops,
309 if (process_ret < 0) {
311 folio_batch_release(&fbatch);
314 pages_processed += folio_nr_pages(folio);
316 folio_batch_release(&fbatch);
320 if (err && processed_end) {
322 * Update @processed_end. I know this is awful since it has
323 * two different return value patterns (inclusive vs exclusive).
325 * But the exclusive pattern is necessary if @start is 0, or we
326 * underflow and check against processed_end won't work as
330 *processed_end = min(end,
331 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
333 *processed_end = start;
338 static noinline void __unlock_for_delalloc(struct inode *inode,
339 struct page *locked_page,
342 unsigned long index = start >> PAGE_SHIFT;
343 unsigned long end_index = end >> PAGE_SHIFT;
346 if (index == locked_page->index && end_index == index)
349 __process_pages_contig(inode->i_mapping, locked_page, start, end,
353 static noinline int lock_delalloc_pages(struct inode *inode,
354 struct page *locked_page,
358 unsigned long index = delalloc_start >> PAGE_SHIFT;
359 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
360 u64 processed_end = delalloc_start;
364 if (index == locked_page->index && index == end_index)
367 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
368 delalloc_end, PAGE_LOCK, &processed_end);
369 if (ret == -EAGAIN && processed_end > delalloc_start)
370 __unlock_for_delalloc(inode, locked_page, delalloc_start,
376 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
377 * more than @max_bytes.
379 * @start: The original start bytenr to search.
380 * Will store the extent range start bytenr.
381 * @end: The original end bytenr of the search range
382 * Will store the extent range end bytenr.
384 * Return true if we find a delalloc range which starts inside the original
385 * range, and @start/@end will store the delalloc range start/end.
387 * Return false if we can't find any delalloc range which starts inside the
388 * original range, and @start/@end will be the non-delalloc range start/end.
391 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
392 struct page *locked_page, u64 *start,
395 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
396 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
397 const u64 orig_start = *start;
398 const u64 orig_end = *end;
399 /* The sanity tests may not set a valid fs_info. */
400 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
404 struct extent_state *cached_state = NULL;
408 /* Caller should pass a valid @end to indicate the search range end */
409 ASSERT(orig_end > orig_start);
411 /* The range should at least cover part of the page */
412 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
413 orig_end <= page_offset(locked_page)));
415 /* step one, find a bunch of delalloc bytes starting at start */
416 delalloc_start = *start;
418 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
419 max_bytes, &cached_state);
420 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
421 *start = delalloc_start;
423 /* @delalloc_end can be -1, never go beyond @orig_end */
424 *end = min(delalloc_end, orig_end);
425 free_extent_state(cached_state);
430 * start comes from the offset of locked_page. We have to lock
431 * pages in order, so we can't process delalloc bytes before
434 if (delalloc_start < *start)
435 delalloc_start = *start;
438 * make sure to limit the number of pages we try to lock down
440 if (delalloc_end + 1 - delalloc_start > max_bytes)
441 delalloc_end = delalloc_start + max_bytes - 1;
443 /* step two, lock all the pages after the page that has start */
444 ret = lock_delalloc_pages(inode, locked_page,
445 delalloc_start, delalloc_end);
446 ASSERT(!ret || ret == -EAGAIN);
447 if (ret == -EAGAIN) {
448 /* some of the pages are gone, lets avoid looping by
449 * shortening the size of the delalloc range we're searching
451 free_extent_state(cached_state);
454 max_bytes = PAGE_SIZE;
463 /* step three, lock the state bits for the whole range */
464 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
466 /* then test to make sure it is all still delalloc */
467 ret = test_range_bit(tree, delalloc_start, delalloc_end,
468 EXTENT_DELALLOC, 1, cached_state);
470 unlock_extent(tree, delalloc_start, delalloc_end,
472 __unlock_for_delalloc(inode, locked_page,
473 delalloc_start, delalloc_end);
477 free_extent_state(cached_state);
478 *start = delalloc_start;
484 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
485 struct page *locked_page,
486 u32 clear_bits, unsigned long page_ops)
488 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
490 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
491 start, end, page_ops, NULL);
494 static int insert_failrec(struct btrfs_inode *inode,
495 struct io_failure_record *failrec)
497 struct rb_node *exist;
499 spin_lock(&inode->io_failure_lock);
500 exist = rb_simple_insert(&inode->io_failure_tree, failrec->bytenr,
502 spin_unlock(&inode->io_failure_lock);
504 return (exist == NULL) ? 0 : -EEXIST;
507 static struct io_failure_record *get_failrec(struct btrfs_inode *inode, u64 start)
509 struct rb_node *node;
510 struct io_failure_record *failrec = ERR_PTR(-ENOENT);
512 spin_lock(&inode->io_failure_lock);
513 node = rb_simple_search(&inode->io_failure_tree, start);
515 failrec = rb_entry(node, struct io_failure_record, rb_node);
516 spin_unlock(&inode->io_failure_lock);
520 static void free_io_failure(struct btrfs_inode *inode,
521 struct io_failure_record *rec)
523 spin_lock(&inode->io_failure_lock);
524 rb_erase(&rec->rb_node, &inode->io_failure_tree);
525 spin_unlock(&inode->io_failure_lock);
531 * this bypasses the standard btrfs submit functions deliberately, as
532 * the standard behavior is to write all copies in a raid setup. here we only
533 * want to write the one bad copy. so we do the mapping for ourselves and issue
534 * submit_bio directly.
535 * to avoid any synchronization issues, wait for the data after writing, which
536 * actually prevents the read that triggered the error from finishing.
537 * currently, there can be no more than two copies of every data bit. thus,
538 * exactly one rewrite is required.
540 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
541 u64 length, u64 logical, struct page *page,
542 unsigned int pg_offset, int mirror_num)
544 struct btrfs_device *dev;
549 struct btrfs_io_context *bioc = NULL;
552 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
555 if (btrfs_repair_one_zone(fs_info, logical))
561 * Avoid races with device replace and make sure our bioc has devices
562 * associated to its stripes that don't go away while we are doing the
563 * read repair operation.
565 btrfs_bio_counter_inc_blocked(fs_info);
566 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
568 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
569 * to update all raid stripes, but here we just want to correct
570 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
571 * stripe's dev and sector.
573 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
574 &map_length, &bioc, 0);
576 goto out_counter_dec;
577 ASSERT(bioc->mirror_num == 1);
579 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
580 &map_length, &bioc, mirror_num);
582 goto out_counter_dec;
584 * This happens when dev-replace is also running, and the
585 * mirror_num indicates the dev-replace target.
587 * In this case, we don't need to do anything, as the read
588 * error just means the replace progress hasn't reached our
589 * read range, and later replace routine would handle it well.
591 if (mirror_num != bioc->mirror_num)
592 goto out_counter_dec;
595 sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
596 dev = bioc->stripes[bioc->mirror_num - 1].dev;
597 btrfs_put_bioc(bioc);
599 if (!dev || !dev->bdev ||
600 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
602 goto out_counter_dec;
605 bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
606 bio.bi_iter.bi_sector = sector;
607 __bio_add_page(&bio, page, length, pg_offset);
609 btrfsic_check_bio(&bio);
610 ret = submit_bio_wait(&bio);
612 /* try to remap that extent elsewhere? */
613 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
617 btrfs_info_rl_in_rcu(fs_info,
618 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
620 rcu_str_deref(dev->name), sector);
626 btrfs_bio_counter_dec(fs_info);
630 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
632 struct btrfs_fs_info *fs_info = eb->fs_info;
633 u64 start = eb->start;
634 int i, num_pages = num_extent_pages(eb);
637 if (sb_rdonly(fs_info->sb))
640 for (i = 0; i < num_pages; i++) {
641 struct page *p = eb->pages[i];
643 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
644 start - page_offset(p), mirror_num);
653 static int next_mirror(const struct io_failure_record *failrec, int cur_mirror)
655 if (cur_mirror == failrec->num_copies)
656 return cur_mirror + 1 - failrec->num_copies;
657 return cur_mirror + 1;
660 static int prev_mirror(const struct io_failure_record *failrec, int cur_mirror)
663 return failrec->num_copies;
664 return cur_mirror - 1;
668 * each time an IO finishes, we do a fast check in the IO failure tree
669 * to see if we need to process or clean up an io_failure_record
671 int btrfs_clean_io_failure(struct btrfs_inode *inode, u64 start,
672 struct page *page, unsigned int pg_offset)
674 struct btrfs_fs_info *fs_info = inode->root->fs_info;
675 struct extent_io_tree *io_tree = &inode->io_tree;
676 u64 ino = btrfs_ino(inode);
677 u64 locked_start, locked_end;
678 struct io_failure_record *failrec;
682 failrec = get_failrec(inode, start);
686 BUG_ON(!failrec->this_mirror);
688 if (sb_rdonly(fs_info->sb))
691 ret = find_first_extent_bit(io_tree, failrec->bytenr, &locked_start,
692 &locked_end, EXTENT_LOCKED, NULL);
693 if (ret || locked_start > failrec->bytenr ||
694 locked_end < failrec->bytenr + failrec->len - 1)
697 mirror = failrec->this_mirror;
699 mirror = prev_mirror(failrec, mirror);
700 repair_io_failure(fs_info, ino, start, failrec->len,
701 failrec->logical, page, pg_offset, mirror);
702 } while (mirror != failrec->failed_mirror);
705 free_io_failure(inode, failrec);
712 * - under ordered extent
713 * - the inode is freeing
715 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
717 struct io_failure_record *failrec;
718 struct rb_node *node, *next;
720 if (RB_EMPTY_ROOT(&inode->io_failure_tree))
723 spin_lock(&inode->io_failure_lock);
724 node = rb_simple_search_first(&inode->io_failure_tree, start);
726 failrec = rb_entry(node, struct io_failure_record, rb_node);
727 if (failrec->bytenr > end)
730 next = rb_next(node);
731 rb_erase(&failrec->rb_node, &inode->io_failure_tree);
736 spin_unlock(&inode->io_failure_lock);
739 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
740 struct btrfs_bio *bbio,
741 unsigned int bio_offset)
743 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
744 u64 start = bbio->file_offset + bio_offset;
745 struct io_failure_record *failrec;
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);
803 int btrfs_repair_one_sector(struct inode *inode, struct btrfs_bio *failed_bbio,
804 u32 bio_offset, struct page *page, unsigned int pgoff,
805 submit_bio_hook_t *submit_bio_hook)
807 u64 start = failed_bbio->file_offset + bio_offset;
808 struct io_failure_record *failrec;
809 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
810 struct bio *failed_bio = &failed_bbio->bio;
811 const int icsum = bio_offset >> fs_info->sectorsize_bits;
812 struct bio *repair_bio;
813 struct btrfs_bio *repair_bbio;
816 "repair read error: read error at %llu", start);
818 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
820 failrec = btrfs_get_io_failure_record(inode, failed_bbio, bio_offset);
822 return PTR_ERR(failrec);
825 * There are two premises:
826 * a) deliver good data to the caller
827 * b) correct the bad sectors on disk
829 * Since we're only doing repair for one sector, we only need to get
830 * a good copy of the failed sector and if we succeed, we have setup
831 * everything for repair_io_failure to do the rest for us.
833 failrec->this_mirror = next_mirror(failrec, failrec->this_mirror);
834 if (failrec->this_mirror == failrec->failed_mirror) {
836 "failed to repair num_copies %d this_mirror %d failed_mirror %d",
837 failrec->num_copies, failrec->this_mirror, failrec->failed_mirror);
838 free_io_failure(BTRFS_I(inode), failrec);
842 repair_bio = btrfs_bio_alloc(1, REQ_OP_READ, failed_bbio->end_io,
843 failed_bbio->private);
844 repair_bbio = btrfs_bio(repair_bio);
845 repair_bbio->file_offset = start;
846 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
848 if (failed_bbio->csum) {
849 const u32 csum_size = fs_info->csum_size;
851 repair_bbio->csum = repair_bbio->csum_inline;
852 memcpy(repair_bbio->csum,
853 failed_bbio->csum + csum_size * icsum, csum_size);
856 bio_add_page(repair_bio, page, failrec->len, pgoff);
857 repair_bbio->iter = repair_bio->bi_iter;
859 btrfs_debug(btrfs_sb(inode->i_sb),
860 "repair read error: submitting new read to mirror %d",
861 failrec->this_mirror);
864 * At this point we have a bio, so any errors from submit_bio_hook()
865 * will be handled by the endio on the repair_bio, so we can't return an
868 submit_bio_hook(inode, repair_bio, failrec->this_mirror, 0);
872 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
874 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
876 ASSERT(page_offset(page) <= start &&
877 start + len <= page_offset(page) + PAGE_SIZE);
880 if (fsverity_active(page->mapping->host) &&
882 !PageUptodate(page) &&
883 start < i_size_read(page->mapping->host) &&
884 !fsverity_verify_page(page)) {
885 btrfs_page_set_error(fs_info, page, start, len);
887 btrfs_page_set_uptodate(fs_info, page, start, len);
890 btrfs_page_clear_uptodate(fs_info, page, start, len);
891 btrfs_page_set_error(fs_info, page, start, len);
894 if (!btrfs_is_subpage(fs_info, page))
897 btrfs_subpage_end_reader(fs_info, page, start, len);
900 static void end_sector_io(struct page *page, u64 offset, bool uptodate)
902 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
903 const u32 sectorsize = inode->root->fs_info->sectorsize;
904 struct extent_state *cached = NULL;
906 end_page_read(page, uptodate, offset, sectorsize);
908 set_extent_uptodate(&inode->io_tree, offset,
909 offset + sectorsize - 1, &cached, GFP_ATOMIC);
910 unlock_extent_atomic(&inode->io_tree, offset, offset + sectorsize - 1,
914 static void submit_data_read_repair(struct inode *inode,
915 struct btrfs_bio *failed_bbio,
916 u32 bio_offset, const struct bio_vec *bvec,
917 unsigned int error_bitmap)
919 const unsigned int pgoff = bvec->bv_offset;
920 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
921 struct page *page = bvec->bv_page;
922 const u64 start = page_offset(bvec->bv_page) + bvec->bv_offset;
923 const u64 end = start + bvec->bv_len - 1;
924 const u32 sectorsize = fs_info->sectorsize;
925 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
928 BUG_ON(bio_op(&failed_bbio->bio) == REQ_OP_WRITE);
930 /* This repair is only for data */
931 ASSERT(is_data_inode(inode));
933 /* We're here because we had some read errors or csum mismatch */
934 ASSERT(error_bitmap);
937 * We only get called on buffered IO, thus page must be mapped and bio
938 * must not be cloned.
940 ASSERT(page->mapping && !bio_flagged(&failed_bbio->bio, BIO_CLONED));
942 /* Iterate through all the sectors in the range */
943 for (i = 0; i < nr_bits; i++) {
944 const unsigned int offset = i * sectorsize;
945 bool uptodate = false;
948 if (!(error_bitmap & (1U << i))) {
950 * This sector has no error, just end the page read
951 * and unlock the range.
957 ret = btrfs_repair_one_sector(inode, failed_bbio,
958 bio_offset + offset, page, pgoff + offset,
959 btrfs_submit_data_read_bio);
962 * We have submitted the read repair, the page release
963 * will be handled by the endio function of the
964 * submitted repair bio.
965 * Thus we don't need to do any thing here.
970 * Continue on failed repair, otherwise the remaining sectors
971 * will not be properly unlocked.
974 end_sector_io(page, start + offset, uptodate);
978 /* lots and lots of room for performance fixes in the end_bio funcs */
980 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
982 struct btrfs_inode *inode;
983 const bool uptodate = (err == 0);
986 ASSERT(page && page->mapping);
987 inode = BTRFS_I(page->mapping->host);
988 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
991 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
994 ASSERT(end + 1 - start <= U32_MAX);
995 len = end + 1 - start;
997 btrfs_page_clear_uptodate(fs_info, page, start, len);
998 btrfs_page_set_error(fs_info, page, start, len);
999 ret = err < 0 ? err : -EIO;
1000 mapping_set_error(page->mapping, ret);
1005 * after a writepage IO is done, we need to:
1006 * clear the uptodate bits on error
1007 * clear the writeback bits in the extent tree for this IO
1008 * end_page_writeback if the page has no more pending IO
1010 * Scheduling is not allowed, so the extent state tree is expected
1011 * to have one and only one object corresponding to this IO.
1013 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
1015 struct bio *bio = &bbio->bio;
1016 int error = blk_status_to_errno(bio->bi_status);
1017 struct bio_vec *bvec;
1020 struct bvec_iter_all iter_all;
1021 bool first_bvec = true;
1023 ASSERT(!bio_flagged(bio, BIO_CLONED));
1024 bio_for_each_segment_all(bvec, bio, iter_all) {
1025 struct page *page = bvec->bv_page;
1026 struct inode *inode = page->mapping->host;
1027 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1028 const u32 sectorsize = fs_info->sectorsize;
1030 /* Our read/write should always be sector aligned. */
1031 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1033 "partial page write in btrfs with offset %u and length %u",
1034 bvec->bv_offset, bvec->bv_len);
1035 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
1037 "incomplete page write with offset %u and length %u",
1038 bvec->bv_offset, bvec->bv_len);
1040 start = page_offset(page) + bvec->bv_offset;
1041 end = start + bvec->bv_len - 1;
1044 btrfs_record_physical_zoned(inode, start, bio);
1048 end_extent_writepage(page, error, start, end);
1050 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
1057 * Record previously processed extent range
1059 * For endio_readpage_release_extent() to handle a full extent range, reducing
1060 * the extent io operations.
1062 struct processed_extent {
1063 struct btrfs_inode *inode;
1064 /* Start of the range in @inode */
1066 /* End of the range in @inode */
1072 * Try to release processed extent range
1074 * May not release the extent range right now if the current range is
1075 * contiguous to processed extent.
1077 * Will release processed extent when any of @inode, @uptodate, the range is
1078 * no longer contiguous to the processed range.
1080 * Passing @inode == NULL will force processed extent to be released.
1082 static void endio_readpage_release_extent(struct processed_extent *processed,
1083 struct btrfs_inode *inode, u64 start, u64 end,
1086 struct extent_state *cached = NULL;
1087 struct extent_io_tree *tree;
1089 /* The first extent, initialize @processed */
1090 if (!processed->inode)
1094 * Contiguous to processed extent, just uptodate the end.
1096 * Several things to notice:
1098 * - bio can be merged as long as on-disk bytenr is contiguous
1099 * This means we can have page belonging to other inodes, thus need to
1100 * check if the inode still matches.
1101 * - bvec can contain range beyond current page for multi-page bvec
1102 * Thus we need to do processed->end + 1 >= start check
1104 if (processed->inode == inode && processed->uptodate == uptodate &&
1105 processed->end + 1 >= start && end >= processed->end) {
1106 processed->end = end;
1110 tree = &processed->inode->io_tree;
1112 * Now we don't have range contiguous to the processed range, release
1113 * the processed range now.
1115 unlock_extent_atomic(tree, processed->start, processed->end, &cached);
1118 /* Update processed to current range */
1119 processed->inode = inode;
1120 processed->start = start;
1121 processed->end = end;
1122 processed->uptodate = uptodate;
1125 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
1127 ASSERT(PageLocked(page));
1128 if (!btrfs_is_subpage(fs_info, page))
1131 ASSERT(PagePrivate(page));
1132 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
1136 * Find extent buffer for a givne bytenr.
1138 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
1141 static struct extent_buffer *find_extent_buffer_readpage(
1142 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
1144 struct extent_buffer *eb;
1147 * For regular sectorsize, we can use page->private to grab extent
1150 if (fs_info->nodesize >= PAGE_SIZE) {
1151 ASSERT(PagePrivate(page) && page->private);
1152 return (struct extent_buffer *)page->private;
1155 /* For subpage case, we need to lookup buffer radix tree */
1157 eb = radix_tree_lookup(&fs_info->buffer_radix,
1158 bytenr >> fs_info->sectorsize_bits);
1165 * after a readpage IO is done, we need to:
1166 * clear the uptodate bits on error
1167 * set the uptodate bits if things worked
1168 * set the page up to date if all extents in the tree are uptodate
1169 * clear the lock bit in the extent tree
1170 * unlock the page if there are no other extents locked for it
1172 * Scheduling is not allowed, so the extent state tree is expected
1173 * to have one and only one object corresponding to this IO.
1175 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
1177 struct bio *bio = &bbio->bio;
1178 struct bio_vec *bvec;
1179 struct processed_extent processed = { 0 };
1181 * The offset to the beginning of a bio, since one bio can never be
1182 * larger than UINT_MAX, u32 here is enough.
1186 struct bvec_iter_all iter_all;
1188 ASSERT(!bio_flagged(bio, BIO_CLONED));
1189 bio_for_each_segment_all(bvec, bio, iter_all) {
1190 bool uptodate = !bio->bi_status;
1191 struct page *page = bvec->bv_page;
1192 struct inode *inode = page->mapping->host;
1193 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1194 const u32 sectorsize = fs_info->sectorsize;
1195 unsigned int error_bitmap = (unsigned int)-1;
1196 bool repair = false;
1201 btrfs_debug(fs_info,
1202 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
1203 bio->bi_iter.bi_sector, bio->bi_status,
1207 * We always issue full-sector reads, but if some block in a
1208 * page fails to read, blk_update_request() will advance
1209 * bv_offset and adjust bv_len to compensate. Print a warning
1210 * for unaligned offsets, and an error if they don't add up to
1213 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1215 "partial page read in btrfs with offset %u and length %u",
1216 bvec->bv_offset, bvec->bv_len);
1217 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
1220 "incomplete page read with offset %u and length %u",
1221 bvec->bv_offset, bvec->bv_len);
1223 start = page_offset(page) + bvec->bv_offset;
1224 end = start + bvec->bv_len - 1;
1227 mirror = bbio->mirror_num;
1228 if (likely(uptodate)) {
1229 if (is_data_inode(inode)) {
1230 error_bitmap = btrfs_verify_data_csum(bbio,
1231 bio_offset, page, start, end);
1235 if (btrfs_validate_metadata_buffer(bbio,
1236 page, start, end, mirror))
1241 if (likely(uptodate)) {
1242 loff_t i_size = i_size_read(inode);
1243 pgoff_t end_index = i_size >> PAGE_SHIFT;
1245 btrfs_clean_io_failure(BTRFS_I(inode), start, page, 0);
1248 * Zero out the remaining part if this range straddles
1251 * Here we should only zero the range inside the bvec,
1252 * not touch anything else.
1254 * NOTE: i_size is exclusive while end is inclusive.
1256 if (page->index == end_index && i_size <= end) {
1257 u32 zero_start = max(offset_in_page(i_size),
1258 offset_in_page(start));
1260 zero_user_segment(page, zero_start,
1261 offset_in_page(end) + 1);
1263 } else if (is_data_inode(inode)) {
1265 * Only try to repair bios that actually made it to a
1266 * device. If the bio failed to be submitted mirror
1267 * is 0 and we need to fail it without retrying.
1269 * This also includes the high level bios for compressed
1270 * extents - these never make it to a device and repair
1271 * is already handled on the lower compressed bio.
1276 struct extent_buffer *eb;
1278 eb = find_extent_buffer_readpage(fs_info, page, start);
1279 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
1280 eb->read_mirror = mirror;
1281 atomic_dec(&eb->io_pages);
1286 * submit_data_read_repair() will handle all the good
1287 * and bad sectors, we just continue to the next bvec.
1289 submit_data_read_repair(inode, bbio, bio_offset, bvec,
1292 /* Update page status and unlock */
1293 end_page_read(page, uptodate, start, len);
1294 endio_readpage_release_extent(&processed, BTRFS_I(inode),
1295 start, end, PageUptodate(page));
1298 ASSERT(bio_offset + len > bio_offset);
1302 /* Release the last extent */
1303 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
1304 btrfs_bio_free_csum(bbio);
1309 * Populate every free slot in a provided array with pages.
1311 * @nr_pages: number of pages to allocate
1312 * @page_array: the array to fill with pages; any existing non-null entries in
1313 * the array will be skipped
1315 * Return: 0 if all pages were able to be allocated;
1316 * -ENOMEM otherwise, and the caller is responsible for freeing all
1317 * non-null page pointers in the array.
1319 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
1321 unsigned int allocated;
1323 for (allocated = 0; allocated < nr_pages;) {
1324 unsigned int last = allocated;
1326 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
1328 if (allocated == nr_pages)
1332 * During this iteration, no page could be allocated, even
1333 * though alloc_pages_bulk_array() falls back to alloc_page()
1334 * if it could not bulk-allocate. So we must be out of memory.
1336 if (allocated == last)
1339 memalloc_retry_wait(GFP_NOFS);
1345 * Attempt to add a page to bio
1347 * @bio_ctrl: record both the bio, and its bio_flags
1348 * @page: page to add to the bio
1349 * @disk_bytenr: offset of the new bio or to check whether we are adding
1350 * a contiguous page to the previous one
1351 * @size: portion of page that we want to write
1352 * @pg_offset: starting offset in the page
1353 * @compress_type: compression type of the current bio to see if we can merge them
1355 * Attempt to add a page to bio considering stripe alignment etc.
1357 * Return >= 0 for the number of bytes added to the bio.
1358 * Can return 0 if the current bio is already at stripe/zone boundary.
1359 * Return <0 for error.
1361 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
1363 u64 disk_bytenr, unsigned int size,
1364 unsigned int pg_offset,
1365 enum btrfs_compression_type compress_type)
1367 struct bio *bio = bio_ctrl->bio;
1368 u32 bio_size = bio->bi_iter.bi_size;
1370 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
1371 bool contig = false;
1375 /* The limit should be calculated when bio_ctrl->bio is allocated */
1376 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
1377 if (bio_ctrl->compress_type != compress_type)
1381 if (bio->bi_iter.bi_size == 0) {
1382 /* We can always add a page into an empty bio. */
1384 } else if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE) {
1385 struct bio_vec *bvec = bio_last_bvec_all(bio);
1388 * The contig check requires the following conditions to be met:
1389 * 1) The pages are belonging to the same inode
1390 * This is implied by the call chain.
1392 * 2) The range has adjacent logical bytenr
1394 * 3) The range has adjacent file offset
1395 * This is required for the usage of btrfs_bio->file_offset.
1397 if (bio_end_sector(bio) == sector &&
1398 page_offset(bvec->bv_page) + bvec->bv_offset +
1399 bvec->bv_len == page_offset(page) + pg_offset)
1403 * For compression, all IO should have its logical bytenr
1404 * set to the starting bytenr of the compressed extent.
1406 contig = bio->bi_iter.bi_sector == sector;
1412 real_size = min(bio_ctrl->len_to_oe_boundary,
1413 bio_ctrl->len_to_stripe_boundary) - bio_size;
1414 real_size = min(real_size, size);
1417 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
1418 * bio will still execute its endio function on the page!
1423 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
1424 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
1426 ret = bio_add_page(bio, page, real_size, pg_offset);
1431 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
1432 struct btrfs_inode *inode, u64 file_offset)
1434 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1435 struct btrfs_io_geometry geom;
1436 struct btrfs_ordered_extent *ordered;
1437 struct extent_map *em;
1438 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
1442 * Pages for compressed extent are never submitted to disk directly,
1443 * thus it has no real boundary, just set them to U32_MAX.
1445 * The split happens for real compressed bio, which happens in
1446 * btrfs_submit_compressed_read/write().
1448 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
1449 bio_ctrl->len_to_oe_boundary = U32_MAX;
1450 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1453 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
1456 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
1458 free_extent_map(em);
1462 if (geom.len > U32_MAX)
1463 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1465 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
1467 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
1468 bio_ctrl->len_to_oe_boundary = U32_MAX;
1472 /* Ordered extent not yet created, so we're good */
1473 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
1475 bio_ctrl->len_to_oe_boundary = U32_MAX;
1479 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
1480 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
1481 btrfs_put_ordered_extent(ordered);
1485 static int alloc_new_bio(struct btrfs_inode *inode,
1486 struct btrfs_bio_ctrl *bio_ctrl,
1487 struct writeback_control *wbc,
1489 u64 disk_bytenr, u32 offset, u64 file_offset,
1490 enum btrfs_compression_type compress_type)
1492 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1496 ASSERT(bio_ctrl->end_io_func);
1498 bio = btrfs_bio_alloc(BIO_MAX_VECS, opf, bio_ctrl->end_io_func, NULL);
1500 * For compressed page range, its disk_bytenr is always @disk_bytenr
1501 * passed in, no matter if we have added any range into previous bio.
1503 if (compress_type != BTRFS_COMPRESS_NONE)
1504 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
1506 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
1507 bio_ctrl->bio = bio;
1508 bio_ctrl->compress_type = compress_type;
1509 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
1515 * For Zone append we need the correct block_device that we are
1516 * going to write to set in the bio to be able to respect the
1517 * hardware limitation. Look it up here:
1519 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
1520 struct btrfs_device *dev;
1522 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
1523 fs_info->sectorsize);
1529 bio_set_dev(bio, dev->bdev);
1532 * Otherwise pick the last added device to support
1533 * cgroup writeback. For multi-device file systems this
1534 * means blk-cgroup policies have to always be set on the
1535 * last added/replaced device. This is a bit odd but has
1536 * been like that for a long time.
1538 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
1540 wbc_init_bio(wbc, bio);
1542 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
1546 bio_ctrl->bio = NULL;
1547 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
1552 * @opf: bio REQ_OP_* and REQ_* flags as one value
1553 * @wbc: optional writeback control for io accounting
1554 * @disk_bytenr: logical bytenr where the write will be
1555 * @page: page to add to the bio
1556 * @size: portion of page that we want to write to
1557 * @pg_offset: offset of the new bio or to check whether we are adding
1558 * a contiguous page to the previous one
1559 * @compress_type: compress type for current bio
1561 * The will either add the page into the existing @bio_ctrl->bio, or allocate a
1562 * new one in @bio_ctrl->bio.
1563 * The mirror number for this IO should already be initizlied in
1564 * @bio_ctrl->mirror_num.
1566 static int submit_extent_page(blk_opf_t opf,
1567 struct writeback_control *wbc,
1568 struct btrfs_bio_ctrl *bio_ctrl,
1569 u64 disk_bytenr, struct page *page,
1570 size_t size, unsigned long pg_offset,
1571 enum btrfs_compression_type compress_type,
1572 bool force_bio_submit)
1575 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1576 unsigned int cur = pg_offset;
1580 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
1581 pg_offset + size <= PAGE_SIZE);
1583 ASSERT(bio_ctrl->end_io_func);
1585 if (force_bio_submit)
1586 submit_one_bio(bio_ctrl);
1588 while (cur < pg_offset + size) {
1589 u32 offset = cur - pg_offset;
1592 /* Allocate new bio if needed */
1593 if (!bio_ctrl->bio) {
1594 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
1595 disk_bytenr, offset,
1596 page_offset(page) + cur,
1602 * We must go through btrfs_bio_add_page() to ensure each
1603 * page range won't cross various boundaries.
1605 if (compress_type != BTRFS_COMPRESS_NONE)
1606 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
1607 size - offset, pg_offset + offset,
1610 added = btrfs_bio_add_page(bio_ctrl, page,
1611 disk_bytenr + offset, size - offset,
1612 pg_offset + offset, compress_type);
1614 /* Metadata page range should never be split */
1615 if (!is_data_inode(&inode->vfs_inode))
1616 ASSERT(added == 0 || added == size - offset);
1618 /* At least we added some page, update the account */
1620 wbc_account_cgroup_owner(wbc, page, added);
1622 /* We have reached boundary, submit right now */
1623 if (added < size - offset) {
1624 /* The bio should contain some page(s) */
1625 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
1626 submit_one_bio(bio_ctrl);
1633 static int attach_extent_buffer_page(struct extent_buffer *eb,
1635 struct btrfs_subpage *prealloc)
1637 struct btrfs_fs_info *fs_info = eb->fs_info;
1641 * If the page is mapped to btree inode, we should hold the private
1642 * lock to prevent race.
1643 * For cloned or dummy extent buffers, their pages are not mapped and
1644 * will not race with any other ebs.
1647 lockdep_assert_held(&page->mapping->private_lock);
1649 if (fs_info->nodesize >= PAGE_SIZE) {
1650 if (!PagePrivate(page))
1651 attach_page_private(page, eb);
1653 WARN_ON(page->private != (unsigned long)eb);
1657 /* Already mapped, just free prealloc */
1658 if (PagePrivate(page)) {
1659 btrfs_free_subpage(prealloc);
1664 /* Has preallocated memory for subpage */
1665 attach_page_private(page, prealloc);
1667 /* Do new allocation to attach subpage */
1668 ret = btrfs_attach_subpage(fs_info, page,
1669 BTRFS_SUBPAGE_METADATA);
1673 int set_page_extent_mapped(struct page *page)
1675 struct btrfs_fs_info *fs_info;
1677 ASSERT(page->mapping);
1679 if (PagePrivate(page))
1682 fs_info = btrfs_sb(page->mapping->host->i_sb);
1684 if (btrfs_is_subpage(fs_info, page))
1685 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1687 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1691 void clear_page_extent_mapped(struct page *page)
1693 struct btrfs_fs_info *fs_info;
1695 ASSERT(page->mapping);
1697 if (!PagePrivate(page))
1700 fs_info = btrfs_sb(page->mapping->host->i_sb);
1701 if (btrfs_is_subpage(fs_info, page))
1702 return btrfs_detach_subpage(fs_info, page);
1704 detach_page_private(page);
1707 static struct extent_map *
1708 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1709 u64 start, u64 len, struct extent_map **em_cached)
1711 struct extent_map *em;
1713 if (em_cached && *em_cached) {
1715 if (extent_map_in_tree(em) && start >= em->start &&
1716 start < extent_map_end(em)) {
1717 refcount_inc(&em->refs);
1721 free_extent_map(em);
1725 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1726 if (em_cached && !IS_ERR(em)) {
1728 refcount_inc(&em->refs);
1734 * basic readpage implementation. Locked extent state structs are inserted
1735 * into the tree that are removed when the IO is done (by the end_io
1737 * XXX JDM: This needs looking at to ensure proper page locking
1738 * return 0 on success, otherwise return error
1740 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1741 struct btrfs_bio_ctrl *bio_ctrl,
1742 blk_opf_t read_flags, u64 *prev_em_start)
1744 struct inode *inode = page->mapping->host;
1745 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1746 u64 start = page_offset(page);
1747 const u64 end = start + PAGE_SIZE - 1;
1750 u64 last_byte = i_size_read(inode);
1752 struct extent_map *em;
1754 size_t pg_offset = 0;
1756 size_t blocksize = inode->i_sb->s_blocksize;
1757 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1759 ret = set_page_extent_mapped(page);
1761 unlock_extent(tree, start, end, NULL);
1762 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1767 if (page->index == last_byte >> PAGE_SHIFT) {
1768 size_t zero_offset = offset_in_page(last_byte);
1771 iosize = PAGE_SIZE - zero_offset;
1772 memzero_page(page, zero_offset, iosize);
1775 bio_ctrl->end_io_func = end_bio_extent_readpage;
1776 begin_page_read(fs_info, page);
1777 while (cur <= end) {
1778 unsigned long this_bio_flag = 0;
1779 bool force_bio_submit = false;
1782 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1783 if (cur >= last_byte) {
1784 struct extent_state *cached = NULL;
1786 iosize = PAGE_SIZE - pg_offset;
1787 memzero_page(page, pg_offset, iosize);
1788 set_extent_uptodate(tree, cur, cur + iosize - 1,
1790 unlock_extent(tree, cur, cur + iosize - 1, &cached);
1791 end_page_read(page, true, cur, iosize);
1794 em = __get_extent_map(inode, page, pg_offset, cur,
1795 end - cur + 1, em_cached);
1797 unlock_extent(tree, cur, end, NULL);
1798 end_page_read(page, false, cur, end + 1 - cur);
1802 extent_offset = cur - em->start;
1803 BUG_ON(extent_map_end(em) <= cur);
1806 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1807 this_bio_flag = em->compress_type;
1809 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1810 iosize = ALIGN(iosize, blocksize);
1811 if (this_bio_flag != BTRFS_COMPRESS_NONE)
1812 disk_bytenr = em->block_start;
1814 disk_bytenr = em->block_start + extent_offset;
1815 block_start = em->block_start;
1816 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1817 block_start = EXTENT_MAP_HOLE;
1820 * If we have a file range that points to a compressed extent
1821 * and it's followed by a consecutive file range that points
1822 * to the same compressed extent (possibly with a different
1823 * offset and/or length, so it either points to the whole extent
1824 * or only part of it), we must make sure we do not submit a
1825 * single bio to populate the pages for the 2 ranges because
1826 * this makes the compressed extent read zero out the pages
1827 * belonging to the 2nd range. Imagine the following scenario:
1830 * [0 - 8K] [8K - 24K]
1833 * points to extent X, points to extent X,
1834 * offset 4K, length of 8K offset 0, length 16K
1836 * [extent X, compressed length = 4K uncompressed length = 16K]
1838 * If the bio to read the compressed extent covers both ranges,
1839 * it will decompress extent X into the pages belonging to the
1840 * first range and then it will stop, zeroing out the remaining
1841 * pages that belong to the other range that points to extent X.
1842 * So here we make sure we submit 2 bios, one for the first
1843 * range and another one for the third range. Both will target
1844 * the same physical extent from disk, but we can't currently
1845 * make the compressed bio endio callback populate the pages
1846 * for both ranges because each compressed bio is tightly
1847 * coupled with a single extent map, and each range can have
1848 * an extent map with a different offset value relative to the
1849 * uncompressed data of our extent and different lengths. This
1850 * is a corner case so we prioritize correctness over
1851 * non-optimal behavior (submitting 2 bios for the same extent).
1853 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1854 prev_em_start && *prev_em_start != (u64)-1 &&
1855 *prev_em_start != em->start)
1856 force_bio_submit = true;
1859 *prev_em_start = em->start;
1861 free_extent_map(em);
1864 /* we've found a hole, just zero and go on */
1865 if (block_start == EXTENT_MAP_HOLE) {
1866 struct extent_state *cached = NULL;
1868 memzero_page(page, pg_offset, iosize);
1870 set_extent_uptodate(tree, cur, cur + iosize - 1,
1872 unlock_extent(tree, cur, cur + iosize - 1, &cached);
1873 end_page_read(page, true, cur, iosize);
1875 pg_offset += iosize;
1878 /* the get_extent function already copied into the page */
1879 if (block_start == EXTENT_MAP_INLINE) {
1880 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1881 end_page_read(page, true, cur, iosize);
1883 pg_offset += iosize;
1887 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
1888 bio_ctrl, disk_bytenr, page, iosize,
1889 pg_offset, this_bio_flag,
1893 * We have to unlock the remaining range, or the page
1894 * will never be unlocked.
1896 unlock_extent(tree, cur, end, NULL);
1897 end_page_read(page, false, cur, end + 1 - cur);
1901 pg_offset += iosize;
1907 int btrfs_read_folio(struct file *file, struct folio *folio)
1909 struct page *page = &folio->page;
1910 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1911 u64 start = page_offset(page);
1912 u64 end = start + PAGE_SIZE - 1;
1913 struct btrfs_bio_ctrl bio_ctrl = { 0 };
1916 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1918 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
1920 * If btrfs_do_readpage() failed we will want to submit the assembled
1921 * bio to do the cleanup.
1923 submit_one_bio(&bio_ctrl);
1927 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1929 struct extent_map **em_cached,
1930 struct btrfs_bio_ctrl *bio_ctrl,
1933 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1936 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1938 for (index = 0; index < nr_pages; index++) {
1939 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1940 REQ_RAHEAD, prev_em_start);
1941 put_page(pages[index]);
1946 * helper for __extent_writepage, doing all of the delayed allocation setup.
1948 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1949 * to write the page (copy into inline extent). In this case the IO has
1950 * been started and the page is already unlocked.
1952 * This returns 0 if all went well (page still locked)
1953 * This returns < 0 if there were errors (page still locked)
1955 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1956 struct page *page, struct writeback_control *wbc)
1958 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1959 u64 delalloc_start = page_offset(page);
1960 u64 delalloc_to_write = 0;
1961 /* How many pages are started by btrfs_run_delalloc_range() */
1962 unsigned long nr_written = 0;
1964 int page_started = 0;
1966 while (delalloc_start < page_end) {
1967 u64 delalloc_end = page_end;
1970 found = find_lock_delalloc_range(&inode->vfs_inode, page,
1974 delalloc_start = delalloc_end + 1;
1977 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1978 delalloc_end, &page_started, &nr_written, wbc);
1980 btrfs_page_set_error(inode->root->fs_info, page,
1981 page_offset(page), PAGE_SIZE);
1985 * delalloc_end is already one less than the total length, so
1986 * we don't subtract one from PAGE_SIZE
1988 delalloc_to_write += (delalloc_end - delalloc_start +
1989 PAGE_SIZE) >> PAGE_SHIFT;
1990 delalloc_start = delalloc_end + 1;
1992 if (wbc->nr_to_write < delalloc_to_write) {
1995 if (delalloc_to_write < thresh * 2)
1996 thresh = delalloc_to_write;
1997 wbc->nr_to_write = min_t(u64, delalloc_to_write,
2001 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
2004 * We've unlocked the page, so we can't update the mapping's
2005 * writeback index, just update nr_to_write.
2007 wbc->nr_to_write -= nr_written;
2015 * Find the first byte we need to write.
2017 * For subpage, one page can contain several sectors, and
2018 * __extent_writepage_io() will just grab all extent maps in the page
2019 * range and try to submit all non-inline/non-compressed extents.
2021 * This is a big problem for subpage, we shouldn't re-submit already written
2023 * This function will lookup subpage dirty bit to find which range we really
2026 * Return the next dirty range in [@start, @end).
2027 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
2029 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
2030 struct page *page, u64 *start, u64 *end)
2032 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2033 struct btrfs_subpage_info *spi = fs_info->subpage_info;
2034 u64 orig_start = *start;
2035 /* Declare as unsigned long so we can use bitmap ops */
2036 unsigned long flags;
2037 int range_start_bit;
2041 * For regular sector size == page size case, since one page only
2042 * contains one sector, we return the page offset directly.
2044 if (!btrfs_is_subpage(fs_info, page)) {
2045 *start = page_offset(page);
2046 *end = page_offset(page) + PAGE_SIZE;
2050 range_start_bit = spi->dirty_offset +
2051 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
2053 /* We should have the page locked, but just in case */
2054 spin_lock_irqsave(&subpage->lock, flags);
2055 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
2056 spi->dirty_offset + spi->bitmap_nr_bits);
2057 spin_unlock_irqrestore(&subpage->lock, flags);
2059 range_start_bit -= spi->dirty_offset;
2060 range_end_bit -= spi->dirty_offset;
2062 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
2063 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
2067 * helper for __extent_writepage. This calls the writepage start hooks,
2068 * and does the loop to map the page into extents and bios.
2070 * We return 1 if the IO is started and the page is unlocked,
2071 * 0 if all went well (page still locked)
2072 * < 0 if there were errors (page still locked)
2074 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
2076 struct writeback_control *wbc,
2077 struct extent_page_data *epd,
2081 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2082 u64 cur = page_offset(page);
2083 u64 end = cur + PAGE_SIZE - 1;
2086 struct extent_map *em;
2090 enum req_op op = REQ_OP_WRITE;
2091 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
2092 bool has_error = false;
2095 ret = btrfs_writepage_cow_fixup(page);
2097 /* Fixup worker will requeue */
2098 redirty_page_for_writepage(wbc, page);
2104 * we don't want to touch the inode after unlocking the page,
2105 * so we update the mapping writeback index now
2109 epd->bio_ctrl.end_io_func = end_bio_extent_writepage;
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, disk_bytenr,
2205 cur - page_offset(page),
2212 btrfs_page_set_error(fs_info, page, cur, iosize);
2213 if (PageWriteback(page))
2214 btrfs_page_clear_writeback(fs_info, page, cur,
2222 * If we finish without problem, we should not only clear page dirty,
2223 * but also empty subpage dirty bits
2226 btrfs_page_assert_not_dirty(fs_info, page);
2234 * the writepage semantics are similar to regular writepage. extent
2235 * records are inserted to lock ranges in the tree, and as dirty areas
2236 * are found, they are marked writeback. Then the lock bits are removed
2237 * and the end_io handler clears the writeback ranges
2239 * Return 0 if everything goes well.
2240 * Return <0 for error.
2242 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2243 struct extent_page_data *epd)
2245 struct folio *folio = page_folio(page);
2246 struct inode *inode = page->mapping->host;
2247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2248 const u64 page_start = page_offset(page);
2249 const u64 page_end = page_start + PAGE_SIZE - 1;
2253 loff_t i_size = i_size_read(inode);
2254 unsigned long end_index = i_size >> PAGE_SHIFT;
2256 trace___extent_writepage(page, inode, wbc);
2258 WARN_ON(!PageLocked(page));
2260 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
2261 page_offset(page), PAGE_SIZE);
2263 pg_offset = offset_in_page(i_size);
2264 if (page->index > end_index ||
2265 (page->index == end_index && !pg_offset)) {
2266 folio_invalidate(folio, 0, folio_size(folio));
2267 folio_unlock(folio);
2271 if (page->index == end_index)
2272 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
2274 ret = set_page_extent_mapped(page);
2280 if (!epd->extent_locked) {
2281 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
2288 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
2295 /* make sure the mapping tag for page dirty gets cleared */
2296 set_page_writeback(page);
2297 end_page_writeback(page);
2300 * Here we used to have a check for PageError() and then set @ret and
2301 * call end_extent_writepage().
2303 * But in fact setting @ret here will cause different error paths
2304 * between subpage and regular sectorsize.
2306 * For regular page size, we never submit current page, but only add
2307 * current page to current bio.
2308 * The bio submission can only happen in next page.
2309 * Thus if we hit the PageError() branch, @ret is already set to
2310 * non-zero value and will not get updated for regular sectorsize.
2312 * But for subpage case, it's possible we submit part of current page,
2313 * thus can get PageError() set by submitted bio of the same page,
2314 * while our @ret is still 0.
2316 * So here we unify the behavior and don't set @ret.
2317 * Error can still be properly passed to higher layer as page will
2318 * be set error, here we just don't handle the IO failure.
2320 * NOTE: This is just a hotfix for subpage.
2321 * The root fix will be properly ending ordered extent when we hit
2322 * an error during writeback.
2324 * But that needs a bigger refactoring, as we not only need to grab the
2325 * submitted OE, but also need to know exactly at which bytenr we hit
2327 * Currently the full page based __extent_writepage_io() is not
2330 if (PageError(page))
2331 end_extent_writepage(page, ret, page_start, page_end);
2332 if (epd->extent_locked) {
2334 * If epd->extent_locked, it's from extent_write_locked_range(),
2335 * the page can either be locked by lock_page() or
2336 * process_one_page().
2337 * Let btrfs_page_unlock_writer() handle both cases.
2340 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
2341 wbc->range_end + 1 - wbc->range_start);
2349 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
2351 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
2352 TASK_UNINTERRUPTIBLE);
2355 static void end_extent_buffer_writeback(struct extent_buffer *eb)
2357 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2358 smp_mb__after_atomic();
2359 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
2363 * Lock extent buffer status and pages for writeback.
2365 * May try to flush write bio if we can't get the lock.
2367 * Return 0 if the extent buffer doesn't need to be submitted.
2368 * (E.g. the extent buffer is not dirty)
2369 * Return >0 is the extent buffer is submitted to bio.
2370 * Return <0 if something went wrong, no page is locked.
2372 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
2373 struct extent_page_data *epd)
2375 struct btrfs_fs_info *fs_info = eb->fs_info;
2380 if (!btrfs_try_tree_write_lock(eb)) {
2381 submit_write_bio(epd, 0);
2383 btrfs_tree_lock(eb);
2386 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
2387 btrfs_tree_unlock(eb);
2391 submit_write_bio(epd, 0);
2395 wait_on_extent_buffer_writeback(eb);
2396 btrfs_tree_lock(eb);
2397 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
2399 btrfs_tree_unlock(eb);
2404 * We need to do this to prevent races in people who check if the eb is
2405 * under IO since we can end up having no IO bits set for a short period
2408 spin_lock(&eb->refs_lock);
2409 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
2410 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2411 spin_unlock(&eb->refs_lock);
2412 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
2413 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2415 fs_info->dirty_metadata_batch);
2418 spin_unlock(&eb->refs_lock);
2421 btrfs_tree_unlock(eb);
2424 * Either we don't need to submit any tree block, or we're submitting
2426 * Subpage metadata doesn't use page locking at all, so we can skip
2429 if (!ret || fs_info->nodesize < PAGE_SIZE)
2432 num_pages = num_extent_pages(eb);
2433 for (i = 0; i < num_pages; i++) {
2434 struct page *p = eb->pages[i];
2436 if (!trylock_page(p)) {
2438 submit_write_bio(epd, 0);
2448 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
2450 struct btrfs_fs_info *fs_info = eb->fs_info;
2452 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
2453 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
2457 * A read may stumble upon this buffer later, make sure that it gets an
2458 * error and knows there was an error.
2460 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
2463 * We need to set the mapping with the io error as well because a write
2464 * error will flip the file system readonly, and then syncfs() will
2465 * return a 0 because we are readonly if we don't modify the err seq for
2468 mapping_set_error(page->mapping, -EIO);
2471 * If we error out, we should add back the dirty_metadata_bytes
2472 * to make it consistent.
2474 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2475 eb->len, fs_info->dirty_metadata_batch);
2478 * If writeback for a btree extent that doesn't belong to a log tree
2479 * failed, increment the counter transaction->eb_write_errors.
2480 * We do this because while the transaction is running and before it's
2481 * committing (when we call filemap_fdata[write|wait]_range against
2482 * the btree inode), we might have
2483 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
2484 * returns an error or an error happens during writeback, when we're
2485 * committing the transaction we wouldn't know about it, since the pages
2486 * can be no longer dirty nor marked anymore for writeback (if a
2487 * subsequent modification to the extent buffer didn't happen before the
2488 * transaction commit), which makes filemap_fdata[write|wait]_range not
2489 * able to find the pages tagged with SetPageError at transaction
2490 * commit time. So if this happens we must abort the transaction,
2491 * otherwise we commit a super block with btree roots that point to
2492 * btree nodes/leafs whose content on disk is invalid - either garbage
2493 * or the content of some node/leaf from a past generation that got
2494 * cowed or deleted and is no longer valid.
2496 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
2497 * not be enough - we need to distinguish between log tree extents vs
2498 * non-log tree extents, and the next filemap_fdatawait_range() call
2499 * will catch and clear such errors in the mapping - and that call might
2500 * be from a log sync and not from a transaction commit. Also, checking
2501 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
2502 * not done and would not be reliable - the eb might have been released
2503 * from memory and reading it back again means that flag would not be
2504 * set (since it's a runtime flag, not persisted on disk).
2506 * Using the flags below in the btree inode also makes us achieve the
2507 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
2508 * writeback for all dirty pages and before filemap_fdatawait_range()
2509 * is called, the writeback for all dirty pages had already finished
2510 * with errors - because we were not using AS_EIO/AS_ENOSPC,
2511 * filemap_fdatawait_range() would return success, as it could not know
2512 * that writeback errors happened (the pages were no longer tagged for
2515 switch (eb->log_index) {
2517 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
2520 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2523 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2526 BUG(); /* unexpected, logic error */
2531 * The endio specific version which won't touch any unsafe spinlock in endio
2534 static struct extent_buffer *find_extent_buffer_nolock(
2535 struct btrfs_fs_info *fs_info, u64 start)
2537 struct extent_buffer *eb;
2540 eb = radix_tree_lookup(&fs_info->buffer_radix,
2541 start >> fs_info->sectorsize_bits);
2542 if (eb && atomic_inc_not_zero(&eb->refs)) {
2551 * The endio function for subpage extent buffer write.
2553 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
2554 * after all extent buffers in the page has finished their writeback.
2556 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
2558 struct bio *bio = &bbio->bio;
2559 struct btrfs_fs_info *fs_info;
2560 struct bio_vec *bvec;
2561 struct bvec_iter_all iter_all;
2563 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
2564 ASSERT(fs_info->nodesize < PAGE_SIZE);
2566 ASSERT(!bio_flagged(bio, BIO_CLONED));
2567 bio_for_each_segment_all(bvec, bio, iter_all) {
2568 struct page *page = bvec->bv_page;
2569 u64 bvec_start = page_offset(page) + bvec->bv_offset;
2570 u64 bvec_end = bvec_start + bvec->bv_len - 1;
2571 u64 cur_bytenr = bvec_start;
2573 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
2575 /* Iterate through all extent buffers in the range */
2576 while (cur_bytenr <= bvec_end) {
2577 struct extent_buffer *eb;
2581 * Here we can't use find_extent_buffer(), as it may
2582 * try to lock eb->refs_lock, which is not safe in endio
2585 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
2588 cur_bytenr = eb->start + eb->len;
2590 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
2591 done = atomic_dec_and_test(&eb->io_pages);
2594 if (bio->bi_status ||
2595 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2596 ClearPageUptodate(page);
2597 set_btree_ioerr(page, eb);
2600 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
2602 end_extent_buffer_writeback(eb);
2604 * free_extent_buffer() will grab spinlock which is not
2605 * safe in endio context. Thus here we manually dec
2608 atomic_dec(&eb->refs);
2614 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
2616 struct bio *bio = &bbio->bio;
2617 struct bio_vec *bvec;
2618 struct extent_buffer *eb;
2620 struct bvec_iter_all iter_all;
2622 ASSERT(!bio_flagged(bio, BIO_CLONED));
2623 bio_for_each_segment_all(bvec, bio, iter_all) {
2624 struct page *page = bvec->bv_page;
2626 eb = (struct extent_buffer *)page->private;
2628 done = atomic_dec_and_test(&eb->io_pages);
2630 if (bio->bi_status ||
2631 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2632 ClearPageUptodate(page);
2633 set_btree_ioerr(page, eb);
2636 end_page_writeback(page);
2641 end_extent_buffer_writeback(eb);
2647 static void prepare_eb_write(struct extent_buffer *eb)
2650 unsigned long start;
2653 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2654 atomic_set(&eb->io_pages, num_extent_pages(eb));
2656 /* Set btree blocks beyond nritems with 0 to avoid stale content */
2657 nritems = btrfs_header_nritems(eb);
2658 if (btrfs_header_level(eb) > 0) {
2659 end = btrfs_node_key_ptr_offset(nritems);
2660 memzero_extent_buffer(eb, end, eb->len - end);
2664 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2666 start = btrfs_item_nr_offset(nritems);
2667 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
2668 memzero_extent_buffer(eb, start, end - start);
2673 * Unlike the work in write_one_eb(), we rely completely on extent locking.
2674 * Page locking is only utilized at minimum to keep the VMM code happy.
2676 static int write_one_subpage_eb(struct extent_buffer *eb,
2677 struct writeback_control *wbc,
2678 struct extent_page_data *epd)
2680 struct btrfs_fs_info *fs_info = eb->fs_info;
2681 struct page *page = eb->pages[0];
2682 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2683 bool no_dirty_ebs = false;
2686 prepare_eb_write(eb);
2688 /* clear_page_dirty_for_io() in subpage helper needs page locked */
2690 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2692 /* Check if this is the last dirty bit to update nr_written */
2693 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2694 eb->start, eb->len);
2696 clear_page_dirty_for_io(page);
2698 epd->bio_ctrl.end_io_func = end_bio_subpage_eb_writepage;
2700 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2701 &epd->bio_ctrl, eb->start, page, eb->len,
2702 eb->start - page_offset(page), 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 epd->bio_ctrl.end_io_func = end_bio_extent_buffer_writepage;
2735 num_pages = num_extent_pages(eb);
2736 for (i = 0; i < num_pages; i++) {
2737 struct page *p = eb->pages[i];
2739 clear_page_dirty_for_io(p);
2740 set_page_writeback(p);
2741 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2742 &epd->bio_ctrl, disk_bytenr, p,
2743 PAGE_SIZE, 0, 0, false);
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->sync_mode == WB_SYNC_NONE &&
3023 wbc->nr_to_write <= 0);
3025 pagevec_release(&pvec);
3028 if (!scanned && !done) {
3030 * We hit the last page and there is more work to be done: wrap
3031 * back to the start of the file
3038 * If something went wrong, don't allow any metadata write bio to be
3041 * This would prevent use-after-free if we had dirty pages not
3042 * cleaned up, which can still happen by fuzzed images.
3045 * Allowing existing tree block to be allocated for other trees.
3047 * - Log tree operations
3048 * Exiting tree blocks get allocated to log tree, bumps its
3049 * generation, then get cleaned in tree re-balance.
3050 * Such tree block will not be written back, since it's clean,
3051 * thus no WRITTEN flag set.
3052 * And after log writes back, this tree block is not traced by
3053 * any dirty extent_io_tree.
3055 * - Offending tree block gets re-dirtied from its original owner
3056 * Since it has bumped generation, no WRITTEN flag, it can be
3057 * reused without COWing. This tree block will not be traced
3058 * by btrfs_transaction::dirty_pages.
3060 * Now such dirty tree block will not be cleaned by any dirty
3061 * extent io tree. Thus we don't want to submit such wild eb
3062 * if the fs already has error.
3064 * We can get ret > 0 from submit_extent_page() indicating how many ebs
3065 * were submitted. Reset it to 0 to avoid false alerts for the caller.
3069 if (!ret && BTRFS_FS_ERROR(fs_info))
3071 submit_write_bio(&epd, ret);
3073 btrfs_zoned_meta_io_unlock(fs_info);
3078 * Walk the list of dirty pages of the given address space and write all of them.
3080 * @mapping: address space structure to write
3081 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3082 * @epd: holds context for the write, namely the bio
3084 * If a page is already under I/O, write_cache_pages() skips it, even
3085 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
3086 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
3087 * and msync() need to guarantee that all the data which was dirty at the time
3088 * the call was made get new I/O started against them. If wbc->sync_mode is
3089 * WB_SYNC_ALL then we were called for data integrity and we must wait for
3090 * existing IO to complete.
3092 static int extent_write_cache_pages(struct address_space *mapping,
3093 struct writeback_control *wbc,
3094 struct extent_page_data *epd)
3096 struct inode *inode = mapping->host;
3099 int nr_to_write_done = 0;
3100 struct pagevec pvec;
3103 pgoff_t end; /* Inclusive */
3105 int range_whole = 0;
3110 * We have to hold onto the inode so that ordered extents can do their
3111 * work when the IO finishes. The alternative to this is failing to add
3112 * an ordered extent if the igrab() fails there and that is a huge pain
3113 * to deal with, so instead just hold onto the inode throughout the
3114 * writepages operation. If it fails here we are freeing up the inode
3115 * anyway and we'd rather not waste our time writing out stuff that is
3116 * going to be truncated anyway.
3121 pagevec_init(&pvec);
3122 if (wbc->range_cyclic) {
3123 index = mapping->writeback_index; /* Start from prev offset */
3126 * Start from the beginning does not need to cycle over the
3127 * range, mark it as scanned.
3129 scanned = (index == 0);
3131 index = wbc->range_start >> PAGE_SHIFT;
3132 end = wbc->range_end >> PAGE_SHIFT;
3133 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3139 * We do the tagged writepage as long as the snapshot flush bit is set
3140 * and we are the first one who do the filemap_flush() on this inode.
3142 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
3143 * not race in and drop the bit.
3145 if (range_whole && wbc->nr_to_write == LONG_MAX &&
3146 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
3147 &BTRFS_I(inode)->runtime_flags))
3148 wbc->tagged_writepages = 1;
3150 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3151 tag = PAGECACHE_TAG_TOWRITE;
3153 tag = PAGECACHE_TAG_DIRTY;
3155 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3156 tag_pages_for_writeback(mapping, index, end);
3158 while (!done && !nr_to_write_done && (index <= end) &&
3159 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
3160 &index, end, tag))) {
3163 for (i = 0; i < nr_pages; i++) {
3164 struct page *page = pvec.pages[i];
3166 done_index = page->index + 1;
3168 * At this point we hold neither the i_pages lock nor
3169 * the page lock: the page may be truncated or
3170 * invalidated (changing page->mapping to NULL),
3171 * or even swizzled back from swapper_space to
3172 * tmpfs file mapping
3174 if (!trylock_page(page)) {
3175 submit_write_bio(epd, 0);
3179 if (unlikely(page->mapping != mapping)) {
3184 if (wbc->sync_mode != WB_SYNC_NONE) {
3185 if (PageWriteback(page))
3186 submit_write_bio(epd, 0);
3187 wait_on_page_writeback(page);
3190 if (PageWriteback(page) ||
3191 !clear_page_dirty_for_io(page)) {
3196 ret = __extent_writepage(page, wbc, epd);
3203 * the filesystem may choose to bump up nr_to_write.
3204 * We have to make sure to honor the new nr_to_write
3207 nr_to_write_done = wbc->nr_to_write <= 0;
3209 pagevec_release(&pvec);
3212 if (!scanned && !done) {
3214 * We hit the last page and there is more work to be done: wrap
3215 * back to the start of the file
3221 * If we're looping we could run into a page that is locked by a
3222 * writer and that writer could be waiting on writeback for a
3223 * page in our current bio, and thus deadlock, so flush the
3226 submit_write_bio(epd, 0);
3230 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
3231 mapping->writeback_index = done_index;
3233 btrfs_add_delayed_iput(inode);
3238 * Submit the pages in the range to bio for call sites which delalloc range has
3239 * already been ran (aka, ordered extent inserted) and all pages are still
3242 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
3244 bool found_error = false;
3245 int first_error = 0;
3247 struct address_space *mapping = inode->i_mapping;
3250 unsigned long nr_pages;
3251 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
3252 struct extent_page_data epd = {
3257 struct writeback_control wbc_writepages = {
3258 .sync_mode = WB_SYNC_ALL,
3259 .range_start = start,
3260 .range_end = end + 1,
3261 /* We're called from an async helper function */
3262 .punt_to_cgroup = 1,
3263 .no_cgroup_owner = 1,
3266 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
3267 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
3269 wbc_writepages.nr_to_write = nr_pages * 2;
3271 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
3272 while (cur <= end) {
3273 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
3275 page = find_get_page(mapping, cur >> PAGE_SHIFT);
3277 * All pages in the range are locked since
3278 * btrfs_run_delalloc_range(), thus there is no way to clear
3279 * the page dirty flag.
3281 ASSERT(PageLocked(page));
3282 ASSERT(PageDirty(page));
3283 clear_page_dirty_for_io(page);
3284 ret = __extent_writepage(page, &wbc_writepages, &epd);
3294 submit_write_bio(&epd, found_error ? ret : 0);
3296 wbc_detach_inode(&wbc_writepages);
3302 int extent_writepages(struct address_space *mapping,
3303 struct writeback_control *wbc)
3305 struct inode *inode = mapping->host;
3307 struct extent_page_data epd = {
3310 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3314 * Allow only a single thread to do the reloc work in zoned mode to
3315 * protect the write pointer updates.
3317 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
3318 ret = extent_write_cache_pages(mapping, wbc, &epd);
3319 submit_write_bio(&epd, ret);
3320 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
3324 void extent_readahead(struct readahead_control *rac)
3326 struct btrfs_bio_ctrl bio_ctrl = { 0 };
3327 struct page *pagepool[16];
3328 struct extent_map *em_cached = NULL;
3329 u64 prev_em_start = (u64)-1;
3332 while ((nr = readahead_page_batch(rac, pagepool))) {
3333 u64 contig_start = readahead_pos(rac);
3334 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
3336 contiguous_readpages(pagepool, nr, contig_start, contig_end,
3337 &em_cached, &bio_ctrl, &prev_em_start);
3341 free_extent_map(em_cached);
3342 submit_one_bio(&bio_ctrl);
3346 * basic invalidate_folio code, this waits on any locked or writeback
3347 * ranges corresponding to the folio, and then deletes any extent state
3348 * records from the tree
3350 int extent_invalidate_folio(struct extent_io_tree *tree,
3351 struct folio *folio, size_t offset)
3353 struct extent_state *cached_state = NULL;
3354 u64 start = folio_pos(folio);
3355 u64 end = start + folio_size(folio) - 1;
3356 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
3358 /* This function is only called for the btree inode */
3359 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
3361 start += ALIGN(offset, blocksize);
3365 lock_extent(tree, start, end, &cached_state);
3366 folio_wait_writeback(folio);
3369 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
3370 * so here we only need to unlock the extent range to free any
3371 * existing extent state.
3373 unlock_extent(tree, start, end, &cached_state);
3378 * a helper for release_folio, this tests for areas of the page that
3379 * are locked or under IO and drops the related state bits if it is safe
3382 static int try_release_extent_state(struct extent_io_tree *tree,
3383 struct page *page, gfp_t mask)
3385 u64 start = page_offset(page);
3386 u64 end = start + PAGE_SIZE - 1;
3389 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
3392 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
3393 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS |
3394 EXTENT_QGROUP_RESERVED);
3397 * At this point we can safely clear everything except the
3398 * locked bit, the nodatasum bit and the delalloc new bit.
3399 * The delalloc new bit will be cleared by ordered extent
3402 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL,
3405 /* if clear_extent_bit failed for enomem reasons,
3406 * we can't allow the release to continue.
3417 * a helper for release_folio. As long as there are no locked extents
3418 * in the range corresponding to the page, both state records and extent
3419 * map records are removed
3421 int try_release_extent_mapping(struct page *page, gfp_t mask)
3423 struct extent_map *em;
3424 u64 start = page_offset(page);
3425 u64 end = start + PAGE_SIZE - 1;
3426 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
3427 struct extent_io_tree *tree = &btrfs_inode->io_tree;
3428 struct extent_map_tree *map = &btrfs_inode->extent_tree;
3430 if (gfpflags_allow_blocking(mask) &&
3431 page->mapping->host->i_size > SZ_16M) {
3433 while (start <= end) {
3434 struct btrfs_fs_info *fs_info;
3437 len = end - start + 1;
3438 write_lock(&map->lock);
3439 em = lookup_extent_mapping(map, start, len);
3441 write_unlock(&map->lock);
3444 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3445 em->start != start) {
3446 write_unlock(&map->lock);
3447 free_extent_map(em);
3450 if (test_range_bit(tree, em->start,
3451 extent_map_end(em) - 1,
3452 EXTENT_LOCKED, 0, NULL))
3455 * If it's not in the list of modified extents, used
3456 * by a fast fsync, we can remove it. If it's being
3457 * logged we can safely remove it since fsync took an
3458 * extra reference on the em.
3460 if (list_empty(&em->list) ||
3461 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
3464 * If it's in the list of modified extents, remove it
3465 * only if its generation is older then the current one,
3466 * in which case we don't need it for a fast fsync.
3467 * Otherwise don't remove it, we could be racing with an
3468 * ongoing fast fsync that could miss the new extent.
3470 fs_info = btrfs_inode->root->fs_info;
3471 spin_lock(&fs_info->trans_lock);
3472 cur_gen = fs_info->generation;
3473 spin_unlock(&fs_info->trans_lock);
3474 if (em->generation >= cur_gen)
3478 * We only remove extent maps that are not in the list of
3479 * modified extents or that are in the list but with a
3480 * generation lower then the current generation, so there
3481 * is no need to set the full fsync flag on the inode (it
3482 * hurts the fsync performance for workloads with a data
3483 * size that exceeds or is close to the system's memory).
3485 remove_extent_mapping(map, em);
3486 /* once for the rb tree */
3487 free_extent_map(em);
3489 start = extent_map_end(em);
3490 write_unlock(&map->lock);
3493 free_extent_map(em);
3495 cond_resched(); /* Allow large-extent preemption. */
3498 return try_release_extent_state(tree, page, mask);
3502 * To cache previous fiemap extent
3504 * Will be used for merging fiemap extent
3506 struct fiemap_cache {
3515 * Helper to submit fiemap extent.
3517 * Will try to merge current fiemap extent specified by @offset, @phys,
3518 * @len and @flags with cached one.
3519 * And only when we fails to merge, cached one will be submitted as
3522 * Return value is the same as fiemap_fill_next_extent().
3524 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
3525 struct fiemap_cache *cache,
3526 u64 offset, u64 phys, u64 len, u32 flags)
3530 /* Set at the end of extent_fiemap(). */
3531 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
3537 * Sanity check, extent_fiemap() should have ensured that new
3538 * fiemap extent won't overlap with cached one.
3541 * NOTE: Physical address can overlap, due to compression
3543 if (cache->offset + cache->len > offset) {
3549 * Only merges fiemap extents if
3550 * 1) Their logical addresses are continuous
3552 * 2) Their physical addresses are continuous
3553 * So truly compressed (physical size smaller than logical size)
3554 * extents won't get merged with each other
3556 * 3) Share same flags
3558 if (cache->offset + cache->len == offset &&
3559 cache->phys + cache->len == phys &&
3560 cache->flags == flags) {
3565 /* Not mergeable, need to submit cached one */
3566 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3567 cache->len, cache->flags);
3568 cache->cached = false;
3572 cache->cached = true;
3573 cache->offset = offset;
3576 cache->flags = flags;
3582 * Emit last fiemap cache
3584 * The last fiemap cache may still be cached in the following case:
3586 * |<- Fiemap range ->|
3587 * |<------------ First extent ----------->|
3589 * In this case, the first extent range will be cached but not emitted.
3590 * So we must emit it before ending extent_fiemap().
3592 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
3593 struct fiemap_cache *cache)
3600 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3601 cache->len, cache->flags);
3602 cache->cached = false;
3608 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
3610 struct extent_buffer *clone;
3611 struct btrfs_key key;
3616 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
3619 ret = btrfs_next_leaf(inode->root, path);
3624 * Don't bother with cloning if there are no more file extent items for
3627 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3628 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
3631 /* See the comment at fiemap_search_slot() about why we clone. */
3632 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3636 slot = path->slots[0];
3637 btrfs_release_path(path);
3638 path->nodes[0] = clone;
3639 path->slots[0] = slot;
3645 * Search for the first file extent item that starts at a given file offset or
3646 * the one that starts immediately before that offset.
3647 * Returns: 0 on success, < 0 on error, 1 if not found.
3649 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
3652 const u64 ino = btrfs_ino(inode);
3653 struct btrfs_root *root = inode->root;
3654 struct extent_buffer *clone;
3655 struct btrfs_key key;
3660 key.type = BTRFS_EXTENT_DATA_KEY;
3661 key.offset = file_offset;
3663 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3667 if (ret > 0 && path->slots[0] > 0) {
3668 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3669 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3673 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3674 ret = btrfs_next_leaf(root, path);
3678 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3679 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3684 * We clone the leaf and use it during fiemap. This is because while
3685 * using the leaf we do expensive things like checking if an extent is
3686 * shared, which can take a long time. In order to prevent blocking
3687 * other tasks for too long, we use a clone of the leaf. We have locked
3688 * the file range in the inode's io tree, so we know none of our file
3689 * extent items can change. This way we avoid blocking other tasks that
3690 * want to insert items for other inodes in the same leaf or b+tree
3691 * rebalance operations (triggered for example when someone is trying
3692 * to push items into this leaf when trying to insert an item in a
3694 * We also need the private clone because holding a read lock on an
3695 * extent buffer of the subvolume's b+tree will make lockdep unhappy
3696 * when we call fiemap_fill_next_extent(), because that may cause a page
3697 * fault when filling the user space buffer with fiemap data.
3699 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3703 slot = path->slots[0];
3704 btrfs_release_path(path);
3705 path->nodes[0] = clone;
3706 path->slots[0] = slot;
3712 * Process a range which is a hole or a prealloc extent in the inode's subvolume
3713 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
3714 * extent. The end offset (@end) is inclusive.
3716 static int fiemap_process_hole(struct btrfs_inode *inode,
3717 struct fiemap_extent_info *fieinfo,
3718 struct fiemap_cache *cache,
3719 struct btrfs_backref_shared_cache *backref_cache,
3720 u64 disk_bytenr, u64 extent_offset,
3722 struct ulist *roots, struct ulist *tmp_ulist,
3725 const u64 i_size = i_size_read(&inode->vfs_inode);
3726 const u64 ino = btrfs_ino(inode);
3727 u64 cur_offset = start;
3728 u64 last_delalloc_end = 0;
3729 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3730 bool checked_extent_shared = false;
3734 * There can be no delalloc past i_size, so don't waste time looking for
3737 while (cur_offset < end && cur_offset < i_size) {
3741 u64 prealloc_len = 0;
3744 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3751 * If this is a prealloc extent we have to report every section
3752 * of it that has no delalloc.
3754 if (disk_bytenr != 0) {
3755 if (last_delalloc_end == 0) {
3756 prealloc_start = start;
3757 prealloc_len = delalloc_start - start;
3759 prealloc_start = last_delalloc_end + 1;
3760 prealloc_len = delalloc_start - prealloc_start;
3764 if (prealloc_len > 0) {
3765 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3766 ret = btrfs_is_data_extent_shared(inode->root,
3774 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3776 checked_extent_shared = true;
3778 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3779 disk_bytenr + extent_offset,
3780 prealloc_len, prealloc_flags);
3783 extent_offset += prealloc_len;
3786 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3787 delalloc_end + 1 - delalloc_start,
3788 FIEMAP_EXTENT_DELALLOC |
3789 FIEMAP_EXTENT_UNKNOWN);
3793 last_delalloc_end = delalloc_end;
3794 cur_offset = delalloc_end + 1;
3795 extent_offset += cur_offset - delalloc_start;
3800 * Either we found no delalloc for the whole prealloc extent or we have
3801 * a prealloc extent that spans i_size or starts at or after i_size.
3803 if (disk_bytenr != 0 && last_delalloc_end < end) {
3807 if (last_delalloc_end == 0) {
3808 prealloc_start = start;
3809 prealloc_len = end + 1 - start;
3811 prealloc_start = last_delalloc_end + 1;
3812 prealloc_len = end + 1 - prealloc_start;
3815 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3816 ret = btrfs_is_data_extent_shared(inode->root,
3824 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3826 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3827 disk_bytenr + extent_offset,
3828 prealloc_len, prealloc_flags);
3836 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3837 struct btrfs_path *path,
3838 u64 *last_extent_end_ret)
3840 const u64 ino = btrfs_ino(inode);
3841 struct btrfs_root *root = inode->root;
3842 struct extent_buffer *leaf;
3843 struct btrfs_file_extent_item *ei;
3844 struct btrfs_key key;
3849 * Lookup the last file extent. We're not using i_size here because
3850 * there might be preallocation past i_size.
3852 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3853 /* There can't be a file extent item at offset (u64)-1 */
3859 * For a non-existing key, btrfs_search_slot() always leaves us at a
3860 * slot > 0, except if the btree is empty, which is impossible because
3861 * at least it has the inode item for this inode and all the items for
3862 * the root inode 256.
3864 ASSERT(path->slots[0] > 0);
3866 leaf = path->nodes[0];
3867 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3868 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3869 /* No file extent items in the subvolume tree. */
3870 *last_extent_end_ret = 0;
3875 * For an inline extent, the disk_bytenr is where inline data starts at,
3876 * so first check if we have an inline extent item before checking if we
3877 * have an implicit hole (disk_bytenr == 0).
3879 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3880 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3881 *last_extent_end_ret = btrfs_file_extent_end(path);
3886 * Find the last file extent item that is not a hole (when NO_HOLES is
3887 * not enabled). This should take at most 2 iterations in the worst
3888 * case: we have one hole file extent item at slot 0 of a leaf and
3889 * another hole file extent item as the last item in the previous leaf.
3890 * This is because we merge file extent items that represent holes.
3892 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3893 while (disk_bytenr == 0) {
3894 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3897 } else if (ret > 0) {
3898 /* No file extent items that are not holes. */
3899 *last_extent_end_ret = 0;
3902 leaf = path->nodes[0];
3903 ei = btrfs_item_ptr(leaf, path->slots[0],
3904 struct btrfs_file_extent_item);
3905 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3908 *last_extent_end_ret = btrfs_file_extent_end(path);
3912 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3915 const u64 ino = btrfs_ino(inode);
3916 struct extent_state *cached_state = NULL;
3917 struct btrfs_path *path;
3918 struct btrfs_root *root = inode->root;
3919 struct fiemap_cache cache = { 0 };
3920 struct btrfs_backref_shared_cache *backref_cache;
3921 struct ulist *roots;
3922 struct ulist *tmp_ulist;
3923 u64 last_extent_end;
3924 u64 prev_extent_end;
3927 bool stopped = false;
3930 backref_cache = kzalloc(sizeof(*backref_cache), GFP_KERNEL);
3931 path = btrfs_alloc_path();
3932 roots = ulist_alloc(GFP_KERNEL);
3933 tmp_ulist = ulist_alloc(GFP_KERNEL);
3934 if (!backref_cache || !path || !roots || !tmp_ulist) {
3939 lockstart = round_down(start, root->fs_info->sectorsize);
3940 lockend = round_up(start + len, root->fs_info->sectorsize);
3941 prev_extent_end = lockstart;
3943 btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
3944 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3946 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3949 btrfs_release_path(path);
3951 path->reada = READA_FORWARD;
3952 ret = fiemap_search_slot(inode, path, lockstart);
3955 } else if (ret > 0) {
3957 * No file extent item found, but we may have delalloc between
3958 * the current offset and i_size. So check for that.
3961 goto check_eof_delalloc;
3964 while (prev_extent_end < lockend) {
3965 struct extent_buffer *leaf = path->nodes[0];
3966 struct btrfs_file_extent_item *ei;
3967 struct btrfs_key key;
3970 u64 extent_offset = 0;
3972 u64 disk_bytenr = 0;
3977 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3978 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3981 extent_end = btrfs_file_extent_end(path);
3984 * The first iteration can leave us at an extent item that ends
3985 * before our range's start. Move to the next item.
3987 if (extent_end <= lockstart)
3990 /* We have in implicit hole (NO_HOLES feature enabled). */
3991 if (prev_extent_end < key.offset) {
3992 const u64 range_end = min(key.offset, lockend) - 1;
3994 ret = fiemap_process_hole(inode, fieinfo, &cache,
3995 backref_cache, 0, 0, 0,
3997 prev_extent_end, range_end);
4000 } else if (ret > 0) {
4001 /* fiemap_fill_next_extent() told us to stop. */
4006 /* We've reached the end of the fiemap range, stop. */
4007 if (key.offset >= lockend) {
4013 extent_len = extent_end - key.offset;
4014 ei = btrfs_item_ptr(leaf, path->slots[0],
4015 struct btrfs_file_extent_item);
4016 compression = btrfs_file_extent_compression(leaf, ei);
4017 extent_type = btrfs_file_extent_type(leaf, ei);
4018 extent_gen = btrfs_file_extent_generation(leaf, ei);
4020 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4021 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
4022 if (compression == BTRFS_COMPRESS_NONE)
4023 extent_offset = btrfs_file_extent_offset(leaf, ei);
4026 if (compression != BTRFS_COMPRESS_NONE)
4027 flags |= FIEMAP_EXTENT_ENCODED;
4029 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4030 flags |= FIEMAP_EXTENT_DATA_INLINE;
4031 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
4032 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
4034 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
4035 ret = fiemap_process_hole(inode, fieinfo, &cache,
4037 disk_bytenr, extent_offset,
4038 extent_gen, roots, tmp_ulist,
4039 key.offset, extent_end - 1);
4040 } else if (disk_bytenr == 0) {
4041 /* We have an explicit hole. */
4042 ret = fiemap_process_hole(inode, fieinfo, &cache,
4043 backref_cache, 0, 0, 0,
4045 key.offset, extent_end - 1);
4047 /* We have a regular extent. */
4048 if (fieinfo->fi_extents_max) {
4049 ret = btrfs_is_data_extent_shared(root, ino,
4058 flags |= FIEMAP_EXTENT_SHARED;
4061 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
4062 disk_bytenr + extent_offset,
4068 } else if (ret > 0) {
4069 /* fiemap_fill_next_extent() told us to stop. */
4074 prev_extent_end = extent_end;
4076 if (fatal_signal_pending(current)) {
4081 ret = fiemap_next_leaf_item(inode, path);
4084 } else if (ret > 0) {
4085 /* No more file extent items for this inode. */
4093 * Release (and free) the path before emitting any final entries to
4094 * fiemap_fill_next_extent() to keep lockdep happy. This is because
4095 * once we find no more file extent items exist, we may have a
4096 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
4097 * faults when copying data to the user space buffer.
4099 btrfs_free_path(path);
4102 if (!stopped && prev_extent_end < lockend) {
4103 ret = fiemap_process_hole(inode, fieinfo, &cache, backref_cache,
4104 0, 0, 0, roots, tmp_ulist,
4105 prev_extent_end, lockend - 1);
4108 prev_extent_end = lockend;
4111 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
4112 const u64 i_size = i_size_read(&inode->vfs_inode);
4114 if (prev_extent_end < i_size) {
4119 delalloc = btrfs_find_delalloc_in_range(inode,
4125 cache.flags |= FIEMAP_EXTENT_LAST;
4127 cache.flags |= FIEMAP_EXTENT_LAST;
4131 ret = emit_last_fiemap_cache(fieinfo, &cache);
4134 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
4135 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
4137 kfree(backref_cache);
4138 btrfs_free_path(path);
4140 ulist_free(tmp_ulist);
4144 static void __free_extent_buffer(struct extent_buffer *eb)
4146 kmem_cache_free(extent_buffer_cache, eb);
4149 int extent_buffer_under_io(const struct extent_buffer *eb)
4151 return (atomic_read(&eb->io_pages) ||
4152 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4153 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4156 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
4158 struct btrfs_subpage *subpage;
4160 lockdep_assert_held(&page->mapping->private_lock);
4162 if (PagePrivate(page)) {
4163 subpage = (struct btrfs_subpage *)page->private;
4164 if (atomic_read(&subpage->eb_refs))
4167 * Even there is no eb refs here, we may still have
4168 * end_page_read() call relying on page::private.
4170 if (atomic_read(&subpage->readers))
4176 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
4178 struct btrfs_fs_info *fs_info = eb->fs_info;
4179 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4182 * For mapped eb, we're going to change the page private, which should
4183 * be done under the private_lock.
4186 spin_lock(&page->mapping->private_lock);
4188 if (!PagePrivate(page)) {
4190 spin_unlock(&page->mapping->private_lock);
4194 if (fs_info->nodesize >= PAGE_SIZE) {
4196 * We do this since we'll remove the pages after we've
4197 * removed the eb from the radix tree, so we could race
4198 * and have this page now attached to the new eb. So
4199 * only clear page_private if it's still connected to
4202 if (PagePrivate(page) &&
4203 page->private == (unsigned long)eb) {
4204 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4205 BUG_ON(PageDirty(page));
4206 BUG_ON(PageWriteback(page));
4208 * We need to make sure we haven't be attached
4211 detach_page_private(page);
4214 spin_unlock(&page->mapping->private_lock);
4219 * For subpage, we can have dummy eb with page private. In this case,
4220 * we can directly detach the private as such page is only attached to
4221 * one dummy eb, no sharing.
4224 btrfs_detach_subpage(fs_info, page);
4228 btrfs_page_dec_eb_refs(fs_info, page);
4231 * We can only detach the page private if there are no other ebs in the
4232 * page range and no unfinished IO.
4234 if (!page_range_has_eb(fs_info, page))
4235 btrfs_detach_subpage(fs_info, page);
4237 spin_unlock(&page->mapping->private_lock);
4240 /* Release all pages attached to the extent buffer */
4241 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4246 ASSERT(!extent_buffer_under_io(eb));
4248 num_pages = num_extent_pages(eb);
4249 for (i = 0; i < num_pages; i++) {
4250 struct page *page = eb->pages[i];
4255 detach_extent_buffer_page(eb, page);
4257 /* One for when we allocated the page */
4263 * Helper for releasing the extent buffer.
4265 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4267 btrfs_release_extent_buffer_pages(eb);
4268 btrfs_leak_debug_del_eb(eb);
4269 __free_extent_buffer(eb);
4272 static struct extent_buffer *
4273 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4276 struct extent_buffer *eb = NULL;
4278 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4281 eb->fs_info = fs_info;
4283 init_rwsem(&eb->lock);
4285 btrfs_leak_debug_add_eb(eb);
4286 INIT_LIST_HEAD(&eb->release_list);
4288 spin_lock_init(&eb->refs_lock);
4289 atomic_set(&eb->refs, 1);
4290 atomic_set(&eb->io_pages, 0);
4292 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
4297 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
4300 struct extent_buffer *new;
4301 int num_pages = num_extent_pages(src);
4304 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4309 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
4310 * btrfs_release_extent_buffer() have different behavior for
4311 * UNMAPPED subpage extent buffer.
4313 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4315 memset(new->pages, 0, sizeof(*new->pages) * num_pages);
4316 ret = btrfs_alloc_page_array(num_pages, new->pages);
4318 btrfs_release_extent_buffer(new);
4322 for (i = 0; i < num_pages; i++) {
4324 struct page *p = new->pages[i];
4326 ret = attach_extent_buffer_page(new, p, NULL);
4328 btrfs_release_extent_buffer(new);
4331 WARN_ON(PageDirty(p));
4332 copy_page(page_address(p), page_address(src->pages[i]));
4334 set_extent_buffer_uptodate(new);
4339 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4340 u64 start, unsigned long len)
4342 struct extent_buffer *eb;
4347 eb = __alloc_extent_buffer(fs_info, start, len);
4351 num_pages = num_extent_pages(eb);
4352 ret = btrfs_alloc_page_array(num_pages, eb->pages);
4356 for (i = 0; i < num_pages; i++) {
4357 struct page *p = eb->pages[i];
4359 ret = attach_extent_buffer_page(eb, p, NULL);
4364 set_extent_buffer_uptodate(eb);
4365 btrfs_set_header_nritems(eb, 0);
4366 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4370 for (i = 0; i < num_pages; i++) {
4372 detach_extent_buffer_page(eb, eb->pages[i]);
4373 __free_page(eb->pages[i]);
4376 __free_extent_buffer(eb);
4380 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4383 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4386 static void check_buffer_tree_ref(struct extent_buffer *eb)
4390 * The TREE_REF bit is first set when the extent_buffer is added
4391 * to the radix tree. It is also reset, if unset, when a new reference
4392 * is created by find_extent_buffer.
4394 * It is only cleared in two cases: freeing the last non-tree
4395 * reference to the extent_buffer when its STALE bit is set or
4396 * calling release_folio when the tree reference is the only reference.
4398 * In both cases, care is taken to ensure that the extent_buffer's
4399 * pages are not under io. However, release_folio can be concurrently
4400 * called with creating new references, which is prone to race
4401 * conditions between the calls to check_buffer_tree_ref in those
4402 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4404 * The actual lifetime of the extent_buffer in the radix tree is
4405 * adequately protected by the refcount, but the TREE_REF bit and
4406 * its corresponding reference are not. To protect against this
4407 * class of races, we call check_buffer_tree_ref from the codepaths
4408 * which trigger io after they set eb->io_pages. Note that once io is
4409 * initiated, TREE_REF can no longer be cleared, so that is the
4410 * moment at which any such race is best fixed.
4412 refs = atomic_read(&eb->refs);
4413 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4416 spin_lock(&eb->refs_lock);
4417 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4418 atomic_inc(&eb->refs);
4419 spin_unlock(&eb->refs_lock);
4422 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4423 struct page *accessed)
4427 check_buffer_tree_ref(eb);
4429 num_pages = num_extent_pages(eb);
4430 for (i = 0; i < num_pages; i++) {
4431 struct page *p = eb->pages[i];
4434 mark_page_accessed(p);
4438 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4441 struct extent_buffer *eb;
4443 eb = find_extent_buffer_nolock(fs_info, start);
4447 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
4448 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
4449 * another task running free_extent_buffer() might have seen that flag
4450 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
4451 * writeback flags not set) and it's still in the tree (flag
4452 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
4453 * decrementing the extent buffer's reference count twice. So here we
4454 * could race and increment the eb's reference count, clear its stale
4455 * flag, mark it as dirty and drop our reference before the other task
4456 * finishes executing free_extent_buffer, which would later result in
4457 * an attempt to free an extent buffer that is dirty.
4459 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4460 spin_lock(&eb->refs_lock);
4461 spin_unlock(&eb->refs_lock);
4463 mark_extent_buffer_accessed(eb, NULL);
4467 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4468 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
4471 struct extent_buffer *eb, *exists = NULL;
4474 eb = find_extent_buffer(fs_info, start);
4477 eb = alloc_dummy_extent_buffer(fs_info, start);
4479 return ERR_PTR(-ENOMEM);
4480 eb->fs_info = fs_info;
4482 ret = radix_tree_preload(GFP_NOFS);
4484 exists = ERR_PTR(ret);
4487 spin_lock(&fs_info->buffer_lock);
4488 ret = radix_tree_insert(&fs_info->buffer_radix,
4489 start >> fs_info->sectorsize_bits, eb);
4490 spin_unlock(&fs_info->buffer_lock);
4491 radix_tree_preload_end();
4492 if (ret == -EEXIST) {
4493 exists = find_extent_buffer(fs_info, start);
4499 check_buffer_tree_ref(eb);
4500 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4504 btrfs_release_extent_buffer(eb);
4509 static struct extent_buffer *grab_extent_buffer(
4510 struct btrfs_fs_info *fs_info, struct page *page)
4512 struct extent_buffer *exists;
4515 * For subpage case, we completely rely on radix tree to ensure we
4516 * don't try to insert two ebs for the same bytenr. So here we always
4517 * return NULL and just continue.
4519 if (fs_info->nodesize < PAGE_SIZE)
4522 /* Page not yet attached to an extent buffer */
4523 if (!PagePrivate(page))
4527 * We could have already allocated an eb for this page and attached one
4528 * so lets see if we can get a ref on the existing eb, and if we can we
4529 * know it's good and we can just return that one, else we know we can
4530 * just overwrite page->private.
4532 exists = (struct extent_buffer *)page->private;
4533 if (atomic_inc_not_zero(&exists->refs))
4536 WARN_ON(PageDirty(page));
4537 detach_page_private(page);
4541 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
4543 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
4544 btrfs_err(fs_info, "bad tree block start %llu", start);
4548 if (fs_info->nodesize < PAGE_SIZE &&
4549 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
4551 "tree block crosses page boundary, start %llu nodesize %u",
4552 start, fs_info->nodesize);
4555 if (fs_info->nodesize >= PAGE_SIZE &&
4556 !PAGE_ALIGNED(start)) {
4558 "tree block is not page aligned, start %llu nodesize %u",
4559 start, fs_info->nodesize);
4565 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
4566 u64 start, u64 owner_root, int level)
4568 unsigned long len = fs_info->nodesize;
4571 unsigned long index = start >> PAGE_SHIFT;
4572 struct extent_buffer *eb;
4573 struct extent_buffer *exists = NULL;
4575 struct address_space *mapping = fs_info->btree_inode->i_mapping;
4576 u64 lockdep_owner = owner_root;
4580 if (check_eb_alignment(fs_info, start))
4581 return ERR_PTR(-EINVAL);
4583 #if BITS_PER_LONG == 32
4584 if (start >= MAX_LFS_FILESIZE) {
4585 btrfs_err_rl(fs_info,
4586 "extent buffer %llu is beyond 32bit page cache limit", start);
4587 btrfs_err_32bit_limit(fs_info);
4588 return ERR_PTR(-EOVERFLOW);
4590 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
4591 btrfs_warn_32bit_limit(fs_info);
4594 eb = find_extent_buffer(fs_info, start);
4598 eb = __alloc_extent_buffer(fs_info, start, len);
4600 return ERR_PTR(-ENOMEM);
4603 * The reloc trees are just snapshots, so we need them to appear to be
4604 * just like any other fs tree WRT lockdep.
4606 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
4607 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4609 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
4611 num_pages = num_extent_pages(eb);
4612 for (i = 0; i < num_pages; i++, index++) {
4613 struct btrfs_subpage *prealloc = NULL;
4615 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
4617 exists = ERR_PTR(-ENOMEM);
4622 * Preallocate page->private for subpage case, so that we won't
4623 * allocate memory with private_lock hold. The memory will be
4624 * freed by attach_extent_buffer_page() or freed manually if
4627 * Although we have ensured one subpage eb can only have one
4628 * page, but it may change in the future for 16K page size
4629 * support, so we still preallocate the memory in the loop.
4631 if (fs_info->nodesize < PAGE_SIZE) {
4632 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
4633 if (IS_ERR(prealloc)) {
4634 ret = PTR_ERR(prealloc);
4637 exists = ERR_PTR(ret);
4642 spin_lock(&mapping->private_lock);
4643 exists = grab_extent_buffer(fs_info, p);
4645 spin_unlock(&mapping->private_lock);
4648 mark_extent_buffer_accessed(exists, p);
4649 btrfs_free_subpage(prealloc);
4652 /* Should not fail, as we have preallocated the memory */
4653 ret = attach_extent_buffer_page(eb, p, prealloc);
4656 * To inform we have extra eb under allocation, so that
4657 * detach_extent_buffer_page() won't release the page private
4658 * when the eb hasn't yet been inserted into radix tree.
4660 * The ref will be decreased when the eb released the page, in
4661 * detach_extent_buffer_page().
4662 * Thus needs no special handling in error path.
4664 btrfs_page_inc_eb_refs(fs_info, p);
4665 spin_unlock(&mapping->private_lock);
4667 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
4669 if (!PageUptodate(p))
4673 * We can't unlock the pages just yet since the extent buffer
4674 * hasn't been properly inserted in the radix tree, this
4675 * opens a race with btree_release_folio which can free a page
4676 * while we are still filling in all pages for the buffer and
4681 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4683 ret = radix_tree_preload(GFP_NOFS);
4685 exists = ERR_PTR(ret);
4689 spin_lock(&fs_info->buffer_lock);
4690 ret = radix_tree_insert(&fs_info->buffer_radix,
4691 start >> fs_info->sectorsize_bits, eb);
4692 spin_unlock(&fs_info->buffer_lock);
4693 radix_tree_preload_end();
4694 if (ret == -EEXIST) {
4695 exists = find_extent_buffer(fs_info, start);
4701 /* add one reference for the tree */
4702 check_buffer_tree_ref(eb);
4703 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4706 * Now it's safe to unlock the pages because any calls to
4707 * btree_release_folio will correctly detect that a page belongs to a
4708 * live buffer and won't free them prematurely.
4710 for (i = 0; i < num_pages; i++)
4711 unlock_page(eb->pages[i]);
4715 WARN_ON(!atomic_dec_and_test(&eb->refs));
4716 for (i = 0; i < num_pages; i++) {
4718 unlock_page(eb->pages[i]);
4721 btrfs_release_extent_buffer(eb);
4725 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4727 struct extent_buffer *eb =
4728 container_of(head, struct extent_buffer, rcu_head);
4730 __free_extent_buffer(eb);
4733 static int release_extent_buffer(struct extent_buffer *eb)
4734 __releases(&eb->refs_lock)
4736 lockdep_assert_held(&eb->refs_lock);
4738 WARN_ON(atomic_read(&eb->refs) == 0);
4739 if (atomic_dec_and_test(&eb->refs)) {
4740 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4741 struct btrfs_fs_info *fs_info = eb->fs_info;
4743 spin_unlock(&eb->refs_lock);
4745 spin_lock(&fs_info->buffer_lock);
4746 radix_tree_delete(&fs_info->buffer_radix,
4747 eb->start >> fs_info->sectorsize_bits);
4748 spin_unlock(&fs_info->buffer_lock);
4750 spin_unlock(&eb->refs_lock);
4753 btrfs_leak_debug_del_eb(eb);
4754 /* Should be safe to release our pages at this point */
4755 btrfs_release_extent_buffer_pages(eb);
4756 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4757 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4758 __free_extent_buffer(eb);
4762 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4765 spin_unlock(&eb->refs_lock);
4770 void free_extent_buffer(struct extent_buffer *eb)
4776 refs = atomic_read(&eb->refs);
4778 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4779 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4782 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4786 spin_lock(&eb->refs_lock);
4787 if (atomic_read(&eb->refs) == 2 &&
4788 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4789 !extent_buffer_under_io(eb) &&
4790 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4791 atomic_dec(&eb->refs);
4794 * I know this is terrible, but it's temporary until we stop tracking
4795 * the uptodate bits and such for the extent buffers.
4797 release_extent_buffer(eb);
4800 void free_extent_buffer_stale(struct extent_buffer *eb)
4805 spin_lock(&eb->refs_lock);
4806 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4808 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4809 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4810 atomic_dec(&eb->refs);
4811 release_extent_buffer(eb);
4814 static void btree_clear_page_dirty(struct page *page)
4816 ASSERT(PageDirty(page));
4817 ASSERT(PageLocked(page));
4818 clear_page_dirty_for_io(page);
4819 xa_lock_irq(&page->mapping->i_pages);
4820 if (!PageDirty(page))
4821 __xa_clear_mark(&page->mapping->i_pages,
4822 page_index(page), PAGECACHE_TAG_DIRTY);
4823 xa_unlock_irq(&page->mapping->i_pages);
4826 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4828 struct btrfs_fs_info *fs_info = eb->fs_info;
4829 struct page *page = eb->pages[0];
4832 /* btree_clear_page_dirty() needs page locked */
4834 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4837 btree_clear_page_dirty(page);
4839 WARN_ON(atomic_read(&eb->refs) == 0);
4842 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
4848 if (eb->fs_info->nodesize < PAGE_SIZE)
4849 return clear_subpage_extent_buffer_dirty(eb);
4851 num_pages = num_extent_pages(eb);
4853 for (i = 0; i < num_pages; i++) {
4854 page = eb->pages[i];
4855 if (!PageDirty(page))
4858 btree_clear_page_dirty(page);
4859 ClearPageError(page);
4862 WARN_ON(atomic_read(&eb->refs) == 0);
4865 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4871 check_buffer_tree_ref(eb);
4873 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4875 num_pages = num_extent_pages(eb);
4876 WARN_ON(atomic_read(&eb->refs) == 0);
4877 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4880 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4883 * For subpage case, we can have other extent buffers in the
4884 * same page, and in clear_subpage_extent_buffer_dirty() we
4885 * have to clear page dirty without subpage lock held.
4886 * This can cause race where our page gets dirty cleared after
4889 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4890 * its page for other reasons, we can use page lock to prevent
4894 lock_page(eb->pages[0]);
4895 for (i = 0; i < num_pages; i++)
4896 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4897 eb->start, eb->len);
4899 unlock_page(eb->pages[0]);
4901 #ifdef CONFIG_BTRFS_DEBUG
4902 for (i = 0; i < num_pages; i++)
4903 ASSERT(PageDirty(eb->pages[i]));
4909 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4911 struct btrfs_fs_info *fs_info = eb->fs_info;
4916 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4917 num_pages = num_extent_pages(eb);
4918 for (i = 0; i < num_pages; i++) {
4919 page = eb->pages[i];
4924 * This is special handling for metadata subpage, as regular
4925 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4927 if (fs_info->nodesize >= PAGE_SIZE)
4928 ClearPageUptodate(page);
4930 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4935 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4937 struct btrfs_fs_info *fs_info = eb->fs_info;
4942 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4943 num_pages = num_extent_pages(eb);
4944 for (i = 0; i < num_pages; i++) {
4945 page = eb->pages[i];
4948 * This is special handling for metadata subpage, as regular
4949 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4951 if (fs_info->nodesize >= PAGE_SIZE)
4952 SetPageUptodate(page);
4954 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4959 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4962 struct btrfs_fs_info *fs_info = eb->fs_info;
4963 struct extent_io_tree *io_tree;
4964 struct page *page = eb->pages[0];
4965 struct btrfs_bio_ctrl bio_ctrl = {
4966 .mirror_num = mirror_num,
4970 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4971 ASSERT(PagePrivate(page));
4972 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4974 if (wait == WAIT_NONE) {
4975 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
4978 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4984 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4985 PageUptodate(page) ||
4986 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4987 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4988 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4992 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4993 eb->read_mirror = 0;
4994 atomic_set(&eb->io_pages, 1);
4995 check_buffer_tree_ref(eb);
4996 bio_ctrl.end_io_func = end_bio_extent_readpage;
4998 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
5000 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
5001 ret = submit_extent_page(REQ_OP_READ, NULL, &bio_ctrl,
5002 eb->start, page, eb->len,
5003 eb->start - page_offset(page), 0, true);
5006 * In the endio function, if we hit something wrong we will
5007 * increase the io_pages, so here we need to decrease it for
5010 atomic_dec(&eb->io_pages);
5012 submit_one_bio(&bio_ctrl);
5013 if (ret || wait != WAIT_COMPLETE)
5016 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
5017 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5022 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5028 int locked_pages = 0;
5029 int all_uptodate = 1;
5031 unsigned long num_reads = 0;
5032 struct btrfs_bio_ctrl bio_ctrl = {
5033 .mirror_num = mirror_num,
5036 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5040 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
5041 * operation, which could potentially still be in flight. In this case
5042 * we simply want to return an error.
5044 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
5047 if (eb->fs_info->nodesize < PAGE_SIZE)
5048 return read_extent_buffer_subpage(eb, wait, mirror_num);
5050 num_pages = num_extent_pages(eb);
5051 for (i = 0; i < num_pages; i++) {
5052 page = eb->pages[i];
5053 if (wait == WAIT_NONE) {
5055 * WAIT_NONE is only utilized by readahead. If we can't
5056 * acquire the lock atomically it means either the eb
5057 * is being read out or under modification.
5058 * Either way the eb will be or has been cached,
5059 * readahead can exit safely.
5061 if (!trylock_page(page))
5069 * We need to firstly lock all pages to make sure that
5070 * the uptodate bit of our pages won't be affected by
5071 * clear_extent_buffer_uptodate().
5073 for (i = 0; i < num_pages; i++) {
5074 page = eb->pages[i];
5075 if (!PageUptodate(page)) {
5082 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5086 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5087 eb->read_mirror = 0;
5088 atomic_set(&eb->io_pages, num_reads);
5090 * It is possible for release_folio to clear the TREE_REF bit before we
5091 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5093 check_buffer_tree_ref(eb);
5094 bio_ctrl.end_io_func = end_bio_extent_readpage;
5095 for (i = 0; i < num_pages; i++) {
5096 page = eb->pages[i];
5098 if (!PageUptodate(page)) {
5100 atomic_dec(&eb->io_pages);
5105 ClearPageError(page);
5106 err = submit_extent_page(REQ_OP_READ, NULL,
5107 &bio_ctrl, page_offset(page), page,
5108 PAGE_SIZE, 0, 0, false);
5111 * We failed to submit the bio so it's the
5112 * caller's responsibility to perform cleanup
5113 * i.e unlock page/set error bit.
5118 atomic_dec(&eb->io_pages);
5125 submit_one_bio(&bio_ctrl);
5127 if (ret || wait != WAIT_COMPLETE)
5130 for (i = 0; i < num_pages; i++) {
5131 page = eb->pages[i];
5132 wait_on_page_locked(page);
5133 if (!PageUptodate(page))
5140 while (locked_pages > 0) {
5142 page = eb->pages[locked_pages];
5148 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5151 btrfs_warn(eb->fs_info,
5152 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
5153 eb->start, eb->len, start, len);
5154 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5160 * Check if the [start, start + len) range is valid before reading/writing
5162 * NOTE: @start and @len are offset inside the eb, not logical address.
5164 * Caller should not touch the dst/src memory if this function returns error.
5166 static inline int check_eb_range(const struct extent_buffer *eb,
5167 unsigned long start, unsigned long len)
5169 unsigned long offset;
5171 /* start, start + len should not go beyond eb->len nor overflow */
5172 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5173 return report_eb_range(eb, start, len);
5178 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5179 unsigned long start, unsigned long len)
5185 char *dst = (char *)dstv;
5186 unsigned long i = get_eb_page_index(start);
5188 if (check_eb_range(eb, start, len)) {
5190 * Invalid range hit, reset the memory, so callers won't get
5191 * some random garbage for their uninitialzed memory.
5193 memset(dstv, 0, len);
5197 offset = get_eb_offset_in_page(eb, start);
5200 page = eb->pages[i];
5202 cur = min(len, (PAGE_SIZE - offset));
5203 kaddr = page_address(page);
5204 memcpy(dst, kaddr + offset, cur);
5213 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5215 unsigned long start, unsigned long len)
5221 char __user *dst = (char __user *)dstv;
5222 unsigned long i = get_eb_page_index(start);
5225 WARN_ON(start > eb->len);
5226 WARN_ON(start + len > eb->start + eb->len);
5228 offset = get_eb_offset_in_page(eb, start);
5231 page = eb->pages[i];
5233 cur = min(len, (PAGE_SIZE - offset));
5234 kaddr = page_address(page);
5235 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
5249 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5250 unsigned long start, unsigned long len)
5256 char *ptr = (char *)ptrv;
5257 unsigned long i = get_eb_page_index(start);
5260 if (check_eb_range(eb, start, len))
5263 offset = get_eb_offset_in_page(eb, start);
5266 page = eb->pages[i];
5268 cur = min(len, (PAGE_SIZE - offset));
5270 kaddr = page_address(page);
5271 ret = memcmp(ptr, kaddr + offset, cur);
5284 * Check that the extent buffer is uptodate.
5286 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
5287 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
5289 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
5292 struct btrfs_fs_info *fs_info = eb->fs_info;
5295 * If we are using the commit root we could potentially clear a page
5296 * Uptodate while we're using the extent buffer that we've previously
5297 * looked up. We don't want to complain in this case, as the page was
5298 * valid before, we just didn't write it out. Instead we want to catch
5299 * the case where we didn't actually read the block properly, which
5300 * would have !PageUptodate && !PageError, as we clear PageError before
5303 if (fs_info->nodesize < PAGE_SIZE) {
5304 bool uptodate, error;
5306 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
5307 eb->start, eb->len);
5308 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
5309 WARN_ON(!uptodate && !error);
5311 WARN_ON(!PageUptodate(page) && !PageError(page));
5315 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
5320 assert_eb_page_uptodate(eb, eb->pages[0]);
5321 kaddr = page_address(eb->pages[0]) +
5322 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
5324 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5327 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
5331 assert_eb_page_uptodate(eb, eb->pages[0]);
5332 kaddr = page_address(eb->pages[0]) +
5333 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
5334 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5337 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
5338 unsigned long start, unsigned long len)
5344 char *src = (char *)srcv;
5345 unsigned long i = get_eb_page_index(start);
5347 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
5349 if (check_eb_range(eb, start, len))
5352 offset = get_eb_offset_in_page(eb, start);
5355 page = eb->pages[i];
5356 assert_eb_page_uptodate(eb, page);
5358 cur = min(len, PAGE_SIZE - offset);
5359 kaddr = page_address(page);
5360 memcpy(kaddr + offset, src, cur);
5369 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
5376 unsigned long i = get_eb_page_index(start);
5378 if (check_eb_range(eb, start, len))
5381 offset = get_eb_offset_in_page(eb, start);
5384 page = eb->pages[i];
5385 assert_eb_page_uptodate(eb, page);
5387 cur = min(len, PAGE_SIZE - offset);
5388 kaddr = page_address(page);
5389 memset(kaddr + offset, 0, cur);
5397 void copy_extent_buffer_full(const struct extent_buffer *dst,
5398 const struct extent_buffer *src)
5403 ASSERT(dst->len == src->len);
5405 if (dst->fs_info->nodesize >= PAGE_SIZE) {
5406 num_pages = num_extent_pages(dst);
5407 for (i = 0; i < num_pages; i++)
5408 copy_page(page_address(dst->pages[i]),
5409 page_address(src->pages[i]));
5411 size_t src_offset = get_eb_offset_in_page(src, 0);
5412 size_t dst_offset = get_eb_offset_in_page(dst, 0);
5414 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
5415 memcpy(page_address(dst->pages[0]) + dst_offset,
5416 page_address(src->pages[0]) + src_offset,
5421 void copy_extent_buffer(const struct extent_buffer *dst,
5422 const struct extent_buffer *src,
5423 unsigned long dst_offset, unsigned long src_offset,
5426 u64 dst_len = dst->len;
5431 unsigned long i = get_eb_page_index(dst_offset);
5433 if (check_eb_range(dst, dst_offset, len) ||
5434 check_eb_range(src, src_offset, len))
5437 WARN_ON(src->len != dst_len);
5439 offset = get_eb_offset_in_page(dst, dst_offset);
5442 page = dst->pages[i];
5443 assert_eb_page_uptodate(dst, page);
5445 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5447 kaddr = page_address(page);
5448 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5458 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5460 * @eb: the extent buffer
5461 * @start: offset of the bitmap item in the extent buffer
5463 * @page_index: return index of the page in the extent buffer that contains the
5465 * @page_offset: return offset into the page given by page_index
5467 * This helper hides the ugliness of finding the byte in an extent buffer which
5468 * contains a given bit.
5470 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
5471 unsigned long start, unsigned long nr,
5472 unsigned long *page_index,
5473 size_t *page_offset)
5475 size_t byte_offset = BIT_BYTE(nr);
5479 * The byte we want is the offset of the extent buffer + the offset of
5480 * the bitmap item in the extent buffer + the offset of the byte in the
5483 offset = start + offset_in_page(eb->start) + byte_offset;
5485 *page_index = offset >> PAGE_SHIFT;
5486 *page_offset = offset_in_page(offset);
5490 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5491 * @eb: the extent buffer
5492 * @start: offset of the bitmap item in the extent buffer
5493 * @nr: bit number to test
5495 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
5503 eb_bitmap_offset(eb, start, nr, &i, &offset);
5504 page = eb->pages[i];
5505 assert_eb_page_uptodate(eb, page);
5506 kaddr = page_address(page);
5507 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5511 * extent_buffer_bitmap_set - set an area of a bitmap
5512 * @eb: the extent buffer
5513 * @start: offset of the bitmap item in the extent buffer
5514 * @pos: bit number of the first bit
5515 * @len: number of bits to set
5517 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
5518 unsigned long pos, unsigned long len)
5524 const unsigned int size = pos + len;
5525 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5526 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5528 eb_bitmap_offset(eb, start, pos, &i, &offset);
5529 page = eb->pages[i];
5530 assert_eb_page_uptodate(eb, page);
5531 kaddr = page_address(page);
5533 while (len >= bits_to_set) {
5534 kaddr[offset] |= mask_to_set;
5536 bits_to_set = BITS_PER_BYTE;
5538 if (++offset >= PAGE_SIZE && len > 0) {
5540 page = eb->pages[++i];
5541 assert_eb_page_uptodate(eb, page);
5542 kaddr = page_address(page);
5546 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5547 kaddr[offset] |= mask_to_set;
5553 * extent_buffer_bitmap_clear - clear an area of a bitmap
5554 * @eb: the extent buffer
5555 * @start: offset of the bitmap item in the extent buffer
5556 * @pos: bit number of the first bit
5557 * @len: number of bits to clear
5559 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
5560 unsigned long start, unsigned long pos,
5567 const unsigned int size = pos + len;
5568 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5569 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5571 eb_bitmap_offset(eb, start, pos, &i, &offset);
5572 page = eb->pages[i];
5573 assert_eb_page_uptodate(eb, page);
5574 kaddr = page_address(page);
5576 while (len >= bits_to_clear) {
5577 kaddr[offset] &= ~mask_to_clear;
5578 len -= bits_to_clear;
5579 bits_to_clear = BITS_PER_BYTE;
5581 if (++offset >= PAGE_SIZE && len > 0) {
5583 page = eb->pages[++i];
5584 assert_eb_page_uptodate(eb, page);
5585 kaddr = page_address(page);
5589 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5590 kaddr[offset] &= ~mask_to_clear;
5594 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5596 unsigned long distance = (src > dst) ? src - dst : dst - src;
5597 return distance < len;
5600 static void copy_pages(struct page *dst_page, struct page *src_page,
5601 unsigned long dst_off, unsigned long src_off,
5604 char *dst_kaddr = page_address(dst_page);
5606 int must_memmove = 0;
5608 if (dst_page != src_page) {
5609 src_kaddr = page_address(src_page);
5611 src_kaddr = dst_kaddr;
5612 if (areas_overlap(src_off, dst_off, len))
5617 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5619 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5622 void memcpy_extent_buffer(const struct extent_buffer *dst,
5623 unsigned long dst_offset, unsigned long src_offset,
5627 size_t dst_off_in_page;
5628 size_t src_off_in_page;
5629 unsigned long dst_i;
5630 unsigned long src_i;
5632 if (check_eb_range(dst, dst_offset, len) ||
5633 check_eb_range(dst, src_offset, len))
5637 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
5638 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
5640 dst_i = get_eb_page_index(dst_offset);
5641 src_i = get_eb_page_index(src_offset);
5643 cur = min(len, (unsigned long)(PAGE_SIZE -
5645 cur = min_t(unsigned long, cur,
5646 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5648 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5649 dst_off_in_page, src_off_in_page, cur);
5657 void memmove_extent_buffer(const struct extent_buffer *dst,
5658 unsigned long dst_offset, unsigned long src_offset,
5662 size_t dst_off_in_page;
5663 size_t src_off_in_page;
5664 unsigned long dst_end = dst_offset + len - 1;
5665 unsigned long src_end = src_offset + len - 1;
5666 unsigned long dst_i;
5667 unsigned long src_i;
5669 if (check_eb_range(dst, dst_offset, len) ||
5670 check_eb_range(dst, src_offset, len))
5672 if (dst_offset < src_offset) {
5673 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5677 dst_i = get_eb_page_index(dst_end);
5678 src_i = get_eb_page_index(src_end);
5680 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
5681 src_off_in_page = get_eb_offset_in_page(dst, src_end);
5683 cur = min_t(unsigned long, len, src_off_in_page + 1);
5684 cur = min(cur, dst_off_in_page + 1);
5685 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5686 dst_off_in_page - cur + 1,
5687 src_off_in_page - cur + 1, cur);
5695 #define GANG_LOOKUP_SIZE 16
5696 static struct extent_buffer *get_next_extent_buffer(
5697 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
5699 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
5700 struct extent_buffer *found = NULL;
5701 u64 page_start = page_offset(page);
5702 u64 cur = page_start;
5704 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
5705 lockdep_assert_held(&fs_info->buffer_lock);
5707 while (cur < page_start + PAGE_SIZE) {
5711 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
5712 (void **)gang, cur >> fs_info->sectorsize_bits,
5713 min_t(unsigned int, GANG_LOOKUP_SIZE,
5714 PAGE_SIZE / fs_info->nodesize));
5717 for (i = 0; i < ret; i++) {
5718 /* Already beyond page end */
5719 if (gang[i]->start >= page_start + PAGE_SIZE)
5722 if (gang[i]->start >= bytenr) {
5727 cur = gang[ret - 1]->start + gang[ret - 1]->len;
5733 static int try_release_subpage_extent_buffer(struct page *page)
5735 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5736 u64 cur = page_offset(page);
5737 const u64 end = page_offset(page) + PAGE_SIZE;
5741 struct extent_buffer *eb = NULL;
5744 * Unlike try_release_extent_buffer() which uses page->private
5745 * to grab buffer, for subpage case we rely on radix tree, thus
5746 * we need to ensure radix tree consistency.
5748 * We also want an atomic snapshot of the radix tree, thus go
5749 * with spinlock rather than RCU.
5751 spin_lock(&fs_info->buffer_lock);
5752 eb = get_next_extent_buffer(fs_info, page, cur);
5754 /* No more eb in the page range after or at cur */
5755 spin_unlock(&fs_info->buffer_lock);
5758 cur = eb->start + eb->len;
5761 * The same as try_release_extent_buffer(), to ensure the eb
5762 * won't disappear out from under us.
5764 spin_lock(&eb->refs_lock);
5765 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5766 spin_unlock(&eb->refs_lock);
5767 spin_unlock(&fs_info->buffer_lock);
5770 spin_unlock(&fs_info->buffer_lock);
5773 * If tree ref isn't set then we know the ref on this eb is a
5774 * real ref, so just return, this eb will likely be freed soon
5777 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5778 spin_unlock(&eb->refs_lock);
5783 * Here we don't care about the return value, we will always
5784 * check the page private at the end. And
5785 * release_extent_buffer() will release the refs_lock.
5787 release_extent_buffer(eb);
5790 * Finally to check if we have cleared page private, as if we have
5791 * released all ebs in the page, the page private should be cleared now.
5793 spin_lock(&page->mapping->private_lock);
5794 if (!PagePrivate(page))
5798 spin_unlock(&page->mapping->private_lock);
5803 int try_release_extent_buffer(struct page *page)
5805 struct extent_buffer *eb;
5807 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5808 return try_release_subpage_extent_buffer(page);
5811 * We need to make sure nobody is changing page->private, as we rely on
5812 * page->private as the pointer to extent buffer.
5814 spin_lock(&page->mapping->private_lock);
5815 if (!PagePrivate(page)) {
5816 spin_unlock(&page->mapping->private_lock);
5820 eb = (struct extent_buffer *)page->private;
5824 * This is a little awful but should be ok, we need to make sure that
5825 * the eb doesn't disappear out from under us while we're looking at
5828 spin_lock(&eb->refs_lock);
5829 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5830 spin_unlock(&eb->refs_lock);
5831 spin_unlock(&page->mapping->private_lock);
5834 spin_unlock(&page->mapping->private_lock);
5837 * If tree ref isn't set then we know the ref on this eb is a real ref,
5838 * so just return, this page will likely be freed soon anyway.
5840 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5841 spin_unlock(&eb->refs_lock);
5845 return release_extent_buffer(eb);
5849 * btrfs_readahead_tree_block - attempt to readahead a child block
5850 * @fs_info: the fs_info
5851 * @bytenr: bytenr to read
5852 * @owner_root: objectid of the root that owns this eb
5853 * @gen: generation for the uptodate check, can be 0
5854 * @level: level for the eb
5856 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5857 * normal uptodate check of the eb, without checking the generation. If we have
5858 * to read the block we will not block on anything.
5860 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5861 u64 bytenr, u64 owner_root, u64 gen, int level)
5863 struct extent_buffer *eb;
5866 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5870 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5871 free_extent_buffer(eb);
5875 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
5877 free_extent_buffer_stale(eb);
5879 free_extent_buffer(eb);
5883 * btrfs_readahead_node_child - readahead a node's child block
5884 * @node: parent node we're reading from
5885 * @slot: slot in the parent node for the child we want to read
5887 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5888 * the slot in the node provided.
5890 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5892 btrfs_readahead_tree_block(node->fs_info,
5893 btrfs_node_blockptr(node, slot),
5894 btrfs_header_owner(node),
5895 btrfs_node_ptr_generation(node, slot),
5896 btrfs_header_level(node) - 1);