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/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/fsverity.h>
17 #include "extent_io.h"
18 #include "extent-io-tree.h"
19 #include "extent_map.h"
21 #include "btrfs_inode.h"
23 #include "check-integrity.h"
25 #include "rcu-string.h"
30 #include "block-group.h"
32 static struct kmem_cache *extent_state_cache;
33 static struct kmem_cache *extent_buffer_cache;
34 static struct bio_set btrfs_bioset;
36 static inline bool extent_state_in_tree(const struct extent_state *state)
38 return !RB_EMPTY_NODE(&state->rb_node);
41 #ifdef CONFIG_BTRFS_DEBUG
42 static LIST_HEAD(states);
43 static DEFINE_SPINLOCK(leak_lock);
45 static inline void btrfs_leak_debug_add(spinlock_t *lock,
46 struct list_head *new,
47 struct list_head *head)
51 spin_lock_irqsave(lock, flags);
53 spin_unlock_irqrestore(lock, flags);
56 static inline void btrfs_leak_debug_del(spinlock_t *lock,
57 struct list_head *entry)
61 spin_lock_irqsave(lock, flags);
63 spin_unlock_irqrestore(lock, flags);
66 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
68 struct extent_buffer *eb;
72 * If we didn't get into open_ctree our allocated_ebs will not be
73 * initialized, so just skip this.
75 if (!fs_info->allocated_ebs.next)
78 WARN_ON(!list_empty(&fs_info->allocated_ebs));
79 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
80 while (!list_empty(&fs_info->allocated_ebs)) {
81 eb = list_first_entry(&fs_info->allocated_ebs,
82 struct extent_buffer, leak_list);
84 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
85 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
86 btrfs_header_owner(eb));
87 list_del(&eb->leak_list);
88 kmem_cache_free(extent_buffer_cache, eb);
90 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
93 static inline void btrfs_extent_state_leak_debug_check(void)
95 struct extent_state *state;
97 while (!list_empty(&states)) {
98 state = list_entry(states.next, struct extent_state, leak_list);
99 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
100 state->start, state->end, state->state,
101 extent_state_in_tree(state),
102 refcount_read(&state->refs));
103 list_del(&state->leak_list);
104 kmem_cache_free(extent_state_cache, state);
108 #define btrfs_debug_check_extent_io_range(tree, start, end) \
109 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
110 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
111 struct extent_io_tree *tree, u64 start, u64 end)
113 struct inode *inode = tree->private_data;
116 if (!inode || !is_data_inode(inode))
119 isize = i_size_read(inode);
120 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
121 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
122 "%s: ino %llu isize %llu odd range [%llu,%llu]",
123 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
127 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
128 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
129 #define btrfs_extent_state_leak_debug_check() do {} while (0)
130 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
136 struct rb_node rb_node;
139 struct extent_page_data {
140 struct btrfs_bio_ctrl bio_ctrl;
141 /* tells writepage not to lock the state bits for this range
142 * it still does the unlocking
144 unsigned int extent_locked:1;
146 /* tells the submit_bio code to use REQ_SYNC */
147 unsigned int sync_io:1;
150 static int add_extent_changeset(struct extent_state *state, u32 bits,
151 struct extent_changeset *changeset,
158 if (set && (state->state & bits) == bits)
160 if (!set && (state->state & bits) == 0)
162 changeset->bytes_changed += state->end - state->start + 1;
163 ret = ulist_add(&changeset->range_changed, state->start, state->end,
168 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
169 unsigned long bio_flags)
171 blk_status_t ret = 0;
172 struct extent_io_tree *tree = bio->bi_private;
174 bio->bi_private = NULL;
176 /* Caller should ensure the bio has at least some range added */
177 ASSERT(bio->bi_iter.bi_size);
178 if (is_data_inode(tree->private_data))
179 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
182 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
183 mirror_num, bio_flags);
185 return blk_status_to_errno(ret);
188 /* Cleanup unsubmitted bios */
189 static void end_write_bio(struct extent_page_data *epd, int ret)
191 struct bio *bio = epd->bio_ctrl.bio;
194 bio->bi_status = errno_to_blk_status(ret);
196 epd->bio_ctrl.bio = NULL;
201 * Submit bio from extent page data via submit_one_bio
203 * Return 0 if everything is OK.
204 * Return <0 for error.
206 static int __must_check flush_write_bio(struct extent_page_data *epd)
209 struct bio *bio = epd->bio_ctrl.bio;
212 ret = submit_one_bio(bio, 0, 0);
214 * Clean up of epd->bio is handled by its endio function.
215 * And endio is either triggered by successful bio execution
216 * or the error handler of submit bio hook.
217 * So at this point, no matter what happened, we don't need
218 * to clean up epd->bio.
220 epd->bio_ctrl.bio = NULL;
225 int __init extent_state_cache_init(void)
227 extent_state_cache = kmem_cache_create("btrfs_extent_state",
228 sizeof(struct extent_state), 0,
229 SLAB_MEM_SPREAD, NULL);
230 if (!extent_state_cache)
235 int __init extent_io_init(void)
237 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
238 sizeof(struct extent_buffer), 0,
239 SLAB_MEM_SPREAD, NULL);
240 if (!extent_buffer_cache)
243 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
244 offsetof(struct btrfs_bio, bio),
246 goto free_buffer_cache;
248 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
254 bioset_exit(&btrfs_bioset);
257 kmem_cache_destroy(extent_buffer_cache);
258 extent_buffer_cache = NULL;
262 void __cold extent_state_cache_exit(void)
264 btrfs_extent_state_leak_debug_check();
265 kmem_cache_destroy(extent_state_cache);
268 void __cold extent_io_exit(void)
271 * Make sure all delayed rcu free are flushed before we
275 kmem_cache_destroy(extent_buffer_cache);
276 bioset_exit(&btrfs_bioset);
280 * For the file_extent_tree, we want to hold the inode lock when we lookup and
281 * update the disk_i_size, but lockdep will complain because our io_tree we hold
282 * the tree lock and get the inode lock when setting delalloc. These two things
283 * are unrelated, so make a class for the file_extent_tree so we don't get the
284 * two locking patterns mixed up.
286 static struct lock_class_key file_extent_tree_class;
288 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
289 struct extent_io_tree *tree, unsigned int owner,
292 tree->fs_info = fs_info;
293 tree->state = RB_ROOT;
294 tree->dirty_bytes = 0;
295 spin_lock_init(&tree->lock);
296 tree->private_data = private_data;
298 if (owner == IO_TREE_INODE_FILE_EXTENT)
299 lockdep_set_class(&tree->lock, &file_extent_tree_class);
302 void extent_io_tree_release(struct extent_io_tree *tree)
304 spin_lock(&tree->lock);
306 * Do a single barrier for the waitqueue_active check here, the state
307 * of the waitqueue should not change once extent_io_tree_release is
311 while (!RB_EMPTY_ROOT(&tree->state)) {
312 struct rb_node *node;
313 struct extent_state *state;
315 node = rb_first(&tree->state);
316 state = rb_entry(node, struct extent_state, rb_node);
317 rb_erase(&state->rb_node, &tree->state);
318 RB_CLEAR_NODE(&state->rb_node);
320 * btree io trees aren't supposed to have tasks waiting for
321 * changes in the flags of extent states ever.
323 ASSERT(!waitqueue_active(&state->wq));
324 free_extent_state(state);
326 cond_resched_lock(&tree->lock);
328 spin_unlock(&tree->lock);
331 static struct extent_state *alloc_extent_state(gfp_t mask)
333 struct extent_state *state;
336 * The given mask might be not appropriate for the slab allocator,
337 * drop the unsupported bits
339 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
340 state = kmem_cache_alloc(extent_state_cache, mask);
344 state->failrec = NULL;
345 RB_CLEAR_NODE(&state->rb_node);
346 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
347 refcount_set(&state->refs, 1);
348 init_waitqueue_head(&state->wq);
349 trace_alloc_extent_state(state, mask, _RET_IP_);
353 void free_extent_state(struct extent_state *state)
357 if (refcount_dec_and_test(&state->refs)) {
358 WARN_ON(extent_state_in_tree(state));
359 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
360 trace_free_extent_state(state, _RET_IP_);
361 kmem_cache_free(extent_state_cache, state);
365 static struct rb_node *tree_insert(struct rb_root *root,
366 struct rb_node *search_start,
368 struct rb_node *node,
369 struct rb_node ***p_in,
370 struct rb_node **parent_in)
373 struct rb_node *parent = NULL;
374 struct tree_entry *entry;
376 if (p_in && parent_in) {
382 p = search_start ? &search_start : &root->rb_node;
385 entry = rb_entry(parent, struct tree_entry, rb_node);
387 if (offset < entry->start)
389 else if (offset > entry->end)
396 rb_link_node(node, parent, p);
397 rb_insert_color(node, root);
402 * Search @tree for an entry that contains @offset. Such entry would have
403 * entry->start <= offset && entry->end >= offset.
405 * @tree: the tree to search
406 * @offset: offset that should fall within an entry in @tree
407 * @next_ret: pointer to the first entry whose range ends after @offset
408 * @prev_ret: pointer to the first entry whose range begins before @offset
409 * @p_ret: pointer where new node should be anchored (used when inserting an
411 * @parent_ret: points to entry which would have been the parent of the entry,
414 * This function returns a pointer to the entry that contains @offset byte
415 * address. If no such entry exists, then NULL is returned and the other
416 * pointer arguments to the function are filled, otherwise the found entry is
417 * returned and other pointers are left untouched.
419 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
420 struct rb_node **next_ret,
421 struct rb_node **prev_ret,
422 struct rb_node ***p_ret,
423 struct rb_node **parent_ret)
425 struct rb_root *root = &tree->state;
426 struct rb_node **n = &root->rb_node;
427 struct rb_node *prev = NULL;
428 struct rb_node *orig_prev = NULL;
429 struct tree_entry *entry;
430 struct tree_entry *prev_entry = NULL;
434 entry = rb_entry(prev, struct tree_entry, rb_node);
437 if (offset < entry->start)
439 else if (offset > entry->end)
452 while (prev && offset > prev_entry->end) {
453 prev = rb_next(prev);
454 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
461 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
462 while (prev && offset < prev_entry->start) {
463 prev = rb_prev(prev);
464 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
471 static inline struct rb_node *
472 tree_search_for_insert(struct extent_io_tree *tree,
474 struct rb_node ***p_ret,
475 struct rb_node **parent_ret)
477 struct rb_node *next= NULL;
480 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
486 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
489 return tree_search_for_insert(tree, offset, NULL, NULL);
493 * utility function to look for merge candidates inside a given range.
494 * Any extents with matching state are merged together into a single
495 * extent in the tree. Extents with EXTENT_IO in their state field
496 * are not merged because the end_io handlers need to be able to do
497 * operations on them without sleeping (or doing allocations/splits).
499 * This should be called with the tree lock held.
501 static void merge_state(struct extent_io_tree *tree,
502 struct extent_state *state)
504 struct extent_state *other;
505 struct rb_node *other_node;
507 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
510 other_node = rb_prev(&state->rb_node);
512 other = rb_entry(other_node, struct extent_state, rb_node);
513 if (other->end == state->start - 1 &&
514 other->state == state->state) {
515 if (tree->private_data &&
516 is_data_inode(tree->private_data))
517 btrfs_merge_delalloc_extent(tree->private_data,
519 state->start = other->start;
520 rb_erase(&other->rb_node, &tree->state);
521 RB_CLEAR_NODE(&other->rb_node);
522 free_extent_state(other);
525 other_node = rb_next(&state->rb_node);
527 other = rb_entry(other_node, struct extent_state, rb_node);
528 if (other->start == state->end + 1 &&
529 other->state == state->state) {
530 if (tree->private_data &&
531 is_data_inode(tree->private_data))
532 btrfs_merge_delalloc_extent(tree->private_data,
534 state->end = other->end;
535 rb_erase(&other->rb_node, &tree->state);
536 RB_CLEAR_NODE(&other->rb_node);
537 free_extent_state(other);
542 static void set_state_bits(struct extent_io_tree *tree,
543 struct extent_state *state, u32 *bits,
544 struct extent_changeset *changeset);
547 * insert an extent_state struct into the tree. 'bits' are set on the
548 * struct before it is inserted.
550 * This may return -EEXIST if the extent is already there, in which case the
551 * state struct is freed.
553 * The tree lock is not taken internally. This is a utility function and
554 * probably isn't what you want to call (see set/clear_extent_bit).
556 static int insert_state(struct extent_io_tree *tree,
557 struct extent_state *state, u64 start, u64 end,
559 struct rb_node **parent,
560 u32 *bits, struct extent_changeset *changeset)
562 struct rb_node *node;
565 btrfs_err(tree->fs_info,
566 "insert state: end < start %llu %llu", end, start);
569 state->start = start;
572 set_state_bits(tree, state, bits, changeset);
574 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
576 struct extent_state *found;
577 found = rb_entry(node, struct extent_state, rb_node);
578 btrfs_err(tree->fs_info,
579 "found node %llu %llu on insert of %llu %llu",
580 found->start, found->end, start, end);
583 merge_state(tree, state);
588 * split a given extent state struct in two, inserting the preallocated
589 * struct 'prealloc' as the newly created second half. 'split' indicates an
590 * offset inside 'orig' where it should be split.
593 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
594 * are two extent state structs in the tree:
595 * prealloc: [orig->start, split - 1]
596 * orig: [ split, orig->end ]
598 * The tree locks are not taken by this function. They need to be held
601 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
602 struct extent_state *prealloc, u64 split)
604 struct rb_node *node;
606 if (tree->private_data && is_data_inode(tree->private_data))
607 btrfs_split_delalloc_extent(tree->private_data, orig, split);
609 prealloc->start = orig->start;
610 prealloc->end = split - 1;
611 prealloc->state = orig->state;
614 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
615 &prealloc->rb_node, NULL, NULL);
617 free_extent_state(prealloc);
623 static struct extent_state *next_state(struct extent_state *state)
625 struct rb_node *next = rb_next(&state->rb_node);
627 return rb_entry(next, struct extent_state, rb_node);
633 * utility function to clear some bits in an extent state struct.
634 * it will optionally wake up anyone waiting on this state (wake == 1).
636 * If no bits are set on the state struct after clearing things, the
637 * struct is freed and removed from the tree
639 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
640 struct extent_state *state,
642 struct extent_changeset *changeset)
644 struct extent_state *next;
645 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
648 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
649 u64 range = state->end - state->start + 1;
650 WARN_ON(range > tree->dirty_bytes);
651 tree->dirty_bytes -= range;
654 if (tree->private_data && is_data_inode(tree->private_data))
655 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
657 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
659 state->state &= ~bits_to_clear;
662 if (state->state == 0) {
663 next = next_state(state);
664 if (extent_state_in_tree(state)) {
665 rb_erase(&state->rb_node, &tree->state);
666 RB_CLEAR_NODE(&state->rb_node);
667 free_extent_state(state);
672 merge_state(tree, state);
673 next = next_state(state);
678 static struct extent_state *
679 alloc_extent_state_atomic(struct extent_state *prealloc)
682 prealloc = alloc_extent_state(GFP_ATOMIC);
687 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
689 btrfs_panic(tree->fs_info, err,
690 "locking error: extent tree was modified by another thread while locked");
694 * clear some bits on a range in the tree. This may require splitting
695 * or inserting elements in the tree, so the gfp mask is used to
696 * indicate which allocations or sleeping are allowed.
698 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
699 * the given range from the tree regardless of state (ie for truncate).
701 * the range [start, end] is inclusive.
703 * This takes the tree lock, and returns 0 on success and < 0 on error.
705 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
706 u32 bits, int wake, int delete,
707 struct extent_state **cached_state,
708 gfp_t mask, struct extent_changeset *changeset)
710 struct extent_state *state;
711 struct extent_state *cached;
712 struct extent_state *prealloc = NULL;
713 struct rb_node *node;
718 btrfs_debug_check_extent_io_range(tree, start, end);
719 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
721 if (bits & EXTENT_DELALLOC)
722 bits |= EXTENT_NORESERVE;
725 bits |= ~EXTENT_CTLBITS;
727 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
730 if (!prealloc && gfpflags_allow_blocking(mask)) {
732 * Don't care for allocation failure here because we might end
733 * up not needing the pre-allocated extent state at all, which
734 * is the case if we only have in the tree extent states that
735 * cover our input range and don't cover too any other range.
736 * If we end up needing a new extent state we allocate it later.
738 prealloc = alloc_extent_state(mask);
741 spin_lock(&tree->lock);
743 cached = *cached_state;
746 *cached_state = NULL;
750 if (cached && extent_state_in_tree(cached) &&
751 cached->start <= start && cached->end > start) {
753 refcount_dec(&cached->refs);
758 free_extent_state(cached);
761 * this search will find the extents that end after
764 node = tree_search(tree, start);
767 state = rb_entry(node, struct extent_state, rb_node);
769 if (state->start > end)
771 WARN_ON(state->end < start);
772 last_end = state->end;
774 /* the state doesn't have the wanted bits, go ahead */
775 if (!(state->state & bits)) {
776 state = next_state(state);
781 * | ---- desired range ---- |
783 * | ------------- state -------------- |
785 * We need to split the extent we found, and may flip
786 * bits on second half.
788 * If the extent we found extends past our range, we
789 * just split and search again. It'll get split again
790 * the next time though.
792 * If the extent we found is inside our range, we clear
793 * the desired bit on it.
796 if (state->start < start) {
797 prealloc = alloc_extent_state_atomic(prealloc);
799 err = split_state(tree, state, prealloc, start);
801 extent_io_tree_panic(tree, err);
806 if (state->end <= end) {
807 state = clear_state_bit(tree, state, &bits, wake,
814 * | ---- desired range ---- |
816 * We need to split the extent, and clear the bit
819 if (state->start <= end && state->end > end) {
820 prealloc = alloc_extent_state_atomic(prealloc);
822 err = split_state(tree, state, prealloc, end + 1);
824 extent_io_tree_panic(tree, err);
829 clear_state_bit(tree, prealloc, &bits, wake, changeset);
835 state = clear_state_bit(tree, state, &bits, wake, changeset);
837 if (last_end == (u64)-1)
839 start = last_end + 1;
840 if (start <= end && state && !need_resched())
846 spin_unlock(&tree->lock);
847 if (gfpflags_allow_blocking(mask))
852 spin_unlock(&tree->lock);
854 free_extent_state(prealloc);
860 static void wait_on_state(struct extent_io_tree *tree,
861 struct extent_state *state)
862 __releases(tree->lock)
863 __acquires(tree->lock)
866 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
867 spin_unlock(&tree->lock);
869 spin_lock(&tree->lock);
870 finish_wait(&state->wq, &wait);
874 * waits for one or more bits to clear on a range in the state tree.
875 * The range [start, end] is inclusive.
876 * The tree lock is taken by this function
878 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
881 struct extent_state *state;
882 struct rb_node *node;
884 btrfs_debug_check_extent_io_range(tree, start, end);
886 spin_lock(&tree->lock);
890 * this search will find all the extents that end after
893 node = tree_search(tree, start);
898 state = rb_entry(node, struct extent_state, rb_node);
900 if (state->start > end)
903 if (state->state & bits) {
904 start = state->start;
905 refcount_inc(&state->refs);
906 wait_on_state(tree, state);
907 free_extent_state(state);
910 start = state->end + 1;
915 if (!cond_resched_lock(&tree->lock)) {
916 node = rb_next(node);
921 spin_unlock(&tree->lock);
924 static void set_state_bits(struct extent_io_tree *tree,
925 struct extent_state *state,
926 u32 *bits, struct extent_changeset *changeset)
928 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
931 if (tree->private_data && is_data_inode(tree->private_data))
932 btrfs_set_delalloc_extent(tree->private_data, state, bits);
934 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
935 u64 range = state->end - state->start + 1;
936 tree->dirty_bytes += range;
938 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
940 state->state |= bits_to_set;
943 static void cache_state_if_flags(struct extent_state *state,
944 struct extent_state **cached_ptr,
947 if (cached_ptr && !(*cached_ptr)) {
948 if (!flags || (state->state & flags)) {
950 refcount_inc(&state->refs);
955 static void cache_state(struct extent_state *state,
956 struct extent_state **cached_ptr)
958 return cache_state_if_flags(state, cached_ptr,
959 EXTENT_LOCKED | EXTENT_BOUNDARY);
963 * set some bits on a range in the tree. This may require allocations or
964 * sleeping, so the gfp mask is used to indicate what is allowed.
966 * If any of the exclusive bits are set, this will fail with -EEXIST if some
967 * part of the range already has the desired bits set. The start of the
968 * existing range is returned in failed_start in this case.
970 * [start, end] is inclusive This takes the tree lock.
972 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
973 u32 exclusive_bits, u64 *failed_start,
974 struct extent_state **cached_state, gfp_t mask,
975 struct extent_changeset *changeset)
977 struct extent_state *state;
978 struct extent_state *prealloc = NULL;
979 struct rb_node *node;
981 struct rb_node *parent;
986 btrfs_debug_check_extent_io_range(tree, start, end);
987 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
990 ASSERT(failed_start);
992 ASSERT(failed_start == NULL);
994 if (!prealloc && gfpflags_allow_blocking(mask)) {
996 * Don't care for allocation failure here because we might end
997 * up not needing the pre-allocated extent state at all, which
998 * is the case if we only have in the tree extent states that
999 * cover our input range and don't cover too any other range.
1000 * If we end up needing a new extent state we allocate it later.
1002 prealloc = alloc_extent_state(mask);
1005 spin_lock(&tree->lock);
1006 if (cached_state && *cached_state) {
1007 state = *cached_state;
1008 if (state->start <= start && state->end > start &&
1009 extent_state_in_tree(state)) {
1010 node = &state->rb_node;
1015 * this search will find all the extents that end after
1018 node = tree_search_for_insert(tree, start, &p, &parent);
1020 prealloc = alloc_extent_state_atomic(prealloc);
1022 err = insert_state(tree, prealloc, start, end,
1023 &p, &parent, &bits, changeset);
1025 extent_io_tree_panic(tree, err);
1027 cache_state(prealloc, cached_state);
1031 state = rb_entry(node, struct extent_state, rb_node);
1033 last_start = state->start;
1034 last_end = state->end;
1037 * | ---- desired range ---- |
1040 * Just lock what we found and keep going
1042 if (state->start == start && state->end <= end) {
1043 if (state->state & exclusive_bits) {
1044 *failed_start = state->start;
1049 set_state_bits(tree, state, &bits, changeset);
1050 cache_state(state, cached_state);
1051 merge_state(tree, state);
1052 if (last_end == (u64)-1)
1054 start = last_end + 1;
1055 state = next_state(state);
1056 if (start < end && state && state->start == start &&
1063 * | ---- desired range ---- |
1066 * | ------------- state -------------- |
1068 * We need to split the extent we found, and may flip bits on
1071 * If the extent we found extends past our
1072 * range, we just split and search again. It'll get split
1073 * again the next time though.
1075 * If the extent we found is inside our range, we set the
1076 * desired bit on it.
1078 if (state->start < start) {
1079 if (state->state & exclusive_bits) {
1080 *failed_start = start;
1086 * If this extent already has all the bits we want set, then
1087 * skip it, not necessary to split it or do anything with it.
1089 if ((state->state & bits) == bits) {
1090 start = state->end + 1;
1091 cache_state(state, cached_state);
1095 prealloc = alloc_extent_state_atomic(prealloc);
1097 err = split_state(tree, state, prealloc, start);
1099 extent_io_tree_panic(tree, err);
1104 if (state->end <= end) {
1105 set_state_bits(tree, state, &bits, changeset);
1106 cache_state(state, cached_state);
1107 merge_state(tree, state);
1108 if (last_end == (u64)-1)
1110 start = last_end + 1;
1111 state = next_state(state);
1112 if (start < end && state && state->start == start &&
1119 * | ---- desired range ---- |
1120 * | state | or | state |
1122 * There's a hole, we need to insert something in it and
1123 * ignore the extent we found.
1125 if (state->start > start) {
1127 if (end < last_start)
1130 this_end = last_start - 1;
1132 prealloc = alloc_extent_state_atomic(prealloc);
1136 * Avoid to free 'prealloc' if it can be merged with
1139 err = insert_state(tree, prealloc, start, this_end,
1140 NULL, NULL, &bits, changeset);
1142 extent_io_tree_panic(tree, err);
1144 cache_state(prealloc, cached_state);
1146 start = this_end + 1;
1150 * | ---- desired range ---- |
1152 * We need to split the extent, and set the bit
1155 if (state->start <= end && state->end > end) {
1156 if (state->state & exclusive_bits) {
1157 *failed_start = start;
1162 prealloc = alloc_extent_state_atomic(prealloc);
1164 err = split_state(tree, state, prealloc, end + 1);
1166 extent_io_tree_panic(tree, err);
1168 set_state_bits(tree, prealloc, &bits, changeset);
1169 cache_state(prealloc, cached_state);
1170 merge_state(tree, prealloc);
1178 spin_unlock(&tree->lock);
1179 if (gfpflags_allow_blocking(mask))
1184 spin_unlock(&tree->lock);
1186 free_extent_state(prealloc);
1193 * convert_extent_bit - convert all bits in a given range from one bit to
1195 * @tree: the io tree to search
1196 * @start: the start offset in bytes
1197 * @end: the end offset in bytes (inclusive)
1198 * @bits: the bits to set in this range
1199 * @clear_bits: the bits to clear in this range
1200 * @cached_state: state that we're going to cache
1202 * This will go through and set bits for the given range. If any states exist
1203 * already in this range they are set with the given bit and cleared of the
1204 * clear_bits. This is only meant to be used by things that are mergeable, ie
1205 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1206 * boundary bits like LOCK.
1208 * All allocations are done with GFP_NOFS.
1210 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1211 u32 bits, u32 clear_bits,
1212 struct extent_state **cached_state)
1214 struct extent_state *state;
1215 struct extent_state *prealloc = NULL;
1216 struct rb_node *node;
1218 struct rb_node *parent;
1222 bool first_iteration = true;
1224 btrfs_debug_check_extent_io_range(tree, start, end);
1225 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1231 * Best effort, don't worry if extent state allocation fails
1232 * here for the first iteration. We might have a cached state
1233 * that matches exactly the target range, in which case no
1234 * extent state allocations are needed. We'll only know this
1235 * after locking the tree.
1237 prealloc = alloc_extent_state(GFP_NOFS);
1238 if (!prealloc && !first_iteration)
1242 spin_lock(&tree->lock);
1243 if (cached_state && *cached_state) {
1244 state = *cached_state;
1245 if (state->start <= start && state->end > start &&
1246 extent_state_in_tree(state)) {
1247 node = &state->rb_node;
1253 * this search will find all the extents that end after
1256 node = tree_search_for_insert(tree, start, &p, &parent);
1258 prealloc = alloc_extent_state_atomic(prealloc);
1263 err = insert_state(tree, prealloc, start, end,
1264 &p, &parent, &bits, NULL);
1266 extent_io_tree_panic(tree, err);
1267 cache_state(prealloc, cached_state);
1271 state = rb_entry(node, struct extent_state, rb_node);
1273 last_start = state->start;
1274 last_end = state->end;
1277 * | ---- desired range ---- |
1280 * Just lock what we found and keep going
1282 if (state->start == start && state->end <= end) {
1283 set_state_bits(tree, state, &bits, NULL);
1284 cache_state(state, cached_state);
1285 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1286 if (last_end == (u64)-1)
1288 start = last_end + 1;
1289 if (start < end && state && state->start == start &&
1296 * | ---- desired range ---- |
1299 * | ------------- state -------------- |
1301 * We need to split the extent we found, and may flip bits on
1304 * If the extent we found extends past our
1305 * range, we just split and search again. It'll get split
1306 * again the next time though.
1308 * If the extent we found is inside our range, we set the
1309 * desired bit on it.
1311 if (state->start < start) {
1312 prealloc = alloc_extent_state_atomic(prealloc);
1317 err = split_state(tree, state, prealloc, start);
1319 extent_io_tree_panic(tree, err);
1323 if (state->end <= end) {
1324 set_state_bits(tree, state, &bits, NULL);
1325 cache_state(state, cached_state);
1326 state = clear_state_bit(tree, state, &clear_bits, 0,
1328 if (last_end == (u64)-1)
1330 start = last_end + 1;
1331 if (start < end && state && state->start == start &&
1338 * | ---- desired range ---- |
1339 * | state | or | state |
1341 * There's a hole, we need to insert something in it and
1342 * ignore the extent we found.
1344 if (state->start > start) {
1346 if (end < last_start)
1349 this_end = last_start - 1;
1351 prealloc = alloc_extent_state_atomic(prealloc);
1358 * Avoid to free 'prealloc' if it can be merged with
1361 err = insert_state(tree, prealloc, start, this_end,
1362 NULL, NULL, &bits, NULL);
1364 extent_io_tree_panic(tree, err);
1365 cache_state(prealloc, cached_state);
1367 start = this_end + 1;
1371 * | ---- desired range ---- |
1373 * We need to split the extent, and set the bit
1376 if (state->start <= end && state->end > end) {
1377 prealloc = alloc_extent_state_atomic(prealloc);
1383 err = split_state(tree, state, prealloc, end + 1);
1385 extent_io_tree_panic(tree, err);
1387 set_state_bits(tree, prealloc, &bits, NULL);
1388 cache_state(prealloc, cached_state);
1389 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1397 spin_unlock(&tree->lock);
1399 first_iteration = false;
1403 spin_unlock(&tree->lock);
1405 free_extent_state(prealloc);
1410 /* wrappers around set/clear extent bit */
1411 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1412 u32 bits, struct extent_changeset *changeset)
1415 * We don't support EXTENT_LOCKED yet, as current changeset will
1416 * record any bits changed, so for EXTENT_LOCKED case, it will
1417 * either fail with -EEXIST or changeset will record the whole
1420 BUG_ON(bits & EXTENT_LOCKED);
1422 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1426 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1429 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1433 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1434 u32 bits, int wake, int delete,
1435 struct extent_state **cached)
1437 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1438 cached, GFP_NOFS, NULL);
1441 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1442 u32 bits, struct extent_changeset *changeset)
1445 * Don't support EXTENT_LOCKED case, same reason as
1446 * set_record_extent_bits().
1448 BUG_ON(bits & EXTENT_LOCKED);
1450 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1455 * either insert or lock state struct between start and end use mask to tell
1456 * us if waiting is desired.
1458 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1459 struct extent_state **cached_state)
1465 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1466 EXTENT_LOCKED, &failed_start,
1467 cached_state, GFP_NOFS, NULL);
1468 if (err == -EEXIST) {
1469 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1470 start = failed_start;
1473 WARN_ON(start > end);
1478 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1483 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1484 &failed_start, NULL, GFP_NOFS, NULL);
1485 if (err == -EEXIST) {
1486 if (failed_start > start)
1487 clear_extent_bit(tree, start, failed_start - 1,
1488 EXTENT_LOCKED, 1, 0, NULL);
1494 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1496 unsigned long index = start >> PAGE_SHIFT;
1497 unsigned long end_index = end >> PAGE_SHIFT;
1500 while (index <= end_index) {
1501 page = find_get_page(inode->i_mapping, index);
1502 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1503 clear_page_dirty_for_io(page);
1509 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1511 struct address_space *mapping = inode->i_mapping;
1512 unsigned long index = start >> PAGE_SHIFT;
1513 unsigned long end_index = end >> PAGE_SHIFT;
1514 struct folio *folio;
1516 while (index <= end_index) {
1517 folio = filemap_get_folio(mapping, index);
1518 filemap_dirty_folio(mapping, folio);
1519 folio_account_redirty(folio);
1520 index += folio_nr_pages(folio);
1525 /* find the first state struct with 'bits' set after 'start', and
1526 * return it. tree->lock must be held. NULL will returned if
1527 * nothing was found after 'start'
1529 static struct extent_state *
1530 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1532 struct rb_node *node;
1533 struct extent_state *state;
1536 * this search will find all the extents that end after
1539 node = tree_search(tree, start);
1544 state = rb_entry(node, struct extent_state, rb_node);
1545 if (state->end >= start && (state->state & bits))
1548 node = rb_next(node);
1557 * Find the first offset in the io tree with one or more @bits set.
1559 * Note: If there are multiple bits set in @bits, any of them will match.
1561 * Return 0 if we find something, and update @start_ret and @end_ret.
1562 * Return 1 if we found nothing.
1564 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1565 u64 *start_ret, u64 *end_ret, u32 bits,
1566 struct extent_state **cached_state)
1568 struct extent_state *state;
1571 spin_lock(&tree->lock);
1572 if (cached_state && *cached_state) {
1573 state = *cached_state;
1574 if (state->end == start - 1 && extent_state_in_tree(state)) {
1575 while ((state = next_state(state)) != NULL) {
1576 if (state->state & bits)
1579 free_extent_state(*cached_state);
1580 *cached_state = NULL;
1583 free_extent_state(*cached_state);
1584 *cached_state = NULL;
1587 state = find_first_extent_bit_state(tree, start, bits);
1590 cache_state_if_flags(state, cached_state, 0);
1591 *start_ret = state->start;
1592 *end_ret = state->end;
1596 spin_unlock(&tree->lock);
1601 * Find a contiguous area of bits
1603 * @tree: io tree to check
1604 * @start: offset to start the search from
1605 * @start_ret: the first offset we found with the bits set
1606 * @end_ret: the final contiguous range of the bits that were set
1607 * @bits: bits to look for
1609 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1610 * to set bits appropriately, and then merge them again. During this time it
1611 * will drop the tree->lock, so use this helper if you want to find the actual
1612 * contiguous area for given bits. We will search to the first bit we find, and
1613 * then walk down the tree until we find a non-contiguous area. The area
1614 * returned will be the full contiguous area with the bits set.
1616 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1617 u64 *start_ret, u64 *end_ret, u32 bits)
1619 struct extent_state *state;
1622 spin_lock(&tree->lock);
1623 state = find_first_extent_bit_state(tree, start, bits);
1625 *start_ret = state->start;
1626 *end_ret = state->end;
1627 while ((state = next_state(state)) != NULL) {
1628 if (state->start > (*end_ret + 1))
1630 *end_ret = state->end;
1634 spin_unlock(&tree->lock);
1639 * Find the first range that has @bits not set. This range could start before
1642 * @tree: the tree to search
1643 * @start: offset at/after which the found extent should start
1644 * @start_ret: records the beginning of the range
1645 * @end_ret: records the end of the range (inclusive)
1646 * @bits: the set of bits which must be unset
1648 * Since unallocated range is also considered one which doesn't have the bits
1649 * set it's possible that @end_ret contains -1, this happens in case the range
1650 * spans (last_range_end, end of device]. In this case it's up to the caller to
1651 * trim @end_ret to the appropriate size.
1653 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1654 u64 *start_ret, u64 *end_ret, u32 bits)
1656 struct extent_state *state;
1657 struct rb_node *node, *prev = NULL, *next;
1659 spin_lock(&tree->lock);
1661 /* Find first extent with bits cleared */
1663 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1664 if (!node && !next && !prev) {
1666 * Tree is completely empty, send full range and let
1667 * caller deal with it
1672 } else if (!node && !next) {
1674 * We are past the last allocated chunk, set start at
1675 * the end of the last extent.
1677 state = rb_entry(prev, struct extent_state, rb_node);
1678 *start_ret = state->end + 1;
1685 * At this point 'node' either contains 'start' or start is
1688 state = rb_entry(node, struct extent_state, rb_node);
1690 if (in_range(start, state->start, state->end - state->start + 1)) {
1691 if (state->state & bits) {
1693 * |--range with bits sets--|
1697 start = state->end + 1;
1700 * 'start' falls within a range that doesn't
1701 * have the bits set, so take its start as
1702 * the beginning of the desired range
1704 * |--range with bits cleared----|
1708 *start_ret = state->start;
1713 * |---prev range---|---hole/unset---|---node range---|
1719 * |---hole/unset--||--first node--|
1724 state = rb_entry(prev, struct extent_state,
1726 *start_ret = state->end + 1;
1735 * Find the longest stretch from start until an entry which has the
1739 state = rb_entry(node, struct extent_state, rb_node);
1740 if (state->end >= start && !(state->state & bits)) {
1741 *end_ret = state->end;
1743 *end_ret = state->start - 1;
1747 node = rb_next(node);
1752 spin_unlock(&tree->lock);
1756 * find a contiguous range of bytes in the file marked as delalloc, not
1757 * more than 'max_bytes'. start and end are used to return the range,
1759 * true is returned if we find something, false if nothing was in the tree
1761 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1762 u64 *end, u64 max_bytes,
1763 struct extent_state **cached_state)
1765 struct rb_node *node;
1766 struct extent_state *state;
1767 u64 cur_start = *start;
1769 u64 total_bytes = 0;
1771 spin_lock(&tree->lock);
1774 * this search will find all the extents that end after
1777 node = tree_search(tree, cur_start);
1784 state = rb_entry(node, struct extent_state, rb_node);
1785 if (found && (state->start != cur_start ||
1786 (state->state & EXTENT_BOUNDARY))) {
1789 if (!(state->state & EXTENT_DELALLOC)) {
1795 *start = state->start;
1796 *cached_state = state;
1797 refcount_inc(&state->refs);
1801 cur_start = state->end + 1;
1802 node = rb_next(node);
1803 total_bytes += state->end - state->start + 1;
1804 if (total_bytes >= max_bytes)
1810 spin_unlock(&tree->lock);
1815 * Process one page for __process_pages_contig().
1817 * Return >0 if we hit @page == @locked_page.
1818 * Return 0 if we updated the page status.
1819 * Return -EGAIN if the we need to try again.
1820 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1822 static int process_one_page(struct btrfs_fs_info *fs_info,
1823 struct address_space *mapping,
1824 struct page *page, struct page *locked_page,
1825 unsigned long page_ops, u64 start, u64 end)
1829 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1830 len = end + 1 - start;
1832 if (page_ops & PAGE_SET_ORDERED)
1833 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
1834 if (page_ops & PAGE_SET_ERROR)
1835 btrfs_page_clamp_set_error(fs_info, page, start, len);
1836 if (page_ops & PAGE_START_WRITEBACK) {
1837 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1838 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1840 if (page_ops & PAGE_END_WRITEBACK)
1841 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1843 if (page == locked_page)
1846 if (page_ops & PAGE_LOCK) {
1849 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
1852 if (!PageDirty(page) || page->mapping != mapping) {
1853 btrfs_page_end_writer_lock(fs_info, page, start, len);
1857 if (page_ops & PAGE_UNLOCK)
1858 btrfs_page_end_writer_lock(fs_info, page, start, len);
1862 static int __process_pages_contig(struct address_space *mapping,
1863 struct page *locked_page,
1864 u64 start, u64 end, unsigned long page_ops,
1867 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1868 pgoff_t start_index = start >> PAGE_SHIFT;
1869 pgoff_t end_index = end >> PAGE_SHIFT;
1870 pgoff_t index = start_index;
1871 unsigned long nr_pages = end_index - start_index + 1;
1872 unsigned long pages_processed = 0;
1873 struct page *pages[16];
1877 if (page_ops & PAGE_LOCK) {
1878 ASSERT(page_ops == PAGE_LOCK);
1879 ASSERT(processed_end && *processed_end == start);
1882 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1883 mapping_set_error(mapping, -EIO);
1885 while (nr_pages > 0) {
1888 found_pages = find_get_pages_contig(mapping, index,
1889 min_t(unsigned long,
1890 nr_pages, ARRAY_SIZE(pages)), pages);
1891 if (found_pages == 0) {
1893 * Only if we're going to lock these pages, we can find
1894 * nothing at @index.
1896 ASSERT(page_ops & PAGE_LOCK);
1901 for (i = 0; i < found_pages; i++) {
1904 process_ret = process_one_page(fs_info, mapping,
1905 pages[i], locked_page, page_ops,
1907 if (process_ret < 0) {
1908 for (; i < found_pages; i++)
1916 nr_pages -= found_pages;
1917 index += found_pages;
1921 if (err && processed_end) {
1923 * Update @processed_end. I know this is awful since it has
1924 * two different return value patterns (inclusive vs exclusive).
1926 * But the exclusive pattern is necessary if @start is 0, or we
1927 * underflow and check against processed_end won't work as
1930 if (pages_processed)
1931 *processed_end = min(end,
1932 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1934 *processed_end = start;
1939 static noinline void __unlock_for_delalloc(struct inode *inode,
1940 struct page *locked_page,
1943 unsigned long index = start >> PAGE_SHIFT;
1944 unsigned long end_index = end >> PAGE_SHIFT;
1946 ASSERT(locked_page);
1947 if (index == locked_page->index && end_index == index)
1950 __process_pages_contig(inode->i_mapping, locked_page, start, end,
1954 static noinline int lock_delalloc_pages(struct inode *inode,
1955 struct page *locked_page,
1959 unsigned long index = delalloc_start >> PAGE_SHIFT;
1960 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1961 u64 processed_end = delalloc_start;
1964 ASSERT(locked_page);
1965 if (index == locked_page->index && index == end_index)
1968 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1969 delalloc_end, PAGE_LOCK, &processed_end);
1970 if (ret == -EAGAIN && processed_end > delalloc_start)
1971 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1977 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1978 * more than @max_bytes.
1980 * @start: The original start bytenr to search.
1981 * Will store the extent range start bytenr.
1982 * @end: The original end bytenr of the search range
1983 * Will store the extent range end bytenr.
1985 * Return true if we find a delalloc range which starts inside the original
1986 * range, and @start/@end will store the delalloc range start/end.
1988 * Return false if we can't find any delalloc range which starts inside the
1989 * original range, and @start/@end will be the non-delalloc range start/end.
1992 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1993 struct page *locked_page, u64 *start,
1996 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1997 const u64 orig_start = *start;
1998 const u64 orig_end = *end;
1999 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
2003 struct extent_state *cached_state = NULL;
2007 /* Caller should pass a valid @end to indicate the search range end */
2008 ASSERT(orig_end > orig_start);
2010 /* The range should at least cover part of the page */
2011 ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
2012 orig_end <= page_offset(locked_page)));
2014 /* step one, find a bunch of delalloc bytes starting at start */
2015 delalloc_start = *start;
2017 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
2018 max_bytes, &cached_state);
2019 if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
2020 *start = delalloc_start;
2022 /* @delalloc_end can be -1, never go beyond @orig_end */
2023 *end = min(delalloc_end, orig_end);
2024 free_extent_state(cached_state);
2029 * start comes from the offset of locked_page. We have to lock
2030 * pages in order, so we can't process delalloc bytes before
2033 if (delalloc_start < *start)
2034 delalloc_start = *start;
2037 * make sure to limit the number of pages we try to lock down
2039 if (delalloc_end + 1 - delalloc_start > max_bytes)
2040 delalloc_end = delalloc_start + max_bytes - 1;
2042 /* step two, lock all the pages after the page that has start */
2043 ret = lock_delalloc_pages(inode, locked_page,
2044 delalloc_start, delalloc_end);
2045 ASSERT(!ret || ret == -EAGAIN);
2046 if (ret == -EAGAIN) {
2047 /* some of the pages are gone, lets avoid looping by
2048 * shortening the size of the delalloc range we're searching
2050 free_extent_state(cached_state);
2051 cached_state = NULL;
2053 max_bytes = PAGE_SIZE;
2062 /* step three, lock the state bits for the whole range */
2063 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2065 /* then test to make sure it is all still delalloc */
2066 ret = test_range_bit(tree, delalloc_start, delalloc_end,
2067 EXTENT_DELALLOC, 1, cached_state);
2069 unlock_extent_cached(tree, delalloc_start, delalloc_end,
2071 __unlock_for_delalloc(inode, locked_page,
2072 delalloc_start, delalloc_end);
2076 free_extent_state(cached_state);
2077 *start = delalloc_start;
2078 *end = delalloc_end;
2083 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2084 struct page *locked_page,
2085 u32 clear_bits, unsigned long page_ops)
2087 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2089 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2090 start, end, page_ops, NULL);
2094 * count the number of bytes in the tree that have a given bit(s)
2095 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2096 * cached. The total number found is returned.
2098 u64 count_range_bits(struct extent_io_tree *tree,
2099 u64 *start, u64 search_end, u64 max_bytes,
2100 u32 bits, int contig)
2102 struct rb_node *node;
2103 struct extent_state *state;
2104 u64 cur_start = *start;
2105 u64 total_bytes = 0;
2109 if (WARN_ON(search_end <= cur_start))
2112 spin_lock(&tree->lock);
2113 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2114 total_bytes = tree->dirty_bytes;
2118 * this search will find all the extents that end after
2121 node = tree_search(tree, cur_start);
2126 state = rb_entry(node, struct extent_state, rb_node);
2127 if (state->start > search_end)
2129 if (contig && found && state->start > last + 1)
2131 if (state->end >= cur_start && (state->state & bits) == bits) {
2132 total_bytes += min(search_end, state->end) + 1 -
2133 max(cur_start, state->start);
2134 if (total_bytes >= max_bytes)
2137 *start = max(cur_start, state->start);
2141 } else if (contig && found) {
2144 node = rb_next(node);
2149 spin_unlock(&tree->lock);
2154 * set the private field for a given byte offset in the tree. If there isn't
2155 * an extent_state there already, this does nothing.
2157 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2158 struct io_failure_record *failrec)
2160 struct rb_node *node;
2161 struct extent_state *state;
2164 spin_lock(&tree->lock);
2166 * this search will find all the extents that end after
2169 node = tree_search(tree, start);
2174 state = rb_entry(node, struct extent_state, rb_node);
2175 if (state->start != start) {
2179 state->failrec = failrec;
2181 spin_unlock(&tree->lock);
2185 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2187 struct rb_node *node;
2188 struct extent_state *state;
2189 struct io_failure_record *failrec;
2191 spin_lock(&tree->lock);
2193 * this search will find all the extents that end after
2196 node = tree_search(tree, start);
2198 failrec = ERR_PTR(-ENOENT);
2201 state = rb_entry(node, struct extent_state, rb_node);
2202 if (state->start != start) {
2203 failrec = ERR_PTR(-ENOENT);
2207 failrec = state->failrec;
2209 spin_unlock(&tree->lock);
2214 * searches a range in the state tree for a given mask.
2215 * If 'filled' == 1, this returns 1 only if every extent in the tree
2216 * has the bits set. Otherwise, 1 is returned if any bit in the
2217 * range is found set.
2219 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2220 u32 bits, int filled, struct extent_state *cached)
2222 struct extent_state *state = NULL;
2223 struct rb_node *node;
2226 spin_lock(&tree->lock);
2227 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2228 cached->end > start)
2229 node = &cached->rb_node;
2231 node = tree_search(tree, start);
2232 while (node && start <= end) {
2233 state = rb_entry(node, struct extent_state, rb_node);
2235 if (filled && state->start > start) {
2240 if (state->start > end)
2243 if (state->state & bits) {
2247 } else if (filled) {
2252 if (state->end == (u64)-1)
2255 start = state->end + 1;
2258 node = rb_next(node);
2265 spin_unlock(&tree->lock);
2269 int free_io_failure(struct extent_io_tree *failure_tree,
2270 struct extent_io_tree *io_tree,
2271 struct io_failure_record *rec)
2276 set_state_failrec(failure_tree, rec->start, NULL);
2277 ret = clear_extent_bits(failure_tree, rec->start,
2278 rec->start + rec->len - 1,
2279 EXTENT_LOCKED | EXTENT_DIRTY);
2283 ret = clear_extent_bits(io_tree, rec->start,
2284 rec->start + rec->len - 1,
2294 * this bypasses the standard btrfs submit functions deliberately, as
2295 * the standard behavior is to write all copies in a raid setup. here we only
2296 * want to write the one bad copy. so we do the mapping for ourselves and issue
2297 * submit_bio directly.
2298 * to avoid any synchronization issues, wait for the data after writing, which
2299 * actually prevents the read that triggered the error from finishing.
2300 * currently, there can be no more than two copies of every data bit. thus,
2301 * exactly one rewrite is required.
2303 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2304 u64 length, u64 logical, struct page *page,
2305 unsigned int pg_offset, int mirror_num)
2308 struct btrfs_device *dev;
2311 struct btrfs_io_context *bioc = NULL;
2314 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2315 BUG_ON(!mirror_num);
2317 if (btrfs_repair_one_zone(fs_info, logical))
2320 bio = btrfs_bio_alloc(1);
2321 bio->bi_iter.bi_size = 0;
2322 map_length = length;
2325 * Avoid races with device replace and make sure our bioc has devices
2326 * associated to its stripes that don't go away while we are doing the
2327 * read repair operation.
2329 btrfs_bio_counter_inc_blocked(fs_info);
2330 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2332 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2333 * to update all raid stripes, but here we just want to correct
2334 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2335 * stripe's dev and sector.
2337 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2338 &map_length, &bioc, 0);
2340 btrfs_bio_counter_dec(fs_info);
2344 ASSERT(bioc->mirror_num == 1);
2346 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2347 &map_length, &bioc, mirror_num);
2349 btrfs_bio_counter_dec(fs_info);
2353 BUG_ON(mirror_num != bioc->mirror_num);
2356 sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
2357 bio->bi_iter.bi_sector = sector;
2358 dev = bioc->stripes[bioc->mirror_num - 1].dev;
2359 btrfs_put_bioc(bioc);
2360 if (!dev || !dev->bdev ||
2361 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2362 btrfs_bio_counter_dec(fs_info);
2366 bio_set_dev(bio, dev->bdev);
2367 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2368 bio_add_page(bio, page, length, pg_offset);
2370 if (btrfsic_submit_bio_wait(bio)) {
2371 /* try to remap that extent elsewhere? */
2372 btrfs_bio_counter_dec(fs_info);
2374 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2378 btrfs_info_rl_in_rcu(fs_info,
2379 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2381 rcu_str_deref(dev->name), sector);
2382 btrfs_bio_counter_dec(fs_info);
2387 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2389 struct btrfs_fs_info *fs_info = eb->fs_info;
2390 u64 start = eb->start;
2391 int i, num_pages = num_extent_pages(eb);
2394 if (sb_rdonly(fs_info->sb))
2397 for (i = 0; i < num_pages; i++) {
2398 struct page *p = eb->pages[i];
2400 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2401 start - page_offset(p), mirror_num);
2411 * each time an IO finishes, we do a fast check in the IO failure tree
2412 * to see if we need to process or clean up an io_failure_record
2414 int clean_io_failure(struct btrfs_fs_info *fs_info,
2415 struct extent_io_tree *failure_tree,
2416 struct extent_io_tree *io_tree, u64 start,
2417 struct page *page, u64 ino, unsigned int pg_offset)
2420 struct io_failure_record *failrec;
2421 struct extent_state *state;
2426 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2431 failrec = get_state_failrec(failure_tree, start);
2432 if (IS_ERR(failrec))
2435 BUG_ON(!failrec->this_mirror);
2437 if (sb_rdonly(fs_info->sb))
2440 spin_lock(&io_tree->lock);
2441 state = find_first_extent_bit_state(io_tree,
2444 spin_unlock(&io_tree->lock);
2446 if (state && state->start <= failrec->start &&
2447 state->end >= failrec->start + failrec->len - 1) {
2448 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2450 if (num_copies > 1) {
2451 repair_io_failure(fs_info, ino, start, failrec->len,
2452 failrec->logical, page, pg_offset,
2453 failrec->failed_mirror);
2458 free_io_failure(failure_tree, io_tree, failrec);
2464 * Can be called when
2465 * - hold extent lock
2466 * - under ordered extent
2467 * - the inode is freeing
2469 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2471 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2472 struct io_failure_record *failrec;
2473 struct extent_state *state, *next;
2475 if (RB_EMPTY_ROOT(&failure_tree->state))
2478 spin_lock(&failure_tree->lock);
2479 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2481 if (state->start > end)
2484 ASSERT(state->end <= end);
2486 next = next_state(state);
2488 failrec = state->failrec;
2489 free_extent_state(state);
2494 spin_unlock(&failure_tree->lock);
2497 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2500 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2501 struct io_failure_record *failrec;
2502 struct extent_map *em;
2503 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2504 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2505 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2506 const u32 sectorsize = fs_info->sectorsize;
2510 failrec = get_state_failrec(failure_tree, start);
2511 if (!IS_ERR(failrec)) {
2512 btrfs_debug(fs_info,
2513 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2514 failrec->logical, failrec->start, failrec->len);
2516 * when data can be on disk more than twice, add to failrec here
2517 * (e.g. with a list for failed_mirror) to make
2518 * clean_io_failure() clean all those errors at once.
2524 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2526 return ERR_PTR(-ENOMEM);
2528 failrec->start = start;
2529 failrec->len = sectorsize;
2530 failrec->this_mirror = 0;
2531 failrec->bio_flags = 0;
2533 read_lock(&em_tree->lock);
2534 em = lookup_extent_mapping(em_tree, start, failrec->len);
2536 read_unlock(&em_tree->lock);
2538 return ERR_PTR(-EIO);
2541 if (em->start > start || em->start + em->len <= start) {
2542 free_extent_map(em);
2545 read_unlock(&em_tree->lock);
2548 return ERR_PTR(-EIO);
2551 logical = start - em->start;
2552 logical = em->block_start + logical;
2553 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2554 logical = em->block_start;
2555 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2556 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2559 btrfs_debug(fs_info,
2560 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2561 logical, start, failrec->len);
2563 failrec->logical = logical;
2564 free_extent_map(em);
2566 /* Set the bits in the private failure tree */
2567 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2568 EXTENT_LOCKED | EXTENT_DIRTY);
2570 ret = set_state_failrec(failure_tree, start, failrec);
2571 /* Set the bits in the inode's tree */
2572 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2574 } else if (ret < 0) {
2576 return ERR_PTR(ret);
2582 static bool btrfs_check_repairable(struct inode *inode,
2583 struct io_failure_record *failrec,
2586 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2589 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2590 if (num_copies == 1) {
2592 * we only have a single copy of the data, so don't bother with
2593 * all the retry and error correction code that follows. no
2594 * matter what the error is, it is very likely to persist.
2596 btrfs_debug(fs_info,
2597 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2598 num_copies, failrec->this_mirror, failed_mirror);
2602 /* The failure record should only contain one sector */
2603 ASSERT(failrec->len == fs_info->sectorsize);
2606 * There are two premises:
2607 * a) deliver good data to the caller
2608 * b) correct the bad sectors on disk
2610 * Since we're only doing repair for one sector, we only need to get
2611 * a good copy of the failed sector and if we succeed, we have setup
2612 * everything for repair_io_failure to do the rest for us.
2614 ASSERT(failed_mirror);
2615 failrec->failed_mirror = failed_mirror;
2616 failrec->this_mirror++;
2617 if (failrec->this_mirror == failed_mirror)
2618 failrec->this_mirror++;
2620 if (failrec->this_mirror > num_copies) {
2621 btrfs_debug(fs_info,
2622 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2623 num_copies, failrec->this_mirror, failed_mirror);
2630 int btrfs_repair_one_sector(struct inode *inode,
2631 struct bio *failed_bio, u32 bio_offset,
2632 struct page *page, unsigned int pgoff,
2633 u64 start, int failed_mirror,
2634 submit_bio_hook_t *submit_bio_hook)
2636 struct io_failure_record *failrec;
2637 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2638 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2639 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2640 struct btrfs_bio *failed_bbio = btrfs_bio(failed_bio);
2641 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2642 struct bio *repair_bio;
2643 struct btrfs_bio *repair_bbio;
2645 btrfs_debug(fs_info,
2646 "repair read error: read error at %llu", start);
2648 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2650 failrec = btrfs_get_io_failure_record(inode, start);
2651 if (IS_ERR(failrec))
2652 return PTR_ERR(failrec);
2655 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2656 free_io_failure(failure_tree, tree, failrec);
2660 repair_bio = btrfs_bio_alloc(1);
2661 repair_bbio = btrfs_bio(repair_bio);
2662 repair_bbio->file_offset = start;
2663 repair_bio->bi_opf = REQ_OP_READ;
2664 repair_bio->bi_end_io = failed_bio->bi_end_io;
2665 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2666 repair_bio->bi_private = failed_bio->bi_private;
2668 if (failed_bbio->csum) {
2669 const u32 csum_size = fs_info->csum_size;
2671 repair_bbio->csum = repair_bbio->csum_inline;
2672 memcpy(repair_bbio->csum,
2673 failed_bbio->csum + csum_size * icsum, csum_size);
2676 bio_add_page(repair_bio, page, failrec->len, pgoff);
2677 repair_bbio->iter = repair_bio->bi_iter;
2679 btrfs_debug(btrfs_sb(inode->i_sb),
2680 "repair read error: submitting new read to mirror %d",
2681 failrec->this_mirror);
2684 * At this point we have a bio, so any errors from submit_bio_hook()
2685 * will be handled by the endio on the repair_bio, so we can't return an
2688 submit_bio_hook(inode, repair_bio, failrec->this_mirror, failrec->bio_flags);
2692 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2694 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2696 ASSERT(page_offset(page) <= start &&
2697 start + len <= page_offset(page) + PAGE_SIZE);
2700 if (fsverity_active(page->mapping->host) &&
2702 !PageUptodate(page) &&
2703 start < i_size_read(page->mapping->host) &&
2704 !fsverity_verify_page(page)) {
2705 btrfs_page_set_error(fs_info, page, start, len);
2707 btrfs_page_set_uptodate(fs_info, page, start, len);
2710 btrfs_page_clear_uptodate(fs_info, page, start, len);
2711 btrfs_page_set_error(fs_info, page, start, len);
2714 if (!btrfs_is_subpage(fs_info, page))
2717 btrfs_subpage_end_reader(fs_info, page, start, len);
2720 static blk_status_t submit_read_repair(struct inode *inode,
2721 struct bio *failed_bio, u32 bio_offset,
2722 struct page *page, unsigned int pgoff,
2723 u64 start, u64 end, int failed_mirror,
2724 unsigned int error_bitmap,
2725 submit_bio_hook_t *submit_bio_hook)
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 /* We're here because we had some read errors or csum mismatch */
2736 ASSERT(error_bitmap);
2739 * We only get called on buffered IO, thus page must be mapped and bio
2740 * must not be cloned.
2742 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2744 /* Iterate through all the sectors in the range */
2745 for (i = 0; i < nr_bits; i++) {
2746 const unsigned int offset = i * sectorsize;
2747 struct extent_state *cached = NULL;
2748 bool uptodate = false;
2751 if (!(error_bitmap & (1U << i))) {
2753 * This sector has no error, just end the page read
2754 * and unlock the range.
2760 ret = btrfs_repair_one_sector(inode, failed_bio,
2761 bio_offset + offset,
2762 page, pgoff + offset, start + offset,
2763 failed_mirror, submit_bio_hook);
2766 * We have submitted the read repair, the page release
2767 * will be handled by the endio function of the
2768 * submitted repair bio.
2769 * Thus we don't need to do any thing here.
2774 * Repair failed, just record the error but still continue.
2775 * Or the remaining sectors will not be properly unlocked.
2780 end_page_read(page, uptodate, start + offset, sectorsize);
2782 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2784 start + offset + sectorsize - 1,
2785 &cached, GFP_ATOMIC);
2786 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2788 start + offset + sectorsize - 1,
2791 return errno_to_blk_status(error);
2794 /* lots and lots of room for performance fixes in the end_bio funcs */
2796 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2798 struct btrfs_inode *inode;
2799 const bool uptodate = (err == 0);
2802 ASSERT(page && page->mapping);
2803 inode = BTRFS_I(page->mapping->host);
2804 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2807 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
2810 ASSERT(end + 1 - start <= U32_MAX);
2811 len = end + 1 - start;
2813 btrfs_page_clear_uptodate(fs_info, page, start, len);
2814 btrfs_page_set_error(fs_info, page, start, len);
2815 ret = err < 0 ? err : -EIO;
2816 mapping_set_error(page->mapping, ret);
2821 * after a writepage IO is done, we need to:
2822 * clear the uptodate bits on error
2823 * clear the writeback bits in the extent tree for this IO
2824 * end_page_writeback if the page has no more pending IO
2826 * Scheduling is not allowed, so the extent state tree is expected
2827 * to have one and only one object corresponding to this IO.
2829 static void end_bio_extent_writepage(struct bio *bio)
2831 int error = blk_status_to_errno(bio->bi_status);
2832 struct bio_vec *bvec;
2835 struct bvec_iter_all iter_all;
2836 bool first_bvec = true;
2838 ASSERT(!bio_flagged(bio, BIO_CLONED));
2839 bio_for_each_segment_all(bvec, bio, iter_all) {
2840 struct page *page = bvec->bv_page;
2841 struct inode *inode = page->mapping->host;
2842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2843 const u32 sectorsize = fs_info->sectorsize;
2845 /* Our read/write should always be sector aligned. */
2846 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2848 "partial page write in btrfs with offset %u and length %u",
2849 bvec->bv_offset, bvec->bv_len);
2850 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2852 "incomplete page write with offset %u and length %u",
2853 bvec->bv_offset, bvec->bv_len);
2855 start = page_offset(page) + bvec->bv_offset;
2856 end = start + bvec->bv_len - 1;
2859 btrfs_record_physical_zoned(inode, start, bio);
2863 end_extent_writepage(page, error, start, end);
2865 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2872 * Record previously processed extent range
2874 * For endio_readpage_release_extent() to handle a full extent range, reducing
2875 * the extent io operations.
2877 struct processed_extent {
2878 struct btrfs_inode *inode;
2879 /* Start of the range in @inode */
2881 /* End of the range in @inode */
2887 * Try to release processed extent range
2889 * May not release the extent range right now if the current range is
2890 * contiguous to processed extent.
2892 * Will release processed extent when any of @inode, @uptodate, the range is
2893 * no longer contiguous to the processed range.
2895 * Passing @inode == NULL will force processed extent to be released.
2897 static void endio_readpage_release_extent(struct processed_extent *processed,
2898 struct btrfs_inode *inode, u64 start, u64 end,
2901 struct extent_state *cached = NULL;
2902 struct extent_io_tree *tree;
2904 /* The first extent, initialize @processed */
2905 if (!processed->inode)
2909 * Contiguous to processed extent, just uptodate the end.
2911 * Several things to notice:
2913 * - bio can be merged as long as on-disk bytenr is contiguous
2914 * This means we can have page belonging to other inodes, thus need to
2915 * check if the inode still matches.
2916 * - bvec can contain range beyond current page for multi-page bvec
2917 * Thus we need to do processed->end + 1 >= start check
2919 if (processed->inode == inode && processed->uptodate == uptodate &&
2920 processed->end + 1 >= start && end >= processed->end) {
2921 processed->end = end;
2925 tree = &processed->inode->io_tree;
2927 * Now we don't have range contiguous to the processed range, release
2928 * the processed range now.
2930 if (processed->uptodate && tree->track_uptodate)
2931 set_extent_uptodate(tree, processed->start, processed->end,
2932 &cached, GFP_ATOMIC);
2933 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2937 /* Update processed to current range */
2938 processed->inode = inode;
2939 processed->start = start;
2940 processed->end = end;
2941 processed->uptodate = uptodate;
2944 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2946 ASSERT(PageLocked(page));
2947 if (!btrfs_is_subpage(fs_info, page))
2950 ASSERT(PagePrivate(page));
2951 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2955 * Find extent buffer for a givne bytenr.
2957 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2960 static struct extent_buffer *find_extent_buffer_readpage(
2961 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2963 struct extent_buffer *eb;
2966 * For regular sectorsize, we can use page->private to grab extent
2969 if (fs_info->nodesize >= PAGE_SIZE) {
2970 ASSERT(PagePrivate(page) && page->private);
2971 return (struct extent_buffer *)page->private;
2974 /* For subpage case, we need to lookup buffer radix tree */
2976 eb = radix_tree_lookup(&fs_info->buffer_radix,
2977 bytenr >> fs_info->sectorsize_bits);
2984 * after a readpage IO is done, we need to:
2985 * clear the uptodate bits on error
2986 * set the uptodate bits if things worked
2987 * set the page up to date if all extents in the tree are uptodate
2988 * clear the lock bit in the extent tree
2989 * unlock the page if there are no other extents locked for it
2991 * Scheduling is not allowed, so the extent state tree is expected
2992 * to have one and only one object corresponding to this IO.
2994 static void end_bio_extent_readpage(struct bio *bio)
2996 struct bio_vec *bvec;
2997 struct btrfs_bio *bbio = btrfs_bio(bio);
2998 struct extent_io_tree *tree, *failure_tree;
2999 struct processed_extent processed = { 0 };
3001 * The offset to the beginning of a bio, since one bio can never be
3002 * larger than UINT_MAX, u32 here is enough.
3007 struct bvec_iter_all iter_all;
3009 ASSERT(!bio_flagged(bio, BIO_CLONED));
3010 bio_for_each_segment_all(bvec, bio, iter_all) {
3011 bool uptodate = !bio->bi_status;
3012 struct page *page = bvec->bv_page;
3013 struct inode *inode = page->mapping->host;
3014 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3015 const u32 sectorsize = fs_info->sectorsize;
3016 unsigned int error_bitmap = (unsigned int)-1;
3021 btrfs_debug(fs_info,
3022 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3023 bio->bi_iter.bi_sector, bio->bi_status,
3025 tree = &BTRFS_I(inode)->io_tree;
3026 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3029 * We always issue full-sector reads, but if some block in a
3030 * page fails to read, blk_update_request() will advance
3031 * bv_offset and adjust bv_len to compensate. Print a warning
3032 * for unaligned offsets, and an error if they don't add up to
3035 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3037 "partial page read in btrfs with offset %u and length %u",
3038 bvec->bv_offset, bvec->bv_len);
3039 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3042 "incomplete page read with offset %u and length %u",
3043 bvec->bv_offset, bvec->bv_len);
3045 start = page_offset(page) + bvec->bv_offset;
3046 end = start + bvec->bv_len - 1;
3049 mirror = bbio->mirror_num;
3050 if (likely(uptodate)) {
3051 if (is_data_inode(inode)) {
3052 error_bitmap = btrfs_verify_data_csum(bbio,
3053 bio_offset, page, start, end);
3056 ret = btrfs_validate_metadata_buffer(bbio,
3057 page, start, end, mirror);
3062 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3063 failure_tree, tree, start,
3065 btrfs_ino(BTRFS_I(inode)), 0);
3068 if (likely(uptodate))
3071 if (is_data_inode(inode)) {
3073 * If we failed to submit the IO at all we'll have a
3074 * mirror_num == 0, in which case we need to just mark
3075 * the page with an error and unlock it and carry on.
3081 * btrfs_submit_read_repair() will handle all the good
3082 * and bad sectors, we just continue to the next bvec.
3084 submit_read_repair(inode, bio, bio_offset, page,
3085 start - page_offset(page), start,
3086 end, mirror, error_bitmap,
3087 btrfs_submit_data_bio);
3089 ASSERT(bio_offset + len > bio_offset);
3093 struct extent_buffer *eb;
3095 eb = find_extent_buffer_readpage(fs_info, page, start);
3096 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3097 eb->read_mirror = mirror;
3098 atomic_dec(&eb->io_pages);
3101 if (likely(uptodate)) {
3102 loff_t i_size = i_size_read(inode);
3103 pgoff_t end_index = i_size >> PAGE_SHIFT;
3106 * Zero out the remaining part if this range straddles
3109 * Here we should only zero the range inside the bvec,
3110 * not touch anything else.
3112 * NOTE: i_size is exclusive while end is inclusive.
3114 if (page->index == end_index && i_size <= end) {
3115 u32 zero_start = max(offset_in_page(i_size),
3116 offset_in_page(start));
3118 zero_user_segment(page, zero_start,
3119 offset_in_page(end) + 1);
3122 ASSERT(bio_offset + len > bio_offset);
3125 /* Update page status and unlock */
3126 end_page_read(page, uptodate, start, len);
3127 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3128 start, end, PageUptodate(page));
3130 /* Release the last extent */
3131 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3132 btrfs_bio_free_csum(bbio);
3137 * Initialize the members up to but not including 'bio'. Use after allocating a
3138 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3139 * 'bio' because use of __GFP_ZERO is not supported.
3141 static inline void btrfs_bio_init(struct btrfs_bio *bbio)
3143 memset(bbio, 0, offsetof(struct btrfs_bio, bio));
3147 * Allocate a btrfs_io_bio, with @nr_iovecs as maximum number of iovecs.
3149 * The bio allocation is backed by bioset and does not fail.
3151 struct bio *btrfs_bio_alloc(unsigned int nr_iovecs)
3155 ASSERT(0 < nr_iovecs && nr_iovecs <= BIO_MAX_VECS);
3156 bio = bio_alloc_bioset(NULL, nr_iovecs, 0, GFP_NOFS, &btrfs_bioset);
3157 btrfs_bio_init(btrfs_bio(bio));
3161 struct bio *btrfs_bio_clone(struct bio *bio)
3163 struct btrfs_bio *bbio;
3166 /* Bio allocation backed by a bioset does not fail */
3167 new = bio_alloc_clone(bio->bi_bdev, bio, GFP_NOFS, &btrfs_bioset);
3168 bbio = btrfs_bio(new);
3169 btrfs_bio_init(bbio);
3170 bbio->iter = bio->bi_iter;
3174 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
3177 struct btrfs_bio *bbio;
3179 ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
3181 /* this will never fail when it's backed by a bioset */
3182 bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
3185 bbio = btrfs_bio(bio);
3186 btrfs_bio_init(bbio);
3188 bio_trim(bio, offset >> 9, size >> 9);
3189 bbio->iter = bio->bi_iter;
3194 * Attempt to add a page to bio
3196 * @bio_ctrl: record both the bio, and its bio_flags
3197 * @page: page to add to the bio
3198 * @disk_bytenr: offset of the new bio or to check whether we are adding
3199 * a contiguous page to the previous one
3200 * @size: portion of page that we want to write
3201 * @pg_offset: starting offset in the page
3202 * @bio_flags: flags of the current bio to see if we can merge them
3204 * Attempt to add a page to bio considering stripe alignment etc.
3206 * Return >= 0 for the number of bytes added to the bio.
3207 * Can return 0 if the current bio is already at stripe/zone boundary.
3208 * Return <0 for error.
3210 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3212 u64 disk_bytenr, unsigned int size,
3213 unsigned int pg_offset,
3214 unsigned long bio_flags)
3216 struct bio *bio = bio_ctrl->bio;
3217 u32 bio_size = bio->bi_iter.bi_size;
3219 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3224 /* The limit should be calculated when bio_ctrl->bio is allocated */
3225 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3226 if (bio_ctrl->bio_flags != bio_flags)
3229 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED)
3230 contig = bio->bi_iter.bi_sector == sector;
3232 contig = bio_end_sector(bio) == sector;
3236 real_size = min(bio_ctrl->len_to_oe_boundary,
3237 bio_ctrl->len_to_stripe_boundary) - bio_size;
3238 real_size = min(real_size, size);
3241 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
3242 * bio will still execute its endio function on the page!
3247 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3248 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
3250 ret = bio_add_page(bio, page, real_size, pg_offset);
3255 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3256 struct btrfs_inode *inode, u64 file_offset)
3258 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3259 struct btrfs_io_geometry geom;
3260 struct btrfs_ordered_extent *ordered;
3261 struct extent_map *em;
3262 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3266 * Pages for compressed extent are never submitted to disk directly,
3267 * thus it has no real boundary, just set them to U32_MAX.
3269 * The split happens for real compressed bio, which happens in
3270 * btrfs_submit_compressed_read/write().
3272 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED) {
3273 bio_ctrl->len_to_oe_boundary = U32_MAX;
3274 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3277 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3280 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3282 free_extent_map(em);
3286 if (geom.len > U32_MAX)
3287 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3289 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3291 if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3292 bio_ctrl->len_to_oe_boundary = U32_MAX;
3296 /* Ordered extent not yet created, so we're good */
3297 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
3299 bio_ctrl->len_to_oe_boundary = U32_MAX;
3303 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3304 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3305 btrfs_put_ordered_extent(ordered);
3309 static int alloc_new_bio(struct btrfs_inode *inode,
3310 struct btrfs_bio_ctrl *bio_ctrl,
3311 struct writeback_control *wbc,
3313 bio_end_io_t end_io_func,
3314 u64 disk_bytenr, u32 offset, u64 file_offset,
3315 unsigned long bio_flags)
3317 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3321 bio = btrfs_bio_alloc(BIO_MAX_VECS);
3323 * For compressed page range, its disk_bytenr is always @disk_bytenr
3324 * passed in, no matter if we have added any range into previous bio.
3326 if (bio_flags & EXTENT_BIO_COMPRESSED)
3327 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
3329 bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
3330 bio_ctrl->bio = bio;
3331 bio_ctrl->bio_flags = bio_flags;
3332 bio->bi_end_io = end_io_func;
3333 bio->bi_private = &inode->io_tree;
3335 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
3341 * For Zone append we need the correct block_device that we are
3342 * going to write to set in the bio to be able to respect the
3343 * hardware limitation. Look it up here:
3345 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3346 struct btrfs_device *dev;
3348 dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
3349 fs_info->sectorsize);
3355 bio_set_dev(bio, dev->bdev);
3358 * Otherwise pick the last added device to support
3359 * cgroup writeback. For multi-device file systems this
3360 * means blk-cgroup policies have to always be set on the
3361 * last added/replaced device. This is a bit odd but has
3362 * been like that for a long time.
3364 bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
3366 wbc_init_bio(wbc, bio);
3368 ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
3372 bio_ctrl->bio = NULL;
3373 bio->bi_status = errno_to_blk_status(ret);
3379 * @opf: bio REQ_OP_* and REQ_* flags as one value
3380 * @wbc: optional writeback control for io accounting
3381 * @page: page to add to the bio
3382 * @disk_bytenr: logical bytenr where the write will be
3383 * @size: portion of page that we want to write to
3384 * @pg_offset: offset of the new bio or to check whether we are adding
3385 * a contiguous page to the previous one
3386 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3387 * @end_io_func: end_io callback for new bio
3388 * @mirror_num: desired mirror to read/write
3389 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3390 * @bio_flags: flags of the current bio to see if we can merge them
3392 static int submit_extent_page(unsigned int opf,
3393 struct writeback_control *wbc,
3394 struct btrfs_bio_ctrl *bio_ctrl,
3395 struct page *page, u64 disk_bytenr,
3396 size_t size, unsigned long pg_offset,
3397 bio_end_io_t end_io_func,
3399 unsigned long bio_flags,
3400 bool force_bio_submit)
3403 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3404 unsigned int cur = pg_offset;
3408 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3409 pg_offset + size <= PAGE_SIZE);
3410 if (force_bio_submit && bio_ctrl->bio) {
3411 ret = submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->bio_flags);
3412 bio_ctrl->bio = NULL;
3417 while (cur < pg_offset + size) {
3418 u32 offset = cur - pg_offset;
3421 /* Allocate new bio if needed */
3422 if (!bio_ctrl->bio) {
3423 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
3424 end_io_func, disk_bytenr, offset,
3425 page_offset(page) + cur,
3431 * We must go through btrfs_bio_add_page() to ensure each
3432 * page range won't cross various boundaries.
3434 if (bio_flags & EXTENT_BIO_COMPRESSED)
3435 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
3436 size - offset, pg_offset + offset,
3439 added = btrfs_bio_add_page(bio_ctrl, page,
3440 disk_bytenr + offset, size - offset,
3441 pg_offset + offset, bio_flags);
3443 /* Metadata page range should never be split */
3444 if (!is_data_inode(&inode->vfs_inode))
3445 ASSERT(added == 0 || added == size - offset);
3447 /* At least we added some page, update the account */
3449 wbc_account_cgroup_owner(wbc, page, added);
3451 /* We have reached boundary, submit right now */
3452 if (added < size - offset) {
3453 /* The bio should contain some page(s) */
3454 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
3455 ret = submit_one_bio(bio_ctrl->bio, mirror_num,
3456 bio_ctrl->bio_flags);
3457 bio_ctrl->bio = NULL;
3466 static int attach_extent_buffer_page(struct extent_buffer *eb,
3468 struct btrfs_subpage *prealloc)
3470 struct btrfs_fs_info *fs_info = eb->fs_info;
3474 * If the page is mapped to btree inode, we should hold the private
3475 * lock to prevent race.
3476 * For cloned or dummy extent buffers, their pages are not mapped and
3477 * will not race with any other ebs.
3480 lockdep_assert_held(&page->mapping->private_lock);
3482 if (fs_info->nodesize >= PAGE_SIZE) {
3483 if (!PagePrivate(page))
3484 attach_page_private(page, eb);
3486 WARN_ON(page->private != (unsigned long)eb);
3490 /* Already mapped, just free prealloc */
3491 if (PagePrivate(page)) {
3492 btrfs_free_subpage(prealloc);
3497 /* Has preallocated memory for subpage */
3498 attach_page_private(page, prealloc);
3500 /* Do new allocation to attach subpage */
3501 ret = btrfs_attach_subpage(fs_info, page,
3502 BTRFS_SUBPAGE_METADATA);
3506 int set_page_extent_mapped(struct page *page)
3508 struct btrfs_fs_info *fs_info;
3510 ASSERT(page->mapping);
3512 if (PagePrivate(page))
3515 fs_info = btrfs_sb(page->mapping->host->i_sb);
3517 if (btrfs_is_subpage(fs_info, page))
3518 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3520 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3524 void clear_page_extent_mapped(struct page *page)
3526 struct btrfs_fs_info *fs_info;
3528 ASSERT(page->mapping);
3530 if (!PagePrivate(page))
3533 fs_info = btrfs_sb(page->mapping->host->i_sb);
3534 if (btrfs_is_subpage(fs_info, page))
3535 return btrfs_detach_subpage(fs_info, page);
3537 detach_page_private(page);
3540 static struct extent_map *
3541 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3542 u64 start, u64 len, struct extent_map **em_cached)
3544 struct extent_map *em;
3546 if (em_cached && *em_cached) {
3548 if (extent_map_in_tree(em) && start >= em->start &&
3549 start < extent_map_end(em)) {
3550 refcount_inc(&em->refs);
3554 free_extent_map(em);
3558 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3559 if (em_cached && !IS_ERR(em)) {
3561 refcount_inc(&em->refs);
3567 * basic readpage implementation. Locked extent state structs are inserted
3568 * into the tree that are removed when the IO is done (by the end_io
3570 * XXX JDM: This needs looking at to ensure proper page locking
3571 * return 0 on success, otherwise return error
3573 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3574 struct btrfs_bio_ctrl *bio_ctrl,
3575 unsigned int read_flags, u64 *prev_em_start)
3577 struct inode *inode = page->mapping->host;
3578 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3579 u64 start = page_offset(page);
3580 const u64 end = start + PAGE_SIZE - 1;
3583 u64 last_byte = i_size_read(inode);
3586 struct extent_map *em;
3588 size_t pg_offset = 0;
3590 size_t blocksize = inode->i_sb->s_blocksize;
3591 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3593 ret = set_page_extent_mapped(page);
3595 unlock_extent(tree, start, end);
3596 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3601 if (page->index == last_byte >> PAGE_SHIFT) {
3602 size_t zero_offset = offset_in_page(last_byte);
3605 iosize = PAGE_SIZE - zero_offset;
3606 memzero_page(page, zero_offset, iosize);
3607 flush_dcache_page(page);
3610 begin_page_read(fs_info, page);
3611 while (cur <= end) {
3612 unsigned long this_bio_flag = 0;
3613 bool force_bio_submit = false;
3616 ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
3617 if (cur >= last_byte) {
3618 struct extent_state *cached = NULL;
3620 iosize = PAGE_SIZE - pg_offset;
3621 memzero_page(page, pg_offset, iosize);
3622 flush_dcache_page(page);
3623 set_extent_uptodate(tree, cur, cur + iosize - 1,
3625 unlock_extent_cached(tree, cur,
3626 cur + iosize - 1, &cached);
3627 end_page_read(page, true, cur, iosize);
3630 em = __get_extent_map(inode, page, pg_offset, cur,
3631 end - cur + 1, em_cached);
3633 unlock_extent(tree, cur, end);
3634 end_page_read(page, false, cur, end + 1 - cur);
3638 extent_offset = cur - em->start;
3639 BUG_ON(extent_map_end(em) <= cur);
3642 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3643 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3644 extent_set_compress_type(&this_bio_flag,
3648 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3649 cur_end = min(extent_map_end(em) - 1, end);
3650 iosize = ALIGN(iosize, blocksize);
3651 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3652 disk_bytenr = em->block_start;
3654 disk_bytenr = em->block_start + extent_offset;
3655 block_start = em->block_start;
3656 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3657 block_start = EXTENT_MAP_HOLE;
3660 * If we have a file range that points to a compressed extent
3661 * and it's followed by a consecutive file range that points
3662 * to the same compressed extent (possibly with a different
3663 * offset and/or length, so it either points to the whole extent
3664 * or only part of it), we must make sure we do not submit a
3665 * single bio to populate the pages for the 2 ranges because
3666 * this makes the compressed extent read zero out the pages
3667 * belonging to the 2nd range. Imagine the following scenario:
3670 * [0 - 8K] [8K - 24K]
3673 * points to extent X, points to extent X,
3674 * offset 4K, length of 8K offset 0, length 16K
3676 * [extent X, compressed length = 4K uncompressed length = 16K]
3678 * If the bio to read the compressed extent covers both ranges,
3679 * it will decompress extent X into the pages belonging to the
3680 * first range and then it will stop, zeroing out the remaining
3681 * pages that belong to the other range that points to extent X.
3682 * So here we make sure we submit 2 bios, one for the first
3683 * range and another one for the third range. Both will target
3684 * the same physical extent from disk, but we can't currently
3685 * make the compressed bio endio callback populate the pages
3686 * for both ranges because each compressed bio is tightly
3687 * coupled with a single extent map, and each range can have
3688 * an extent map with a different offset value relative to the
3689 * uncompressed data of our extent and different lengths. This
3690 * is a corner case so we prioritize correctness over
3691 * non-optimal behavior (submitting 2 bios for the same extent).
3693 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3694 prev_em_start && *prev_em_start != (u64)-1 &&
3695 *prev_em_start != em->start)
3696 force_bio_submit = true;
3699 *prev_em_start = em->start;
3701 free_extent_map(em);
3704 /* we've found a hole, just zero and go on */
3705 if (block_start == EXTENT_MAP_HOLE) {
3706 struct extent_state *cached = NULL;
3708 memzero_page(page, pg_offset, iosize);
3709 flush_dcache_page(page);
3711 set_extent_uptodate(tree, cur, cur + iosize - 1,
3713 unlock_extent_cached(tree, cur,
3714 cur + iosize - 1, &cached);
3715 end_page_read(page, true, cur, iosize);
3717 pg_offset += iosize;
3720 /* the get_extent function already copied into the page */
3721 if (test_range_bit(tree, cur, cur_end,
3722 EXTENT_UPTODATE, 1, NULL)) {
3723 unlock_extent(tree, cur, cur + iosize - 1);
3724 end_page_read(page, true, cur, iosize);
3726 pg_offset += iosize;
3729 /* we have an inline extent but it didn't get marked up
3730 * to date. Error out
3732 if (block_start == EXTENT_MAP_INLINE) {
3733 unlock_extent(tree, cur, cur + iosize - 1);
3734 end_page_read(page, false, cur, iosize);
3736 pg_offset += iosize;
3740 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3741 bio_ctrl, page, disk_bytenr, iosize,
3743 end_bio_extent_readpage, 0,
3747 unlock_extent(tree, cur, cur + iosize - 1);
3748 end_page_read(page, false, cur, iosize);
3752 pg_offset += iosize;
3758 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3760 struct extent_map **em_cached,
3761 struct btrfs_bio_ctrl *bio_ctrl,
3764 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3767 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3769 for (index = 0; index < nr_pages; index++) {
3770 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3771 REQ_RAHEAD, prev_em_start);
3772 put_page(pages[index]);
3776 static void update_nr_written(struct writeback_control *wbc,
3777 unsigned long nr_written)
3779 wbc->nr_to_write -= nr_written;
3783 * helper for __extent_writepage, doing all of the delayed allocation setup.
3785 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3786 * to write the page (copy into inline extent). In this case the IO has
3787 * been started and the page is already unlocked.
3789 * This returns 0 if all went well (page still locked)
3790 * This returns < 0 if there were errors (page still locked)
3792 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3793 struct page *page, struct writeback_control *wbc)
3795 const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
3796 u64 delalloc_start = page_offset(page);
3797 u64 delalloc_to_write = 0;
3798 /* How many pages are started by btrfs_run_delalloc_range() */
3799 unsigned long nr_written = 0;
3801 int page_started = 0;
3803 while (delalloc_start < page_end) {
3804 u64 delalloc_end = page_end;
3807 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3811 delalloc_start = delalloc_end + 1;
3814 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3815 delalloc_end, &page_started, &nr_written, wbc);
3817 btrfs_page_set_error(inode->root->fs_info, page,
3818 page_offset(page), PAGE_SIZE);
3822 * delalloc_end is already one less than the total length, so
3823 * we don't subtract one from PAGE_SIZE
3825 delalloc_to_write += (delalloc_end - delalloc_start +
3826 PAGE_SIZE) >> PAGE_SHIFT;
3827 delalloc_start = delalloc_end + 1;
3829 if (wbc->nr_to_write < delalloc_to_write) {
3832 if (delalloc_to_write < thresh * 2)
3833 thresh = delalloc_to_write;
3834 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3838 /* Did btrfs_run_dealloc_range() already unlock and start the IO? */
3841 * We've unlocked the page, so we can't update the mapping's
3842 * writeback index, just update nr_to_write.
3844 wbc->nr_to_write -= nr_written;
3852 * Find the first byte we need to write.
3854 * For subpage, one page can contain several sectors, and
3855 * __extent_writepage_io() will just grab all extent maps in the page
3856 * range and try to submit all non-inline/non-compressed extents.
3858 * This is a big problem for subpage, we shouldn't re-submit already written
3860 * This function will lookup subpage dirty bit to find which range we really
3863 * Return the next dirty range in [@start, @end).
3864 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
3866 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
3867 struct page *page, u64 *start, u64 *end)
3869 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
3870 struct btrfs_subpage_info *spi = fs_info->subpage_info;
3871 u64 orig_start = *start;
3872 /* Declare as unsigned long so we can use bitmap ops */
3873 unsigned long flags;
3874 int range_start_bit;
3878 * For regular sector size == page size case, since one page only
3879 * contains one sector, we return the page offset directly.
3881 if (!btrfs_is_subpage(fs_info, page)) {
3882 *start = page_offset(page);
3883 *end = page_offset(page) + PAGE_SIZE;
3887 range_start_bit = spi->dirty_offset +
3888 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
3890 /* We should have the page locked, but just in case */
3891 spin_lock_irqsave(&subpage->lock, flags);
3892 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
3893 spi->dirty_offset + spi->bitmap_nr_bits);
3894 spin_unlock_irqrestore(&subpage->lock, flags);
3896 range_start_bit -= spi->dirty_offset;
3897 range_end_bit -= spi->dirty_offset;
3899 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
3900 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
3904 * helper for __extent_writepage. This calls the writepage start hooks,
3905 * and does the loop to map the page into extents and bios.
3907 * We return 1 if the IO is started and the page is unlocked,
3908 * 0 if all went well (page still locked)
3909 * < 0 if there were errors (page still locked)
3911 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3913 struct writeback_control *wbc,
3914 struct extent_page_data *epd,
3918 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3919 u64 cur = page_offset(page);
3920 u64 end = cur + PAGE_SIZE - 1;
3923 struct extent_map *em;
3926 u32 opf = REQ_OP_WRITE;
3927 const unsigned int write_flags = wbc_to_write_flags(wbc);
3930 ret = btrfs_writepage_cow_fixup(page);
3932 /* Fixup worker will requeue */
3933 redirty_page_for_writepage(wbc, page);
3939 * we don't want to touch the inode after unlocking the page,
3940 * so we update the mapping writeback index now
3942 update_nr_written(wbc, 1);
3944 while (cur <= end) {
3947 u64 dirty_range_start = cur;
3948 u64 dirty_range_end;
3951 if (cur >= i_size) {
3952 btrfs_writepage_endio_finish_ordered(inode, page, cur,
3955 * This range is beyond i_size, thus we don't need to
3956 * bother writing back.
3957 * But we still need to clear the dirty subpage bit, or
3958 * the next time the page gets dirtied, we will try to
3959 * writeback the sectors with subpage dirty bits,
3960 * causing writeback without ordered extent.
3962 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
3966 find_next_dirty_byte(fs_info, page, &dirty_range_start,
3968 if (cur < dirty_range_start) {
3969 cur = dirty_range_start;
3973 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3975 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
3976 ret = PTR_ERR_OR_ZERO(em);
3980 extent_offset = cur - em->start;
3981 em_end = extent_map_end(em);
3982 ASSERT(cur <= em_end);
3984 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3985 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3986 block_start = em->block_start;
3987 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3988 disk_bytenr = em->block_start + extent_offset;
3991 * Note that em_end from extent_map_end() and dirty_range_end from
3992 * find_next_dirty_byte() are all exclusive
3994 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
3996 if (btrfs_use_zone_append(inode, em->block_start))
3997 opf = REQ_OP_ZONE_APPEND;
3999 free_extent_map(em);
4003 * compressed and inline extents are written through other
4006 if (compressed || block_start == EXTENT_MAP_HOLE ||
4007 block_start == EXTENT_MAP_INLINE) {
4011 btrfs_writepage_endio_finish_ordered(inode,
4012 page, cur, cur + iosize - 1, true);
4013 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4018 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
4019 if (!PageWriteback(page)) {
4020 btrfs_err(inode->root->fs_info,
4021 "page %lu not writeback, cur %llu end %llu",
4022 page->index, cur, end);
4026 * Although the PageDirty bit is cleared before entering this
4027 * function, subpage dirty bit is not cleared.
4028 * So clear subpage dirty bit here so next time we won't submit
4029 * page for range already written to disk.
4031 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4033 ret = submit_extent_page(opf | write_flags, wbc,
4034 &epd->bio_ctrl, page,
4035 disk_bytenr, iosize,
4036 cur - page_offset(page),
4037 end_bio_extent_writepage,
4040 btrfs_page_set_error(fs_info, page, cur, iosize);
4041 if (PageWriteback(page))
4042 btrfs_page_clear_writeback(fs_info, page, cur,
4050 * If we finish without problem, we should not only clear page dirty,
4051 * but also empty subpage dirty bits
4054 btrfs_page_assert_not_dirty(fs_info, page);
4060 * the writepage semantics are similar to regular writepage. extent
4061 * records are inserted to lock ranges in the tree, and as dirty areas
4062 * are found, they are marked writeback. Then the lock bits are removed
4063 * and the end_io handler clears the writeback ranges
4065 * Return 0 if everything goes well.
4066 * Return <0 for error.
4068 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
4069 struct extent_page_data *epd)
4071 struct folio *folio = page_folio(page);
4072 struct inode *inode = page->mapping->host;
4073 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4074 const u64 page_start = page_offset(page);
4075 const u64 page_end = page_start + PAGE_SIZE - 1;
4079 loff_t i_size = i_size_read(inode);
4080 unsigned long end_index = i_size >> PAGE_SHIFT;
4082 trace___extent_writepage(page, inode, wbc);
4084 WARN_ON(!PageLocked(page));
4086 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
4087 page_offset(page), PAGE_SIZE);
4089 pg_offset = offset_in_page(i_size);
4090 if (page->index > end_index ||
4091 (page->index == end_index && !pg_offset)) {
4092 folio_invalidate(folio, 0, folio_size(folio));
4093 folio_unlock(folio);
4097 if (page->index == end_index) {
4098 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
4099 flush_dcache_page(page);
4102 ret = set_page_extent_mapped(page);
4108 if (!epd->extent_locked) {
4109 ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
4116 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
4123 /* make sure the mapping tag for page dirty gets cleared */
4124 set_page_writeback(page);
4125 end_page_writeback(page);
4128 * Here we used to have a check for PageError() and then set @ret and
4129 * call end_extent_writepage().
4131 * But in fact setting @ret here will cause different error paths
4132 * between subpage and regular sectorsize.
4134 * For regular page size, we never submit current page, but only add
4135 * current page to current bio.
4136 * The bio submission can only happen in next page.
4137 * Thus if we hit the PageError() branch, @ret is already set to
4138 * non-zero value and will not get updated for regular sectorsize.
4140 * But for subpage case, it's possible we submit part of current page,
4141 * thus can get PageError() set by submitted bio of the same page,
4142 * while our @ret is still 0.
4144 * So here we unify the behavior and don't set @ret.
4145 * Error can still be properly passed to higher layer as page will
4146 * be set error, here we just don't handle the IO failure.
4148 * NOTE: This is just a hotfix for subpage.
4149 * The root fix will be properly ending ordered extent when we hit
4150 * an error during writeback.
4152 * But that needs a bigger refactoring, as we not only need to grab the
4153 * submitted OE, but also need to know exactly at which bytenr we hit
4155 * Currently the full page based __extent_writepage_io() is not
4158 if (PageError(page))
4159 end_extent_writepage(page, ret, page_start, page_end);
4160 if (epd->extent_locked) {
4162 * If epd->extent_locked, it's from extent_write_locked_range(),
4163 * the page can either be locked by lock_page() or
4164 * process_one_page().
4165 * Let btrfs_page_unlock_writer() handle both cases.
4168 btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
4169 wbc->range_end + 1 - wbc->range_start);
4177 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
4179 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
4180 TASK_UNINTERRUPTIBLE);
4183 static void end_extent_buffer_writeback(struct extent_buffer *eb)
4185 if (test_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags))
4186 btrfs_zone_finish_endio(eb->fs_info, eb->start, eb->len);
4188 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4189 smp_mb__after_atomic();
4190 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
4194 * Lock extent buffer status and pages for writeback.
4196 * May try to flush write bio if we can't get the lock.
4198 * Return 0 if the extent buffer doesn't need to be submitted.
4199 * (E.g. the extent buffer is not dirty)
4200 * Return >0 is the extent buffer is submitted to bio.
4201 * Return <0 if something went wrong, no page is locked.
4203 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4204 struct extent_page_data *epd)
4206 struct btrfs_fs_info *fs_info = eb->fs_info;
4207 int i, num_pages, failed_page_nr;
4211 if (!btrfs_try_tree_write_lock(eb)) {
4212 ret = flush_write_bio(epd);
4216 btrfs_tree_lock(eb);
4219 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4220 btrfs_tree_unlock(eb);
4224 ret = flush_write_bio(epd);
4230 wait_on_extent_buffer_writeback(eb);
4231 btrfs_tree_lock(eb);
4232 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4234 btrfs_tree_unlock(eb);
4239 * We need to do this to prevent races in people who check if the eb is
4240 * under IO since we can end up having no IO bits set for a short period
4243 spin_lock(&eb->refs_lock);
4244 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4245 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4246 spin_unlock(&eb->refs_lock);
4247 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4248 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4250 fs_info->dirty_metadata_batch);
4253 spin_unlock(&eb->refs_lock);
4256 btrfs_tree_unlock(eb);
4259 * Either we don't need to submit any tree block, or we're submitting
4261 * Subpage metadata doesn't use page locking at all, so we can skip
4264 if (!ret || fs_info->nodesize < PAGE_SIZE)
4267 num_pages = num_extent_pages(eb);
4268 for (i = 0; i < num_pages; i++) {
4269 struct page *p = eb->pages[i];
4271 if (!trylock_page(p)) {
4275 err = flush_write_bio(epd);
4289 /* Unlock already locked pages */
4290 for (i = 0; i < failed_page_nr; i++)
4291 unlock_page(eb->pages[i]);
4293 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
4294 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
4295 * be made and undo everything done before.
4297 btrfs_tree_lock(eb);
4298 spin_lock(&eb->refs_lock);
4299 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4300 end_extent_buffer_writeback(eb);
4301 spin_unlock(&eb->refs_lock);
4302 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4303 fs_info->dirty_metadata_batch);
4304 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4305 btrfs_tree_unlock(eb);
4309 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4311 struct btrfs_fs_info *fs_info = eb->fs_info;
4313 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4314 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4318 * A read may stumble upon this buffer later, make sure that it gets an
4319 * error and knows there was an error.
4321 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4324 * We need to set the mapping with the io error as well because a write
4325 * error will flip the file system readonly, and then syncfs() will
4326 * return a 0 because we are readonly if we don't modify the err seq for
4329 mapping_set_error(page->mapping, -EIO);
4332 * If we error out, we should add back the dirty_metadata_bytes
4333 * to make it consistent.
4335 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4336 eb->len, fs_info->dirty_metadata_batch);
4339 * If writeback for a btree extent that doesn't belong to a log tree
4340 * failed, increment the counter transaction->eb_write_errors.
4341 * We do this because while the transaction is running and before it's
4342 * committing (when we call filemap_fdata[write|wait]_range against
4343 * the btree inode), we might have
4344 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4345 * returns an error or an error happens during writeback, when we're
4346 * committing the transaction we wouldn't know about it, since the pages
4347 * can be no longer dirty nor marked anymore for writeback (if a
4348 * subsequent modification to the extent buffer didn't happen before the
4349 * transaction commit), which makes filemap_fdata[write|wait]_range not
4350 * able to find the pages tagged with SetPageError at transaction
4351 * commit time. So if this happens we must abort the transaction,
4352 * otherwise we commit a super block with btree roots that point to
4353 * btree nodes/leafs whose content on disk is invalid - either garbage
4354 * or the content of some node/leaf from a past generation that got
4355 * cowed or deleted and is no longer valid.
4357 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4358 * not be enough - we need to distinguish between log tree extents vs
4359 * non-log tree extents, and the next filemap_fdatawait_range() call
4360 * will catch and clear such errors in the mapping - and that call might
4361 * be from a log sync and not from a transaction commit. Also, checking
4362 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4363 * not done and would not be reliable - the eb might have been released
4364 * from memory and reading it back again means that flag would not be
4365 * set (since it's a runtime flag, not persisted on disk).
4367 * Using the flags below in the btree inode also makes us achieve the
4368 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4369 * writeback for all dirty pages and before filemap_fdatawait_range()
4370 * is called, the writeback for all dirty pages had already finished
4371 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4372 * filemap_fdatawait_range() would return success, as it could not know
4373 * that writeback errors happened (the pages were no longer tagged for
4376 switch (eb->log_index) {
4378 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4381 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4384 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4387 BUG(); /* unexpected, logic error */
4392 * The endio specific version which won't touch any unsafe spinlock in endio
4395 static struct extent_buffer *find_extent_buffer_nolock(
4396 struct btrfs_fs_info *fs_info, u64 start)
4398 struct extent_buffer *eb;
4401 eb = radix_tree_lookup(&fs_info->buffer_radix,
4402 start >> fs_info->sectorsize_bits);
4403 if (eb && atomic_inc_not_zero(&eb->refs)) {
4412 * The endio function for subpage extent buffer write.
4414 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4415 * after all extent buffers in the page has finished their writeback.
4417 static void end_bio_subpage_eb_writepage(struct bio *bio)
4419 struct btrfs_fs_info *fs_info;
4420 struct bio_vec *bvec;
4421 struct bvec_iter_all iter_all;
4423 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4424 ASSERT(fs_info->nodesize < PAGE_SIZE);
4426 ASSERT(!bio_flagged(bio, BIO_CLONED));
4427 bio_for_each_segment_all(bvec, bio, iter_all) {
4428 struct page *page = bvec->bv_page;
4429 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4430 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4431 u64 cur_bytenr = bvec_start;
4433 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4435 /* Iterate through all extent buffers in the range */
4436 while (cur_bytenr <= bvec_end) {
4437 struct extent_buffer *eb;
4441 * Here we can't use find_extent_buffer(), as it may
4442 * try to lock eb->refs_lock, which is not safe in endio
4445 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4448 cur_bytenr = eb->start + eb->len;
4450 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4451 done = atomic_dec_and_test(&eb->io_pages);
4454 if (bio->bi_status ||
4455 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4456 ClearPageUptodate(page);
4457 set_btree_ioerr(page, eb);
4460 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4462 end_extent_buffer_writeback(eb);
4464 * free_extent_buffer() will grab spinlock which is not
4465 * safe in endio context. Thus here we manually dec
4468 atomic_dec(&eb->refs);
4474 static void end_bio_extent_buffer_writepage(struct bio *bio)
4476 struct bio_vec *bvec;
4477 struct extent_buffer *eb;
4479 struct bvec_iter_all iter_all;
4481 ASSERT(!bio_flagged(bio, BIO_CLONED));
4482 bio_for_each_segment_all(bvec, bio, iter_all) {
4483 struct page *page = bvec->bv_page;
4485 eb = (struct extent_buffer *)page->private;
4487 done = atomic_dec_and_test(&eb->io_pages);
4489 if (bio->bi_status ||
4490 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4491 ClearPageUptodate(page);
4492 set_btree_ioerr(page, eb);
4495 end_page_writeback(page);
4500 end_extent_buffer_writeback(eb);
4506 static void prepare_eb_write(struct extent_buffer *eb)
4509 unsigned long start;
4512 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4513 atomic_set(&eb->io_pages, num_extent_pages(eb));
4515 /* Set btree blocks beyond nritems with 0 to avoid stale content */
4516 nritems = btrfs_header_nritems(eb);
4517 if (btrfs_header_level(eb) > 0) {
4518 end = btrfs_node_key_ptr_offset(nritems);
4519 memzero_extent_buffer(eb, end, eb->len - end);
4523 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4525 start = btrfs_item_nr_offset(nritems);
4526 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4527 memzero_extent_buffer(eb, start, end - start);
4532 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4533 * Page locking is only utilized at minimum to keep the VMM code happy.
4535 static int write_one_subpage_eb(struct extent_buffer *eb,
4536 struct writeback_control *wbc,
4537 struct extent_page_data *epd)
4539 struct btrfs_fs_info *fs_info = eb->fs_info;
4540 struct page *page = eb->pages[0];
4541 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4542 bool no_dirty_ebs = false;
4545 prepare_eb_write(eb);
4547 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4549 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4551 /* Check if this is the last dirty bit to update nr_written */
4552 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4553 eb->start, eb->len);
4555 clear_page_dirty_for_io(page);
4557 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4558 &epd->bio_ctrl, page, eb->start, eb->len,
4559 eb->start - page_offset(page),
4560 end_bio_subpage_eb_writepage, 0, 0, false);
4562 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4563 set_btree_ioerr(page, eb);
4566 if (atomic_dec_and_test(&eb->io_pages))
4567 end_extent_buffer_writeback(eb);
4572 * Submission finished without problem, if no range of the page is
4573 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4576 update_nr_written(wbc, 1);
4580 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4581 struct writeback_control *wbc,
4582 struct extent_page_data *epd)
4584 u64 disk_bytenr = eb->start;
4586 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4589 prepare_eb_write(eb);
4591 num_pages = num_extent_pages(eb);
4592 for (i = 0; i < num_pages; i++) {
4593 struct page *p = eb->pages[i];
4595 clear_page_dirty_for_io(p);
4596 set_page_writeback(p);
4597 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4598 &epd->bio_ctrl, p, disk_bytenr,
4600 end_bio_extent_buffer_writepage,
4603 set_btree_ioerr(p, eb);
4604 if (PageWriteback(p))
4605 end_page_writeback(p);
4606 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4607 end_extent_buffer_writeback(eb);
4611 disk_bytenr += PAGE_SIZE;
4612 update_nr_written(wbc, 1);
4616 if (unlikely(ret)) {
4617 for (; i < num_pages; i++) {
4618 struct page *p = eb->pages[i];
4619 clear_page_dirty_for_io(p);
4628 * Submit one subpage btree page.
4630 * The main difference to submit_eb_page() is:
4632 * For subpage, we don't rely on page locking at all.
4635 * We only flush bio if we may be unable to fit current extent buffers into
4638 * Return >=0 for the number of submitted extent buffers.
4639 * Return <0 for fatal error.
4641 static int submit_eb_subpage(struct page *page,
4642 struct writeback_control *wbc,
4643 struct extent_page_data *epd)
4645 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4647 u64 page_start = page_offset(page);
4649 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4652 /* Lock and write each dirty extent buffers in the range */
4653 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
4654 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4655 struct extent_buffer *eb;
4656 unsigned long flags;
4660 * Take private lock to ensure the subpage won't be detached
4663 spin_lock(&page->mapping->private_lock);
4664 if (!PagePrivate(page)) {
4665 spin_unlock(&page->mapping->private_lock);
4668 spin_lock_irqsave(&subpage->lock, flags);
4669 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
4670 subpage->bitmaps)) {
4671 spin_unlock_irqrestore(&subpage->lock, flags);
4672 spin_unlock(&page->mapping->private_lock);
4677 start = page_start + bit_start * fs_info->sectorsize;
4678 bit_start += sectors_per_node;
4681 * Here we just want to grab the eb without touching extra
4682 * spin locks, so call find_extent_buffer_nolock().
4684 eb = find_extent_buffer_nolock(fs_info, start);
4685 spin_unlock_irqrestore(&subpage->lock, flags);
4686 spin_unlock(&page->mapping->private_lock);
4689 * The eb has already reached 0 refs thus find_extent_buffer()
4690 * doesn't return it. We don't need to write back such eb
4696 ret = lock_extent_buffer_for_io(eb, epd);
4698 free_extent_buffer(eb);
4702 free_extent_buffer(eb);
4705 ret = write_one_subpage_eb(eb, wbc, epd);
4706 free_extent_buffer(eb);
4714 /* We hit error, end bio for the submitted extent buffers */
4715 end_write_bio(epd, ret);
4720 * Submit all page(s) of one extent buffer.
4722 * @page: the page of one extent buffer
4723 * @eb_context: to determine if we need to submit this page, if current page
4724 * belongs to this eb, we don't need to submit
4726 * The caller should pass each page in their bytenr order, and here we use
4727 * @eb_context to determine if we have submitted pages of one extent buffer.
4729 * If we have, we just skip until we hit a new page that doesn't belong to
4730 * current @eb_context.
4732 * If not, we submit all the page(s) of the extent buffer.
4734 * Return >0 if we have submitted the extent buffer successfully.
4735 * Return 0 if we don't need to submit the page, as it's already submitted by
4737 * Return <0 for fatal error.
4739 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4740 struct extent_page_data *epd,
4741 struct extent_buffer **eb_context)
4743 struct address_space *mapping = page->mapping;
4744 struct btrfs_block_group *cache = NULL;
4745 struct extent_buffer *eb;
4748 if (!PagePrivate(page))
4751 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
4752 return submit_eb_subpage(page, wbc, epd);
4754 spin_lock(&mapping->private_lock);
4755 if (!PagePrivate(page)) {
4756 spin_unlock(&mapping->private_lock);
4760 eb = (struct extent_buffer *)page->private;
4763 * Shouldn't happen and normally this would be a BUG_ON but no point
4764 * crashing the machine for something we can survive anyway.
4767 spin_unlock(&mapping->private_lock);
4771 if (eb == *eb_context) {
4772 spin_unlock(&mapping->private_lock);
4775 ret = atomic_inc_not_zero(&eb->refs);
4776 spin_unlock(&mapping->private_lock);
4780 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4782 * If for_sync, this hole will be filled with
4783 * trasnsaction commit.
4785 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4789 free_extent_buffer(eb);
4795 ret = lock_extent_buffer_for_io(eb, epd);
4797 btrfs_revert_meta_write_pointer(cache, eb);
4799 btrfs_put_block_group(cache);
4800 free_extent_buffer(eb);
4805 * Implies write in zoned mode. Mark the last eb in a block group.
4807 if (cache->seq_zone && eb->start + eb->len == cache->zone_capacity)
4808 set_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags);
4809 btrfs_put_block_group(cache);
4811 ret = write_one_eb(eb, wbc, epd);
4812 free_extent_buffer(eb);
4818 int btree_write_cache_pages(struct address_space *mapping,
4819 struct writeback_control *wbc)
4821 struct extent_buffer *eb_context = NULL;
4822 struct extent_page_data epd = {
4825 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4827 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4830 int nr_to_write_done = 0;
4831 struct pagevec pvec;
4834 pgoff_t end; /* Inclusive */
4838 pagevec_init(&pvec);
4839 if (wbc->range_cyclic) {
4840 index = mapping->writeback_index; /* Start from prev offset */
4843 * Start from the beginning does not need to cycle over the
4844 * range, mark it as scanned.
4846 scanned = (index == 0);
4848 index = wbc->range_start >> PAGE_SHIFT;
4849 end = wbc->range_end >> PAGE_SHIFT;
4852 if (wbc->sync_mode == WB_SYNC_ALL)
4853 tag = PAGECACHE_TAG_TOWRITE;
4855 tag = PAGECACHE_TAG_DIRTY;
4856 btrfs_zoned_meta_io_lock(fs_info);
4858 if (wbc->sync_mode == WB_SYNC_ALL)
4859 tag_pages_for_writeback(mapping, index, end);
4860 while (!done && !nr_to_write_done && (index <= end) &&
4861 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4865 for (i = 0; i < nr_pages; i++) {
4866 struct page *page = pvec.pages[i];
4868 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4877 * the filesystem may choose to bump up nr_to_write.
4878 * We have to make sure to honor the new nr_to_write
4881 nr_to_write_done = wbc->nr_to_write <= 0;
4883 pagevec_release(&pvec);
4886 if (!scanned && !done) {
4888 * We hit the last page and there is more work to be done: wrap
4889 * back to the start of the file
4896 end_write_bio(&epd, ret);
4900 * If something went wrong, don't allow any metadata write bio to be
4903 * This would prevent use-after-free if we had dirty pages not
4904 * cleaned up, which can still happen by fuzzed images.
4907 * Allowing existing tree block to be allocated for other trees.
4909 * - Log tree operations
4910 * Exiting tree blocks get allocated to log tree, bumps its
4911 * generation, then get cleaned in tree re-balance.
4912 * Such tree block will not be written back, since it's clean,
4913 * thus no WRITTEN flag set.
4914 * And after log writes back, this tree block is not traced by
4915 * any dirty extent_io_tree.
4917 * - Offending tree block gets re-dirtied from its original owner
4918 * Since it has bumped generation, no WRITTEN flag, it can be
4919 * reused without COWing. This tree block will not be traced
4920 * by btrfs_transaction::dirty_pages.
4922 * Now such dirty tree block will not be cleaned by any dirty
4923 * extent io tree. Thus we don't want to submit such wild eb
4924 * if the fs already has error.
4926 if (!BTRFS_FS_ERROR(fs_info)) {
4927 ret = flush_write_bio(&epd);
4930 end_write_bio(&epd, ret);
4933 btrfs_zoned_meta_io_unlock(fs_info);
4938 * Walk the list of dirty pages of the given address space and write all of them.
4940 * @mapping: address space structure to write
4941 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4942 * @epd: holds context for the write, namely the bio
4944 * If a page is already under I/O, write_cache_pages() skips it, even
4945 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4946 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4947 * and msync() need to guarantee that all the data which was dirty at the time
4948 * the call was made get new I/O started against them. If wbc->sync_mode is
4949 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4950 * existing IO to complete.
4952 static int extent_write_cache_pages(struct address_space *mapping,
4953 struct writeback_control *wbc,
4954 struct extent_page_data *epd)
4956 struct inode *inode = mapping->host;
4959 int nr_to_write_done = 0;
4960 struct pagevec pvec;
4963 pgoff_t end; /* Inclusive */
4965 int range_whole = 0;
4970 * We have to hold onto the inode so that ordered extents can do their
4971 * work when the IO finishes. The alternative to this is failing to add
4972 * an ordered extent if the igrab() fails there and that is a huge pain
4973 * to deal with, so instead just hold onto the inode throughout the
4974 * writepages operation. If it fails here we are freeing up the inode
4975 * anyway and we'd rather not waste our time writing out stuff that is
4976 * going to be truncated anyway.
4981 pagevec_init(&pvec);
4982 if (wbc->range_cyclic) {
4983 index = mapping->writeback_index; /* Start from prev offset */
4986 * Start from the beginning does not need to cycle over the
4987 * range, mark it as scanned.
4989 scanned = (index == 0);
4991 index = wbc->range_start >> PAGE_SHIFT;
4992 end = wbc->range_end >> PAGE_SHIFT;
4993 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4999 * We do the tagged writepage as long as the snapshot flush bit is set
5000 * and we are the first one who do the filemap_flush() on this inode.
5002 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
5003 * not race in and drop the bit.
5005 if (range_whole && wbc->nr_to_write == LONG_MAX &&
5006 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
5007 &BTRFS_I(inode)->runtime_flags))
5008 wbc->tagged_writepages = 1;
5010 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5011 tag = PAGECACHE_TAG_TOWRITE;
5013 tag = PAGECACHE_TAG_DIRTY;
5015 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5016 tag_pages_for_writeback(mapping, index, end);
5018 while (!done && !nr_to_write_done && (index <= end) &&
5019 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
5020 &index, end, tag))) {
5023 for (i = 0; i < nr_pages; i++) {
5024 struct page *page = pvec.pages[i];
5026 done_index = page->index + 1;
5028 * At this point we hold neither the i_pages lock nor
5029 * the page lock: the page may be truncated or
5030 * invalidated (changing page->mapping to NULL),
5031 * or even swizzled back from swapper_space to
5032 * tmpfs file mapping
5034 if (!trylock_page(page)) {
5035 ret = flush_write_bio(epd);
5040 if (unlikely(page->mapping != mapping)) {
5045 if (wbc->sync_mode != WB_SYNC_NONE) {
5046 if (PageWriteback(page)) {
5047 ret = flush_write_bio(epd);
5050 wait_on_page_writeback(page);
5053 if (PageWriteback(page) ||
5054 !clear_page_dirty_for_io(page)) {
5059 ret = __extent_writepage(page, wbc, epd);
5066 * the filesystem may choose to bump up nr_to_write.
5067 * We have to make sure to honor the new nr_to_write
5070 nr_to_write_done = wbc->nr_to_write <= 0;
5072 pagevec_release(&pvec);
5075 if (!scanned && !done) {
5077 * We hit the last page and there is more work to be done: wrap
5078 * back to the start of the file
5084 * If we're looping we could run into a page that is locked by a
5085 * writer and that writer could be waiting on writeback for a
5086 * page in our current bio, and thus deadlock, so flush the
5089 ret = flush_write_bio(epd);
5094 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
5095 mapping->writeback_index = done_index;
5097 btrfs_add_delayed_iput(inode);
5101 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
5104 struct extent_page_data epd = {
5107 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5110 ret = __extent_writepage(page, wbc, &epd);
5113 end_write_bio(&epd, ret);
5117 ret = flush_write_bio(&epd);
5123 * Submit the pages in the range to bio for call sites which delalloc range has
5124 * already been ran (aka, ordered extent inserted) and all pages are still
5127 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
5129 bool found_error = false;
5130 int first_error = 0;
5132 struct address_space *mapping = inode->i_mapping;
5135 unsigned long nr_pages;
5136 const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
5137 struct extent_page_data epd = {
5142 struct writeback_control wbc_writepages = {
5143 .sync_mode = WB_SYNC_ALL,
5144 .range_start = start,
5145 .range_end = end + 1,
5146 /* We're called from an async helper function */
5147 .punt_to_cgroup = 1,
5148 .no_cgroup_owner = 1,
5151 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
5152 nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
5154 wbc_writepages.nr_to_write = nr_pages * 2;
5156 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
5157 while (cur <= end) {
5158 u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
5160 page = find_get_page(mapping, cur >> PAGE_SHIFT);
5162 * All pages in the range are locked since
5163 * btrfs_run_delalloc_range(), thus there is no way to clear
5164 * the page dirty flag.
5166 ASSERT(PageLocked(page));
5167 ASSERT(PageDirty(page));
5168 clear_page_dirty_for_io(page);
5169 ret = __extent_writepage(page, &wbc_writepages, &epd);
5180 ret = flush_write_bio(&epd);
5182 end_write_bio(&epd, ret);
5184 wbc_detach_inode(&wbc_writepages);
5190 int extent_writepages(struct address_space *mapping,
5191 struct writeback_control *wbc)
5193 struct inode *inode = mapping->host;
5195 struct extent_page_data epd = {
5198 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5202 * Allow only a single thread to do the reloc work in zoned mode to
5203 * protect the write pointer updates.
5205 btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
5206 ret = extent_write_cache_pages(mapping, wbc, &epd);
5207 btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5210 end_write_bio(&epd, ret);
5213 ret = flush_write_bio(&epd);
5217 void extent_readahead(struct readahead_control *rac)
5219 struct btrfs_bio_ctrl bio_ctrl = { 0 };
5220 struct page *pagepool[16];
5221 struct extent_map *em_cached = NULL;
5222 u64 prev_em_start = (u64)-1;
5225 while ((nr = readahead_page_batch(rac, pagepool))) {
5226 u64 contig_start = readahead_pos(rac);
5227 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
5229 contiguous_readpages(pagepool, nr, contig_start, contig_end,
5230 &em_cached, &bio_ctrl, &prev_em_start);
5234 free_extent_map(em_cached);
5237 if (submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags))
5243 * basic invalidate_folio code, this waits on any locked or writeback
5244 * ranges corresponding to the folio, and then deletes any extent state
5245 * records from the tree
5247 int extent_invalidate_folio(struct extent_io_tree *tree,
5248 struct folio *folio, size_t offset)
5250 struct extent_state *cached_state = NULL;
5251 u64 start = folio_pos(folio);
5252 u64 end = start + folio_size(folio) - 1;
5253 size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
5255 /* This function is only called for the btree inode */
5256 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5258 start += ALIGN(offset, blocksize);
5262 lock_extent_bits(tree, start, end, &cached_state);
5263 folio_wait_writeback(folio);
5266 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5267 * so here we only need to unlock the extent range to free any
5268 * existing extent state.
5270 unlock_extent_cached(tree, start, end, &cached_state);
5275 * a helper for releasepage, this tests for areas of the page that
5276 * are locked or under IO and drops the related state bits if it is safe
5279 static int try_release_extent_state(struct extent_io_tree *tree,
5280 struct page *page, gfp_t mask)
5282 u64 start = page_offset(page);
5283 u64 end = start + PAGE_SIZE - 1;
5286 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5290 * At this point we can safely clear everything except the
5291 * locked bit, the nodatasum bit and the delalloc new bit.
5292 * The delalloc new bit will be cleared by ordered extent
5295 ret = __clear_extent_bit(tree, start, end,
5296 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5297 0, 0, NULL, mask, NULL);
5299 /* if clear_extent_bit failed for enomem reasons,
5300 * we can't allow the release to continue.
5311 * a helper for releasepage. As long as there are no locked extents
5312 * in the range corresponding to the page, both state records and extent
5313 * map records are removed
5315 int try_release_extent_mapping(struct page *page, gfp_t mask)
5317 struct extent_map *em;
5318 u64 start = page_offset(page);
5319 u64 end = start + PAGE_SIZE - 1;
5320 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5321 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5322 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5324 if (gfpflags_allow_blocking(mask) &&
5325 page->mapping->host->i_size > SZ_16M) {
5327 while (start <= end) {
5328 struct btrfs_fs_info *fs_info;
5331 len = end - start + 1;
5332 write_lock(&map->lock);
5333 em = lookup_extent_mapping(map, start, len);
5335 write_unlock(&map->lock);
5338 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5339 em->start != start) {
5340 write_unlock(&map->lock);
5341 free_extent_map(em);
5344 if (test_range_bit(tree, em->start,
5345 extent_map_end(em) - 1,
5346 EXTENT_LOCKED, 0, NULL))
5349 * If it's not in the list of modified extents, used
5350 * by a fast fsync, we can remove it. If it's being
5351 * logged we can safely remove it since fsync took an
5352 * extra reference on the em.
5354 if (list_empty(&em->list) ||
5355 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5358 * If it's in the list of modified extents, remove it
5359 * only if its generation is older then the current one,
5360 * in which case we don't need it for a fast fsync.
5361 * Otherwise don't remove it, we could be racing with an
5362 * ongoing fast fsync that could miss the new extent.
5364 fs_info = btrfs_inode->root->fs_info;
5365 spin_lock(&fs_info->trans_lock);
5366 cur_gen = fs_info->generation;
5367 spin_unlock(&fs_info->trans_lock);
5368 if (em->generation >= cur_gen)
5372 * We only remove extent maps that are not in the list of
5373 * modified extents or that are in the list but with a
5374 * generation lower then the current generation, so there
5375 * is no need to set the full fsync flag on the inode (it
5376 * hurts the fsync performance for workloads with a data
5377 * size that exceeds or is close to the system's memory).
5379 remove_extent_mapping(map, em);
5380 /* once for the rb tree */
5381 free_extent_map(em);
5383 start = extent_map_end(em);
5384 write_unlock(&map->lock);
5387 free_extent_map(em);
5389 cond_resched(); /* Allow large-extent preemption. */
5392 return try_release_extent_state(tree, page, mask);
5396 * helper function for fiemap, which doesn't want to see any holes.
5397 * This maps until we find something past 'last'
5399 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5400 u64 offset, u64 last)
5402 u64 sectorsize = btrfs_inode_sectorsize(inode);
5403 struct extent_map *em;
5410 len = last - offset;
5413 len = ALIGN(len, sectorsize);
5414 em = btrfs_get_extent_fiemap(inode, offset, len);
5418 /* if this isn't a hole return it */
5419 if (em->block_start != EXTENT_MAP_HOLE)
5422 /* this is a hole, advance to the next extent */
5423 offset = extent_map_end(em);
5424 free_extent_map(em);
5432 * To cache previous fiemap extent
5434 * Will be used for merging fiemap extent
5436 struct fiemap_cache {
5445 * Helper to submit fiemap extent.
5447 * Will try to merge current fiemap extent specified by @offset, @phys,
5448 * @len and @flags with cached one.
5449 * And only when we fails to merge, cached one will be submitted as
5452 * Return value is the same as fiemap_fill_next_extent().
5454 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5455 struct fiemap_cache *cache,
5456 u64 offset, u64 phys, u64 len, u32 flags)
5464 * Sanity check, extent_fiemap() should have ensured that new
5465 * fiemap extent won't overlap with cached one.
5468 * NOTE: Physical address can overlap, due to compression
5470 if (cache->offset + cache->len > offset) {
5476 * Only merges fiemap extents if
5477 * 1) Their logical addresses are continuous
5479 * 2) Their physical addresses are continuous
5480 * So truly compressed (physical size smaller than logical size)
5481 * extents won't get merged with each other
5483 * 3) Share same flags except FIEMAP_EXTENT_LAST
5484 * So regular extent won't get merged with prealloc extent
5486 if (cache->offset + cache->len == offset &&
5487 cache->phys + cache->len == phys &&
5488 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5489 (flags & ~FIEMAP_EXTENT_LAST)) {
5491 cache->flags |= flags;
5492 goto try_submit_last;
5495 /* Not mergeable, need to submit cached one */
5496 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5497 cache->len, cache->flags);
5498 cache->cached = false;
5502 cache->cached = true;
5503 cache->offset = offset;
5506 cache->flags = flags;
5508 if (cache->flags & FIEMAP_EXTENT_LAST) {
5509 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5510 cache->phys, cache->len, cache->flags);
5511 cache->cached = false;
5517 * Emit last fiemap cache
5519 * The last fiemap cache may still be cached in the following case:
5521 * |<- Fiemap range ->|
5522 * |<------------ First extent ----------->|
5524 * In this case, the first extent range will be cached but not emitted.
5525 * So we must emit it before ending extent_fiemap().
5527 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5528 struct fiemap_cache *cache)
5535 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5536 cache->len, cache->flags);
5537 cache->cached = false;
5543 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5548 u64 max = start + len;
5552 u64 last_for_get_extent = 0;
5554 u64 isize = i_size_read(&inode->vfs_inode);
5555 struct btrfs_key found_key;
5556 struct extent_map *em = NULL;
5557 struct extent_state *cached_state = NULL;
5558 struct btrfs_path *path;
5559 struct btrfs_root *root = inode->root;
5560 struct fiemap_cache cache = { 0 };
5561 struct ulist *roots;
5562 struct ulist *tmp_ulist;
5571 path = btrfs_alloc_path();
5575 roots = ulist_alloc(GFP_KERNEL);
5576 tmp_ulist = ulist_alloc(GFP_KERNEL);
5577 if (!roots || !tmp_ulist) {
5579 goto out_free_ulist;
5583 * We can't initialize that to 'start' as this could miss extents due
5584 * to extent item merging
5587 start = round_down(start, btrfs_inode_sectorsize(inode));
5588 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5591 * lookup the last file extent. We're not using i_size here
5592 * because there might be preallocation past i_size
5594 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5597 goto out_free_ulist;
5605 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5606 found_type = found_key.type;
5608 /* No extents, but there might be delalloc bits */
5609 if (found_key.objectid != btrfs_ino(inode) ||
5610 found_type != BTRFS_EXTENT_DATA_KEY) {
5611 /* have to trust i_size as the end */
5613 last_for_get_extent = isize;
5616 * remember the start of the last extent. There are a
5617 * bunch of different factors that go into the length of the
5618 * extent, so its much less complex to remember where it started
5620 last = found_key.offset;
5621 last_for_get_extent = last + 1;
5623 btrfs_release_path(path);
5626 * we might have some extents allocated but more delalloc past those
5627 * extents. so, we trust isize unless the start of the last extent is
5632 last_for_get_extent = isize;
5635 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5638 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5647 u64 offset_in_extent = 0;
5649 /* break if the extent we found is outside the range */
5650 if (em->start >= max || extent_map_end(em) < off)
5654 * get_extent may return an extent that starts before our
5655 * requested range. We have to make sure the ranges
5656 * we return to fiemap always move forward and don't
5657 * overlap, so adjust the offsets here
5659 em_start = max(em->start, off);
5662 * record the offset from the start of the extent
5663 * for adjusting the disk offset below. Only do this if the
5664 * extent isn't compressed since our in ram offset may be past
5665 * what we have actually allocated on disk.
5667 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5668 offset_in_extent = em_start - em->start;
5669 em_end = extent_map_end(em);
5670 em_len = em_end - em_start;
5672 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5673 disko = em->block_start + offset_in_extent;
5678 * bump off for our next call to get_extent
5680 off = extent_map_end(em);
5684 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5686 flags |= FIEMAP_EXTENT_LAST;
5687 } else if (em->block_start == EXTENT_MAP_INLINE) {
5688 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5689 FIEMAP_EXTENT_NOT_ALIGNED);
5690 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5691 flags |= (FIEMAP_EXTENT_DELALLOC |
5692 FIEMAP_EXTENT_UNKNOWN);
5693 } else if (fieinfo->fi_extents_max) {
5694 u64 bytenr = em->block_start -
5695 (em->start - em->orig_start);
5698 * As btrfs supports shared space, this information
5699 * can be exported to userspace tools via
5700 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5701 * then we're just getting a count and we can skip the
5704 ret = btrfs_check_shared(root, btrfs_ino(inode),
5705 bytenr, roots, tmp_ulist);
5709 flags |= FIEMAP_EXTENT_SHARED;
5712 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5713 flags |= FIEMAP_EXTENT_ENCODED;
5714 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5715 flags |= FIEMAP_EXTENT_UNWRITTEN;
5717 free_extent_map(em);
5719 if ((em_start >= last) || em_len == (u64)-1 ||
5720 (last == (u64)-1 && isize <= em_end)) {
5721 flags |= FIEMAP_EXTENT_LAST;
5725 /* now scan forward to see if this is really the last extent. */
5726 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5732 flags |= FIEMAP_EXTENT_LAST;
5735 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5745 ret = emit_last_fiemap_cache(fieinfo, &cache);
5746 free_extent_map(em);
5748 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5752 btrfs_free_path(path);
5754 ulist_free(tmp_ulist);
5758 static void __free_extent_buffer(struct extent_buffer *eb)
5760 kmem_cache_free(extent_buffer_cache, eb);
5763 int extent_buffer_under_io(const struct extent_buffer *eb)
5765 return (atomic_read(&eb->io_pages) ||
5766 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5767 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5770 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5772 struct btrfs_subpage *subpage;
5774 lockdep_assert_held(&page->mapping->private_lock);
5776 if (PagePrivate(page)) {
5777 subpage = (struct btrfs_subpage *)page->private;
5778 if (atomic_read(&subpage->eb_refs))
5781 * Even there is no eb refs here, we may still have
5782 * end_page_read() call relying on page::private.
5784 if (atomic_read(&subpage->readers))
5790 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5792 struct btrfs_fs_info *fs_info = eb->fs_info;
5793 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5796 * For mapped eb, we're going to change the page private, which should
5797 * be done under the private_lock.
5800 spin_lock(&page->mapping->private_lock);
5802 if (!PagePrivate(page)) {
5804 spin_unlock(&page->mapping->private_lock);
5808 if (fs_info->nodesize >= PAGE_SIZE) {
5810 * We do this since we'll remove the pages after we've
5811 * removed the eb from the radix tree, so we could race
5812 * and have this page now attached to the new eb. So
5813 * only clear page_private if it's still connected to
5816 if (PagePrivate(page) &&
5817 page->private == (unsigned long)eb) {
5818 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5819 BUG_ON(PageDirty(page));
5820 BUG_ON(PageWriteback(page));
5822 * We need to make sure we haven't be attached
5825 detach_page_private(page);
5828 spin_unlock(&page->mapping->private_lock);
5833 * For subpage, we can have dummy eb with page private. In this case,
5834 * we can directly detach the private as such page is only attached to
5835 * one dummy eb, no sharing.
5838 btrfs_detach_subpage(fs_info, page);
5842 btrfs_page_dec_eb_refs(fs_info, page);
5845 * We can only detach the page private if there are no other ebs in the
5846 * page range and no unfinished IO.
5848 if (!page_range_has_eb(fs_info, page))
5849 btrfs_detach_subpage(fs_info, page);
5851 spin_unlock(&page->mapping->private_lock);
5854 /* Release all pages attached to the extent buffer */
5855 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5860 ASSERT(!extent_buffer_under_io(eb));
5862 num_pages = num_extent_pages(eb);
5863 for (i = 0; i < num_pages; i++) {
5864 struct page *page = eb->pages[i];
5869 detach_extent_buffer_page(eb, page);
5871 /* One for when we allocated the page */
5877 * Helper for releasing the extent buffer.
5879 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5881 btrfs_release_extent_buffer_pages(eb);
5882 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5883 __free_extent_buffer(eb);
5886 static struct extent_buffer *
5887 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5890 struct extent_buffer *eb = NULL;
5892 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5895 eb->fs_info = fs_info;
5897 init_rwsem(&eb->lock);
5899 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5900 &fs_info->allocated_ebs);
5901 INIT_LIST_HEAD(&eb->release_list);
5903 spin_lock_init(&eb->refs_lock);
5904 atomic_set(&eb->refs, 1);
5905 atomic_set(&eb->io_pages, 0);
5907 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5912 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5916 struct extent_buffer *new;
5917 int num_pages = num_extent_pages(src);
5919 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5924 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5925 * btrfs_release_extent_buffer() have different behavior for
5926 * UNMAPPED subpage extent buffer.
5928 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5930 for (i = 0; i < num_pages; i++) {
5933 p = alloc_page(GFP_NOFS);
5935 btrfs_release_extent_buffer(new);
5938 ret = attach_extent_buffer_page(new, p, NULL);
5941 btrfs_release_extent_buffer(new);
5944 WARN_ON(PageDirty(p));
5946 copy_page(page_address(p), page_address(src->pages[i]));
5948 set_extent_buffer_uptodate(new);
5953 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5954 u64 start, unsigned long len)
5956 struct extent_buffer *eb;
5960 eb = __alloc_extent_buffer(fs_info, start, len);
5964 num_pages = num_extent_pages(eb);
5965 for (i = 0; i < num_pages; i++) {
5968 eb->pages[i] = alloc_page(GFP_NOFS);
5971 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5975 set_extent_buffer_uptodate(eb);
5976 btrfs_set_header_nritems(eb, 0);
5977 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5981 for (; i > 0; i--) {
5982 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5983 __free_page(eb->pages[i - 1]);
5985 __free_extent_buffer(eb);
5989 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5992 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5995 static void check_buffer_tree_ref(struct extent_buffer *eb)
5999 * The TREE_REF bit is first set when the extent_buffer is added
6000 * to the radix tree. It is also reset, if unset, when a new reference
6001 * is created by find_extent_buffer.
6003 * It is only cleared in two cases: freeing the last non-tree
6004 * reference to the extent_buffer when its STALE bit is set or
6005 * calling releasepage when the tree reference is the only reference.
6007 * In both cases, care is taken to ensure that the extent_buffer's
6008 * pages are not under io. However, releasepage can be concurrently
6009 * called with creating new references, which is prone to race
6010 * conditions between the calls to check_buffer_tree_ref in those
6011 * codepaths and clearing TREE_REF in try_release_extent_buffer.
6013 * The actual lifetime of the extent_buffer in the radix tree is
6014 * adequately protected by the refcount, but the TREE_REF bit and
6015 * its corresponding reference are not. To protect against this
6016 * class of races, we call check_buffer_tree_ref from the codepaths
6017 * which trigger io after they set eb->io_pages. Note that once io is
6018 * initiated, TREE_REF can no longer be cleared, so that is the
6019 * moment at which any such race is best fixed.
6021 refs = atomic_read(&eb->refs);
6022 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6025 spin_lock(&eb->refs_lock);
6026 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6027 atomic_inc(&eb->refs);
6028 spin_unlock(&eb->refs_lock);
6031 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
6032 struct page *accessed)
6036 check_buffer_tree_ref(eb);
6038 num_pages = num_extent_pages(eb);
6039 for (i = 0; i < num_pages; i++) {
6040 struct page *p = eb->pages[i];
6043 mark_page_accessed(p);
6047 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
6050 struct extent_buffer *eb;
6052 eb = find_extent_buffer_nolock(fs_info, start);
6056 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
6057 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
6058 * another task running free_extent_buffer() might have seen that flag
6059 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
6060 * writeback flags not set) and it's still in the tree (flag
6061 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
6062 * decrementing the extent buffer's reference count twice. So here we
6063 * could race and increment the eb's reference count, clear its stale
6064 * flag, mark it as dirty and drop our reference before the other task
6065 * finishes executing free_extent_buffer, which would later result in
6066 * an attempt to free an extent buffer that is dirty.
6068 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
6069 spin_lock(&eb->refs_lock);
6070 spin_unlock(&eb->refs_lock);
6072 mark_extent_buffer_accessed(eb, NULL);
6076 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6077 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
6080 struct extent_buffer *eb, *exists = NULL;
6083 eb = find_extent_buffer(fs_info, start);
6086 eb = alloc_dummy_extent_buffer(fs_info, start);
6088 return ERR_PTR(-ENOMEM);
6089 eb->fs_info = fs_info;
6091 ret = radix_tree_preload(GFP_NOFS);
6093 exists = ERR_PTR(ret);
6096 spin_lock(&fs_info->buffer_lock);
6097 ret = radix_tree_insert(&fs_info->buffer_radix,
6098 start >> fs_info->sectorsize_bits, eb);
6099 spin_unlock(&fs_info->buffer_lock);
6100 radix_tree_preload_end();
6101 if (ret == -EEXIST) {
6102 exists = find_extent_buffer(fs_info, start);
6108 check_buffer_tree_ref(eb);
6109 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6113 btrfs_release_extent_buffer(eb);
6118 static struct extent_buffer *grab_extent_buffer(
6119 struct btrfs_fs_info *fs_info, struct page *page)
6121 struct extent_buffer *exists;
6124 * For subpage case, we completely rely on radix tree to ensure we
6125 * don't try to insert two ebs for the same bytenr. So here we always
6126 * return NULL and just continue.
6128 if (fs_info->nodesize < PAGE_SIZE)
6131 /* Page not yet attached to an extent buffer */
6132 if (!PagePrivate(page))
6136 * We could have already allocated an eb for this page and attached one
6137 * so lets see if we can get a ref on the existing eb, and if we can we
6138 * know it's good and we can just return that one, else we know we can
6139 * just overwrite page->private.
6141 exists = (struct extent_buffer *)page->private;
6142 if (atomic_inc_not_zero(&exists->refs))
6145 WARN_ON(PageDirty(page));
6146 detach_page_private(page);
6150 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
6152 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
6153 btrfs_err(fs_info, "bad tree block start %llu", start);
6157 if (fs_info->nodesize < PAGE_SIZE &&
6158 offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
6160 "tree block crosses page boundary, start %llu nodesize %u",
6161 start, fs_info->nodesize);
6164 if (fs_info->nodesize >= PAGE_SIZE &&
6165 !IS_ALIGNED(start, PAGE_SIZE)) {
6167 "tree block is not page aligned, start %llu nodesize %u",
6168 start, fs_info->nodesize);
6174 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
6175 u64 start, u64 owner_root, int level)
6177 unsigned long len = fs_info->nodesize;
6180 unsigned long index = start >> PAGE_SHIFT;
6181 struct extent_buffer *eb;
6182 struct extent_buffer *exists = NULL;
6184 struct address_space *mapping = fs_info->btree_inode->i_mapping;
6188 if (check_eb_alignment(fs_info, start))
6189 return ERR_PTR(-EINVAL);
6191 #if BITS_PER_LONG == 32
6192 if (start >= MAX_LFS_FILESIZE) {
6193 btrfs_err_rl(fs_info,
6194 "extent buffer %llu is beyond 32bit page cache limit", start);
6195 btrfs_err_32bit_limit(fs_info);
6196 return ERR_PTR(-EOVERFLOW);
6198 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6199 btrfs_warn_32bit_limit(fs_info);
6202 eb = find_extent_buffer(fs_info, start);
6206 eb = __alloc_extent_buffer(fs_info, start, len);
6208 return ERR_PTR(-ENOMEM);
6209 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
6211 num_pages = num_extent_pages(eb);
6212 for (i = 0; i < num_pages; i++, index++) {
6213 struct btrfs_subpage *prealloc = NULL;
6215 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
6217 exists = ERR_PTR(-ENOMEM);
6222 * Preallocate page->private for subpage case, so that we won't
6223 * allocate memory with private_lock hold. The memory will be
6224 * freed by attach_extent_buffer_page() or freed manually if
6227 * Although we have ensured one subpage eb can only have one
6228 * page, but it may change in the future for 16K page size
6229 * support, so we still preallocate the memory in the loop.
6231 if (fs_info->nodesize < PAGE_SIZE) {
6232 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
6233 if (IS_ERR(prealloc)) {
6234 ret = PTR_ERR(prealloc);
6237 exists = ERR_PTR(ret);
6242 spin_lock(&mapping->private_lock);
6243 exists = grab_extent_buffer(fs_info, p);
6245 spin_unlock(&mapping->private_lock);
6248 mark_extent_buffer_accessed(exists, p);
6249 btrfs_free_subpage(prealloc);
6252 /* Should not fail, as we have preallocated the memory */
6253 ret = attach_extent_buffer_page(eb, p, prealloc);
6256 * To inform we have extra eb under allocation, so that
6257 * detach_extent_buffer_page() won't release the page private
6258 * when the eb hasn't yet been inserted into radix tree.
6260 * The ref will be decreased when the eb released the page, in
6261 * detach_extent_buffer_page().
6262 * Thus needs no special handling in error path.
6264 btrfs_page_inc_eb_refs(fs_info, p);
6265 spin_unlock(&mapping->private_lock);
6267 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6269 if (!PageUptodate(p))
6273 * We can't unlock the pages just yet since the extent buffer
6274 * hasn't been properly inserted in the radix tree, this
6275 * opens a race with btree_releasepage which can free a page
6276 * while we are still filling in all pages for the buffer and
6281 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6283 ret = radix_tree_preload(GFP_NOFS);
6285 exists = ERR_PTR(ret);
6289 spin_lock(&fs_info->buffer_lock);
6290 ret = radix_tree_insert(&fs_info->buffer_radix,
6291 start >> fs_info->sectorsize_bits, eb);
6292 spin_unlock(&fs_info->buffer_lock);
6293 radix_tree_preload_end();
6294 if (ret == -EEXIST) {
6295 exists = find_extent_buffer(fs_info, start);
6301 /* add one reference for the tree */
6302 check_buffer_tree_ref(eb);
6303 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6306 * Now it's safe to unlock the pages because any calls to
6307 * btree_releasepage will correctly detect that a page belongs to a
6308 * live buffer and won't free them prematurely.
6310 for (i = 0; i < num_pages; i++)
6311 unlock_page(eb->pages[i]);
6315 WARN_ON(!atomic_dec_and_test(&eb->refs));
6316 for (i = 0; i < num_pages; i++) {
6318 unlock_page(eb->pages[i]);
6321 btrfs_release_extent_buffer(eb);
6325 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6327 struct extent_buffer *eb =
6328 container_of(head, struct extent_buffer, rcu_head);
6330 __free_extent_buffer(eb);
6333 static int release_extent_buffer(struct extent_buffer *eb)
6334 __releases(&eb->refs_lock)
6336 lockdep_assert_held(&eb->refs_lock);
6338 WARN_ON(atomic_read(&eb->refs) == 0);
6339 if (atomic_dec_and_test(&eb->refs)) {
6340 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6341 struct btrfs_fs_info *fs_info = eb->fs_info;
6343 spin_unlock(&eb->refs_lock);
6345 spin_lock(&fs_info->buffer_lock);
6346 radix_tree_delete(&fs_info->buffer_radix,
6347 eb->start >> fs_info->sectorsize_bits);
6348 spin_unlock(&fs_info->buffer_lock);
6350 spin_unlock(&eb->refs_lock);
6353 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6354 /* Should be safe to release our pages at this point */
6355 btrfs_release_extent_buffer_pages(eb);
6356 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6357 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6358 __free_extent_buffer(eb);
6362 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6365 spin_unlock(&eb->refs_lock);
6370 void free_extent_buffer(struct extent_buffer *eb)
6378 refs = atomic_read(&eb->refs);
6379 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6380 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6383 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6388 spin_lock(&eb->refs_lock);
6389 if (atomic_read(&eb->refs) == 2 &&
6390 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6391 !extent_buffer_under_io(eb) &&
6392 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6393 atomic_dec(&eb->refs);
6396 * I know this is terrible, but it's temporary until we stop tracking
6397 * the uptodate bits and such for the extent buffers.
6399 release_extent_buffer(eb);
6402 void free_extent_buffer_stale(struct extent_buffer *eb)
6407 spin_lock(&eb->refs_lock);
6408 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6410 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6411 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6412 atomic_dec(&eb->refs);
6413 release_extent_buffer(eb);
6416 static void btree_clear_page_dirty(struct page *page)
6418 ASSERT(PageDirty(page));
6419 ASSERT(PageLocked(page));
6420 clear_page_dirty_for_io(page);
6421 xa_lock_irq(&page->mapping->i_pages);
6422 if (!PageDirty(page))
6423 __xa_clear_mark(&page->mapping->i_pages,
6424 page_index(page), PAGECACHE_TAG_DIRTY);
6425 xa_unlock_irq(&page->mapping->i_pages);
6428 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6430 struct btrfs_fs_info *fs_info = eb->fs_info;
6431 struct page *page = eb->pages[0];
6434 /* btree_clear_page_dirty() needs page locked */
6436 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6439 btree_clear_page_dirty(page);
6441 WARN_ON(atomic_read(&eb->refs) == 0);
6444 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6450 if (eb->fs_info->nodesize < PAGE_SIZE)
6451 return clear_subpage_extent_buffer_dirty(eb);
6453 num_pages = num_extent_pages(eb);
6455 for (i = 0; i < num_pages; i++) {
6456 page = eb->pages[i];
6457 if (!PageDirty(page))
6460 btree_clear_page_dirty(page);
6461 ClearPageError(page);
6464 WARN_ON(atomic_read(&eb->refs) == 0);
6467 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6473 check_buffer_tree_ref(eb);
6475 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6477 num_pages = num_extent_pages(eb);
6478 WARN_ON(atomic_read(&eb->refs) == 0);
6479 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6482 bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
6485 * For subpage case, we can have other extent buffers in the
6486 * same page, and in clear_subpage_extent_buffer_dirty() we
6487 * have to clear page dirty without subpage lock held.
6488 * This can cause race where our page gets dirty cleared after
6491 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6492 * its page for other reasons, we can use page lock to prevent
6496 lock_page(eb->pages[0]);
6497 for (i = 0; i < num_pages; i++)
6498 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6499 eb->start, eb->len);
6501 unlock_page(eb->pages[0]);
6503 #ifdef CONFIG_BTRFS_DEBUG
6504 for (i = 0; i < num_pages; i++)
6505 ASSERT(PageDirty(eb->pages[i]));
6511 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6513 struct btrfs_fs_info *fs_info = eb->fs_info;
6518 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6519 num_pages = num_extent_pages(eb);
6520 for (i = 0; i < num_pages; i++) {
6521 page = eb->pages[i];
6526 * This is special handling for metadata subpage, as regular
6527 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6529 if (fs_info->nodesize >= PAGE_SIZE)
6530 ClearPageUptodate(page);
6532 btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
6537 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6539 struct btrfs_fs_info *fs_info = eb->fs_info;
6544 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6545 num_pages = num_extent_pages(eb);
6546 for (i = 0; i < num_pages; i++) {
6547 page = eb->pages[i];
6550 * This is special handling for metadata subpage, as regular
6551 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6553 if (fs_info->nodesize >= PAGE_SIZE)
6554 SetPageUptodate(page);
6556 btrfs_subpage_set_uptodate(fs_info, page, eb->start,
6561 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6564 struct btrfs_fs_info *fs_info = eb->fs_info;
6565 struct extent_io_tree *io_tree;
6566 struct page *page = eb->pages[0];
6567 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6570 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6571 ASSERT(PagePrivate(page));
6572 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6574 if (wait == WAIT_NONE) {
6575 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6578 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6584 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6585 PageUptodate(page) ||
6586 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6587 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6588 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6592 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6593 eb->read_mirror = 0;
6594 atomic_set(&eb->io_pages, 1);
6595 check_buffer_tree_ref(eb);
6596 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6598 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
6599 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6600 page, eb->start, eb->len,
6601 eb->start - page_offset(page),
6602 end_bio_extent_readpage, mirror_num, 0,
6606 * In the endio function, if we hit something wrong we will
6607 * increase the io_pages, so here we need to decrease it for
6610 atomic_dec(&eb->io_pages);
6615 tmp = submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6616 bio_ctrl.bio = NULL;
6620 if (ret || wait != WAIT_COMPLETE)
6623 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6624 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6629 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6635 int locked_pages = 0;
6636 int all_uptodate = 1;
6638 unsigned long num_reads = 0;
6639 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6641 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6645 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
6646 * operation, which could potentially still be in flight. In this case
6647 * we simply want to return an error.
6649 if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
6652 if (eb->fs_info->nodesize < PAGE_SIZE)
6653 return read_extent_buffer_subpage(eb, wait, mirror_num);
6655 num_pages = num_extent_pages(eb);
6656 for (i = 0; i < num_pages; i++) {
6657 page = eb->pages[i];
6658 if (wait == WAIT_NONE) {
6660 * WAIT_NONE is only utilized by readahead. If we can't
6661 * acquire the lock atomically it means either the eb
6662 * is being read out or under modification.
6663 * Either way the eb will be or has been cached,
6664 * readahead can exit safely.
6666 if (!trylock_page(page))
6674 * We need to firstly lock all pages to make sure that
6675 * the uptodate bit of our pages won't be affected by
6676 * clear_extent_buffer_uptodate().
6678 for (i = 0; i < num_pages; i++) {
6679 page = eb->pages[i];
6680 if (!PageUptodate(page)) {
6687 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6691 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6692 eb->read_mirror = 0;
6693 atomic_set(&eb->io_pages, num_reads);
6695 * It is possible for releasepage to clear the TREE_REF bit before we
6696 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6698 check_buffer_tree_ref(eb);
6699 for (i = 0; i < num_pages; i++) {
6700 page = eb->pages[i];
6702 if (!PageUptodate(page)) {
6704 atomic_dec(&eb->io_pages);
6709 ClearPageError(page);
6710 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6711 &bio_ctrl, page, page_offset(page),
6712 PAGE_SIZE, 0, end_bio_extent_readpage,
6713 mirror_num, 0, false);
6716 * We failed to submit the bio so it's the
6717 * caller's responsibility to perform cleanup
6718 * i.e unlock page/set error bit.
6723 atomic_dec(&eb->io_pages);
6731 err = submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.bio_flags);
6732 bio_ctrl.bio = NULL;
6737 if (ret || wait != WAIT_COMPLETE)
6740 for (i = 0; i < num_pages; i++) {
6741 page = eb->pages[i];
6742 wait_on_page_locked(page);
6743 if (!PageUptodate(page))
6750 while (locked_pages > 0) {
6752 page = eb->pages[locked_pages];
6758 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6761 btrfs_warn(eb->fs_info,
6762 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6763 eb->start, eb->len, start, len);
6764 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6770 * Check if the [start, start + len) range is valid before reading/writing
6772 * NOTE: @start and @len are offset inside the eb, not logical address.
6774 * Caller should not touch the dst/src memory if this function returns error.
6776 static inline int check_eb_range(const struct extent_buffer *eb,
6777 unsigned long start, unsigned long len)
6779 unsigned long offset;
6781 /* start, start + len should not go beyond eb->len nor overflow */
6782 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6783 return report_eb_range(eb, start, len);
6788 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6789 unsigned long start, unsigned long len)
6795 char *dst = (char *)dstv;
6796 unsigned long i = get_eb_page_index(start);
6798 if (check_eb_range(eb, start, len))
6801 offset = get_eb_offset_in_page(eb, start);
6804 page = eb->pages[i];
6806 cur = min(len, (PAGE_SIZE - offset));
6807 kaddr = page_address(page);
6808 memcpy(dst, kaddr + offset, cur);
6817 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6819 unsigned long start, unsigned long len)
6825 char __user *dst = (char __user *)dstv;
6826 unsigned long i = get_eb_page_index(start);
6829 WARN_ON(start > eb->len);
6830 WARN_ON(start + len > eb->start + eb->len);
6832 offset = get_eb_offset_in_page(eb, start);
6835 page = eb->pages[i];
6837 cur = min(len, (PAGE_SIZE - offset));
6838 kaddr = page_address(page);
6839 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6853 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6854 unsigned long start, unsigned long len)
6860 char *ptr = (char *)ptrv;
6861 unsigned long i = get_eb_page_index(start);
6864 if (check_eb_range(eb, start, len))
6867 offset = get_eb_offset_in_page(eb, start);
6870 page = eb->pages[i];
6872 cur = min(len, (PAGE_SIZE - offset));
6874 kaddr = page_address(page);
6875 ret = memcmp(ptr, kaddr + offset, cur);
6888 * Check that the extent buffer is uptodate.
6890 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6891 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6893 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6896 struct btrfs_fs_info *fs_info = eb->fs_info;
6899 * If we are using the commit root we could potentially clear a page
6900 * Uptodate while we're using the extent buffer that we've previously
6901 * looked up. We don't want to complain in this case, as the page was
6902 * valid before, we just didn't write it out. Instead we want to catch
6903 * the case where we didn't actually read the block properly, which
6904 * would have !PageUptodate && !PageError, as we clear PageError before
6907 if (fs_info->nodesize < PAGE_SIZE) {
6908 bool uptodate, error;
6910 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6911 eb->start, eb->len);
6912 error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
6913 WARN_ON(!uptodate && !error);
6915 WARN_ON(!PageUptodate(page) && !PageError(page));
6919 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6924 assert_eb_page_uptodate(eb, eb->pages[0]);
6925 kaddr = page_address(eb->pages[0]) +
6926 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6928 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6931 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6935 assert_eb_page_uptodate(eb, eb->pages[0]);
6936 kaddr = page_address(eb->pages[0]) +
6937 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6938 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6941 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6942 unsigned long start, unsigned long len)
6948 char *src = (char *)srcv;
6949 unsigned long i = get_eb_page_index(start);
6951 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6953 if (check_eb_range(eb, start, len))
6956 offset = get_eb_offset_in_page(eb, start);
6959 page = eb->pages[i];
6960 assert_eb_page_uptodate(eb, page);
6962 cur = min(len, PAGE_SIZE - offset);
6963 kaddr = page_address(page);
6964 memcpy(kaddr + offset, src, cur);
6973 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6980 unsigned long i = get_eb_page_index(start);
6982 if (check_eb_range(eb, start, len))
6985 offset = get_eb_offset_in_page(eb, start);
6988 page = eb->pages[i];
6989 assert_eb_page_uptodate(eb, page);
6991 cur = min(len, PAGE_SIZE - offset);
6992 kaddr = page_address(page);
6993 memset(kaddr + offset, 0, cur);
7001 void copy_extent_buffer_full(const struct extent_buffer *dst,
7002 const struct extent_buffer *src)
7007 ASSERT(dst->len == src->len);
7009 if (dst->fs_info->nodesize >= PAGE_SIZE) {
7010 num_pages = num_extent_pages(dst);
7011 for (i = 0; i < num_pages; i++)
7012 copy_page(page_address(dst->pages[i]),
7013 page_address(src->pages[i]));
7015 size_t src_offset = get_eb_offset_in_page(src, 0);
7016 size_t dst_offset = get_eb_offset_in_page(dst, 0);
7018 ASSERT(src->fs_info->nodesize < PAGE_SIZE);
7019 memcpy(page_address(dst->pages[0]) + dst_offset,
7020 page_address(src->pages[0]) + src_offset,
7025 void copy_extent_buffer(const struct extent_buffer *dst,
7026 const struct extent_buffer *src,
7027 unsigned long dst_offset, unsigned long src_offset,
7030 u64 dst_len = dst->len;
7035 unsigned long i = get_eb_page_index(dst_offset);
7037 if (check_eb_range(dst, dst_offset, len) ||
7038 check_eb_range(src, src_offset, len))
7041 WARN_ON(src->len != dst_len);
7043 offset = get_eb_offset_in_page(dst, dst_offset);
7046 page = dst->pages[i];
7047 assert_eb_page_uptodate(dst, page);
7049 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
7051 kaddr = page_address(page);
7052 read_extent_buffer(src, kaddr + offset, src_offset, cur);
7062 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
7064 * @eb: the extent buffer
7065 * @start: offset of the bitmap item in the extent buffer
7067 * @page_index: return index of the page in the extent buffer that contains the
7069 * @page_offset: return offset into the page given by page_index
7071 * This helper hides the ugliness of finding the byte in an extent buffer which
7072 * contains a given bit.
7074 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
7075 unsigned long start, unsigned long nr,
7076 unsigned long *page_index,
7077 size_t *page_offset)
7079 size_t byte_offset = BIT_BYTE(nr);
7083 * The byte we want is the offset of the extent buffer + the offset of
7084 * the bitmap item in the extent buffer + the offset of the byte in the
7087 offset = start + offset_in_page(eb->start) + byte_offset;
7089 *page_index = offset >> PAGE_SHIFT;
7090 *page_offset = offset_in_page(offset);
7094 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
7095 * @eb: the extent buffer
7096 * @start: offset of the bitmap item in the extent buffer
7097 * @nr: bit number to test
7099 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
7107 eb_bitmap_offset(eb, start, nr, &i, &offset);
7108 page = eb->pages[i];
7109 assert_eb_page_uptodate(eb, page);
7110 kaddr = page_address(page);
7111 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
7115 * extent_buffer_bitmap_set - set an area of a bitmap
7116 * @eb: the extent buffer
7117 * @start: offset of the bitmap item in the extent buffer
7118 * @pos: bit number of the first bit
7119 * @len: number of bits to set
7121 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
7122 unsigned long pos, unsigned long len)
7128 const unsigned int size = pos + len;
7129 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7130 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
7132 eb_bitmap_offset(eb, start, pos, &i, &offset);
7133 page = eb->pages[i];
7134 assert_eb_page_uptodate(eb, page);
7135 kaddr = page_address(page);
7137 while (len >= bits_to_set) {
7138 kaddr[offset] |= mask_to_set;
7140 bits_to_set = BITS_PER_BYTE;
7142 if (++offset >= PAGE_SIZE && len > 0) {
7144 page = eb->pages[++i];
7145 assert_eb_page_uptodate(eb, page);
7146 kaddr = page_address(page);
7150 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
7151 kaddr[offset] |= mask_to_set;
7157 * extent_buffer_bitmap_clear - clear an area of a bitmap
7158 * @eb: the extent buffer
7159 * @start: offset of the bitmap item in the extent buffer
7160 * @pos: bit number of the first bit
7161 * @len: number of bits to clear
7163 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
7164 unsigned long start, unsigned long pos,
7171 const unsigned int size = pos + len;
7172 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7173 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
7175 eb_bitmap_offset(eb, start, pos, &i, &offset);
7176 page = eb->pages[i];
7177 assert_eb_page_uptodate(eb, page);
7178 kaddr = page_address(page);
7180 while (len >= bits_to_clear) {
7181 kaddr[offset] &= ~mask_to_clear;
7182 len -= bits_to_clear;
7183 bits_to_clear = BITS_PER_BYTE;
7185 if (++offset >= PAGE_SIZE && len > 0) {
7187 page = eb->pages[++i];
7188 assert_eb_page_uptodate(eb, page);
7189 kaddr = page_address(page);
7193 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
7194 kaddr[offset] &= ~mask_to_clear;
7198 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
7200 unsigned long distance = (src > dst) ? src - dst : dst - src;
7201 return distance < len;
7204 static void copy_pages(struct page *dst_page, struct page *src_page,
7205 unsigned long dst_off, unsigned long src_off,
7208 char *dst_kaddr = page_address(dst_page);
7210 int must_memmove = 0;
7212 if (dst_page != src_page) {
7213 src_kaddr = page_address(src_page);
7215 src_kaddr = dst_kaddr;
7216 if (areas_overlap(src_off, dst_off, len))
7221 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
7223 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
7226 void memcpy_extent_buffer(const struct extent_buffer *dst,
7227 unsigned long dst_offset, unsigned long src_offset,
7231 size_t dst_off_in_page;
7232 size_t src_off_in_page;
7233 unsigned long dst_i;
7234 unsigned long src_i;
7236 if (check_eb_range(dst, dst_offset, len) ||
7237 check_eb_range(dst, src_offset, len))
7241 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
7242 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
7244 dst_i = get_eb_page_index(dst_offset);
7245 src_i = get_eb_page_index(src_offset);
7247 cur = min(len, (unsigned long)(PAGE_SIZE -
7249 cur = min_t(unsigned long, cur,
7250 (unsigned long)(PAGE_SIZE - dst_off_in_page));
7252 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7253 dst_off_in_page, src_off_in_page, cur);
7261 void memmove_extent_buffer(const struct extent_buffer *dst,
7262 unsigned long dst_offset, unsigned long src_offset,
7266 size_t dst_off_in_page;
7267 size_t src_off_in_page;
7268 unsigned long dst_end = dst_offset + len - 1;
7269 unsigned long src_end = src_offset + len - 1;
7270 unsigned long dst_i;
7271 unsigned long src_i;
7273 if (check_eb_range(dst, dst_offset, len) ||
7274 check_eb_range(dst, src_offset, len))
7276 if (dst_offset < src_offset) {
7277 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
7281 dst_i = get_eb_page_index(dst_end);
7282 src_i = get_eb_page_index(src_end);
7284 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
7285 src_off_in_page = get_eb_offset_in_page(dst, src_end);
7287 cur = min_t(unsigned long, len, src_off_in_page + 1);
7288 cur = min(cur, dst_off_in_page + 1);
7289 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7290 dst_off_in_page - cur + 1,
7291 src_off_in_page - cur + 1, cur);
7299 #define GANG_LOOKUP_SIZE 16
7300 static struct extent_buffer *get_next_extent_buffer(
7301 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
7303 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
7304 struct extent_buffer *found = NULL;
7305 u64 page_start = page_offset(page);
7306 u64 cur = page_start;
7308 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7309 lockdep_assert_held(&fs_info->buffer_lock);
7311 while (cur < page_start + PAGE_SIZE) {
7315 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
7316 (void **)gang, cur >> fs_info->sectorsize_bits,
7317 min_t(unsigned int, GANG_LOOKUP_SIZE,
7318 PAGE_SIZE / fs_info->nodesize));
7321 for (i = 0; i < ret; i++) {
7322 /* Already beyond page end */
7323 if (gang[i]->start >= page_start + PAGE_SIZE)
7326 if (gang[i]->start >= bytenr) {
7331 cur = gang[ret - 1]->start + gang[ret - 1]->len;
7337 static int try_release_subpage_extent_buffer(struct page *page)
7339 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7340 u64 cur = page_offset(page);
7341 const u64 end = page_offset(page) + PAGE_SIZE;
7345 struct extent_buffer *eb = NULL;
7348 * Unlike try_release_extent_buffer() which uses page->private
7349 * to grab buffer, for subpage case we rely on radix tree, thus
7350 * we need to ensure radix tree consistency.
7352 * We also want an atomic snapshot of the radix tree, thus go
7353 * with spinlock rather than RCU.
7355 spin_lock(&fs_info->buffer_lock);
7356 eb = get_next_extent_buffer(fs_info, page, cur);
7358 /* No more eb in the page range after or at cur */
7359 spin_unlock(&fs_info->buffer_lock);
7362 cur = eb->start + eb->len;
7365 * The same as try_release_extent_buffer(), to ensure the eb
7366 * won't disappear out from under us.
7368 spin_lock(&eb->refs_lock);
7369 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7370 spin_unlock(&eb->refs_lock);
7371 spin_unlock(&fs_info->buffer_lock);
7374 spin_unlock(&fs_info->buffer_lock);
7377 * If tree ref isn't set then we know the ref on this eb is a
7378 * real ref, so just return, this eb will likely be freed soon
7381 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7382 spin_unlock(&eb->refs_lock);
7387 * Here we don't care about the return value, we will always
7388 * check the page private at the end. And
7389 * release_extent_buffer() will release the refs_lock.
7391 release_extent_buffer(eb);
7394 * Finally to check if we have cleared page private, as if we have
7395 * released all ebs in the page, the page private should be cleared now.
7397 spin_lock(&page->mapping->private_lock);
7398 if (!PagePrivate(page))
7402 spin_unlock(&page->mapping->private_lock);
7407 int try_release_extent_buffer(struct page *page)
7409 struct extent_buffer *eb;
7411 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
7412 return try_release_subpage_extent_buffer(page);
7415 * We need to make sure nobody is changing page->private, as we rely on
7416 * page->private as the pointer to extent buffer.
7418 spin_lock(&page->mapping->private_lock);
7419 if (!PagePrivate(page)) {
7420 spin_unlock(&page->mapping->private_lock);
7424 eb = (struct extent_buffer *)page->private;
7428 * This is a little awful but should be ok, we need to make sure that
7429 * the eb doesn't disappear out from under us while we're looking at
7432 spin_lock(&eb->refs_lock);
7433 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7434 spin_unlock(&eb->refs_lock);
7435 spin_unlock(&page->mapping->private_lock);
7438 spin_unlock(&page->mapping->private_lock);
7441 * If tree ref isn't set then we know the ref on this eb is a real ref,
7442 * so just return, this page will likely be freed soon anyway.
7444 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7445 spin_unlock(&eb->refs_lock);
7449 return release_extent_buffer(eb);
7453 * btrfs_readahead_tree_block - attempt to readahead a child block
7454 * @fs_info: the fs_info
7455 * @bytenr: bytenr to read
7456 * @owner_root: objectid of the root that owns this eb
7457 * @gen: generation for the uptodate check, can be 0
7458 * @level: level for the eb
7460 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7461 * normal uptodate check of the eb, without checking the generation. If we have
7462 * to read the block we will not block on anything.
7464 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7465 u64 bytenr, u64 owner_root, u64 gen, int level)
7467 struct extent_buffer *eb;
7470 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7474 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7475 free_extent_buffer(eb);
7479 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7481 free_extent_buffer_stale(eb);
7483 free_extent_buffer(eb);
7487 * btrfs_readahead_node_child - readahead a node's child block
7488 * @node: parent node we're reading from
7489 * @slot: slot in the parent node for the child we want to read
7491 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7492 * the slot in the node provided.
7494 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7496 btrfs_readahead_tree_block(node->fs_info,
7497 btrfs_node_blockptr(node, slot),
7498 btrfs_header_owner(node),
7499 btrfs_node_ptr_generation(node, slot),
7500 btrfs_header_level(node) - 1);