1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/sched/mm.h>
10 #include <linux/spinlock.h>
11 #include <linux/blkdev.h>
12 #include <linux/swap.h>
13 #include <linux/writeback.h>
14 #include <linux/pagevec.h>
15 #include <linux/prefetch.h>
16 #include <linux/fsverity.h>
18 #include "extent_io.h"
19 #include "extent-io-tree.h"
20 #include "extent_map.h"
22 #include "btrfs_inode.h"
24 #include "check-integrity.h"
26 #include "rcu-string.h"
31 #include "block-group.h"
32 #include "compression.h"
34 #include "accessors.h"
35 #include "file-item.h"
37 #include "dev-replace.h"
40 static struct kmem_cache *extent_buffer_cache;
42 #ifdef CONFIG_BTRFS_DEBUG
43 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
45 struct btrfs_fs_info *fs_info = eb->fs_info;
48 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
49 list_add(&eb->leak_list, &fs_info->allocated_ebs);
50 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
53 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
55 struct btrfs_fs_info *fs_info = eb->fs_info;
58 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
59 list_del(&eb->leak_list);
60 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
63 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
65 struct extent_buffer *eb;
69 * If we didn't get into open_ctree our allocated_ebs will not be
70 * initialized, so just skip this.
72 if (!fs_info->allocated_ebs.next)
75 WARN_ON(!list_empty(&fs_info->allocated_ebs));
76 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
77 while (!list_empty(&fs_info->allocated_ebs)) {
78 eb = list_first_entry(&fs_info->allocated_ebs,
79 struct extent_buffer, leak_list);
81 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
82 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
83 btrfs_header_owner(eb));
84 list_del(&eb->leak_list);
85 kmem_cache_free(extent_buffer_cache, eb);
87 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
90 #define btrfs_leak_debug_add_eb(eb) do {} while (0)
91 #define btrfs_leak_debug_del_eb(eb) do {} while (0)
95 * Structure to record info about the bio being assembled, and other info like
96 * how many bytes are there before stripe/ordered extent boundary.
98 struct btrfs_bio_ctrl {
101 enum btrfs_compression_type compress_type;
102 u32 len_to_stripe_boundary;
103 u32 len_to_oe_boundary;
104 btrfs_bio_end_io_t end_io_func;
107 * Tell writepage not to lock the state bits for this range, it still
108 * does the unlocking.
112 /* Tell the submit_bio code to use REQ_SYNC */
116 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
120 struct btrfs_inode *inode;
127 bv = bio_first_bvec_all(bio);
128 inode = BTRFS_I(bv->bv_page->mapping->host);
129 mirror_num = bio_ctrl->mirror_num;
131 /* Caller should ensure the bio has at least some range added */
132 ASSERT(bio->bi_iter.bi_size);
134 btrfs_bio(bio)->file_offset = page_offset(bv->bv_page) + bv->bv_offset;
136 if (!is_data_inode(&inode->vfs_inode))
137 btrfs_submit_metadata_bio(inode, bio, mirror_num);
138 else if (btrfs_op(bio) == BTRFS_MAP_WRITE)
139 btrfs_submit_data_write_bio(inode, bio, mirror_num);
141 btrfs_submit_data_read_bio(inode, bio, mirror_num,
142 bio_ctrl->compress_type);
144 /* The bio is owned by the end_io handler now */
145 bio_ctrl->bio = NULL;
149 * Submit or fail the current bio in the bio_ctrl structure.
151 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
153 struct bio *bio = bio_ctrl->bio;
160 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
161 /* The bio is owned by the end_io handler now */
162 bio_ctrl->bio = NULL;
164 submit_one_bio(bio_ctrl);
168 int __init extent_buffer_init_cachep(void)
170 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
171 sizeof(struct extent_buffer), 0,
172 SLAB_MEM_SPREAD, NULL);
173 if (!extent_buffer_cache)
179 void __cold extent_buffer_free_cachep(void)
182 * Make sure all delayed rcu free are flushed before we
186 kmem_cache_destroy(extent_buffer_cache);
189 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
191 unsigned long index = start >> PAGE_SHIFT;
192 unsigned long end_index = end >> PAGE_SHIFT;
195 while (index <= end_index) {
196 page = find_get_page(inode->i_mapping, index);
197 BUG_ON(!page); /* Pages should be in the extent_io_tree */
198 clear_page_dirty_for_io(page);
204 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
206 struct address_space *mapping = inode->i_mapping;
207 unsigned long index = start >> PAGE_SHIFT;
208 unsigned long end_index = end >> PAGE_SHIFT;
211 while (index <= end_index) {
212 folio = filemap_get_folio(mapping, index);
213 filemap_dirty_folio(mapping, folio);
214 folio_account_redirty(folio);
215 index += folio_nr_pages(folio);
221 * Process one page for __process_pages_contig().
223 * Return >0 if we hit @page == @locked_page.
224 * Return 0 if we updated the page status.
225 * Return -EGAIN if the we need to try again.
226 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
228 static int process_one_page(struct btrfs_fs_info *fs_info,
229 struct address_space *mapping,
230 struct page *page, struct page *locked_page,
231 unsigned long page_ops, u64 start, u64 end)
235 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
236 len = end + 1 - start;
238 if (page_ops & PAGE_SET_ORDERED)
239 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
240 if (page_ops & PAGE_SET_ERROR)
241 btrfs_page_clamp_set_error(fs_info, page, start, len);
242 if (page_ops & PAGE_START_WRITEBACK) {
243 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
244 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
246 if (page_ops & PAGE_END_WRITEBACK)
247 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
249 if (page == locked_page)
252 if (page_ops & PAGE_LOCK) {
255 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
258 if (!PageDirty(page) || page->mapping != mapping) {
259 btrfs_page_end_writer_lock(fs_info, page, start, len);
263 if (page_ops & PAGE_UNLOCK)
264 btrfs_page_end_writer_lock(fs_info, page, start, len);
268 static int __process_pages_contig(struct address_space *mapping,
269 struct page *locked_page,
270 u64 start, u64 end, unsigned long page_ops,
273 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
274 pgoff_t start_index = start >> PAGE_SHIFT;
275 pgoff_t end_index = end >> PAGE_SHIFT;
276 pgoff_t index = start_index;
277 unsigned long pages_processed = 0;
278 struct folio_batch fbatch;
282 if (page_ops & PAGE_LOCK) {
283 ASSERT(page_ops == PAGE_LOCK);
284 ASSERT(processed_end && *processed_end == start);
287 if ((page_ops & PAGE_SET_ERROR) && start_index <= end_index)
288 mapping_set_error(mapping, -EIO);
290 folio_batch_init(&fbatch);
291 while (index <= end_index) {
294 found_folios = filemap_get_folios_contig(mapping, &index,
297 if (found_folios == 0) {
299 * Only if we're going to lock these pages, we can find
302 ASSERT(page_ops & PAGE_LOCK);
307 for (i = 0; i < found_folios; i++) {
309 struct folio *folio = fbatch.folios[i];
310 process_ret = process_one_page(fs_info, mapping,
311 &folio->page, locked_page, page_ops,
313 if (process_ret < 0) {
315 folio_batch_release(&fbatch);
318 pages_processed += folio_nr_pages(folio);
320 folio_batch_release(&fbatch);
324 if (err && processed_end) {
326 * Update @processed_end. I know this is awful since it has
327 * two different return value patterns (inclusive vs exclusive).
329 * But the exclusive pattern is necessary if @start is 0, or we
330 * underflow and check against processed_end won't work as
334 *processed_end = min(end,
335 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
337 *processed_end = start;
342 static noinline void __unlock_for_delalloc(struct inode *inode,
343 struct page *locked_page,
346 unsigned long index = start >> PAGE_SHIFT;
347 unsigned long end_index = end >> PAGE_SHIFT;
350 if (index == locked_page->index && end_index == index)
353 __process_pages_contig(inode->i_mapping, locked_page, start, end,
357 static noinline int lock_delalloc_pages(struct inode *inode,
358 struct page *locked_page,
362 unsigned long index = delalloc_start >> PAGE_SHIFT;
363 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
364 u64 processed_end = delalloc_start;
368 if (index == locked_page->index && index == end_index)
371 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
372 delalloc_end, PAGE_LOCK, &processed_end);
373 if (ret == -EAGAIN && processed_end > delalloc_start)
374 __unlock_for_delalloc(inode, locked_page, delalloc_start,
380 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
381 * more than @max_bytes.
383 * @start: The original start bytenr to search.
384 * Will store the extent range start bytenr.
385 * @end: The original end bytenr of the search range
386 * Will store the extent range end bytenr.
388 * Return true if we find a delalloc range which starts inside the original
389 * range, and @start/@end will store the delalloc range start/end.
391 * Return false if we can't find any delalloc range which starts inside the
392 * original range, and @start/@end will be the non-delalloc range start/end.
395 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
396 struct page *locked_page, u64 *start,
399 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
400 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
401 const u64 orig_start = *start;
402 const u64 orig_end = *end;
403 /* The sanity tests may not set a valid fs_info. */
404 u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
408 struct extent_state *cached_state = NULL;
412 /* Caller should pass a valid @end to indicate the search range end */
413 ASSERT(orig_end > orig_start);
415 /* The range should at least cover part of the page */
416 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
417 orig_end <= page_offset(locked_page)));
419 /* step one, find a bunch of delalloc bytes starting at start */
420 delalloc_start = *start;
422 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
423 max_bytes, &cached_state);
424 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
425 *start = delalloc_start;
427 /* @delalloc_end can be -1, never go beyond @orig_end */
428 *end = min(delalloc_end, orig_end);
429 free_extent_state(cached_state);
434 * start comes from the offset of locked_page. We have to lock
435 * pages in order, so we can't process delalloc bytes before
438 if (delalloc_start < *start)
439 delalloc_start = *start;
442 * make sure to limit the number of pages we try to lock down
444 if (delalloc_end + 1 - delalloc_start > max_bytes)
445 delalloc_end = delalloc_start + max_bytes - 1;
447 /* step two, lock all the pages after the page that has start */
448 ret = lock_delalloc_pages(inode, locked_page,
449 delalloc_start, delalloc_end);
450 ASSERT(!ret || ret == -EAGAIN);
451 if (ret == -EAGAIN) {
452 /* some of the pages are gone, lets avoid looping by
453 * shortening the size of the delalloc range we're searching
455 free_extent_state(cached_state);
458 max_bytes = PAGE_SIZE;
467 /* step three, lock the state bits for the whole range */
468 lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
470 /* then test to make sure it is all still delalloc */
471 ret = test_range_bit(tree, delalloc_start, delalloc_end,
472 EXTENT_DELALLOC, 1, cached_state);
474 unlock_extent(tree, delalloc_start, delalloc_end,
476 __unlock_for_delalloc(inode, locked_page,
477 delalloc_start, delalloc_end);
481 free_extent_state(cached_state);
482 *start = delalloc_start;
488 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
489 struct page *locked_page,
490 u32 clear_bits, unsigned long page_ops)
492 clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
494 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
495 start, end, page_ops, NULL);
498 static int insert_failrec(struct btrfs_inode *inode,
499 struct io_failure_record *failrec)
501 struct rb_node *exist;
503 spin_lock(&inode->io_failure_lock);
504 exist = rb_simple_insert(&inode->io_failure_tree, failrec->bytenr,
506 spin_unlock(&inode->io_failure_lock);
508 return (exist == NULL) ? 0 : -EEXIST;
511 static struct io_failure_record *get_failrec(struct btrfs_inode *inode, u64 start)
513 struct rb_node *node;
514 struct io_failure_record *failrec = ERR_PTR(-ENOENT);
516 spin_lock(&inode->io_failure_lock);
517 node = rb_simple_search(&inode->io_failure_tree, start);
519 failrec = rb_entry(node, struct io_failure_record, rb_node);
520 spin_unlock(&inode->io_failure_lock);
524 static void free_io_failure(struct btrfs_inode *inode,
525 struct io_failure_record *rec)
527 spin_lock(&inode->io_failure_lock);
528 rb_erase(&rec->rb_node, &inode->io_failure_tree);
529 spin_unlock(&inode->io_failure_lock);
534 static int next_mirror(const struct io_failure_record *failrec, int cur_mirror)
536 if (cur_mirror == failrec->num_copies)
537 return cur_mirror + 1 - failrec->num_copies;
538 return cur_mirror + 1;
541 static int prev_mirror(const struct io_failure_record *failrec, int cur_mirror)
544 return failrec->num_copies;
545 return cur_mirror - 1;
549 * each time an IO finishes, we do a fast check in the IO failure tree
550 * to see if we need to process or clean up an io_failure_record
552 int btrfs_clean_io_failure(struct btrfs_inode *inode, u64 start,
553 struct page *page, unsigned int pg_offset)
555 struct btrfs_fs_info *fs_info = inode->root->fs_info;
556 struct extent_io_tree *io_tree = &inode->io_tree;
557 u64 ino = btrfs_ino(inode);
558 u64 locked_start, locked_end;
559 struct io_failure_record *failrec;
563 failrec = get_failrec(inode, start);
567 BUG_ON(!failrec->this_mirror);
569 if (sb_rdonly(fs_info->sb))
572 ret = find_first_extent_bit(io_tree, failrec->bytenr, &locked_start,
573 &locked_end, EXTENT_LOCKED, NULL);
574 if (ret || locked_start > failrec->bytenr ||
575 locked_end < failrec->bytenr + failrec->len - 1)
578 mirror = failrec->this_mirror;
580 mirror = prev_mirror(failrec, mirror);
581 btrfs_repair_io_failure(fs_info, ino, start, failrec->len,
582 failrec->logical, page, pg_offset, mirror);
583 } while (mirror != failrec->failed_mirror);
586 free_io_failure(inode, failrec);
593 * - under ordered extent
594 * - the inode is freeing
596 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
598 struct io_failure_record *failrec;
599 struct rb_node *node, *next;
601 if (RB_EMPTY_ROOT(&inode->io_failure_tree))
604 spin_lock(&inode->io_failure_lock);
605 node = rb_simple_search_first(&inode->io_failure_tree, start);
607 failrec = rb_entry(node, struct io_failure_record, rb_node);
608 if (failrec->bytenr > end)
611 next = rb_next(node);
612 rb_erase(&failrec->rb_node, &inode->io_failure_tree);
617 spin_unlock(&inode->io_failure_lock);
620 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
621 struct btrfs_bio *bbio,
622 unsigned int bio_offset)
624 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
625 u64 start = bbio->file_offset + bio_offset;
626 struct io_failure_record *failrec;
627 const u32 sectorsize = fs_info->sectorsize;
630 failrec = get_failrec(BTRFS_I(inode), start);
631 if (!IS_ERR(failrec)) {
633 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
634 failrec->logical, failrec->bytenr, failrec->len);
636 * when data can be on disk more than twice, add to failrec here
637 * (e.g. with a list for failed_mirror) to make
638 * clean_io_failure() clean all those errors at once.
640 ASSERT(failrec->this_mirror == bbio->mirror_num);
641 ASSERT(failrec->len == fs_info->sectorsize);
645 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
647 return ERR_PTR(-ENOMEM);
649 RB_CLEAR_NODE(&failrec->rb_node);
650 failrec->bytenr = start;
651 failrec->len = sectorsize;
652 failrec->failed_mirror = bbio->mirror_num;
653 failrec->this_mirror = bbio->mirror_num;
654 failrec->logical = (bbio->iter.bi_sector << SECTOR_SHIFT) + bio_offset;
657 "new io failure record logical %llu start %llu",
658 failrec->logical, start);
660 failrec->num_copies = btrfs_num_copies(fs_info, failrec->logical, sectorsize);
661 if (failrec->num_copies == 1) {
663 * We only have a single copy of the data, so don't bother with
664 * all the retry and error correction code that follows. No
665 * matter what the error is, it is very likely to persist.
668 "cannot repair logical %llu num_copies %d",
669 failrec->logical, failrec->num_copies);
671 return ERR_PTR(-EIO);
674 /* Set the bits in the private failure tree */
675 ret = insert_failrec(BTRFS_I(inode), failrec);
684 int btrfs_repair_one_sector(struct btrfs_inode *inode, struct btrfs_bio *failed_bbio,
685 u32 bio_offset, struct page *page, unsigned int pgoff,
686 bool submit_buffered)
688 u64 start = failed_bbio->file_offset + bio_offset;
689 struct io_failure_record *failrec;
690 struct btrfs_fs_info *fs_info = inode->root->fs_info;
691 struct bio *failed_bio = &failed_bbio->bio;
692 const int icsum = bio_offset >> fs_info->sectorsize_bits;
693 struct bio *repair_bio;
694 struct btrfs_bio *repair_bbio;
697 "repair read error: read error at %llu", start);
699 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
701 failrec = btrfs_get_io_failure_record(&inode->vfs_inode, failed_bbio, bio_offset);
703 return PTR_ERR(failrec);
706 * There are two premises:
707 * a) deliver good data to the caller
708 * b) correct the bad sectors on disk
710 * Since we're only doing repair for one sector, we only need to get
711 * a good copy of the failed sector and if we succeed, we have setup
712 * everything for btrfs_repair_io_failure to do the rest for us.
714 failrec->this_mirror = next_mirror(failrec, failrec->this_mirror);
715 if (failrec->this_mirror == failrec->failed_mirror) {
717 "failed to repair num_copies %d this_mirror %d failed_mirror %d",
718 failrec->num_copies, failrec->this_mirror, failrec->failed_mirror);
719 free_io_failure(inode, failrec);
723 repair_bio = btrfs_bio_alloc(1, REQ_OP_READ, failed_bbio->end_io,
724 failed_bbio->private);
725 repair_bbio = btrfs_bio(repair_bio);
726 repair_bbio->file_offset = start;
727 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
729 if (failed_bbio->csum) {
730 const u32 csum_size = fs_info->csum_size;
732 repair_bbio->csum = repair_bbio->csum_inline;
733 memcpy(repair_bbio->csum,
734 failed_bbio->csum + csum_size * icsum, csum_size);
737 bio_add_page(repair_bio, page, failrec->len, pgoff);
738 repair_bbio->iter = repair_bio->bi_iter;
741 "repair read error: submitting new read to mirror %d",
742 failrec->this_mirror);
745 * At this point we have a bio, so any errors from bio submission will
746 * be handled by the endio on the repair_bio, so we can't return an
750 btrfs_submit_data_read_bio(inode, repair_bio,
751 failrec->this_mirror, 0);
753 btrfs_submit_dio_repair_bio(inode, repair_bio, failrec->this_mirror);
758 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
760 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
762 ASSERT(page_offset(page) <= start &&
763 start + len <= page_offset(page) + PAGE_SIZE);
766 if (fsverity_active(page->mapping->host) &&
768 !PageUptodate(page) &&
769 start < i_size_read(page->mapping->host) &&
770 !fsverity_verify_page(page)) {
771 btrfs_page_set_error(fs_info, page, start, len);
773 btrfs_page_set_uptodate(fs_info, page, start, len);
776 btrfs_page_clear_uptodate(fs_info, page, start, len);
777 btrfs_page_set_error(fs_info, page, start, len);
780 if (!btrfs_is_subpage(fs_info, page))
783 btrfs_subpage_end_reader(fs_info, page, start, len);
786 static void end_sector_io(struct page *page, u64 offset, bool uptodate)
788 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
789 const u32 sectorsize = inode->root->fs_info->sectorsize;
791 end_page_read(page, uptodate, offset, sectorsize);
792 unlock_extent(&inode->io_tree, offset, offset + sectorsize - 1, NULL);
795 static void submit_data_read_repair(struct inode *inode,
796 struct btrfs_bio *failed_bbio,
797 u32 bio_offset, const struct bio_vec *bvec,
798 unsigned int error_bitmap)
800 const unsigned int pgoff = bvec->bv_offset;
801 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
802 struct page *page = bvec->bv_page;
803 const u64 start = page_offset(bvec->bv_page) + bvec->bv_offset;
804 const u64 end = start + bvec->bv_len - 1;
805 const u32 sectorsize = fs_info->sectorsize;
806 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
809 BUG_ON(bio_op(&failed_bbio->bio) == REQ_OP_WRITE);
811 /* This repair is only for data */
812 ASSERT(is_data_inode(inode));
814 /* We're here because we had some read errors or csum mismatch */
815 ASSERT(error_bitmap);
818 * We only get called on buffered IO, thus page must be mapped and bio
819 * must not be cloned.
821 ASSERT(page->mapping && !bio_flagged(&failed_bbio->bio, BIO_CLONED));
823 /* Iterate through all the sectors in the range */
824 for (i = 0; i < nr_bits; i++) {
825 const unsigned int offset = i * sectorsize;
826 bool uptodate = false;
829 if (!(error_bitmap & (1U << i))) {
831 * This sector has no error, just end the page read
832 * and unlock the range.
838 ret = btrfs_repair_one_sector(BTRFS_I(inode), failed_bbio,
839 bio_offset + offset, page, pgoff + offset,
843 * We have submitted the read repair, the page release
844 * will be handled by the endio function of the
845 * submitted repair bio.
846 * Thus we don't need to do any thing here.
851 * Continue on failed repair, otherwise the remaining sectors
852 * will not be properly unlocked.
855 end_sector_io(page, start + offset, uptodate);
859 /* lots and lots of room for performance fixes in the end_bio funcs */
861 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
863 struct btrfs_inode *inode;
864 const bool uptodate = (err == 0);
867 ASSERT(page && page->mapping);
868 inode = BTRFS_I(page->mapping->host);
869 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
872 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
875 ASSERT(end + 1 - start <= U32_MAX);
876 len = end + 1 - start;
878 btrfs_page_clear_uptodate(fs_info, page, start, len);
879 btrfs_page_set_error(fs_info, page, start, len);
880 ret = err < 0 ? err : -EIO;
881 mapping_set_error(page->mapping, ret);
886 * after a writepage IO is done, we need to:
887 * clear the uptodate bits on error
888 * clear the writeback bits in the extent tree for this IO
889 * end_page_writeback if the page has no more pending IO
891 * Scheduling is not allowed, so the extent state tree is expected
892 * to have one and only one object corresponding to this IO.
894 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
896 struct bio *bio = &bbio->bio;
897 int error = blk_status_to_errno(bio->bi_status);
898 struct bio_vec *bvec;
901 struct bvec_iter_all iter_all;
902 bool first_bvec = true;
904 ASSERT(!bio_flagged(bio, BIO_CLONED));
905 bio_for_each_segment_all(bvec, bio, iter_all) {
906 struct page *page = bvec->bv_page;
907 struct inode *inode = page->mapping->host;
908 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
909 const u32 sectorsize = fs_info->sectorsize;
911 /* Our read/write should always be sector aligned. */
912 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
914 "partial page write in btrfs with offset %u and length %u",
915 bvec->bv_offset, bvec->bv_len);
916 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
918 "incomplete page write with offset %u and length %u",
919 bvec->bv_offset, bvec->bv_len);
921 start = page_offset(page) + bvec->bv_offset;
922 end = start + bvec->bv_len - 1;
925 btrfs_record_physical_zoned(inode, start, bio);
929 end_extent_writepage(page, error, start, end);
931 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
938 * Record previously processed extent range
940 * For endio_readpage_release_extent() to handle a full extent range, reducing
941 * the extent io operations.
943 struct processed_extent {
944 struct btrfs_inode *inode;
945 /* Start of the range in @inode */
947 /* End of the range in @inode */
953 * Try to release processed extent range
955 * May not release the extent range right now if the current range is
956 * contiguous to processed extent.
958 * Will release processed extent when any of @inode, @uptodate, the range is
959 * no longer contiguous to the processed range.
961 * Passing @inode == NULL will force processed extent to be released.
963 static void endio_readpage_release_extent(struct processed_extent *processed,
964 struct btrfs_inode *inode, u64 start, u64 end,
967 struct extent_state *cached = NULL;
968 struct extent_io_tree *tree;
970 /* The first extent, initialize @processed */
971 if (!processed->inode)
975 * Contiguous to processed extent, just uptodate the end.
977 * Several things to notice:
979 * - bio can be merged as long as on-disk bytenr is contiguous
980 * This means we can have page belonging to other inodes, thus need to
981 * check if the inode still matches.
982 * - bvec can contain range beyond current page for multi-page bvec
983 * Thus we need to do processed->end + 1 >= start check
985 if (processed->inode == inode && processed->uptodate == uptodate &&
986 processed->end + 1 >= start && end >= processed->end) {
987 processed->end = end;
991 tree = &processed->inode->io_tree;
993 * Now we don't have range contiguous to the processed range, release
994 * the processed range now.
996 unlock_extent(tree, processed->start, processed->end, &cached);
999 /* Update processed to current range */
1000 processed->inode = inode;
1001 processed->start = start;
1002 processed->end = end;
1003 processed->uptodate = uptodate;
1006 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
1008 ASSERT(PageLocked(page));
1009 if (!btrfs_is_subpage(fs_info, page))
1012 ASSERT(PagePrivate(page));
1013 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
1017 * Find extent buffer for a givne bytenr.
1019 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
1022 static struct extent_buffer *find_extent_buffer_readpage(
1023 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
1025 struct extent_buffer *eb;
1028 * For regular sectorsize, we can use page->private to grab extent
1031 if (fs_info->nodesize >= PAGE_SIZE) {
1032 ASSERT(PagePrivate(page) && page->private);
1033 return (struct extent_buffer *)page->private;
1036 /* For subpage case, we need to lookup buffer radix tree */
1038 eb = radix_tree_lookup(&fs_info->buffer_radix,
1039 bytenr >> fs_info->sectorsize_bits);
1046 * after a readpage IO is done, we need to:
1047 * clear the uptodate bits on error
1048 * set the uptodate bits if things worked
1049 * set the page up to date if all extents in the tree are uptodate
1050 * clear the lock bit in the extent tree
1051 * unlock the page if there are no other extents locked for it
1053 * Scheduling is not allowed, so the extent state tree is expected
1054 * to have one and only one object corresponding to this IO.
1056 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
1058 struct bio *bio = &bbio->bio;
1059 struct bio_vec *bvec;
1060 struct processed_extent processed = { 0 };
1062 * The offset to the beginning of a bio, since one bio can never be
1063 * larger than UINT_MAX, u32 here is enough.
1067 struct bvec_iter_all iter_all;
1069 ASSERT(!bio_flagged(bio, BIO_CLONED));
1070 bio_for_each_segment_all(bvec, bio, iter_all) {
1071 bool uptodate = !bio->bi_status;
1072 struct page *page = bvec->bv_page;
1073 struct inode *inode = page->mapping->host;
1074 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1075 const u32 sectorsize = fs_info->sectorsize;
1076 unsigned int error_bitmap = (unsigned int)-1;
1077 bool repair = false;
1082 btrfs_debug(fs_info,
1083 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
1084 bio->bi_iter.bi_sector, bio->bi_status,
1088 * We always issue full-sector reads, but if some block in a
1089 * page fails to read, blk_update_request() will advance
1090 * bv_offset and adjust bv_len to compensate. Print a warning
1091 * for unaligned offsets, and an error if they don't add up to
1094 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1096 "partial page read in btrfs with offset %u and length %u",
1097 bvec->bv_offset, bvec->bv_len);
1098 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
1101 "incomplete page read with offset %u and length %u",
1102 bvec->bv_offset, bvec->bv_len);
1104 start = page_offset(page) + bvec->bv_offset;
1105 end = start + bvec->bv_len - 1;
1108 mirror = bbio->mirror_num;
1109 if (likely(uptodate)) {
1110 if (is_data_inode(inode)) {
1111 error_bitmap = btrfs_verify_data_csum(bbio,
1112 bio_offset, page, start, end);
1116 if (btrfs_validate_metadata_buffer(bbio,
1117 page, start, end, mirror))
1122 if (likely(uptodate)) {
1123 loff_t i_size = i_size_read(inode);
1124 pgoff_t end_index = i_size >> PAGE_SHIFT;
1126 btrfs_clean_io_failure(BTRFS_I(inode), start, page, 0);
1129 * Zero out the remaining part if this range straddles
1132 * Here we should only zero the range inside the bvec,
1133 * not touch anything else.
1135 * NOTE: i_size is exclusive while end is inclusive.
1137 if (page->index == end_index && i_size <= end) {
1138 u32 zero_start = max(offset_in_page(i_size),
1139 offset_in_page(start));
1141 zero_user_segment(page, zero_start,
1142 offset_in_page(end) + 1);
1144 } else if (is_data_inode(inode)) {
1146 * Only try to repair bios that actually made it to a
1147 * device. If the bio failed to be submitted mirror
1148 * is 0 and we need to fail it without retrying.
1150 * This also includes the high level bios for compressed
1151 * extents - these never make it to a device and repair
1152 * is already handled on the lower compressed bio.
1157 struct extent_buffer *eb;
1159 eb = find_extent_buffer_readpage(fs_info, page, start);
1160 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
1161 eb->read_mirror = mirror;
1162 atomic_dec(&eb->io_pages);
1167 * submit_data_read_repair() will handle all the good
1168 * and bad sectors, we just continue to the next bvec.
1170 submit_data_read_repair(inode, bbio, bio_offset, bvec,
1173 /* Update page status and unlock */
1174 end_page_read(page, uptodate, start, len);
1175 endio_readpage_release_extent(&processed, BTRFS_I(inode),
1176 start, end, PageUptodate(page));
1179 ASSERT(bio_offset + len > bio_offset);
1183 /* Release the last extent */
1184 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
1185 btrfs_bio_free_csum(bbio);
1190 * Populate every free slot in a provided array with pages.
1192 * @nr_pages: number of pages to allocate
1193 * @page_array: the array to fill with pages; any existing non-null entries in
1194 * the array will be skipped
1196 * Return: 0 if all pages were able to be allocated;
1197 * -ENOMEM otherwise, and the caller is responsible for freeing all
1198 * non-null page pointers in the array.
1200 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
1202 unsigned int allocated;
1204 for (allocated = 0; allocated < nr_pages;) {
1205 unsigned int last = allocated;
1207 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
1209 if (allocated == nr_pages)
1213 * During this iteration, no page could be allocated, even
1214 * though alloc_pages_bulk_array() falls back to alloc_page()
1215 * if it could not bulk-allocate. So we must be out of memory.
1217 if (allocated == last)
1220 memalloc_retry_wait(GFP_NOFS);
1226 * Attempt to add a page to bio.
1228 * @bio_ctrl: record both the bio, and its bio_flags
1229 * @page: page to add to the bio
1230 * @disk_bytenr: offset of the new bio or to check whether we are adding
1231 * a contiguous page to the previous one
1232 * @size: portion of page that we want to write
1233 * @pg_offset: starting offset in the page
1234 * @compress_type: compression type of the current bio to see if we can merge them
1236 * Attempt to add a page to bio considering stripe alignment etc.
1238 * Return >= 0 for the number of bytes added to the bio.
1239 * Can return 0 if the current bio is already at stripe/zone boundary.
1240 * Return <0 for error.
1242 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
1244 u64 disk_bytenr, unsigned int size,
1245 unsigned int pg_offset,
1246 enum btrfs_compression_type compress_type)
1248 struct bio *bio = bio_ctrl->bio;
1249 u32 bio_size = bio->bi_iter.bi_size;
1251 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
1252 bool contig = false;
1256 /* The limit should be calculated when bio_ctrl->bio is allocated */
1257 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
1258 if (bio_ctrl->compress_type != compress_type)
1262 if (bio->bi_iter.bi_size == 0) {
1263 /* We can always add a page into an empty bio. */
1265 } else if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE) {
1266 struct bio_vec *bvec = bio_last_bvec_all(bio);
1269 * The contig check requires the following conditions to be met:
1270 * 1) The pages are belonging to the same inode
1271 * This is implied by the call chain.
1273 * 2) The range has adjacent logical bytenr
1275 * 3) The range has adjacent file offset
1276 * This is required for the usage of btrfs_bio->file_offset.
1278 if (bio_end_sector(bio) == sector &&
1279 page_offset(bvec->bv_page) + bvec->bv_offset +
1280 bvec->bv_len == page_offset(page) + pg_offset)
1284 * For compression, all IO should have its logical bytenr
1285 * set to the starting bytenr of the compressed extent.
1287 contig = bio->bi_iter.bi_sector == sector;
1293 real_size = min(bio_ctrl->len_to_oe_boundary,
1294 bio_ctrl->len_to_stripe_boundary) - bio_size;
1295 real_size = min(real_size, size);
1298 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
1299 * bio will still execute its endio function on the page!
1304 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
1305 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
1307 ret = bio_add_page(bio, page, real_size, pg_offset);
1312 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
1313 struct btrfs_inode *inode, u64 file_offset)
1315 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1316 struct btrfs_io_geometry geom;
1317 struct btrfs_ordered_extent *ordered;
1318 struct extent_map *em;
1319 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
1323 * Pages for compressed extent are never submitted to disk directly,
1324 * thus it has no real boundary, just set them to U32_MAX.
1326 * The split happens for real compressed bio, which happens in
1327 * btrfs_submit_compressed_read/write().
1329 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
1330 bio_ctrl->len_to_oe_boundary = U32_MAX;
1331 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1334 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
1337 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
1339 free_extent_map(em);
1343 if (geom.len > U32_MAX)
1344 bio_ctrl->len_to_stripe_boundary = U32_MAX;
1346 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
1348 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
1349 bio_ctrl->len_to_oe_boundary = U32_MAX;
1353 /* Ordered extent not yet created, so we're good */
1354 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
1356 bio_ctrl->len_to_oe_boundary = U32_MAX;
1360 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
1361 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
1362 btrfs_put_ordered_extent(ordered);
1366 static int alloc_new_bio(struct btrfs_inode *inode,
1367 struct btrfs_bio_ctrl *bio_ctrl,
1368 struct writeback_control *wbc,
1370 u64 disk_bytenr, u32 offset, u64 file_offset,
1371 enum btrfs_compression_type compress_type)
1373 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1377 ASSERT(bio_ctrl->end_io_func);
1379 bio = btrfs_bio_alloc(BIO_MAX_VECS, opf, bio_ctrl->end_io_func, NULL);
1381 * For compressed page range, its disk_bytenr is always @disk_bytenr
1382 * passed in, no matter if we have added any range into previous bio.
1384 if (compress_type != BTRFS_COMPRESS_NONE)
1385 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
1387 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
1388 bio_ctrl->bio = bio;
1389 bio_ctrl->compress_type = compress_type;
1390 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
1396 * For Zone append we need the correct block_device that we are
1397 * going to write to set in the bio to be able to respect the
1398 * hardware limitation. Look it up here:
1400 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
1401 struct btrfs_device *dev;
1403 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
1404 fs_info->sectorsize);
1410 bio_set_dev(bio, dev->bdev);
1413 * Otherwise pick the last added device to support
1414 * cgroup writeback. For multi-device file systems this
1415 * means blk-cgroup policies have to always be set on the
1416 * last added/replaced device. This is a bit odd but has
1417 * been like that for a long time.
1419 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
1421 wbc_init_bio(wbc, bio);
1423 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
1427 bio_ctrl->bio = NULL;
1428 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
1433 * @opf: bio REQ_OP_* and REQ_* flags as one value
1434 * @wbc: optional writeback control for io accounting
1435 * @disk_bytenr: logical bytenr where the write will be
1436 * @page: page to add to the bio
1437 * @size: portion of page that we want to write to
1438 * @pg_offset: offset of the new bio or to check whether we are adding
1439 * a contiguous page to the previous one
1440 * @compress_type: compress type for current bio
1442 * The will either add the page into the existing @bio_ctrl->bio, or allocate a
1443 * new one in @bio_ctrl->bio.
1444 * The mirror number for this IO should already be initizlied in
1445 * @bio_ctrl->mirror_num.
1447 static int submit_extent_page(blk_opf_t opf,
1448 struct writeback_control *wbc,
1449 struct btrfs_bio_ctrl *bio_ctrl,
1450 u64 disk_bytenr, struct page *page,
1451 size_t size, unsigned long pg_offset,
1452 enum btrfs_compression_type compress_type,
1453 bool force_bio_submit)
1456 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1457 unsigned int cur = pg_offset;
1461 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
1462 pg_offset + size <= PAGE_SIZE);
1464 ASSERT(bio_ctrl->end_io_func);
1466 if (force_bio_submit)
1467 submit_one_bio(bio_ctrl);
1469 while (cur < pg_offset + size) {
1470 u32 offset = cur - pg_offset;
1473 /* Allocate new bio if needed */
1474 if (!bio_ctrl->bio) {
1475 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
1476 disk_bytenr, offset,
1477 page_offset(page) + cur,
1483 * We must go through btrfs_bio_add_page() to ensure each
1484 * page range won't cross various boundaries.
1486 if (compress_type != BTRFS_COMPRESS_NONE)
1487 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
1488 size - offset, pg_offset + offset,
1491 added = btrfs_bio_add_page(bio_ctrl, page,
1492 disk_bytenr + offset, size - offset,
1493 pg_offset + offset, compress_type);
1495 /* Metadata page range should never be split */
1496 if (!is_data_inode(&inode->vfs_inode))
1497 ASSERT(added == 0 || added == size - offset);
1499 /* At least we added some page, update the account */
1501 wbc_account_cgroup_owner(wbc, page, added);
1503 /* We have reached boundary, submit right now */
1504 if (added < size - offset) {
1505 /* The bio should contain some page(s) */
1506 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
1507 submit_one_bio(bio_ctrl);
1514 static int attach_extent_buffer_page(struct extent_buffer *eb,
1516 struct btrfs_subpage *prealloc)
1518 struct btrfs_fs_info *fs_info = eb->fs_info;
1522 * If the page is mapped to btree inode, we should hold the private
1523 * lock to prevent race.
1524 * For cloned or dummy extent buffers, their pages are not mapped and
1525 * will not race with any other ebs.
1528 lockdep_assert_held(&page->mapping->private_lock);
1530 if (fs_info->nodesize >= PAGE_SIZE) {
1531 if (!PagePrivate(page))
1532 attach_page_private(page, eb);
1534 WARN_ON(page->private != (unsigned long)eb);
1538 /* Already mapped, just free prealloc */
1539 if (PagePrivate(page)) {
1540 btrfs_free_subpage(prealloc);
1545 /* Has preallocated memory for subpage */
1546 attach_page_private(page, prealloc);
1548 /* Do new allocation to attach subpage */
1549 ret = btrfs_attach_subpage(fs_info, page,
1550 BTRFS_SUBPAGE_METADATA);
1554 int set_page_extent_mapped(struct page *page)
1556 struct btrfs_fs_info *fs_info;
1558 ASSERT(page->mapping);
1560 if (PagePrivate(page))
1563 fs_info = btrfs_sb(page->mapping->host->i_sb);
1565 if (btrfs_is_subpage(fs_info, page))
1566 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1568 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1572 void clear_page_extent_mapped(struct page *page)
1574 struct btrfs_fs_info *fs_info;
1576 ASSERT(page->mapping);
1578 if (!PagePrivate(page))
1581 fs_info = btrfs_sb(page->mapping->host->i_sb);
1582 if (btrfs_is_subpage(fs_info, page))
1583 return btrfs_detach_subpage(fs_info, page);
1585 detach_page_private(page);
1588 static struct extent_map *
1589 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1590 u64 start, u64 len, struct extent_map **em_cached)
1592 struct extent_map *em;
1594 if (em_cached && *em_cached) {
1596 if (extent_map_in_tree(em) && start >= em->start &&
1597 start < extent_map_end(em)) {
1598 refcount_inc(&em->refs);
1602 free_extent_map(em);
1606 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1607 if (em_cached && !IS_ERR(em)) {
1609 refcount_inc(&em->refs);
1615 * basic readpage implementation. Locked extent state structs are inserted
1616 * into the tree that are removed when the IO is done (by the end_io
1618 * XXX JDM: This needs looking at to ensure proper page locking
1619 * return 0 on success, otherwise return error
1621 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1622 struct btrfs_bio_ctrl *bio_ctrl,
1623 blk_opf_t read_flags, u64 *prev_em_start)
1625 struct inode *inode = page->mapping->host;
1626 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1627 u64 start = page_offset(page);
1628 const u64 end = start + PAGE_SIZE - 1;
1631 u64 last_byte = i_size_read(inode);
1633 struct extent_map *em;
1635 size_t pg_offset = 0;
1637 size_t blocksize = inode->i_sb->s_blocksize;
1638 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1640 ret = set_page_extent_mapped(page);
1642 unlock_extent(tree, start, end, NULL);
1643 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1648 if (page->index == last_byte >> PAGE_SHIFT) {
1649 size_t zero_offset = offset_in_page(last_byte);
1652 iosize = PAGE_SIZE - zero_offset;
1653 memzero_page(page, zero_offset, iosize);
1656 bio_ctrl->end_io_func = end_bio_extent_readpage;
1657 begin_page_read(fs_info, page);
1658 while (cur <= end) {
1659 unsigned long this_bio_flag = 0;
1660 bool force_bio_submit = false;
1663 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1664 if (cur >= last_byte) {
1665 iosize = PAGE_SIZE - pg_offset;
1666 memzero_page(page, pg_offset, iosize);
1667 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1668 end_page_read(page, true, cur, iosize);
1671 em = __get_extent_map(inode, page, pg_offset, cur,
1672 end - cur + 1, em_cached);
1674 unlock_extent(tree, cur, end, NULL);
1675 end_page_read(page, false, cur, end + 1 - cur);
1679 extent_offset = cur - em->start;
1680 BUG_ON(extent_map_end(em) <= cur);
1683 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1684 this_bio_flag = em->compress_type;
1686 iosize = min(extent_map_end(em) - cur, end - cur + 1);
1687 iosize = ALIGN(iosize, blocksize);
1688 if (this_bio_flag != BTRFS_COMPRESS_NONE)
1689 disk_bytenr = em->block_start;
1691 disk_bytenr = em->block_start + extent_offset;
1692 block_start = em->block_start;
1693 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1694 block_start = EXTENT_MAP_HOLE;
1697 * If we have a file range that points to a compressed extent
1698 * and it's followed by a consecutive file range that points
1699 * to the same compressed extent (possibly with a different
1700 * offset and/or length, so it either points to the whole extent
1701 * or only part of it), we must make sure we do not submit a
1702 * single bio to populate the pages for the 2 ranges because
1703 * this makes the compressed extent read zero out the pages
1704 * belonging to the 2nd range. Imagine the following scenario:
1707 * [0 - 8K] [8K - 24K]
1710 * points to extent X, points to extent X,
1711 * offset 4K, length of 8K offset 0, length 16K
1713 * [extent X, compressed length = 4K uncompressed length = 16K]
1715 * If the bio to read the compressed extent covers both ranges,
1716 * it will decompress extent X into the pages belonging to the
1717 * first range and then it will stop, zeroing out the remaining
1718 * pages that belong to the other range that points to extent X.
1719 * So here we make sure we submit 2 bios, one for the first
1720 * range and another one for the third range. Both will target
1721 * the same physical extent from disk, but we can't currently
1722 * make the compressed bio endio callback populate the pages
1723 * for both ranges because each compressed bio is tightly
1724 * coupled with a single extent map, and each range can have
1725 * an extent map with a different offset value relative to the
1726 * uncompressed data of our extent and different lengths. This
1727 * is a corner case so we prioritize correctness over
1728 * non-optimal behavior (submitting 2 bios for the same extent).
1730 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1731 prev_em_start && *prev_em_start != (u64)-1 &&
1732 *prev_em_start != em->start)
1733 force_bio_submit = true;
1736 *prev_em_start = em->start;
1738 free_extent_map(em);
1741 /* we've found a hole, just zero and go on */
1742 if (block_start == EXTENT_MAP_HOLE) {
1743 memzero_page(page, pg_offset, iosize);
1745 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1746 end_page_read(page, true, cur, iosize);
1748 pg_offset += iosize;
1751 /* the get_extent function already copied into the page */
1752 if (block_start == EXTENT_MAP_INLINE) {
1753 unlock_extent(tree, cur, cur + iosize - 1, NULL);
1754 end_page_read(page, true, cur, iosize);
1756 pg_offset += iosize;
1760 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
1761 bio_ctrl, disk_bytenr, page, iosize,
1762 pg_offset, this_bio_flag,
1766 * We have to unlock the remaining range, or the page
1767 * will never be unlocked.
1769 unlock_extent(tree, cur, end, NULL);
1770 end_page_read(page, false, cur, end + 1 - cur);
1774 pg_offset += iosize;
1780 int btrfs_read_folio(struct file *file, struct folio *folio)
1782 struct page *page = &folio->page;
1783 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1784 u64 start = page_offset(page);
1785 u64 end = start + PAGE_SIZE - 1;
1786 struct btrfs_bio_ctrl bio_ctrl = { 0 };
1789 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1791 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
1793 * If btrfs_do_readpage() failed we will want to submit the assembled
1794 * bio to do the cleanup.
1796 submit_one_bio(&bio_ctrl);
1800 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1802 struct extent_map **em_cached,
1803 struct btrfs_bio_ctrl *bio_ctrl,
1806 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1809 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1811 for (index = 0; index < nr_pages; index++) {
1812 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1813 REQ_RAHEAD, prev_em_start);
1814 put_page(pages[index]);
1819 * helper for __extent_writepage, doing all of the delayed allocation setup.
1821 * This returns 1 if btrfs_run_delalloc_range function did all the work required
1822 * to write the page (copy into inline extent). In this case the IO has
1823 * been started and the page is already unlocked.
1825 * This returns 0 if all went well (page still locked)
1826 * This returns < 0 if there were errors (page still locked)
1828 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1829 struct page *page, struct writeback_control *wbc)
1831 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1832 u64 delalloc_start = page_offset(page);
1833 u64 delalloc_to_write = 0;
1834 /* How many pages are started by btrfs_run_delalloc_range() */
1835 unsigned long nr_written = 0;
1837 int page_started = 0;
1839 while (delalloc_start < page_end) {
1840 u64 delalloc_end = page_end;
1843 found = find_lock_delalloc_range(&inode->vfs_inode, page,
1847 delalloc_start = delalloc_end + 1;
1850 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1851 delalloc_end, &page_started, &nr_written, wbc);
1853 btrfs_page_set_error(inode->root->fs_info, page,
1854 page_offset(page), PAGE_SIZE);
1858 * delalloc_end is already one less than the total length, so
1859 * we don't subtract one from PAGE_SIZE
1861 delalloc_to_write += (delalloc_end - delalloc_start +
1862 PAGE_SIZE) >> PAGE_SHIFT;
1863 delalloc_start = delalloc_end + 1;
1865 if (wbc->nr_to_write < delalloc_to_write) {
1868 if (delalloc_to_write < thresh * 2)
1869 thresh = delalloc_to_write;
1870 wbc->nr_to_write = min_t(u64, delalloc_to_write,
1874 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
1877 * We've unlocked the page, so we can't update the mapping's
1878 * writeback index, just update nr_to_write.
1880 wbc->nr_to_write -= nr_written;
1888 * Find the first byte we need to write.
1890 * For subpage, one page can contain several sectors, and
1891 * __extent_writepage_io() will just grab all extent maps in the page
1892 * range and try to submit all non-inline/non-compressed extents.
1894 * This is a big problem for subpage, we shouldn't re-submit already written
1896 * This function will lookup subpage dirty bit to find which range we really
1899 * Return the next dirty range in [@start, @end).
1900 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
1902 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
1903 struct page *page, u64 *start, u64 *end)
1905 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
1906 struct btrfs_subpage_info *spi = fs_info->subpage_info;
1907 u64 orig_start = *start;
1908 /* Declare as unsigned long so we can use bitmap ops */
1909 unsigned long flags;
1910 int range_start_bit;
1914 * For regular sector size == page size case, since one page only
1915 * contains one sector, we return the page offset directly.
1917 if (!btrfs_is_subpage(fs_info, page)) {
1918 *start = page_offset(page);
1919 *end = page_offset(page) + PAGE_SIZE;
1923 range_start_bit = spi->dirty_offset +
1924 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
1926 /* We should have the page locked, but just in case */
1927 spin_lock_irqsave(&subpage->lock, flags);
1928 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
1929 spi->dirty_offset + spi->bitmap_nr_bits);
1930 spin_unlock_irqrestore(&subpage->lock, flags);
1932 range_start_bit -= spi->dirty_offset;
1933 range_end_bit -= spi->dirty_offset;
1935 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
1936 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
1940 * helper for __extent_writepage. This calls the writepage start hooks,
1941 * and does the loop to map the page into extents and bios.
1943 * We return 1 if the IO is started and the page is unlocked,
1944 * 0 if all went well (page still locked)
1945 * < 0 if there were errors (page still locked)
1947 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
1949 struct writeback_control *wbc,
1950 struct btrfs_bio_ctrl *bio_ctrl,
1954 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1955 u64 cur = page_offset(page);
1956 u64 end = cur + PAGE_SIZE - 1;
1959 struct extent_map *em;
1963 enum req_op op = REQ_OP_WRITE;
1964 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1965 bool has_error = false;
1968 ret = btrfs_writepage_cow_fixup(page);
1970 /* Fixup worker will requeue */
1971 redirty_page_for_writepage(wbc, page);
1977 * we don't want to touch the inode after unlocking the page,
1978 * so we update the mapping writeback index now
1982 bio_ctrl->end_io_func = end_bio_extent_writepage;
1983 while (cur <= end) {
1986 u64 dirty_range_start = cur;
1987 u64 dirty_range_end;
1990 if (cur >= i_size) {
1991 btrfs_writepage_endio_finish_ordered(inode, page, cur,
1994 * This range is beyond i_size, thus we don't need to
1995 * bother writing back.
1996 * But we still need to clear the dirty subpage bit, or
1997 * the next time the page gets dirtied, we will try to
1998 * writeback the sectors with subpage dirty bits,
1999 * causing writeback without ordered extent.
2001 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
2005 find_next_dirty_byte(fs_info, page, &dirty_range_start,
2007 if (cur < dirty_range_start) {
2008 cur = dirty_range_start;
2012 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
2014 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
2015 ret = PTR_ERR_OR_ZERO(em);
2022 extent_offset = cur - em->start;
2023 em_end = extent_map_end(em);
2024 ASSERT(cur <= em_end);
2026 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
2027 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
2028 block_start = em->block_start;
2029 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
2030 disk_bytenr = em->block_start + extent_offset;
2033 * Note that em_end from extent_map_end() and dirty_range_end from
2034 * find_next_dirty_byte() are all exclusive
2036 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
2038 if (btrfs_use_zone_append(inode, em->block_start))
2039 op = REQ_OP_ZONE_APPEND;
2041 free_extent_map(em);
2045 * compressed and inline extents are written through other
2048 if (compressed || block_start == EXTENT_MAP_HOLE ||
2049 block_start == EXTENT_MAP_INLINE) {
2053 btrfs_writepage_endio_finish_ordered(inode,
2054 page, cur, cur + iosize - 1, true);
2055 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2060 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
2061 if (!PageWriteback(page)) {
2062 btrfs_err(inode->root->fs_info,
2063 "page %lu not writeback, cur %llu end %llu",
2064 page->index, cur, end);
2068 * Although the PageDirty bit is cleared before entering this
2069 * function, subpage dirty bit is not cleared.
2070 * So clear subpage dirty bit here so next time we won't submit
2071 * page for range already written to disk.
2073 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2075 ret = submit_extent_page(op | write_flags, wbc,
2076 bio_ctrl, disk_bytenr,
2078 cur - page_offset(page),
2085 btrfs_page_set_error(fs_info, page, cur, iosize);
2086 if (PageWriteback(page))
2087 btrfs_page_clear_writeback(fs_info, page, cur,
2095 * If we finish without problem, we should not only clear page dirty,
2096 * but also empty subpage dirty bits
2099 btrfs_page_assert_not_dirty(fs_info, page);
2107 * the writepage semantics are similar to regular writepage. extent
2108 * records are inserted to lock ranges in the tree, and as dirty areas
2109 * are found, they are marked writeback. Then the lock bits are removed
2110 * and the end_io handler clears the writeback ranges
2112 * Return 0 if everything goes well.
2113 * Return <0 for error.
2115 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2116 struct btrfs_bio_ctrl *bio_ctrl)
2118 struct folio *folio = page_folio(page);
2119 struct inode *inode = page->mapping->host;
2120 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2121 const u64 page_start = page_offset(page);
2122 const u64 page_end = page_start + PAGE_SIZE - 1;
2126 loff_t i_size = i_size_read(inode);
2127 unsigned long end_index = i_size >> PAGE_SHIFT;
2129 trace___extent_writepage(page, inode, wbc);
2131 WARN_ON(!PageLocked(page));
2133 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
2134 page_offset(page), PAGE_SIZE);
2136 pg_offset = offset_in_page(i_size);
2137 if (page->index > end_index ||
2138 (page->index == end_index && !pg_offset)) {
2139 folio_invalidate(folio, 0, folio_size(folio));
2140 folio_unlock(folio);
2144 if (page->index == end_index)
2145 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
2147 ret = set_page_extent_mapped(page);
2153 if (!bio_ctrl->extent_locked) {
2154 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
2161 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, bio_ctrl, i_size,
2168 /* make sure the mapping tag for page dirty gets cleared */
2169 set_page_writeback(page);
2170 end_page_writeback(page);
2173 * Here we used to have a check for PageError() and then set @ret and
2174 * call end_extent_writepage().
2176 * But in fact setting @ret here will cause different error paths
2177 * between subpage and regular sectorsize.
2179 * For regular page size, we never submit current page, but only add
2180 * current page to current bio.
2181 * The bio submission can only happen in next page.
2182 * Thus if we hit the PageError() branch, @ret is already set to
2183 * non-zero value and will not get updated for regular sectorsize.
2185 * But for subpage case, it's possible we submit part of current page,
2186 * thus can get PageError() set by submitted bio of the same page,
2187 * while our @ret is still 0.
2189 * So here we unify the behavior and don't set @ret.
2190 * Error can still be properly passed to higher layer as page will
2191 * be set error, here we just don't handle the IO failure.
2193 * NOTE: This is just a hotfix for subpage.
2194 * The root fix will be properly ending ordered extent when we hit
2195 * an error during writeback.
2197 * But that needs a bigger refactoring, as we not only need to grab the
2198 * submitted OE, but also need to know exactly at which bytenr we hit
2200 * Currently the full page based __extent_writepage_io() is not
2203 if (PageError(page))
2204 end_extent_writepage(page, ret, page_start, page_end);
2205 if (bio_ctrl->extent_locked) {
2207 * If bio_ctrl->extent_locked, it's from extent_write_locked_range(),
2208 * the page can either be locked by lock_page() or
2209 * process_one_page().
2210 * Let btrfs_page_unlock_writer() handle both cases.
2213 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
2214 wbc->range_end + 1 - wbc->range_start);
2222 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
2224 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
2225 TASK_UNINTERRUPTIBLE);
2228 static void end_extent_buffer_writeback(struct extent_buffer *eb)
2230 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2231 smp_mb__after_atomic();
2232 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
2236 * Lock extent buffer status and pages for writeback.
2238 * May try to flush write bio if we can't get the lock.
2240 * Return 0 if the extent buffer doesn't need to be submitted.
2241 * (E.g. the extent buffer is not dirty)
2242 * Return >0 is the extent buffer is submitted to bio.
2243 * Return <0 if something went wrong, no page is locked.
2245 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
2246 struct btrfs_bio_ctrl *bio_ctrl)
2248 struct btrfs_fs_info *fs_info = eb->fs_info;
2253 if (!btrfs_try_tree_write_lock(eb)) {
2254 submit_write_bio(bio_ctrl, 0);
2256 btrfs_tree_lock(eb);
2259 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
2260 btrfs_tree_unlock(eb);
2261 if (!bio_ctrl->sync_io)
2264 submit_write_bio(bio_ctrl, 0);
2268 wait_on_extent_buffer_writeback(eb);
2269 btrfs_tree_lock(eb);
2270 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
2272 btrfs_tree_unlock(eb);
2277 * We need to do this to prevent races in people who check if the eb is
2278 * under IO since we can end up having no IO bits set for a short period
2281 spin_lock(&eb->refs_lock);
2282 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
2283 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2284 spin_unlock(&eb->refs_lock);
2285 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
2286 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2288 fs_info->dirty_metadata_batch);
2291 spin_unlock(&eb->refs_lock);
2294 btrfs_tree_unlock(eb);
2297 * Either we don't need to submit any tree block, or we're submitting
2299 * Subpage metadata doesn't use page locking at all, so we can skip
2302 if (!ret || fs_info->nodesize < PAGE_SIZE)
2305 num_pages = num_extent_pages(eb);
2306 for (i = 0; i < num_pages; i++) {
2307 struct page *p = eb->pages[i];
2309 if (!trylock_page(p)) {
2311 submit_write_bio(bio_ctrl, 0);
2321 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
2323 struct btrfs_fs_info *fs_info = eb->fs_info;
2325 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
2326 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
2330 * A read may stumble upon this buffer later, make sure that it gets an
2331 * error and knows there was an error.
2333 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
2336 * We need to set the mapping with the io error as well because a write
2337 * error will flip the file system readonly, and then syncfs() will
2338 * return a 0 because we are readonly if we don't modify the err seq for
2341 mapping_set_error(page->mapping, -EIO);
2344 * If we error out, we should add back the dirty_metadata_bytes
2345 * to make it consistent.
2347 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2348 eb->len, fs_info->dirty_metadata_batch);
2351 * If writeback for a btree extent that doesn't belong to a log tree
2352 * failed, increment the counter transaction->eb_write_errors.
2353 * We do this because while the transaction is running and before it's
2354 * committing (when we call filemap_fdata[write|wait]_range against
2355 * the btree inode), we might have
2356 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
2357 * returns an error or an error happens during writeback, when we're
2358 * committing the transaction we wouldn't know about it, since the pages
2359 * can be no longer dirty nor marked anymore for writeback (if a
2360 * subsequent modification to the extent buffer didn't happen before the
2361 * transaction commit), which makes filemap_fdata[write|wait]_range not
2362 * able to find the pages tagged with SetPageError at transaction
2363 * commit time. So if this happens we must abort the transaction,
2364 * otherwise we commit a super block with btree roots that point to
2365 * btree nodes/leafs whose content on disk is invalid - either garbage
2366 * or the content of some node/leaf from a past generation that got
2367 * cowed or deleted and is no longer valid.
2369 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
2370 * not be enough - we need to distinguish between log tree extents vs
2371 * non-log tree extents, and the next filemap_fdatawait_range() call
2372 * will catch and clear such errors in the mapping - and that call might
2373 * be from a log sync and not from a transaction commit. Also, checking
2374 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
2375 * not done and would not be reliable - the eb might have been released
2376 * from memory and reading it back again means that flag would not be
2377 * set (since it's a runtime flag, not persisted on disk).
2379 * Using the flags below in the btree inode also makes us achieve the
2380 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
2381 * writeback for all dirty pages and before filemap_fdatawait_range()
2382 * is called, the writeback for all dirty pages had already finished
2383 * with errors - because we were not using AS_EIO/AS_ENOSPC,
2384 * filemap_fdatawait_range() would return success, as it could not know
2385 * that writeback errors happened (the pages were no longer tagged for
2388 switch (eb->log_index) {
2390 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
2393 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2396 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2399 BUG(); /* unexpected, logic error */
2404 * The endio specific version which won't touch any unsafe spinlock in endio
2407 static struct extent_buffer *find_extent_buffer_nolock(
2408 struct btrfs_fs_info *fs_info, u64 start)
2410 struct extent_buffer *eb;
2413 eb = radix_tree_lookup(&fs_info->buffer_radix,
2414 start >> fs_info->sectorsize_bits);
2415 if (eb && atomic_inc_not_zero(&eb->refs)) {
2424 * The endio function for subpage extent buffer write.
2426 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
2427 * after all extent buffers in the page has finished their writeback.
2429 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
2431 struct bio *bio = &bbio->bio;
2432 struct btrfs_fs_info *fs_info;
2433 struct bio_vec *bvec;
2434 struct bvec_iter_all iter_all;
2436 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
2437 ASSERT(fs_info->nodesize < PAGE_SIZE);
2439 ASSERT(!bio_flagged(bio, BIO_CLONED));
2440 bio_for_each_segment_all(bvec, bio, iter_all) {
2441 struct page *page = bvec->bv_page;
2442 u64 bvec_start = page_offset(page) + bvec->bv_offset;
2443 u64 bvec_end = bvec_start + bvec->bv_len - 1;
2444 u64 cur_bytenr = bvec_start;
2446 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
2448 /* Iterate through all extent buffers in the range */
2449 while (cur_bytenr <= bvec_end) {
2450 struct extent_buffer *eb;
2454 * Here we can't use find_extent_buffer(), as it may
2455 * try to lock eb->refs_lock, which is not safe in endio
2458 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
2461 cur_bytenr = eb->start + eb->len;
2463 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
2464 done = atomic_dec_and_test(&eb->io_pages);
2467 if (bio->bi_status ||
2468 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2469 ClearPageUptodate(page);
2470 set_btree_ioerr(page, eb);
2473 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
2475 end_extent_buffer_writeback(eb);
2477 * free_extent_buffer() will grab spinlock which is not
2478 * safe in endio context. Thus here we manually dec
2481 atomic_dec(&eb->refs);
2487 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
2489 struct bio *bio = &bbio->bio;
2490 struct bio_vec *bvec;
2491 struct extent_buffer *eb;
2493 struct bvec_iter_all iter_all;
2495 ASSERT(!bio_flagged(bio, BIO_CLONED));
2496 bio_for_each_segment_all(bvec, bio, iter_all) {
2497 struct page *page = bvec->bv_page;
2499 eb = (struct extent_buffer *)page->private;
2501 done = atomic_dec_and_test(&eb->io_pages);
2503 if (bio->bi_status ||
2504 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2505 ClearPageUptodate(page);
2506 set_btree_ioerr(page, eb);
2509 end_page_writeback(page);
2514 end_extent_buffer_writeback(eb);
2520 static void prepare_eb_write(struct extent_buffer *eb)
2523 unsigned long start;
2526 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2527 atomic_set(&eb->io_pages, num_extent_pages(eb));
2529 /* Set btree blocks beyond nritems with 0 to avoid stale content */
2530 nritems = btrfs_header_nritems(eb);
2531 if (btrfs_header_level(eb) > 0) {
2532 end = btrfs_node_key_ptr_offset(eb, nritems);
2533 memzero_extent_buffer(eb, end, eb->len - end);
2537 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2539 start = btrfs_item_nr_offset(eb, nritems);
2540 end = btrfs_item_nr_offset(eb, 0);
2542 end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
2544 end += btrfs_item_offset(eb, nritems - 1);
2545 memzero_extent_buffer(eb, start, end - start);
2550 * Unlike the work in write_one_eb(), we rely completely on extent locking.
2551 * Page locking is only utilized at minimum to keep the VMM code happy.
2553 static int write_one_subpage_eb(struct extent_buffer *eb,
2554 struct writeback_control *wbc,
2555 struct btrfs_bio_ctrl *bio_ctrl)
2557 struct btrfs_fs_info *fs_info = eb->fs_info;
2558 struct page *page = eb->pages[0];
2559 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2560 bool no_dirty_ebs = false;
2563 prepare_eb_write(eb);
2565 /* clear_page_dirty_for_io() in subpage helper needs page locked */
2567 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2569 /* Check if this is the last dirty bit to update nr_written */
2570 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2571 eb->start, eb->len);
2573 clear_page_dirty_for_io(page);
2575 bio_ctrl->end_io_func = end_bio_subpage_eb_writepage;
2577 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2578 bio_ctrl, eb->start, page, eb->len,
2579 eb->start - page_offset(page), 0, false);
2581 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
2582 set_btree_ioerr(page, eb);
2585 if (atomic_dec_and_test(&eb->io_pages))
2586 end_extent_buffer_writeback(eb);
2591 * Submission finished without problem, if no range of the page is
2592 * dirty anymore, we have submitted a page. Update nr_written in wbc.
2599 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
2600 struct writeback_control *wbc,
2601 struct btrfs_bio_ctrl *bio_ctrl)
2603 u64 disk_bytenr = eb->start;
2605 blk_opf_t write_flags = wbc_to_write_flags(wbc);
2608 prepare_eb_write(eb);
2610 bio_ctrl->end_io_func = end_bio_extent_buffer_writepage;
2612 num_pages = num_extent_pages(eb);
2613 for (i = 0; i < num_pages; i++) {
2614 struct page *p = eb->pages[i];
2616 clear_page_dirty_for_io(p);
2617 set_page_writeback(p);
2618 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2619 bio_ctrl, disk_bytenr, p,
2620 PAGE_SIZE, 0, 0, false);
2622 set_btree_ioerr(p, eb);
2623 if (PageWriteback(p))
2624 end_page_writeback(p);
2625 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
2626 end_extent_buffer_writeback(eb);
2630 disk_bytenr += PAGE_SIZE;
2635 if (unlikely(ret)) {
2636 for (; i < num_pages; i++) {
2637 struct page *p = eb->pages[i];
2638 clear_page_dirty_for_io(p);
2647 * Submit one subpage btree page.
2649 * The main difference to submit_eb_page() is:
2651 * For subpage, we don't rely on page locking at all.
2654 * We only flush bio if we may be unable to fit current extent buffers into
2657 * Return >=0 for the number of submitted extent buffers.
2658 * Return <0 for fatal error.
2660 static int submit_eb_subpage(struct page *page,
2661 struct writeback_control *wbc,
2662 struct btrfs_bio_ctrl *bio_ctrl)
2664 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2666 u64 page_start = page_offset(page);
2668 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
2671 /* Lock and write each dirty extent buffers in the range */
2672 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
2673 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2674 struct extent_buffer *eb;
2675 unsigned long flags;
2679 * Take private lock to ensure the subpage won't be detached
2682 spin_lock(&page->mapping->private_lock);
2683 if (!PagePrivate(page)) {
2684 spin_unlock(&page->mapping->private_lock);
2687 spin_lock_irqsave(&subpage->lock, flags);
2688 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
2689 subpage->bitmaps)) {
2690 spin_unlock_irqrestore(&subpage->lock, flags);
2691 spin_unlock(&page->mapping->private_lock);
2696 start = page_start + bit_start * fs_info->sectorsize;
2697 bit_start += sectors_per_node;
2700 * Here we just want to grab the eb without touching extra
2701 * spin locks, so call find_extent_buffer_nolock().
2703 eb = find_extent_buffer_nolock(fs_info, start);
2704 spin_unlock_irqrestore(&subpage->lock, flags);
2705 spin_unlock(&page->mapping->private_lock);
2708 * The eb has already reached 0 refs thus find_extent_buffer()
2709 * doesn't return it. We don't need to write back such eb
2715 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2717 free_extent_buffer(eb);
2721 free_extent_buffer(eb);
2724 ret = write_one_subpage_eb(eb, wbc, bio_ctrl);
2725 free_extent_buffer(eb);
2733 /* We hit error, end bio for the submitted extent buffers */
2734 submit_write_bio(bio_ctrl, ret);
2739 * Submit all page(s) of one extent buffer.
2741 * @page: the page of one extent buffer
2742 * @eb_context: to determine if we need to submit this page, if current page
2743 * belongs to this eb, we don't need to submit
2745 * The caller should pass each page in their bytenr order, and here we use
2746 * @eb_context to determine if we have submitted pages of one extent buffer.
2748 * If we have, we just skip until we hit a new page that doesn't belong to
2749 * current @eb_context.
2751 * If not, we submit all the page(s) of the extent buffer.
2753 * Return >0 if we have submitted the extent buffer successfully.
2754 * Return 0 if we don't need to submit the page, as it's already submitted by
2756 * Return <0 for fatal error.
2758 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
2759 struct btrfs_bio_ctrl *bio_ctrl,
2760 struct extent_buffer **eb_context)
2762 struct address_space *mapping = page->mapping;
2763 struct btrfs_block_group *cache = NULL;
2764 struct extent_buffer *eb;
2767 if (!PagePrivate(page))
2770 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
2771 return submit_eb_subpage(page, wbc, bio_ctrl);
2773 spin_lock(&mapping->private_lock);
2774 if (!PagePrivate(page)) {
2775 spin_unlock(&mapping->private_lock);
2779 eb = (struct extent_buffer *)page->private;
2782 * Shouldn't happen and normally this would be a BUG_ON but no point
2783 * crashing the machine for something we can survive anyway.
2786 spin_unlock(&mapping->private_lock);
2790 if (eb == *eb_context) {
2791 spin_unlock(&mapping->private_lock);
2794 ret = atomic_inc_not_zero(&eb->refs);
2795 spin_unlock(&mapping->private_lock);
2799 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
2801 * If for_sync, this hole will be filled with
2802 * trasnsaction commit.
2804 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
2808 free_extent_buffer(eb);
2814 ret = lock_extent_buffer_for_io(eb, bio_ctrl);
2816 btrfs_revert_meta_write_pointer(cache, eb);
2818 btrfs_put_block_group(cache);
2819 free_extent_buffer(eb);
2824 * Implies write in zoned mode. Mark the last eb in a block group.
2826 btrfs_schedule_zone_finish_bg(cache, eb);
2827 btrfs_put_block_group(cache);
2829 ret = write_one_eb(eb, wbc, bio_ctrl);
2830 free_extent_buffer(eb);
2836 int btree_write_cache_pages(struct address_space *mapping,
2837 struct writeback_control *wbc)
2839 struct extent_buffer *eb_context = NULL;
2840 struct btrfs_bio_ctrl bio_ctrl = {
2842 .sync_io = (wbc->sync_mode == WB_SYNC_ALL),
2844 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
2847 int nr_to_write_done = 0;
2848 struct pagevec pvec;
2851 pgoff_t end; /* Inclusive */
2855 pagevec_init(&pvec);
2856 if (wbc->range_cyclic) {
2857 index = mapping->writeback_index; /* Start from prev offset */
2860 * Start from the beginning does not need to cycle over the
2861 * range, mark it as scanned.
2863 scanned = (index == 0);
2865 index = wbc->range_start >> PAGE_SHIFT;
2866 end = wbc->range_end >> PAGE_SHIFT;
2869 if (wbc->sync_mode == WB_SYNC_ALL)
2870 tag = PAGECACHE_TAG_TOWRITE;
2872 tag = PAGECACHE_TAG_DIRTY;
2873 btrfs_zoned_meta_io_lock(fs_info);
2875 if (wbc->sync_mode == WB_SYNC_ALL)
2876 tag_pages_for_writeback(mapping, index, end);
2877 while (!done && !nr_to_write_done && (index <= end) &&
2878 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2882 for (i = 0; i < nr_pages; i++) {
2883 struct page *page = pvec.pages[i];
2885 ret = submit_eb_page(page, wbc, &bio_ctrl, &eb_context);
2894 * the filesystem may choose to bump up nr_to_write.
2895 * We have to make sure to honor the new nr_to_write
2898 nr_to_write_done = wbc->nr_to_write <= 0;
2900 pagevec_release(&pvec);
2903 if (!scanned && !done) {
2905 * We hit the last page and there is more work to be done: wrap
2906 * back to the start of the file
2913 * If something went wrong, don't allow any metadata write bio to be
2916 * This would prevent use-after-free if we had dirty pages not
2917 * cleaned up, which can still happen by fuzzed images.
2920 * Allowing existing tree block to be allocated for other trees.
2922 * - Log tree operations
2923 * Exiting tree blocks get allocated to log tree, bumps its
2924 * generation, then get cleaned in tree re-balance.
2925 * Such tree block will not be written back, since it's clean,
2926 * thus no WRITTEN flag set.
2927 * And after log writes back, this tree block is not traced by
2928 * any dirty extent_io_tree.
2930 * - Offending tree block gets re-dirtied from its original owner
2931 * Since it has bumped generation, no WRITTEN flag, it can be
2932 * reused without COWing. This tree block will not be traced
2933 * by btrfs_transaction::dirty_pages.
2935 * Now such dirty tree block will not be cleaned by any dirty
2936 * extent io tree. Thus we don't want to submit such wild eb
2937 * if the fs already has error.
2939 * We can get ret > 0 from submit_extent_page() indicating how many ebs
2940 * were submitted. Reset it to 0 to avoid false alerts for the caller.
2944 if (!ret && BTRFS_FS_ERROR(fs_info))
2946 submit_write_bio(&bio_ctrl, ret);
2948 btrfs_zoned_meta_io_unlock(fs_info);
2953 * Walk the list of dirty pages of the given address space and write all of them.
2955 * @mapping: address space structure to write
2956 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2957 * @bio_ctrl: holds context for the write, namely the bio
2959 * If a page is already under I/O, write_cache_pages() skips it, even
2960 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
2961 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
2962 * and msync() need to guarantee that all the data which was dirty at the time
2963 * the call was made get new I/O started against them. If wbc->sync_mode is
2964 * WB_SYNC_ALL then we were called for data integrity and we must wait for
2965 * existing IO to complete.
2967 static int extent_write_cache_pages(struct address_space *mapping,
2968 struct writeback_control *wbc,
2969 struct btrfs_bio_ctrl *bio_ctrl)
2971 struct inode *inode = mapping->host;
2974 int nr_to_write_done = 0;
2975 struct pagevec pvec;
2978 pgoff_t end; /* Inclusive */
2980 int range_whole = 0;
2985 * We have to hold onto the inode so that ordered extents can do their
2986 * work when the IO finishes. The alternative to this is failing to add
2987 * an ordered extent if the igrab() fails there and that is a huge pain
2988 * to deal with, so instead just hold onto the inode throughout the
2989 * writepages operation. If it fails here we are freeing up the inode
2990 * anyway and we'd rather not waste our time writing out stuff that is
2991 * going to be truncated anyway.
2996 pagevec_init(&pvec);
2997 if (wbc->range_cyclic) {
2998 index = mapping->writeback_index; /* Start from prev offset */
3001 * Start from the beginning does not need to cycle over the
3002 * range, mark it as scanned.
3004 scanned = (index == 0);
3006 index = wbc->range_start >> PAGE_SHIFT;
3007 end = wbc->range_end >> PAGE_SHIFT;
3008 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3014 * We do the tagged writepage as long as the snapshot flush bit is set
3015 * and we are the first one who do the filemap_flush() on this inode.
3017 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
3018 * not race in and drop the bit.
3020 if (range_whole && wbc->nr_to_write == LONG_MAX &&
3021 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
3022 &BTRFS_I(inode)->runtime_flags))
3023 wbc->tagged_writepages = 1;
3025 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3026 tag = PAGECACHE_TAG_TOWRITE;
3028 tag = PAGECACHE_TAG_DIRTY;
3030 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3031 tag_pages_for_writeback(mapping, index, end);
3033 while (!done && !nr_to_write_done && (index <= end) &&
3034 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
3035 &index, end, tag))) {
3038 for (i = 0; i < nr_pages; i++) {
3039 struct page *page = pvec.pages[i];
3041 done_index = page->index + 1;
3043 * At this point we hold neither the i_pages lock nor
3044 * the page lock: the page may be truncated or
3045 * invalidated (changing page->mapping to NULL),
3046 * or even swizzled back from swapper_space to
3047 * tmpfs file mapping
3049 if (!trylock_page(page)) {
3050 submit_write_bio(bio_ctrl, 0);
3054 if (unlikely(page->mapping != mapping)) {
3059 if (wbc->sync_mode != WB_SYNC_NONE) {
3060 if (PageWriteback(page))
3061 submit_write_bio(bio_ctrl, 0);
3062 wait_on_page_writeback(page);
3065 if (PageWriteback(page) ||
3066 !clear_page_dirty_for_io(page)) {
3071 ret = __extent_writepage(page, wbc, bio_ctrl);
3078 * the filesystem may choose to bump up nr_to_write.
3079 * We have to make sure to honor the new nr_to_write
3082 nr_to_write_done = wbc->nr_to_write <= 0;
3084 pagevec_release(&pvec);
3087 if (!scanned && !done) {
3089 * We hit the last page and there is more work to be done: wrap
3090 * back to the start of the file
3096 * If we're looping we could run into a page that is locked by a
3097 * writer and that writer could be waiting on writeback for a
3098 * page in our current bio, and thus deadlock, so flush the
3101 submit_write_bio(bio_ctrl, 0);
3105 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
3106 mapping->writeback_index = done_index;
3108 btrfs_add_delayed_iput(BTRFS_I(inode));
3113 * Submit the pages in the range to bio for call sites which delalloc range has
3114 * already been ran (aka, ordered extent inserted) and all pages are still
3117 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
3119 bool found_error = false;
3120 int first_error = 0;
3122 struct address_space *mapping = inode->i_mapping;
3125 unsigned long nr_pages;
3126 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
3127 struct btrfs_bio_ctrl bio_ctrl = {
3131 struct writeback_control wbc_writepages = {
3132 .sync_mode = WB_SYNC_ALL,
3133 .range_start = start,
3134 .range_end = end + 1,
3135 /* We're called from an async helper function */
3136 .punt_to_cgroup = 1,
3137 .no_cgroup_owner = 1,
3140 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
3141 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
3143 wbc_writepages.nr_to_write = nr_pages * 2;
3145 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
3146 while (cur <= end) {
3147 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
3149 page = find_get_page(mapping, cur >> PAGE_SHIFT);
3151 * All pages in the range are locked since
3152 * btrfs_run_delalloc_range(), thus there is no way to clear
3153 * the page dirty flag.
3155 ASSERT(PageLocked(page));
3156 ASSERT(PageDirty(page));
3157 clear_page_dirty_for_io(page);
3158 ret = __extent_writepage(page, &wbc_writepages, &bio_ctrl);
3168 submit_write_bio(&bio_ctrl, found_error ? ret : 0);
3170 wbc_detach_inode(&wbc_writepages);
3176 int extent_writepages(struct address_space *mapping,
3177 struct writeback_control *wbc)
3179 struct inode *inode = mapping->host;
3181 struct btrfs_bio_ctrl bio_ctrl = {
3183 .sync_io = (wbc->sync_mode == WB_SYNC_ALL),
3187 * Allow only a single thread to do the reloc work in zoned mode to
3188 * protect the write pointer updates.
3190 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
3191 ret = extent_write_cache_pages(mapping, wbc, &bio_ctrl);
3192 submit_write_bio(&bio_ctrl, ret);
3193 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
3197 void extent_readahead(struct readahead_control *rac)
3199 struct btrfs_bio_ctrl bio_ctrl = { 0 };
3200 struct page *pagepool[16];
3201 struct extent_map *em_cached = NULL;
3202 u64 prev_em_start = (u64)-1;
3205 while ((nr = readahead_page_batch(rac, pagepool))) {
3206 u64 contig_start = readahead_pos(rac);
3207 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
3209 contiguous_readpages(pagepool, nr, contig_start, contig_end,
3210 &em_cached, &bio_ctrl, &prev_em_start);
3214 free_extent_map(em_cached);
3215 submit_one_bio(&bio_ctrl);
3219 * basic invalidate_folio code, this waits on any locked or writeback
3220 * ranges corresponding to the folio, and then deletes any extent state
3221 * records from the tree
3223 int extent_invalidate_folio(struct extent_io_tree *tree,
3224 struct folio *folio, size_t offset)
3226 struct extent_state *cached_state = NULL;
3227 u64 start = folio_pos(folio);
3228 u64 end = start + folio_size(folio) - 1;
3229 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
3231 /* This function is only called for the btree inode */
3232 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
3234 start += ALIGN(offset, blocksize);
3238 lock_extent(tree, start, end, &cached_state);
3239 folio_wait_writeback(folio);
3242 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
3243 * so here we only need to unlock the extent range to free any
3244 * existing extent state.
3246 unlock_extent(tree, start, end, &cached_state);
3251 * a helper for release_folio, this tests for areas of the page that
3252 * are locked or under IO and drops the related state bits if it is safe
3255 static int try_release_extent_state(struct extent_io_tree *tree,
3256 struct page *page, gfp_t mask)
3258 u64 start = page_offset(page);
3259 u64 end = start + PAGE_SIZE - 1;
3262 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
3265 u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
3266 EXTENT_DELALLOC_NEW | EXTENT_CTLBITS);
3269 * At this point we can safely clear everything except the
3270 * locked bit, the nodatasum bit and the delalloc new bit.
3271 * The delalloc new bit will be cleared by ordered extent
3274 ret = __clear_extent_bit(tree, start, end, clear_bits, NULL,
3277 /* if clear_extent_bit failed for enomem reasons,
3278 * we can't allow the release to continue.
3289 * a helper for release_folio. As long as there are no locked extents
3290 * in the range corresponding to the page, both state records and extent
3291 * map records are removed
3293 int try_release_extent_mapping(struct page *page, gfp_t mask)
3295 struct extent_map *em;
3296 u64 start = page_offset(page);
3297 u64 end = start + PAGE_SIZE - 1;
3298 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
3299 struct extent_io_tree *tree = &btrfs_inode->io_tree;
3300 struct extent_map_tree *map = &btrfs_inode->extent_tree;
3302 if (gfpflags_allow_blocking(mask) &&
3303 page->mapping->host->i_size > SZ_16M) {
3305 while (start <= end) {
3306 struct btrfs_fs_info *fs_info;
3309 len = end - start + 1;
3310 write_lock(&map->lock);
3311 em = lookup_extent_mapping(map, start, len);
3313 write_unlock(&map->lock);
3316 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3317 em->start != start) {
3318 write_unlock(&map->lock);
3319 free_extent_map(em);
3322 if (test_range_bit(tree, em->start,
3323 extent_map_end(em) - 1,
3324 EXTENT_LOCKED, 0, NULL))
3327 * If it's not in the list of modified extents, used
3328 * by a fast fsync, we can remove it. If it's being
3329 * logged we can safely remove it since fsync took an
3330 * extra reference on the em.
3332 if (list_empty(&em->list) ||
3333 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
3336 * If it's in the list of modified extents, remove it
3337 * only if its generation is older then the current one,
3338 * in which case we don't need it for a fast fsync.
3339 * Otherwise don't remove it, we could be racing with an
3340 * ongoing fast fsync that could miss the new extent.
3342 fs_info = btrfs_inode->root->fs_info;
3343 spin_lock(&fs_info->trans_lock);
3344 cur_gen = fs_info->generation;
3345 spin_unlock(&fs_info->trans_lock);
3346 if (em->generation >= cur_gen)
3350 * We only remove extent maps that are not in the list of
3351 * modified extents or that are in the list but with a
3352 * generation lower then the current generation, so there
3353 * is no need to set the full fsync flag on the inode (it
3354 * hurts the fsync performance for workloads with a data
3355 * size that exceeds or is close to the system's memory).
3357 remove_extent_mapping(map, em);
3358 /* once for the rb tree */
3359 free_extent_map(em);
3361 start = extent_map_end(em);
3362 write_unlock(&map->lock);
3365 free_extent_map(em);
3367 cond_resched(); /* Allow large-extent preemption. */
3370 return try_release_extent_state(tree, page, mask);
3374 * To cache previous fiemap extent
3376 * Will be used for merging fiemap extent
3378 struct fiemap_cache {
3387 * Helper to submit fiemap extent.
3389 * Will try to merge current fiemap extent specified by @offset, @phys,
3390 * @len and @flags with cached one.
3391 * And only when we fails to merge, cached one will be submitted as
3394 * Return value is the same as fiemap_fill_next_extent().
3396 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
3397 struct fiemap_cache *cache,
3398 u64 offset, u64 phys, u64 len, u32 flags)
3402 /* Set at the end of extent_fiemap(). */
3403 ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
3409 * Sanity check, extent_fiemap() should have ensured that new
3410 * fiemap extent won't overlap with cached one.
3413 * NOTE: Physical address can overlap, due to compression
3415 if (cache->offset + cache->len > offset) {
3421 * Only merges fiemap extents if
3422 * 1) Their logical addresses are continuous
3424 * 2) Their physical addresses are continuous
3425 * So truly compressed (physical size smaller than logical size)
3426 * extents won't get merged with each other
3428 * 3) Share same flags
3430 if (cache->offset + cache->len == offset &&
3431 cache->phys + cache->len == phys &&
3432 cache->flags == flags) {
3437 /* Not mergeable, need to submit cached one */
3438 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3439 cache->len, cache->flags);
3440 cache->cached = false;
3444 cache->cached = true;
3445 cache->offset = offset;
3448 cache->flags = flags;
3454 * Emit last fiemap cache
3456 * The last fiemap cache may still be cached in the following case:
3458 * |<- Fiemap range ->|
3459 * |<------------ First extent ----------->|
3461 * In this case, the first extent range will be cached but not emitted.
3462 * So we must emit it before ending extent_fiemap().
3464 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
3465 struct fiemap_cache *cache)
3472 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3473 cache->len, cache->flags);
3474 cache->cached = false;
3480 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
3482 struct extent_buffer *clone;
3483 struct btrfs_key key;
3488 if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
3491 ret = btrfs_next_leaf(inode->root, path);
3496 * Don't bother with cloning if there are no more file extent items for
3499 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3500 if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
3503 /* See the comment at fiemap_search_slot() about why we clone. */
3504 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3508 slot = path->slots[0];
3509 btrfs_release_path(path);
3510 path->nodes[0] = clone;
3511 path->slots[0] = slot;
3517 * Search for the first file extent item that starts at a given file offset or
3518 * the one that starts immediately before that offset.
3519 * Returns: 0 on success, < 0 on error, 1 if not found.
3521 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
3524 const u64 ino = btrfs_ino(inode);
3525 struct btrfs_root *root = inode->root;
3526 struct extent_buffer *clone;
3527 struct btrfs_key key;
3532 key.type = BTRFS_EXTENT_DATA_KEY;
3533 key.offset = file_offset;
3535 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3539 if (ret > 0 && path->slots[0] > 0) {
3540 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3541 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3545 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3546 ret = btrfs_next_leaf(root, path);
3550 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3551 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3556 * We clone the leaf and use it during fiemap. This is because while
3557 * using the leaf we do expensive things like checking if an extent is
3558 * shared, which can take a long time. In order to prevent blocking
3559 * other tasks for too long, we use a clone of the leaf. We have locked
3560 * the file range in the inode's io tree, so we know none of our file
3561 * extent items can change. This way we avoid blocking other tasks that
3562 * want to insert items for other inodes in the same leaf or b+tree
3563 * rebalance operations (triggered for example when someone is trying
3564 * to push items into this leaf when trying to insert an item in a
3566 * We also need the private clone because holding a read lock on an
3567 * extent buffer of the subvolume's b+tree will make lockdep unhappy
3568 * when we call fiemap_fill_next_extent(), because that may cause a page
3569 * fault when filling the user space buffer with fiemap data.
3571 clone = btrfs_clone_extent_buffer(path->nodes[0]);
3575 slot = path->slots[0];
3576 btrfs_release_path(path);
3577 path->nodes[0] = clone;
3578 path->slots[0] = slot;
3584 * Process a range which is a hole or a prealloc extent in the inode's subvolume
3585 * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
3586 * extent. The end offset (@end) is inclusive.
3588 static int fiemap_process_hole(struct btrfs_inode *inode,
3589 struct fiemap_extent_info *fieinfo,
3590 struct fiemap_cache *cache,
3591 struct extent_state **delalloc_cached_state,
3592 struct btrfs_backref_share_check_ctx *backref_ctx,
3593 u64 disk_bytenr, u64 extent_offset,
3597 const u64 i_size = i_size_read(&inode->vfs_inode);
3598 u64 cur_offset = start;
3599 u64 last_delalloc_end = 0;
3600 u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3601 bool checked_extent_shared = false;
3605 * There can be no delalloc past i_size, so don't waste time looking for
3608 while (cur_offset < end && cur_offset < i_size) {
3612 u64 prealloc_len = 0;
3615 delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3616 delalloc_cached_state,
3623 * If this is a prealloc extent we have to report every section
3624 * of it that has no delalloc.
3626 if (disk_bytenr != 0) {
3627 if (last_delalloc_end == 0) {
3628 prealloc_start = start;
3629 prealloc_len = delalloc_start - start;
3631 prealloc_start = last_delalloc_end + 1;
3632 prealloc_len = delalloc_start - prealloc_start;
3636 if (prealloc_len > 0) {
3637 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3638 ret = btrfs_is_data_extent_shared(inode,
3645 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3647 checked_extent_shared = true;
3649 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3650 disk_bytenr + extent_offset,
3651 prealloc_len, prealloc_flags);
3654 extent_offset += prealloc_len;
3657 ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3658 delalloc_end + 1 - delalloc_start,
3659 FIEMAP_EXTENT_DELALLOC |
3660 FIEMAP_EXTENT_UNKNOWN);
3664 last_delalloc_end = delalloc_end;
3665 cur_offset = delalloc_end + 1;
3666 extent_offset += cur_offset - delalloc_start;
3671 * Either we found no delalloc for the whole prealloc extent or we have
3672 * a prealloc extent that spans i_size or starts at or after i_size.
3674 if (disk_bytenr != 0 && last_delalloc_end < end) {
3678 if (last_delalloc_end == 0) {
3679 prealloc_start = start;
3680 prealloc_len = end + 1 - start;
3682 prealloc_start = last_delalloc_end + 1;
3683 prealloc_len = end + 1 - prealloc_start;
3686 if (!checked_extent_shared && fieinfo->fi_extents_max) {
3687 ret = btrfs_is_data_extent_shared(inode,
3694 prealloc_flags |= FIEMAP_EXTENT_SHARED;
3696 ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3697 disk_bytenr + extent_offset,
3698 prealloc_len, prealloc_flags);
3706 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3707 struct btrfs_path *path,
3708 u64 *last_extent_end_ret)
3710 const u64 ino = btrfs_ino(inode);
3711 struct btrfs_root *root = inode->root;
3712 struct extent_buffer *leaf;
3713 struct btrfs_file_extent_item *ei;
3714 struct btrfs_key key;
3719 * Lookup the last file extent. We're not using i_size here because
3720 * there might be preallocation past i_size.
3722 ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3723 /* There can't be a file extent item at offset (u64)-1 */
3729 * For a non-existing key, btrfs_search_slot() always leaves us at a
3730 * slot > 0, except if the btree is empty, which is impossible because
3731 * at least it has the inode item for this inode and all the items for
3732 * the root inode 256.
3734 ASSERT(path->slots[0] > 0);
3736 leaf = path->nodes[0];
3737 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3738 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3739 /* No file extent items in the subvolume tree. */
3740 *last_extent_end_ret = 0;
3745 * For an inline extent, the disk_bytenr is where inline data starts at,
3746 * so first check if we have an inline extent item before checking if we
3747 * have an implicit hole (disk_bytenr == 0).
3749 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3750 if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3751 *last_extent_end_ret = btrfs_file_extent_end(path);
3756 * Find the last file extent item that is not a hole (when NO_HOLES is
3757 * not enabled). This should take at most 2 iterations in the worst
3758 * case: we have one hole file extent item at slot 0 of a leaf and
3759 * another hole file extent item as the last item in the previous leaf.
3760 * This is because we merge file extent items that represent holes.
3762 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3763 while (disk_bytenr == 0) {
3764 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3767 } else if (ret > 0) {
3768 /* No file extent items that are not holes. */
3769 *last_extent_end_ret = 0;
3772 leaf = path->nodes[0];
3773 ei = btrfs_item_ptr(leaf, path->slots[0],
3774 struct btrfs_file_extent_item);
3775 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3778 *last_extent_end_ret = btrfs_file_extent_end(path);
3782 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3785 const u64 ino = btrfs_ino(inode);
3786 struct extent_state *cached_state = NULL;
3787 struct extent_state *delalloc_cached_state = NULL;
3788 struct btrfs_path *path;
3789 struct fiemap_cache cache = { 0 };
3790 struct btrfs_backref_share_check_ctx *backref_ctx;
3791 u64 last_extent_end;
3792 u64 prev_extent_end;
3795 bool stopped = false;
3798 backref_ctx = btrfs_alloc_backref_share_check_ctx();
3799 path = btrfs_alloc_path();
3800 if (!backref_ctx || !path) {
3805 lockstart = round_down(start, inode->root->fs_info->sectorsize);
3806 lockend = round_up(start + len, inode->root->fs_info->sectorsize);
3807 prev_extent_end = lockstart;
3809 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3811 ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3814 btrfs_release_path(path);
3816 path->reada = READA_FORWARD;
3817 ret = fiemap_search_slot(inode, path, lockstart);
3820 } else if (ret > 0) {
3822 * No file extent item found, but we may have delalloc between
3823 * the current offset and i_size. So check for that.
3826 goto check_eof_delalloc;
3829 while (prev_extent_end < lockend) {
3830 struct extent_buffer *leaf = path->nodes[0];
3831 struct btrfs_file_extent_item *ei;
3832 struct btrfs_key key;
3835 u64 extent_offset = 0;
3837 u64 disk_bytenr = 0;
3842 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3843 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3846 extent_end = btrfs_file_extent_end(path);
3849 * The first iteration can leave us at an extent item that ends
3850 * before our range's start. Move to the next item.
3852 if (extent_end <= lockstart)
3855 backref_ctx->curr_leaf_bytenr = leaf->start;
3857 /* We have in implicit hole (NO_HOLES feature enabled). */
3858 if (prev_extent_end < key.offset) {
3859 const u64 range_end = min(key.offset, lockend) - 1;
3861 ret = fiemap_process_hole(inode, fieinfo, &cache,
3862 &delalloc_cached_state,
3863 backref_ctx, 0, 0, 0,
3864 prev_extent_end, range_end);
3867 } else if (ret > 0) {
3868 /* fiemap_fill_next_extent() told us to stop. */
3873 /* We've reached the end of the fiemap range, stop. */
3874 if (key.offset >= lockend) {
3880 extent_len = extent_end - key.offset;
3881 ei = btrfs_item_ptr(leaf, path->slots[0],
3882 struct btrfs_file_extent_item);
3883 compression = btrfs_file_extent_compression(leaf, ei);
3884 extent_type = btrfs_file_extent_type(leaf, ei);
3885 extent_gen = btrfs_file_extent_generation(leaf, ei);
3887 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3888 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3889 if (compression == BTRFS_COMPRESS_NONE)
3890 extent_offset = btrfs_file_extent_offset(leaf, ei);
3893 if (compression != BTRFS_COMPRESS_NONE)
3894 flags |= FIEMAP_EXTENT_ENCODED;
3896 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3897 flags |= FIEMAP_EXTENT_DATA_INLINE;
3898 flags |= FIEMAP_EXTENT_NOT_ALIGNED;
3899 ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
3901 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
3902 ret = fiemap_process_hole(inode, fieinfo, &cache,
3903 &delalloc_cached_state,
3905 disk_bytenr, extent_offset,
3906 extent_gen, key.offset,
3908 } else if (disk_bytenr == 0) {
3909 /* We have an explicit hole. */
3910 ret = fiemap_process_hole(inode, fieinfo, &cache,
3911 &delalloc_cached_state,
3912 backref_ctx, 0, 0, 0,
3913 key.offset, extent_end - 1);
3915 /* We have a regular extent. */
3916 if (fieinfo->fi_extents_max) {
3917 ret = btrfs_is_data_extent_shared(inode,
3924 flags |= FIEMAP_EXTENT_SHARED;
3927 ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
3928 disk_bytenr + extent_offset,
3934 } else if (ret > 0) {
3935 /* fiemap_fill_next_extent() told us to stop. */
3940 prev_extent_end = extent_end;
3942 if (fatal_signal_pending(current)) {
3947 ret = fiemap_next_leaf_item(inode, path);
3950 } else if (ret > 0) {
3951 /* No more file extent items for this inode. */
3959 * Release (and free) the path before emitting any final entries to
3960 * fiemap_fill_next_extent() to keep lockdep happy. This is because
3961 * once we find no more file extent items exist, we may have a
3962 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
3963 * faults when copying data to the user space buffer.
3965 btrfs_free_path(path);
3968 if (!stopped && prev_extent_end < lockend) {
3969 ret = fiemap_process_hole(inode, fieinfo, &cache,
3970 &delalloc_cached_state, backref_ctx,
3971 0, 0, 0, prev_extent_end, lockend - 1);
3974 prev_extent_end = lockend;
3977 if (cache.cached && cache.offset + cache.len >= last_extent_end) {
3978 const u64 i_size = i_size_read(&inode->vfs_inode);
3980 if (prev_extent_end < i_size) {
3985 delalloc = btrfs_find_delalloc_in_range(inode,
3988 &delalloc_cached_state,
3992 cache.flags |= FIEMAP_EXTENT_LAST;
3994 cache.flags |= FIEMAP_EXTENT_LAST;
3998 ret = emit_last_fiemap_cache(fieinfo, &cache);
4001 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
4003 free_extent_state(delalloc_cached_state);
4004 btrfs_free_backref_share_ctx(backref_ctx);
4005 btrfs_free_path(path);
4009 static void __free_extent_buffer(struct extent_buffer *eb)
4011 kmem_cache_free(extent_buffer_cache, eb);
4014 int extent_buffer_under_io(const struct extent_buffer *eb)
4016 return (atomic_read(&eb->io_pages) ||
4017 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4018 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4021 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
4023 struct btrfs_subpage *subpage;
4025 lockdep_assert_held(&page->mapping->private_lock);
4027 if (PagePrivate(page)) {
4028 subpage = (struct btrfs_subpage *)page->private;
4029 if (atomic_read(&subpage->eb_refs))
4032 * Even there is no eb refs here, we may still have
4033 * end_page_read() call relying on page::private.
4035 if (atomic_read(&subpage->readers))
4041 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
4043 struct btrfs_fs_info *fs_info = eb->fs_info;
4044 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4047 * For mapped eb, we're going to change the page private, which should
4048 * be done under the private_lock.
4051 spin_lock(&page->mapping->private_lock);
4053 if (!PagePrivate(page)) {
4055 spin_unlock(&page->mapping->private_lock);
4059 if (fs_info->nodesize >= PAGE_SIZE) {
4061 * We do this since we'll remove the pages after we've
4062 * removed the eb from the radix tree, so we could race
4063 * and have this page now attached to the new eb. So
4064 * only clear page_private if it's still connected to
4067 if (PagePrivate(page) &&
4068 page->private == (unsigned long)eb) {
4069 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4070 BUG_ON(PageDirty(page));
4071 BUG_ON(PageWriteback(page));
4073 * We need to make sure we haven't be attached
4076 detach_page_private(page);
4079 spin_unlock(&page->mapping->private_lock);
4084 * For subpage, we can have dummy eb with page private. In this case,
4085 * we can directly detach the private as such page is only attached to
4086 * one dummy eb, no sharing.
4089 btrfs_detach_subpage(fs_info, page);
4093 btrfs_page_dec_eb_refs(fs_info, page);
4096 * We can only detach the page private if there are no other ebs in the
4097 * page range and no unfinished IO.
4099 if (!page_range_has_eb(fs_info, page))
4100 btrfs_detach_subpage(fs_info, page);
4102 spin_unlock(&page->mapping->private_lock);
4105 /* Release all pages attached to the extent buffer */
4106 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4111 ASSERT(!extent_buffer_under_io(eb));
4113 num_pages = num_extent_pages(eb);
4114 for (i = 0; i < num_pages; i++) {
4115 struct page *page = eb->pages[i];
4120 detach_extent_buffer_page(eb, page);
4122 /* One for when we allocated the page */
4128 * Helper for releasing the extent buffer.
4130 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4132 btrfs_release_extent_buffer_pages(eb);
4133 btrfs_leak_debug_del_eb(eb);
4134 __free_extent_buffer(eb);
4137 static struct extent_buffer *
4138 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4141 struct extent_buffer *eb = NULL;
4143 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4146 eb->fs_info = fs_info;
4147 init_rwsem(&eb->lock);
4149 btrfs_leak_debug_add_eb(eb);
4150 INIT_LIST_HEAD(&eb->release_list);
4152 spin_lock_init(&eb->refs_lock);
4153 atomic_set(&eb->refs, 1);
4154 atomic_set(&eb->io_pages, 0);
4156 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
4161 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
4164 struct extent_buffer *new;
4165 int num_pages = num_extent_pages(src);
4168 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4173 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
4174 * btrfs_release_extent_buffer() have different behavior for
4175 * UNMAPPED subpage extent buffer.
4177 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4179 ret = btrfs_alloc_page_array(num_pages, new->pages);
4181 btrfs_release_extent_buffer(new);
4185 for (i = 0; i < num_pages; i++) {
4187 struct page *p = new->pages[i];
4189 ret = attach_extent_buffer_page(new, p, NULL);
4191 btrfs_release_extent_buffer(new);
4194 WARN_ON(PageDirty(p));
4195 copy_page(page_address(p), page_address(src->pages[i]));
4197 set_extent_buffer_uptodate(new);
4202 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4203 u64 start, unsigned long len)
4205 struct extent_buffer *eb;
4210 eb = __alloc_extent_buffer(fs_info, start, len);
4214 num_pages = num_extent_pages(eb);
4215 ret = btrfs_alloc_page_array(num_pages, eb->pages);
4219 for (i = 0; i < num_pages; i++) {
4220 struct page *p = eb->pages[i];
4222 ret = attach_extent_buffer_page(eb, p, NULL);
4227 set_extent_buffer_uptodate(eb);
4228 btrfs_set_header_nritems(eb, 0);
4229 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4233 for (i = 0; i < num_pages; i++) {
4235 detach_extent_buffer_page(eb, eb->pages[i]);
4236 __free_page(eb->pages[i]);
4239 __free_extent_buffer(eb);
4243 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4246 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4249 static void check_buffer_tree_ref(struct extent_buffer *eb)
4253 * The TREE_REF bit is first set when the extent_buffer is added
4254 * to the radix tree. It is also reset, if unset, when a new reference
4255 * is created by find_extent_buffer.
4257 * It is only cleared in two cases: freeing the last non-tree
4258 * reference to the extent_buffer when its STALE bit is set or
4259 * calling release_folio when the tree reference is the only reference.
4261 * In both cases, care is taken to ensure that the extent_buffer's
4262 * pages are not under io. However, release_folio can be concurrently
4263 * called with creating new references, which is prone to race
4264 * conditions between the calls to check_buffer_tree_ref in those
4265 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4267 * The actual lifetime of the extent_buffer in the radix tree is
4268 * adequately protected by the refcount, but the TREE_REF bit and
4269 * its corresponding reference are not. To protect against this
4270 * class of races, we call check_buffer_tree_ref from the codepaths
4271 * which trigger io after they set eb->io_pages. Note that once io is
4272 * initiated, TREE_REF can no longer be cleared, so that is the
4273 * moment at which any such race is best fixed.
4275 refs = atomic_read(&eb->refs);
4276 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4279 spin_lock(&eb->refs_lock);
4280 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4281 atomic_inc(&eb->refs);
4282 spin_unlock(&eb->refs_lock);
4285 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4286 struct page *accessed)
4290 check_buffer_tree_ref(eb);
4292 num_pages = num_extent_pages(eb);
4293 for (i = 0; i < num_pages; i++) {
4294 struct page *p = eb->pages[i];
4297 mark_page_accessed(p);
4301 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4304 struct extent_buffer *eb;
4306 eb = find_extent_buffer_nolock(fs_info, start);
4310 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
4311 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
4312 * another task running free_extent_buffer() might have seen that flag
4313 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
4314 * writeback flags not set) and it's still in the tree (flag
4315 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
4316 * decrementing the extent buffer's reference count twice. So here we
4317 * could race and increment the eb's reference count, clear its stale
4318 * flag, mark it as dirty and drop our reference before the other task
4319 * finishes executing free_extent_buffer, which would later result in
4320 * an attempt to free an extent buffer that is dirty.
4322 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4323 spin_lock(&eb->refs_lock);
4324 spin_unlock(&eb->refs_lock);
4326 mark_extent_buffer_accessed(eb, NULL);
4330 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4331 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
4334 struct extent_buffer *eb, *exists = NULL;
4337 eb = find_extent_buffer(fs_info, start);
4340 eb = alloc_dummy_extent_buffer(fs_info, start);
4342 return ERR_PTR(-ENOMEM);
4343 eb->fs_info = fs_info;
4345 ret = radix_tree_preload(GFP_NOFS);
4347 exists = ERR_PTR(ret);
4350 spin_lock(&fs_info->buffer_lock);
4351 ret = radix_tree_insert(&fs_info->buffer_radix,
4352 start >> fs_info->sectorsize_bits, eb);
4353 spin_unlock(&fs_info->buffer_lock);
4354 radix_tree_preload_end();
4355 if (ret == -EEXIST) {
4356 exists = find_extent_buffer(fs_info, start);
4362 check_buffer_tree_ref(eb);
4363 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4367 btrfs_release_extent_buffer(eb);
4372 static struct extent_buffer *grab_extent_buffer(
4373 struct btrfs_fs_info *fs_info, struct page *page)
4375 struct extent_buffer *exists;
4378 * For subpage case, we completely rely on radix tree to ensure we
4379 * don't try to insert two ebs for the same bytenr. So here we always
4380 * return NULL and just continue.
4382 if (fs_info->nodesize < PAGE_SIZE)
4385 /* Page not yet attached to an extent buffer */
4386 if (!PagePrivate(page))
4390 * We could have already allocated an eb for this page and attached one
4391 * so lets see if we can get a ref on the existing eb, and if we can we
4392 * know it's good and we can just return that one, else we know we can
4393 * just overwrite page->private.
4395 exists = (struct extent_buffer *)page->private;
4396 if (atomic_inc_not_zero(&exists->refs))
4399 WARN_ON(PageDirty(page));
4400 detach_page_private(page);
4404 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
4406 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
4407 btrfs_err(fs_info, "bad tree block start %llu", start);
4411 if (fs_info->nodesize < PAGE_SIZE &&
4412 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
4414 "tree block crosses page boundary, start %llu nodesize %u",
4415 start, fs_info->nodesize);
4418 if (fs_info->nodesize >= PAGE_SIZE &&
4419 !PAGE_ALIGNED(start)) {
4421 "tree block is not page aligned, start %llu nodesize %u",
4422 start, fs_info->nodesize);
4428 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
4429 u64 start, u64 owner_root, int level)
4431 unsigned long len = fs_info->nodesize;
4434 unsigned long index = start >> PAGE_SHIFT;
4435 struct extent_buffer *eb;
4436 struct extent_buffer *exists = NULL;
4438 struct address_space *mapping = fs_info->btree_inode->i_mapping;
4439 u64 lockdep_owner = owner_root;
4443 if (check_eb_alignment(fs_info, start))
4444 return ERR_PTR(-EINVAL);
4446 #if BITS_PER_LONG == 32
4447 if (start >= MAX_LFS_FILESIZE) {
4448 btrfs_err_rl(fs_info,
4449 "extent buffer %llu is beyond 32bit page cache limit", start);
4450 btrfs_err_32bit_limit(fs_info);
4451 return ERR_PTR(-EOVERFLOW);
4453 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
4454 btrfs_warn_32bit_limit(fs_info);
4457 eb = find_extent_buffer(fs_info, start);
4461 eb = __alloc_extent_buffer(fs_info, start, len);
4463 return ERR_PTR(-ENOMEM);
4466 * The reloc trees are just snapshots, so we need them to appear to be
4467 * just like any other fs tree WRT lockdep.
4469 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
4470 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4472 btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
4474 num_pages = num_extent_pages(eb);
4475 for (i = 0; i < num_pages; i++, index++) {
4476 struct btrfs_subpage *prealloc = NULL;
4478 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
4480 exists = ERR_PTR(-ENOMEM);
4485 * Preallocate page->private for subpage case, so that we won't
4486 * allocate memory with private_lock hold. The memory will be
4487 * freed by attach_extent_buffer_page() or freed manually if
4490 * Although we have ensured one subpage eb can only have one
4491 * page, but it may change in the future for 16K page size
4492 * support, so we still preallocate the memory in the loop.
4494 if (fs_info->nodesize < PAGE_SIZE) {
4495 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
4496 if (IS_ERR(prealloc)) {
4497 ret = PTR_ERR(prealloc);
4500 exists = ERR_PTR(ret);
4505 spin_lock(&mapping->private_lock);
4506 exists = grab_extent_buffer(fs_info, p);
4508 spin_unlock(&mapping->private_lock);
4511 mark_extent_buffer_accessed(exists, p);
4512 btrfs_free_subpage(prealloc);
4515 /* Should not fail, as we have preallocated the memory */
4516 ret = attach_extent_buffer_page(eb, p, prealloc);
4519 * To inform we have extra eb under allocation, so that
4520 * detach_extent_buffer_page() won't release the page private
4521 * when the eb hasn't yet been inserted into radix tree.
4523 * The ref will be decreased when the eb released the page, in
4524 * detach_extent_buffer_page().
4525 * Thus needs no special handling in error path.
4527 btrfs_page_inc_eb_refs(fs_info, p);
4528 spin_unlock(&mapping->private_lock);
4530 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
4532 if (!PageUptodate(p))
4536 * We can't unlock the pages just yet since the extent buffer
4537 * hasn't been properly inserted in the radix tree, this
4538 * opens a race with btree_release_folio which can free a page
4539 * while we are still filling in all pages for the buffer and
4544 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4546 ret = radix_tree_preload(GFP_NOFS);
4548 exists = ERR_PTR(ret);
4552 spin_lock(&fs_info->buffer_lock);
4553 ret = radix_tree_insert(&fs_info->buffer_radix,
4554 start >> fs_info->sectorsize_bits, eb);
4555 spin_unlock(&fs_info->buffer_lock);
4556 radix_tree_preload_end();
4557 if (ret == -EEXIST) {
4558 exists = find_extent_buffer(fs_info, start);
4564 /* add one reference for the tree */
4565 check_buffer_tree_ref(eb);
4566 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4569 * Now it's safe to unlock the pages because any calls to
4570 * btree_release_folio will correctly detect that a page belongs to a
4571 * live buffer and won't free them prematurely.
4573 for (i = 0; i < num_pages; i++)
4574 unlock_page(eb->pages[i]);
4578 WARN_ON(!atomic_dec_and_test(&eb->refs));
4579 for (i = 0; i < num_pages; i++) {
4581 unlock_page(eb->pages[i]);
4584 btrfs_release_extent_buffer(eb);
4588 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4590 struct extent_buffer *eb =
4591 container_of(head, struct extent_buffer, rcu_head);
4593 __free_extent_buffer(eb);
4596 static int release_extent_buffer(struct extent_buffer *eb)
4597 __releases(&eb->refs_lock)
4599 lockdep_assert_held(&eb->refs_lock);
4601 WARN_ON(atomic_read(&eb->refs) == 0);
4602 if (atomic_dec_and_test(&eb->refs)) {
4603 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4604 struct btrfs_fs_info *fs_info = eb->fs_info;
4606 spin_unlock(&eb->refs_lock);
4608 spin_lock(&fs_info->buffer_lock);
4609 radix_tree_delete(&fs_info->buffer_radix,
4610 eb->start >> fs_info->sectorsize_bits);
4611 spin_unlock(&fs_info->buffer_lock);
4613 spin_unlock(&eb->refs_lock);
4616 btrfs_leak_debug_del_eb(eb);
4617 /* Should be safe to release our pages at this point */
4618 btrfs_release_extent_buffer_pages(eb);
4619 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4620 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4621 __free_extent_buffer(eb);
4625 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4628 spin_unlock(&eb->refs_lock);
4633 void free_extent_buffer(struct extent_buffer *eb)
4639 refs = atomic_read(&eb->refs);
4641 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4642 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4645 if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4649 spin_lock(&eb->refs_lock);
4650 if (atomic_read(&eb->refs) == 2 &&
4651 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4652 !extent_buffer_under_io(eb) &&
4653 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4654 atomic_dec(&eb->refs);
4657 * I know this is terrible, but it's temporary until we stop tracking
4658 * the uptodate bits and such for the extent buffers.
4660 release_extent_buffer(eb);
4663 void free_extent_buffer_stale(struct extent_buffer *eb)
4668 spin_lock(&eb->refs_lock);
4669 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4671 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4672 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4673 atomic_dec(&eb->refs);
4674 release_extent_buffer(eb);
4677 static void btree_clear_page_dirty(struct page *page)
4679 ASSERT(PageDirty(page));
4680 ASSERT(PageLocked(page));
4681 clear_page_dirty_for_io(page);
4682 xa_lock_irq(&page->mapping->i_pages);
4683 if (!PageDirty(page))
4684 __xa_clear_mark(&page->mapping->i_pages,
4685 page_index(page), PAGECACHE_TAG_DIRTY);
4686 xa_unlock_irq(&page->mapping->i_pages);
4689 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4691 struct btrfs_fs_info *fs_info = eb->fs_info;
4692 struct page *page = eb->pages[0];
4695 /* btree_clear_page_dirty() needs page locked */
4697 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4700 btree_clear_page_dirty(page);
4702 WARN_ON(atomic_read(&eb->refs) == 0);
4705 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
4711 if (eb->fs_info->nodesize < PAGE_SIZE)
4712 return clear_subpage_extent_buffer_dirty(eb);
4714 num_pages = num_extent_pages(eb);
4716 for (i = 0; i < num_pages; i++) {
4717 page = eb->pages[i];
4718 if (!PageDirty(page))
4721 btree_clear_page_dirty(page);
4722 ClearPageError(page);
4725 WARN_ON(atomic_read(&eb->refs) == 0);
4728 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4734 check_buffer_tree_ref(eb);
4736 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4738 num_pages = num_extent_pages(eb);
4739 WARN_ON(atomic_read(&eb->refs) == 0);
4740 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4743 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4746 * For subpage case, we can have other extent buffers in the
4747 * same page, and in clear_subpage_extent_buffer_dirty() we
4748 * have to clear page dirty without subpage lock held.
4749 * This can cause race where our page gets dirty cleared after
4752 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4753 * its page for other reasons, we can use page lock to prevent
4757 lock_page(eb->pages[0]);
4758 for (i = 0; i < num_pages; i++)
4759 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4760 eb->start, eb->len);
4762 unlock_page(eb->pages[0]);
4764 #ifdef CONFIG_BTRFS_DEBUG
4765 for (i = 0; i < num_pages; i++)
4766 ASSERT(PageDirty(eb->pages[i]));
4772 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4774 struct btrfs_fs_info *fs_info = eb->fs_info;
4779 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4780 num_pages = num_extent_pages(eb);
4781 for (i = 0; i < num_pages; i++) {
4782 page = eb->pages[i];
4787 * This is special handling for metadata subpage, as regular
4788 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4790 if (fs_info->nodesize >= PAGE_SIZE)
4791 ClearPageUptodate(page);
4793 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4798 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4800 struct btrfs_fs_info *fs_info = eb->fs_info;
4805 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4806 num_pages = num_extent_pages(eb);
4807 for (i = 0; i < num_pages; i++) {
4808 page = eb->pages[i];
4811 * This is special handling for metadata subpage, as regular
4812 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4814 if (fs_info->nodesize >= PAGE_SIZE)
4815 SetPageUptodate(page);
4817 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4822 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4824 struct btrfs_tree_parent_check *check)
4826 struct btrfs_fs_info *fs_info = eb->fs_info;
4827 struct extent_io_tree *io_tree;
4828 struct page *page = eb->pages[0];
4829 struct extent_state *cached_state = NULL;
4830 struct btrfs_bio_ctrl bio_ctrl = {
4831 .mirror_num = mirror_num,
4835 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4836 ASSERT(PagePrivate(page));
4838 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4840 if (wait == WAIT_NONE) {
4841 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4845 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4852 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4853 PageUptodate(page) ||
4854 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4855 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4856 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
4861 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4862 eb->read_mirror = 0;
4863 atomic_set(&eb->io_pages, 1);
4864 check_buffer_tree_ref(eb);
4865 bio_ctrl.end_io_func = end_bio_extent_readpage;
4867 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
4869 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
4870 ret = submit_extent_page(REQ_OP_READ, NULL, &bio_ctrl,
4871 eb->start, page, eb->len,
4872 eb->start - page_offset(page), 0, true);
4875 * In the endio function, if we hit something wrong we will
4876 * increase the io_pages, so here we need to decrease it for
4879 atomic_dec(&eb->io_pages);
4881 memcpy(&btrfs_bio(bio_ctrl.bio)->parent_check, check, sizeof(*check));
4882 submit_one_bio(&bio_ctrl);
4883 if (ret || wait != WAIT_COMPLETE) {
4884 free_extent_state(cached_state);
4888 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1,
4889 EXTENT_LOCKED, &cached_state);
4890 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4895 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
4896 struct btrfs_tree_parent_check *check)
4902 int locked_pages = 0;
4903 int all_uptodate = 1;
4905 unsigned long num_reads = 0;
4906 struct btrfs_bio_ctrl bio_ctrl = {
4907 .mirror_num = mirror_num,
4910 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4914 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
4915 * operation, which could potentially still be in flight. In this case
4916 * we simply want to return an error.
4918 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
4921 if (eb->fs_info->nodesize < PAGE_SIZE)
4922 return read_extent_buffer_subpage(eb, wait, mirror_num, check);
4924 num_pages = num_extent_pages(eb);
4925 for (i = 0; i < num_pages; i++) {
4926 page = eb->pages[i];
4927 if (wait == WAIT_NONE) {
4929 * WAIT_NONE is only utilized by readahead. If we can't
4930 * acquire the lock atomically it means either the eb
4931 * is being read out or under modification.
4932 * Either way the eb will be or has been cached,
4933 * readahead can exit safely.
4935 if (!trylock_page(page))
4943 * We need to firstly lock all pages to make sure that
4944 * the uptodate bit of our pages won't be affected by
4945 * clear_extent_buffer_uptodate().
4947 for (i = 0; i < num_pages; i++) {
4948 page = eb->pages[i];
4949 if (!PageUptodate(page)) {
4956 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4960 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
4961 eb->read_mirror = 0;
4962 atomic_set(&eb->io_pages, num_reads);
4964 * It is possible for release_folio to clear the TREE_REF bit before we
4965 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
4967 check_buffer_tree_ref(eb);
4968 bio_ctrl.end_io_func = end_bio_extent_readpage;
4969 for (i = 0; i < num_pages; i++) {
4970 page = eb->pages[i];
4972 if (!PageUptodate(page)) {
4974 atomic_dec(&eb->io_pages);
4979 ClearPageError(page);
4980 err = submit_extent_page(REQ_OP_READ, NULL,
4981 &bio_ctrl, page_offset(page), page,
4982 PAGE_SIZE, 0, 0, false);
4985 * We failed to submit the bio so it's the
4986 * caller's responsibility to perform cleanup
4987 * i.e unlock page/set error bit.
4992 atomic_dec(&eb->io_pages);
4999 memcpy(&btrfs_bio(bio_ctrl.bio)->parent_check, check, sizeof(*check));
5000 submit_one_bio(&bio_ctrl);
5002 if (ret || wait != WAIT_COMPLETE)
5005 for (i = 0; i < num_pages; i++) {
5006 page = eb->pages[i];
5007 wait_on_page_locked(page);
5008 if (!PageUptodate(page))
5015 while (locked_pages > 0) {
5017 page = eb->pages[locked_pages];
5023 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5026 btrfs_warn(eb->fs_info,
5027 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
5028 eb->start, eb->len, start, len);
5029 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5035 * Check if the [start, start + len) range is valid before reading/writing
5037 * NOTE: @start and @len are offset inside the eb, not logical address.
5039 * Caller should not touch the dst/src memory if this function returns error.
5041 static inline int check_eb_range(const struct extent_buffer *eb,
5042 unsigned long start, unsigned long len)
5044 unsigned long offset;
5046 /* start, start + len should not go beyond eb->len nor overflow */
5047 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5048 return report_eb_range(eb, start, len);
5053 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5054 unsigned long start, unsigned long len)
5060 char *dst = (char *)dstv;
5061 unsigned long i = get_eb_page_index(start);
5063 if (check_eb_range(eb, start, len))
5066 offset = get_eb_offset_in_page(eb, start);
5069 page = eb->pages[i];
5071 cur = min(len, (PAGE_SIZE - offset));
5072 kaddr = page_address(page);
5073 memcpy(dst, kaddr + offset, cur);
5082 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5084 unsigned long start, unsigned long len)
5090 char __user *dst = (char __user *)dstv;
5091 unsigned long i = get_eb_page_index(start);
5094 WARN_ON(start > eb->len);
5095 WARN_ON(start + len > eb->start + eb->len);
5097 offset = get_eb_offset_in_page(eb, start);
5100 page = eb->pages[i];
5102 cur = min(len, (PAGE_SIZE - offset));
5103 kaddr = page_address(page);
5104 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
5118 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5119 unsigned long start, unsigned long len)
5125 char *ptr = (char *)ptrv;
5126 unsigned long i = get_eb_page_index(start);
5129 if (check_eb_range(eb, start, len))
5132 offset = get_eb_offset_in_page(eb, start);
5135 page = eb->pages[i];
5137 cur = min(len, (PAGE_SIZE - offset));
5139 kaddr = page_address(page);
5140 ret = memcmp(ptr, kaddr + offset, cur);
5153 * Check that the extent buffer is uptodate.
5155 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
5156 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
5158 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
5161 struct btrfs_fs_info *fs_info = eb->fs_info;
5164 * If we are using the commit root we could potentially clear a page
5165 * Uptodate while we're using the extent buffer that we've previously
5166 * looked up. We don't want to complain in this case, as the page was
5167 * valid before, we just didn't write it out. Instead we want to catch
5168 * the case where we didn't actually read the block properly, which
5169 * would have !PageUptodate && !PageError, as we clear PageError before
5172 if (fs_info->nodesize < PAGE_SIZE) {
5173 bool uptodate, error;
5175 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
5176 eb->start, eb->len);
5177 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
5178 WARN_ON(!uptodate && !error);
5180 WARN_ON(!PageUptodate(page) && !PageError(page));
5184 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
5189 assert_eb_page_uptodate(eb, eb->pages[0]);
5190 kaddr = page_address(eb->pages[0]) +
5191 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
5193 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5196 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
5200 assert_eb_page_uptodate(eb, eb->pages[0]);
5201 kaddr = page_address(eb->pages[0]) +
5202 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
5203 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5206 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
5207 unsigned long start, unsigned long len)
5213 char *src = (char *)srcv;
5214 unsigned long i = get_eb_page_index(start);
5216 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
5218 if (check_eb_range(eb, start, len))
5221 offset = get_eb_offset_in_page(eb, start);
5224 page = eb->pages[i];
5225 assert_eb_page_uptodate(eb, page);
5227 cur = min(len, PAGE_SIZE - offset);
5228 kaddr = page_address(page);
5229 memcpy(kaddr + offset, src, cur);
5238 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
5245 unsigned long i = get_eb_page_index(start);
5247 if (check_eb_range(eb, start, len))
5250 offset = get_eb_offset_in_page(eb, start);
5253 page = eb->pages[i];
5254 assert_eb_page_uptodate(eb, page);
5256 cur = min(len, PAGE_SIZE - offset);
5257 kaddr = page_address(page);
5258 memset(kaddr + offset, 0, cur);
5266 void copy_extent_buffer_full(const struct extent_buffer *dst,
5267 const struct extent_buffer *src)
5272 ASSERT(dst->len == src->len);
5274 if (dst->fs_info->nodesize >= PAGE_SIZE) {
5275 num_pages = num_extent_pages(dst);
5276 for (i = 0; i < num_pages; i++)
5277 copy_page(page_address(dst->pages[i]),
5278 page_address(src->pages[i]));
5280 size_t src_offset = get_eb_offset_in_page(src, 0);
5281 size_t dst_offset = get_eb_offset_in_page(dst, 0);
5283 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
5284 memcpy(page_address(dst->pages[0]) + dst_offset,
5285 page_address(src->pages[0]) + src_offset,
5290 void copy_extent_buffer(const struct extent_buffer *dst,
5291 const struct extent_buffer *src,
5292 unsigned long dst_offset, unsigned long src_offset,
5295 u64 dst_len = dst->len;
5300 unsigned long i = get_eb_page_index(dst_offset);
5302 if (check_eb_range(dst, dst_offset, len) ||
5303 check_eb_range(src, src_offset, len))
5306 WARN_ON(src->len != dst_len);
5308 offset = get_eb_offset_in_page(dst, dst_offset);
5311 page = dst->pages[i];
5312 assert_eb_page_uptodate(dst, page);
5314 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5316 kaddr = page_address(page);
5317 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5327 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5329 * @eb: the extent buffer
5330 * @start: offset of the bitmap item in the extent buffer
5332 * @page_index: return index of the page in the extent buffer that contains the
5334 * @page_offset: return offset into the page given by page_index
5336 * This helper hides the ugliness of finding the byte in an extent buffer which
5337 * contains a given bit.
5339 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
5340 unsigned long start, unsigned long nr,
5341 unsigned long *page_index,
5342 size_t *page_offset)
5344 size_t byte_offset = BIT_BYTE(nr);
5348 * The byte we want is the offset of the extent buffer + the offset of
5349 * the bitmap item in the extent buffer + the offset of the byte in the
5352 offset = start + offset_in_page(eb->start) + byte_offset;
5354 *page_index = offset >> PAGE_SHIFT;
5355 *page_offset = offset_in_page(offset);
5359 * Determine whether a bit in a bitmap item is set.
5361 * @eb: the extent buffer
5362 * @start: offset of the bitmap item in the extent buffer
5363 * @nr: bit number to test
5365 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
5373 eb_bitmap_offset(eb, start, nr, &i, &offset);
5374 page = eb->pages[i];
5375 assert_eb_page_uptodate(eb, page);
5376 kaddr = page_address(page);
5377 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5381 * Set an area of a bitmap to 1.
5383 * @eb: the extent buffer
5384 * @start: offset of the bitmap item in the extent buffer
5385 * @pos: bit number of the first bit
5386 * @len: number of bits to set
5388 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
5389 unsigned long pos, unsigned long len)
5395 const unsigned int size = pos + len;
5396 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5397 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5399 eb_bitmap_offset(eb, start, pos, &i, &offset);
5400 page = eb->pages[i];
5401 assert_eb_page_uptodate(eb, page);
5402 kaddr = page_address(page);
5404 while (len >= bits_to_set) {
5405 kaddr[offset] |= mask_to_set;
5407 bits_to_set = BITS_PER_BYTE;
5409 if (++offset >= PAGE_SIZE && len > 0) {
5411 page = eb->pages[++i];
5412 assert_eb_page_uptodate(eb, page);
5413 kaddr = page_address(page);
5417 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5418 kaddr[offset] |= mask_to_set;
5424 * Clear an area of a bitmap.
5426 * @eb: the extent buffer
5427 * @start: offset of the bitmap item in the extent buffer
5428 * @pos: bit number of the first bit
5429 * @len: number of bits to clear
5431 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
5432 unsigned long start, unsigned long pos,
5439 const unsigned int size = pos + len;
5440 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5441 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5443 eb_bitmap_offset(eb, start, pos, &i, &offset);
5444 page = eb->pages[i];
5445 assert_eb_page_uptodate(eb, page);
5446 kaddr = page_address(page);
5448 while (len >= bits_to_clear) {
5449 kaddr[offset] &= ~mask_to_clear;
5450 len -= bits_to_clear;
5451 bits_to_clear = BITS_PER_BYTE;
5453 if (++offset >= PAGE_SIZE && len > 0) {
5455 page = eb->pages[++i];
5456 assert_eb_page_uptodate(eb, page);
5457 kaddr = page_address(page);
5461 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5462 kaddr[offset] &= ~mask_to_clear;
5466 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5468 unsigned long distance = (src > dst) ? src - dst : dst - src;
5469 return distance < len;
5472 static void copy_pages(struct page *dst_page, struct page *src_page,
5473 unsigned long dst_off, unsigned long src_off,
5476 char *dst_kaddr = page_address(dst_page);
5478 int must_memmove = 0;
5480 if (dst_page != src_page) {
5481 src_kaddr = page_address(src_page);
5483 src_kaddr = dst_kaddr;
5484 if (areas_overlap(src_off, dst_off, len))
5489 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5491 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5494 void memcpy_extent_buffer(const struct extent_buffer *dst,
5495 unsigned long dst_offset, unsigned long src_offset,
5499 size_t dst_off_in_page;
5500 size_t src_off_in_page;
5501 unsigned long dst_i;
5502 unsigned long src_i;
5504 if (check_eb_range(dst, dst_offset, len) ||
5505 check_eb_range(dst, src_offset, len))
5509 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
5510 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
5512 dst_i = get_eb_page_index(dst_offset);
5513 src_i = get_eb_page_index(src_offset);
5515 cur = min(len, (unsigned long)(PAGE_SIZE -
5517 cur = min_t(unsigned long, cur,
5518 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5520 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5521 dst_off_in_page, src_off_in_page, cur);
5529 void memmove_extent_buffer(const struct extent_buffer *dst,
5530 unsigned long dst_offset, unsigned long src_offset,
5534 size_t dst_off_in_page;
5535 size_t src_off_in_page;
5536 unsigned long dst_end = dst_offset + len - 1;
5537 unsigned long src_end = src_offset + len - 1;
5538 unsigned long dst_i;
5539 unsigned long src_i;
5541 if (check_eb_range(dst, dst_offset, len) ||
5542 check_eb_range(dst, src_offset, len))
5544 if (dst_offset < src_offset) {
5545 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5549 dst_i = get_eb_page_index(dst_end);
5550 src_i = get_eb_page_index(src_end);
5552 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
5553 src_off_in_page = get_eb_offset_in_page(dst, src_end);
5555 cur = min_t(unsigned long, len, src_off_in_page + 1);
5556 cur = min(cur, dst_off_in_page + 1);
5557 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5558 dst_off_in_page - cur + 1,
5559 src_off_in_page - cur + 1, cur);
5567 #define GANG_LOOKUP_SIZE 16
5568 static struct extent_buffer *get_next_extent_buffer(
5569 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
5571 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
5572 struct extent_buffer *found = NULL;
5573 u64 page_start = page_offset(page);
5574 u64 cur = page_start;
5576 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
5577 lockdep_assert_held(&fs_info->buffer_lock);
5579 while (cur < page_start + PAGE_SIZE) {
5583 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
5584 (void **)gang, cur >> fs_info->sectorsize_bits,
5585 min_t(unsigned int, GANG_LOOKUP_SIZE,
5586 PAGE_SIZE / fs_info->nodesize));
5589 for (i = 0; i < ret; i++) {
5590 /* Already beyond page end */
5591 if (gang[i]->start >= page_start + PAGE_SIZE)
5594 if (gang[i]->start >= bytenr) {
5599 cur = gang[ret - 1]->start + gang[ret - 1]->len;
5605 static int try_release_subpage_extent_buffer(struct page *page)
5607 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5608 u64 cur = page_offset(page);
5609 const u64 end = page_offset(page) + PAGE_SIZE;
5613 struct extent_buffer *eb = NULL;
5616 * Unlike try_release_extent_buffer() which uses page->private
5617 * to grab buffer, for subpage case we rely on radix tree, thus
5618 * we need to ensure radix tree consistency.
5620 * We also want an atomic snapshot of the radix tree, thus go
5621 * with spinlock rather than RCU.
5623 spin_lock(&fs_info->buffer_lock);
5624 eb = get_next_extent_buffer(fs_info, page, cur);
5626 /* No more eb in the page range after or at cur */
5627 spin_unlock(&fs_info->buffer_lock);
5630 cur = eb->start + eb->len;
5633 * The same as try_release_extent_buffer(), to ensure the eb
5634 * won't disappear out from under us.
5636 spin_lock(&eb->refs_lock);
5637 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5638 spin_unlock(&eb->refs_lock);
5639 spin_unlock(&fs_info->buffer_lock);
5642 spin_unlock(&fs_info->buffer_lock);
5645 * If tree ref isn't set then we know the ref on this eb is a
5646 * real ref, so just return, this eb will likely be freed soon
5649 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5650 spin_unlock(&eb->refs_lock);
5655 * Here we don't care about the return value, we will always
5656 * check the page private at the end. And
5657 * release_extent_buffer() will release the refs_lock.
5659 release_extent_buffer(eb);
5662 * Finally to check if we have cleared page private, as if we have
5663 * released all ebs in the page, the page private should be cleared now.
5665 spin_lock(&page->mapping->private_lock);
5666 if (!PagePrivate(page))
5670 spin_unlock(&page->mapping->private_lock);
5675 int try_release_extent_buffer(struct page *page)
5677 struct extent_buffer *eb;
5679 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5680 return try_release_subpage_extent_buffer(page);
5683 * We need to make sure nobody is changing page->private, as we rely on
5684 * page->private as the pointer to extent buffer.
5686 spin_lock(&page->mapping->private_lock);
5687 if (!PagePrivate(page)) {
5688 spin_unlock(&page->mapping->private_lock);
5692 eb = (struct extent_buffer *)page->private;
5696 * This is a little awful but should be ok, we need to make sure that
5697 * the eb doesn't disappear out from under us while we're looking at
5700 spin_lock(&eb->refs_lock);
5701 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5702 spin_unlock(&eb->refs_lock);
5703 spin_unlock(&page->mapping->private_lock);
5706 spin_unlock(&page->mapping->private_lock);
5709 * If tree ref isn't set then we know the ref on this eb is a real ref,
5710 * so just return, this page will likely be freed soon anyway.
5712 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5713 spin_unlock(&eb->refs_lock);
5717 return release_extent_buffer(eb);
5721 * btrfs_readahead_tree_block - attempt to readahead a child block
5722 * @fs_info: the fs_info
5723 * @bytenr: bytenr to read
5724 * @owner_root: objectid of the root that owns this eb
5725 * @gen: generation for the uptodate check, can be 0
5726 * @level: level for the eb
5728 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
5729 * normal uptodate check of the eb, without checking the generation. If we have
5730 * to read the block we will not block on anything.
5732 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5733 u64 bytenr, u64 owner_root, u64 gen, int level)
5735 struct btrfs_tree_parent_check check = {
5740 struct extent_buffer *eb;
5743 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5747 if (btrfs_buffer_uptodate(eb, gen, 1)) {
5748 free_extent_buffer(eb);
5752 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
5754 free_extent_buffer_stale(eb);
5756 free_extent_buffer(eb);
5760 * btrfs_readahead_node_child - readahead a node's child block
5761 * @node: parent node we're reading from
5762 * @slot: slot in the parent node for the child we want to read
5764 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5765 * the slot in the node provided.
5767 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5769 btrfs_readahead_tree_block(node->fs_info,
5770 btrfs_node_blockptr(node, slot),
5771 btrfs_header_owner(node),
5772 btrfs_node_ptr_generation(node, slot),
5773 btrfs_header_level(node) - 1);