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 {
139 struct btrfs_bio_ctrl bio_ctrl;
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)
188 struct bio *bio = epd->bio_ctrl.bio;
191 bio->bi_status = errno_to_blk_status(ret);
193 epd->bio_ctrl.bio = NULL;
198 * Submit bio from extent page data via submit_one_bio
200 * Return 0 if everything is OK.
201 * Return <0 for error.
203 static int __must_check flush_write_bio(struct extent_page_data *epd)
206 struct bio *bio = epd->bio_ctrl.bio;
209 ret = submit_one_bio(bio, 0, 0);
211 * Clean up of epd->bio is handled by its endio function.
212 * And endio is either triggered by successful bio execution
213 * or the error handler of submit bio hook.
214 * So at this point, no matter what happened, we don't need
215 * to clean up epd->bio.
217 epd->bio_ctrl.bio = NULL;
222 int __init extent_state_cache_init(void)
224 extent_state_cache = kmem_cache_create("btrfs_extent_state",
225 sizeof(struct extent_state), 0,
226 SLAB_MEM_SPREAD, NULL);
227 if (!extent_state_cache)
232 int __init extent_io_init(void)
234 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
235 sizeof(struct extent_buffer), 0,
236 SLAB_MEM_SPREAD, NULL);
237 if (!extent_buffer_cache)
240 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
241 offsetof(struct btrfs_io_bio, bio),
243 goto free_buffer_cache;
245 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
251 bioset_exit(&btrfs_bioset);
254 kmem_cache_destroy(extent_buffer_cache);
255 extent_buffer_cache = NULL;
259 void __cold extent_state_cache_exit(void)
261 btrfs_extent_state_leak_debug_check();
262 kmem_cache_destroy(extent_state_cache);
265 void __cold extent_io_exit(void)
268 * Make sure all delayed rcu free are flushed before we
272 kmem_cache_destroy(extent_buffer_cache);
273 bioset_exit(&btrfs_bioset);
277 * For the file_extent_tree, we want to hold the inode lock when we lookup and
278 * update the disk_i_size, but lockdep will complain because our io_tree we hold
279 * the tree lock and get the inode lock when setting delalloc. These two things
280 * are unrelated, so make a class for the file_extent_tree so we don't get the
281 * two locking patterns mixed up.
283 static struct lock_class_key file_extent_tree_class;
285 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
286 struct extent_io_tree *tree, unsigned int owner,
289 tree->fs_info = fs_info;
290 tree->state = RB_ROOT;
291 tree->dirty_bytes = 0;
292 spin_lock_init(&tree->lock);
293 tree->private_data = private_data;
295 if (owner == IO_TREE_INODE_FILE_EXTENT)
296 lockdep_set_class(&tree->lock, &file_extent_tree_class);
299 void extent_io_tree_release(struct extent_io_tree *tree)
301 spin_lock(&tree->lock);
303 * Do a single barrier for the waitqueue_active check here, the state
304 * of the waitqueue should not change once extent_io_tree_release is
308 while (!RB_EMPTY_ROOT(&tree->state)) {
309 struct rb_node *node;
310 struct extent_state *state;
312 node = rb_first(&tree->state);
313 state = rb_entry(node, struct extent_state, rb_node);
314 rb_erase(&state->rb_node, &tree->state);
315 RB_CLEAR_NODE(&state->rb_node);
317 * btree io trees aren't supposed to have tasks waiting for
318 * changes in the flags of extent states ever.
320 ASSERT(!waitqueue_active(&state->wq));
321 free_extent_state(state);
323 cond_resched_lock(&tree->lock);
325 spin_unlock(&tree->lock);
328 static struct extent_state *alloc_extent_state(gfp_t mask)
330 struct extent_state *state;
333 * The given mask might be not appropriate for the slab allocator,
334 * drop the unsupported bits
336 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
337 state = kmem_cache_alloc(extent_state_cache, mask);
341 state->failrec = NULL;
342 RB_CLEAR_NODE(&state->rb_node);
343 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
344 refcount_set(&state->refs, 1);
345 init_waitqueue_head(&state->wq);
346 trace_alloc_extent_state(state, mask, _RET_IP_);
350 void free_extent_state(struct extent_state *state)
354 if (refcount_dec_and_test(&state->refs)) {
355 WARN_ON(extent_state_in_tree(state));
356 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
357 trace_free_extent_state(state, _RET_IP_);
358 kmem_cache_free(extent_state_cache, state);
362 static struct rb_node *tree_insert(struct rb_root *root,
363 struct rb_node *search_start,
365 struct rb_node *node,
366 struct rb_node ***p_in,
367 struct rb_node **parent_in)
370 struct rb_node *parent = NULL;
371 struct tree_entry *entry;
373 if (p_in && parent_in) {
379 p = search_start ? &search_start : &root->rb_node;
382 entry = rb_entry(parent, struct tree_entry, rb_node);
384 if (offset < entry->start)
386 else if (offset > entry->end)
393 rb_link_node(node, parent, p);
394 rb_insert_color(node, root);
399 * Search @tree for an entry that contains @offset. Such entry would have
400 * entry->start <= offset && entry->end >= offset.
402 * @tree: the tree to search
403 * @offset: offset that should fall within an entry in @tree
404 * @next_ret: pointer to the first entry whose range ends after @offset
405 * @prev_ret: pointer to the first entry whose range begins before @offset
406 * @p_ret: pointer where new node should be anchored (used when inserting an
408 * @parent_ret: points to entry which would have been the parent of the entry,
411 * This function returns a pointer to the entry that contains @offset byte
412 * address. If no such entry exists, then NULL is returned and the other
413 * pointer arguments to the function are filled, otherwise the found entry is
414 * returned and other pointers are left untouched.
416 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
417 struct rb_node **next_ret,
418 struct rb_node **prev_ret,
419 struct rb_node ***p_ret,
420 struct rb_node **parent_ret)
422 struct rb_root *root = &tree->state;
423 struct rb_node **n = &root->rb_node;
424 struct rb_node *prev = NULL;
425 struct rb_node *orig_prev = NULL;
426 struct tree_entry *entry;
427 struct tree_entry *prev_entry = NULL;
431 entry = rb_entry(prev, struct tree_entry, rb_node);
434 if (offset < entry->start)
436 else if (offset > entry->end)
449 while (prev && offset > prev_entry->end) {
450 prev = rb_next(prev);
451 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
458 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
459 while (prev && offset < prev_entry->start) {
460 prev = rb_prev(prev);
461 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
468 static inline struct rb_node *
469 tree_search_for_insert(struct extent_io_tree *tree,
471 struct rb_node ***p_ret,
472 struct rb_node **parent_ret)
474 struct rb_node *next= NULL;
477 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
483 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
486 return tree_search_for_insert(tree, offset, NULL, NULL);
490 * utility function to look for merge candidates inside a given range.
491 * Any extents with matching state are merged together into a single
492 * extent in the tree. Extents with EXTENT_IO in their state field
493 * are not merged because the end_io handlers need to be able to do
494 * operations on them without sleeping (or doing allocations/splits).
496 * This should be called with the tree lock held.
498 static void merge_state(struct extent_io_tree *tree,
499 struct extent_state *state)
501 struct extent_state *other;
502 struct rb_node *other_node;
504 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
507 other_node = rb_prev(&state->rb_node);
509 other = rb_entry(other_node, struct extent_state, rb_node);
510 if (other->end == state->start - 1 &&
511 other->state == state->state) {
512 if (tree->private_data &&
513 is_data_inode(tree->private_data))
514 btrfs_merge_delalloc_extent(tree->private_data,
516 state->start = other->start;
517 rb_erase(&other->rb_node, &tree->state);
518 RB_CLEAR_NODE(&other->rb_node);
519 free_extent_state(other);
522 other_node = rb_next(&state->rb_node);
524 other = rb_entry(other_node, struct extent_state, rb_node);
525 if (other->start == state->end + 1 &&
526 other->state == state->state) {
527 if (tree->private_data &&
528 is_data_inode(tree->private_data))
529 btrfs_merge_delalloc_extent(tree->private_data,
531 state->end = other->end;
532 rb_erase(&other->rb_node, &tree->state);
533 RB_CLEAR_NODE(&other->rb_node);
534 free_extent_state(other);
539 static void set_state_bits(struct extent_io_tree *tree,
540 struct extent_state *state, u32 *bits,
541 struct extent_changeset *changeset);
544 * insert an extent_state struct into the tree. 'bits' are set on the
545 * struct before it is inserted.
547 * This may return -EEXIST if the extent is already there, in which case the
548 * state struct is freed.
550 * The tree lock is not taken internally. This is a utility function and
551 * probably isn't what you want to call (see set/clear_extent_bit).
553 static int insert_state(struct extent_io_tree *tree,
554 struct extent_state *state, u64 start, u64 end,
556 struct rb_node **parent,
557 u32 *bits, struct extent_changeset *changeset)
559 struct rb_node *node;
562 btrfs_err(tree->fs_info,
563 "insert state: end < start %llu %llu", end, start);
566 state->start = start;
569 set_state_bits(tree, state, bits, changeset);
571 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
573 struct extent_state *found;
574 found = rb_entry(node, struct extent_state, rb_node);
575 btrfs_err(tree->fs_info,
576 "found node %llu %llu on insert of %llu %llu",
577 found->start, found->end, start, end);
580 merge_state(tree, state);
585 * split a given extent state struct in two, inserting the preallocated
586 * struct 'prealloc' as the newly created second half. 'split' indicates an
587 * offset inside 'orig' where it should be split.
590 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
591 * are two extent state structs in the tree:
592 * prealloc: [orig->start, split - 1]
593 * orig: [ split, orig->end ]
595 * The tree locks are not taken by this function. They need to be held
598 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
599 struct extent_state *prealloc, u64 split)
601 struct rb_node *node;
603 if (tree->private_data && is_data_inode(tree->private_data))
604 btrfs_split_delalloc_extent(tree->private_data, orig, split);
606 prealloc->start = orig->start;
607 prealloc->end = split - 1;
608 prealloc->state = orig->state;
611 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
612 &prealloc->rb_node, NULL, NULL);
614 free_extent_state(prealloc);
620 static struct extent_state *next_state(struct extent_state *state)
622 struct rb_node *next = rb_next(&state->rb_node);
624 return rb_entry(next, struct extent_state, rb_node);
630 * utility function to clear some bits in an extent state struct.
631 * it will optionally wake up anyone waiting on this state (wake == 1).
633 * If no bits are set on the state struct after clearing things, the
634 * struct is freed and removed from the tree
636 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
637 struct extent_state *state,
639 struct extent_changeset *changeset)
641 struct extent_state *next;
642 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
645 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
646 u64 range = state->end - state->start + 1;
647 WARN_ON(range > tree->dirty_bytes);
648 tree->dirty_bytes -= range;
651 if (tree->private_data && is_data_inode(tree->private_data))
652 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
654 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
656 state->state &= ~bits_to_clear;
659 if (state->state == 0) {
660 next = next_state(state);
661 if (extent_state_in_tree(state)) {
662 rb_erase(&state->rb_node, &tree->state);
663 RB_CLEAR_NODE(&state->rb_node);
664 free_extent_state(state);
669 merge_state(tree, state);
670 next = next_state(state);
675 static struct extent_state *
676 alloc_extent_state_atomic(struct extent_state *prealloc)
679 prealloc = alloc_extent_state(GFP_ATOMIC);
684 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
686 btrfs_panic(tree->fs_info, err,
687 "locking error: extent tree was modified by another thread while locked");
691 * clear some bits on a range in the tree. This may require splitting
692 * or inserting elements in the tree, so the gfp mask is used to
693 * indicate which allocations or sleeping are allowed.
695 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
696 * the given range from the tree regardless of state (ie for truncate).
698 * the range [start, end] is inclusive.
700 * This takes the tree lock, and returns 0 on success and < 0 on error.
702 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
703 u32 bits, int wake, int delete,
704 struct extent_state **cached_state,
705 gfp_t mask, struct extent_changeset *changeset)
707 struct extent_state *state;
708 struct extent_state *cached;
709 struct extent_state *prealloc = NULL;
710 struct rb_node *node;
715 btrfs_debug_check_extent_io_range(tree, start, end);
716 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
718 if (bits & EXTENT_DELALLOC)
719 bits |= EXTENT_NORESERVE;
722 bits |= ~EXTENT_CTLBITS;
724 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
727 if (!prealloc && gfpflags_allow_blocking(mask)) {
729 * Don't care for allocation failure here because we might end
730 * up not needing the pre-allocated extent state at all, which
731 * is the case if we only have in the tree extent states that
732 * cover our input range and don't cover too any other range.
733 * If we end up needing a new extent state we allocate it later.
735 prealloc = alloc_extent_state(mask);
738 spin_lock(&tree->lock);
740 cached = *cached_state;
743 *cached_state = NULL;
747 if (cached && extent_state_in_tree(cached) &&
748 cached->start <= start && cached->end > start) {
750 refcount_dec(&cached->refs);
755 free_extent_state(cached);
758 * this search will find the extents that end after
761 node = tree_search(tree, start);
764 state = rb_entry(node, struct extent_state, rb_node);
766 if (state->start > end)
768 WARN_ON(state->end < start);
769 last_end = state->end;
771 /* the state doesn't have the wanted bits, go ahead */
772 if (!(state->state & bits)) {
773 state = next_state(state);
778 * | ---- desired range ---- |
780 * | ------------- state -------------- |
782 * We need to split the extent we found, and may flip
783 * bits on second half.
785 * If the extent we found extends past our range, we
786 * just split and search again. It'll get split again
787 * the next time though.
789 * If the extent we found is inside our range, we clear
790 * the desired bit on it.
793 if (state->start < start) {
794 prealloc = alloc_extent_state_atomic(prealloc);
796 err = split_state(tree, state, prealloc, start);
798 extent_io_tree_panic(tree, err);
803 if (state->end <= end) {
804 state = clear_state_bit(tree, state, &bits, wake,
811 * | ---- desired range ---- |
813 * We need to split the extent, and clear the bit
816 if (state->start <= end && state->end > end) {
817 prealloc = alloc_extent_state_atomic(prealloc);
819 err = split_state(tree, state, prealloc, end + 1);
821 extent_io_tree_panic(tree, err);
826 clear_state_bit(tree, prealloc, &bits, wake, changeset);
832 state = clear_state_bit(tree, state, &bits, wake, changeset);
834 if (last_end == (u64)-1)
836 start = last_end + 1;
837 if (start <= end && state && !need_resched())
843 spin_unlock(&tree->lock);
844 if (gfpflags_allow_blocking(mask))
849 spin_unlock(&tree->lock);
851 free_extent_state(prealloc);
857 static void wait_on_state(struct extent_io_tree *tree,
858 struct extent_state *state)
859 __releases(tree->lock)
860 __acquires(tree->lock)
863 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
864 spin_unlock(&tree->lock);
866 spin_lock(&tree->lock);
867 finish_wait(&state->wq, &wait);
871 * waits for one or more bits to clear on a range in the state tree.
872 * The range [start, end] is inclusive.
873 * The tree lock is taken by this function
875 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
878 struct extent_state *state;
879 struct rb_node *node;
881 btrfs_debug_check_extent_io_range(tree, start, end);
883 spin_lock(&tree->lock);
887 * this search will find all the extents that end after
890 node = tree_search(tree, start);
895 state = rb_entry(node, struct extent_state, rb_node);
897 if (state->start > end)
900 if (state->state & bits) {
901 start = state->start;
902 refcount_inc(&state->refs);
903 wait_on_state(tree, state);
904 free_extent_state(state);
907 start = state->end + 1;
912 if (!cond_resched_lock(&tree->lock)) {
913 node = rb_next(node);
918 spin_unlock(&tree->lock);
921 static void set_state_bits(struct extent_io_tree *tree,
922 struct extent_state *state,
923 u32 *bits, struct extent_changeset *changeset)
925 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
928 if (tree->private_data && is_data_inode(tree->private_data))
929 btrfs_set_delalloc_extent(tree->private_data, state, bits);
931 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
932 u64 range = state->end - state->start + 1;
933 tree->dirty_bytes += range;
935 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
937 state->state |= bits_to_set;
940 static void cache_state_if_flags(struct extent_state *state,
941 struct extent_state **cached_ptr,
944 if (cached_ptr && !(*cached_ptr)) {
945 if (!flags || (state->state & flags)) {
947 refcount_inc(&state->refs);
952 static void cache_state(struct extent_state *state,
953 struct extent_state **cached_ptr)
955 return cache_state_if_flags(state, cached_ptr,
956 EXTENT_LOCKED | EXTENT_BOUNDARY);
960 * set some bits on a range in the tree. This may require allocations or
961 * sleeping, so the gfp mask is used to indicate what is allowed.
963 * If any of the exclusive bits are set, this will fail with -EEXIST if some
964 * part of the range already has the desired bits set. The start of the
965 * existing range is returned in failed_start in this case.
967 * [start, end] is inclusive This takes the tree lock.
969 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
970 u32 exclusive_bits, u64 *failed_start,
971 struct extent_state **cached_state, gfp_t mask,
972 struct extent_changeset *changeset)
974 struct extent_state *state;
975 struct extent_state *prealloc = NULL;
976 struct rb_node *node;
978 struct rb_node *parent;
983 btrfs_debug_check_extent_io_range(tree, start, end);
984 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
987 ASSERT(failed_start);
989 ASSERT(failed_start == NULL);
991 if (!prealloc && gfpflags_allow_blocking(mask)) {
993 * Don't care for allocation failure here because we might end
994 * up not needing the pre-allocated extent state at all, which
995 * is the case if we only have in the tree extent states that
996 * cover our input range and don't cover too any other range.
997 * If we end up needing a new extent state we allocate it later.
999 prealloc = alloc_extent_state(mask);
1002 spin_lock(&tree->lock);
1003 if (cached_state && *cached_state) {
1004 state = *cached_state;
1005 if (state->start <= start && state->end > start &&
1006 extent_state_in_tree(state)) {
1007 node = &state->rb_node;
1012 * this search will find all the extents that end after
1015 node = tree_search_for_insert(tree, start, &p, &parent);
1017 prealloc = alloc_extent_state_atomic(prealloc);
1019 err = insert_state(tree, prealloc, start, end,
1020 &p, &parent, &bits, changeset);
1022 extent_io_tree_panic(tree, err);
1024 cache_state(prealloc, cached_state);
1028 state = rb_entry(node, struct extent_state, rb_node);
1030 last_start = state->start;
1031 last_end = state->end;
1034 * | ---- desired range ---- |
1037 * Just lock what we found and keep going
1039 if (state->start == start && state->end <= end) {
1040 if (state->state & exclusive_bits) {
1041 *failed_start = state->start;
1046 set_state_bits(tree, state, &bits, changeset);
1047 cache_state(state, cached_state);
1048 merge_state(tree, state);
1049 if (last_end == (u64)-1)
1051 start = last_end + 1;
1052 state = next_state(state);
1053 if (start < end && state && state->start == start &&
1060 * | ---- desired range ---- |
1063 * | ------------- state -------------- |
1065 * We need to split the extent we found, and may flip bits on
1068 * If the extent we found extends past our
1069 * range, we just split and search again. It'll get split
1070 * again the next time though.
1072 * If the extent we found is inside our range, we set the
1073 * desired bit on it.
1075 if (state->start < start) {
1076 if (state->state & exclusive_bits) {
1077 *failed_start = start;
1083 * If this extent already has all the bits we want set, then
1084 * skip it, not necessary to split it or do anything with it.
1086 if ((state->state & bits) == bits) {
1087 start = state->end + 1;
1088 cache_state(state, cached_state);
1092 prealloc = alloc_extent_state_atomic(prealloc);
1094 err = split_state(tree, state, prealloc, start);
1096 extent_io_tree_panic(tree, err);
1101 if (state->end <= end) {
1102 set_state_bits(tree, state, &bits, changeset);
1103 cache_state(state, cached_state);
1104 merge_state(tree, state);
1105 if (last_end == (u64)-1)
1107 start = last_end + 1;
1108 state = next_state(state);
1109 if (start < end && state && state->start == start &&
1116 * | ---- desired range ---- |
1117 * | state | or | state |
1119 * There's a hole, we need to insert something in it and
1120 * ignore the extent we found.
1122 if (state->start > start) {
1124 if (end < last_start)
1127 this_end = last_start - 1;
1129 prealloc = alloc_extent_state_atomic(prealloc);
1133 * Avoid to free 'prealloc' if it can be merged with
1136 err = insert_state(tree, prealloc, start, this_end,
1137 NULL, NULL, &bits, changeset);
1139 extent_io_tree_panic(tree, err);
1141 cache_state(prealloc, cached_state);
1143 start = this_end + 1;
1147 * | ---- desired range ---- |
1149 * We need to split the extent, and set the bit
1152 if (state->start <= end && state->end > end) {
1153 if (state->state & exclusive_bits) {
1154 *failed_start = start;
1159 prealloc = alloc_extent_state_atomic(prealloc);
1161 err = split_state(tree, state, prealloc, end + 1);
1163 extent_io_tree_panic(tree, err);
1165 set_state_bits(tree, prealloc, &bits, changeset);
1166 cache_state(prealloc, cached_state);
1167 merge_state(tree, prealloc);
1175 spin_unlock(&tree->lock);
1176 if (gfpflags_allow_blocking(mask))
1181 spin_unlock(&tree->lock);
1183 free_extent_state(prealloc);
1190 * convert_extent_bit - convert all bits in a given range from one bit to
1192 * @tree: the io tree to search
1193 * @start: the start offset in bytes
1194 * @end: the end offset in bytes (inclusive)
1195 * @bits: the bits to set in this range
1196 * @clear_bits: the bits to clear in this range
1197 * @cached_state: state that we're going to cache
1199 * This will go through and set bits for the given range. If any states exist
1200 * already in this range they are set with the given bit and cleared of the
1201 * clear_bits. This is only meant to be used by things that are mergeable, ie
1202 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1203 * boundary bits like LOCK.
1205 * All allocations are done with GFP_NOFS.
1207 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1208 u32 bits, u32 clear_bits,
1209 struct extent_state **cached_state)
1211 struct extent_state *state;
1212 struct extent_state *prealloc = NULL;
1213 struct rb_node *node;
1215 struct rb_node *parent;
1219 bool first_iteration = true;
1221 btrfs_debug_check_extent_io_range(tree, start, end);
1222 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1228 * Best effort, don't worry if extent state allocation fails
1229 * here for the first iteration. We might have a cached state
1230 * that matches exactly the target range, in which case no
1231 * extent state allocations are needed. We'll only know this
1232 * after locking the tree.
1234 prealloc = alloc_extent_state(GFP_NOFS);
1235 if (!prealloc && !first_iteration)
1239 spin_lock(&tree->lock);
1240 if (cached_state && *cached_state) {
1241 state = *cached_state;
1242 if (state->start <= start && state->end > start &&
1243 extent_state_in_tree(state)) {
1244 node = &state->rb_node;
1250 * this search will find all the extents that end after
1253 node = tree_search_for_insert(tree, start, &p, &parent);
1255 prealloc = alloc_extent_state_atomic(prealloc);
1260 err = insert_state(tree, prealloc, start, end,
1261 &p, &parent, &bits, NULL);
1263 extent_io_tree_panic(tree, err);
1264 cache_state(prealloc, cached_state);
1268 state = rb_entry(node, struct extent_state, rb_node);
1270 last_start = state->start;
1271 last_end = state->end;
1274 * | ---- desired range ---- |
1277 * Just lock what we found and keep going
1279 if (state->start == start && state->end <= end) {
1280 set_state_bits(tree, state, &bits, NULL);
1281 cache_state(state, cached_state);
1282 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1283 if (last_end == (u64)-1)
1285 start = last_end + 1;
1286 if (start < end && state && state->start == start &&
1293 * | ---- desired range ---- |
1296 * | ------------- state -------------- |
1298 * We need to split the extent we found, and may flip bits on
1301 * If the extent we found extends past our
1302 * range, we just split and search again. It'll get split
1303 * again the next time though.
1305 * If the extent we found is inside our range, we set the
1306 * desired bit on it.
1308 if (state->start < start) {
1309 prealloc = alloc_extent_state_atomic(prealloc);
1314 err = split_state(tree, state, prealloc, start);
1316 extent_io_tree_panic(tree, err);
1320 if (state->end <= end) {
1321 set_state_bits(tree, state, &bits, NULL);
1322 cache_state(state, cached_state);
1323 state = clear_state_bit(tree, state, &clear_bits, 0,
1325 if (last_end == (u64)-1)
1327 start = last_end + 1;
1328 if (start < end && state && state->start == start &&
1335 * | ---- desired range ---- |
1336 * | state | or | state |
1338 * There's a hole, we need to insert something in it and
1339 * ignore the extent we found.
1341 if (state->start > start) {
1343 if (end < last_start)
1346 this_end = last_start - 1;
1348 prealloc = alloc_extent_state_atomic(prealloc);
1355 * Avoid to free 'prealloc' if it can be merged with
1358 err = insert_state(tree, prealloc, start, this_end,
1359 NULL, NULL, &bits, NULL);
1361 extent_io_tree_panic(tree, err);
1362 cache_state(prealloc, cached_state);
1364 start = this_end + 1;
1368 * | ---- desired range ---- |
1370 * We need to split the extent, and set the bit
1373 if (state->start <= end && state->end > end) {
1374 prealloc = alloc_extent_state_atomic(prealloc);
1380 err = split_state(tree, state, prealloc, end + 1);
1382 extent_io_tree_panic(tree, err);
1384 set_state_bits(tree, prealloc, &bits, NULL);
1385 cache_state(prealloc, cached_state);
1386 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1394 spin_unlock(&tree->lock);
1396 first_iteration = false;
1400 spin_unlock(&tree->lock);
1402 free_extent_state(prealloc);
1407 /* wrappers around set/clear extent bit */
1408 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1409 u32 bits, struct extent_changeset *changeset)
1412 * We don't support EXTENT_LOCKED yet, as current changeset will
1413 * record any bits changed, so for EXTENT_LOCKED case, it will
1414 * either fail with -EEXIST or changeset will record the whole
1417 BUG_ON(bits & EXTENT_LOCKED);
1419 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1423 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1426 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1430 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1431 u32 bits, int wake, int delete,
1432 struct extent_state **cached)
1434 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1435 cached, GFP_NOFS, NULL);
1438 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1439 u32 bits, struct extent_changeset *changeset)
1442 * Don't support EXTENT_LOCKED case, same reason as
1443 * set_record_extent_bits().
1445 BUG_ON(bits & EXTENT_LOCKED);
1447 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1452 * either insert or lock state struct between start and end use mask to tell
1453 * us if waiting is desired.
1455 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1456 struct extent_state **cached_state)
1462 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1463 EXTENT_LOCKED, &failed_start,
1464 cached_state, GFP_NOFS, NULL);
1465 if (err == -EEXIST) {
1466 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1467 start = failed_start;
1470 WARN_ON(start > end);
1475 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1480 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1481 &failed_start, NULL, GFP_NOFS, NULL);
1482 if (err == -EEXIST) {
1483 if (failed_start > start)
1484 clear_extent_bit(tree, start, failed_start - 1,
1485 EXTENT_LOCKED, 1, 0, NULL);
1491 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1493 unsigned long index = start >> PAGE_SHIFT;
1494 unsigned long end_index = end >> PAGE_SHIFT;
1497 while (index <= end_index) {
1498 page = find_get_page(inode->i_mapping, index);
1499 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1500 clear_page_dirty_for_io(page);
1506 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1508 unsigned long index = start >> PAGE_SHIFT;
1509 unsigned long end_index = end >> PAGE_SHIFT;
1512 while (index <= end_index) {
1513 page = find_get_page(inode->i_mapping, index);
1514 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1515 __set_page_dirty_nobuffers(page);
1516 account_page_redirty(page);
1522 /* find the first state struct with 'bits' set after 'start', and
1523 * return it. tree->lock must be held. NULL will returned if
1524 * nothing was found after 'start'
1526 static struct extent_state *
1527 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1529 struct rb_node *node;
1530 struct extent_state *state;
1533 * this search will find all the extents that end after
1536 node = tree_search(tree, start);
1541 state = rb_entry(node, struct extent_state, rb_node);
1542 if (state->end >= start && (state->state & bits))
1545 node = rb_next(node);
1554 * Find the first offset in the io tree with one or more @bits set.
1556 * Note: If there are multiple bits set in @bits, any of them will match.
1558 * Return 0 if we find something, and update @start_ret and @end_ret.
1559 * Return 1 if we found nothing.
1561 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1562 u64 *start_ret, u64 *end_ret, u32 bits,
1563 struct extent_state **cached_state)
1565 struct extent_state *state;
1568 spin_lock(&tree->lock);
1569 if (cached_state && *cached_state) {
1570 state = *cached_state;
1571 if (state->end == start - 1 && extent_state_in_tree(state)) {
1572 while ((state = next_state(state)) != NULL) {
1573 if (state->state & bits)
1576 free_extent_state(*cached_state);
1577 *cached_state = NULL;
1580 free_extent_state(*cached_state);
1581 *cached_state = NULL;
1584 state = find_first_extent_bit_state(tree, start, bits);
1587 cache_state_if_flags(state, cached_state, 0);
1588 *start_ret = state->start;
1589 *end_ret = state->end;
1593 spin_unlock(&tree->lock);
1598 * Find a contiguous area of bits
1600 * @tree: io tree to check
1601 * @start: offset to start the search from
1602 * @start_ret: the first offset we found with the bits set
1603 * @end_ret: the final contiguous range of the bits that were set
1604 * @bits: bits to look for
1606 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1607 * to set bits appropriately, and then merge them again. During this time it
1608 * will drop the tree->lock, so use this helper if you want to find the actual
1609 * contiguous area for given bits. We will search to the first bit we find, and
1610 * then walk down the tree until we find a non-contiguous area. The area
1611 * returned will be the full contiguous area with the bits set.
1613 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1614 u64 *start_ret, u64 *end_ret, u32 bits)
1616 struct extent_state *state;
1619 spin_lock(&tree->lock);
1620 state = find_first_extent_bit_state(tree, start, bits);
1622 *start_ret = state->start;
1623 *end_ret = state->end;
1624 while ((state = next_state(state)) != NULL) {
1625 if (state->start > (*end_ret + 1))
1627 *end_ret = state->end;
1631 spin_unlock(&tree->lock);
1636 * Find the first range that has @bits not set. This range could start before
1639 * @tree: the tree to search
1640 * @start: offset at/after which the found extent should start
1641 * @start_ret: records the beginning of the range
1642 * @end_ret: records the end of the range (inclusive)
1643 * @bits: the set of bits which must be unset
1645 * Since unallocated range is also considered one which doesn't have the bits
1646 * set it's possible that @end_ret contains -1, this happens in case the range
1647 * spans (last_range_end, end of device]. In this case it's up to the caller to
1648 * trim @end_ret to the appropriate size.
1650 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1651 u64 *start_ret, u64 *end_ret, u32 bits)
1653 struct extent_state *state;
1654 struct rb_node *node, *prev = NULL, *next;
1656 spin_lock(&tree->lock);
1658 /* Find first extent with bits cleared */
1660 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1661 if (!node && !next && !prev) {
1663 * Tree is completely empty, send full range and let
1664 * caller deal with it
1669 } else if (!node && !next) {
1671 * We are past the last allocated chunk, set start at
1672 * the end of the last extent.
1674 state = rb_entry(prev, struct extent_state, rb_node);
1675 *start_ret = state->end + 1;
1682 * At this point 'node' either contains 'start' or start is
1685 state = rb_entry(node, struct extent_state, rb_node);
1687 if (in_range(start, state->start, state->end - state->start + 1)) {
1688 if (state->state & bits) {
1690 * |--range with bits sets--|
1694 start = state->end + 1;
1697 * 'start' falls within a range that doesn't
1698 * have the bits set, so take its start as
1699 * the beginning of the desired range
1701 * |--range with bits cleared----|
1705 *start_ret = state->start;
1710 * |---prev range---|---hole/unset---|---node range---|
1716 * |---hole/unset--||--first node--|
1721 state = rb_entry(prev, struct extent_state,
1723 *start_ret = state->end + 1;
1732 * Find the longest stretch from start until an entry which has the
1736 state = rb_entry(node, struct extent_state, rb_node);
1737 if (state->end >= start && !(state->state & bits)) {
1738 *end_ret = state->end;
1740 *end_ret = state->start - 1;
1744 node = rb_next(node);
1749 spin_unlock(&tree->lock);
1753 * find a contiguous range of bytes in the file marked as delalloc, not
1754 * more than 'max_bytes'. start and end are used to return the range,
1756 * true is returned if we find something, false if nothing was in the tree
1758 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1759 u64 *end, u64 max_bytes,
1760 struct extent_state **cached_state)
1762 struct rb_node *node;
1763 struct extent_state *state;
1764 u64 cur_start = *start;
1766 u64 total_bytes = 0;
1768 spin_lock(&tree->lock);
1771 * this search will find all the extents that end after
1774 node = tree_search(tree, cur_start);
1781 state = rb_entry(node, struct extent_state, rb_node);
1782 if (found && (state->start != cur_start ||
1783 (state->state & EXTENT_BOUNDARY))) {
1786 if (!(state->state & EXTENT_DELALLOC)) {
1792 *start = state->start;
1793 *cached_state = state;
1794 refcount_inc(&state->refs);
1798 cur_start = state->end + 1;
1799 node = rb_next(node);
1800 total_bytes += state->end - state->start + 1;
1801 if (total_bytes >= max_bytes)
1807 spin_unlock(&tree->lock);
1812 * Process one page for __process_pages_contig().
1814 * Return >0 if we hit @page == @locked_page.
1815 * Return 0 if we updated the page status.
1816 * Return -EGAIN if the we need to try again.
1817 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1819 static int process_one_page(struct btrfs_fs_info *fs_info,
1820 struct address_space *mapping,
1821 struct page *page, struct page *locked_page,
1822 unsigned long page_ops, u64 start, u64 end)
1826 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1827 len = end + 1 - start;
1829 if (page_ops & PAGE_SET_ORDERED)
1830 SetPageOrdered(page);
1832 if (page == locked_page)
1835 if (page_ops & PAGE_SET_ERROR)
1836 btrfs_page_clamp_set_error(fs_info, page, start, len);
1837 if (page_ops & PAGE_START_WRITEBACK) {
1838 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1839 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1841 if (page_ops & PAGE_END_WRITEBACK)
1842 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1843 if (page_ops & PAGE_LOCK) {
1845 if (!PageDirty(page) || page->mapping != mapping) {
1850 if (page_ops & PAGE_UNLOCK)
1855 static int __process_pages_contig(struct address_space *mapping,
1856 struct page *locked_page,
1857 u64 start, u64 end, unsigned long page_ops,
1860 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1861 pgoff_t start_index = start >> PAGE_SHIFT;
1862 pgoff_t end_index = end >> PAGE_SHIFT;
1863 pgoff_t index = start_index;
1864 unsigned long nr_pages = end_index - start_index + 1;
1865 unsigned long pages_processed = 0;
1866 struct page *pages[16];
1870 if (page_ops & PAGE_LOCK) {
1871 ASSERT(page_ops == PAGE_LOCK);
1872 ASSERT(processed_end && *processed_end == start);
1875 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1876 mapping_set_error(mapping, -EIO);
1878 while (nr_pages > 0) {
1881 found_pages = find_get_pages_contig(mapping, index,
1882 min_t(unsigned long,
1883 nr_pages, ARRAY_SIZE(pages)), pages);
1884 if (found_pages == 0) {
1886 * Only if we're going to lock these pages, we can find
1887 * nothing at @index.
1889 ASSERT(page_ops & PAGE_LOCK);
1894 for (i = 0; i < found_pages; i++) {
1897 process_ret = process_one_page(fs_info, mapping,
1898 pages[i], locked_page, page_ops,
1900 if (process_ret < 0) {
1901 for (; i < found_pages; i++)
1909 nr_pages -= found_pages;
1910 index += found_pages;
1914 if (err && processed_end) {
1916 * Update @processed_end. I know this is awful since it has
1917 * two different return value patterns (inclusive vs exclusive).
1919 * But the exclusive pattern is necessary if @start is 0, or we
1920 * underflow and check against processed_end won't work as
1923 if (pages_processed)
1924 *processed_end = min(end,
1925 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1927 *processed_end = start;
1932 static noinline void __unlock_for_delalloc(struct inode *inode,
1933 struct page *locked_page,
1936 unsigned long index = start >> PAGE_SHIFT;
1937 unsigned long end_index = end >> PAGE_SHIFT;
1939 ASSERT(locked_page);
1940 if (index == locked_page->index && end_index == index)
1943 __process_pages_contig(inode->i_mapping, locked_page, start, end,
1947 static noinline int lock_delalloc_pages(struct inode *inode,
1948 struct page *locked_page,
1952 unsigned long index = delalloc_start >> PAGE_SHIFT;
1953 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1954 u64 processed_end = delalloc_start;
1957 ASSERT(locked_page);
1958 if (index == locked_page->index && index == end_index)
1961 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1962 delalloc_end, PAGE_LOCK, &processed_end);
1963 if (ret == -EAGAIN && processed_end > delalloc_start)
1964 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1970 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1971 * more than @max_bytes. @Start and @end are used to return the range,
1973 * Return: true if we find something
1974 * false if nothing was in the tree
1977 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1978 struct page *locked_page, u64 *start,
1981 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1982 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1986 struct extent_state *cached_state = NULL;
1991 /* step one, find a bunch of delalloc bytes starting at start */
1992 delalloc_start = *start;
1994 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1995 max_bytes, &cached_state);
1996 if (!found || delalloc_end <= *start) {
1997 *start = delalloc_start;
1998 *end = delalloc_end;
1999 free_extent_state(cached_state);
2004 * start comes from the offset of locked_page. We have to lock
2005 * pages in order, so we can't process delalloc bytes before
2008 if (delalloc_start < *start)
2009 delalloc_start = *start;
2012 * make sure to limit the number of pages we try to lock down
2014 if (delalloc_end + 1 - delalloc_start > max_bytes)
2015 delalloc_end = delalloc_start + max_bytes - 1;
2017 /* step two, lock all the pages after the page that has start */
2018 ret = lock_delalloc_pages(inode, locked_page,
2019 delalloc_start, delalloc_end);
2020 ASSERT(!ret || ret == -EAGAIN);
2021 if (ret == -EAGAIN) {
2022 /* some of the pages are gone, lets avoid looping by
2023 * shortening the size of the delalloc range we're searching
2025 free_extent_state(cached_state);
2026 cached_state = NULL;
2028 max_bytes = PAGE_SIZE;
2037 /* step three, lock the state bits for the whole range */
2038 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2040 /* then test to make sure it is all still delalloc */
2041 ret = test_range_bit(tree, delalloc_start, delalloc_end,
2042 EXTENT_DELALLOC, 1, cached_state);
2044 unlock_extent_cached(tree, delalloc_start, delalloc_end,
2046 __unlock_for_delalloc(inode, locked_page,
2047 delalloc_start, delalloc_end);
2051 free_extent_state(cached_state);
2052 *start = delalloc_start;
2053 *end = delalloc_end;
2058 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2059 struct page *locked_page,
2060 u32 clear_bits, unsigned long page_ops)
2062 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2064 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2065 start, end, page_ops, NULL);
2069 * count the number of bytes in the tree that have a given bit(s)
2070 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2071 * cached. The total number found is returned.
2073 u64 count_range_bits(struct extent_io_tree *tree,
2074 u64 *start, u64 search_end, u64 max_bytes,
2075 u32 bits, int contig)
2077 struct rb_node *node;
2078 struct extent_state *state;
2079 u64 cur_start = *start;
2080 u64 total_bytes = 0;
2084 if (WARN_ON(search_end <= cur_start))
2087 spin_lock(&tree->lock);
2088 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2089 total_bytes = tree->dirty_bytes;
2093 * this search will find all the extents that end after
2096 node = tree_search(tree, cur_start);
2101 state = rb_entry(node, struct extent_state, rb_node);
2102 if (state->start > search_end)
2104 if (contig && found && state->start > last + 1)
2106 if (state->end >= cur_start && (state->state & bits) == bits) {
2107 total_bytes += min(search_end, state->end) + 1 -
2108 max(cur_start, state->start);
2109 if (total_bytes >= max_bytes)
2112 *start = max(cur_start, state->start);
2116 } else if (contig && found) {
2119 node = rb_next(node);
2124 spin_unlock(&tree->lock);
2129 * set the private field for a given byte offset in the tree. If there isn't
2130 * an extent_state there already, this does nothing.
2132 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2133 struct io_failure_record *failrec)
2135 struct rb_node *node;
2136 struct extent_state *state;
2139 spin_lock(&tree->lock);
2141 * this search will find all the extents that end after
2144 node = tree_search(tree, start);
2149 state = rb_entry(node, struct extent_state, rb_node);
2150 if (state->start != start) {
2154 state->failrec = failrec;
2156 spin_unlock(&tree->lock);
2160 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2162 struct rb_node *node;
2163 struct extent_state *state;
2164 struct io_failure_record *failrec;
2166 spin_lock(&tree->lock);
2168 * this search will find all the extents that end after
2171 node = tree_search(tree, start);
2173 failrec = ERR_PTR(-ENOENT);
2176 state = rb_entry(node, struct extent_state, rb_node);
2177 if (state->start != start) {
2178 failrec = ERR_PTR(-ENOENT);
2182 failrec = state->failrec;
2184 spin_unlock(&tree->lock);
2189 * searches a range in the state tree for a given mask.
2190 * If 'filled' == 1, this returns 1 only if every extent in the tree
2191 * has the bits set. Otherwise, 1 is returned if any bit in the
2192 * range is found set.
2194 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2195 u32 bits, int filled, struct extent_state *cached)
2197 struct extent_state *state = NULL;
2198 struct rb_node *node;
2201 spin_lock(&tree->lock);
2202 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2203 cached->end > start)
2204 node = &cached->rb_node;
2206 node = tree_search(tree, start);
2207 while (node && start <= end) {
2208 state = rb_entry(node, struct extent_state, rb_node);
2210 if (filled && state->start > start) {
2215 if (state->start > end)
2218 if (state->state & bits) {
2222 } else if (filled) {
2227 if (state->end == (u64)-1)
2230 start = state->end + 1;
2233 node = rb_next(node);
2240 spin_unlock(&tree->lock);
2245 * helper function to set a given page up to date if all the
2246 * extents in the tree for that page are up to date
2248 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2250 u64 start = page_offset(page);
2251 u64 end = start + PAGE_SIZE - 1;
2252 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2253 SetPageUptodate(page);
2256 int free_io_failure(struct extent_io_tree *failure_tree,
2257 struct extent_io_tree *io_tree,
2258 struct io_failure_record *rec)
2263 set_state_failrec(failure_tree, rec->start, NULL);
2264 ret = clear_extent_bits(failure_tree, rec->start,
2265 rec->start + rec->len - 1,
2266 EXTENT_LOCKED | EXTENT_DIRTY);
2270 ret = clear_extent_bits(io_tree, rec->start,
2271 rec->start + rec->len - 1,
2281 * this bypasses the standard btrfs submit functions deliberately, as
2282 * the standard behavior is to write all copies in a raid setup. here we only
2283 * want to write the one bad copy. so we do the mapping for ourselves and issue
2284 * submit_bio directly.
2285 * to avoid any synchronization issues, wait for the data after writing, which
2286 * actually prevents the read that triggered the error from finishing.
2287 * currently, there can be no more than two copies of every data bit. thus,
2288 * exactly one rewrite is required.
2290 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2291 u64 length, u64 logical, struct page *page,
2292 unsigned int pg_offset, int mirror_num)
2295 struct btrfs_device *dev;
2298 struct btrfs_bio *bbio = NULL;
2301 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2302 BUG_ON(!mirror_num);
2304 if (btrfs_is_zoned(fs_info))
2305 return btrfs_repair_one_zone(fs_info, logical);
2307 bio = btrfs_io_bio_alloc(1);
2308 bio->bi_iter.bi_size = 0;
2309 map_length = length;
2312 * Avoid races with device replace and make sure our bbio has devices
2313 * associated to its stripes that don't go away while we are doing the
2314 * read repair operation.
2316 btrfs_bio_counter_inc_blocked(fs_info);
2317 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2319 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2320 * to update all raid stripes, but here we just want to correct
2321 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2322 * stripe's dev and sector.
2324 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2325 &map_length, &bbio, 0);
2327 btrfs_bio_counter_dec(fs_info);
2331 ASSERT(bbio->mirror_num == 1);
2333 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2334 &map_length, &bbio, mirror_num);
2336 btrfs_bio_counter_dec(fs_info);
2340 BUG_ON(mirror_num != bbio->mirror_num);
2343 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2344 bio->bi_iter.bi_sector = sector;
2345 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2346 btrfs_put_bbio(bbio);
2347 if (!dev || !dev->bdev ||
2348 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2349 btrfs_bio_counter_dec(fs_info);
2353 bio_set_dev(bio, dev->bdev);
2354 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2355 bio_add_page(bio, page, length, pg_offset);
2357 if (btrfsic_submit_bio_wait(bio)) {
2358 /* try to remap that extent elsewhere? */
2359 btrfs_bio_counter_dec(fs_info);
2361 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2365 btrfs_info_rl_in_rcu(fs_info,
2366 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2368 rcu_str_deref(dev->name), sector);
2369 btrfs_bio_counter_dec(fs_info);
2374 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2376 struct btrfs_fs_info *fs_info = eb->fs_info;
2377 u64 start = eb->start;
2378 int i, num_pages = num_extent_pages(eb);
2381 if (sb_rdonly(fs_info->sb))
2384 for (i = 0; i < num_pages; i++) {
2385 struct page *p = eb->pages[i];
2387 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2388 start - page_offset(p), mirror_num);
2398 * each time an IO finishes, we do a fast check in the IO failure tree
2399 * to see if we need to process or clean up an io_failure_record
2401 int clean_io_failure(struct btrfs_fs_info *fs_info,
2402 struct extent_io_tree *failure_tree,
2403 struct extent_io_tree *io_tree, u64 start,
2404 struct page *page, u64 ino, unsigned int pg_offset)
2407 struct io_failure_record *failrec;
2408 struct extent_state *state;
2413 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2418 failrec = get_state_failrec(failure_tree, start);
2419 if (IS_ERR(failrec))
2422 BUG_ON(!failrec->this_mirror);
2424 if (sb_rdonly(fs_info->sb))
2427 spin_lock(&io_tree->lock);
2428 state = find_first_extent_bit_state(io_tree,
2431 spin_unlock(&io_tree->lock);
2433 if (state && state->start <= failrec->start &&
2434 state->end >= failrec->start + failrec->len - 1) {
2435 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2437 if (num_copies > 1) {
2438 repair_io_failure(fs_info, ino, start, failrec->len,
2439 failrec->logical, page, pg_offset,
2440 failrec->failed_mirror);
2445 free_io_failure(failure_tree, io_tree, failrec);
2451 * Can be called when
2452 * - hold extent lock
2453 * - under ordered extent
2454 * - the inode is freeing
2456 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2458 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2459 struct io_failure_record *failrec;
2460 struct extent_state *state, *next;
2462 if (RB_EMPTY_ROOT(&failure_tree->state))
2465 spin_lock(&failure_tree->lock);
2466 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2468 if (state->start > end)
2471 ASSERT(state->end <= end);
2473 next = next_state(state);
2475 failrec = state->failrec;
2476 free_extent_state(state);
2481 spin_unlock(&failure_tree->lock);
2484 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2487 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2488 struct io_failure_record *failrec;
2489 struct extent_map *em;
2490 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2491 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2492 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2493 const u32 sectorsize = fs_info->sectorsize;
2497 failrec = get_state_failrec(failure_tree, start);
2498 if (!IS_ERR(failrec)) {
2499 btrfs_debug(fs_info,
2500 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2501 failrec->logical, failrec->start, failrec->len);
2503 * when data can be on disk more than twice, add to failrec here
2504 * (e.g. with a list for failed_mirror) to make
2505 * clean_io_failure() clean all those errors at once.
2511 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2513 return ERR_PTR(-ENOMEM);
2515 failrec->start = start;
2516 failrec->len = sectorsize;
2517 failrec->this_mirror = 0;
2518 failrec->bio_flags = 0;
2520 read_lock(&em_tree->lock);
2521 em = lookup_extent_mapping(em_tree, start, failrec->len);
2523 read_unlock(&em_tree->lock);
2525 return ERR_PTR(-EIO);
2528 if (em->start > start || em->start + em->len <= start) {
2529 free_extent_map(em);
2532 read_unlock(&em_tree->lock);
2535 return ERR_PTR(-EIO);
2538 logical = start - em->start;
2539 logical = em->block_start + logical;
2540 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2541 logical = em->block_start;
2542 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2543 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2546 btrfs_debug(fs_info,
2547 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2548 logical, start, failrec->len);
2550 failrec->logical = logical;
2551 free_extent_map(em);
2553 /* Set the bits in the private failure tree */
2554 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2555 EXTENT_LOCKED | EXTENT_DIRTY);
2557 ret = set_state_failrec(failure_tree, start, failrec);
2558 /* Set the bits in the inode's tree */
2559 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2561 } else if (ret < 0) {
2563 return ERR_PTR(ret);
2569 static bool btrfs_check_repairable(struct inode *inode,
2570 struct io_failure_record *failrec,
2573 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2576 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2577 if (num_copies == 1) {
2579 * we only have a single copy of the data, so don't bother with
2580 * all the retry and error correction code that follows. no
2581 * matter what the error is, it is very likely to persist.
2583 btrfs_debug(fs_info,
2584 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2585 num_copies, failrec->this_mirror, failed_mirror);
2589 /* The failure record should only contain one sector */
2590 ASSERT(failrec->len == fs_info->sectorsize);
2593 * There are two premises:
2594 * a) deliver good data to the caller
2595 * b) correct the bad sectors on disk
2597 * Since we're only doing repair for one sector, we only need to get
2598 * a good copy of the failed sector and if we succeed, we have setup
2599 * everything for repair_io_failure to do the rest for us.
2601 failrec->failed_mirror = failed_mirror;
2602 failrec->this_mirror++;
2603 if (failrec->this_mirror == failed_mirror)
2604 failrec->this_mirror++;
2606 if (failrec->this_mirror > num_copies) {
2607 btrfs_debug(fs_info,
2608 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2609 num_copies, failrec->this_mirror, failed_mirror);
2616 int btrfs_repair_one_sector(struct inode *inode,
2617 struct bio *failed_bio, u32 bio_offset,
2618 struct page *page, unsigned int pgoff,
2619 u64 start, int failed_mirror,
2620 submit_bio_hook_t *submit_bio_hook)
2622 struct io_failure_record *failrec;
2623 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2624 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2625 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2626 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2627 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2628 struct bio *repair_bio;
2629 struct btrfs_io_bio *repair_io_bio;
2630 blk_status_t status;
2632 btrfs_debug(fs_info,
2633 "repair read error: read error at %llu", start);
2635 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2637 failrec = btrfs_get_io_failure_record(inode, start);
2638 if (IS_ERR(failrec))
2639 return PTR_ERR(failrec);
2642 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2643 free_io_failure(failure_tree, tree, failrec);
2647 repair_bio = btrfs_io_bio_alloc(1);
2648 repair_io_bio = btrfs_io_bio(repair_bio);
2649 repair_bio->bi_opf = REQ_OP_READ;
2650 repair_bio->bi_end_io = failed_bio->bi_end_io;
2651 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2652 repair_bio->bi_private = failed_bio->bi_private;
2654 if (failed_io_bio->csum) {
2655 const u32 csum_size = fs_info->csum_size;
2657 repair_io_bio->csum = repair_io_bio->csum_inline;
2658 memcpy(repair_io_bio->csum,
2659 failed_io_bio->csum + csum_size * icsum, csum_size);
2662 bio_add_page(repair_bio, page, failrec->len, pgoff);
2663 repair_io_bio->logical = failrec->start;
2664 repair_io_bio->iter = repair_bio->bi_iter;
2666 btrfs_debug(btrfs_sb(inode->i_sb),
2667 "repair read error: submitting new read to mirror %d",
2668 failrec->this_mirror);
2670 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2671 failrec->bio_flags);
2673 free_io_failure(failure_tree, tree, failrec);
2674 bio_put(repair_bio);
2676 return blk_status_to_errno(status);
2679 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2681 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2683 ASSERT(page_offset(page) <= start &&
2684 start + len <= page_offset(page) + PAGE_SIZE);
2687 * For subapge metadata case, all btrfs_page_* helpers need page to
2688 * have page::private populated.
2689 * But we can have rare case where the last eb in the page is only
2690 * referred by the IO, and it gets released immedately after it's
2691 * read and verified.
2693 * This can detach the page private completely.
2694 * In that case, we can just skip the page status update completely,
2695 * as the page has no eb anymore.
2697 if (fs_info->sectorsize < PAGE_SIZE && unlikely(!PagePrivate(page))) {
2698 ASSERT(!is_data_inode(page->mapping->host));
2702 btrfs_page_set_uptodate(fs_info, page, start, len);
2704 btrfs_page_clear_uptodate(fs_info, page, start, len);
2705 btrfs_page_set_error(fs_info, page, start, len);
2708 if (fs_info->sectorsize == PAGE_SIZE)
2710 else if (is_data_inode(page->mapping->host))
2712 * For subpage data, unlock the page if we're the last reader.
2713 * For subpage metadata, page lock is not utilized for read.
2715 btrfs_subpage_end_reader(fs_info, page, start, len);
2718 static blk_status_t submit_read_repair(struct inode *inode,
2719 struct bio *failed_bio, u32 bio_offset,
2720 struct page *page, unsigned int pgoff,
2721 u64 start, u64 end, int failed_mirror,
2722 unsigned int error_bitmap,
2723 submit_bio_hook_t *submit_bio_hook)
2725 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2726 const u32 sectorsize = fs_info->sectorsize;
2727 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2731 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2733 /* We're here because we had some read errors or csum mismatch */
2734 ASSERT(error_bitmap);
2737 * We only get called on buffered IO, thus page must be mapped and bio
2738 * must not be cloned.
2740 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2742 /* Iterate through all the sectors in the range */
2743 for (i = 0; i < nr_bits; i++) {
2744 const unsigned int offset = i * sectorsize;
2745 struct extent_state *cached = NULL;
2746 bool uptodate = false;
2749 if (!(error_bitmap & (1U << i))) {
2751 * This sector has no error, just end the page read
2752 * and unlock the range.
2758 ret = btrfs_repair_one_sector(inode, failed_bio,
2759 bio_offset + offset,
2760 page, pgoff + offset, start + offset,
2761 failed_mirror, submit_bio_hook);
2764 * We have submitted the read repair, the page release
2765 * will be handled by the endio function of the
2766 * submitted repair bio.
2767 * Thus we don't need to do any thing here.
2772 * Repair failed, just record the error but still continue.
2773 * Or the remaining sectors will not be properly unlocked.
2778 end_page_read(page, uptodate, start + offset, sectorsize);
2780 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2782 start + offset + sectorsize - 1,
2783 &cached, GFP_ATOMIC);
2784 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2786 start + offset + sectorsize - 1,
2789 return errno_to_blk_status(error);
2792 /* lots and lots of room for performance fixes in the end_bio funcs */
2794 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2796 struct btrfs_inode *inode;
2797 int uptodate = (err == 0);
2800 ASSERT(page && page->mapping);
2801 inode = BTRFS_I(page->mapping->host);
2802 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2805 ClearPageUptodate(page);
2807 ret = err < 0 ? err : -EIO;
2808 mapping_set_error(page->mapping, ret);
2813 * after a writepage IO is done, we need to:
2814 * clear the uptodate bits on error
2815 * clear the writeback bits in the extent tree for this IO
2816 * end_page_writeback if the page has no more pending IO
2818 * Scheduling is not allowed, so the extent state tree is expected
2819 * to have one and only one object corresponding to this IO.
2821 static void end_bio_extent_writepage(struct bio *bio)
2823 int error = blk_status_to_errno(bio->bi_status);
2824 struct bio_vec *bvec;
2827 struct bvec_iter_all iter_all;
2828 bool first_bvec = true;
2830 ASSERT(!bio_flagged(bio, BIO_CLONED));
2831 bio_for_each_segment_all(bvec, bio, iter_all) {
2832 struct page *page = bvec->bv_page;
2833 struct inode *inode = page->mapping->host;
2834 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2835 const u32 sectorsize = fs_info->sectorsize;
2837 /* Our read/write should always be sector aligned. */
2838 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2840 "partial page write in btrfs with offset %u and length %u",
2841 bvec->bv_offset, bvec->bv_len);
2842 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2844 "incomplete page write with offset %u and length %u",
2845 bvec->bv_offset, bvec->bv_len);
2847 start = page_offset(page) + bvec->bv_offset;
2848 end = start + bvec->bv_len - 1;
2851 btrfs_record_physical_zoned(inode, start, bio);
2855 end_extent_writepage(page, error, start, end);
2857 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2864 * Record previously processed extent range
2866 * For endio_readpage_release_extent() to handle a full extent range, reducing
2867 * the extent io operations.
2869 struct processed_extent {
2870 struct btrfs_inode *inode;
2871 /* Start of the range in @inode */
2873 /* End of the range in @inode */
2879 * Try to release processed extent range
2881 * May not release the extent range right now if the current range is
2882 * contiguous to processed extent.
2884 * Will release processed extent when any of @inode, @uptodate, the range is
2885 * no longer contiguous to the processed range.
2887 * Passing @inode == NULL will force processed extent to be released.
2889 static void endio_readpage_release_extent(struct processed_extent *processed,
2890 struct btrfs_inode *inode, u64 start, u64 end,
2893 struct extent_state *cached = NULL;
2894 struct extent_io_tree *tree;
2896 /* The first extent, initialize @processed */
2897 if (!processed->inode)
2901 * Contiguous to processed extent, just uptodate the end.
2903 * Several things to notice:
2905 * - bio can be merged as long as on-disk bytenr is contiguous
2906 * This means we can have page belonging to other inodes, thus need to
2907 * check if the inode still matches.
2908 * - bvec can contain range beyond current page for multi-page bvec
2909 * Thus we need to do processed->end + 1 >= start check
2911 if (processed->inode == inode && processed->uptodate == uptodate &&
2912 processed->end + 1 >= start && end >= processed->end) {
2913 processed->end = end;
2917 tree = &processed->inode->io_tree;
2919 * Now we don't have range contiguous to the processed range, release
2920 * the processed range now.
2922 if (processed->uptodate && tree->track_uptodate)
2923 set_extent_uptodate(tree, processed->start, processed->end,
2924 &cached, GFP_ATOMIC);
2925 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2929 /* Update processed to current range */
2930 processed->inode = inode;
2931 processed->start = start;
2932 processed->end = end;
2933 processed->uptodate = uptodate;
2936 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2938 ASSERT(PageLocked(page));
2939 if (fs_info->sectorsize == PAGE_SIZE)
2942 ASSERT(PagePrivate(page));
2943 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2947 * Find extent buffer for a givne bytenr.
2949 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2952 static struct extent_buffer *find_extent_buffer_readpage(
2953 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2955 struct extent_buffer *eb;
2958 * For regular sectorsize, we can use page->private to grab extent
2961 if (fs_info->sectorsize == PAGE_SIZE) {
2962 ASSERT(PagePrivate(page) && page->private);
2963 return (struct extent_buffer *)page->private;
2966 /* For subpage case, we need to lookup buffer radix tree */
2968 eb = radix_tree_lookup(&fs_info->buffer_radix,
2969 bytenr >> fs_info->sectorsize_bits);
2976 * after a readpage IO is done, we need to:
2977 * clear the uptodate bits on error
2978 * set the uptodate bits if things worked
2979 * set the page up to date if all extents in the tree are uptodate
2980 * clear the lock bit in the extent tree
2981 * unlock the page if there are no other extents locked for it
2983 * Scheduling is not allowed, so the extent state tree is expected
2984 * to have one and only one object corresponding to this IO.
2986 static void end_bio_extent_readpage(struct bio *bio)
2988 struct bio_vec *bvec;
2989 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2990 struct extent_io_tree *tree, *failure_tree;
2991 struct processed_extent processed = { 0 };
2993 * The offset to the beginning of a bio, since one bio can never be
2994 * larger than UINT_MAX, u32 here is enough.
2999 struct bvec_iter_all iter_all;
3001 ASSERT(!bio_flagged(bio, BIO_CLONED));
3002 bio_for_each_segment_all(bvec, bio, iter_all) {
3003 bool uptodate = !bio->bi_status;
3004 struct page *page = bvec->bv_page;
3005 struct inode *inode = page->mapping->host;
3006 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3007 const u32 sectorsize = fs_info->sectorsize;
3008 unsigned int error_bitmap = (unsigned int)-1;
3013 btrfs_debug(fs_info,
3014 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3015 bio->bi_iter.bi_sector, bio->bi_status,
3016 io_bio->mirror_num);
3017 tree = &BTRFS_I(inode)->io_tree;
3018 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3021 * We always issue full-sector reads, but if some block in a
3022 * page fails to read, blk_update_request() will advance
3023 * bv_offset and adjust bv_len to compensate. Print a warning
3024 * for unaligned offsets, and an error if they don't add up to
3027 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3029 "partial page read in btrfs with offset %u and length %u",
3030 bvec->bv_offset, bvec->bv_len);
3031 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3034 "incomplete page read with offset %u and length %u",
3035 bvec->bv_offset, bvec->bv_len);
3037 start = page_offset(page) + bvec->bv_offset;
3038 end = start + bvec->bv_len - 1;
3041 mirror = io_bio->mirror_num;
3042 if (likely(uptodate)) {
3043 if (is_data_inode(inode)) {
3044 error_bitmap = btrfs_verify_data_csum(io_bio,
3045 bio_offset, page, start, end);
3048 ret = btrfs_validate_metadata_buffer(io_bio,
3049 page, start, end, mirror);
3054 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3055 failure_tree, tree, start,
3057 btrfs_ino(BTRFS_I(inode)), 0);
3060 if (likely(uptodate))
3063 if (is_data_inode(inode)) {
3065 * btrfs_submit_read_repair() will handle all the good
3066 * and bad sectors, we just continue to the next bvec.
3068 submit_read_repair(inode, bio, bio_offset, page,
3069 start - page_offset(page), start,
3070 end, mirror, error_bitmap,
3071 btrfs_submit_data_bio);
3073 ASSERT(bio_offset + len > bio_offset);
3077 struct extent_buffer *eb;
3079 eb = find_extent_buffer_readpage(fs_info, page, start);
3080 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3081 eb->read_mirror = mirror;
3082 atomic_dec(&eb->io_pages);
3083 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
3085 btree_readahead_hook(eb, -EIO);
3088 if (likely(uptodate)) {
3089 loff_t i_size = i_size_read(inode);
3090 pgoff_t end_index = i_size >> PAGE_SHIFT;
3093 * Zero out the remaining part if this range straddles
3096 * Here we should only zero the range inside the bvec,
3097 * not touch anything else.
3099 * NOTE: i_size is exclusive while end is inclusive.
3101 if (page->index == end_index && i_size <= end) {
3102 u32 zero_start = max(offset_in_page(i_size),
3103 offset_in_page(start));
3105 zero_user_segment(page, zero_start,
3106 offset_in_page(end) + 1);
3109 ASSERT(bio_offset + len > bio_offset);
3112 /* Update page status and unlock */
3113 end_page_read(page, uptodate, start, len);
3114 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3115 start, end, uptodate);
3117 /* Release the last extent */
3118 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3119 btrfs_io_bio_free_csum(io_bio);
3124 * Initialize the members up to but not including 'bio'. Use after allocating a
3125 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3126 * 'bio' because use of __GFP_ZERO is not supported.
3128 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3130 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3134 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3135 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3136 * for the appropriate container_of magic
3138 struct bio *btrfs_bio_alloc(u64 first_byte)
3142 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &btrfs_bioset);
3143 bio->bi_iter.bi_sector = first_byte >> 9;
3144 btrfs_io_bio_init(btrfs_io_bio(bio));
3148 struct bio *btrfs_bio_clone(struct bio *bio)
3150 struct btrfs_io_bio *btrfs_bio;
3153 /* Bio allocation backed by a bioset does not fail */
3154 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3155 btrfs_bio = btrfs_io_bio(new);
3156 btrfs_io_bio_init(btrfs_bio);
3157 btrfs_bio->iter = bio->bi_iter;
3161 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3165 /* Bio allocation backed by a bioset does not fail */
3166 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3167 btrfs_io_bio_init(btrfs_io_bio(bio));
3171 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
3174 struct btrfs_io_bio *btrfs_bio;
3176 /* this will never fail when it's backed by a bioset */
3177 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3180 btrfs_bio = btrfs_io_bio(bio);
3181 btrfs_io_bio_init(btrfs_bio);
3183 bio_trim(bio, offset >> 9, size >> 9);
3184 btrfs_bio->iter = bio->bi_iter;
3189 * Attempt to add a page to bio
3191 * @bio: destination bio
3192 * @page: page to add to the bio
3193 * @disk_bytenr: offset of the new bio or to check whether we are adding
3194 * a contiguous page to the previous one
3195 * @pg_offset: starting offset in the page
3196 * @size: portion of page that we want to write
3197 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3198 * @bio_flags: flags of the current bio to see if we can merge them
3199 * @return: true if page was added, false otherwise
3201 * Attempt to add a page to bio considering stripe alignment etc.
3203 * Return true if successfully page added. Otherwise, return false.
3205 static bool btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3207 u64 disk_bytenr, unsigned int size,
3208 unsigned int pg_offset,
3209 unsigned long bio_flags)
3211 struct bio *bio = bio_ctrl->bio;
3212 u32 bio_size = bio->bi_iter.bi_size;
3213 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3218 /* The limit should be calculated when bio_ctrl->bio is allocated */
3219 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3220 if (bio_ctrl->bio_flags != bio_flags)
3223 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED)
3224 contig = bio->bi_iter.bi_sector == sector;
3226 contig = bio_end_sector(bio) == sector;
3230 if (bio_size + size > bio_ctrl->len_to_oe_boundary ||
3231 bio_size + size > bio_ctrl->len_to_stripe_boundary)
3234 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3235 ret = bio_add_zone_append_page(bio, page, size, pg_offset);
3237 ret = bio_add_page(bio, page, size, pg_offset);
3242 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3243 struct btrfs_inode *inode)
3245 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3246 struct btrfs_io_geometry geom;
3247 struct btrfs_ordered_extent *ordered;
3248 struct extent_map *em;
3249 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3253 * Pages for compressed extent are never submitted to disk directly,
3254 * thus it has no real boundary, just set them to U32_MAX.
3256 * The split happens for real compressed bio, which happens in
3257 * btrfs_submit_compressed_read/write().
3259 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED) {
3260 bio_ctrl->len_to_oe_boundary = U32_MAX;
3261 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3264 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3267 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3269 free_extent_map(em);
3273 if (geom.len > U32_MAX)
3274 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3276 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3278 if (!btrfs_is_zoned(fs_info) ||
3279 bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3280 bio_ctrl->len_to_oe_boundary = U32_MAX;
3284 ASSERT(fs_info->max_zone_append_size > 0);
3285 /* Ordered extent not yet created, so we're good */
3286 ordered = btrfs_lookup_ordered_extent(inode, logical);
3288 bio_ctrl->len_to_oe_boundary = U32_MAX;
3292 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3293 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3294 btrfs_put_ordered_extent(ordered);
3299 * @opf: bio REQ_OP_* and REQ_* flags as one value
3300 * @wbc: optional writeback control for io accounting
3301 * @page: page to add to the bio
3302 * @disk_bytenr: logical bytenr where the write will be
3303 * @size: portion of page that we want to write to
3304 * @pg_offset: offset of the new bio or to check whether we are adding
3305 * a contiguous page to the previous one
3306 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3307 * @end_io_func: end_io callback for new bio
3308 * @mirror_num: desired mirror to read/write
3309 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3310 * @bio_flags: flags of the current bio to see if we can merge them
3312 static int submit_extent_page(unsigned int opf,
3313 struct writeback_control *wbc,
3314 struct btrfs_bio_ctrl *bio_ctrl,
3315 struct page *page, u64 disk_bytenr,
3316 size_t size, unsigned long pg_offset,
3317 bio_end_io_t end_io_func,
3319 unsigned long bio_flags,
3320 bool force_bio_submit)
3324 size_t io_size = min_t(size_t, size, PAGE_SIZE);
3325 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3326 struct extent_io_tree *tree = &inode->io_tree;
3327 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3331 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3332 pg_offset + size <= PAGE_SIZE);
3333 if (bio_ctrl->bio) {
3334 bio = bio_ctrl->bio;
3335 if (force_bio_submit ||
3336 !btrfs_bio_add_page(bio_ctrl, page, disk_bytenr, io_size,
3337 pg_offset, bio_flags)) {
3338 ret = submit_one_bio(bio, mirror_num, bio_ctrl->bio_flags);
3339 bio_ctrl->bio = NULL;
3344 wbc_account_cgroup_owner(wbc, page, io_size);
3349 bio = btrfs_bio_alloc(disk_bytenr);
3350 bio_add_page(bio, page, io_size, pg_offset);
3351 bio->bi_end_io = end_io_func;
3352 bio->bi_private = tree;
3353 bio->bi_write_hint = page->mapping->host->i_write_hint;
3356 struct block_device *bdev;
3358 bdev = fs_info->fs_devices->latest_bdev;
3359 bio_set_dev(bio, bdev);
3360 wbc_init_bio(wbc, bio);
3361 wbc_account_cgroup_owner(wbc, page, io_size);
3363 if (btrfs_is_zoned(fs_info) && bio_op(bio) == REQ_OP_ZONE_APPEND) {
3364 struct btrfs_device *device;
3366 device = btrfs_zoned_get_device(fs_info, disk_bytenr, io_size);
3368 return PTR_ERR(device);
3370 btrfs_io_bio(bio)->device = device;
3373 bio_ctrl->bio = bio;
3374 bio_ctrl->bio_flags = bio_flags;
3375 ret = calc_bio_boundaries(bio_ctrl, inode);
3380 static int attach_extent_buffer_page(struct extent_buffer *eb,
3382 struct btrfs_subpage *prealloc)
3384 struct btrfs_fs_info *fs_info = eb->fs_info;
3388 * If the page is mapped to btree inode, we should hold the private
3389 * lock to prevent race.
3390 * For cloned or dummy extent buffers, their pages are not mapped and
3391 * will not race with any other ebs.
3394 lockdep_assert_held(&page->mapping->private_lock);
3396 if (fs_info->sectorsize == PAGE_SIZE) {
3397 if (!PagePrivate(page))
3398 attach_page_private(page, eb);
3400 WARN_ON(page->private != (unsigned long)eb);
3404 /* Already mapped, just free prealloc */
3405 if (PagePrivate(page)) {
3406 btrfs_free_subpage(prealloc);
3411 /* Has preallocated memory for subpage */
3412 attach_page_private(page, prealloc);
3414 /* Do new allocation to attach subpage */
3415 ret = btrfs_attach_subpage(fs_info, page,
3416 BTRFS_SUBPAGE_METADATA);
3420 int set_page_extent_mapped(struct page *page)
3422 struct btrfs_fs_info *fs_info;
3424 ASSERT(page->mapping);
3426 if (PagePrivate(page))
3429 fs_info = btrfs_sb(page->mapping->host->i_sb);
3431 if (fs_info->sectorsize < PAGE_SIZE)
3432 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3434 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3438 void clear_page_extent_mapped(struct page *page)
3440 struct btrfs_fs_info *fs_info;
3442 ASSERT(page->mapping);
3444 if (!PagePrivate(page))
3447 fs_info = btrfs_sb(page->mapping->host->i_sb);
3448 if (fs_info->sectorsize < PAGE_SIZE)
3449 return btrfs_detach_subpage(fs_info, page);
3451 detach_page_private(page);
3454 static struct extent_map *
3455 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3456 u64 start, u64 len, struct extent_map **em_cached)
3458 struct extent_map *em;
3460 if (em_cached && *em_cached) {
3462 if (extent_map_in_tree(em) && start >= em->start &&
3463 start < extent_map_end(em)) {
3464 refcount_inc(&em->refs);
3468 free_extent_map(em);
3472 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3473 if (em_cached && !IS_ERR_OR_NULL(em)) {
3475 refcount_inc(&em->refs);
3481 * basic readpage implementation. Locked extent state structs are inserted
3482 * into the tree that are removed when the IO is done (by the end_io
3484 * XXX JDM: This needs looking at to ensure proper page locking
3485 * return 0 on success, otherwise return error
3487 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3488 struct btrfs_bio_ctrl *bio_ctrl,
3489 unsigned int read_flags, u64 *prev_em_start)
3491 struct inode *inode = page->mapping->host;
3492 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3493 u64 start = page_offset(page);
3494 const u64 end = start + PAGE_SIZE - 1;
3497 u64 last_byte = i_size_read(inode);
3500 struct extent_map *em;
3503 size_t pg_offset = 0;
3505 size_t blocksize = inode->i_sb->s_blocksize;
3506 unsigned long this_bio_flag = 0;
3507 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3509 ret = set_page_extent_mapped(page);
3511 unlock_extent(tree, start, end);
3512 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3517 if (!PageUptodate(page)) {
3518 if (cleancache_get_page(page) == 0) {
3519 BUG_ON(blocksize != PAGE_SIZE);
3520 unlock_extent(tree, start, end);
3526 if (page->index == last_byte >> PAGE_SHIFT) {
3527 size_t zero_offset = offset_in_page(last_byte);
3530 iosize = PAGE_SIZE - zero_offset;
3531 memzero_page(page, zero_offset, iosize);
3532 flush_dcache_page(page);
3535 begin_page_read(fs_info, page);
3536 while (cur <= end) {
3537 bool force_bio_submit = false;
3540 if (cur >= last_byte) {
3541 struct extent_state *cached = NULL;
3543 iosize = PAGE_SIZE - pg_offset;
3544 memzero_page(page, pg_offset, iosize);
3545 flush_dcache_page(page);
3546 set_extent_uptodate(tree, cur, cur + iosize - 1,
3548 unlock_extent_cached(tree, cur,
3549 cur + iosize - 1, &cached);
3550 end_page_read(page, true, cur, iosize);
3553 em = __get_extent_map(inode, page, pg_offset, cur,
3554 end - cur + 1, em_cached);
3555 if (IS_ERR_OR_NULL(em)) {
3556 unlock_extent(tree, cur, end);
3557 end_page_read(page, false, cur, end + 1 - cur);
3560 extent_offset = cur - em->start;
3561 BUG_ON(extent_map_end(em) <= cur);
3564 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3565 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3566 extent_set_compress_type(&this_bio_flag,
3570 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3571 cur_end = min(extent_map_end(em) - 1, end);
3572 iosize = ALIGN(iosize, blocksize);
3573 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3574 disk_bytenr = em->block_start;
3576 disk_bytenr = em->block_start + extent_offset;
3577 block_start = em->block_start;
3578 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3579 block_start = EXTENT_MAP_HOLE;
3582 * If we have a file range that points to a compressed extent
3583 * and it's followed by a consecutive file range that points
3584 * to the same compressed extent (possibly with a different
3585 * offset and/or length, so it either points to the whole extent
3586 * or only part of it), we must make sure we do not submit a
3587 * single bio to populate the pages for the 2 ranges because
3588 * this makes the compressed extent read zero out the pages
3589 * belonging to the 2nd range. Imagine the following scenario:
3592 * [0 - 8K] [8K - 24K]
3595 * points to extent X, points to extent X,
3596 * offset 4K, length of 8K offset 0, length 16K
3598 * [extent X, compressed length = 4K uncompressed length = 16K]
3600 * If the bio to read the compressed extent covers both ranges,
3601 * it will decompress extent X into the pages belonging to the
3602 * first range and then it will stop, zeroing out the remaining
3603 * pages that belong to the other range that points to extent X.
3604 * So here we make sure we submit 2 bios, one for the first
3605 * range and another one for the third range. Both will target
3606 * the same physical extent from disk, but we can't currently
3607 * make the compressed bio endio callback populate the pages
3608 * for both ranges because each compressed bio is tightly
3609 * coupled with a single extent map, and each range can have
3610 * an extent map with a different offset value relative to the
3611 * uncompressed data of our extent and different lengths. This
3612 * is a corner case so we prioritize correctness over
3613 * non-optimal behavior (submitting 2 bios for the same extent).
3615 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3616 prev_em_start && *prev_em_start != (u64)-1 &&
3617 *prev_em_start != em->start)
3618 force_bio_submit = true;
3621 *prev_em_start = em->start;
3623 free_extent_map(em);
3626 /* we've found a hole, just zero and go on */
3627 if (block_start == EXTENT_MAP_HOLE) {
3628 struct extent_state *cached = NULL;
3630 memzero_page(page, pg_offset, iosize);
3631 flush_dcache_page(page);
3633 set_extent_uptodate(tree, cur, cur + iosize - 1,
3635 unlock_extent_cached(tree, cur,
3636 cur + iosize - 1, &cached);
3637 end_page_read(page, true, cur, iosize);
3639 pg_offset += iosize;
3642 /* the get_extent function already copied into the page */
3643 if (test_range_bit(tree, cur, cur_end,
3644 EXTENT_UPTODATE, 1, NULL)) {
3645 check_page_uptodate(tree, page);
3646 unlock_extent(tree, cur, cur + iosize - 1);
3647 end_page_read(page, true, cur, iosize);
3649 pg_offset += iosize;
3652 /* we have an inline extent but it didn't get marked up
3653 * to date. Error out
3655 if (block_start == EXTENT_MAP_INLINE) {
3656 unlock_extent(tree, cur, cur + iosize - 1);
3657 end_page_read(page, false, cur, iosize);
3659 pg_offset += iosize;
3663 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3664 bio_ctrl, page, disk_bytenr, iosize,
3666 end_bio_extent_readpage, 0,
3672 unlock_extent(tree, cur, cur + iosize - 1);
3673 end_page_read(page, false, cur, iosize);
3677 pg_offset += iosize;
3683 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3685 struct extent_map **em_cached,
3686 struct btrfs_bio_ctrl *bio_ctrl,
3689 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3692 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3694 for (index = 0; index < nr_pages; index++) {
3695 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3696 REQ_RAHEAD, prev_em_start);
3697 put_page(pages[index]);
3701 static void update_nr_written(struct writeback_control *wbc,
3702 unsigned long nr_written)
3704 wbc->nr_to_write -= nr_written;
3708 * helper for __extent_writepage, doing all of the delayed allocation setup.
3710 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3711 * to write the page (copy into inline extent). In this case the IO has
3712 * been started and the page is already unlocked.
3714 * This returns 0 if all went well (page still locked)
3715 * This returns < 0 if there were errors (page still locked)
3717 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3718 struct page *page, struct writeback_control *wbc,
3719 u64 delalloc_start, unsigned long *nr_written)
3721 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3723 u64 delalloc_to_write = 0;
3724 u64 delalloc_end = 0;
3726 int page_started = 0;
3729 while (delalloc_end < page_end) {
3730 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3734 delalloc_start = delalloc_end + 1;
3737 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3738 delalloc_end, &page_started, nr_written, wbc);
3742 * btrfs_run_delalloc_range should return < 0 for error
3743 * but just in case, we use > 0 here meaning the IO is
3744 * started, so we don't want to return > 0 unless
3745 * things are going well.
3747 return ret < 0 ? ret : -EIO;
3750 * delalloc_end is already one less than the total length, so
3751 * we don't subtract one from PAGE_SIZE
3753 delalloc_to_write += (delalloc_end - delalloc_start +
3754 PAGE_SIZE) >> PAGE_SHIFT;
3755 delalloc_start = delalloc_end + 1;
3757 if (wbc->nr_to_write < delalloc_to_write) {
3760 if (delalloc_to_write < thresh * 2)
3761 thresh = delalloc_to_write;
3762 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3766 /* did the fill delalloc function already unlock and start
3771 * we've unlocked the page, so we can't update
3772 * the mapping's writeback index, just update
3775 wbc->nr_to_write -= *nr_written;
3783 * helper for __extent_writepage. This calls the writepage start hooks,
3784 * and does the loop to map the page into extents and bios.
3786 * We return 1 if the IO is started and the page is unlocked,
3787 * 0 if all went well (page still locked)
3788 * < 0 if there were errors (page still locked)
3790 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3792 struct writeback_control *wbc,
3793 struct extent_page_data *epd,
3795 unsigned long nr_written,
3798 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3799 struct extent_io_tree *tree = &inode->io_tree;
3800 u64 start = page_offset(page);
3801 u64 end = start + PAGE_SIZE - 1;
3805 struct extent_map *em;
3808 u32 opf = REQ_OP_WRITE;
3809 const unsigned int write_flags = wbc_to_write_flags(wbc);
3812 ret = btrfs_writepage_cow_fixup(page, start, end);
3814 /* Fixup worker will requeue */
3815 redirty_page_for_writepage(wbc, page);
3816 update_nr_written(wbc, nr_written);
3822 * we don't want to touch the inode after unlocking the page,
3823 * so we update the mapping writeback index now
3825 update_nr_written(wbc, nr_written + 1);
3827 while (cur <= end) {
3832 if (cur >= i_size) {
3833 btrfs_writepage_endio_finish_ordered(inode, page, cur,
3837 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3838 if (IS_ERR_OR_NULL(em)) {
3840 ret = PTR_ERR_OR_ZERO(em);
3844 extent_offset = cur - em->start;
3845 em_end = extent_map_end(em);
3846 ASSERT(cur <= em_end);
3848 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3849 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3850 block_start = em->block_start;
3851 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3852 disk_bytenr = em->block_start + extent_offset;
3854 /* Note that em_end from extent_map_end() is exclusive */
3855 iosize = min(em_end, end + 1) - cur;
3857 if (btrfs_use_zone_append(inode, em->block_start))
3858 opf = REQ_OP_ZONE_APPEND;
3860 free_extent_map(em);
3864 * compressed and inline extents are written through other
3867 if (compressed || block_start == EXTENT_MAP_HOLE ||
3868 block_start == EXTENT_MAP_INLINE) {
3872 btrfs_writepage_endio_finish_ordered(inode,
3873 page, cur, cur + iosize - 1, 1);
3878 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3879 if (!PageWriteback(page)) {
3880 btrfs_err(inode->root->fs_info,
3881 "page %lu not writeback, cur %llu end %llu",
3882 page->index, cur, end);
3885 ret = submit_extent_page(opf | write_flags, wbc,
3886 &epd->bio_ctrl, page,
3887 disk_bytenr, iosize,
3888 cur - page_offset(page),
3889 end_bio_extent_writepage,
3893 if (PageWriteback(page))
3894 end_page_writeback(page);
3905 * the writepage semantics are similar to regular writepage. extent
3906 * records are inserted to lock ranges in the tree, and as dirty areas
3907 * are found, they are marked writeback. Then the lock bits are removed
3908 * and the end_io handler clears the writeback ranges
3910 * Return 0 if everything goes well.
3911 * Return <0 for error.
3913 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3914 struct extent_page_data *epd)
3916 struct inode *inode = page->mapping->host;
3917 u64 start = page_offset(page);
3918 u64 page_end = start + PAGE_SIZE - 1;
3922 loff_t i_size = i_size_read(inode);
3923 unsigned long end_index = i_size >> PAGE_SHIFT;
3924 unsigned long nr_written = 0;
3926 trace___extent_writepage(page, inode, wbc);
3928 WARN_ON(!PageLocked(page));
3930 ClearPageError(page);
3932 pg_offset = offset_in_page(i_size);
3933 if (page->index > end_index ||
3934 (page->index == end_index && !pg_offset)) {
3935 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3940 if (page->index == end_index) {
3941 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
3942 flush_dcache_page(page);
3945 ret = set_page_extent_mapped(page);
3951 if (!epd->extent_locked) {
3952 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3960 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3967 /* make sure the mapping tag for page dirty gets cleared */
3968 set_page_writeback(page);
3969 end_page_writeback(page);
3971 if (PageError(page)) {
3972 ret = ret < 0 ? ret : -EIO;
3973 end_extent_writepage(page, ret, start, page_end);
3980 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3982 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3983 TASK_UNINTERRUPTIBLE);
3986 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3988 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3989 smp_mb__after_atomic();
3990 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3994 * Lock extent buffer status and pages for writeback.
3996 * May try to flush write bio if we can't get the lock.
3998 * Return 0 if the extent buffer doesn't need to be submitted.
3999 * (E.g. the extent buffer is not dirty)
4000 * Return >0 is the extent buffer is submitted to bio.
4001 * Return <0 if something went wrong, no page is locked.
4003 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4004 struct extent_page_data *epd)
4006 struct btrfs_fs_info *fs_info = eb->fs_info;
4007 int i, num_pages, failed_page_nr;
4011 if (!btrfs_try_tree_write_lock(eb)) {
4012 ret = flush_write_bio(epd);
4016 btrfs_tree_lock(eb);
4019 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4020 btrfs_tree_unlock(eb);
4024 ret = flush_write_bio(epd);
4030 wait_on_extent_buffer_writeback(eb);
4031 btrfs_tree_lock(eb);
4032 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4034 btrfs_tree_unlock(eb);
4039 * We need to do this to prevent races in people who check if the eb is
4040 * under IO since we can end up having no IO bits set for a short period
4043 spin_lock(&eb->refs_lock);
4044 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4045 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4046 spin_unlock(&eb->refs_lock);
4047 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4048 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4050 fs_info->dirty_metadata_batch);
4053 spin_unlock(&eb->refs_lock);
4056 btrfs_tree_unlock(eb);
4059 * Either we don't need to submit any tree block, or we're submitting
4061 * Subpage metadata doesn't use page locking at all, so we can skip
4064 if (!ret || fs_info->sectorsize < PAGE_SIZE)
4067 num_pages = num_extent_pages(eb);
4068 for (i = 0; i < num_pages; i++) {
4069 struct page *p = eb->pages[i];
4071 if (!trylock_page(p)) {
4075 err = flush_write_bio(epd);
4089 /* Unlock already locked pages */
4090 for (i = 0; i < failed_page_nr; i++)
4091 unlock_page(eb->pages[i]);
4093 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
4094 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
4095 * be made and undo everything done before.
4097 btrfs_tree_lock(eb);
4098 spin_lock(&eb->refs_lock);
4099 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4100 end_extent_buffer_writeback(eb);
4101 spin_unlock(&eb->refs_lock);
4102 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4103 fs_info->dirty_metadata_batch);
4104 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4105 btrfs_tree_unlock(eb);
4109 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4111 struct btrfs_fs_info *fs_info = eb->fs_info;
4113 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4114 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4118 * If we error out, we should add back the dirty_metadata_bytes
4119 * to make it consistent.
4121 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4122 eb->len, fs_info->dirty_metadata_batch);
4125 * If writeback for a btree extent that doesn't belong to a log tree
4126 * failed, increment the counter transaction->eb_write_errors.
4127 * We do this because while the transaction is running and before it's
4128 * committing (when we call filemap_fdata[write|wait]_range against
4129 * the btree inode), we might have
4130 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4131 * returns an error or an error happens during writeback, when we're
4132 * committing the transaction we wouldn't know about it, since the pages
4133 * can be no longer dirty nor marked anymore for writeback (if a
4134 * subsequent modification to the extent buffer didn't happen before the
4135 * transaction commit), which makes filemap_fdata[write|wait]_range not
4136 * able to find the pages tagged with SetPageError at transaction
4137 * commit time. So if this happens we must abort the transaction,
4138 * otherwise we commit a super block with btree roots that point to
4139 * btree nodes/leafs whose content on disk is invalid - either garbage
4140 * or the content of some node/leaf from a past generation that got
4141 * cowed or deleted and is no longer valid.
4143 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4144 * not be enough - we need to distinguish between log tree extents vs
4145 * non-log tree extents, and the next filemap_fdatawait_range() call
4146 * will catch and clear such errors in the mapping - and that call might
4147 * be from a log sync and not from a transaction commit. Also, checking
4148 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4149 * not done and would not be reliable - the eb might have been released
4150 * from memory and reading it back again means that flag would not be
4151 * set (since it's a runtime flag, not persisted on disk).
4153 * Using the flags below in the btree inode also makes us achieve the
4154 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4155 * writeback for all dirty pages and before filemap_fdatawait_range()
4156 * is called, the writeback for all dirty pages had already finished
4157 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4158 * filemap_fdatawait_range() would return success, as it could not know
4159 * that writeback errors happened (the pages were no longer tagged for
4162 switch (eb->log_index) {
4164 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4167 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4170 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4173 BUG(); /* unexpected, logic error */
4178 * The endio specific version which won't touch any unsafe spinlock in endio
4181 static struct extent_buffer *find_extent_buffer_nolock(
4182 struct btrfs_fs_info *fs_info, u64 start)
4184 struct extent_buffer *eb;
4187 eb = radix_tree_lookup(&fs_info->buffer_radix,
4188 start >> fs_info->sectorsize_bits);
4189 if (eb && atomic_inc_not_zero(&eb->refs)) {
4198 * The endio function for subpage extent buffer write.
4200 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4201 * after all extent buffers in the page has finished their writeback.
4203 static void end_bio_subpage_eb_writepage(struct bio *bio)
4205 struct btrfs_fs_info *fs_info;
4206 struct bio_vec *bvec;
4207 struct bvec_iter_all iter_all;
4209 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4210 ASSERT(fs_info->sectorsize < PAGE_SIZE);
4212 ASSERT(!bio_flagged(bio, BIO_CLONED));
4213 bio_for_each_segment_all(bvec, bio, iter_all) {
4214 struct page *page = bvec->bv_page;
4215 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4216 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4217 u64 cur_bytenr = bvec_start;
4219 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4221 /* Iterate through all extent buffers in the range */
4222 while (cur_bytenr <= bvec_end) {
4223 struct extent_buffer *eb;
4227 * Here we can't use find_extent_buffer(), as it may
4228 * try to lock eb->refs_lock, which is not safe in endio
4231 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4234 cur_bytenr = eb->start + eb->len;
4236 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4237 done = atomic_dec_and_test(&eb->io_pages);
4240 if (bio->bi_status ||
4241 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4242 ClearPageUptodate(page);
4243 set_btree_ioerr(page, eb);
4246 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4248 end_extent_buffer_writeback(eb);
4250 * free_extent_buffer() will grab spinlock which is not
4251 * safe in endio context. Thus here we manually dec
4254 atomic_dec(&eb->refs);
4260 static void end_bio_extent_buffer_writepage(struct bio *bio)
4262 struct bio_vec *bvec;
4263 struct extent_buffer *eb;
4265 struct bvec_iter_all iter_all;
4267 ASSERT(!bio_flagged(bio, BIO_CLONED));
4268 bio_for_each_segment_all(bvec, bio, iter_all) {
4269 struct page *page = bvec->bv_page;
4271 eb = (struct extent_buffer *)page->private;
4273 done = atomic_dec_and_test(&eb->io_pages);
4275 if (bio->bi_status ||
4276 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4277 ClearPageUptodate(page);
4278 set_btree_ioerr(page, eb);
4281 end_page_writeback(page);
4286 end_extent_buffer_writeback(eb);
4292 static void prepare_eb_write(struct extent_buffer *eb)
4295 unsigned long start;
4298 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4299 atomic_set(&eb->io_pages, num_extent_pages(eb));
4301 /* Set btree blocks beyond nritems with 0 to avoid stale content */
4302 nritems = btrfs_header_nritems(eb);
4303 if (btrfs_header_level(eb) > 0) {
4304 end = btrfs_node_key_ptr_offset(nritems);
4305 memzero_extent_buffer(eb, end, eb->len - end);
4309 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4311 start = btrfs_item_nr_offset(nritems);
4312 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4313 memzero_extent_buffer(eb, start, end - start);
4318 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4319 * Page locking is only utilized at minimum to keep the VMM code happy.
4321 static int write_one_subpage_eb(struct extent_buffer *eb,
4322 struct writeback_control *wbc,
4323 struct extent_page_data *epd)
4325 struct btrfs_fs_info *fs_info = eb->fs_info;
4326 struct page *page = eb->pages[0];
4327 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4328 bool no_dirty_ebs = false;
4331 prepare_eb_write(eb);
4333 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4335 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4337 /* Check if this is the last dirty bit to update nr_written */
4338 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4339 eb->start, eb->len);
4341 clear_page_dirty_for_io(page);
4343 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4344 &epd->bio_ctrl, page, eb->start, eb->len,
4345 eb->start - page_offset(page),
4346 end_bio_subpage_eb_writepage, 0, 0, false);
4348 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4349 set_btree_ioerr(page, eb);
4352 if (atomic_dec_and_test(&eb->io_pages))
4353 end_extent_buffer_writeback(eb);
4358 * Submission finished without problem, if no range of the page is
4359 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4362 update_nr_written(wbc, 1);
4366 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4367 struct writeback_control *wbc,
4368 struct extent_page_data *epd)
4370 u64 disk_bytenr = eb->start;
4372 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4375 prepare_eb_write(eb);
4377 num_pages = num_extent_pages(eb);
4378 for (i = 0; i < num_pages; i++) {
4379 struct page *p = eb->pages[i];
4381 clear_page_dirty_for_io(p);
4382 set_page_writeback(p);
4383 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4384 &epd->bio_ctrl, p, disk_bytenr,
4386 end_bio_extent_buffer_writepage,
4389 set_btree_ioerr(p, eb);
4390 if (PageWriteback(p))
4391 end_page_writeback(p);
4392 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4393 end_extent_buffer_writeback(eb);
4397 disk_bytenr += PAGE_SIZE;
4398 update_nr_written(wbc, 1);
4402 if (unlikely(ret)) {
4403 for (; i < num_pages; i++) {
4404 struct page *p = eb->pages[i];
4405 clear_page_dirty_for_io(p);
4414 * Submit one subpage btree page.
4416 * The main difference to submit_eb_page() is:
4418 * For subpage, we don't rely on page locking at all.
4421 * We only flush bio if we may be unable to fit current extent buffers into
4424 * Return >=0 for the number of submitted extent buffers.
4425 * Return <0 for fatal error.
4427 static int submit_eb_subpage(struct page *page,
4428 struct writeback_control *wbc,
4429 struct extent_page_data *epd)
4431 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4433 u64 page_start = page_offset(page);
4435 const int nbits = BTRFS_SUBPAGE_BITMAP_SIZE;
4436 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4439 /* Lock and write each dirty extent buffers in the range */
4440 while (bit_start < nbits) {
4441 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4442 struct extent_buffer *eb;
4443 unsigned long flags;
4447 * Take private lock to ensure the subpage won't be detached
4450 spin_lock(&page->mapping->private_lock);
4451 if (!PagePrivate(page)) {
4452 spin_unlock(&page->mapping->private_lock);
4455 spin_lock_irqsave(&subpage->lock, flags);
4456 if (!((1 << bit_start) & subpage->dirty_bitmap)) {
4457 spin_unlock_irqrestore(&subpage->lock, flags);
4458 spin_unlock(&page->mapping->private_lock);
4463 start = page_start + bit_start * fs_info->sectorsize;
4464 bit_start += sectors_per_node;
4467 * Here we just want to grab the eb without touching extra
4468 * spin locks, so call find_extent_buffer_nolock().
4470 eb = find_extent_buffer_nolock(fs_info, start);
4471 spin_unlock_irqrestore(&subpage->lock, flags);
4472 spin_unlock(&page->mapping->private_lock);
4475 * The eb has already reached 0 refs thus find_extent_buffer()
4476 * doesn't return it. We don't need to write back such eb
4482 ret = lock_extent_buffer_for_io(eb, epd);
4484 free_extent_buffer(eb);
4488 free_extent_buffer(eb);
4491 ret = write_one_subpage_eb(eb, wbc, epd);
4492 free_extent_buffer(eb);
4500 /* We hit error, end bio for the submitted extent buffers */
4501 end_write_bio(epd, ret);
4506 * Submit all page(s) of one extent buffer.
4508 * @page: the page of one extent buffer
4509 * @eb_context: to determine if we need to submit this page, if current page
4510 * belongs to this eb, we don't need to submit
4512 * The caller should pass each page in their bytenr order, and here we use
4513 * @eb_context to determine if we have submitted pages of one extent buffer.
4515 * If we have, we just skip until we hit a new page that doesn't belong to
4516 * current @eb_context.
4518 * If not, we submit all the page(s) of the extent buffer.
4520 * Return >0 if we have submitted the extent buffer successfully.
4521 * Return 0 if we don't need to submit the page, as it's already submitted by
4523 * Return <0 for fatal error.
4525 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4526 struct extent_page_data *epd,
4527 struct extent_buffer **eb_context)
4529 struct address_space *mapping = page->mapping;
4530 struct btrfs_block_group *cache = NULL;
4531 struct extent_buffer *eb;
4534 if (!PagePrivate(page))
4537 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
4538 return submit_eb_subpage(page, wbc, epd);
4540 spin_lock(&mapping->private_lock);
4541 if (!PagePrivate(page)) {
4542 spin_unlock(&mapping->private_lock);
4546 eb = (struct extent_buffer *)page->private;
4549 * Shouldn't happen and normally this would be a BUG_ON but no point
4550 * crashing the machine for something we can survive anyway.
4553 spin_unlock(&mapping->private_lock);
4557 if (eb == *eb_context) {
4558 spin_unlock(&mapping->private_lock);
4561 ret = atomic_inc_not_zero(&eb->refs);
4562 spin_unlock(&mapping->private_lock);
4566 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4568 * If for_sync, this hole will be filled with
4569 * trasnsaction commit.
4571 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4575 free_extent_buffer(eb);
4581 ret = lock_extent_buffer_for_io(eb, epd);
4583 btrfs_revert_meta_write_pointer(cache, eb);
4585 btrfs_put_block_group(cache);
4586 free_extent_buffer(eb);
4590 btrfs_put_block_group(cache);
4591 ret = write_one_eb(eb, wbc, epd);
4592 free_extent_buffer(eb);
4598 int btree_write_cache_pages(struct address_space *mapping,
4599 struct writeback_control *wbc)
4601 struct extent_buffer *eb_context = NULL;
4602 struct extent_page_data epd = {
4605 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4607 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4610 int nr_to_write_done = 0;
4611 struct pagevec pvec;
4614 pgoff_t end; /* Inclusive */
4618 pagevec_init(&pvec);
4619 if (wbc->range_cyclic) {
4620 index = mapping->writeback_index; /* Start from prev offset */
4623 * Start from the beginning does not need to cycle over the
4624 * range, mark it as scanned.
4626 scanned = (index == 0);
4628 index = wbc->range_start >> PAGE_SHIFT;
4629 end = wbc->range_end >> PAGE_SHIFT;
4632 if (wbc->sync_mode == WB_SYNC_ALL)
4633 tag = PAGECACHE_TAG_TOWRITE;
4635 tag = PAGECACHE_TAG_DIRTY;
4636 btrfs_zoned_meta_io_lock(fs_info);
4638 if (wbc->sync_mode == WB_SYNC_ALL)
4639 tag_pages_for_writeback(mapping, index, end);
4640 while (!done && !nr_to_write_done && (index <= end) &&
4641 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4645 for (i = 0; i < nr_pages; i++) {
4646 struct page *page = pvec.pages[i];
4648 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4657 * the filesystem may choose to bump up nr_to_write.
4658 * We have to make sure to honor the new nr_to_write
4661 nr_to_write_done = wbc->nr_to_write <= 0;
4663 pagevec_release(&pvec);
4666 if (!scanned && !done) {
4668 * We hit the last page and there is more work to be done: wrap
4669 * back to the start of the file
4676 end_write_bio(&epd, ret);
4680 * If something went wrong, don't allow any metadata write bio to be
4683 * This would prevent use-after-free if we had dirty pages not
4684 * cleaned up, which can still happen by fuzzed images.
4687 * Allowing existing tree block to be allocated for other trees.
4689 * - Log tree operations
4690 * Exiting tree blocks get allocated to log tree, bumps its
4691 * generation, then get cleaned in tree re-balance.
4692 * Such tree block will not be written back, since it's clean,
4693 * thus no WRITTEN flag set.
4694 * And after log writes back, this tree block is not traced by
4695 * any dirty extent_io_tree.
4697 * - Offending tree block gets re-dirtied from its original owner
4698 * Since it has bumped generation, no WRITTEN flag, it can be
4699 * reused without COWing. This tree block will not be traced
4700 * by btrfs_transaction::dirty_pages.
4702 * Now such dirty tree block will not be cleaned by any dirty
4703 * extent io tree. Thus we don't want to submit such wild eb
4704 * if the fs already has error.
4706 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4707 ret = flush_write_bio(&epd);
4710 end_write_bio(&epd, ret);
4713 btrfs_zoned_meta_io_unlock(fs_info);
4718 * Walk the list of dirty pages of the given address space and write all of them.
4720 * @mapping: address space structure to write
4721 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4722 * @epd: holds context for the write, namely the bio
4724 * If a page is already under I/O, write_cache_pages() skips it, even
4725 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4726 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4727 * and msync() need to guarantee that all the data which was dirty at the time
4728 * the call was made get new I/O started against them. If wbc->sync_mode is
4729 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4730 * existing IO to complete.
4732 static int extent_write_cache_pages(struct address_space *mapping,
4733 struct writeback_control *wbc,
4734 struct extent_page_data *epd)
4736 struct inode *inode = mapping->host;
4739 int nr_to_write_done = 0;
4740 struct pagevec pvec;
4743 pgoff_t end; /* Inclusive */
4745 int range_whole = 0;
4750 * We have to hold onto the inode so that ordered extents can do their
4751 * work when the IO finishes. The alternative to this is failing to add
4752 * an ordered extent if the igrab() fails there and that is a huge pain
4753 * to deal with, so instead just hold onto the inode throughout the
4754 * writepages operation. If it fails here we are freeing up the inode
4755 * anyway and we'd rather not waste our time writing out stuff that is
4756 * going to be truncated anyway.
4761 pagevec_init(&pvec);
4762 if (wbc->range_cyclic) {
4763 index = mapping->writeback_index; /* Start from prev offset */
4766 * Start from the beginning does not need to cycle over the
4767 * range, mark it as scanned.
4769 scanned = (index == 0);
4771 index = wbc->range_start >> PAGE_SHIFT;
4772 end = wbc->range_end >> PAGE_SHIFT;
4773 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4779 * We do the tagged writepage as long as the snapshot flush bit is set
4780 * and we are the first one who do the filemap_flush() on this inode.
4782 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4783 * not race in and drop the bit.
4785 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4786 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4787 &BTRFS_I(inode)->runtime_flags))
4788 wbc->tagged_writepages = 1;
4790 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4791 tag = PAGECACHE_TAG_TOWRITE;
4793 tag = PAGECACHE_TAG_DIRTY;
4795 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4796 tag_pages_for_writeback(mapping, index, end);
4798 while (!done && !nr_to_write_done && (index <= end) &&
4799 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4800 &index, end, tag))) {
4803 for (i = 0; i < nr_pages; i++) {
4804 struct page *page = pvec.pages[i];
4806 done_index = page->index + 1;
4808 * At this point we hold neither the i_pages lock nor
4809 * the page lock: the page may be truncated or
4810 * invalidated (changing page->mapping to NULL),
4811 * or even swizzled back from swapper_space to
4812 * tmpfs file mapping
4814 if (!trylock_page(page)) {
4815 ret = flush_write_bio(epd);
4820 if (unlikely(page->mapping != mapping)) {
4825 if (wbc->sync_mode != WB_SYNC_NONE) {
4826 if (PageWriteback(page)) {
4827 ret = flush_write_bio(epd);
4830 wait_on_page_writeback(page);
4833 if (PageWriteback(page) ||
4834 !clear_page_dirty_for_io(page)) {
4839 ret = __extent_writepage(page, wbc, epd);
4846 * the filesystem may choose to bump up nr_to_write.
4847 * We have to make sure to honor the new nr_to_write
4850 nr_to_write_done = wbc->nr_to_write <= 0;
4852 pagevec_release(&pvec);
4855 if (!scanned && !done) {
4857 * We hit the last page and there is more work to be done: wrap
4858 * back to the start of the file
4864 * If we're looping we could run into a page that is locked by a
4865 * writer and that writer could be waiting on writeback for a
4866 * page in our current bio, and thus deadlock, so flush the
4869 ret = flush_write_bio(epd);
4874 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4875 mapping->writeback_index = done_index;
4877 btrfs_add_delayed_iput(inode);
4881 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4884 struct extent_page_data epd = {
4887 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4890 ret = __extent_writepage(page, wbc, &epd);
4893 end_write_bio(&epd, ret);
4897 ret = flush_write_bio(&epd);
4902 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4906 struct address_space *mapping = inode->i_mapping;
4908 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4911 struct extent_page_data epd = {
4914 .sync_io = mode == WB_SYNC_ALL,
4916 struct writeback_control wbc_writepages = {
4918 .nr_to_write = nr_pages * 2,
4919 .range_start = start,
4920 .range_end = end + 1,
4921 /* We're called from an async helper function */
4922 .punt_to_cgroup = 1,
4923 .no_cgroup_owner = 1,
4926 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
4927 while (start <= end) {
4928 page = find_get_page(mapping, start >> PAGE_SHIFT);
4929 if (clear_page_dirty_for_io(page))
4930 ret = __extent_writepage(page, &wbc_writepages, &epd);
4932 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode),
4933 page, start, start + PAGE_SIZE - 1, 1);
4942 ret = flush_write_bio(&epd);
4944 end_write_bio(&epd, ret);
4946 wbc_detach_inode(&wbc_writepages);
4950 int extent_writepages(struct address_space *mapping,
4951 struct writeback_control *wbc)
4954 struct extent_page_data epd = {
4957 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4960 ret = extent_write_cache_pages(mapping, wbc, &epd);
4963 end_write_bio(&epd, ret);
4966 ret = flush_write_bio(&epd);
4970 void extent_readahead(struct readahead_control *rac)
4972 struct btrfs_bio_ctrl bio_ctrl = { 0 };
4973 struct page *pagepool[16];
4974 struct extent_map *em_cached = NULL;
4975 u64 prev_em_start = (u64)-1;
4978 while ((nr = readahead_page_batch(rac, pagepool))) {
4979 u64 contig_start = readahead_pos(rac);
4980 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
4982 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4983 &em_cached, &bio_ctrl, &prev_em_start);
4987 free_extent_map(em_cached);
4990 if (submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags))
4996 * basic invalidatepage code, this waits on any locked or writeback
4997 * ranges corresponding to the page, and then deletes any extent state
4998 * records from the tree
5000 int extent_invalidatepage(struct extent_io_tree *tree,
5001 struct page *page, unsigned long offset)
5003 struct extent_state *cached_state = NULL;
5004 u64 start = page_offset(page);
5005 u64 end = start + PAGE_SIZE - 1;
5006 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
5008 /* This function is only called for the btree inode */
5009 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5011 start += ALIGN(offset, blocksize);
5015 lock_extent_bits(tree, start, end, &cached_state);
5016 wait_on_page_writeback(page);
5019 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5020 * so here we only need to unlock the extent range to free any
5021 * existing extent state.
5023 unlock_extent_cached(tree, start, end, &cached_state);
5028 * a helper for releasepage, this tests for areas of the page that
5029 * are locked or under IO and drops the related state bits if it is safe
5032 static int try_release_extent_state(struct extent_io_tree *tree,
5033 struct page *page, gfp_t mask)
5035 u64 start = page_offset(page);
5036 u64 end = start + PAGE_SIZE - 1;
5039 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5043 * At this point we can safely clear everything except the
5044 * locked bit, the nodatasum bit and the delalloc new bit.
5045 * The delalloc new bit will be cleared by ordered extent
5048 ret = __clear_extent_bit(tree, start, end,
5049 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5050 0, 0, NULL, mask, NULL);
5052 /* if clear_extent_bit failed for enomem reasons,
5053 * we can't allow the release to continue.
5064 * a helper for releasepage. As long as there are no locked extents
5065 * in the range corresponding to the page, both state records and extent
5066 * map records are removed
5068 int try_release_extent_mapping(struct page *page, gfp_t mask)
5070 struct extent_map *em;
5071 u64 start = page_offset(page);
5072 u64 end = start + PAGE_SIZE - 1;
5073 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5074 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5075 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5077 if (gfpflags_allow_blocking(mask) &&
5078 page->mapping->host->i_size > SZ_16M) {
5080 while (start <= end) {
5081 struct btrfs_fs_info *fs_info;
5084 len = end - start + 1;
5085 write_lock(&map->lock);
5086 em = lookup_extent_mapping(map, start, len);
5088 write_unlock(&map->lock);
5091 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5092 em->start != start) {
5093 write_unlock(&map->lock);
5094 free_extent_map(em);
5097 if (test_range_bit(tree, em->start,
5098 extent_map_end(em) - 1,
5099 EXTENT_LOCKED, 0, NULL))
5102 * If it's not in the list of modified extents, used
5103 * by a fast fsync, we can remove it. If it's being
5104 * logged we can safely remove it since fsync took an
5105 * extra reference on the em.
5107 if (list_empty(&em->list) ||
5108 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5111 * If it's in the list of modified extents, remove it
5112 * only if its generation is older then the current one,
5113 * in which case we don't need it for a fast fsync.
5114 * Otherwise don't remove it, we could be racing with an
5115 * ongoing fast fsync that could miss the new extent.
5117 fs_info = btrfs_inode->root->fs_info;
5118 spin_lock(&fs_info->trans_lock);
5119 cur_gen = fs_info->generation;
5120 spin_unlock(&fs_info->trans_lock);
5121 if (em->generation >= cur_gen)
5125 * We only remove extent maps that are not in the list of
5126 * modified extents or that are in the list but with a
5127 * generation lower then the current generation, so there
5128 * is no need to set the full fsync flag on the inode (it
5129 * hurts the fsync performance for workloads with a data
5130 * size that exceeds or is close to the system's memory).
5132 remove_extent_mapping(map, em);
5133 /* once for the rb tree */
5134 free_extent_map(em);
5136 start = extent_map_end(em);
5137 write_unlock(&map->lock);
5140 free_extent_map(em);
5142 cond_resched(); /* Allow large-extent preemption. */
5145 return try_release_extent_state(tree, page, mask);
5149 * helper function for fiemap, which doesn't want to see any holes.
5150 * This maps until we find something past 'last'
5152 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5153 u64 offset, u64 last)
5155 u64 sectorsize = btrfs_inode_sectorsize(inode);
5156 struct extent_map *em;
5163 len = last - offset;
5166 len = ALIGN(len, sectorsize);
5167 em = btrfs_get_extent_fiemap(inode, offset, len);
5168 if (IS_ERR_OR_NULL(em))
5171 /* if this isn't a hole return it */
5172 if (em->block_start != EXTENT_MAP_HOLE)
5175 /* this is a hole, advance to the next extent */
5176 offset = extent_map_end(em);
5177 free_extent_map(em);
5185 * To cache previous fiemap extent
5187 * Will be used for merging fiemap extent
5189 struct fiemap_cache {
5198 * Helper to submit fiemap extent.
5200 * Will try to merge current fiemap extent specified by @offset, @phys,
5201 * @len and @flags with cached one.
5202 * And only when we fails to merge, cached one will be submitted as
5205 * Return value is the same as fiemap_fill_next_extent().
5207 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5208 struct fiemap_cache *cache,
5209 u64 offset, u64 phys, u64 len, u32 flags)
5217 * Sanity check, extent_fiemap() should have ensured that new
5218 * fiemap extent won't overlap with cached one.
5221 * NOTE: Physical address can overlap, due to compression
5223 if (cache->offset + cache->len > offset) {
5229 * Only merges fiemap extents if
5230 * 1) Their logical addresses are continuous
5232 * 2) Their physical addresses are continuous
5233 * So truly compressed (physical size smaller than logical size)
5234 * extents won't get merged with each other
5236 * 3) Share same flags except FIEMAP_EXTENT_LAST
5237 * So regular extent won't get merged with prealloc extent
5239 if (cache->offset + cache->len == offset &&
5240 cache->phys + cache->len == phys &&
5241 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5242 (flags & ~FIEMAP_EXTENT_LAST)) {
5244 cache->flags |= flags;
5245 goto try_submit_last;
5248 /* Not mergeable, need to submit cached one */
5249 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5250 cache->len, cache->flags);
5251 cache->cached = false;
5255 cache->cached = true;
5256 cache->offset = offset;
5259 cache->flags = flags;
5261 if (cache->flags & FIEMAP_EXTENT_LAST) {
5262 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5263 cache->phys, cache->len, cache->flags);
5264 cache->cached = false;
5270 * Emit last fiemap cache
5272 * The last fiemap cache may still be cached in the following case:
5274 * |<- Fiemap range ->|
5275 * |<------------ First extent ----------->|
5277 * In this case, the first extent range will be cached but not emitted.
5278 * So we must emit it before ending extent_fiemap().
5280 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5281 struct fiemap_cache *cache)
5288 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5289 cache->len, cache->flags);
5290 cache->cached = false;
5296 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5301 u64 max = start + len;
5305 u64 last_for_get_extent = 0;
5307 u64 isize = i_size_read(&inode->vfs_inode);
5308 struct btrfs_key found_key;
5309 struct extent_map *em = NULL;
5310 struct extent_state *cached_state = NULL;
5311 struct btrfs_path *path;
5312 struct btrfs_root *root = inode->root;
5313 struct fiemap_cache cache = { 0 };
5314 struct ulist *roots;
5315 struct ulist *tmp_ulist;
5324 path = btrfs_alloc_path();
5328 roots = ulist_alloc(GFP_KERNEL);
5329 tmp_ulist = ulist_alloc(GFP_KERNEL);
5330 if (!roots || !tmp_ulist) {
5332 goto out_free_ulist;
5336 * We can't initialize that to 'start' as this could miss extents due
5337 * to extent item merging
5340 start = round_down(start, btrfs_inode_sectorsize(inode));
5341 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5344 * lookup the last file extent. We're not using i_size here
5345 * because there might be preallocation past i_size
5347 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5350 goto out_free_ulist;
5358 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5359 found_type = found_key.type;
5361 /* No extents, but there might be delalloc bits */
5362 if (found_key.objectid != btrfs_ino(inode) ||
5363 found_type != BTRFS_EXTENT_DATA_KEY) {
5364 /* have to trust i_size as the end */
5366 last_for_get_extent = isize;
5369 * remember the start of the last extent. There are a
5370 * bunch of different factors that go into the length of the
5371 * extent, so its much less complex to remember where it started
5373 last = found_key.offset;
5374 last_for_get_extent = last + 1;
5376 btrfs_release_path(path);
5379 * we might have some extents allocated but more delalloc past those
5380 * extents. so, we trust isize unless the start of the last extent is
5385 last_for_get_extent = isize;
5388 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5391 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5400 u64 offset_in_extent = 0;
5402 /* break if the extent we found is outside the range */
5403 if (em->start >= max || extent_map_end(em) < off)
5407 * get_extent may return an extent that starts before our
5408 * requested range. We have to make sure the ranges
5409 * we return to fiemap always move forward and don't
5410 * overlap, so adjust the offsets here
5412 em_start = max(em->start, off);
5415 * record the offset from the start of the extent
5416 * for adjusting the disk offset below. Only do this if the
5417 * extent isn't compressed since our in ram offset may be past
5418 * what we have actually allocated on disk.
5420 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5421 offset_in_extent = em_start - em->start;
5422 em_end = extent_map_end(em);
5423 em_len = em_end - em_start;
5425 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5426 disko = em->block_start + offset_in_extent;
5431 * bump off for our next call to get_extent
5433 off = extent_map_end(em);
5437 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5439 flags |= FIEMAP_EXTENT_LAST;
5440 } else if (em->block_start == EXTENT_MAP_INLINE) {
5441 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5442 FIEMAP_EXTENT_NOT_ALIGNED);
5443 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5444 flags |= (FIEMAP_EXTENT_DELALLOC |
5445 FIEMAP_EXTENT_UNKNOWN);
5446 } else if (fieinfo->fi_extents_max) {
5447 u64 bytenr = em->block_start -
5448 (em->start - em->orig_start);
5451 * As btrfs supports shared space, this information
5452 * can be exported to userspace tools via
5453 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5454 * then we're just getting a count and we can skip the
5457 ret = btrfs_check_shared(root, btrfs_ino(inode),
5458 bytenr, roots, tmp_ulist);
5462 flags |= FIEMAP_EXTENT_SHARED;
5465 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5466 flags |= FIEMAP_EXTENT_ENCODED;
5467 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5468 flags |= FIEMAP_EXTENT_UNWRITTEN;
5470 free_extent_map(em);
5472 if ((em_start >= last) || em_len == (u64)-1 ||
5473 (last == (u64)-1 && isize <= em_end)) {
5474 flags |= FIEMAP_EXTENT_LAST;
5478 /* now scan forward to see if this is really the last extent. */
5479 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5485 flags |= FIEMAP_EXTENT_LAST;
5488 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5498 ret = emit_last_fiemap_cache(fieinfo, &cache);
5499 free_extent_map(em);
5501 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5505 btrfs_free_path(path);
5507 ulist_free(tmp_ulist);
5511 static void __free_extent_buffer(struct extent_buffer *eb)
5513 kmem_cache_free(extent_buffer_cache, eb);
5516 int extent_buffer_under_io(const struct extent_buffer *eb)
5518 return (atomic_read(&eb->io_pages) ||
5519 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5520 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5523 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5525 struct btrfs_subpage *subpage;
5527 lockdep_assert_held(&page->mapping->private_lock);
5529 if (PagePrivate(page)) {
5530 subpage = (struct btrfs_subpage *)page->private;
5531 if (atomic_read(&subpage->eb_refs))
5537 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5539 struct btrfs_fs_info *fs_info = eb->fs_info;
5540 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5543 * For mapped eb, we're going to change the page private, which should
5544 * be done under the private_lock.
5547 spin_lock(&page->mapping->private_lock);
5549 if (!PagePrivate(page)) {
5551 spin_unlock(&page->mapping->private_lock);
5555 if (fs_info->sectorsize == PAGE_SIZE) {
5557 * We do this since we'll remove the pages after we've
5558 * removed the eb from the radix tree, so we could race
5559 * and have this page now attached to the new eb. So
5560 * only clear page_private if it's still connected to
5563 if (PagePrivate(page) &&
5564 page->private == (unsigned long)eb) {
5565 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5566 BUG_ON(PageDirty(page));
5567 BUG_ON(PageWriteback(page));
5569 * We need to make sure we haven't be attached
5572 detach_page_private(page);
5575 spin_unlock(&page->mapping->private_lock);
5580 * For subpage, we can have dummy eb with page private. In this case,
5581 * we can directly detach the private as such page is only attached to
5582 * one dummy eb, no sharing.
5585 btrfs_detach_subpage(fs_info, page);
5589 btrfs_page_dec_eb_refs(fs_info, page);
5592 * We can only detach the page private if there are no other ebs in the
5595 if (!page_range_has_eb(fs_info, page))
5596 btrfs_detach_subpage(fs_info, page);
5598 spin_unlock(&page->mapping->private_lock);
5601 /* Release all pages attached to the extent buffer */
5602 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5607 ASSERT(!extent_buffer_under_io(eb));
5609 num_pages = num_extent_pages(eb);
5610 for (i = 0; i < num_pages; i++) {
5611 struct page *page = eb->pages[i];
5616 detach_extent_buffer_page(eb, page);
5618 /* One for when we allocated the page */
5624 * Helper for releasing the extent buffer.
5626 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5628 btrfs_release_extent_buffer_pages(eb);
5629 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5630 __free_extent_buffer(eb);
5633 static struct extent_buffer *
5634 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5637 struct extent_buffer *eb = NULL;
5639 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5642 eb->fs_info = fs_info;
5644 init_rwsem(&eb->lock);
5646 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5647 &fs_info->allocated_ebs);
5648 INIT_LIST_HEAD(&eb->release_list);
5650 spin_lock_init(&eb->refs_lock);
5651 atomic_set(&eb->refs, 1);
5652 atomic_set(&eb->io_pages, 0);
5654 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5659 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5663 struct extent_buffer *new;
5664 int num_pages = num_extent_pages(src);
5666 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5671 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5672 * btrfs_release_extent_buffer() have different behavior for
5673 * UNMAPPED subpage extent buffer.
5675 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5677 for (i = 0; i < num_pages; i++) {
5680 p = alloc_page(GFP_NOFS);
5682 btrfs_release_extent_buffer(new);
5685 ret = attach_extent_buffer_page(new, p, NULL);
5688 btrfs_release_extent_buffer(new);
5691 WARN_ON(PageDirty(p));
5693 copy_page(page_address(p), page_address(src->pages[i]));
5695 set_extent_buffer_uptodate(new);
5700 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5701 u64 start, unsigned long len)
5703 struct extent_buffer *eb;
5707 eb = __alloc_extent_buffer(fs_info, start, len);
5711 num_pages = num_extent_pages(eb);
5712 for (i = 0; i < num_pages; i++) {
5715 eb->pages[i] = alloc_page(GFP_NOFS);
5718 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5722 set_extent_buffer_uptodate(eb);
5723 btrfs_set_header_nritems(eb, 0);
5724 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5728 for (; i > 0; i--) {
5729 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5730 __free_page(eb->pages[i - 1]);
5732 __free_extent_buffer(eb);
5736 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5739 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5742 static void check_buffer_tree_ref(struct extent_buffer *eb)
5746 * The TREE_REF bit is first set when the extent_buffer is added
5747 * to the radix tree. It is also reset, if unset, when a new reference
5748 * is created by find_extent_buffer.
5750 * It is only cleared in two cases: freeing the last non-tree
5751 * reference to the extent_buffer when its STALE bit is set or
5752 * calling releasepage when the tree reference is the only reference.
5754 * In both cases, care is taken to ensure that the extent_buffer's
5755 * pages are not under io. However, releasepage can be concurrently
5756 * called with creating new references, which is prone to race
5757 * conditions between the calls to check_buffer_tree_ref in those
5758 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5760 * The actual lifetime of the extent_buffer in the radix tree is
5761 * adequately protected by the refcount, but the TREE_REF bit and
5762 * its corresponding reference are not. To protect against this
5763 * class of races, we call check_buffer_tree_ref from the codepaths
5764 * which trigger io after they set eb->io_pages. Note that once io is
5765 * initiated, TREE_REF can no longer be cleared, so that is the
5766 * moment at which any such race is best fixed.
5768 refs = atomic_read(&eb->refs);
5769 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5772 spin_lock(&eb->refs_lock);
5773 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5774 atomic_inc(&eb->refs);
5775 spin_unlock(&eb->refs_lock);
5778 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5779 struct page *accessed)
5783 check_buffer_tree_ref(eb);
5785 num_pages = num_extent_pages(eb);
5786 for (i = 0; i < num_pages; i++) {
5787 struct page *p = eb->pages[i];
5790 mark_page_accessed(p);
5794 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5797 struct extent_buffer *eb;
5799 eb = find_extent_buffer_nolock(fs_info, start);
5803 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
5804 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
5805 * another task running free_extent_buffer() might have seen that flag
5806 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
5807 * writeback flags not set) and it's still in the tree (flag
5808 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
5809 * decrementing the extent buffer's reference count twice. So here we
5810 * could race and increment the eb's reference count, clear its stale
5811 * flag, mark it as dirty and drop our reference before the other task
5812 * finishes executing free_extent_buffer, which would later result in
5813 * an attempt to free an extent buffer that is dirty.
5815 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5816 spin_lock(&eb->refs_lock);
5817 spin_unlock(&eb->refs_lock);
5819 mark_extent_buffer_accessed(eb, NULL);
5823 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5824 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5827 struct extent_buffer *eb, *exists = NULL;
5830 eb = find_extent_buffer(fs_info, start);
5833 eb = alloc_dummy_extent_buffer(fs_info, start);
5835 return ERR_PTR(-ENOMEM);
5836 eb->fs_info = fs_info;
5838 ret = radix_tree_preload(GFP_NOFS);
5840 exists = ERR_PTR(ret);
5843 spin_lock(&fs_info->buffer_lock);
5844 ret = radix_tree_insert(&fs_info->buffer_radix,
5845 start >> fs_info->sectorsize_bits, eb);
5846 spin_unlock(&fs_info->buffer_lock);
5847 radix_tree_preload_end();
5848 if (ret == -EEXIST) {
5849 exists = find_extent_buffer(fs_info, start);
5855 check_buffer_tree_ref(eb);
5856 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5860 btrfs_release_extent_buffer(eb);
5865 static struct extent_buffer *grab_extent_buffer(
5866 struct btrfs_fs_info *fs_info, struct page *page)
5868 struct extent_buffer *exists;
5871 * For subpage case, we completely rely on radix tree to ensure we
5872 * don't try to insert two ebs for the same bytenr. So here we always
5873 * return NULL and just continue.
5875 if (fs_info->sectorsize < PAGE_SIZE)
5878 /* Page not yet attached to an extent buffer */
5879 if (!PagePrivate(page))
5883 * We could have already allocated an eb for this page and attached one
5884 * so lets see if we can get a ref on the existing eb, and if we can we
5885 * know it's good and we can just return that one, else we know we can
5886 * just overwrite page->private.
5888 exists = (struct extent_buffer *)page->private;
5889 if (atomic_inc_not_zero(&exists->refs))
5892 WARN_ON(PageDirty(page));
5893 detach_page_private(page);
5897 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5898 u64 start, u64 owner_root, int level)
5900 unsigned long len = fs_info->nodesize;
5903 unsigned long index = start >> PAGE_SHIFT;
5904 struct extent_buffer *eb;
5905 struct extent_buffer *exists = NULL;
5907 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5911 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5912 btrfs_err(fs_info, "bad tree block start %llu", start);
5913 return ERR_PTR(-EINVAL);
5916 #if BITS_PER_LONG == 32
5917 if (start >= MAX_LFS_FILESIZE) {
5918 btrfs_err_rl(fs_info,
5919 "extent buffer %llu is beyond 32bit page cache limit", start);
5920 btrfs_err_32bit_limit(fs_info);
5921 return ERR_PTR(-EOVERFLOW);
5923 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
5924 btrfs_warn_32bit_limit(fs_info);
5927 if (fs_info->sectorsize < PAGE_SIZE &&
5928 offset_in_page(start) + len > PAGE_SIZE) {
5930 "tree block crosses page boundary, start %llu nodesize %lu",
5932 return ERR_PTR(-EINVAL);
5935 eb = find_extent_buffer(fs_info, start);
5939 eb = __alloc_extent_buffer(fs_info, start, len);
5941 return ERR_PTR(-ENOMEM);
5942 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
5944 num_pages = num_extent_pages(eb);
5945 for (i = 0; i < num_pages; i++, index++) {
5946 struct btrfs_subpage *prealloc = NULL;
5948 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5950 exists = ERR_PTR(-ENOMEM);
5955 * Preallocate page->private for subpage case, so that we won't
5956 * allocate memory with private_lock hold. The memory will be
5957 * freed by attach_extent_buffer_page() or freed manually if
5960 * Although we have ensured one subpage eb can only have one
5961 * page, but it may change in the future for 16K page size
5962 * support, so we still preallocate the memory in the loop.
5964 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5965 BTRFS_SUBPAGE_METADATA);
5969 exists = ERR_PTR(ret);
5973 spin_lock(&mapping->private_lock);
5974 exists = grab_extent_buffer(fs_info, p);
5976 spin_unlock(&mapping->private_lock);
5979 mark_extent_buffer_accessed(exists, p);
5980 btrfs_free_subpage(prealloc);
5983 /* Should not fail, as we have preallocated the memory */
5984 ret = attach_extent_buffer_page(eb, p, prealloc);
5987 * To inform we have extra eb under allocation, so that
5988 * detach_extent_buffer_page() won't release the page private
5989 * when the eb hasn't yet been inserted into radix tree.
5991 * The ref will be decreased when the eb released the page, in
5992 * detach_extent_buffer_page().
5993 * Thus needs no special handling in error path.
5995 btrfs_page_inc_eb_refs(fs_info, p);
5996 spin_unlock(&mapping->private_lock);
5998 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6000 if (!PageUptodate(p))
6004 * We can't unlock the pages just yet since the extent buffer
6005 * hasn't been properly inserted in the radix tree, this
6006 * opens a race with btree_releasepage which can free a page
6007 * while we are still filling in all pages for the buffer and
6012 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6014 ret = radix_tree_preload(GFP_NOFS);
6016 exists = ERR_PTR(ret);
6020 spin_lock(&fs_info->buffer_lock);
6021 ret = radix_tree_insert(&fs_info->buffer_radix,
6022 start >> fs_info->sectorsize_bits, eb);
6023 spin_unlock(&fs_info->buffer_lock);
6024 radix_tree_preload_end();
6025 if (ret == -EEXIST) {
6026 exists = find_extent_buffer(fs_info, start);
6032 /* add one reference for the tree */
6033 check_buffer_tree_ref(eb);
6034 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6037 * Now it's safe to unlock the pages because any calls to
6038 * btree_releasepage will correctly detect that a page belongs to a
6039 * live buffer and won't free them prematurely.
6041 for (i = 0; i < num_pages; i++)
6042 unlock_page(eb->pages[i]);
6046 WARN_ON(!atomic_dec_and_test(&eb->refs));
6047 for (i = 0; i < num_pages; i++) {
6049 unlock_page(eb->pages[i]);
6052 btrfs_release_extent_buffer(eb);
6056 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6058 struct extent_buffer *eb =
6059 container_of(head, struct extent_buffer, rcu_head);
6061 __free_extent_buffer(eb);
6064 static int release_extent_buffer(struct extent_buffer *eb)
6065 __releases(&eb->refs_lock)
6067 lockdep_assert_held(&eb->refs_lock);
6069 WARN_ON(atomic_read(&eb->refs) == 0);
6070 if (atomic_dec_and_test(&eb->refs)) {
6071 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6072 struct btrfs_fs_info *fs_info = eb->fs_info;
6074 spin_unlock(&eb->refs_lock);
6076 spin_lock(&fs_info->buffer_lock);
6077 radix_tree_delete(&fs_info->buffer_radix,
6078 eb->start >> fs_info->sectorsize_bits);
6079 spin_unlock(&fs_info->buffer_lock);
6081 spin_unlock(&eb->refs_lock);
6084 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6085 /* Should be safe to release our pages at this point */
6086 btrfs_release_extent_buffer_pages(eb);
6087 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6088 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6089 __free_extent_buffer(eb);
6093 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6096 spin_unlock(&eb->refs_lock);
6101 void free_extent_buffer(struct extent_buffer *eb)
6109 refs = atomic_read(&eb->refs);
6110 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6111 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6114 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6119 spin_lock(&eb->refs_lock);
6120 if (atomic_read(&eb->refs) == 2 &&
6121 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6122 !extent_buffer_under_io(eb) &&
6123 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6124 atomic_dec(&eb->refs);
6127 * I know this is terrible, but it's temporary until we stop tracking
6128 * the uptodate bits and such for the extent buffers.
6130 release_extent_buffer(eb);
6133 void free_extent_buffer_stale(struct extent_buffer *eb)
6138 spin_lock(&eb->refs_lock);
6139 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6141 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6142 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6143 atomic_dec(&eb->refs);
6144 release_extent_buffer(eb);
6147 static void btree_clear_page_dirty(struct page *page)
6149 ASSERT(PageDirty(page));
6150 ASSERT(PageLocked(page));
6151 clear_page_dirty_for_io(page);
6152 xa_lock_irq(&page->mapping->i_pages);
6153 if (!PageDirty(page))
6154 __xa_clear_mark(&page->mapping->i_pages,
6155 page_index(page), PAGECACHE_TAG_DIRTY);
6156 xa_unlock_irq(&page->mapping->i_pages);
6159 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6161 struct btrfs_fs_info *fs_info = eb->fs_info;
6162 struct page *page = eb->pages[0];
6165 /* btree_clear_page_dirty() needs page locked */
6167 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6170 btree_clear_page_dirty(page);
6172 WARN_ON(atomic_read(&eb->refs) == 0);
6175 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6181 if (eb->fs_info->sectorsize < PAGE_SIZE)
6182 return clear_subpage_extent_buffer_dirty(eb);
6184 num_pages = num_extent_pages(eb);
6186 for (i = 0; i < num_pages; i++) {
6187 page = eb->pages[i];
6188 if (!PageDirty(page))
6191 btree_clear_page_dirty(page);
6192 ClearPageError(page);
6195 WARN_ON(atomic_read(&eb->refs) == 0);
6198 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6204 check_buffer_tree_ref(eb);
6206 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6208 num_pages = num_extent_pages(eb);
6209 WARN_ON(atomic_read(&eb->refs) == 0);
6210 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6213 bool subpage = eb->fs_info->sectorsize < PAGE_SIZE;
6216 * For subpage case, we can have other extent buffers in the
6217 * same page, and in clear_subpage_extent_buffer_dirty() we
6218 * have to clear page dirty without subpage lock held.
6219 * This can cause race where our page gets dirty cleared after
6222 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6223 * its page for other reasons, we can use page lock to prevent
6227 lock_page(eb->pages[0]);
6228 for (i = 0; i < num_pages; i++)
6229 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6230 eb->start, eb->len);
6232 unlock_page(eb->pages[0]);
6234 #ifdef CONFIG_BTRFS_DEBUG
6235 for (i = 0; i < num_pages; i++)
6236 ASSERT(PageDirty(eb->pages[i]));
6242 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6244 struct btrfs_fs_info *fs_info = eb->fs_info;
6249 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6250 num_pages = num_extent_pages(eb);
6251 for (i = 0; i < num_pages; i++) {
6252 page = eb->pages[i];
6254 btrfs_page_clear_uptodate(fs_info, page,
6255 eb->start, eb->len);
6259 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6261 struct btrfs_fs_info *fs_info = eb->fs_info;
6266 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6267 num_pages = num_extent_pages(eb);
6268 for (i = 0; i < num_pages; i++) {
6269 page = eb->pages[i];
6270 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
6274 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6277 struct btrfs_fs_info *fs_info = eb->fs_info;
6278 struct extent_io_tree *io_tree;
6279 struct page *page = eb->pages[0];
6280 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6283 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6284 ASSERT(PagePrivate(page));
6285 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6287 if (wait == WAIT_NONE) {
6288 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6291 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6297 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6298 PageUptodate(page) ||
6299 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6300 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6301 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6305 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6306 eb->read_mirror = 0;
6307 atomic_set(&eb->io_pages, 1);
6308 check_buffer_tree_ref(eb);
6309 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6311 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6312 page, eb->start, eb->len,
6313 eb->start - page_offset(page),
6314 end_bio_extent_readpage, mirror_num, 0,
6318 * In the endio function, if we hit something wrong we will
6319 * increase the io_pages, so here we need to decrease it for
6322 atomic_dec(&eb->io_pages);
6327 tmp = submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6328 bio_ctrl.bio = NULL;
6332 if (ret || wait != WAIT_COMPLETE)
6335 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6336 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6341 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6347 int locked_pages = 0;
6348 int all_uptodate = 1;
6350 unsigned long num_reads = 0;
6351 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6353 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6356 if (eb->fs_info->sectorsize < PAGE_SIZE)
6357 return read_extent_buffer_subpage(eb, wait, mirror_num);
6359 num_pages = num_extent_pages(eb);
6360 for (i = 0; i < num_pages; i++) {
6361 page = eb->pages[i];
6362 if (wait == WAIT_NONE) {
6364 * WAIT_NONE is only utilized by readahead. If we can't
6365 * acquire the lock atomically it means either the eb
6366 * is being read out or under modification.
6367 * Either way the eb will be or has been cached,
6368 * readahead can exit safely.
6370 if (!trylock_page(page))
6378 * We need to firstly lock all pages to make sure that
6379 * the uptodate bit of our pages won't be affected by
6380 * clear_extent_buffer_uptodate().
6382 for (i = 0; i < num_pages; i++) {
6383 page = eb->pages[i];
6384 if (!PageUptodate(page)) {
6391 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6395 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6396 eb->read_mirror = 0;
6397 atomic_set(&eb->io_pages, num_reads);
6399 * It is possible for releasepage to clear the TREE_REF bit before we
6400 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6402 check_buffer_tree_ref(eb);
6403 for (i = 0; i < num_pages; i++) {
6404 page = eb->pages[i];
6406 if (!PageUptodate(page)) {
6408 atomic_dec(&eb->io_pages);
6413 ClearPageError(page);
6414 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6415 &bio_ctrl, page, page_offset(page),
6416 PAGE_SIZE, 0, end_bio_extent_readpage,
6417 mirror_num, 0, false);
6420 * We failed to submit the bio so it's the
6421 * caller's responsibility to perform cleanup
6422 * i.e unlock page/set error bit.
6427 atomic_dec(&eb->io_pages);
6435 err = submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.bio_flags);
6436 bio_ctrl.bio = NULL;
6441 if (ret || wait != WAIT_COMPLETE)
6444 for (i = 0; i < num_pages; i++) {
6445 page = eb->pages[i];
6446 wait_on_page_locked(page);
6447 if (!PageUptodate(page))
6454 while (locked_pages > 0) {
6456 page = eb->pages[locked_pages];
6462 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6465 btrfs_warn(eb->fs_info,
6466 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6467 eb->start, eb->len, start, len);
6468 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6474 * Check if the [start, start + len) range is valid before reading/writing
6476 * NOTE: @start and @len are offset inside the eb, not logical address.
6478 * Caller should not touch the dst/src memory if this function returns error.
6480 static inline int check_eb_range(const struct extent_buffer *eb,
6481 unsigned long start, unsigned long len)
6483 unsigned long offset;
6485 /* start, start + len should not go beyond eb->len nor overflow */
6486 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6487 return report_eb_range(eb, start, len);
6492 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6493 unsigned long start, unsigned long len)
6499 char *dst = (char *)dstv;
6500 unsigned long i = get_eb_page_index(start);
6502 if (check_eb_range(eb, start, len))
6505 offset = get_eb_offset_in_page(eb, start);
6508 page = eb->pages[i];
6510 cur = min(len, (PAGE_SIZE - offset));
6511 kaddr = page_address(page);
6512 memcpy(dst, kaddr + offset, cur);
6521 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6523 unsigned long start, unsigned long len)
6529 char __user *dst = (char __user *)dstv;
6530 unsigned long i = get_eb_page_index(start);
6533 WARN_ON(start > eb->len);
6534 WARN_ON(start + len > eb->start + eb->len);
6536 offset = get_eb_offset_in_page(eb, start);
6539 page = eb->pages[i];
6541 cur = min(len, (PAGE_SIZE - offset));
6542 kaddr = page_address(page);
6543 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6557 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6558 unsigned long start, unsigned long len)
6564 char *ptr = (char *)ptrv;
6565 unsigned long i = get_eb_page_index(start);
6568 if (check_eb_range(eb, start, len))
6571 offset = get_eb_offset_in_page(eb, start);
6574 page = eb->pages[i];
6576 cur = min(len, (PAGE_SIZE - offset));
6578 kaddr = page_address(page);
6579 ret = memcmp(ptr, kaddr + offset, cur);
6592 * Check that the extent buffer is uptodate.
6594 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6595 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6597 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6600 struct btrfs_fs_info *fs_info = eb->fs_info;
6602 if (fs_info->sectorsize < PAGE_SIZE) {
6605 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6606 eb->start, eb->len);
6609 WARN_ON(!PageUptodate(page));
6613 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6618 assert_eb_page_uptodate(eb, eb->pages[0]);
6619 kaddr = page_address(eb->pages[0]) +
6620 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6622 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6625 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6629 assert_eb_page_uptodate(eb, eb->pages[0]);
6630 kaddr = page_address(eb->pages[0]) +
6631 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6632 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6635 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6636 unsigned long start, unsigned long len)
6642 char *src = (char *)srcv;
6643 unsigned long i = get_eb_page_index(start);
6645 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6647 if (check_eb_range(eb, start, len))
6650 offset = get_eb_offset_in_page(eb, start);
6653 page = eb->pages[i];
6654 assert_eb_page_uptodate(eb, page);
6656 cur = min(len, PAGE_SIZE - offset);
6657 kaddr = page_address(page);
6658 memcpy(kaddr + offset, src, cur);
6667 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6674 unsigned long i = get_eb_page_index(start);
6676 if (check_eb_range(eb, start, len))
6679 offset = get_eb_offset_in_page(eb, start);
6682 page = eb->pages[i];
6683 assert_eb_page_uptodate(eb, page);
6685 cur = min(len, PAGE_SIZE - offset);
6686 kaddr = page_address(page);
6687 memset(kaddr + offset, 0, cur);
6695 void copy_extent_buffer_full(const struct extent_buffer *dst,
6696 const struct extent_buffer *src)
6701 ASSERT(dst->len == src->len);
6703 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6704 num_pages = num_extent_pages(dst);
6705 for (i = 0; i < num_pages; i++)
6706 copy_page(page_address(dst->pages[i]),
6707 page_address(src->pages[i]));
6709 size_t src_offset = get_eb_offset_in_page(src, 0);
6710 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6712 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6713 memcpy(page_address(dst->pages[0]) + dst_offset,
6714 page_address(src->pages[0]) + src_offset,
6719 void copy_extent_buffer(const struct extent_buffer *dst,
6720 const struct extent_buffer *src,
6721 unsigned long dst_offset, unsigned long src_offset,
6724 u64 dst_len = dst->len;
6729 unsigned long i = get_eb_page_index(dst_offset);
6731 if (check_eb_range(dst, dst_offset, len) ||
6732 check_eb_range(src, src_offset, len))
6735 WARN_ON(src->len != dst_len);
6737 offset = get_eb_offset_in_page(dst, dst_offset);
6740 page = dst->pages[i];
6741 assert_eb_page_uptodate(dst, page);
6743 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
6745 kaddr = page_address(page);
6746 read_extent_buffer(src, kaddr + offset, src_offset, cur);
6756 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6758 * @eb: the extent buffer
6759 * @start: offset of the bitmap item in the extent buffer
6761 * @page_index: return index of the page in the extent buffer that contains the
6763 * @page_offset: return offset into the page given by page_index
6765 * This helper hides the ugliness of finding the byte in an extent buffer which
6766 * contains a given bit.
6768 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
6769 unsigned long start, unsigned long nr,
6770 unsigned long *page_index,
6771 size_t *page_offset)
6773 size_t byte_offset = BIT_BYTE(nr);
6777 * The byte we want is the offset of the extent buffer + the offset of
6778 * the bitmap item in the extent buffer + the offset of the byte in the
6781 offset = start + offset_in_page(eb->start) + byte_offset;
6783 *page_index = offset >> PAGE_SHIFT;
6784 *page_offset = offset_in_page(offset);
6788 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6789 * @eb: the extent buffer
6790 * @start: offset of the bitmap item in the extent buffer
6791 * @nr: bit number to test
6793 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
6801 eb_bitmap_offset(eb, start, nr, &i, &offset);
6802 page = eb->pages[i];
6803 assert_eb_page_uptodate(eb, page);
6804 kaddr = page_address(page);
6805 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6809 * extent_buffer_bitmap_set - set an area of a bitmap
6810 * @eb: the extent buffer
6811 * @start: offset of the bitmap item in the extent buffer
6812 * @pos: bit number of the first bit
6813 * @len: number of bits to set
6815 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
6816 unsigned long pos, unsigned long len)
6822 const unsigned int size = pos + len;
6823 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6824 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
6826 eb_bitmap_offset(eb, start, pos, &i, &offset);
6827 page = eb->pages[i];
6828 assert_eb_page_uptodate(eb, page);
6829 kaddr = page_address(page);
6831 while (len >= bits_to_set) {
6832 kaddr[offset] |= mask_to_set;
6834 bits_to_set = BITS_PER_BYTE;
6836 if (++offset >= PAGE_SIZE && len > 0) {
6838 page = eb->pages[++i];
6839 assert_eb_page_uptodate(eb, page);
6840 kaddr = page_address(page);
6844 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6845 kaddr[offset] |= mask_to_set;
6851 * extent_buffer_bitmap_clear - clear an area of a bitmap
6852 * @eb: the extent buffer
6853 * @start: offset of the bitmap item in the extent buffer
6854 * @pos: bit number of the first bit
6855 * @len: number of bits to clear
6857 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6858 unsigned long start, unsigned long pos,
6865 const unsigned int size = pos + len;
6866 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6867 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
6869 eb_bitmap_offset(eb, start, pos, &i, &offset);
6870 page = eb->pages[i];
6871 assert_eb_page_uptodate(eb, page);
6872 kaddr = page_address(page);
6874 while (len >= bits_to_clear) {
6875 kaddr[offset] &= ~mask_to_clear;
6876 len -= bits_to_clear;
6877 bits_to_clear = BITS_PER_BYTE;
6879 if (++offset >= PAGE_SIZE && len > 0) {
6881 page = eb->pages[++i];
6882 assert_eb_page_uptodate(eb, page);
6883 kaddr = page_address(page);
6887 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6888 kaddr[offset] &= ~mask_to_clear;
6892 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6894 unsigned long distance = (src > dst) ? src - dst : dst - src;
6895 return distance < len;
6898 static void copy_pages(struct page *dst_page, struct page *src_page,
6899 unsigned long dst_off, unsigned long src_off,
6902 char *dst_kaddr = page_address(dst_page);
6904 int must_memmove = 0;
6906 if (dst_page != src_page) {
6907 src_kaddr = page_address(src_page);
6909 src_kaddr = dst_kaddr;
6910 if (areas_overlap(src_off, dst_off, len))
6915 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6917 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6920 void memcpy_extent_buffer(const struct extent_buffer *dst,
6921 unsigned long dst_offset, unsigned long src_offset,
6925 size_t dst_off_in_page;
6926 size_t src_off_in_page;
6927 unsigned long dst_i;
6928 unsigned long src_i;
6930 if (check_eb_range(dst, dst_offset, len) ||
6931 check_eb_range(dst, src_offset, len))
6935 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6936 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
6938 dst_i = get_eb_page_index(dst_offset);
6939 src_i = get_eb_page_index(src_offset);
6941 cur = min(len, (unsigned long)(PAGE_SIZE -
6943 cur = min_t(unsigned long, cur,
6944 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6946 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6947 dst_off_in_page, src_off_in_page, cur);
6955 void memmove_extent_buffer(const struct extent_buffer *dst,
6956 unsigned long dst_offset, unsigned long src_offset,
6960 size_t dst_off_in_page;
6961 size_t src_off_in_page;
6962 unsigned long dst_end = dst_offset + len - 1;
6963 unsigned long src_end = src_offset + len - 1;
6964 unsigned long dst_i;
6965 unsigned long src_i;
6967 if (check_eb_range(dst, dst_offset, len) ||
6968 check_eb_range(dst, src_offset, len))
6970 if (dst_offset < src_offset) {
6971 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6975 dst_i = get_eb_page_index(dst_end);
6976 src_i = get_eb_page_index(src_end);
6978 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6979 src_off_in_page = get_eb_offset_in_page(dst, src_end);
6981 cur = min_t(unsigned long, len, src_off_in_page + 1);
6982 cur = min(cur, dst_off_in_page + 1);
6983 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6984 dst_off_in_page - cur + 1,
6985 src_off_in_page - cur + 1, cur);
6993 static struct extent_buffer *get_next_extent_buffer(
6994 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6996 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6997 struct extent_buffer *found = NULL;
6998 u64 page_start = page_offset(page);
7002 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7003 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
7004 lockdep_assert_held(&fs_info->buffer_lock);
7006 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
7007 bytenr >> fs_info->sectorsize_bits,
7008 PAGE_SIZE / fs_info->nodesize);
7009 for (i = 0; i < ret; i++) {
7010 /* Already beyond page end */
7011 if (gang[i]->start >= page_start + PAGE_SIZE)
7014 if (gang[i]->start >= bytenr) {
7022 static int try_release_subpage_extent_buffer(struct page *page)
7024 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7025 u64 cur = page_offset(page);
7026 const u64 end = page_offset(page) + PAGE_SIZE;
7030 struct extent_buffer *eb = NULL;
7033 * Unlike try_release_extent_buffer() which uses page->private
7034 * to grab buffer, for subpage case we rely on radix tree, thus
7035 * we need to ensure radix tree consistency.
7037 * We also want an atomic snapshot of the radix tree, thus go
7038 * with spinlock rather than RCU.
7040 spin_lock(&fs_info->buffer_lock);
7041 eb = get_next_extent_buffer(fs_info, page, cur);
7043 /* No more eb in the page range after or at cur */
7044 spin_unlock(&fs_info->buffer_lock);
7047 cur = eb->start + eb->len;
7050 * The same as try_release_extent_buffer(), to ensure the eb
7051 * won't disappear out from under us.
7053 spin_lock(&eb->refs_lock);
7054 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7055 spin_unlock(&eb->refs_lock);
7056 spin_unlock(&fs_info->buffer_lock);
7059 spin_unlock(&fs_info->buffer_lock);
7062 * If tree ref isn't set then we know the ref on this eb is a
7063 * real ref, so just return, this eb will likely be freed soon
7066 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7067 spin_unlock(&eb->refs_lock);
7072 * Here we don't care about the return value, we will always
7073 * check the page private at the end. And
7074 * release_extent_buffer() will release the refs_lock.
7076 release_extent_buffer(eb);
7079 * Finally to check if we have cleared page private, as if we have
7080 * released all ebs in the page, the page private should be cleared now.
7082 spin_lock(&page->mapping->private_lock);
7083 if (!PagePrivate(page))
7087 spin_unlock(&page->mapping->private_lock);
7092 int try_release_extent_buffer(struct page *page)
7094 struct extent_buffer *eb;
7096 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
7097 return try_release_subpage_extent_buffer(page);
7100 * We need to make sure nobody is changing page->private, as we rely on
7101 * page->private as the pointer to extent buffer.
7103 spin_lock(&page->mapping->private_lock);
7104 if (!PagePrivate(page)) {
7105 spin_unlock(&page->mapping->private_lock);
7109 eb = (struct extent_buffer *)page->private;
7113 * This is a little awful but should be ok, we need to make sure that
7114 * the eb doesn't disappear out from under us while we're looking at
7117 spin_lock(&eb->refs_lock);
7118 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7119 spin_unlock(&eb->refs_lock);
7120 spin_unlock(&page->mapping->private_lock);
7123 spin_unlock(&page->mapping->private_lock);
7126 * If tree ref isn't set then we know the ref on this eb is a real ref,
7127 * so just return, this page will likely be freed soon anyway.
7129 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7130 spin_unlock(&eb->refs_lock);
7134 return release_extent_buffer(eb);
7138 * btrfs_readahead_tree_block - attempt to readahead a child block
7139 * @fs_info: the fs_info
7140 * @bytenr: bytenr to read
7141 * @owner_root: objectid of the root that owns this eb
7142 * @gen: generation for the uptodate check, can be 0
7143 * @level: level for the eb
7145 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7146 * normal uptodate check of the eb, without checking the generation. If we have
7147 * to read the block we will not block on anything.
7149 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7150 u64 bytenr, u64 owner_root, u64 gen, int level)
7152 struct extent_buffer *eb;
7155 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7159 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7160 free_extent_buffer(eb);
7164 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7166 free_extent_buffer_stale(eb);
7168 free_extent_buffer(eb);
7172 * btrfs_readahead_node_child - readahead a node's child block
7173 * @node: parent node we're reading from
7174 * @slot: slot in the parent node for the child we want to read
7176 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7177 * the slot in the node provided.
7179 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7181 btrfs_readahead_tree_block(node->fs_info,
7182 btrfs_node_blockptr(node, slot),
7183 btrfs_header_owner(node),
7184 btrfs_node_ptr_generation(node, slot),
7185 btrfs_header_level(node) - 1);