1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/sched/mm.h>
10 #include <linux/spinlock.h>
11 #include <linux/blkdev.h>
12 #include <linux/swap.h>
13 #include <linux/writeback.h>
14 #include <linux/pagevec.h>
15 #include <linux/prefetch.h>
16 #include <linux/fsverity.h>
18 #include "extent_io.h"
19 #include "extent-io-tree.h"
20 #include "extent_map.h"
22 #include "btrfs_inode.h"
24 #include "check-integrity.h"
26 #include "rcu-string.h"
31 #include "block-group.h"
32 #include "compression.h"
34 static struct kmem_cache *extent_state_cache;
35 static struct kmem_cache *extent_buffer_cache;
36 static struct bio_set btrfs_bioset;
38 static inline bool extent_state_in_tree(const struct extent_state *state)
40 return !RB_EMPTY_NODE(&state->rb_node);
43 #ifdef CONFIG_BTRFS_DEBUG
44 static LIST_HEAD(states);
45 static DEFINE_SPINLOCK(leak_lock);
47 static inline void btrfs_leak_debug_add(spinlock_t *lock,
48 struct list_head *new,
49 struct list_head *head)
53 spin_lock_irqsave(lock, flags);
55 spin_unlock_irqrestore(lock, flags);
58 static inline void btrfs_leak_debug_del(spinlock_t *lock,
59 struct list_head *entry)
63 spin_lock_irqsave(lock, flags);
65 spin_unlock_irqrestore(lock, flags);
68 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
70 struct extent_buffer *eb;
74 * If we didn't get into open_ctree our allocated_ebs will not be
75 * initialized, so just skip this.
77 if (!fs_info->allocated_ebs.next)
80 WARN_ON(!list_empty(&fs_info->allocated_ebs));
81 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
82 while (!list_empty(&fs_info->allocated_ebs)) {
83 eb = list_first_entry(&fs_info->allocated_ebs,
84 struct extent_buffer, leak_list);
86 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
87 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
88 btrfs_header_owner(eb));
89 list_del(&eb->leak_list);
90 kmem_cache_free(extent_buffer_cache, eb);
92 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
95 static inline void btrfs_extent_state_leak_debug_check(void)
97 struct extent_state *state;
99 while (!list_empty(&states)) {
100 state = list_entry(states.next, struct extent_state, leak_list);
101 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
102 state->start, state->end, state->state,
103 extent_state_in_tree(state),
104 refcount_read(&state->refs));
105 list_del(&state->leak_list);
106 kmem_cache_free(extent_state_cache, state);
110 #define btrfs_debug_check_extent_io_range(tree, start, end) \
111 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
112 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
113 struct extent_io_tree *tree, u64 start, u64 end)
115 struct inode *inode = tree->private_data;
118 if (!inode || !is_data_inode(inode))
121 isize = i_size_read(inode);
122 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
123 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
124 "%s: ino %llu isize %llu odd range [%llu,%llu]",
125 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
129 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
130 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
131 #define btrfs_extent_state_leak_debug_check() do {} while (0)
132 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
138 struct rb_node rb_node;
142 * Structure to record info about the bio being assembled, and other info like
143 * how many bytes are there before stripe/ordered extent boundary.
145 struct btrfs_bio_ctrl {
147 enum btrfs_compression_type compress_type;
148 u32 len_to_stripe_boundary;
149 u32 len_to_oe_boundary;
152 struct extent_page_data {
153 struct btrfs_bio_ctrl bio_ctrl;
154 /* tells writepage not to lock the state bits for this range
155 * it still does the unlocking
157 unsigned int extent_locked:1;
159 /* tells the submit_bio code to use REQ_SYNC */
160 unsigned int sync_io:1;
163 static int add_extent_changeset(struct extent_state *state, u32 bits,
164 struct extent_changeset *changeset,
171 if (set && (state->state & bits) == bits)
173 if (!set && (state->state & bits) == 0)
175 changeset->bytes_changed += state->end - state->start + 1;
176 ret = ulist_add(&changeset->range_changed, state->start, state->end,
181 static void submit_one_bio(struct bio *bio, int mirror_num,
182 enum btrfs_compression_type compress_type)
184 struct extent_io_tree *tree = bio->bi_private;
186 bio->bi_private = NULL;
188 /* Caller should ensure the bio has at least some range added */
189 ASSERT(bio->bi_iter.bi_size);
191 if (is_data_inode(tree->private_data))
192 btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
195 btrfs_submit_metadata_bio(tree->private_data, bio, mirror_num);
197 * Above submission hooks will handle the error by ending the bio,
198 * which will do the cleanup properly. So here we should not return
199 * any error, or the caller of submit_extent_page() will do cleanup
200 * again, causing problems.
204 /* Cleanup unsubmitted bios */
205 static void end_write_bio(struct extent_page_data *epd, int ret)
207 struct bio *bio = epd->bio_ctrl.bio;
210 bio->bi_status = errno_to_blk_status(ret);
212 epd->bio_ctrl.bio = NULL;
217 * Submit bio from extent page data via submit_one_bio
219 * Return 0 if everything is OK.
220 * Return <0 for error.
222 static void flush_write_bio(struct extent_page_data *epd)
224 struct bio *bio = epd->bio_ctrl.bio;
227 submit_one_bio(bio, 0, 0);
229 * Clean up of epd->bio is handled by its endio function.
230 * And endio is either triggered by successful bio execution
231 * or the error handler of submit bio hook.
232 * So at this point, no matter what happened, we don't need
233 * to clean up epd->bio.
235 epd->bio_ctrl.bio = NULL;
239 int __init extent_state_cache_init(void)
241 extent_state_cache = kmem_cache_create("btrfs_extent_state",
242 sizeof(struct extent_state), 0,
243 SLAB_MEM_SPREAD, NULL);
244 if (!extent_state_cache)
249 int __init extent_io_init(void)
251 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
252 sizeof(struct extent_buffer), 0,
253 SLAB_MEM_SPREAD, NULL);
254 if (!extent_buffer_cache)
257 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
258 offsetof(struct btrfs_bio, bio),
260 goto free_buffer_cache;
262 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
268 bioset_exit(&btrfs_bioset);
271 kmem_cache_destroy(extent_buffer_cache);
272 extent_buffer_cache = NULL;
276 void __cold extent_state_cache_exit(void)
278 btrfs_extent_state_leak_debug_check();
279 kmem_cache_destroy(extent_state_cache);
282 void __cold extent_io_exit(void)
285 * Make sure all delayed rcu free are flushed before we
289 kmem_cache_destroy(extent_buffer_cache);
290 bioset_exit(&btrfs_bioset);
294 * For the file_extent_tree, we want to hold the inode lock when we lookup and
295 * update the disk_i_size, but lockdep will complain because our io_tree we hold
296 * the tree lock and get the inode lock when setting delalloc. These two things
297 * are unrelated, so make a class for the file_extent_tree so we don't get the
298 * two locking patterns mixed up.
300 static struct lock_class_key file_extent_tree_class;
302 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
303 struct extent_io_tree *tree, unsigned int owner,
306 tree->fs_info = fs_info;
307 tree->state = RB_ROOT;
308 tree->dirty_bytes = 0;
309 spin_lock_init(&tree->lock);
310 tree->private_data = private_data;
312 if (owner == IO_TREE_INODE_FILE_EXTENT)
313 lockdep_set_class(&tree->lock, &file_extent_tree_class);
316 void extent_io_tree_release(struct extent_io_tree *tree)
318 spin_lock(&tree->lock);
320 * Do a single barrier for the waitqueue_active check here, the state
321 * of the waitqueue should not change once extent_io_tree_release is
325 while (!RB_EMPTY_ROOT(&tree->state)) {
326 struct rb_node *node;
327 struct extent_state *state;
329 node = rb_first(&tree->state);
330 state = rb_entry(node, struct extent_state, rb_node);
331 rb_erase(&state->rb_node, &tree->state);
332 RB_CLEAR_NODE(&state->rb_node);
334 * btree io trees aren't supposed to have tasks waiting for
335 * changes in the flags of extent states ever.
337 ASSERT(!waitqueue_active(&state->wq));
338 free_extent_state(state);
340 cond_resched_lock(&tree->lock);
342 spin_unlock(&tree->lock);
345 static struct extent_state *alloc_extent_state(gfp_t mask)
347 struct extent_state *state;
350 * The given mask might be not appropriate for the slab allocator,
351 * drop the unsupported bits
353 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
354 state = kmem_cache_alloc(extent_state_cache, mask);
358 state->failrec = NULL;
359 RB_CLEAR_NODE(&state->rb_node);
360 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
361 refcount_set(&state->refs, 1);
362 init_waitqueue_head(&state->wq);
363 trace_alloc_extent_state(state, mask, _RET_IP_);
367 void free_extent_state(struct extent_state *state)
371 if (refcount_dec_and_test(&state->refs)) {
372 WARN_ON(extent_state_in_tree(state));
373 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
374 trace_free_extent_state(state, _RET_IP_);
375 kmem_cache_free(extent_state_cache, state);
379 static struct rb_node *tree_insert(struct rb_root *root,
380 struct rb_node *search_start,
382 struct rb_node *node,
383 struct rb_node ***p_in,
384 struct rb_node **parent_in)
387 struct rb_node *parent = NULL;
388 struct tree_entry *entry;
390 if (p_in && parent_in) {
396 p = search_start ? &search_start : &root->rb_node;
399 entry = rb_entry(parent, struct tree_entry, rb_node);
401 if (offset < entry->start)
403 else if (offset > entry->end)
410 rb_link_node(node, parent, p);
411 rb_insert_color(node, root);
416 * Search @tree for an entry that contains @offset. Such entry would have
417 * entry->start <= offset && entry->end >= offset.
419 * @tree: the tree to search
420 * @offset: offset that should fall within an entry in @tree
421 * @next_ret: pointer to the first entry whose range ends after @offset
422 * @prev_ret: pointer to the first entry whose range begins before @offset
423 * @p_ret: pointer where new node should be anchored (used when inserting an
425 * @parent_ret: points to entry which would have been the parent of the entry,
428 * This function returns a pointer to the entry that contains @offset byte
429 * address. If no such entry exists, then NULL is returned and the other
430 * pointer arguments to the function are filled, otherwise the found entry is
431 * returned and other pointers are left untouched.
433 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
434 struct rb_node **next_ret,
435 struct rb_node **prev_ret,
436 struct rb_node ***p_ret,
437 struct rb_node **parent_ret)
439 struct rb_root *root = &tree->state;
440 struct rb_node **n = &root->rb_node;
441 struct rb_node *prev = NULL;
442 struct rb_node *orig_prev = NULL;
443 struct tree_entry *entry;
444 struct tree_entry *prev_entry = NULL;
448 entry = rb_entry(prev, struct tree_entry, rb_node);
451 if (offset < entry->start)
453 else if (offset > entry->end)
466 while (prev && offset > prev_entry->end) {
467 prev = rb_next(prev);
468 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
475 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
476 while (prev && offset < prev_entry->start) {
477 prev = rb_prev(prev);
478 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
485 static inline struct rb_node *
486 tree_search_for_insert(struct extent_io_tree *tree,
488 struct rb_node ***p_ret,
489 struct rb_node **parent_ret)
491 struct rb_node *next= NULL;
494 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
500 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
503 return tree_search_for_insert(tree, offset, NULL, NULL);
507 * utility function to look for merge candidates inside a given range.
508 * Any extents with matching state are merged together into a single
509 * extent in the tree. Extents with EXTENT_IO in their state field
510 * are not merged because the end_io handlers need to be able to do
511 * operations on them without sleeping (or doing allocations/splits).
513 * This should be called with the tree lock held.
515 static void merge_state(struct extent_io_tree *tree,
516 struct extent_state *state)
518 struct extent_state *other;
519 struct rb_node *other_node;
521 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
524 other_node = rb_prev(&state->rb_node);
526 other = rb_entry(other_node, struct extent_state, rb_node);
527 if (other->end == state->start - 1 &&
528 other->state == state->state) {
529 if (tree->private_data &&
530 is_data_inode(tree->private_data))
531 btrfs_merge_delalloc_extent(tree->private_data,
533 state->start = other->start;
534 rb_erase(&other->rb_node, &tree->state);
535 RB_CLEAR_NODE(&other->rb_node);
536 free_extent_state(other);
539 other_node = rb_next(&state->rb_node);
541 other = rb_entry(other_node, struct extent_state, rb_node);
542 if (other->start == state->end + 1 &&
543 other->state == state->state) {
544 if (tree->private_data &&
545 is_data_inode(tree->private_data))
546 btrfs_merge_delalloc_extent(tree->private_data,
548 state->end = other->end;
549 rb_erase(&other->rb_node, &tree->state);
550 RB_CLEAR_NODE(&other->rb_node);
551 free_extent_state(other);
556 static void set_state_bits(struct extent_io_tree *tree,
557 struct extent_state *state, u32 *bits,
558 struct extent_changeset *changeset);
561 * insert an extent_state struct into the tree. 'bits' are set on the
562 * struct before it is inserted.
564 * This may return -EEXIST if the extent is already there, in which case the
565 * state struct is freed.
567 * The tree lock is not taken internally. This is a utility function and
568 * probably isn't what you want to call (see set/clear_extent_bit).
570 static int insert_state(struct extent_io_tree *tree,
571 struct extent_state *state, u64 start, u64 end,
573 struct rb_node **parent,
574 u32 *bits, struct extent_changeset *changeset)
576 struct rb_node *node;
579 btrfs_err(tree->fs_info,
580 "insert state: end < start %llu %llu", end, start);
583 state->start = start;
586 set_state_bits(tree, state, bits, changeset);
588 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
590 struct extent_state *found;
591 found = rb_entry(node, struct extent_state, rb_node);
592 btrfs_err(tree->fs_info,
593 "found node %llu %llu on insert of %llu %llu",
594 found->start, found->end, start, end);
597 merge_state(tree, state);
602 * split a given extent state struct in two, inserting the preallocated
603 * struct 'prealloc' as the newly created second half. 'split' indicates an
604 * offset inside 'orig' where it should be split.
607 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
608 * are two extent state structs in the tree:
609 * prealloc: [orig->start, split - 1]
610 * orig: [ split, orig->end ]
612 * The tree locks are not taken by this function. They need to be held
615 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
616 struct extent_state *prealloc, u64 split)
618 struct rb_node *node;
620 if (tree->private_data && is_data_inode(tree->private_data))
621 btrfs_split_delalloc_extent(tree->private_data, orig, split);
623 prealloc->start = orig->start;
624 prealloc->end = split - 1;
625 prealloc->state = orig->state;
628 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
629 &prealloc->rb_node, NULL, NULL);
631 free_extent_state(prealloc);
637 static struct extent_state *next_state(struct extent_state *state)
639 struct rb_node *next = rb_next(&state->rb_node);
641 return rb_entry(next, struct extent_state, rb_node);
647 * utility function to clear some bits in an extent state struct.
648 * it will optionally wake up anyone waiting on this state (wake == 1).
650 * If no bits are set on the state struct after clearing things, the
651 * struct is freed and removed from the tree
653 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
654 struct extent_state *state,
656 struct extent_changeset *changeset)
658 struct extent_state *next;
659 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
662 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
663 u64 range = state->end - state->start + 1;
664 WARN_ON(range > tree->dirty_bytes);
665 tree->dirty_bytes -= range;
668 if (tree->private_data && is_data_inode(tree->private_data))
669 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
671 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
673 state->state &= ~bits_to_clear;
676 if (state->state == 0) {
677 next = next_state(state);
678 if (extent_state_in_tree(state)) {
679 rb_erase(&state->rb_node, &tree->state);
680 RB_CLEAR_NODE(&state->rb_node);
681 free_extent_state(state);
686 merge_state(tree, state);
687 next = next_state(state);
692 static struct extent_state *
693 alloc_extent_state_atomic(struct extent_state *prealloc)
696 prealloc = alloc_extent_state(GFP_ATOMIC);
701 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
703 btrfs_panic(tree->fs_info, err,
704 "locking error: extent tree was modified by another thread while locked");
708 * clear some bits on a range in the tree. This may require splitting
709 * or inserting elements in the tree, so the gfp mask is used to
710 * indicate which allocations or sleeping are allowed.
712 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
713 * the given range from the tree regardless of state (ie for truncate).
715 * the range [start, end] is inclusive.
717 * This takes the tree lock, and returns 0 on success and < 0 on error.
719 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
720 u32 bits, int wake, int delete,
721 struct extent_state **cached_state,
722 gfp_t mask, struct extent_changeset *changeset)
724 struct extent_state *state;
725 struct extent_state *cached;
726 struct extent_state *prealloc = NULL;
727 struct rb_node *node;
732 btrfs_debug_check_extent_io_range(tree, start, end);
733 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
735 if (bits & EXTENT_DELALLOC)
736 bits |= EXTENT_NORESERVE;
739 bits |= ~EXTENT_CTLBITS;
741 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
744 if (!prealloc && gfpflags_allow_blocking(mask)) {
746 * Don't care for allocation failure here because we might end
747 * up not needing the pre-allocated extent state at all, which
748 * is the case if we only have in the tree extent states that
749 * cover our input range and don't cover too any other range.
750 * If we end up needing a new extent state we allocate it later.
752 prealloc = alloc_extent_state(mask);
755 spin_lock(&tree->lock);
757 cached = *cached_state;
760 *cached_state = NULL;
764 if (cached && extent_state_in_tree(cached) &&
765 cached->start <= start && cached->end > start) {
767 refcount_dec(&cached->refs);
772 free_extent_state(cached);
775 * this search will find the extents that end after
778 node = tree_search(tree, start);
781 state = rb_entry(node, struct extent_state, rb_node);
783 if (state->start > end)
785 WARN_ON(state->end < start);
786 last_end = state->end;
788 /* the state doesn't have the wanted bits, go ahead */
789 if (!(state->state & bits)) {
790 state = next_state(state);
795 * | ---- desired range ---- |
797 * | ------------- state -------------- |
799 * We need to split the extent we found, and may flip
800 * bits on second half.
802 * If the extent we found extends past our range, we
803 * just split and search again. It'll get split again
804 * the next time though.
806 * If the extent we found is inside our range, we clear
807 * the desired bit on it.
810 if (state->start < start) {
811 prealloc = alloc_extent_state_atomic(prealloc);
813 err = split_state(tree, state, prealloc, start);
815 extent_io_tree_panic(tree, err);
820 if (state->end <= end) {
821 state = clear_state_bit(tree, state, &bits, wake,
828 * | ---- desired range ---- |
830 * We need to split the extent, and clear the bit
833 if (state->start <= end && state->end > end) {
834 prealloc = alloc_extent_state_atomic(prealloc);
836 err = split_state(tree, state, prealloc, end + 1);
838 extent_io_tree_panic(tree, err);
843 clear_state_bit(tree, prealloc, &bits, wake, changeset);
849 state = clear_state_bit(tree, state, &bits, wake, changeset);
851 if (last_end == (u64)-1)
853 start = last_end + 1;
854 if (start <= end && state && !need_resched())
860 spin_unlock(&tree->lock);
861 if (gfpflags_allow_blocking(mask))
866 spin_unlock(&tree->lock);
868 free_extent_state(prealloc);
874 static void wait_on_state(struct extent_io_tree *tree,
875 struct extent_state *state)
876 __releases(tree->lock)
877 __acquires(tree->lock)
880 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
881 spin_unlock(&tree->lock);
883 spin_lock(&tree->lock);
884 finish_wait(&state->wq, &wait);
888 * waits for one or more bits to clear on a range in the state tree.
889 * The range [start, end] is inclusive.
890 * The tree lock is taken by this function
892 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
895 struct extent_state *state;
896 struct rb_node *node;
898 btrfs_debug_check_extent_io_range(tree, start, end);
900 spin_lock(&tree->lock);
904 * this search will find all the extents that end after
907 node = tree_search(tree, start);
912 state = rb_entry(node, struct extent_state, rb_node);
914 if (state->start > end)
917 if (state->state & bits) {
918 start = state->start;
919 refcount_inc(&state->refs);
920 wait_on_state(tree, state);
921 free_extent_state(state);
924 start = state->end + 1;
929 if (!cond_resched_lock(&tree->lock)) {
930 node = rb_next(node);
935 spin_unlock(&tree->lock);
938 static void set_state_bits(struct extent_io_tree *tree,
939 struct extent_state *state,
940 u32 *bits, struct extent_changeset *changeset)
942 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
945 if (tree->private_data && is_data_inode(tree->private_data))
946 btrfs_set_delalloc_extent(tree->private_data, state, bits);
948 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
949 u64 range = state->end - state->start + 1;
950 tree->dirty_bytes += range;
952 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
954 state->state |= bits_to_set;
957 static void cache_state_if_flags(struct extent_state *state,
958 struct extent_state **cached_ptr,
961 if (cached_ptr && !(*cached_ptr)) {
962 if (!flags || (state->state & flags)) {
964 refcount_inc(&state->refs);
969 static void cache_state(struct extent_state *state,
970 struct extent_state **cached_ptr)
972 return cache_state_if_flags(state, cached_ptr,
973 EXTENT_LOCKED | EXTENT_BOUNDARY);
977 * set some bits on a range in the tree. This may require allocations or
978 * sleeping, so the gfp mask is used to indicate what is allowed.
980 * If any of the exclusive bits are set, this will fail with -EEXIST if some
981 * part of the range already has the desired bits set. The start of the
982 * existing range is returned in failed_start in this case.
984 * [start, end] is inclusive This takes the tree lock.
986 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
987 u32 exclusive_bits, u64 *failed_start,
988 struct extent_state **cached_state, gfp_t mask,
989 struct extent_changeset *changeset)
991 struct extent_state *state;
992 struct extent_state *prealloc = NULL;
993 struct rb_node *node;
995 struct rb_node *parent;
1000 btrfs_debug_check_extent_io_range(tree, start, end);
1001 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
1004 ASSERT(failed_start);
1006 ASSERT(failed_start == NULL);
1008 if (!prealloc && gfpflags_allow_blocking(mask)) {
1010 * Don't care for allocation failure here because we might end
1011 * up not needing the pre-allocated extent state at all, which
1012 * is the case if we only have in the tree extent states that
1013 * cover our input range and don't cover too any other range.
1014 * If we end up needing a new extent state we allocate it later.
1016 prealloc = alloc_extent_state(mask);
1019 spin_lock(&tree->lock);
1020 if (cached_state && *cached_state) {
1021 state = *cached_state;
1022 if (state->start <= start && state->end > start &&
1023 extent_state_in_tree(state)) {
1024 node = &state->rb_node;
1029 * this search will find all the extents that end after
1032 node = tree_search_for_insert(tree, start, &p, &parent);
1034 prealloc = alloc_extent_state_atomic(prealloc);
1036 err = insert_state(tree, prealloc, start, end,
1037 &p, &parent, &bits, changeset);
1039 extent_io_tree_panic(tree, err);
1041 cache_state(prealloc, cached_state);
1045 state = rb_entry(node, struct extent_state, rb_node);
1047 last_start = state->start;
1048 last_end = state->end;
1051 * | ---- desired range ---- |
1054 * Just lock what we found and keep going
1056 if (state->start == start && state->end <= end) {
1057 if (state->state & exclusive_bits) {
1058 *failed_start = state->start;
1063 set_state_bits(tree, state, &bits, changeset);
1064 cache_state(state, cached_state);
1065 merge_state(tree, state);
1066 if (last_end == (u64)-1)
1068 start = last_end + 1;
1069 state = next_state(state);
1070 if (start < end && state && state->start == start &&
1077 * | ---- desired range ---- |
1080 * | ------------- state -------------- |
1082 * We need to split the extent we found, and may flip bits on
1085 * If the extent we found extends past our
1086 * range, we just split and search again. It'll get split
1087 * again the next time though.
1089 * If the extent we found is inside our range, we set the
1090 * desired bit on it.
1092 if (state->start < start) {
1093 if (state->state & exclusive_bits) {
1094 *failed_start = start;
1100 * If this extent already has all the bits we want set, then
1101 * skip it, not necessary to split it or do anything with it.
1103 if ((state->state & bits) == bits) {
1104 start = state->end + 1;
1105 cache_state(state, cached_state);
1109 prealloc = alloc_extent_state_atomic(prealloc);
1111 err = split_state(tree, state, prealloc, start);
1113 extent_io_tree_panic(tree, err);
1118 if (state->end <= end) {
1119 set_state_bits(tree, state, &bits, changeset);
1120 cache_state(state, cached_state);
1121 merge_state(tree, state);
1122 if (last_end == (u64)-1)
1124 start = last_end + 1;
1125 state = next_state(state);
1126 if (start < end && state && state->start == start &&
1133 * | ---- desired range ---- |
1134 * | state | or | state |
1136 * There's a hole, we need to insert something in it and
1137 * ignore the extent we found.
1139 if (state->start > start) {
1141 if (end < last_start)
1144 this_end = last_start - 1;
1146 prealloc = alloc_extent_state_atomic(prealloc);
1150 * Avoid to free 'prealloc' if it can be merged with
1153 err = insert_state(tree, prealloc, start, this_end,
1154 NULL, NULL, &bits, changeset);
1156 extent_io_tree_panic(tree, err);
1158 cache_state(prealloc, cached_state);
1160 start = this_end + 1;
1164 * | ---- desired range ---- |
1166 * We need to split the extent, and set the bit
1169 if (state->start <= end && state->end > end) {
1170 if (state->state & exclusive_bits) {
1171 *failed_start = start;
1176 prealloc = alloc_extent_state_atomic(prealloc);
1178 err = split_state(tree, state, prealloc, end + 1);
1180 extent_io_tree_panic(tree, err);
1182 set_state_bits(tree, prealloc, &bits, changeset);
1183 cache_state(prealloc, cached_state);
1184 merge_state(tree, prealloc);
1192 spin_unlock(&tree->lock);
1193 if (gfpflags_allow_blocking(mask))
1198 spin_unlock(&tree->lock);
1200 free_extent_state(prealloc);
1207 * convert_extent_bit - convert all bits in a given range from one bit to
1209 * @tree: the io tree to search
1210 * @start: the start offset in bytes
1211 * @end: the end offset in bytes (inclusive)
1212 * @bits: the bits to set in this range
1213 * @clear_bits: the bits to clear in this range
1214 * @cached_state: state that we're going to cache
1216 * This will go through and set bits for the given range. If any states exist
1217 * already in this range they are set with the given bit and cleared of the
1218 * clear_bits. This is only meant to be used by things that are mergeable, ie
1219 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1220 * boundary bits like LOCK.
1222 * All allocations are done with GFP_NOFS.
1224 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1225 u32 bits, u32 clear_bits,
1226 struct extent_state **cached_state)
1228 struct extent_state *state;
1229 struct extent_state *prealloc = NULL;
1230 struct rb_node *node;
1232 struct rb_node *parent;
1236 bool first_iteration = true;
1238 btrfs_debug_check_extent_io_range(tree, start, end);
1239 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1245 * Best effort, don't worry if extent state allocation fails
1246 * here for the first iteration. We might have a cached state
1247 * that matches exactly the target range, in which case no
1248 * extent state allocations are needed. We'll only know this
1249 * after locking the tree.
1251 prealloc = alloc_extent_state(GFP_NOFS);
1252 if (!prealloc && !first_iteration)
1256 spin_lock(&tree->lock);
1257 if (cached_state && *cached_state) {
1258 state = *cached_state;
1259 if (state->start <= start && state->end > start &&
1260 extent_state_in_tree(state)) {
1261 node = &state->rb_node;
1267 * this search will find all the extents that end after
1270 node = tree_search_for_insert(tree, start, &p, &parent);
1272 prealloc = alloc_extent_state_atomic(prealloc);
1277 err = insert_state(tree, prealloc, start, end,
1278 &p, &parent, &bits, NULL);
1280 extent_io_tree_panic(tree, err);
1281 cache_state(prealloc, cached_state);
1285 state = rb_entry(node, struct extent_state, rb_node);
1287 last_start = state->start;
1288 last_end = state->end;
1291 * | ---- desired range ---- |
1294 * Just lock what we found and keep going
1296 if (state->start == start && state->end <= end) {
1297 set_state_bits(tree, state, &bits, NULL);
1298 cache_state(state, cached_state);
1299 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1300 if (last_end == (u64)-1)
1302 start = last_end + 1;
1303 if (start < end && state && state->start == start &&
1310 * | ---- desired range ---- |
1313 * | ------------- state -------------- |
1315 * We need to split the extent we found, and may flip bits on
1318 * If the extent we found extends past our
1319 * range, we just split and search again. It'll get split
1320 * again the next time though.
1322 * If the extent we found is inside our range, we set the
1323 * desired bit on it.
1325 if (state->start < start) {
1326 prealloc = alloc_extent_state_atomic(prealloc);
1331 err = split_state(tree, state, prealloc, start);
1333 extent_io_tree_panic(tree, err);
1337 if (state->end <= end) {
1338 set_state_bits(tree, state, &bits, NULL);
1339 cache_state(state, cached_state);
1340 state = clear_state_bit(tree, state, &clear_bits, 0,
1342 if (last_end == (u64)-1)
1344 start = last_end + 1;
1345 if (start < end && state && state->start == start &&
1352 * | ---- desired range ---- |
1353 * | state | or | state |
1355 * There's a hole, we need to insert something in it and
1356 * ignore the extent we found.
1358 if (state->start > start) {
1360 if (end < last_start)
1363 this_end = last_start - 1;
1365 prealloc = alloc_extent_state_atomic(prealloc);
1372 * Avoid to free 'prealloc' if it can be merged with
1375 err = insert_state(tree, prealloc, start, this_end,
1376 NULL, NULL, &bits, NULL);
1378 extent_io_tree_panic(tree, err);
1379 cache_state(prealloc, cached_state);
1381 start = this_end + 1;
1385 * | ---- desired range ---- |
1387 * We need to split the extent, and set the bit
1390 if (state->start <= end && state->end > end) {
1391 prealloc = alloc_extent_state_atomic(prealloc);
1397 err = split_state(tree, state, prealloc, end + 1);
1399 extent_io_tree_panic(tree, err);
1401 set_state_bits(tree, prealloc, &bits, NULL);
1402 cache_state(prealloc, cached_state);
1403 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1411 spin_unlock(&tree->lock);
1413 first_iteration = false;
1417 spin_unlock(&tree->lock);
1419 free_extent_state(prealloc);
1424 /* wrappers around set/clear extent bit */
1425 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1426 u32 bits, struct extent_changeset *changeset)
1429 * We don't support EXTENT_LOCKED yet, as current changeset will
1430 * record any bits changed, so for EXTENT_LOCKED case, it will
1431 * either fail with -EEXIST or changeset will record the whole
1434 BUG_ON(bits & EXTENT_LOCKED);
1436 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1440 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1443 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1447 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1448 u32 bits, int wake, int delete,
1449 struct extent_state **cached)
1451 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1452 cached, GFP_NOFS, NULL);
1455 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1456 u32 bits, struct extent_changeset *changeset)
1459 * Don't support EXTENT_LOCKED case, same reason as
1460 * set_record_extent_bits().
1462 BUG_ON(bits & EXTENT_LOCKED);
1464 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1469 * either insert or lock state struct between start and end use mask to tell
1470 * us if waiting is desired.
1472 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1473 struct extent_state **cached_state)
1479 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1480 EXTENT_LOCKED, &failed_start,
1481 cached_state, GFP_NOFS, NULL);
1482 if (err == -EEXIST) {
1483 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1484 start = failed_start;
1487 WARN_ON(start > end);
1492 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1497 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1498 &failed_start, NULL, GFP_NOFS, NULL);
1499 if (err == -EEXIST) {
1500 if (failed_start > start)
1501 clear_extent_bit(tree, start, failed_start - 1,
1502 EXTENT_LOCKED, 1, 0, NULL);
1508 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1510 unsigned long index = start >> PAGE_SHIFT;
1511 unsigned long end_index = end >> PAGE_SHIFT;
1514 while (index <= end_index) {
1515 page = find_get_page(inode->i_mapping, index);
1516 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1517 clear_page_dirty_for_io(page);
1523 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1525 struct address_space *mapping = inode->i_mapping;
1526 unsigned long index = start >> PAGE_SHIFT;
1527 unsigned long end_index = end >> PAGE_SHIFT;
1528 struct folio *folio;
1530 while (index <= end_index) {
1531 folio = filemap_get_folio(mapping, index);
1532 filemap_dirty_folio(mapping, folio);
1533 folio_account_redirty(folio);
1534 index += folio_nr_pages(folio);
1539 /* find the first state struct with 'bits' set after 'start', and
1540 * return it. tree->lock must be held. NULL will returned if
1541 * nothing was found after 'start'
1543 static struct extent_state *
1544 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1546 struct rb_node *node;
1547 struct extent_state *state;
1550 * this search will find all the extents that end after
1553 node = tree_search(tree, start);
1558 state = rb_entry(node, struct extent_state, rb_node);
1559 if (state->end >= start && (state->state & bits))
1562 node = rb_next(node);
1571 * Find the first offset in the io tree with one or more @bits set.
1573 * Note: If there are multiple bits set in @bits, any of them will match.
1575 * Return 0 if we find something, and update @start_ret and @end_ret.
1576 * Return 1 if we found nothing.
1578 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1579 u64 *start_ret, u64 *end_ret, u32 bits,
1580 struct extent_state **cached_state)
1582 struct extent_state *state;
1585 spin_lock(&tree->lock);
1586 if (cached_state && *cached_state) {
1587 state = *cached_state;
1588 if (state->end == start - 1 && extent_state_in_tree(state)) {
1589 while ((state = next_state(state)) != NULL) {
1590 if (state->state & bits)
1593 free_extent_state(*cached_state);
1594 *cached_state = NULL;
1597 free_extent_state(*cached_state);
1598 *cached_state = NULL;
1601 state = find_first_extent_bit_state(tree, start, bits);
1604 cache_state_if_flags(state, cached_state, 0);
1605 *start_ret = state->start;
1606 *end_ret = state->end;
1610 spin_unlock(&tree->lock);
1615 * Find a contiguous area of bits
1617 * @tree: io tree to check
1618 * @start: offset to start the search from
1619 * @start_ret: the first offset we found with the bits set
1620 * @end_ret: the final contiguous range of the bits that were set
1621 * @bits: bits to look for
1623 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1624 * to set bits appropriately, and then merge them again. During this time it
1625 * will drop the tree->lock, so use this helper if you want to find the actual
1626 * contiguous area for given bits. We will search to the first bit we find, and
1627 * then walk down the tree until we find a non-contiguous area. The area
1628 * returned will be the full contiguous area with the bits set.
1630 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1631 u64 *start_ret, u64 *end_ret, u32 bits)
1633 struct extent_state *state;
1636 spin_lock(&tree->lock);
1637 state = find_first_extent_bit_state(tree, start, bits);
1639 *start_ret = state->start;
1640 *end_ret = state->end;
1641 while ((state = next_state(state)) != NULL) {
1642 if (state->start > (*end_ret + 1))
1644 *end_ret = state->end;
1648 spin_unlock(&tree->lock);
1653 * Find the first range that has @bits not set. This range could start before
1656 * @tree: the tree to search
1657 * @start: offset at/after which the found extent should start
1658 * @start_ret: records the beginning of the range
1659 * @end_ret: records the end of the range (inclusive)
1660 * @bits: the set of bits which must be unset
1662 * Since unallocated range is also considered one which doesn't have the bits
1663 * set it's possible that @end_ret contains -1, this happens in case the range
1664 * spans (last_range_end, end of device]. In this case it's up to the caller to
1665 * trim @end_ret to the appropriate size.
1667 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1668 u64 *start_ret, u64 *end_ret, u32 bits)
1670 struct extent_state *state;
1671 struct rb_node *node, *prev = NULL, *next;
1673 spin_lock(&tree->lock);
1675 /* Find first extent with bits cleared */
1677 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1678 if (!node && !next && !prev) {
1680 * Tree is completely empty, send full range and let
1681 * caller deal with it
1686 } else if (!node && !next) {
1688 * We are past the last allocated chunk, set start at
1689 * the end of the last extent.
1691 state = rb_entry(prev, struct extent_state, rb_node);
1692 *start_ret = state->end + 1;
1699 * At this point 'node' either contains 'start' or start is
1702 state = rb_entry(node, struct extent_state, rb_node);
1704 if (in_range(start, state->start, state->end - state->start + 1)) {
1705 if (state->state & bits) {
1707 * |--range with bits sets--|
1711 start = state->end + 1;
1714 * 'start' falls within a range that doesn't
1715 * have the bits set, so take its start as
1716 * the beginning of the desired range
1718 * |--range with bits cleared----|
1722 *start_ret = state->start;
1727 * |---prev range---|---hole/unset---|---node range---|
1733 * |---hole/unset--||--first node--|
1738 state = rb_entry(prev, struct extent_state,
1740 *start_ret = state->end + 1;
1749 * Find the longest stretch from start until an entry which has the
1753 state = rb_entry(node, struct extent_state, rb_node);
1754 if (state->end >= start && !(state->state & bits)) {
1755 *end_ret = state->end;
1757 *end_ret = state->start - 1;
1761 node = rb_next(node);
1766 spin_unlock(&tree->lock);
1770 * find a contiguous range of bytes in the file marked as delalloc, not
1771 * more than 'max_bytes'. start and end are used to return the range,
1773 * true is returned if we find something, false if nothing was in the tree
1775 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1776 u64 *end, u64 max_bytes,
1777 struct extent_state **cached_state)
1779 struct rb_node *node;
1780 struct extent_state *state;
1781 u64 cur_start = *start;
1783 u64 total_bytes = 0;
1785 spin_lock(&tree->lock);
1788 * this search will find all the extents that end after
1791 node = tree_search(tree, cur_start);
1798 state = rb_entry(node, struct extent_state, rb_node);
1799 if (found && (state->start != cur_start ||
1800 (state->state & EXTENT_BOUNDARY))) {
1803 if (!(state->state & EXTENT_DELALLOC)) {
1809 *start = state->start;
1810 *cached_state = state;
1811 refcount_inc(&state->refs);
1815 cur_start = state->end + 1;
1816 node = rb_next(node);
1817 total_bytes += state->end - state->start + 1;
1818 if (total_bytes >= max_bytes)
1824 spin_unlock(&tree->lock);
1829 * Process one page for __process_pages_contig().
1831 * Return >0 if we hit @page == @locked_page.
1832 * Return 0 if we updated the page status.
1833 * Return -EGAIN if the we need to try again.
1834 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1836 static int process_one_page(struct btrfs_fs_info *fs_info,
1837 struct address_space *mapping,
1838 struct page *page, struct page *locked_page,
1839 unsigned long page_ops, u64 start, u64 end)
1843 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1844 len = end + 1 - start;
1846 if (page_ops & PAGE_SET_ORDERED)
1847 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
1848 if (page_ops & PAGE_SET_ERROR)
1849 btrfs_page_clamp_set_error(fs_info, page, start, len);
1850 if (page_ops & PAGE_START_WRITEBACK) {
1851 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1852 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1854 if (page_ops & PAGE_END_WRITEBACK)
1855 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1857 if (page == locked_page)
1860 if (page_ops & PAGE_LOCK) {
1863 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
1866 if (!PageDirty(page) || page->mapping != mapping) {
1867 btrfs_page_end_writer_lock(fs_info, page, start, len);
1871 if (page_ops & PAGE_UNLOCK)
1872 btrfs_page_end_writer_lock(fs_info, page, start, len);
1876 static int __process_pages_contig(struct address_space *mapping,
1877 struct page *locked_page,
1878 u64 start, u64 end, unsigned long page_ops,
1881 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1882 pgoff_t start_index = start >> PAGE_SHIFT;
1883 pgoff_t end_index = end >> PAGE_SHIFT;
1884 pgoff_t index = start_index;
1885 unsigned long nr_pages = end_index - start_index + 1;
1886 unsigned long pages_processed = 0;
1887 struct page *pages[16];
1891 if (page_ops & PAGE_LOCK) {
1892 ASSERT(page_ops == PAGE_LOCK);
1893 ASSERT(processed_end && *processed_end == start);
1896 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1897 mapping_set_error(mapping, -EIO);
1899 while (nr_pages > 0) {
1902 found_pages = find_get_pages_contig(mapping, index,
1903 min_t(unsigned long,
1904 nr_pages, ARRAY_SIZE(pages)), pages);
1905 if (found_pages == 0) {
1907 * Only if we're going to lock these pages, we can find
1908 * nothing at @index.
1910 ASSERT(page_ops & PAGE_LOCK);
1915 for (i = 0; i < found_pages; i++) {
1918 process_ret = process_one_page(fs_info, mapping,
1919 pages[i], locked_page, page_ops,
1921 if (process_ret < 0) {
1922 for (; i < found_pages; i++)
1930 nr_pages -= found_pages;
1931 index += found_pages;
1935 if (err && processed_end) {
1937 * Update @processed_end. I know this is awful since it has
1938 * two different return value patterns (inclusive vs exclusive).
1940 * But the exclusive pattern is necessary if @start is 0, or we
1941 * underflow and check against processed_end won't work as
1944 if (pages_processed)
1945 *processed_end = min(end,
1946 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1948 *processed_end = start;
1953 static noinline void __unlock_for_delalloc(struct inode *inode,
1954 struct page *locked_page,
1957 unsigned long index = start >> PAGE_SHIFT;
1958 unsigned long end_index = end >> PAGE_SHIFT;
1960 ASSERT(locked_page);
1961 if (index == locked_page->index && end_index == index)
1964 __process_pages_contig(inode->i_mapping, locked_page, start, end,
1968 static noinline int lock_delalloc_pages(struct inode *inode,
1969 struct page *locked_page,
1973 unsigned long index = delalloc_start >> PAGE_SHIFT;
1974 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1975 u64 processed_end = delalloc_start;
1978 ASSERT(locked_page);
1979 if (index == locked_page->index && index == end_index)
1982 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1983 delalloc_end, PAGE_LOCK, &processed_end);
1984 if (ret == -EAGAIN && processed_end > delalloc_start)
1985 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1991 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1992 * more than @max_bytes.
1994 * @start: The original start bytenr to search.
1995 * Will store the extent range start bytenr.
1996 * @end: The original end bytenr of the search range
1997 * Will store the extent range end bytenr.
1999 * Return true if we find a delalloc range which starts inside the original
2000 * range, and @start/@end will store the delalloc range start/end.
2002 * Return false if we can't find any delalloc range which starts inside the
2003 * original range, and @start/@end will be the non-delalloc range start/end.
2006 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
2007 struct page *locked_page, u64 *start,
2010 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2011 const u64 orig_start = *start;
2012 const u64 orig_end = *end;
2013 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
2017 struct extent_state *cached_state = NULL;
2021 /* Caller should pass a valid @end to indicate the search range end */
2022 ASSERT(orig_end > orig_start);
2024 /* The range should at least cover part of the page */
2025 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
2026 orig_end <= page_offset(locked_page)));
2028 /* step one, find a bunch of delalloc bytes starting at start */
2029 delalloc_start = *start;
2031 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
2032 max_bytes, &cached_state);
2033 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
2034 *start = delalloc_start;
2036 /* @delalloc_end can be -1, never go beyond @orig_end */
2037 *end = min(delalloc_end, orig_end);
2038 free_extent_state(cached_state);
2043 * start comes from the offset of locked_page. We have to lock
2044 * pages in order, so we can't process delalloc bytes before
2047 if (delalloc_start < *start)
2048 delalloc_start = *start;
2051 * make sure to limit the number of pages we try to lock down
2053 if (delalloc_end + 1 - delalloc_start > max_bytes)
2054 delalloc_end = delalloc_start + max_bytes - 1;
2056 /* step two, lock all the pages after the page that has start */
2057 ret = lock_delalloc_pages(inode, locked_page,
2058 delalloc_start, delalloc_end);
2059 ASSERT(!ret || ret == -EAGAIN);
2060 if (ret == -EAGAIN) {
2061 /* some of the pages are gone, lets avoid looping by
2062 * shortening the size of the delalloc range we're searching
2064 free_extent_state(cached_state);
2065 cached_state = NULL;
2067 max_bytes = PAGE_SIZE;
2076 /* step three, lock the state bits for the whole range */
2077 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2079 /* then test to make sure it is all still delalloc */
2080 ret = test_range_bit(tree, delalloc_start, delalloc_end,
2081 EXTENT_DELALLOC, 1, cached_state);
2083 unlock_extent_cached(tree, delalloc_start, delalloc_end,
2085 __unlock_for_delalloc(inode, locked_page,
2086 delalloc_start, delalloc_end);
2090 free_extent_state(cached_state);
2091 *start = delalloc_start;
2092 *end = delalloc_end;
2097 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2098 struct page *locked_page,
2099 u32 clear_bits, unsigned long page_ops)
2101 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2103 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2104 start, end, page_ops, NULL);
2108 * count the number of bytes in the tree that have a given bit(s)
2109 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2110 * cached. The total number found is returned.
2112 u64 count_range_bits(struct extent_io_tree *tree,
2113 u64 *start, u64 search_end, u64 max_bytes,
2114 u32 bits, int contig)
2116 struct rb_node *node;
2117 struct extent_state *state;
2118 u64 cur_start = *start;
2119 u64 total_bytes = 0;
2123 if (WARN_ON(search_end <= cur_start))
2126 spin_lock(&tree->lock);
2127 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2128 total_bytes = tree->dirty_bytes;
2132 * this search will find all the extents that end after
2135 node = tree_search(tree, cur_start);
2140 state = rb_entry(node, struct extent_state, rb_node);
2141 if (state->start > search_end)
2143 if (contig && found && state->start > last + 1)
2145 if (state->end >= cur_start && (state->state & bits) == bits) {
2146 total_bytes += min(search_end, state->end) + 1 -
2147 max(cur_start, state->start);
2148 if (total_bytes >= max_bytes)
2151 *start = max(cur_start, state->start);
2155 } else if (contig && found) {
2158 node = rb_next(node);
2163 spin_unlock(&tree->lock);
2168 * set the private field for a given byte offset in the tree. If there isn't
2169 * an extent_state there already, this does nothing.
2171 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2172 struct io_failure_record *failrec)
2174 struct rb_node *node;
2175 struct extent_state *state;
2178 spin_lock(&tree->lock);
2180 * this search will find all the extents that end after
2183 node = tree_search(tree, start);
2188 state = rb_entry(node, struct extent_state, rb_node);
2189 if (state->start != start) {
2193 state->failrec = failrec;
2195 spin_unlock(&tree->lock);
2199 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2201 struct rb_node *node;
2202 struct extent_state *state;
2203 struct io_failure_record *failrec;
2205 spin_lock(&tree->lock);
2207 * this search will find all the extents that end after
2210 node = tree_search(tree, start);
2212 failrec = ERR_PTR(-ENOENT);
2215 state = rb_entry(node, struct extent_state, rb_node);
2216 if (state->start != start) {
2217 failrec = ERR_PTR(-ENOENT);
2221 failrec = state->failrec;
2223 spin_unlock(&tree->lock);
2228 * searches a range in the state tree for a given mask.
2229 * If 'filled' == 1, this returns 1 only if every extent in the tree
2230 * has the bits set. Otherwise, 1 is returned if any bit in the
2231 * range is found set.
2233 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2234 u32 bits, int filled, struct extent_state *cached)
2236 struct extent_state *state = NULL;
2237 struct rb_node *node;
2240 spin_lock(&tree->lock);
2241 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2242 cached->end > start)
2243 node = &cached->rb_node;
2245 node = tree_search(tree, start);
2246 while (node && start <= end) {
2247 state = rb_entry(node, struct extent_state, rb_node);
2249 if (filled && state->start > start) {
2254 if (state->start > end)
2257 if (state->state & bits) {
2261 } else if (filled) {
2266 if (state->end == (u64)-1)
2269 start = state->end + 1;
2272 node = rb_next(node);
2279 spin_unlock(&tree->lock);
2283 int free_io_failure(struct extent_io_tree *failure_tree,
2284 struct extent_io_tree *io_tree,
2285 struct io_failure_record *rec)
2290 set_state_failrec(failure_tree, rec->start, NULL);
2291 ret = clear_extent_bits(failure_tree, rec->start,
2292 rec->start + rec->len - 1,
2293 EXTENT_LOCKED | EXTENT_DIRTY);
2297 ret = clear_extent_bits(io_tree, rec->start,
2298 rec->start + rec->len - 1,
2308 * this bypasses the standard btrfs submit functions deliberately, as
2309 * the standard behavior is to write all copies in a raid setup. here we only
2310 * want to write the one bad copy. so we do the mapping for ourselves and issue
2311 * submit_bio directly.
2312 * to avoid any synchronization issues, wait for the data after writing, which
2313 * actually prevents the read that triggered the error from finishing.
2314 * currently, there can be no more than two copies of every data bit. thus,
2315 * exactly one rewrite is required.
2317 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2318 u64 length, u64 logical, struct page *page,
2319 unsigned int pg_offset, int mirror_num)
2321 struct btrfs_device *dev;
2322 struct bio_vec bvec;
2326 struct btrfs_io_context *bioc = NULL;
2329 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2330 BUG_ON(!mirror_num);
2332 if (btrfs_repair_one_zone(fs_info, logical))
2335 map_length = length;
2338 * Avoid races with device replace and make sure our bioc has devices
2339 * associated to its stripes that don't go away while we are doing the
2340 * read repair operation.
2342 btrfs_bio_counter_inc_blocked(fs_info);
2343 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2345 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2346 * to update all raid stripes, but here we just want to correct
2347 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2348 * stripe's dev and sector.
2350 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2351 &map_length, &bioc, 0);
2353 goto out_counter_dec;
2354 ASSERT(bioc->mirror_num == 1);
2356 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2357 &map_length, &bioc, mirror_num);
2359 goto out_counter_dec;
2360 BUG_ON(mirror_num != bioc->mirror_num);
2363 sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
2364 dev = bioc->stripes[bioc->mirror_num - 1].dev;
2365 btrfs_put_bioc(bioc);
2367 if (!dev || !dev->bdev ||
2368 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2370 goto out_counter_dec;
2373 bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
2374 bio.bi_iter.bi_sector = sector;
2375 __bio_add_page(&bio, page, length, pg_offset);
2377 btrfsic_check_bio(&bio);
2378 ret = submit_bio_wait(&bio);
2380 /* try to remap that extent elsewhere? */
2381 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2382 goto out_bio_uninit;
2385 btrfs_info_rl_in_rcu(fs_info,
2386 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2388 rcu_str_deref(dev->name), sector);
2394 btrfs_bio_counter_dec(fs_info);
2398 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2400 struct btrfs_fs_info *fs_info = eb->fs_info;
2401 u64 start = eb->start;
2402 int i, num_pages = num_extent_pages(eb);
2405 if (sb_rdonly(fs_info->sb))
2408 for (i = 0; i < num_pages; i++) {
2409 struct page *p = eb->pages[i];
2411 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2412 start - page_offset(p), mirror_num);
2422 * each time an IO finishes, we do a fast check in the IO failure tree
2423 * to see if we need to process or clean up an io_failure_record
2425 int clean_io_failure(struct btrfs_fs_info *fs_info,
2426 struct extent_io_tree *failure_tree,
2427 struct extent_io_tree *io_tree, u64 start,
2428 struct page *page, u64 ino, unsigned int pg_offset)
2431 struct io_failure_record *failrec;
2432 struct extent_state *state;
2437 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2442 failrec = get_state_failrec(failure_tree, start);
2443 if (IS_ERR(failrec))
2446 BUG_ON(!failrec->this_mirror);
2448 if (sb_rdonly(fs_info->sb))
2451 spin_lock(&io_tree->lock);
2452 state = find_first_extent_bit_state(io_tree,
2455 spin_unlock(&io_tree->lock);
2457 if (state && state->start <= failrec->start &&
2458 state->end >= failrec->start + failrec->len - 1) {
2459 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2461 if (num_copies > 1) {
2462 repair_io_failure(fs_info, ino, start, failrec->len,
2463 failrec->logical, page, pg_offset,
2464 failrec->failed_mirror);
2469 free_io_failure(failure_tree, io_tree, failrec);
2475 * Can be called when
2476 * - hold extent lock
2477 * - under ordered extent
2478 * - the inode is freeing
2480 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2482 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2483 struct io_failure_record *failrec;
2484 struct extent_state *state, *next;
2486 if (RB_EMPTY_ROOT(&failure_tree->state))
2489 spin_lock(&failure_tree->lock);
2490 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2492 if (state->start > end)
2495 ASSERT(state->end <= end);
2497 next = next_state(state);
2499 failrec = state->failrec;
2500 free_extent_state(state);
2505 spin_unlock(&failure_tree->lock);
2508 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2511 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2512 struct io_failure_record *failrec;
2513 struct extent_map *em;
2514 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2515 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2516 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2517 const u32 sectorsize = fs_info->sectorsize;
2521 failrec = get_state_failrec(failure_tree, start);
2522 if (!IS_ERR(failrec)) {
2523 btrfs_debug(fs_info,
2524 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2525 failrec->logical, failrec->start, failrec->len);
2527 * when data can be on disk more than twice, add to failrec here
2528 * (e.g. with a list for failed_mirror) to make
2529 * clean_io_failure() clean all those errors at once.
2535 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2537 return ERR_PTR(-ENOMEM);
2539 failrec->start = start;
2540 failrec->len = sectorsize;
2541 failrec->this_mirror = 0;
2542 failrec->compress_type = BTRFS_COMPRESS_NONE;
2544 read_lock(&em_tree->lock);
2545 em = lookup_extent_mapping(em_tree, start, failrec->len);
2547 read_unlock(&em_tree->lock);
2549 return ERR_PTR(-EIO);
2552 if (em->start > start || em->start + em->len <= start) {
2553 free_extent_map(em);
2556 read_unlock(&em_tree->lock);
2559 return ERR_PTR(-EIO);
2562 logical = start - em->start;
2563 logical = em->block_start + logical;
2564 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2565 logical = em->block_start;
2566 failrec->compress_type = em->compress_type;
2569 btrfs_debug(fs_info,
2570 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2571 logical, start, failrec->len);
2573 failrec->logical = logical;
2574 free_extent_map(em);
2576 /* Set the bits in the private failure tree */
2577 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2578 EXTENT_LOCKED | EXTENT_DIRTY);
2580 ret = set_state_failrec(failure_tree, start, failrec);
2581 /* Set the bits in the inode's tree */
2582 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2584 } else if (ret < 0) {
2586 return ERR_PTR(ret);
2592 static bool btrfs_check_repairable(struct inode *inode,
2593 struct io_failure_record *failrec,
2596 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2599 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2600 if (num_copies == 1) {
2602 * we only have a single copy of the data, so don't bother with
2603 * all the retry and error correction code that follows. no
2604 * matter what the error is, it is very likely to persist.
2606 btrfs_debug(fs_info,
2607 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2608 num_copies, failrec->this_mirror, failed_mirror);
2612 /* The failure record should only contain one sector */
2613 ASSERT(failrec->len == fs_info->sectorsize);
2616 * There are two premises:
2617 * a) deliver good data to the caller
2618 * b) correct the bad sectors on disk
2620 * Since we're only doing repair for one sector, we only need to get
2621 * a good copy of the failed sector and if we succeed, we have setup
2622 * everything for repair_io_failure to do the rest for us.
2624 ASSERT(failed_mirror);
2625 failrec->failed_mirror = failed_mirror;
2626 failrec->this_mirror++;
2627 if (failrec->this_mirror == failed_mirror)
2628 failrec->this_mirror++;
2630 if (failrec->this_mirror > num_copies) {
2631 btrfs_debug(fs_info,
2632 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2633 num_copies, failrec->this_mirror, failed_mirror);
2640 int btrfs_repair_one_sector(struct inode *inode,
2641 struct bio *failed_bio, u32 bio_offset,
2642 struct page *page, unsigned int pgoff,
2643 u64 start, int failed_mirror,
2644 submit_bio_hook_t *submit_bio_hook)
2646 struct io_failure_record *failrec;
2647 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2648 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2649 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2650 struct btrfs_bio *failed_bbio = btrfs_bio(failed_bio);
2651 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2652 struct bio *repair_bio;
2653 struct btrfs_bio *repair_bbio;
2655 btrfs_debug(fs_info,
2656 "repair read error: read error at %llu", start);
2658 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2660 failrec = btrfs_get_io_failure_record(inode, start);
2661 if (IS_ERR(failrec))
2662 return PTR_ERR(failrec);
2665 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2666 free_io_failure(failure_tree, tree, failrec);
2670 repair_bio = btrfs_bio_alloc(1);
2671 repair_bbio = btrfs_bio(repair_bio);
2672 repair_bbio->file_offset = start;
2673 repair_bio->bi_opf = REQ_OP_READ;
2674 repair_bio->bi_end_io = failed_bio->bi_end_io;
2675 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2676 repair_bio->bi_private = failed_bio->bi_private;
2678 if (failed_bbio->csum) {
2679 const u32 csum_size = fs_info->csum_size;
2681 repair_bbio->csum = repair_bbio->csum_inline;
2682 memcpy(repair_bbio->csum,
2683 failed_bbio->csum + csum_size * icsum, csum_size);
2686 bio_add_page(repair_bio, page, failrec->len, pgoff);
2687 repair_bbio->iter = repair_bio->bi_iter;
2689 btrfs_debug(btrfs_sb(inode->i_sb),
2690 "repair read error: submitting new read to mirror %d",
2691 failrec->this_mirror);
2694 * At this point we have a bio, so any errors from submit_bio_hook()
2695 * will be handled by the endio on the repair_bio, so we can't return an
2698 submit_bio_hook(inode, repair_bio, failrec->this_mirror, failrec->compress_type);
2702 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2704 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2706 ASSERT(page_offset(page) <= start &&
2707 start + len <= page_offset(page) + PAGE_SIZE);
2710 if (fsverity_active(page->mapping->host) &&
2712 !PageUptodate(page) &&
2713 start < i_size_read(page->mapping->host) &&
2714 !fsverity_verify_page(page)) {
2715 btrfs_page_set_error(fs_info, page, start, len);
2717 btrfs_page_set_uptodate(fs_info, page, start, len);
2720 btrfs_page_clear_uptodate(fs_info, page, start, len);
2721 btrfs_page_set_error(fs_info, page, start, len);
2724 if (!btrfs_is_subpage(fs_info, page))
2727 btrfs_subpage_end_reader(fs_info, page, start, len);
2730 static blk_status_t submit_data_read_repair(struct inode *inode,
2731 struct bio *failed_bio,
2732 u32 bio_offset, struct page *page,
2736 unsigned int error_bitmap)
2738 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2739 const u32 sectorsize = fs_info->sectorsize;
2740 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2744 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2746 /* This repair is only for data */
2747 ASSERT(is_data_inode(inode));
2749 /* We're here because we had some read errors or csum mismatch */
2750 ASSERT(error_bitmap);
2753 * We only get called on buffered IO, thus page must be mapped and bio
2754 * must not be cloned.
2756 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2758 /* Iterate through all the sectors in the range */
2759 for (i = 0; i < nr_bits; i++) {
2760 const unsigned int offset = i * sectorsize;
2761 struct extent_state *cached = NULL;
2762 bool uptodate = false;
2765 if (!(error_bitmap & (1U << i))) {
2767 * This sector has no error, just end the page read
2768 * and unlock the range.
2774 ret = btrfs_repair_one_sector(inode, failed_bio,
2775 bio_offset + offset,
2776 page, pgoff + offset, start + offset,
2777 failed_mirror, btrfs_submit_data_bio);
2780 * We have submitted the read repair, the page release
2781 * will be handled by the endio function of the
2782 * submitted repair bio.
2783 * Thus we don't need to do any thing here.
2788 * Repair failed, just record the error but still continue.
2789 * Or the remaining sectors will not be properly unlocked.
2794 end_page_read(page, uptodate, start + offset, sectorsize);
2796 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2798 start + offset + sectorsize - 1,
2799 &cached, GFP_ATOMIC);
2800 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2802 start + offset + sectorsize - 1,
2805 return errno_to_blk_status(error);
2808 /* lots and lots of room for performance fixes in the end_bio funcs */
2810 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2812 struct btrfs_inode *inode;
2813 const bool uptodate = (err == 0);
2816 ASSERT(page && page->mapping);
2817 inode = BTRFS_I(page->mapping->host);
2818 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2821 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
2824 ASSERT(end + 1 - start <= U32_MAX);
2825 len = end + 1 - start;
2827 btrfs_page_clear_uptodate(fs_info, page, start, len);
2828 btrfs_page_set_error(fs_info, page, start, len);
2829 ret = err < 0 ? err : -EIO;
2830 mapping_set_error(page->mapping, ret);
2835 * after a writepage IO is done, we need to:
2836 * clear the uptodate bits on error
2837 * clear the writeback bits in the extent tree for this IO
2838 * end_page_writeback if the page has no more pending IO
2840 * Scheduling is not allowed, so the extent state tree is expected
2841 * to have one and only one object corresponding to this IO.
2843 static void end_bio_extent_writepage(struct bio *bio)
2845 int error = blk_status_to_errno(bio->bi_status);
2846 struct bio_vec *bvec;
2849 struct bvec_iter_all iter_all;
2850 bool first_bvec = true;
2852 ASSERT(!bio_flagged(bio, BIO_CLONED));
2853 bio_for_each_segment_all(bvec, bio, iter_all) {
2854 struct page *page = bvec->bv_page;
2855 struct inode *inode = page->mapping->host;
2856 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2857 const u32 sectorsize = fs_info->sectorsize;
2859 /* Our read/write should always be sector aligned. */
2860 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2862 "partial page write in btrfs with offset %u and length %u",
2863 bvec->bv_offset, bvec->bv_len);
2864 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2866 "incomplete page write with offset %u and length %u",
2867 bvec->bv_offset, bvec->bv_len);
2869 start = page_offset(page) + bvec->bv_offset;
2870 end = start + bvec->bv_len - 1;
2873 btrfs_record_physical_zoned(inode, start, bio);
2877 end_extent_writepage(page, error, start, end);
2879 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2886 * Record previously processed extent range
2888 * For endio_readpage_release_extent() to handle a full extent range, reducing
2889 * the extent io operations.
2891 struct processed_extent {
2892 struct btrfs_inode *inode;
2893 /* Start of the range in @inode */
2895 /* End of the range in @inode */
2901 * Try to release processed extent range
2903 * May not release the extent range right now if the current range is
2904 * contiguous to processed extent.
2906 * Will release processed extent when any of @inode, @uptodate, the range is
2907 * no longer contiguous to the processed range.
2909 * Passing @inode == NULL will force processed extent to be released.
2911 static void endio_readpage_release_extent(struct processed_extent *processed,
2912 struct btrfs_inode *inode, u64 start, u64 end,
2915 struct extent_state *cached = NULL;
2916 struct extent_io_tree *tree;
2918 /* The first extent, initialize @processed */
2919 if (!processed->inode)
2923 * Contiguous to processed extent, just uptodate the end.
2925 * Several things to notice:
2927 * - bio can be merged as long as on-disk bytenr is contiguous
2928 * This means we can have page belonging to other inodes, thus need to
2929 * check if the inode still matches.
2930 * - bvec can contain range beyond current page for multi-page bvec
2931 * Thus we need to do processed->end + 1 >= start check
2933 if (processed->inode == inode && processed->uptodate == uptodate &&
2934 processed->end + 1 >= start && end >= processed->end) {
2935 processed->end = end;
2939 tree = &processed->inode->io_tree;
2941 * Now we don't have range contiguous to the processed range, release
2942 * the processed range now.
2944 if (processed->uptodate && tree->track_uptodate)
2945 set_extent_uptodate(tree, processed->start, processed->end,
2946 &cached, GFP_ATOMIC);
2947 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2951 /* Update processed to current range */
2952 processed->inode = inode;
2953 processed->start = start;
2954 processed->end = end;
2955 processed->uptodate = uptodate;
2958 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2960 ASSERT(PageLocked(page));
2961 if (!btrfs_is_subpage(fs_info, page))
2964 ASSERT(PagePrivate(page));
2965 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2969 * Find extent buffer for a givne bytenr.
2971 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2974 static struct extent_buffer *find_extent_buffer_readpage(
2975 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2977 struct extent_buffer *eb;
2980 * For regular sectorsize, we can use page->private to grab extent
2983 if (fs_info->nodesize >= PAGE_SIZE) {
2984 ASSERT(PagePrivate(page) && page->private);
2985 return (struct extent_buffer *)page->private;
2988 /* For subpage case, we need to lookup buffer radix tree */
2990 eb = radix_tree_lookup(&fs_info->buffer_radix,
2991 bytenr >> fs_info->sectorsize_bits);
2998 * after a readpage IO is done, we need to:
2999 * clear the uptodate bits on error
3000 * set the uptodate bits if things worked
3001 * set the page up to date if all extents in the tree are uptodate
3002 * clear the lock bit in the extent tree
3003 * unlock the page if there are no other extents locked for it
3005 * Scheduling is not allowed, so the extent state tree is expected
3006 * to have one and only one object corresponding to this IO.
3008 static void end_bio_extent_readpage(struct bio *bio)
3010 struct bio_vec *bvec;
3011 struct btrfs_bio *bbio = btrfs_bio(bio);
3012 struct extent_io_tree *tree, *failure_tree;
3013 struct processed_extent processed = { 0 };
3015 * The offset to the beginning of a bio, since one bio can never be
3016 * larger than UINT_MAX, u32 here is enough.
3021 struct bvec_iter_all iter_all;
3023 ASSERT(!bio_flagged(bio, BIO_CLONED));
3024 bio_for_each_segment_all(bvec, bio, iter_all) {
3025 bool uptodate = !bio->bi_status;
3026 struct page *page = bvec->bv_page;
3027 struct inode *inode = page->mapping->host;
3028 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3029 const u32 sectorsize = fs_info->sectorsize;
3030 unsigned int error_bitmap = (unsigned int)-1;
3035 btrfs_debug(fs_info,
3036 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3037 bio->bi_iter.bi_sector, bio->bi_status,
3039 tree = &BTRFS_I(inode)->io_tree;
3040 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3043 * We always issue full-sector reads, but if some block in a
3044 * page fails to read, blk_update_request() will advance
3045 * bv_offset and adjust bv_len to compensate. Print a warning
3046 * for unaligned offsets, and an error if they don't add up to
3049 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3051 "partial page read in btrfs with offset %u and length %u",
3052 bvec->bv_offset, bvec->bv_len);
3053 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3056 "incomplete page read with offset %u and length %u",
3057 bvec->bv_offset, bvec->bv_len);
3059 start = page_offset(page) + bvec->bv_offset;
3060 end = start + bvec->bv_len - 1;
3063 mirror = bbio->mirror_num;
3064 if (likely(uptodate)) {
3065 if (is_data_inode(inode)) {
3066 error_bitmap = btrfs_verify_data_csum(bbio,
3067 bio_offset, page, start, end);
3070 ret = btrfs_validate_metadata_buffer(bbio,
3071 page, start, end, mirror);
3076 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3077 failure_tree, tree, start,
3079 btrfs_ino(BTRFS_I(inode)), 0);
3082 if (likely(uptodate))
3085 if (is_data_inode(inode)) {
3087 * If we failed to submit the IO at all we'll have a
3088 * mirror_num == 0, in which case we need to just mark
3089 * the page with an error and unlock it and carry on.
3095 * submit_data_read_repair() will handle all the good
3096 * and bad sectors, we just continue to the next bvec.
3098 submit_data_read_repair(inode, bio, bio_offset, page,
3099 start - page_offset(page),
3103 ASSERT(bio_offset + len > bio_offset);
3107 struct extent_buffer *eb;
3109 eb = find_extent_buffer_readpage(fs_info, page, start);
3110 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3111 eb->read_mirror = mirror;
3112 atomic_dec(&eb->io_pages);
3115 if (likely(uptodate)) {
3116 loff_t i_size = i_size_read(inode);
3117 pgoff_t end_index = i_size >> PAGE_SHIFT;
3120 * Zero out the remaining part if this range straddles
3123 * Here we should only zero the range inside the bvec,
3124 * not touch anything else.
3126 * NOTE: i_size is exclusive while end is inclusive.
3128 if (page->index == end_index && i_size <= end) {
3129 u32 zero_start = max(offset_in_page(i_size),
3130 offset_in_page(start));
3132 zero_user_segment(page, zero_start,
3133 offset_in_page(end) + 1);
3136 ASSERT(bio_offset + len > bio_offset);
3139 /* Update page status and unlock */
3140 end_page_read(page, uptodate, start, len);
3141 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3142 start, end, PageUptodate(page));
3144 /* Release the last extent */
3145 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3146 btrfs_bio_free_csum(bbio);
3151 * Populate every free slot in a provided array with pages.
3153 * @nr_pages: number of pages to allocate
3154 * @page_array: the array to fill with pages; any existing non-null entries in
3155 * the array will be skipped
3157 * Return: 0 if all pages were able to be allocated;
3158 * -ENOMEM otherwise, and the caller is responsible for freeing all
3159 * non-null page pointers in the array.
3161 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
3163 unsigned int allocated;
3165 for (allocated = 0; allocated < nr_pages;) {
3166 unsigned int last = allocated;
3168 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
3170 if (allocated == nr_pages)
3174 * During this iteration, no page could be allocated, even
3175 * though alloc_pages_bulk_array() falls back to alloc_page()
3176 * if it could not bulk-allocate. So we must be out of memory.
3178 if (allocated == last)
3181 memalloc_retry_wait(GFP_NOFS);
3187 * Initialize the members up to but not including 'bio'. Use after allocating a
3188 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3189 * 'bio' because use of __GFP_ZERO is not supported.
3191 static inline void btrfs_bio_init(struct btrfs_bio *bbio)
3193 memset(bbio, 0, offsetof(struct btrfs_bio, bio));
3197 * Allocate a btrfs_io_bio, with @nr_iovecs as maximum number of iovecs.
3199 * The bio allocation is backed by bioset and does not fail.
3201 struct bio *btrfs_bio_alloc(unsigned int nr_iovecs)
3205 ASSERT(0 < nr_iovecs && nr_iovecs <= BIO_MAX_VECS);
3206 bio = bio_alloc_bioset(NULL, nr_iovecs, 0, GFP_NOFS, &btrfs_bioset);
3207 btrfs_bio_init(btrfs_bio(bio));
3211 struct bio *btrfs_bio_clone(struct block_device *bdev, struct bio *bio)
3213 struct btrfs_bio *bbio;
3216 /* Bio allocation backed by a bioset does not fail */
3217 new = bio_alloc_clone(bdev, bio, GFP_NOFS, &btrfs_bioset);
3218 bbio = btrfs_bio(new);
3219 btrfs_bio_init(bbio);
3220 bbio->iter = bio->bi_iter;
3224 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
3227 struct btrfs_bio *bbio;
3229 ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
3231 /* this will never fail when it's backed by a bioset */
3232 bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
3235 bbio = btrfs_bio(bio);
3236 btrfs_bio_init(bbio);
3238 bio_trim(bio, offset >> 9, size >> 9);
3239 bbio->iter = bio->bi_iter;
3244 * Attempt to add a page to bio
3246 * @bio_ctrl: record both the bio, and its bio_flags
3247 * @page: page to add to the bio
3248 * @disk_bytenr: offset of the new bio or to check whether we are adding
3249 * a contiguous page to the previous one
3250 * @size: portion of page that we want to write
3251 * @pg_offset: starting offset in the page
3252 * @compress_type: compression type of the current bio to see if we can merge them
3254 * Attempt to add a page to bio considering stripe alignment etc.
3256 * Return >= 0 for the number of bytes added to the bio.
3257 * Can return 0 if the current bio is already at stripe/zone boundary.
3258 * Return <0 for error.
3260 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3262 u64 disk_bytenr, unsigned int size,
3263 unsigned int pg_offset,
3264 enum btrfs_compression_type compress_type)
3266 struct bio *bio = bio_ctrl->bio;
3267 u32 bio_size = bio->bi_iter.bi_size;
3269 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3274 /* The limit should be calculated when bio_ctrl->bio is allocated */
3275 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3276 if (bio_ctrl->compress_type != compress_type)
3279 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
3280 contig = bio->bi_iter.bi_sector == sector;
3282 contig = bio_end_sector(bio) == sector;
3286 real_size = min(bio_ctrl->len_to_oe_boundary,
3287 bio_ctrl->len_to_stripe_boundary) - bio_size;
3288 real_size = min(real_size, size);
3291 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
3292 * bio will still execute its endio function on the page!
3297 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3298 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
3300 ret = bio_add_page(bio, page, real_size, pg_offset);
3305 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3306 struct btrfs_inode *inode, u64 file_offset)
3308 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3309 struct btrfs_io_geometry geom;
3310 struct btrfs_ordered_extent *ordered;
3311 struct extent_map *em;
3312 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3316 * Pages for compressed extent are never submitted to disk directly,
3317 * thus it has no real boundary, just set them to U32_MAX.
3319 * The split happens for real compressed bio, which happens in
3320 * btrfs_submit_compressed_read/write().
3322 if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
3323 bio_ctrl->len_to_oe_boundary = U32_MAX;
3324 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3327 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3330 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3332 free_extent_map(em);
3336 if (geom.len > U32_MAX)
3337 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3339 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3341 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3342 bio_ctrl->len_to_oe_boundary = U32_MAX;
3346 /* Ordered extent not yet created, so we're good */
3347 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
3349 bio_ctrl->len_to_oe_boundary = U32_MAX;
3353 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3354 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3355 btrfs_put_ordered_extent(ordered);
3359 static int alloc_new_bio(struct btrfs_inode *inode,
3360 struct btrfs_bio_ctrl *bio_ctrl,
3361 struct writeback_control *wbc,
3363 bio_end_io_t end_io_func,
3364 u64 disk_bytenr, u32 offset, u64 file_offset,
3365 enum btrfs_compression_type compress_type)
3367 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3371 bio = btrfs_bio_alloc(BIO_MAX_VECS);
3373 * For compressed page range, its disk_bytenr is always @disk_bytenr
3374 * passed in, no matter if we have added any range into previous bio.
3376 if (compress_type != BTRFS_COMPRESS_NONE)
3377 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
3379 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
3380 bio_ctrl->bio = bio;
3381 bio_ctrl->compress_type = compress_type;
3382 bio->bi_end_io = end_io_func;
3383 bio->bi_private = &inode->io_tree;
3385 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
3391 * For Zone append we need the correct block_device that we are
3392 * going to write to set in the bio to be able to respect the
3393 * hardware limitation. Look it up here:
3395 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3396 struct btrfs_device *dev;
3398 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
3399 fs_info->sectorsize);
3405 bio_set_dev(bio, dev->bdev);
3408 * Otherwise pick the last added device to support
3409 * cgroup writeback. For multi-device file systems this
3410 * means blk-cgroup policies have to always be set on the
3411 * last added/replaced device. This is a bit odd but has
3412 * been like that for a long time.
3414 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
3416 wbc_init_bio(wbc, bio);
3418 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
3422 bio_ctrl->bio = NULL;
3423 bio->bi_status = errno_to_blk_status(ret);
3429 * @opf: bio REQ_OP_* and REQ_* flags as one value
3430 * @wbc: optional writeback control for io accounting
3431 * @page: page to add to the bio
3432 * @disk_bytenr: logical bytenr where the write will be
3433 * @size: portion of page that we want to write to
3434 * @pg_offset: offset of the new bio or to check whether we are adding
3435 * a contiguous page to the previous one
3436 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3437 * @end_io_func: end_io callback for new bio
3438 * @mirror_num: desired mirror to read/write
3439 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3440 * @compress_type: compress type for current bio
3442 static int submit_extent_page(unsigned int opf,
3443 struct writeback_control *wbc,
3444 struct btrfs_bio_ctrl *bio_ctrl,
3445 struct page *page, u64 disk_bytenr,
3446 size_t size, unsigned long pg_offset,
3447 bio_end_io_t end_io_func,
3449 enum btrfs_compression_type compress_type,
3450 bool force_bio_submit)
3453 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3454 unsigned int cur = pg_offset;
3458 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3459 pg_offset + size <= PAGE_SIZE);
3460 if (force_bio_submit && bio_ctrl->bio) {
3461 submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->compress_type);
3462 bio_ctrl->bio = NULL;
3465 while (cur < pg_offset + size) {
3466 u32 offset = cur - pg_offset;
3469 /* Allocate new bio if needed */
3470 if (!bio_ctrl->bio) {
3471 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
3472 end_io_func, disk_bytenr, offset,
3473 page_offset(page) + cur,
3479 * We must go through btrfs_bio_add_page() to ensure each
3480 * page range won't cross various boundaries.
3482 if (compress_type != BTRFS_COMPRESS_NONE)
3483 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
3484 size - offset, pg_offset + offset,
3487 added = btrfs_bio_add_page(bio_ctrl, page,
3488 disk_bytenr + offset, size - offset,
3489 pg_offset + offset, compress_type);
3491 /* Metadata page range should never be split */
3492 if (!is_data_inode(&inode->vfs_inode))
3493 ASSERT(added == 0 || added == size - offset);
3495 /* At least we added some page, update the account */
3497 wbc_account_cgroup_owner(wbc, page, added);
3499 /* We have reached boundary, submit right now */
3500 if (added < size - offset) {
3501 /* The bio should contain some page(s) */
3502 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
3503 submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->compress_type);
3504 bio_ctrl->bio = NULL;
3511 static int attach_extent_buffer_page(struct extent_buffer *eb,
3513 struct btrfs_subpage *prealloc)
3515 struct btrfs_fs_info *fs_info = eb->fs_info;
3519 * If the page is mapped to btree inode, we should hold the private
3520 * lock to prevent race.
3521 * For cloned or dummy extent buffers, their pages are not mapped and
3522 * will not race with any other ebs.
3525 lockdep_assert_held(&page->mapping->private_lock);
3527 if (fs_info->nodesize >= PAGE_SIZE) {
3528 if (!PagePrivate(page))
3529 attach_page_private(page, eb);
3531 WARN_ON(page->private != (unsigned long)eb);
3535 /* Already mapped, just free prealloc */
3536 if (PagePrivate(page)) {
3537 btrfs_free_subpage(prealloc);
3542 /* Has preallocated memory for subpage */
3543 attach_page_private(page, prealloc);
3545 /* Do new allocation to attach subpage */
3546 ret = btrfs_attach_subpage(fs_info, page,
3547 BTRFS_SUBPAGE_METADATA);
3551 int set_page_extent_mapped(struct page *page)
3553 struct btrfs_fs_info *fs_info;
3555 ASSERT(page->mapping);
3557 if (PagePrivate(page))
3560 fs_info = btrfs_sb(page->mapping->host->i_sb);
3562 if (btrfs_is_subpage(fs_info, page))
3563 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3565 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3569 void clear_page_extent_mapped(struct page *page)
3571 struct btrfs_fs_info *fs_info;
3573 ASSERT(page->mapping);
3575 if (!PagePrivate(page))
3578 fs_info = btrfs_sb(page->mapping->host->i_sb);
3579 if (btrfs_is_subpage(fs_info, page))
3580 return btrfs_detach_subpage(fs_info, page);
3582 detach_page_private(page);
3585 static struct extent_map *
3586 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3587 u64 start, u64 len, struct extent_map **em_cached)
3589 struct extent_map *em;
3591 if (em_cached && *em_cached) {
3593 if (extent_map_in_tree(em) && start >= em->start &&
3594 start < extent_map_end(em)) {
3595 refcount_inc(&em->refs);
3599 free_extent_map(em);
3603 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3604 if (em_cached && !IS_ERR(em)) {
3606 refcount_inc(&em->refs);
3612 * basic readpage implementation. Locked extent state structs are inserted
3613 * into the tree that are removed when the IO is done (by the end_io
3615 * XXX JDM: This needs looking at to ensure proper page locking
3616 * return 0 on success, otherwise return error
3618 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3619 struct btrfs_bio_ctrl *bio_ctrl,
3620 unsigned int read_flags, u64 *prev_em_start)
3622 struct inode *inode = page->mapping->host;
3623 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3624 u64 start = page_offset(page);
3625 const u64 end = start + PAGE_SIZE - 1;
3628 u64 last_byte = i_size_read(inode);
3631 struct extent_map *em;
3633 size_t pg_offset = 0;
3635 size_t blocksize = inode->i_sb->s_blocksize;
3636 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3638 ret = set_page_extent_mapped(page);
3640 unlock_extent(tree, start, end);
3641 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3646 if (page->index == last_byte >> PAGE_SHIFT) {
3647 size_t zero_offset = offset_in_page(last_byte);
3650 iosize = PAGE_SIZE - zero_offset;
3651 memzero_page(page, zero_offset, iosize);
3652 flush_dcache_page(page);
3655 begin_page_read(fs_info, page);
3656 while (cur <= end) {
3657 unsigned long this_bio_flag = 0;
3658 bool force_bio_submit = false;
3661 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
3662 if (cur >= last_byte) {
3663 struct extent_state *cached = NULL;
3665 iosize = PAGE_SIZE - pg_offset;
3666 memzero_page(page, pg_offset, iosize);
3667 flush_dcache_page(page);
3668 set_extent_uptodate(tree, cur, cur + iosize - 1,
3670 unlock_extent_cached(tree, cur,
3671 cur + iosize - 1, &cached);
3672 end_page_read(page, true, cur, iosize);
3675 em = __get_extent_map(inode, page, pg_offset, cur,
3676 end - cur + 1, em_cached);
3678 unlock_extent(tree, cur, end);
3679 end_page_read(page, false, cur, end + 1 - cur);
3683 extent_offset = cur - em->start;
3684 BUG_ON(extent_map_end(em) <= cur);
3687 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
3688 this_bio_flag = em->compress_type;
3690 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3691 cur_end = min(extent_map_end(em) - 1, end);
3692 iosize = ALIGN(iosize, blocksize);
3693 if (this_bio_flag != BTRFS_COMPRESS_NONE)
3694 disk_bytenr = em->block_start;
3696 disk_bytenr = em->block_start + extent_offset;
3697 block_start = em->block_start;
3698 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3699 block_start = EXTENT_MAP_HOLE;
3702 * If we have a file range that points to a compressed extent
3703 * and it's followed by a consecutive file range that points
3704 * to the same compressed extent (possibly with a different
3705 * offset and/or length, so it either points to the whole extent
3706 * or only part of it), we must make sure we do not submit a
3707 * single bio to populate the pages for the 2 ranges because
3708 * this makes the compressed extent read zero out the pages
3709 * belonging to the 2nd range. Imagine the following scenario:
3712 * [0 - 8K] [8K - 24K]
3715 * points to extent X, points to extent X,
3716 * offset 4K, length of 8K offset 0, length 16K
3718 * [extent X, compressed length = 4K uncompressed length = 16K]
3720 * If the bio to read the compressed extent covers both ranges,
3721 * it will decompress extent X into the pages belonging to the
3722 * first range and then it will stop, zeroing out the remaining
3723 * pages that belong to the other range that points to extent X.
3724 * So here we make sure we submit 2 bios, one for the first
3725 * range and another one for the third range. Both will target
3726 * the same physical extent from disk, but we can't currently
3727 * make the compressed bio endio callback populate the pages
3728 * for both ranges because each compressed bio is tightly
3729 * coupled with a single extent map, and each range can have
3730 * an extent map with a different offset value relative to the
3731 * uncompressed data of our extent and different lengths. This
3732 * is a corner case so we prioritize correctness over
3733 * non-optimal behavior (submitting 2 bios for the same extent).
3735 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3736 prev_em_start && *prev_em_start != (u64)-1 &&
3737 *prev_em_start != em->start)
3738 force_bio_submit = true;
3741 *prev_em_start = em->start;
3743 free_extent_map(em);
3746 /* we've found a hole, just zero and go on */
3747 if (block_start == EXTENT_MAP_HOLE) {
3748 struct extent_state *cached = NULL;
3750 memzero_page(page, pg_offset, iosize);
3751 flush_dcache_page(page);
3753 set_extent_uptodate(tree, cur, cur + iosize - 1,
3755 unlock_extent_cached(tree, cur,
3756 cur + iosize - 1, &cached);
3757 end_page_read(page, true, cur, iosize);
3759 pg_offset += iosize;
3762 /* the get_extent function already copied into the page */
3763 if (test_range_bit(tree, cur, cur_end,
3764 EXTENT_UPTODATE, 1, NULL)) {
3765 unlock_extent(tree, cur, cur + iosize - 1);
3766 end_page_read(page, true, cur, iosize);
3768 pg_offset += iosize;
3771 /* we have an inline extent but it didn't get marked up
3772 * to date. Error out
3774 if (block_start == EXTENT_MAP_INLINE) {
3775 unlock_extent(tree, cur, cur + iosize - 1);
3776 end_page_read(page, false, cur, iosize);
3778 pg_offset += iosize;
3782 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3783 bio_ctrl, page, disk_bytenr, iosize,
3785 end_bio_extent_readpage, 0,
3790 * We have to unlock the remaining range, or the page
3791 * will never be unlocked.
3793 unlock_extent(tree, cur, end);
3794 end_page_read(page, false, cur, end + 1 - cur);
3798 pg_offset += iosize;
3804 int btrfs_read_folio(struct file *file, struct folio *folio)
3806 struct page *page = &folio->page;
3807 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3808 u64 start = page_offset(page);
3809 u64 end = start + PAGE_SIZE - 1;
3810 struct btrfs_bio_ctrl bio_ctrl = { 0 };
3813 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3815 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
3817 * If btrfs_do_readpage() failed we will want to submit the assembled
3818 * bio to do the cleanup.
3821 submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.compress_type);
3825 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3827 struct extent_map **em_cached,
3828 struct btrfs_bio_ctrl *bio_ctrl,
3831 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3834 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3836 for (index = 0; index < nr_pages; index++) {
3837 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3838 REQ_RAHEAD, prev_em_start);
3839 put_page(pages[index]);
3844 * helper for __extent_writepage, doing all of the delayed allocation setup.
3846 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3847 * to write the page (copy into inline extent). In this case the IO has
3848 * been started and the page is already unlocked.
3850 * This returns 0 if all went well (page still locked)
3851 * This returns < 0 if there were errors (page still locked)
3853 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3854 struct page *page, struct writeback_control *wbc)
3856 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
3857 u64 delalloc_start = page_offset(page);
3858 u64 delalloc_to_write = 0;
3859 /* How many pages are started by btrfs_run_delalloc_range() */
3860 unsigned long nr_written = 0;
3862 int page_started = 0;
3864 while (delalloc_start < page_end) {
3865 u64 delalloc_end = page_end;
3868 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3872 delalloc_start = delalloc_end + 1;
3875 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3876 delalloc_end, &page_started, &nr_written, wbc);
3878 btrfs_page_set_error(inode->root->fs_info, page,
3879 page_offset(page), PAGE_SIZE);
3883 * delalloc_end is already one less than the total length, so
3884 * we don't subtract one from PAGE_SIZE
3886 delalloc_to_write += (delalloc_end - delalloc_start +
3887 PAGE_SIZE) >> PAGE_SHIFT;
3888 delalloc_start = delalloc_end + 1;
3890 if (wbc->nr_to_write < delalloc_to_write) {
3893 if (delalloc_to_write < thresh * 2)
3894 thresh = delalloc_to_write;
3895 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3899 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
3902 * We've unlocked the page, so we can't update the mapping's
3903 * writeback index, just update nr_to_write.
3905 wbc->nr_to_write -= nr_written;
3913 * Find the first byte we need to write.
3915 * For subpage, one page can contain several sectors, and
3916 * __extent_writepage_io() will just grab all extent maps in the page
3917 * range and try to submit all non-inline/non-compressed extents.
3919 * This is a big problem for subpage, we shouldn't re-submit already written
3921 * This function will lookup subpage dirty bit to find which range we really
3924 * Return the next dirty range in [@start, @end).
3925 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
3927 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
3928 struct page *page, u64 *start, u64 *end)
3930 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
3931 struct btrfs_subpage_info *spi = fs_info->subpage_info;
3932 u64 orig_start = *start;
3933 /* Declare as unsigned long so we can use bitmap ops */
3934 unsigned long flags;
3935 int range_start_bit;
3939 * For regular sector size == page size case, since one page only
3940 * contains one sector, we return the page offset directly.
3942 if (!btrfs_is_subpage(fs_info, page)) {
3943 *start = page_offset(page);
3944 *end = page_offset(page) + PAGE_SIZE;
3948 range_start_bit = spi->dirty_offset +
3949 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
3951 /* We should have the page locked, but just in case */
3952 spin_lock_irqsave(&subpage->lock, flags);
3953 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
3954 spi->dirty_offset + spi->bitmap_nr_bits);
3955 spin_unlock_irqrestore(&subpage->lock, flags);
3957 range_start_bit -= spi->dirty_offset;
3958 range_end_bit -= spi->dirty_offset;
3960 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
3961 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
3965 * helper for __extent_writepage. This calls the writepage start hooks,
3966 * and does the loop to map the page into extents and bios.
3968 * We return 1 if the IO is started and the page is unlocked,
3969 * 0 if all went well (page still locked)
3970 * < 0 if there were errors (page still locked)
3972 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3974 struct writeback_control *wbc,
3975 struct extent_page_data *epd,
3979 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3980 u64 cur = page_offset(page);
3981 u64 end = cur + PAGE_SIZE - 1;
3984 struct extent_map *em;
3988 u32 opf = REQ_OP_WRITE;
3989 const unsigned int write_flags = wbc_to_write_flags(wbc);
3990 bool has_error = false;
3993 ret = btrfs_writepage_cow_fixup(page);
3995 /* Fixup worker will requeue */
3996 redirty_page_for_writepage(wbc, page);
4002 * we don't want to touch the inode after unlocking the page,
4003 * so we update the mapping writeback index now
4007 while (cur <= end) {
4010 u64 dirty_range_start = cur;
4011 u64 dirty_range_end;
4014 if (cur >= i_size) {
4015 btrfs_writepage_endio_finish_ordered(inode, page, cur,
4018 * This range is beyond i_size, thus we don't need to
4019 * bother writing back.
4020 * But we still need to clear the dirty subpage bit, or
4021 * the next time the page gets dirtied, we will try to
4022 * writeback the sectors with subpage dirty bits,
4023 * causing writeback without ordered extent.
4025 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
4029 find_next_dirty_byte(fs_info, page, &dirty_range_start,
4031 if (cur < dirty_range_start) {
4032 cur = dirty_range_start;
4036 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
4038 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
4039 ret = PTR_ERR_OR_ZERO(em);
4046 extent_offset = cur - em->start;
4047 em_end = extent_map_end(em);
4048 ASSERT(cur <= em_end);
4050 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
4051 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
4052 block_start = em->block_start;
4053 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4054 disk_bytenr = em->block_start + extent_offset;
4057 * Note that em_end from extent_map_end() and dirty_range_end from
4058 * find_next_dirty_byte() are all exclusive
4060 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
4062 if (btrfs_use_zone_append(inode, em->block_start))
4063 opf = REQ_OP_ZONE_APPEND;
4065 free_extent_map(em);
4069 * compressed and inline extents are written through other
4072 if (compressed || block_start == EXTENT_MAP_HOLE ||
4073 block_start == EXTENT_MAP_INLINE) {
4077 btrfs_writepage_endio_finish_ordered(inode,
4078 page, cur, cur + iosize - 1, true);
4079 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4084 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
4085 if (!PageWriteback(page)) {
4086 btrfs_err(inode->root->fs_info,
4087 "page %lu not writeback, cur %llu end %llu",
4088 page->index, cur, end);
4092 * Although the PageDirty bit is cleared before entering this
4093 * function, subpage dirty bit is not cleared.
4094 * So clear subpage dirty bit here so next time we won't submit
4095 * page for range already written to disk.
4097 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4099 ret = submit_extent_page(opf | write_flags, wbc,
4100 &epd->bio_ctrl, page,
4101 disk_bytenr, iosize,
4102 cur - page_offset(page),
4103 end_bio_extent_writepage,
4110 btrfs_page_set_error(fs_info, page, cur, iosize);
4111 if (PageWriteback(page))
4112 btrfs_page_clear_writeback(fs_info, page, cur,
4120 * If we finish without problem, we should not only clear page dirty,
4121 * but also empty subpage dirty bits
4124 btrfs_page_assert_not_dirty(fs_info, page);
4132 * the writepage semantics are similar to regular writepage. extent
4133 * records are inserted to lock ranges in the tree, and as dirty areas
4134 * are found, they are marked writeback. Then the lock bits are removed
4135 * and the end_io handler clears the writeback ranges
4137 * Return 0 if everything goes well.
4138 * Return <0 for error.
4140 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
4141 struct extent_page_data *epd)
4143 struct folio *folio = page_folio(page);
4144 struct inode *inode = page->mapping->host;
4145 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4146 const u64 page_start = page_offset(page);
4147 const u64 page_end = page_start + PAGE_SIZE - 1;
4151 loff_t i_size = i_size_read(inode);
4152 unsigned long end_index = i_size >> PAGE_SHIFT;
4154 trace___extent_writepage(page, inode, wbc);
4156 WARN_ON(!PageLocked(page));
4158 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
4159 page_offset(page), PAGE_SIZE);
4161 pg_offset = offset_in_page(i_size);
4162 if (page->index > end_index ||
4163 (page->index == end_index && !pg_offset)) {
4164 folio_invalidate(folio, 0, folio_size(folio));
4165 folio_unlock(folio);
4169 if (page->index == end_index) {
4170 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
4171 flush_dcache_page(page);
4174 ret = set_page_extent_mapped(page);
4180 if (!epd->extent_locked) {
4181 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
4188 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
4195 /* make sure the mapping tag for page dirty gets cleared */
4196 set_page_writeback(page);
4197 end_page_writeback(page);
4200 * Here we used to have a check for PageError() and then set @ret and
4201 * call end_extent_writepage().
4203 * But in fact setting @ret here will cause different error paths
4204 * between subpage and regular sectorsize.
4206 * For regular page size, we never submit current page, but only add
4207 * current page to current bio.
4208 * The bio submission can only happen in next page.
4209 * Thus if we hit the PageError() branch, @ret is already set to
4210 * non-zero value and will not get updated for regular sectorsize.
4212 * But for subpage case, it's possible we submit part of current page,
4213 * thus can get PageError() set by submitted bio of the same page,
4214 * while our @ret is still 0.
4216 * So here we unify the behavior and don't set @ret.
4217 * Error can still be properly passed to higher layer as page will
4218 * be set error, here we just don't handle the IO failure.
4220 * NOTE: This is just a hotfix for subpage.
4221 * The root fix will be properly ending ordered extent when we hit
4222 * an error during writeback.
4224 * But that needs a bigger refactoring, as we not only need to grab the
4225 * submitted OE, but also need to know exactly at which bytenr we hit
4227 * Currently the full page based __extent_writepage_io() is not
4230 if (PageError(page))
4231 end_extent_writepage(page, ret, page_start, page_end);
4232 if (epd->extent_locked) {
4234 * If epd->extent_locked, it's from extent_write_locked_range(),
4235 * the page can either be locked by lock_page() or
4236 * process_one_page().
4237 * Let btrfs_page_unlock_writer() handle both cases.
4240 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
4241 wbc->range_end + 1 - wbc->range_start);
4249 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
4251 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
4252 TASK_UNINTERRUPTIBLE);
4255 static void end_extent_buffer_writeback(struct extent_buffer *eb)
4257 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4258 smp_mb__after_atomic();
4259 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
4263 * Lock extent buffer status and pages for writeback.
4265 * May try to flush write bio if we can't get the lock.
4267 * Return 0 if the extent buffer doesn't need to be submitted.
4268 * (E.g. the extent buffer is not dirty)
4269 * Return >0 is the extent buffer is submitted to bio.
4270 * Return <0 if something went wrong, no page is locked.
4272 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4273 struct extent_page_data *epd)
4275 struct btrfs_fs_info *fs_info = eb->fs_info;
4280 if (!btrfs_try_tree_write_lock(eb)) {
4281 flush_write_bio(epd);
4283 btrfs_tree_lock(eb);
4286 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4287 btrfs_tree_unlock(eb);
4291 flush_write_bio(epd);
4295 wait_on_extent_buffer_writeback(eb);
4296 btrfs_tree_lock(eb);
4297 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4299 btrfs_tree_unlock(eb);
4304 * We need to do this to prevent races in people who check if the eb is
4305 * under IO since we can end up having no IO bits set for a short period
4308 spin_lock(&eb->refs_lock);
4309 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4310 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4311 spin_unlock(&eb->refs_lock);
4312 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4313 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4315 fs_info->dirty_metadata_batch);
4318 spin_unlock(&eb->refs_lock);
4321 btrfs_tree_unlock(eb);
4324 * Either we don't need to submit any tree block, or we're submitting
4326 * Subpage metadata doesn't use page locking at all, so we can skip
4329 if (!ret || fs_info->nodesize < PAGE_SIZE)
4332 num_pages = num_extent_pages(eb);
4333 for (i = 0; i < num_pages; i++) {
4334 struct page *p = eb->pages[i];
4336 if (!trylock_page(p)) {
4338 flush_write_bio(epd);
4348 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4350 struct btrfs_fs_info *fs_info = eb->fs_info;
4352 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4353 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4357 * A read may stumble upon this buffer later, make sure that it gets an
4358 * error and knows there was an error.
4360 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4363 * We need to set the mapping with the io error as well because a write
4364 * error will flip the file system readonly, and then syncfs() will
4365 * return a 0 because we are readonly if we don't modify the err seq for
4368 mapping_set_error(page->mapping, -EIO);
4371 * If we error out, we should add back the dirty_metadata_bytes
4372 * to make it consistent.
4374 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4375 eb->len, fs_info->dirty_metadata_batch);
4378 * If writeback for a btree extent that doesn't belong to a log tree
4379 * failed, increment the counter transaction->eb_write_errors.
4380 * We do this because while the transaction is running and before it's
4381 * committing (when we call filemap_fdata[write|wait]_range against
4382 * the btree inode), we might have
4383 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4384 * returns an error or an error happens during writeback, when we're
4385 * committing the transaction we wouldn't know about it, since the pages
4386 * can be no longer dirty nor marked anymore for writeback (if a
4387 * subsequent modification to the extent buffer didn't happen before the
4388 * transaction commit), which makes filemap_fdata[write|wait]_range not
4389 * able to find the pages tagged with SetPageError at transaction
4390 * commit time. So if this happens we must abort the transaction,
4391 * otherwise we commit a super block with btree roots that point to
4392 * btree nodes/leafs whose content on disk is invalid - either garbage
4393 * or the content of some node/leaf from a past generation that got
4394 * cowed or deleted and is no longer valid.
4396 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4397 * not be enough - we need to distinguish between log tree extents vs
4398 * non-log tree extents, and the next filemap_fdatawait_range() call
4399 * will catch and clear such errors in the mapping - and that call might
4400 * be from a log sync and not from a transaction commit. Also, checking
4401 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4402 * not done and would not be reliable - the eb might have been released
4403 * from memory and reading it back again means that flag would not be
4404 * set (since it's a runtime flag, not persisted on disk).
4406 * Using the flags below in the btree inode also makes us achieve the
4407 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4408 * writeback for all dirty pages and before filemap_fdatawait_range()
4409 * is called, the writeback for all dirty pages had already finished
4410 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4411 * filemap_fdatawait_range() would return success, as it could not know
4412 * that writeback errors happened (the pages were no longer tagged for
4415 switch (eb->log_index) {
4417 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4420 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4423 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4426 BUG(); /* unexpected, logic error */
4431 * The endio specific version which won't touch any unsafe spinlock in endio
4434 static struct extent_buffer *find_extent_buffer_nolock(
4435 struct btrfs_fs_info *fs_info, u64 start)
4437 struct extent_buffer *eb;
4440 eb = radix_tree_lookup(&fs_info->buffer_radix,
4441 start >> fs_info->sectorsize_bits);
4442 if (eb && atomic_inc_not_zero(&eb->refs)) {
4451 * The endio function for subpage extent buffer write.
4453 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4454 * after all extent buffers in the page has finished their writeback.
4456 static void end_bio_subpage_eb_writepage(struct bio *bio)
4458 struct btrfs_fs_info *fs_info;
4459 struct bio_vec *bvec;
4460 struct bvec_iter_all iter_all;
4462 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4463 ASSERT(fs_info->nodesize < PAGE_SIZE);
4465 ASSERT(!bio_flagged(bio, BIO_CLONED));
4466 bio_for_each_segment_all(bvec, bio, iter_all) {
4467 struct page *page = bvec->bv_page;
4468 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4469 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4470 u64 cur_bytenr = bvec_start;
4472 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4474 /* Iterate through all extent buffers in the range */
4475 while (cur_bytenr <= bvec_end) {
4476 struct extent_buffer *eb;
4480 * Here we can't use find_extent_buffer(), as it may
4481 * try to lock eb->refs_lock, which is not safe in endio
4484 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4487 cur_bytenr = eb->start + eb->len;
4489 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4490 done = atomic_dec_and_test(&eb->io_pages);
4493 if (bio->bi_status ||
4494 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4495 ClearPageUptodate(page);
4496 set_btree_ioerr(page, eb);
4499 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4501 end_extent_buffer_writeback(eb);
4503 * free_extent_buffer() will grab spinlock which is not
4504 * safe in endio context. Thus here we manually dec
4507 atomic_dec(&eb->refs);
4513 static void end_bio_extent_buffer_writepage(struct bio *bio)
4515 struct bio_vec *bvec;
4516 struct extent_buffer *eb;
4518 struct bvec_iter_all iter_all;
4520 ASSERT(!bio_flagged(bio, BIO_CLONED));
4521 bio_for_each_segment_all(bvec, bio, iter_all) {
4522 struct page *page = bvec->bv_page;
4524 eb = (struct extent_buffer *)page->private;
4526 done = atomic_dec_and_test(&eb->io_pages);
4528 if (bio->bi_status ||
4529 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4530 ClearPageUptodate(page);
4531 set_btree_ioerr(page, eb);
4534 end_page_writeback(page);
4539 end_extent_buffer_writeback(eb);
4545 static void prepare_eb_write(struct extent_buffer *eb)
4548 unsigned long start;
4551 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4552 atomic_set(&eb->io_pages, num_extent_pages(eb));
4554 /* Set btree blocks beyond nritems with 0 to avoid stale content */
4555 nritems = btrfs_header_nritems(eb);
4556 if (btrfs_header_level(eb) > 0) {
4557 end = btrfs_node_key_ptr_offset(nritems);
4558 memzero_extent_buffer(eb, end, eb->len - end);
4562 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4564 start = btrfs_item_nr_offset(nritems);
4565 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4566 memzero_extent_buffer(eb, start, end - start);
4571 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4572 * Page locking is only utilized at minimum to keep the VMM code happy.
4574 static int write_one_subpage_eb(struct extent_buffer *eb,
4575 struct writeback_control *wbc,
4576 struct extent_page_data *epd)
4578 struct btrfs_fs_info *fs_info = eb->fs_info;
4579 struct page *page = eb->pages[0];
4580 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4581 bool no_dirty_ebs = false;
4584 prepare_eb_write(eb);
4586 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4588 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4590 /* Check if this is the last dirty bit to update nr_written */
4591 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4592 eb->start, eb->len);
4594 clear_page_dirty_for_io(page);
4596 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4597 &epd->bio_ctrl, page, eb->start, eb->len,
4598 eb->start - page_offset(page),
4599 end_bio_subpage_eb_writepage, 0, 0, false);
4601 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4602 set_btree_ioerr(page, eb);
4605 if (atomic_dec_and_test(&eb->io_pages))
4606 end_extent_buffer_writeback(eb);
4611 * Submission finished without problem, if no range of the page is
4612 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4619 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4620 struct writeback_control *wbc,
4621 struct extent_page_data *epd)
4623 u64 disk_bytenr = eb->start;
4625 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4628 prepare_eb_write(eb);
4630 num_pages = num_extent_pages(eb);
4631 for (i = 0; i < num_pages; i++) {
4632 struct page *p = eb->pages[i];
4634 clear_page_dirty_for_io(p);
4635 set_page_writeback(p);
4636 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4637 &epd->bio_ctrl, p, disk_bytenr,
4639 end_bio_extent_buffer_writepage,
4642 set_btree_ioerr(p, eb);
4643 if (PageWriteback(p))
4644 end_page_writeback(p);
4645 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4646 end_extent_buffer_writeback(eb);
4650 disk_bytenr += PAGE_SIZE;
4655 if (unlikely(ret)) {
4656 for (; i < num_pages; i++) {
4657 struct page *p = eb->pages[i];
4658 clear_page_dirty_for_io(p);
4667 * Submit one subpage btree page.
4669 * The main difference to submit_eb_page() is:
4671 * For subpage, we don't rely on page locking at all.
4674 * We only flush bio if we may be unable to fit current extent buffers into
4677 * Return >=0 for the number of submitted extent buffers.
4678 * Return <0 for fatal error.
4680 static int submit_eb_subpage(struct page *page,
4681 struct writeback_control *wbc,
4682 struct extent_page_data *epd)
4684 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4686 u64 page_start = page_offset(page);
4688 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4691 /* Lock and write each dirty extent buffers in the range */
4692 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
4693 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4694 struct extent_buffer *eb;
4695 unsigned long flags;
4699 * Take private lock to ensure the subpage won't be detached
4702 spin_lock(&page->mapping->private_lock);
4703 if (!PagePrivate(page)) {
4704 spin_unlock(&page->mapping->private_lock);
4707 spin_lock_irqsave(&subpage->lock, flags);
4708 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
4709 subpage->bitmaps)) {
4710 spin_unlock_irqrestore(&subpage->lock, flags);
4711 spin_unlock(&page->mapping->private_lock);
4716 start = page_start + bit_start * fs_info->sectorsize;
4717 bit_start += sectors_per_node;
4720 * Here we just want to grab the eb without touching extra
4721 * spin locks, so call find_extent_buffer_nolock().
4723 eb = find_extent_buffer_nolock(fs_info, start);
4724 spin_unlock_irqrestore(&subpage->lock, flags);
4725 spin_unlock(&page->mapping->private_lock);
4728 * The eb has already reached 0 refs thus find_extent_buffer()
4729 * doesn't return it. We don't need to write back such eb
4735 ret = lock_extent_buffer_for_io(eb, epd);
4737 free_extent_buffer(eb);
4741 free_extent_buffer(eb);
4744 ret = write_one_subpage_eb(eb, wbc, epd);
4745 free_extent_buffer(eb);
4753 /* We hit error, end bio for the submitted extent buffers */
4754 end_write_bio(epd, ret);
4759 * Submit all page(s) of one extent buffer.
4761 * @page: the page of one extent buffer
4762 * @eb_context: to determine if we need to submit this page, if current page
4763 * belongs to this eb, we don't need to submit
4765 * The caller should pass each page in their bytenr order, and here we use
4766 * @eb_context to determine if we have submitted pages of one extent buffer.
4768 * If we have, we just skip until we hit a new page that doesn't belong to
4769 * current @eb_context.
4771 * If not, we submit all the page(s) of the extent buffer.
4773 * Return >0 if we have submitted the extent buffer successfully.
4774 * Return 0 if we don't need to submit the page, as it's already submitted by
4776 * Return <0 for fatal error.
4778 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4779 struct extent_page_data *epd,
4780 struct extent_buffer **eb_context)
4782 struct address_space *mapping = page->mapping;
4783 struct btrfs_block_group *cache = NULL;
4784 struct extent_buffer *eb;
4787 if (!PagePrivate(page))
4790 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
4791 return submit_eb_subpage(page, wbc, epd);
4793 spin_lock(&mapping->private_lock);
4794 if (!PagePrivate(page)) {
4795 spin_unlock(&mapping->private_lock);
4799 eb = (struct extent_buffer *)page->private;
4802 * Shouldn't happen and normally this would be a BUG_ON but no point
4803 * crashing the machine for something we can survive anyway.
4806 spin_unlock(&mapping->private_lock);
4810 if (eb == *eb_context) {
4811 spin_unlock(&mapping->private_lock);
4814 ret = atomic_inc_not_zero(&eb->refs);
4815 spin_unlock(&mapping->private_lock);
4819 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4821 * If for_sync, this hole will be filled with
4822 * trasnsaction commit.
4824 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4828 free_extent_buffer(eb);
4834 ret = lock_extent_buffer_for_io(eb, epd);
4836 btrfs_revert_meta_write_pointer(cache, eb);
4838 btrfs_put_block_group(cache);
4839 free_extent_buffer(eb);
4844 * Implies write in zoned mode. Mark the last eb in a block group.
4846 btrfs_schedule_zone_finish_bg(cache, eb);
4847 btrfs_put_block_group(cache);
4849 ret = write_one_eb(eb, wbc, epd);
4850 free_extent_buffer(eb);
4856 int btree_write_cache_pages(struct address_space *mapping,
4857 struct writeback_control *wbc)
4859 struct extent_buffer *eb_context = NULL;
4860 struct extent_page_data epd = {
4863 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4865 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4868 int nr_to_write_done = 0;
4869 struct pagevec pvec;
4872 pgoff_t end; /* Inclusive */
4876 pagevec_init(&pvec);
4877 if (wbc->range_cyclic) {
4878 index = mapping->writeback_index; /* Start from prev offset */
4881 * Start from the beginning does not need to cycle over the
4882 * range, mark it as scanned.
4884 scanned = (index == 0);
4886 index = wbc->range_start >> PAGE_SHIFT;
4887 end = wbc->range_end >> PAGE_SHIFT;
4890 if (wbc->sync_mode == WB_SYNC_ALL)
4891 tag = PAGECACHE_TAG_TOWRITE;
4893 tag = PAGECACHE_TAG_DIRTY;
4894 btrfs_zoned_meta_io_lock(fs_info);
4896 if (wbc->sync_mode == WB_SYNC_ALL)
4897 tag_pages_for_writeback(mapping, index, end);
4898 while (!done && !nr_to_write_done && (index <= end) &&
4899 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4903 for (i = 0; i < nr_pages; i++) {
4904 struct page *page = pvec.pages[i];
4906 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4915 * the filesystem may choose to bump up nr_to_write.
4916 * We have to make sure to honor the new nr_to_write
4919 nr_to_write_done = wbc->nr_to_write <= 0;
4921 pagevec_release(&pvec);
4924 if (!scanned && !done) {
4926 * We hit the last page and there is more work to be done: wrap
4927 * back to the start of the file
4934 end_write_bio(&epd, ret);
4938 * If something went wrong, don't allow any metadata write bio to be
4941 * This would prevent use-after-free if we had dirty pages not
4942 * cleaned up, which can still happen by fuzzed images.
4945 * Allowing existing tree block to be allocated for other trees.
4947 * - Log tree operations
4948 * Exiting tree blocks get allocated to log tree, bumps its
4949 * generation, then get cleaned in tree re-balance.
4950 * Such tree block will not be written back, since it's clean,
4951 * thus no WRITTEN flag set.
4952 * And after log writes back, this tree block is not traced by
4953 * any dirty extent_io_tree.
4955 * - Offending tree block gets re-dirtied from its original owner
4956 * Since it has bumped generation, no WRITTEN flag, it can be
4957 * reused without COWing. This tree block will not be traced
4958 * by btrfs_transaction::dirty_pages.
4960 * Now such dirty tree block will not be cleaned by any dirty
4961 * extent io tree. Thus we don't want to submit such wild eb
4962 * if the fs already has error.
4964 if (!BTRFS_FS_ERROR(fs_info)) {
4965 flush_write_bio(&epd);
4968 end_write_bio(&epd, ret);
4971 btrfs_zoned_meta_io_unlock(fs_info);
4973 * We can get ret > 0 from submit_extent_page() indicating how many ebs
4974 * were submitted. Reset it to 0 to avoid false alerts for the caller.
4982 * Walk the list of dirty pages of the given address space and write all of them.
4984 * @mapping: address space structure to write
4985 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4986 * @epd: holds context for the write, namely the bio
4988 * If a page is already under I/O, write_cache_pages() skips it, even
4989 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4990 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4991 * and msync() need to guarantee that all the data which was dirty at the time
4992 * the call was made get new I/O started against them. If wbc->sync_mode is
4993 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4994 * existing IO to complete.
4996 static int extent_write_cache_pages(struct address_space *mapping,
4997 struct writeback_control *wbc,
4998 struct extent_page_data *epd)
5000 struct inode *inode = mapping->host;
5003 int nr_to_write_done = 0;
5004 struct pagevec pvec;
5007 pgoff_t end; /* Inclusive */
5009 int range_whole = 0;
5014 * We have to hold onto the inode so that ordered extents can do their
5015 * work when the IO finishes. The alternative to this is failing to add
5016 * an ordered extent if the igrab() fails there and that is a huge pain
5017 * to deal with, so instead just hold onto the inode throughout the
5018 * writepages operation. If it fails here we are freeing up the inode
5019 * anyway and we'd rather not waste our time writing out stuff that is
5020 * going to be truncated anyway.
5025 pagevec_init(&pvec);
5026 if (wbc->range_cyclic) {
5027 index = mapping->writeback_index; /* Start from prev offset */
5030 * Start from the beginning does not need to cycle over the
5031 * range, mark it as scanned.
5033 scanned = (index == 0);
5035 index = wbc->range_start >> PAGE_SHIFT;
5036 end = wbc->range_end >> PAGE_SHIFT;
5037 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
5043 * We do the tagged writepage as long as the snapshot flush bit is set
5044 * and we are the first one who do the filemap_flush() on this inode.
5046 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
5047 * not race in and drop the bit.
5049 if (range_whole && wbc->nr_to_write == LONG_MAX &&
5050 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
5051 &BTRFS_I(inode)->runtime_flags))
5052 wbc->tagged_writepages = 1;
5054 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5055 tag = PAGECACHE_TAG_TOWRITE;
5057 tag = PAGECACHE_TAG_DIRTY;
5059 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5060 tag_pages_for_writeback(mapping, index, end);
5062 while (!done && !nr_to_write_done && (index <= end) &&
5063 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
5064 &index, end, tag))) {
5067 for (i = 0; i < nr_pages; i++) {
5068 struct page *page = pvec.pages[i];
5070 done_index = page->index + 1;
5072 * At this point we hold neither the i_pages lock nor
5073 * the page lock: the page may be truncated or
5074 * invalidated (changing page->mapping to NULL),
5075 * or even swizzled back from swapper_space to
5076 * tmpfs file mapping
5078 if (!trylock_page(page)) {
5079 flush_write_bio(epd);
5083 if (unlikely(page->mapping != mapping)) {
5088 if (wbc->sync_mode != WB_SYNC_NONE) {
5089 if (PageWriteback(page))
5090 flush_write_bio(epd);
5091 wait_on_page_writeback(page);
5094 if (PageWriteback(page) ||
5095 !clear_page_dirty_for_io(page)) {
5100 ret = __extent_writepage(page, wbc, epd);
5107 * the filesystem may choose to bump up nr_to_write.
5108 * We have to make sure to honor the new nr_to_write
5111 nr_to_write_done = wbc->nr_to_write <= 0;
5113 pagevec_release(&pvec);
5116 if (!scanned && !done) {
5118 * We hit the last page and there is more work to be done: wrap
5119 * back to the start of the file
5125 * If we're looping we could run into a page that is locked by a
5126 * writer and that writer could be waiting on writeback for a
5127 * page in our current bio, and thus deadlock, so flush the
5130 flush_write_bio(epd);
5134 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
5135 mapping->writeback_index = done_index;
5137 btrfs_add_delayed_iput(inode);
5141 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
5144 struct extent_page_data epd = {
5147 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5150 ret = __extent_writepage(page, wbc, &epd);
5153 end_write_bio(&epd, ret);
5157 flush_write_bio(&epd);
5162 * Submit the pages in the range to bio for call sites which delalloc range has
5163 * already been ran (aka, ordered extent inserted) and all pages are still
5166 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
5168 bool found_error = false;
5169 int first_error = 0;
5171 struct address_space *mapping = inode->i_mapping;
5174 unsigned long nr_pages;
5175 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
5176 struct extent_page_data epd = {
5181 struct writeback_control wbc_writepages = {
5182 .sync_mode = WB_SYNC_ALL,
5183 .range_start = start,
5184 .range_end = end + 1,
5185 /* We're called from an async helper function */
5186 .punt_to_cgroup = 1,
5187 .no_cgroup_owner = 1,
5190 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
5191 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
5193 wbc_writepages.nr_to_write = nr_pages * 2;
5195 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
5196 while (cur <= end) {
5197 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
5199 page = find_get_page(mapping, cur >> PAGE_SHIFT);
5201 * All pages in the range are locked since
5202 * btrfs_run_delalloc_range(), thus there is no way to clear
5203 * the page dirty flag.
5205 ASSERT(PageLocked(page));
5206 ASSERT(PageDirty(page));
5207 clear_page_dirty_for_io(page);
5208 ret = __extent_writepage(page, &wbc_writepages, &epd);
5219 flush_write_bio(&epd);
5221 end_write_bio(&epd, ret);
5223 wbc_detach_inode(&wbc_writepages);
5229 int extent_writepages(struct address_space *mapping,
5230 struct writeback_control *wbc)
5232 struct inode *inode = mapping->host;
5234 struct extent_page_data epd = {
5237 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5241 * Allow only a single thread to do the reloc work in zoned mode to
5242 * protect the write pointer updates.
5244 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
5245 ret = extent_write_cache_pages(mapping, wbc, &epd);
5248 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5249 end_write_bio(&epd, ret);
5252 flush_write_bio(&epd);
5253 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5257 void extent_readahead(struct readahead_control *rac)
5259 struct btrfs_bio_ctrl bio_ctrl = { 0 };
5260 struct page *pagepool[16];
5261 struct extent_map *em_cached = NULL;
5262 u64 prev_em_start = (u64)-1;
5265 while ((nr = readahead_page_batch(rac, pagepool))) {
5266 u64 contig_start = readahead_pos(rac);
5267 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
5269 contiguous_readpages(pagepool, nr, contig_start, contig_end,
5270 &em_cached, &bio_ctrl, &prev_em_start);
5274 free_extent_map(em_cached);
5277 submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.compress_type);
5281 * basic invalidate_folio code, this waits on any locked or writeback
5282 * ranges corresponding to the folio, and then deletes any extent state
5283 * records from the tree
5285 int extent_invalidate_folio(struct extent_io_tree *tree,
5286 struct folio *folio, size_t offset)
5288 struct extent_state *cached_state = NULL;
5289 u64 start = folio_pos(folio);
5290 u64 end = start + folio_size(folio) - 1;
5291 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
5293 /* This function is only called for the btree inode */
5294 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5296 start += ALIGN(offset, blocksize);
5300 lock_extent_bits(tree, start, end, &cached_state);
5301 folio_wait_writeback(folio);
5304 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5305 * so here we only need to unlock the extent range to free any
5306 * existing extent state.
5308 unlock_extent_cached(tree, start, end, &cached_state);
5313 * a helper for release_folio, this tests for areas of the page that
5314 * are locked or under IO and drops the related state bits if it is safe
5317 static int try_release_extent_state(struct extent_io_tree *tree,
5318 struct page *page, gfp_t mask)
5320 u64 start = page_offset(page);
5321 u64 end = start + PAGE_SIZE - 1;
5324 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5328 * At this point we can safely clear everything except the
5329 * locked bit, the nodatasum bit and the delalloc new bit.
5330 * The delalloc new bit will be cleared by ordered extent
5333 ret = __clear_extent_bit(tree, start, end,
5334 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5335 0, 0, NULL, mask, NULL);
5337 /* if clear_extent_bit failed for enomem reasons,
5338 * we can't allow the release to continue.
5349 * a helper for release_folio. As long as there are no locked extents
5350 * in the range corresponding to the page, both state records and extent
5351 * map records are removed
5353 int try_release_extent_mapping(struct page *page, gfp_t mask)
5355 struct extent_map *em;
5356 u64 start = page_offset(page);
5357 u64 end = start + PAGE_SIZE - 1;
5358 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5359 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5360 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5362 if (gfpflags_allow_blocking(mask) &&
5363 page->mapping->host->i_size > SZ_16M) {
5365 while (start <= end) {
5366 struct btrfs_fs_info *fs_info;
5369 len = end - start + 1;
5370 write_lock(&map->lock);
5371 em = lookup_extent_mapping(map, start, len);
5373 write_unlock(&map->lock);
5376 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5377 em->start != start) {
5378 write_unlock(&map->lock);
5379 free_extent_map(em);
5382 if (test_range_bit(tree, em->start,
5383 extent_map_end(em) - 1,
5384 EXTENT_LOCKED, 0, NULL))
5387 * If it's not in the list of modified extents, used
5388 * by a fast fsync, we can remove it. If it's being
5389 * logged we can safely remove it since fsync took an
5390 * extra reference on the em.
5392 if (list_empty(&em->list) ||
5393 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5396 * If it's in the list of modified extents, remove it
5397 * only if its generation is older then the current one,
5398 * in which case we don't need it for a fast fsync.
5399 * Otherwise don't remove it, we could be racing with an
5400 * ongoing fast fsync that could miss the new extent.
5402 fs_info = btrfs_inode->root->fs_info;
5403 spin_lock(&fs_info->trans_lock);
5404 cur_gen = fs_info->generation;
5405 spin_unlock(&fs_info->trans_lock);
5406 if (em->generation >= cur_gen)
5410 * We only remove extent maps that are not in the list of
5411 * modified extents or that are in the list but with a
5412 * generation lower then the current generation, so there
5413 * is no need to set the full fsync flag on the inode (it
5414 * hurts the fsync performance for workloads with a data
5415 * size that exceeds or is close to the system's memory).
5417 remove_extent_mapping(map, em);
5418 /* once for the rb tree */
5419 free_extent_map(em);
5421 start = extent_map_end(em);
5422 write_unlock(&map->lock);
5425 free_extent_map(em);
5427 cond_resched(); /* Allow large-extent preemption. */
5430 return try_release_extent_state(tree, page, mask);
5434 * helper function for fiemap, which doesn't want to see any holes.
5435 * This maps until we find something past 'last'
5437 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5438 u64 offset, u64 last)
5440 u64 sectorsize = btrfs_inode_sectorsize(inode);
5441 struct extent_map *em;
5448 len = last - offset;
5451 len = ALIGN(len, sectorsize);
5452 em = btrfs_get_extent_fiemap(inode, offset, len);
5456 /* if this isn't a hole return it */
5457 if (em->block_start != EXTENT_MAP_HOLE)
5460 /* this is a hole, advance to the next extent */
5461 offset = extent_map_end(em);
5462 free_extent_map(em);
5470 * To cache previous fiemap extent
5472 * Will be used for merging fiemap extent
5474 struct fiemap_cache {
5483 * Helper to submit fiemap extent.
5485 * Will try to merge current fiemap extent specified by @offset, @phys,
5486 * @len and @flags with cached one.
5487 * And only when we fails to merge, cached one will be submitted as
5490 * Return value is the same as fiemap_fill_next_extent().
5492 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5493 struct fiemap_cache *cache,
5494 u64 offset, u64 phys, u64 len, u32 flags)
5502 * Sanity check, extent_fiemap() should have ensured that new
5503 * fiemap extent won't overlap with cached one.
5506 * NOTE: Physical address can overlap, due to compression
5508 if (cache->offset + cache->len > offset) {
5514 * Only merges fiemap extents if
5515 * 1) Their logical addresses are continuous
5517 * 2) Their physical addresses are continuous
5518 * So truly compressed (physical size smaller than logical size)
5519 * extents won't get merged with each other
5521 * 3) Share same flags except FIEMAP_EXTENT_LAST
5522 * So regular extent won't get merged with prealloc extent
5524 if (cache->offset + cache->len == offset &&
5525 cache->phys + cache->len == phys &&
5526 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5527 (flags & ~FIEMAP_EXTENT_LAST)) {
5529 cache->flags |= flags;
5530 goto try_submit_last;
5533 /* Not mergeable, need to submit cached one */
5534 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5535 cache->len, cache->flags);
5536 cache->cached = false;
5540 cache->cached = true;
5541 cache->offset = offset;
5544 cache->flags = flags;
5546 if (cache->flags & FIEMAP_EXTENT_LAST) {
5547 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5548 cache->phys, cache->len, cache->flags);
5549 cache->cached = false;
5555 * Emit last fiemap cache
5557 * The last fiemap cache may still be cached in the following case:
5559 * |<- Fiemap range ->|
5560 * |<------------ First extent ----------->|
5562 * In this case, the first extent range will be cached but not emitted.
5563 * So we must emit it before ending extent_fiemap().
5565 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5566 struct fiemap_cache *cache)
5573 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5574 cache->len, cache->flags);
5575 cache->cached = false;
5581 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5586 u64 max = start + len;
5590 u64 last_for_get_extent = 0;
5592 u64 isize = i_size_read(&inode->vfs_inode);
5593 struct btrfs_key found_key;
5594 struct extent_map *em = NULL;
5595 struct extent_state *cached_state = NULL;
5596 struct btrfs_path *path;
5597 struct btrfs_root *root = inode->root;
5598 struct fiemap_cache cache = { 0 };
5599 struct ulist *roots;
5600 struct ulist *tmp_ulist;
5609 path = btrfs_alloc_path();
5613 roots = ulist_alloc(GFP_KERNEL);
5614 tmp_ulist = ulist_alloc(GFP_KERNEL);
5615 if (!roots || !tmp_ulist) {
5617 goto out_free_ulist;
5621 * We can't initialize that to 'start' as this could miss extents due
5622 * to extent item merging
5625 start = round_down(start, btrfs_inode_sectorsize(inode));
5626 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5629 * lookup the last file extent. We're not using i_size here
5630 * because there might be preallocation past i_size
5632 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5635 goto out_free_ulist;
5643 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5644 found_type = found_key.type;
5646 /* No extents, but there might be delalloc bits */
5647 if (found_key.objectid != btrfs_ino(inode) ||
5648 found_type != BTRFS_EXTENT_DATA_KEY) {
5649 /* have to trust i_size as the end */
5651 last_for_get_extent = isize;
5654 * remember the start of the last extent. There are a
5655 * bunch of different factors that go into the length of the
5656 * extent, so its much less complex to remember where it started
5658 last = found_key.offset;
5659 last_for_get_extent = last + 1;
5661 btrfs_release_path(path);
5664 * we might have some extents allocated but more delalloc past those
5665 * extents. so, we trust isize unless the start of the last extent is
5670 last_for_get_extent = isize;
5673 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5676 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5685 u64 offset_in_extent = 0;
5687 /* break if the extent we found is outside the range */
5688 if (em->start >= max || extent_map_end(em) < off)
5692 * get_extent may return an extent that starts before our
5693 * requested range. We have to make sure the ranges
5694 * we return to fiemap always move forward and don't
5695 * overlap, so adjust the offsets here
5697 em_start = max(em->start, off);
5700 * record the offset from the start of the extent
5701 * for adjusting the disk offset below. Only do this if the
5702 * extent isn't compressed since our in ram offset may be past
5703 * what we have actually allocated on disk.
5705 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5706 offset_in_extent = em_start - em->start;
5707 em_end = extent_map_end(em);
5708 em_len = em_end - em_start;
5710 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5711 disko = em->block_start + offset_in_extent;
5716 * bump off for our next call to get_extent
5718 off = extent_map_end(em);
5722 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5724 flags |= FIEMAP_EXTENT_LAST;
5725 } else if (em->block_start == EXTENT_MAP_INLINE) {
5726 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5727 FIEMAP_EXTENT_NOT_ALIGNED);
5728 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5729 flags |= (FIEMAP_EXTENT_DELALLOC |
5730 FIEMAP_EXTENT_UNKNOWN);
5731 } else if (fieinfo->fi_extents_max) {
5732 u64 bytenr = em->block_start -
5733 (em->start - em->orig_start);
5736 * As btrfs supports shared space, this information
5737 * can be exported to userspace tools via
5738 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5739 * then we're just getting a count and we can skip the
5742 ret = btrfs_check_shared(root, btrfs_ino(inode),
5743 bytenr, roots, tmp_ulist);
5747 flags |= FIEMAP_EXTENT_SHARED;
5750 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5751 flags |= FIEMAP_EXTENT_ENCODED;
5752 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5753 flags |= FIEMAP_EXTENT_UNWRITTEN;
5755 free_extent_map(em);
5757 if ((em_start >= last) || em_len == (u64)-1 ||
5758 (last == (u64)-1 && isize <= em_end)) {
5759 flags |= FIEMAP_EXTENT_LAST;
5763 /* now scan forward to see if this is really the last extent. */
5764 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5770 flags |= FIEMAP_EXTENT_LAST;
5773 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5783 ret = emit_last_fiemap_cache(fieinfo, &cache);
5784 free_extent_map(em);
5786 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5790 btrfs_free_path(path);
5792 ulist_free(tmp_ulist);
5796 static void __free_extent_buffer(struct extent_buffer *eb)
5798 kmem_cache_free(extent_buffer_cache, eb);
5801 int extent_buffer_under_io(const struct extent_buffer *eb)
5803 return (atomic_read(&eb->io_pages) ||
5804 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5805 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5808 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5810 struct btrfs_subpage *subpage;
5812 lockdep_assert_held(&page->mapping->private_lock);
5814 if (PagePrivate(page)) {
5815 subpage = (struct btrfs_subpage *)page->private;
5816 if (atomic_read(&subpage->eb_refs))
5819 * Even there is no eb refs here, we may still have
5820 * end_page_read() call relying on page::private.
5822 if (atomic_read(&subpage->readers))
5828 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5830 struct btrfs_fs_info *fs_info = eb->fs_info;
5831 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5834 * For mapped eb, we're going to change the page private, which should
5835 * be done under the private_lock.
5838 spin_lock(&page->mapping->private_lock);
5840 if (!PagePrivate(page)) {
5842 spin_unlock(&page->mapping->private_lock);
5846 if (fs_info->nodesize >= PAGE_SIZE) {
5848 * We do this since we'll remove the pages after we've
5849 * removed the eb from the radix tree, so we could race
5850 * and have this page now attached to the new eb. So
5851 * only clear page_private if it's still connected to
5854 if (PagePrivate(page) &&
5855 page->private == (unsigned long)eb) {
5856 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5857 BUG_ON(PageDirty(page));
5858 BUG_ON(PageWriteback(page));
5860 * We need to make sure we haven't be attached
5863 detach_page_private(page);
5866 spin_unlock(&page->mapping->private_lock);
5871 * For subpage, we can have dummy eb with page private. In this case,
5872 * we can directly detach the private as such page is only attached to
5873 * one dummy eb, no sharing.
5876 btrfs_detach_subpage(fs_info, page);
5880 btrfs_page_dec_eb_refs(fs_info, page);
5883 * We can only detach the page private if there are no other ebs in the
5884 * page range and no unfinished IO.
5886 if (!page_range_has_eb(fs_info, page))
5887 btrfs_detach_subpage(fs_info, page);
5889 spin_unlock(&page->mapping->private_lock);
5892 /* Release all pages attached to the extent buffer */
5893 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5898 ASSERT(!extent_buffer_under_io(eb));
5900 num_pages = num_extent_pages(eb);
5901 for (i = 0; i < num_pages; i++) {
5902 struct page *page = eb->pages[i];
5907 detach_extent_buffer_page(eb, page);
5909 /* One for when we allocated the page */
5915 * Helper for releasing the extent buffer.
5917 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5919 btrfs_release_extent_buffer_pages(eb);
5920 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5921 __free_extent_buffer(eb);
5924 static struct extent_buffer *
5925 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5928 struct extent_buffer *eb = NULL;
5930 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5933 eb->fs_info = fs_info;
5935 init_rwsem(&eb->lock);
5937 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5938 &fs_info->allocated_ebs);
5939 INIT_LIST_HEAD(&eb->release_list);
5941 spin_lock_init(&eb->refs_lock);
5942 atomic_set(&eb->refs, 1);
5943 atomic_set(&eb->io_pages, 0);
5945 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5950 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5953 struct extent_buffer *new;
5954 int num_pages = num_extent_pages(src);
5957 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5962 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5963 * btrfs_release_extent_buffer() have different behavior for
5964 * UNMAPPED subpage extent buffer.
5966 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5968 memset(new->pages, 0, sizeof(*new->pages) * num_pages);
5969 ret = btrfs_alloc_page_array(num_pages, new->pages);
5971 btrfs_release_extent_buffer(new);
5975 for (i = 0; i < num_pages; i++) {
5977 struct page *p = new->pages[i];
5979 ret = attach_extent_buffer_page(new, p, NULL);
5981 btrfs_release_extent_buffer(new);
5984 WARN_ON(PageDirty(p));
5985 copy_page(page_address(p), page_address(src->pages[i]));
5987 set_extent_buffer_uptodate(new);
5992 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5993 u64 start, unsigned long len)
5995 struct extent_buffer *eb;
6000 eb = __alloc_extent_buffer(fs_info, start, len);
6004 num_pages = num_extent_pages(eb);
6005 ret = btrfs_alloc_page_array(num_pages, eb->pages);
6009 for (i = 0; i < num_pages; i++) {
6010 struct page *p = eb->pages[i];
6012 ret = attach_extent_buffer_page(eb, p, NULL);
6017 set_extent_buffer_uptodate(eb);
6018 btrfs_set_header_nritems(eb, 0);
6019 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
6023 for (i = 0; i < num_pages; i++) {
6025 detach_extent_buffer_page(eb, eb->pages[i]);
6026 __free_page(eb->pages[i]);
6029 __free_extent_buffer(eb);
6033 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
6036 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
6039 static void check_buffer_tree_ref(struct extent_buffer *eb)
6043 * The TREE_REF bit is first set when the extent_buffer is added
6044 * to the radix tree. It is also reset, if unset, when a new reference
6045 * is created by find_extent_buffer.
6047 * It is only cleared in two cases: freeing the last non-tree
6048 * reference to the extent_buffer when its STALE bit is set or
6049 * calling release_folio when the tree reference is the only reference.
6051 * In both cases, care is taken to ensure that the extent_buffer's
6052 * pages are not under io. However, release_folio can be concurrently
6053 * called with creating new references, which is prone to race
6054 * conditions between the calls to check_buffer_tree_ref in those
6055 * codepaths and clearing TREE_REF in try_release_extent_buffer.
6057 * The actual lifetime of the extent_buffer in the radix tree is
6058 * adequately protected by the refcount, but the TREE_REF bit and
6059 * its corresponding reference are not. To protect against this
6060 * class of races, we call check_buffer_tree_ref from the codepaths
6061 * which trigger io after they set eb->io_pages. Note that once io is
6062 * initiated, TREE_REF can no longer be cleared, so that is the
6063 * moment at which any such race is best fixed.
6065 refs = atomic_read(&eb->refs);
6066 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6069 spin_lock(&eb->refs_lock);
6070 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6071 atomic_inc(&eb->refs);
6072 spin_unlock(&eb->refs_lock);
6075 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
6076 struct page *accessed)
6080 check_buffer_tree_ref(eb);
6082 num_pages = num_extent_pages(eb);
6083 for (i = 0; i < num_pages; i++) {
6084 struct page *p = eb->pages[i];
6087 mark_page_accessed(p);
6091 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
6094 struct extent_buffer *eb;
6096 eb = find_extent_buffer_nolock(fs_info, start);
6100 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
6101 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
6102 * another task running free_extent_buffer() might have seen that flag
6103 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
6104 * writeback flags not set) and it's still in the tree (flag
6105 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
6106 * decrementing the extent buffer's reference count twice. So here we
6107 * could race and increment the eb's reference count, clear its stale
6108 * flag, mark it as dirty and drop our reference before the other task
6109 * finishes executing free_extent_buffer, which would later result in
6110 * an attempt to free an extent buffer that is dirty.
6112 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
6113 spin_lock(&eb->refs_lock);
6114 spin_unlock(&eb->refs_lock);
6116 mark_extent_buffer_accessed(eb, NULL);
6120 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6121 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
6124 struct extent_buffer *eb, *exists = NULL;
6127 eb = find_extent_buffer(fs_info, start);
6130 eb = alloc_dummy_extent_buffer(fs_info, start);
6132 return ERR_PTR(-ENOMEM);
6133 eb->fs_info = fs_info;
6135 ret = radix_tree_preload(GFP_NOFS);
6137 exists = ERR_PTR(ret);
6140 spin_lock(&fs_info->buffer_lock);
6141 ret = radix_tree_insert(&fs_info->buffer_radix,
6142 start >> fs_info->sectorsize_bits, eb);
6143 spin_unlock(&fs_info->buffer_lock);
6144 radix_tree_preload_end();
6145 if (ret == -EEXIST) {
6146 exists = find_extent_buffer(fs_info, start);
6152 check_buffer_tree_ref(eb);
6153 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6157 btrfs_release_extent_buffer(eb);
6162 static struct extent_buffer *grab_extent_buffer(
6163 struct btrfs_fs_info *fs_info, struct page *page)
6165 struct extent_buffer *exists;
6168 * For subpage case, we completely rely on radix tree to ensure we
6169 * don't try to insert two ebs for the same bytenr. So here we always
6170 * return NULL and just continue.
6172 if (fs_info->nodesize < PAGE_SIZE)
6175 /* Page not yet attached to an extent buffer */
6176 if (!PagePrivate(page))
6180 * We could have already allocated an eb for this page and attached one
6181 * so lets see if we can get a ref on the existing eb, and if we can we
6182 * know it's good and we can just return that one, else we know we can
6183 * just overwrite page->private.
6185 exists = (struct extent_buffer *)page->private;
6186 if (atomic_inc_not_zero(&exists->refs))
6189 WARN_ON(PageDirty(page));
6190 detach_page_private(page);
6194 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
6196 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
6197 btrfs_err(fs_info, "bad tree block start %llu", start);
6201 if (fs_info->nodesize < PAGE_SIZE &&
6202 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
6204 "tree block crosses page boundary, start %llu nodesize %u",
6205 start, fs_info->nodesize);
6208 if (fs_info->nodesize >= PAGE_SIZE &&
6209 !IS_ALIGNED(start, PAGE_SIZE)) {
6211 "tree block is not page aligned, start %llu nodesize %u",
6212 start, fs_info->nodesize);
6218 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
6219 u64 start, u64 owner_root, int level)
6221 unsigned long len = fs_info->nodesize;
6224 unsigned long index = start >> PAGE_SHIFT;
6225 struct extent_buffer *eb;
6226 struct extent_buffer *exists = NULL;
6228 struct address_space *mapping = fs_info->btree_inode->i_mapping;
6232 if (check_eb_alignment(fs_info, start))
6233 return ERR_PTR(-EINVAL);
6235 #if BITS_PER_LONG == 32
6236 if (start >= MAX_LFS_FILESIZE) {
6237 btrfs_err_rl(fs_info,
6238 "extent buffer %llu is beyond 32bit page cache limit", start);
6239 btrfs_err_32bit_limit(fs_info);
6240 return ERR_PTR(-EOVERFLOW);
6242 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6243 btrfs_warn_32bit_limit(fs_info);
6246 eb = find_extent_buffer(fs_info, start);
6250 eb = __alloc_extent_buffer(fs_info, start, len);
6252 return ERR_PTR(-ENOMEM);
6253 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
6255 num_pages = num_extent_pages(eb);
6256 for (i = 0; i < num_pages; i++, index++) {
6257 struct btrfs_subpage *prealloc = NULL;
6259 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
6261 exists = ERR_PTR(-ENOMEM);
6266 * Preallocate page->private for subpage case, so that we won't
6267 * allocate memory with private_lock hold. The memory will be
6268 * freed by attach_extent_buffer_page() or freed manually if
6271 * Although we have ensured one subpage eb can only have one
6272 * page, but it may change in the future for 16K page size
6273 * support, so we still preallocate the memory in the loop.
6275 if (fs_info->nodesize < PAGE_SIZE) {
6276 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
6277 if (IS_ERR(prealloc)) {
6278 ret = PTR_ERR(prealloc);
6281 exists = ERR_PTR(ret);
6286 spin_lock(&mapping->private_lock);
6287 exists = grab_extent_buffer(fs_info, p);
6289 spin_unlock(&mapping->private_lock);
6292 mark_extent_buffer_accessed(exists, p);
6293 btrfs_free_subpage(prealloc);
6296 /* Should not fail, as we have preallocated the memory */
6297 ret = attach_extent_buffer_page(eb, p, prealloc);
6300 * To inform we have extra eb under allocation, so that
6301 * detach_extent_buffer_page() won't release the page private
6302 * when the eb hasn't yet been inserted into radix tree.
6304 * The ref will be decreased when the eb released the page, in
6305 * detach_extent_buffer_page().
6306 * Thus needs no special handling in error path.
6308 btrfs_page_inc_eb_refs(fs_info, p);
6309 spin_unlock(&mapping->private_lock);
6311 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6313 if (!PageUptodate(p))
6317 * We can't unlock the pages just yet since the extent buffer
6318 * hasn't been properly inserted in the radix tree, this
6319 * opens a race with btree_release_folio which can free a page
6320 * while we are still filling in all pages for the buffer and
6325 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6327 ret = radix_tree_preload(GFP_NOFS);
6329 exists = ERR_PTR(ret);
6333 spin_lock(&fs_info->buffer_lock);
6334 ret = radix_tree_insert(&fs_info->buffer_radix,
6335 start >> fs_info->sectorsize_bits, eb);
6336 spin_unlock(&fs_info->buffer_lock);
6337 radix_tree_preload_end();
6338 if (ret == -EEXIST) {
6339 exists = find_extent_buffer(fs_info, start);
6345 /* add one reference for the tree */
6346 check_buffer_tree_ref(eb);
6347 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6350 * Now it's safe to unlock the pages because any calls to
6351 * btree_release_folio will correctly detect that a page belongs to a
6352 * live buffer and won't free them prematurely.
6354 for (i = 0; i < num_pages; i++)
6355 unlock_page(eb->pages[i]);
6359 WARN_ON(!atomic_dec_and_test(&eb->refs));
6360 for (i = 0; i < num_pages; i++) {
6362 unlock_page(eb->pages[i]);
6365 btrfs_release_extent_buffer(eb);
6369 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6371 struct extent_buffer *eb =
6372 container_of(head, struct extent_buffer, rcu_head);
6374 __free_extent_buffer(eb);
6377 static int release_extent_buffer(struct extent_buffer *eb)
6378 __releases(&eb->refs_lock)
6380 lockdep_assert_held(&eb->refs_lock);
6382 WARN_ON(atomic_read(&eb->refs) == 0);
6383 if (atomic_dec_and_test(&eb->refs)) {
6384 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6385 struct btrfs_fs_info *fs_info = eb->fs_info;
6387 spin_unlock(&eb->refs_lock);
6389 spin_lock(&fs_info->buffer_lock);
6390 radix_tree_delete(&fs_info->buffer_radix,
6391 eb->start >> fs_info->sectorsize_bits);
6392 spin_unlock(&fs_info->buffer_lock);
6394 spin_unlock(&eb->refs_lock);
6397 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6398 /* Should be safe to release our pages at this point */
6399 btrfs_release_extent_buffer_pages(eb);
6400 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6401 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6402 __free_extent_buffer(eb);
6406 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6409 spin_unlock(&eb->refs_lock);
6414 void free_extent_buffer(struct extent_buffer *eb)
6422 refs = atomic_read(&eb->refs);
6423 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6424 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6427 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6432 spin_lock(&eb->refs_lock);
6433 if (atomic_read(&eb->refs) == 2 &&
6434 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6435 !extent_buffer_under_io(eb) &&
6436 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6437 atomic_dec(&eb->refs);
6440 * I know this is terrible, but it's temporary until we stop tracking
6441 * the uptodate bits and such for the extent buffers.
6443 release_extent_buffer(eb);
6446 void free_extent_buffer_stale(struct extent_buffer *eb)
6451 spin_lock(&eb->refs_lock);
6452 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6454 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6455 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6456 atomic_dec(&eb->refs);
6457 release_extent_buffer(eb);
6460 static void btree_clear_page_dirty(struct page *page)
6462 ASSERT(PageDirty(page));
6463 ASSERT(PageLocked(page));
6464 clear_page_dirty_for_io(page);
6465 xa_lock_irq(&page->mapping->i_pages);
6466 if (!PageDirty(page))
6467 __xa_clear_mark(&page->mapping->i_pages,
6468 page_index(page), PAGECACHE_TAG_DIRTY);
6469 xa_unlock_irq(&page->mapping->i_pages);
6472 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6474 struct btrfs_fs_info *fs_info = eb->fs_info;
6475 struct page *page = eb->pages[0];
6478 /* btree_clear_page_dirty() needs page locked */
6480 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6483 btree_clear_page_dirty(page);
6485 WARN_ON(atomic_read(&eb->refs) == 0);
6488 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6494 if (eb->fs_info->nodesize < PAGE_SIZE)
6495 return clear_subpage_extent_buffer_dirty(eb);
6497 num_pages = num_extent_pages(eb);
6499 for (i = 0; i < num_pages; i++) {
6500 page = eb->pages[i];
6501 if (!PageDirty(page))
6504 btree_clear_page_dirty(page);
6505 ClearPageError(page);
6508 WARN_ON(atomic_read(&eb->refs) == 0);
6511 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6517 check_buffer_tree_ref(eb);
6519 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6521 num_pages = num_extent_pages(eb);
6522 WARN_ON(atomic_read(&eb->refs) == 0);
6523 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6526 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
6529 * For subpage case, we can have other extent buffers in the
6530 * same page, and in clear_subpage_extent_buffer_dirty() we
6531 * have to clear page dirty without subpage lock held.
6532 * This can cause race where our page gets dirty cleared after
6535 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6536 * its page for other reasons, we can use page lock to prevent
6540 lock_page(eb->pages[0]);
6541 for (i = 0; i < num_pages; i++)
6542 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6543 eb->start, eb->len);
6545 unlock_page(eb->pages[0]);
6547 #ifdef CONFIG_BTRFS_DEBUG
6548 for (i = 0; i < num_pages; i++)
6549 ASSERT(PageDirty(eb->pages[i]));
6555 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6557 struct btrfs_fs_info *fs_info = eb->fs_info;
6562 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6563 num_pages = num_extent_pages(eb);
6564 for (i = 0; i < num_pages; i++) {
6565 page = eb->pages[i];
6570 * This is special handling for metadata subpage, as regular
6571 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6573 if (fs_info->nodesize >= PAGE_SIZE)
6574 ClearPageUptodate(page);
6576 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
6581 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6583 struct btrfs_fs_info *fs_info = eb->fs_info;
6588 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6589 num_pages = num_extent_pages(eb);
6590 for (i = 0; i < num_pages; i++) {
6591 page = eb->pages[i];
6594 * This is special handling for metadata subpage, as regular
6595 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6597 if (fs_info->nodesize >= PAGE_SIZE)
6598 SetPageUptodate(page);
6600 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
6605 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6608 struct btrfs_fs_info *fs_info = eb->fs_info;
6609 struct extent_io_tree *io_tree;
6610 struct page *page = eb->pages[0];
6611 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6614 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6615 ASSERT(PagePrivate(page));
6616 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6618 if (wait == WAIT_NONE) {
6619 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6622 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6628 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6629 PageUptodate(page) ||
6630 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6631 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6632 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6636 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6637 eb->read_mirror = 0;
6638 atomic_set(&eb->io_pages, 1);
6639 check_buffer_tree_ref(eb);
6640 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6642 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
6643 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6644 page, eb->start, eb->len,
6645 eb->start - page_offset(page),
6646 end_bio_extent_readpage, mirror_num, 0,
6650 * In the endio function, if we hit something wrong we will
6651 * increase the io_pages, so here we need to decrease it for
6654 atomic_dec(&eb->io_pages);
6657 submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6658 bio_ctrl.bio = NULL;
6660 if (ret || wait != WAIT_COMPLETE)
6663 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6664 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6669 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6675 int locked_pages = 0;
6676 int all_uptodate = 1;
6678 unsigned long num_reads = 0;
6679 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6681 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6685 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
6686 * operation, which could potentially still be in flight. In this case
6687 * we simply want to return an error.
6689 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
6692 if (eb->fs_info->nodesize < PAGE_SIZE)
6693 return read_extent_buffer_subpage(eb, wait, mirror_num);
6695 num_pages = num_extent_pages(eb);
6696 for (i = 0; i < num_pages; i++) {
6697 page = eb->pages[i];
6698 if (wait == WAIT_NONE) {
6700 * WAIT_NONE is only utilized by readahead. If we can't
6701 * acquire the lock atomically it means either the eb
6702 * is being read out or under modification.
6703 * Either way the eb will be or has been cached,
6704 * readahead can exit safely.
6706 if (!trylock_page(page))
6714 * We need to firstly lock all pages to make sure that
6715 * the uptodate bit of our pages won't be affected by
6716 * clear_extent_buffer_uptodate().
6718 for (i = 0; i < num_pages; i++) {
6719 page = eb->pages[i];
6720 if (!PageUptodate(page)) {
6727 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6731 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6732 eb->read_mirror = 0;
6733 atomic_set(&eb->io_pages, num_reads);
6735 * It is possible for release_folio to clear the TREE_REF bit before we
6736 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6738 check_buffer_tree_ref(eb);
6739 for (i = 0; i < num_pages; i++) {
6740 page = eb->pages[i];
6742 if (!PageUptodate(page)) {
6744 atomic_dec(&eb->io_pages);
6749 ClearPageError(page);
6750 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6751 &bio_ctrl, page, page_offset(page),
6752 PAGE_SIZE, 0, end_bio_extent_readpage,
6753 mirror_num, 0, false);
6756 * We failed to submit the bio so it's the
6757 * caller's responsibility to perform cleanup
6758 * i.e unlock page/set error bit.
6763 atomic_dec(&eb->io_pages);
6771 submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.compress_type);
6772 bio_ctrl.bio = NULL;
6775 if (ret || wait != WAIT_COMPLETE)
6778 for (i = 0; i < num_pages; i++) {
6779 page = eb->pages[i];
6780 wait_on_page_locked(page);
6781 if (!PageUptodate(page))
6788 while (locked_pages > 0) {
6790 page = eb->pages[locked_pages];
6796 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6799 btrfs_warn(eb->fs_info,
6800 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6801 eb->start, eb->len, start, len);
6802 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6808 * Check if the [start, start + len) range is valid before reading/writing
6810 * NOTE: @start and @len are offset inside the eb, not logical address.
6812 * Caller should not touch the dst/src memory if this function returns error.
6814 static inline int check_eb_range(const struct extent_buffer *eb,
6815 unsigned long start, unsigned long len)
6817 unsigned long offset;
6819 /* start, start + len should not go beyond eb->len nor overflow */
6820 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6821 return report_eb_range(eb, start, len);
6826 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6827 unsigned long start, unsigned long len)
6833 char *dst = (char *)dstv;
6834 unsigned long i = get_eb_page_index(start);
6836 if (check_eb_range(eb, start, len))
6839 offset = get_eb_offset_in_page(eb, start);
6842 page = eb->pages[i];
6844 cur = min(len, (PAGE_SIZE - offset));
6845 kaddr = page_address(page);
6846 memcpy(dst, kaddr + offset, cur);
6855 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6857 unsigned long start, unsigned long len)
6863 char __user *dst = (char __user *)dstv;
6864 unsigned long i = get_eb_page_index(start);
6867 WARN_ON(start > eb->len);
6868 WARN_ON(start + len > eb->start + eb->len);
6870 offset = get_eb_offset_in_page(eb, start);
6873 page = eb->pages[i];
6875 cur = min(len, (PAGE_SIZE - offset));
6876 kaddr = page_address(page);
6877 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6891 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6892 unsigned long start, unsigned long len)
6898 char *ptr = (char *)ptrv;
6899 unsigned long i = get_eb_page_index(start);
6902 if (check_eb_range(eb, start, len))
6905 offset = get_eb_offset_in_page(eb, start);
6908 page = eb->pages[i];
6910 cur = min(len, (PAGE_SIZE - offset));
6912 kaddr = page_address(page);
6913 ret = memcmp(ptr, kaddr + offset, cur);
6926 * Check that the extent buffer is uptodate.
6928 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6929 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6931 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6934 struct btrfs_fs_info *fs_info = eb->fs_info;
6937 * If we are using the commit root we could potentially clear a page
6938 * Uptodate while we're using the extent buffer that we've previously
6939 * looked up. We don't want to complain in this case, as the page was
6940 * valid before, we just didn't write it out. Instead we want to catch
6941 * the case where we didn't actually read the block properly, which
6942 * would have !PageUptodate && !PageError, as we clear PageError before
6945 if (fs_info->nodesize < PAGE_SIZE) {
6946 bool uptodate, error;
6948 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6949 eb->start, eb->len);
6950 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
6951 WARN_ON(!uptodate && !error);
6953 WARN_ON(!PageUptodate(page) && !PageError(page));
6957 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6962 assert_eb_page_uptodate(eb, eb->pages[0]);
6963 kaddr = page_address(eb->pages[0]) +
6964 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6966 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6969 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6973 assert_eb_page_uptodate(eb, eb->pages[0]);
6974 kaddr = page_address(eb->pages[0]) +
6975 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6976 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6979 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6980 unsigned long start, unsigned long len)
6986 char *src = (char *)srcv;
6987 unsigned long i = get_eb_page_index(start);
6989 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6991 if (check_eb_range(eb, start, len))
6994 offset = get_eb_offset_in_page(eb, start);
6997 page = eb->pages[i];
6998 assert_eb_page_uptodate(eb, page);
7000 cur = min(len, PAGE_SIZE - offset);
7001 kaddr = page_address(page);
7002 memcpy(kaddr + offset, src, cur);
7011 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
7018 unsigned long i = get_eb_page_index(start);
7020 if (check_eb_range(eb, start, len))
7023 offset = get_eb_offset_in_page(eb, start);
7026 page = eb->pages[i];
7027 assert_eb_page_uptodate(eb, page);
7029 cur = min(len, PAGE_SIZE - offset);
7030 kaddr = page_address(page);
7031 memset(kaddr + offset, 0, cur);
7039 void copy_extent_buffer_full(const struct extent_buffer *dst,
7040 const struct extent_buffer *src)
7045 ASSERT(dst->len == src->len);
7047 if (dst->fs_info->nodesize >= PAGE_SIZE) {
7048 num_pages = num_extent_pages(dst);
7049 for (i = 0; i < num_pages; i++)
7050 copy_page(page_address(dst->pages[i]),
7051 page_address(src->pages[i]));
7053 size_t src_offset = get_eb_offset_in_page(src, 0);
7054 size_t dst_offset = get_eb_offset_in_page(dst, 0);
7056 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
7057 memcpy(page_address(dst->pages[0]) + dst_offset,
7058 page_address(src->pages[0]) + src_offset,
7063 void copy_extent_buffer(const struct extent_buffer *dst,
7064 const struct extent_buffer *src,
7065 unsigned long dst_offset, unsigned long src_offset,
7068 u64 dst_len = dst->len;
7073 unsigned long i = get_eb_page_index(dst_offset);
7075 if (check_eb_range(dst, dst_offset, len) ||
7076 check_eb_range(src, src_offset, len))
7079 WARN_ON(src->len != dst_len);
7081 offset = get_eb_offset_in_page(dst, dst_offset);
7084 page = dst->pages[i];
7085 assert_eb_page_uptodate(dst, page);
7087 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
7089 kaddr = page_address(page);
7090 read_extent_buffer(src, kaddr + offset, src_offset, cur);
7100 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
7102 * @eb: the extent buffer
7103 * @start: offset of the bitmap item in the extent buffer
7105 * @page_index: return index of the page in the extent buffer that contains the
7107 * @page_offset: return offset into the page given by page_index
7109 * This helper hides the ugliness of finding the byte in an extent buffer which
7110 * contains a given bit.
7112 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
7113 unsigned long start, unsigned long nr,
7114 unsigned long *page_index,
7115 size_t *page_offset)
7117 size_t byte_offset = BIT_BYTE(nr);
7121 * The byte we want is the offset of the extent buffer + the offset of
7122 * the bitmap item in the extent buffer + the offset of the byte in the
7125 offset = start + offset_in_page(eb->start) + byte_offset;
7127 *page_index = offset >> PAGE_SHIFT;
7128 *page_offset = offset_in_page(offset);
7132 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
7133 * @eb: the extent buffer
7134 * @start: offset of the bitmap item in the extent buffer
7135 * @nr: bit number to test
7137 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
7145 eb_bitmap_offset(eb, start, nr, &i, &offset);
7146 page = eb->pages[i];
7147 assert_eb_page_uptodate(eb, page);
7148 kaddr = page_address(page);
7149 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
7153 * extent_buffer_bitmap_set - set an area of a bitmap
7154 * @eb: the extent buffer
7155 * @start: offset of the bitmap item in the extent buffer
7156 * @pos: bit number of the first bit
7157 * @len: number of bits to set
7159 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
7160 unsigned long pos, unsigned long len)
7166 const unsigned int size = pos + len;
7167 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7168 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
7170 eb_bitmap_offset(eb, start, pos, &i, &offset);
7171 page = eb->pages[i];
7172 assert_eb_page_uptodate(eb, page);
7173 kaddr = page_address(page);
7175 while (len >= bits_to_set) {
7176 kaddr[offset] |= mask_to_set;
7178 bits_to_set = BITS_PER_BYTE;
7180 if (++offset >= PAGE_SIZE && len > 0) {
7182 page = eb->pages[++i];
7183 assert_eb_page_uptodate(eb, page);
7184 kaddr = page_address(page);
7188 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
7189 kaddr[offset] |= mask_to_set;
7195 * extent_buffer_bitmap_clear - clear an area of a bitmap
7196 * @eb: the extent buffer
7197 * @start: offset of the bitmap item in the extent buffer
7198 * @pos: bit number of the first bit
7199 * @len: number of bits to clear
7201 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
7202 unsigned long start, unsigned long pos,
7209 const unsigned int size = pos + len;
7210 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7211 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
7213 eb_bitmap_offset(eb, start, pos, &i, &offset);
7214 page = eb->pages[i];
7215 assert_eb_page_uptodate(eb, page);
7216 kaddr = page_address(page);
7218 while (len >= bits_to_clear) {
7219 kaddr[offset] &= ~mask_to_clear;
7220 len -= bits_to_clear;
7221 bits_to_clear = BITS_PER_BYTE;
7223 if (++offset >= PAGE_SIZE && len > 0) {
7225 page = eb->pages[++i];
7226 assert_eb_page_uptodate(eb, page);
7227 kaddr = page_address(page);
7231 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
7232 kaddr[offset] &= ~mask_to_clear;
7236 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
7238 unsigned long distance = (src > dst) ? src - dst : dst - src;
7239 return distance < len;
7242 static void copy_pages(struct page *dst_page, struct page *src_page,
7243 unsigned long dst_off, unsigned long src_off,
7246 char *dst_kaddr = page_address(dst_page);
7248 int must_memmove = 0;
7250 if (dst_page != src_page) {
7251 src_kaddr = page_address(src_page);
7253 src_kaddr = dst_kaddr;
7254 if (areas_overlap(src_off, dst_off, len))
7259 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
7261 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
7264 void memcpy_extent_buffer(const struct extent_buffer *dst,
7265 unsigned long dst_offset, unsigned long src_offset,
7269 size_t dst_off_in_page;
7270 size_t src_off_in_page;
7271 unsigned long dst_i;
7272 unsigned long src_i;
7274 if (check_eb_range(dst, dst_offset, len) ||
7275 check_eb_range(dst, src_offset, len))
7279 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
7280 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
7282 dst_i = get_eb_page_index(dst_offset);
7283 src_i = get_eb_page_index(src_offset);
7285 cur = min(len, (unsigned long)(PAGE_SIZE -
7287 cur = min_t(unsigned long, cur,
7288 (unsigned long)(PAGE_SIZE - dst_off_in_page));
7290 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7291 dst_off_in_page, src_off_in_page, cur);
7299 void memmove_extent_buffer(const struct extent_buffer *dst,
7300 unsigned long dst_offset, unsigned long src_offset,
7304 size_t dst_off_in_page;
7305 size_t src_off_in_page;
7306 unsigned long dst_end = dst_offset + len - 1;
7307 unsigned long src_end = src_offset + len - 1;
7308 unsigned long dst_i;
7309 unsigned long src_i;
7311 if (check_eb_range(dst, dst_offset, len) ||
7312 check_eb_range(dst, src_offset, len))
7314 if (dst_offset < src_offset) {
7315 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
7319 dst_i = get_eb_page_index(dst_end);
7320 src_i = get_eb_page_index(src_end);
7322 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
7323 src_off_in_page = get_eb_offset_in_page(dst, src_end);
7325 cur = min_t(unsigned long, len, src_off_in_page + 1);
7326 cur = min(cur, dst_off_in_page + 1);
7327 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7328 dst_off_in_page - cur + 1,
7329 src_off_in_page - cur + 1, cur);
7337 #define GANG_LOOKUP_SIZE 16
7338 static struct extent_buffer *get_next_extent_buffer(
7339 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
7341 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
7342 struct extent_buffer *found = NULL;
7343 u64 page_start = page_offset(page);
7344 u64 cur = page_start;
7346 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7347 lockdep_assert_held(&fs_info->buffer_lock);
7349 while (cur < page_start + PAGE_SIZE) {
7353 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
7354 (void **)gang, cur >> fs_info->sectorsize_bits,
7355 min_t(unsigned int, GANG_LOOKUP_SIZE,
7356 PAGE_SIZE / fs_info->nodesize));
7359 for (i = 0; i < ret; i++) {
7360 /* Already beyond page end */
7361 if (gang[i]->start >= page_start + PAGE_SIZE)
7364 if (gang[i]->start >= bytenr) {
7369 cur = gang[ret - 1]->start + gang[ret - 1]->len;
7375 static int try_release_subpage_extent_buffer(struct page *page)
7377 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7378 u64 cur = page_offset(page);
7379 const u64 end = page_offset(page) + PAGE_SIZE;
7383 struct extent_buffer *eb = NULL;
7386 * Unlike try_release_extent_buffer() which uses page->private
7387 * to grab buffer, for subpage case we rely on radix tree, thus
7388 * we need to ensure radix tree consistency.
7390 * We also want an atomic snapshot of the radix tree, thus go
7391 * with spinlock rather than RCU.
7393 spin_lock(&fs_info->buffer_lock);
7394 eb = get_next_extent_buffer(fs_info, page, cur);
7396 /* No more eb in the page range after or at cur */
7397 spin_unlock(&fs_info->buffer_lock);
7400 cur = eb->start + eb->len;
7403 * The same as try_release_extent_buffer(), to ensure the eb
7404 * won't disappear out from under us.
7406 spin_lock(&eb->refs_lock);
7407 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7408 spin_unlock(&eb->refs_lock);
7409 spin_unlock(&fs_info->buffer_lock);
7412 spin_unlock(&fs_info->buffer_lock);
7415 * If tree ref isn't set then we know the ref on this eb is a
7416 * real ref, so just return, this eb will likely be freed soon
7419 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7420 spin_unlock(&eb->refs_lock);
7425 * Here we don't care about the return value, we will always
7426 * check the page private at the end. And
7427 * release_extent_buffer() will release the refs_lock.
7429 release_extent_buffer(eb);
7432 * Finally to check if we have cleared page private, as if we have
7433 * released all ebs in the page, the page private should be cleared now.
7435 spin_lock(&page->mapping->private_lock);
7436 if (!PagePrivate(page))
7440 spin_unlock(&page->mapping->private_lock);
7445 int try_release_extent_buffer(struct page *page)
7447 struct extent_buffer *eb;
7449 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
7450 return try_release_subpage_extent_buffer(page);
7453 * We need to make sure nobody is changing page->private, as we rely on
7454 * page->private as the pointer to extent buffer.
7456 spin_lock(&page->mapping->private_lock);
7457 if (!PagePrivate(page)) {
7458 spin_unlock(&page->mapping->private_lock);
7462 eb = (struct extent_buffer *)page->private;
7466 * This is a little awful but should be ok, we need to make sure that
7467 * the eb doesn't disappear out from under us while we're looking at
7470 spin_lock(&eb->refs_lock);
7471 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7472 spin_unlock(&eb->refs_lock);
7473 spin_unlock(&page->mapping->private_lock);
7476 spin_unlock(&page->mapping->private_lock);
7479 * If tree ref isn't set then we know the ref on this eb is a real ref,
7480 * so just return, this page will likely be freed soon anyway.
7482 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7483 spin_unlock(&eb->refs_lock);
7487 return release_extent_buffer(eb);
7491 * btrfs_readahead_tree_block - attempt to readahead a child block
7492 * @fs_info: the fs_info
7493 * @bytenr: bytenr to read
7494 * @owner_root: objectid of the root that owns this eb
7495 * @gen: generation for the uptodate check, can be 0
7496 * @level: level for the eb
7498 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7499 * normal uptodate check of the eb, without checking the generation. If we have
7500 * to read the block we will not block on anything.
7502 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7503 u64 bytenr, u64 owner_root, u64 gen, int level)
7505 struct extent_buffer *eb;
7508 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7512 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7513 free_extent_buffer(eb);
7517 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7519 free_extent_buffer_stale(eb);
7521 free_extent_buffer(eb);
7525 * btrfs_readahead_node_child - readahead a node's child block
7526 * @node: parent node we're reading from
7527 * @slot: slot in the parent node for the child we want to read
7529 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7530 * the slot in the node provided.
7532 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7534 btrfs_readahead_tree_block(node->fs_info,
7535 btrfs_node_blockptr(node, slot),
7536 btrfs_header_owner(node),
7537 btrfs_node_ptr_generation(node, slot),
7538 btrfs_header_level(node) - 1);