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/cleancache.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 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
79 while (!list_empty(&fs_info->allocated_ebs)) {
80 eb = list_first_entry(&fs_info->allocated_ebs,
81 struct extent_buffer, leak_list);
83 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
84 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
85 btrfs_header_owner(eb));
86 list_del(&eb->leak_list);
87 kmem_cache_free(extent_buffer_cache, eb);
89 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
92 static inline void btrfs_extent_state_leak_debug_check(void)
94 struct extent_state *state;
96 while (!list_empty(&states)) {
97 state = list_entry(states.next, struct extent_state, leak_list);
98 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
99 state->start, state->end, state->state,
100 extent_state_in_tree(state),
101 refcount_read(&state->refs));
102 list_del(&state->leak_list);
103 kmem_cache_free(extent_state_cache, state);
107 #define btrfs_debug_check_extent_io_range(tree, start, end) \
108 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
109 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
110 struct extent_io_tree *tree, u64 start, u64 end)
112 struct inode *inode = tree->private_data;
115 if (!inode || !is_data_inode(inode))
118 isize = i_size_read(inode);
119 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
120 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
121 "%s: ino %llu isize %llu odd range [%llu,%llu]",
122 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
126 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
127 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
128 #define btrfs_extent_state_leak_debug_check() do {} while (0)
129 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
135 struct rb_node rb_node;
138 struct extent_page_data {
140 /* tells writepage not to lock the state bits for this range
141 * it still does the unlocking
143 unsigned int extent_locked:1;
145 /* tells the submit_bio code to use REQ_SYNC */
146 unsigned int sync_io:1;
149 static int add_extent_changeset(struct extent_state *state, u32 bits,
150 struct extent_changeset *changeset,
157 if (set && (state->state & bits) == bits)
159 if (!set && (state->state & bits) == 0)
161 changeset->bytes_changed += state->end - state->start + 1;
162 ret = ulist_add(&changeset->range_changed, state->start, state->end,
167 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
168 unsigned long bio_flags)
170 blk_status_t ret = 0;
171 struct extent_io_tree *tree = bio->bi_private;
173 bio->bi_private = NULL;
175 if (is_data_inode(tree->private_data))
176 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
179 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
180 mirror_num, bio_flags);
182 return blk_status_to_errno(ret);
185 /* Cleanup unsubmitted bios */
186 static void end_write_bio(struct extent_page_data *epd, int ret)
189 epd->bio->bi_status = errno_to_blk_status(ret);
196 * Submit bio from extent page data via submit_one_bio
198 * Return 0 if everything is OK.
199 * Return <0 for error.
201 static int __must_check flush_write_bio(struct extent_page_data *epd)
206 ret = submit_one_bio(epd->bio, 0, 0);
208 * Clean up of epd->bio is handled by its endio function.
209 * And endio is either triggered by successful bio execution
210 * or the error handler of submit bio hook.
211 * So at this point, no matter what happened, we don't need
212 * to clean up epd->bio.
219 int __init extent_state_cache_init(void)
221 extent_state_cache = kmem_cache_create("btrfs_extent_state",
222 sizeof(struct extent_state), 0,
223 SLAB_MEM_SPREAD, NULL);
224 if (!extent_state_cache)
229 int __init extent_io_init(void)
231 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
232 sizeof(struct extent_buffer), 0,
233 SLAB_MEM_SPREAD, NULL);
234 if (!extent_buffer_cache)
237 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
238 offsetof(struct btrfs_io_bio, bio),
240 goto free_buffer_cache;
242 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
248 bioset_exit(&btrfs_bioset);
251 kmem_cache_destroy(extent_buffer_cache);
252 extent_buffer_cache = NULL;
256 void __cold extent_state_cache_exit(void)
258 btrfs_extent_state_leak_debug_check();
259 kmem_cache_destroy(extent_state_cache);
262 void __cold extent_io_exit(void)
265 * Make sure all delayed rcu free are flushed before we
269 kmem_cache_destroy(extent_buffer_cache);
270 bioset_exit(&btrfs_bioset);
274 * For the file_extent_tree, we want to hold the inode lock when we lookup and
275 * update the disk_i_size, but lockdep will complain because our io_tree we hold
276 * the tree lock and get the inode lock when setting delalloc. These two things
277 * are unrelated, so make a class for the file_extent_tree so we don't get the
278 * two locking patterns mixed up.
280 static struct lock_class_key file_extent_tree_class;
282 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
283 struct extent_io_tree *tree, unsigned int owner,
286 tree->fs_info = fs_info;
287 tree->state = RB_ROOT;
288 tree->dirty_bytes = 0;
289 spin_lock_init(&tree->lock);
290 tree->private_data = private_data;
292 if (owner == IO_TREE_INODE_FILE_EXTENT)
293 lockdep_set_class(&tree->lock, &file_extent_tree_class);
296 void extent_io_tree_release(struct extent_io_tree *tree)
298 spin_lock(&tree->lock);
300 * Do a single barrier for the waitqueue_active check here, the state
301 * of the waitqueue should not change once extent_io_tree_release is
305 while (!RB_EMPTY_ROOT(&tree->state)) {
306 struct rb_node *node;
307 struct extent_state *state;
309 node = rb_first(&tree->state);
310 state = rb_entry(node, struct extent_state, rb_node);
311 rb_erase(&state->rb_node, &tree->state);
312 RB_CLEAR_NODE(&state->rb_node);
314 * btree io trees aren't supposed to have tasks waiting for
315 * changes in the flags of extent states ever.
317 ASSERT(!waitqueue_active(&state->wq));
318 free_extent_state(state);
320 cond_resched_lock(&tree->lock);
322 spin_unlock(&tree->lock);
325 static struct extent_state *alloc_extent_state(gfp_t mask)
327 struct extent_state *state;
330 * The given mask might be not appropriate for the slab allocator,
331 * drop the unsupported bits
333 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
334 state = kmem_cache_alloc(extent_state_cache, mask);
338 state->failrec = NULL;
339 RB_CLEAR_NODE(&state->rb_node);
340 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
341 refcount_set(&state->refs, 1);
342 init_waitqueue_head(&state->wq);
343 trace_alloc_extent_state(state, mask, _RET_IP_);
347 void free_extent_state(struct extent_state *state)
351 if (refcount_dec_and_test(&state->refs)) {
352 WARN_ON(extent_state_in_tree(state));
353 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
354 trace_free_extent_state(state, _RET_IP_);
355 kmem_cache_free(extent_state_cache, state);
359 static struct rb_node *tree_insert(struct rb_root *root,
360 struct rb_node *search_start,
362 struct rb_node *node,
363 struct rb_node ***p_in,
364 struct rb_node **parent_in)
367 struct rb_node *parent = NULL;
368 struct tree_entry *entry;
370 if (p_in && parent_in) {
376 p = search_start ? &search_start : &root->rb_node;
379 entry = rb_entry(parent, struct tree_entry, rb_node);
381 if (offset < entry->start)
383 else if (offset > entry->end)
390 rb_link_node(node, parent, p);
391 rb_insert_color(node, root);
396 * Search @tree for an entry that contains @offset. Such entry would have
397 * entry->start <= offset && entry->end >= offset.
399 * @tree: the tree to search
400 * @offset: offset that should fall within an entry in @tree
401 * @next_ret: pointer to the first entry whose range ends after @offset
402 * @prev_ret: pointer to the first entry whose range begins before @offset
403 * @p_ret: pointer where new node should be anchored (used when inserting an
405 * @parent_ret: points to entry which would have been the parent of the entry,
408 * This function returns a pointer to the entry that contains @offset byte
409 * address. If no such entry exists, then NULL is returned and the other
410 * pointer arguments to the function are filled, otherwise the found entry is
411 * returned and other pointers are left untouched.
413 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
414 struct rb_node **next_ret,
415 struct rb_node **prev_ret,
416 struct rb_node ***p_ret,
417 struct rb_node **parent_ret)
419 struct rb_root *root = &tree->state;
420 struct rb_node **n = &root->rb_node;
421 struct rb_node *prev = NULL;
422 struct rb_node *orig_prev = NULL;
423 struct tree_entry *entry;
424 struct tree_entry *prev_entry = NULL;
428 entry = rb_entry(prev, struct tree_entry, rb_node);
431 if (offset < entry->start)
433 else if (offset > entry->end)
446 while (prev && offset > prev_entry->end) {
447 prev = rb_next(prev);
448 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
455 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
456 while (prev && offset < prev_entry->start) {
457 prev = rb_prev(prev);
458 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
465 static inline struct rb_node *
466 tree_search_for_insert(struct extent_io_tree *tree,
468 struct rb_node ***p_ret,
469 struct rb_node **parent_ret)
471 struct rb_node *next= NULL;
474 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
480 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
483 return tree_search_for_insert(tree, offset, NULL, NULL);
487 * utility function to look for merge candidates inside a given range.
488 * Any extents with matching state are merged together into a single
489 * extent in the tree. Extents with EXTENT_IO in their state field
490 * are not merged because the end_io handlers need to be able to do
491 * operations on them without sleeping (or doing allocations/splits).
493 * This should be called with the tree lock held.
495 static void merge_state(struct extent_io_tree *tree,
496 struct extent_state *state)
498 struct extent_state *other;
499 struct rb_node *other_node;
501 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
504 other_node = rb_prev(&state->rb_node);
506 other = rb_entry(other_node, struct extent_state, rb_node);
507 if (other->end == state->start - 1 &&
508 other->state == state->state) {
509 if (tree->private_data &&
510 is_data_inode(tree->private_data))
511 btrfs_merge_delalloc_extent(tree->private_data,
513 state->start = other->start;
514 rb_erase(&other->rb_node, &tree->state);
515 RB_CLEAR_NODE(&other->rb_node);
516 free_extent_state(other);
519 other_node = rb_next(&state->rb_node);
521 other = rb_entry(other_node, struct extent_state, rb_node);
522 if (other->start == state->end + 1 &&
523 other->state == state->state) {
524 if (tree->private_data &&
525 is_data_inode(tree->private_data))
526 btrfs_merge_delalloc_extent(tree->private_data,
528 state->end = other->end;
529 rb_erase(&other->rb_node, &tree->state);
530 RB_CLEAR_NODE(&other->rb_node);
531 free_extent_state(other);
536 static void set_state_bits(struct extent_io_tree *tree,
537 struct extent_state *state, u32 *bits,
538 struct extent_changeset *changeset);
541 * insert an extent_state struct into the tree. 'bits' are set on the
542 * struct before it is inserted.
544 * This may return -EEXIST if the extent is already there, in which case the
545 * state struct is freed.
547 * The tree lock is not taken internally. This is a utility function and
548 * probably isn't what you want to call (see set/clear_extent_bit).
550 static int insert_state(struct extent_io_tree *tree,
551 struct extent_state *state, u64 start, u64 end,
553 struct rb_node **parent,
554 u32 *bits, struct extent_changeset *changeset)
556 struct rb_node *node;
559 btrfs_err(tree->fs_info,
560 "insert state: end < start %llu %llu", end, start);
563 state->start = start;
566 set_state_bits(tree, state, bits, changeset);
568 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
570 struct extent_state *found;
571 found = rb_entry(node, struct extent_state, rb_node);
572 btrfs_err(tree->fs_info,
573 "found node %llu %llu on insert of %llu %llu",
574 found->start, found->end, start, end);
577 merge_state(tree, state);
582 * split a given extent state struct in two, inserting the preallocated
583 * struct 'prealloc' as the newly created second half. 'split' indicates an
584 * offset inside 'orig' where it should be split.
587 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
588 * are two extent state structs in the tree:
589 * prealloc: [orig->start, split - 1]
590 * orig: [ split, orig->end ]
592 * The tree locks are not taken by this function. They need to be held
595 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
596 struct extent_state *prealloc, u64 split)
598 struct rb_node *node;
600 if (tree->private_data && is_data_inode(tree->private_data))
601 btrfs_split_delalloc_extent(tree->private_data, orig, split);
603 prealloc->start = orig->start;
604 prealloc->end = split - 1;
605 prealloc->state = orig->state;
608 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
609 &prealloc->rb_node, NULL, NULL);
611 free_extent_state(prealloc);
617 static struct extent_state *next_state(struct extent_state *state)
619 struct rb_node *next = rb_next(&state->rb_node);
621 return rb_entry(next, struct extent_state, rb_node);
627 * utility function to clear some bits in an extent state struct.
628 * it will optionally wake up anyone waiting on this state (wake == 1).
630 * If no bits are set on the state struct after clearing things, the
631 * struct is freed and removed from the tree
633 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
634 struct extent_state *state,
636 struct extent_changeset *changeset)
638 struct extent_state *next;
639 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
642 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
643 u64 range = state->end - state->start + 1;
644 WARN_ON(range > tree->dirty_bytes);
645 tree->dirty_bytes -= range;
648 if (tree->private_data && is_data_inode(tree->private_data))
649 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
651 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
653 state->state &= ~bits_to_clear;
656 if (state->state == 0) {
657 next = next_state(state);
658 if (extent_state_in_tree(state)) {
659 rb_erase(&state->rb_node, &tree->state);
660 RB_CLEAR_NODE(&state->rb_node);
661 free_extent_state(state);
666 merge_state(tree, state);
667 next = next_state(state);
672 static struct extent_state *
673 alloc_extent_state_atomic(struct extent_state *prealloc)
676 prealloc = alloc_extent_state(GFP_ATOMIC);
681 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
683 btrfs_panic(tree->fs_info, err,
684 "locking error: extent tree was modified by another thread while locked");
688 * clear some bits on a range in the tree. This may require splitting
689 * or inserting elements in the tree, so the gfp mask is used to
690 * indicate which allocations or sleeping are allowed.
692 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
693 * the given range from the tree regardless of state (ie for truncate).
695 * the range [start, end] is inclusive.
697 * This takes the tree lock, and returns 0 on success and < 0 on error.
699 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
700 u32 bits, int wake, int delete,
701 struct extent_state **cached_state,
702 gfp_t mask, struct extent_changeset *changeset)
704 struct extent_state *state;
705 struct extent_state *cached;
706 struct extent_state *prealloc = NULL;
707 struct rb_node *node;
712 btrfs_debug_check_extent_io_range(tree, start, end);
713 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
715 if (bits & EXTENT_DELALLOC)
716 bits |= EXTENT_NORESERVE;
719 bits |= ~EXTENT_CTLBITS;
721 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
724 if (!prealloc && gfpflags_allow_blocking(mask)) {
726 * Don't care for allocation failure here because we might end
727 * up not needing the pre-allocated extent state at all, which
728 * is the case if we only have in the tree extent states that
729 * cover our input range and don't cover too any other range.
730 * If we end up needing a new extent state we allocate it later.
732 prealloc = alloc_extent_state(mask);
735 spin_lock(&tree->lock);
737 cached = *cached_state;
740 *cached_state = NULL;
744 if (cached && extent_state_in_tree(cached) &&
745 cached->start <= start && cached->end > start) {
747 refcount_dec(&cached->refs);
752 free_extent_state(cached);
755 * this search will find the extents that end after
758 node = tree_search(tree, start);
761 state = rb_entry(node, struct extent_state, rb_node);
763 if (state->start > end)
765 WARN_ON(state->end < start);
766 last_end = state->end;
768 /* the state doesn't have the wanted bits, go ahead */
769 if (!(state->state & bits)) {
770 state = next_state(state);
775 * | ---- desired range ---- |
777 * | ------------- state -------------- |
779 * We need to split the extent we found, and may flip
780 * bits on second half.
782 * If the extent we found extends past our range, we
783 * just split and search again. It'll get split again
784 * the next time though.
786 * If the extent we found is inside our range, we clear
787 * the desired bit on it.
790 if (state->start < start) {
791 prealloc = alloc_extent_state_atomic(prealloc);
793 err = split_state(tree, state, prealloc, start);
795 extent_io_tree_panic(tree, err);
800 if (state->end <= end) {
801 state = clear_state_bit(tree, state, &bits, wake,
808 * | ---- desired range ---- |
810 * We need to split the extent, and clear the bit
813 if (state->start <= end && state->end > end) {
814 prealloc = alloc_extent_state_atomic(prealloc);
816 err = split_state(tree, state, prealloc, end + 1);
818 extent_io_tree_panic(tree, err);
823 clear_state_bit(tree, prealloc, &bits, wake, changeset);
829 state = clear_state_bit(tree, state, &bits, wake, changeset);
831 if (last_end == (u64)-1)
833 start = last_end + 1;
834 if (start <= end && state && !need_resched())
840 spin_unlock(&tree->lock);
841 if (gfpflags_allow_blocking(mask))
846 spin_unlock(&tree->lock);
848 free_extent_state(prealloc);
854 static void wait_on_state(struct extent_io_tree *tree,
855 struct extent_state *state)
856 __releases(tree->lock)
857 __acquires(tree->lock)
860 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
861 spin_unlock(&tree->lock);
863 spin_lock(&tree->lock);
864 finish_wait(&state->wq, &wait);
868 * waits for one or more bits to clear on a range in the state tree.
869 * The range [start, end] is inclusive.
870 * The tree lock is taken by this function
872 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
875 struct extent_state *state;
876 struct rb_node *node;
878 btrfs_debug_check_extent_io_range(tree, start, end);
880 spin_lock(&tree->lock);
884 * this search will find all the extents that end after
887 node = tree_search(tree, start);
892 state = rb_entry(node, struct extent_state, rb_node);
894 if (state->start > end)
897 if (state->state & bits) {
898 start = state->start;
899 refcount_inc(&state->refs);
900 wait_on_state(tree, state);
901 free_extent_state(state);
904 start = state->end + 1;
909 if (!cond_resched_lock(&tree->lock)) {
910 node = rb_next(node);
915 spin_unlock(&tree->lock);
918 static void set_state_bits(struct extent_io_tree *tree,
919 struct extent_state *state,
920 u32 *bits, struct extent_changeset *changeset)
922 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
925 if (tree->private_data && is_data_inode(tree->private_data))
926 btrfs_set_delalloc_extent(tree->private_data, state, bits);
928 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
929 u64 range = state->end - state->start + 1;
930 tree->dirty_bytes += range;
932 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
934 state->state |= bits_to_set;
937 static void cache_state_if_flags(struct extent_state *state,
938 struct extent_state **cached_ptr,
941 if (cached_ptr && !(*cached_ptr)) {
942 if (!flags || (state->state & flags)) {
944 refcount_inc(&state->refs);
949 static void cache_state(struct extent_state *state,
950 struct extent_state **cached_ptr)
952 return cache_state_if_flags(state, cached_ptr,
953 EXTENT_LOCKED | EXTENT_BOUNDARY);
957 * set some bits on a range in the tree. This may require allocations or
958 * sleeping, so the gfp mask is used to indicate what is allowed.
960 * If any of the exclusive bits are set, this will fail with -EEXIST if some
961 * part of the range already has the desired bits set. The start of the
962 * existing range is returned in failed_start in this case.
964 * [start, end] is inclusive This takes the tree lock.
966 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
967 u32 exclusive_bits, u64 *failed_start,
968 struct extent_state **cached_state, gfp_t mask,
969 struct extent_changeset *changeset)
971 struct extent_state *state;
972 struct extent_state *prealloc = NULL;
973 struct rb_node *node;
975 struct rb_node *parent;
980 btrfs_debug_check_extent_io_range(tree, start, end);
981 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
984 ASSERT(failed_start);
986 ASSERT(failed_start == NULL);
988 if (!prealloc && gfpflags_allow_blocking(mask)) {
990 * Don't care for allocation failure here because we might end
991 * up not needing the pre-allocated extent state at all, which
992 * is the case if we only have in the tree extent states that
993 * cover our input range and don't cover too any other range.
994 * If we end up needing a new extent state we allocate it later.
996 prealloc = alloc_extent_state(mask);
999 spin_lock(&tree->lock);
1000 if (cached_state && *cached_state) {
1001 state = *cached_state;
1002 if (state->start <= start && state->end > start &&
1003 extent_state_in_tree(state)) {
1004 node = &state->rb_node;
1009 * this search will find all the extents that end after
1012 node = tree_search_for_insert(tree, start, &p, &parent);
1014 prealloc = alloc_extent_state_atomic(prealloc);
1016 err = insert_state(tree, prealloc, start, end,
1017 &p, &parent, &bits, changeset);
1019 extent_io_tree_panic(tree, err);
1021 cache_state(prealloc, cached_state);
1025 state = rb_entry(node, struct extent_state, rb_node);
1027 last_start = state->start;
1028 last_end = state->end;
1031 * | ---- desired range ---- |
1034 * Just lock what we found and keep going
1036 if (state->start == start && state->end <= end) {
1037 if (state->state & exclusive_bits) {
1038 *failed_start = state->start;
1043 set_state_bits(tree, state, &bits, changeset);
1044 cache_state(state, cached_state);
1045 merge_state(tree, state);
1046 if (last_end == (u64)-1)
1048 start = last_end + 1;
1049 state = next_state(state);
1050 if (start < end && state && state->start == start &&
1057 * | ---- desired range ---- |
1060 * | ------------- state -------------- |
1062 * We need to split the extent we found, and may flip bits on
1065 * If the extent we found extends past our
1066 * range, we just split and search again. It'll get split
1067 * again the next time though.
1069 * If the extent we found is inside our range, we set the
1070 * desired bit on it.
1072 if (state->start < start) {
1073 if (state->state & exclusive_bits) {
1074 *failed_start = start;
1080 * If this extent already has all the bits we want set, then
1081 * skip it, not necessary to split it or do anything with it.
1083 if ((state->state & bits) == bits) {
1084 start = state->end + 1;
1085 cache_state(state, cached_state);
1089 prealloc = alloc_extent_state_atomic(prealloc);
1091 err = split_state(tree, state, prealloc, start);
1093 extent_io_tree_panic(tree, err);
1098 if (state->end <= end) {
1099 set_state_bits(tree, state, &bits, changeset);
1100 cache_state(state, cached_state);
1101 merge_state(tree, state);
1102 if (last_end == (u64)-1)
1104 start = last_end + 1;
1105 state = next_state(state);
1106 if (start < end && state && state->start == start &&
1113 * | ---- desired range ---- |
1114 * | state | or | state |
1116 * There's a hole, we need to insert something in it and
1117 * ignore the extent we found.
1119 if (state->start > start) {
1121 if (end < last_start)
1124 this_end = last_start - 1;
1126 prealloc = alloc_extent_state_atomic(prealloc);
1130 * Avoid to free 'prealloc' if it can be merged with
1133 err = insert_state(tree, prealloc, start, this_end,
1134 NULL, NULL, &bits, changeset);
1136 extent_io_tree_panic(tree, err);
1138 cache_state(prealloc, cached_state);
1140 start = this_end + 1;
1144 * | ---- desired range ---- |
1146 * We need to split the extent, and set the bit
1149 if (state->start <= end && state->end > end) {
1150 if (state->state & exclusive_bits) {
1151 *failed_start = start;
1156 prealloc = alloc_extent_state_atomic(prealloc);
1158 err = split_state(tree, state, prealloc, end + 1);
1160 extent_io_tree_panic(tree, err);
1162 set_state_bits(tree, prealloc, &bits, changeset);
1163 cache_state(prealloc, cached_state);
1164 merge_state(tree, prealloc);
1172 spin_unlock(&tree->lock);
1173 if (gfpflags_allow_blocking(mask))
1178 spin_unlock(&tree->lock);
1180 free_extent_state(prealloc);
1187 * convert_extent_bit - convert all bits in a given range from one bit to
1189 * @tree: the io tree to search
1190 * @start: the start offset in bytes
1191 * @end: the end offset in bytes (inclusive)
1192 * @bits: the bits to set in this range
1193 * @clear_bits: the bits to clear in this range
1194 * @cached_state: state that we're going to cache
1196 * This will go through and set bits for the given range. If any states exist
1197 * already in this range they are set with the given bit and cleared of the
1198 * clear_bits. This is only meant to be used by things that are mergeable, ie
1199 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1200 * boundary bits like LOCK.
1202 * All allocations are done with GFP_NOFS.
1204 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1205 u32 bits, u32 clear_bits,
1206 struct extent_state **cached_state)
1208 struct extent_state *state;
1209 struct extent_state *prealloc = NULL;
1210 struct rb_node *node;
1212 struct rb_node *parent;
1216 bool first_iteration = true;
1218 btrfs_debug_check_extent_io_range(tree, start, end);
1219 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1225 * Best effort, don't worry if extent state allocation fails
1226 * here for the first iteration. We might have a cached state
1227 * that matches exactly the target range, in which case no
1228 * extent state allocations are needed. We'll only know this
1229 * after locking the tree.
1231 prealloc = alloc_extent_state(GFP_NOFS);
1232 if (!prealloc && !first_iteration)
1236 spin_lock(&tree->lock);
1237 if (cached_state && *cached_state) {
1238 state = *cached_state;
1239 if (state->start <= start && state->end > start &&
1240 extent_state_in_tree(state)) {
1241 node = &state->rb_node;
1247 * this search will find all the extents that end after
1250 node = tree_search_for_insert(tree, start, &p, &parent);
1252 prealloc = alloc_extent_state_atomic(prealloc);
1257 err = insert_state(tree, prealloc, start, end,
1258 &p, &parent, &bits, NULL);
1260 extent_io_tree_panic(tree, err);
1261 cache_state(prealloc, cached_state);
1265 state = rb_entry(node, struct extent_state, rb_node);
1267 last_start = state->start;
1268 last_end = state->end;
1271 * | ---- desired range ---- |
1274 * Just lock what we found and keep going
1276 if (state->start == start && state->end <= end) {
1277 set_state_bits(tree, state, &bits, NULL);
1278 cache_state(state, cached_state);
1279 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1280 if (last_end == (u64)-1)
1282 start = last_end + 1;
1283 if (start < end && state && state->start == start &&
1290 * | ---- desired range ---- |
1293 * | ------------- state -------------- |
1295 * We need to split the extent we found, and may flip bits on
1298 * If the extent we found extends past our
1299 * range, we just split and search again. It'll get split
1300 * again the next time though.
1302 * If the extent we found is inside our range, we set the
1303 * desired bit on it.
1305 if (state->start < start) {
1306 prealloc = alloc_extent_state_atomic(prealloc);
1311 err = split_state(tree, state, prealloc, start);
1313 extent_io_tree_panic(tree, err);
1317 if (state->end <= end) {
1318 set_state_bits(tree, state, &bits, NULL);
1319 cache_state(state, cached_state);
1320 state = clear_state_bit(tree, state, &clear_bits, 0,
1322 if (last_end == (u64)-1)
1324 start = last_end + 1;
1325 if (start < end && state && state->start == start &&
1332 * | ---- desired range ---- |
1333 * | state | or | state |
1335 * There's a hole, we need to insert something in it and
1336 * ignore the extent we found.
1338 if (state->start > start) {
1340 if (end < last_start)
1343 this_end = last_start - 1;
1345 prealloc = alloc_extent_state_atomic(prealloc);
1352 * Avoid to free 'prealloc' if it can be merged with
1355 err = insert_state(tree, prealloc, start, this_end,
1356 NULL, NULL, &bits, NULL);
1358 extent_io_tree_panic(tree, err);
1359 cache_state(prealloc, cached_state);
1361 start = this_end + 1;
1365 * | ---- desired range ---- |
1367 * We need to split the extent, and set the bit
1370 if (state->start <= end && state->end > end) {
1371 prealloc = alloc_extent_state_atomic(prealloc);
1377 err = split_state(tree, state, prealloc, end + 1);
1379 extent_io_tree_panic(tree, err);
1381 set_state_bits(tree, prealloc, &bits, NULL);
1382 cache_state(prealloc, cached_state);
1383 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1391 spin_unlock(&tree->lock);
1393 first_iteration = false;
1397 spin_unlock(&tree->lock);
1399 free_extent_state(prealloc);
1404 /* wrappers around set/clear extent bit */
1405 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1406 u32 bits, struct extent_changeset *changeset)
1409 * We don't support EXTENT_LOCKED yet, as current changeset will
1410 * record any bits changed, so for EXTENT_LOCKED case, it will
1411 * either fail with -EEXIST or changeset will record the whole
1414 BUG_ON(bits & EXTENT_LOCKED);
1416 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1420 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1423 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1427 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1428 u32 bits, int wake, int delete,
1429 struct extent_state **cached)
1431 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1432 cached, GFP_NOFS, NULL);
1435 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1436 u32 bits, struct extent_changeset *changeset)
1439 * Don't support EXTENT_LOCKED case, same reason as
1440 * set_record_extent_bits().
1442 BUG_ON(bits & EXTENT_LOCKED);
1444 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1449 * either insert or lock state struct between start and end use mask to tell
1450 * us if waiting is desired.
1452 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1453 struct extent_state **cached_state)
1459 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1460 EXTENT_LOCKED, &failed_start,
1461 cached_state, GFP_NOFS, NULL);
1462 if (err == -EEXIST) {
1463 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1464 start = failed_start;
1467 WARN_ON(start > end);
1472 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1477 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1478 &failed_start, NULL, GFP_NOFS, NULL);
1479 if (err == -EEXIST) {
1480 if (failed_start > start)
1481 clear_extent_bit(tree, start, failed_start - 1,
1482 EXTENT_LOCKED, 1, 0, NULL);
1488 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1490 unsigned long index = start >> PAGE_SHIFT;
1491 unsigned long end_index = end >> PAGE_SHIFT;
1494 while (index <= end_index) {
1495 page = find_get_page(inode->i_mapping, index);
1496 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1497 clear_page_dirty_for_io(page);
1503 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1505 unsigned long index = start >> PAGE_SHIFT;
1506 unsigned long end_index = end >> PAGE_SHIFT;
1509 while (index <= end_index) {
1510 page = find_get_page(inode->i_mapping, index);
1511 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1512 __set_page_dirty_nobuffers(page);
1513 account_page_redirty(page);
1519 /* find the first state struct with 'bits' set after 'start', and
1520 * return it. tree->lock must be held. NULL will returned if
1521 * nothing was found after 'start'
1523 static struct extent_state *
1524 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1526 struct rb_node *node;
1527 struct extent_state *state;
1530 * this search will find all the extents that end after
1533 node = tree_search(tree, start);
1538 state = rb_entry(node, struct extent_state, rb_node);
1539 if (state->end >= start && (state->state & bits))
1542 node = rb_next(node);
1551 * Find the first offset in the io tree with one or more @bits set.
1553 * Note: If there are multiple bits set in @bits, any of them will match.
1555 * Return 0 if we find something, and update @start_ret and @end_ret.
1556 * Return 1 if we found nothing.
1558 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1559 u64 *start_ret, u64 *end_ret, u32 bits,
1560 struct extent_state **cached_state)
1562 struct extent_state *state;
1565 spin_lock(&tree->lock);
1566 if (cached_state && *cached_state) {
1567 state = *cached_state;
1568 if (state->end == start - 1 && extent_state_in_tree(state)) {
1569 while ((state = next_state(state)) != NULL) {
1570 if (state->state & bits)
1573 free_extent_state(*cached_state);
1574 *cached_state = NULL;
1577 free_extent_state(*cached_state);
1578 *cached_state = NULL;
1581 state = find_first_extent_bit_state(tree, start, bits);
1584 cache_state_if_flags(state, cached_state, 0);
1585 *start_ret = state->start;
1586 *end_ret = state->end;
1590 spin_unlock(&tree->lock);
1595 * Find a contiguous area of bits
1597 * @tree: io tree to check
1598 * @start: offset to start the search from
1599 * @start_ret: the first offset we found with the bits set
1600 * @end_ret: the final contiguous range of the bits that were set
1601 * @bits: bits to look for
1603 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1604 * to set bits appropriately, and then merge them again. During this time it
1605 * will drop the tree->lock, so use this helper if you want to find the actual
1606 * contiguous area for given bits. We will search to the first bit we find, and
1607 * then walk down the tree until we find a non-contiguous area. The area
1608 * returned will be the full contiguous area with the bits set.
1610 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1611 u64 *start_ret, u64 *end_ret, u32 bits)
1613 struct extent_state *state;
1616 spin_lock(&tree->lock);
1617 state = find_first_extent_bit_state(tree, start, bits);
1619 *start_ret = state->start;
1620 *end_ret = state->end;
1621 while ((state = next_state(state)) != NULL) {
1622 if (state->start > (*end_ret + 1))
1624 *end_ret = state->end;
1628 spin_unlock(&tree->lock);
1633 * Find the first range that has @bits not set. This range could start before
1636 * @tree: the tree to search
1637 * @start: offset at/after which the found extent should start
1638 * @start_ret: records the beginning of the range
1639 * @end_ret: records the end of the range (inclusive)
1640 * @bits: the set of bits which must be unset
1642 * Since unallocated range is also considered one which doesn't have the bits
1643 * set it's possible that @end_ret contains -1, this happens in case the range
1644 * spans (last_range_end, end of device]. In this case it's up to the caller to
1645 * trim @end_ret to the appropriate size.
1647 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1648 u64 *start_ret, u64 *end_ret, u32 bits)
1650 struct extent_state *state;
1651 struct rb_node *node, *prev = NULL, *next;
1653 spin_lock(&tree->lock);
1655 /* Find first extent with bits cleared */
1657 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1658 if (!node && !next && !prev) {
1660 * Tree is completely empty, send full range and let
1661 * caller deal with it
1666 } else if (!node && !next) {
1668 * We are past the last allocated chunk, set start at
1669 * the end of the last extent.
1671 state = rb_entry(prev, struct extent_state, rb_node);
1672 *start_ret = state->end + 1;
1679 * At this point 'node' either contains 'start' or start is
1682 state = rb_entry(node, struct extent_state, rb_node);
1684 if (in_range(start, state->start, state->end - state->start + 1)) {
1685 if (state->state & bits) {
1687 * |--range with bits sets--|
1691 start = state->end + 1;
1694 * 'start' falls within a range that doesn't
1695 * have the bits set, so take its start as
1696 * the beginning of the desired range
1698 * |--range with bits cleared----|
1702 *start_ret = state->start;
1707 * |---prev range---|---hole/unset---|---node range---|
1713 * |---hole/unset--||--first node--|
1718 state = rb_entry(prev, struct extent_state,
1720 *start_ret = state->end + 1;
1729 * Find the longest stretch from start until an entry which has the
1733 state = rb_entry(node, struct extent_state, rb_node);
1734 if (state->end >= start && !(state->state & bits)) {
1735 *end_ret = state->end;
1737 *end_ret = state->start - 1;
1741 node = rb_next(node);
1746 spin_unlock(&tree->lock);
1750 * find a contiguous range of bytes in the file marked as delalloc, not
1751 * more than 'max_bytes'. start and end are used to return the range,
1753 * true is returned if we find something, false if nothing was in the tree
1755 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1756 u64 *end, u64 max_bytes,
1757 struct extent_state **cached_state)
1759 struct rb_node *node;
1760 struct extent_state *state;
1761 u64 cur_start = *start;
1763 u64 total_bytes = 0;
1765 spin_lock(&tree->lock);
1768 * this search will find all the extents that end after
1771 node = tree_search(tree, cur_start);
1778 state = rb_entry(node, struct extent_state, rb_node);
1779 if (found && (state->start != cur_start ||
1780 (state->state & EXTENT_BOUNDARY))) {
1783 if (!(state->state & EXTENT_DELALLOC)) {
1789 *start = state->start;
1790 *cached_state = state;
1791 refcount_inc(&state->refs);
1795 cur_start = state->end + 1;
1796 node = rb_next(node);
1797 total_bytes += state->end - state->start + 1;
1798 if (total_bytes >= max_bytes)
1804 spin_unlock(&tree->lock);
1808 static int __process_pages_contig(struct address_space *mapping,
1809 struct page *locked_page,
1810 pgoff_t start_index, pgoff_t end_index,
1811 unsigned long page_ops, pgoff_t *index_ret);
1813 static noinline void __unlock_for_delalloc(struct inode *inode,
1814 struct page *locked_page,
1817 unsigned long index = start >> PAGE_SHIFT;
1818 unsigned long end_index = end >> PAGE_SHIFT;
1820 ASSERT(locked_page);
1821 if (index == locked_page->index && end_index == index)
1824 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1828 static noinline int lock_delalloc_pages(struct inode *inode,
1829 struct page *locked_page,
1833 unsigned long index = delalloc_start >> PAGE_SHIFT;
1834 unsigned long index_ret = index;
1835 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1838 ASSERT(locked_page);
1839 if (index == locked_page->index && index == end_index)
1842 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1843 end_index, PAGE_LOCK, &index_ret);
1845 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1846 (u64)index_ret << PAGE_SHIFT);
1851 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1852 * more than @max_bytes. @Start and @end are used to return the range,
1854 * Return: true if we find something
1855 * false if nothing was in the tree
1858 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1859 struct page *locked_page, u64 *start,
1862 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1863 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1867 struct extent_state *cached_state = NULL;
1872 /* step one, find a bunch of delalloc bytes starting at start */
1873 delalloc_start = *start;
1875 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1876 max_bytes, &cached_state);
1877 if (!found || delalloc_end <= *start) {
1878 *start = delalloc_start;
1879 *end = delalloc_end;
1880 free_extent_state(cached_state);
1885 * start comes from the offset of locked_page. We have to lock
1886 * pages in order, so we can't process delalloc bytes before
1889 if (delalloc_start < *start)
1890 delalloc_start = *start;
1893 * make sure to limit the number of pages we try to lock down
1895 if (delalloc_end + 1 - delalloc_start > max_bytes)
1896 delalloc_end = delalloc_start + max_bytes - 1;
1898 /* step two, lock all the pages after the page that has start */
1899 ret = lock_delalloc_pages(inode, locked_page,
1900 delalloc_start, delalloc_end);
1901 ASSERT(!ret || ret == -EAGAIN);
1902 if (ret == -EAGAIN) {
1903 /* some of the pages are gone, lets avoid looping by
1904 * shortening the size of the delalloc range we're searching
1906 free_extent_state(cached_state);
1907 cached_state = NULL;
1909 max_bytes = PAGE_SIZE;
1918 /* step three, lock the state bits for the whole range */
1919 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1921 /* then test to make sure it is all still delalloc */
1922 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1923 EXTENT_DELALLOC, 1, cached_state);
1925 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1927 __unlock_for_delalloc(inode, locked_page,
1928 delalloc_start, delalloc_end);
1932 free_extent_state(cached_state);
1933 *start = delalloc_start;
1934 *end = delalloc_end;
1939 static int __process_pages_contig(struct address_space *mapping,
1940 struct page *locked_page,
1941 pgoff_t start_index, pgoff_t end_index,
1942 unsigned long page_ops, pgoff_t *index_ret)
1944 unsigned long nr_pages = end_index - start_index + 1;
1945 unsigned long pages_processed = 0;
1946 pgoff_t index = start_index;
1947 struct page *pages[16];
1952 if (page_ops & PAGE_LOCK) {
1953 ASSERT(page_ops == PAGE_LOCK);
1954 ASSERT(index_ret && *index_ret == start_index);
1957 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1958 mapping_set_error(mapping, -EIO);
1960 while (nr_pages > 0) {
1961 ret = find_get_pages_contig(mapping, index,
1962 min_t(unsigned long,
1963 nr_pages, ARRAY_SIZE(pages)), pages);
1966 * Only if we're going to lock these pages,
1967 * can we find nothing at @index.
1969 ASSERT(page_ops & PAGE_LOCK);
1974 for (i = 0; i < ret; i++) {
1975 if (page_ops & PAGE_SET_PRIVATE2)
1976 SetPagePrivate2(pages[i]);
1978 if (locked_page && pages[i] == locked_page) {
1983 if (page_ops & PAGE_START_WRITEBACK) {
1984 clear_page_dirty_for_io(pages[i]);
1985 set_page_writeback(pages[i]);
1987 if (page_ops & PAGE_SET_ERROR)
1988 SetPageError(pages[i]);
1989 if (page_ops & PAGE_END_WRITEBACK)
1990 end_page_writeback(pages[i]);
1991 if (page_ops & PAGE_UNLOCK)
1992 unlock_page(pages[i]);
1993 if (page_ops & PAGE_LOCK) {
1994 lock_page(pages[i]);
1995 if (!PageDirty(pages[i]) ||
1996 pages[i]->mapping != mapping) {
1997 unlock_page(pages[i]);
1998 for (; i < ret; i++)
2012 if (err && index_ret)
2013 *index_ret = start_index + pages_processed - 1;
2017 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2018 struct page *locked_page,
2019 u32 clear_bits, unsigned long page_ops)
2021 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2023 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2024 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
2029 * count the number of bytes in the tree that have a given bit(s)
2030 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2031 * cached. The total number found is returned.
2033 u64 count_range_bits(struct extent_io_tree *tree,
2034 u64 *start, u64 search_end, u64 max_bytes,
2035 u32 bits, int contig)
2037 struct rb_node *node;
2038 struct extent_state *state;
2039 u64 cur_start = *start;
2040 u64 total_bytes = 0;
2044 if (WARN_ON(search_end <= cur_start))
2047 spin_lock(&tree->lock);
2048 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2049 total_bytes = tree->dirty_bytes;
2053 * this search will find all the extents that end after
2056 node = tree_search(tree, cur_start);
2061 state = rb_entry(node, struct extent_state, rb_node);
2062 if (state->start > search_end)
2064 if (contig && found && state->start > last + 1)
2066 if (state->end >= cur_start && (state->state & bits) == bits) {
2067 total_bytes += min(search_end, state->end) + 1 -
2068 max(cur_start, state->start);
2069 if (total_bytes >= max_bytes)
2072 *start = max(cur_start, state->start);
2076 } else if (contig && found) {
2079 node = rb_next(node);
2084 spin_unlock(&tree->lock);
2089 * set the private field for a given byte offset in the tree. If there isn't
2090 * an extent_state there already, this does nothing.
2092 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2093 struct io_failure_record *failrec)
2095 struct rb_node *node;
2096 struct extent_state *state;
2099 spin_lock(&tree->lock);
2101 * this search will find all the extents that end after
2104 node = tree_search(tree, start);
2109 state = rb_entry(node, struct extent_state, rb_node);
2110 if (state->start != start) {
2114 state->failrec = failrec;
2116 spin_unlock(&tree->lock);
2120 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2122 struct rb_node *node;
2123 struct extent_state *state;
2124 struct io_failure_record *failrec;
2126 spin_lock(&tree->lock);
2128 * this search will find all the extents that end after
2131 node = tree_search(tree, start);
2133 failrec = ERR_PTR(-ENOENT);
2136 state = rb_entry(node, struct extent_state, rb_node);
2137 if (state->start != start) {
2138 failrec = ERR_PTR(-ENOENT);
2142 failrec = state->failrec;
2144 spin_unlock(&tree->lock);
2149 * searches a range in the state tree for a given mask.
2150 * If 'filled' == 1, this returns 1 only if every extent in the tree
2151 * has the bits set. Otherwise, 1 is returned if any bit in the
2152 * range is found set.
2154 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2155 u32 bits, int filled, struct extent_state *cached)
2157 struct extent_state *state = NULL;
2158 struct rb_node *node;
2161 spin_lock(&tree->lock);
2162 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2163 cached->end > start)
2164 node = &cached->rb_node;
2166 node = tree_search(tree, start);
2167 while (node && start <= end) {
2168 state = rb_entry(node, struct extent_state, rb_node);
2170 if (filled && state->start > start) {
2175 if (state->start > end)
2178 if (state->state & bits) {
2182 } else if (filled) {
2187 if (state->end == (u64)-1)
2190 start = state->end + 1;
2193 node = rb_next(node);
2200 spin_unlock(&tree->lock);
2205 * helper function to set a given page up to date if all the
2206 * extents in the tree for that page are up to date
2208 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2210 u64 start = page_offset(page);
2211 u64 end = start + PAGE_SIZE - 1;
2212 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2213 SetPageUptodate(page);
2216 int free_io_failure(struct extent_io_tree *failure_tree,
2217 struct extent_io_tree *io_tree,
2218 struct io_failure_record *rec)
2223 set_state_failrec(failure_tree, rec->start, NULL);
2224 ret = clear_extent_bits(failure_tree, rec->start,
2225 rec->start + rec->len - 1,
2226 EXTENT_LOCKED | EXTENT_DIRTY);
2230 ret = clear_extent_bits(io_tree, rec->start,
2231 rec->start + rec->len - 1,
2241 * this bypasses the standard btrfs submit functions deliberately, as
2242 * the standard behavior is to write all copies in a raid setup. here we only
2243 * want to write the one bad copy. so we do the mapping for ourselves and issue
2244 * submit_bio directly.
2245 * to avoid any synchronization issues, wait for the data after writing, which
2246 * actually prevents the read that triggered the error from finishing.
2247 * currently, there can be no more than two copies of every data bit. thus,
2248 * exactly one rewrite is required.
2250 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2251 u64 length, u64 logical, struct page *page,
2252 unsigned int pg_offset, int mirror_num)
2255 struct btrfs_device *dev;
2258 struct btrfs_bio *bbio = NULL;
2261 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2262 BUG_ON(!mirror_num);
2264 if (btrfs_is_zoned(fs_info))
2265 return btrfs_repair_one_zone(fs_info, logical);
2267 bio = btrfs_io_bio_alloc(1);
2268 bio->bi_iter.bi_size = 0;
2269 map_length = length;
2272 * Avoid races with device replace and make sure our bbio has devices
2273 * associated to its stripes that don't go away while we are doing the
2274 * read repair operation.
2276 btrfs_bio_counter_inc_blocked(fs_info);
2277 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2279 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2280 * to update all raid stripes, but here we just want to correct
2281 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2282 * stripe's dev and sector.
2284 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2285 &map_length, &bbio, 0);
2287 btrfs_bio_counter_dec(fs_info);
2291 ASSERT(bbio->mirror_num == 1);
2293 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2294 &map_length, &bbio, mirror_num);
2296 btrfs_bio_counter_dec(fs_info);
2300 BUG_ON(mirror_num != bbio->mirror_num);
2303 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2304 bio->bi_iter.bi_sector = sector;
2305 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2306 btrfs_put_bbio(bbio);
2307 if (!dev || !dev->bdev ||
2308 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2309 btrfs_bio_counter_dec(fs_info);
2313 bio_set_dev(bio, dev->bdev);
2314 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2315 bio_add_page(bio, page, length, pg_offset);
2317 if (btrfsic_submit_bio_wait(bio)) {
2318 /* try to remap that extent elsewhere? */
2319 btrfs_bio_counter_dec(fs_info);
2321 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2325 btrfs_info_rl_in_rcu(fs_info,
2326 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2328 rcu_str_deref(dev->name), sector);
2329 btrfs_bio_counter_dec(fs_info);
2334 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2336 struct btrfs_fs_info *fs_info = eb->fs_info;
2337 u64 start = eb->start;
2338 int i, num_pages = num_extent_pages(eb);
2341 if (sb_rdonly(fs_info->sb))
2344 for (i = 0; i < num_pages; i++) {
2345 struct page *p = eb->pages[i];
2347 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2348 start - page_offset(p), mirror_num);
2358 * each time an IO finishes, we do a fast check in the IO failure tree
2359 * to see if we need to process or clean up an io_failure_record
2361 int clean_io_failure(struct btrfs_fs_info *fs_info,
2362 struct extent_io_tree *failure_tree,
2363 struct extent_io_tree *io_tree, u64 start,
2364 struct page *page, u64 ino, unsigned int pg_offset)
2367 struct io_failure_record *failrec;
2368 struct extent_state *state;
2373 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2378 failrec = get_state_failrec(failure_tree, start);
2379 if (IS_ERR(failrec))
2382 BUG_ON(!failrec->this_mirror);
2384 if (failrec->in_validation) {
2385 /* there was no real error, just free the record */
2386 btrfs_debug(fs_info,
2387 "clean_io_failure: freeing dummy error at %llu",
2391 if (sb_rdonly(fs_info->sb))
2394 spin_lock(&io_tree->lock);
2395 state = find_first_extent_bit_state(io_tree,
2398 spin_unlock(&io_tree->lock);
2400 if (state && state->start <= failrec->start &&
2401 state->end >= failrec->start + failrec->len - 1) {
2402 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2404 if (num_copies > 1) {
2405 repair_io_failure(fs_info, ino, start, failrec->len,
2406 failrec->logical, page, pg_offset,
2407 failrec->failed_mirror);
2412 free_io_failure(failure_tree, io_tree, failrec);
2418 * Can be called when
2419 * - hold extent lock
2420 * - under ordered extent
2421 * - the inode is freeing
2423 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2425 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2426 struct io_failure_record *failrec;
2427 struct extent_state *state, *next;
2429 if (RB_EMPTY_ROOT(&failure_tree->state))
2432 spin_lock(&failure_tree->lock);
2433 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2435 if (state->start > end)
2438 ASSERT(state->end <= end);
2440 next = next_state(state);
2442 failrec = state->failrec;
2443 free_extent_state(state);
2448 spin_unlock(&failure_tree->lock);
2451 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2454 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2455 struct io_failure_record *failrec;
2456 struct extent_map *em;
2457 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2458 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2459 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2460 const u32 sectorsize = fs_info->sectorsize;
2464 failrec = get_state_failrec(failure_tree, start);
2465 if (!IS_ERR(failrec)) {
2466 btrfs_debug(fs_info,
2467 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2468 failrec->logical, failrec->start, failrec->len,
2469 failrec->in_validation);
2471 * when data can be on disk more than twice, add to failrec here
2472 * (e.g. with a list for failed_mirror) to make
2473 * clean_io_failure() clean all those errors at once.
2479 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2481 return ERR_PTR(-ENOMEM);
2483 failrec->start = start;
2484 failrec->len = sectorsize;
2485 failrec->this_mirror = 0;
2486 failrec->bio_flags = 0;
2487 failrec->in_validation = 0;
2489 read_lock(&em_tree->lock);
2490 em = lookup_extent_mapping(em_tree, start, failrec->len);
2492 read_unlock(&em_tree->lock);
2494 return ERR_PTR(-EIO);
2497 if (em->start > start || em->start + em->len <= start) {
2498 free_extent_map(em);
2501 read_unlock(&em_tree->lock);
2504 return ERR_PTR(-EIO);
2507 logical = start - em->start;
2508 logical = em->block_start + logical;
2509 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2510 logical = em->block_start;
2511 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2512 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2515 btrfs_debug(fs_info,
2516 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2517 logical, start, failrec->len);
2519 failrec->logical = logical;
2520 free_extent_map(em);
2522 /* Set the bits in the private failure tree */
2523 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2524 EXTENT_LOCKED | EXTENT_DIRTY);
2526 ret = set_state_failrec(failure_tree, start, failrec);
2527 /* Set the bits in the inode's tree */
2528 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2530 } else if (ret < 0) {
2532 return ERR_PTR(ret);
2538 static bool btrfs_check_repairable(struct inode *inode, bool needs_validation,
2539 struct io_failure_record *failrec,
2542 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2545 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2546 if (num_copies == 1) {
2548 * we only have a single copy of the data, so don't bother with
2549 * all the retry and error correction code that follows. no
2550 * matter what the error is, it is very likely to persist.
2552 btrfs_debug(fs_info,
2553 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2554 num_copies, failrec->this_mirror, failed_mirror);
2559 * there are two premises:
2560 * a) deliver good data to the caller
2561 * b) correct the bad sectors on disk
2563 if (needs_validation) {
2565 * to fulfill b), we need to know the exact failing sectors, as
2566 * we don't want to rewrite any more than the failed ones. thus,
2567 * we need separate read requests for the failed bio
2569 * if the following BUG_ON triggers, our validation request got
2570 * merged. we need separate requests for our algorithm to work.
2572 BUG_ON(failrec->in_validation);
2573 failrec->in_validation = 1;
2574 failrec->this_mirror = failed_mirror;
2577 * we're ready to fulfill a) and b) alongside. get a good copy
2578 * of the failed sector and if we succeed, we have setup
2579 * everything for repair_io_failure to do the rest for us.
2581 if (failrec->in_validation) {
2582 BUG_ON(failrec->this_mirror != failed_mirror);
2583 failrec->in_validation = 0;
2584 failrec->this_mirror = 0;
2586 failrec->failed_mirror = failed_mirror;
2587 failrec->this_mirror++;
2588 if (failrec->this_mirror == failed_mirror)
2589 failrec->this_mirror++;
2592 if (failrec->this_mirror > num_copies) {
2593 btrfs_debug(fs_info,
2594 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2595 num_copies, failrec->this_mirror, failed_mirror);
2602 static bool btrfs_io_needs_validation(struct inode *inode, struct bio *bio)
2605 const u32 blocksize = inode->i_sb->s_blocksize;
2608 * If bi_status is BLK_STS_OK, then this was a checksum error, not an
2609 * I/O error. In this case, we already know exactly which sector was
2610 * bad, so we don't need to validate.
2612 if (bio->bi_status == BLK_STS_OK)
2616 * We need to validate each sector individually if the failed I/O was
2617 * for multiple sectors.
2619 * There are a few possible bios that can end up here:
2620 * 1. A buffered read bio, which is not cloned.
2621 * 2. A direct I/O read bio, which is cloned.
2622 * 3. A (buffered or direct) repair bio, which is not cloned.
2624 * For cloned bios (case 2), we can get the size from
2625 * btrfs_io_bio->iter; for non-cloned bios (cases 1 and 3), we can get
2626 * it from the bvecs.
2628 if (bio_flagged(bio, BIO_CLONED)) {
2629 if (btrfs_io_bio(bio)->iter.bi_size > blocksize)
2632 struct bio_vec *bvec;
2635 bio_for_each_bvec_all(bvec, bio, i) {
2636 len += bvec->bv_len;
2637 if (len > blocksize)
2644 int btrfs_repair_one_sector(struct inode *inode,
2645 struct bio *failed_bio, u32 bio_offset,
2646 struct page *page, unsigned int pgoff,
2647 u64 start, int failed_mirror,
2648 submit_bio_hook_t *submit_bio_hook)
2650 struct io_failure_record *failrec;
2651 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2652 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2653 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2654 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2655 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2656 bool need_validation;
2657 struct bio *repair_bio;
2658 struct btrfs_io_bio *repair_io_bio;
2659 blk_status_t status;
2661 btrfs_debug(fs_info,
2662 "repair read error: read error at %llu", start);
2664 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2666 failrec = btrfs_get_io_failure_record(inode, start);
2667 if (IS_ERR(failrec))
2668 return PTR_ERR(failrec);
2671 * We will only submit repair for one sector, thus we don't need
2672 * extra validation anymore.
2674 * TODO: All those extra validation related code will be cleaned up
2677 need_validation = false;
2678 if (!btrfs_check_repairable(inode, need_validation, failrec,
2680 free_io_failure(failure_tree, tree, failrec);
2684 repair_bio = btrfs_io_bio_alloc(1);
2685 repair_io_bio = btrfs_io_bio(repair_bio);
2686 repair_bio->bi_opf = REQ_OP_READ;
2687 if (need_validation)
2688 repair_bio->bi_opf |= REQ_FAILFAST_DEV;
2689 repair_bio->bi_end_io = failed_bio->bi_end_io;
2690 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2691 repair_bio->bi_private = failed_bio->bi_private;
2693 if (failed_io_bio->csum) {
2694 const u32 csum_size = fs_info->csum_size;
2696 repair_io_bio->csum = repair_io_bio->csum_inline;
2697 memcpy(repair_io_bio->csum,
2698 failed_io_bio->csum + csum_size * icsum, csum_size);
2701 bio_add_page(repair_bio, page, failrec->len, pgoff);
2702 repair_io_bio->logical = failrec->start;
2703 repair_io_bio->iter = repair_bio->bi_iter;
2705 btrfs_debug(btrfs_sb(inode->i_sb),
2706 "repair read error: submitting new read to mirror %d, in_validation=%d",
2707 failrec->this_mirror, failrec->in_validation);
2709 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2710 failrec->bio_flags);
2712 free_io_failure(failure_tree, tree, failrec);
2713 bio_put(repair_bio);
2715 return blk_status_to_errno(status);
2718 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2720 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2722 ASSERT(page_offset(page) <= start &&
2723 start + len <= page_offset(page) + PAGE_SIZE);
2726 * For subapge metadata case, all btrfs_page_* helpers need page to
2727 * have page::private populated.
2728 * But we can have rare case where the last eb in the page is only
2729 * referred by the IO, and it gets released immedately after it's
2730 * read and verified.
2732 * This can detach the page private completely.
2733 * In that case, we can just skip the page status update completely,
2734 * as the page has no eb anymore.
2736 if (fs_info->sectorsize < PAGE_SIZE && unlikely(!PagePrivate(page))) {
2737 ASSERT(!is_data_inode(page->mapping->host));
2741 btrfs_page_set_uptodate(fs_info, page, start, len);
2743 btrfs_page_clear_uptodate(fs_info, page, start, len);
2744 btrfs_page_set_error(fs_info, page, start, len);
2747 if (fs_info->sectorsize == PAGE_SIZE)
2749 else if (is_data_inode(page->mapping->host))
2751 * For subpage data, unlock the page if we're the last reader.
2752 * For subpage metadata, page lock is not utilized for read.
2754 btrfs_subpage_end_reader(fs_info, page, start, len);
2757 static blk_status_t submit_read_repair(struct inode *inode,
2758 struct bio *failed_bio, u32 bio_offset,
2759 struct page *page, unsigned int pgoff,
2760 u64 start, u64 end, int failed_mirror,
2761 unsigned int error_bitmap,
2762 submit_bio_hook_t *submit_bio_hook)
2764 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2765 const u32 sectorsize = fs_info->sectorsize;
2766 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2770 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2772 /* We're here because we had some read errors or csum mismatch */
2773 ASSERT(error_bitmap);
2776 * We only get called on buffered IO, thus page must be mapped and bio
2777 * must not be cloned.
2779 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2781 /* Iterate through all the sectors in the range */
2782 for (i = 0; i < nr_bits; i++) {
2783 const unsigned int offset = i * sectorsize;
2784 struct extent_state *cached = NULL;
2785 bool uptodate = false;
2788 if (!(error_bitmap & (1U << i))) {
2790 * This sector has no error, just end the page read
2791 * and unlock the range.
2797 ret = btrfs_repair_one_sector(inode, failed_bio,
2798 bio_offset + offset,
2799 page, pgoff + offset, start + offset,
2800 failed_mirror, submit_bio_hook);
2803 * We have submitted the read repair, the page release
2804 * will be handled by the endio function of the
2805 * submitted repair bio.
2806 * Thus we don't need to do any thing here.
2811 * Repair failed, just record the error but still continue.
2812 * Or the remaining sectors will not be properly unlocked.
2817 end_page_read(page, uptodate, start + offset, sectorsize);
2819 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2821 start + offset + sectorsize - 1,
2822 &cached, GFP_ATOMIC);
2823 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2825 start + offset + sectorsize - 1,
2828 return errno_to_blk_status(error);
2831 /* lots and lots of room for performance fixes in the end_bio funcs */
2833 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2835 int uptodate = (err == 0);
2838 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2841 ClearPageUptodate(page);
2843 ret = err < 0 ? err : -EIO;
2844 mapping_set_error(page->mapping, ret);
2849 * after a writepage IO is done, we need to:
2850 * clear the uptodate bits on error
2851 * clear the writeback bits in the extent tree for this IO
2852 * end_page_writeback if the page has no more pending IO
2854 * Scheduling is not allowed, so the extent state tree is expected
2855 * to have one and only one object corresponding to this IO.
2857 static void end_bio_extent_writepage(struct bio *bio)
2859 int error = blk_status_to_errno(bio->bi_status);
2860 struct bio_vec *bvec;
2863 struct bvec_iter_all iter_all;
2864 bool first_bvec = true;
2866 ASSERT(!bio_flagged(bio, BIO_CLONED));
2867 bio_for_each_segment_all(bvec, bio, iter_all) {
2868 struct page *page = bvec->bv_page;
2869 struct inode *inode = page->mapping->host;
2870 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2872 /* We always issue full-page reads, but if some block
2873 * in a page fails to read, blk_update_request() will
2874 * advance bv_offset and adjust bv_len to compensate.
2875 * Print a warning for nonzero offsets, and an error
2876 * if they don't add up to a full page. */
2877 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2878 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2880 "partial page write in btrfs with offset %u and length %u",
2881 bvec->bv_offset, bvec->bv_len);
2884 "incomplete page write in btrfs with offset %u and length %u",
2885 bvec->bv_offset, bvec->bv_len);
2888 start = page_offset(page);
2889 end = start + bvec->bv_offset + bvec->bv_len - 1;
2892 btrfs_record_physical_zoned(inode, start, bio);
2896 end_extent_writepage(page, error, start, end);
2897 end_page_writeback(page);
2904 * Record previously processed extent range
2906 * For endio_readpage_release_extent() to handle a full extent range, reducing
2907 * the extent io operations.
2909 struct processed_extent {
2910 struct btrfs_inode *inode;
2911 /* Start of the range in @inode */
2913 /* End of the range in @inode */
2919 * Try to release processed extent range
2921 * May not release the extent range right now if the current range is
2922 * contiguous to processed extent.
2924 * Will release processed extent when any of @inode, @uptodate, the range is
2925 * no longer contiguous to the processed range.
2927 * Passing @inode == NULL will force processed extent to be released.
2929 static void endio_readpage_release_extent(struct processed_extent *processed,
2930 struct btrfs_inode *inode, u64 start, u64 end,
2933 struct extent_state *cached = NULL;
2934 struct extent_io_tree *tree;
2936 /* The first extent, initialize @processed */
2937 if (!processed->inode)
2941 * Contiguous to processed extent, just uptodate the end.
2943 * Several things to notice:
2945 * - bio can be merged as long as on-disk bytenr is contiguous
2946 * This means we can have page belonging to other inodes, thus need to
2947 * check if the inode still matches.
2948 * - bvec can contain range beyond current page for multi-page bvec
2949 * Thus we need to do processed->end + 1 >= start check
2951 if (processed->inode == inode && processed->uptodate == uptodate &&
2952 processed->end + 1 >= start && end >= processed->end) {
2953 processed->end = end;
2957 tree = &processed->inode->io_tree;
2959 * Now we don't have range contiguous to the processed range, release
2960 * the processed range now.
2962 if (processed->uptodate && tree->track_uptodate)
2963 set_extent_uptodate(tree, processed->start, processed->end,
2964 &cached, GFP_ATOMIC);
2965 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2969 /* Update processed to current range */
2970 processed->inode = inode;
2971 processed->start = start;
2972 processed->end = end;
2973 processed->uptodate = uptodate;
2976 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2978 ASSERT(PageLocked(page));
2979 if (fs_info->sectorsize == PAGE_SIZE)
2982 ASSERT(PagePrivate(page));
2983 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2987 * Find extent buffer for a givne bytenr.
2989 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2992 static struct extent_buffer *find_extent_buffer_readpage(
2993 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2995 struct extent_buffer *eb;
2998 * For regular sectorsize, we can use page->private to grab extent
3001 if (fs_info->sectorsize == PAGE_SIZE) {
3002 ASSERT(PagePrivate(page) && page->private);
3003 return (struct extent_buffer *)page->private;
3006 /* For subpage case, we need to lookup buffer radix tree */
3008 eb = radix_tree_lookup(&fs_info->buffer_radix,
3009 bytenr >> fs_info->sectorsize_bits);
3016 * after a readpage IO is done, we need to:
3017 * clear the uptodate bits on error
3018 * set the uptodate bits if things worked
3019 * set the page up to date if all extents in the tree are uptodate
3020 * clear the lock bit in the extent tree
3021 * unlock the page if there are no other extents locked for it
3023 * Scheduling is not allowed, so the extent state tree is expected
3024 * to have one and only one object corresponding to this IO.
3026 static void end_bio_extent_readpage(struct bio *bio)
3028 struct bio_vec *bvec;
3029 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
3030 struct extent_io_tree *tree, *failure_tree;
3031 struct processed_extent processed = { 0 };
3033 * The offset to the beginning of a bio, since one bio can never be
3034 * larger than UINT_MAX, u32 here is enough.
3039 struct bvec_iter_all iter_all;
3041 ASSERT(!bio_flagged(bio, BIO_CLONED));
3042 bio_for_each_segment_all(bvec, bio, iter_all) {
3043 bool uptodate = !bio->bi_status;
3044 struct page *page = bvec->bv_page;
3045 struct inode *inode = page->mapping->host;
3046 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3047 const u32 sectorsize = fs_info->sectorsize;
3048 unsigned int error_bitmap = (unsigned int)-1;
3053 btrfs_debug(fs_info,
3054 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3055 bio->bi_iter.bi_sector, bio->bi_status,
3056 io_bio->mirror_num);
3057 tree = &BTRFS_I(inode)->io_tree;
3058 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3061 * We always issue full-sector reads, but if some block in a
3062 * page fails to read, blk_update_request() will advance
3063 * bv_offset and adjust bv_len to compensate. Print a warning
3064 * for unaligned offsets, and an error if they don't add up to
3067 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3069 "partial page read in btrfs with offset %u and length %u",
3070 bvec->bv_offset, bvec->bv_len);
3071 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3074 "incomplete page read with offset %u and length %u",
3075 bvec->bv_offset, bvec->bv_len);
3077 start = page_offset(page) + bvec->bv_offset;
3078 end = start + bvec->bv_len - 1;
3081 mirror = io_bio->mirror_num;
3082 if (likely(uptodate)) {
3083 if (is_data_inode(inode)) {
3084 error_bitmap = btrfs_verify_data_csum(io_bio,
3085 bio_offset, page, start, end);
3088 ret = btrfs_validate_metadata_buffer(io_bio,
3089 page, start, end, mirror);
3094 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3095 failure_tree, tree, start,
3097 btrfs_ino(BTRFS_I(inode)), 0);
3100 if (likely(uptodate))
3103 if (is_data_inode(inode)) {
3105 * btrfs_submit_read_repair() will handle all the good
3106 * and bad sectors, we just continue to the next bvec.
3108 submit_read_repair(inode, bio, bio_offset, page,
3109 start - page_offset(page), start,
3110 end, mirror, error_bitmap,
3111 btrfs_submit_data_bio);
3113 ASSERT(bio_offset + len > bio_offset);
3117 struct extent_buffer *eb;
3119 eb = find_extent_buffer_readpage(fs_info, page, start);
3120 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3121 eb->read_mirror = mirror;
3122 atomic_dec(&eb->io_pages);
3123 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
3125 btree_readahead_hook(eb, -EIO);
3128 if (likely(uptodate)) {
3129 loff_t i_size = i_size_read(inode);
3130 pgoff_t end_index = i_size >> PAGE_SHIFT;
3133 * Zero out the remaining part if this range straddles
3136 * Here we should only zero the range inside the bvec,
3137 * not touch anything else.
3139 * NOTE: i_size is exclusive while end is inclusive.
3141 if (page->index == end_index && i_size <= end) {
3142 u32 zero_start = max(offset_in_page(i_size),
3143 offset_in_page(start));
3145 zero_user_segment(page, zero_start,
3146 offset_in_page(end) + 1);
3149 ASSERT(bio_offset + len > bio_offset);
3152 /* Update page status and unlock */
3153 end_page_read(page, uptodate, start, len);
3154 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3155 start, end, uptodate);
3157 /* Release the last extent */
3158 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3159 btrfs_io_bio_free_csum(io_bio);
3164 * Initialize the members up to but not including 'bio'. Use after allocating a
3165 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3166 * 'bio' because use of __GFP_ZERO is not supported.
3168 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3170 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3174 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3175 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3176 * for the appropriate container_of magic
3178 struct bio *btrfs_bio_alloc(u64 first_byte)
3182 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &btrfs_bioset);
3183 bio->bi_iter.bi_sector = first_byte >> 9;
3184 btrfs_io_bio_init(btrfs_io_bio(bio));
3188 struct bio *btrfs_bio_clone(struct bio *bio)
3190 struct btrfs_io_bio *btrfs_bio;
3193 /* Bio allocation backed by a bioset does not fail */
3194 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3195 btrfs_bio = btrfs_io_bio(new);
3196 btrfs_io_bio_init(btrfs_bio);
3197 btrfs_bio->iter = bio->bi_iter;
3201 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3205 /* Bio allocation backed by a bioset does not fail */
3206 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3207 btrfs_io_bio_init(btrfs_io_bio(bio));
3211 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
3214 struct btrfs_io_bio *btrfs_bio;
3216 /* this will never fail when it's backed by a bioset */
3217 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3220 btrfs_bio = btrfs_io_bio(bio);
3221 btrfs_io_bio_init(btrfs_bio);
3223 bio_trim(bio, offset >> 9, size >> 9);
3224 btrfs_bio->iter = bio->bi_iter;
3229 * Attempt to add a page to bio
3231 * @bio: destination bio
3232 * @page: page to add to the bio
3233 * @disk_bytenr: offset of the new bio or to check whether we are adding
3234 * a contiguous page to the previous one
3235 * @pg_offset: starting offset in the page
3236 * @size: portion of page that we want to write
3237 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3238 * @bio_flags: flags of the current bio to see if we can merge them
3239 * @return: true if page was added, false otherwise
3241 * Attempt to add a page to bio considering stripe alignment etc.
3243 * Return true if successfully page added. Otherwise, return false.
3245 static bool btrfs_bio_add_page(struct bio *bio, struct page *page,
3246 u64 disk_bytenr, unsigned int size,
3247 unsigned int pg_offset,
3248 unsigned long prev_bio_flags,
3249 unsigned long bio_flags)
3251 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3255 if (prev_bio_flags != bio_flags)
3258 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
3259 contig = bio->bi_iter.bi_sector == sector;
3261 contig = bio_end_sector(bio) == sector;
3265 if (btrfs_bio_fits_in_stripe(page, size, bio, bio_flags))
3268 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3269 struct page *first_page = bio_first_bvec_all(bio)->bv_page;
3271 if (!btrfs_bio_fits_in_ordered_extent(first_page, bio, size))
3273 ret = bio_add_zone_append_page(bio, page, size, pg_offset);
3275 ret = bio_add_page(bio, page, size, pg_offset);
3282 * @opf: bio REQ_OP_* and REQ_* flags as one value
3283 * @wbc: optional writeback control for io accounting
3284 * @page: page to add to the bio
3285 * @disk_bytenr: logical bytenr where the write will be
3286 * @size: portion of page that we want to write to
3287 * @pg_offset: offset of the new bio or to check whether we are adding
3288 * a contiguous page to the previous one
3289 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3290 * @end_io_func: end_io callback for new bio
3291 * @mirror_num: desired mirror to read/write
3292 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3293 * @bio_flags: flags of the current bio to see if we can merge them
3295 static int submit_extent_page(unsigned int opf,
3296 struct writeback_control *wbc,
3297 struct page *page, u64 disk_bytenr,
3298 size_t size, unsigned long pg_offset,
3299 struct bio **bio_ret,
3300 bio_end_io_t end_io_func,
3302 unsigned long prev_bio_flags,
3303 unsigned long bio_flags,
3304 bool force_bio_submit)
3308 size_t io_size = min_t(size_t, size, PAGE_SIZE);
3309 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3310 struct extent_io_tree *tree = &inode->io_tree;
3311 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3317 if (force_bio_submit ||
3318 !btrfs_bio_add_page(bio, page, disk_bytenr, io_size,
3319 pg_offset, prev_bio_flags, bio_flags)) {
3320 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
3328 wbc_account_cgroup_owner(wbc, page, io_size);
3333 bio = btrfs_bio_alloc(disk_bytenr);
3334 bio_add_page(bio, page, io_size, pg_offset);
3335 bio->bi_end_io = end_io_func;
3336 bio->bi_private = tree;
3337 bio->bi_write_hint = page->mapping->host->i_write_hint;
3340 struct block_device *bdev;
3342 bdev = fs_info->fs_devices->latest_bdev;
3343 bio_set_dev(bio, bdev);
3344 wbc_init_bio(wbc, bio);
3345 wbc_account_cgroup_owner(wbc, page, io_size);
3347 if (btrfs_is_zoned(fs_info) && bio_op(bio) == REQ_OP_ZONE_APPEND) {
3348 struct extent_map *em;
3349 struct map_lookup *map;
3351 em = btrfs_get_chunk_map(fs_info, disk_bytenr, io_size);
3355 map = em->map_lookup;
3356 /* We only support single profile for now */
3357 ASSERT(map->num_stripes == 1);
3358 btrfs_io_bio(bio)->device = map->stripes[0].dev;
3360 free_extent_map(em);
3368 static int attach_extent_buffer_page(struct extent_buffer *eb,
3370 struct btrfs_subpage *prealloc)
3372 struct btrfs_fs_info *fs_info = eb->fs_info;
3376 * If the page is mapped to btree inode, we should hold the private
3377 * lock to prevent race.
3378 * For cloned or dummy extent buffers, their pages are not mapped and
3379 * will not race with any other ebs.
3382 lockdep_assert_held(&page->mapping->private_lock);
3384 if (fs_info->sectorsize == PAGE_SIZE) {
3385 if (!PagePrivate(page))
3386 attach_page_private(page, eb);
3388 WARN_ON(page->private != (unsigned long)eb);
3392 /* Already mapped, just free prealloc */
3393 if (PagePrivate(page)) {
3394 btrfs_free_subpage(prealloc);
3399 /* Has preallocated memory for subpage */
3400 attach_page_private(page, prealloc);
3402 /* Do new allocation to attach subpage */
3403 ret = btrfs_attach_subpage(fs_info, page,
3404 BTRFS_SUBPAGE_METADATA);
3408 int set_page_extent_mapped(struct page *page)
3410 struct btrfs_fs_info *fs_info;
3412 ASSERT(page->mapping);
3414 if (PagePrivate(page))
3417 fs_info = btrfs_sb(page->mapping->host->i_sb);
3419 if (fs_info->sectorsize < PAGE_SIZE)
3420 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3422 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3426 void clear_page_extent_mapped(struct page *page)
3428 struct btrfs_fs_info *fs_info;
3430 ASSERT(page->mapping);
3432 if (!PagePrivate(page))
3435 fs_info = btrfs_sb(page->mapping->host->i_sb);
3436 if (fs_info->sectorsize < PAGE_SIZE)
3437 return btrfs_detach_subpage(fs_info, page);
3439 detach_page_private(page);
3442 static struct extent_map *
3443 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3444 u64 start, u64 len, struct extent_map **em_cached)
3446 struct extent_map *em;
3448 if (em_cached && *em_cached) {
3450 if (extent_map_in_tree(em) && start >= em->start &&
3451 start < extent_map_end(em)) {
3452 refcount_inc(&em->refs);
3456 free_extent_map(em);
3460 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3461 if (em_cached && !IS_ERR_OR_NULL(em)) {
3463 refcount_inc(&em->refs);
3469 * basic readpage implementation. Locked extent state structs are inserted
3470 * into the tree that are removed when the IO is done (by the end_io
3472 * XXX JDM: This needs looking at to ensure proper page locking
3473 * return 0 on success, otherwise return error
3475 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3476 struct bio **bio, unsigned long *bio_flags,
3477 unsigned int read_flags, u64 *prev_em_start)
3479 struct inode *inode = page->mapping->host;
3480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3481 u64 start = page_offset(page);
3482 const u64 end = start + PAGE_SIZE - 1;
3485 u64 last_byte = i_size_read(inode);
3488 struct extent_map *em;
3491 size_t pg_offset = 0;
3493 size_t blocksize = inode->i_sb->s_blocksize;
3494 unsigned long this_bio_flag = 0;
3495 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3497 ret = set_page_extent_mapped(page);
3499 unlock_extent(tree, start, end);
3500 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3505 if (!PageUptodate(page)) {
3506 if (cleancache_get_page(page) == 0) {
3507 BUG_ON(blocksize != PAGE_SIZE);
3508 unlock_extent(tree, start, end);
3514 if (page->index == last_byte >> PAGE_SHIFT) {
3515 size_t zero_offset = offset_in_page(last_byte);
3518 iosize = PAGE_SIZE - zero_offset;
3519 memzero_page(page, zero_offset, iosize);
3520 flush_dcache_page(page);
3523 begin_page_read(fs_info, page);
3524 while (cur <= end) {
3525 bool force_bio_submit = false;
3528 if (cur >= last_byte) {
3529 struct extent_state *cached = NULL;
3531 iosize = PAGE_SIZE - pg_offset;
3532 memzero_page(page, pg_offset, iosize);
3533 flush_dcache_page(page);
3534 set_extent_uptodate(tree, cur, cur + iosize - 1,
3536 unlock_extent_cached(tree, cur,
3537 cur + iosize - 1, &cached);
3538 end_page_read(page, true, cur, iosize);
3541 em = __get_extent_map(inode, page, pg_offset, cur,
3542 end - cur + 1, em_cached);
3543 if (IS_ERR_OR_NULL(em)) {
3544 unlock_extent(tree, cur, end);
3545 end_page_read(page, false, cur, end + 1 - cur);
3548 extent_offset = cur - em->start;
3549 BUG_ON(extent_map_end(em) <= cur);
3552 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3553 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3554 extent_set_compress_type(&this_bio_flag,
3558 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3559 cur_end = min(extent_map_end(em) - 1, end);
3560 iosize = ALIGN(iosize, blocksize);
3561 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3562 disk_bytenr = em->block_start;
3564 disk_bytenr = em->block_start + extent_offset;
3565 block_start = em->block_start;
3566 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3567 block_start = EXTENT_MAP_HOLE;
3570 * If we have a file range that points to a compressed extent
3571 * and it's followed by a consecutive file range that points
3572 * to the same compressed extent (possibly with a different
3573 * offset and/or length, so it either points to the whole extent
3574 * or only part of it), we must make sure we do not submit a
3575 * single bio to populate the pages for the 2 ranges because
3576 * this makes the compressed extent read zero out the pages
3577 * belonging to the 2nd range. Imagine the following scenario:
3580 * [0 - 8K] [8K - 24K]
3583 * points to extent X, points to extent X,
3584 * offset 4K, length of 8K offset 0, length 16K
3586 * [extent X, compressed length = 4K uncompressed length = 16K]
3588 * If the bio to read the compressed extent covers both ranges,
3589 * it will decompress extent X into the pages belonging to the
3590 * first range and then it will stop, zeroing out the remaining
3591 * pages that belong to the other range that points to extent X.
3592 * So here we make sure we submit 2 bios, one for the first
3593 * range and another one for the third range. Both will target
3594 * the same physical extent from disk, but we can't currently
3595 * make the compressed bio endio callback populate the pages
3596 * for both ranges because each compressed bio is tightly
3597 * coupled with a single extent map, and each range can have
3598 * an extent map with a different offset value relative to the
3599 * uncompressed data of our extent and different lengths. This
3600 * is a corner case so we prioritize correctness over
3601 * non-optimal behavior (submitting 2 bios for the same extent).
3603 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3604 prev_em_start && *prev_em_start != (u64)-1 &&
3605 *prev_em_start != em->start)
3606 force_bio_submit = true;
3609 *prev_em_start = em->start;
3611 free_extent_map(em);
3614 /* we've found a hole, just zero and go on */
3615 if (block_start == EXTENT_MAP_HOLE) {
3616 struct extent_state *cached = NULL;
3618 memzero_page(page, pg_offset, iosize);
3619 flush_dcache_page(page);
3621 set_extent_uptodate(tree, cur, cur + iosize - 1,
3623 unlock_extent_cached(tree, cur,
3624 cur + iosize - 1, &cached);
3625 end_page_read(page, true, cur, iosize);
3627 pg_offset += iosize;
3630 /* the get_extent function already copied into the page */
3631 if (test_range_bit(tree, cur, cur_end,
3632 EXTENT_UPTODATE, 1, NULL)) {
3633 check_page_uptodate(tree, page);
3634 unlock_extent(tree, cur, cur + iosize - 1);
3635 end_page_read(page, true, cur, iosize);
3637 pg_offset += iosize;
3640 /* we have an inline extent but it didn't get marked up
3641 * to date. Error out
3643 if (block_start == EXTENT_MAP_INLINE) {
3644 unlock_extent(tree, cur, cur + iosize - 1);
3645 end_page_read(page, false, cur, iosize);
3647 pg_offset += iosize;
3651 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3652 page, disk_bytenr, iosize,
3654 end_bio_extent_readpage, 0,
3660 *bio_flags = this_bio_flag;
3662 unlock_extent(tree, cur, cur + iosize - 1);
3663 end_page_read(page, false, cur, iosize);
3667 pg_offset += iosize;
3673 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3675 struct extent_map **em_cached,
3677 unsigned long *bio_flags,
3680 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3683 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3685 for (index = 0; index < nr_pages; index++) {
3686 btrfs_do_readpage(pages[index], em_cached, bio, bio_flags,
3687 REQ_RAHEAD, prev_em_start);
3688 put_page(pages[index]);
3692 static void update_nr_written(struct writeback_control *wbc,
3693 unsigned long nr_written)
3695 wbc->nr_to_write -= nr_written;
3699 * helper for __extent_writepage, doing all of the delayed allocation setup.
3701 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3702 * to write the page (copy into inline extent). In this case the IO has
3703 * been started and the page is already unlocked.
3705 * This returns 0 if all went well (page still locked)
3706 * This returns < 0 if there were errors (page still locked)
3708 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3709 struct page *page, struct writeback_control *wbc,
3710 u64 delalloc_start, unsigned long *nr_written)
3712 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3714 u64 delalloc_to_write = 0;
3715 u64 delalloc_end = 0;
3717 int page_started = 0;
3720 while (delalloc_end < page_end) {
3721 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3725 delalloc_start = delalloc_end + 1;
3728 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3729 delalloc_end, &page_started, nr_written, wbc);
3733 * btrfs_run_delalloc_range should return < 0 for error
3734 * but just in case, we use > 0 here meaning the IO is
3735 * started, so we don't want to return > 0 unless
3736 * things are going well.
3738 return ret < 0 ? ret : -EIO;
3741 * delalloc_end is already one less than the total length, so
3742 * we don't subtract one from PAGE_SIZE
3744 delalloc_to_write += (delalloc_end - delalloc_start +
3745 PAGE_SIZE) >> PAGE_SHIFT;
3746 delalloc_start = delalloc_end + 1;
3748 if (wbc->nr_to_write < delalloc_to_write) {
3751 if (delalloc_to_write < thresh * 2)
3752 thresh = delalloc_to_write;
3753 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3757 /* did the fill delalloc function already unlock and start
3762 * we've unlocked the page, so we can't update
3763 * the mapping's writeback index, just update
3766 wbc->nr_to_write -= *nr_written;
3774 * helper for __extent_writepage. This calls the writepage start hooks,
3775 * and does the loop to map the page into extents and bios.
3777 * We return 1 if the IO is started and the page is unlocked,
3778 * 0 if all went well (page still locked)
3779 * < 0 if there were errors (page still locked)
3781 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3783 struct writeback_control *wbc,
3784 struct extent_page_data *epd,
3786 unsigned long nr_written,
3789 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3790 struct extent_io_tree *tree = &inode->io_tree;
3791 u64 start = page_offset(page);
3792 u64 end = start + PAGE_SIZE - 1;
3796 struct extent_map *em;
3799 u32 opf = REQ_OP_WRITE;
3800 const unsigned int write_flags = wbc_to_write_flags(wbc);
3803 ret = btrfs_writepage_cow_fixup(page, start, end);
3805 /* Fixup worker will requeue */
3806 redirty_page_for_writepage(wbc, page);
3807 update_nr_written(wbc, nr_written);
3813 * we don't want to touch the inode after unlocking the page,
3814 * so we update the mapping writeback index now
3816 update_nr_written(wbc, nr_written + 1);
3818 while (cur <= end) {
3823 if (cur >= i_size) {
3824 btrfs_writepage_endio_finish_ordered(page, cur, end, 1);
3827 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3828 if (IS_ERR_OR_NULL(em)) {
3830 ret = PTR_ERR_OR_ZERO(em);
3834 extent_offset = cur - em->start;
3835 em_end = extent_map_end(em);
3836 ASSERT(cur <= em_end);
3838 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3839 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3840 block_start = em->block_start;
3841 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3842 disk_bytenr = em->block_start + extent_offset;
3844 /* Note that em_end from extent_map_end() is exclusive */
3845 iosize = min(em_end, end + 1) - cur;
3847 if (btrfs_use_zone_append(inode, em->block_start))
3848 opf = REQ_OP_ZONE_APPEND;
3850 free_extent_map(em);
3854 * compressed and inline extents are written through other
3857 if (compressed || block_start == EXTENT_MAP_HOLE ||
3858 block_start == EXTENT_MAP_INLINE) {
3862 btrfs_writepage_endio_finish_ordered(page, cur,
3863 cur + iosize - 1, 1);
3868 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3869 if (!PageWriteback(page)) {
3870 btrfs_err(inode->root->fs_info,
3871 "page %lu not writeback, cur %llu end %llu",
3872 page->index, cur, end);
3875 ret = submit_extent_page(opf | write_flags, wbc, page,
3876 disk_bytenr, iosize,
3877 cur - page_offset(page), &epd->bio,
3878 end_bio_extent_writepage,
3882 if (PageWriteback(page))
3883 end_page_writeback(page);
3894 * the writepage semantics are similar to regular writepage. extent
3895 * records are inserted to lock ranges in the tree, and as dirty areas
3896 * are found, they are marked writeback. Then the lock bits are removed
3897 * and the end_io handler clears the writeback ranges
3899 * Return 0 if everything goes well.
3900 * Return <0 for error.
3902 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3903 struct extent_page_data *epd)
3905 struct inode *inode = page->mapping->host;
3906 u64 start = page_offset(page);
3907 u64 page_end = start + PAGE_SIZE - 1;
3911 loff_t i_size = i_size_read(inode);
3912 unsigned long end_index = i_size >> PAGE_SHIFT;
3913 unsigned long nr_written = 0;
3915 trace___extent_writepage(page, inode, wbc);
3917 WARN_ON(!PageLocked(page));
3919 ClearPageError(page);
3921 pg_offset = offset_in_page(i_size);
3922 if (page->index > end_index ||
3923 (page->index == end_index && !pg_offset)) {
3924 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3929 if (page->index == end_index) {
3930 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
3931 flush_dcache_page(page);
3934 ret = set_page_extent_mapped(page);
3940 if (!epd->extent_locked) {
3941 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3949 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3956 /* make sure the mapping tag for page dirty gets cleared */
3957 set_page_writeback(page);
3958 end_page_writeback(page);
3960 if (PageError(page)) {
3961 ret = ret < 0 ? ret : -EIO;
3962 end_extent_writepage(page, ret, start, page_end);
3969 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3971 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3972 TASK_UNINTERRUPTIBLE);
3975 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3977 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3978 smp_mb__after_atomic();
3979 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3983 * Lock extent buffer status and pages for writeback.
3985 * May try to flush write bio if we can't get the lock.
3987 * Return 0 if the extent buffer doesn't need to be submitted.
3988 * (E.g. the extent buffer is not dirty)
3989 * Return >0 is the extent buffer is submitted to bio.
3990 * Return <0 if something went wrong, no page is locked.
3992 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3993 struct extent_page_data *epd)
3995 struct btrfs_fs_info *fs_info = eb->fs_info;
3996 int i, num_pages, failed_page_nr;
4000 if (!btrfs_try_tree_write_lock(eb)) {
4001 ret = flush_write_bio(epd);
4005 btrfs_tree_lock(eb);
4008 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4009 btrfs_tree_unlock(eb);
4013 ret = flush_write_bio(epd);
4019 wait_on_extent_buffer_writeback(eb);
4020 btrfs_tree_lock(eb);
4021 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4023 btrfs_tree_unlock(eb);
4028 * We need to do this to prevent races in people who check if the eb is
4029 * under IO since we can end up having no IO bits set for a short period
4032 spin_lock(&eb->refs_lock);
4033 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4034 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4035 spin_unlock(&eb->refs_lock);
4036 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4037 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4039 fs_info->dirty_metadata_batch);
4042 spin_unlock(&eb->refs_lock);
4045 btrfs_tree_unlock(eb);
4048 * Either we don't need to submit any tree block, or we're submitting
4050 * Subpage metadata doesn't use page locking at all, so we can skip
4053 if (!ret || fs_info->sectorsize < PAGE_SIZE)
4056 num_pages = num_extent_pages(eb);
4057 for (i = 0; i < num_pages; i++) {
4058 struct page *p = eb->pages[i];
4060 if (!trylock_page(p)) {
4064 err = flush_write_bio(epd);
4078 /* Unlock already locked pages */
4079 for (i = 0; i < failed_page_nr; i++)
4080 unlock_page(eb->pages[i]);
4082 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
4083 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
4084 * be made and undo everything done before.
4086 btrfs_tree_lock(eb);
4087 spin_lock(&eb->refs_lock);
4088 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4089 end_extent_buffer_writeback(eb);
4090 spin_unlock(&eb->refs_lock);
4091 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4092 fs_info->dirty_metadata_batch);
4093 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4094 btrfs_tree_unlock(eb);
4098 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4100 struct btrfs_fs_info *fs_info = eb->fs_info;
4102 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4103 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4107 * If we error out, we should add back the dirty_metadata_bytes
4108 * to make it consistent.
4110 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4111 eb->len, fs_info->dirty_metadata_batch);
4114 * If writeback for a btree extent that doesn't belong to a log tree
4115 * failed, increment the counter transaction->eb_write_errors.
4116 * We do this because while the transaction is running and before it's
4117 * committing (when we call filemap_fdata[write|wait]_range against
4118 * the btree inode), we might have
4119 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4120 * returns an error or an error happens during writeback, when we're
4121 * committing the transaction we wouldn't know about it, since the pages
4122 * can be no longer dirty nor marked anymore for writeback (if a
4123 * subsequent modification to the extent buffer didn't happen before the
4124 * transaction commit), which makes filemap_fdata[write|wait]_range not
4125 * able to find the pages tagged with SetPageError at transaction
4126 * commit time. So if this happens we must abort the transaction,
4127 * otherwise we commit a super block with btree roots that point to
4128 * btree nodes/leafs whose content on disk is invalid - either garbage
4129 * or the content of some node/leaf from a past generation that got
4130 * cowed or deleted and is no longer valid.
4132 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4133 * not be enough - we need to distinguish between log tree extents vs
4134 * non-log tree extents, and the next filemap_fdatawait_range() call
4135 * will catch and clear such errors in the mapping - and that call might
4136 * be from a log sync and not from a transaction commit. Also, checking
4137 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4138 * not done and would not be reliable - the eb might have been released
4139 * from memory and reading it back again means that flag would not be
4140 * set (since it's a runtime flag, not persisted on disk).
4142 * Using the flags below in the btree inode also makes us achieve the
4143 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4144 * writeback for all dirty pages and before filemap_fdatawait_range()
4145 * is called, the writeback for all dirty pages had already finished
4146 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4147 * filemap_fdatawait_range() would return success, as it could not know
4148 * that writeback errors happened (the pages were no longer tagged for
4151 switch (eb->log_index) {
4153 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4156 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4159 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4162 BUG(); /* unexpected, logic error */
4167 * The endio specific version which won't touch any unsafe spinlock in endio
4170 static struct extent_buffer *find_extent_buffer_nolock(
4171 struct btrfs_fs_info *fs_info, u64 start)
4173 struct extent_buffer *eb;
4176 eb = radix_tree_lookup(&fs_info->buffer_radix,
4177 start >> fs_info->sectorsize_bits);
4178 if (eb && atomic_inc_not_zero(&eb->refs)) {
4187 * The endio function for subpage extent buffer write.
4189 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4190 * after all extent buffers in the page has finished their writeback.
4192 static void end_bio_subpage_eb_writepage(struct btrfs_fs_info *fs_info,
4195 struct bio_vec *bvec;
4196 struct bvec_iter_all iter_all;
4198 ASSERT(!bio_flagged(bio, BIO_CLONED));
4199 bio_for_each_segment_all(bvec, bio, iter_all) {
4200 struct page *page = bvec->bv_page;
4201 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4202 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4203 u64 cur_bytenr = bvec_start;
4205 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4207 /* Iterate through all extent buffers in the range */
4208 while (cur_bytenr <= bvec_end) {
4209 struct extent_buffer *eb;
4213 * Here we can't use find_extent_buffer(), as it may
4214 * try to lock eb->refs_lock, which is not safe in endio
4217 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4220 cur_bytenr = eb->start + eb->len;
4222 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4223 done = atomic_dec_and_test(&eb->io_pages);
4226 if (bio->bi_status ||
4227 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4228 ClearPageUptodate(page);
4229 set_btree_ioerr(page, eb);
4232 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4234 end_extent_buffer_writeback(eb);
4236 * free_extent_buffer() will grab spinlock which is not
4237 * safe in endio context. Thus here we manually dec
4240 atomic_dec(&eb->refs);
4246 static void end_bio_extent_buffer_writepage(struct bio *bio)
4248 struct btrfs_fs_info *fs_info;
4249 struct bio_vec *bvec;
4250 struct extent_buffer *eb;
4252 struct bvec_iter_all iter_all;
4254 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4255 if (fs_info->sectorsize < PAGE_SIZE)
4256 return end_bio_subpage_eb_writepage(fs_info, bio);
4258 ASSERT(!bio_flagged(bio, BIO_CLONED));
4259 bio_for_each_segment_all(bvec, bio, iter_all) {
4260 struct page *page = bvec->bv_page;
4262 eb = (struct extent_buffer *)page->private;
4264 done = atomic_dec_and_test(&eb->io_pages);
4266 if (bio->bi_status ||
4267 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4268 ClearPageUptodate(page);
4269 set_btree_ioerr(page, eb);
4272 end_page_writeback(page);
4277 end_extent_buffer_writeback(eb);
4284 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4285 * Page locking is only utilized at minimum to keep the VMM code happy.
4287 * Caller should still call write_one_eb() other than this function directly.
4288 * As write_one_eb() has extra preparation before submitting the extent buffer.
4290 static int write_one_subpage_eb(struct extent_buffer *eb,
4291 struct writeback_control *wbc,
4292 struct extent_page_data *epd)
4294 struct btrfs_fs_info *fs_info = eb->fs_info;
4295 struct page *page = eb->pages[0];
4296 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4297 bool no_dirty_ebs = false;
4300 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4302 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4304 /* Check if this is the last dirty bit to update nr_written */
4305 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4306 eb->start, eb->len);
4308 clear_page_dirty_for_io(page);
4310 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc, page,
4311 eb->start, eb->len, eb->start - page_offset(page),
4312 &epd->bio, end_bio_extent_buffer_writepage, 0, 0, 0,
4315 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4316 set_btree_ioerr(page, eb);
4319 if (atomic_dec_and_test(&eb->io_pages))
4320 end_extent_buffer_writeback(eb);
4325 * Submission finished without problem, if no range of the page is
4326 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4329 update_nr_written(wbc, 1);
4333 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4334 struct writeback_control *wbc,
4335 struct extent_page_data *epd)
4337 u64 disk_bytenr = eb->start;
4340 unsigned long start, end;
4341 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4344 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4345 num_pages = num_extent_pages(eb);
4346 atomic_set(&eb->io_pages, num_pages);
4348 /* set btree blocks beyond nritems with 0 to avoid stale content. */
4349 nritems = btrfs_header_nritems(eb);
4350 if (btrfs_header_level(eb) > 0) {
4351 end = btrfs_node_key_ptr_offset(nritems);
4353 memzero_extent_buffer(eb, end, eb->len - end);
4357 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4359 start = btrfs_item_nr_offset(nritems);
4360 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4361 memzero_extent_buffer(eb, start, end - start);
4364 if (eb->fs_info->sectorsize < PAGE_SIZE)
4365 return write_one_subpage_eb(eb, wbc, epd);
4367 for (i = 0; i < num_pages; i++) {
4368 struct page *p = eb->pages[i];
4370 clear_page_dirty_for_io(p);
4371 set_page_writeback(p);
4372 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4373 p, disk_bytenr, PAGE_SIZE, 0,
4375 end_bio_extent_buffer_writepage,
4378 set_btree_ioerr(p, eb);
4379 if (PageWriteback(p))
4380 end_page_writeback(p);
4381 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4382 end_extent_buffer_writeback(eb);
4386 disk_bytenr += PAGE_SIZE;
4387 update_nr_written(wbc, 1);
4391 if (unlikely(ret)) {
4392 for (; i < num_pages; i++) {
4393 struct page *p = eb->pages[i];
4394 clear_page_dirty_for_io(p);
4403 * Submit one subpage btree page.
4405 * The main difference to submit_eb_page() is:
4407 * For subpage, we don't rely on page locking at all.
4410 * We only flush bio if we may be unable to fit current extent buffers into
4413 * Return >=0 for the number of submitted extent buffers.
4414 * Return <0 for fatal error.
4416 static int submit_eb_subpage(struct page *page,
4417 struct writeback_control *wbc,
4418 struct extent_page_data *epd)
4420 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4422 u64 page_start = page_offset(page);
4424 const int nbits = BTRFS_SUBPAGE_BITMAP_SIZE;
4425 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4428 /* Lock and write each dirty extent buffers in the range */
4429 while (bit_start < nbits) {
4430 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4431 struct extent_buffer *eb;
4432 unsigned long flags;
4436 * Take private lock to ensure the subpage won't be detached
4439 spin_lock(&page->mapping->private_lock);
4440 if (!PagePrivate(page)) {
4441 spin_unlock(&page->mapping->private_lock);
4444 spin_lock_irqsave(&subpage->lock, flags);
4445 if (!((1 << bit_start) & subpage->dirty_bitmap)) {
4446 spin_unlock_irqrestore(&subpage->lock, flags);
4447 spin_unlock(&page->mapping->private_lock);
4452 start = page_start + bit_start * fs_info->sectorsize;
4453 bit_start += sectors_per_node;
4456 * Here we just want to grab the eb without touching extra
4457 * spin locks, so call find_extent_buffer_nolock().
4459 eb = find_extent_buffer_nolock(fs_info, start);
4460 spin_unlock_irqrestore(&subpage->lock, flags);
4461 spin_unlock(&page->mapping->private_lock);
4464 * The eb has already reached 0 refs thus find_extent_buffer()
4465 * doesn't return it. We don't need to write back such eb
4471 ret = lock_extent_buffer_for_io(eb, epd);
4473 free_extent_buffer(eb);
4477 free_extent_buffer(eb);
4480 ret = write_one_eb(eb, wbc, epd);
4481 free_extent_buffer(eb);
4489 /* We hit error, end bio for the submitted extent buffers */
4490 end_write_bio(epd, ret);
4495 * Submit all page(s) of one extent buffer.
4497 * @page: the page of one extent buffer
4498 * @eb_context: to determine if we need to submit this page, if current page
4499 * belongs to this eb, we don't need to submit
4501 * The caller should pass each page in their bytenr order, and here we use
4502 * @eb_context to determine if we have submitted pages of one extent buffer.
4504 * If we have, we just skip until we hit a new page that doesn't belong to
4505 * current @eb_context.
4507 * If not, we submit all the page(s) of the extent buffer.
4509 * Return >0 if we have submitted the extent buffer successfully.
4510 * Return 0 if we don't need to submit the page, as it's already submitted by
4512 * Return <0 for fatal error.
4514 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4515 struct extent_page_data *epd,
4516 struct extent_buffer **eb_context)
4518 struct address_space *mapping = page->mapping;
4519 struct btrfs_block_group *cache = NULL;
4520 struct extent_buffer *eb;
4523 if (!PagePrivate(page))
4526 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
4527 return submit_eb_subpage(page, wbc, epd);
4529 spin_lock(&mapping->private_lock);
4530 if (!PagePrivate(page)) {
4531 spin_unlock(&mapping->private_lock);
4535 eb = (struct extent_buffer *)page->private;
4538 * Shouldn't happen and normally this would be a BUG_ON but no point
4539 * crashing the machine for something we can survive anyway.
4542 spin_unlock(&mapping->private_lock);
4546 if (eb == *eb_context) {
4547 spin_unlock(&mapping->private_lock);
4550 ret = atomic_inc_not_zero(&eb->refs);
4551 spin_unlock(&mapping->private_lock);
4555 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4557 * If for_sync, this hole will be filled with
4558 * trasnsaction commit.
4560 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4564 free_extent_buffer(eb);
4570 ret = lock_extent_buffer_for_io(eb, epd);
4572 btrfs_revert_meta_write_pointer(cache, eb);
4574 btrfs_put_block_group(cache);
4575 free_extent_buffer(eb);
4579 btrfs_put_block_group(cache);
4580 ret = write_one_eb(eb, wbc, epd);
4581 free_extent_buffer(eb);
4587 int btree_write_cache_pages(struct address_space *mapping,
4588 struct writeback_control *wbc)
4590 struct extent_buffer *eb_context = NULL;
4591 struct extent_page_data epd = {
4594 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4596 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4599 int nr_to_write_done = 0;
4600 struct pagevec pvec;
4603 pgoff_t end; /* Inclusive */
4607 pagevec_init(&pvec);
4608 if (wbc->range_cyclic) {
4609 index = mapping->writeback_index; /* Start from prev offset */
4612 * Start from the beginning does not need to cycle over the
4613 * range, mark it as scanned.
4615 scanned = (index == 0);
4617 index = wbc->range_start >> PAGE_SHIFT;
4618 end = wbc->range_end >> PAGE_SHIFT;
4621 if (wbc->sync_mode == WB_SYNC_ALL)
4622 tag = PAGECACHE_TAG_TOWRITE;
4624 tag = PAGECACHE_TAG_DIRTY;
4625 btrfs_zoned_meta_io_lock(fs_info);
4627 if (wbc->sync_mode == WB_SYNC_ALL)
4628 tag_pages_for_writeback(mapping, index, end);
4629 while (!done && !nr_to_write_done && (index <= end) &&
4630 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4634 for (i = 0; i < nr_pages; i++) {
4635 struct page *page = pvec.pages[i];
4637 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4646 * the filesystem may choose to bump up nr_to_write.
4647 * We have to make sure to honor the new nr_to_write
4650 nr_to_write_done = wbc->nr_to_write <= 0;
4652 pagevec_release(&pvec);
4655 if (!scanned && !done) {
4657 * We hit the last page and there is more work to be done: wrap
4658 * back to the start of the file
4665 end_write_bio(&epd, ret);
4669 * If something went wrong, don't allow any metadata write bio to be
4672 * This would prevent use-after-free if we had dirty pages not
4673 * cleaned up, which can still happen by fuzzed images.
4676 * Allowing existing tree block to be allocated for other trees.
4678 * - Log tree operations
4679 * Exiting tree blocks get allocated to log tree, bumps its
4680 * generation, then get cleaned in tree re-balance.
4681 * Such tree block will not be written back, since it's clean,
4682 * thus no WRITTEN flag set.
4683 * And after log writes back, this tree block is not traced by
4684 * any dirty extent_io_tree.
4686 * - Offending tree block gets re-dirtied from its original owner
4687 * Since it has bumped generation, no WRITTEN flag, it can be
4688 * reused without COWing. This tree block will not be traced
4689 * by btrfs_transaction::dirty_pages.
4691 * Now such dirty tree block will not be cleaned by any dirty
4692 * extent io tree. Thus we don't want to submit such wild eb
4693 * if the fs already has error.
4695 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4696 ret = flush_write_bio(&epd);
4699 end_write_bio(&epd, ret);
4702 btrfs_zoned_meta_io_unlock(fs_info);
4707 * Walk the list of dirty pages of the given address space and write all of them.
4709 * @mapping: address space structure to write
4710 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4711 * @epd: holds context for the write, namely the bio
4713 * If a page is already under I/O, write_cache_pages() skips it, even
4714 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4715 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4716 * and msync() need to guarantee that all the data which was dirty at the time
4717 * the call was made get new I/O started against them. If wbc->sync_mode is
4718 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4719 * existing IO to complete.
4721 static int extent_write_cache_pages(struct address_space *mapping,
4722 struct writeback_control *wbc,
4723 struct extent_page_data *epd)
4725 struct inode *inode = mapping->host;
4728 int nr_to_write_done = 0;
4729 struct pagevec pvec;
4732 pgoff_t end; /* Inclusive */
4734 int range_whole = 0;
4739 * We have to hold onto the inode so that ordered extents can do their
4740 * work when the IO finishes. The alternative to this is failing to add
4741 * an ordered extent if the igrab() fails there and that is a huge pain
4742 * to deal with, so instead just hold onto the inode throughout the
4743 * writepages operation. If it fails here we are freeing up the inode
4744 * anyway and we'd rather not waste our time writing out stuff that is
4745 * going to be truncated anyway.
4750 pagevec_init(&pvec);
4751 if (wbc->range_cyclic) {
4752 index = mapping->writeback_index; /* Start from prev offset */
4755 * Start from the beginning does not need to cycle over the
4756 * range, mark it as scanned.
4758 scanned = (index == 0);
4760 index = wbc->range_start >> PAGE_SHIFT;
4761 end = wbc->range_end >> PAGE_SHIFT;
4762 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4768 * We do the tagged writepage as long as the snapshot flush bit is set
4769 * and we are the first one who do the filemap_flush() on this inode.
4771 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4772 * not race in and drop the bit.
4774 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4775 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4776 &BTRFS_I(inode)->runtime_flags))
4777 wbc->tagged_writepages = 1;
4779 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4780 tag = PAGECACHE_TAG_TOWRITE;
4782 tag = PAGECACHE_TAG_DIRTY;
4784 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4785 tag_pages_for_writeback(mapping, index, end);
4787 while (!done && !nr_to_write_done && (index <= end) &&
4788 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4789 &index, end, tag))) {
4792 for (i = 0; i < nr_pages; i++) {
4793 struct page *page = pvec.pages[i];
4795 done_index = page->index + 1;
4797 * At this point we hold neither the i_pages lock nor
4798 * the page lock: the page may be truncated or
4799 * invalidated (changing page->mapping to NULL),
4800 * or even swizzled back from swapper_space to
4801 * tmpfs file mapping
4803 if (!trylock_page(page)) {
4804 ret = flush_write_bio(epd);
4809 if (unlikely(page->mapping != mapping)) {
4814 if (wbc->sync_mode != WB_SYNC_NONE) {
4815 if (PageWriteback(page)) {
4816 ret = flush_write_bio(epd);
4819 wait_on_page_writeback(page);
4822 if (PageWriteback(page) ||
4823 !clear_page_dirty_for_io(page)) {
4828 ret = __extent_writepage(page, wbc, epd);
4835 * the filesystem may choose to bump up nr_to_write.
4836 * We have to make sure to honor the new nr_to_write
4839 nr_to_write_done = wbc->nr_to_write <= 0;
4841 pagevec_release(&pvec);
4844 if (!scanned && !done) {
4846 * We hit the last page and there is more work to be done: wrap
4847 * back to the start of the file
4853 * If we're looping we could run into a page that is locked by a
4854 * writer and that writer could be waiting on writeback for a
4855 * page in our current bio, and thus deadlock, so flush the
4858 ret = flush_write_bio(epd);
4863 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4864 mapping->writeback_index = done_index;
4866 btrfs_add_delayed_iput(inode);
4870 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4873 struct extent_page_data epd = {
4876 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4879 ret = __extent_writepage(page, wbc, &epd);
4882 end_write_bio(&epd, ret);
4886 ret = flush_write_bio(&epd);
4891 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4895 struct address_space *mapping = inode->i_mapping;
4897 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4900 struct extent_page_data epd = {
4903 .sync_io = mode == WB_SYNC_ALL,
4905 struct writeback_control wbc_writepages = {
4907 .nr_to_write = nr_pages * 2,
4908 .range_start = start,
4909 .range_end = end + 1,
4910 /* We're called from an async helper function */
4911 .punt_to_cgroup = 1,
4912 .no_cgroup_owner = 1,
4915 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
4916 while (start <= end) {
4917 page = find_get_page(mapping, start >> PAGE_SHIFT);
4918 if (clear_page_dirty_for_io(page))
4919 ret = __extent_writepage(page, &wbc_writepages, &epd);
4921 btrfs_writepage_endio_finish_ordered(page, start,
4922 start + PAGE_SIZE - 1, 1);
4931 ret = flush_write_bio(&epd);
4933 end_write_bio(&epd, ret);
4935 wbc_detach_inode(&wbc_writepages);
4939 int extent_writepages(struct address_space *mapping,
4940 struct writeback_control *wbc)
4943 struct extent_page_data epd = {
4946 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4949 ret = extent_write_cache_pages(mapping, wbc, &epd);
4952 end_write_bio(&epd, ret);
4955 ret = flush_write_bio(&epd);
4959 void extent_readahead(struct readahead_control *rac)
4961 struct bio *bio = NULL;
4962 unsigned long bio_flags = 0;
4963 struct page *pagepool[16];
4964 struct extent_map *em_cached = NULL;
4965 u64 prev_em_start = (u64)-1;
4968 while ((nr = readahead_page_batch(rac, pagepool))) {
4969 u64 contig_start = readahead_pos(rac);
4970 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
4972 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4973 &em_cached, &bio, &bio_flags, &prev_em_start);
4977 free_extent_map(em_cached);
4980 if (submit_one_bio(bio, 0, bio_flags))
4986 * basic invalidatepage code, this waits on any locked or writeback
4987 * ranges corresponding to the page, and then deletes any extent state
4988 * records from the tree
4990 int extent_invalidatepage(struct extent_io_tree *tree,
4991 struct page *page, unsigned long offset)
4993 struct extent_state *cached_state = NULL;
4994 u64 start = page_offset(page);
4995 u64 end = start + PAGE_SIZE - 1;
4996 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4998 /* This function is only called for the btree inode */
4999 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5001 start += ALIGN(offset, blocksize);
5005 lock_extent_bits(tree, start, end, &cached_state);
5006 wait_on_page_writeback(page);
5009 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5010 * so here we only need to unlock the extent range to free any
5011 * existing extent state.
5013 unlock_extent_cached(tree, start, end, &cached_state);
5018 * a helper for releasepage, this tests for areas of the page that
5019 * are locked or under IO and drops the related state bits if it is safe
5022 static int try_release_extent_state(struct extent_io_tree *tree,
5023 struct page *page, gfp_t mask)
5025 u64 start = page_offset(page);
5026 u64 end = start + PAGE_SIZE - 1;
5029 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5033 * At this point we can safely clear everything except the
5034 * locked bit, the nodatasum bit and the delalloc new bit.
5035 * The delalloc new bit will be cleared by ordered extent
5038 ret = __clear_extent_bit(tree, start, end,
5039 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5040 0, 0, NULL, mask, NULL);
5042 /* if clear_extent_bit failed for enomem reasons,
5043 * we can't allow the release to continue.
5054 * a helper for releasepage. As long as there are no locked extents
5055 * in the range corresponding to the page, both state records and extent
5056 * map records are removed
5058 int try_release_extent_mapping(struct page *page, gfp_t mask)
5060 struct extent_map *em;
5061 u64 start = page_offset(page);
5062 u64 end = start + PAGE_SIZE - 1;
5063 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5064 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5065 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5067 if (gfpflags_allow_blocking(mask) &&
5068 page->mapping->host->i_size > SZ_16M) {
5070 while (start <= end) {
5071 struct btrfs_fs_info *fs_info;
5074 len = end - start + 1;
5075 write_lock(&map->lock);
5076 em = lookup_extent_mapping(map, start, len);
5078 write_unlock(&map->lock);
5081 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5082 em->start != start) {
5083 write_unlock(&map->lock);
5084 free_extent_map(em);
5087 if (test_range_bit(tree, em->start,
5088 extent_map_end(em) - 1,
5089 EXTENT_LOCKED, 0, NULL))
5092 * If it's not in the list of modified extents, used
5093 * by a fast fsync, we can remove it. If it's being
5094 * logged we can safely remove it since fsync took an
5095 * extra reference on the em.
5097 if (list_empty(&em->list) ||
5098 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5101 * If it's in the list of modified extents, remove it
5102 * only if its generation is older then the current one,
5103 * in which case we don't need it for a fast fsync.
5104 * Otherwise don't remove it, we could be racing with an
5105 * ongoing fast fsync that could miss the new extent.
5107 fs_info = btrfs_inode->root->fs_info;
5108 spin_lock(&fs_info->trans_lock);
5109 cur_gen = fs_info->generation;
5110 spin_unlock(&fs_info->trans_lock);
5111 if (em->generation >= cur_gen)
5115 * We only remove extent maps that are not in the list of
5116 * modified extents or that are in the list but with a
5117 * generation lower then the current generation, so there
5118 * is no need to set the full fsync flag on the inode (it
5119 * hurts the fsync performance for workloads with a data
5120 * size that exceeds or is close to the system's memory).
5122 remove_extent_mapping(map, em);
5123 /* once for the rb tree */
5124 free_extent_map(em);
5126 start = extent_map_end(em);
5127 write_unlock(&map->lock);
5130 free_extent_map(em);
5132 cond_resched(); /* Allow large-extent preemption. */
5135 return try_release_extent_state(tree, page, mask);
5139 * helper function for fiemap, which doesn't want to see any holes.
5140 * This maps until we find something past 'last'
5142 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5143 u64 offset, u64 last)
5145 u64 sectorsize = btrfs_inode_sectorsize(inode);
5146 struct extent_map *em;
5153 len = last - offset;
5156 len = ALIGN(len, sectorsize);
5157 em = btrfs_get_extent_fiemap(inode, offset, len);
5158 if (IS_ERR_OR_NULL(em))
5161 /* if this isn't a hole return it */
5162 if (em->block_start != EXTENT_MAP_HOLE)
5165 /* this is a hole, advance to the next extent */
5166 offset = extent_map_end(em);
5167 free_extent_map(em);
5175 * To cache previous fiemap extent
5177 * Will be used for merging fiemap extent
5179 struct fiemap_cache {
5188 * Helper to submit fiemap extent.
5190 * Will try to merge current fiemap extent specified by @offset, @phys,
5191 * @len and @flags with cached one.
5192 * And only when we fails to merge, cached one will be submitted as
5195 * Return value is the same as fiemap_fill_next_extent().
5197 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5198 struct fiemap_cache *cache,
5199 u64 offset, u64 phys, u64 len, u32 flags)
5207 * Sanity check, extent_fiemap() should have ensured that new
5208 * fiemap extent won't overlap with cached one.
5211 * NOTE: Physical address can overlap, due to compression
5213 if (cache->offset + cache->len > offset) {
5219 * Only merges fiemap extents if
5220 * 1) Their logical addresses are continuous
5222 * 2) Their physical addresses are continuous
5223 * So truly compressed (physical size smaller than logical size)
5224 * extents won't get merged with each other
5226 * 3) Share same flags except FIEMAP_EXTENT_LAST
5227 * So regular extent won't get merged with prealloc extent
5229 if (cache->offset + cache->len == offset &&
5230 cache->phys + cache->len == phys &&
5231 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5232 (flags & ~FIEMAP_EXTENT_LAST)) {
5234 cache->flags |= flags;
5235 goto try_submit_last;
5238 /* Not mergeable, need to submit cached one */
5239 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5240 cache->len, cache->flags);
5241 cache->cached = false;
5245 cache->cached = true;
5246 cache->offset = offset;
5249 cache->flags = flags;
5251 if (cache->flags & FIEMAP_EXTENT_LAST) {
5252 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5253 cache->phys, cache->len, cache->flags);
5254 cache->cached = false;
5260 * Emit last fiemap cache
5262 * The last fiemap cache may still be cached in the following case:
5264 * |<- Fiemap range ->|
5265 * |<------------ First extent ----------->|
5267 * In this case, the first extent range will be cached but not emitted.
5268 * So we must emit it before ending extent_fiemap().
5270 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5271 struct fiemap_cache *cache)
5278 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5279 cache->len, cache->flags);
5280 cache->cached = false;
5286 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5291 u64 max = start + len;
5295 u64 last_for_get_extent = 0;
5297 u64 isize = i_size_read(&inode->vfs_inode);
5298 struct btrfs_key found_key;
5299 struct extent_map *em = NULL;
5300 struct extent_state *cached_state = NULL;
5301 struct btrfs_path *path;
5302 struct btrfs_root *root = inode->root;
5303 struct fiemap_cache cache = { 0 };
5304 struct ulist *roots;
5305 struct ulist *tmp_ulist;
5314 path = btrfs_alloc_path();
5318 roots = ulist_alloc(GFP_KERNEL);
5319 tmp_ulist = ulist_alloc(GFP_KERNEL);
5320 if (!roots || !tmp_ulist) {
5322 goto out_free_ulist;
5326 * We can't initialize that to 'start' as this could miss extents due
5327 * to extent item merging
5330 start = round_down(start, btrfs_inode_sectorsize(inode));
5331 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5334 * lookup the last file extent. We're not using i_size here
5335 * because there might be preallocation past i_size
5337 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5340 goto out_free_ulist;
5348 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5349 found_type = found_key.type;
5351 /* No extents, but there might be delalloc bits */
5352 if (found_key.objectid != btrfs_ino(inode) ||
5353 found_type != BTRFS_EXTENT_DATA_KEY) {
5354 /* have to trust i_size as the end */
5356 last_for_get_extent = isize;
5359 * remember the start of the last extent. There are a
5360 * bunch of different factors that go into the length of the
5361 * extent, so its much less complex to remember where it started
5363 last = found_key.offset;
5364 last_for_get_extent = last + 1;
5366 btrfs_release_path(path);
5369 * we might have some extents allocated but more delalloc past those
5370 * extents. so, we trust isize unless the start of the last extent is
5375 last_for_get_extent = isize;
5378 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5381 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5390 u64 offset_in_extent = 0;
5392 /* break if the extent we found is outside the range */
5393 if (em->start >= max || extent_map_end(em) < off)
5397 * get_extent may return an extent that starts before our
5398 * requested range. We have to make sure the ranges
5399 * we return to fiemap always move forward and don't
5400 * overlap, so adjust the offsets here
5402 em_start = max(em->start, off);
5405 * record the offset from the start of the extent
5406 * for adjusting the disk offset below. Only do this if the
5407 * extent isn't compressed since our in ram offset may be past
5408 * what we have actually allocated on disk.
5410 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5411 offset_in_extent = em_start - em->start;
5412 em_end = extent_map_end(em);
5413 em_len = em_end - em_start;
5415 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5416 disko = em->block_start + offset_in_extent;
5421 * bump off for our next call to get_extent
5423 off = extent_map_end(em);
5427 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5429 flags |= FIEMAP_EXTENT_LAST;
5430 } else if (em->block_start == EXTENT_MAP_INLINE) {
5431 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5432 FIEMAP_EXTENT_NOT_ALIGNED);
5433 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5434 flags |= (FIEMAP_EXTENT_DELALLOC |
5435 FIEMAP_EXTENT_UNKNOWN);
5436 } else if (fieinfo->fi_extents_max) {
5437 u64 bytenr = em->block_start -
5438 (em->start - em->orig_start);
5441 * As btrfs supports shared space, this information
5442 * can be exported to userspace tools via
5443 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5444 * then we're just getting a count and we can skip the
5447 ret = btrfs_check_shared(root, btrfs_ino(inode),
5448 bytenr, roots, tmp_ulist);
5452 flags |= FIEMAP_EXTENT_SHARED;
5455 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5456 flags |= FIEMAP_EXTENT_ENCODED;
5457 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5458 flags |= FIEMAP_EXTENT_UNWRITTEN;
5460 free_extent_map(em);
5462 if ((em_start >= last) || em_len == (u64)-1 ||
5463 (last == (u64)-1 && isize <= em_end)) {
5464 flags |= FIEMAP_EXTENT_LAST;
5468 /* now scan forward to see if this is really the last extent. */
5469 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5475 flags |= FIEMAP_EXTENT_LAST;
5478 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5488 ret = emit_last_fiemap_cache(fieinfo, &cache);
5489 free_extent_map(em);
5491 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5495 btrfs_free_path(path);
5497 ulist_free(tmp_ulist);
5501 static void __free_extent_buffer(struct extent_buffer *eb)
5503 kmem_cache_free(extent_buffer_cache, eb);
5506 int extent_buffer_under_io(const struct extent_buffer *eb)
5508 return (atomic_read(&eb->io_pages) ||
5509 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5510 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5513 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5515 struct btrfs_subpage *subpage;
5517 lockdep_assert_held(&page->mapping->private_lock);
5519 if (PagePrivate(page)) {
5520 subpage = (struct btrfs_subpage *)page->private;
5521 if (atomic_read(&subpage->eb_refs))
5527 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5529 struct btrfs_fs_info *fs_info = eb->fs_info;
5530 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5533 * For mapped eb, we're going to change the page private, which should
5534 * be done under the private_lock.
5537 spin_lock(&page->mapping->private_lock);
5539 if (!PagePrivate(page)) {
5541 spin_unlock(&page->mapping->private_lock);
5545 if (fs_info->sectorsize == PAGE_SIZE) {
5547 * We do this since we'll remove the pages after we've
5548 * removed the eb from the radix tree, so we could race
5549 * and have this page now attached to the new eb. So
5550 * only clear page_private if it's still connected to
5553 if (PagePrivate(page) &&
5554 page->private == (unsigned long)eb) {
5555 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5556 BUG_ON(PageDirty(page));
5557 BUG_ON(PageWriteback(page));
5559 * We need to make sure we haven't be attached
5562 detach_page_private(page);
5565 spin_unlock(&page->mapping->private_lock);
5570 * For subpage, we can have dummy eb with page private. In this case,
5571 * we can directly detach the private as such page is only attached to
5572 * one dummy eb, no sharing.
5575 btrfs_detach_subpage(fs_info, page);
5579 btrfs_page_dec_eb_refs(fs_info, page);
5582 * We can only detach the page private if there are no other ebs in the
5585 if (!page_range_has_eb(fs_info, page))
5586 btrfs_detach_subpage(fs_info, page);
5588 spin_unlock(&page->mapping->private_lock);
5591 /* Release all pages attached to the extent buffer */
5592 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5597 ASSERT(!extent_buffer_under_io(eb));
5599 num_pages = num_extent_pages(eb);
5600 for (i = 0; i < num_pages; i++) {
5601 struct page *page = eb->pages[i];
5606 detach_extent_buffer_page(eb, page);
5608 /* One for when we allocated the page */
5614 * Helper for releasing the extent buffer.
5616 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5618 btrfs_release_extent_buffer_pages(eb);
5619 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5620 __free_extent_buffer(eb);
5623 static struct extent_buffer *
5624 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5627 struct extent_buffer *eb = NULL;
5629 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5632 eb->fs_info = fs_info;
5634 init_rwsem(&eb->lock);
5636 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5637 &fs_info->allocated_ebs);
5638 INIT_LIST_HEAD(&eb->release_list);
5640 spin_lock_init(&eb->refs_lock);
5641 atomic_set(&eb->refs, 1);
5642 atomic_set(&eb->io_pages, 0);
5644 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5649 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5653 struct extent_buffer *new;
5654 int num_pages = num_extent_pages(src);
5656 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5661 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5662 * btrfs_release_extent_buffer() have different behavior for
5663 * UNMAPPED subpage extent buffer.
5665 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5667 for (i = 0; i < num_pages; i++) {
5670 p = alloc_page(GFP_NOFS);
5672 btrfs_release_extent_buffer(new);
5675 ret = attach_extent_buffer_page(new, p, NULL);
5678 btrfs_release_extent_buffer(new);
5681 WARN_ON(PageDirty(p));
5683 copy_page(page_address(p), page_address(src->pages[i]));
5685 set_extent_buffer_uptodate(new);
5690 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5691 u64 start, unsigned long len)
5693 struct extent_buffer *eb;
5697 eb = __alloc_extent_buffer(fs_info, start, len);
5701 num_pages = num_extent_pages(eb);
5702 for (i = 0; i < num_pages; i++) {
5705 eb->pages[i] = alloc_page(GFP_NOFS);
5708 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5712 set_extent_buffer_uptodate(eb);
5713 btrfs_set_header_nritems(eb, 0);
5714 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5718 for (; i > 0; i--) {
5719 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5720 __free_page(eb->pages[i - 1]);
5722 __free_extent_buffer(eb);
5726 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5729 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5732 static void check_buffer_tree_ref(struct extent_buffer *eb)
5736 * The TREE_REF bit is first set when the extent_buffer is added
5737 * to the radix tree. It is also reset, if unset, when a new reference
5738 * is created by find_extent_buffer.
5740 * It is only cleared in two cases: freeing the last non-tree
5741 * reference to the extent_buffer when its STALE bit is set or
5742 * calling releasepage when the tree reference is the only reference.
5744 * In both cases, care is taken to ensure that the extent_buffer's
5745 * pages are not under io. However, releasepage can be concurrently
5746 * called with creating new references, which is prone to race
5747 * conditions between the calls to check_buffer_tree_ref in those
5748 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5750 * The actual lifetime of the extent_buffer in the radix tree is
5751 * adequately protected by the refcount, but the TREE_REF bit and
5752 * its corresponding reference are not. To protect against this
5753 * class of races, we call check_buffer_tree_ref from the codepaths
5754 * which trigger io after they set eb->io_pages. Note that once io is
5755 * initiated, TREE_REF can no longer be cleared, so that is the
5756 * moment at which any such race is best fixed.
5758 refs = atomic_read(&eb->refs);
5759 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5762 spin_lock(&eb->refs_lock);
5763 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5764 atomic_inc(&eb->refs);
5765 spin_unlock(&eb->refs_lock);
5768 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5769 struct page *accessed)
5773 check_buffer_tree_ref(eb);
5775 num_pages = num_extent_pages(eb);
5776 for (i = 0; i < num_pages; i++) {
5777 struct page *p = eb->pages[i];
5780 mark_page_accessed(p);
5784 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5787 struct extent_buffer *eb;
5789 eb = find_extent_buffer_nolock(fs_info, start);
5793 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
5794 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
5795 * another task running free_extent_buffer() might have seen that flag
5796 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
5797 * writeback flags not set) and it's still in the tree (flag
5798 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
5799 * decrementing the extent buffer's reference count twice. So here we
5800 * could race and increment the eb's reference count, clear its stale
5801 * flag, mark it as dirty and drop our reference before the other task
5802 * finishes executing free_extent_buffer, which would later result in
5803 * an attempt to free an extent buffer that is dirty.
5805 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5806 spin_lock(&eb->refs_lock);
5807 spin_unlock(&eb->refs_lock);
5809 mark_extent_buffer_accessed(eb, NULL);
5813 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5814 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5817 struct extent_buffer *eb, *exists = NULL;
5820 eb = find_extent_buffer(fs_info, start);
5823 eb = alloc_dummy_extent_buffer(fs_info, start);
5825 return ERR_PTR(-ENOMEM);
5826 eb->fs_info = fs_info;
5828 ret = radix_tree_preload(GFP_NOFS);
5830 exists = ERR_PTR(ret);
5833 spin_lock(&fs_info->buffer_lock);
5834 ret = radix_tree_insert(&fs_info->buffer_radix,
5835 start >> fs_info->sectorsize_bits, eb);
5836 spin_unlock(&fs_info->buffer_lock);
5837 radix_tree_preload_end();
5838 if (ret == -EEXIST) {
5839 exists = find_extent_buffer(fs_info, start);
5845 check_buffer_tree_ref(eb);
5846 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5850 btrfs_release_extent_buffer(eb);
5855 static struct extent_buffer *grab_extent_buffer(
5856 struct btrfs_fs_info *fs_info, struct page *page)
5858 struct extent_buffer *exists;
5861 * For subpage case, we completely rely on radix tree to ensure we
5862 * don't try to insert two ebs for the same bytenr. So here we always
5863 * return NULL and just continue.
5865 if (fs_info->sectorsize < PAGE_SIZE)
5868 /* Page not yet attached to an extent buffer */
5869 if (!PagePrivate(page))
5873 * We could have already allocated an eb for this page and attached one
5874 * so lets see if we can get a ref on the existing eb, and if we can we
5875 * know it's good and we can just return that one, else we know we can
5876 * just overwrite page->private.
5878 exists = (struct extent_buffer *)page->private;
5879 if (atomic_inc_not_zero(&exists->refs))
5882 WARN_ON(PageDirty(page));
5883 detach_page_private(page);
5887 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5888 u64 start, u64 owner_root, int level)
5890 unsigned long len = fs_info->nodesize;
5893 unsigned long index = start >> PAGE_SHIFT;
5894 struct extent_buffer *eb;
5895 struct extent_buffer *exists = NULL;
5897 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5901 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5902 btrfs_err(fs_info, "bad tree block start %llu", start);
5903 return ERR_PTR(-EINVAL);
5906 #if BITS_PER_LONG == 32
5907 if (start >= MAX_LFS_FILESIZE) {
5908 btrfs_err_rl(fs_info,
5909 "extent buffer %llu is beyond 32bit page cache limit", start);
5910 btrfs_err_32bit_limit(fs_info);
5911 return ERR_PTR(-EOVERFLOW);
5913 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
5914 btrfs_warn_32bit_limit(fs_info);
5917 if (fs_info->sectorsize < PAGE_SIZE &&
5918 offset_in_page(start) + len > PAGE_SIZE) {
5920 "tree block crosses page boundary, start %llu nodesize %lu",
5922 return ERR_PTR(-EINVAL);
5925 eb = find_extent_buffer(fs_info, start);
5929 eb = __alloc_extent_buffer(fs_info, start, len);
5931 return ERR_PTR(-ENOMEM);
5932 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
5934 num_pages = num_extent_pages(eb);
5935 for (i = 0; i < num_pages; i++, index++) {
5936 struct btrfs_subpage *prealloc = NULL;
5938 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5940 exists = ERR_PTR(-ENOMEM);
5945 * Preallocate page->private for subpage case, so that we won't
5946 * allocate memory with private_lock hold. The memory will be
5947 * freed by attach_extent_buffer_page() or freed manually if
5950 * Although we have ensured one subpage eb can only have one
5951 * page, but it may change in the future for 16K page size
5952 * support, so we still preallocate the memory in the loop.
5954 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5955 BTRFS_SUBPAGE_METADATA);
5959 exists = ERR_PTR(ret);
5963 spin_lock(&mapping->private_lock);
5964 exists = grab_extent_buffer(fs_info, p);
5966 spin_unlock(&mapping->private_lock);
5969 mark_extent_buffer_accessed(exists, p);
5970 btrfs_free_subpage(prealloc);
5973 /* Should not fail, as we have preallocated the memory */
5974 ret = attach_extent_buffer_page(eb, p, prealloc);
5977 * To inform we have extra eb under allocation, so that
5978 * detach_extent_buffer_page() won't release the page private
5979 * when the eb hasn't yet been inserted into radix tree.
5981 * The ref will be decreased when the eb released the page, in
5982 * detach_extent_buffer_page().
5983 * Thus needs no special handling in error path.
5985 btrfs_page_inc_eb_refs(fs_info, p);
5986 spin_unlock(&mapping->private_lock);
5988 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
5990 if (!PageUptodate(p))
5994 * We can't unlock the pages just yet since the extent buffer
5995 * hasn't been properly inserted in the radix tree, this
5996 * opens a race with btree_releasepage which can free a page
5997 * while we are still filling in all pages for the buffer and
6002 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6004 ret = radix_tree_preload(GFP_NOFS);
6006 exists = ERR_PTR(ret);
6010 spin_lock(&fs_info->buffer_lock);
6011 ret = radix_tree_insert(&fs_info->buffer_radix,
6012 start >> fs_info->sectorsize_bits, eb);
6013 spin_unlock(&fs_info->buffer_lock);
6014 radix_tree_preload_end();
6015 if (ret == -EEXIST) {
6016 exists = find_extent_buffer(fs_info, start);
6022 /* add one reference for the tree */
6023 check_buffer_tree_ref(eb);
6024 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6027 * Now it's safe to unlock the pages because any calls to
6028 * btree_releasepage will correctly detect that a page belongs to a
6029 * live buffer and won't free them prematurely.
6031 for (i = 0; i < num_pages; i++)
6032 unlock_page(eb->pages[i]);
6036 WARN_ON(!atomic_dec_and_test(&eb->refs));
6037 for (i = 0; i < num_pages; i++) {
6039 unlock_page(eb->pages[i]);
6042 btrfs_release_extent_buffer(eb);
6046 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6048 struct extent_buffer *eb =
6049 container_of(head, struct extent_buffer, rcu_head);
6051 __free_extent_buffer(eb);
6054 static int release_extent_buffer(struct extent_buffer *eb)
6055 __releases(&eb->refs_lock)
6057 lockdep_assert_held(&eb->refs_lock);
6059 WARN_ON(atomic_read(&eb->refs) == 0);
6060 if (atomic_dec_and_test(&eb->refs)) {
6061 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6062 struct btrfs_fs_info *fs_info = eb->fs_info;
6064 spin_unlock(&eb->refs_lock);
6066 spin_lock(&fs_info->buffer_lock);
6067 radix_tree_delete(&fs_info->buffer_radix,
6068 eb->start >> fs_info->sectorsize_bits);
6069 spin_unlock(&fs_info->buffer_lock);
6071 spin_unlock(&eb->refs_lock);
6074 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6075 /* Should be safe to release our pages at this point */
6076 btrfs_release_extent_buffer_pages(eb);
6077 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6078 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6079 __free_extent_buffer(eb);
6083 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6086 spin_unlock(&eb->refs_lock);
6091 void free_extent_buffer(struct extent_buffer *eb)
6099 refs = atomic_read(&eb->refs);
6100 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6101 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6104 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6109 spin_lock(&eb->refs_lock);
6110 if (atomic_read(&eb->refs) == 2 &&
6111 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6112 !extent_buffer_under_io(eb) &&
6113 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6114 atomic_dec(&eb->refs);
6117 * I know this is terrible, but it's temporary until we stop tracking
6118 * the uptodate bits and such for the extent buffers.
6120 release_extent_buffer(eb);
6123 void free_extent_buffer_stale(struct extent_buffer *eb)
6128 spin_lock(&eb->refs_lock);
6129 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6131 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6132 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6133 atomic_dec(&eb->refs);
6134 release_extent_buffer(eb);
6137 static void btree_clear_page_dirty(struct page *page)
6139 ASSERT(PageDirty(page));
6140 ASSERT(PageLocked(page));
6141 clear_page_dirty_for_io(page);
6142 xa_lock_irq(&page->mapping->i_pages);
6143 if (!PageDirty(page))
6144 __xa_clear_mark(&page->mapping->i_pages,
6145 page_index(page), PAGECACHE_TAG_DIRTY);
6146 xa_unlock_irq(&page->mapping->i_pages);
6149 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6151 struct btrfs_fs_info *fs_info = eb->fs_info;
6152 struct page *page = eb->pages[0];
6155 /* btree_clear_page_dirty() needs page locked */
6157 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6160 btree_clear_page_dirty(page);
6162 WARN_ON(atomic_read(&eb->refs) == 0);
6165 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6171 if (eb->fs_info->sectorsize < PAGE_SIZE)
6172 return clear_subpage_extent_buffer_dirty(eb);
6174 num_pages = num_extent_pages(eb);
6176 for (i = 0; i < num_pages; i++) {
6177 page = eb->pages[i];
6178 if (!PageDirty(page))
6181 btree_clear_page_dirty(page);
6182 ClearPageError(page);
6185 WARN_ON(atomic_read(&eb->refs) == 0);
6188 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6194 check_buffer_tree_ref(eb);
6196 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6198 num_pages = num_extent_pages(eb);
6199 WARN_ON(atomic_read(&eb->refs) == 0);
6200 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6203 bool subpage = eb->fs_info->sectorsize < PAGE_SIZE;
6206 * For subpage case, we can have other extent buffers in the
6207 * same page, and in clear_subpage_extent_buffer_dirty() we
6208 * have to clear page dirty without subpage lock held.
6209 * This can cause race where our page gets dirty cleared after
6212 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6213 * its page for other reasons, we can use page lock to prevent
6217 lock_page(eb->pages[0]);
6218 for (i = 0; i < num_pages; i++)
6219 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6220 eb->start, eb->len);
6222 unlock_page(eb->pages[0]);
6224 #ifdef CONFIG_BTRFS_DEBUG
6225 for (i = 0; i < num_pages; i++)
6226 ASSERT(PageDirty(eb->pages[i]));
6232 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6234 struct btrfs_fs_info *fs_info = eb->fs_info;
6239 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6240 num_pages = num_extent_pages(eb);
6241 for (i = 0; i < num_pages; i++) {
6242 page = eb->pages[i];
6244 btrfs_page_clear_uptodate(fs_info, page,
6245 eb->start, eb->len);
6249 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6251 struct btrfs_fs_info *fs_info = eb->fs_info;
6256 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6257 num_pages = num_extent_pages(eb);
6258 for (i = 0; i < num_pages; i++) {
6259 page = eb->pages[i];
6260 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
6264 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6267 struct btrfs_fs_info *fs_info = eb->fs_info;
6268 struct extent_io_tree *io_tree;
6269 struct page *page = eb->pages[0];
6270 struct bio *bio = NULL;
6273 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6274 ASSERT(PagePrivate(page));
6275 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6277 if (wait == WAIT_NONE) {
6278 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6281 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6287 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6288 PageUptodate(page) ||
6289 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6290 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6291 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6295 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6296 eb->read_mirror = 0;
6297 atomic_set(&eb->io_pages, 1);
6298 check_buffer_tree_ref(eb);
6299 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6301 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, page, eb->start,
6302 eb->len, eb->start - page_offset(page), &bio,
6303 end_bio_extent_readpage, mirror_num, 0, 0,
6307 * In the endio function, if we hit something wrong we will
6308 * increase the io_pages, so here we need to decrease it for
6311 atomic_dec(&eb->io_pages);
6316 tmp = submit_one_bio(bio, mirror_num, 0);
6320 if (ret || wait != WAIT_COMPLETE)
6323 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6324 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6329 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6335 int locked_pages = 0;
6336 int all_uptodate = 1;
6338 unsigned long num_reads = 0;
6339 struct bio *bio = NULL;
6340 unsigned long bio_flags = 0;
6342 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6345 if (eb->fs_info->sectorsize < PAGE_SIZE)
6346 return read_extent_buffer_subpage(eb, wait, mirror_num);
6348 num_pages = num_extent_pages(eb);
6349 for (i = 0; i < num_pages; i++) {
6350 page = eb->pages[i];
6351 if (wait == WAIT_NONE) {
6353 * WAIT_NONE is only utilized by readahead. If we can't
6354 * acquire the lock atomically it means either the eb
6355 * is being read out or under modification.
6356 * Either way the eb will be or has been cached,
6357 * readahead can exit safely.
6359 if (!trylock_page(page))
6367 * We need to firstly lock all pages to make sure that
6368 * the uptodate bit of our pages won't be affected by
6369 * clear_extent_buffer_uptodate().
6371 for (i = 0; i < num_pages; i++) {
6372 page = eb->pages[i];
6373 if (!PageUptodate(page)) {
6380 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6384 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6385 eb->read_mirror = 0;
6386 atomic_set(&eb->io_pages, num_reads);
6388 * It is possible for releasepage to clear the TREE_REF bit before we
6389 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6391 check_buffer_tree_ref(eb);
6392 for (i = 0; i < num_pages; i++) {
6393 page = eb->pages[i];
6395 if (!PageUptodate(page)) {
6397 atomic_dec(&eb->io_pages);
6402 ClearPageError(page);
6403 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6404 page, page_offset(page), PAGE_SIZE, 0,
6405 &bio, end_bio_extent_readpage,
6406 mirror_num, 0, 0, false);
6409 * We failed to submit the bio so it's the
6410 * caller's responsibility to perform cleanup
6411 * i.e unlock page/set error bit.
6416 atomic_dec(&eb->io_pages);
6424 err = submit_one_bio(bio, mirror_num, bio_flags);
6429 if (ret || wait != WAIT_COMPLETE)
6432 for (i = 0; i < num_pages; i++) {
6433 page = eb->pages[i];
6434 wait_on_page_locked(page);
6435 if (!PageUptodate(page))
6442 while (locked_pages > 0) {
6444 page = eb->pages[locked_pages];
6450 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6453 btrfs_warn(eb->fs_info,
6454 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6455 eb->start, eb->len, start, len);
6456 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6462 * Check if the [start, start + len) range is valid before reading/writing
6464 * NOTE: @start and @len are offset inside the eb, not logical address.
6466 * Caller should not touch the dst/src memory if this function returns error.
6468 static inline int check_eb_range(const struct extent_buffer *eb,
6469 unsigned long start, unsigned long len)
6471 unsigned long offset;
6473 /* start, start + len should not go beyond eb->len nor overflow */
6474 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6475 return report_eb_range(eb, start, len);
6480 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6481 unsigned long start, unsigned long len)
6487 char *dst = (char *)dstv;
6488 unsigned long i = get_eb_page_index(start);
6490 if (check_eb_range(eb, start, len))
6493 offset = get_eb_offset_in_page(eb, start);
6496 page = eb->pages[i];
6498 cur = min(len, (PAGE_SIZE - offset));
6499 kaddr = page_address(page);
6500 memcpy(dst, kaddr + offset, cur);
6509 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6511 unsigned long start, unsigned long len)
6517 char __user *dst = (char __user *)dstv;
6518 unsigned long i = get_eb_page_index(start);
6521 WARN_ON(start > eb->len);
6522 WARN_ON(start + len > eb->start + eb->len);
6524 offset = get_eb_offset_in_page(eb, start);
6527 page = eb->pages[i];
6529 cur = min(len, (PAGE_SIZE - offset));
6530 kaddr = page_address(page);
6531 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6545 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6546 unsigned long start, unsigned long len)
6552 char *ptr = (char *)ptrv;
6553 unsigned long i = get_eb_page_index(start);
6556 if (check_eb_range(eb, start, len))
6559 offset = get_eb_offset_in_page(eb, start);
6562 page = eb->pages[i];
6564 cur = min(len, (PAGE_SIZE - offset));
6566 kaddr = page_address(page);
6567 ret = memcmp(ptr, kaddr + offset, cur);
6580 * Check that the extent buffer is uptodate.
6582 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6583 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6585 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6588 struct btrfs_fs_info *fs_info = eb->fs_info;
6590 if (fs_info->sectorsize < PAGE_SIZE) {
6593 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6594 eb->start, eb->len);
6597 WARN_ON(!PageUptodate(page));
6601 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6606 assert_eb_page_uptodate(eb, eb->pages[0]);
6607 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6608 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
6612 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6616 assert_eb_page_uptodate(eb, eb->pages[0]);
6617 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6618 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
6622 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6623 unsigned long start, unsigned long len)
6629 char *src = (char *)srcv;
6630 unsigned long i = get_eb_page_index(start);
6632 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6634 if (check_eb_range(eb, start, len))
6637 offset = get_eb_offset_in_page(eb, start);
6640 page = eb->pages[i];
6641 assert_eb_page_uptodate(eb, page);
6643 cur = min(len, PAGE_SIZE - offset);
6644 kaddr = page_address(page);
6645 memcpy(kaddr + offset, src, cur);
6654 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6661 unsigned long i = get_eb_page_index(start);
6663 if (check_eb_range(eb, start, len))
6666 offset = get_eb_offset_in_page(eb, start);
6669 page = eb->pages[i];
6670 assert_eb_page_uptodate(eb, page);
6672 cur = min(len, PAGE_SIZE - offset);
6673 kaddr = page_address(page);
6674 memset(kaddr + offset, 0, cur);
6682 void copy_extent_buffer_full(const struct extent_buffer *dst,
6683 const struct extent_buffer *src)
6688 ASSERT(dst->len == src->len);
6690 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6691 num_pages = num_extent_pages(dst);
6692 for (i = 0; i < num_pages; i++)
6693 copy_page(page_address(dst->pages[i]),
6694 page_address(src->pages[i]));
6696 size_t src_offset = get_eb_offset_in_page(src, 0);
6697 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6699 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6700 memcpy(page_address(dst->pages[0]) + dst_offset,
6701 page_address(src->pages[0]) + src_offset,
6706 void copy_extent_buffer(const struct extent_buffer *dst,
6707 const struct extent_buffer *src,
6708 unsigned long dst_offset, unsigned long src_offset,
6711 u64 dst_len = dst->len;
6716 unsigned long i = get_eb_page_index(dst_offset);
6718 if (check_eb_range(dst, dst_offset, len) ||
6719 check_eb_range(src, src_offset, len))
6722 WARN_ON(src->len != dst_len);
6724 offset = get_eb_offset_in_page(dst, dst_offset);
6727 page = dst->pages[i];
6728 assert_eb_page_uptodate(dst, page);
6730 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
6732 kaddr = page_address(page);
6733 read_extent_buffer(src, kaddr + offset, src_offset, cur);
6743 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6745 * @eb: the extent buffer
6746 * @start: offset of the bitmap item in the extent buffer
6748 * @page_index: return index of the page in the extent buffer that contains the
6750 * @page_offset: return offset into the page given by page_index
6752 * This helper hides the ugliness of finding the byte in an extent buffer which
6753 * contains a given bit.
6755 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
6756 unsigned long start, unsigned long nr,
6757 unsigned long *page_index,
6758 size_t *page_offset)
6760 size_t byte_offset = BIT_BYTE(nr);
6764 * The byte we want is the offset of the extent buffer + the offset of
6765 * the bitmap item in the extent buffer + the offset of the byte in the
6768 offset = start + offset_in_page(eb->start) + byte_offset;
6770 *page_index = offset >> PAGE_SHIFT;
6771 *page_offset = offset_in_page(offset);
6775 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6776 * @eb: the extent buffer
6777 * @start: offset of the bitmap item in the extent buffer
6778 * @nr: bit number to test
6780 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
6788 eb_bitmap_offset(eb, start, nr, &i, &offset);
6789 page = eb->pages[i];
6790 assert_eb_page_uptodate(eb, page);
6791 kaddr = page_address(page);
6792 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6796 * extent_buffer_bitmap_set - set an area of a bitmap
6797 * @eb: the extent buffer
6798 * @start: offset of the bitmap item in the extent buffer
6799 * @pos: bit number of the first bit
6800 * @len: number of bits to set
6802 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
6803 unsigned long pos, unsigned long len)
6809 const unsigned int size = pos + len;
6810 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6811 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
6813 eb_bitmap_offset(eb, start, pos, &i, &offset);
6814 page = eb->pages[i];
6815 assert_eb_page_uptodate(eb, page);
6816 kaddr = page_address(page);
6818 while (len >= bits_to_set) {
6819 kaddr[offset] |= mask_to_set;
6821 bits_to_set = BITS_PER_BYTE;
6823 if (++offset >= PAGE_SIZE && len > 0) {
6825 page = eb->pages[++i];
6826 assert_eb_page_uptodate(eb, page);
6827 kaddr = page_address(page);
6831 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6832 kaddr[offset] |= mask_to_set;
6838 * extent_buffer_bitmap_clear - clear an area of a bitmap
6839 * @eb: the extent buffer
6840 * @start: offset of the bitmap item in the extent buffer
6841 * @pos: bit number of the first bit
6842 * @len: number of bits to clear
6844 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6845 unsigned long start, unsigned long pos,
6852 const unsigned int size = pos + len;
6853 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6854 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
6856 eb_bitmap_offset(eb, start, pos, &i, &offset);
6857 page = eb->pages[i];
6858 assert_eb_page_uptodate(eb, page);
6859 kaddr = page_address(page);
6861 while (len >= bits_to_clear) {
6862 kaddr[offset] &= ~mask_to_clear;
6863 len -= bits_to_clear;
6864 bits_to_clear = BITS_PER_BYTE;
6866 if (++offset >= PAGE_SIZE && len > 0) {
6868 page = eb->pages[++i];
6869 assert_eb_page_uptodate(eb, page);
6870 kaddr = page_address(page);
6874 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6875 kaddr[offset] &= ~mask_to_clear;
6879 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6881 unsigned long distance = (src > dst) ? src - dst : dst - src;
6882 return distance < len;
6885 static void copy_pages(struct page *dst_page, struct page *src_page,
6886 unsigned long dst_off, unsigned long src_off,
6889 char *dst_kaddr = page_address(dst_page);
6891 int must_memmove = 0;
6893 if (dst_page != src_page) {
6894 src_kaddr = page_address(src_page);
6896 src_kaddr = dst_kaddr;
6897 if (areas_overlap(src_off, dst_off, len))
6902 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6904 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6907 void memcpy_extent_buffer(const struct extent_buffer *dst,
6908 unsigned long dst_offset, unsigned long src_offset,
6912 size_t dst_off_in_page;
6913 size_t src_off_in_page;
6914 unsigned long dst_i;
6915 unsigned long src_i;
6917 if (check_eb_range(dst, dst_offset, len) ||
6918 check_eb_range(dst, src_offset, len))
6922 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6923 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
6925 dst_i = get_eb_page_index(dst_offset);
6926 src_i = get_eb_page_index(src_offset);
6928 cur = min(len, (unsigned long)(PAGE_SIZE -
6930 cur = min_t(unsigned long, cur,
6931 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6933 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6934 dst_off_in_page, src_off_in_page, cur);
6942 void memmove_extent_buffer(const struct extent_buffer *dst,
6943 unsigned long dst_offset, unsigned long src_offset,
6947 size_t dst_off_in_page;
6948 size_t src_off_in_page;
6949 unsigned long dst_end = dst_offset + len - 1;
6950 unsigned long src_end = src_offset + len - 1;
6951 unsigned long dst_i;
6952 unsigned long src_i;
6954 if (check_eb_range(dst, dst_offset, len) ||
6955 check_eb_range(dst, src_offset, len))
6957 if (dst_offset < src_offset) {
6958 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6962 dst_i = get_eb_page_index(dst_end);
6963 src_i = get_eb_page_index(src_end);
6965 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6966 src_off_in_page = get_eb_offset_in_page(dst, src_end);
6968 cur = min_t(unsigned long, len, src_off_in_page + 1);
6969 cur = min(cur, dst_off_in_page + 1);
6970 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6971 dst_off_in_page - cur + 1,
6972 src_off_in_page - cur + 1, cur);
6980 static struct extent_buffer *get_next_extent_buffer(
6981 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6983 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6984 struct extent_buffer *found = NULL;
6985 u64 page_start = page_offset(page);
6989 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
6990 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
6991 lockdep_assert_held(&fs_info->buffer_lock);
6993 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
6994 bytenr >> fs_info->sectorsize_bits,
6995 PAGE_SIZE / fs_info->nodesize);
6996 for (i = 0; i < ret; i++) {
6997 /* Already beyond page end */
6998 if (gang[i]->start >= page_start + PAGE_SIZE)
7001 if (gang[i]->start >= bytenr) {
7009 static int try_release_subpage_extent_buffer(struct page *page)
7011 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7012 u64 cur = page_offset(page);
7013 const u64 end = page_offset(page) + PAGE_SIZE;
7017 struct extent_buffer *eb = NULL;
7020 * Unlike try_release_extent_buffer() which uses page->private
7021 * to grab buffer, for subpage case we rely on radix tree, thus
7022 * we need to ensure radix tree consistency.
7024 * We also want an atomic snapshot of the radix tree, thus go
7025 * with spinlock rather than RCU.
7027 spin_lock(&fs_info->buffer_lock);
7028 eb = get_next_extent_buffer(fs_info, page, cur);
7030 /* No more eb in the page range after or at cur */
7031 spin_unlock(&fs_info->buffer_lock);
7034 cur = eb->start + eb->len;
7037 * The same as try_release_extent_buffer(), to ensure the eb
7038 * won't disappear out from under us.
7040 spin_lock(&eb->refs_lock);
7041 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7042 spin_unlock(&eb->refs_lock);
7043 spin_unlock(&fs_info->buffer_lock);
7046 spin_unlock(&fs_info->buffer_lock);
7049 * If tree ref isn't set then we know the ref on this eb is a
7050 * real ref, so just return, this eb will likely be freed soon
7053 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7054 spin_unlock(&eb->refs_lock);
7059 * Here we don't care about the return value, we will always
7060 * check the page private at the end. And
7061 * release_extent_buffer() will release the refs_lock.
7063 release_extent_buffer(eb);
7066 * Finally to check if we have cleared page private, as if we have
7067 * released all ebs in the page, the page private should be cleared now.
7069 spin_lock(&page->mapping->private_lock);
7070 if (!PagePrivate(page))
7074 spin_unlock(&page->mapping->private_lock);
7079 int try_release_extent_buffer(struct page *page)
7081 struct extent_buffer *eb;
7083 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
7084 return try_release_subpage_extent_buffer(page);
7087 * We need to make sure nobody is changing page->private, as we rely on
7088 * page->private as the pointer to extent buffer.
7090 spin_lock(&page->mapping->private_lock);
7091 if (!PagePrivate(page)) {
7092 spin_unlock(&page->mapping->private_lock);
7096 eb = (struct extent_buffer *)page->private;
7100 * This is a little awful but should be ok, we need to make sure that
7101 * the eb doesn't disappear out from under us while we're looking at
7104 spin_lock(&eb->refs_lock);
7105 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7106 spin_unlock(&eb->refs_lock);
7107 spin_unlock(&page->mapping->private_lock);
7110 spin_unlock(&page->mapping->private_lock);
7113 * If tree ref isn't set then we know the ref on this eb is a real ref,
7114 * so just return, this page will likely be freed soon anyway.
7116 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7117 spin_unlock(&eb->refs_lock);
7121 return release_extent_buffer(eb);
7125 * btrfs_readahead_tree_block - attempt to readahead a child block
7126 * @fs_info: the fs_info
7127 * @bytenr: bytenr to read
7128 * @owner_root: objectid of the root that owns this eb
7129 * @gen: generation for the uptodate check, can be 0
7130 * @level: level for the eb
7132 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7133 * normal uptodate check of the eb, without checking the generation. If we have
7134 * to read the block we will not block on anything.
7136 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7137 u64 bytenr, u64 owner_root, u64 gen, int level)
7139 struct extent_buffer *eb;
7142 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7146 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7147 free_extent_buffer(eb);
7151 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7153 free_extent_buffer_stale(eb);
7155 free_extent_buffer(eb);
7159 * btrfs_readahead_node_child - readahead a node's child block
7160 * @node: parent node we're reading from
7161 * @slot: slot in the parent node for the child we want to read
7163 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7164 * the slot in the node provided.
7166 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7168 btrfs_readahead_tree_block(node->fs_info,
7169 btrfs_node_blockptr(node, slot),
7170 btrfs_header_owner(node),
7171 btrfs_node_ptr_generation(node, slot),
7172 btrfs_header_level(node) - 1);