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_map.h"
19 #include "btrfs_inode.h"
21 #include "check-integrity.h"
23 #include "rcu-string.h"
27 static struct kmem_cache *extent_state_cache;
28 static struct kmem_cache *extent_buffer_cache;
29 static struct bio_set btrfs_bioset;
31 static inline bool extent_state_in_tree(const struct extent_state *state)
33 return !RB_EMPTY_NODE(&state->rb_node);
36 #ifdef CONFIG_BTRFS_DEBUG
37 static LIST_HEAD(buffers);
38 static LIST_HEAD(states);
40 static DEFINE_SPINLOCK(leak_lock);
43 void btrfs_leak_debug_add(struct list_head *new, struct list_head *head)
47 spin_lock_irqsave(&leak_lock, flags);
49 spin_unlock_irqrestore(&leak_lock, flags);
53 void btrfs_leak_debug_del(struct list_head *entry)
57 spin_lock_irqsave(&leak_lock, flags);
59 spin_unlock_irqrestore(&leak_lock, flags);
63 void btrfs_leak_debug_check(void)
65 struct extent_state *state;
66 struct extent_buffer *eb;
68 while (!list_empty(&states)) {
69 state = list_entry(states.next, struct extent_state, leak_list);
70 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
71 state->start, state->end, state->state,
72 extent_state_in_tree(state),
73 refcount_read(&state->refs));
74 list_del(&state->leak_list);
75 kmem_cache_free(extent_state_cache, state);
78 while (!list_empty(&buffers)) {
79 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
80 pr_err("BTRFS: buffer leak start %llu len %lu refs %d bflags %lu\n",
81 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags);
82 list_del(&eb->leak_list);
83 kmem_cache_free(extent_buffer_cache, eb);
87 #define btrfs_debug_check_extent_io_range(tree, start, end) \
88 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
89 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
90 struct extent_io_tree *tree, u64 start, u64 end)
92 struct inode *inode = tree->private_data;
95 if (!inode || !is_data_inode(inode))
98 isize = i_size_read(inode);
99 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
100 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
101 "%s: ino %llu isize %llu odd range [%llu,%llu]",
102 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
106 #define btrfs_leak_debug_add(new, head) do {} while (0)
107 #define btrfs_leak_debug_del(entry) do {} while (0)
108 #define btrfs_leak_debug_check() do {} while (0)
109 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
115 struct rb_node rb_node;
118 struct extent_page_data {
120 struct extent_io_tree *tree;
121 /* tells writepage not to lock the state bits for this range
122 * it still does the unlocking
124 unsigned int extent_locked:1;
126 /* tells the submit_bio code to use REQ_SYNC */
127 unsigned int sync_io:1;
130 static int add_extent_changeset(struct extent_state *state, unsigned bits,
131 struct extent_changeset *changeset,
138 if (set && (state->state & bits) == bits)
140 if (!set && (state->state & bits) == 0)
142 changeset->bytes_changed += state->end - state->start + 1;
143 ret = ulist_add(&changeset->range_changed, state->start, state->end,
148 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
149 unsigned long bio_flags)
151 blk_status_t ret = 0;
152 struct extent_io_tree *tree = bio->bi_private;
154 bio->bi_private = NULL;
157 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
158 mirror_num, bio_flags);
160 btrfsic_submit_bio(bio);
162 return blk_status_to_errno(ret);
165 /* Cleanup unsubmitted bios */
166 static void end_write_bio(struct extent_page_data *epd, int ret)
169 epd->bio->bi_status = errno_to_blk_status(ret);
176 * Submit bio from extent page data via submit_one_bio
178 * Return 0 if everything is OK.
179 * Return <0 for error.
181 static int __must_check flush_write_bio(struct extent_page_data *epd)
186 ret = submit_one_bio(epd->bio, 0, 0);
188 * Clean up of epd->bio is handled by its endio function.
189 * And endio is either triggered by successful bio execution
190 * or the error handler of submit bio hook.
191 * So at this point, no matter what happened, we don't need
192 * to clean up epd->bio.
199 int __init extent_io_init(void)
201 extent_state_cache = kmem_cache_create("btrfs_extent_state",
202 sizeof(struct extent_state), 0,
203 SLAB_MEM_SPREAD, NULL);
204 if (!extent_state_cache)
207 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
208 sizeof(struct extent_buffer), 0,
209 SLAB_MEM_SPREAD, NULL);
210 if (!extent_buffer_cache)
211 goto free_state_cache;
213 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
214 offsetof(struct btrfs_io_bio, bio),
216 goto free_buffer_cache;
218 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
224 bioset_exit(&btrfs_bioset);
227 kmem_cache_destroy(extent_buffer_cache);
228 extent_buffer_cache = NULL;
231 kmem_cache_destroy(extent_state_cache);
232 extent_state_cache = NULL;
236 void __cold extent_io_exit(void)
238 btrfs_leak_debug_check();
241 * Make sure all delayed rcu free are flushed before we
245 kmem_cache_destroy(extent_state_cache);
246 kmem_cache_destroy(extent_buffer_cache);
247 bioset_exit(&btrfs_bioset);
250 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
251 struct extent_io_tree *tree, unsigned int owner,
254 tree->fs_info = fs_info;
255 tree->state = RB_ROOT;
257 tree->dirty_bytes = 0;
258 spin_lock_init(&tree->lock);
259 tree->private_data = private_data;
263 void extent_io_tree_release(struct extent_io_tree *tree)
265 spin_lock(&tree->lock);
267 * Do a single barrier for the waitqueue_active check here, the state
268 * of the waitqueue should not change once extent_io_tree_release is
272 while (!RB_EMPTY_ROOT(&tree->state)) {
273 struct rb_node *node;
274 struct extent_state *state;
276 node = rb_first(&tree->state);
277 state = rb_entry(node, struct extent_state, rb_node);
278 rb_erase(&state->rb_node, &tree->state);
279 RB_CLEAR_NODE(&state->rb_node);
281 * btree io trees aren't supposed to have tasks waiting for
282 * changes in the flags of extent states ever.
284 ASSERT(!waitqueue_active(&state->wq));
285 free_extent_state(state);
287 cond_resched_lock(&tree->lock);
289 spin_unlock(&tree->lock);
292 static struct extent_state *alloc_extent_state(gfp_t mask)
294 struct extent_state *state;
297 * The given mask might be not appropriate for the slab allocator,
298 * drop the unsupported bits
300 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
301 state = kmem_cache_alloc(extent_state_cache, mask);
305 state->failrec = NULL;
306 RB_CLEAR_NODE(&state->rb_node);
307 btrfs_leak_debug_add(&state->leak_list, &states);
308 refcount_set(&state->refs, 1);
309 init_waitqueue_head(&state->wq);
310 trace_alloc_extent_state(state, mask, _RET_IP_);
314 void free_extent_state(struct extent_state *state)
318 if (refcount_dec_and_test(&state->refs)) {
319 WARN_ON(extent_state_in_tree(state));
320 btrfs_leak_debug_del(&state->leak_list);
321 trace_free_extent_state(state, _RET_IP_);
322 kmem_cache_free(extent_state_cache, state);
326 static struct rb_node *tree_insert(struct rb_root *root,
327 struct rb_node *search_start,
329 struct rb_node *node,
330 struct rb_node ***p_in,
331 struct rb_node **parent_in)
334 struct rb_node *parent = NULL;
335 struct tree_entry *entry;
337 if (p_in && parent_in) {
343 p = search_start ? &search_start : &root->rb_node;
346 entry = rb_entry(parent, struct tree_entry, rb_node);
348 if (offset < entry->start)
350 else if (offset > entry->end)
357 rb_link_node(node, parent, p);
358 rb_insert_color(node, root);
363 * __etree_search - searche @tree for an entry that contains @offset. Such
364 * entry would have entry->start <= offset && entry->end >= offset.
366 * @tree - the tree to search
367 * @offset - offset that should fall within an entry in @tree
368 * @next_ret - pointer to the first entry whose range ends after @offset
369 * @prev - pointer to the first entry whose range begins before @offset
370 * @p_ret - pointer where new node should be anchored (used when inserting an
372 * @parent_ret - points to entry which would have been the parent of the entry,
375 * This function returns a pointer to the entry that contains @offset byte
376 * address. If no such entry exists, then NULL is returned and the other
377 * pointer arguments to the function are filled, otherwise the found entry is
378 * returned and other pointers are left untouched.
380 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
381 struct rb_node **next_ret,
382 struct rb_node **prev_ret,
383 struct rb_node ***p_ret,
384 struct rb_node **parent_ret)
386 struct rb_root *root = &tree->state;
387 struct rb_node **n = &root->rb_node;
388 struct rb_node *prev = NULL;
389 struct rb_node *orig_prev = NULL;
390 struct tree_entry *entry;
391 struct tree_entry *prev_entry = NULL;
395 entry = rb_entry(prev, struct tree_entry, rb_node);
398 if (offset < entry->start)
400 else if (offset > entry->end)
413 while (prev && offset > prev_entry->end) {
414 prev = rb_next(prev);
415 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
422 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
423 while (prev && offset < prev_entry->start) {
424 prev = rb_prev(prev);
425 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
432 static inline struct rb_node *
433 tree_search_for_insert(struct extent_io_tree *tree,
435 struct rb_node ***p_ret,
436 struct rb_node **parent_ret)
438 struct rb_node *next= NULL;
441 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
447 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
450 return tree_search_for_insert(tree, offset, NULL, NULL);
454 * utility function to look for merge candidates inside a given range.
455 * Any extents with matching state are merged together into a single
456 * extent in the tree. Extents with EXTENT_IO in their state field
457 * are not merged because the end_io handlers need to be able to do
458 * operations on them without sleeping (or doing allocations/splits).
460 * This should be called with the tree lock held.
462 static void merge_state(struct extent_io_tree *tree,
463 struct extent_state *state)
465 struct extent_state *other;
466 struct rb_node *other_node;
468 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
471 other_node = rb_prev(&state->rb_node);
473 other = rb_entry(other_node, struct extent_state, rb_node);
474 if (other->end == state->start - 1 &&
475 other->state == state->state) {
476 if (tree->private_data &&
477 is_data_inode(tree->private_data))
478 btrfs_merge_delalloc_extent(tree->private_data,
480 state->start = other->start;
481 rb_erase(&other->rb_node, &tree->state);
482 RB_CLEAR_NODE(&other->rb_node);
483 free_extent_state(other);
486 other_node = rb_next(&state->rb_node);
488 other = rb_entry(other_node, struct extent_state, rb_node);
489 if (other->start == state->end + 1 &&
490 other->state == state->state) {
491 if (tree->private_data &&
492 is_data_inode(tree->private_data))
493 btrfs_merge_delalloc_extent(tree->private_data,
495 state->end = other->end;
496 rb_erase(&other->rb_node, &tree->state);
497 RB_CLEAR_NODE(&other->rb_node);
498 free_extent_state(other);
503 static void set_state_bits(struct extent_io_tree *tree,
504 struct extent_state *state, unsigned *bits,
505 struct extent_changeset *changeset);
508 * insert an extent_state struct into the tree. 'bits' are set on the
509 * struct before it is inserted.
511 * This may return -EEXIST if the extent is already there, in which case the
512 * state struct is freed.
514 * The tree lock is not taken internally. This is a utility function and
515 * probably isn't what you want to call (see set/clear_extent_bit).
517 static int insert_state(struct extent_io_tree *tree,
518 struct extent_state *state, u64 start, u64 end,
520 struct rb_node **parent,
521 unsigned *bits, struct extent_changeset *changeset)
523 struct rb_node *node;
526 btrfs_err(tree->fs_info,
527 "insert state: end < start %llu %llu", end, start);
530 state->start = start;
533 set_state_bits(tree, state, bits, changeset);
535 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
537 struct extent_state *found;
538 found = rb_entry(node, struct extent_state, rb_node);
539 btrfs_err(tree->fs_info,
540 "found node %llu %llu on insert of %llu %llu",
541 found->start, found->end, start, end);
544 merge_state(tree, state);
549 * split a given extent state struct in two, inserting the preallocated
550 * struct 'prealloc' as the newly created second half. 'split' indicates an
551 * offset inside 'orig' where it should be split.
554 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
555 * are two extent state structs in the tree:
556 * prealloc: [orig->start, split - 1]
557 * orig: [ split, orig->end ]
559 * The tree locks are not taken by this function. They need to be held
562 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
563 struct extent_state *prealloc, u64 split)
565 struct rb_node *node;
567 if (tree->private_data && is_data_inode(tree->private_data))
568 btrfs_split_delalloc_extent(tree->private_data, orig, split);
570 prealloc->start = orig->start;
571 prealloc->end = split - 1;
572 prealloc->state = orig->state;
575 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
576 &prealloc->rb_node, NULL, NULL);
578 free_extent_state(prealloc);
584 static struct extent_state *next_state(struct extent_state *state)
586 struct rb_node *next = rb_next(&state->rb_node);
588 return rb_entry(next, struct extent_state, rb_node);
594 * utility function to clear some bits in an extent state struct.
595 * it will optionally wake up anyone waiting on this state (wake == 1).
597 * If no bits are set on the state struct after clearing things, the
598 * struct is freed and removed from the tree
600 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
601 struct extent_state *state,
602 unsigned *bits, int wake,
603 struct extent_changeset *changeset)
605 struct extent_state *next;
606 unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
609 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
610 u64 range = state->end - state->start + 1;
611 WARN_ON(range > tree->dirty_bytes);
612 tree->dirty_bytes -= range;
615 if (tree->private_data && is_data_inode(tree->private_data))
616 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
618 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
620 state->state &= ~bits_to_clear;
623 if (state->state == 0) {
624 next = next_state(state);
625 if (extent_state_in_tree(state)) {
626 rb_erase(&state->rb_node, &tree->state);
627 RB_CLEAR_NODE(&state->rb_node);
628 free_extent_state(state);
633 merge_state(tree, state);
634 next = next_state(state);
639 static struct extent_state *
640 alloc_extent_state_atomic(struct extent_state *prealloc)
643 prealloc = alloc_extent_state(GFP_ATOMIC);
648 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
650 btrfs_panic(tree->fs_info, err,
651 "locking error: extent tree was modified by another thread while locked");
655 * clear some bits on a range in the tree. This may require splitting
656 * or inserting elements in the tree, so the gfp mask is used to
657 * indicate which allocations or sleeping are allowed.
659 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
660 * the given range from the tree regardless of state (ie for truncate).
662 * the range [start, end] is inclusive.
664 * This takes the tree lock, and returns 0 on success and < 0 on error.
666 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
667 unsigned bits, int wake, int delete,
668 struct extent_state **cached_state,
669 gfp_t mask, struct extent_changeset *changeset)
671 struct extent_state *state;
672 struct extent_state *cached;
673 struct extent_state *prealloc = NULL;
674 struct rb_node *node;
679 btrfs_debug_check_extent_io_range(tree, start, end);
680 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
682 if (bits & EXTENT_DELALLOC)
683 bits |= EXTENT_NORESERVE;
686 bits |= ~EXTENT_CTLBITS;
688 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
691 if (!prealloc && gfpflags_allow_blocking(mask)) {
693 * Don't care for allocation failure here because we might end
694 * up not needing the pre-allocated extent state at all, which
695 * is the case if we only have in the tree extent states that
696 * cover our input range and don't cover too any other range.
697 * If we end up needing a new extent state we allocate it later.
699 prealloc = alloc_extent_state(mask);
702 spin_lock(&tree->lock);
704 cached = *cached_state;
707 *cached_state = NULL;
711 if (cached && extent_state_in_tree(cached) &&
712 cached->start <= start && cached->end > start) {
714 refcount_dec(&cached->refs);
719 free_extent_state(cached);
722 * this search will find the extents that end after
725 node = tree_search(tree, start);
728 state = rb_entry(node, struct extent_state, rb_node);
730 if (state->start > end)
732 WARN_ON(state->end < start);
733 last_end = state->end;
735 /* the state doesn't have the wanted bits, go ahead */
736 if (!(state->state & bits)) {
737 state = next_state(state);
742 * | ---- desired range ---- |
744 * | ------------- state -------------- |
746 * We need to split the extent we found, and may flip
747 * bits on second half.
749 * If the extent we found extends past our range, we
750 * just split and search again. It'll get split again
751 * the next time though.
753 * If the extent we found is inside our range, we clear
754 * the desired bit on it.
757 if (state->start < start) {
758 prealloc = alloc_extent_state_atomic(prealloc);
760 err = split_state(tree, state, prealloc, start);
762 extent_io_tree_panic(tree, err);
767 if (state->end <= end) {
768 state = clear_state_bit(tree, state, &bits, wake,
775 * | ---- desired range ---- |
777 * We need to split the extent, and clear the bit
780 if (state->start <= end && state->end > end) {
781 prealloc = alloc_extent_state_atomic(prealloc);
783 err = split_state(tree, state, prealloc, end + 1);
785 extent_io_tree_panic(tree, err);
790 clear_state_bit(tree, prealloc, &bits, wake, changeset);
796 state = clear_state_bit(tree, state, &bits, wake, changeset);
798 if (last_end == (u64)-1)
800 start = last_end + 1;
801 if (start <= end && state && !need_resched())
807 spin_unlock(&tree->lock);
808 if (gfpflags_allow_blocking(mask))
813 spin_unlock(&tree->lock);
815 free_extent_state(prealloc);
821 static void wait_on_state(struct extent_io_tree *tree,
822 struct extent_state *state)
823 __releases(tree->lock)
824 __acquires(tree->lock)
827 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
828 spin_unlock(&tree->lock);
830 spin_lock(&tree->lock);
831 finish_wait(&state->wq, &wait);
835 * waits for one or more bits to clear on a range in the state tree.
836 * The range [start, end] is inclusive.
837 * The tree lock is taken by this function
839 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
842 struct extent_state *state;
843 struct rb_node *node;
845 btrfs_debug_check_extent_io_range(tree, start, end);
847 spin_lock(&tree->lock);
851 * this search will find all the extents that end after
854 node = tree_search(tree, start);
859 state = rb_entry(node, struct extent_state, rb_node);
861 if (state->start > end)
864 if (state->state & bits) {
865 start = state->start;
866 refcount_inc(&state->refs);
867 wait_on_state(tree, state);
868 free_extent_state(state);
871 start = state->end + 1;
876 if (!cond_resched_lock(&tree->lock)) {
877 node = rb_next(node);
882 spin_unlock(&tree->lock);
885 static void set_state_bits(struct extent_io_tree *tree,
886 struct extent_state *state,
887 unsigned *bits, struct extent_changeset *changeset)
889 unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
892 if (tree->private_data && is_data_inode(tree->private_data))
893 btrfs_set_delalloc_extent(tree->private_data, state, bits);
895 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
896 u64 range = state->end - state->start + 1;
897 tree->dirty_bytes += range;
899 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
901 state->state |= bits_to_set;
904 static void cache_state_if_flags(struct extent_state *state,
905 struct extent_state **cached_ptr,
908 if (cached_ptr && !(*cached_ptr)) {
909 if (!flags || (state->state & flags)) {
911 refcount_inc(&state->refs);
916 static void cache_state(struct extent_state *state,
917 struct extent_state **cached_ptr)
919 return cache_state_if_flags(state, cached_ptr,
920 EXTENT_LOCKED | EXTENT_BOUNDARY);
924 * set some bits on a range in the tree. This may require allocations or
925 * sleeping, so the gfp mask is used to indicate what is allowed.
927 * If any of the exclusive bits are set, this will fail with -EEXIST if some
928 * part of the range already has the desired bits set. The start of the
929 * existing range is returned in failed_start in this case.
931 * [start, end] is inclusive This takes the tree lock.
934 static int __must_check
935 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
936 unsigned bits, unsigned exclusive_bits,
937 u64 *failed_start, struct extent_state **cached_state,
938 gfp_t mask, struct extent_changeset *changeset)
940 struct extent_state *state;
941 struct extent_state *prealloc = NULL;
942 struct rb_node *node;
944 struct rb_node *parent;
949 btrfs_debug_check_extent_io_range(tree, start, end);
950 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
953 if (!prealloc && gfpflags_allow_blocking(mask)) {
955 * Don't care for allocation failure here because we might end
956 * up not needing the pre-allocated extent state at all, which
957 * is the case if we only have in the tree extent states that
958 * cover our input range and don't cover too any other range.
959 * If we end up needing a new extent state we allocate it later.
961 prealloc = alloc_extent_state(mask);
964 spin_lock(&tree->lock);
965 if (cached_state && *cached_state) {
966 state = *cached_state;
967 if (state->start <= start && state->end > start &&
968 extent_state_in_tree(state)) {
969 node = &state->rb_node;
974 * this search will find all the extents that end after
977 node = tree_search_for_insert(tree, start, &p, &parent);
979 prealloc = alloc_extent_state_atomic(prealloc);
981 err = insert_state(tree, prealloc, start, end,
982 &p, &parent, &bits, changeset);
984 extent_io_tree_panic(tree, err);
986 cache_state(prealloc, cached_state);
990 state = rb_entry(node, struct extent_state, rb_node);
992 last_start = state->start;
993 last_end = state->end;
996 * | ---- desired range ---- |
999 * Just lock what we found and keep going
1001 if (state->start == start && state->end <= end) {
1002 if (state->state & exclusive_bits) {
1003 *failed_start = state->start;
1008 set_state_bits(tree, state, &bits, changeset);
1009 cache_state(state, cached_state);
1010 merge_state(tree, state);
1011 if (last_end == (u64)-1)
1013 start = last_end + 1;
1014 state = next_state(state);
1015 if (start < end && state && state->start == start &&
1022 * | ---- desired range ---- |
1025 * | ------------- state -------------- |
1027 * We need to split the extent we found, and may flip bits on
1030 * If the extent we found extends past our
1031 * range, we just split and search again. It'll get split
1032 * again the next time though.
1034 * If the extent we found is inside our range, we set the
1035 * desired bit on it.
1037 if (state->start < start) {
1038 if (state->state & exclusive_bits) {
1039 *failed_start = start;
1044 prealloc = alloc_extent_state_atomic(prealloc);
1046 err = split_state(tree, state, prealloc, start);
1048 extent_io_tree_panic(tree, err);
1053 if (state->end <= end) {
1054 set_state_bits(tree, state, &bits, changeset);
1055 cache_state(state, cached_state);
1056 merge_state(tree, state);
1057 if (last_end == (u64)-1)
1059 start = last_end + 1;
1060 state = next_state(state);
1061 if (start < end && state && state->start == start &&
1068 * | ---- desired range ---- |
1069 * | state | or | state |
1071 * There's a hole, we need to insert something in it and
1072 * ignore the extent we found.
1074 if (state->start > start) {
1076 if (end < last_start)
1079 this_end = last_start - 1;
1081 prealloc = alloc_extent_state_atomic(prealloc);
1085 * Avoid to free 'prealloc' if it can be merged with
1088 err = insert_state(tree, prealloc, start, this_end,
1089 NULL, NULL, &bits, changeset);
1091 extent_io_tree_panic(tree, err);
1093 cache_state(prealloc, cached_state);
1095 start = this_end + 1;
1099 * | ---- desired range ---- |
1101 * We need to split the extent, and set the bit
1104 if (state->start <= end && state->end > end) {
1105 if (state->state & exclusive_bits) {
1106 *failed_start = start;
1111 prealloc = alloc_extent_state_atomic(prealloc);
1113 err = split_state(tree, state, prealloc, end + 1);
1115 extent_io_tree_panic(tree, err);
1117 set_state_bits(tree, prealloc, &bits, changeset);
1118 cache_state(prealloc, cached_state);
1119 merge_state(tree, prealloc);
1127 spin_unlock(&tree->lock);
1128 if (gfpflags_allow_blocking(mask))
1133 spin_unlock(&tree->lock);
1135 free_extent_state(prealloc);
1141 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1142 unsigned bits, u64 * failed_start,
1143 struct extent_state **cached_state, gfp_t mask)
1145 return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1146 cached_state, mask, NULL);
1151 * convert_extent_bit - convert all bits in a given range from one bit to
1153 * @tree: the io tree to search
1154 * @start: the start offset in bytes
1155 * @end: the end offset in bytes (inclusive)
1156 * @bits: the bits to set in this range
1157 * @clear_bits: the bits to clear in this range
1158 * @cached_state: state that we're going to cache
1160 * This will go through and set bits for the given range. If any states exist
1161 * already in this range they are set with the given bit and cleared of the
1162 * clear_bits. This is only meant to be used by things that are mergeable, ie
1163 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1164 * boundary bits like LOCK.
1166 * All allocations are done with GFP_NOFS.
1168 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1169 unsigned bits, unsigned clear_bits,
1170 struct extent_state **cached_state)
1172 struct extent_state *state;
1173 struct extent_state *prealloc = NULL;
1174 struct rb_node *node;
1176 struct rb_node *parent;
1180 bool first_iteration = true;
1182 btrfs_debug_check_extent_io_range(tree, start, end);
1183 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1189 * Best effort, don't worry if extent state allocation fails
1190 * here for the first iteration. We might have a cached state
1191 * that matches exactly the target range, in which case no
1192 * extent state allocations are needed. We'll only know this
1193 * after locking the tree.
1195 prealloc = alloc_extent_state(GFP_NOFS);
1196 if (!prealloc && !first_iteration)
1200 spin_lock(&tree->lock);
1201 if (cached_state && *cached_state) {
1202 state = *cached_state;
1203 if (state->start <= start && state->end > start &&
1204 extent_state_in_tree(state)) {
1205 node = &state->rb_node;
1211 * this search will find all the extents that end after
1214 node = tree_search_for_insert(tree, start, &p, &parent);
1216 prealloc = alloc_extent_state_atomic(prealloc);
1221 err = insert_state(tree, prealloc, start, end,
1222 &p, &parent, &bits, NULL);
1224 extent_io_tree_panic(tree, err);
1225 cache_state(prealloc, cached_state);
1229 state = rb_entry(node, struct extent_state, rb_node);
1231 last_start = state->start;
1232 last_end = state->end;
1235 * | ---- desired range ---- |
1238 * Just lock what we found and keep going
1240 if (state->start == start && state->end <= end) {
1241 set_state_bits(tree, state, &bits, NULL);
1242 cache_state(state, cached_state);
1243 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1244 if (last_end == (u64)-1)
1246 start = last_end + 1;
1247 if (start < end && state && state->start == start &&
1254 * | ---- desired range ---- |
1257 * | ------------- state -------------- |
1259 * We need to split the extent we found, and may flip bits on
1262 * If the extent we found extends past our
1263 * range, we just split and search again. It'll get split
1264 * again the next time though.
1266 * If the extent we found is inside our range, we set the
1267 * desired bit on it.
1269 if (state->start < start) {
1270 prealloc = alloc_extent_state_atomic(prealloc);
1275 err = split_state(tree, state, prealloc, start);
1277 extent_io_tree_panic(tree, err);
1281 if (state->end <= end) {
1282 set_state_bits(tree, state, &bits, NULL);
1283 cache_state(state, cached_state);
1284 state = clear_state_bit(tree, state, &clear_bits, 0,
1286 if (last_end == (u64)-1)
1288 start = last_end + 1;
1289 if (start < end && state && state->start == start &&
1296 * | ---- desired range ---- |
1297 * | state | or | state |
1299 * There's a hole, we need to insert something in it and
1300 * ignore the extent we found.
1302 if (state->start > start) {
1304 if (end < last_start)
1307 this_end = last_start - 1;
1309 prealloc = alloc_extent_state_atomic(prealloc);
1316 * Avoid to free 'prealloc' if it can be merged with
1319 err = insert_state(tree, prealloc, start, this_end,
1320 NULL, NULL, &bits, NULL);
1322 extent_io_tree_panic(tree, err);
1323 cache_state(prealloc, cached_state);
1325 start = this_end + 1;
1329 * | ---- desired range ---- |
1331 * We need to split the extent, and set the bit
1334 if (state->start <= end && state->end > end) {
1335 prealloc = alloc_extent_state_atomic(prealloc);
1341 err = split_state(tree, state, prealloc, end + 1);
1343 extent_io_tree_panic(tree, err);
1345 set_state_bits(tree, prealloc, &bits, NULL);
1346 cache_state(prealloc, cached_state);
1347 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1355 spin_unlock(&tree->lock);
1357 first_iteration = false;
1361 spin_unlock(&tree->lock);
1363 free_extent_state(prealloc);
1368 /* wrappers around set/clear extent bit */
1369 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1370 unsigned bits, struct extent_changeset *changeset)
1373 * We don't support EXTENT_LOCKED yet, as current changeset will
1374 * record any bits changed, so for EXTENT_LOCKED case, it will
1375 * either fail with -EEXIST or changeset will record the whole
1378 BUG_ON(bits & EXTENT_LOCKED);
1380 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1384 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1387 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1391 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1392 unsigned bits, int wake, int delete,
1393 struct extent_state **cached)
1395 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1396 cached, GFP_NOFS, NULL);
1399 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1400 unsigned bits, struct extent_changeset *changeset)
1403 * Don't support EXTENT_LOCKED case, same reason as
1404 * set_record_extent_bits().
1406 BUG_ON(bits & EXTENT_LOCKED);
1408 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1413 * either insert or lock state struct between start and end use mask to tell
1414 * us if waiting is desired.
1416 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1417 struct extent_state **cached_state)
1423 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1424 EXTENT_LOCKED, &failed_start,
1425 cached_state, GFP_NOFS, NULL);
1426 if (err == -EEXIST) {
1427 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1428 start = failed_start;
1431 WARN_ON(start > end);
1436 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1441 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1442 &failed_start, NULL, GFP_NOFS, NULL);
1443 if (err == -EEXIST) {
1444 if (failed_start > start)
1445 clear_extent_bit(tree, start, failed_start - 1,
1446 EXTENT_LOCKED, 1, 0, NULL);
1452 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1454 unsigned long index = start >> PAGE_SHIFT;
1455 unsigned long end_index = end >> PAGE_SHIFT;
1458 while (index <= end_index) {
1459 page = find_get_page(inode->i_mapping, index);
1460 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1461 clear_page_dirty_for_io(page);
1467 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1469 unsigned long index = start >> PAGE_SHIFT;
1470 unsigned long end_index = end >> PAGE_SHIFT;
1473 while (index <= end_index) {
1474 page = find_get_page(inode->i_mapping, index);
1475 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1476 __set_page_dirty_nobuffers(page);
1477 account_page_redirty(page);
1483 /* find the first state struct with 'bits' set after 'start', and
1484 * return it. tree->lock must be held. NULL will returned if
1485 * nothing was found after 'start'
1487 static struct extent_state *
1488 find_first_extent_bit_state(struct extent_io_tree *tree,
1489 u64 start, unsigned bits)
1491 struct rb_node *node;
1492 struct extent_state *state;
1495 * this search will find all the extents that end after
1498 node = tree_search(tree, start);
1503 state = rb_entry(node, struct extent_state, rb_node);
1504 if (state->end >= start && (state->state & bits))
1507 node = rb_next(node);
1516 * find the first offset in the io tree with 'bits' set. zero is
1517 * returned if we find something, and *start_ret and *end_ret are
1518 * set to reflect the state struct that was found.
1520 * If nothing was found, 1 is returned. If found something, return 0.
1522 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1523 u64 *start_ret, u64 *end_ret, unsigned bits,
1524 struct extent_state **cached_state)
1526 struct extent_state *state;
1529 spin_lock(&tree->lock);
1530 if (cached_state && *cached_state) {
1531 state = *cached_state;
1532 if (state->end == start - 1 && extent_state_in_tree(state)) {
1533 while ((state = next_state(state)) != NULL) {
1534 if (state->state & bits)
1537 free_extent_state(*cached_state);
1538 *cached_state = NULL;
1541 free_extent_state(*cached_state);
1542 *cached_state = NULL;
1545 state = find_first_extent_bit_state(tree, start, bits);
1548 cache_state_if_flags(state, cached_state, 0);
1549 *start_ret = state->start;
1550 *end_ret = state->end;
1554 spin_unlock(&tree->lock);
1559 * find_first_clear_extent_bit - find the first range that has @bits not set.
1560 * This range could start before @start.
1562 * @tree - the tree to search
1563 * @start - the offset at/after which the found extent should start
1564 * @start_ret - records the beginning of the range
1565 * @end_ret - records the end of the range (inclusive)
1566 * @bits - the set of bits which must be unset
1568 * Since unallocated range is also considered one which doesn't have the bits
1569 * set it's possible that @end_ret contains -1, this happens in case the range
1570 * spans (last_range_end, end of device]. In this case it's up to the caller to
1571 * trim @end_ret to the appropriate size.
1573 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1574 u64 *start_ret, u64 *end_ret, unsigned bits)
1576 struct extent_state *state;
1577 struct rb_node *node, *prev = NULL, *next;
1579 spin_lock(&tree->lock);
1581 /* Find first extent with bits cleared */
1583 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1584 if (!node && !next && !prev) {
1586 * Tree is completely empty, send full range and let
1587 * caller deal with it
1592 } else if (!node && !next) {
1594 * We are past the last allocated chunk, set start at
1595 * the end of the last extent.
1597 state = rb_entry(prev, struct extent_state, rb_node);
1598 *start_ret = state->end + 1;
1605 * At this point 'node' either contains 'start' or start is
1608 state = rb_entry(node, struct extent_state, rb_node);
1610 if (in_range(start, state->start, state->end - state->start + 1)) {
1611 if (state->state & bits) {
1613 * |--range with bits sets--|
1617 start = state->end + 1;
1620 * 'start' falls within a range that doesn't
1621 * have the bits set, so take its start as
1622 * the beginning of the desired range
1624 * |--range with bits cleared----|
1628 *start_ret = state->start;
1633 * |---prev range---|---hole/unset---|---node range---|
1639 * |---hole/unset--||--first node--|
1644 state = rb_entry(prev, struct extent_state,
1646 *start_ret = state->end + 1;
1655 * Find the longest stretch from start until an entry which has the
1659 state = rb_entry(node, struct extent_state, rb_node);
1660 if (state->end >= start && !(state->state & bits)) {
1661 *end_ret = state->end;
1663 *end_ret = state->start - 1;
1667 node = rb_next(node);
1672 spin_unlock(&tree->lock);
1676 * find a contiguous range of bytes in the file marked as delalloc, not
1677 * more than 'max_bytes'. start and end are used to return the range,
1679 * true is returned if we find something, false if nothing was in the tree
1681 static noinline bool find_delalloc_range(struct extent_io_tree *tree,
1682 u64 *start, u64 *end, u64 max_bytes,
1683 struct extent_state **cached_state)
1685 struct rb_node *node;
1686 struct extent_state *state;
1687 u64 cur_start = *start;
1689 u64 total_bytes = 0;
1691 spin_lock(&tree->lock);
1694 * this search will find all the extents that end after
1697 node = tree_search(tree, cur_start);
1704 state = rb_entry(node, struct extent_state, rb_node);
1705 if (found && (state->start != cur_start ||
1706 (state->state & EXTENT_BOUNDARY))) {
1709 if (!(state->state & EXTENT_DELALLOC)) {
1715 *start = state->start;
1716 *cached_state = state;
1717 refcount_inc(&state->refs);
1721 cur_start = state->end + 1;
1722 node = rb_next(node);
1723 total_bytes += state->end - state->start + 1;
1724 if (total_bytes >= max_bytes)
1730 spin_unlock(&tree->lock);
1734 static int __process_pages_contig(struct address_space *mapping,
1735 struct page *locked_page,
1736 pgoff_t start_index, pgoff_t end_index,
1737 unsigned long page_ops, pgoff_t *index_ret);
1739 static noinline void __unlock_for_delalloc(struct inode *inode,
1740 struct page *locked_page,
1743 unsigned long index = start >> PAGE_SHIFT;
1744 unsigned long end_index = end >> PAGE_SHIFT;
1746 ASSERT(locked_page);
1747 if (index == locked_page->index && end_index == index)
1750 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1754 static noinline int lock_delalloc_pages(struct inode *inode,
1755 struct page *locked_page,
1759 unsigned long index = delalloc_start >> PAGE_SHIFT;
1760 unsigned long index_ret = index;
1761 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1764 ASSERT(locked_page);
1765 if (index == locked_page->index && index == end_index)
1768 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1769 end_index, PAGE_LOCK, &index_ret);
1771 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1772 (u64)index_ret << PAGE_SHIFT);
1777 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1778 * more than @max_bytes. @Start and @end are used to return the range,
1780 * Return: true if we find something
1781 * false if nothing was in the tree
1784 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1785 struct page *locked_page, u64 *start,
1788 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1789 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1793 struct extent_state *cached_state = NULL;
1798 /* step one, find a bunch of delalloc bytes starting at start */
1799 delalloc_start = *start;
1801 found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1802 max_bytes, &cached_state);
1803 if (!found || delalloc_end <= *start) {
1804 *start = delalloc_start;
1805 *end = delalloc_end;
1806 free_extent_state(cached_state);
1811 * start comes from the offset of locked_page. We have to lock
1812 * pages in order, so we can't process delalloc bytes before
1815 if (delalloc_start < *start)
1816 delalloc_start = *start;
1819 * make sure to limit the number of pages we try to lock down
1821 if (delalloc_end + 1 - delalloc_start > max_bytes)
1822 delalloc_end = delalloc_start + max_bytes - 1;
1824 /* step two, lock all the pages after the page that has start */
1825 ret = lock_delalloc_pages(inode, locked_page,
1826 delalloc_start, delalloc_end);
1827 ASSERT(!ret || ret == -EAGAIN);
1828 if (ret == -EAGAIN) {
1829 /* some of the pages are gone, lets avoid looping by
1830 * shortening the size of the delalloc range we're searching
1832 free_extent_state(cached_state);
1833 cached_state = NULL;
1835 max_bytes = PAGE_SIZE;
1844 /* step three, lock the state bits for the whole range */
1845 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1847 /* then test to make sure it is all still delalloc */
1848 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1849 EXTENT_DELALLOC, 1, cached_state);
1851 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1853 __unlock_for_delalloc(inode, locked_page,
1854 delalloc_start, delalloc_end);
1858 free_extent_state(cached_state);
1859 *start = delalloc_start;
1860 *end = delalloc_end;
1865 static int __process_pages_contig(struct address_space *mapping,
1866 struct page *locked_page,
1867 pgoff_t start_index, pgoff_t end_index,
1868 unsigned long page_ops, pgoff_t *index_ret)
1870 unsigned long nr_pages = end_index - start_index + 1;
1871 unsigned long pages_locked = 0;
1872 pgoff_t index = start_index;
1873 struct page *pages[16];
1878 if (page_ops & PAGE_LOCK) {
1879 ASSERT(page_ops == PAGE_LOCK);
1880 ASSERT(index_ret && *index_ret == start_index);
1883 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1884 mapping_set_error(mapping, -EIO);
1886 while (nr_pages > 0) {
1887 ret = find_get_pages_contig(mapping, index,
1888 min_t(unsigned long,
1889 nr_pages, ARRAY_SIZE(pages)), pages);
1892 * Only if we're going to lock these pages,
1893 * can we find nothing at @index.
1895 ASSERT(page_ops & PAGE_LOCK);
1900 for (i = 0; i < ret; i++) {
1901 if (page_ops & PAGE_SET_PRIVATE2)
1902 SetPagePrivate2(pages[i]);
1904 if (locked_page && pages[i] == locked_page) {
1909 if (page_ops & PAGE_CLEAR_DIRTY)
1910 clear_page_dirty_for_io(pages[i]);
1911 if (page_ops & PAGE_SET_WRITEBACK)
1912 set_page_writeback(pages[i]);
1913 if (page_ops & PAGE_SET_ERROR)
1914 SetPageError(pages[i]);
1915 if (page_ops & PAGE_END_WRITEBACK)
1916 end_page_writeback(pages[i]);
1917 if (page_ops & PAGE_UNLOCK)
1918 unlock_page(pages[i]);
1919 if (page_ops & PAGE_LOCK) {
1920 lock_page(pages[i]);
1921 if (!PageDirty(pages[i]) ||
1922 pages[i]->mapping != mapping) {
1923 unlock_page(pages[i]);
1924 for (; i < ret; i++)
1938 if (err && index_ret)
1939 *index_ret = start_index + pages_locked - 1;
1943 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1944 struct page *locked_page,
1945 unsigned clear_bits,
1946 unsigned long page_ops)
1948 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1951 __process_pages_contig(inode->i_mapping, locked_page,
1952 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1957 * count the number of bytes in the tree that have a given bit(s)
1958 * set. This can be fairly slow, except for EXTENT_DIRTY which is
1959 * cached. The total number found is returned.
1961 u64 count_range_bits(struct extent_io_tree *tree,
1962 u64 *start, u64 search_end, u64 max_bytes,
1963 unsigned bits, int contig)
1965 struct rb_node *node;
1966 struct extent_state *state;
1967 u64 cur_start = *start;
1968 u64 total_bytes = 0;
1972 if (WARN_ON(search_end <= cur_start))
1975 spin_lock(&tree->lock);
1976 if (cur_start == 0 && bits == EXTENT_DIRTY) {
1977 total_bytes = tree->dirty_bytes;
1981 * this search will find all the extents that end after
1984 node = tree_search(tree, cur_start);
1989 state = rb_entry(node, struct extent_state, rb_node);
1990 if (state->start > search_end)
1992 if (contig && found && state->start > last + 1)
1994 if (state->end >= cur_start && (state->state & bits) == bits) {
1995 total_bytes += min(search_end, state->end) + 1 -
1996 max(cur_start, state->start);
1997 if (total_bytes >= max_bytes)
2000 *start = max(cur_start, state->start);
2004 } else if (contig && found) {
2007 node = rb_next(node);
2012 spin_unlock(&tree->lock);
2017 * set the private field for a given byte offset in the tree. If there isn't
2018 * an extent_state there already, this does nothing.
2020 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
2021 struct io_failure_record *failrec)
2023 struct rb_node *node;
2024 struct extent_state *state;
2027 spin_lock(&tree->lock);
2029 * this search will find all the extents that end after
2032 node = tree_search(tree, start);
2037 state = rb_entry(node, struct extent_state, rb_node);
2038 if (state->start != start) {
2042 state->failrec = failrec;
2044 spin_unlock(&tree->lock);
2048 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
2049 struct io_failure_record **failrec)
2051 struct rb_node *node;
2052 struct extent_state *state;
2055 spin_lock(&tree->lock);
2057 * this search will find all the extents that end after
2060 node = tree_search(tree, start);
2065 state = rb_entry(node, struct extent_state, rb_node);
2066 if (state->start != start) {
2070 *failrec = state->failrec;
2072 spin_unlock(&tree->lock);
2077 * searches a range in the state tree for a given mask.
2078 * If 'filled' == 1, this returns 1 only if every extent in the tree
2079 * has the bits set. Otherwise, 1 is returned if any bit in the
2080 * range is found set.
2082 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2083 unsigned bits, int filled, struct extent_state *cached)
2085 struct extent_state *state = NULL;
2086 struct rb_node *node;
2089 spin_lock(&tree->lock);
2090 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2091 cached->end > start)
2092 node = &cached->rb_node;
2094 node = tree_search(tree, start);
2095 while (node && start <= end) {
2096 state = rb_entry(node, struct extent_state, rb_node);
2098 if (filled && state->start > start) {
2103 if (state->start > end)
2106 if (state->state & bits) {
2110 } else if (filled) {
2115 if (state->end == (u64)-1)
2118 start = state->end + 1;
2121 node = rb_next(node);
2128 spin_unlock(&tree->lock);
2133 * helper function to set a given page up to date if all the
2134 * extents in the tree for that page are up to date
2136 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2138 u64 start = page_offset(page);
2139 u64 end = start + PAGE_SIZE - 1;
2140 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2141 SetPageUptodate(page);
2144 int free_io_failure(struct extent_io_tree *failure_tree,
2145 struct extent_io_tree *io_tree,
2146 struct io_failure_record *rec)
2151 set_state_failrec(failure_tree, rec->start, NULL);
2152 ret = clear_extent_bits(failure_tree, rec->start,
2153 rec->start + rec->len - 1,
2154 EXTENT_LOCKED | EXTENT_DIRTY);
2158 ret = clear_extent_bits(io_tree, rec->start,
2159 rec->start + rec->len - 1,
2169 * this bypasses the standard btrfs submit functions deliberately, as
2170 * the standard behavior is to write all copies in a raid setup. here we only
2171 * want to write the one bad copy. so we do the mapping for ourselves and issue
2172 * submit_bio directly.
2173 * to avoid any synchronization issues, wait for the data after writing, which
2174 * actually prevents the read that triggered the error from finishing.
2175 * currently, there can be no more than two copies of every data bit. thus,
2176 * exactly one rewrite is required.
2178 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2179 u64 length, u64 logical, struct page *page,
2180 unsigned int pg_offset, int mirror_num)
2183 struct btrfs_device *dev;
2186 struct btrfs_bio *bbio = NULL;
2189 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2190 BUG_ON(!mirror_num);
2192 bio = btrfs_io_bio_alloc(1);
2193 bio->bi_iter.bi_size = 0;
2194 map_length = length;
2197 * Avoid races with device replace and make sure our bbio has devices
2198 * associated to its stripes that don't go away while we are doing the
2199 * read repair operation.
2201 btrfs_bio_counter_inc_blocked(fs_info);
2202 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2204 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2205 * to update all raid stripes, but here we just want to correct
2206 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2207 * stripe's dev and sector.
2209 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2210 &map_length, &bbio, 0);
2212 btrfs_bio_counter_dec(fs_info);
2216 ASSERT(bbio->mirror_num == 1);
2218 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2219 &map_length, &bbio, mirror_num);
2221 btrfs_bio_counter_dec(fs_info);
2225 BUG_ON(mirror_num != bbio->mirror_num);
2228 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2229 bio->bi_iter.bi_sector = sector;
2230 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2231 btrfs_put_bbio(bbio);
2232 if (!dev || !dev->bdev ||
2233 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2234 btrfs_bio_counter_dec(fs_info);
2238 bio_set_dev(bio, dev->bdev);
2239 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2240 bio_add_page(bio, page, length, pg_offset);
2242 if (btrfsic_submit_bio_wait(bio)) {
2243 /* try to remap that extent elsewhere? */
2244 btrfs_bio_counter_dec(fs_info);
2246 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2250 btrfs_info_rl_in_rcu(fs_info,
2251 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2253 rcu_str_deref(dev->name), sector);
2254 btrfs_bio_counter_dec(fs_info);
2259 int btrfs_repair_eb_io_failure(struct extent_buffer *eb, int mirror_num)
2261 struct btrfs_fs_info *fs_info = eb->fs_info;
2262 u64 start = eb->start;
2263 int i, num_pages = num_extent_pages(eb);
2266 if (sb_rdonly(fs_info->sb))
2269 for (i = 0; i < num_pages; i++) {
2270 struct page *p = eb->pages[i];
2272 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2273 start - page_offset(p), mirror_num);
2283 * each time an IO finishes, we do a fast check in the IO failure tree
2284 * to see if we need to process or clean up an io_failure_record
2286 int clean_io_failure(struct btrfs_fs_info *fs_info,
2287 struct extent_io_tree *failure_tree,
2288 struct extent_io_tree *io_tree, u64 start,
2289 struct page *page, u64 ino, unsigned int pg_offset)
2292 struct io_failure_record *failrec;
2293 struct extent_state *state;
2298 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2303 ret = get_state_failrec(failure_tree, start, &failrec);
2307 BUG_ON(!failrec->this_mirror);
2309 if (failrec->in_validation) {
2310 /* there was no real error, just free the record */
2311 btrfs_debug(fs_info,
2312 "clean_io_failure: freeing dummy error at %llu",
2316 if (sb_rdonly(fs_info->sb))
2319 spin_lock(&io_tree->lock);
2320 state = find_first_extent_bit_state(io_tree,
2323 spin_unlock(&io_tree->lock);
2325 if (state && state->start <= failrec->start &&
2326 state->end >= failrec->start + failrec->len - 1) {
2327 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2329 if (num_copies > 1) {
2330 repair_io_failure(fs_info, ino, start, failrec->len,
2331 failrec->logical, page, pg_offset,
2332 failrec->failed_mirror);
2337 free_io_failure(failure_tree, io_tree, failrec);
2343 * Can be called when
2344 * - hold extent lock
2345 * - under ordered extent
2346 * - the inode is freeing
2348 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2350 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2351 struct io_failure_record *failrec;
2352 struct extent_state *state, *next;
2354 if (RB_EMPTY_ROOT(&failure_tree->state))
2357 spin_lock(&failure_tree->lock);
2358 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2360 if (state->start > end)
2363 ASSERT(state->end <= end);
2365 next = next_state(state);
2367 failrec = state->failrec;
2368 free_extent_state(state);
2373 spin_unlock(&failure_tree->lock);
2376 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2377 struct io_failure_record **failrec_ret)
2379 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2380 struct io_failure_record *failrec;
2381 struct extent_map *em;
2382 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2383 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2384 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2388 ret = get_state_failrec(failure_tree, start, &failrec);
2390 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2394 failrec->start = start;
2395 failrec->len = end - start + 1;
2396 failrec->this_mirror = 0;
2397 failrec->bio_flags = 0;
2398 failrec->in_validation = 0;
2400 read_lock(&em_tree->lock);
2401 em = lookup_extent_mapping(em_tree, start, failrec->len);
2403 read_unlock(&em_tree->lock);
2408 if (em->start > start || em->start + em->len <= start) {
2409 free_extent_map(em);
2412 read_unlock(&em_tree->lock);
2418 logical = start - em->start;
2419 logical = em->block_start + logical;
2420 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2421 logical = em->block_start;
2422 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2423 extent_set_compress_type(&failrec->bio_flags,
2427 btrfs_debug(fs_info,
2428 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2429 logical, start, failrec->len);
2431 failrec->logical = logical;
2432 free_extent_map(em);
2434 /* set the bits in the private failure tree */
2435 ret = set_extent_bits(failure_tree, start, end,
2436 EXTENT_LOCKED | EXTENT_DIRTY);
2438 ret = set_state_failrec(failure_tree, start, failrec);
2439 /* set the bits in the inode's tree */
2441 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2447 btrfs_debug(fs_info,
2448 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2449 failrec->logical, failrec->start, failrec->len,
2450 failrec->in_validation);
2452 * when data can be on disk more than twice, add to failrec here
2453 * (e.g. with a list for failed_mirror) to make
2454 * clean_io_failure() clean all those errors at once.
2458 *failrec_ret = failrec;
2463 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2464 struct io_failure_record *failrec, int failed_mirror)
2466 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2469 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2470 if (num_copies == 1) {
2472 * we only have a single copy of the data, so don't bother with
2473 * all the retry and error correction code that follows. no
2474 * matter what the error is, it is very likely to persist.
2476 btrfs_debug(fs_info,
2477 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2478 num_copies, failrec->this_mirror, failed_mirror);
2483 * there are two premises:
2484 * a) deliver good data to the caller
2485 * b) correct the bad sectors on disk
2487 if (failed_bio_pages > 1) {
2489 * to fulfill b), we need to know the exact failing sectors, as
2490 * we don't want to rewrite any more than the failed ones. thus,
2491 * we need separate read requests for the failed bio
2493 * if the following BUG_ON triggers, our validation request got
2494 * merged. we need separate requests for our algorithm to work.
2496 BUG_ON(failrec->in_validation);
2497 failrec->in_validation = 1;
2498 failrec->this_mirror = failed_mirror;
2501 * we're ready to fulfill a) and b) alongside. get a good copy
2502 * of the failed sector and if we succeed, we have setup
2503 * everything for repair_io_failure to do the rest for us.
2505 if (failrec->in_validation) {
2506 BUG_ON(failrec->this_mirror != failed_mirror);
2507 failrec->in_validation = 0;
2508 failrec->this_mirror = 0;
2510 failrec->failed_mirror = failed_mirror;
2511 failrec->this_mirror++;
2512 if (failrec->this_mirror == failed_mirror)
2513 failrec->this_mirror++;
2516 if (failrec->this_mirror > num_copies) {
2517 btrfs_debug(fs_info,
2518 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2519 num_copies, failrec->this_mirror, failed_mirror);
2527 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2528 struct io_failure_record *failrec,
2529 struct page *page, int pg_offset, int icsum,
2530 bio_end_io_t *endio_func, void *data)
2532 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2534 struct btrfs_io_bio *btrfs_failed_bio;
2535 struct btrfs_io_bio *btrfs_bio;
2537 bio = btrfs_io_bio_alloc(1);
2538 bio->bi_end_io = endio_func;
2539 bio->bi_iter.bi_sector = failrec->logical >> 9;
2540 bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2541 bio->bi_iter.bi_size = 0;
2542 bio->bi_private = data;
2544 btrfs_failed_bio = btrfs_io_bio(failed_bio);
2545 if (btrfs_failed_bio->csum) {
2546 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2548 btrfs_bio = btrfs_io_bio(bio);
2549 btrfs_bio->csum = btrfs_bio->csum_inline;
2551 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2555 bio_add_page(bio, page, failrec->len, pg_offset);
2561 * This is a generic handler for readpage errors. If other copies exist, read
2562 * those and write back good data to the failed position. Does not investigate
2563 * in remapping the failed extent elsewhere, hoping the device will be smart
2564 * enough to do this as needed
2566 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2567 struct page *page, u64 start, u64 end,
2570 struct io_failure_record *failrec;
2571 struct inode *inode = page->mapping->host;
2572 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2573 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2576 blk_status_t status;
2578 unsigned failed_bio_pages = failed_bio->bi_iter.bi_size >> PAGE_SHIFT;
2580 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2582 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2586 if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2588 free_io_failure(failure_tree, tree, failrec);
2592 if (failed_bio_pages > 1)
2593 read_mode |= REQ_FAILFAST_DEV;
2595 phy_offset >>= inode->i_sb->s_blocksize_bits;
2596 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2597 start - page_offset(page),
2598 (int)phy_offset, failed_bio->bi_end_io,
2600 bio->bi_opf = REQ_OP_READ | read_mode;
2602 btrfs_debug(btrfs_sb(inode->i_sb),
2603 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2604 read_mode, failrec->this_mirror, failrec->in_validation);
2606 status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2607 failrec->bio_flags);
2609 free_io_failure(failure_tree, tree, failrec);
2611 ret = blk_status_to_errno(status);
2617 /* lots and lots of room for performance fixes in the end_bio funcs */
2619 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2621 int uptodate = (err == 0);
2624 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2627 ClearPageUptodate(page);
2629 ret = err < 0 ? err : -EIO;
2630 mapping_set_error(page->mapping, ret);
2635 * after a writepage IO is done, we need to:
2636 * clear the uptodate bits on error
2637 * clear the writeback bits in the extent tree for this IO
2638 * end_page_writeback if the page has no more pending IO
2640 * Scheduling is not allowed, so the extent state tree is expected
2641 * to have one and only one object corresponding to this IO.
2643 static void end_bio_extent_writepage(struct bio *bio)
2645 int error = blk_status_to_errno(bio->bi_status);
2646 struct bio_vec *bvec;
2649 struct bvec_iter_all iter_all;
2651 ASSERT(!bio_flagged(bio, BIO_CLONED));
2652 bio_for_each_segment_all(bvec, bio, iter_all) {
2653 struct page *page = bvec->bv_page;
2654 struct inode *inode = page->mapping->host;
2655 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2657 /* We always issue full-page reads, but if some block
2658 * in a page fails to read, blk_update_request() will
2659 * advance bv_offset and adjust bv_len to compensate.
2660 * Print a warning for nonzero offsets, and an error
2661 * if they don't add up to a full page. */
2662 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2663 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2665 "partial page write in btrfs with offset %u and length %u",
2666 bvec->bv_offset, bvec->bv_len);
2669 "incomplete page write in btrfs with offset %u and length %u",
2670 bvec->bv_offset, bvec->bv_len);
2673 start = page_offset(page);
2674 end = start + bvec->bv_offset + bvec->bv_len - 1;
2676 end_extent_writepage(page, error, start, end);
2677 end_page_writeback(page);
2684 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2687 struct extent_state *cached = NULL;
2688 u64 end = start + len - 1;
2690 if (uptodate && tree->track_uptodate)
2691 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2692 unlock_extent_cached_atomic(tree, start, end, &cached);
2696 * after a readpage IO is done, we need to:
2697 * clear the uptodate bits on error
2698 * set the uptodate bits if things worked
2699 * set the page up to date if all extents in the tree are uptodate
2700 * clear the lock bit in the extent tree
2701 * unlock the page if there are no other extents locked for it
2703 * Scheduling is not allowed, so the extent state tree is expected
2704 * to have one and only one object corresponding to this IO.
2706 static void end_bio_extent_readpage(struct bio *bio)
2708 struct bio_vec *bvec;
2709 int uptodate = !bio->bi_status;
2710 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2711 struct extent_io_tree *tree, *failure_tree;
2716 u64 extent_start = 0;
2720 struct bvec_iter_all iter_all;
2722 ASSERT(!bio_flagged(bio, BIO_CLONED));
2723 bio_for_each_segment_all(bvec, bio, iter_all) {
2724 struct page *page = bvec->bv_page;
2725 struct inode *inode = page->mapping->host;
2726 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2727 bool data_inode = btrfs_ino(BTRFS_I(inode))
2728 != BTRFS_BTREE_INODE_OBJECTID;
2730 btrfs_debug(fs_info,
2731 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2732 (u64)bio->bi_iter.bi_sector, bio->bi_status,
2733 io_bio->mirror_num);
2734 tree = &BTRFS_I(inode)->io_tree;
2735 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2737 /* We always issue full-page reads, but if some block
2738 * in a page fails to read, blk_update_request() will
2739 * advance bv_offset and adjust bv_len to compensate.
2740 * Print a warning for nonzero offsets, and an error
2741 * if they don't add up to a full page. */
2742 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2743 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2745 "partial page read in btrfs with offset %u and length %u",
2746 bvec->bv_offset, bvec->bv_len);
2749 "incomplete page read in btrfs with offset %u and length %u",
2750 bvec->bv_offset, bvec->bv_len);
2753 start = page_offset(page);
2754 end = start + bvec->bv_offset + bvec->bv_len - 1;
2757 mirror = io_bio->mirror_num;
2758 if (likely(uptodate)) {
2759 ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2765 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2766 failure_tree, tree, start,
2768 btrfs_ino(BTRFS_I(inode)), 0);
2771 if (likely(uptodate))
2777 * The generic bio_readpage_error handles errors the
2778 * following way: If possible, new read requests are
2779 * created and submitted and will end up in
2780 * end_bio_extent_readpage as well (if we're lucky,
2781 * not in the !uptodate case). In that case it returns
2782 * 0 and we just go on with the next page in our bio.
2783 * If it can't handle the error it will return -EIO and
2784 * we remain responsible for that page.
2786 ret = bio_readpage_error(bio, offset, page, start, end,
2789 uptodate = !bio->bi_status;
2794 struct extent_buffer *eb;
2796 eb = (struct extent_buffer *)page->private;
2797 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2798 eb->read_mirror = mirror;
2799 atomic_dec(&eb->io_pages);
2800 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2802 btree_readahead_hook(eb, -EIO);
2805 if (likely(uptodate)) {
2806 loff_t i_size = i_size_read(inode);
2807 pgoff_t end_index = i_size >> PAGE_SHIFT;
2810 /* Zero out the end if this page straddles i_size */
2811 off = offset_in_page(i_size);
2812 if (page->index == end_index && off)
2813 zero_user_segment(page, off, PAGE_SIZE);
2814 SetPageUptodate(page);
2816 ClearPageUptodate(page);
2822 if (unlikely(!uptodate)) {
2824 endio_readpage_release_extent(tree,
2830 endio_readpage_release_extent(tree, start,
2831 end - start + 1, 0);
2832 } else if (!extent_len) {
2833 extent_start = start;
2834 extent_len = end + 1 - start;
2835 } else if (extent_start + extent_len == start) {
2836 extent_len += end + 1 - start;
2838 endio_readpage_release_extent(tree, extent_start,
2839 extent_len, uptodate);
2840 extent_start = start;
2841 extent_len = end + 1 - start;
2846 endio_readpage_release_extent(tree, extent_start, extent_len,
2848 btrfs_io_bio_free_csum(io_bio);
2853 * Initialize the members up to but not including 'bio'. Use after allocating a
2854 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2855 * 'bio' because use of __GFP_ZERO is not supported.
2857 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2859 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2863 * The following helpers allocate a bio. As it's backed by a bioset, it'll
2864 * never fail. We're returning a bio right now but you can call btrfs_io_bio
2865 * for the appropriate container_of magic
2867 struct bio *btrfs_bio_alloc(u64 first_byte)
2871 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2872 bio->bi_iter.bi_sector = first_byte >> 9;
2873 btrfs_io_bio_init(btrfs_io_bio(bio));
2877 struct bio *btrfs_bio_clone(struct bio *bio)
2879 struct btrfs_io_bio *btrfs_bio;
2882 /* Bio allocation backed by a bioset does not fail */
2883 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2884 btrfs_bio = btrfs_io_bio(new);
2885 btrfs_io_bio_init(btrfs_bio);
2886 btrfs_bio->iter = bio->bi_iter;
2890 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2894 /* Bio allocation backed by a bioset does not fail */
2895 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2896 btrfs_io_bio_init(btrfs_io_bio(bio));
2900 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2903 struct btrfs_io_bio *btrfs_bio;
2905 /* this will never fail when it's backed by a bioset */
2906 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2909 btrfs_bio = btrfs_io_bio(bio);
2910 btrfs_io_bio_init(btrfs_bio);
2912 bio_trim(bio, offset >> 9, size >> 9);
2913 btrfs_bio->iter = bio->bi_iter;
2918 * @opf: bio REQ_OP_* and REQ_* flags as one value
2919 * @tree: tree so we can call our merge_bio hook
2920 * @wbc: optional writeback control for io accounting
2921 * @page: page to add to the bio
2922 * @pg_offset: offset of the new bio or to check whether we are adding
2923 * a contiguous page to the previous one
2924 * @size: portion of page that we want to write
2925 * @offset: starting offset in the page
2926 * @bdev: attach newly created bios to this bdev
2927 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
2928 * @end_io_func: end_io callback for new bio
2929 * @mirror_num: desired mirror to read/write
2930 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
2931 * @bio_flags: flags of the current bio to see if we can merge them
2933 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2934 struct writeback_control *wbc,
2935 struct page *page, u64 offset,
2936 size_t size, unsigned long pg_offset,
2937 struct block_device *bdev,
2938 struct bio **bio_ret,
2939 bio_end_io_t end_io_func,
2941 unsigned long prev_bio_flags,
2942 unsigned long bio_flags,
2943 bool force_bio_submit)
2947 size_t page_size = min_t(size_t, size, PAGE_SIZE);
2948 sector_t sector = offset >> 9;
2954 bool can_merge = true;
2957 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2958 contig = bio->bi_iter.bi_sector == sector;
2960 contig = bio_end_sector(bio) == sector;
2963 if (btrfs_bio_fits_in_stripe(page, page_size, bio, bio_flags))
2966 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2968 bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2969 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2977 wbc_account_cgroup_owner(wbc, page, page_size);
2982 bio = btrfs_bio_alloc(offset);
2983 bio_set_dev(bio, bdev);
2984 bio_add_page(bio, page, page_size, pg_offset);
2985 bio->bi_end_io = end_io_func;
2986 bio->bi_private = tree;
2987 bio->bi_write_hint = page->mapping->host->i_write_hint;
2990 wbc_init_bio(wbc, bio);
2991 wbc_account_cgroup_owner(wbc, page, page_size);
2999 static void attach_extent_buffer_page(struct extent_buffer *eb,
3002 if (!PagePrivate(page)) {
3003 SetPagePrivate(page);
3005 set_page_private(page, (unsigned long)eb);
3007 WARN_ON(page->private != (unsigned long)eb);
3011 void set_page_extent_mapped(struct page *page)
3013 if (!PagePrivate(page)) {
3014 SetPagePrivate(page);
3016 set_page_private(page, EXTENT_PAGE_PRIVATE);
3020 static struct extent_map *
3021 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3022 u64 start, u64 len, get_extent_t *get_extent,
3023 struct extent_map **em_cached)
3025 struct extent_map *em;
3027 if (em_cached && *em_cached) {
3029 if (extent_map_in_tree(em) && start >= em->start &&
3030 start < extent_map_end(em)) {
3031 refcount_inc(&em->refs);
3035 free_extent_map(em);
3039 em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
3040 if (em_cached && !IS_ERR_OR_NULL(em)) {
3042 refcount_inc(&em->refs);
3048 * basic readpage implementation. Locked extent state structs are inserted
3049 * into the tree that are removed when the IO is done (by the end_io
3051 * XXX JDM: This needs looking at to ensure proper page locking
3052 * return 0 on success, otherwise return error
3054 static int __do_readpage(struct extent_io_tree *tree,
3056 get_extent_t *get_extent,
3057 struct extent_map **em_cached,
3058 struct bio **bio, int mirror_num,
3059 unsigned long *bio_flags, unsigned int read_flags,
3062 struct inode *inode = page->mapping->host;
3063 u64 start = page_offset(page);
3064 const u64 end = start + PAGE_SIZE - 1;
3067 u64 last_byte = i_size_read(inode);
3070 struct extent_map *em;
3071 struct block_device *bdev;
3074 size_t pg_offset = 0;
3076 size_t disk_io_size;
3077 size_t blocksize = inode->i_sb->s_blocksize;
3078 unsigned long this_bio_flag = 0;
3080 set_page_extent_mapped(page);
3082 if (!PageUptodate(page)) {
3083 if (cleancache_get_page(page) == 0) {
3084 BUG_ON(blocksize != PAGE_SIZE);
3085 unlock_extent(tree, start, end);
3090 if (page->index == last_byte >> PAGE_SHIFT) {
3092 size_t zero_offset = offset_in_page(last_byte);
3095 iosize = PAGE_SIZE - zero_offset;
3096 userpage = kmap_atomic(page);
3097 memset(userpage + zero_offset, 0, iosize);
3098 flush_dcache_page(page);
3099 kunmap_atomic(userpage);
3102 while (cur <= end) {
3103 bool force_bio_submit = false;
3106 if (cur >= last_byte) {
3108 struct extent_state *cached = NULL;
3110 iosize = PAGE_SIZE - pg_offset;
3111 userpage = kmap_atomic(page);
3112 memset(userpage + pg_offset, 0, iosize);
3113 flush_dcache_page(page);
3114 kunmap_atomic(userpage);
3115 set_extent_uptodate(tree, cur, cur + iosize - 1,
3117 unlock_extent_cached(tree, cur,
3118 cur + iosize - 1, &cached);
3121 em = __get_extent_map(inode, page, pg_offset, cur,
3122 end - cur + 1, get_extent, em_cached);
3123 if (IS_ERR_OR_NULL(em)) {
3125 unlock_extent(tree, cur, end);
3128 extent_offset = cur - em->start;
3129 BUG_ON(extent_map_end(em) <= cur);
3132 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3133 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3134 extent_set_compress_type(&this_bio_flag,
3138 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3139 cur_end = min(extent_map_end(em) - 1, end);
3140 iosize = ALIGN(iosize, blocksize);
3141 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
3142 disk_io_size = em->block_len;
3143 offset = em->block_start;
3145 offset = em->block_start + extent_offset;
3146 disk_io_size = iosize;
3149 block_start = em->block_start;
3150 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3151 block_start = EXTENT_MAP_HOLE;
3154 * If we have a file range that points to a compressed extent
3155 * and it's followed by a consecutive file range that points
3156 * to the same compressed extent (possibly with a different
3157 * offset and/or length, so it either points to the whole extent
3158 * or only part of it), we must make sure we do not submit a
3159 * single bio to populate the pages for the 2 ranges because
3160 * this makes the compressed extent read zero out the pages
3161 * belonging to the 2nd range. Imagine the following scenario:
3164 * [0 - 8K] [8K - 24K]
3167 * points to extent X, points to extent X,
3168 * offset 4K, length of 8K offset 0, length 16K
3170 * [extent X, compressed length = 4K uncompressed length = 16K]
3172 * If the bio to read the compressed extent covers both ranges,
3173 * it will decompress extent X into the pages belonging to the
3174 * first range and then it will stop, zeroing out the remaining
3175 * pages that belong to the other range that points to extent X.
3176 * So here we make sure we submit 2 bios, one for the first
3177 * range and another one for the third range. Both will target
3178 * the same physical extent from disk, but we can't currently
3179 * make the compressed bio endio callback populate the pages
3180 * for both ranges because each compressed bio is tightly
3181 * coupled with a single extent map, and each range can have
3182 * an extent map with a different offset value relative to the
3183 * uncompressed data of our extent and different lengths. This
3184 * is a corner case so we prioritize correctness over
3185 * non-optimal behavior (submitting 2 bios for the same extent).
3187 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3188 prev_em_start && *prev_em_start != (u64)-1 &&
3189 *prev_em_start != em->start)
3190 force_bio_submit = true;
3193 *prev_em_start = em->start;
3195 free_extent_map(em);
3198 /* we've found a hole, just zero and go on */
3199 if (block_start == EXTENT_MAP_HOLE) {
3201 struct extent_state *cached = NULL;
3203 userpage = kmap_atomic(page);
3204 memset(userpage + pg_offset, 0, iosize);
3205 flush_dcache_page(page);
3206 kunmap_atomic(userpage);
3208 set_extent_uptodate(tree, cur, cur + iosize - 1,
3210 unlock_extent_cached(tree, cur,
3211 cur + iosize - 1, &cached);
3213 pg_offset += iosize;
3216 /* the get_extent function already copied into the page */
3217 if (test_range_bit(tree, cur, cur_end,
3218 EXTENT_UPTODATE, 1, NULL)) {
3219 check_page_uptodate(tree, page);
3220 unlock_extent(tree, cur, cur + iosize - 1);
3222 pg_offset += iosize;
3225 /* we have an inline extent but it didn't get marked up
3226 * to date. Error out
3228 if (block_start == EXTENT_MAP_INLINE) {
3230 unlock_extent(tree, cur, cur + iosize - 1);
3232 pg_offset += iosize;
3236 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3237 page, offset, disk_io_size,
3238 pg_offset, bdev, bio,
3239 end_bio_extent_readpage, mirror_num,
3245 *bio_flags = this_bio_flag;
3248 unlock_extent(tree, cur, cur + iosize - 1);
3252 pg_offset += iosize;
3256 if (!PageError(page))
3257 SetPageUptodate(page);
3263 static inline void contiguous_readpages(struct extent_io_tree *tree,
3264 struct page *pages[], int nr_pages,
3266 struct extent_map **em_cached,
3268 unsigned long *bio_flags,
3271 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3274 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3276 for (index = 0; index < nr_pages; index++) {
3277 __do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3278 bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3279 put_page(pages[index]);
3283 static int __extent_read_full_page(struct extent_io_tree *tree,
3285 get_extent_t *get_extent,
3286 struct bio **bio, int mirror_num,
3287 unsigned long *bio_flags,
3288 unsigned int read_flags)
3290 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3291 u64 start = page_offset(page);
3292 u64 end = start + PAGE_SIZE - 1;
3295 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3297 ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3298 bio_flags, read_flags, NULL);
3302 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3303 get_extent_t *get_extent, int mirror_num)
3305 struct bio *bio = NULL;
3306 unsigned long bio_flags = 0;
3309 ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3312 ret = submit_one_bio(bio, mirror_num, bio_flags);
3316 static void update_nr_written(struct writeback_control *wbc,
3317 unsigned long nr_written)
3319 wbc->nr_to_write -= nr_written;
3323 * helper for __extent_writepage, doing all of the delayed allocation setup.
3325 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3326 * to write the page (copy into inline extent). In this case the IO has
3327 * been started and the page is already unlocked.
3329 * This returns 0 if all went well (page still locked)
3330 * This returns < 0 if there were errors (page still locked)
3332 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3333 struct page *page, struct writeback_control *wbc,
3334 u64 delalloc_start, unsigned long *nr_written)
3336 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3338 u64 delalloc_to_write = 0;
3339 u64 delalloc_end = 0;
3341 int page_started = 0;
3344 while (delalloc_end < page_end) {
3345 found = find_lock_delalloc_range(inode, page,
3349 delalloc_start = delalloc_end + 1;
3352 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3353 delalloc_end, &page_started, nr_written, wbc);
3357 * btrfs_run_delalloc_range should return < 0 for error
3358 * but just in case, we use > 0 here meaning the IO is
3359 * started, so we don't want to return > 0 unless
3360 * things are going well.
3362 ret = ret < 0 ? ret : -EIO;
3366 * delalloc_end is already one less than the total length, so
3367 * we don't subtract one from PAGE_SIZE
3369 delalloc_to_write += (delalloc_end - delalloc_start +
3370 PAGE_SIZE) >> PAGE_SHIFT;
3371 delalloc_start = delalloc_end + 1;
3373 if (wbc->nr_to_write < delalloc_to_write) {
3376 if (delalloc_to_write < thresh * 2)
3377 thresh = delalloc_to_write;
3378 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3382 /* did the fill delalloc function already unlock and start
3387 * we've unlocked the page, so we can't update
3388 * the mapping's writeback index, just update
3391 wbc->nr_to_write -= *nr_written;
3402 * helper for __extent_writepage. This calls the writepage start hooks,
3403 * and does the loop to map the page into extents and bios.
3405 * We return 1 if the IO is started and the page is unlocked,
3406 * 0 if all went well (page still locked)
3407 * < 0 if there were errors (page still locked)
3409 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3411 struct writeback_control *wbc,
3412 struct extent_page_data *epd,
3414 unsigned long nr_written,
3415 unsigned int write_flags, int *nr_ret)
3417 struct extent_io_tree *tree = epd->tree;
3418 u64 start = page_offset(page);
3419 u64 page_end = start + PAGE_SIZE - 1;
3425 struct extent_map *em;
3426 struct block_device *bdev;
3427 size_t pg_offset = 0;
3433 ret = btrfs_writepage_cow_fixup(page, start, page_end);
3435 /* Fixup worker will requeue */
3437 wbc->pages_skipped++;
3439 redirty_page_for_writepage(wbc, page);
3441 update_nr_written(wbc, nr_written);
3447 * we don't want to touch the inode after unlocking the page,
3448 * so we update the mapping writeback index now
3450 update_nr_written(wbc, nr_written + 1);
3453 if (i_size <= start) {
3454 btrfs_writepage_endio_finish_ordered(page, start, page_end, 1);
3458 blocksize = inode->i_sb->s_blocksize;
3460 while (cur <= end) {
3464 if (cur >= i_size) {
3465 btrfs_writepage_endio_finish_ordered(page, cur,
3469 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3471 if (IS_ERR_OR_NULL(em)) {
3473 ret = PTR_ERR_OR_ZERO(em);
3477 extent_offset = cur - em->start;
3478 em_end = extent_map_end(em);
3479 BUG_ON(em_end <= cur);
3481 iosize = min(em_end - cur, end - cur + 1);
3482 iosize = ALIGN(iosize, blocksize);
3483 offset = em->block_start + extent_offset;
3485 block_start = em->block_start;
3486 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3487 free_extent_map(em);
3491 * compressed and inline extents are written through other
3494 if (compressed || block_start == EXTENT_MAP_HOLE ||
3495 block_start == EXTENT_MAP_INLINE) {
3497 * end_io notification does not happen here for
3498 * compressed extents
3501 btrfs_writepage_endio_finish_ordered(page, cur,
3504 else if (compressed) {
3505 /* we don't want to end_page_writeback on
3506 * a compressed extent. this happens
3513 pg_offset += iosize;
3517 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3518 if (!PageWriteback(page)) {
3519 btrfs_err(BTRFS_I(inode)->root->fs_info,
3520 "page %lu not writeback, cur %llu end %llu",
3521 page->index, cur, end);
3524 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3525 page, offset, iosize, pg_offset,
3527 end_bio_extent_writepage,
3531 if (PageWriteback(page))
3532 end_page_writeback(page);
3536 pg_offset += iosize;
3545 * the writepage semantics are similar to regular writepage. extent
3546 * records are inserted to lock ranges in the tree, and as dirty areas
3547 * are found, they are marked writeback. Then the lock bits are removed
3548 * and the end_io handler clears the writeback ranges
3550 * Return 0 if everything goes well.
3551 * Return <0 for error.
3553 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3554 struct extent_page_data *epd)
3556 struct inode *inode = page->mapping->host;
3557 u64 start = page_offset(page);
3558 u64 page_end = start + PAGE_SIZE - 1;
3561 size_t pg_offset = 0;
3562 loff_t i_size = i_size_read(inode);
3563 unsigned long end_index = i_size >> PAGE_SHIFT;
3564 unsigned int write_flags = 0;
3565 unsigned long nr_written = 0;
3567 write_flags = wbc_to_write_flags(wbc);
3569 trace___extent_writepage(page, inode, wbc);
3571 WARN_ON(!PageLocked(page));
3573 ClearPageError(page);
3575 pg_offset = offset_in_page(i_size);
3576 if (page->index > end_index ||
3577 (page->index == end_index && !pg_offset)) {
3578 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3583 if (page->index == end_index) {
3586 userpage = kmap_atomic(page);
3587 memset(userpage + pg_offset, 0,
3588 PAGE_SIZE - pg_offset);
3589 kunmap_atomic(userpage);
3590 flush_dcache_page(page);
3595 set_page_extent_mapped(page);
3597 if (!epd->extent_locked) {
3598 ret = writepage_delalloc(inode, page, wbc, start, &nr_written);
3605 ret = __extent_writepage_io(inode, page, wbc, epd,
3606 i_size, nr_written, write_flags, &nr);
3612 /* make sure the mapping tag for page dirty gets cleared */
3613 set_page_writeback(page);
3614 end_page_writeback(page);
3616 if (PageError(page)) {
3617 ret = ret < 0 ? ret : -EIO;
3618 end_extent_writepage(page, ret, start, page_end);
3628 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3630 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3631 TASK_UNINTERRUPTIBLE);
3634 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3636 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3637 smp_mb__after_atomic();
3638 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3642 * Lock eb pages and flush the bio if we can't the locks
3644 * Return 0 if nothing went wrong
3645 * Return >0 is same as 0, except bio is not submitted
3646 * Return <0 if something went wrong, no page is locked
3648 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3649 struct extent_page_data *epd)
3651 struct btrfs_fs_info *fs_info = eb->fs_info;
3652 int i, num_pages, failed_page_nr;
3656 if (!btrfs_try_tree_write_lock(eb)) {
3657 ret = flush_write_bio(epd);
3661 btrfs_tree_lock(eb);
3664 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3665 btrfs_tree_unlock(eb);
3669 ret = flush_write_bio(epd);
3675 wait_on_extent_buffer_writeback(eb);
3676 btrfs_tree_lock(eb);
3677 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3679 btrfs_tree_unlock(eb);
3684 * We need to do this to prevent races in people who check if the eb is
3685 * under IO since we can end up having no IO bits set for a short period
3688 spin_lock(&eb->refs_lock);
3689 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3690 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3691 spin_unlock(&eb->refs_lock);
3692 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3693 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3695 fs_info->dirty_metadata_batch);
3698 spin_unlock(&eb->refs_lock);
3701 btrfs_tree_unlock(eb);
3706 num_pages = num_extent_pages(eb);
3707 for (i = 0; i < num_pages; i++) {
3708 struct page *p = eb->pages[i];
3710 if (!trylock_page(p)) {
3714 err = flush_write_bio(epd);
3728 /* Unlock already locked pages */
3729 for (i = 0; i < failed_page_nr; i++)
3730 unlock_page(eb->pages[i]);
3732 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3733 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3734 * be made and undo everything done before.
3736 btrfs_tree_lock(eb);
3737 spin_lock(&eb->refs_lock);
3738 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3739 end_extent_buffer_writeback(eb);
3740 spin_unlock(&eb->refs_lock);
3741 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3742 fs_info->dirty_metadata_batch);
3743 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3744 btrfs_tree_unlock(eb);
3748 static void set_btree_ioerr(struct page *page)
3750 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3751 struct btrfs_fs_info *fs_info;
3754 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3758 * A read may stumble upon this buffer later, make sure that it gets an
3759 * error and knows there was an error.
3761 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3764 * If we error out, we should add back the dirty_metadata_bytes
3765 * to make it consistent.
3767 fs_info = eb->fs_info;
3768 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3769 eb->len, fs_info->dirty_metadata_batch);
3772 * If writeback for a btree extent that doesn't belong to a log tree
3773 * failed, increment the counter transaction->eb_write_errors.
3774 * We do this because while the transaction is running and before it's
3775 * committing (when we call filemap_fdata[write|wait]_range against
3776 * the btree inode), we might have
3777 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3778 * returns an error or an error happens during writeback, when we're
3779 * committing the transaction we wouldn't know about it, since the pages
3780 * can be no longer dirty nor marked anymore for writeback (if a
3781 * subsequent modification to the extent buffer didn't happen before the
3782 * transaction commit), which makes filemap_fdata[write|wait]_range not
3783 * able to find the pages tagged with SetPageError at transaction
3784 * commit time. So if this happens we must abort the transaction,
3785 * otherwise we commit a super block with btree roots that point to
3786 * btree nodes/leafs whose content on disk is invalid - either garbage
3787 * or the content of some node/leaf from a past generation that got
3788 * cowed or deleted and is no longer valid.
3790 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3791 * not be enough - we need to distinguish between log tree extents vs
3792 * non-log tree extents, and the next filemap_fdatawait_range() call
3793 * will catch and clear such errors in the mapping - and that call might
3794 * be from a log sync and not from a transaction commit. Also, checking
3795 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3796 * not done and would not be reliable - the eb might have been released
3797 * from memory and reading it back again means that flag would not be
3798 * set (since it's a runtime flag, not persisted on disk).
3800 * Using the flags below in the btree inode also makes us achieve the
3801 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3802 * writeback for all dirty pages and before filemap_fdatawait_range()
3803 * is called, the writeback for all dirty pages had already finished
3804 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3805 * filemap_fdatawait_range() would return success, as it could not know
3806 * that writeback errors happened (the pages were no longer tagged for
3809 switch (eb->log_index) {
3811 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3814 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3817 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3820 BUG(); /* unexpected, logic error */
3824 static void end_bio_extent_buffer_writepage(struct bio *bio)
3826 struct bio_vec *bvec;
3827 struct extent_buffer *eb;
3829 struct bvec_iter_all iter_all;
3831 ASSERT(!bio_flagged(bio, BIO_CLONED));
3832 bio_for_each_segment_all(bvec, bio, iter_all) {
3833 struct page *page = bvec->bv_page;
3835 eb = (struct extent_buffer *)page->private;
3837 done = atomic_dec_and_test(&eb->io_pages);
3839 if (bio->bi_status ||
3840 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3841 ClearPageUptodate(page);
3842 set_btree_ioerr(page);
3845 end_page_writeback(page);
3850 end_extent_buffer_writeback(eb);
3856 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3857 struct writeback_control *wbc,
3858 struct extent_page_data *epd)
3860 struct btrfs_fs_info *fs_info = eb->fs_info;
3861 struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3862 struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3863 u64 offset = eb->start;
3866 unsigned long start, end;
3867 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3870 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3871 num_pages = num_extent_pages(eb);
3872 atomic_set(&eb->io_pages, num_pages);
3874 /* set btree blocks beyond nritems with 0 to avoid stale content. */
3875 nritems = btrfs_header_nritems(eb);
3876 if (btrfs_header_level(eb) > 0) {
3877 end = btrfs_node_key_ptr_offset(nritems);
3879 memzero_extent_buffer(eb, end, eb->len - end);
3883 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3885 start = btrfs_item_nr_offset(nritems);
3886 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
3887 memzero_extent_buffer(eb, start, end - start);
3890 for (i = 0; i < num_pages; i++) {
3891 struct page *p = eb->pages[i];
3893 clear_page_dirty_for_io(p);
3894 set_page_writeback(p);
3895 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3896 p, offset, PAGE_SIZE, 0, bdev,
3898 end_bio_extent_buffer_writepage,
3902 if (PageWriteback(p))
3903 end_page_writeback(p);
3904 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3905 end_extent_buffer_writeback(eb);
3909 offset += PAGE_SIZE;
3910 update_nr_written(wbc, 1);
3914 if (unlikely(ret)) {
3915 for (; i < num_pages; i++) {
3916 struct page *p = eb->pages[i];
3917 clear_page_dirty_for_io(p);
3925 int btree_write_cache_pages(struct address_space *mapping,
3926 struct writeback_control *wbc)
3928 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3929 struct extent_buffer *eb, *prev_eb = NULL;
3930 struct extent_page_data epd = {
3934 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3936 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3939 int nr_to_write_done = 0;
3940 struct pagevec pvec;
3943 pgoff_t end; /* Inclusive */
3947 pagevec_init(&pvec);
3948 if (wbc->range_cyclic) {
3949 index = mapping->writeback_index; /* Start from prev offset */
3952 * Start from the beginning does not need to cycle over the
3953 * range, mark it as scanned.
3955 scanned = (index == 0);
3957 index = wbc->range_start >> PAGE_SHIFT;
3958 end = wbc->range_end >> PAGE_SHIFT;
3961 if (wbc->sync_mode == WB_SYNC_ALL)
3962 tag = PAGECACHE_TAG_TOWRITE;
3964 tag = PAGECACHE_TAG_DIRTY;
3966 if (wbc->sync_mode == WB_SYNC_ALL)
3967 tag_pages_for_writeback(mapping, index, end);
3968 while (!done && !nr_to_write_done && (index <= end) &&
3969 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3973 for (i = 0; i < nr_pages; i++) {
3974 struct page *page = pvec.pages[i];
3976 if (!PagePrivate(page))
3979 spin_lock(&mapping->private_lock);
3980 if (!PagePrivate(page)) {
3981 spin_unlock(&mapping->private_lock);
3985 eb = (struct extent_buffer *)page->private;
3988 * Shouldn't happen and normally this would be a BUG_ON
3989 * but no sense in crashing the users box for something
3990 * we can survive anyway.
3993 spin_unlock(&mapping->private_lock);
3997 if (eb == prev_eb) {
3998 spin_unlock(&mapping->private_lock);
4002 ret = atomic_inc_not_zero(&eb->refs);
4003 spin_unlock(&mapping->private_lock);
4008 ret = lock_extent_buffer_for_io(eb, &epd);
4010 free_extent_buffer(eb);
4012 } else if (ret < 0) {
4014 free_extent_buffer(eb);
4018 ret = write_one_eb(eb, wbc, &epd);
4021 free_extent_buffer(eb);
4024 free_extent_buffer(eb);
4027 * The filesystem may choose to bump up nr_to_write.
4028 * We have to make sure to honor the new nr_to_write
4031 nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
4032 wbc->nr_to_write <= 0);
4034 pagevec_release(&pvec);
4037 if (!scanned && !done) {
4039 * We hit the last page and there is more work to be done: wrap
4040 * back to the start of the file
4048 end_write_bio(&epd, ret);
4052 * If something went wrong, don't allow any metadata write bio to be
4055 * This would prevent use-after-free if we had dirty pages not
4056 * cleaned up, which can still happen by fuzzed images.
4059 * Allowing existing tree block to be allocated for other trees.
4061 * - Log tree operations
4062 * Exiting tree blocks get allocated to log tree, bumps its
4063 * generation, then get cleaned in tree re-balance.
4064 * Such tree block will not be written back, since it's clean,
4065 * thus no WRITTEN flag set.
4066 * And after log writes back, this tree block is not traced by
4067 * any dirty extent_io_tree.
4069 * - Offending tree block gets re-dirtied from its original owner
4070 * Since it has bumped generation, no WRITTEN flag, it can be
4071 * reused without COWing. This tree block will not be traced
4072 * by btrfs_transaction::dirty_pages.
4074 * Now such dirty tree block will not be cleaned by any dirty
4075 * extent io tree. Thus we don't want to submit such wild eb
4076 * if the fs already has error.
4078 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4079 ret = flush_write_bio(&epd);
4082 end_write_bio(&epd, ret);
4088 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
4089 * @mapping: address space structure to write
4090 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4091 * @data: data passed to __extent_writepage function
4093 * If a page is already under I/O, write_cache_pages() skips it, even
4094 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4095 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4096 * and msync() need to guarantee that all the data which was dirty at the time
4097 * the call was made get new I/O started against them. If wbc->sync_mode is
4098 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4099 * existing IO to complete.
4101 static int extent_write_cache_pages(struct address_space *mapping,
4102 struct writeback_control *wbc,
4103 struct extent_page_data *epd)
4105 struct inode *inode = mapping->host;
4108 int nr_to_write_done = 0;
4109 struct pagevec pvec;
4112 pgoff_t end; /* Inclusive */
4114 int range_whole = 0;
4119 * We have to hold onto the inode so that ordered extents can do their
4120 * work when the IO finishes. The alternative to this is failing to add
4121 * an ordered extent if the igrab() fails there and that is a huge pain
4122 * to deal with, so instead just hold onto the inode throughout the
4123 * writepages operation. If it fails here we are freeing up the inode
4124 * anyway and we'd rather not waste our time writing out stuff that is
4125 * going to be truncated anyway.
4130 pagevec_init(&pvec);
4131 if (wbc->range_cyclic) {
4132 index = mapping->writeback_index; /* Start from prev offset */
4135 * Start from the beginning does not need to cycle over the
4136 * range, mark it as scanned.
4138 scanned = (index == 0);
4140 index = wbc->range_start >> PAGE_SHIFT;
4141 end = wbc->range_end >> PAGE_SHIFT;
4142 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4148 * We do the tagged writepage as long as the snapshot flush bit is set
4149 * and we are the first one who do the filemap_flush() on this inode.
4151 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4152 * not race in and drop the bit.
4154 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4155 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4156 &BTRFS_I(inode)->runtime_flags))
4157 wbc->tagged_writepages = 1;
4159 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4160 tag = PAGECACHE_TAG_TOWRITE;
4162 tag = PAGECACHE_TAG_DIRTY;
4164 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4165 tag_pages_for_writeback(mapping, index, end);
4167 while (!done && !nr_to_write_done && (index <= end) &&
4168 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4169 &index, end, tag))) {
4172 for (i = 0; i < nr_pages; i++) {
4173 struct page *page = pvec.pages[i];
4175 done_index = page->index + 1;
4177 * At this point we hold neither the i_pages lock nor
4178 * the page lock: the page may be truncated or
4179 * invalidated (changing page->mapping to NULL),
4180 * or even swizzled back from swapper_space to
4181 * tmpfs file mapping
4183 if (!trylock_page(page)) {
4184 ret = flush_write_bio(epd);
4189 if (unlikely(page->mapping != mapping)) {
4194 if (wbc->sync_mode != WB_SYNC_NONE) {
4195 if (PageWriteback(page)) {
4196 ret = flush_write_bio(epd);
4199 wait_on_page_writeback(page);
4202 if (PageWriteback(page) ||
4203 !clear_page_dirty_for_io(page)) {
4208 ret = __extent_writepage(page, wbc, epd);
4215 * the filesystem may choose to bump up nr_to_write.
4216 * We have to make sure to honor the new nr_to_write
4219 nr_to_write_done = wbc->nr_to_write <= 0;
4221 pagevec_release(&pvec);
4224 if (!scanned && !done) {
4226 * We hit the last page and there is more work to be done: wrap
4227 * back to the start of the file
4233 * If we're looping we could run into a page that is locked by a
4234 * writer and that writer could be waiting on writeback for a
4235 * page in our current bio, and thus deadlock, so flush the
4238 ret = flush_write_bio(epd);
4243 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4244 mapping->writeback_index = done_index;
4246 btrfs_add_delayed_iput(inode);
4250 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4253 struct extent_page_data epd = {
4255 .tree = &BTRFS_I(page->mapping->host)->io_tree,
4257 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4260 ret = __extent_writepage(page, wbc, &epd);
4263 end_write_bio(&epd, ret);
4267 ret = flush_write_bio(&epd);
4272 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4276 struct address_space *mapping = inode->i_mapping;
4277 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4279 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4282 struct extent_page_data epd = {
4286 .sync_io = mode == WB_SYNC_ALL,
4288 struct writeback_control wbc_writepages = {
4290 .nr_to_write = nr_pages * 2,
4291 .range_start = start,
4292 .range_end = end + 1,
4295 while (start <= end) {
4296 page = find_get_page(mapping, start >> PAGE_SHIFT);
4297 if (clear_page_dirty_for_io(page))
4298 ret = __extent_writepage(page, &wbc_writepages, &epd);
4300 btrfs_writepage_endio_finish_ordered(page, start,
4301 start + PAGE_SIZE - 1, 1);
4310 end_write_bio(&epd, ret);
4313 ret = flush_write_bio(&epd);
4317 int extent_writepages(struct address_space *mapping,
4318 struct writeback_control *wbc)
4321 struct extent_page_data epd = {
4323 .tree = &BTRFS_I(mapping->host)->io_tree,
4325 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4328 ret = extent_write_cache_pages(mapping, wbc, &epd);
4331 end_write_bio(&epd, ret);
4334 ret = flush_write_bio(&epd);
4338 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4341 struct bio *bio = NULL;
4342 unsigned long bio_flags = 0;
4343 struct page *pagepool[16];
4344 struct extent_map *em_cached = NULL;
4345 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4347 u64 prev_em_start = (u64)-1;
4349 while (!list_empty(pages)) {
4352 for (nr = 0; nr < ARRAY_SIZE(pagepool) && !list_empty(pages);) {
4353 struct page *page = lru_to_page(pages);
4355 prefetchw(&page->flags);
4356 list_del(&page->lru);
4357 if (add_to_page_cache_lru(page, mapping, page->index,
4358 readahead_gfp_mask(mapping))) {
4363 pagepool[nr++] = page;
4364 contig_end = page_offset(page) + PAGE_SIZE - 1;
4368 u64 contig_start = page_offset(pagepool[0]);
4370 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4372 contiguous_readpages(tree, pagepool, nr, contig_start,
4373 contig_end, &em_cached, &bio, &bio_flags,
4379 free_extent_map(em_cached);
4382 return submit_one_bio(bio, 0, bio_flags);
4387 * basic invalidatepage code, this waits on any locked or writeback
4388 * ranges corresponding to the page, and then deletes any extent state
4389 * records from the tree
4391 int extent_invalidatepage(struct extent_io_tree *tree,
4392 struct page *page, unsigned long offset)
4394 struct extent_state *cached_state = NULL;
4395 u64 start = page_offset(page);
4396 u64 end = start + PAGE_SIZE - 1;
4397 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4399 start += ALIGN(offset, blocksize);
4403 lock_extent_bits(tree, start, end, &cached_state);
4404 wait_on_page_writeback(page);
4405 clear_extent_bit(tree, start, end, EXTENT_LOCKED | EXTENT_DELALLOC |
4406 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state);
4411 * a helper for releasepage, this tests for areas of the page that
4412 * are locked or under IO and drops the related state bits if it is safe
4415 static int try_release_extent_state(struct extent_io_tree *tree,
4416 struct page *page, gfp_t mask)
4418 u64 start = page_offset(page);
4419 u64 end = start + PAGE_SIZE - 1;
4422 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4426 * at this point we can safely clear everything except the
4427 * locked bit and the nodatasum bit
4429 ret = __clear_extent_bit(tree, start, end,
4430 ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4431 0, 0, NULL, mask, NULL);
4433 /* if clear_extent_bit failed for enomem reasons,
4434 * we can't allow the release to continue.
4445 * a helper for releasepage. As long as there are no locked extents
4446 * in the range corresponding to the page, both state records and extent
4447 * map records are removed
4449 int try_release_extent_mapping(struct page *page, gfp_t mask)
4451 struct extent_map *em;
4452 u64 start = page_offset(page);
4453 u64 end = start + PAGE_SIZE - 1;
4454 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4455 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4456 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4458 if (gfpflags_allow_blocking(mask) &&
4459 page->mapping->host->i_size > SZ_16M) {
4461 while (start <= end) {
4462 len = end - start + 1;
4463 write_lock(&map->lock);
4464 em = lookup_extent_mapping(map, start, len);
4466 write_unlock(&map->lock);
4469 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4470 em->start != start) {
4471 write_unlock(&map->lock);
4472 free_extent_map(em);
4475 if (test_range_bit(tree, em->start,
4476 extent_map_end(em) - 1,
4477 EXTENT_LOCKED, 0, NULL))
4480 * If it's not in the list of modified extents, used
4481 * by a fast fsync, we can remove it. If it's being
4482 * logged we can safely remove it since fsync took an
4483 * extra reference on the em.
4485 if (list_empty(&em->list) ||
4486 test_bit(EXTENT_FLAG_LOGGING, &em->flags)) {
4487 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4488 &btrfs_inode->runtime_flags);
4489 remove_extent_mapping(map, em);
4490 /* once for the rb tree */
4491 free_extent_map(em);
4494 start = extent_map_end(em);
4495 write_unlock(&map->lock);
4498 free_extent_map(em);
4500 cond_resched(); /* Allow large-extent preemption. */
4503 return try_release_extent_state(tree, page, mask);
4507 * helper function for fiemap, which doesn't want to see any holes.
4508 * This maps until we find something past 'last'
4510 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4511 u64 offset, u64 last)
4513 u64 sectorsize = btrfs_inode_sectorsize(inode);
4514 struct extent_map *em;
4521 len = last - offset;
4524 len = ALIGN(len, sectorsize);
4525 em = btrfs_get_extent_fiemap(BTRFS_I(inode), offset, len);
4526 if (IS_ERR_OR_NULL(em))
4529 /* if this isn't a hole return it */
4530 if (em->block_start != EXTENT_MAP_HOLE)
4533 /* this is a hole, advance to the next extent */
4534 offset = extent_map_end(em);
4535 free_extent_map(em);
4543 * To cache previous fiemap extent
4545 * Will be used for merging fiemap extent
4547 struct fiemap_cache {
4556 * Helper to submit fiemap extent.
4558 * Will try to merge current fiemap extent specified by @offset, @phys,
4559 * @len and @flags with cached one.
4560 * And only when we fails to merge, cached one will be submitted as
4563 * Return value is the same as fiemap_fill_next_extent().
4565 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4566 struct fiemap_cache *cache,
4567 u64 offset, u64 phys, u64 len, u32 flags)
4575 * Sanity check, extent_fiemap() should have ensured that new
4576 * fiemap extent won't overlap with cached one.
4579 * NOTE: Physical address can overlap, due to compression
4581 if (cache->offset + cache->len > offset) {
4587 * Only merges fiemap extents if
4588 * 1) Their logical addresses are continuous
4590 * 2) Their physical addresses are continuous
4591 * So truly compressed (physical size smaller than logical size)
4592 * extents won't get merged with each other
4594 * 3) Share same flags except FIEMAP_EXTENT_LAST
4595 * So regular extent won't get merged with prealloc extent
4597 if (cache->offset + cache->len == offset &&
4598 cache->phys + cache->len == phys &&
4599 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4600 (flags & ~FIEMAP_EXTENT_LAST)) {
4602 cache->flags |= flags;
4603 goto try_submit_last;
4606 /* Not mergeable, need to submit cached one */
4607 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4608 cache->len, cache->flags);
4609 cache->cached = false;
4613 cache->cached = true;
4614 cache->offset = offset;
4617 cache->flags = flags;
4619 if (cache->flags & FIEMAP_EXTENT_LAST) {
4620 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4621 cache->phys, cache->len, cache->flags);
4622 cache->cached = false;
4628 * Emit last fiemap cache
4630 * The last fiemap cache may still be cached in the following case:
4632 * |<- Fiemap range ->|
4633 * |<------------ First extent ----------->|
4635 * In this case, the first extent range will be cached but not emitted.
4636 * So we must emit it before ending extent_fiemap().
4638 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4639 struct fiemap_cache *cache)
4646 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4647 cache->len, cache->flags);
4648 cache->cached = false;
4654 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4655 __u64 start, __u64 len)
4659 u64 max = start + len;
4663 u64 last_for_get_extent = 0;
4665 u64 isize = i_size_read(inode);
4666 struct btrfs_key found_key;
4667 struct extent_map *em = NULL;
4668 struct extent_state *cached_state = NULL;
4669 struct btrfs_path *path;
4670 struct btrfs_root *root = BTRFS_I(inode)->root;
4671 struct fiemap_cache cache = { 0 };
4672 struct ulist *roots;
4673 struct ulist *tmp_ulist;
4682 path = btrfs_alloc_path();
4685 path->leave_spinning = 1;
4687 roots = ulist_alloc(GFP_KERNEL);
4688 tmp_ulist = ulist_alloc(GFP_KERNEL);
4689 if (!roots || !tmp_ulist) {
4691 goto out_free_ulist;
4695 * We can't initialize that to 'start' as this could miss extents due
4696 * to extent item merging
4699 start = round_down(start, btrfs_inode_sectorsize(inode));
4700 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4703 * lookup the last file extent. We're not using i_size here
4704 * because there might be preallocation past i_size
4706 ret = btrfs_lookup_file_extent(NULL, root, path,
4707 btrfs_ino(BTRFS_I(inode)), -1, 0);
4709 goto out_free_ulist;
4717 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4718 found_type = found_key.type;
4720 /* No extents, but there might be delalloc bits */
4721 if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4722 found_type != BTRFS_EXTENT_DATA_KEY) {
4723 /* have to trust i_size as the end */
4725 last_for_get_extent = isize;
4728 * remember the start of the last extent. There are a
4729 * bunch of different factors that go into the length of the
4730 * extent, so its much less complex to remember where it started
4732 last = found_key.offset;
4733 last_for_get_extent = last + 1;
4735 btrfs_release_path(path);
4738 * we might have some extents allocated but more delalloc past those
4739 * extents. so, we trust isize unless the start of the last extent is
4744 last_for_get_extent = isize;
4747 lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4750 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4759 u64 offset_in_extent = 0;
4761 /* break if the extent we found is outside the range */
4762 if (em->start >= max || extent_map_end(em) < off)
4766 * get_extent may return an extent that starts before our
4767 * requested range. We have to make sure the ranges
4768 * we return to fiemap always move forward and don't
4769 * overlap, so adjust the offsets here
4771 em_start = max(em->start, off);
4774 * record the offset from the start of the extent
4775 * for adjusting the disk offset below. Only do this if the
4776 * extent isn't compressed since our in ram offset may be past
4777 * what we have actually allocated on disk.
4779 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4780 offset_in_extent = em_start - em->start;
4781 em_end = extent_map_end(em);
4782 em_len = em_end - em_start;
4784 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4785 disko = em->block_start + offset_in_extent;
4790 * bump off for our next call to get_extent
4792 off = extent_map_end(em);
4796 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4798 flags |= FIEMAP_EXTENT_LAST;
4799 } else if (em->block_start == EXTENT_MAP_INLINE) {
4800 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4801 FIEMAP_EXTENT_NOT_ALIGNED);
4802 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4803 flags |= (FIEMAP_EXTENT_DELALLOC |
4804 FIEMAP_EXTENT_UNKNOWN);
4805 } else if (fieinfo->fi_extents_max) {
4806 u64 bytenr = em->block_start -
4807 (em->start - em->orig_start);
4810 * As btrfs supports shared space, this information
4811 * can be exported to userspace tools via
4812 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4813 * then we're just getting a count and we can skip the
4816 ret = btrfs_check_shared(root,
4817 btrfs_ino(BTRFS_I(inode)),
4818 bytenr, roots, tmp_ulist);
4822 flags |= FIEMAP_EXTENT_SHARED;
4825 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4826 flags |= FIEMAP_EXTENT_ENCODED;
4827 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4828 flags |= FIEMAP_EXTENT_UNWRITTEN;
4830 free_extent_map(em);
4832 if ((em_start >= last) || em_len == (u64)-1 ||
4833 (last == (u64)-1 && isize <= em_end)) {
4834 flags |= FIEMAP_EXTENT_LAST;
4838 /* now scan forward to see if this is really the last extent. */
4839 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4845 flags |= FIEMAP_EXTENT_LAST;
4848 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4858 ret = emit_last_fiemap_cache(fieinfo, &cache);
4859 free_extent_map(em);
4861 unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4865 btrfs_free_path(path);
4867 ulist_free(tmp_ulist);
4871 static void __free_extent_buffer(struct extent_buffer *eb)
4873 btrfs_leak_debug_del(&eb->leak_list);
4874 kmem_cache_free(extent_buffer_cache, eb);
4877 int extent_buffer_under_io(struct extent_buffer *eb)
4879 return (atomic_read(&eb->io_pages) ||
4880 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4881 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4885 * Release all pages attached to the extent buffer.
4887 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4891 int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4893 BUG_ON(extent_buffer_under_io(eb));
4895 num_pages = num_extent_pages(eb);
4896 for (i = 0; i < num_pages; i++) {
4897 struct page *page = eb->pages[i];
4902 spin_lock(&page->mapping->private_lock);
4904 * We do this since we'll remove the pages after we've
4905 * removed the eb from the radix tree, so we could race
4906 * and have this page now attached to the new eb. So
4907 * only clear page_private if it's still connected to
4910 if (PagePrivate(page) &&
4911 page->private == (unsigned long)eb) {
4912 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4913 BUG_ON(PageDirty(page));
4914 BUG_ON(PageWriteback(page));
4916 * We need to make sure we haven't be attached
4919 ClearPagePrivate(page);
4920 set_page_private(page, 0);
4921 /* One for the page private */
4926 spin_unlock(&page->mapping->private_lock);
4928 /* One for when we allocated the page */
4934 * Helper for releasing the extent buffer.
4936 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4938 btrfs_release_extent_buffer_pages(eb);
4939 __free_extent_buffer(eb);
4942 static struct extent_buffer *
4943 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4946 struct extent_buffer *eb = NULL;
4948 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4951 eb->fs_info = fs_info;
4953 rwlock_init(&eb->lock);
4954 atomic_set(&eb->blocking_readers, 0);
4955 eb->blocking_writers = 0;
4956 eb->lock_nested = false;
4957 init_waitqueue_head(&eb->write_lock_wq);
4958 init_waitqueue_head(&eb->read_lock_wq);
4960 btrfs_leak_debug_add(&eb->leak_list, &buffers);
4962 spin_lock_init(&eb->refs_lock);
4963 atomic_set(&eb->refs, 1);
4964 atomic_set(&eb->io_pages, 0);
4967 * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4969 BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4970 > MAX_INLINE_EXTENT_BUFFER_SIZE);
4971 BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4973 #ifdef CONFIG_BTRFS_DEBUG
4974 eb->spinning_writers = 0;
4975 atomic_set(&eb->spinning_readers, 0);
4976 atomic_set(&eb->read_locks, 0);
4977 eb->write_locks = 0;
4983 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4987 struct extent_buffer *new;
4988 int num_pages = num_extent_pages(src);
4990 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4994 for (i = 0; i < num_pages; i++) {
4995 p = alloc_page(GFP_NOFS);
4997 btrfs_release_extent_buffer(new);
5000 attach_extent_buffer_page(new, p);
5001 WARN_ON(PageDirty(p));
5004 copy_page(page_address(p), page_address(src->pages[i]));
5007 set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
5008 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5013 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5014 u64 start, unsigned long len)
5016 struct extent_buffer *eb;
5020 eb = __alloc_extent_buffer(fs_info, start, len);
5024 num_pages = num_extent_pages(eb);
5025 for (i = 0; i < num_pages; i++) {
5026 eb->pages[i] = alloc_page(GFP_NOFS);
5030 set_extent_buffer_uptodate(eb);
5031 btrfs_set_header_nritems(eb, 0);
5032 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5037 __free_page(eb->pages[i - 1]);
5038 __free_extent_buffer(eb);
5042 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5045 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5048 static void check_buffer_tree_ref(struct extent_buffer *eb)
5052 * The TREE_REF bit is first set when the extent_buffer is added
5053 * to the radix tree. It is also reset, if unset, when a new reference
5054 * is created by find_extent_buffer.
5056 * It is only cleared in two cases: freeing the last non-tree
5057 * reference to the extent_buffer when its STALE bit is set or
5058 * calling releasepage when the tree reference is the only reference.
5060 * In both cases, care is taken to ensure that the extent_buffer's
5061 * pages are not under io. However, releasepage can be concurrently
5062 * called with creating new references, which is prone to race
5063 * conditions between the calls to check_buffer_tree_ref in those
5064 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5066 * The actual lifetime of the extent_buffer in the radix tree is
5067 * adequately protected by the refcount, but the TREE_REF bit and
5068 * its corresponding reference are not. To protect against this
5069 * class of races, we call check_buffer_tree_ref from the codepaths
5070 * which trigger io after they set eb->io_pages. Note that once io is
5071 * initiated, TREE_REF can no longer be cleared, so that is the
5072 * moment at which any such race is best fixed.
5074 refs = atomic_read(&eb->refs);
5075 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5078 spin_lock(&eb->refs_lock);
5079 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5080 atomic_inc(&eb->refs);
5081 spin_unlock(&eb->refs_lock);
5084 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5085 struct page *accessed)
5089 check_buffer_tree_ref(eb);
5091 num_pages = num_extent_pages(eb);
5092 for (i = 0; i < num_pages; i++) {
5093 struct page *p = eb->pages[i];
5096 mark_page_accessed(p);
5100 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5103 struct extent_buffer *eb;
5106 eb = radix_tree_lookup(&fs_info->buffer_radix,
5107 start >> PAGE_SHIFT);
5108 if (eb && atomic_inc_not_zero(&eb->refs)) {
5111 * Lock our eb's refs_lock to avoid races with
5112 * free_extent_buffer. When we get our eb it might be flagged
5113 * with EXTENT_BUFFER_STALE and another task running
5114 * free_extent_buffer might have seen that flag set,
5115 * eb->refs == 2, that the buffer isn't under IO (dirty and
5116 * writeback flags not set) and it's still in the tree (flag
5117 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5118 * of decrementing the extent buffer's reference count twice.
5119 * So here we could race and increment the eb's reference count,
5120 * clear its stale flag, mark it as dirty and drop our reference
5121 * before the other task finishes executing free_extent_buffer,
5122 * which would later result in an attempt to free an extent
5123 * buffer that is dirty.
5125 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5126 spin_lock(&eb->refs_lock);
5127 spin_unlock(&eb->refs_lock);
5129 mark_extent_buffer_accessed(eb, NULL);
5137 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5138 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5141 struct extent_buffer *eb, *exists = NULL;
5144 eb = find_extent_buffer(fs_info, start);
5147 eb = alloc_dummy_extent_buffer(fs_info, start);
5149 return ERR_PTR(-ENOMEM);
5150 eb->fs_info = fs_info;
5152 ret = radix_tree_preload(GFP_NOFS);
5154 exists = ERR_PTR(ret);
5157 spin_lock(&fs_info->buffer_lock);
5158 ret = radix_tree_insert(&fs_info->buffer_radix,
5159 start >> PAGE_SHIFT, eb);
5160 spin_unlock(&fs_info->buffer_lock);
5161 radix_tree_preload_end();
5162 if (ret == -EEXIST) {
5163 exists = find_extent_buffer(fs_info, start);
5169 check_buffer_tree_ref(eb);
5170 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5174 btrfs_release_extent_buffer(eb);
5179 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5182 unsigned long len = fs_info->nodesize;
5185 unsigned long index = start >> PAGE_SHIFT;
5186 struct extent_buffer *eb;
5187 struct extent_buffer *exists = NULL;
5189 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5193 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5194 btrfs_err(fs_info, "bad tree block start %llu", start);
5195 return ERR_PTR(-EINVAL);
5198 eb = find_extent_buffer(fs_info, start);
5202 eb = __alloc_extent_buffer(fs_info, start, len);
5204 return ERR_PTR(-ENOMEM);
5206 num_pages = num_extent_pages(eb);
5207 for (i = 0; i < num_pages; i++, index++) {
5208 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5210 exists = ERR_PTR(-ENOMEM);
5214 spin_lock(&mapping->private_lock);
5215 if (PagePrivate(p)) {
5217 * We could have already allocated an eb for this page
5218 * and attached one so lets see if we can get a ref on
5219 * the existing eb, and if we can we know it's good and
5220 * we can just return that one, else we know we can just
5221 * overwrite page->private.
5223 exists = (struct extent_buffer *)p->private;
5224 if (atomic_inc_not_zero(&exists->refs)) {
5225 spin_unlock(&mapping->private_lock);
5228 mark_extent_buffer_accessed(exists, p);
5234 * Do this so attach doesn't complain and we need to
5235 * drop the ref the old guy had.
5237 ClearPagePrivate(p);
5238 WARN_ON(PageDirty(p));
5241 attach_extent_buffer_page(eb, p);
5242 spin_unlock(&mapping->private_lock);
5243 WARN_ON(PageDirty(p));
5245 if (!PageUptodate(p))
5249 * We can't unlock the pages just yet since the extent buffer
5250 * hasn't been properly inserted in the radix tree, this
5251 * opens a race with btree_releasepage which can free a page
5252 * while we are still filling in all pages for the buffer and
5257 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5259 ret = radix_tree_preload(GFP_NOFS);
5261 exists = ERR_PTR(ret);
5265 spin_lock(&fs_info->buffer_lock);
5266 ret = radix_tree_insert(&fs_info->buffer_radix,
5267 start >> PAGE_SHIFT, eb);
5268 spin_unlock(&fs_info->buffer_lock);
5269 radix_tree_preload_end();
5270 if (ret == -EEXIST) {
5271 exists = find_extent_buffer(fs_info, start);
5277 /* add one reference for the tree */
5278 check_buffer_tree_ref(eb);
5279 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5282 * Now it's safe to unlock the pages because any calls to
5283 * btree_releasepage will correctly detect that a page belongs to a
5284 * live buffer and won't free them prematurely.
5286 for (i = 0; i < num_pages; i++)
5287 unlock_page(eb->pages[i]);
5291 WARN_ON(!atomic_dec_and_test(&eb->refs));
5292 for (i = 0; i < num_pages; i++) {
5294 unlock_page(eb->pages[i]);
5297 btrfs_release_extent_buffer(eb);
5301 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5303 struct extent_buffer *eb =
5304 container_of(head, struct extent_buffer, rcu_head);
5306 __free_extent_buffer(eb);
5309 static int release_extent_buffer(struct extent_buffer *eb)
5311 lockdep_assert_held(&eb->refs_lock);
5313 WARN_ON(atomic_read(&eb->refs) == 0);
5314 if (atomic_dec_and_test(&eb->refs)) {
5315 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5316 struct btrfs_fs_info *fs_info = eb->fs_info;
5318 spin_unlock(&eb->refs_lock);
5320 spin_lock(&fs_info->buffer_lock);
5321 radix_tree_delete(&fs_info->buffer_radix,
5322 eb->start >> PAGE_SHIFT);
5323 spin_unlock(&fs_info->buffer_lock);
5325 spin_unlock(&eb->refs_lock);
5328 /* Should be safe to release our pages at this point */
5329 btrfs_release_extent_buffer_pages(eb);
5330 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5331 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5332 __free_extent_buffer(eb);
5336 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5339 spin_unlock(&eb->refs_lock);
5344 void free_extent_buffer(struct extent_buffer *eb)
5352 refs = atomic_read(&eb->refs);
5353 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5354 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5357 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5362 spin_lock(&eb->refs_lock);
5363 if (atomic_read(&eb->refs) == 2 &&
5364 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5365 !extent_buffer_under_io(eb) &&
5366 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5367 atomic_dec(&eb->refs);
5370 * I know this is terrible, but it's temporary until we stop tracking
5371 * the uptodate bits and such for the extent buffers.
5373 release_extent_buffer(eb);
5376 void free_extent_buffer_stale(struct extent_buffer *eb)
5381 spin_lock(&eb->refs_lock);
5382 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5384 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5385 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5386 atomic_dec(&eb->refs);
5387 release_extent_buffer(eb);
5390 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5396 num_pages = num_extent_pages(eb);
5398 for (i = 0; i < num_pages; i++) {
5399 page = eb->pages[i];
5400 if (!PageDirty(page))
5404 WARN_ON(!PagePrivate(page));
5406 clear_page_dirty_for_io(page);
5407 xa_lock_irq(&page->mapping->i_pages);
5408 if (!PageDirty(page))
5409 __xa_clear_mark(&page->mapping->i_pages,
5410 page_index(page), PAGECACHE_TAG_DIRTY);
5411 xa_unlock_irq(&page->mapping->i_pages);
5412 ClearPageError(page);
5415 WARN_ON(atomic_read(&eb->refs) == 0);
5418 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5424 check_buffer_tree_ref(eb);
5426 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5428 num_pages = num_extent_pages(eb);
5429 WARN_ON(atomic_read(&eb->refs) == 0);
5430 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5433 for (i = 0; i < num_pages; i++)
5434 set_page_dirty(eb->pages[i]);
5436 #ifdef CONFIG_BTRFS_DEBUG
5437 for (i = 0; i < num_pages; i++)
5438 ASSERT(PageDirty(eb->pages[i]));
5444 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5450 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5451 num_pages = num_extent_pages(eb);
5452 for (i = 0; i < num_pages; i++) {
5453 page = eb->pages[i];
5455 ClearPageUptodate(page);
5459 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5465 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5466 num_pages = num_extent_pages(eb);
5467 for (i = 0; i < num_pages; i++) {
5468 page = eb->pages[i];
5469 SetPageUptodate(page);
5473 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5479 int locked_pages = 0;
5480 int all_uptodate = 1;
5482 unsigned long num_reads = 0;
5483 struct bio *bio = NULL;
5484 unsigned long bio_flags = 0;
5485 struct extent_io_tree *tree = &BTRFS_I(eb->fs_info->btree_inode)->io_tree;
5487 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5490 num_pages = num_extent_pages(eb);
5491 for (i = 0; i < num_pages; i++) {
5492 page = eb->pages[i];
5493 if (wait == WAIT_NONE) {
5494 if (!trylock_page(page))
5502 * We need to firstly lock all pages to make sure that
5503 * the uptodate bit of our pages won't be affected by
5504 * clear_extent_buffer_uptodate().
5506 for (i = 0; i < num_pages; i++) {
5507 page = eb->pages[i];
5508 if (!PageUptodate(page)) {
5515 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5519 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5520 eb->read_mirror = 0;
5521 atomic_set(&eb->io_pages, num_reads);
5523 * It is possible for releasepage to clear the TREE_REF bit before we
5524 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5526 check_buffer_tree_ref(eb);
5527 for (i = 0; i < num_pages; i++) {
5528 page = eb->pages[i];
5530 if (!PageUptodate(page)) {
5532 atomic_dec(&eb->io_pages);
5537 ClearPageError(page);
5538 err = __extent_read_full_page(tree, page,
5539 btree_get_extent, &bio,
5540 mirror_num, &bio_flags,
5545 * We use &bio in above __extent_read_full_page,
5546 * so we ensure that if it returns error, the
5547 * current page fails to add itself to bio and
5548 * it's been unlocked.
5550 * We must dec io_pages by ourselves.
5552 atomic_dec(&eb->io_pages);
5560 err = submit_one_bio(bio, mirror_num, bio_flags);
5565 if (ret || wait != WAIT_COMPLETE)
5568 for (i = 0; i < num_pages; i++) {
5569 page = eb->pages[i];
5570 wait_on_page_locked(page);
5571 if (!PageUptodate(page))
5578 while (locked_pages > 0) {
5580 page = eb->pages[locked_pages];
5586 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5587 unsigned long start, unsigned long len)
5593 char *dst = (char *)dstv;
5594 size_t start_offset = offset_in_page(eb->start);
5595 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5597 if (start + len > eb->len) {
5598 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5599 eb->start, eb->len, start, len);
5600 memset(dst, 0, len);
5604 offset = offset_in_page(start_offset + start);
5607 page = eb->pages[i];
5609 cur = min(len, (PAGE_SIZE - offset));
5610 kaddr = page_address(page);
5611 memcpy(dst, kaddr + offset, cur);
5620 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5622 unsigned long start, unsigned long len)
5628 char __user *dst = (char __user *)dstv;
5629 size_t start_offset = offset_in_page(eb->start);
5630 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5633 WARN_ON(start > eb->len);
5634 WARN_ON(start + len > eb->start + eb->len);
5636 offset = offset_in_page(start_offset + start);
5639 page = eb->pages[i];
5641 cur = min(len, (PAGE_SIZE - offset));
5642 kaddr = page_address(page);
5643 if (probe_user_write(dst, kaddr + offset, cur)) {
5658 * return 0 if the item is found within a page.
5659 * return 1 if the item spans two pages.
5660 * return -EINVAL otherwise.
5662 int map_private_extent_buffer(const struct extent_buffer *eb,
5663 unsigned long start, unsigned long min_len,
5664 char **map, unsigned long *map_start,
5665 unsigned long *map_len)
5670 size_t start_offset = offset_in_page(eb->start);
5671 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5672 unsigned long end_i = (start_offset + start + min_len - 1) >>
5675 if (start + min_len > eb->len) {
5676 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5677 eb->start, eb->len, start, min_len);
5685 offset = start_offset;
5689 *map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5693 kaddr = page_address(p);
5694 *map = kaddr + offset;
5695 *map_len = PAGE_SIZE - offset;
5699 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5700 unsigned long start, unsigned long len)
5706 char *ptr = (char *)ptrv;
5707 size_t start_offset = offset_in_page(eb->start);
5708 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5711 WARN_ON(start > eb->len);
5712 WARN_ON(start + len > eb->start + eb->len);
5714 offset = offset_in_page(start_offset + start);
5717 page = eb->pages[i];
5719 cur = min(len, (PAGE_SIZE - offset));
5721 kaddr = page_address(page);
5722 ret = memcmp(ptr, kaddr + offset, cur);
5734 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5739 WARN_ON(!PageUptodate(eb->pages[0]));
5740 kaddr = page_address(eb->pages[0]);
5741 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5745 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5749 WARN_ON(!PageUptodate(eb->pages[0]));
5750 kaddr = page_address(eb->pages[0]);
5751 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5755 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5756 unsigned long start, unsigned long len)
5762 char *src = (char *)srcv;
5763 size_t start_offset = offset_in_page(eb->start);
5764 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5766 WARN_ON(start > eb->len);
5767 WARN_ON(start + len > eb->start + eb->len);
5769 offset = offset_in_page(start_offset + start);
5772 page = eb->pages[i];
5773 WARN_ON(!PageUptodate(page));
5775 cur = min(len, PAGE_SIZE - offset);
5776 kaddr = page_address(page);
5777 memcpy(kaddr + offset, src, cur);
5786 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5793 size_t start_offset = offset_in_page(eb->start);
5794 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5796 WARN_ON(start > eb->len);
5797 WARN_ON(start + len > eb->start + eb->len);
5799 offset = offset_in_page(start_offset + start);
5802 page = eb->pages[i];
5803 WARN_ON(!PageUptodate(page));
5805 cur = min(len, PAGE_SIZE - offset);
5806 kaddr = page_address(page);
5807 memset(kaddr + offset, 0, cur);
5815 void copy_extent_buffer_full(struct extent_buffer *dst,
5816 struct extent_buffer *src)
5821 ASSERT(dst->len == src->len);
5823 num_pages = num_extent_pages(dst);
5824 for (i = 0; i < num_pages; i++)
5825 copy_page(page_address(dst->pages[i]),
5826 page_address(src->pages[i]));
5829 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5830 unsigned long dst_offset, unsigned long src_offset,
5833 u64 dst_len = dst->len;
5838 size_t start_offset = offset_in_page(dst->start);
5839 unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5841 WARN_ON(src->len != dst_len);
5843 offset = offset_in_page(start_offset + dst_offset);
5846 page = dst->pages[i];
5847 WARN_ON(!PageUptodate(page));
5849 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5851 kaddr = page_address(page);
5852 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5862 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5864 * @eb: the extent buffer
5865 * @start: offset of the bitmap item in the extent buffer
5867 * @page_index: return index of the page in the extent buffer that contains the
5869 * @page_offset: return offset into the page given by page_index
5871 * This helper hides the ugliness of finding the byte in an extent buffer which
5872 * contains a given bit.
5874 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5875 unsigned long start, unsigned long nr,
5876 unsigned long *page_index,
5877 size_t *page_offset)
5879 size_t start_offset = offset_in_page(eb->start);
5880 size_t byte_offset = BIT_BYTE(nr);
5884 * The byte we want is the offset of the extent buffer + the offset of
5885 * the bitmap item in the extent buffer + the offset of the byte in the
5888 offset = start_offset + start + byte_offset;
5890 *page_index = offset >> PAGE_SHIFT;
5891 *page_offset = offset_in_page(offset);
5895 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5896 * @eb: the extent buffer
5897 * @start: offset of the bitmap item in the extent buffer
5898 * @nr: bit number to test
5900 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5908 eb_bitmap_offset(eb, start, nr, &i, &offset);
5909 page = eb->pages[i];
5910 WARN_ON(!PageUptodate(page));
5911 kaddr = page_address(page);
5912 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5916 * extent_buffer_bitmap_set - set an area of a bitmap
5917 * @eb: the extent buffer
5918 * @start: offset of the bitmap item in the extent buffer
5919 * @pos: bit number of the first bit
5920 * @len: number of bits to set
5922 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5923 unsigned long pos, unsigned long len)
5929 const unsigned int size = pos + len;
5930 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5931 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5933 eb_bitmap_offset(eb, start, pos, &i, &offset);
5934 page = eb->pages[i];
5935 WARN_ON(!PageUptodate(page));
5936 kaddr = page_address(page);
5938 while (len >= bits_to_set) {
5939 kaddr[offset] |= mask_to_set;
5941 bits_to_set = BITS_PER_BYTE;
5943 if (++offset >= PAGE_SIZE && len > 0) {
5945 page = eb->pages[++i];
5946 WARN_ON(!PageUptodate(page));
5947 kaddr = page_address(page);
5951 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5952 kaddr[offset] |= mask_to_set;
5958 * extent_buffer_bitmap_clear - clear an area of a bitmap
5959 * @eb: the extent buffer
5960 * @start: offset of the bitmap item in the extent buffer
5961 * @pos: bit number of the first bit
5962 * @len: number of bits to clear
5964 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5965 unsigned long pos, unsigned long len)
5971 const unsigned int size = pos + len;
5972 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5973 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5975 eb_bitmap_offset(eb, start, pos, &i, &offset);
5976 page = eb->pages[i];
5977 WARN_ON(!PageUptodate(page));
5978 kaddr = page_address(page);
5980 while (len >= bits_to_clear) {
5981 kaddr[offset] &= ~mask_to_clear;
5982 len -= bits_to_clear;
5983 bits_to_clear = BITS_PER_BYTE;
5985 if (++offset >= PAGE_SIZE && len > 0) {
5987 page = eb->pages[++i];
5988 WARN_ON(!PageUptodate(page));
5989 kaddr = page_address(page);
5993 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5994 kaddr[offset] &= ~mask_to_clear;
5998 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6000 unsigned long distance = (src > dst) ? src - dst : dst - src;
6001 return distance < len;
6004 static void copy_pages(struct page *dst_page, struct page *src_page,
6005 unsigned long dst_off, unsigned long src_off,
6008 char *dst_kaddr = page_address(dst_page);
6010 int must_memmove = 0;
6012 if (dst_page != src_page) {
6013 src_kaddr = page_address(src_page);
6015 src_kaddr = dst_kaddr;
6016 if (areas_overlap(src_off, dst_off, len))
6021 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6023 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6026 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
6027 unsigned long src_offset, unsigned long len)
6029 struct btrfs_fs_info *fs_info = dst->fs_info;
6031 size_t dst_off_in_page;
6032 size_t src_off_in_page;
6033 size_t start_offset = offset_in_page(dst->start);
6034 unsigned long dst_i;
6035 unsigned long src_i;
6037 if (src_offset + len > dst->len) {
6039 "memmove bogus src_offset %lu move len %lu dst len %lu",
6040 src_offset, len, dst->len);
6043 if (dst_offset + len > dst->len) {
6045 "memmove bogus dst_offset %lu move len %lu dst len %lu",
6046 dst_offset, len, dst->len);
6051 dst_off_in_page = offset_in_page(start_offset + dst_offset);
6052 src_off_in_page = offset_in_page(start_offset + src_offset);
6054 dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
6055 src_i = (start_offset + src_offset) >> PAGE_SHIFT;
6057 cur = min(len, (unsigned long)(PAGE_SIZE -
6059 cur = min_t(unsigned long, cur,
6060 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6062 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6063 dst_off_in_page, src_off_in_page, cur);
6071 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
6072 unsigned long src_offset, unsigned long len)
6074 struct btrfs_fs_info *fs_info = dst->fs_info;
6076 size_t dst_off_in_page;
6077 size_t src_off_in_page;
6078 unsigned long dst_end = dst_offset + len - 1;
6079 unsigned long src_end = src_offset + len - 1;
6080 size_t start_offset = offset_in_page(dst->start);
6081 unsigned long dst_i;
6082 unsigned long src_i;
6084 if (src_offset + len > dst->len) {
6086 "memmove bogus src_offset %lu move len %lu len %lu",
6087 src_offset, len, dst->len);
6090 if (dst_offset + len > dst->len) {
6092 "memmove bogus dst_offset %lu move len %lu len %lu",
6093 dst_offset, len, dst->len);
6096 if (dst_offset < src_offset) {
6097 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6101 dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
6102 src_i = (start_offset + src_end) >> PAGE_SHIFT;
6104 dst_off_in_page = offset_in_page(start_offset + dst_end);
6105 src_off_in_page = offset_in_page(start_offset + src_end);
6107 cur = min_t(unsigned long, len, src_off_in_page + 1);
6108 cur = min(cur, dst_off_in_page + 1);
6109 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6110 dst_off_in_page - cur + 1,
6111 src_off_in_page - cur + 1, cur);
6119 int try_release_extent_buffer(struct page *page)
6121 struct extent_buffer *eb;
6124 * We need to make sure nobody is attaching this page to an eb right
6127 spin_lock(&page->mapping->private_lock);
6128 if (!PagePrivate(page)) {
6129 spin_unlock(&page->mapping->private_lock);
6133 eb = (struct extent_buffer *)page->private;
6137 * This is a little awful but should be ok, we need to make sure that
6138 * the eb doesn't disappear out from under us while we're looking at
6141 spin_lock(&eb->refs_lock);
6142 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6143 spin_unlock(&eb->refs_lock);
6144 spin_unlock(&page->mapping->private_lock);
6147 spin_unlock(&page->mapping->private_lock);
6150 * If tree ref isn't set then we know the ref on this eb is a real ref,
6151 * so just return, this page will likely be freed soon anyway.
6153 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6154 spin_unlock(&eb->refs_lock);
6158 return release_extent_buffer(eb);