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>
16 #include "extent_io.h"
17 #include "extent-io-tree.h"
18 #include "extent_map.h"
20 #include "btrfs_inode.h"
22 #include "check-integrity.h"
24 #include "rcu-string.h"
29 static struct kmem_cache *extent_state_cache;
30 static struct kmem_cache *extent_buffer_cache;
31 static struct bio_set btrfs_bioset;
33 static inline bool extent_state_in_tree(const struct extent_state *state)
35 return !RB_EMPTY_NODE(&state->rb_node);
38 #ifdef CONFIG_BTRFS_DEBUG
39 static LIST_HEAD(states);
40 static DEFINE_SPINLOCK(leak_lock);
42 static inline void btrfs_leak_debug_add(spinlock_t *lock,
43 struct list_head *new,
44 struct list_head *head)
48 spin_lock_irqsave(lock, flags);
50 spin_unlock_irqrestore(lock, flags);
53 static inline void btrfs_leak_debug_del(spinlock_t *lock,
54 struct list_head *entry)
58 spin_lock_irqsave(lock, flags);
60 spin_unlock_irqrestore(lock, flags);
63 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
65 struct extent_buffer *eb;
69 * If we didn't get into open_ctree our allocated_ebs will not be
70 * initialized, so just skip this.
72 if (!fs_info->allocated_ebs.next)
75 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
76 while (!list_empty(&fs_info->allocated_ebs)) {
77 eb = list_first_entry(&fs_info->allocated_ebs,
78 struct extent_buffer, leak_list);
80 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
81 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
82 btrfs_header_owner(eb));
83 list_del(&eb->leak_list);
84 kmem_cache_free(extent_buffer_cache, eb);
86 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
89 static inline void btrfs_extent_state_leak_debug_check(void)
91 struct extent_state *state;
93 while (!list_empty(&states)) {
94 state = list_entry(states.next, struct extent_state, leak_list);
95 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
96 state->start, state->end, state->state,
97 extent_state_in_tree(state),
98 refcount_read(&state->refs));
99 list_del(&state->leak_list);
100 kmem_cache_free(extent_state_cache, state);
104 #define btrfs_debug_check_extent_io_range(tree, start, end) \
105 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
106 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
107 struct extent_io_tree *tree, u64 start, u64 end)
109 struct inode *inode = tree->private_data;
112 if (!inode || !is_data_inode(inode))
115 isize = i_size_read(inode);
116 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
117 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
118 "%s: ino %llu isize %llu odd range [%llu,%llu]",
119 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
123 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
124 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
125 #define btrfs_extent_state_leak_debug_check() do {} while (0)
126 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
132 struct rb_node rb_node;
135 struct extent_page_data {
137 /* tells writepage not to lock the state bits for this range
138 * it still does the unlocking
140 unsigned int extent_locked:1;
142 /* tells the submit_bio code to use REQ_SYNC */
143 unsigned int sync_io:1;
146 static int add_extent_changeset(struct extent_state *state, u32 bits,
147 struct extent_changeset *changeset,
154 if (set && (state->state & bits) == bits)
156 if (!set && (state->state & bits) == 0)
158 changeset->bytes_changed += state->end - state->start + 1;
159 ret = ulist_add(&changeset->range_changed, state->start, state->end,
164 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
165 unsigned long bio_flags)
167 blk_status_t ret = 0;
168 struct extent_io_tree *tree = bio->bi_private;
170 bio->bi_private = NULL;
172 if (is_data_inode(tree->private_data))
173 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
176 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
177 mirror_num, bio_flags);
179 return blk_status_to_errno(ret);
182 /* Cleanup unsubmitted bios */
183 static void end_write_bio(struct extent_page_data *epd, int ret)
186 epd->bio->bi_status = errno_to_blk_status(ret);
193 * Submit bio from extent page data via submit_one_bio
195 * Return 0 if everything is OK.
196 * Return <0 for error.
198 static int __must_check flush_write_bio(struct extent_page_data *epd)
203 ret = submit_one_bio(epd->bio, 0, 0);
205 * Clean up of epd->bio is handled by its endio function.
206 * And endio is either triggered by successful bio execution
207 * or the error handler of submit bio hook.
208 * So at this point, no matter what happened, we don't need
209 * to clean up epd->bio.
216 int __init extent_state_cache_init(void)
218 extent_state_cache = kmem_cache_create("btrfs_extent_state",
219 sizeof(struct extent_state), 0,
220 SLAB_MEM_SPREAD, NULL);
221 if (!extent_state_cache)
226 int __init extent_io_init(void)
228 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
229 sizeof(struct extent_buffer), 0,
230 SLAB_MEM_SPREAD, NULL);
231 if (!extent_buffer_cache)
234 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
235 offsetof(struct btrfs_io_bio, bio),
237 goto free_buffer_cache;
239 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
245 bioset_exit(&btrfs_bioset);
248 kmem_cache_destroy(extent_buffer_cache);
249 extent_buffer_cache = NULL;
253 void __cold extent_state_cache_exit(void)
255 btrfs_extent_state_leak_debug_check();
256 kmem_cache_destroy(extent_state_cache);
259 void __cold extent_io_exit(void)
262 * Make sure all delayed rcu free are flushed before we
266 kmem_cache_destroy(extent_buffer_cache);
267 bioset_exit(&btrfs_bioset);
271 * For the file_extent_tree, we want to hold the inode lock when we lookup and
272 * update the disk_i_size, but lockdep will complain because our io_tree we hold
273 * the tree lock and get the inode lock when setting delalloc. These two things
274 * are unrelated, so make a class for the file_extent_tree so we don't get the
275 * two locking patterns mixed up.
277 static struct lock_class_key file_extent_tree_class;
279 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
280 struct extent_io_tree *tree, unsigned int owner,
283 tree->fs_info = fs_info;
284 tree->state = RB_ROOT;
285 tree->dirty_bytes = 0;
286 spin_lock_init(&tree->lock);
287 tree->private_data = private_data;
289 if (owner == IO_TREE_INODE_FILE_EXTENT)
290 lockdep_set_class(&tree->lock, &file_extent_tree_class);
293 void extent_io_tree_release(struct extent_io_tree *tree)
295 spin_lock(&tree->lock);
297 * Do a single barrier for the waitqueue_active check here, the state
298 * of the waitqueue should not change once extent_io_tree_release is
302 while (!RB_EMPTY_ROOT(&tree->state)) {
303 struct rb_node *node;
304 struct extent_state *state;
306 node = rb_first(&tree->state);
307 state = rb_entry(node, struct extent_state, rb_node);
308 rb_erase(&state->rb_node, &tree->state);
309 RB_CLEAR_NODE(&state->rb_node);
311 * btree io trees aren't supposed to have tasks waiting for
312 * changes in the flags of extent states ever.
314 ASSERT(!waitqueue_active(&state->wq));
315 free_extent_state(state);
317 cond_resched_lock(&tree->lock);
319 spin_unlock(&tree->lock);
322 static struct extent_state *alloc_extent_state(gfp_t mask)
324 struct extent_state *state;
327 * The given mask might be not appropriate for the slab allocator,
328 * drop the unsupported bits
330 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
331 state = kmem_cache_alloc(extent_state_cache, mask);
335 state->failrec = NULL;
336 RB_CLEAR_NODE(&state->rb_node);
337 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
338 refcount_set(&state->refs, 1);
339 init_waitqueue_head(&state->wq);
340 trace_alloc_extent_state(state, mask, _RET_IP_);
344 void free_extent_state(struct extent_state *state)
348 if (refcount_dec_and_test(&state->refs)) {
349 WARN_ON(extent_state_in_tree(state));
350 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
351 trace_free_extent_state(state, _RET_IP_);
352 kmem_cache_free(extent_state_cache, state);
356 static struct rb_node *tree_insert(struct rb_root *root,
357 struct rb_node *search_start,
359 struct rb_node *node,
360 struct rb_node ***p_in,
361 struct rb_node **parent_in)
364 struct rb_node *parent = NULL;
365 struct tree_entry *entry;
367 if (p_in && parent_in) {
373 p = search_start ? &search_start : &root->rb_node;
376 entry = rb_entry(parent, struct tree_entry, rb_node);
378 if (offset < entry->start)
380 else if (offset > entry->end)
387 rb_link_node(node, parent, p);
388 rb_insert_color(node, root);
393 * Search @tree for an entry that contains @offset. Such entry would have
394 * entry->start <= offset && entry->end >= offset.
396 * @tree: the tree to search
397 * @offset: offset that should fall within an entry in @tree
398 * @next_ret: pointer to the first entry whose range ends after @offset
399 * @prev_ret: pointer to the first entry whose range begins before @offset
400 * @p_ret: pointer where new node should be anchored (used when inserting an
402 * @parent_ret: points to entry which would have been the parent of the entry,
405 * This function returns a pointer to the entry that contains @offset byte
406 * address. If no such entry exists, then NULL is returned and the other
407 * pointer arguments to the function are filled, otherwise the found entry is
408 * returned and other pointers are left untouched.
410 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
411 struct rb_node **next_ret,
412 struct rb_node **prev_ret,
413 struct rb_node ***p_ret,
414 struct rb_node **parent_ret)
416 struct rb_root *root = &tree->state;
417 struct rb_node **n = &root->rb_node;
418 struct rb_node *prev = NULL;
419 struct rb_node *orig_prev = NULL;
420 struct tree_entry *entry;
421 struct tree_entry *prev_entry = NULL;
425 entry = rb_entry(prev, struct tree_entry, rb_node);
428 if (offset < entry->start)
430 else if (offset > entry->end)
443 while (prev && offset > prev_entry->end) {
444 prev = rb_next(prev);
445 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
452 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
453 while (prev && offset < prev_entry->start) {
454 prev = rb_prev(prev);
455 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
462 static inline struct rb_node *
463 tree_search_for_insert(struct extent_io_tree *tree,
465 struct rb_node ***p_ret,
466 struct rb_node **parent_ret)
468 struct rb_node *next= NULL;
471 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
477 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
480 return tree_search_for_insert(tree, offset, NULL, NULL);
484 * utility function to look for merge candidates inside a given range.
485 * Any extents with matching state are merged together into a single
486 * extent in the tree. Extents with EXTENT_IO in their state field
487 * are not merged because the end_io handlers need to be able to do
488 * operations on them without sleeping (or doing allocations/splits).
490 * This should be called with the tree lock held.
492 static void merge_state(struct extent_io_tree *tree,
493 struct extent_state *state)
495 struct extent_state *other;
496 struct rb_node *other_node;
498 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
501 other_node = rb_prev(&state->rb_node);
503 other = rb_entry(other_node, struct extent_state, rb_node);
504 if (other->end == state->start - 1 &&
505 other->state == state->state) {
506 if (tree->private_data &&
507 is_data_inode(tree->private_data))
508 btrfs_merge_delalloc_extent(tree->private_data,
510 state->start = other->start;
511 rb_erase(&other->rb_node, &tree->state);
512 RB_CLEAR_NODE(&other->rb_node);
513 free_extent_state(other);
516 other_node = rb_next(&state->rb_node);
518 other = rb_entry(other_node, struct extent_state, rb_node);
519 if (other->start == state->end + 1 &&
520 other->state == state->state) {
521 if (tree->private_data &&
522 is_data_inode(tree->private_data))
523 btrfs_merge_delalloc_extent(tree->private_data,
525 state->end = other->end;
526 rb_erase(&other->rb_node, &tree->state);
527 RB_CLEAR_NODE(&other->rb_node);
528 free_extent_state(other);
533 static void set_state_bits(struct extent_io_tree *tree,
534 struct extent_state *state, u32 *bits,
535 struct extent_changeset *changeset);
538 * insert an extent_state struct into the tree. 'bits' are set on the
539 * struct before it is inserted.
541 * This may return -EEXIST if the extent is already there, in which case the
542 * state struct is freed.
544 * The tree lock is not taken internally. This is a utility function and
545 * probably isn't what you want to call (see set/clear_extent_bit).
547 static int insert_state(struct extent_io_tree *tree,
548 struct extent_state *state, u64 start, u64 end,
550 struct rb_node **parent,
551 u32 *bits, struct extent_changeset *changeset)
553 struct rb_node *node;
556 btrfs_err(tree->fs_info,
557 "insert state: end < start %llu %llu", end, start);
560 state->start = start;
563 set_state_bits(tree, state, bits, changeset);
565 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
567 struct extent_state *found;
568 found = rb_entry(node, struct extent_state, rb_node);
569 btrfs_err(tree->fs_info,
570 "found node %llu %llu on insert of %llu %llu",
571 found->start, found->end, start, end);
574 merge_state(tree, state);
579 * split a given extent state struct in two, inserting the preallocated
580 * struct 'prealloc' as the newly created second half. 'split' indicates an
581 * offset inside 'orig' where it should be split.
584 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
585 * are two extent state structs in the tree:
586 * prealloc: [orig->start, split - 1]
587 * orig: [ split, orig->end ]
589 * The tree locks are not taken by this function. They need to be held
592 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
593 struct extent_state *prealloc, u64 split)
595 struct rb_node *node;
597 if (tree->private_data && is_data_inode(tree->private_data))
598 btrfs_split_delalloc_extent(tree->private_data, orig, split);
600 prealloc->start = orig->start;
601 prealloc->end = split - 1;
602 prealloc->state = orig->state;
605 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
606 &prealloc->rb_node, NULL, NULL);
608 free_extent_state(prealloc);
614 static struct extent_state *next_state(struct extent_state *state)
616 struct rb_node *next = rb_next(&state->rb_node);
618 return rb_entry(next, struct extent_state, rb_node);
624 * utility function to clear some bits in an extent state struct.
625 * it will optionally wake up anyone waiting on this state (wake == 1).
627 * If no bits are set on the state struct after clearing things, the
628 * struct is freed and removed from the tree
630 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
631 struct extent_state *state,
633 struct extent_changeset *changeset)
635 struct extent_state *next;
636 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
639 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
640 u64 range = state->end - state->start + 1;
641 WARN_ON(range > tree->dirty_bytes);
642 tree->dirty_bytes -= range;
645 if (tree->private_data && is_data_inode(tree->private_data))
646 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
648 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
650 state->state &= ~bits_to_clear;
653 if (state->state == 0) {
654 next = next_state(state);
655 if (extent_state_in_tree(state)) {
656 rb_erase(&state->rb_node, &tree->state);
657 RB_CLEAR_NODE(&state->rb_node);
658 free_extent_state(state);
663 merge_state(tree, state);
664 next = next_state(state);
669 static struct extent_state *
670 alloc_extent_state_atomic(struct extent_state *prealloc)
673 prealloc = alloc_extent_state(GFP_ATOMIC);
678 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
680 btrfs_panic(tree->fs_info, err,
681 "locking error: extent tree was modified by another thread while locked");
685 * clear some bits on a range in the tree. This may require splitting
686 * or inserting elements in the tree, so the gfp mask is used to
687 * indicate which allocations or sleeping are allowed.
689 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
690 * the given range from the tree regardless of state (ie for truncate).
692 * the range [start, end] is inclusive.
694 * This takes the tree lock, and returns 0 on success and < 0 on error.
696 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
697 u32 bits, int wake, int delete,
698 struct extent_state **cached_state,
699 gfp_t mask, struct extent_changeset *changeset)
701 struct extent_state *state;
702 struct extent_state *cached;
703 struct extent_state *prealloc = NULL;
704 struct rb_node *node;
709 btrfs_debug_check_extent_io_range(tree, start, end);
710 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
712 if (bits & EXTENT_DELALLOC)
713 bits |= EXTENT_NORESERVE;
716 bits |= ~EXTENT_CTLBITS;
718 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
721 if (!prealloc && gfpflags_allow_blocking(mask)) {
723 * Don't care for allocation failure here because we might end
724 * up not needing the pre-allocated extent state at all, which
725 * is the case if we only have in the tree extent states that
726 * cover our input range and don't cover too any other range.
727 * If we end up needing a new extent state we allocate it later.
729 prealloc = alloc_extent_state(mask);
732 spin_lock(&tree->lock);
734 cached = *cached_state;
737 *cached_state = NULL;
741 if (cached && extent_state_in_tree(cached) &&
742 cached->start <= start && cached->end > start) {
744 refcount_dec(&cached->refs);
749 free_extent_state(cached);
752 * this search will find the extents that end after
755 node = tree_search(tree, start);
758 state = rb_entry(node, struct extent_state, rb_node);
760 if (state->start > end)
762 WARN_ON(state->end < start);
763 last_end = state->end;
765 /* the state doesn't have the wanted bits, go ahead */
766 if (!(state->state & bits)) {
767 state = next_state(state);
772 * | ---- desired range ---- |
774 * | ------------- state -------------- |
776 * We need to split the extent we found, and may flip
777 * bits on second half.
779 * If the extent we found extends past our range, we
780 * just split and search again. It'll get split again
781 * the next time though.
783 * If the extent we found is inside our range, we clear
784 * the desired bit on it.
787 if (state->start < start) {
788 prealloc = alloc_extent_state_atomic(prealloc);
790 err = split_state(tree, state, prealloc, start);
792 extent_io_tree_panic(tree, err);
797 if (state->end <= end) {
798 state = clear_state_bit(tree, state, &bits, wake,
805 * | ---- desired range ---- |
807 * We need to split the extent, and clear the bit
810 if (state->start <= end && state->end > end) {
811 prealloc = alloc_extent_state_atomic(prealloc);
813 err = split_state(tree, state, prealloc, end + 1);
815 extent_io_tree_panic(tree, err);
820 clear_state_bit(tree, prealloc, &bits, wake, changeset);
826 state = clear_state_bit(tree, state, &bits, wake, changeset);
828 if (last_end == (u64)-1)
830 start = last_end + 1;
831 if (start <= end && state && !need_resched())
837 spin_unlock(&tree->lock);
838 if (gfpflags_allow_blocking(mask))
843 spin_unlock(&tree->lock);
845 free_extent_state(prealloc);
851 static void wait_on_state(struct extent_io_tree *tree,
852 struct extent_state *state)
853 __releases(tree->lock)
854 __acquires(tree->lock)
857 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
858 spin_unlock(&tree->lock);
860 spin_lock(&tree->lock);
861 finish_wait(&state->wq, &wait);
865 * waits for one or more bits to clear on a range in the state tree.
866 * The range [start, end] is inclusive.
867 * The tree lock is taken by this function
869 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
872 struct extent_state *state;
873 struct rb_node *node;
875 btrfs_debug_check_extent_io_range(tree, start, end);
877 spin_lock(&tree->lock);
881 * this search will find all the extents that end after
884 node = tree_search(tree, start);
889 state = rb_entry(node, struct extent_state, rb_node);
891 if (state->start > end)
894 if (state->state & bits) {
895 start = state->start;
896 refcount_inc(&state->refs);
897 wait_on_state(tree, state);
898 free_extent_state(state);
901 start = state->end + 1;
906 if (!cond_resched_lock(&tree->lock)) {
907 node = rb_next(node);
912 spin_unlock(&tree->lock);
915 static void set_state_bits(struct extent_io_tree *tree,
916 struct extent_state *state,
917 u32 *bits, struct extent_changeset *changeset)
919 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
922 if (tree->private_data && is_data_inode(tree->private_data))
923 btrfs_set_delalloc_extent(tree->private_data, state, bits);
925 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
926 u64 range = state->end - state->start + 1;
927 tree->dirty_bytes += range;
929 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
931 state->state |= bits_to_set;
934 static void cache_state_if_flags(struct extent_state *state,
935 struct extent_state **cached_ptr,
938 if (cached_ptr && !(*cached_ptr)) {
939 if (!flags || (state->state & flags)) {
941 refcount_inc(&state->refs);
946 static void cache_state(struct extent_state *state,
947 struct extent_state **cached_ptr)
949 return cache_state_if_flags(state, cached_ptr,
950 EXTENT_LOCKED | EXTENT_BOUNDARY);
954 * set some bits on a range in the tree. This may require allocations or
955 * sleeping, so the gfp mask is used to indicate what is allowed.
957 * If any of the exclusive bits are set, this will fail with -EEXIST if some
958 * part of the range already has the desired bits set. The start of the
959 * existing range is returned in failed_start in this case.
961 * [start, end] is inclusive This takes the tree lock.
963 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
964 u32 exclusive_bits, u64 *failed_start,
965 struct extent_state **cached_state, gfp_t mask,
966 struct extent_changeset *changeset)
968 struct extent_state *state;
969 struct extent_state *prealloc = NULL;
970 struct rb_node *node;
972 struct rb_node *parent;
977 btrfs_debug_check_extent_io_range(tree, start, end);
978 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
981 ASSERT(failed_start);
983 ASSERT(failed_start == NULL);
985 if (!prealloc && gfpflags_allow_blocking(mask)) {
987 * Don't care for allocation failure here because we might end
988 * up not needing the pre-allocated extent state at all, which
989 * is the case if we only have in the tree extent states that
990 * cover our input range and don't cover too any other range.
991 * If we end up needing a new extent state we allocate it later.
993 prealloc = alloc_extent_state(mask);
996 spin_lock(&tree->lock);
997 if (cached_state && *cached_state) {
998 state = *cached_state;
999 if (state->start <= start && state->end > start &&
1000 extent_state_in_tree(state)) {
1001 node = &state->rb_node;
1006 * this search will find all the extents that end after
1009 node = tree_search_for_insert(tree, start, &p, &parent);
1011 prealloc = alloc_extent_state_atomic(prealloc);
1013 err = insert_state(tree, prealloc, start, end,
1014 &p, &parent, &bits, changeset);
1016 extent_io_tree_panic(tree, err);
1018 cache_state(prealloc, cached_state);
1022 state = rb_entry(node, struct extent_state, rb_node);
1024 last_start = state->start;
1025 last_end = state->end;
1028 * | ---- desired range ---- |
1031 * Just lock what we found and keep going
1033 if (state->start == start && state->end <= end) {
1034 if (state->state & exclusive_bits) {
1035 *failed_start = state->start;
1040 set_state_bits(tree, state, &bits, changeset);
1041 cache_state(state, cached_state);
1042 merge_state(tree, state);
1043 if (last_end == (u64)-1)
1045 start = last_end + 1;
1046 state = next_state(state);
1047 if (start < end && state && state->start == start &&
1054 * | ---- desired range ---- |
1057 * | ------------- state -------------- |
1059 * We need to split the extent we found, and may flip bits on
1062 * If the extent we found extends past our
1063 * range, we just split and search again. It'll get split
1064 * again the next time though.
1066 * If the extent we found is inside our range, we set the
1067 * desired bit on it.
1069 if (state->start < start) {
1070 if (state->state & exclusive_bits) {
1071 *failed_start = start;
1077 * If this extent already has all the bits we want set, then
1078 * skip it, not necessary to split it or do anything with it.
1080 if ((state->state & bits) == bits) {
1081 start = state->end + 1;
1082 cache_state(state, cached_state);
1086 prealloc = alloc_extent_state_atomic(prealloc);
1088 err = split_state(tree, state, prealloc, start);
1090 extent_io_tree_panic(tree, err);
1095 if (state->end <= end) {
1096 set_state_bits(tree, state, &bits, changeset);
1097 cache_state(state, cached_state);
1098 merge_state(tree, state);
1099 if (last_end == (u64)-1)
1101 start = last_end + 1;
1102 state = next_state(state);
1103 if (start < end && state && state->start == start &&
1110 * | ---- desired range ---- |
1111 * | state | or | state |
1113 * There's a hole, we need to insert something in it and
1114 * ignore the extent we found.
1116 if (state->start > start) {
1118 if (end < last_start)
1121 this_end = last_start - 1;
1123 prealloc = alloc_extent_state_atomic(prealloc);
1127 * Avoid to free 'prealloc' if it can be merged with
1130 err = insert_state(tree, prealloc, start, this_end,
1131 NULL, NULL, &bits, changeset);
1133 extent_io_tree_panic(tree, err);
1135 cache_state(prealloc, cached_state);
1137 start = this_end + 1;
1141 * | ---- desired range ---- |
1143 * We need to split the extent, and set the bit
1146 if (state->start <= end && state->end > end) {
1147 if (state->state & exclusive_bits) {
1148 *failed_start = start;
1153 prealloc = alloc_extent_state_atomic(prealloc);
1155 err = split_state(tree, state, prealloc, end + 1);
1157 extent_io_tree_panic(tree, err);
1159 set_state_bits(tree, prealloc, &bits, changeset);
1160 cache_state(prealloc, cached_state);
1161 merge_state(tree, prealloc);
1169 spin_unlock(&tree->lock);
1170 if (gfpflags_allow_blocking(mask))
1175 spin_unlock(&tree->lock);
1177 free_extent_state(prealloc);
1184 * convert_extent_bit - convert all bits in a given range from one bit to
1186 * @tree: the io tree to search
1187 * @start: the start offset in bytes
1188 * @end: the end offset in bytes (inclusive)
1189 * @bits: the bits to set in this range
1190 * @clear_bits: the bits to clear in this range
1191 * @cached_state: state that we're going to cache
1193 * This will go through and set bits for the given range. If any states exist
1194 * already in this range they are set with the given bit and cleared of the
1195 * clear_bits. This is only meant to be used by things that are mergeable, ie
1196 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1197 * boundary bits like LOCK.
1199 * All allocations are done with GFP_NOFS.
1201 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1202 u32 bits, u32 clear_bits,
1203 struct extent_state **cached_state)
1205 struct extent_state *state;
1206 struct extent_state *prealloc = NULL;
1207 struct rb_node *node;
1209 struct rb_node *parent;
1213 bool first_iteration = true;
1215 btrfs_debug_check_extent_io_range(tree, start, end);
1216 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1222 * Best effort, don't worry if extent state allocation fails
1223 * here for the first iteration. We might have a cached state
1224 * that matches exactly the target range, in which case no
1225 * extent state allocations are needed. We'll only know this
1226 * after locking the tree.
1228 prealloc = alloc_extent_state(GFP_NOFS);
1229 if (!prealloc && !first_iteration)
1233 spin_lock(&tree->lock);
1234 if (cached_state && *cached_state) {
1235 state = *cached_state;
1236 if (state->start <= start && state->end > start &&
1237 extent_state_in_tree(state)) {
1238 node = &state->rb_node;
1244 * this search will find all the extents that end after
1247 node = tree_search_for_insert(tree, start, &p, &parent);
1249 prealloc = alloc_extent_state_atomic(prealloc);
1254 err = insert_state(tree, prealloc, start, end,
1255 &p, &parent, &bits, NULL);
1257 extent_io_tree_panic(tree, err);
1258 cache_state(prealloc, cached_state);
1262 state = rb_entry(node, struct extent_state, rb_node);
1264 last_start = state->start;
1265 last_end = state->end;
1268 * | ---- desired range ---- |
1271 * Just lock what we found and keep going
1273 if (state->start == start && state->end <= end) {
1274 set_state_bits(tree, state, &bits, NULL);
1275 cache_state(state, cached_state);
1276 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1277 if (last_end == (u64)-1)
1279 start = last_end + 1;
1280 if (start < end && state && state->start == start &&
1287 * | ---- desired range ---- |
1290 * | ------------- state -------------- |
1292 * We need to split the extent we found, and may flip bits on
1295 * If the extent we found extends past our
1296 * range, we just split and search again. It'll get split
1297 * again the next time though.
1299 * If the extent we found is inside our range, we set the
1300 * desired bit on it.
1302 if (state->start < start) {
1303 prealloc = alloc_extent_state_atomic(prealloc);
1308 err = split_state(tree, state, prealloc, start);
1310 extent_io_tree_panic(tree, err);
1314 if (state->end <= end) {
1315 set_state_bits(tree, state, &bits, NULL);
1316 cache_state(state, cached_state);
1317 state = clear_state_bit(tree, state, &clear_bits, 0,
1319 if (last_end == (u64)-1)
1321 start = last_end + 1;
1322 if (start < end && state && state->start == start &&
1329 * | ---- desired range ---- |
1330 * | state | or | state |
1332 * There's a hole, we need to insert something in it and
1333 * ignore the extent we found.
1335 if (state->start > start) {
1337 if (end < last_start)
1340 this_end = last_start - 1;
1342 prealloc = alloc_extent_state_atomic(prealloc);
1349 * Avoid to free 'prealloc' if it can be merged with
1352 err = insert_state(tree, prealloc, start, this_end,
1353 NULL, NULL, &bits, NULL);
1355 extent_io_tree_panic(tree, err);
1356 cache_state(prealloc, cached_state);
1358 start = this_end + 1;
1362 * | ---- desired range ---- |
1364 * We need to split the extent, and set the bit
1367 if (state->start <= end && state->end > end) {
1368 prealloc = alloc_extent_state_atomic(prealloc);
1374 err = split_state(tree, state, prealloc, end + 1);
1376 extent_io_tree_panic(tree, err);
1378 set_state_bits(tree, prealloc, &bits, NULL);
1379 cache_state(prealloc, cached_state);
1380 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1388 spin_unlock(&tree->lock);
1390 first_iteration = false;
1394 spin_unlock(&tree->lock);
1396 free_extent_state(prealloc);
1401 /* wrappers around set/clear extent bit */
1402 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1403 u32 bits, struct extent_changeset *changeset)
1406 * We don't support EXTENT_LOCKED yet, as current changeset will
1407 * record any bits changed, so for EXTENT_LOCKED case, it will
1408 * either fail with -EEXIST or changeset will record the whole
1411 BUG_ON(bits & EXTENT_LOCKED);
1413 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1417 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1420 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1424 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1425 u32 bits, int wake, int delete,
1426 struct extent_state **cached)
1428 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1429 cached, GFP_NOFS, NULL);
1432 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1433 u32 bits, struct extent_changeset *changeset)
1436 * Don't support EXTENT_LOCKED case, same reason as
1437 * set_record_extent_bits().
1439 BUG_ON(bits & EXTENT_LOCKED);
1441 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1446 * either insert or lock state struct between start and end use mask to tell
1447 * us if waiting is desired.
1449 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1450 struct extent_state **cached_state)
1456 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1457 EXTENT_LOCKED, &failed_start,
1458 cached_state, GFP_NOFS, NULL);
1459 if (err == -EEXIST) {
1460 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1461 start = failed_start;
1464 WARN_ON(start > end);
1469 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1474 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1475 &failed_start, NULL, GFP_NOFS, NULL);
1476 if (err == -EEXIST) {
1477 if (failed_start > start)
1478 clear_extent_bit(tree, start, failed_start - 1,
1479 EXTENT_LOCKED, 1, 0, NULL);
1485 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1487 unsigned long index = start >> PAGE_SHIFT;
1488 unsigned long end_index = end >> PAGE_SHIFT;
1491 while (index <= end_index) {
1492 page = find_get_page(inode->i_mapping, index);
1493 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1494 clear_page_dirty_for_io(page);
1500 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1502 unsigned long index = start >> PAGE_SHIFT;
1503 unsigned long end_index = end >> PAGE_SHIFT;
1506 while (index <= end_index) {
1507 page = find_get_page(inode->i_mapping, index);
1508 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1509 __set_page_dirty_nobuffers(page);
1510 account_page_redirty(page);
1516 /* find the first state struct with 'bits' set after 'start', and
1517 * return it. tree->lock must be held. NULL will returned if
1518 * nothing was found after 'start'
1520 static struct extent_state *
1521 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1523 struct rb_node *node;
1524 struct extent_state *state;
1527 * this search will find all the extents that end after
1530 node = tree_search(tree, start);
1535 state = rb_entry(node, struct extent_state, rb_node);
1536 if (state->end >= start && (state->state & bits))
1539 node = rb_next(node);
1548 * Find the first offset in the io tree with one or more @bits set.
1550 * Note: If there are multiple bits set in @bits, any of them will match.
1552 * Return 0 if we find something, and update @start_ret and @end_ret.
1553 * Return 1 if we found nothing.
1555 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1556 u64 *start_ret, u64 *end_ret, u32 bits,
1557 struct extent_state **cached_state)
1559 struct extent_state *state;
1562 spin_lock(&tree->lock);
1563 if (cached_state && *cached_state) {
1564 state = *cached_state;
1565 if (state->end == start - 1 && extent_state_in_tree(state)) {
1566 while ((state = next_state(state)) != NULL) {
1567 if (state->state & bits)
1570 free_extent_state(*cached_state);
1571 *cached_state = NULL;
1574 free_extent_state(*cached_state);
1575 *cached_state = NULL;
1578 state = find_first_extent_bit_state(tree, start, bits);
1581 cache_state_if_flags(state, cached_state, 0);
1582 *start_ret = state->start;
1583 *end_ret = state->end;
1587 spin_unlock(&tree->lock);
1592 * Find a contiguous area of bits
1594 * @tree: io tree to check
1595 * @start: offset to start the search from
1596 * @start_ret: the first offset we found with the bits set
1597 * @end_ret: the final contiguous range of the bits that were set
1598 * @bits: bits to look for
1600 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1601 * to set bits appropriately, and then merge them again. During this time it
1602 * will drop the tree->lock, so use this helper if you want to find the actual
1603 * contiguous area for given bits. We will search to the first bit we find, and
1604 * then walk down the tree until we find a non-contiguous area. The area
1605 * returned will be the full contiguous area with the bits set.
1607 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1608 u64 *start_ret, u64 *end_ret, u32 bits)
1610 struct extent_state *state;
1613 spin_lock(&tree->lock);
1614 state = find_first_extent_bit_state(tree, start, bits);
1616 *start_ret = state->start;
1617 *end_ret = state->end;
1618 while ((state = next_state(state)) != NULL) {
1619 if (state->start > (*end_ret + 1))
1621 *end_ret = state->end;
1625 spin_unlock(&tree->lock);
1630 * Find the first range that has @bits not set. This range could start before
1633 * @tree: the tree to search
1634 * @start: offset at/after which the found extent should start
1635 * @start_ret: records the beginning of the range
1636 * @end_ret: records the end of the range (inclusive)
1637 * @bits: the set of bits which must be unset
1639 * Since unallocated range is also considered one which doesn't have the bits
1640 * set it's possible that @end_ret contains -1, this happens in case the range
1641 * spans (last_range_end, end of device]. In this case it's up to the caller to
1642 * trim @end_ret to the appropriate size.
1644 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1645 u64 *start_ret, u64 *end_ret, u32 bits)
1647 struct extent_state *state;
1648 struct rb_node *node, *prev = NULL, *next;
1650 spin_lock(&tree->lock);
1652 /* Find first extent with bits cleared */
1654 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1655 if (!node && !next && !prev) {
1657 * Tree is completely empty, send full range and let
1658 * caller deal with it
1663 } else if (!node && !next) {
1665 * We are past the last allocated chunk, set start at
1666 * the end of the last extent.
1668 state = rb_entry(prev, struct extent_state, rb_node);
1669 *start_ret = state->end + 1;
1676 * At this point 'node' either contains 'start' or start is
1679 state = rb_entry(node, struct extent_state, rb_node);
1681 if (in_range(start, state->start, state->end - state->start + 1)) {
1682 if (state->state & bits) {
1684 * |--range with bits sets--|
1688 start = state->end + 1;
1691 * 'start' falls within a range that doesn't
1692 * have the bits set, so take its start as
1693 * the beginning of the desired range
1695 * |--range with bits cleared----|
1699 *start_ret = state->start;
1704 * |---prev range---|---hole/unset---|---node range---|
1710 * |---hole/unset--||--first node--|
1715 state = rb_entry(prev, struct extent_state,
1717 *start_ret = state->end + 1;
1726 * Find the longest stretch from start until an entry which has the
1730 state = rb_entry(node, struct extent_state, rb_node);
1731 if (state->end >= start && !(state->state & bits)) {
1732 *end_ret = state->end;
1734 *end_ret = state->start - 1;
1738 node = rb_next(node);
1743 spin_unlock(&tree->lock);
1747 * find a contiguous range of bytes in the file marked as delalloc, not
1748 * more than 'max_bytes'. start and end are used to return the range,
1750 * true is returned if we find something, false if nothing was in the tree
1752 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1753 u64 *end, u64 max_bytes,
1754 struct extent_state **cached_state)
1756 struct rb_node *node;
1757 struct extent_state *state;
1758 u64 cur_start = *start;
1760 u64 total_bytes = 0;
1762 spin_lock(&tree->lock);
1765 * this search will find all the extents that end after
1768 node = tree_search(tree, cur_start);
1775 state = rb_entry(node, struct extent_state, rb_node);
1776 if (found && (state->start != cur_start ||
1777 (state->state & EXTENT_BOUNDARY))) {
1780 if (!(state->state & EXTENT_DELALLOC)) {
1786 *start = state->start;
1787 *cached_state = state;
1788 refcount_inc(&state->refs);
1792 cur_start = state->end + 1;
1793 node = rb_next(node);
1794 total_bytes += state->end - state->start + 1;
1795 if (total_bytes >= max_bytes)
1801 spin_unlock(&tree->lock);
1805 static int __process_pages_contig(struct address_space *mapping,
1806 struct page *locked_page,
1807 pgoff_t start_index, pgoff_t end_index,
1808 unsigned long page_ops, pgoff_t *index_ret);
1810 static noinline void __unlock_for_delalloc(struct inode *inode,
1811 struct page *locked_page,
1814 unsigned long index = start >> PAGE_SHIFT;
1815 unsigned long end_index = end >> PAGE_SHIFT;
1817 ASSERT(locked_page);
1818 if (index == locked_page->index && end_index == index)
1821 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1825 static noinline int lock_delalloc_pages(struct inode *inode,
1826 struct page *locked_page,
1830 unsigned long index = delalloc_start >> PAGE_SHIFT;
1831 unsigned long index_ret = index;
1832 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1835 ASSERT(locked_page);
1836 if (index == locked_page->index && index == end_index)
1839 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1840 end_index, PAGE_LOCK, &index_ret);
1842 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1843 (u64)index_ret << PAGE_SHIFT);
1848 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1849 * more than @max_bytes. @Start and @end are used to return the range,
1851 * Return: true if we find something
1852 * false if nothing was in the tree
1855 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1856 struct page *locked_page, u64 *start,
1859 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1860 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1864 struct extent_state *cached_state = NULL;
1869 /* step one, find a bunch of delalloc bytes starting at start */
1870 delalloc_start = *start;
1872 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1873 max_bytes, &cached_state);
1874 if (!found || delalloc_end <= *start) {
1875 *start = delalloc_start;
1876 *end = delalloc_end;
1877 free_extent_state(cached_state);
1882 * start comes from the offset of locked_page. We have to lock
1883 * pages in order, so we can't process delalloc bytes before
1886 if (delalloc_start < *start)
1887 delalloc_start = *start;
1890 * make sure to limit the number of pages we try to lock down
1892 if (delalloc_end + 1 - delalloc_start > max_bytes)
1893 delalloc_end = delalloc_start + max_bytes - 1;
1895 /* step two, lock all the pages after the page that has start */
1896 ret = lock_delalloc_pages(inode, locked_page,
1897 delalloc_start, delalloc_end);
1898 ASSERT(!ret || ret == -EAGAIN);
1899 if (ret == -EAGAIN) {
1900 /* some of the pages are gone, lets avoid looping by
1901 * shortening the size of the delalloc range we're searching
1903 free_extent_state(cached_state);
1904 cached_state = NULL;
1906 max_bytes = PAGE_SIZE;
1915 /* step three, lock the state bits for the whole range */
1916 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1918 /* then test to make sure it is all still delalloc */
1919 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1920 EXTENT_DELALLOC, 1, cached_state);
1922 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1924 __unlock_for_delalloc(inode, locked_page,
1925 delalloc_start, delalloc_end);
1929 free_extent_state(cached_state);
1930 *start = delalloc_start;
1931 *end = delalloc_end;
1936 static int __process_pages_contig(struct address_space *mapping,
1937 struct page *locked_page,
1938 pgoff_t start_index, pgoff_t end_index,
1939 unsigned long page_ops, pgoff_t *index_ret)
1941 unsigned long nr_pages = end_index - start_index + 1;
1942 unsigned long pages_processed = 0;
1943 pgoff_t index = start_index;
1944 struct page *pages[16];
1949 if (page_ops & PAGE_LOCK) {
1950 ASSERT(page_ops == PAGE_LOCK);
1951 ASSERT(index_ret && *index_ret == start_index);
1954 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1955 mapping_set_error(mapping, -EIO);
1957 while (nr_pages > 0) {
1958 ret = find_get_pages_contig(mapping, index,
1959 min_t(unsigned long,
1960 nr_pages, ARRAY_SIZE(pages)), pages);
1963 * Only if we're going to lock these pages,
1964 * can we find nothing at @index.
1966 ASSERT(page_ops & PAGE_LOCK);
1971 for (i = 0; i < ret; i++) {
1972 if (page_ops & PAGE_SET_PRIVATE2)
1973 SetPagePrivate2(pages[i]);
1975 if (locked_page && pages[i] == locked_page) {
1980 if (page_ops & PAGE_START_WRITEBACK) {
1981 clear_page_dirty_for_io(pages[i]);
1982 set_page_writeback(pages[i]);
1984 if (page_ops & PAGE_SET_ERROR)
1985 SetPageError(pages[i]);
1986 if (page_ops & PAGE_END_WRITEBACK)
1987 end_page_writeback(pages[i]);
1988 if (page_ops & PAGE_UNLOCK)
1989 unlock_page(pages[i]);
1990 if (page_ops & PAGE_LOCK) {
1991 lock_page(pages[i]);
1992 if (!PageDirty(pages[i]) ||
1993 pages[i]->mapping != mapping) {
1994 unlock_page(pages[i]);
1995 for (; i < ret; i++)
2009 if (err && index_ret)
2010 *index_ret = start_index + pages_processed - 1;
2014 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2015 struct page *locked_page,
2016 u32 clear_bits, unsigned long page_ops)
2018 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2020 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2021 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
2026 * count the number of bytes in the tree that have a given bit(s)
2027 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2028 * cached. The total number found is returned.
2030 u64 count_range_bits(struct extent_io_tree *tree,
2031 u64 *start, u64 search_end, u64 max_bytes,
2032 u32 bits, int contig)
2034 struct rb_node *node;
2035 struct extent_state *state;
2036 u64 cur_start = *start;
2037 u64 total_bytes = 0;
2041 if (WARN_ON(search_end <= cur_start))
2044 spin_lock(&tree->lock);
2045 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2046 total_bytes = tree->dirty_bytes;
2050 * this search will find all the extents that end after
2053 node = tree_search(tree, cur_start);
2058 state = rb_entry(node, struct extent_state, rb_node);
2059 if (state->start > search_end)
2061 if (contig && found && state->start > last + 1)
2063 if (state->end >= cur_start && (state->state & bits) == bits) {
2064 total_bytes += min(search_end, state->end) + 1 -
2065 max(cur_start, state->start);
2066 if (total_bytes >= max_bytes)
2069 *start = max(cur_start, state->start);
2073 } else if (contig && found) {
2076 node = rb_next(node);
2081 spin_unlock(&tree->lock);
2086 * set the private field for a given byte offset in the tree. If there isn't
2087 * an extent_state there already, this does nothing.
2089 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2090 struct io_failure_record *failrec)
2092 struct rb_node *node;
2093 struct extent_state *state;
2096 spin_lock(&tree->lock);
2098 * this search will find all the extents that end after
2101 node = tree_search(tree, start);
2106 state = rb_entry(node, struct extent_state, rb_node);
2107 if (state->start != start) {
2111 state->failrec = failrec;
2113 spin_unlock(&tree->lock);
2117 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2119 struct rb_node *node;
2120 struct extent_state *state;
2121 struct io_failure_record *failrec;
2123 spin_lock(&tree->lock);
2125 * this search will find all the extents that end after
2128 node = tree_search(tree, start);
2130 failrec = ERR_PTR(-ENOENT);
2133 state = rb_entry(node, struct extent_state, rb_node);
2134 if (state->start != start) {
2135 failrec = ERR_PTR(-ENOENT);
2139 failrec = state->failrec;
2141 spin_unlock(&tree->lock);
2146 * searches a range in the state tree for a given mask.
2147 * If 'filled' == 1, this returns 1 only if every extent in the tree
2148 * has the bits set. Otherwise, 1 is returned if any bit in the
2149 * range is found set.
2151 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2152 u32 bits, int filled, struct extent_state *cached)
2154 struct extent_state *state = NULL;
2155 struct rb_node *node;
2158 spin_lock(&tree->lock);
2159 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2160 cached->end > start)
2161 node = &cached->rb_node;
2163 node = tree_search(tree, start);
2164 while (node && start <= end) {
2165 state = rb_entry(node, struct extent_state, rb_node);
2167 if (filled && state->start > start) {
2172 if (state->start > end)
2175 if (state->state & bits) {
2179 } else if (filled) {
2184 if (state->end == (u64)-1)
2187 start = state->end + 1;
2190 node = rb_next(node);
2197 spin_unlock(&tree->lock);
2202 * helper function to set a given page up to date if all the
2203 * extents in the tree for that page are up to date
2205 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2207 u64 start = page_offset(page);
2208 u64 end = start + PAGE_SIZE - 1;
2209 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2210 SetPageUptodate(page);
2213 int free_io_failure(struct extent_io_tree *failure_tree,
2214 struct extent_io_tree *io_tree,
2215 struct io_failure_record *rec)
2220 set_state_failrec(failure_tree, rec->start, NULL);
2221 ret = clear_extent_bits(failure_tree, rec->start,
2222 rec->start + rec->len - 1,
2223 EXTENT_LOCKED | EXTENT_DIRTY);
2227 ret = clear_extent_bits(io_tree, rec->start,
2228 rec->start + rec->len - 1,
2238 * this bypasses the standard btrfs submit functions deliberately, as
2239 * the standard behavior is to write all copies in a raid setup. here we only
2240 * want to write the one bad copy. so we do the mapping for ourselves and issue
2241 * submit_bio directly.
2242 * to avoid any synchronization issues, wait for the data after writing, which
2243 * actually prevents the read that triggered the error from finishing.
2244 * currently, there can be no more than two copies of every data bit. thus,
2245 * exactly one rewrite is required.
2247 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2248 u64 length, u64 logical, struct page *page,
2249 unsigned int pg_offset, int mirror_num)
2252 struct btrfs_device *dev;
2255 struct btrfs_bio *bbio = NULL;
2258 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2259 BUG_ON(!mirror_num);
2261 bio = btrfs_io_bio_alloc(1);
2262 bio->bi_iter.bi_size = 0;
2263 map_length = length;
2266 * Avoid races with device replace and make sure our bbio has devices
2267 * associated to its stripes that don't go away while we are doing the
2268 * read repair operation.
2270 btrfs_bio_counter_inc_blocked(fs_info);
2271 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2273 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2274 * to update all raid stripes, but here we just want to correct
2275 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2276 * stripe's dev and sector.
2278 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2279 &map_length, &bbio, 0);
2281 btrfs_bio_counter_dec(fs_info);
2285 ASSERT(bbio->mirror_num == 1);
2287 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2288 &map_length, &bbio, mirror_num);
2290 btrfs_bio_counter_dec(fs_info);
2294 BUG_ON(mirror_num != bbio->mirror_num);
2297 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2298 bio->bi_iter.bi_sector = sector;
2299 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2300 btrfs_put_bbio(bbio);
2301 if (!dev || !dev->bdev ||
2302 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2303 btrfs_bio_counter_dec(fs_info);
2307 bio_set_dev(bio, dev->bdev);
2308 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2309 bio_add_page(bio, page, length, pg_offset);
2311 if (btrfsic_submit_bio_wait(bio)) {
2312 /* try to remap that extent elsewhere? */
2313 btrfs_bio_counter_dec(fs_info);
2315 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2319 btrfs_info_rl_in_rcu(fs_info,
2320 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2322 rcu_str_deref(dev->name), sector);
2323 btrfs_bio_counter_dec(fs_info);
2328 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2330 struct btrfs_fs_info *fs_info = eb->fs_info;
2331 u64 start = eb->start;
2332 int i, num_pages = num_extent_pages(eb);
2335 if (sb_rdonly(fs_info->sb))
2338 for (i = 0; i < num_pages; i++) {
2339 struct page *p = eb->pages[i];
2341 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2342 start - page_offset(p), mirror_num);
2352 * each time an IO finishes, we do a fast check in the IO failure tree
2353 * to see if we need to process or clean up an io_failure_record
2355 int clean_io_failure(struct btrfs_fs_info *fs_info,
2356 struct extent_io_tree *failure_tree,
2357 struct extent_io_tree *io_tree, u64 start,
2358 struct page *page, u64 ino, unsigned int pg_offset)
2361 struct io_failure_record *failrec;
2362 struct extent_state *state;
2367 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2372 failrec = get_state_failrec(failure_tree, start);
2373 if (IS_ERR(failrec))
2376 BUG_ON(!failrec->this_mirror);
2378 if (failrec->in_validation) {
2379 /* there was no real error, just free the record */
2380 btrfs_debug(fs_info,
2381 "clean_io_failure: freeing dummy error at %llu",
2385 if (sb_rdonly(fs_info->sb))
2388 spin_lock(&io_tree->lock);
2389 state = find_first_extent_bit_state(io_tree,
2392 spin_unlock(&io_tree->lock);
2394 if (state && state->start <= failrec->start &&
2395 state->end >= failrec->start + failrec->len - 1) {
2396 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2398 if (num_copies > 1) {
2399 repair_io_failure(fs_info, ino, start, failrec->len,
2400 failrec->logical, page, pg_offset,
2401 failrec->failed_mirror);
2406 free_io_failure(failure_tree, io_tree, failrec);
2412 * Can be called when
2413 * - hold extent lock
2414 * - under ordered extent
2415 * - the inode is freeing
2417 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2419 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2420 struct io_failure_record *failrec;
2421 struct extent_state *state, *next;
2423 if (RB_EMPTY_ROOT(&failure_tree->state))
2426 spin_lock(&failure_tree->lock);
2427 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2429 if (state->start > end)
2432 ASSERT(state->end <= end);
2434 next = next_state(state);
2436 failrec = state->failrec;
2437 free_extent_state(state);
2442 spin_unlock(&failure_tree->lock);
2445 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2448 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2449 struct io_failure_record *failrec;
2450 struct extent_map *em;
2451 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2452 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2453 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2457 failrec = get_state_failrec(failure_tree, start);
2458 if (!IS_ERR(failrec)) {
2459 btrfs_debug(fs_info,
2460 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2461 failrec->logical, failrec->start, failrec->len,
2462 failrec->in_validation);
2464 * when data can be on disk more than twice, add to failrec here
2465 * (e.g. with a list for failed_mirror) to make
2466 * clean_io_failure() clean all those errors at once.
2472 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2474 return ERR_PTR(-ENOMEM);
2476 failrec->start = start;
2477 failrec->len = end - start + 1;
2478 failrec->this_mirror = 0;
2479 failrec->bio_flags = 0;
2480 failrec->in_validation = 0;
2482 read_lock(&em_tree->lock);
2483 em = lookup_extent_mapping(em_tree, start, failrec->len);
2485 read_unlock(&em_tree->lock);
2487 return ERR_PTR(-EIO);
2490 if (em->start > start || em->start + em->len <= start) {
2491 free_extent_map(em);
2494 read_unlock(&em_tree->lock);
2497 return ERR_PTR(-EIO);
2500 logical = start - em->start;
2501 logical = em->block_start + logical;
2502 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2503 logical = em->block_start;
2504 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2505 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2508 btrfs_debug(fs_info,
2509 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2510 logical, start, failrec->len);
2512 failrec->logical = logical;
2513 free_extent_map(em);
2515 /* Set the bits in the private failure tree */
2516 ret = set_extent_bits(failure_tree, start, end,
2517 EXTENT_LOCKED | EXTENT_DIRTY);
2519 ret = set_state_failrec(failure_tree, start, failrec);
2520 /* Set the bits in the inode's tree */
2521 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2522 } else if (ret < 0) {
2524 return ERR_PTR(ret);
2530 static bool btrfs_check_repairable(struct inode *inode, bool needs_validation,
2531 struct io_failure_record *failrec,
2534 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2537 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2538 if (num_copies == 1) {
2540 * we only have a single copy of the data, so don't bother with
2541 * all the retry and error correction code that follows. no
2542 * matter what the error is, it is very likely to persist.
2544 btrfs_debug(fs_info,
2545 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2546 num_copies, failrec->this_mirror, failed_mirror);
2551 * there are two premises:
2552 * a) deliver good data to the caller
2553 * b) correct the bad sectors on disk
2555 if (needs_validation) {
2557 * to fulfill b), we need to know the exact failing sectors, as
2558 * we don't want to rewrite any more than the failed ones. thus,
2559 * we need separate read requests for the failed bio
2561 * if the following BUG_ON triggers, our validation request got
2562 * merged. we need separate requests for our algorithm to work.
2564 BUG_ON(failrec->in_validation);
2565 failrec->in_validation = 1;
2566 failrec->this_mirror = failed_mirror;
2569 * we're ready to fulfill a) and b) alongside. get a good copy
2570 * of the failed sector and if we succeed, we have setup
2571 * everything for repair_io_failure to do the rest for us.
2573 if (failrec->in_validation) {
2574 BUG_ON(failrec->this_mirror != failed_mirror);
2575 failrec->in_validation = 0;
2576 failrec->this_mirror = 0;
2578 failrec->failed_mirror = failed_mirror;
2579 failrec->this_mirror++;
2580 if (failrec->this_mirror == failed_mirror)
2581 failrec->this_mirror++;
2584 if (failrec->this_mirror > num_copies) {
2585 btrfs_debug(fs_info,
2586 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2587 num_copies, failrec->this_mirror, failed_mirror);
2594 static bool btrfs_io_needs_validation(struct inode *inode, struct bio *bio)
2597 const u32 blocksize = inode->i_sb->s_blocksize;
2600 * If bi_status is BLK_STS_OK, then this was a checksum error, not an
2601 * I/O error. In this case, we already know exactly which sector was
2602 * bad, so we don't need to validate.
2604 if (bio->bi_status == BLK_STS_OK)
2608 * We need to validate each sector individually if the failed I/O was
2609 * for multiple sectors.
2611 * There are a few possible bios that can end up here:
2612 * 1. A buffered read bio, which is not cloned.
2613 * 2. A direct I/O read bio, which is cloned.
2614 * 3. A (buffered or direct) repair bio, which is not cloned.
2616 * For cloned bios (case 2), we can get the size from
2617 * btrfs_io_bio->iter; for non-cloned bios (cases 1 and 3), we can get
2618 * it from the bvecs.
2620 if (bio_flagged(bio, BIO_CLONED)) {
2621 if (btrfs_io_bio(bio)->iter.bi_size > blocksize)
2624 struct bio_vec *bvec;
2627 bio_for_each_bvec_all(bvec, bio, i) {
2628 len += bvec->bv_len;
2629 if (len > blocksize)
2636 blk_status_t btrfs_submit_read_repair(struct inode *inode,
2637 struct bio *failed_bio, u32 bio_offset,
2638 struct page *page, unsigned int pgoff,
2639 u64 start, u64 end, int failed_mirror,
2640 submit_bio_hook_t *submit_bio_hook)
2642 struct io_failure_record *failrec;
2643 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2644 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2645 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2646 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2647 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2648 bool need_validation;
2649 struct bio *repair_bio;
2650 struct btrfs_io_bio *repair_io_bio;
2651 blk_status_t status;
2653 btrfs_debug(fs_info,
2654 "repair read error: read error at %llu", start);
2656 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2658 failrec = btrfs_get_io_failure_record(inode, start, end);
2659 if (IS_ERR(failrec))
2660 return errno_to_blk_status(PTR_ERR(failrec));
2662 need_validation = btrfs_io_needs_validation(inode, failed_bio);
2664 if (!btrfs_check_repairable(inode, need_validation, failrec,
2666 free_io_failure(failure_tree, tree, failrec);
2667 return BLK_STS_IOERR;
2670 repair_bio = btrfs_io_bio_alloc(1);
2671 repair_io_bio = btrfs_io_bio(repair_bio);
2672 repair_bio->bi_opf = REQ_OP_READ;
2673 if (need_validation)
2674 repair_bio->bi_opf |= REQ_FAILFAST_DEV;
2675 repair_bio->bi_end_io = failed_bio->bi_end_io;
2676 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2677 repair_bio->bi_private = failed_bio->bi_private;
2679 if (failed_io_bio->csum) {
2680 const u32 csum_size = fs_info->csum_size;
2682 repair_io_bio->csum = repair_io_bio->csum_inline;
2683 memcpy(repair_io_bio->csum,
2684 failed_io_bio->csum + csum_size * icsum, csum_size);
2687 bio_add_page(repair_bio, page, failrec->len, pgoff);
2688 repair_io_bio->logical = failrec->start;
2689 repair_io_bio->iter = repair_bio->bi_iter;
2691 btrfs_debug(btrfs_sb(inode->i_sb),
2692 "repair read error: submitting new read to mirror %d, in_validation=%d",
2693 failrec->this_mirror, failrec->in_validation);
2695 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2696 failrec->bio_flags);
2698 free_io_failure(failure_tree, tree, failrec);
2699 bio_put(repair_bio);
2704 /* lots and lots of room for performance fixes in the end_bio funcs */
2706 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2708 int uptodate = (err == 0);
2711 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2714 ClearPageUptodate(page);
2716 ret = err < 0 ? err : -EIO;
2717 mapping_set_error(page->mapping, ret);
2722 * after a writepage IO is done, we need to:
2723 * clear the uptodate bits on error
2724 * clear the writeback bits in the extent tree for this IO
2725 * end_page_writeback if the page has no more pending IO
2727 * Scheduling is not allowed, so the extent state tree is expected
2728 * to have one and only one object corresponding to this IO.
2730 static void end_bio_extent_writepage(struct bio *bio)
2732 int error = blk_status_to_errno(bio->bi_status);
2733 struct bio_vec *bvec;
2736 struct bvec_iter_all iter_all;
2738 ASSERT(!bio_flagged(bio, BIO_CLONED));
2739 bio_for_each_segment_all(bvec, bio, iter_all) {
2740 struct page *page = bvec->bv_page;
2741 struct inode *inode = page->mapping->host;
2742 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2744 /* We always issue full-page reads, but if some block
2745 * in a page fails to read, blk_update_request() will
2746 * advance bv_offset and adjust bv_len to compensate.
2747 * Print a warning for nonzero offsets, and an error
2748 * if they don't add up to a full page. */
2749 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2750 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2752 "partial page write in btrfs with offset %u and length %u",
2753 bvec->bv_offset, bvec->bv_len);
2756 "incomplete page write in btrfs with offset %u and length %u",
2757 bvec->bv_offset, bvec->bv_len);
2760 start = page_offset(page);
2761 end = start + bvec->bv_offset + bvec->bv_len - 1;
2763 end_extent_writepage(page, error, start, end);
2764 end_page_writeback(page);
2771 * Record previously processed extent range
2773 * For endio_readpage_release_extent() to handle a full extent range, reducing
2774 * the extent io operations.
2776 struct processed_extent {
2777 struct btrfs_inode *inode;
2778 /* Start of the range in @inode */
2780 /* End of the range in @inode */
2786 * Try to release processed extent range
2788 * May not release the extent range right now if the current range is
2789 * contiguous to processed extent.
2791 * Will release processed extent when any of @inode, @uptodate, the range is
2792 * no longer contiguous to the processed range.
2794 * Passing @inode == NULL will force processed extent to be released.
2796 static void endio_readpage_release_extent(struct processed_extent *processed,
2797 struct btrfs_inode *inode, u64 start, u64 end,
2800 struct extent_state *cached = NULL;
2801 struct extent_io_tree *tree;
2803 /* The first extent, initialize @processed */
2804 if (!processed->inode)
2808 * Contiguous to processed extent, just uptodate the end.
2810 * Several things to notice:
2812 * - bio can be merged as long as on-disk bytenr is contiguous
2813 * This means we can have page belonging to other inodes, thus need to
2814 * check if the inode still matches.
2815 * - bvec can contain range beyond current page for multi-page bvec
2816 * Thus we need to do processed->end + 1 >= start check
2818 if (processed->inode == inode && processed->uptodate == uptodate &&
2819 processed->end + 1 >= start && end >= processed->end) {
2820 processed->end = end;
2824 tree = &processed->inode->io_tree;
2826 * Now we don't have range contiguous to the processed range, release
2827 * the processed range now.
2829 if (processed->uptodate && tree->track_uptodate)
2830 set_extent_uptodate(tree, processed->start, processed->end,
2831 &cached, GFP_ATOMIC);
2832 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2836 /* Update processed to current range */
2837 processed->inode = inode;
2838 processed->start = start;
2839 processed->end = end;
2840 processed->uptodate = uptodate;
2843 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2845 ASSERT(PageLocked(page));
2846 if (fs_info->sectorsize == PAGE_SIZE)
2849 ASSERT(PagePrivate(page));
2850 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2853 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2855 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2857 ASSERT(page_offset(page) <= start &&
2858 start + len <= page_offset(page) + PAGE_SIZE);
2861 btrfs_page_set_uptodate(fs_info, page, start, len);
2863 btrfs_page_clear_uptodate(fs_info, page, start, len);
2864 btrfs_page_set_error(fs_info, page, start, len);
2867 if (fs_info->sectorsize == PAGE_SIZE)
2869 else if (is_data_inode(page->mapping->host))
2871 * For subpage data, unlock the page if we're the last reader.
2872 * For subpage metadata, page lock is not utilized for read.
2874 btrfs_subpage_end_reader(fs_info, page, start, len);
2878 * after a readpage IO is done, we need to:
2879 * clear the uptodate bits on error
2880 * set the uptodate bits if things worked
2881 * set the page up to date if all extents in the tree are uptodate
2882 * clear the lock bit in the extent tree
2883 * unlock the page if there are no other extents locked for it
2885 * Scheduling is not allowed, so the extent state tree is expected
2886 * to have one and only one object corresponding to this IO.
2888 static void end_bio_extent_readpage(struct bio *bio)
2890 struct bio_vec *bvec;
2891 int uptodate = !bio->bi_status;
2892 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2893 struct extent_io_tree *tree, *failure_tree;
2894 struct processed_extent processed = { 0 };
2896 * The offset to the beginning of a bio, since one bio can never be
2897 * larger than UINT_MAX, u32 here is enough.
2902 struct bvec_iter_all iter_all;
2904 ASSERT(!bio_flagged(bio, BIO_CLONED));
2905 bio_for_each_segment_all(bvec, bio, iter_all) {
2906 struct page *page = bvec->bv_page;
2907 struct inode *inode = page->mapping->host;
2908 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2909 const u32 sectorsize = fs_info->sectorsize;
2914 btrfs_debug(fs_info,
2915 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2916 bio->bi_iter.bi_sector, bio->bi_status,
2917 io_bio->mirror_num);
2918 tree = &BTRFS_I(inode)->io_tree;
2919 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2922 * We always issue full-sector reads, but if some block in a
2923 * page fails to read, blk_update_request() will advance
2924 * bv_offset and adjust bv_len to compensate. Print a warning
2925 * for unaligned offsets, and an error if they don't add up to
2928 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2930 "partial page read in btrfs with offset %u and length %u",
2931 bvec->bv_offset, bvec->bv_len);
2932 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
2935 "incomplete page read with offset %u and length %u",
2936 bvec->bv_offset, bvec->bv_len);
2938 start = page_offset(page) + bvec->bv_offset;
2939 end = start + bvec->bv_len - 1;
2942 mirror = io_bio->mirror_num;
2943 if (likely(uptodate)) {
2944 if (is_data_inode(inode))
2945 ret = btrfs_verify_data_csum(io_bio,
2946 bio_offset, page, start, end,
2949 ret = btrfs_validate_metadata_buffer(io_bio,
2950 page, start, end, mirror);
2954 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2955 failure_tree, tree, start,
2957 btrfs_ino(BTRFS_I(inode)), 0);
2960 if (likely(uptodate))
2963 if (is_data_inode(inode)) {
2966 * The generic bio_readpage_error handles errors the
2967 * following way: If possible, new read requests are
2968 * created and submitted and will end up in
2969 * end_bio_extent_readpage as well (if we're lucky,
2970 * not in the !uptodate case). In that case it returns
2971 * 0 and we just go on with the next page in our bio.
2972 * If it can't handle the error it will return -EIO and
2973 * we remain responsible for that page.
2975 if (!btrfs_submit_read_repair(inode, bio, bio_offset,
2977 start - page_offset(page),
2979 btrfs_submit_data_bio)) {
2980 uptodate = !bio->bi_status;
2981 ASSERT(bio_offset + len > bio_offset);
2986 struct extent_buffer *eb;
2988 eb = (struct extent_buffer *)page->private;
2989 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2990 eb->read_mirror = mirror;
2991 atomic_dec(&eb->io_pages);
2992 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2994 btree_readahead_hook(eb, -EIO);
2997 if (likely(uptodate)) {
2998 loff_t i_size = i_size_read(inode);
2999 pgoff_t end_index = i_size >> PAGE_SHIFT;
3002 /* Zero out the end if this page straddles i_size */
3003 off = offset_in_page(i_size);
3004 if (page->index == end_index && off)
3005 zero_user_segment(page, off, PAGE_SIZE);
3007 ASSERT(bio_offset + len > bio_offset);
3010 /* Update page status and unlock */
3011 end_page_read(page, uptodate, start, len);
3012 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3013 start, end, uptodate);
3015 /* Release the last extent */
3016 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3017 btrfs_io_bio_free_csum(io_bio);
3022 * Initialize the members up to but not including 'bio'. Use after allocating a
3023 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3024 * 'bio' because use of __GFP_ZERO is not supported.
3026 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3028 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3032 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3033 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3034 * for the appropriate container_of magic
3036 struct bio *btrfs_bio_alloc(u64 first_byte)
3040 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
3041 bio->bi_iter.bi_sector = first_byte >> 9;
3042 btrfs_io_bio_init(btrfs_io_bio(bio));
3046 struct bio *btrfs_bio_clone(struct bio *bio)
3048 struct btrfs_io_bio *btrfs_bio;
3051 /* Bio allocation backed by a bioset does not fail */
3052 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3053 btrfs_bio = btrfs_io_bio(new);
3054 btrfs_io_bio_init(btrfs_bio);
3055 btrfs_bio->iter = bio->bi_iter;
3059 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3063 /* Bio allocation backed by a bioset does not fail */
3064 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3065 btrfs_io_bio_init(btrfs_io_bio(bio));
3069 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
3072 struct btrfs_io_bio *btrfs_bio;
3074 /* this will never fail when it's backed by a bioset */
3075 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3078 btrfs_bio = btrfs_io_bio(bio);
3079 btrfs_io_bio_init(btrfs_bio);
3081 bio_trim(bio, offset >> 9, size >> 9);
3082 btrfs_bio->iter = bio->bi_iter;
3087 * @opf: bio REQ_OP_* and REQ_* flags as one value
3088 * @wbc: optional writeback control for io accounting
3089 * @page: page to add to the bio
3090 * @disk_bytenr: logical bytenr where the write will be
3091 * @size: portion of page that we want to write to
3092 * @pg_offset: offset of the new bio or to check whether we are adding
3093 * a contiguous page to the previous one
3094 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3095 * @end_io_func: end_io callback for new bio
3096 * @mirror_num: desired mirror to read/write
3097 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3098 * @bio_flags: flags of the current bio to see if we can merge them
3100 static int submit_extent_page(unsigned int opf,
3101 struct writeback_control *wbc,
3102 struct page *page, u64 disk_bytenr,
3103 size_t size, unsigned long pg_offset,
3104 struct bio **bio_ret,
3105 bio_end_io_t end_io_func,
3107 unsigned long prev_bio_flags,
3108 unsigned long bio_flags,
3109 bool force_bio_submit)
3113 size_t io_size = min_t(size_t, size, PAGE_SIZE);
3114 sector_t sector = disk_bytenr >> 9;
3115 struct extent_io_tree *tree = &BTRFS_I(page->mapping->host)->io_tree;
3121 bool can_merge = true;
3124 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
3125 contig = bio->bi_iter.bi_sector == sector;
3127 contig = bio_end_sector(bio) == sector;
3129 if (btrfs_bio_fits_in_stripe(page, io_size, bio, bio_flags))
3132 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
3134 bio_add_page(bio, page, io_size, pg_offset) < io_size) {
3135 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
3143 wbc_account_cgroup_owner(wbc, page, io_size);
3148 bio = btrfs_bio_alloc(disk_bytenr);
3149 bio_add_page(bio, page, io_size, pg_offset);
3150 bio->bi_end_io = end_io_func;
3151 bio->bi_private = tree;
3152 bio->bi_write_hint = page->mapping->host->i_write_hint;
3155 struct block_device *bdev;
3157 bdev = BTRFS_I(page->mapping->host)->root->fs_info->fs_devices->latest_bdev;
3158 bio_set_dev(bio, bdev);
3159 wbc_init_bio(wbc, bio);
3160 wbc_account_cgroup_owner(wbc, page, io_size);
3168 static int attach_extent_buffer_page(struct extent_buffer *eb,
3170 struct btrfs_subpage *prealloc)
3172 struct btrfs_fs_info *fs_info = eb->fs_info;
3176 * If the page is mapped to btree inode, we should hold the private
3177 * lock to prevent race.
3178 * For cloned or dummy extent buffers, their pages are not mapped and
3179 * will not race with any other ebs.
3182 lockdep_assert_held(&page->mapping->private_lock);
3184 if (fs_info->sectorsize == PAGE_SIZE) {
3185 if (!PagePrivate(page))
3186 attach_page_private(page, eb);
3188 WARN_ON(page->private != (unsigned long)eb);
3192 /* Already mapped, just free prealloc */
3193 if (PagePrivate(page)) {
3194 btrfs_free_subpage(prealloc);
3199 /* Has preallocated memory for subpage */
3200 attach_page_private(page, prealloc);
3202 /* Do new allocation to attach subpage */
3203 ret = btrfs_attach_subpage(fs_info, page,
3204 BTRFS_SUBPAGE_METADATA);
3208 int set_page_extent_mapped(struct page *page)
3210 struct btrfs_fs_info *fs_info;
3212 ASSERT(page->mapping);
3214 if (PagePrivate(page))
3217 fs_info = btrfs_sb(page->mapping->host->i_sb);
3219 if (fs_info->sectorsize < PAGE_SIZE)
3220 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3222 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3226 void clear_page_extent_mapped(struct page *page)
3228 struct btrfs_fs_info *fs_info;
3230 ASSERT(page->mapping);
3232 if (!PagePrivate(page))
3235 fs_info = btrfs_sb(page->mapping->host->i_sb);
3236 if (fs_info->sectorsize < PAGE_SIZE)
3237 return btrfs_detach_subpage(fs_info, page);
3239 detach_page_private(page);
3242 static struct extent_map *
3243 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3244 u64 start, u64 len, struct extent_map **em_cached)
3246 struct extent_map *em;
3248 if (em_cached && *em_cached) {
3250 if (extent_map_in_tree(em) && start >= em->start &&
3251 start < extent_map_end(em)) {
3252 refcount_inc(&em->refs);
3256 free_extent_map(em);
3260 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3261 if (em_cached && !IS_ERR_OR_NULL(em)) {
3263 refcount_inc(&em->refs);
3269 * basic readpage implementation. Locked extent state structs are inserted
3270 * into the tree that are removed when the IO is done (by the end_io
3272 * XXX JDM: This needs looking at to ensure proper page locking
3273 * return 0 on success, otherwise return error
3275 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3276 struct bio **bio, unsigned long *bio_flags,
3277 unsigned int read_flags, u64 *prev_em_start)
3279 struct inode *inode = page->mapping->host;
3280 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3281 u64 start = page_offset(page);
3282 const u64 end = start + PAGE_SIZE - 1;
3285 u64 last_byte = i_size_read(inode);
3288 struct extent_map *em;
3291 size_t pg_offset = 0;
3293 size_t blocksize = inode->i_sb->s_blocksize;
3294 unsigned long this_bio_flag = 0;
3295 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3297 ret = set_page_extent_mapped(page);
3299 unlock_extent(tree, start, end);
3300 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3305 if (!PageUptodate(page)) {
3306 if (cleancache_get_page(page) == 0) {
3307 BUG_ON(blocksize != PAGE_SIZE);
3308 unlock_extent(tree, start, end);
3314 if (page->index == last_byte >> PAGE_SHIFT) {
3316 size_t zero_offset = offset_in_page(last_byte);
3319 iosize = PAGE_SIZE - zero_offset;
3320 userpage = kmap_atomic(page);
3321 memset(userpage + zero_offset, 0, iosize);
3322 flush_dcache_page(page);
3323 kunmap_atomic(userpage);
3326 begin_page_read(fs_info, page);
3327 while (cur <= end) {
3328 bool force_bio_submit = false;
3331 if (cur >= last_byte) {
3333 struct extent_state *cached = NULL;
3335 iosize = PAGE_SIZE - pg_offset;
3336 userpage = kmap_atomic(page);
3337 memset(userpage + pg_offset, 0, iosize);
3338 flush_dcache_page(page);
3339 kunmap_atomic(userpage);
3340 set_extent_uptodate(tree, cur, cur + iosize - 1,
3342 unlock_extent_cached(tree, cur,
3343 cur + iosize - 1, &cached);
3344 end_page_read(page, true, cur, iosize);
3347 em = __get_extent_map(inode, page, pg_offset, cur,
3348 end - cur + 1, em_cached);
3349 if (IS_ERR_OR_NULL(em)) {
3350 unlock_extent(tree, cur, end);
3351 end_page_read(page, false, cur, end + 1 - cur);
3354 extent_offset = cur - em->start;
3355 BUG_ON(extent_map_end(em) <= cur);
3358 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3359 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3360 extent_set_compress_type(&this_bio_flag,
3364 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3365 cur_end = min(extent_map_end(em) - 1, end);
3366 iosize = ALIGN(iosize, blocksize);
3367 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3368 disk_bytenr = em->block_start;
3370 disk_bytenr = em->block_start + extent_offset;
3371 block_start = em->block_start;
3372 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3373 block_start = EXTENT_MAP_HOLE;
3376 * If we have a file range that points to a compressed extent
3377 * and it's followed by a consecutive file range that points
3378 * to the same compressed extent (possibly with a different
3379 * offset and/or length, so it either points to the whole extent
3380 * or only part of it), we must make sure we do not submit a
3381 * single bio to populate the pages for the 2 ranges because
3382 * this makes the compressed extent read zero out the pages
3383 * belonging to the 2nd range. Imagine the following scenario:
3386 * [0 - 8K] [8K - 24K]
3389 * points to extent X, points to extent X,
3390 * offset 4K, length of 8K offset 0, length 16K
3392 * [extent X, compressed length = 4K uncompressed length = 16K]
3394 * If the bio to read the compressed extent covers both ranges,
3395 * it will decompress extent X into the pages belonging to the
3396 * first range and then it will stop, zeroing out the remaining
3397 * pages that belong to the other range that points to extent X.
3398 * So here we make sure we submit 2 bios, one for the first
3399 * range and another one for the third range. Both will target
3400 * the same physical extent from disk, but we can't currently
3401 * make the compressed bio endio callback populate the pages
3402 * for both ranges because each compressed bio is tightly
3403 * coupled with a single extent map, and each range can have
3404 * an extent map with a different offset value relative to the
3405 * uncompressed data of our extent and different lengths. This
3406 * is a corner case so we prioritize correctness over
3407 * non-optimal behavior (submitting 2 bios for the same extent).
3409 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3410 prev_em_start && *prev_em_start != (u64)-1 &&
3411 *prev_em_start != em->start)
3412 force_bio_submit = true;
3415 *prev_em_start = em->start;
3417 free_extent_map(em);
3420 /* we've found a hole, just zero and go on */
3421 if (block_start == EXTENT_MAP_HOLE) {
3423 struct extent_state *cached = NULL;
3425 userpage = kmap_atomic(page);
3426 memset(userpage + pg_offset, 0, iosize);
3427 flush_dcache_page(page);
3428 kunmap_atomic(userpage);
3430 set_extent_uptodate(tree, cur, cur + iosize - 1,
3432 unlock_extent_cached(tree, cur,
3433 cur + iosize - 1, &cached);
3434 end_page_read(page, true, cur, iosize);
3436 pg_offset += iosize;
3439 /* the get_extent function already copied into the page */
3440 if (test_range_bit(tree, cur, cur_end,
3441 EXTENT_UPTODATE, 1, NULL)) {
3442 check_page_uptodate(tree, page);
3443 unlock_extent(tree, cur, cur + iosize - 1);
3444 end_page_read(page, true, cur, iosize);
3446 pg_offset += iosize;
3449 /* we have an inline extent but it didn't get marked up
3450 * to date. Error out
3452 if (block_start == EXTENT_MAP_INLINE) {
3453 unlock_extent(tree, cur, cur + iosize - 1);
3454 end_page_read(page, false, cur, iosize);
3456 pg_offset += iosize;
3460 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3461 page, disk_bytenr, iosize,
3463 end_bio_extent_readpage, 0,
3469 *bio_flags = this_bio_flag;
3471 unlock_extent(tree, cur, cur + iosize - 1);
3472 end_page_read(page, false, cur, iosize);
3476 pg_offset += iosize;
3482 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3484 struct extent_map **em_cached,
3486 unsigned long *bio_flags,
3489 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3492 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3494 for (index = 0; index < nr_pages; index++) {
3495 btrfs_do_readpage(pages[index], em_cached, bio, bio_flags,
3496 REQ_RAHEAD, prev_em_start);
3497 put_page(pages[index]);
3501 static void update_nr_written(struct writeback_control *wbc,
3502 unsigned long nr_written)
3504 wbc->nr_to_write -= nr_written;
3508 * helper for __extent_writepage, doing all of the delayed allocation setup.
3510 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3511 * to write the page (copy into inline extent). In this case the IO has
3512 * been started and the page is already unlocked.
3514 * This returns 0 if all went well (page still locked)
3515 * This returns < 0 if there were errors (page still locked)
3517 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3518 struct page *page, struct writeback_control *wbc,
3519 u64 delalloc_start, unsigned long *nr_written)
3521 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3523 u64 delalloc_to_write = 0;
3524 u64 delalloc_end = 0;
3526 int page_started = 0;
3529 while (delalloc_end < page_end) {
3530 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3534 delalloc_start = delalloc_end + 1;
3537 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3538 delalloc_end, &page_started, nr_written, wbc);
3542 * btrfs_run_delalloc_range should return < 0 for error
3543 * but just in case, we use > 0 here meaning the IO is
3544 * started, so we don't want to return > 0 unless
3545 * things are going well.
3547 return ret < 0 ? ret : -EIO;
3550 * delalloc_end is already one less than the total length, so
3551 * we don't subtract one from PAGE_SIZE
3553 delalloc_to_write += (delalloc_end - delalloc_start +
3554 PAGE_SIZE) >> PAGE_SHIFT;
3555 delalloc_start = delalloc_end + 1;
3557 if (wbc->nr_to_write < delalloc_to_write) {
3560 if (delalloc_to_write < thresh * 2)
3561 thresh = delalloc_to_write;
3562 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3566 /* did the fill delalloc function already unlock and start
3571 * we've unlocked the page, so we can't update
3572 * the mapping's writeback index, just update
3575 wbc->nr_to_write -= *nr_written;
3583 * helper for __extent_writepage. This calls the writepage start hooks,
3584 * and does the loop to map the page into extents and bios.
3586 * We return 1 if the IO is started and the page is unlocked,
3587 * 0 if all went well (page still locked)
3588 * < 0 if there were errors (page still locked)
3590 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3592 struct writeback_control *wbc,
3593 struct extent_page_data *epd,
3595 unsigned long nr_written,
3598 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3599 struct extent_io_tree *tree = &inode->io_tree;
3600 u64 start = page_offset(page);
3601 u64 end = start + PAGE_SIZE - 1;
3605 struct extent_map *em;
3608 const unsigned int write_flags = wbc_to_write_flags(wbc);
3611 ret = btrfs_writepage_cow_fixup(page, start, end);
3613 /* Fixup worker will requeue */
3614 redirty_page_for_writepage(wbc, page);
3615 update_nr_written(wbc, nr_written);
3621 * we don't want to touch the inode after unlocking the page,
3622 * so we update the mapping writeback index now
3624 update_nr_written(wbc, nr_written + 1);
3626 while (cur <= end) {
3631 if (cur >= i_size) {
3632 btrfs_writepage_endio_finish_ordered(page, cur, end, 1);
3635 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3636 if (IS_ERR_OR_NULL(em)) {
3638 ret = PTR_ERR_OR_ZERO(em);
3642 extent_offset = cur - em->start;
3643 em_end = extent_map_end(em);
3644 ASSERT(cur <= em_end);
3646 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3647 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3648 block_start = em->block_start;
3649 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3650 disk_bytenr = em->block_start + extent_offset;
3652 /* Note that em_end from extent_map_end() is exclusive */
3653 iosize = min(em_end, end + 1) - cur;
3654 free_extent_map(em);
3658 * compressed and inline extents are written through other
3661 if (compressed || block_start == EXTENT_MAP_HOLE ||
3662 block_start == EXTENT_MAP_INLINE) {
3666 btrfs_writepage_endio_finish_ordered(page, cur,
3667 cur + iosize - 1, 1);
3672 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3673 if (!PageWriteback(page)) {
3674 btrfs_err(inode->root->fs_info,
3675 "page %lu not writeback, cur %llu end %llu",
3676 page->index, cur, end);
3679 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
3680 page, disk_bytenr, iosize,
3681 cur - page_offset(page), &epd->bio,
3682 end_bio_extent_writepage,
3686 if (PageWriteback(page))
3687 end_page_writeback(page);
3698 * the writepage semantics are similar to regular writepage. extent
3699 * records are inserted to lock ranges in the tree, and as dirty areas
3700 * are found, they are marked writeback. Then the lock bits are removed
3701 * and the end_io handler clears the writeback ranges
3703 * Return 0 if everything goes well.
3704 * Return <0 for error.
3706 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3707 struct extent_page_data *epd)
3709 struct inode *inode = page->mapping->host;
3710 u64 start = page_offset(page);
3711 u64 page_end = start + PAGE_SIZE - 1;
3715 loff_t i_size = i_size_read(inode);
3716 unsigned long end_index = i_size >> PAGE_SHIFT;
3717 unsigned long nr_written = 0;
3719 trace___extent_writepage(page, inode, wbc);
3721 WARN_ON(!PageLocked(page));
3723 ClearPageError(page);
3725 pg_offset = offset_in_page(i_size);
3726 if (page->index > end_index ||
3727 (page->index == end_index && !pg_offset)) {
3728 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3733 if (page->index == end_index) {
3736 userpage = kmap_atomic(page);
3737 memset(userpage + pg_offset, 0,
3738 PAGE_SIZE - pg_offset);
3739 kunmap_atomic(userpage);
3740 flush_dcache_page(page);
3743 ret = set_page_extent_mapped(page);
3749 if (!epd->extent_locked) {
3750 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3758 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3765 /* make sure the mapping tag for page dirty gets cleared */
3766 set_page_writeback(page);
3767 end_page_writeback(page);
3769 if (PageError(page)) {
3770 ret = ret < 0 ? ret : -EIO;
3771 end_extent_writepage(page, ret, start, page_end);
3778 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3780 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3781 TASK_UNINTERRUPTIBLE);
3784 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3786 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3787 smp_mb__after_atomic();
3788 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3792 * Lock extent buffer status and pages for writeback.
3794 * May try to flush write bio if we can't get the lock.
3796 * Return 0 if the extent buffer doesn't need to be submitted.
3797 * (E.g. the extent buffer is not dirty)
3798 * Return >0 is the extent buffer is submitted to bio.
3799 * Return <0 if something went wrong, no page is locked.
3801 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3802 struct extent_page_data *epd)
3804 struct btrfs_fs_info *fs_info = eb->fs_info;
3805 int i, num_pages, failed_page_nr;
3809 if (!btrfs_try_tree_write_lock(eb)) {
3810 ret = flush_write_bio(epd);
3814 btrfs_tree_lock(eb);
3817 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3818 btrfs_tree_unlock(eb);
3822 ret = flush_write_bio(epd);
3828 wait_on_extent_buffer_writeback(eb);
3829 btrfs_tree_lock(eb);
3830 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3832 btrfs_tree_unlock(eb);
3837 * We need to do this to prevent races in people who check if the eb is
3838 * under IO since we can end up having no IO bits set for a short period
3841 spin_lock(&eb->refs_lock);
3842 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3843 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3844 spin_unlock(&eb->refs_lock);
3845 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3846 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3848 fs_info->dirty_metadata_batch);
3851 spin_unlock(&eb->refs_lock);
3854 btrfs_tree_unlock(eb);
3859 num_pages = num_extent_pages(eb);
3860 for (i = 0; i < num_pages; i++) {
3861 struct page *p = eb->pages[i];
3863 if (!trylock_page(p)) {
3867 err = flush_write_bio(epd);
3881 /* Unlock already locked pages */
3882 for (i = 0; i < failed_page_nr; i++)
3883 unlock_page(eb->pages[i]);
3885 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3886 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3887 * be made and undo everything done before.
3889 btrfs_tree_lock(eb);
3890 spin_lock(&eb->refs_lock);
3891 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3892 end_extent_buffer_writeback(eb);
3893 spin_unlock(&eb->refs_lock);
3894 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3895 fs_info->dirty_metadata_batch);
3896 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3897 btrfs_tree_unlock(eb);
3901 static void set_btree_ioerr(struct page *page)
3903 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3904 struct btrfs_fs_info *fs_info;
3907 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3911 * If we error out, we should add back the dirty_metadata_bytes
3912 * to make it consistent.
3914 fs_info = eb->fs_info;
3915 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3916 eb->len, fs_info->dirty_metadata_batch);
3919 * If writeback for a btree extent that doesn't belong to a log tree
3920 * failed, increment the counter transaction->eb_write_errors.
3921 * We do this because while the transaction is running and before it's
3922 * committing (when we call filemap_fdata[write|wait]_range against
3923 * the btree inode), we might have
3924 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3925 * returns an error or an error happens during writeback, when we're
3926 * committing the transaction we wouldn't know about it, since the pages
3927 * can be no longer dirty nor marked anymore for writeback (if a
3928 * subsequent modification to the extent buffer didn't happen before the
3929 * transaction commit), which makes filemap_fdata[write|wait]_range not
3930 * able to find the pages tagged with SetPageError at transaction
3931 * commit time. So if this happens we must abort the transaction,
3932 * otherwise we commit a super block with btree roots that point to
3933 * btree nodes/leafs whose content on disk is invalid - either garbage
3934 * or the content of some node/leaf from a past generation that got
3935 * cowed or deleted and is no longer valid.
3937 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3938 * not be enough - we need to distinguish between log tree extents vs
3939 * non-log tree extents, and the next filemap_fdatawait_range() call
3940 * will catch and clear such errors in the mapping - and that call might
3941 * be from a log sync and not from a transaction commit. Also, checking
3942 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3943 * not done and would not be reliable - the eb might have been released
3944 * from memory and reading it back again means that flag would not be
3945 * set (since it's a runtime flag, not persisted on disk).
3947 * Using the flags below in the btree inode also makes us achieve the
3948 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3949 * writeback for all dirty pages and before filemap_fdatawait_range()
3950 * is called, the writeback for all dirty pages had already finished
3951 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3952 * filemap_fdatawait_range() would return success, as it could not know
3953 * that writeback errors happened (the pages were no longer tagged for
3956 switch (eb->log_index) {
3958 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3961 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3964 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3967 BUG(); /* unexpected, logic error */
3971 static void end_bio_extent_buffer_writepage(struct bio *bio)
3973 struct bio_vec *bvec;
3974 struct extent_buffer *eb;
3976 struct bvec_iter_all iter_all;
3978 ASSERT(!bio_flagged(bio, BIO_CLONED));
3979 bio_for_each_segment_all(bvec, bio, iter_all) {
3980 struct page *page = bvec->bv_page;
3982 eb = (struct extent_buffer *)page->private;
3984 done = atomic_dec_and_test(&eb->io_pages);
3986 if (bio->bi_status ||
3987 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3988 ClearPageUptodate(page);
3989 set_btree_ioerr(page);
3992 end_page_writeback(page);
3997 end_extent_buffer_writeback(eb);
4003 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4004 struct writeback_control *wbc,
4005 struct extent_page_data *epd)
4007 u64 disk_bytenr = eb->start;
4010 unsigned long start, end;
4011 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4014 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4015 num_pages = num_extent_pages(eb);
4016 atomic_set(&eb->io_pages, num_pages);
4018 /* set btree blocks beyond nritems with 0 to avoid stale content. */
4019 nritems = btrfs_header_nritems(eb);
4020 if (btrfs_header_level(eb) > 0) {
4021 end = btrfs_node_key_ptr_offset(nritems);
4023 memzero_extent_buffer(eb, end, eb->len - end);
4027 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4029 start = btrfs_item_nr_offset(nritems);
4030 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4031 memzero_extent_buffer(eb, start, end - start);
4034 for (i = 0; i < num_pages; i++) {
4035 struct page *p = eb->pages[i];
4037 clear_page_dirty_for_io(p);
4038 set_page_writeback(p);
4039 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4040 p, disk_bytenr, PAGE_SIZE, 0,
4042 end_bio_extent_buffer_writepage,
4046 if (PageWriteback(p))
4047 end_page_writeback(p);
4048 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4049 end_extent_buffer_writeback(eb);
4053 disk_bytenr += PAGE_SIZE;
4054 update_nr_written(wbc, 1);
4058 if (unlikely(ret)) {
4059 for (; i < num_pages; i++) {
4060 struct page *p = eb->pages[i];
4061 clear_page_dirty_for_io(p);
4070 * Submit all page(s) of one extent buffer.
4072 * @page: the page of one extent buffer
4073 * @eb_context: to determine if we need to submit this page, if current page
4074 * belongs to this eb, we don't need to submit
4076 * The caller should pass each page in their bytenr order, and here we use
4077 * @eb_context to determine if we have submitted pages of one extent buffer.
4079 * If we have, we just skip until we hit a new page that doesn't belong to
4080 * current @eb_context.
4082 * If not, we submit all the page(s) of the extent buffer.
4084 * Return >0 if we have submitted the extent buffer successfully.
4085 * Return 0 if we don't need to submit the page, as it's already submitted by
4087 * Return <0 for fatal error.
4089 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4090 struct extent_page_data *epd,
4091 struct extent_buffer **eb_context)
4093 struct address_space *mapping = page->mapping;
4094 struct extent_buffer *eb;
4097 if (!PagePrivate(page))
4100 spin_lock(&mapping->private_lock);
4101 if (!PagePrivate(page)) {
4102 spin_unlock(&mapping->private_lock);
4106 eb = (struct extent_buffer *)page->private;
4109 * Shouldn't happen and normally this would be a BUG_ON but no point
4110 * crashing the machine for something we can survive anyway.
4113 spin_unlock(&mapping->private_lock);
4117 if (eb == *eb_context) {
4118 spin_unlock(&mapping->private_lock);
4121 ret = atomic_inc_not_zero(&eb->refs);
4122 spin_unlock(&mapping->private_lock);
4128 ret = lock_extent_buffer_for_io(eb, epd);
4130 free_extent_buffer(eb);
4133 ret = write_one_eb(eb, wbc, epd);
4134 free_extent_buffer(eb);
4140 int btree_write_cache_pages(struct address_space *mapping,
4141 struct writeback_control *wbc)
4143 struct extent_buffer *eb_context = NULL;
4144 struct extent_page_data epd = {
4147 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4149 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4152 int nr_to_write_done = 0;
4153 struct pagevec pvec;
4156 pgoff_t end; /* Inclusive */
4160 pagevec_init(&pvec);
4161 if (wbc->range_cyclic) {
4162 index = mapping->writeback_index; /* Start from prev offset */
4165 * Start from the beginning does not need to cycle over the
4166 * range, mark it as scanned.
4168 scanned = (index == 0);
4170 index = wbc->range_start >> PAGE_SHIFT;
4171 end = wbc->range_end >> PAGE_SHIFT;
4174 if (wbc->sync_mode == WB_SYNC_ALL)
4175 tag = PAGECACHE_TAG_TOWRITE;
4177 tag = PAGECACHE_TAG_DIRTY;
4179 if (wbc->sync_mode == WB_SYNC_ALL)
4180 tag_pages_for_writeback(mapping, index, end);
4181 while (!done && !nr_to_write_done && (index <= end) &&
4182 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4186 for (i = 0; i < nr_pages; i++) {
4187 struct page *page = pvec.pages[i];
4189 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4198 * the filesystem may choose to bump up nr_to_write.
4199 * We have to make sure to honor the new nr_to_write
4202 nr_to_write_done = wbc->nr_to_write <= 0;
4204 pagevec_release(&pvec);
4207 if (!scanned && !done) {
4209 * We hit the last page and there is more work to be done: wrap
4210 * back to the start of the file
4217 end_write_bio(&epd, ret);
4221 * If something went wrong, don't allow any metadata write bio to be
4224 * This would prevent use-after-free if we had dirty pages not
4225 * cleaned up, which can still happen by fuzzed images.
4228 * Allowing existing tree block to be allocated for other trees.
4230 * - Log tree operations
4231 * Exiting tree blocks get allocated to log tree, bumps its
4232 * generation, then get cleaned in tree re-balance.
4233 * Such tree block will not be written back, since it's clean,
4234 * thus no WRITTEN flag set.
4235 * And after log writes back, this tree block is not traced by
4236 * any dirty extent_io_tree.
4238 * - Offending tree block gets re-dirtied from its original owner
4239 * Since it has bumped generation, no WRITTEN flag, it can be
4240 * reused without COWing. This tree block will not be traced
4241 * by btrfs_transaction::dirty_pages.
4243 * Now such dirty tree block will not be cleaned by any dirty
4244 * extent io tree. Thus we don't want to submit such wild eb
4245 * if the fs already has error.
4247 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4248 ret = flush_write_bio(&epd);
4251 end_write_bio(&epd, ret);
4257 * Walk the list of dirty pages of the given address space and write all of them.
4259 * @mapping: address space structure to write
4260 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4261 * @epd: holds context for the write, namely the bio
4263 * If a page is already under I/O, write_cache_pages() skips it, even
4264 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4265 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4266 * and msync() need to guarantee that all the data which was dirty at the time
4267 * the call was made get new I/O started against them. If wbc->sync_mode is
4268 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4269 * existing IO to complete.
4271 static int extent_write_cache_pages(struct address_space *mapping,
4272 struct writeback_control *wbc,
4273 struct extent_page_data *epd)
4275 struct inode *inode = mapping->host;
4278 int nr_to_write_done = 0;
4279 struct pagevec pvec;
4282 pgoff_t end; /* Inclusive */
4284 int range_whole = 0;
4289 * We have to hold onto the inode so that ordered extents can do their
4290 * work when the IO finishes. The alternative to this is failing to add
4291 * an ordered extent if the igrab() fails there and that is a huge pain
4292 * to deal with, so instead just hold onto the inode throughout the
4293 * writepages operation. If it fails here we are freeing up the inode
4294 * anyway and we'd rather not waste our time writing out stuff that is
4295 * going to be truncated anyway.
4300 pagevec_init(&pvec);
4301 if (wbc->range_cyclic) {
4302 index = mapping->writeback_index; /* Start from prev offset */
4305 * Start from the beginning does not need to cycle over the
4306 * range, mark it as scanned.
4308 scanned = (index == 0);
4310 index = wbc->range_start >> PAGE_SHIFT;
4311 end = wbc->range_end >> PAGE_SHIFT;
4312 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4318 * We do the tagged writepage as long as the snapshot flush bit is set
4319 * and we are the first one who do the filemap_flush() on this inode.
4321 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4322 * not race in and drop the bit.
4324 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4325 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4326 &BTRFS_I(inode)->runtime_flags))
4327 wbc->tagged_writepages = 1;
4329 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4330 tag = PAGECACHE_TAG_TOWRITE;
4332 tag = PAGECACHE_TAG_DIRTY;
4334 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4335 tag_pages_for_writeback(mapping, index, end);
4337 while (!done && !nr_to_write_done && (index <= end) &&
4338 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4339 &index, end, tag))) {
4342 for (i = 0; i < nr_pages; i++) {
4343 struct page *page = pvec.pages[i];
4345 done_index = page->index + 1;
4347 * At this point we hold neither the i_pages lock nor
4348 * the page lock: the page may be truncated or
4349 * invalidated (changing page->mapping to NULL),
4350 * or even swizzled back from swapper_space to
4351 * tmpfs file mapping
4353 if (!trylock_page(page)) {
4354 ret = flush_write_bio(epd);
4359 if (unlikely(page->mapping != mapping)) {
4364 if (wbc->sync_mode != WB_SYNC_NONE) {
4365 if (PageWriteback(page)) {
4366 ret = flush_write_bio(epd);
4369 wait_on_page_writeback(page);
4372 if (PageWriteback(page) ||
4373 !clear_page_dirty_for_io(page)) {
4378 ret = __extent_writepage(page, wbc, epd);
4385 * the filesystem may choose to bump up nr_to_write.
4386 * We have to make sure to honor the new nr_to_write
4389 nr_to_write_done = wbc->nr_to_write <= 0;
4391 pagevec_release(&pvec);
4394 if (!scanned && !done) {
4396 * We hit the last page and there is more work to be done: wrap
4397 * back to the start of the file
4403 * If we're looping we could run into a page that is locked by a
4404 * writer and that writer could be waiting on writeback for a
4405 * page in our current bio, and thus deadlock, so flush the
4408 ret = flush_write_bio(epd);
4413 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4414 mapping->writeback_index = done_index;
4416 btrfs_add_delayed_iput(inode);
4420 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4423 struct extent_page_data epd = {
4426 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4429 ret = __extent_writepage(page, wbc, &epd);
4432 end_write_bio(&epd, ret);
4436 ret = flush_write_bio(&epd);
4441 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4445 struct address_space *mapping = inode->i_mapping;
4447 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4450 struct extent_page_data epd = {
4453 .sync_io = mode == WB_SYNC_ALL,
4455 struct writeback_control wbc_writepages = {
4457 .nr_to_write = nr_pages * 2,
4458 .range_start = start,
4459 .range_end = end + 1,
4460 /* We're called from an async helper function */
4461 .punt_to_cgroup = 1,
4462 .no_cgroup_owner = 1,
4465 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
4466 while (start <= end) {
4467 page = find_get_page(mapping, start >> PAGE_SHIFT);
4468 if (clear_page_dirty_for_io(page))
4469 ret = __extent_writepage(page, &wbc_writepages, &epd);
4471 btrfs_writepage_endio_finish_ordered(page, start,
4472 start + PAGE_SIZE - 1, 1);
4481 ret = flush_write_bio(&epd);
4483 end_write_bio(&epd, ret);
4485 wbc_detach_inode(&wbc_writepages);
4489 int extent_writepages(struct address_space *mapping,
4490 struct writeback_control *wbc)
4493 struct extent_page_data epd = {
4496 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4499 ret = extent_write_cache_pages(mapping, wbc, &epd);
4502 end_write_bio(&epd, ret);
4505 ret = flush_write_bio(&epd);
4509 void extent_readahead(struct readahead_control *rac)
4511 struct bio *bio = NULL;
4512 unsigned long bio_flags = 0;
4513 struct page *pagepool[16];
4514 struct extent_map *em_cached = NULL;
4515 u64 prev_em_start = (u64)-1;
4518 while ((nr = readahead_page_batch(rac, pagepool))) {
4519 u64 contig_start = page_offset(pagepool[0]);
4520 u64 contig_end = page_offset(pagepool[nr - 1]) + PAGE_SIZE - 1;
4522 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4524 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4525 &em_cached, &bio, &bio_flags, &prev_em_start);
4529 free_extent_map(em_cached);
4532 if (submit_one_bio(bio, 0, bio_flags))
4538 * basic invalidatepage code, this waits on any locked or writeback
4539 * ranges corresponding to the page, and then deletes any extent state
4540 * records from the tree
4542 int extent_invalidatepage(struct extent_io_tree *tree,
4543 struct page *page, unsigned long offset)
4545 struct extent_state *cached_state = NULL;
4546 u64 start = page_offset(page);
4547 u64 end = start + PAGE_SIZE - 1;
4548 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4550 /* This function is only called for the btree inode */
4551 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
4553 start += ALIGN(offset, blocksize);
4557 lock_extent_bits(tree, start, end, &cached_state);
4558 wait_on_page_writeback(page);
4561 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
4562 * so here we only need to unlock the extent range to free any
4563 * existing extent state.
4565 unlock_extent_cached(tree, start, end, &cached_state);
4570 * a helper for releasepage, this tests for areas of the page that
4571 * are locked or under IO and drops the related state bits if it is safe
4574 static int try_release_extent_state(struct extent_io_tree *tree,
4575 struct page *page, gfp_t mask)
4577 u64 start = page_offset(page);
4578 u64 end = start + PAGE_SIZE - 1;
4581 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4585 * At this point we can safely clear everything except the
4586 * locked bit, the nodatasum bit and the delalloc new bit.
4587 * The delalloc new bit will be cleared by ordered extent
4590 ret = __clear_extent_bit(tree, start, end,
4591 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
4592 0, 0, NULL, mask, NULL);
4594 /* if clear_extent_bit failed for enomem reasons,
4595 * we can't allow the release to continue.
4606 * a helper for releasepage. As long as there are no locked extents
4607 * in the range corresponding to the page, both state records and extent
4608 * map records are removed
4610 int try_release_extent_mapping(struct page *page, gfp_t mask)
4612 struct extent_map *em;
4613 u64 start = page_offset(page);
4614 u64 end = start + PAGE_SIZE - 1;
4615 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4616 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4617 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4619 if (gfpflags_allow_blocking(mask) &&
4620 page->mapping->host->i_size > SZ_16M) {
4622 while (start <= end) {
4623 struct btrfs_fs_info *fs_info;
4626 len = end - start + 1;
4627 write_lock(&map->lock);
4628 em = lookup_extent_mapping(map, start, len);
4630 write_unlock(&map->lock);
4633 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4634 em->start != start) {
4635 write_unlock(&map->lock);
4636 free_extent_map(em);
4639 if (test_range_bit(tree, em->start,
4640 extent_map_end(em) - 1,
4641 EXTENT_LOCKED, 0, NULL))
4644 * If it's not in the list of modified extents, used
4645 * by a fast fsync, we can remove it. If it's being
4646 * logged we can safely remove it since fsync took an
4647 * extra reference on the em.
4649 if (list_empty(&em->list) ||
4650 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
4653 * If it's in the list of modified extents, remove it
4654 * only if its generation is older then the current one,
4655 * in which case we don't need it for a fast fsync.
4656 * Otherwise don't remove it, we could be racing with an
4657 * ongoing fast fsync that could miss the new extent.
4659 fs_info = btrfs_inode->root->fs_info;
4660 spin_lock(&fs_info->trans_lock);
4661 cur_gen = fs_info->generation;
4662 spin_unlock(&fs_info->trans_lock);
4663 if (em->generation >= cur_gen)
4667 * We only remove extent maps that are not in the list of
4668 * modified extents or that are in the list but with a
4669 * generation lower then the current generation, so there
4670 * is no need to set the full fsync flag on the inode (it
4671 * hurts the fsync performance for workloads with a data
4672 * size that exceeds or is close to the system's memory).
4674 remove_extent_mapping(map, em);
4675 /* once for the rb tree */
4676 free_extent_map(em);
4678 start = extent_map_end(em);
4679 write_unlock(&map->lock);
4682 free_extent_map(em);
4684 cond_resched(); /* Allow large-extent preemption. */
4687 return try_release_extent_state(tree, page, mask);
4691 * helper function for fiemap, which doesn't want to see any holes.
4692 * This maps until we find something past 'last'
4694 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
4695 u64 offset, u64 last)
4697 u64 sectorsize = btrfs_inode_sectorsize(inode);
4698 struct extent_map *em;
4705 len = last - offset;
4708 len = ALIGN(len, sectorsize);
4709 em = btrfs_get_extent_fiemap(inode, offset, len);
4710 if (IS_ERR_OR_NULL(em))
4713 /* if this isn't a hole return it */
4714 if (em->block_start != EXTENT_MAP_HOLE)
4717 /* this is a hole, advance to the next extent */
4718 offset = extent_map_end(em);
4719 free_extent_map(em);
4727 * To cache previous fiemap extent
4729 * Will be used for merging fiemap extent
4731 struct fiemap_cache {
4740 * Helper to submit fiemap extent.
4742 * Will try to merge current fiemap extent specified by @offset, @phys,
4743 * @len and @flags with cached one.
4744 * And only when we fails to merge, cached one will be submitted as
4747 * Return value is the same as fiemap_fill_next_extent().
4749 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4750 struct fiemap_cache *cache,
4751 u64 offset, u64 phys, u64 len, u32 flags)
4759 * Sanity check, extent_fiemap() should have ensured that new
4760 * fiemap extent won't overlap with cached one.
4763 * NOTE: Physical address can overlap, due to compression
4765 if (cache->offset + cache->len > offset) {
4771 * Only merges fiemap extents if
4772 * 1) Their logical addresses are continuous
4774 * 2) Their physical addresses are continuous
4775 * So truly compressed (physical size smaller than logical size)
4776 * extents won't get merged with each other
4778 * 3) Share same flags except FIEMAP_EXTENT_LAST
4779 * So regular extent won't get merged with prealloc extent
4781 if (cache->offset + cache->len == offset &&
4782 cache->phys + cache->len == phys &&
4783 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4784 (flags & ~FIEMAP_EXTENT_LAST)) {
4786 cache->flags |= flags;
4787 goto try_submit_last;
4790 /* Not mergeable, need to submit cached one */
4791 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4792 cache->len, cache->flags);
4793 cache->cached = false;
4797 cache->cached = true;
4798 cache->offset = offset;
4801 cache->flags = flags;
4803 if (cache->flags & FIEMAP_EXTENT_LAST) {
4804 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4805 cache->phys, cache->len, cache->flags);
4806 cache->cached = false;
4812 * Emit last fiemap cache
4814 * The last fiemap cache may still be cached in the following case:
4816 * |<- Fiemap range ->|
4817 * |<------------ First extent ----------->|
4819 * In this case, the first extent range will be cached but not emitted.
4820 * So we must emit it before ending extent_fiemap().
4822 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4823 struct fiemap_cache *cache)
4830 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4831 cache->len, cache->flags);
4832 cache->cached = false;
4838 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
4843 u64 max = start + len;
4847 u64 last_for_get_extent = 0;
4849 u64 isize = i_size_read(&inode->vfs_inode);
4850 struct btrfs_key found_key;
4851 struct extent_map *em = NULL;
4852 struct extent_state *cached_state = NULL;
4853 struct btrfs_path *path;
4854 struct btrfs_root *root = inode->root;
4855 struct fiemap_cache cache = { 0 };
4856 struct ulist *roots;
4857 struct ulist *tmp_ulist;
4866 path = btrfs_alloc_path();
4870 roots = ulist_alloc(GFP_KERNEL);
4871 tmp_ulist = ulist_alloc(GFP_KERNEL);
4872 if (!roots || !tmp_ulist) {
4874 goto out_free_ulist;
4877 start = round_down(start, btrfs_inode_sectorsize(inode));
4878 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4881 * lookup the last file extent. We're not using i_size here
4882 * because there might be preallocation past i_size
4884 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
4887 goto out_free_ulist;
4895 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4896 found_type = found_key.type;
4898 /* No extents, but there might be delalloc bits */
4899 if (found_key.objectid != btrfs_ino(inode) ||
4900 found_type != BTRFS_EXTENT_DATA_KEY) {
4901 /* have to trust i_size as the end */
4903 last_for_get_extent = isize;
4906 * remember the start of the last extent. There are a
4907 * bunch of different factors that go into the length of the
4908 * extent, so its much less complex to remember where it started
4910 last = found_key.offset;
4911 last_for_get_extent = last + 1;
4913 btrfs_release_path(path);
4916 * we might have some extents allocated but more delalloc past those
4917 * extents. so, we trust isize unless the start of the last extent is
4922 last_for_get_extent = isize;
4925 lock_extent_bits(&inode->io_tree, start, start + len - 1,
4928 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4937 u64 offset_in_extent = 0;
4939 /* break if the extent we found is outside the range */
4940 if (em->start >= max || extent_map_end(em) < off)
4944 * get_extent may return an extent that starts before our
4945 * requested range. We have to make sure the ranges
4946 * we return to fiemap always move forward and don't
4947 * overlap, so adjust the offsets here
4949 em_start = max(em->start, off);
4952 * record the offset from the start of the extent
4953 * for adjusting the disk offset below. Only do this if the
4954 * extent isn't compressed since our in ram offset may be past
4955 * what we have actually allocated on disk.
4957 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4958 offset_in_extent = em_start - em->start;
4959 em_end = extent_map_end(em);
4960 em_len = em_end - em_start;
4962 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4963 disko = em->block_start + offset_in_extent;
4968 * bump off for our next call to get_extent
4970 off = extent_map_end(em);
4974 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4976 flags |= FIEMAP_EXTENT_LAST;
4977 } else if (em->block_start == EXTENT_MAP_INLINE) {
4978 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4979 FIEMAP_EXTENT_NOT_ALIGNED);
4980 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4981 flags |= (FIEMAP_EXTENT_DELALLOC |
4982 FIEMAP_EXTENT_UNKNOWN);
4983 } else if (fieinfo->fi_extents_max) {
4984 u64 bytenr = em->block_start -
4985 (em->start - em->orig_start);
4988 * As btrfs supports shared space, this information
4989 * can be exported to userspace tools via
4990 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4991 * then we're just getting a count and we can skip the
4994 ret = btrfs_check_shared(root, btrfs_ino(inode),
4995 bytenr, roots, tmp_ulist);
4999 flags |= FIEMAP_EXTENT_SHARED;
5002 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5003 flags |= FIEMAP_EXTENT_ENCODED;
5004 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5005 flags |= FIEMAP_EXTENT_UNWRITTEN;
5007 free_extent_map(em);
5009 if ((em_start >= last) || em_len == (u64)-1 ||
5010 (last == (u64)-1 && isize <= em_end)) {
5011 flags |= FIEMAP_EXTENT_LAST;
5015 /* now scan forward to see if this is really the last extent. */
5016 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5022 flags |= FIEMAP_EXTENT_LAST;
5025 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5035 ret = emit_last_fiemap_cache(fieinfo, &cache);
5036 free_extent_map(em);
5038 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5042 btrfs_free_path(path);
5044 ulist_free(tmp_ulist);
5048 static void __free_extent_buffer(struct extent_buffer *eb)
5050 kmem_cache_free(extent_buffer_cache, eb);
5053 int extent_buffer_under_io(const struct extent_buffer *eb)
5055 return (atomic_read(&eb->io_pages) ||
5056 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5057 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5060 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5062 struct btrfs_subpage *subpage;
5064 lockdep_assert_held(&page->mapping->private_lock);
5066 if (PagePrivate(page)) {
5067 subpage = (struct btrfs_subpage *)page->private;
5068 if (atomic_read(&subpage->eb_refs))
5074 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5076 struct btrfs_fs_info *fs_info = eb->fs_info;
5077 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5080 * For mapped eb, we're going to change the page private, which should
5081 * be done under the private_lock.
5084 spin_lock(&page->mapping->private_lock);
5086 if (!PagePrivate(page)) {
5088 spin_unlock(&page->mapping->private_lock);
5092 if (fs_info->sectorsize == PAGE_SIZE) {
5094 * We do this since we'll remove the pages after we've
5095 * removed the eb from the radix tree, so we could race
5096 * and have this page now attached to the new eb. So
5097 * only clear page_private if it's still connected to
5100 if (PagePrivate(page) &&
5101 page->private == (unsigned long)eb) {
5102 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5103 BUG_ON(PageDirty(page));
5104 BUG_ON(PageWriteback(page));
5106 * We need to make sure we haven't be attached
5109 detach_page_private(page);
5112 spin_unlock(&page->mapping->private_lock);
5117 * For subpage, we can have dummy eb with page private. In this case,
5118 * we can directly detach the private as such page is only attached to
5119 * one dummy eb, no sharing.
5122 btrfs_detach_subpage(fs_info, page);
5126 btrfs_page_dec_eb_refs(fs_info, page);
5129 * We can only detach the page private if there are no other ebs in the
5132 if (!page_range_has_eb(fs_info, page))
5133 btrfs_detach_subpage(fs_info, page);
5135 spin_unlock(&page->mapping->private_lock);
5138 /* Release all pages attached to the extent buffer */
5139 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5144 ASSERT(!extent_buffer_under_io(eb));
5146 num_pages = num_extent_pages(eb);
5147 for (i = 0; i < num_pages; i++) {
5148 struct page *page = eb->pages[i];
5153 detach_extent_buffer_page(eb, page);
5155 /* One for when we allocated the page */
5161 * Helper for releasing the extent buffer.
5163 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5165 btrfs_release_extent_buffer_pages(eb);
5166 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5167 __free_extent_buffer(eb);
5170 static struct extent_buffer *
5171 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5174 struct extent_buffer *eb = NULL;
5176 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5179 eb->fs_info = fs_info;
5181 init_rwsem(&eb->lock);
5183 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5184 &fs_info->allocated_ebs);
5186 spin_lock_init(&eb->refs_lock);
5187 atomic_set(&eb->refs, 1);
5188 atomic_set(&eb->io_pages, 0);
5190 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5195 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5199 struct extent_buffer *new;
5200 int num_pages = num_extent_pages(src);
5202 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5207 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5208 * btrfs_release_extent_buffer() have different behavior for
5209 * UNMAPPED subpage extent buffer.
5211 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5213 for (i = 0; i < num_pages; i++) {
5216 p = alloc_page(GFP_NOFS);
5218 btrfs_release_extent_buffer(new);
5221 ret = attach_extent_buffer_page(new, p, NULL);
5224 btrfs_release_extent_buffer(new);
5227 WARN_ON(PageDirty(p));
5229 copy_page(page_address(p), page_address(src->pages[i]));
5231 set_extent_buffer_uptodate(new);
5236 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5237 u64 start, unsigned long len)
5239 struct extent_buffer *eb;
5243 eb = __alloc_extent_buffer(fs_info, start, len);
5247 num_pages = num_extent_pages(eb);
5248 for (i = 0; i < num_pages; i++) {
5251 eb->pages[i] = alloc_page(GFP_NOFS);
5254 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5258 set_extent_buffer_uptodate(eb);
5259 btrfs_set_header_nritems(eb, 0);
5260 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5264 for (; i > 0; i--) {
5265 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5266 __free_page(eb->pages[i - 1]);
5268 __free_extent_buffer(eb);
5272 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5275 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5278 static void check_buffer_tree_ref(struct extent_buffer *eb)
5282 * The TREE_REF bit is first set when the extent_buffer is added
5283 * to the radix tree. It is also reset, if unset, when a new reference
5284 * is created by find_extent_buffer.
5286 * It is only cleared in two cases: freeing the last non-tree
5287 * reference to the extent_buffer when its STALE bit is set or
5288 * calling releasepage when the tree reference is the only reference.
5290 * In both cases, care is taken to ensure that the extent_buffer's
5291 * pages are not under io. However, releasepage can be concurrently
5292 * called with creating new references, which is prone to race
5293 * conditions between the calls to check_buffer_tree_ref in those
5294 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5296 * The actual lifetime of the extent_buffer in the radix tree is
5297 * adequately protected by the refcount, but the TREE_REF bit and
5298 * its corresponding reference are not. To protect against this
5299 * class of races, we call check_buffer_tree_ref from the codepaths
5300 * which trigger io after they set eb->io_pages. Note that once io is
5301 * initiated, TREE_REF can no longer be cleared, so that is the
5302 * moment at which any such race is best fixed.
5304 refs = atomic_read(&eb->refs);
5305 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5308 spin_lock(&eb->refs_lock);
5309 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5310 atomic_inc(&eb->refs);
5311 spin_unlock(&eb->refs_lock);
5314 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5315 struct page *accessed)
5319 check_buffer_tree_ref(eb);
5321 num_pages = num_extent_pages(eb);
5322 for (i = 0; i < num_pages; i++) {
5323 struct page *p = eb->pages[i];
5326 mark_page_accessed(p);
5330 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5333 struct extent_buffer *eb;
5336 eb = radix_tree_lookup(&fs_info->buffer_radix,
5337 start >> fs_info->sectorsize_bits);
5338 if (eb && atomic_inc_not_zero(&eb->refs)) {
5341 * Lock our eb's refs_lock to avoid races with
5342 * free_extent_buffer. When we get our eb it might be flagged
5343 * with EXTENT_BUFFER_STALE and another task running
5344 * free_extent_buffer might have seen that flag set,
5345 * eb->refs == 2, that the buffer isn't under IO (dirty and
5346 * writeback flags not set) and it's still in the tree (flag
5347 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5348 * of decrementing the extent buffer's reference count twice.
5349 * So here we could race and increment the eb's reference count,
5350 * clear its stale flag, mark it as dirty and drop our reference
5351 * before the other task finishes executing free_extent_buffer,
5352 * which would later result in an attempt to free an extent
5353 * buffer that is dirty.
5355 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5356 spin_lock(&eb->refs_lock);
5357 spin_unlock(&eb->refs_lock);
5359 mark_extent_buffer_accessed(eb, NULL);
5367 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5368 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5371 struct extent_buffer *eb, *exists = NULL;
5374 eb = find_extent_buffer(fs_info, start);
5377 eb = alloc_dummy_extent_buffer(fs_info, start);
5379 return ERR_PTR(-ENOMEM);
5380 eb->fs_info = fs_info;
5382 ret = radix_tree_preload(GFP_NOFS);
5384 exists = ERR_PTR(ret);
5387 spin_lock(&fs_info->buffer_lock);
5388 ret = radix_tree_insert(&fs_info->buffer_radix,
5389 start >> fs_info->sectorsize_bits, eb);
5390 spin_unlock(&fs_info->buffer_lock);
5391 radix_tree_preload_end();
5392 if (ret == -EEXIST) {
5393 exists = find_extent_buffer(fs_info, start);
5399 check_buffer_tree_ref(eb);
5400 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5404 btrfs_release_extent_buffer(eb);
5409 static struct extent_buffer *grab_extent_buffer(
5410 struct btrfs_fs_info *fs_info, struct page *page)
5412 struct extent_buffer *exists;
5415 * For subpage case, we completely rely on radix tree to ensure we
5416 * don't try to insert two ebs for the same bytenr. So here we always
5417 * return NULL and just continue.
5419 if (fs_info->sectorsize < PAGE_SIZE)
5422 /* Page not yet attached to an extent buffer */
5423 if (!PagePrivate(page))
5427 * We could have already allocated an eb for this page and attached one
5428 * so lets see if we can get a ref on the existing eb, and if we can we
5429 * know it's good and we can just return that one, else we know we can
5430 * just overwrite page->private.
5432 exists = (struct extent_buffer *)page->private;
5433 if (atomic_inc_not_zero(&exists->refs))
5436 WARN_ON(PageDirty(page));
5437 detach_page_private(page);
5441 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5442 u64 start, u64 owner_root, int level)
5444 unsigned long len = fs_info->nodesize;
5447 unsigned long index = start >> PAGE_SHIFT;
5448 struct extent_buffer *eb;
5449 struct extent_buffer *exists = NULL;
5451 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5455 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5456 btrfs_err(fs_info, "bad tree block start %llu", start);
5457 return ERR_PTR(-EINVAL);
5460 if (fs_info->sectorsize < PAGE_SIZE &&
5461 offset_in_page(start) + len > PAGE_SIZE) {
5463 "tree block crosses page boundary, start %llu nodesize %lu",
5465 return ERR_PTR(-EINVAL);
5468 eb = find_extent_buffer(fs_info, start);
5472 eb = __alloc_extent_buffer(fs_info, start, len);
5474 return ERR_PTR(-ENOMEM);
5475 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
5477 num_pages = num_extent_pages(eb);
5478 for (i = 0; i < num_pages; i++, index++) {
5479 struct btrfs_subpage *prealloc = NULL;
5481 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5483 exists = ERR_PTR(-ENOMEM);
5488 * Preallocate page->private for subpage case, so that we won't
5489 * allocate memory with private_lock hold. The memory will be
5490 * freed by attach_extent_buffer_page() or freed manually if
5493 * Although we have ensured one subpage eb can only have one
5494 * page, but it may change in the future for 16K page size
5495 * support, so we still preallocate the memory in the loop.
5497 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5498 BTRFS_SUBPAGE_METADATA);
5502 exists = ERR_PTR(ret);
5506 spin_lock(&mapping->private_lock);
5507 exists = grab_extent_buffer(fs_info, p);
5509 spin_unlock(&mapping->private_lock);
5512 mark_extent_buffer_accessed(exists, p);
5513 btrfs_free_subpage(prealloc);
5516 /* Should not fail, as we have preallocated the memory */
5517 ret = attach_extent_buffer_page(eb, p, prealloc);
5520 * To inform we have extra eb under allocation, so that
5521 * detach_extent_buffer_page() won't release the page private
5522 * when the eb hasn't yet been inserted into radix tree.
5524 * The ref will be decreased when the eb released the page, in
5525 * detach_extent_buffer_page().
5526 * Thus needs no special handling in error path.
5528 btrfs_page_inc_eb_refs(fs_info, p);
5529 spin_unlock(&mapping->private_lock);
5531 WARN_ON(PageDirty(p));
5533 if (!PageUptodate(p))
5537 * We can't unlock the pages just yet since the extent buffer
5538 * hasn't been properly inserted in the radix tree, this
5539 * opens a race with btree_releasepage which can free a page
5540 * while we are still filling in all pages for the buffer and
5545 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5547 ret = radix_tree_preload(GFP_NOFS);
5549 exists = ERR_PTR(ret);
5553 spin_lock(&fs_info->buffer_lock);
5554 ret = radix_tree_insert(&fs_info->buffer_radix,
5555 start >> fs_info->sectorsize_bits, eb);
5556 spin_unlock(&fs_info->buffer_lock);
5557 radix_tree_preload_end();
5558 if (ret == -EEXIST) {
5559 exists = find_extent_buffer(fs_info, start);
5565 /* add one reference for the tree */
5566 check_buffer_tree_ref(eb);
5567 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5570 * Now it's safe to unlock the pages because any calls to
5571 * btree_releasepage will correctly detect that a page belongs to a
5572 * live buffer and won't free them prematurely.
5574 for (i = 0; i < num_pages; i++)
5575 unlock_page(eb->pages[i]);
5579 WARN_ON(!atomic_dec_and_test(&eb->refs));
5580 for (i = 0; i < num_pages; i++) {
5582 unlock_page(eb->pages[i]);
5585 btrfs_release_extent_buffer(eb);
5589 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5591 struct extent_buffer *eb =
5592 container_of(head, struct extent_buffer, rcu_head);
5594 __free_extent_buffer(eb);
5597 static int release_extent_buffer(struct extent_buffer *eb)
5598 __releases(&eb->refs_lock)
5600 lockdep_assert_held(&eb->refs_lock);
5602 WARN_ON(atomic_read(&eb->refs) == 0);
5603 if (atomic_dec_and_test(&eb->refs)) {
5604 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5605 struct btrfs_fs_info *fs_info = eb->fs_info;
5607 spin_unlock(&eb->refs_lock);
5609 spin_lock(&fs_info->buffer_lock);
5610 radix_tree_delete(&fs_info->buffer_radix,
5611 eb->start >> fs_info->sectorsize_bits);
5612 spin_unlock(&fs_info->buffer_lock);
5614 spin_unlock(&eb->refs_lock);
5617 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5618 /* Should be safe to release our pages at this point */
5619 btrfs_release_extent_buffer_pages(eb);
5620 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5621 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5622 __free_extent_buffer(eb);
5626 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5629 spin_unlock(&eb->refs_lock);
5634 void free_extent_buffer(struct extent_buffer *eb)
5642 refs = atomic_read(&eb->refs);
5643 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5644 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5647 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5652 spin_lock(&eb->refs_lock);
5653 if (atomic_read(&eb->refs) == 2 &&
5654 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5655 !extent_buffer_under_io(eb) &&
5656 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5657 atomic_dec(&eb->refs);
5660 * I know this is terrible, but it's temporary until we stop tracking
5661 * the uptodate bits and such for the extent buffers.
5663 release_extent_buffer(eb);
5666 void free_extent_buffer_stale(struct extent_buffer *eb)
5671 spin_lock(&eb->refs_lock);
5672 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5674 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5675 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5676 atomic_dec(&eb->refs);
5677 release_extent_buffer(eb);
5680 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
5686 num_pages = num_extent_pages(eb);
5688 for (i = 0; i < num_pages; i++) {
5689 page = eb->pages[i];
5690 if (!PageDirty(page))
5694 WARN_ON(!PagePrivate(page));
5696 clear_page_dirty_for_io(page);
5697 xa_lock_irq(&page->mapping->i_pages);
5698 if (!PageDirty(page))
5699 __xa_clear_mark(&page->mapping->i_pages,
5700 page_index(page), PAGECACHE_TAG_DIRTY);
5701 xa_unlock_irq(&page->mapping->i_pages);
5702 ClearPageError(page);
5705 WARN_ON(atomic_read(&eb->refs) == 0);
5708 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5714 check_buffer_tree_ref(eb);
5716 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5718 num_pages = num_extent_pages(eb);
5719 WARN_ON(atomic_read(&eb->refs) == 0);
5720 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5723 for (i = 0; i < num_pages; i++)
5724 set_page_dirty(eb->pages[i]);
5726 #ifdef CONFIG_BTRFS_DEBUG
5727 for (i = 0; i < num_pages; i++)
5728 ASSERT(PageDirty(eb->pages[i]));
5734 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5736 struct btrfs_fs_info *fs_info = eb->fs_info;
5741 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5742 num_pages = num_extent_pages(eb);
5743 for (i = 0; i < num_pages; i++) {
5744 page = eb->pages[i];
5746 btrfs_page_clear_uptodate(fs_info, page,
5747 eb->start, eb->len);
5751 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5753 struct btrfs_fs_info *fs_info = eb->fs_info;
5758 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5759 num_pages = num_extent_pages(eb);
5760 for (i = 0; i < num_pages; i++) {
5761 page = eb->pages[i];
5762 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
5766 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
5769 struct btrfs_fs_info *fs_info = eb->fs_info;
5770 struct extent_io_tree *io_tree;
5771 struct page *page = eb->pages[0];
5772 struct bio *bio = NULL;
5775 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
5776 ASSERT(PagePrivate(page));
5777 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
5779 if (wait == WAIT_NONE) {
5780 ret = try_lock_extent(io_tree, eb->start,
5781 eb->start + eb->len - 1);
5785 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5791 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
5792 PageUptodate(page) ||
5793 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
5794 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5795 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5799 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5800 eb->read_mirror = 0;
5801 atomic_set(&eb->io_pages, 1);
5802 check_buffer_tree_ref(eb);
5803 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
5805 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, page, eb->start,
5806 eb->len, eb->start - page_offset(page), &bio,
5807 end_bio_extent_readpage, mirror_num, 0, 0,
5811 * In the endio function, if we hit something wrong we will
5812 * increase the io_pages, so here we need to decrease it for
5815 atomic_dec(&eb->io_pages);
5820 tmp = submit_one_bio(bio, mirror_num, 0);
5824 if (ret || wait != WAIT_COMPLETE)
5827 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
5828 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5833 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5839 int locked_pages = 0;
5840 int all_uptodate = 1;
5842 unsigned long num_reads = 0;
5843 struct bio *bio = NULL;
5844 unsigned long bio_flags = 0;
5846 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5849 if (eb->fs_info->sectorsize < PAGE_SIZE)
5850 return read_extent_buffer_subpage(eb, wait, mirror_num);
5852 num_pages = num_extent_pages(eb);
5853 for (i = 0; i < num_pages; i++) {
5854 page = eb->pages[i];
5855 if (wait == WAIT_NONE) {
5856 if (!trylock_page(page))
5864 * We need to firstly lock all pages to make sure that
5865 * the uptodate bit of our pages won't be affected by
5866 * clear_extent_buffer_uptodate().
5868 for (i = 0; i < num_pages; i++) {
5869 page = eb->pages[i];
5870 if (!PageUptodate(page)) {
5877 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5881 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5882 eb->read_mirror = 0;
5883 atomic_set(&eb->io_pages, num_reads);
5885 * It is possible for releasepage to clear the TREE_REF bit before we
5886 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5888 check_buffer_tree_ref(eb);
5889 for (i = 0; i < num_pages; i++) {
5890 page = eb->pages[i];
5892 if (!PageUptodate(page)) {
5894 atomic_dec(&eb->io_pages);
5899 ClearPageError(page);
5900 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
5901 page, page_offset(page), PAGE_SIZE, 0,
5902 &bio, end_bio_extent_readpage,
5903 mirror_num, 0, 0, false);
5906 * We failed to submit the bio so it's the
5907 * caller's responsibility to perform cleanup
5908 * i.e unlock page/set error bit.
5913 atomic_dec(&eb->io_pages);
5921 err = submit_one_bio(bio, mirror_num, bio_flags);
5926 if (ret || wait != WAIT_COMPLETE)
5929 for (i = 0; i < num_pages; i++) {
5930 page = eb->pages[i];
5931 wait_on_page_locked(page);
5932 if (!PageUptodate(page))
5939 while (locked_pages > 0) {
5941 page = eb->pages[locked_pages];
5947 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5950 btrfs_warn(eb->fs_info,
5951 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
5952 eb->start, eb->len, start, len);
5953 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5959 * Check if the [start, start + len) range is valid before reading/writing
5961 * NOTE: @start and @len are offset inside the eb, not logical address.
5963 * Caller should not touch the dst/src memory if this function returns error.
5965 static inline int check_eb_range(const struct extent_buffer *eb,
5966 unsigned long start, unsigned long len)
5968 unsigned long offset;
5970 /* start, start + len should not go beyond eb->len nor overflow */
5971 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5972 return report_eb_range(eb, start, len);
5977 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5978 unsigned long start, unsigned long len)
5984 char *dst = (char *)dstv;
5985 unsigned long i = get_eb_page_index(start);
5987 if (check_eb_range(eb, start, len))
5990 offset = get_eb_offset_in_page(eb, start);
5993 page = eb->pages[i];
5995 cur = min(len, (PAGE_SIZE - offset));
5996 kaddr = page_address(page);
5997 memcpy(dst, kaddr + offset, cur);
6006 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6008 unsigned long start, unsigned long len)
6014 char __user *dst = (char __user *)dstv;
6015 unsigned long i = get_eb_page_index(start);
6018 WARN_ON(start > eb->len);
6019 WARN_ON(start + len > eb->start + eb->len);
6021 offset = get_eb_offset_in_page(eb, start);
6024 page = eb->pages[i];
6026 cur = min(len, (PAGE_SIZE - offset));
6027 kaddr = page_address(page);
6028 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6042 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6043 unsigned long start, unsigned long len)
6049 char *ptr = (char *)ptrv;
6050 unsigned long i = get_eb_page_index(start);
6053 if (check_eb_range(eb, start, len))
6056 offset = get_eb_offset_in_page(eb, start);
6059 page = eb->pages[i];
6061 cur = min(len, (PAGE_SIZE - offset));
6063 kaddr = page_address(page);
6064 ret = memcmp(ptr, kaddr + offset, cur);
6076 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6081 WARN_ON(!PageUptodate(eb->pages[0]));
6082 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6083 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
6087 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6091 WARN_ON(!PageUptodate(eb->pages[0]));
6092 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6093 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
6097 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6098 unsigned long start, unsigned long len)
6104 char *src = (char *)srcv;
6105 unsigned long i = get_eb_page_index(start);
6107 if (check_eb_range(eb, start, len))
6110 offset = get_eb_offset_in_page(eb, start);
6113 page = eb->pages[i];
6114 WARN_ON(!PageUptodate(page));
6116 cur = min(len, PAGE_SIZE - offset);
6117 kaddr = page_address(page);
6118 memcpy(kaddr + offset, src, cur);
6127 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6134 unsigned long i = get_eb_page_index(start);
6136 if (check_eb_range(eb, start, len))
6139 offset = get_eb_offset_in_page(eb, start);
6142 page = eb->pages[i];
6143 WARN_ON(!PageUptodate(page));
6145 cur = min(len, PAGE_SIZE - offset);
6146 kaddr = page_address(page);
6147 memset(kaddr + offset, 0, cur);
6155 void copy_extent_buffer_full(const struct extent_buffer *dst,
6156 const struct extent_buffer *src)
6161 ASSERT(dst->len == src->len);
6163 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6164 num_pages = num_extent_pages(dst);
6165 for (i = 0; i < num_pages; i++)
6166 copy_page(page_address(dst->pages[i]),
6167 page_address(src->pages[i]));
6169 size_t src_offset = get_eb_offset_in_page(src, 0);
6170 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6172 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6173 memcpy(page_address(dst->pages[0]) + dst_offset,
6174 page_address(src->pages[0]) + src_offset,
6179 void copy_extent_buffer(const struct extent_buffer *dst,
6180 const struct extent_buffer *src,
6181 unsigned long dst_offset, unsigned long src_offset,
6184 u64 dst_len = dst->len;
6189 unsigned long i = get_eb_page_index(dst_offset);
6191 if (check_eb_range(dst, dst_offset, len) ||
6192 check_eb_range(src, src_offset, len))
6195 WARN_ON(src->len != dst_len);
6197 offset = get_eb_offset_in_page(dst, dst_offset);
6200 page = dst->pages[i];
6201 WARN_ON(!PageUptodate(page));
6203 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
6205 kaddr = page_address(page);
6206 read_extent_buffer(src, kaddr + offset, src_offset, cur);
6216 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6218 * @eb: the extent buffer
6219 * @start: offset of the bitmap item in the extent buffer
6221 * @page_index: return index of the page in the extent buffer that contains the
6223 * @page_offset: return offset into the page given by page_index
6225 * This helper hides the ugliness of finding the byte in an extent buffer which
6226 * contains a given bit.
6228 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
6229 unsigned long start, unsigned long nr,
6230 unsigned long *page_index,
6231 size_t *page_offset)
6233 size_t byte_offset = BIT_BYTE(nr);
6237 * The byte we want is the offset of the extent buffer + the offset of
6238 * the bitmap item in the extent buffer + the offset of the byte in the
6241 offset = start + offset_in_page(eb->start) + byte_offset;
6243 *page_index = offset >> PAGE_SHIFT;
6244 *page_offset = offset_in_page(offset);
6248 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6249 * @eb: the extent buffer
6250 * @start: offset of the bitmap item in the extent buffer
6251 * @nr: bit number to test
6253 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
6261 eb_bitmap_offset(eb, start, nr, &i, &offset);
6262 page = eb->pages[i];
6263 WARN_ON(!PageUptodate(page));
6264 kaddr = page_address(page);
6265 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6269 * extent_buffer_bitmap_set - set an area of a bitmap
6270 * @eb: the extent buffer
6271 * @start: offset of the bitmap item in the extent buffer
6272 * @pos: bit number of the first bit
6273 * @len: number of bits to set
6275 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
6276 unsigned long pos, unsigned long len)
6282 const unsigned int size = pos + len;
6283 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6284 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
6286 eb_bitmap_offset(eb, start, pos, &i, &offset);
6287 page = eb->pages[i];
6288 WARN_ON(!PageUptodate(page));
6289 kaddr = page_address(page);
6291 while (len >= bits_to_set) {
6292 kaddr[offset] |= mask_to_set;
6294 bits_to_set = BITS_PER_BYTE;
6296 if (++offset >= PAGE_SIZE && len > 0) {
6298 page = eb->pages[++i];
6299 WARN_ON(!PageUptodate(page));
6300 kaddr = page_address(page);
6304 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6305 kaddr[offset] |= mask_to_set;
6311 * extent_buffer_bitmap_clear - clear an area of a bitmap
6312 * @eb: the extent buffer
6313 * @start: offset of the bitmap item in the extent buffer
6314 * @pos: bit number of the first bit
6315 * @len: number of bits to clear
6317 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6318 unsigned long start, unsigned long pos,
6325 const unsigned int size = pos + len;
6326 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6327 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
6329 eb_bitmap_offset(eb, start, pos, &i, &offset);
6330 page = eb->pages[i];
6331 WARN_ON(!PageUptodate(page));
6332 kaddr = page_address(page);
6334 while (len >= bits_to_clear) {
6335 kaddr[offset] &= ~mask_to_clear;
6336 len -= bits_to_clear;
6337 bits_to_clear = BITS_PER_BYTE;
6339 if (++offset >= PAGE_SIZE && len > 0) {
6341 page = eb->pages[++i];
6342 WARN_ON(!PageUptodate(page));
6343 kaddr = page_address(page);
6347 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6348 kaddr[offset] &= ~mask_to_clear;
6352 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6354 unsigned long distance = (src > dst) ? src - dst : dst - src;
6355 return distance < len;
6358 static void copy_pages(struct page *dst_page, struct page *src_page,
6359 unsigned long dst_off, unsigned long src_off,
6362 char *dst_kaddr = page_address(dst_page);
6364 int must_memmove = 0;
6366 if (dst_page != src_page) {
6367 src_kaddr = page_address(src_page);
6369 src_kaddr = dst_kaddr;
6370 if (areas_overlap(src_off, dst_off, len))
6375 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6377 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6380 void memcpy_extent_buffer(const struct extent_buffer *dst,
6381 unsigned long dst_offset, unsigned long src_offset,
6385 size_t dst_off_in_page;
6386 size_t src_off_in_page;
6387 unsigned long dst_i;
6388 unsigned long src_i;
6390 if (check_eb_range(dst, dst_offset, len) ||
6391 check_eb_range(dst, src_offset, len))
6395 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6396 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
6398 dst_i = get_eb_page_index(dst_offset);
6399 src_i = get_eb_page_index(src_offset);
6401 cur = min(len, (unsigned long)(PAGE_SIZE -
6403 cur = min_t(unsigned long, cur,
6404 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6406 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6407 dst_off_in_page, src_off_in_page, cur);
6415 void memmove_extent_buffer(const struct extent_buffer *dst,
6416 unsigned long dst_offset, unsigned long src_offset,
6420 size_t dst_off_in_page;
6421 size_t src_off_in_page;
6422 unsigned long dst_end = dst_offset + len - 1;
6423 unsigned long src_end = src_offset + len - 1;
6424 unsigned long dst_i;
6425 unsigned long src_i;
6427 if (check_eb_range(dst, dst_offset, len) ||
6428 check_eb_range(dst, src_offset, len))
6430 if (dst_offset < src_offset) {
6431 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6435 dst_i = get_eb_page_index(dst_end);
6436 src_i = get_eb_page_index(src_end);
6438 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6439 src_off_in_page = get_eb_offset_in_page(dst, src_end);
6441 cur = min_t(unsigned long, len, src_off_in_page + 1);
6442 cur = min(cur, dst_off_in_page + 1);
6443 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6444 dst_off_in_page - cur + 1,
6445 src_off_in_page - cur + 1, cur);
6453 static struct extent_buffer *get_next_extent_buffer(
6454 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6456 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6457 struct extent_buffer *found = NULL;
6458 u64 page_start = page_offset(page);
6462 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
6463 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
6464 lockdep_assert_held(&fs_info->buffer_lock);
6466 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
6467 bytenr >> fs_info->sectorsize_bits,
6468 PAGE_SIZE / fs_info->nodesize);
6469 for (i = 0; i < ret; i++) {
6470 /* Already beyond page end */
6471 if (gang[i]->start >= page_start + PAGE_SIZE)
6474 if (gang[i]->start >= bytenr) {
6482 static int try_release_subpage_extent_buffer(struct page *page)
6484 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
6485 u64 cur = page_offset(page);
6486 const u64 end = page_offset(page) + PAGE_SIZE;
6490 struct extent_buffer *eb = NULL;
6493 * Unlike try_release_extent_buffer() which uses page->private
6494 * to grab buffer, for subpage case we rely on radix tree, thus
6495 * we need to ensure radix tree consistency.
6497 * We also want an atomic snapshot of the radix tree, thus go
6498 * with spinlock rather than RCU.
6500 spin_lock(&fs_info->buffer_lock);
6501 eb = get_next_extent_buffer(fs_info, page, cur);
6503 /* No more eb in the page range after or at cur */
6504 spin_unlock(&fs_info->buffer_lock);
6507 cur = eb->start + eb->len;
6510 * The same as try_release_extent_buffer(), to ensure the eb
6511 * won't disappear out from under us.
6513 spin_lock(&eb->refs_lock);
6514 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6515 spin_unlock(&eb->refs_lock);
6516 spin_unlock(&fs_info->buffer_lock);
6519 spin_unlock(&fs_info->buffer_lock);
6522 * If tree ref isn't set then we know the ref on this eb is a
6523 * real ref, so just return, this eb will likely be freed soon
6526 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6527 spin_unlock(&eb->refs_lock);
6532 * Here we don't care about the return value, we will always
6533 * check the page private at the end. And
6534 * release_extent_buffer() will release the refs_lock.
6536 release_extent_buffer(eb);
6539 * Finally to check if we have cleared page private, as if we have
6540 * released all ebs in the page, the page private should be cleared now.
6542 spin_lock(&page->mapping->private_lock);
6543 if (!PagePrivate(page))
6547 spin_unlock(&page->mapping->private_lock);
6552 int try_release_extent_buffer(struct page *page)
6554 struct extent_buffer *eb;
6556 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
6557 return try_release_subpage_extent_buffer(page);
6560 * We need to make sure nobody is changing page->private, as we rely on
6561 * page->private as the pointer to extent buffer.
6563 spin_lock(&page->mapping->private_lock);
6564 if (!PagePrivate(page)) {
6565 spin_unlock(&page->mapping->private_lock);
6569 eb = (struct extent_buffer *)page->private;
6573 * This is a little awful but should be ok, we need to make sure that
6574 * the eb doesn't disappear out from under us while we're looking at
6577 spin_lock(&eb->refs_lock);
6578 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6579 spin_unlock(&eb->refs_lock);
6580 spin_unlock(&page->mapping->private_lock);
6583 spin_unlock(&page->mapping->private_lock);
6586 * If tree ref isn't set then we know the ref on this eb is a real ref,
6587 * so just return, this page will likely be freed soon anyway.
6589 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6590 spin_unlock(&eb->refs_lock);
6594 return release_extent_buffer(eb);
6598 * btrfs_readahead_tree_block - attempt to readahead a child block
6599 * @fs_info: the fs_info
6600 * @bytenr: bytenr to read
6601 * @owner_root: objectid of the root that owns this eb
6602 * @gen: generation for the uptodate check, can be 0
6603 * @level: level for the eb
6605 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
6606 * normal uptodate check of the eb, without checking the generation. If we have
6607 * to read the block we will not block on anything.
6609 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
6610 u64 bytenr, u64 owner_root, u64 gen, int level)
6612 struct extent_buffer *eb;
6615 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
6619 if (btrfs_buffer_uptodate(eb, gen, 1)) {
6620 free_extent_buffer(eb);
6624 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
6626 free_extent_buffer_stale(eb);
6628 free_extent_buffer(eb);
6632 * btrfs_readahead_node_child - readahead a node's child block
6633 * @node: parent node we're reading from
6634 * @slot: slot in the parent node for the child we want to read
6636 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
6637 * the slot in the node provided.
6639 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
6641 btrfs_readahead_tree_block(node->fs_info,
6642 btrfs_node_blockptr(node, slot),
6643 btrfs_header_owner(node),
6644 btrfs_node_ptr_generation(node, slot),
6645 btrfs_header_level(node) - 1);