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"
33 static struct kmem_cache *extent_state_cache;
34 static struct kmem_cache *extent_buffer_cache;
35 static struct bio_set btrfs_bioset;
37 static inline bool extent_state_in_tree(const struct extent_state *state)
39 return !RB_EMPTY_NODE(&state->rb_node);
42 #ifdef CONFIG_BTRFS_DEBUG
43 static LIST_HEAD(states);
44 static DEFINE_SPINLOCK(leak_lock);
46 static inline void btrfs_leak_debug_add(spinlock_t *lock,
47 struct list_head *new,
48 struct list_head *head)
52 spin_lock_irqsave(lock, flags);
54 spin_unlock_irqrestore(lock, flags);
57 static inline void btrfs_leak_debug_del(spinlock_t *lock,
58 struct list_head *entry)
62 spin_lock_irqsave(lock, flags);
64 spin_unlock_irqrestore(lock, flags);
67 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
69 struct extent_buffer *eb;
73 * If we didn't get into open_ctree our allocated_ebs will not be
74 * initialized, so just skip this.
76 if (!fs_info->allocated_ebs.next)
79 WARN_ON(!list_empty(&fs_info->allocated_ebs));
80 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
81 while (!list_empty(&fs_info->allocated_ebs)) {
82 eb = list_first_entry(&fs_info->allocated_ebs,
83 struct extent_buffer, leak_list);
85 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
86 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
87 btrfs_header_owner(eb));
88 list_del(&eb->leak_list);
89 kmem_cache_free(extent_buffer_cache, eb);
91 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
94 static inline void btrfs_extent_state_leak_debug_check(void)
96 struct extent_state *state;
98 while (!list_empty(&states)) {
99 state = list_entry(states.next, struct extent_state, leak_list);
100 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
101 state->start, state->end, state->state,
102 extent_state_in_tree(state),
103 refcount_read(&state->refs));
104 list_del(&state->leak_list);
105 kmem_cache_free(extent_state_cache, state);
109 #define btrfs_debug_check_extent_io_range(tree, start, end) \
110 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
111 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
112 struct extent_io_tree *tree, u64 start, u64 end)
114 struct inode *inode = tree->private_data;
117 if (!inode || !is_data_inode(inode))
120 isize = i_size_read(inode);
121 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
122 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
123 "%s: ino %llu isize %llu odd range [%llu,%llu]",
124 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
128 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
129 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
130 #define btrfs_extent_state_leak_debug_check() do {} while (0)
131 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
137 struct rb_node rb_node;
140 struct extent_page_data {
141 struct btrfs_bio_ctrl bio_ctrl;
142 /* tells writepage not to lock the state bits for this range
143 * it still does the unlocking
145 unsigned int extent_locked:1;
147 /* tells the submit_bio code to use REQ_SYNC */
148 unsigned int sync_io:1;
151 static int add_extent_changeset(struct extent_state *state, u32 bits,
152 struct extent_changeset *changeset,
159 if (set && (state->state & bits) == bits)
161 if (!set && (state->state & bits) == 0)
163 changeset->bytes_changed += state->end - state->start + 1;
164 ret = ulist_add(&changeset->range_changed, state->start, state->end,
169 void submit_one_bio(struct bio *bio, int mirror_num, unsigned long bio_flags)
171 struct extent_io_tree *tree = bio->bi_private;
173 bio->bi_private = NULL;
175 /* Caller should ensure the bio has at least some range added */
176 ASSERT(bio->bi_iter.bi_size);
178 if (is_data_inode(tree->private_data))
179 btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
182 btrfs_submit_metadata_bio(tree->private_data, bio,
183 mirror_num, bio_flags);
185 * Above submission hooks will handle the error by ending the bio,
186 * which will do the cleanup properly. So here we should not return
187 * any error, or the caller of submit_extent_page() will do cleanup
188 * again, causing problems.
192 /* Cleanup unsubmitted bios */
193 static void end_write_bio(struct extent_page_data *epd, int ret)
195 struct bio *bio = epd->bio_ctrl.bio;
198 bio->bi_status = errno_to_blk_status(ret);
200 epd->bio_ctrl.bio = NULL;
205 * Submit bio from extent page data via submit_one_bio
207 * Return 0 if everything is OK.
208 * Return <0 for error.
210 static void flush_write_bio(struct extent_page_data *epd)
212 struct bio *bio = epd->bio_ctrl.bio;
215 submit_one_bio(bio, 0, 0);
217 * Clean up of epd->bio is handled by its endio function.
218 * And endio is either triggered by successful bio execution
219 * or the error handler of submit bio hook.
220 * So at this point, no matter what happened, we don't need
221 * to clean up epd->bio.
223 epd->bio_ctrl.bio = NULL;
227 int __init extent_state_cache_init(void)
229 extent_state_cache = kmem_cache_create("btrfs_extent_state",
230 sizeof(struct extent_state), 0,
231 SLAB_MEM_SPREAD, NULL);
232 if (!extent_state_cache)
237 int __init extent_io_init(void)
239 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
240 sizeof(struct extent_buffer), 0,
241 SLAB_MEM_SPREAD, NULL);
242 if (!extent_buffer_cache)
245 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
246 offsetof(struct btrfs_bio, bio),
248 goto free_buffer_cache;
250 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
256 bioset_exit(&btrfs_bioset);
259 kmem_cache_destroy(extent_buffer_cache);
260 extent_buffer_cache = NULL;
264 void __cold extent_state_cache_exit(void)
266 btrfs_extent_state_leak_debug_check();
267 kmem_cache_destroy(extent_state_cache);
270 void __cold extent_io_exit(void)
273 * Make sure all delayed rcu free are flushed before we
277 kmem_cache_destroy(extent_buffer_cache);
278 bioset_exit(&btrfs_bioset);
282 * For the file_extent_tree, we want to hold the inode lock when we lookup and
283 * update the disk_i_size, but lockdep will complain because our io_tree we hold
284 * the tree lock and get the inode lock when setting delalloc. These two things
285 * are unrelated, so make a class for the file_extent_tree so we don't get the
286 * two locking patterns mixed up.
288 static struct lock_class_key file_extent_tree_class;
290 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
291 struct extent_io_tree *tree, unsigned int owner,
294 tree->fs_info = fs_info;
295 tree->state = RB_ROOT;
296 tree->dirty_bytes = 0;
297 spin_lock_init(&tree->lock);
298 tree->private_data = private_data;
300 if (owner == IO_TREE_INODE_FILE_EXTENT)
301 lockdep_set_class(&tree->lock, &file_extent_tree_class);
304 void extent_io_tree_release(struct extent_io_tree *tree)
306 spin_lock(&tree->lock);
308 * Do a single barrier for the waitqueue_active check here, the state
309 * of the waitqueue should not change once extent_io_tree_release is
313 while (!RB_EMPTY_ROOT(&tree->state)) {
314 struct rb_node *node;
315 struct extent_state *state;
317 node = rb_first(&tree->state);
318 state = rb_entry(node, struct extent_state, rb_node);
319 rb_erase(&state->rb_node, &tree->state);
320 RB_CLEAR_NODE(&state->rb_node);
322 * btree io trees aren't supposed to have tasks waiting for
323 * changes in the flags of extent states ever.
325 ASSERT(!waitqueue_active(&state->wq));
326 free_extent_state(state);
328 cond_resched_lock(&tree->lock);
330 spin_unlock(&tree->lock);
333 static struct extent_state *alloc_extent_state(gfp_t mask)
335 struct extent_state *state;
338 * The given mask might be not appropriate for the slab allocator,
339 * drop the unsupported bits
341 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
342 state = kmem_cache_alloc(extent_state_cache, mask);
346 state->failrec = NULL;
347 RB_CLEAR_NODE(&state->rb_node);
348 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
349 refcount_set(&state->refs, 1);
350 init_waitqueue_head(&state->wq);
351 trace_alloc_extent_state(state, mask, _RET_IP_);
355 void free_extent_state(struct extent_state *state)
359 if (refcount_dec_and_test(&state->refs)) {
360 WARN_ON(extent_state_in_tree(state));
361 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
362 trace_free_extent_state(state, _RET_IP_);
363 kmem_cache_free(extent_state_cache, state);
367 static struct rb_node *tree_insert(struct rb_root *root,
368 struct rb_node *search_start,
370 struct rb_node *node,
371 struct rb_node ***p_in,
372 struct rb_node **parent_in)
375 struct rb_node *parent = NULL;
376 struct tree_entry *entry;
378 if (p_in && parent_in) {
384 p = search_start ? &search_start : &root->rb_node;
387 entry = rb_entry(parent, struct tree_entry, rb_node);
389 if (offset < entry->start)
391 else if (offset > entry->end)
398 rb_link_node(node, parent, p);
399 rb_insert_color(node, root);
404 * Search @tree for an entry that contains @offset. Such entry would have
405 * entry->start <= offset && entry->end >= offset.
407 * @tree: the tree to search
408 * @offset: offset that should fall within an entry in @tree
409 * @next_ret: pointer to the first entry whose range ends after @offset
410 * @prev_ret: pointer to the first entry whose range begins before @offset
411 * @p_ret: pointer where new node should be anchored (used when inserting an
413 * @parent_ret: points to entry which would have been the parent of the entry,
416 * This function returns a pointer to the entry that contains @offset byte
417 * address. If no such entry exists, then NULL is returned and the other
418 * pointer arguments to the function are filled, otherwise the found entry is
419 * returned and other pointers are left untouched.
421 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
422 struct rb_node **next_ret,
423 struct rb_node **prev_ret,
424 struct rb_node ***p_ret,
425 struct rb_node **parent_ret)
427 struct rb_root *root = &tree->state;
428 struct rb_node **n = &root->rb_node;
429 struct rb_node *prev = NULL;
430 struct rb_node *orig_prev = NULL;
431 struct tree_entry *entry;
432 struct tree_entry *prev_entry = NULL;
436 entry = rb_entry(prev, struct tree_entry, rb_node);
439 if (offset < entry->start)
441 else if (offset > entry->end)
454 while (prev && offset > prev_entry->end) {
455 prev = rb_next(prev);
456 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
463 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
464 while (prev && offset < prev_entry->start) {
465 prev = rb_prev(prev);
466 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
473 static inline struct rb_node *
474 tree_search_for_insert(struct extent_io_tree *tree,
476 struct rb_node ***p_ret,
477 struct rb_node **parent_ret)
479 struct rb_node *next= NULL;
482 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
488 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
491 return tree_search_for_insert(tree, offset, NULL, NULL);
495 * utility function to look for merge candidates inside a given range.
496 * Any extents with matching state are merged together into a single
497 * extent in the tree. Extents with EXTENT_IO in their state field
498 * are not merged because the end_io handlers need to be able to do
499 * operations on them without sleeping (or doing allocations/splits).
501 * This should be called with the tree lock held.
503 static void merge_state(struct extent_io_tree *tree,
504 struct extent_state *state)
506 struct extent_state *other;
507 struct rb_node *other_node;
509 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
512 other_node = rb_prev(&state->rb_node);
514 other = rb_entry(other_node, struct extent_state, rb_node);
515 if (other->end == state->start - 1 &&
516 other->state == state->state) {
517 if (tree->private_data &&
518 is_data_inode(tree->private_data))
519 btrfs_merge_delalloc_extent(tree->private_data,
521 state->start = other->start;
522 rb_erase(&other->rb_node, &tree->state);
523 RB_CLEAR_NODE(&other->rb_node);
524 free_extent_state(other);
527 other_node = rb_next(&state->rb_node);
529 other = rb_entry(other_node, struct extent_state, rb_node);
530 if (other->start == state->end + 1 &&
531 other->state == state->state) {
532 if (tree->private_data &&
533 is_data_inode(tree->private_data))
534 btrfs_merge_delalloc_extent(tree->private_data,
536 state->end = other->end;
537 rb_erase(&other->rb_node, &tree->state);
538 RB_CLEAR_NODE(&other->rb_node);
539 free_extent_state(other);
544 static void set_state_bits(struct extent_io_tree *tree,
545 struct extent_state *state, u32 *bits,
546 struct extent_changeset *changeset);
549 * insert an extent_state struct into the tree. 'bits' are set on the
550 * struct before it is inserted.
552 * This may return -EEXIST if the extent is already there, in which case the
553 * state struct is freed.
555 * The tree lock is not taken internally. This is a utility function and
556 * probably isn't what you want to call (see set/clear_extent_bit).
558 static int insert_state(struct extent_io_tree *tree,
559 struct extent_state *state, u64 start, u64 end,
561 struct rb_node **parent,
562 u32 *bits, struct extent_changeset *changeset)
564 struct rb_node *node;
567 btrfs_err(tree->fs_info,
568 "insert state: end < start %llu %llu", end, start);
571 state->start = start;
574 set_state_bits(tree, state, bits, changeset);
576 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
578 struct extent_state *found;
579 found = rb_entry(node, struct extent_state, rb_node);
580 btrfs_err(tree->fs_info,
581 "found node %llu %llu on insert of %llu %llu",
582 found->start, found->end, start, end);
585 merge_state(tree, state);
590 * split a given extent state struct in two, inserting the preallocated
591 * struct 'prealloc' as the newly created second half. 'split' indicates an
592 * offset inside 'orig' where it should be split.
595 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
596 * are two extent state structs in the tree:
597 * prealloc: [orig->start, split - 1]
598 * orig: [ split, orig->end ]
600 * The tree locks are not taken by this function. They need to be held
603 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
604 struct extent_state *prealloc, u64 split)
606 struct rb_node *node;
608 if (tree->private_data && is_data_inode(tree->private_data))
609 btrfs_split_delalloc_extent(tree->private_data, orig, split);
611 prealloc->start = orig->start;
612 prealloc->end = split - 1;
613 prealloc->state = orig->state;
616 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
617 &prealloc->rb_node, NULL, NULL);
619 free_extent_state(prealloc);
625 static struct extent_state *next_state(struct extent_state *state)
627 struct rb_node *next = rb_next(&state->rb_node);
629 return rb_entry(next, struct extent_state, rb_node);
635 * utility function to clear some bits in an extent state struct.
636 * it will optionally wake up anyone waiting on this state (wake == 1).
638 * If no bits are set on the state struct after clearing things, the
639 * struct is freed and removed from the tree
641 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
642 struct extent_state *state,
644 struct extent_changeset *changeset)
646 struct extent_state *next;
647 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
650 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
651 u64 range = state->end - state->start + 1;
652 WARN_ON(range > tree->dirty_bytes);
653 tree->dirty_bytes -= range;
656 if (tree->private_data && is_data_inode(tree->private_data))
657 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
659 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
661 state->state &= ~bits_to_clear;
664 if (state->state == 0) {
665 next = next_state(state);
666 if (extent_state_in_tree(state)) {
667 rb_erase(&state->rb_node, &tree->state);
668 RB_CLEAR_NODE(&state->rb_node);
669 free_extent_state(state);
674 merge_state(tree, state);
675 next = next_state(state);
680 static struct extent_state *
681 alloc_extent_state_atomic(struct extent_state *prealloc)
684 prealloc = alloc_extent_state(GFP_ATOMIC);
689 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
691 btrfs_panic(tree->fs_info, err,
692 "locking error: extent tree was modified by another thread while locked");
696 * clear some bits on a range in the tree. This may require splitting
697 * or inserting elements in the tree, so the gfp mask is used to
698 * indicate which allocations or sleeping are allowed.
700 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
701 * the given range from the tree regardless of state (ie for truncate).
703 * the range [start, end] is inclusive.
705 * This takes the tree lock, and returns 0 on success and < 0 on error.
707 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
708 u32 bits, int wake, int delete,
709 struct extent_state **cached_state,
710 gfp_t mask, struct extent_changeset *changeset)
712 struct extent_state *state;
713 struct extent_state *cached;
714 struct extent_state *prealloc = NULL;
715 struct rb_node *node;
720 btrfs_debug_check_extent_io_range(tree, start, end);
721 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
723 if (bits & EXTENT_DELALLOC)
724 bits |= EXTENT_NORESERVE;
727 bits |= ~EXTENT_CTLBITS;
729 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
732 if (!prealloc && gfpflags_allow_blocking(mask)) {
734 * Don't care for allocation failure here because we might end
735 * up not needing the pre-allocated extent state at all, which
736 * is the case if we only have in the tree extent states that
737 * cover our input range and don't cover too any other range.
738 * If we end up needing a new extent state we allocate it later.
740 prealloc = alloc_extent_state(mask);
743 spin_lock(&tree->lock);
745 cached = *cached_state;
748 *cached_state = NULL;
752 if (cached && extent_state_in_tree(cached) &&
753 cached->start <= start && cached->end > start) {
755 refcount_dec(&cached->refs);
760 free_extent_state(cached);
763 * this search will find the extents that end after
766 node = tree_search(tree, start);
769 state = rb_entry(node, struct extent_state, rb_node);
771 if (state->start > end)
773 WARN_ON(state->end < start);
774 last_end = state->end;
776 /* the state doesn't have the wanted bits, go ahead */
777 if (!(state->state & bits)) {
778 state = next_state(state);
783 * | ---- desired range ---- |
785 * | ------------- state -------------- |
787 * We need to split the extent we found, and may flip
788 * bits on second half.
790 * If the extent we found extends past our range, we
791 * just split and search again. It'll get split again
792 * the next time though.
794 * If the extent we found is inside our range, we clear
795 * the desired bit on it.
798 if (state->start < start) {
799 prealloc = alloc_extent_state_atomic(prealloc);
801 err = split_state(tree, state, prealloc, start);
803 extent_io_tree_panic(tree, err);
808 if (state->end <= end) {
809 state = clear_state_bit(tree, state, &bits, wake,
816 * | ---- desired range ---- |
818 * We need to split the extent, and clear the bit
821 if (state->start <= end && state->end > end) {
822 prealloc = alloc_extent_state_atomic(prealloc);
824 err = split_state(tree, state, prealloc, end + 1);
826 extent_io_tree_panic(tree, err);
831 clear_state_bit(tree, prealloc, &bits, wake, changeset);
837 state = clear_state_bit(tree, state, &bits, wake, changeset);
839 if (last_end == (u64)-1)
841 start = last_end + 1;
842 if (start <= end && state && !need_resched())
848 spin_unlock(&tree->lock);
849 if (gfpflags_allow_blocking(mask))
854 spin_unlock(&tree->lock);
856 free_extent_state(prealloc);
862 static void wait_on_state(struct extent_io_tree *tree,
863 struct extent_state *state)
864 __releases(tree->lock)
865 __acquires(tree->lock)
868 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
869 spin_unlock(&tree->lock);
871 spin_lock(&tree->lock);
872 finish_wait(&state->wq, &wait);
876 * waits for one or more bits to clear on a range in the state tree.
877 * The range [start, end] is inclusive.
878 * The tree lock is taken by this function
880 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
883 struct extent_state *state;
884 struct rb_node *node;
886 btrfs_debug_check_extent_io_range(tree, start, end);
888 spin_lock(&tree->lock);
892 * this search will find all the extents that end after
895 node = tree_search(tree, start);
900 state = rb_entry(node, struct extent_state, rb_node);
902 if (state->start > end)
905 if (state->state & bits) {
906 start = state->start;
907 refcount_inc(&state->refs);
908 wait_on_state(tree, state);
909 free_extent_state(state);
912 start = state->end + 1;
917 if (!cond_resched_lock(&tree->lock)) {
918 node = rb_next(node);
923 spin_unlock(&tree->lock);
926 static void set_state_bits(struct extent_io_tree *tree,
927 struct extent_state *state,
928 u32 *bits, struct extent_changeset *changeset)
930 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
933 if (tree->private_data && is_data_inode(tree->private_data))
934 btrfs_set_delalloc_extent(tree->private_data, state, bits);
936 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
937 u64 range = state->end - state->start + 1;
938 tree->dirty_bytes += range;
940 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
942 state->state |= bits_to_set;
945 static void cache_state_if_flags(struct extent_state *state,
946 struct extent_state **cached_ptr,
949 if (cached_ptr && !(*cached_ptr)) {
950 if (!flags || (state->state & flags)) {
952 refcount_inc(&state->refs);
957 static void cache_state(struct extent_state *state,
958 struct extent_state **cached_ptr)
960 return cache_state_if_flags(state, cached_ptr,
961 EXTENT_LOCKED | EXTENT_BOUNDARY);
965 * set some bits on a range in the tree. This may require allocations or
966 * sleeping, so the gfp mask is used to indicate what is allowed.
968 * If any of the exclusive bits are set, this will fail with -EEXIST if some
969 * part of the range already has the desired bits set. The start of the
970 * existing range is returned in failed_start in this case.
972 * [start, end] is inclusive This takes the tree lock.
974 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
975 u32 exclusive_bits, u64 *failed_start,
976 struct extent_state **cached_state, gfp_t mask,
977 struct extent_changeset *changeset)
979 struct extent_state *state;
980 struct extent_state *prealloc = NULL;
981 struct rb_node *node;
983 struct rb_node *parent;
988 btrfs_debug_check_extent_io_range(tree, start, end);
989 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
992 ASSERT(failed_start);
994 ASSERT(failed_start == NULL);
996 if (!prealloc && gfpflags_allow_blocking(mask)) {
998 * Don't care for allocation failure here because we might end
999 * up not needing the pre-allocated extent state at all, which
1000 * is the case if we only have in the tree extent states that
1001 * cover our input range and don't cover too any other range.
1002 * If we end up needing a new extent state we allocate it later.
1004 prealloc = alloc_extent_state(mask);
1007 spin_lock(&tree->lock);
1008 if (cached_state && *cached_state) {
1009 state = *cached_state;
1010 if (state->start <= start && state->end > start &&
1011 extent_state_in_tree(state)) {
1012 node = &state->rb_node;
1017 * this search will find all the extents that end after
1020 node = tree_search_for_insert(tree, start, &p, &parent);
1022 prealloc = alloc_extent_state_atomic(prealloc);
1024 err = insert_state(tree, prealloc, start, end,
1025 &p, &parent, &bits, changeset);
1027 extent_io_tree_panic(tree, err);
1029 cache_state(prealloc, cached_state);
1033 state = rb_entry(node, struct extent_state, rb_node);
1035 last_start = state->start;
1036 last_end = state->end;
1039 * | ---- desired range ---- |
1042 * Just lock what we found and keep going
1044 if (state->start == start && state->end <= end) {
1045 if (state->state & exclusive_bits) {
1046 *failed_start = state->start;
1051 set_state_bits(tree, state, &bits, changeset);
1052 cache_state(state, cached_state);
1053 merge_state(tree, state);
1054 if (last_end == (u64)-1)
1056 start = last_end + 1;
1057 state = next_state(state);
1058 if (start < end && state && state->start == start &&
1065 * | ---- desired range ---- |
1068 * | ------------- state -------------- |
1070 * We need to split the extent we found, and may flip bits on
1073 * If the extent we found extends past our
1074 * range, we just split and search again. It'll get split
1075 * again the next time though.
1077 * If the extent we found is inside our range, we set the
1078 * desired bit on it.
1080 if (state->start < start) {
1081 if (state->state & exclusive_bits) {
1082 *failed_start = start;
1088 * If this extent already has all the bits we want set, then
1089 * skip it, not necessary to split it or do anything with it.
1091 if ((state->state & bits) == bits) {
1092 start = state->end + 1;
1093 cache_state(state, cached_state);
1097 prealloc = alloc_extent_state_atomic(prealloc);
1099 err = split_state(tree, state, prealloc, start);
1101 extent_io_tree_panic(tree, err);
1106 if (state->end <= end) {
1107 set_state_bits(tree, state, &bits, changeset);
1108 cache_state(state, cached_state);
1109 merge_state(tree, state);
1110 if (last_end == (u64)-1)
1112 start = last_end + 1;
1113 state = next_state(state);
1114 if (start < end && state && state->start == start &&
1121 * | ---- desired range ---- |
1122 * | state | or | state |
1124 * There's a hole, we need to insert something in it and
1125 * ignore the extent we found.
1127 if (state->start > start) {
1129 if (end < last_start)
1132 this_end = last_start - 1;
1134 prealloc = alloc_extent_state_atomic(prealloc);
1138 * Avoid to free 'prealloc' if it can be merged with
1141 err = insert_state(tree, prealloc, start, this_end,
1142 NULL, NULL, &bits, changeset);
1144 extent_io_tree_panic(tree, err);
1146 cache_state(prealloc, cached_state);
1148 start = this_end + 1;
1152 * | ---- desired range ---- |
1154 * We need to split the extent, and set the bit
1157 if (state->start <= end && state->end > end) {
1158 if (state->state & exclusive_bits) {
1159 *failed_start = start;
1164 prealloc = alloc_extent_state_atomic(prealloc);
1166 err = split_state(tree, state, prealloc, end + 1);
1168 extent_io_tree_panic(tree, err);
1170 set_state_bits(tree, prealloc, &bits, changeset);
1171 cache_state(prealloc, cached_state);
1172 merge_state(tree, prealloc);
1180 spin_unlock(&tree->lock);
1181 if (gfpflags_allow_blocking(mask))
1186 spin_unlock(&tree->lock);
1188 free_extent_state(prealloc);
1195 * convert_extent_bit - convert all bits in a given range from one bit to
1197 * @tree: the io tree to search
1198 * @start: the start offset in bytes
1199 * @end: the end offset in bytes (inclusive)
1200 * @bits: the bits to set in this range
1201 * @clear_bits: the bits to clear in this range
1202 * @cached_state: state that we're going to cache
1204 * This will go through and set bits for the given range. If any states exist
1205 * already in this range they are set with the given bit and cleared of the
1206 * clear_bits. This is only meant to be used by things that are mergeable, ie
1207 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1208 * boundary bits like LOCK.
1210 * All allocations are done with GFP_NOFS.
1212 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1213 u32 bits, u32 clear_bits,
1214 struct extent_state **cached_state)
1216 struct extent_state *state;
1217 struct extent_state *prealloc = NULL;
1218 struct rb_node *node;
1220 struct rb_node *parent;
1224 bool first_iteration = true;
1226 btrfs_debug_check_extent_io_range(tree, start, end);
1227 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1233 * Best effort, don't worry if extent state allocation fails
1234 * here for the first iteration. We might have a cached state
1235 * that matches exactly the target range, in which case no
1236 * extent state allocations are needed. We'll only know this
1237 * after locking the tree.
1239 prealloc = alloc_extent_state(GFP_NOFS);
1240 if (!prealloc && !first_iteration)
1244 spin_lock(&tree->lock);
1245 if (cached_state && *cached_state) {
1246 state = *cached_state;
1247 if (state->start <= start && state->end > start &&
1248 extent_state_in_tree(state)) {
1249 node = &state->rb_node;
1255 * this search will find all the extents that end after
1258 node = tree_search_for_insert(tree, start, &p, &parent);
1260 prealloc = alloc_extent_state_atomic(prealloc);
1265 err = insert_state(tree, prealloc, start, end,
1266 &p, &parent, &bits, NULL);
1268 extent_io_tree_panic(tree, err);
1269 cache_state(prealloc, cached_state);
1273 state = rb_entry(node, struct extent_state, rb_node);
1275 last_start = state->start;
1276 last_end = state->end;
1279 * | ---- desired range ---- |
1282 * Just lock what we found and keep going
1284 if (state->start == start && state->end <= end) {
1285 set_state_bits(tree, state, &bits, NULL);
1286 cache_state(state, cached_state);
1287 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1288 if (last_end == (u64)-1)
1290 start = last_end + 1;
1291 if (start < end && state && state->start == start &&
1298 * | ---- desired range ---- |
1301 * | ------------- state -------------- |
1303 * We need to split the extent we found, and may flip bits on
1306 * If the extent we found extends past our
1307 * range, we just split and search again. It'll get split
1308 * again the next time though.
1310 * If the extent we found is inside our range, we set the
1311 * desired bit on it.
1313 if (state->start < start) {
1314 prealloc = alloc_extent_state_atomic(prealloc);
1319 err = split_state(tree, state, prealloc, start);
1321 extent_io_tree_panic(tree, err);
1325 if (state->end <= end) {
1326 set_state_bits(tree, state, &bits, NULL);
1327 cache_state(state, cached_state);
1328 state = clear_state_bit(tree, state, &clear_bits, 0,
1330 if (last_end == (u64)-1)
1332 start = last_end + 1;
1333 if (start < end && state && state->start == start &&
1340 * | ---- desired range ---- |
1341 * | state | or | state |
1343 * There's a hole, we need to insert something in it and
1344 * ignore the extent we found.
1346 if (state->start > start) {
1348 if (end < last_start)
1351 this_end = last_start - 1;
1353 prealloc = alloc_extent_state_atomic(prealloc);
1360 * Avoid to free 'prealloc' if it can be merged with
1363 err = insert_state(tree, prealloc, start, this_end,
1364 NULL, NULL, &bits, NULL);
1366 extent_io_tree_panic(tree, err);
1367 cache_state(prealloc, cached_state);
1369 start = this_end + 1;
1373 * | ---- desired range ---- |
1375 * We need to split the extent, and set the bit
1378 if (state->start <= end && state->end > end) {
1379 prealloc = alloc_extent_state_atomic(prealloc);
1385 err = split_state(tree, state, prealloc, end + 1);
1387 extent_io_tree_panic(tree, err);
1389 set_state_bits(tree, prealloc, &bits, NULL);
1390 cache_state(prealloc, cached_state);
1391 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1399 spin_unlock(&tree->lock);
1401 first_iteration = false;
1405 spin_unlock(&tree->lock);
1407 free_extent_state(prealloc);
1412 /* wrappers around set/clear extent bit */
1413 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1414 u32 bits, struct extent_changeset *changeset)
1417 * We don't support EXTENT_LOCKED yet, as current changeset will
1418 * record any bits changed, so for EXTENT_LOCKED case, it will
1419 * either fail with -EEXIST or changeset will record the whole
1422 BUG_ON(bits & EXTENT_LOCKED);
1424 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1428 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1431 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1435 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1436 u32 bits, int wake, int delete,
1437 struct extent_state **cached)
1439 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1440 cached, GFP_NOFS, NULL);
1443 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1444 u32 bits, struct extent_changeset *changeset)
1447 * Don't support EXTENT_LOCKED case, same reason as
1448 * set_record_extent_bits().
1450 BUG_ON(bits & EXTENT_LOCKED);
1452 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1457 * either insert or lock state struct between start and end use mask to tell
1458 * us if waiting is desired.
1460 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1461 struct extent_state **cached_state)
1467 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1468 EXTENT_LOCKED, &failed_start,
1469 cached_state, GFP_NOFS, NULL);
1470 if (err == -EEXIST) {
1471 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1472 start = failed_start;
1475 WARN_ON(start > end);
1480 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1485 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1486 &failed_start, NULL, GFP_NOFS, NULL);
1487 if (err == -EEXIST) {
1488 if (failed_start > start)
1489 clear_extent_bit(tree, start, failed_start - 1,
1490 EXTENT_LOCKED, 1, 0, NULL);
1496 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1498 unsigned long index = start >> PAGE_SHIFT;
1499 unsigned long end_index = end >> PAGE_SHIFT;
1502 while (index <= end_index) {
1503 page = find_get_page(inode->i_mapping, index);
1504 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1505 clear_page_dirty_for_io(page);
1511 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1513 struct address_space *mapping = inode->i_mapping;
1514 unsigned long index = start >> PAGE_SHIFT;
1515 unsigned long end_index = end >> PAGE_SHIFT;
1516 struct folio *folio;
1518 while (index <= end_index) {
1519 folio = filemap_get_folio(mapping, index);
1520 filemap_dirty_folio(mapping, folio);
1521 folio_account_redirty(folio);
1522 index += folio_nr_pages(folio);
1527 /* find the first state struct with 'bits' set after 'start', and
1528 * return it. tree->lock must be held. NULL will returned if
1529 * nothing was found after 'start'
1531 static struct extent_state *
1532 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1534 struct rb_node *node;
1535 struct extent_state *state;
1538 * this search will find all the extents that end after
1541 node = tree_search(tree, start);
1546 state = rb_entry(node, struct extent_state, rb_node);
1547 if (state->end >= start && (state->state & bits))
1550 node = rb_next(node);
1559 * Find the first offset in the io tree with one or more @bits set.
1561 * Note: If there are multiple bits set in @bits, any of them will match.
1563 * Return 0 if we find something, and update @start_ret and @end_ret.
1564 * Return 1 if we found nothing.
1566 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1567 u64 *start_ret, u64 *end_ret, u32 bits,
1568 struct extent_state **cached_state)
1570 struct extent_state *state;
1573 spin_lock(&tree->lock);
1574 if (cached_state && *cached_state) {
1575 state = *cached_state;
1576 if (state->end == start - 1 && extent_state_in_tree(state)) {
1577 while ((state = next_state(state)) != NULL) {
1578 if (state->state & bits)
1581 free_extent_state(*cached_state);
1582 *cached_state = NULL;
1585 free_extent_state(*cached_state);
1586 *cached_state = NULL;
1589 state = find_first_extent_bit_state(tree, start, bits);
1592 cache_state_if_flags(state, cached_state, 0);
1593 *start_ret = state->start;
1594 *end_ret = state->end;
1598 spin_unlock(&tree->lock);
1603 * Find a contiguous area of bits
1605 * @tree: io tree to check
1606 * @start: offset to start the search from
1607 * @start_ret: the first offset we found with the bits set
1608 * @end_ret: the final contiguous range of the bits that were set
1609 * @bits: bits to look for
1611 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1612 * to set bits appropriately, and then merge them again. During this time it
1613 * will drop the tree->lock, so use this helper if you want to find the actual
1614 * contiguous area for given bits. We will search to the first bit we find, and
1615 * then walk down the tree until we find a non-contiguous area. The area
1616 * returned will be the full contiguous area with the bits set.
1618 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1619 u64 *start_ret, u64 *end_ret, u32 bits)
1621 struct extent_state *state;
1624 spin_lock(&tree->lock);
1625 state = find_first_extent_bit_state(tree, start, bits);
1627 *start_ret = state->start;
1628 *end_ret = state->end;
1629 while ((state = next_state(state)) != NULL) {
1630 if (state->start > (*end_ret + 1))
1632 *end_ret = state->end;
1636 spin_unlock(&tree->lock);
1641 * Find the first range that has @bits not set. This range could start before
1644 * @tree: the tree to search
1645 * @start: offset at/after which the found extent should start
1646 * @start_ret: records the beginning of the range
1647 * @end_ret: records the end of the range (inclusive)
1648 * @bits: the set of bits which must be unset
1650 * Since unallocated range is also considered one which doesn't have the bits
1651 * set it's possible that @end_ret contains -1, this happens in case the range
1652 * spans (last_range_end, end of device]. In this case it's up to the caller to
1653 * trim @end_ret to the appropriate size.
1655 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1656 u64 *start_ret, u64 *end_ret, u32 bits)
1658 struct extent_state *state;
1659 struct rb_node *node, *prev = NULL, *next;
1661 spin_lock(&tree->lock);
1663 /* Find first extent with bits cleared */
1665 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1666 if (!node && !next && !prev) {
1668 * Tree is completely empty, send full range and let
1669 * caller deal with it
1674 } else if (!node && !next) {
1676 * We are past the last allocated chunk, set start at
1677 * the end of the last extent.
1679 state = rb_entry(prev, struct extent_state, rb_node);
1680 *start_ret = state->end + 1;
1687 * At this point 'node' either contains 'start' or start is
1690 state = rb_entry(node, struct extent_state, rb_node);
1692 if (in_range(start, state->start, state->end - state->start + 1)) {
1693 if (state->state & bits) {
1695 * |--range with bits sets--|
1699 start = state->end + 1;
1702 * 'start' falls within a range that doesn't
1703 * have the bits set, so take its start as
1704 * the beginning of the desired range
1706 * |--range with bits cleared----|
1710 *start_ret = state->start;
1715 * |---prev range---|---hole/unset---|---node range---|
1721 * |---hole/unset--||--first node--|
1726 state = rb_entry(prev, struct extent_state,
1728 *start_ret = state->end + 1;
1737 * Find the longest stretch from start until an entry which has the
1741 state = rb_entry(node, struct extent_state, rb_node);
1742 if (state->end >= start && !(state->state & bits)) {
1743 *end_ret = state->end;
1745 *end_ret = state->start - 1;
1749 node = rb_next(node);
1754 spin_unlock(&tree->lock);
1758 * find a contiguous range of bytes in the file marked as delalloc, not
1759 * more than 'max_bytes'. start and end are used to return the range,
1761 * true is returned if we find something, false if nothing was in the tree
1763 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1764 u64 *end, u64 max_bytes,
1765 struct extent_state **cached_state)
1767 struct rb_node *node;
1768 struct extent_state *state;
1769 u64 cur_start = *start;
1771 u64 total_bytes = 0;
1773 spin_lock(&tree->lock);
1776 * this search will find all the extents that end after
1779 node = tree_search(tree, cur_start);
1786 state = rb_entry(node, struct extent_state, rb_node);
1787 if (found && (state->start != cur_start ||
1788 (state->state & EXTENT_BOUNDARY))) {
1791 if (!(state->state & EXTENT_DELALLOC)) {
1797 *start = state->start;
1798 *cached_state = state;
1799 refcount_inc(&state->refs);
1803 cur_start = state->end + 1;
1804 node = rb_next(node);
1805 total_bytes += state->end - state->start + 1;
1806 if (total_bytes >= max_bytes)
1812 spin_unlock(&tree->lock);
1817 * Process one page for __process_pages_contig().
1819 * Return >0 if we hit @page == @locked_page.
1820 * Return 0 if we updated the page status.
1821 * Return -EGAIN if the we need to try again.
1822 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1824 static int process_one_page(struct btrfs_fs_info *fs_info,
1825 struct address_space *mapping,
1826 struct page *page, struct page *locked_page,
1827 unsigned long page_ops, u64 start, u64 end)
1831 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1832 len = end + 1 - start;
1834 if (page_ops & PAGE_SET_ORDERED)
1835 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
1836 if (page_ops & PAGE_SET_ERROR)
1837 btrfs_page_clamp_set_error(fs_info, page, start, len);
1838 if (page_ops & PAGE_START_WRITEBACK) {
1839 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1840 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1842 if (page_ops & PAGE_END_WRITEBACK)
1843 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1845 if (page == locked_page)
1848 if (page_ops & PAGE_LOCK) {
1851 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
1854 if (!PageDirty(page) || page->mapping != mapping) {
1855 btrfs_page_end_writer_lock(fs_info, page, start, len);
1859 if (page_ops & PAGE_UNLOCK)
1860 btrfs_page_end_writer_lock(fs_info, page, start, len);
1864 static int __process_pages_contig(struct address_space *mapping,
1865 struct page *locked_page,
1866 u64 start, u64 end, unsigned long page_ops,
1869 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1870 pgoff_t start_index = start >> PAGE_SHIFT;
1871 pgoff_t end_index = end >> PAGE_SHIFT;
1872 pgoff_t index = start_index;
1873 unsigned long nr_pages = end_index - start_index + 1;
1874 unsigned long pages_processed = 0;
1875 struct page *pages[16];
1879 if (page_ops & PAGE_LOCK) {
1880 ASSERT(page_ops == PAGE_LOCK);
1881 ASSERT(processed_end && *processed_end == start);
1884 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1885 mapping_set_error(mapping, -EIO);
1887 while (nr_pages > 0) {
1890 found_pages = find_get_pages_contig(mapping, index,
1891 min_t(unsigned long,
1892 nr_pages, ARRAY_SIZE(pages)), pages);
1893 if (found_pages == 0) {
1895 * Only if we're going to lock these pages, we can find
1896 * nothing at @index.
1898 ASSERT(page_ops & PAGE_LOCK);
1903 for (i = 0; i < found_pages; i++) {
1906 process_ret = process_one_page(fs_info, mapping,
1907 pages[i], locked_page, page_ops,
1909 if (process_ret < 0) {
1910 for (; i < found_pages; i++)
1918 nr_pages -= found_pages;
1919 index += found_pages;
1923 if (err && processed_end) {
1925 * Update @processed_end. I know this is awful since it has
1926 * two different return value patterns (inclusive vs exclusive).
1928 * But the exclusive pattern is necessary if @start is 0, or we
1929 * underflow and check against processed_end won't work as
1932 if (pages_processed)
1933 *processed_end = min(end,
1934 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1936 *processed_end = start;
1941 static noinline void __unlock_for_delalloc(struct inode *inode,
1942 struct page *locked_page,
1945 unsigned long index = start >> PAGE_SHIFT;
1946 unsigned long end_index = end >> PAGE_SHIFT;
1948 ASSERT(locked_page);
1949 if (index == locked_page->index && end_index == index)
1952 __process_pages_contig(inode->i_mapping, locked_page, start, end,
1956 static noinline int lock_delalloc_pages(struct inode *inode,
1957 struct page *locked_page,
1961 unsigned long index = delalloc_start >> PAGE_SHIFT;
1962 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1963 u64 processed_end = delalloc_start;
1966 ASSERT(locked_page);
1967 if (index == locked_page->index && index == end_index)
1970 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1971 delalloc_end, PAGE_LOCK, &processed_end);
1972 if (ret == -EAGAIN && processed_end > delalloc_start)
1973 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1979 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1980 * more than @max_bytes.
1982 * @start: The original start bytenr to search.
1983 * Will store the extent range start bytenr.
1984 * @end: The original end bytenr of the search range
1985 * Will store the extent range end bytenr.
1987 * Return true if we find a delalloc range which starts inside the original
1988 * range, and @start/@end will store the delalloc range start/end.
1990 * Return false if we can't find any delalloc range which starts inside the
1991 * original range, and @start/@end will be the non-delalloc range start/end.
1994 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1995 struct page *locked_page, u64 *start,
1998 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1999 const u64 orig_start = *start;
2000 const u64 orig_end = *end;
2001 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
2005 struct extent_state *cached_state = NULL;
2009 /* Caller should pass a valid @end to indicate the search range end */
2010 ASSERT(orig_end > orig_start);
2012 /* The range should at least cover part of the page */
2013 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
2014 orig_end <= page_offset(locked_page)));
2016 /* step one, find a bunch of delalloc bytes starting at start */
2017 delalloc_start = *start;
2019 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
2020 max_bytes, &cached_state);
2021 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
2022 *start = delalloc_start;
2024 /* @delalloc_end can be -1, never go beyond @orig_end */
2025 *end = min(delalloc_end, orig_end);
2026 free_extent_state(cached_state);
2031 * start comes from the offset of locked_page. We have to lock
2032 * pages in order, so we can't process delalloc bytes before
2035 if (delalloc_start < *start)
2036 delalloc_start = *start;
2039 * make sure to limit the number of pages we try to lock down
2041 if (delalloc_end + 1 - delalloc_start > max_bytes)
2042 delalloc_end = delalloc_start + max_bytes - 1;
2044 /* step two, lock all the pages after the page that has start */
2045 ret = lock_delalloc_pages(inode, locked_page,
2046 delalloc_start, delalloc_end);
2047 ASSERT(!ret || ret == -EAGAIN);
2048 if (ret == -EAGAIN) {
2049 /* some of the pages are gone, lets avoid looping by
2050 * shortening the size of the delalloc range we're searching
2052 free_extent_state(cached_state);
2053 cached_state = NULL;
2055 max_bytes = PAGE_SIZE;
2064 /* step three, lock the state bits for the whole range */
2065 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2067 /* then test to make sure it is all still delalloc */
2068 ret = test_range_bit(tree, delalloc_start, delalloc_end,
2069 EXTENT_DELALLOC, 1, cached_state);
2071 unlock_extent_cached(tree, delalloc_start, delalloc_end,
2073 __unlock_for_delalloc(inode, locked_page,
2074 delalloc_start, delalloc_end);
2078 free_extent_state(cached_state);
2079 *start = delalloc_start;
2080 *end = delalloc_end;
2085 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2086 struct page *locked_page,
2087 u32 clear_bits, unsigned long page_ops)
2089 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2091 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2092 start, end, page_ops, NULL);
2096 * count the number of bytes in the tree that have a given bit(s)
2097 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2098 * cached. The total number found is returned.
2100 u64 count_range_bits(struct extent_io_tree *tree,
2101 u64 *start, u64 search_end, u64 max_bytes,
2102 u32 bits, int contig)
2104 struct rb_node *node;
2105 struct extent_state *state;
2106 u64 cur_start = *start;
2107 u64 total_bytes = 0;
2111 if (WARN_ON(search_end <= cur_start))
2114 spin_lock(&tree->lock);
2115 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2116 total_bytes = tree->dirty_bytes;
2120 * this search will find all the extents that end after
2123 node = tree_search(tree, cur_start);
2128 state = rb_entry(node, struct extent_state, rb_node);
2129 if (state->start > search_end)
2131 if (contig && found && state->start > last + 1)
2133 if (state->end >= cur_start && (state->state & bits) == bits) {
2134 total_bytes += min(search_end, state->end) + 1 -
2135 max(cur_start, state->start);
2136 if (total_bytes >= max_bytes)
2139 *start = max(cur_start, state->start);
2143 } else if (contig && found) {
2146 node = rb_next(node);
2151 spin_unlock(&tree->lock);
2156 * set the private field for a given byte offset in the tree. If there isn't
2157 * an extent_state there already, this does nothing.
2159 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2160 struct io_failure_record *failrec)
2162 struct rb_node *node;
2163 struct extent_state *state;
2166 spin_lock(&tree->lock);
2168 * this search will find all the extents that end after
2171 node = tree_search(tree, start);
2176 state = rb_entry(node, struct extent_state, rb_node);
2177 if (state->start != start) {
2181 state->failrec = failrec;
2183 spin_unlock(&tree->lock);
2187 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2189 struct rb_node *node;
2190 struct extent_state *state;
2191 struct io_failure_record *failrec;
2193 spin_lock(&tree->lock);
2195 * this search will find all the extents that end after
2198 node = tree_search(tree, start);
2200 failrec = ERR_PTR(-ENOENT);
2203 state = rb_entry(node, struct extent_state, rb_node);
2204 if (state->start != start) {
2205 failrec = ERR_PTR(-ENOENT);
2209 failrec = state->failrec;
2211 spin_unlock(&tree->lock);
2216 * searches a range in the state tree for a given mask.
2217 * If 'filled' == 1, this returns 1 only if every extent in the tree
2218 * has the bits set. Otherwise, 1 is returned if any bit in the
2219 * range is found set.
2221 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2222 u32 bits, int filled, struct extent_state *cached)
2224 struct extent_state *state = NULL;
2225 struct rb_node *node;
2228 spin_lock(&tree->lock);
2229 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2230 cached->end > start)
2231 node = &cached->rb_node;
2233 node = tree_search(tree, start);
2234 while (node && start <= end) {
2235 state = rb_entry(node, struct extent_state, rb_node);
2237 if (filled && state->start > start) {
2242 if (state->start > end)
2245 if (state->state & bits) {
2249 } else if (filled) {
2254 if (state->end == (u64)-1)
2257 start = state->end + 1;
2260 node = rb_next(node);
2267 spin_unlock(&tree->lock);
2271 int free_io_failure(struct extent_io_tree *failure_tree,
2272 struct extent_io_tree *io_tree,
2273 struct io_failure_record *rec)
2278 set_state_failrec(failure_tree, rec->start, NULL);
2279 ret = clear_extent_bits(failure_tree, rec->start,
2280 rec->start + rec->len - 1,
2281 EXTENT_LOCKED | EXTENT_DIRTY);
2285 ret = clear_extent_bits(io_tree, rec->start,
2286 rec->start + rec->len - 1,
2296 * this bypasses the standard btrfs submit functions deliberately, as
2297 * the standard behavior is to write all copies in a raid setup. here we only
2298 * want to write the one bad copy. so we do the mapping for ourselves and issue
2299 * submit_bio directly.
2300 * to avoid any synchronization issues, wait for the data after writing, which
2301 * actually prevents the read that triggered the error from finishing.
2302 * currently, there can be no more than two copies of every data bit. thus,
2303 * exactly one rewrite is required.
2305 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2306 u64 length, u64 logical, struct page *page,
2307 unsigned int pg_offset, int mirror_num)
2309 struct btrfs_device *dev;
2310 struct bio_vec bvec;
2314 struct btrfs_io_context *bioc = NULL;
2317 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2318 BUG_ON(!mirror_num);
2320 if (btrfs_repair_one_zone(fs_info, logical))
2323 map_length = length;
2326 * Avoid races with device replace and make sure our bioc has devices
2327 * associated to its stripes that don't go away while we are doing the
2328 * read repair operation.
2330 btrfs_bio_counter_inc_blocked(fs_info);
2331 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2333 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2334 * to update all raid stripes, but here we just want to correct
2335 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2336 * stripe's dev and sector.
2338 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2339 &map_length, &bioc, 0);
2341 goto out_counter_dec;
2342 ASSERT(bioc->mirror_num == 1);
2344 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2345 &map_length, &bioc, mirror_num);
2347 goto out_counter_dec;
2348 BUG_ON(mirror_num != bioc->mirror_num);
2351 sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
2352 dev = bioc->stripes[bioc->mirror_num - 1].dev;
2353 btrfs_put_bioc(bioc);
2355 if (!dev || !dev->bdev ||
2356 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2358 goto out_counter_dec;
2361 bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
2362 bio.bi_iter.bi_sector = sector;
2363 __bio_add_page(&bio, page, length, pg_offset);
2365 btrfsic_check_bio(&bio);
2366 ret = submit_bio_wait(&bio);
2368 /* try to remap that extent elsewhere? */
2369 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2370 goto out_bio_uninit;
2373 btrfs_info_rl_in_rcu(fs_info,
2374 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2376 rcu_str_deref(dev->name), sector);
2382 btrfs_bio_counter_dec(fs_info);
2386 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2388 struct btrfs_fs_info *fs_info = eb->fs_info;
2389 u64 start = eb->start;
2390 int i, num_pages = num_extent_pages(eb);
2393 if (sb_rdonly(fs_info->sb))
2396 for (i = 0; i < num_pages; i++) {
2397 struct page *p = eb->pages[i];
2399 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2400 start - page_offset(p), mirror_num);
2410 * each time an IO finishes, we do a fast check in the IO failure tree
2411 * to see if we need to process or clean up an io_failure_record
2413 int clean_io_failure(struct btrfs_fs_info *fs_info,
2414 struct extent_io_tree *failure_tree,
2415 struct extent_io_tree *io_tree, u64 start,
2416 struct page *page, u64 ino, unsigned int pg_offset)
2419 struct io_failure_record *failrec;
2420 struct extent_state *state;
2425 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2430 failrec = get_state_failrec(failure_tree, start);
2431 if (IS_ERR(failrec))
2434 BUG_ON(!failrec->this_mirror);
2436 if (sb_rdonly(fs_info->sb))
2439 spin_lock(&io_tree->lock);
2440 state = find_first_extent_bit_state(io_tree,
2443 spin_unlock(&io_tree->lock);
2445 if (state && state->start <= failrec->start &&
2446 state->end >= failrec->start + failrec->len - 1) {
2447 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2449 if (num_copies > 1) {
2450 repair_io_failure(fs_info, ino, start, failrec->len,
2451 failrec->logical, page, pg_offset,
2452 failrec->failed_mirror);
2457 free_io_failure(failure_tree, io_tree, failrec);
2463 * Can be called when
2464 * - hold extent lock
2465 * - under ordered extent
2466 * - the inode is freeing
2468 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2470 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2471 struct io_failure_record *failrec;
2472 struct extent_state *state, *next;
2474 if (RB_EMPTY_ROOT(&failure_tree->state))
2477 spin_lock(&failure_tree->lock);
2478 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2480 if (state->start > end)
2483 ASSERT(state->end <= end);
2485 next = next_state(state);
2487 failrec = state->failrec;
2488 free_extent_state(state);
2493 spin_unlock(&failure_tree->lock);
2496 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2499 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2500 struct io_failure_record *failrec;
2501 struct extent_map *em;
2502 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2503 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2504 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2505 const u32 sectorsize = fs_info->sectorsize;
2509 failrec = get_state_failrec(failure_tree, start);
2510 if (!IS_ERR(failrec)) {
2511 btrfs_debug(fs_info,
2512 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2513 failrec->logical, failrec->start, failrec->len);
2515 * when data can be on disk more than twice, add to failrec here
2516 * (e.g. with a list for failed_mirror) to make
2517 * clean_io_failure() clean all those errors at once.
2523 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2525 return ERR_PTR(-ENOMEM);
2527 failrec->start = start;
2528 failrec->len = sectorsize;
2529 failrec->this_mirror = 0;
2530 failrec->bio_flags = 0;
2532 read_lock(&em_tree->lock);
2533 em = lookup_extent_mapping(em_tree, start, failrec->len);
2535 read_unlock(&em_tree->lock);
2537 return ERR_PTR(-EIO);
2540 if (em->start > start || em->start + em->len <= start) {
2541 free_extent_map(em);
2544 read_unlock(&em_tree->lock);
2547 return ERR_PTR(-EIO);
2550 logical = start - em->start;
2551 logical = em->block_start + logical;
2552 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2553 logical = em->block_start;
2554 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2555 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2558 btrfs_debug(fs_info,
2559 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2560 logical, start, failrec->len);
2562 failrec->logical = logical;
2563 free_extent_map(em);
2565 /* Set the bits in the private failure tree */
2566 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2567 EXTENT_LOCKED | EXTENT_DIRTY);
2569 ret = set_state_failrec(failure_tree, start, failrec);
2570 /* Set the bits in the inode's tree */
2571 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2573 } else if (ret < 0) {
2575 return ERR_PTR(ret);
2581 static bool btrfs_check_repairable(struct inode *inode,
2582 struct io_failure_record *failrec,
2585 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2588 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2589 if (num_copies == 1) {
2591 * we only have a single copy of the data, so don't bother with
2592 * all the retry and error correction code that follows. no
2593 * matter what the error is, it is very likely to persist.
2595 btrfs_debug(fs_info,
2596 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2597 num_copies, failrec->this_mirror, failed_mirror);
2601 /* The failure record should only contain one sector */
2602 ASSERT(failrec->len == fs_info->sectorsize);
2605 * There are two premises:
2606 * a) deliver good data to the caller
2607 * b) correct the bad sectors on disk
2609 * Since we're only doing repair for one sector, we only need to get
2610 * a good copy of the failed sector and if we succeed, we have setup
2611 * everything for repair_io_failure to do the rest for us.
2613 ASSERT(failed_mirror);
2614 failrec->failed_mirror = failed_mirror;
2615 failrec->this_mirror++;
2616 if (failrec->this_mirror == failed_mirror)
2617 failrec->this_mirror++;
2619 if (failrec->this_mirror > num_copies) {
2620 btrfs_debug(fs_info,
2621 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2622 num_copies, failrec->this_mirror, failed_mirror);
2629 int btrfs_repair_one_sector(struct inode *inode,
2630 struct bio *failed_bio, u32 bio_offset,
2631 struct page *page, unsigned int pgoff,
2632 u64 start, int failed_mirror,
2633 submit_bio_hook_t *submit_bio_hook)
2635 struct io_failure_record *failrec;
2636 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2637 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2638 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2639 struct btrfs_bio *failed_bbio = btrfs_bio(failed_bio);
2640 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2641 struct bio *repair_bio;
2642 struct btrfs_bio *repair_bbio;
2644 btrfs_debug(fs_info,
2645 "repair read error: read error at %llu", start);
2647 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2649 failrec = btrfs_get_io_failure_record(inode, start);
2650 if (IS_ERR(failrec))
2651 return PTR_ERR(failrec);
2654 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2655 free_io_failure(failure_tree, tree, failrec);
2659 repair_bio = btrfs_bio_alloc(1);
2660 repair_bbio = btrfs_bio(repair_bio);
2661 repair_bbio->file_offset = start;
2662 repair_bio->bi_opf = REQ_OP_READ;
2663 repair_bio->bi_end_io = failed_bio->bi_end_io;
2664 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2665 repair_bio->bi_private = failed_bio->bi_private;
2667 if (failed_bbio->csum) {
2668 const u32 csum_size = fs_info->csum_size;
2670 repair_bbio->csum = repair_bbio->csum_inline;
2671 memcpy(repair_bbio->csum,
2672 failed_bbio->csum + csum_size * icsum, csum_size);
2675 bio_add_page(repair_bio, page, failrec->len, pgoff);
2676 repair_bbio->iter = repair_bio->bi_iter;
2678 btrfs_debug(btrfs_sb(inode->i_sb),
2679 "repair read error: submitting new read to mirror %d",
2680 failrec->this_mirror);
2683 * At this point we have a bio, so any errors from submit_bio_hook()
2684 * will be handled by the endio on the repair_bio, so we can't return an
2687 submit_bio_hook(inode, repair_bio, failrec->this_mirror, failrec->bio_flags);
2691 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2693 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2695 ASSERT(page_offset(page) <= start &&
2696 start + len <= page_offset(page) + PAGE_SIZE);
2699 if (fsverity_active(page->mapping->host) &&
2701 !PageUptodate(page) &&
2702 start < i_size_read(page->mapping->host) &&
2703 !fsverity_verify_page(page)) {
2704 btrfs_page_set_error(fs_info, page, start, len);
2706 btrfs_page_set_uptodate(fs_info, page, start, len);
2709 btrfs_page_clear_uptodate(fs_info, page, start, len);
2710 btrfs_page_set_error(fs_info, page, start, len);
2713 if (!btrfs_is_subpage(fs_info, page))
2716 btrfs_subpage_end_reader(fs_info, page, start, len);
2719 static blk_status_t submit_data_read_repair(struct inode *inode,
2720 struct bio *failed_bio,
2721 u32 bio_offset, struct page *page,
2725 unsigned int error_bitmap)
2727 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2728 const u32 sectorsize = fs_info->sectorsize;
2729 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2733 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2735 /* This repair is only for data */
2736 ASSERT(is_data_inode(inode));
2738 /* We're here because we had some read errors or csum mismatch */
2739 ASSERT(error_bitmap);
2742 * We only get called on buffered IO, thus page must be mapped and bio
2743 * must not be cloned.
2745 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2747 /* Iterate through all the sectors in the range */
2748 for (i = 0; i < nr_bits; i++) {
2749 const unsigned int offset = i * sectorsize;
2750 struct extent_state *cached = NULL;
2751 bool uptodate = false;
2754 if (!(error_bitmap & (1U << i))) {
2756 * This sector has no error, just end the page read
2757 * and unlock the range.
2763 ret = btrfs_repair_one_sector(inode, failed_bio,
2764 bio_offset + offset,
2765 page, pgoff + offset, start + offset,
2766 failed_mirror, btrfs_submit_data_bio);
2769 * We have submitted the read repair, the page release
2770 * will be handled by the endio function of the
2771 * submitted repair bio.
2772 * Thus we don't need to do any thing here.
2777 * Repair failed, just record the error but still continue.
2778 * Or the remaining sectors will not be properly unlocked.
2783 end_page_read(page, uptodate, start + offset, sectorsize);
2785 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2787 start + offset + sectorsize - 1,
2788 &cached, GFP_ATOMIC);
2789 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2791 start + offset + sectorsize - 1,
2794 return errno_to_blk_status(error);
2797 /* lots and lots of room for performance fixes in the end_bio funcs */
2799 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2801 struct btrfs_inode *inode;
2802 const bool uptodate = (err == 0);
2805 ASSERT(page && page->mapping);
2806 inode = BTRFS_I(page->mapping->host);
2807 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2810 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
2813 ASSERT(end + 1 - start <= U32_MAX);
2814 len = end + 1 - start;
2816 btrfs_page_clear_uptodate(fs_info, page, start, len);
2817 btrfs_page_set_error(fs_info, page, start, len);
2818 ret = err < 0 ? err : -EIO;
2819 mapping_set_error(page->mapping, ret);
2824 * after a writepage IO is done, we need to:
2825 * clear the uptodate bits on error
2826 * clear the writeback bits in the extent tree for this IO
2827 * end_page_writeback if the page has no more pending IO
2829 * Scheduling is not allowed, so the extent state tree is expected
2830 * to have one and only one object corresponding to this IO.
2832 static void end_bio_extent_writepage(struct bio *bio)
2834 int error = blk_status_to_errno(bio->bi_status);
2835 struct bio_vec *bvec;
2838 struct bvec_iter_all iter_all;
2839 bool first_bvec = true;
2841 ASSERT(!bio_flagged(bio, BIO_CLONED));
2842 bio_for_each_segment_all(bvec, bio, iter_all) {
2843 struct page *page = bvec->bv_page;
2844 struct inode *inode = page->mapping->host;
2845 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2846 const u32 sectorsize = fs_info->sectorsize;
2848 /* Our read/write should always be sector aligned. */
2849 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2851 "partial page write in btrfs with offset %u and length %u",
2852 bvec->bv_offset, bvec->bv_len);
2853 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2855 "incomplete page write with offset %u and length %u",
2856 bvec->bv_offset, bvec->bv_len);
2858 start = page_offset(page) + bvec->bv_offset;
2859 end = start + bvec->bv_len - 1;
2862 btrfs_record_physical_zoned(inode, start, bio);
2866 end_extent_writepage(page, error, start, end);
2868 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2875 * Record previously processed extent range
2877 * For endio_readpage_release_extent() to handle a full extent range, reducing
2878 * the extent io operations.
2880 struct processed_extent {
2881 struct btrfs_inode *inode;
2882 /* Start of the range in @inode */
2884 /* End of the range in @inode */
2890 * Try to release processed extent range
2892 * May not release the extent range right now if the current range is
2893 * contiguous to processed extent.
2895 * Will release processed extent when any of @inode, @uptodate, the range is
2896 * no longer contiguous to the processed range.
2898 * Passing @inode == NULL will force processed extent to be released.
2900 static void endio_readpage_release_extent(struct processed_extent *processed,
2901 struct btrfs_inode *inode, u64 start, u64 end,
2904 struct extent_state *cached = NULL;
2905 struct extent_io_tree *tree;
2907 /* The first extent, initialize @processed */
2908 if (!processed->inode)
2912 * Contiguous to processed extent, just uptodate the end.
2914 * Several things to notice:
2916 * - bio can be merged as long as on-disk bytenr is contiguous
2917 * This means we can have page belonging to other inodes, thus need to
2918 * check if the inode still matches.
2919 * - bvec can contain range beyond current page for multi-page bvec
2920 * Thus we need to do processed->end + 1 >= start check
2922 if (processed->inode == inode && processed->uptodate == uptodate &&
2923 processed->end + 1 >= start && end >= processed->end) {
2924 processed->end = end;
2928 tree = &processed->inode->io_tree;
2930 * Now we don't have range contiguous to the processed range, release
2931 * the processed range now.
2933 if (processed->uptodate && tree->track_uptodate)
2934 set_extent_uptodate(tree, processed->start, processed->end,
2935 &cached, GFP_ATOMIC);
2936 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2940 /* Update processed to current range */
2941 processed->inode = inode;
2942 processed->start = start;
2943 processed->end = end;
2944 processed->uptodate = uptodate;
2947 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2949 ASSERT(PageLocked(page));
2950 if (!btrfs_is_subpage(fs_info, page))
2953 ASSERT(PagePrivate(page));
2954 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2958 * Find extent buffer for a givne bytenr.
2960 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2963 static struct extent_buffer *find_extent_buffer_readpage(
2964 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2966 struct extent_buffer *eb;
2969 * For regular sectorsize, we can use page->private to grab extent
2972 if (fs_info->nodesize >= PAGE_SIZE) {
2973 ASSERT(PagePrivate(page) && page->private);
2974 return (struct extent_buffer *)page->private;
2977 /* For subpage case, we need to lookup buffer radix tree */
2979 eb = radix_tree_lookup(&fs_info->buffer_radix,
2980 bytenr >> fs_info->sectorsize_bits);
2987 * after a readpage IO is done, we need to:
2988 * clear the uptodate bits on error
2989 * set the uptodate bits if things worked
2990 * set the page up to date if all extents in the tree are uptodate
2991 * clear the lock bit in the extent tree
2992 * unlock the page if there are no other extents locked for it
2994 * Scheduling is not allowed, so the extent state tree is expected
2995 * to have one and only one object corresponding to this IO.
2997 static void end_bio_extent_readpage(struct bio *bio)
2999 struct bio_vec *bvec;
3000 struct btrfs_bio *bbio = btrfs_bio(bio);
3001 struct extent_io_tree *tree, *failure_tree;
3002 struct processed_extent processed = { 0 };
3004 * The offset to the beginning of a bio, since one bio can never be
3005 * larger than UINT_MAX, u32 here is enough.
3010 struct bvec_iter_all iter_all;
3012 ASSERT(!bio_flagged(bio, BIO_CLONED));
3013 bio_for_each_segment_all(bvec, bio, iter_all) {
3014 bool uptodate = !bio->bi_status;
3015 struct page *page = bvec->bv_page;
3016 struct inode *inode = page->mapping->host;
3017 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3018 const u32 sectorsize = fs_info->sectorsize;
3019 unsigned int error_bitmap = (unsigned int)-1;
3024 btrfs_debug(fs_info,
3025 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3026 bio->bi_iter.bi_sector, bio->bi_status,
3028 tree = &BTRFS_I(inode)->io_tree;
3029 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3032 * We always issue full-sector reads, but if some block in a
3033 * page fails to read, blk_update_request() will advance
3034 * bv_offset and adjust bv_len to compensate. Print a warning
3035 * for unaligned offsets, and an error if they don't add up to
3038 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3040 "partial page read in btrfs with offset %u and length %u",
3041 bvec->bv_offset, bvec->bv_len);
3042 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3045 "incomplete page read with offset %u and length %u",
3046 bvec->bv_offset, bvec->bv_len);
3048 start = page_offset(page) + bvec->bv_offset;
3049 end = start + bvec->bv_len - 1;
3052 mirror = bbio->mirror_num;
3053 if (likely(uptodate)) {
3054 if (is_data_inode(inode)) {
3055 error_bitmap = btrfs_verify_data_csum(bbio,
3056 bio_offset, page, start, end);
3059 ret = btrfs_validate_metadata_buffer(bbio,
3060 page, start, end, mirror);
3065 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3066 failure_tree, tree, start,
3068 btrfs_ino(BTRFS_I(inode)), 0);
3071 if (likely(uptodate))
3074 if (is_data_inode(inode)) {
3076 * If we failed to submit the IO at all we'll have a
3077 * mirror_num == 0, in which case we need to just mark
3078 * the page with an error and unlock it and carry on.
3084 * submit_data_read_repair() will handle all the good
3085 * and bad sectors, we just continue to the next bvec.
3087 submit_data_read_repair(inode, bio, bio_offset, page,
3088 start - page_offset(page),
3092 ASSERT(bio_offset + len > bio_offset);
3096 struct extent_buffer *eb;
3098 eb = find_extent_buffer_readpage(fs_info, page, start);
3099 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3100 eb->read_mirror = mirror;
3101 atomic_dec(&eb->io_pages);
3104 if (likely(uptodate)) {
3105 loff_t i_size = i_size_read(inode);
3106 pgoff_t end_index = i_size >> PAGE_SHIFT;
3109 * Zero out the remaining part if this range straddles
3112 * Here we should only zero the range inside the bvec,
3113 * not touch anything else.
3115 * NOTE: i_size is exclusive while end is inclusive.
3117 if (page->index == end_index && i_size <= end) {
3118 u32 zero_start = max(offset_in_page(i_size),
3119 offset_in_page(start));
3121 zero_user_segment(page, zero_start,
3122 offset_in_page(end) + 1);
3125 ASSERT(bio_offset + len > bio_offset);
3128 /* Update page status and unlock */
3129 end_page_read(page, uptodate, start, len);
3130 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3131 start, end, PageUptodate(page));
3133 /* Release the last extent */
3134 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3135 btrfs_bio_free_csum(bbio);
3140 * Populate every free slot in a provided array with pages.
3142 * @nr_pages: number of pages to allocate
3143 * @page_array: the array to fill with pages; any existing non-null entries in
3144 * the array will be skipped
3146 * Return: 0 if all pages were able to be allocated;
3147 * -ENOMEM otherwise, and the caller is responsible for freeing all
3148 * non-null page pointers in the array.
3150 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
3152 unsigned int allocated;
3154 for (allocated = 0; allocated < nr_pages;) {
3155 unsigned int last = allocated;
3157 allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
3159 if (allocated == nr_pages)
3163 * During this iteration, no page could be allocated, even
3164 * though alloc_pages_bulk_array() falls back to alloc_page()
3165 * if it could not bulk-allocate. So we must be out of memory.
3167 if (allocated == last)
3170 memalloc_retry_wait(GFP_NOFS);
3176 * Initialize the members up to but not including 'bio'. Use after allocating a
3177 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3178 * 'bio' because use of __GFP_ZERO is not supported.
3180 static inline void btrfs_bio_init(struct btrfs_bio *bbio)
3182 memset(bbio, 0, offsetof(struct btrfs_bio, bio));
3186 * Allocate a btrfs_io_bio, with @nr_iovecs as maximum number of iovecs.
3188 * The bio allocation is backed by bioset and does not fail.
3190 struct bio *btrfs_bio_alloc(unsigned int nr_iovecs)
3194 ASSERT(0 < nr_iovecs && nr_iovecs <= BIO_MAX_VECS);
3195 bio = bio_alloc_bioset(NULL, nr_iovecs, 0, GFP_NOFS, &btrfs_bioset);
3196 btrfs_bio_init(btrfs_bio(bio));
3200 struct bio *btrfs_bio_clone(struct block_device *bdev, struct bio *bio)
3202 struct btrfs_bio *bbio;
3205 /* Bio allocation backed by a bioset does not fail */
3206 new = bio_alloc_clone(bdev, bio, GFP_NOFS, &btrfs_bioset);
3207 bbio = btrfs_bio(new);
3208 btrfs_bio_init(bbio);
3209 bbio->iter = bio->bi_iter;
3213 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
3216 struct btrfs_bio *bbio;
3218 ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
3220 /* this will never fail when it's backed by a bioset */
3221 bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
3224 bbio = btrfs_bio(bio);
3225 btrfs_bio_init(bbio);
3227 bio_trim(bio, offset >> 9, size >> 9);
3228 bbio->iter = bio->bi_iter;
3233 * Attempt to add a page to bio
3235 * @bio_ctrl: record both the bio, and its bio_flags
3236 * @page: page to add to the bio
3237 * @disk_bytenr: offset of the new bio or to check whether we are adding
3238 * a contiguous page to the previous one
3239 * @size: portion of page that we want to write
3240 * @pg_offset: starting offset in the page
3241 * @bio_flags: flags of the current bio to see if we can merge them
3243 * Attempt to add a page to bio considering stripe alignment etc.
3245 * Return >= 0 for the number of bytes added to the bio.
3246 * Can return 0 if the current bio is already at stripe/zone boundary.
3247 * Return <0 for error.
3249 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3251 u64 disk_bytenr, unsigned int size,
3252 unsigned int pg_offset,
3253 unsigned long bio_flags)
3255 struct bio *bio = bio_ctrl->bio;
3256 u32 bio_size = bio->bi_iter.bi_size;
3258 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3263 /* The limit should be calculated when bio_ctrl->bio is allocated */
3264 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3265 if (bio_ctrl->bio_flags != bio_flags)
3268 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED)
3269 contig = bio->bi_iter.bi_sector == sector;
3271 contig = bio_end_sector(bio) == sector;
3275 real_size = min(bio_ctrl->len_to_oe_boundary,
3276 bio_ctrl->len_to_stripe_boundary) - bio_size;
3277 real_size = min(real_size, size);
3280 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
3281 * bio will still execute its endio function on the page!
3286 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3287 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
3289 ret = bio_add_page(bio, page, real_size, pg_offset);
3294 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3295 struct btrfs_inode *inode, u64 file_offset)
3297 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3298 struct btrfs_io_geometry geom;
3299 struct btrfs_ordered_extent *ordered;
3300 struct extent_map *em;
3301 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3305 * Pages for compressed extent are never submitted to disk directly,
3306 * thus it has no real boundary, just set them to U32_MAX.
3308 * The split happens for real compressed bio, which happens in
3309 * btrfs_submit_compressed_read/write().
3311 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED) {
3312 bio_ctrl->len_to_oe_boundary = U32_MAX;
3313 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3316 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3319 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3321 free_extent_map(em);
3325 if (geom.len > U32_MAX)
3326 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3328 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3330 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3331 bio_ctrl->len_to_oe_boundary = U32_MAX;
3335 /* Ordered extent not yet created, so we're good */
3336 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
3338 bio_ctrl->len_to_oe_boundary = U32_MAX;
3342 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3343 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3344 btrfs_put_ordered_extent(ordered);
3348 static int alloc_new_bio(struct btrfs_inode *inode,
3349 struct btrfs_bio_ctrl *bio_ctrl,
3350 struct writeback_control *wbc,
3352 bio_end_io_t end_io_func,
3353 u64 disk_bytenr, u32 offset, u64 file_offset,
3354 unsigned long bio_flags)
3356 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3360 bio = btrfs_bio_alloc(BIO_MAX_VECS);
3362 * For compressed page range, its disk_bytenr is always @disk_bytenr
3363 * passed in, no matter if we have added any range into previous bio.
3365 if (bio_flags & EXTENT_BIO_COMPRESSED)
3366 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
3368 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
3369 bio_ctrl->bio = bio;
3370 bio_ctrl->bio_flags = bio_flags;
3371 bio->bi_end_io = end_io_func;
3372 bio->bi_private = &inode->io_tree;
3374 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
3380 * For Zone append we need the correct block_device that we are
3381 * going to write to set in the bio to be able to respect the
3382 * hardware limitation. Look it up here:
3384 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3385 struct btrfs_device *dev;
3387 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
3388 fs_info->sectorsize);
3394 bio_set_dev(bio, dev->bdev);
3397 * Otherwise pick the last added device to support
3398 * cgroup writeback. For multi-device file systems this
3399 * means blk-cgroup policies have to always be set on the
3400 * last added/replaced device. This is a bit odd but has
3401 * been like that for a long time.
3403 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
3405 wbc_init_bio(wbc, bio);
3407 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
3411 bio_ctrl->bio = NULL;
3412 bio->bi_status = errno_to_blk_status(ret);
3418 * @opf: bio REQ_OP_* and REQ_* flags as one value
3419 * @wbc: optional writeback control for io accounting
3420 * @page: page to add to the bio
3421 * @disk_bytenr: logical bytenr where the write will be
3422 * @size: portion of page that we want to write to
3423 * @pg_offset: offset of the new bio or to check whether we are adding
3424 * a contiguous page to the previous one
3425 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3426 * @end_io_func: end_io callback for new bio
3427 * @mirror_num: desired mirror to read/write
3428 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3429 * @bio_flags: flags of the current bio to see if we can merge them
3431 static int submit_extent_page(unsigned int opf,
3432 struct writeback_control *wbc,
3433 struct btrfs_bio_ctrl *bio_ctrl,
3434 struct page *page, u64 disk_bytenr,
3435 size_t size, unsigned long pg_offset,
3436 bio_end_io_t end_io_func,
3438 unsigned long bio_flags,
3439 bool force_bio_submit)
3442 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3443 unsigned int cur = pg_offset;
3447 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3448 pg_offset + size <= PAGE_SIZE);
3449 if (force_bio_submit && bio_ctrl->bio) {
3450 submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->bio_flags);
3451 bio_ctrl->bio = NULL;
3454 while (cur < pg_offset + size) {
3455 u32 offset = cur - pg_offset;
3458 /* Allocate new bio if needed */
3459 if (!bio_ctrl->bio) {
3460 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
3461 end_io_func, disk_bytenr, offset,
3462 page_offset(page) + cur,
3468 * We must go through btrfs_bio_add_page() to ensure each
3469 * page range won't cross various boundaries.
3471 if (bio_flags & EXTENT_BIO_COMPRESSED)
3472 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
3473 size - offset, pg_offset + offset,
3476 added = btrfs_bio_add_page(bio_ctrl, page,
3477 disk_bytenr + offset, size - offset,
3478 pg_offset + offset, bio_flags);
3480 /* Metadata page range should never be split */
3481 if (!is_data_inode(&inode->vfs_inode))
3482 ASSERT(added == 0 || added == size - offset);
3484 /* At least we added some page, update the account */
3486 wbc_account_cgroup_owner(wbc, page, added);
3488 /* We have reached boundary, submit right now */
3489 if (added < size - offset) {
3490 /* The bio should contain some page(s) */
3491 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
3492 submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->bio_flags);
3493 bio_ctrl->bio = NULL;
3500 static int attach_extent_buffer_page(struct extent_buffer *eb,
3502 struct btrfs_subpage *prealloc)
3504 struct btrfs_fs_info *fs_info = eb->fs_info;
3508 * If the page is mapped to btree inode, we should hold the private
3509 * lock to prevent race.
3510 * For cloned or dummy extent buffers, their pages are not mapped and
3511 * will not race with any other ebs.
3514 lockdep_assert_held(&page->mapping->private_lock);
3516 if (fs_info->nodesize >= PAGE_SIZE) {
3517 if (!PagePrivate(page))
3518 attach_page_private(page, eb);
3520 WARN_ON(page->private != (unsigned long)eb);
3524 /* Already mapped, just free prealloc */
3525 if (PagePrivate(page)) {
3526 btrfs_free_subpage(prealloc);
3531 /* Has preallocated memory for subpage */
3532 attach_page_private(page, prealloc);
3534 /* Do new allocation to attach subpage */
3535 ret = btrfs_attach_subpage(fs_info, page,
3536 BTRFS_SUBPAGE_METADATA);
3540 int set_page_extent_mapped(struct page *page)
3542 struct btrfs_fs_info *fs_info;
3544 ASSERT(page->mapping);
3546 if (PagePrivate(page))
3549 fs_info = btrfs_sb(page->mapping->host->i_sb);
3551 if (btrfs_is_subpage(fs_info, page))
3552 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3554 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3558 void clear_page_extent_mapped(struct page *page)
3560 struct btrfs_fs_info *fs_info;
3562 ASSERT(page->mapping);
3564 if (!PagePrivate(page))
3567 fs_info = btrfs_sb(page->mapping->host->i_sb);
3568 if (btrfs_is_subpage(fs_info, page))
3569 return btrfs_detach_subpage(fs_info, page);
3571 detach_page_private(page);
3574 static struct extent_map *
3575 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3576 u64 start, u64 len, struct extent_map **em_cached)
3578 struct extent_map *em;
3580 if (em_cached && *em_cached) {
3582 if (extent_map_in_tree(em) && start >= em->start &&
3583 start < extent_map_end(em)) {
3584 refcount_inc(&em->refs);
3588 free_extent_map(em);
3592 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3593 if (em_cached && !IS_ERR(em)) {
3595 refcount_inc(&em->refs);
3601 * basic readpage implementation. Locked extent state structs are inserted
3602 * into the tree that are removed when the IO is done (by the end_io
3604 * XXX JDM: This needs looking at to ensure proper page locking
3605 * return 0 on success, otherwise return error
3607 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3608 struct btrfs_bio_ctrl *bio_ctrl,
3609 unsigned int read_flags, u64 *prev_em_start)
3611 struct inode *inode = page->mapping->host;
3612 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3613 u64 start = page_offset(page);
3614 const u64 end = start + PAGE_SIZE - 1;
3617 u64 last_byte = i_size_read(inode);
3620 struct extent_map *em;
3622 size_t pg_offset = 0;
3624 size_t blocksize = inode->i_sb->s_blocksize;
3625 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3627 ret = set_page_extent_mapped(page);
3629 unlock_extent(tree, start, end);
3630 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3635 if (page->index == last_byte >> PAGE_SHIFT) {
3636 size_t zero_offset = offset_in_page(last_byte);
3639 iosize = PAGE_SIZE - zero_offset;
3640 memzero_page(page, zero_offset, iosize);
3641 flush_dcache_page(page);
3644 begin_page_read(fs_info, page);
3645 while (cur <= end) {
3646 unsigned long this_bio_flag = 0;
3647 bool force_bio_submit = false;
3650 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
3651 if (cur >= last_byte) {
3652 struct extent_state *cached = NULL;
3654 iosize = PAGE_SIZE - pg_offset;
3655 memzero_page(page, pg_offset, iosize);
3656 flush_dcache_page(page);
3657 set_extent_uptodate(tree, cur, cur + iosize - 1,
3659 unlock_extent_cached(tree, cur,
3660 cur + iosize - 1, &cached);
3661 end_page_read(page, true, cur, iosize);
3664 em = __get_extent_map(inode, page, pg_offset, cur,
3665 end - cur + 1, em_cached);
3667 unlock_extent(tree, cur, end);
3668 end_page_read(page, false, cur, end + 1 - cur);
3672 extent_offset = cur - em->start;
3673 BUG_ON(extent_map_end(em) <= cur);
3676 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3677 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3678 extent_set_compress_type(&this_bio_flag,
3682 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3683 cur_end = min(extent_map_end(em) - 1, end);
3684 iosize = ALIGN(iosize, blocksize);
3685 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3686 disk_bytenr = em->block_start;
3688 disk_bytenr = em->block_start + extent_offset;
3689 block_start = em->block_start;
3690 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3691 block_start = EXTENT_MAP_HOLE;
3694 * If we have a file range that points to a compressed extent
3695 * and it's followed by a consecutive file range that points
3696 * to the same compressed extent (possibly with a different
3697 * offset and/or length, so it either points to the whole extent
3698 * or only part of it), we must make sure we do not submit a
3699 * single bio to populate the pages for the 2 ranges because
3700 * this makes the compressed extent read zero out the pages
3701 * belonging to the 2nd range. Imagine the following scenario:
3704 * [0 - 8K] [8K - 24K]
3707 * points to extent X, points to extent X,
3708 * offset 4K, length of 8K offset 0, length 16K
3710 * [extent X, compressed length = 4K uncompressed length = 16K]
3712 * If the bio to read the compressed extent covers both ranges,
3713 * it will decompress extent X into the pages belonging to the
3714 * first range and then it will stop, zeroing out the remaining
3715 * pages that belong to the other range that points to extent X.
3716 * So here we make sure we submit 2 bios, one for the first
3717 * range and another one for the third range. Both will target
3718 * the same physical extent from disk, but we can't currently
3719 * make the compressed bio endio callback populate the pages
3720 * for both ranges because each compressed bio is tightly
3721 * coupled with a single extent map, and each range can have
3722 * an extent map with a different offset value relative to the
3723 * uncompressed data of our extent and different lengths. This
3724 * is a corner case so we prioritize correctness over
3725 * non-optimal behavior (submitting 2 bios for the same extent).
3727 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3728 prev_em_start && *prev_em_start != (u64)-1 &&
3729 *prev_em_start != em->start)
3730 force_bio_submit = true;
3733 *prev_em_start = em->start;
3735 free_extent_map(em);
3738 /* we've found a hole, just zero and go on */
3739 if (block_start == EXTENT_MAP_HOLE) {
3740 struct extent_state *cached = NULL;
3742 memzero_page(page, pg_offset, iosize);
3743 flush_dcache_page(page);
3745 set_extent_uptodate(tree, cur, cur + iosize - 1,
3747 unlock_extent_cached(tree, cur,
3748 cur + iosize - 1, &cached);
3749 end_page_read(page, true, cur, iosize);
3751 pg_offset += iosize;
3754 /* the get_extent function already copied into the page */
3755 if (test_range_bit(tree, cur, cur_end,
3756 EXTENT_UPTODATE, 1, NULL)) {
3757 unlock_extent(tree, cur, cur + iosize - 1);
3758 end_page_read(page, true, cur, iosize);
3760 pg_offset += iosize;
3763 /* we have an inline extent but it didn't get marked up
3764 * to date. Error out
3766 if (block_start == EXTENT_MAP_INLINE) {
3767 unlock_extent(tree, cur, cur + iosize - 1);
3768 end_page_read(page, false, cur, iosize);
3770 pg_offset += iosize;
3774 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3775 bio_ctrl, page, disk_bytenr, iosize,
3777 end_bio_extent_readpage, 0,
3782 * We have to unlock the remaining range, or the page
3783 * will never be unlocked.
3785 unlock_extent(tree, cur, end);
3786 end_page_read(page, false, cur, end + 1 - cur);
3790 pg_offset += iosize;
3796 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3798 struct extent_map **em_cached,
3799 struct btrfs_bio_ctrl *bio_ctrl,
3802 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3805 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3807 for (index = 0; index < nr_pages; index++) {
3808 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3809 REQ_RAHEAD, prev_em_start);
3810 put_page(pages[index]);
3814 static void update_nr_written(struct writeback_control *wbc,
3815 unsigned long nr_written)
3817 wbc->nr_to_write -= nr_written;
3821 * helper for __extent_writepage, doing all of the delayed allocation setup.
3823 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3824 * to write the page (copy into inline extent). In this case the IO has
3825 * been started and the page is already unlocked.
3827 * This returns 0 if all went well (page still locked)
3828 * This returns < 0 if there were errors (page still locked)
3830 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3831 struct page *page, struct writeback_control *wbc)
3833 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
3834 u64 delalloc_start = page_offset(page);
3835 u64 delalloc_to_write = 0;
3836 /* How many pages are started by btrfs_run_delalloc_range() */
3837 unsigned long nr_written = 0;
3839 int page_started = 0;
3841 while (delalloc_start < page_end) {
3842 u64 delalloc_end = page_end;
3845 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3849 delalloc_start = delalloc_end + 1;
3852 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3853 delalloc_end, &page_started, &nr_written, wbc);
3855 btrfs_page_set_error(inode->root->fs_info, page,
3856 page_offset(page), PAGE_SIZE);
3860 * delalloc_end is already one less than the total length, so
3861 * we don't subtract one from PAGE_SIZE
3863 delalloc_to_write += (delalloc_end - delalloc_start +
3864 PAGE_SIZE) >> PAGE_SHIFT;
3865 delalloc_start = delalloc_end + 1;
3867 if (wbc->nr_to_write < delalloc_to_write) {
3870 if (delalloc_to_write < thresh * 2)
3871 thresh = delalloc_to_write;
3872 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3876 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
3879 * We've unlocked the page, so we can't update the mapping's
3880 * writeback index, just update nr_to_write.
3882 wbc->nr_to_write -= nr_written;
3890 * Find the first byte we need to write.
3892 * For subpage, one page can contain several sectors, and
3893 * __extent_writepage_io() will just grab all extent maps in the page
3894 * range and try to submit all non-inline/non-compressed extents.
3896 * This is a big problem for subpage, we shouldn't re-submit already written
3898 * This function will lookup subpage dirty bit to find which range we really
3901 * Return the next dirty range in [@start, @end).
3902 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
3904 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
3905 struct page *page, u64 *start, u64 *end)
3907 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
3908 struct btrfs_subpage_info *spi = fs_info->subpage_info;
3909 u64 orig_start = *start;
3910 /* Declare as unsigned long so we can use bitmap ops */
3911 unsigned long flags;
3912 int range_start_bit;
3916 * For regular sector size == page size case, since one page only
3917 * contains one sector, we return the page offset directly.
3919 if (!btrfs_is_subpage(fs_info, page)) {
3920 *start = page_offset(page);
3921 *end = page_offset(page) + PAGE_SIZE;
3925 range_start_bit = spi->dirty_offset +
3926 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
3928 /* We should have the page locked, but just in case */
3929 spin_lock_irqsave(&subpage->lock, flags);
3930 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
3931 spi->dirty_offset + spi->bitmap_nr_bits);
3932 spin_unlock_irqrestore(&subpage->lock, flags);
3934 range_start_bit -= spi->dirty_offset;
3935 range_end_bit -= spi->dirty_offset;
3937 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
3938 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
3942 * helper for __extent_writepage. This calls the writepage start hooks,
3943 * and does the loop to map the page into extents and bios.
3945 * We return 1 if the IO is started and the page is unlocked,
3946 * 0 if all went well (page still locked)
3947 * < 0 if there were errors (page still locked)
3949 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3951 struct writeback_control *wbc,
3952 struct extent_page_data *epd,
3956 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3957 u64 cur = page_offset(page);
3958 u64 end = cur + PAGE_SIZE - 1;
3961 struct extent_map *em;
3964 u32 opf = REQ_OP_WRITE;
3965 const unsigned int write_flags = wbc_to_write_flags(wbc);
3968 ret = btrfs_writepage_cow_fixup(page);
3970 /* Fixup worker will requeue */
3971 redirty_page_for_writepage(wbc, page);
3977 * we don't want to touch the inode after unlocking the page,
3978 * so we update the mapping writeback index now
3980 update_nr_written(wbc, 1);
3982 while (cur <= end) {
3985 u64 dirty_range_start = cur;
3986 u64 dirty_range_end;
3989 if (cur >= i_size) {
3990 btrfs_writepage_endio_finish_ordered(inode, page, cur,
3993 * This range is beyond i_size, thus we don't need to
3994 * bother writing back.
3995 * But we still need to clear the dirty subpage bit, or
3996 * the next time the page gets dirtied, we will try to
3997 * writeback the sectors with subpage dirty bits,
3998 * causing writeback without ordered extent.
4000 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
4004 find_next_dirty_byte(fs_info, page, &dirty_range_start,
4006 if (cur < dirty_range_start) {
4007 cur = dirty_range_start;
4011 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
4013 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
4014 ret = PTR_ERR_OR_ZERO(em);
4018 extent_offset = cur - em->start;
4019 em_end = extent_map_end(em);
4020 ASSERT(cur <= em_end);
4022 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
4023 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
4024 block_start = em->block_start;
4025 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4026 disk_bytenr = em->block_start + extent_offset;
4029 * Note that em_end from extent_map_end() and dirty_range_end from
4030 * find_next_dirty_byte() are all exclusive
4032 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
4034 if (btrfs_use_zone_append(inode, em->block_start))
4035 opf = REQ_OP_ZONE_APPEND;
4037 free_extent_map(em);
4041 * compressed and inline extents are written through other
4044 if (compressed || block_start == EXTENT_MAP_HOLE ||
4045 block_start == EXTENT_MAP_INLINE) {
4049 btrfs_writepage_endio_finish_ordered(inode,
4050 page, cur, cur + iosize - 1, true);
4051 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4056 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
4057 if (!PageWriteback(page)) {
4058 btrfs_err(inode->root->fs_info,
4059 "page %lu not writeback, cur %llu end %llu",
4060 page->index, cur, end);
4064 * Although the PageDirty bit is cleared before entering this
4065 * function, subpage dirty bit is not cleared.
4066 * So clear subpage dirty bit here so next time we won't submit
4067 * page for range already written to disk.
4069 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4071 ret = submit_extent_page(opf | write_flags, wbc,
4072 &epd->bio_ctrl, page,
4073 disk_bytenr, iosize,
4074 cur - page_offset(page),
4075 end_bio_extent_writepage,
4078 btrfs_page_set_error(fs_info, page, cur, iosize);
4079 if (PageWriteback(page))
4080 btrfs_page_clear_writeback(fs_info, page, cur,
4088 * If we finish without problem, we should not only clear page dirty,
4089 * but also empty subpage dirty bits
4092 btrfs_page_assert_not_dirty(fs_info, page);
4098 * the writepage semantics are similar to regular writepage. extent
4099 * records are inserted to lock ranges in the tree, and as dirty areas
4100 * are found, they are marked writeback. Then the lock bits are removed
4101 * and the end_io handler clears the writeback ranges
4103 * Return 0 if everything goes well.
4104 * Return <0 for error.
4106 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
4107 struct extent_page_data *epd)
4109 struct folio *folio = page_folio(page);
4110 struct inode *inode = page->mapping->host;
4111 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4112 const u64 page_start = page_offset(page);
4113 const u64 page_end = page_start + PAGE_SIZE - 1;
4117 loff_t i_size = i_size_read(inode);
4118 unsigned long end_index = i_size >> PAGE_SHIFT;
4120 trace___extent_writepage(page, inode, wbc);
4122 WARN_ON(!PageLocked(page));
4124 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
4125 page_offset(page), PAGE_SIZE);
4127 pg_offset = offset_in_page(i_size);
4128 if (page->index > end_index ||
4129 (page->index == end_index && !pg_offset)) {
4130 folio_invalidate(folio, 0, folio_size(folio));
4131 folio_unlock(folio);
4135 if (page->index == end_index) {
4136 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
4137 flush_dcache_page(page);
4140 ret = set_page_extent_mapped(page);
4146 if (!epd->extent_locked) {
4147 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
4154 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
4161 /* make sure the mapping tag for page dirty gets cleared */
4162 set_page_writeback(page);
4163 end_page_writeback(page);
4166 * Here we used to have a check for PageError() and then set @ret and
4167 * call end_extent_writepage().
4169 * But in fact setting @ret here will cause different error paths
4170 * between subpage and regular sectorsize.
4172 * For regular page size, we never submit current page, but only add
4173 * current page to current bio.
4174 * The bio submission can only happen in next page.
4175 * Thus if we hit the PageError() branch, @ret is already set to
4176 * non-zero value and will not get updated for regular sectorsize.
4178 * But for subpage case, it's possible we submit part of current page,
4179 * thus can get PageError() set by submitted bio of the same page,
4180 * while our @ret is still 0.
4182 * So here we unify the behavior and don't set @ret.
4183 * Error can still be properly passed to higher layer as page will
4184 * be set error, here we just don't handle the IO failure.
4186 * NOTE: This is just a hotfix for subpage.
4187 * The root fix will be properly ending ordered extent when we hit
4188 * an error during writeback.
4190 * But that needs a bigger refactoring, as we not only need to grab the
4191 * submitted OE, but also need to know exactly at which bytenr we hit
4193 * Currently the full page based __extent_writepage_io() is not
4196 if (PageError(page))
4197 end_extent_writepage(page, ret, page_start, page_end);
4198 if (epd->extent_locked) {
4200 * If epd->extent_locked, it's from extent_write_locked_range(),
4201 * the page can either be locked by lock_page() or
4202 * process_one_page().
4203 * Let btrfs_page_unlock_writer() handle both cases.
4206 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
4207 wbc->range_end + 1 - wbc->range_start);
4215 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
4217 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
4218 TASK_UNINTERRUPTIBLE);
4221 static void end_extent_buffer_writeback(struct extent_buffer *eb)
4223 if (test_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags))
4224 btrfs_zone_finish_endio(eb->fs_info, eb->start, eb->len);
4226 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4227 smp_mb__after_atomic();
4228 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
4232 * Lock extent buffer status and pages for writeback.
4234 * May try to flush write bio if we can't get the lock.
4236 * Return 0 if the extent buffer doesn't need to be submitted.
4237 * (E.g. the extent buffer is not dirty)
4238 * Return >0 is the extent buffer is submitted to bio.
4239 * Return <0 if something went wrong, no page is locked.
4241 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4242 struct extent_page_data *epd)
4244 struct btrfs_fs_info *fs_info = eb->fs_info;
4249 if (!btrfs_try_tree_write_lock(eb)) {
4250 flush_write_bio(epd);
4252 btrfs_tree_lock(eb);
4255 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4256 btrfs_tree_unlock(eb);
4260 flush_write_bio(epd);
4264 wait_on_extent_buffer_writeback(eb);
4265 btrfs_tree_lock(eb);
4266 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4268 btrfs_tree_unlock(eb);
4273 * We need to do this to prevent races in people who check if the eb is
4274 * under IO since we can end up having no IO bits set for a short period
4277 spin_lock(&eb->refs_lock);
4278 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4279 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4280 spin_unlock(&eb->refs_lock);
4281 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4282 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4284 fs_info->dirty_metadata_batch);
4287 spin_unlock(&eb->refs_lock);
4290 btrfs_tree_unlock(eb);
4293 * Either we don't need to submit any tree block, or we're submitting
4295 * Subpage metadata doesn't use page locking at all, so we can skip
4298 if (!ret || fs_info->nodesize < PAGE_SIZE)
4301 num_pages = num_extent_pages(eb);
4302 for (i = 0; i < num_pages; i++) {
4303 struct page *p = eb->pages[i];
4305 if (!trylock_page(p)) {
4307 flush_write_bio(epd);
4317 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4319 struct btrfs_fs_info *fs_info = eb->fs_info;
4321 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4322 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4326 * A read may stumble upon this buffer later, make sure that it gets an
4327 * error and knows there was an error.
4329 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4332 * We need to set the mapping with the io error as well because a write
4333 * error will flip the file system readonly, and then syncfs() will
4334 * return a 0 because we are readonly if we don't modify the err seq for
4337 mapping_set_error(page->mapping, -EIO);
4340 * If we error out, we should add back the dirty_metadata_bytes
4341 * to make it consistent.
4343 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4344 eb->len, fs_info->dirty_metadata_batch);
4347 * If writeback for a btree extent that doesn't belong to a log tree
4348 * failed, increment the counter transaction->eb_write_errors.
4349 * We do this because while the transaction is running and before it's
4350 * committing (when we call filemap_fdata[write|wait]_range against
4351 * the btree inode), we might have
4352 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4353 * returns an error or an error happens during writeback, when we're
4354 * committing the transaction we wouldn't know about it, since the pages
4355 * can be no longer dirty nor marked anymore for writeback (if a
4356 * subsequent modification to the extent buffer didn't happen before the
4357 * transaction commit), which makes filemap_fdata[write|wait]_range not
4358 * able to find the pages tagged with SetPageError at transaction
4359 * commit time. So if this happens we must abort the transaction,
4360 * otherwise we commit a super block with btree roots that point to
4361 * btree nodes/leafs whose content on disk is invalid - either garbage
4362 * or the content of some node/leaf from a past generation that got
4363 * cowed or deleted and is no longer valid.
4365 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4366 * not be enough - we need to distinguish between log tree extents vs
4367 * non-log tree extents, and the next filemap_fdatawait_range() call
4368 * will catch and clear such errors in the mapping - and that call might
4369 * be from a log sync and not from a transaction commit. Also, checking
4370 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4371 * not done and would not be reliable - the eb might have been released
4372 * from memory and reading it back again means that flag would not be
4373 * set (since it's a runtime flag, not persisted on disk).
4375 * Using the flags below in the btree inode also makes us achieve the
4376 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4377 * writeback for all dirty pages and before filemap_fdatawait_range()
4378 * is called, the writeback for all dirty pages had already finished
4379 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4380 * filemap_fdatawait_range() would return success, as it could not know
4381 * that writeback errors happened (the pages were no longer tagged for
4384 switch (eb->log_index) {
4386 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4389 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4392 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4395 BUG(); /* unexpected, logic error */
4400 * The endio specific version which won't touch any unsafe spinlock in endio
4403 static struct extent_buffer *find_extent_buffer_nolock(
4404 struct btrfs_fs_info *fs_info, u64 start)
4406 struct extent_buffer *eb;
4409 eb = radix_tree_lookup(&fs_info->buffer_radix,
4410 start >> fs_info->sectorsize_bits);
4411 if (eb && atomic_inc_not_zero(&eb->refs)) {
4420 * The endio function for subpage extent buffer write.
4422 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4423 * after all extent buffers in the page has finished their writeback.
4425 static void end_bio_subpage_eb_writepage(struct bio *bio)
4427 struct btrfs_fs_info *fs_info;
4428 struct bio_vec *bvec;
4429 struct bvec_iter_all iter_all;
4431 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4432 ASSERT(fs_info->nodesize < PAGE_SIZE);
4434 ASSERT(!bio_flagged(bio, BIO_CLONED));
4435 bio_for_each_segment_all(bvec, bio, iter_all) {
4436 struct page *page = bvec->bv_page;
4437 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4438 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4439 u64 cur_bytenr = bvec_start;
4441 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4443 /* Iterate through all extent buffers in the range */
4444 while (cur_bytenr <= bvec_end) {
4445 struct extent_buffer *eb;
4449 * Here we can't use find_extent_buffer(), as it may
4450 * try to lock eb->refs_lock, which is not safe in endio
4453 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4456 cur_bytenr = eb->start + eb->len;
4458 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4459 done = atomic_dec_and_test(&eb->io_pages);
4462 if (bio->bi_status ||
4463 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4464 ClearPageUptodate(page);
4465 set_btree_ioerr(page, eb);
4468 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4470 end_extent_buffer_writeback(eb);
4472 * free_extent_buffer() will grab spinlock which is not
4473 * safe in endio context. Thus here we manually dec
4476 atomic_dec(&eb->refs);
4482 static void end_bio_extent_buffer_writepage(struct bio *bio)
4484 struct bio_vec *bvec;
4485 struct extent_buffer *eb;
4487 struct bvec_iter_all iter_all;
4489 ASSERT(!bio_flagged(bio, BIO_CLONED));
4490 bio_for_each_segment_all(bvec, bio, iter_all) {
4491 struct page *page = bvec->bv_page;
4493 eb = (struct extent_buffer *)page->private;
4495 done = atomic_dec_and_test(&eb->io_pages);
4497 if (bio->bi_status ||
4498 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4499 ClearPageUptodate(page);
4500 set_btree_ioerr(page, eb);
4503 end_page_writeback(page);
4508 end_extent_buffer_writeback(eb);
4514 static void prepare_eb_write(struct extent_buffer *eb)
4517 unsigned long start;
4520 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4521 atomic_set(&eb->io_pages, num_extent_pages(eb));
4523 /* Set btree blocks beyond nritems with 0 to avoid stale content */
4524 nritems = btrfs_header_nritems(eb);
4525 if (btrfs_header_level(eb) > 0) {
4526 end = btrfs_node_key_ptr_offset(nritems);
4527 memzero_extent_buffer(eb, end, eb->len - end);
4531 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4533 start = btrfs_item_nr_offset(nritems);
4534 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4535 memzero_extent_buffer(eb, start, end - start);
4540 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4541 * Page locking is only utilized at minimum to keep the VMM code happy.
4543 static int write_one_subpage_eb(struct extent_buffer *eb,
4544 struct writeback_control *wbc,
4545 struct extent_page_data *epd)
4547 struct btrfs_fs_info *fs_info = eb->fs_info;
4548 struct page *page = eb->pages[0];
4549 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4550 bool no_dirty_ebs = false;
4553 prepare_eb_write(eb);
4555 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4557 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4559 /* Check if this is the last dirty bit to update nr_written */
4560 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4561 eb->start, eb->len);
4563 clear_page_dirty_for_io(page);
4565 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4566 &epd->bio_ctrl, page, eb->start, eb->len,
4567 eb->start - page_offset(page),
4568 end_bio_subpage_eb_writepage, 0, 0, false);
4570 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4571 set_btree_ioerr(page, eb);
4574 if (atomic_dec_and_test(&eb->io_pages))
4575 end_extent_buffer_writeback(eb);
4580 * Submission finished without problem, if no range of the page is
4581 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4584 update_nr_written(wbc, 1);
4588 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4589 struct writeback_control *wbc,
4590 struct extent_page_data *epd)
4592 u64 disk_bytenr = eb->start;
4594 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4597 prepare_eb_write(eb);
4599 num_pages = num_extent_pages(eb);
4600 for (i = 0; i < num_pages; i++) {
4601 struct page *p = eb->pages[i];
4603 clear_page_dirty_for_io(p);
4604 set_page_writeback(p);
4605 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4606 &epd->bio_ctrl, p, disk_bytenr,
4608 end_bio_extent_buffer_writepage,
4611 set_btree_ioerr(p, eb);
4612 if (PageWriteback(p))
4613 end_page_writeback(p);
4614 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4615 end_extent_buffer_writeback(eb);
4619 disk_bytenr += PAGE_SIZE;
4620 update_nr_written(wbc, 1);
4624 if (unlikely(ret)) {
4625 for (; i < num_pages; i++) {
4626 struct page *p = eb->pages[i];
4627 clear_page_dirty_for_io(p);
4636 * Submit one subpage btree page.
4638 * The main difference to submit_eb_page() is:
4640 * For subpage, we don't rely on page locking at all.
4643 * We only flush bio if we may be unable to fit current extent buffers into
4646 * Return >=0 for the number of submitted extent buffers.
4647 * Return <0 for fatal error.
4649 static int submit_eb_subpage(struct page *page,
4650 struct writeback_control *wbc,
4651 struct extent_page_data *epd)
4653 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4655 u64 page_start = page_offset(page);
4657 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4660 /* Lock and write each dirty extent buffers in the range */
4661 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
4662 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4663 struct extent_buffer *eb;
4664 unsigned long flags;
4668 * Take private lock to ensure the subpage won't be detached
4671 spin_lock(&page->mapping->private_lock);
4672 if (!PagePrivate(page)) {
4673 spin_unlock(&page->mapping->private_lock);
4676 spin_lock_irqsave(&subpage->lock, flags);
4677 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
4678 subpage->bitmaps)) {
4679 spin_unlock_irqrestore(&subpage->lock, flags);
4680 spin_unlock(&page->mapping->private_lock);
4685 start = page_start + bit_start * fs_info->sectorsize;
4686 bit_start += sectors_per_node;
4689 * Here we just want to grab the eb without touching extra
4690 * spin locks, so call find_extent_buffer_nolock().
4692 eb = find_extent_buffer_nolock(fs_info, start);
4693 spin_unlock_irqrestore(&subpage->lock, flags);
4694 spin_unlock(&page->mapping->private_lock);
4697 * The eb has already reached 0 refs thus find_extent_buffer()
4698 * doesn't return it. We don't need to write back such eb
4704 ret = lock_extent_buffer_for_io(eb, epd);
4706 free_extent_buffer(eb);
4710 free_extent_buffer(eb);
4713 ret = write_one_subpage_eb(eb, wbc, epd);
4714 free_extent_buffer(eb);
4722 /* We hit error, end bio for the submitted extent buffers */
4723 end_write_bio(epd, ret);
4728 * Submit all page(s) of one extent buffer.
4730 * @page: the page of one extent buffer
4731 * @eb_context: to determine if we need to submit this page, if current page
4732 * belongs to this eb, we don't need to submit
4734 * The caller should pass each page in their bytenr order, and here we use
4735 * @eb_context to determine if we have submitted pages of one extent buffer.
4737 * If we have, we just skip until we hit a new page that doesn't belong to
4738 * current @eb_context.
4740 * If not, we submit all the page(s) of the extent buffer.
4742 * Return >0 if we have submitted the extent buffer successfully.
4743 * Return 0 if we don't need to submit the page, as it's already submitted by
4745 * Return <0 for fatal error.
4747 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4748 struct extent_page_data *epd,
4749 struct extent_buffer **eb_context)
4751 struct address_space *mapping = page->mapping;
4752 struct btrfs_block_group *cache = NULL;
4753 struct extent_buffer *eb;
4756 if (!PagePrivate(page))
4759 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
4760 return submit_eb_subpage(page, wbc, epd);
4762 spin_lock(&mapping->private_lock);
4763 if (!PagePrivate(page)) {
4764 spin_unlock(&mapping->private_lock);
4768 eb = (struct extent_buffer *)page->private;
4771 * Shouldn't happen and normally this would be a BUG_ON but no point
4772 * crashing the machine for something we can survive anyway.
4775 spin_unlock(&mapping->private_lock);
4779 if (eb == *eb_context) {
4780 spin_unlock(&mapping->private_lock);
4783 ret = atomic_inc_not_zero(&eb->refs);
4784 spin_unlock(&mapping->private_lock);
4788 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4790 * If for_sync, this hole will be filled with
4791 * trasnsaction commit.
4793 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4797 free_extent_buffer(eb);
4803 ret = lock_extent_buffer_for_io(eb, epd);
4805 btrfs_revert_meta_write_pointer(cache, eb);
4807 btrfs_put_block_group(cache);
4808 free_extent_buffer(eb);
4813 * Implies write in zoned mode. Mark the last eb in a block group.
4815 if (cache->seq_zone && eb->start + eb->len == cache->zone_capacity)
4816 set_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags);
4817 btrfs_put_block_group(cache);
4819 ret = write_one_eb(eb, wbc, epd);
4820 free_extent_buffer(eb);
4826 int btree_write_cache_pages(struct address_space *mapping,
4827 struct writeback_control *wbc)
4829 struct extent_buffer *eb_context = NULL;
4830 struct extent_page_data epd = {
4833 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4835 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4838 int nr_to_write_done = 0;
4839 struct pagevec pvec;
4842 pgoff_t end; /* Inclusive */
4846 pagevec_init(&pvec);
4847 if (wbc->range_cyclic) {
4848 index = mapping->writeback_index; /* Start from prev offset */
4851 * Start from the beginning does not need to cycle over the
4852 * range, mark it as scanned.
4854 scanned = (index == 0);
4856 index = wbc->range_start >> PAGE_SHIFT;
4857 end = wbc->range_end >> PAGE_SHIFT;
4860 if (wbc->sync_mode == WB_SYNC_ALL)
4861 tag = PAGECACHE_TAG_TOWRITE;
4863 tag = PAGECACHE_TAG_DIRTY;
4864 btrfs_zoned_meta_io_lock(fs_info);
4866 if (wbc->sync_mode == WB_SYNC_ALL)
4867 tag_pages_for_writeback(mapping, index, end);
4868 while (!done && !nr_to_write_done && (index <= end) &&
4869 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4873 for (i = 0; i < nr_pages; i++) {
4874 struct page *page = pvec.pages[i];
4876 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4885 * the filesystem may choose to bump up nr_to_write.
4886 * We have to make sure to honor the new nr_to_write
4889 nr_to_write_done = wbc->nr_to_write <= 0;
4891 pagevec_release(&pvec);
4894 if (!scanned && !done) {
4896 * We hit the last page and there is more work to be done: wrap
4897 * back to the start of the file
4904 end_write_bio(&epd, ret);
4908 * If something went wrong, don't allow any metadata write bio to be
4911 * This would prevent use-after-free if we had dirty pages not
4912 * cleaned up, which can still happen by fuzzed images.
4915 * Allowing existing tree block to be allocated for other trees.
4917 * - Log tree operations
4918 * Exiting tree blocks get allocated to log tree, bumps its
4919 * generation, then get cleaned in tree re-balance.
4920 * Such tree block will not be written back, since it's clean,
4921 * thus no WRITTEN flag set.
4922 * And after log writes back, this tree block is not traced by
4923 * any dirty extent_io_tree.
4925 * - Offending tree block gets re-dirtied from its original owner
4926 * Since it has bumped generation, no WRITTEN flag, it can be
4927 * reused without COWing. This tree block will not be traced
4928 * by btrfs_transaction::dirty_pages.
4930 * Now such dirty tree block will not be cleaned by any dirty
4931 * extent io tree. Thus we don't want to submit such wild eb
4932 * if the fs already has error.
4934 if (!BTRFS_FS_ERROR(fs_info)) {
4935 flush_write_bio(&epd);
4938 end_write_bio(&epd, ret);
4941 btrfs_zoned_meta_io_unlock(fs_info);
4943 * We can get ret > 0 from submit_extent_page() indicating how many ebs
4944 * were submitted. Reset it to 0 to avoid false alerts for the caller.
4952 * Walk the list of dirty pages of the given address space and write all of them.
4954 * @mapping: address space structure to write
4955 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4956 * @epd: holds context for the write, namely the bio
4958 * If a page is already under I/O, write_cache_pages() skips it, even
4959 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4960 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4961 * and msync() need to guarantee that all the data which was dirty at the time
4962 * the call was made get new I/O started against them. If wbc->sync_mode is
4963 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4964 * existing IO to complete.
4966 static int extent_write_cache_pages(struct address_space *mapping,
4967 struct writeback_control *wbc,
4968 struct extent_page_data *epd)
4970 struct inode *inode = mapping->host;
4973 int nr_to_write_done = 0;
4974 struct pagevec pvec;
4977 pgoff_t end; /* Inclusive */
4979 int range_whole = 0;
4984 * We have to hold onto the inode so that ordered extents can do their
4985 * work when the IO finishes. The alternative to this is failing to add
4986 * an ordered extent if the igrab() fails there and that is a huge pain
4987 * to deal with, so instead just hold onto the inode throughout the
4988 * writepages operation. If it fails here we are freeing up the inode
4989 * anyway and we'd rather not waste our time writing out stuff that is
4990 * going to be truncated anyway.
4995 pagevec_init(&pvec);
4996 if (wbc->range_cyclic) {
4997 index = mapping->writeback_index; /* Start from prev offset */
5000 * Start from the beginning does not need to cycle over the
5001 * range, mark it as scanned.
5003 scanned = (index == 0);
5005 index = wbc->range_start >> PAGE_SHIFT;
5006 end = wbc->range_end >> PAGE_SHIFT;
5007 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
5013 * We do the tagged writepage as long as the snapshot flush bit is set
5014 * and we are the first one who do the filemap_flush() on this inode.
5016 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
5017 * not race in and drop the bit.
5019 if (range_whole && wbc->nr_to_write == LONG_MAX &&
5020 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
5021 &BTRFS_I(inode)->runtime_flags))
5022 wbc->tagged_writepages = 1;
5024 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5025 tag = PAGECACHE_TAG_TOWRITE;
5027 tag = PAGECACHE_TAG_DIRTY;
5029 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5030 tag_pages_for_writeback(mapping, index, end);
5032 while (!done && !nr_to_write_done && (index <= end) &&
5033 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
5034 &index, end, tag))) {
5037 for (i = 0; i < nr_pages; i++) {
5038 struct page *page = pvec.pages[i];
5040 done_index = page->index + 1;
5042 * At this point we hold neither the i_pages lock nor
5043 * the page lock: the page may be truncated or
5044 * invalidated (changing page->mapping to NULL),
5045 * or even swizzled back from swapper_space to
5046 * tmpfs file mapping
5048 if (!trylock_page(page)) {
5049 flush_write_bio(epd);
5053 if (unlikely(page->mapping != mapping)) {
5058 if (wbc->sync_mode != WB_SYNC_NONE) {
5059 if (PageWriteback(page))
5060 flush_write_bio(epd);
5061 wait_on_page_writeback(page);
5064 if (PageWriteback(page) ||
5065 !clear_page_dirty_for_io(page)) {
5070 ret = __extent_writepage(page, wbc, epd);
5077 * the filesystem may choose to bump up nr_to_write.
5078 * We have to make sure to honor the new nr_to_write
5081 nr_to_write_done = wbc->nr_to_write <= 0;
5083 pagevec_release(&pvec);
5086 if (!scanned && !done) {
5088 * We hit the last page and there is more work to be done: wrap
5089 * back to the start of the file
5095 * If we're looping we could run into a page that is locked by a
5096 * writer and that writer could be waiting on writeback for a
5097 * page in our current bio, and thus deadlock, so flush the
5100 flush_write_bio(epd);
5104 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
5105 mapping->writeback_index = done_index;
5107 btrfs_add_delayed_iput(inode);
5111 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
5114 struct extent_page_data epd = {
5117 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5120 ret = __extent_writepage(page, wbc, &epd);
5123 end_write_bio(&epd, ret);
5127 flush_write_bio(&epd);
5132 * Submit the pages in the range to bio for call sites which delalloc range has
5133 * already been ran (aka, ordered extent inserted) and all pages are still
5136 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
5138 bool found_error = false;
5139 int first_error = 0;
5141 struct address_space *mapping = inode->i_mapping;
5144 unsigned long nr_pages;
5145 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
5146 struct extent_page_data epd = {
5151 struct writeback_control wbc_writepages = {
5152 .sync_mode = WB_SYNC_ALL,
5153 .range_start = start,
5154 .range_end = end + 1,
5155 /* We're called from an async helper function */
5156 .punt_to_cgroup = 1,
5157 .no_cgroup_owner = 1,
5160 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
5161 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
5163 wbc_writepages.nr_to_write = nr_pages * 2;
5165 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
5166 while (cur <= end) {
5167 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
5169 page = find_get_page(mapping, cur >> PAGE_SHIFT);
5171 * All pages in the range are locked since
5172 * btrfs_run_delalloc_range(), thus there is no way to clear
5173 * the page dirty flag.
5175 ASSERT(PageLocked(page));
5176 ASSERT(PageDirty(page));
5177 clear_page_dirty_for_io(page);
5178 ret = __extent_writepage(page, &wbc_writepages, &epd);
5189 flush_write_bio(&epd);
5191 end_write_bio(&epd, ret);
5193 wbc_detach_inode(&wbc_writepages);
5199 int extent_writepages(struct address_space *mapping,
5200 struct writeback_control *wbc)
5202 struct inode *inode = mapping->host;
5204 struct extent_page_data epd = {
5207 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5211 * Allow only a single thread to do the reloc work in zoned mode to
5212 * protect the write pointer updates.
5214 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
5215 ret = extent_write_cache_pages(mapping, wbc, &epd);
5216 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5219 end_write_bio(&epd, ret);
5222 flush_write_bio(&epd);
5226 void extent_readahead(struct readahead_control *rac)
5228 struct btrfs_bio_ctrl bio_ctrl = { 0 };
5229 struct page *pagepool[16];
5230 struct extent_map *em_cached = NULL;
5231 u64 prev_em_start = (u64)-1;
5234 while ((nr = readahead_page_batch(rac, pagepool))) {
5235 u64 contig_start = readahead_pos(rac);
5236 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
5238 contiguous_readpages(pagepool, nr, contig_start, contig_end,
5239 &em_cached, &bio_ctrl, &prev_em_start);
5243 free_extent_map(em_cached);
5246 submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags);
5250 * basic invalidate_folio code, this waits on any locked or writeback
5251 * ranges corresponding to the folio, and then deletes any extent state
5252 * records from the tree
5254 int extent_invalidate_folio(struct extent_io_tree *tree,
5255 struct folio *folio, size_t offset)
5257 struct extent_state *cached_state = NULL;
5258 u64 start = folio_pos(folio);
5259 u64 end = start + folio_size(folio) - 1;
5260 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
5262 /* This function is only called for the btree inode */
5263 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5265 start += ALIGN(offset, blocksize);
5269 lock_extent_bits(tree, start, end, &cached_state);
5270 folio_wait_writeback(folio);
5273 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5274 * so here we only need to unlock the extent range to free any
5275 * existing extent state.
5277 unlock_extent_cached(tree, start, end, &cached_state);
5282 * a helper for releasepage, this tests for areas of the page that
5283 * are locked or under IO and drops the related state bits if it is safe
5286 static int try_release_extent_state(struct extent_io_tree *tree,
5287 struct page *page, gfp_t mask)
5289 u64 start = page_offset(page);
5290 u64 end = start + PAGE_SIZE - 1;
5293 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5297 * At this point we can safely clear everything except the
5298 * locked bit, the nodatasum bit and the delalloc new bit.
5299 * The delalloc new bit will be cleared by ordered extent
5302 ret = __clear_extent_bit(tree, start, end,
5303 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5304 0, 0, NULL, mask, NULL);
5306 /* if clear_extent_bit failed for enomem reasons,
5307 * we can't allow the release to continue.
5318 * a helper for releasepage. As long as there are no locked extents
5319 * in the range corresponding to the page, both state records and extent
5320 * map records are removed
5322 int try_release_extent_mapping(struct page *page, gfp_t mask)
5324 struct extent_map *em;
5325 u64 start = page_offset(page);
5326 u64 end = start + PAGE_SIZE - 1;
5327 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5328 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5329 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5331 if (gfpflags_allow_blocking(mask) &&
5332 page->mapping->host->i_size > SZ_16M) {
5334 while (start <= end) {
5335 struct btrfs_fs_info *fs_info;
5338 len = end - start + 1;
5339 write_lock(&map->lock);
5340 em = lookup_extent_mapping(map, start, len);
5342 write_unlock(&map->lock);
5345 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5346 em->start != start) {
5347 write_unlock(&map->lock);
5348 free_extent_map(em);
5351 if (test_range_bit(tree, em->start,
5352 extent_map_end(em) - 1,
5353 EXTENT_LOCKED, 0, NULL))
5356 * If it's not in the list of modified extents, used
5357 * by a fast fsync, we can remove it. If it's being
5358 * logged we can safely remove it since fsync took an
5359 * extra reference on the em.
5361 if (list_empty(&em->list) ||
5362 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5365 * If it's in the list of modified extents, remove it
5366 * only if its generation is older then the current one,
5367 * in which case we don't need it for a fast fsync.
5368 * Otherwise don't remove it, we could be racing with an
5369 * ongoing fast fsync that could miss the new extent.
5371 fs_info = btrfs_inode->root->fs_info;
5372 spin_lock(&fs_info->trans_lock);
5373 cur_gen = fs_info->generation;
5374 spin_unlock(&fs_info->trans_lock);
5375 if (em->generation >= cur_gen)
5379 * We only remove extent maps that are not in the list of
5380 * modified extents or that are in the list but with a
5381 * generation lower then the current generation, so there
5382 * is no need to set the full fsync flag on the inode (it
5383 * hurts the fsync performance for workloads with a data
5384 * size that exceeds or is close to the system's memory).
5386 remove_extent_mapping(map, em);
5387 /* once for the rb tree */
5388 free_extent_map(em);
5390 start = extent_map_end(em);
5391 write_unlock(&map->lock);
5394 free_extent_map(em);
5396 cond_resched(); /* Allow large-extent preemption. */
5399 return try_release_extent_state(tree, page, mask);
5403 * helper function for fiemap, which doesn't want to see any holes.
5404 * This maps until we find something past 'last'
5406 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5407 u64 offset, u64 last)
5409 u64 sectorsize = btrfs_inode_sectorsize(inode);
5410 struct extent_map *em;
5417 len = last - offset;
5420 len = ALIGN(len, sectorsize);
5421 em = btrfs_get_extent_fiemap(inode, offset, len);
5425 /* if this isn't a hole return it */
5426 if (em->block_start != EXTENT_MAP_HOLE)
5429 /* this is a hole, advance to the next extent */
5430 offset = extent_map_end(em);
5431 free_extent_map(em);
5439 * To cache previous fiemap extent
5441 * Will be used for merging fiemap extent
5443 struct fiemap_cache {
5452 * Helper to submit fiemap extent.
5454 * Will try to merge current fiemap extent specified by @offset, @phys,
5455 * @len and @flags with cached one.
5456 * And only when we fails to merge, cached one will be submitted as
5459 * Return value is the same as fiemap_fill_next_extent().
5461 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5462 struct fiemap_cache *cache,
5463 u64 offset, u64 phys, u64 len, u32 flags)
5471 * Sanity check, extent_fiemap() should have ensured that new
5472 * fiemap extent won't overlap with cached one.
5475 * NOTE: Physical address can overlap, due to compression
5477 if (cache->offset + cache->len > offset) {
5483 * Only merges fiemap extents if
5484 * 1) Their logical addresses are continuous
5486 * 2) Their physical addresses are continuous
5487 * So truly compressed (physical size smaller than logical size)
5488 * extents won't get merged with each other
5490 * 3) Share same flags except FIEMAP_EXTENT_LAST
5491 * So regular extent won't get merged with prealloc extent
5493 if (cache->offset + cache->len == offset &&
5494 cache->phys + cache->len == phys &&
5495 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5496 (flags & ~FIEMAP_EXTENT_LAST)) {
5498 cache->flags |= flags;
5499 goto try_submit_last;
5502 /* Not mergeable, need to submit cached one */
5503 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5504 cache->len, cache->flags);
5505 cache->cached = false;
5509 cache->cached = true;
5510 cache->offset = offset;
5513 cache->flags = flags;
5515 if (cache->flags & FIEMAP_EXTENT_LAST) {
5516 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5517 cache->phys, cache->len, cache->flags);
5518 cache->cached = false;
5524 * Emit last fiemap cache
5526 * The last fiemap cache may still be cached in the following case:
5528 * |<- Fiemap range ->|
5529 * |<------------ First extent ----------->|
5531 * In this case, the first extent range will be cached but not emitted.
5532 * So we must emit it before ending extent_fiemap().
5534 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5535 struct fiemap_cache *cache)
5542 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5543 cache->len, cache->flags);
5544 cache->cached = false;
5550 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5555 u64 max = start + len;
5559 u64 last_for_get_extent = 0;
5561 u64 isize = i_size_read(&inode->vfs_inode);
5562 struct btrfs_key found_key;
5563 struct extent_map *em = NULL;
5564 struct extent_state *cached_state = NULL;
5565 struct btrfs_path *path;
5566 struct btrfs_root *root = inode->root;
5567 struct fiemap_cache cache = { 0 };
5568 struct ulist *roots;
5569 struct ulist *tmp_ulist;
5578 path = btrfs_alloc_path();
5582 roots = ulist_alloc(GFP_KERNEL);
5583 tmp_ulist = ulist_alloc(GFP_KERNEL);
5584 if (!roots || !tmp_ulist) {
5586 goto out_free_ulist;
5590 * We can't initialize that to 'start' as this could miss extents due
5591 * to extent item merging
5594 start = round_down(start, btrfs_inode_sectorsize(inode));
5595 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5598 * lookup the last file extent. We're not using i_size here
5599 * because there might be preallocation past i_size
5601 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5604 goto out_free_ulist;
5612 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5613 found_type = found_key.type;
5615 /* No extents, but there might be delalloc bits */
5616 if (found_key.objectid != btrfs_ino(inode) ||
5617 found_type != BTRFS_EXTENT_DATA_KEY) {
5618 /* have to trust i_size as the end */
5620 last_for_get_extent = isize;
5623 * remember the start of the last extent. There are a
5624 * bunch of different factors that go into the length of the
5625 * extent, so its much less complex to remember where it started
5627 last = found_key.offset;
5628 last_for_get_extent = last + 1;
5630 btrfs_release_path(path);
5633 * we might have some extents allocated but more delalloc past those
5634 * extents. so, we trust isize unless the start of the last extent is
5639 last_for_get_extent = isize;
5642 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5645 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5654 u64 offset_in_extent = 0;
5656 /* break if the extent we found is outside the range */
5657 if (em->start >= max || extent_map_end(em) < off)
5661 * get_extent may return an extent that starts before our
5662 * requested range. We have to make sure the ranges
5663 * we return to fiemap always move forward and don't
5664 * overlap, so adjust the offsets here
5666 em_start = max(em->start, off);
5669 * record the offset from the start of the extent
5670 * for adjusting the disk offset below. Only do this if the
5671 * extent isn't compressed since our in ram offset may be past
5672 * what we have actually allocated on disk.
5674 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5675 offset_in_extent = em_start - em->start;
5676 em_end = extent_map_end(em);
5677 em_len = em_end - em_start;
5679 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5680 disko = em->block_start + offset_in_extent;
5685 * bump off for our next call to get_extent
5687 off = extent_map_end(em);
5691 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5693 flags |= FIEMAP_EXTENT_LAST;
5694 } else if (em->block_start == EXTENT_MAP_INLINE) {
5695 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5696 FIEMAP_EXTENT_NOT_ALIGNED);
5697 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5698 flags |= (FIEMAP_EXTENT_DELALLOC |
5699 FIEMAP_EXTENT_UNKNOWN);
5700 } else if (fieinfo->fi_extents_max) {
5701 u64 bytenr = em->block_start -
5702 (em->start - em->orig_start);
5705 * As btrfs supports shared space, this information
5706 * can be exported to userspace tools via
5707 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5708 * then we're just getting a count and we can skip the
5711 ret = btrfs_check_shared(root, btrfs_ino(inode),
5712 bytenr, roots, tmp_ulist);
5716 flags |= FIEMAP_EXTENT_SHARED;
5719 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5720 flags |= FIEMAP_EXTENT_ENCODED;
5721 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5722 flags |= FIEMAP_EXTENT_UNWRITTEN;
5724 free_extent_map(em);
5726 if ((em_start >= last) || em_len == (u64)-1 ||
5727 (last == (u64)-1 && isize <= em_end)) {
5728 flags |= FIEMAP_EXTENT_LAST;
5732 /* now scan forward to see if this is really the last extent. */
5733 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5739 flags |= FIEMAP_EXTENT_LAST;
5742 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5752 ret = emit_last_fiemap_cache(fieinfo, &cache);
5753 free_extent_map(em);
5755 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5759 btrfs_free_path(path);
5761 ulist_free(tmp_ulist);
5765 static void __free_extent_buffer(struct extent_buffer *eb)
5767 kmem_cache_free(extent_buffer_cache, eb);
5770 int extent_buffer_under_io(const struct extent_buffer *eb)
5772 return (atomic_read(&eb->io_pages) ||
5773 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5774 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5777 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5779 struct btrfs_subpage *subpage;
5781 lockdep_assert_held(&page->mapping->private_lock);
5783 if (PagePrivate(page)) {
5784 subpage = (struct btrfs_subpage *)page->private;
5785 if (atomic_read(&subpage->eb_refs))
5788 * Even there is no eb refs here, we may still have
5789 * end_page_read() call relying on page::private.
5791 if (atomic_read(&subpage->readers))
5797 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5799 struct btrfs_fs_info *fs_info = eb->fs_info;
5800 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5803 * For mapped eb, we're going to change the page private, which should
5804 * be done under the private_lock.
5807 spin_lock(&page->mapping->private_lock);
5809 if (!PagePrivate(page)) {
5811 spin_unlock(&page->mapping->private_lock);
5815 if (fs_info->nodesize >= PAGE_SIZE) {
5817 * We do this since we'll remove the pages after we've
5818 * removed the eb from the radix tree, so we could race
5819 * and have this page now attached to the new eb. So
5820 * only clear page_private if it's still connected to
5823 if (PagePrivate(page) &&
5824 page->private == (unsigned long)eb) {
5825 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5826 BUG_ON(PageDirty(page));
5827 BUG_ON(PageWriteback(page));
5829 * We need to make sure we haven't be attached
5832 detach_page_private(page);
5835 spin_unlock(&page->mapping->private_lock);
5840 * For subpage, we can have dummy eb with page private. In this case,
5841 * we can directly detach the private as such page is only attached to
5842 * one dummy eb, no sharing.
5845 btrfs_detach_subpage(fs_info, page);
5849 btrfs_page_dec_eb_refs(fs_info, page);
5852 * We can only detach the page private if there are no other ebs in the
5853 * page range and no unfinished IO.
5855 if (!page_range_has_eb(fs_info, page))
5856 btrfs_detach_subpage(fs_info, page);
5858 spin_unlock(&page->mapping->private_lock);
5861 /* Release all pages attached to the extent buffer */
5862 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5867 ASSERT(!extent_buffer_under_io(eb));
5869 num_pages = num_extent_pages(eb);
5870 for (i = 0; i < num_pages; i++) {
5871 struct page *page = eb->pages[i];
5876 detach_extent_buffer_page(eb, page);
5878 /* One for when we allocated the page */
5884 * Helper for releasing the extent buffer.
5886 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5888 btrfs_release_extent_buffer_pages(eb);
5889 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5890 __free_extent_buffer(eb);
5893 static struct extent_buffer *
5894 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5897 struct extent_buffer *eb = NULL;
5899 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5902 eb->fs_info = fs_info;
5904 init_rwsem(&eb->lock);
5906 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5907 &fs_info->allocated_ebs);
5908 INIT_LIST_HEAD(&eb->release_list);
5910 spin_lock_init(&eb->refs_lock);
5911 atomic_set(&eb->refs, 1);
5912 atomic_set(&eb->io_pages, 0);
5914 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5919 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5922 struct extent_buffer *new;
5923 int num_pages = num_extent_pages(src);
5926 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5931 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5932 * btrfs_release_extent_buffer() have different behavior for
5933 * UNMAPPED subpage extent buffer.
5935 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5937 memset(new->pages, 0, sizeof(*new->pages) * num_pages);
5938 ret = btrfs_alloc_page_array(num_pages, new->pages);
5940 btrfs_release_extent_buffer(new);
5944 for (i = 0; i < num_pages; i++) {
5946 struct page *p = new->pages[i];
5948 ret = attach_extent_buffer_page(new, p, NULL);
5950 btrfs_release_extent_buffer(new);
5953 WARN_ON(PageDirty(p));
5954 copy_page(page_address(p), page_address(src->pages[i]));
5956 set_extent_buffer_uptodate(new);
5961 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5962 u64 start, unsigned long len)
5964 struct extent_buffer *eb;
5969 eb = __alloc_extent_buffer(fs_info, start, len);
5973 num_pages = num_extent_pages(eb);
5974 ret = btrfs_alloc_page_array(num_pages, eb->pages);
5978 for (i = 0; i < num_pages; i++) {
5979 struct page *p = eb->pages[i];
5981 ret = attach_extent_buffer_page(eb, p, NULL);
5986 set_extent_buffer_uptodate(eb);
5987 btrfs_set_header_nritems(eb, 0);
5988 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5992 for (i = 0; i < num_pages; i++) {
5994 detach_extent_buffer_page(eb, eb->pages[i]);
5995 __free_page(eb->pages[i]);
5998 __free_extent_buffer(eb);
6002 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
6005 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
6008 static void check_buffer_tree_ref(struct extent_buffer *eb)
6012 * The TREE_REF bit is first set when the extent_buffer is added
6013 * to the radix tree. It is also reset, if unset, when a new reference
6014 * is created by find_extent_buffer.
6016 * It is only cleared in two cases: freeing the last non-tree
6017 * reference to the extent_buffer when its STALE bit is set or
6018 * calling releasepage when the tree reference is the only reference.
6020 * In both cases, care is taken to ensure that the extent_buffer's
6021 * pages are not under io. However, releasepage can be concurrently
6022 * called with creating new references, which is prone to race
6023 * conditions between the calls to check_buffer_tree_ref in those
6024 * codepaths and clearing TREE_REF in try_release_extent_buffer.
6026 * The actual lifetime of the extent_buffer in the radix tree is
6027 * adequately protected by the refcount, but the TREE_REF bit and
6028 * its corresponding reference are not. To protect against this
6029 * class of races, we call check_buffer_tree_ref from the codepaths
6030 * which trigger io after they set eb->io_pages. Note that once io is
6031 * initiated, TREE_REF can no longer be cleared, so that is the
6032 * moment at which any such race is best fixed.
6034 refs = atomic_read(&eb->refs);
6035 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6038 spin_lock(&eb->refs_lock);
6039 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6040 atomic_inc(&eb->refs);
6041 spin_unlock(&eb->refs_lock);
6044 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
6045 struct page *accessed)
6049 check_buffer_tree_ref(eb);
6051 num_pages = num_extent_pages(eb);
6052 for (i = 0; i < num_pages; i++) {
6053 struct page *p = eb->pages[i];
6056 mark_page_accessed(p);
6060 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
6063 struct extent_buffer *eb;
6065 eb = find_extent_buffer_nolock(fs_info, start);
6069 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
6070 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
6071 * another task running free_extent_buffer() might have seen that flag
6072 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
6073 * writeback flags not set) and it's still in the tree (flag
6074 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
6075 * decrementing the extent buffer's reference count twice. So here we
6076 * could race and increment the eb's reference count, clear its stale
6077 * flag, mark it as dirty and drop our reference before the other task
6078 * finishes executing free_extent_buffer, which would later result in
6079 * an attempt to free an extent buffer that is dirty.
6081 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
6082 spin_lock(&eb->refs_lock);
6083 spin_unlock(&eb->refs_lock);
6085 mark_extent_buffer_accessed(eb, NULL);
6089 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6090 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
6093 struct extent_buffer *eb, *exists = NULL;
6096 eb = find_extent_buffer(fs_info, start);
6099 eb = alloc_dummy_extent_buffer(fs_info, start);
6101 return ERR_PTR(-ENOMEM);
6102 eb->fs_info = fs_info;
6104 ret = radix_tree_preload(GFP_NOFS);
6106 exists = ERR_PTR(ret);
6109 spin_lock(&fs_info->buffer_lock);
6110 ret = radix_tree_insert(&fs_info->buffer_radix,
6111 start >> fs_info->sectorsize_bits, eb);
6112 spin_unlock(&fs_info->buffer_lock);
6113 radix_tree_preload_end();
6114 if (ret == -EEXIST) {
6115 exists = find_extent_buffer(fs_info, start);
6121 check_buffer_tree_ref(eb);
6122 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6126 btrfs_release_extent_buffer(eb);
6131 static struct extent_buffer *grab_extent_buffer(
6132 struct btrfs_fs_info *fs_info, struct page *page)
6134 struct extent_buffer *exists;
6137 * For subpage case, we completely rely on radix tree to ensure we
6138 * don't try to insert two ebs for the same bytenr. So here we always
6139 * return NULL and just continue.
6141 if (fs_info->nodesize < PAGE_SIZE)
6144 /* Page not yet attached to an extent buffer */
6145 if (!PagePrivate(page))
6149 * We could have already allocated an eb for this page and attached one
6150 * so lets see if we can get a ref on the existing eb, and if we can we
6151 * know it's good and we can just return that one, else we know we can
6152 * just overwrite page->private.
6154 exists = (struct extent_buffer *)page->private;
6155 if (atomic_inc_not_zero(&exists->refs))
6158 WARN_ON(PageDirty(page));
6159 detach_page_private(page);
6163 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
6165 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
6166 btrfs_err(fs_info, "bad tree block start %llu", start);
6170 if (fs_info->nodesize < PAGE_SIZE &&
6171 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
6173 "tree block crosses page boundary, start %llu nodesize %u",
6174 start, fs_info->nodesize);
6177 if (fs_info->nodesize >= PAGE_SIZE &&
6178 !IS_ALIGNED(start, PAGE_SIZE)) {
6180 "tree block is not page aligned, start %llu nodesize %u",
6181 start, fs_info->nodesize);
6187 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
6188 u64 start, u64 owner_root, int level)
6190 unsigned long len = fs_info->nodesize;
6193 unsigned long index = start >> PAGE_SHIFT;
6194 struct extent_buffer *eb;
6195 struct extent_buffer *exists = NULL;
6197 struct address_space *mapping = fs_info->btree_inode->i_mapping;
6201 if (check_eb_alignment(fs_info, start))
6202 return ERR_PTR(-EINVAL);
6204 #if BITS_PER_LONG == 32
6205 if (start >= MAX_LFS_FILESIZE) {
6206 btrfs_err_rl(fs_info,
6207 "extent buffer %llu is beyond 32bit page cache limit", start);
6208 btrfs_err_32bit_limit(fs_info);
6209 return ERR_PTR(-EOVERFLOW);
6211 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6212 btrfs_warn_32bit_limit(fs_info);
6215 eb = find_extent_buffer(fs_info, start);
6219 eb = __alloc_extent_buffer(fs_info, start, len);
6221 return ERR_PTR(-ENOMEM);
6222 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
6224 num_pages = num_extent_pages(eb);
6225 for (i = 0; i < num_pages; i++, index++) {
6226 struct btrfs_subpage *prealloc = NULL;
6228 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
6230 exists = ERR_PTR(-ENOMEM);
6235 * Preallocate page->private for subpage case, so that we won't
6236 * allocate memory with private_lock hold. The memory will be
6237 * freed by attach_extent_buffer_page() or freed manually if
6240 * Although we have ensured one subpage eb can only have one
6241 * page, but it may change in the future for 16K page size
6242 * support, so we still preallocate the memory in the loop.
6244 if (fs_info->nodesize < PAGE_SIZE) {
6245 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
6246 if (IS_ERR(prealloc)) {
6247 ret = PTR_ERR(prealloc);
6250 exists = ERR_PTR(ret);
6255 spin_lock(&mapping->private_lock);
6256 exists = grab_extent_buffer(fs_info, p);
6258 spin_unlock(&mapping->private_lock);
6261 mark_extent_buffer_accessed(exists, p);
6262 btrfs_free_subpage(prealloc);
6265 /* Should not fail, as we have preallocated the memory */
6266 ret = attach_extent_buffer_page(eb, p, prealloc);
6269 * To inform we have extra eb under allocation, so that
6270 * detach_extent_buffer_page() won't release the page private
6271 * when the eb hasn't yet been inserted into radix tree.
6273 * The ref will be decreased when the eb released the page, in
6274 * detach_extent_buffer_page().
6275 * Thus needs no special handling in error path.
6277 btrfs_page_inc_eb_refs(fs_info, p);
6278 spin_unlock(&mapping->private_lock);
6280 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6282 if (!PageUptodate(p))
6286 * We can't unlock the pages just yet since the extent buffer
6287 * hasn't been properly inserted in the radix tree, this
6288 * opens a race with btree_releasepage which can free a page
6289 * while we are still filling in all pages for the buffer and
6294 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6296 ret = radix_tree_preload(GFP_NOFS);
6298 exists = ERR_PTR(ret);
6302 spin_lock(&fs_info->buffer_lock);
6303 ret = radix_tree_insert(&fs_info->buffer_radix,
6304 start >> fs_info->sectorsize_bits, eb);
6305 spin_unlock(&fs_info->buffer_lock);
6306 radix_tree_preload_end();
6307 if (ret == -EEXIST) {
6308 exists = find_extent_buffer(fs_info, start);
6314 /* add one reference for the tree */
6315 check_buffer_tree_ref(eb);
6316 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6319 * Now it's safe to unlock the pages because any calls to
6320 * btree_releasepage will correctly detect that a page belongs to a
6321 * live buffer and won't free them prematurely.
6323 for (i = 0; i < num_pages; i++)
6324 unlock_page(eb->pages[i]);
6328 WARN_ON(!atomic_dec_and_test(&eb->refs));
6329 for (i = 0; i < num_pages; i++) {
6331 unlock_page(eb->pages[i]);
6334 btrfs_release_extent_buffer(eb);
6338 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6340 struct extent_buffer *eb =
6341 container_of(head, struct extent_buffer, rcu_head);
6343 __free_extent_buffer(eb);
6346 static int release_extent_buffer(struct extent_buffer *eb)
6347 __releases(&eb->refs_lock)
6349 lockdep_assert_held(&eb->refs_lock);
6351 WARN_ON(atomic_read(&eb->refs) == 0);
6352 if (atomic_dec_and_test(&eb->refs)) {
6353 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6354 struct btrfs_fs_info *fs_info = eb->fs_info;
6356 spin_unlock(&eb->refs_lock);
6358 spin_lock(&fs_info->buffer_lock);
6359 radix_tree_delete(&fs_info->buffer_radix,
6360 eb->start >> fs_info->sectorsize_bits);
6361 spin_unlock(&fs_info->buffer_lock);
6363 spin_unlock(&eb->refs_lock);
6366 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6367 /* Should be safe to release our pages at this point */
6368 btrfs_release_extent_buffer_pages(eb);
6369 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6370 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6371 __free_extent_buffer(eb);
6375 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6378 spin_unlock(&eb->refs_lock);
6383 void free_extent_buffer(struct extent_buffer *eb)
6391 refs = atomic_read(&eb->refs);
6392 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6393 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6396 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6401 spin_lock(&eb->refs_lock);
6402 if (atomic_read(&eb->refs) == 2 &&
6403 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6404 !extent_buffer_under_io(eb) &&
6405 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6406 atomic_dec(&eb->refs);
6409 * I know this is terrible, but it's temporary until we stop tracking
6410 * the uptodate bits and such for the extent buffers.
6412 release_extent_buffer(eb);
6415 void free_extent_buffer_stale(struct extent_buffer *eb)
6420 spin_lock(&eb->refs_lock);
6421 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6423 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6424 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6425 atomic_dec(&eb->refs);
6426 release_extent_buffer(eb);
6429 static void btree_clear_page_dirty(struct page *page)
6431 ASSERT(PageDirty(page));
6432 ASSERT(PageLocked(page));
6433 clear_page_dirty_for_io(page);
6434 xa_lock_irq(&page->mapping->i_pages);
6435 if (!PageDirty(page))
6436 __xa_clear_mark(&page->mapping->i_pages,
6437 page_index(page), PAGECACHE_TAG_DIRTY);
6438 xa_unlock_irq(&page->mapping->i_pages);
6441 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6443 struct btrfs_fs_info *fs_info = eb->fs_info;
6444 struct page *page = eb->pages[0];
6447 /* btree_clear_page_dirty() needs page locked */
6449 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6452 btree_clear_page_dirty(page);
6454 WARN_ON(atomic_read(&eb->refs) == 0);
6457 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6463 if (eb->fs_info->nodesize < PAGE_SIZE)
6464 return clear_subpage_extent_buffer_dirty(eb);
6466 num_pages = num_extent_pages(eb);
6468 for (i = 0; i < num_pages; i++) {
6469 page = eb->pages[i];
6470 if (!PageDirty(page))
6473 btree_clear_page_dirty(page);
6474 ClearPageError(page);
6477 WARN_ON(atomic_read(&eb->refs) == 0);
6480 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6486 check_buffer_tree_ref(eb);
6488 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6490 num_pages = num_extent_pages(eb);
6491 WARN_ON(atomic_read(&eb->refs) == 0);
6492 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6495 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
6498 * For subpage case, we can have other extent buffers in the
6499 * same page, and in clear_subpage_extent_buffer_dirty() we
6500 * have to clear page dirty without subpage lock held.
6501 * This can cause race where our page gets dirty cleared after
6504 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6505 * its page for other reasons, we can use page lock to prevent
6509 lock_page(eb->pages[0]);
6510 for (i = 0; i < num_pages; i++)
6511 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6512 eb->start, eb->len);
6514 unlock_page(eb->pages[0]);
6516 #ifdef CONFIG_BTRFS_DEBUG
6517 for (i = 0; i < num_pages; i++)
6518 ASSERT(PageDirty(eb->pages[i]));
6524 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6526 struct btrfs_fs_info *fs_info = eb->fs_info;
6531 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6532 num_pages = num_extent_pages(eb);
6533 for (i = 0; i < num_pages; i++) {
6534 page = eb->pages[i];
6539 * This is special handling for metadata subpage, as regular
6540 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6542 if (fs_info->nodesize >= PAGE_SIZE)
6543 ClearPageUptodate(page);
6545 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
6550 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6552 struct btrfs_fs_info *fs_info = eb->fs_info;
6557 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6558 num_pages = num_extent_pages(eb);
6559 for (i = 0; i < num_pages; i++) {
6560 page = eb->pages[i];
6563 * This is special handling for metadata subpage, as regular
6564 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6566 if (fs_info->nodesize >= PAGE_SIZE)
6567 SetPageUptodate(page);
6569 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
6574 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6577 struct btrfs_fs_info *fs_info = eb->fs_info;
6578 struct extent_io_tree *io_tree;
6579 struct page *page = eb->pages[0];
6580 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6583 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6584 ASSERT(PagePrivate(page));
6585 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6587 if (wait == WAIT_NONE) {
6588 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6591 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6597 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6598 PageUptodate(page) ||
6599 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6600 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6601 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6605 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6606 eb->read_mirror = 0;
6607 atomic_set(&eb->io_pages, 1);
6608 check_buffer_tree_ref(eb);
6609 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6611 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
6612 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6613 page, eb->start, eb->len,
6614 eb->start - page_offset(page),
6615 end_bio_extent_readpage, mirror_num, 0,
6619 * In the endio function, if we hit something wrong we will
6620 * increase the io_pages, so here we need to decrease it for
6623 atomic_dec(&eb->io_pages);
6626 submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6627 bio_ctrl.bio = NULL;
6629 if (ret || wait != WAIT_COMPLETE)
6632 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6633 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6638 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6644 int locked_pages = 0;
6645 int all_uptodate = 1;
6647 unsigned long num_reads = 0;
6648 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6650 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6654 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
6655 * operation, which could potentially still be in flight. In this case
6656 * we simply want to return an error.
6658 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
6661 if (eb->fs_info->nodesize < PAGE_SIZE)
6662 return read_extent_buffer_subpage(eb, wait, mirror_num);
6664 num_pages = num_extent_pages(eb);
6665 for (i = 0; i < num_pages; i++) {
6666 page = eb->pages[i];
6667 if (wait == WAIT_NONE) {
6669 * WAIT_NONE is only utilized by readahead. If we can't
6670 * acquire the lock atomically it means either the eb
6671 * is being read out or under modification.
6672 * Either way the eb will be or has been cached,
6673 * readahead can exit safely.
6675 if (!trylock_page(page))
6683 * We need to firstly lock all pages to make sure that
6684 * the uptodate bit of our pages won't be affected by
6685 * clear_extent_buffer_uptodate().
6687 for (i = 0; i < num_pages; i++) {
6688 page = eb->pages[i];
6689 if (!PageUptodate(page)) {
6696 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6700 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6701 eb->read_mirror = 0;
6702 atomic_set(&eb->io_pages, num_reads);
6704 * It is possible for releasepage to clear the TREE_REF bit before we
6705 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6707 check_buffer_tree_ref(eb);
6708 for (i = 0; i < num_pages; i++) {
6709 page = eb->pages[i];
6711 if (!PageUptodate(page)) {
6713 atomic_dec(&eb->io_pages);
6718 ClearPageError(page);
6719 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6720 &bio_ctrl, page, page_offset(page),
6721 PAGE_SIZE, 0, end_bio_extent_readpage,
6722 mirror_num, 0, false);
6725 * We failed to submit the bio so it's the
6726 * caller's responsibility to perform cleanup
6727 * i.e unlock page/set error bit.
6732 atomic_dec(&eb->io_pages);
6740 submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.bio_flags);
6741 bio_ctrl.bio = NULL;
6744 if (ret || wait != WAIT_COMPLETE)
6747 for (i = 0; i < num_pages; i++) {
6748 page = eb->pages[i];
6749 wait_on_page_locked(page);
6750 if (!PageUptodate(page))
6757 while (locked_pages > 0) {
6759 page = eb->pages[locked_pages];
6765 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6768 btrfs_warn(eb->fs_info,
6769 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6770 eb->start, eb->len, start, len);
6771 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6777 * Check if the [start, start + len) range is valid before reading/writing
6779 * NOTE: @start and @len are offset inside the eb, not logical address.
6781 * Caller should not touch the dst/src memory if this function returns error.
6783 static inline int check_eb_range(const struct extent_buffer *eb,
6784 unsigned long start, unsigned long len)
6786 unsigned long offset;
6788 /* start, start + len should not go beyond eb->len nor overflow */
6789 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6790 return report_eb_range(eb, start, len);
6795 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6796 unsigned long start, unsigned long len)
6802 char *dst = (char *)dstv;
6803 unsigned long i = get_eb_page_index(start);
6805 if (check_eb_range(eb, start, len))
6808 offset = get_eb_offset_in_page(eb, start);
6811 page = eb->pages[i];
6813 cur = min(len, (PAGE_SIZE - offset));
6814 kaddr = page_address(page);
6815 memcpy(dst, kaddr + offset, cur);
6824 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6826 unsigned long start, unsigned long len)
6832 char __user *dst = (char __user *)dstv;
6833 unsigned long i = get_eb_page_index(start);
6836 WARN_ON(start > eb->len);
6837 WARN_ON(start + len > eb->start + eb->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 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6860 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6861 unsigned long start, unsigned long len)
6867 char *ptr = (char *)ptrv;
6868 unsigned long i = get_eb_page_index(start);
6871 if (check_eb_range(eb, start, len))
6874 offset = get_eb_offset_in_page(eb, start);
6877 page = eb->pages[i];
6879 cur = min(len, (PAGE_SIZE - offset));
6881 kaddr = page_address(page);
6882 ret = memcmp(ptr, kaddr + offset, cur);
6895 * Check that the extent buffer is uptodate.
6897 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6898 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6900 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6903 struct btrfs_fs_info *fs_info = eb->fs_info;
6906 * If we are using the commit root we could potentially clear a page
6907 * Uptodate while we're using the extent buffer that we've previously
6908 * looked up. We don't want to complain in this case, as the page was
6909 * valid before, we just didn't write it out. Instead we want to catch
6910 * the case where we didn't actually read the block properly, which
6911 * would have !PageUptodate && !PageError, as we clear PageError before
6914 if (fs_info->nodesize < PAGE_SIZE) {
6915 bool uptodate, error;
6917 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6918 eb->start, eb->len);
6919 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
6920 WARN_ON(!uptodate && !error);
6922 WARN_ON(!PageUptodate(page) && !PageError(page));
6926 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6931 assert_eb_page_uptodate(eb, eb->pages[0]);
6932 kaddr = page_address(eb->pages[0]) +
6933 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6935 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6938 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6942 assert_eb_page_uptodate(eb, eb->pages[0]);
6943 kaddr = page_address(eb->pages[0]) +
6944 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6945 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6948 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6949 unsigned long start, unsigned long len)
6955 char *src = (char *)srcv;
6956 unsigned long i = get_eb_page_index(start);
6958 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6960 if (check_eb_range(eb, start, len))
6963 offset = get_eb_offset_in_page(eb, start);
6966 page = eb->pages[i];
6967 assert_eb_page_uptodate(eb, page);
6969 cur = min(len, PAGE_SIZE - offset);
6970 kaddr = page_address(page);
6971 memcpy(kaddr + offset, src, cur);
6980 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6987 unsigned long i = get_eb_page_index(start);
6989 if (check_eb_range(eb, start, len))
6992 offset = get_eb_offset_in_page(eb, start);
6995 page = eb->pages[i];
6996 assert_eb_page_uptodate(eb, page);
6998 cur = min(len, PAGE_SIZE - offset);
6999 kaddr = page_address(page);
7000 memset(kaddr + offset, 0, cur);
7008 void copy_extent_buffer_full(const struct extent_buffer *dst,
7009 const struct extent_buffer *src)
7014 ASSERT(dst->len == src->len);
7016 if (dst->fs_info->nodesize >= PAGE_SIZE) {
7017 num_pages = num_extent_pages(dst);
7018 for (i = 0; i < num_pages; i++)
7019 copy_page(page_address(dst->pages[i]),
7020 page_address(src->pages[i]));
7022 size_t src_offset = get_eb_offset_in_page(src, 0);
7023 size_t dst_offset = get_eb_offset_in_page(dst, 0);
7025 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
7026 memcpy(page_address(dst->pages[0]) + dst_offset,
7027 page_address(src->pages[0]) + src_offset,
7032 void copy_extent_buffer(const struct extent_buffer *dst,
7033 const struct extent_buffer *src,
7034 unsigned long dst_offset, unsigned long src_offset,
7037 u64 dst_len = dst->len;
7042 unsigned long i = get_eb_page_index(dst_offset);
7044 if (check_eb_range(dst, dst_offset, len) ||
7045 check_eb_range(src, src_offset, len))
7048 WARN_ON(src->len != dst_len);
7050 offset = get_eb_offset_in_page(dst, dst_offset);
7053 page = dst->pages[i];
7054 assert_eb_page_uptodate(dst, page);
7056 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
7058 kaddr = page_address(page);
7059 read_extent_buffer(src, kaddr + offset, src_offset, cur);
7069 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
7071 * @eb: the extent buffer
7072 * @start: offset of the bitmap item in the extent buffer
7074 * @page_index: return index of the page in the extent buffer that contains the
7076 * @page_offset: return offset into the page given by page_index
7078 * This helper hides the ugliness of finding the byte in an extent buffer which
7079 * contains a given bit.
7081 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
7082 unsigned long start, unsigned long nr,
7083 unsigned long *page_index,
7084 size_t *page_offset)
7086 size_t byte_offset = BIT_BYTE(nr);
7090 * The byte we want is the offset of the extent buffer + the offset of
7091 * the bitmap item in the extent buffer + the offset of the byte in the
7094 offset = start + offset_in_page(eb->start) + byte_offset;
7096 *page_index = offset >> PAGE_SHIFT;
7097 *page_offset = offset_in_page(offset);
7101 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
7102 * @eb: the extent buffer
7103 * @start: offset of the bitmap item in the extent buffer
7104 * @nr: bit number to test
7106 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
7114 eb_bitmap_offset(eb, start, nr, &i, &offset);
7115 page = eb->pages[i];
7116 assert_eb_page_uptodate(eb, page);
7117 kaddr = page_address(page);
7118 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
7122 * extent_buffer_bitmap_set - set an area of a bitmap
7123 * @eb: the extent buffer
7124 * @start: offset of the bitmap item in the extent buffer
7125 * @pos: bit number of the first bit
7126 * @len: number of bits to set
7128 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
7129 unsigned long pos, unsigned long len)
7135 const unsigned int size = pos + len;
7136 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7137 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
7139 eb_bitmap_offset(eb, start, pos, &i, &offset);
7140 page = eb->pages[i];
7141 assert_eb_page_uptodate(eb, page);
7142 kaddr = page_address(page);
7144 while (len >= bits_to_set) {
7145 kaddr[offset] |= mask_to_set;
7147 bits_to_set = BITS_PER_BYTE;
7149 if (++offset >= PAGE_SIZE && len > 0) {
7151 page = eb->pages[++i];
7152 assert_eb_page_uptodate(eb, page);
7153 kaddr = page_address(page);
7157 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
7158 kaddr[offset] |= mask_to_set;
7164 * extent_buffer_bitmap_clear - clear an area of a bitmap
7165 * @eb: the extent buffer
7166 * @start: offset of the bitmap item in the extent buffer
7167 * @pos: bit number of the first bit
7168 * @len: number of bits to clear
7170 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
7171 unsigned long start, unsigned long pos,
7178 const unsigned int size = pos + len;
7179 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7180 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
7182 eb_bitmap_offset(eb, start, pos, &i, &offset);
7183 page = eb->pages[i];
7184 assert_eb_page_uptodate(eb, page);
7185 kaddr = page_address(page);
7187 while (len >= bits_to_clear) {
7188 kaddr[offset] &= ~mask_to_clear;
7189 len -= bits_to_clear;
7190 bits_to_clear = BITS_PER_BYTE;
7192 if (++offset >= PAGE_SIZE && len > 0) {
7194 page = eb->pages[++i];
7195 assert_eb_page_uptodate(eb, page);
7196 kaddr = page_address(page);
7200 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
7201 kaddr[offset] &= ~mask_to_clear;
7205 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
7207 unsigned long distance = (src > dst) ? src - dst : dst - src;
7208 return distance < len;
7211 static void copy_pages(struct page *dst_page, struct page *src_page,
7212 unsigned long dst_off, unsigned long src_off,
7215 char *dst_kaddr = page_address(dst_page);
7217 int must_memmove = 0;
7219 if (dst_page != src_page) {
7220 src_kaddr = page_address(src_page);
7222 src_kaddr = dst_kaddr;
7223 if (areas_overlap(src_off, dst_off, len))
7228 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
7230 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
7233 void memcpy_extent_buffer(const struct extent_buffer *dst,
7234 unsigned long dst_offset, unsigned long src_offset,
7238 size_t dst_off_in_page;
7239 size_t src_off_in_page;
7240 unsigned long dst_i;
7241 unsigned long src_i;
7243 if (check_eb_range(dst, dst_offset, len) ||
7244 check_eb_range(dst, src_offset, len))
7248 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
7249 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
7251 dst_i = get_eb_page_index(dst_offset);
7252 src_i = get_eb_page_index(src_offset);
7254 cur = min(len, (unsigned long)(PAGE_SIZE -
7256 cur = min_t(unsigned long, cur,
7257 (unsigned long)(PAGE_SIZE - dst_off_in_page));
7259 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7260 dst_off_in_page, src_off_in_page, cur);
7268 void memmove_extent_buffer(const struct extent_buffer *dst,
7269 unsigned long dst_offset, unsigned long src_offset,
7273 size_t dst_off_in_page;
7274 size_t src_off_in_page;
7275 unsigned long dst_end = dst_offset + len - 1;
7276 unsigned long src_end = src_offset + len - 1;
7277 unsigned long dst_i;
7278 unsigned long src_i;
7280 if (check_eb_range(dst, dst_offset, len) ||
7281 check_eb_range(dst, src_offset, len))
7283 if (dst_offset < src_offset) {
7284 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
7288 dst_i = get_eb_page_index(dst_end);
7289 src_i = get_eb_page_index(src_end);
7291 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
7292 src_off_in_page = get_eb_offset_in_page(dst, src_end);
7294 cur = min_t(unsigned long, len, src_off_in_page + 1);
7295 cur = min(cur, dst_off_in_page + 1);
7296 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7297 dst_off_in_page - cur + 1,
7298 src_off_in_page - cur + 1, cur);
7306 #define GANG_LOOKUP_SIZE 16
7307 static struct extent_buffer *get_next_extent_buffer(
7308 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
7310 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
7311 struct extent_buffer *found = NULL;
7312 u64 page_start = page_offset(page);
7313 u64 cur = page_start;
7315 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7316 lockdep_assert_held(&fs_info->buffer_lock);
7318 while (cur < page_start + PAGE_SIZE) {
7322 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
7323 (void **)gang, cur >> fs_info->sectorsize_bits,
7324 min_t(unsigned int, GANG_LOOKUP_SIZE,
7325 PAGE_SIZE / fs_info->nodesize));
7328 for (i = 0; i < ret; i++) {
7329 /* Already beyond page end */
7330 if (gang[i]->start >= page_start + PAGE_SIZE)
7333 if (gang[i]->start >= bytenr) {
7338 cur = gang[ret - 1]->start + gang[ret - 1]->len;
7344 static int try_release_subpage_extent_buffer(struct page *page)
7346 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7347 u64 cur = page_offset(page);
7348 const u64 end = page_offset(page) + PAGE_SIZE;
7352 struct extent_buffer *eb = NULL;
7355 * Unlike try_release_extent_buffer() which uses page->private
7356 * to grab buffer, for subpage case we rely on radix tree, thus
7357 * we need to ensure radix tree consistency.
7359 * We also want an atomic snapshot of the radix tree, thus go
7360 * with spinlock rather than RCU.
7362 spin_lock(&fs_info->buffer_lock);
7363 eb = get_next_extent_buffer(fs_info, page, cur);
7365 /* No more eb in the page range after or at cur */
7366 spin_unlock(&fs_info->buffer_lock);
7369 cur = eb->start + eb->len;
7372 * The same as try_release_extent_buffer(), to ensure the eb
7373 * won't disappear out from under us.
7375 spin_lock(&eb->refs_lock);
7376 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7377 spin_unlock(&eb->refs_lock);
7378 spin_unlock(&fs_info->buffer_lock);
7381 spin_unlock(&fs_info->buffer_lock);
7384 * If tree ref isn't set then we know the ref on this eb is a
7385 * real ref, so just return, this eb will likely be freed soon
7388 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7389 spin_unlock(&eb->refs_lock);
7394 * Here we don't care about the return value, we will always
7395 * check the page private at the end. And
7396 * release_extent_buffer() will release the refs_lock.
7398 release_extent_buffer(eb);
7401 * Finally to check if we have cleared page private, as if we have
7402 * released all ebs in the page, the page private should be cleared now.
7404 spin_lock(&page->mapping->private_lock);
7405 if (!PagePrivate(page))
7409 spin_unlock(&page->mapping->private_lock);
7414 int try_release_extent_buffer(struct page *page)
7416 struct extent_buffer *eb;
7418 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
7419 return try_release_subpage_extent_buffer(page);
7422 * We need to make sure nobody is changing page->private, as we rely on
7423 * page->private as the pointer to extent buffer.
7425 spin_lock(&page->mapping->private_lock);
7426 if (!PagePrivate(page)) {
7427 spin_unlock(&page->mapping->private_lock);
7431 eb = (struct extent_buffer *)page->private;
7435 * This is a little awful but should be ok, we need to make sure that
7436 * the eb doesn't disappear out from under us while we're looking at
7439 spin_lock(&eb->refs_lock);
7440 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7441 spin_unlock(&eb->refs_lock);
7442 spin_unlock(&page->mapping->private_lock);
7445 spin_unlock(&page->mapping->private_lock);
7448 * If tree ref isn't set then we know the ref on this eb is a real ref,
7449 * so just return, this page will likely be freed soon anyway.
7451 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7452 spin_unlock(&eb->refs_lock);
7456 return release_extent_buffer(eb);
7460 * btrfs_readahead_tree_block - attempt to readahead a child block
7461 * @fs_info: the fs_info
7462 * @bytenr: bytenr to read
7463 * @owner_root: objectid of the root that owns this eb
7464 * @gen: generation for the uptodate check, can be 0
7465 * @level: level for the eb
7467 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7468 * normal uptodate check of the eb, without checking the generation. If we have
7469 * to read the block we will not block on anything.
7471 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7472 u64 bytenr, u64 owner_root, u64 gen, int level)
7474 struct extent_buffer *eb;
7477 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7481 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7482 free_extent_buffer(eb);
7486 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7488 free_extent_buffer_stale(eb);
7490 free_extent_buffer(eb);
7494 * btrfs_readahead_node_child - readahead a node's child block
7495 * @node: parent node we're reading from
7496 * @slot: slot in the parent node for the child we want to read
7498 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7499 * the slot in the node provided.
7501 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7503 btrfs_readahead_tree_block(node->fs_info,
7504 btrfs_node_blockptr(node, slot),
7505 btrfs_header_owner(node),
7506 btrfs_node_ptr_generation(node, slot),
7507 btrfs_header_level(node) - 1);