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 if (tree->ops && tree->ops->check_extent_io_range)
93 tree->ops->check_extent_io_range(tree->private_data, caller,
97 #define btrfs_leak_debug_add(new, head) do {} while (0)
98 #define btrfs_leak_debug_del(entry) do {} while (0)
99 #define btrfs_leak_debug_check() do {} while (0)
100 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
103 #define BUFFER_LRU_MAX 64
108 struct rb_node rb_node;
111 struct extent_page_data {
113 struct extent_io_tree *tree;
114 /* tells writepage not to lock the state bits for this range
115 * it still does the unlocking
117 unsigned int extent_locked:1;
119 /* tells the submit_bio code to use REQ_SYNC */
120 unsigned int sync_io:1;
123 static int add_extent_changeset(struct extent_state *state, unsigned bits,
124 struct extent_changeset *changeset,
131 if (set && (state->state & bits) == bits)
133 if (!set && (state->state & bits) == 0)
135 changeset->bytes_changed += state->end - state->start + 1;
136 ret = ulist_add(&changeset->range_changed, state->start, state->end,
141 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
142 unsigned long bio_flags)
144 blk_status_t ret = 0;
145 struct bio_vec *bvec = bio_last_bvec_all(bio);
146 struct page *page = bvec->bv_page;
147 struct extent_io_tree *tree = bio->bi_private;
150 start = page_offset(page) + bvec->bv_offset;
152 bio->bi_private = NULL;
155 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
156 mirror_num, bio_flags, start);
158 btrfsic_submit_bio(bio);
160 return blk_status_to_errno(ret);
163 /* Cleanup unsubmitted bios */
164 static void end_write_bio(struct extent_page_data *epd, int ret)
167 epd->bio->bi_status = errno_to_blk_status(ret);
174 * Submit bio from extent page data via submit_one_bio
176 * Return 0 if everything is OK.
177 * Return <0 for error.
179 static int __must_check flush_write_bio(struct extent_page_data *epd)
184 ret = submit_one_bio(epd->bio, 0, 0);
186 * Clean up of epd->bio is handled by its endio function.
187 * And endio is either triggered by successful bio execution
188 * or the error handler of submit bio hook.
189 * So at this point, no matter what happened, we don't need
190 * to clean up epd->bio.
197 int __init extent_io_init(void)
199 extent_state_cache = kmem_cache_create("btrfs_extent_state",
200 sizeof(struct extent_state), 0,
201 SLAB_MEM_SPREAD, NULL);
202 if (!extent_state_cache)
205 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
206 sizeof(struct extent_buffer), 0,
207 SLAB_MEM_SPREAD, NULL);
208 if (!extent_buffer_cache)
209 goto free_state_cache;
211 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
212 offsetof(struct btrfs_io_bio, bio),
214 goto free_buffer_cache;
216 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
222 bioset_exit(&btrfs_bioset);
225 kmem_cache_destroy(extent_buffer_cache);
226 extent_buffer_cache = NULL;
229 kmem_cache_destroy(extent_state_cache);
230 extent_state_cache = NULL;
234 void __cold extent_io_exit(void)
236 btrfs_leak_debug_check();
239 * Make sure all delayed rcu free are flushed before we
243 kmem_cache_destroy(extent_state_cache);
244 kmem_cache_destroy(extent_buffer_cache);
245 bioset_exit(&btrfs_bioset);
248 void extent_io_tree_init(struct extent_io_tree *tree,
251 tree->state = RB_ROOT;
253 tree->dirty_bytes = 0;
254 spin_lock_init(&tree->lock);
255 tree->private_data = private_data;
258 static struct extent_state *alloc_extent_state(gfp_t mask)
260 struct extent_state *state;
263 * The given mask might be not appropriate for the slab allocator,
264 * drop the unsupported bits
266 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
267 state = kmem_cache_alloc(extent_state_cache, mask);
271 state->failrec = NULL;
272 RB_CLEAR_NODE(&state->rb_node);
273 btrfs_leak_debug_add(&state->leak_list, &states);
274 refcount_set(&state->refs, 1);
275 init_waitqueue_head(&state->wq);
276 trace_alloc_extent_state(state, mask, _RET_IP_);
280 void free_extent_state(struct extent_state *state)
284 if (refcount_dec_and_test(&state->refs)) {
285 WARN_ON(extent_state_in_tree(state));
286 btrfs_leak_debug_del(&state->leak_list);
287 trace_free_extent_state(state, _RET_IP_);
288 kmem_cache_free(extent_state_cache, state);
292 static struct rb_node *tree_insert(struct rb_root *root,
293 struct rb_node *search_start,
295 struct rb_node *node,
296 struct rb_node ***p_in,
297 struct rb_node **parent_in)
300 struct rb_node *parent = NULL;
301 struct tree_entry *entry;
303 if (p_in && parent_in) {
309 p = search_start ? &search_start : &root->rb_node;
312 entry = rb_entry(parent, struct tree_entry, rb_node);
314 if (offset < entry->start)
316 else if (offset > entry->end)
323 rb_link_node(node, parent, p);
324 rb_insert_color(node, root);
328 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
329 struct rb_node **prev_ret,
330 struct rb_node **next_ret,
331 struct rb_node ***p_ret,
332 struct rb_node **parent_ret)
334 struct rb_root *root = &tree->state;
335 struct rb_node **n = &root->rb_node;
336 struct rb_node *prev = NULL;
337 struct rb_node *orig_prev = NULL;
338 struct tree_entry *entry;
339 struct tree_entry *prev_entry = NULL;
343 entry = rb_entry(prev, struct tree_entry, rb_node);
346 if (offset < entry->start)
348 else if (offset > entry->end)
361 while (prev && offset > prev_entry->end) {
362 prev = rb_next(prev);
363 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
370 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
371 while (prev && offset < prev_entry->start) {
372 prev = rb_prev(prev);
373 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
380 static inline struct rb_node *
381 tree_search_for_insert(struct extent_io_tree *tree,
383 struct rb_node ***p_ret,
384 struct rb_node **parent_ret)
386 struct rb_node *prev = NULL;
389 ret = __etree_search(tree, offset, &prev, NULL, p_ret, parent_ret);
395 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
398 return tree_search_for_insert(tree, offset, NULL, NULL);
401 static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
402 struct extent_state *other)
404 if (tree->ops && tree->ops->merge_extent_hook)
405 tree->ops->merge_extent_hook(tree->private_data, new, other);
409 * utility function to look for merge candidates inside a given range.
410 * Any extents with matching state are merged together into a single
411 * extent in the tree. Extents with EXTENT_IO in their state field
412 * are not merged because the end_io handlers need to be able to do
413 * operations on them without sleeping (or doing allocations/splits).
415 * This should be called with the tree lock held.
417 static void merge_state(struct extent_io_tree *tree,
418 struct extent_state *state)
420 struct extent_state *other;
421 struct rb_node *other_node;
423 if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
426 other_node = rb_prev(&state->rb_node);
428 other = rb_entry(other_node, struct extent_state, rb_node);
429 if (other->end == state->start - 1 &&
430 other->state == state->state) {
431 merge_cb(tree, state, other);
432 state->start = other->start;
433 rb_erase(&other->rb_node, &tree->state);
434 RB_CLEAR_NODE(&other->rb_node);
435 free_extent_state(other);
438 other_node = rb_next(&state->rb_node);
440 other = rb_entry(other_node, struct extent_state, rb_node);
441 if (other->start == state->end + 1 &&
442 other->state == state->state) {
443 merge_cb(tree, state, other);
444 state->end = other->end;
445 rb_erase(&other->rb_node, &tree->state);
446 RB_CLEAR_NODE(&other->rb_node);
447 free_extent_state(other);
452 static void set_state_cb(struct extent_io_tree *tree,
453 struct extent_state *state, unsigned *bits)
455 if (tree->ops && tree->ops->set_bit_hook)
456 tree->ops->set_bit_hook(tree->private_data, state, bits);
459 static void clear_state_cb(struct extent_io_tree *tree,
460 struct extent_state *state, unsigned *bits)
462 if (tree->ops && tree->ops->clear_bit_hook)
463 tree->ops->clear_bit_hook(tree->private_data, state, bits);
466 static void set_state_bits(struct extent_io_tree *tree,
467 struct extent_state *state, unsigned *bits,
468 struct extent_changeset *changeset);
471 * insert an extent_state struct into the tree. 'bits' are set on the
472 * struct before it is inserted.
474 * This may return -EEXIST if the extent is already there, in which case the
475 * state struct is freed.
477 * The tree lock is not taken internally. This is a utility function and
478 * probably isn't what you want to call (see set/clear_extent_bit).
480 static int insert_state(struct extent_io_tree *tree,
481 struct extent_state *state, u64 start, u64 end,
483 struct rb_node **parent,
484 unsigned *bits, struct extent_changeset *changeset)
486 struct rb_node *node;
489 WARN(1, KERN_ERR "BTRFS: end < start %llu %llu\n",
491 state->start = start;
494 set_state_bits(tree, state, bits, changeset);
496 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
498 struct extent_state *found;
499 found = rb_entry(node, struct extent_state, rb_node);
500 pr_err("BTRFS: found node %llu %llu on insert of %llu %llu\n",
501 found->start, found->end, start, end);
504 merge_state(tree, state);
508 static void split_cb(struct extent_io_tree *tree, struct extent_state *orig,
511 if (tree->ops && tree->ops->split_extent_hook)
512 tree->ops->split_extent_hook(tree->private_data, orig, split);
516 * split a given extent state struct in two, inserting the preallocated
517 * struct 'prealloc' as the newly created second half. 'split' indicates an
518 * offset inside 'orig' where it should be split.
521 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
522 * are two extent state structs in the tree:
523 * prealloc: [orig->start, split - 1]
524 * orig: [ split, orig->end ]
526 * The tree locks are not taken by this function. They need to be held
529 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
530 struct extent_state *prealloc, u64 split)
532 struct rb_node *node;
534 split_cb(tree, orig, split);
536 prealloc->start = orig->start;
537 prealloc->end = split - 1;
538 prealloc->state = orig->state;
541 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
542 &prealloc->rb_node, NULL, NULL);
544 free_extent_state(prealloc);
550 static struct extent_state *next_state(struct extent_state *state)
552 struct rb_node *next = rb_next(&state->rb_node);
554 return rb_entry(next, struct extent_state, rb_node);
560 * utility function to clear some bits in an extent state struct.
561 * it will optionally wake up any one waiting on this state (wake == 1).
563 * If no bits are set on the state struct after clearing things, the
564 * struct is freed and removed from the tree
566 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
567 struct extent_state *state,
568 unsigned *bits, int wake,
569 struct extent_changeset *changeset)
571 struct extent_state *next;
572 unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
575 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
576 u64 range = state->end - state->start + 1;
577 WARN_ON(range > tree->dirty_bytes);
578 tree->dirty_bytes -= range;
580 clear_state_cb(tree, state, bits);
581 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
583 state->state &= ~bits_to_clear;
586 if (state->state == 0) {
587 next = next_state(state);
588 if (extent_state_in_tree(state)) {
589 rb_erase(&state->rb_node, &tree->state);
590 RB_CLEAR_NODE(&state->rb_node);
591 free_extent_state(state);
596 merge_state(tree, state);
597 next = next_state(state);
602 static struct extent_state *
603 alloc_extent_state_atomic(struct extent_state *prealloc)
606 prealloc = alloc_extent_state(GFP_ATOMIC);
611 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
613 struct inode *inode = tree->private_data;
615 btrfs_panic(btrfs_sb(inode->i_sb), err,
616 "locking error: extent tree was modified by another thread while locked");
620 * clear some bits on a range in the tree. This may require splitting
621 * or inserting elements in the tree, so the gfp mask is used to
622 * indicate which allocations or sleeping are allowed.
624 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
625 * the given range from the tree regardless of state (ie for truncate).
627 * the range [start, end] is inclusive.
629 * This takes the tree lock, and returns 0 on success and < 0 on error.
631 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
632 unsigned bits, int wake, int delete,
633 struct extent_state **cached_state,
634 gfp_t mask, struct extent_changeset *changeset)
636 struct extent_state *state;
637 struct extent_state *cached;
638 struct extent_state *prealloc = NULL;
639 struct rb_node *node;
644 btrfs_debug_check_extent_io_range(tree, start, end);
646 if (bits & EXTENT_DELALLOC)
647 bits |= EXTENT_NORESERVE;
650 bits |= ~EXTENT_CTLBITS;
651 bits |= EXTENT_FIRST_DELALLOC;
653 if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
656 if (!prealloc && gfpflags_allow_blocking(mask)) {
658 * Don't care for allocation failure here because we might end
659 * up not needing the pre-allocated extent state at all, which
660 * is the case if we only have in the tree extent states that
661 * cover our input range and don't cover too any other range.
662 * If we end up needing a new extent state we allocate it later.
664 prealloc = alloc_extent_state(mask);
667 spin_lock(&tree->lock);
669 cached = *cached_state;
672 *cached_state = NULL;
676 if (cached && extent_state_in_tree(cached) &&
677 cached->start <= start && cached->end > start) {
679 refcount_dec(&cached->refs);
684 free_extent_state(cached);
687 * this search will find the extents that end after
690 node = tree_search(tree, start);
693 state = rb_entry(node, struct extent_state, rb_node);
695 if (state->start > end)
697 WARN_ON(state->end < start);
698 last_end = state->end;
700 /* the state doesn't have the wanted bits, go ahead */
701 if (!(state->state & bits)) {
702 state = next_state(state);
707 * | ---- desired range ---- |
709 * | ------------- state -------------- |
711 * We need to split the extent we found, and may flip
712 * bits on second half.
714 * If the extent we found extends past our range, we
715 * just split and search again. It'll get split again
716 * the next time though.
718 * If the extent we found is inside our range, we clear
719 * the desired bit on it.
722 if (state->start < start) {
723 prealloc = alloc_extent_state_atomic(prealloc);
725 err = split_state(tree, state, prealloc, start);
727 extent_io_tree_panic(tree, err);
732 if (state->end <= end) {
733 state = clear_state_bit(tree, state, &bits, wake,
740 * | ---- desired range ---- |
742 * We need to split the extent, and clear the bit
745 if (state->start <= end && state->end > end) {
746 prealloc = alloc_extent_state_atomic(prealloc);
748 err = split_state(tree, state, prealloc, end + 1);
750 extent_io_tree_panic(tree, err);
755 clear_state_bit(tree, prealloc, &bits, wake, changeset);
761 state = clear_state_bit(tree, state, &bits, wake, changeset);
763 if (last_end == (u64)-1)
765 start = last_end + 1;
766 if (start <= end && state && !need_resched())
772 spin_unlock(&tree->lock);
773 if (gfpflags_allow_blocking(mask))
778 spin_unlock(&tree->lock);
780 free_extent_state(prealloc);
786 static void wait_on_state(struct extent_io_tree *tree,
787 struct extent_state *state)
788 __releases(tree->lock)
789 __acquires(tree->lock)
792 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
793 spin_unlock(&tree->lock);
795 spin_lock(&tree->lock);
796 finish_wait(&state->wq, &wait);
800 * waits for one or more bits to clear on a range in the state tree.
801 * The range [start, end] is inclusive.
802 * The tree lock is taken by this function
804 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
807 struct extent_state *state;
808 struct rb_node *node;
810 btrfs_debug_check_extent_io_range(tree, start, end);
812 spin_lock(&tree->lock);
816 * this search will find all the extents that end after
819 node = tree_search(tree, start);
824 state = rb_entry(node, struct extent_state, rb_node);
826 if (state->start > end)
829 if (state->state & bits) {
830 start = state->start;
831 refcount_inc(&state->refs);
832 wait_on_state(tree, state);
833 free_extent_state(state);
836 start = state->end + 1;
841 if (!cond_resched_lock(&tree->lock)) {
842 node = rb_next(node);
847 spin_unlock(&tree->lock);
850 static void set_state_bits(struct extent_io_tree *tree,
851 struct extent_state *state,
852 unsigned *bits, struct extent_changeset *changeset)
854 unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
857 set_state_cb(tree, state, bits);
858 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
859 u64 range = state->end - state->start + 1;
860 tree->dirty_bytes += range;
862 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
864 state->state |= bits_to_set;
867 static void cache_state_if_flags(struct extent_state *state,
868 struct extent_state **cached_ptr,
871 if (cached_ptr && !(*cached_ptr)) {
872 if (!flags || (state->state & flags)) {
874 refcount_inc(&state->refs);
879 static void cache_state(struct extent_state *state,
880 struct extent_state **cached_ptr)
882 return cache_state_if_flags(state, cached_ptr,
883 EXTENT_IOBITS | EXTENT_BOUNDARY);
887 * set some bits on a range in the tree. This may require allocations or
888 * sleeping, so the gfp mask is used to indicate what is allowed.
890 * If any of the exclusive bits are set, this will fail with -EEXIST if some
891 * part of the range already has the desired bits set. The start of the
892 * existing range is returned in failed_start in this case.
894 * [start, end] is inclusive This takes the tree lock.
897 static int __must_check
898 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
899 unsigned bits, unsigned exclusive_bits,
900 u64 *failed_start, struct extent_state **cached_state,
901 gfp_t mask, struct extent_changeset *changeset)
903 struct extent_state *state;
904 struct extent_state *prealloc = NULL;
905 struct rb_node *node;
907 struct rb_node *parent;
912 btrfs_debug_check_extent_io_range(tree, start, end);
914 bits |= EXTENT_FIRST_DELALLOC;
916 if (!prealloc && gfpflags_allow_blocking(mask)) {
918 * Don't care for allocation failure here because we might end
919 * up not needing the pre-allocated extent state at all, which
920 * is the case if we only have in the tree extent states that
921 * cover our input range and don't cover too any other range.
922 * If we end up needing a new extent state we allocate it later.
924 prealloc = alloc_extent_state(mask);
927 spin_lock(&tree->lock);
928 if (cached_state && *cached_state) {
929 state = *cached_state;
930 if (state->start <= start && state->end > start &&
931 extent_state_in_tree(state)) {
932 node = &state->rb_node;
937 * this search will find all the extents that end after
940 node = tree_search_for_insert(tree, start, &p, &parent);
942 prealloc = alloc_extent_state_atomic(prealloc);
944 err = insert_state(tree, prealloc, start, end,
945 &p, &parent, &bits, changeset);
947 extent_io_tree_panic(tree, err);
949 cache_state(prealloc, cached_state);
953 state = rb_entry(node, struct extent_state, rb_node);
955 last_start = state->start;
956 last_end = state->end;
959 * | ---- desired range ---- |
962 * Just lock what we found and keep going
964 if (state->start == start && state->end <= end) {
965 if (state->state & exclusive_bits) {
966 *failed_start = state->start;
971 set_state_bits(tree, state, &bits, changeset);
972 cache_state(state, cached_state);
973 merge_state(tree, state);
974 if (last_end == (u64)-1)
976 start = last_end + 1;
977 state = next_state(state);
978 if (start < end && state && state->start == start &&
985 * | ---- desired range ---- |
988 * | ------------- state -------------- |
990 * We need to split the extent we found, and may flip bits on
993 * If the extent we found extends past our
994 * range, we just split and search again. It'll get split
995 * again the next time though.
997 * If the extent we found is inside our range, we set the
1000 if (state->start < start) {
1001 if (state->state & exclusive_bits) {
1002 *failed_start = start;
1007 prealloc = alloc_extent_state_atomic(prealloc);
1009 err = split_state(tree, state, prealloc, start);
1011 extent_io_tree_panic(tree, err);
1016 if (state->end <= end) {
1017 set_state_bits(tree, state, &bits, changeset);
1018 cache_state(state, cached_state);
1019 merge_state(tree, state);
1020 if (last_end == (u64)-1)
1022 start = last_end + 1;
1023 state = next_state(state);
1024 if (start < end && state && state->start == start &&
1031 * | ---- desired range ---- |
1032 * | state | or | state |
1034 * There's a hole, we need to insert something in it and
1035 * ignore the extent we found.
1037 if (state->start > start) {
1039 if (end < last_start)
1042 this_end = last_start - 1;
1044 prealloc = alloc_extent_state_atomic(prealloc);
1048 * Avoid to free 'prealloc' if it can be merged with
1051 err = insert_state(tree, prealloc, start, this_end,
1052 NULL, NULL, &bits, changeset);
1054 extent_io_tree_panic(tree, err);
1056 cache_state(prealloc, cached_state);
1058 start = this_end + 1;
1062 * | ---- desired range ---- |
1064 * We need to split the extent, and set the bit
1067 if (state->start <= end && state->end > end) {
1068 if (state->state & exclusive_bits) {
1069 *failed_start = start;
1074 prealloc = alloc_extent_state_atomic(prealloc);
1076 err = split_state(tree, state, prealloc, end + 1);
1078 extent_io_tree_panic(tree, err);
1080 set_state_bits(tree, prealloc, &bits, changeset);
1081 cache_state(prealloc, cached_state);
1082 merge_state(tree, prealloc);
1090 spin_unlock(&tree->lock);
1091 if (gfpflags_allow_blocking(mask))
1096 spin_unlock(&tree->lock);
1098 free_extent_state(prealloc);
1104 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1105 unsigned bits, u64 * failed_start,
1106 struct extent_state **cached_state, gfp_t mask)
1108 return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1109 cached_state, mask, NULL);
1114 * convert_extent_bit - convert all bits in a given range from one bit to
1116 * @tree: the io tree to search
1117 * @start: the start offset in bytes
1118 * @end: the end offset in bytes (inclusive)
1119 * @bits: the bits to set in this range
1120 * @clear_bits: the bits to clear in this range
1121 * @cached_state: state that we're going to cache
1123 * This will go through and set bits for the given range. If any states exist
1124 * already in this range they are set with the given bit and cleared of the
1125 * clear_bits. This is only meant to be used by things that are mergeable, ie
1126 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1127 * boundary bits like LOCK.
1129 * All allocations are done with GFP_NOFS.
1131 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1132 unsigned bits, unsigned clear_bits,
1133 struct extent_state **cached_state)
1135 struct extent_state *state;
1136 struct extent_state *prealloc = NULL;
1137 struct rb_node *node;
1139 struct rb_node *parent;
1143 bool first_iteration = true;
1145 btrfs_debug_check_extent_io_range(tree, start, end);
1150 * Best effort, don't worry if extent state allocation fails
1151 * here for the first iteration. We might have a cached state
1152 * that matches exactly the target range, in which case no
1153 * extent state allocations are needed. We'll only know this
1154 * after locking the tree.
1156 prealloc = alloc_extent_state(GFP_NOFS);
1157 if (!prealloc && !first_iteration)
1161 spin_lock(&tree->lock);
1162 if (cached_state && *cached_state) {
1163 state = *cached_state;
1164 if (state->start <= start && state->end > start &&
1165 extent_state_in_tree(state)) {
1166 node = &state->rb_node;
1172 * this search will find all the extents that end after
1175 node = tree_search_for_insert(tree, start, &p, &parent);
1177 prealloc = alloc_extent_state_atomic(prealloc);
1182 err = insert_state(tree, prealloc, start, end,
1183 &p, &parent, &bits, NULL);
1185 extent_io_tree_panic(tree, err);
1186 cache_state(prealloc, cached_state);
1190 state = rb_entry(node, struct extent_state, rb_node);
1192 last_start = state->start;
1193 last_end = state->end;
1196 * | ---- desired range ---- |
1199 * Just lock what we found and keep going
1201 if (state->start == start && state->end <= end) {
1202 set_state_bits(tree, state, &bits, NULL);
1203 cache_state(state, cached_state);
1204 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1205 if (last_end == (u64)-1)
1207 start = last_end + 1;
1208 if (start < end && state && state->start == start &&
1215 * | ---- desired range ---- |
1218 * | ------------- state -------------- |
1220 * We need to split the extent we found, and may flip bits on
1223 * If the extent we found extends past our
1224 * range, we just split and search again. It'll get split
1225 * again the next time though.
1227 * If the extent we found is inside our range, we set the
1228 * desired bit on it.
1230 if (state->start < start) {
1231 prealloc = alloc_extent_state_atomic(prealloc);
1236 err = split_state(tree, state, prealloc, start);
1238 extent_io_tree_panic(tree, err);
1242 if (state->end <= end) {
1243 set_state_bits(tree, state, &bits, NULL);
1244 cache_state(state, cached_state);
1245 state = clear_state_bit(tree, state, &clear_bits, 0,
1247 if (last_end == (u64)-1)
1249 start = last_end + 1;
1250 if (start < end && state && state->start == start &&
1257 * | ---- desired range ---- |
1258 * | state | or | state |
1260 * There's a hole, we need to insert something in it and
1261 * ignore the extent we found.
1263 if (state->start > start) {
1265 if (end < last_start)
1268 this_end = last_start - 1;
1270 prealloc = alloc_extent_state_atomic(prealloc);
1277 * Avoid to free 'prealloc' if it can be merged with
1280 err = insert_state(tree, prealloc, start, this_end,
1281 NULL, NULL, &bits, NULL);
1283 extent_io_tree_panic(tree, err);
1284 cache_state(prealloc, cached_state);
1286 start = this_end + 1;
1290 * | ---- desired range ---- |
1292 * We need to split the extent, and set the bit
1295 if (state->start <= end && state->end > end) {
1296 prealloc = alloc_extent_state_atomic(prealloc);
1302 err = split_state(tree, state, prealloc, end + 1);
1304 extent_io_tree_panic(tree, err);
1306 set_state_bits(tree, prealloc, &bits, NULL);
1307 cache_state(prealloc, cached_state);
1308 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1316 spin_unlock(&tree->lock);
1318 first_iteration = false;
1322 spin_unlock(&tree->lock);
1324 free_extent_state(prealloc);
1329 /* wrappers around set/clear extent bit */
1330 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1331 unsigned bits, struct extent_changeset *changeset)
1334 * We don't support EXTENT_LOCKED yet, as current changeset will
1335 * record any bits changed, so for EXTENT_LOCKED case, it will
1336 * either fail with -EEXIST or changeset will record the whole
1339 BUG_ON(bits & EXTENT_LOCKED);
1341 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1345 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1346 unsigned bits, int wake, int delete,
1347 struct extent_state **cached)
1349 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1350 cached, GFP_NOFS, NULL);
1353 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1354 unsigned bits, struct extent_changeset *changeset)
1357 * Don't support EXTENT_LOCKED case, same reason as
1358 * set_record_extent_bits().
1360 BUG_ON(bits & EXTENT_LOCKED);
1362 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1367 * either insert or lock state struct between start and end use mask to tell
1368 * us if waiting is desired.
1370 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1371 struct extent_state **cached_state)
1377 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1378 EXTENT_LOCKED, &failed_start,
1379 cached_state, GFP_NOFS, NULL);
1380 if (err == -EEXIST) {
1381 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1382 start = failed_start;
1385 WARN_ON(start > end);
1390 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1395 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1396 &failed_start, NULL, GFP_NOFS, NULL);
1397 if (err == -EEXIST) {
1398 if (failed_start > start)
1399 clear_extent_bit(tree, start, failed_start - 1,
1400 EXTENT_LOCKED, 1, 0, NULL);
1406 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1408 unsigned long index = start >> PAGE_SHIFT;
1409 unsigned long end_index = end >> PAGE_SHIFT;
1412 while (index <= end_index) {
1413 page = find_get_page(inode->i_mapping, index);
1414 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1415 clear_page_dirty_for_io(page);
1421 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1423 unsigned long index = start >> PAGE_SHIFT;
1424 unsigned long end_index = end >> PAGE_SHIFT;
1427 while (index <= end_index) {
1428 page = find_get_page(inode->i_mapping, index);
1429 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1430 __set_page_dirty_nobuffers(page);
1431 account_page_redirty(page);
1437 /* find the first state struct with 'bits' set after 'start', and
1438 * return it. tree->lock must be held. NULL will returned if
1439 * nothing was found after 'start'
1441 static struct extent_state *
1442 find_first_extent_bit_state(struct extent_io_tree *tree,
1443 u64 start, unsigned bits)
1445 struct rb_node *node;
1446 struct extent_state *state;
1449 * this search will find all the extents that end after
1452 node = tree_search(tree, start);
1457 state = rb_entry(node, struct extent_state, rb_node);
1458 if (state->end >= start && (state->state & bits))
1461 node = rb_next(node);
1470 * find the first offset in the io tree with 'bits' set. zero is
1471 * returned if we find something, and *start_ret and *end_ret are
1472 * set to reflect the state struct that was found.
1474 * If nothing was found, 1 is returned. If found something, return 0.
1476 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1477 u64 *start_ret, u64 *end_ret, unsigned bits,
1478 struct extent_state **cached_state)
1480 struct extent_state *state;
1484 spin_lock(&tree->lock);
1485 if (cached_state && *cached_state) {
1486 state = *cached_state;
1487 if (state->end == start - 1 && extent_state_in_tree(state)) {
1488 n = rb_next(&state->rb_node);
1490 state = rb_entry(n, struct extent_state,
1492 if (state->state & bits)
1496 free_extent_state(*cached_state);
1497 *cached_state = NULL;
1500 free_extent_state(*cached_state);
1501 *cached_state = NULL;
1504 state = find_first_extent_bit_state(tree, start, bits);
1507 cache_state_if_flags(state, cached_state, 0);
1508 *start_ret = state->start;
1509 *end_ret = state->end;
1513 spin_unlock(&tree->lock);
1518 * find a contiguous range of bytes in the file marked as delalloc, not
1519 * more than 'max_bytes'. start and end are used to return the range,
1521 * 1 is returned if we find something, 0 if nothing was in the tree
1523 static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
1524 u64 *start, u64 *end, u64 max_bytes,
1525 struct extent_state **cached_state)
1527 struct rb_node *node;
1528 struct extent_state *state;
1529 u64 cur_start = *start;
1531 u64 total_bytes = 0;
1533 spin_lock(&tree->lock);
1536 * this search will find all the extents that end after
1539 node = tree_search(tree, cur_start);
1547 state = rb_entry(node, struct extent_state, rb_node);
1548 if (found && (state->start != cur_start ||
1549 (state->state & EXTENT_BOUNDARY))) {
1552 if (!(state->state & EXTENT_DELALLOC)) {
1558 *start = state->start;
1559 *cached_state = state;
1560 refcount_inc(&state->refs);
1564 cur_start = state->end + 1;
1565 node = rb_next(node);
1566 total_bytes += state->end - state->start + 1;
1567 if (total_bytes >= max_bytes)
1573 spin_unlock(&tree->lock);
1577 static int __process_pages_contig(struct address_space *mapping,
1578 struct page *locked_page,
1579 pgoff_t start_index, pgoff_t end_index,
1580 unsigned long page_ops, pgoff_t *index_ret);
1582 static noinline void __unlock_for_delalloc(struct inode *inode,
1583 struct page *locked_page,
1586 unsigned long index = start >> PAGE_SHIFT;
1587 unsigned long end_index = end >> PAGE_SHIFT;
1589 ASSERT(locked_page);
1590 if (index == locked_page->index && end_index == index)
1593 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1597 static noinline int lock_delalloc_pages(struct inode *inode,
1598 struct page *locked_page,
1602 unsigned long index = delalloc_start >> PAGE_SHIFT;
1603 unsigned long index_ret = index;
1604 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1607 ASSERT(locked_page);
1608 if (index == locked_page->index && index == end_index)
1611 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1612 end_index, PAGE_LOCK, &index_ret);
1614 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1615 (u64)index_ret << PAGE_SHIFT);
1620 * find a contiguous range of bytes in the file marked as delalloc, not
1621 * more than 'max_bytes'. start and end are used to return the range,
1623 * 1 is returned if we find something, 0 if nothing was in the tree
1625 STATIC u64 find_lock_delalloc_range(struct inode *inode,
1626 struct extent_io_tree *tree,
1627 struct page *locked_page, u64 *start,
1628 u64 *end, u64 max_bytes)
1633 struct extent_state *cached_state = NULL;
1638 /* step one, find a bunch of delalloc bytes starting at start */
1639 delalloc_start = *start;
1641 found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1642 max_bytes, &cached_state);
1643 if (!found || delalloc_end <= *start) {
1644 *start = delalloc_start;
1645 *end = delalloc_end;
1646 free_extent_state(cached_state);
1651 * start comes from the offset of locked_page. We have to lock
1652 * pages in order, so we can't process delalloc bytes before
1655 if (delalloc_start < *start)
1656 delalloc_start = *start;
1659 * make sure to limit the number of pages we try to lock down
1661 if (delalloc_end + 1 - delalloc_start > max_bytes)
1662 delalloc_end = delalloc_start + max_bytes - 1;
1664 /* step two, lock all the pages after the page that has start */
1665 ret = lock_delalloc_pages(inode, locked_page,
1666 delalloc_start, delalloc_end);
1667 if (ret == -EAGAIN) {
1668 /* some of the pages are gone, lets avoid looping by
1669 * shortening the size of the delalloc range we're searching
1671 free_extent_state(cached_state);
1672 cached_state = NULL;
1674 max_bytes = PAGE_SIZE;
1682 BUG_ON(ret); /* Only valid values are 0 and -EAGAIN */
1684 /* step three, lock the state bits for the whole range */
1685 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1687 /* then test to make sure it is all still delalloc */
1688 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1689 EXTENT_DELALLOC, 1, cached_state);
1691 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1693 __unlock_for_delalloc(inode, locked_page,
1694 delalloc_start, delalloc_end);
1698 free_extent_state(cached_state);
1699 *start = delalloc_start;
1700 *end = delalloc_end;
1705 static int __process_pages_contig(struct address_space *mapping,
1706 struct page *locked_page,
1707 pgoff_t start_index, pgoff_t end_index,
1708 unsigned long page_ops, pgoff_t *index_ret)
1710 unsigned long nr_pages = end_index - start_index + 1;
1711 unsigned long pages_locked = 0;
1712 pgoff_t index = start_index;
1713 struct page *pages[16];
1718 if (page_ops & PAGE_LOCK) {
1719 ASSERT(page_ops == PAGE_LOCK);
1720 ASSERT(index_ret && *index_ret == start_index);
1723 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1724 mapping_set_error(mapping, -EIO);
1726 while (nr_pages > 0) {
1727 ret = find_get_pages_contig(mapping, index,
1728 min_t(unsigned long,
1729 nr_pages, ARRAY_SIZE(pages)), pages);
1732 * Only if we're going to lock these pages,
1733 * can we find nothing at @index.
1735 ASSERT(page_ops & PAGE_LOCK);
1740 for (i = 0; i < ret; i++) {
1741 if (page_ops & PAGE_SET_PRIVATE2)
1742 SetPagePrivate2(pages[i]);
1744 if (pages[i] == locked_page) {
1749 if (page_ops & PAGE_CLEAR_DIRTY)
1750 clear_page_dirty_for_io(pages[i]);
1751 if (page_ops & PAGE_SET_WRITEBACK)
1752 set_page_writeback(pages[i]);
1753 if (page_ops & PAGE_SET_ERROR)
1754 SetPageError(pages[i]);
1755 if (page_ops & PAGE_END_WRITEBACK)
1756 end_page_writeback(pages[i]);
1757 if (page_ops & PAGE_UNLOCK)
1758 unlock_page(pages[i]);
1759 if (page_ops & PAGE_LOCK) {
1760 lock_page(pages[i]);
1761 if (!PageDirty(pages[i]) ||
1762 pages[i]->mapping != mapping) {
1763 unlock_page(pages[i]);
1764 for (; i < ret; i++)
1778 if (err && index_ret)
1779 *index_ret = start_index + pages_locked - 1;
1783 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1784 u64 delalloc_end, struct page *locked_page,
1785 unsigned clear_bits,
1786 unsigned long page_ops)
1788 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1791 __process_pages_contig(inode->i_mapping, locked_page,
1792 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1797 * count the number of bytes in the tree that have a given bit(s)
1798 * set. This can be fairly slow, except for EXTENT_DIRTY which is
1799 * cached. The total number found is returned.
1801 u64 count_range_bits(struct extent_io_tree *tree,
1802 u64 *start, u64 search_end, u64 max_bytes,
1803 unsigned bits, int contig)
1805 struct rb_node *node;
1806 struct extent_state *state;
1807 u64 cur_start = *start;
1808 u64 total_bytes = 0;
1812 if (WARN_ON(search_end <= cur_start))
1815 spin_lock(&tree->lock);
1816 if (cur_start == 0 && bits == EXTENT_DIRTY) {
1817 total_bytes = tree->dirty_bytes;
1821 * this search will find all the extents that end after
1824 node = tree_search(tree, cur_start);
1829 state = rb_entry(node, struct extent_state, rb_node);
1830 if (state->start > search_end)
1832 if (contig && found && state->start > last + 1)
1834 if (state->end >= cur_start && (state->state & bits) == bits) {
1835 total_bytes += min(search_end, state->end) + 1 -
1836 max(cur_start, state->start);
1837 if (total_bytes >= max_bytes)
1840 *start = max(cur_start, state->start);
1844 } else if (contig && found) {
1847 node = rb_next(node);
1852 spin_unlock(&tree->lock);
1857 * set the private field for a given byte offset in the tree. If there isn't
1858 * an extent_state there already, this does nothing.
1860 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
1861 struct io_failure_record *failrec)
1863 struct rb_node *node;
1864 struct extent_state *state;
1867 spin_lock(&tree->lock);
1869 * this search will find all the extents that end after
1872 node = tree_search(tree, start);
1877 state = rb_entry(node, struct extent_state, rb_node);
1878 if (state->start != start) {
1882 state->failrec = failrec;
1884 spin_unlock(&tree->lock);
1888 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
1889 struct io_failure_record **failrec)
1891 struct rb_node *node;
1892 struct extent_state *state;
1895 spin_lock(&tree->lock);
1897 * this search will find all the extents that end after
1900 node = tree_search(tree, start);
1905 state = rb_entry(node, struct extent_state, rb_node);
1906 if (state->start != start) {
1910 *failrec = state->failrec;
1912 spin_unlock(&tree->lock);
1917 * searches a range in the state tree for a given mask.
1918 * If 'filled' == 1, this returns 1 only if every extent in the tree
1919 * has the bits set. Otherwise, 1 is returned if any bit in the
1920 * range is found set.
1922 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1923 unsigned bits, int filled, struct extent_state *cached)
1925 struct extent_state *state = NULL;
1926 struct rb_node *node;
1929 spin_lock(&tree->lock);
1930 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
1931 cached->end > start)
1932 node = &cached->rb_node;
1934 node = tree_search(tree, start);
1935 while (node && start <= end) {
1936 state = rb_entry(node, struct extent_state, rb_node);
1938 if (filled && state->start > start) {
1943 if (state->start > end)
1946 if (state->state & bits) {
1950 } else if (filled) {
1955 if (state->end == (u64)-1)
1958 start = state->end + 1;
1961 node = rb_next(node);
1968 spin_unlock(&tree->lock);
1973 * helper function to set a given page up to date if all the
1974 * extents in the tree for that page are up to date
1976 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1978 u64 start = page_offset(page);
1979 u64 end = start + PAGE_SIZE - 1;
1980 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1981 SetPageUptodate(page);
1984 int free_io_failure(struct extent_io_tree *failure_tree,
1985 struct extent_io_tree *io_tree,
1986 struct io_failure_record *rec)
1991 set_state_failrec(failure_tree, rec->start, NULL);
1992 ret = clear_extent_bits(failure_tree, rec->start,
1993 rec->start + rec->len - 1,
1994 EXTENT_LOCKED | EXTENT_DIRTY);
1998 ret = clear_extent_bits(io_tree, rec->start,
1999 rec->start + rec->len - 1,
2009 * this bypasses the standard btrfs submit functions deliberately, as
2010 * the standard behavior is to write all copies in a raid setup. here we only
2011 * want to write the one bad copy. so we do the mapping for ourselves and issue
2012 * submit_bio directly.
2013 * to avoid any synchronization issues, wait for the data after writing, which
2014 * actually prevents the read that triggered the error from finishing.
2015 * currently, there can be no more than two copies of every data bit. thus,
2016 * exactly one rewrite is required.
2018 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2019 u64 length, u64 logical, struct page *page,
2020 unsigned int pg_offset, int mirror_num)
2023 struct btrfs_device *dev;
2026 struct btrfs_bio *bbio = NULL;
2029 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2030 BUG_ON(!mirror_num);
2032 bio = btrfs_io_bio_alloc(1);
2033 bio->bi_iter.bi_size = 0;
2034 map_length = length;
2037 * Avoid races with device replace and make sure our bbio has devices
2038 * associated to its stripes that don't go away while we are doing the
2039 * read repair operation.
2041 btrfs_bio_counter_inc_blocked(fs_info);
2042 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2044 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2045 * to update all raid stripes, but here we just want to correct
2046 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2047 * stripe's dev and sector.
2049 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2050 &map_length, &bbio, 0);
2052 btrfs_bio_counter_dec(fs_info);
2056 ASSERT(bbio->mirror_num == 1);
2058 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2059 &map_length, &bbio, mirror_num);
2061 btrfs_bio_counter_dec(fs_info);
2065 BUG_ON(mirror_num != bbio->mirror_num);
2068 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2069 bio->bi_iter.bi_sector = sector;
2070 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2071 btrfs_put_bbio(bbio);
2072 if (!dev || !dev->bdev ||
2073 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2074 btrfs_bio_counter_dec(fs_info);
2078 bio_set_dev(bio, dev->bdev);
2079 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2080 bio_add_page(bio, page, length, pg_offset);
2082 if (btrfsic_submit_bio_wait(bio)) {
2083 /* try to remap that extent elsewhere? */
2084 btrfs_bio_counter_dec(fs_info);
2086 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2090 btrfs_info_rl_in_rcu(fs_info,
2091 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2093 rcu_str_deref(dev->name), sector);
2094 btrfs_bio_counter_dec(fs_info);
2099 int repair_eb_io_failure(struct btrfs_fs_info *fs_info,
2100 struct extent_buffer *eb, int mirror_num)
2102 u64 start = eb->start;
2103 int i, num_pages = num_extent_pages(eb);
2106 if (sb_rdonly(fs_info->sb))
2109 for (i = 0; i < num_pages; i++) {
2110 struct page *p = eb->pages[i];
2112 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2113 start - page_offset(p), mirror_num);
2123 * each time an IO finishes, we do a fast check in the IO failure tree
2124 * to see if we need to process or clean up an io_failure_record
2126 int clean_io_failure(struct btrfs_fs_info *fs_info,
2127 struct extent_io_tree *failure_tree,
2128 struct extent_io_tree *io_tree, u64 start,
2129 struct page *page, u64 ino, unsigned int pg_offset)
2132 struct io_failure_record *failrec;
2133 struct extent_state *state;
2138 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2143 ret = get_state_failrec(failure_tree, start, &failrec);
2147 BUG_ON(!failrec->this_mirror);
2149 if (failrec->in_validation) {
2150 /* there was no real error, just free the record */
2151 btrfs_debug(fs_info,
2152 "clean_io_failure: freeing dummy error at %llu",
2156 if (sb_rdonly(fs_info->sb))
2159 spin_lock(&io_tree->lock);
2160 state = find_first_extent_bit_state(io_tree,
2163 spin_unlock(&io_tree->lock);
2165 if (state && state->start <= failrec->start &&
2166 state->end >= failrec->start + failrec->len - 1) {
2167 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2169 if (num_copies > 1) {
2170 repair_io_failure(fs_info, ino, start, failrec->len,
2171 failrec->logical, page, pg_offset,
2172 failrec->failed_mirror);
2177 free_io_failure(failure_tree, io_tree, failrec);
2183 * Can be called when
2184 * - hold extent lock
2185 * - under ordered extent
2186 * - the inode is freeing
2188 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2190 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2191 struct io_failure_record *failrec;
2192 struct extent_state *state, *next;
2194 if (RB_EMPTY_ROOT(&failure_tree->state))
2197 spin_lock(&failure_tree->lock);
2198 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2200 if (state->start > end)
2203 ASSERT(state->end <= end);
2205 next = next_state(state);
2207 failrec = state->failrec;
2208 free_extent_state(state);
2213 spin_unlock(&failure_tree->lock);
2216 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2217 struct io_failure_record **failrec_ret)
2219 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2220 struct io_failure_record *failrec;
2221 struct extent_map *em;
2222 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2223 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2224 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2228 ret = get_state_failrec(failure_tree, start, &failrec);
2230 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2234 failrec->start = start;
2235 failrec->len = end - start + 1;
2236 failrec->this_mirror = 0;
2237 failrec->bio_flags = 0;
2238 failrec->in_validation = 0;
2240 read_lock(&em_tree->lock);
2241 em = lookup_extent_mapping(em_tree, start, failrec->len);
2243 read_unlock(&em_tree->lock);
2248 if (em->start > start || em->start + em->len <= start) {
2249 free_extent_map(em);
2252 read_unlock(&em_tree->lock);
2258 logical = start - em->start;
2259 logical = em->block_start + logical;
2260 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2261 logical = em->block_start;
2262 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2263 extent_set_compress_type(&failrec->bio_flags,
2267 btrfs_debug(fs_info,
2268 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2269 logical, start, failrec->len);
2271 failrec->logical = logical;
2272 free_extent_map(em);
2274 /* set the bits in the private failure tree */
2275 ret = set_extent_bits(failure_tree, start, end,
2276 EXTENT_LOCKED | EXTENT_DIRTY);
2278 ret = set_state_failrec(failure_tree, start, failrec);
2279 /* set the bits in the inode's tree */
2281 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2287 btrfs_debug(fs_info,
2288 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2289 failrec->logical, failrec->start, failrec->len,
2290 failrec->in_validation);
2292 * when data can be on disk more than twice, add to failrec here
2293 * (e.g. with a list for failed_mirror) to make
2294 * clean_io_failure() clean all those errors at once.
2298 *failrec_ret = failrec;
2303 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2304 struct io_failure_record *failrec, int failed_mirror)
2306 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2309 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2310 if (num_copies == 1) {
2312 * we only have a single copy of the data, so don't bother with
2313 * all the retry and error correction code that follows. no
2314 * matter what the error is, it is very likely to persist.
2316 btrfs_debug(fs_info,
2317 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2318 num_copies, failrec->this_mirror, failed_mirror);
2323 * there are two premises:
2324 * a) deliver good data to the caller
2325 * b) correct the bad sectors on disk
2327 if (failed_bio_pages > 1) {
2329 * to fulfill b), we need to know the exact failing sectors, as
2330 * we don't want to rewrite any more than the failed ones. thus,
2331 * we need separate read requests for the failed bio
2333 * if the following BUG_ON triggers, our validation request got
2334 * merged. we need separate requests for our algorithm to work.
2336 BUG_ON(failrec->in_validation);
2337 failrec->in_validation = 1;
2338 failrec->this_mirror = failed_mirror;
2341 * we're ready to fulfill a) and b) alongside. get a good copy
2342 * of the failed sector and if we succeed, we have setup
2343 * everything for repair_io_failure to do the rest for us.
2345 if (failrec->in_validation) {
2346 BUG_ON(failrec->this_mirror != failed_mirror);
2347 failrec->in_validation = 0;
2348 failrec->this_mirror = 0;
2350 failrec->failed_mirror = failed_mirror;
2351 failrec->this_mirror++;
2352 if (failrec->this_mirror == failed_mirror)
2353 failrec->this_mirror++;
2356 if (failrec->this_mirror > num_copies) {
2357 btrfs_debug(fs_info,
2358 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2359 num_copies, failrec->this_mirror, failed_mirror);
2367 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2368 struct io_failure_record *failrec,
2369 struct page *page, int pg_offset, int icsum,
2370 bio_end_io_t *endio_func, void *data)
2372 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2374 struct btrfs_io_bio *btrfs_failed_bio;
2375 struct btrfs_io_bio *btrfs_bio;
2377 bio = btrfs_io_bio_alloc(1);
2378 bio->bi_end_io = endio_func;
2379 bio->bi_iter.bi_sector = failrec->logical >> 9;
2380 bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2381 bio->bi_iter.bi_size = 0;
2382 bio->bi_private = data;
2384 btrfs_failed_bio = btrfs_io_bio(failed_bio);
2385 if (btrfs_failed_bio->csum) {
2386 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2388 btrfs_bio = btrfs_io_bio(bio);
2389 btrfs_bio->csum = btrfs_bio->csum_inline;
2391 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2395 bio_add_page(bio, page, failrec->len, pg_offset);
2401 * this is a generic handler for readpage errors (default
2402 * readpage_io_failed_hook). if other copies exist, read those and write back
2403 * good data to the failed position. does not investigate in remapping the
2404 * failed extent elsewhere, hoping the device will be smart enough to do this as
2408 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2409 struct page *page, u64 start, u64 end,
2412 struct io_failure_record *failrec;
2413 struct inode *inode = page->mapping->host;
2414 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2415 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2418 blk_status_t status;
2420 unsigned failed_bio_pages = bio_pages_all(failed_bio);
2422 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2424 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2428 if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2430 free_io_failure(failure_tree, tree, failrec);
2434 if (failed_bio_pages > 1)
2435 read_mode |= REQ_FAILFAST_DEV;
2437 phy_offset >>= inode->i_sb->s_blocksize_bits;
2438 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2439 start - page_offset(page),
2440 (int)phy_offset, failed_bio->bi_end_io,
2442 bio->bi_opf = REQ_OP_READ | read_mode;
2444 btrfs_debug(btrfs_sb(inode->i_sb),
2445 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2446 read_mode, failrec->this_mirror, failrec->in_validation);
2448 status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2449 failrec->bio_flags, 0);
2451 free_io_failure(failure_tree, tree, failrec);
2453 ret = blk_status_to_errno(status);
2459 /* lots and lots of room for performance fixes in the end_bio funcs */
2461 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2463 int uptodate = (err == 0);
2464 struct extent_io_tree *tree;
2467 tree = &BTRFS_I(page->mapping->host)->io_tree;
2469 if (tree->ops && tree->ops->writepage_end_io_hook)
2470 tree->ops->writepage_end_io_hook(page, start, end, NULL,
2474 ClearPageUptodate(page);
2476 ret = err < 0 ? err : -EIO;
2477 mapping_set_error(page->mapping, ret);
2482 * after a writepage IO is done, we need to:
2483 * clear the uptodate bits on error
2484 * clear the writeback bits in the extent tree for this IO
2485 * end_page_writeback if the page has no more pending IO
2487 * Scheduling is not allowed, so the extent state tree is expected
2488 * to have one and only one object corresponding to this IO.
2490 static void end_bio_extent_writepage(struct bio *bio)
2492 int error = blk_status_to_errno(bio->bi_status);
2493 struct bio_vec *bvec;
2498 ASSERT(!bio_flagged(bio, BIO_CLONED));
2499 bio_for_each_segment_all(bvec, bio, i) {
2500 struct page *page = bvec->bv_page;
2501 struct inode *inode = page->mapping->host;
2502 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2504 /* We always issue full-page reads, but if some block
2505 * in a page fails to read, blk_update_request() will
2506 * advance bv_offset and adjust bv_len to compensate.
2507 * Print a warning for nonzero offsets, and an error
2508 * if they don't add up to a full page. */
2509 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2510 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2512 "partial page write in btrfs with offset %u and length %u",
2513 bvec->bv_offset, bvec->bv_len);
2516 "incomplete page write in btrfs with offset %u and length %u",
2517 bvec->bv_offset, bvec->bv_len);
2520 start = page_offset(page);
2521 end = start + bvec->bv_offset + bvec->bv_len - 1;
2523 end_extent_writepage(page, error, start, end);
2524 end_page_writeback(page);
2531 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2534 struct extent_state *cached = NULL;
2535 u64 end = start + len - 1;
2537 if (uptodate && tree->track_uptodate)
2538 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2539 unlock_extent_cached_atomic(tree, start, end, &cached);
2543 * after a readpage IO is done, we need to:
2544 * clear the uptodate bits on error
2545 * set the uptodate bits if things worked
2546 * set the page up to date if all extents in the tree are uptodate
2547 * clear the lock bit in the extent tree
2548 * unlock the page if there are no other extents locked for it
2550 * Scheduling is not allowed, so the extent state tree is expected
2551 * to have one and only one object corresponding to this IO.
2553 static void end_bio_extent_readpage(struct bio *bio)
2555 struct bio_vec *bvec;
2556 int uptodate = !bio->bi_status;
2557 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2558 struct extent_io_tree *tree, *failure_tree;
2563 u64 extent_start = 0;
2569 ASSERT(!bio_flagged(bio, BIO_CLONED));
2570 bio_for_each_segment_all(bvec, bio, i) {
2571 struct page *page = bvec->bv_page;
2572 struct inode *inode = page->mapping->host;
2573 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2575 btrfs_debug(fs_info,
2576 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2577 (u64)bio->bi_iter.bi_sector, bio->bi_status,
2578 io_bio->mirror_num);
2579 tree = &BTRFS_I(inode)->io_tree;
2580 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2582 /* We always issue full-page reads, but if some block
2583 * in a page fails to read, blk_update_request() will
2584 * advance bv_offset and adjust bv_len to compensate.
2585 * Print a warning for nonzero offsets, and an error
2586 * if they don't add up to a full page. */
2587 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2588 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2590 "partial page read in btrfs with offset %u and length %u",
2591 bvec->bv_offset, bvec->bv_len);
2594 "incomplete page read in btrfs with offset %u and length %u",
2595 bvec->bv_offset, bvec->bv_len);
2598 start = page_offset(page);
2599 end = start + bvec->bv_offset + bvec->bv_len - 1;
2602 mirror = io_bio->mirror_num;
2603 if (likely(uptodate && tree->ops)) {
2604 ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2610 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2611 failure_tree, tree, start,
2613 btrfs_ino(BTRFS_I(inode)), 0);
2616 if (likely(uptodate))
2620 ret = tree->ops->readpage_io_failed_hook(page, mirror);
2621 if (ret == -EAGAIN) {
2623 * Data inode's readpage_io_failed_hook() always
2626 * The generic bio_readpage_error handles errors
2627 * the following way: If possible, new read
2628 * requests are created and submitted and will
2629 * end up in end_bio_extent_readpage as well (if
2630 * we're lucky, not in the !uptodate case). In
2631 * that case it returns 0 and we just go on with
2632 * the next page in our bio. If it can't handle
2633 * the error it will return -EIO and we remain
2634 * responsible for that page.
2636 ret = bio_readpage_error(bio, offset, page,
2637 start, end, mirror);
2639 uptodate = !bio->bi_status;
2646 * metadata's readpage_io_failed_hook() always returns
2647 * -EIO and fixes nothing. -EIO is also returned if
2648 * data inode error could not be fixed.
2650 ASSERT(ret == -EIO);
2653 if (likely(uptodate)) {
2654 loff_t i_size = i_size_read(inode);
2655 pgoff_t end_index = i_size >> PAGE_SHIFT;
2658 /* Zero out the end if this page straddles i_size */
2659 off = i_size & (PAGE_SIZE-1);
2660 if (page->index == end_index && off)
2661 zero_user_segment(page, off, PAGE_SIZE);
2662 SetPageUptodate(page);
2664 ClearPageUptodate(page);
2670 if (unlikely(!uptodate)) {
2672 endio_readpage_release_extent(tree,
2678 endio_readpage_release_extent(tree, start,
2679 end - start + 1, 0);
2680 } else if (!extent_len) {
2681 extent_start = start;
2682 extent_len = end + 1 - start;
2683 } else if (extent_start + extent_len == start) {
2684 extent_len += end + 1 - start;
2686 endio_readpage_release_extent(tree, extent_start,
2687 extent_len, uptodate);
2688 extent_start = start;
2689 extent_len = end + 1 - start;
2694 endio_readpage_release_extent(tree, extent_start, extent_len,
2697 io_bio->end_io(io_bio, blk_status_to_errno(bio->bi_status));
2702 * Initialize the members up to but not including 'bio'. Use after allocating a
2703 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2704 * 'bio' because use of __GFP_ZERO is not supported.
2706 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2708 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2712 * The following helpers allocate a bio. As it's backed by a bioset, it'll
2713 * never fail. We're returning a bio right now but you can call btrfs_io_bio
2714 * for the appropriate container_of magic
2716 struct bio *btrfs_bio_alloc(struct block_device *bdev, u64 first_byte)
2720 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2721 bio_set_dev(bio, bdev);
2722 bio->bi_iter.bi_sector = first_byte >> 9;
2723 btrfs_io_bio_init(btrfs_io_bio(bio));
2727 struct bio *btrfs_bio_clone(struct bio *bio)
2729 struct btrfs_io_bio *btrfs_bio;
2732 /* Bio allocation backed by a bioset does not fail */
2733 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2734 btrfs_bio = btrfs_io_bio(new);
2735 btrfs_io_bio_init(btrfs_bio);
2736 btrfs_bio->iter = bio->bi_iter;
2740 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2744 /* Bio allocation backed by a bioset does not fail */
2745 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2746 btrfs_io_bio_init(btrfs_io_bio(bio));
2750 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2753 struct btrfs_io_bio *btrfs_bio;
2755 /* this will never fail when it's backed by a bioset */
2756 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2759 btrfs_bio = btrfs_io_bio(bio);
2760 btrfs_io_bio_init(btrfs_bio);
2762 bio_trim(bio, offset >> 9, size >> 9);
2763 btrfs_bio->iter = bio->bi_iter;
2768 * @opf: bio REQ_OP_* and REQ_* flags as one value
2769 * @tree: tree so we can call our merge_bio hook
2770 * @wbc: optional writeback control for io accounting
2771 * @page: page to add to the bio
2772 * @pg_offset: offset of the new bio or to check whether we are adding
2773 * a contiguous page to the previous one
2774 * @size: portion of page that we want to write
2775 * @offset: starting offset in the page
2776 * @bdev: attach newly created bios to this bdev
2777 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
2778 * @end_io_func: end_io callback for new bio
2779 * @mirror_num: desired mirror to read/write
2780 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
2781 * @bio_flags: flags of the current bio to see if we can merge them
2783 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2784 struct writeback_control *wbc,
2785 struct page *page, u64 offset,
2786 size_t size, unsigned long pg_offset,
2787 struct block_device *bdev,
2788 struct bio **bio_ret,
2789 bio_end_io_t end_io_func,
2791 unsigned long prev_bio_flags,
2792 unsigned long bio_flags,
2793 bool force_bio_submit)
2797 size_t page_size = min_t(size_t, size, PAGE_SIZE);
2798 sector_t sector = offset >> 9;
2804 bool can_merge = true;
2807 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2808 contig = bio->bi_iter.bi_sector == sector;
2810 contig = bio_end_sector(bio) == sector;
2812 if (tree->ops && btrfs_merge_bio_hook(page, offset, page_size,
2816 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2818 bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2819 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2827 wbc_account_io(wbc, page, page_size);
2832 bio = btrfs_bio_alloc(bdev, offset);
2833 bio_add_page(bio, page, page_size, pg_offset);
2834 bio->bi_end_io = end_io_func;
2835 bio->bi_private = tree;
2836 bio->bi_write_hint = page->mapping->host->i_write_hint;
2839 wbc_init_bio(wbc, bio);
2840 wbc_account_io(wbc, page, page_size);
2848 static void attach_extent_buffer_page(struct extent_buffer *eb,
2851 if (!PagePrivate(page)) {
2852 SetPagePrivate(page);
2854 set_page_private(page, (unsigned long)eb);
2856 WARN_ON(page->private != (unsigned long)eb);
2860 void set_page_extent_mapped(struct page *page)
2862 if (!PagePrivate(page)) {
2863 SetPagePrivate(page);
2865 set_page_private(page, EXTENT_PAGE_PRIVATE);
2869 static struct extent_map *
2870 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
2871 u64 start, u64 len, get_extent_t *get_extent,
2872 struct extent_map **em_cached)
2874 struct extent_map *em;
2876 if (em_cached && *em_cached) {
2878 if (extent_map_in_tree(em) && start >= em->start &&
2879 start < extent_map_end(em)) {
2880 refcount_inc(&em->refs);
2884 free_extent_map(em);
2888 em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
2889 if (em_cached && !IS_ERR_OR_NULL(em)) {
2891 refcount_inc(&em->refs);
2897 * basic readpage implementation. Locked extent state structs are inserted
2898 * into the tree that are removed when the IO is done (by the end_io
2900 * XXX JDM: This needs looking at to ensure proper page locking
2901 * return 0 on success, otherwise return error
2903 static int __do_readpage(struct extent_io_tree *tree,
2905 get_extent_t *get_extent,
2906 struct extent_map **em_cached,
2907 struct bio **bio, int mirror_num,
2908 unsigned long *bio_flags, unsigned int read_flags,
2911 struct inode *inode = page->mapping->host;
2912 u64 start = page_offset(page);
2913 const u64 end = start + PAGE_SIZE - 1;
2916 u64 last_byte = i_size_read(inode);
2919 struct extent_map *em;
2920 struct block_device *bdev;
2923 size_t pg_offset = 0;
2925 size_t disk_io_size;
2926 size_t blocksize = inode->i_sb->s_blocksize;
2927 unsigned long this_bio_flag = 0;
2929 set_page_extent_mapped(page);
2931 if (!PageUptodate(page)) {
2932 if (cleancache_get_page(page) == 0) {
2933 BUG_ON(blocksize != PAGE_SIZE);
2934 unlock_extent(tree, start, end);
2939 if (page->index == last_byte >> PAGE_SHIFT) {
2941 size_t zero_offset = last_byte & (PAGE_SIZE - 1);
2944 iosize = PAGE_SIZE - zero_offset;
2945 userpage = kmap_atomic(page);
2946 memset(userpage + zero_offset, 0, iosize);
2947 flush_dcache_page(page);
2948 kunmap_atomic(userpage);
2951 while (cur <= end) {
2952 bool force_bio_submit = false;
2955 if (cur >= last_byte) {
2957 struct extent_state *cached = NULL;
2959 iosize = PAGE_SIZE - pg_offset;
2960 userpage = kmap_atomic(page);
2961 memset(userpage + pg_offset, 0, iosize);
2962 flush_dcache_page(page);
2963 kunmap_atomic(userpage);
2964 set_extent_uptodate(tree, cur, cur + iosize - 1,
2966 unlock_extent_cached(tree, cur,
2967 cur + iosize - 1, &cached);
2970 em = __get_extent_map(inode, page, pg_offset, cur,
2971 end - cur + 1, get_extent, em_cached);
2972 if (IS_ERR_OR_NULL(em)) {
2974 unlock_extent(tree, cur, end);
2977 extent_offset = cur - em->start;
2978 BUG_ON(extent_map_end(em) <= cur);
2981 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2982 this_bio_flag |= EXTENT_BIO_COMPRESSED;
2983 extent_set_compress_type(&this_bio_flag,
2987 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2988 cur_end = min(extent_map_end(em) - 1, end);
2989 iosize = ALIGN(iosize, blocksize);
2990 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2991 disk_io_size = em->block_len;
2992 offset = em->block_start;
2994 offset = em->block_start + extent_offset;
2995 disk_io_size = iosize;
2998 block_start = em->block_start;
2999 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3000 block_start = EXTENT_MAP_HOLE;
3003 * If we have a file range that points to a compressed extent
3004 * and it's followed by a consecutive file range that points to
3005 * to the same compressed extent (possibly with a different
3006 * offset and/or length, so it either points to the whole extent
3007 * or only part of it), we must make sure we do not submit a
3008 * single bio to populate the pages for the 2 ranges because
3009 * this makes the compressed extent read zero out the pages
3010 * belonging to the 2nd range. Imagine the following scenario:
3013 * [0 - 8K] [8K - 24K]
3016 * points to extent X, points to extent X,
3017 * offset 4K, length of 8K offset 0, length 16K
3019 * [extent X, compressed length = 4K uncompressed length = 16K]
3021 * If the bio to read the compressed extent covers both ranges,
3022 * it will decompress extent X into the pages belonging to the
3023 * first range and then it will stop, zeroing out the remaining
3024 * pages that belong to the other range that points to extent X.
3025 * So here we make sure we submit 2 bios, one for the first
3026 * range and another one for the third range. Both will target
3027 * the same physical extent from disk, but we can't currently
3028 * make the compressed bio endio callback populate the pages
3029 * for both ranges because each compressed bio is tightly
3030 * coupled with a single extent map, and each range can have
3031 * an extent map with a different offset value relative to the
3032 * uncompressed data of our extent and different lengths. This
3033 * is a corner case so we prioritize correctness over
3034 * non-optimal behavior (submitting 2 bios for the same extent).
3036 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3037 prev_em_start && *prev_em_start != (u64)-1 &&
3038 *prev_em_start != em->start)
3039 force_bio_submit = true;
3042 *prev_em_start = em->start;
3044 free_extent_map(em);
3047 /* we've found a hole, just zero and go on */
3048 if (block_start == EXTENT_MAP_HOLE) {
3050 struct extent_state *cached = NULL;
3052 userpage = kmap_atomic(page);
3053 memset(userpage + pg_offset, 0, iosize);
3054 flush_dcache_page(page);
3055 kunmap_atomic(userpage);
3057 set_extent_uptodate(tree, cur, cur + iosize - 1,
3059 unlock_extent_cached(tree, cur,
3060 cur + iosize - 1, &cached);
3062 pg_offset += iosize;
3065 /* the get_extent function already copied into the page */
3066 if (test_range_bit(tree, cur, cur_end,
3067 EXTENT_UPTODATE, 1, NULL)) {
3068 check_page_uptodate(tree, page);
3069 unlock_extent(tree, cur, cur + iosize - 1);
3071 pg_offset += iosize;
3074 /* we have an inline extent but it didn't get marked up
3075 * to date. Error out
3077 if (block_start == EXTENT_MAP_INLINE) {
3079 unlock_extent(tree, cur, cur + iosize - 1);
3081 pg_offset += iosize;
3085 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3086 page, offset, disk_io_size,
3087 pg_offset, bdev, bio,
3088 end_bio_extent_readpage, mirror_num,
3094 *bio_flags = this_bio_flag;
3097 unlock_extent(tree, cur, cur + iosize - 1);
3101 pg_offset += iosize;
3105 if (!PageError(page))
3106 SetPageUptodate(page);
3112 static inline void __do_contiguous_readpages(struct extent_io_tree *tree,
3113 struct page *pages[], int nr_pages,
3115 struct extent_map **em_cached,
3117 unsigned long *bio_flags,
3120 struct inode *inode;
3121 struct btrfs_ordered_extent *ordered;
3124 inode = pages[0]->mapping->host;
3126 lock_extent(tree, start, end);
3127 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3131 unlock_extent(tree, start, end);
3132 btrfs_start_ordered_extent(inode, ordered, 1);
3133 btrfs_put_ordered_extent(ordered);
3136 for (index = 0; index < nr_pages; index++) {
3137 __do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3138 bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3139 put_page(pages[index]);
3143 static void __extent_readpages(struct extent_io_tree *tree,
3144 struct page *pages[],
3146 struct extent_map **em_cached,
3147 struct bio **bio, unsigned long *bio_flags,
3154 int first_index = 0;
3156 for (index = 0; index < nr_pages; index++) {
3157 page_start = page_offset(pages[index]);
3160 end = start + PAGE_SIZE - 1;
3161 first_index = index;
3162 } else if (end + 1 == page_start) {
3165 __do_contiguous_readpages(tree, &pages[first_index],
3166 index - first_index, start,
3171 end = start + PAGE_SIZE - 1;
3172 first_index = index;
3177 __do_contiguous_readpages(tree, &pages[first_index],
3178 index - first_index, start,
3179 end, em_cached, bio,
3180 bio_flags, prev_em_start);
3183 static int __extent_read_full_page(struct extent_io_tree *tree,
3185 get_extent_t *get_extent,
3186 struct bio **bio, int mirror_num,
3187 unsigned long *bio_flags,
3188 unsigned int read_flags)
3190 struct inode *inode = page->mapping->host;
3191 struct btrfs_ordered_extent *ordered;
3192 u64 start = page_offset(page);
3193 u64 end = start + PAGE_SIZE - 1;
3197 lock_extent(tree, start, end);
3198 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3202 unlock_extent(tree, start, end);
3203 btrfs_start_ordered_extent(inode, ordered, 1);
3204 btrfs_put_ordered_extent(ordered);
3207 ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3208 bio_flags, read_flags, NULL);
3212 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3213 get_extent_t *get_extent, int mirror_num)
3215 struct bio *bio = NULL;
3216 unsigned long bio_flags = 0;
3219 ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3222 ret = submit_one_bio(bio, mirror_num, bio_flags);
3226 static void update_nr_written(struct writeback_control *wbc,
3227 unsigned long nr_written)
3229 wbc->nr_to_write -= nr_written;
3233 * helper for __extent_writepage, doing all of the delayed allocation setup.
3235 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3236 * to write the page (copy into inline extent). In this case the IO has
3237 * been started and the page is already unlocked.
3239 * This returns 0 if all went well (page still locked)
3240 * This returns < 0 if there were errors (page still locked)
3242 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3243 struct page *page, struct writeback_control *wbc,
3244 struct extent_page_data *epd,
3246 unsigned long *nr_written)
3248 struct extent_io_tree *tree = epd->tree;
3249 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3251 u64 delalloc_to_write = 0;
3252 u64 delalloc_end = 0;
3254 int page_started = 0;
3256 if (epd->extent_locked)
3259 while (delalloc_end < page_end) {
3260 nr_delalloc = find_lock_delalloc_range(inode, tree,
3264 BTRFS_MAX_EXTENT_SIZE);
3265 if (nr_delalloc == 0) {
3266 delalloc_start = delalloc_end + 1;
3269 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3270 delalloc_end, &page_started, nr_written, wbc);
3271 /* File system has been set read-only */
3275 * btrfs_run_delalloc_range should return < 0 for error
3276 * but just in case, we use > 0 here meaning the IO is
3277 * started, so we don't want to return > 0 unless
3278 * things are going well.
3280 ret = ret < 0 ? ret : -EIO;
3284 * delalloc_end is already one less than the total length, so
3285 * we don't subtract one from PAGE_SIZE
3287 delalloc_to_write += (delalloc_end - delalloc_start +
3288 PAGE_SIZE) >> PAGE_SHIFT;
3289 delalloc_start = delalloc_end + 1;
3291 if (wbc->nr_to_write < delalloc_to_write) {
3294 if (delalloc_to_write < thresh * 2)
3295 thresh = delalloc_to_write;
3296 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3300 /* did the fill delalloc function already unlock and start
3305 * we've unlocked the page, so we can't update
3306 * the mapping's writeback index, just update
3309 wbc->nr_to_write -= *nr_written;
3320 * helper for __extent_writepage. This calls the writepage start hooks,
3321 * and does the loop to map the page into extents and bios.
3323 * We return 1 if the IO is started and the page is unlocked,
3324 * 0 if all went well (page still locked)
3325 * < 0 if there were errors (page still locked)
3327 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3329 struct writeback_control *wbc,
3330 struct extent_page_data *epd,
3332 unsigned long nr_written,
3333 unsigned int write_flags, int *nr_ret)
3335 struct extent_io_tree *tree = epd->tree;
3336 u64 start = page_offset(page);
3337 u64 page_end = start + PAGE_SIZE - 1;
3343 struct extent_map *em;
3344 struct block_device *bdev;
3345 size_t pg_offset = 0;
3351 if (tree->ops && tree->ops->writepage_start_hook) {
3352 ret = tree->ops->writepage_start_hook(page, start,
3355 /* Fixup worker will requeue */
3357 wbc->pages_skipped++;
3359 redirty_page_for_writepage(wbc, page);
3361 update_nr_written(wbc, nr_written);
3368 * we don't want to touch the inode after unlocking the page,
3369 * so we update the mapping writeback index now
3371 update_nr_written(wbc, nr_written + 1);
3374 if (i_size <= start) {
3375 if (tree->ops && tree->ops->writepage_end_io_hook)
3376 tree->ops->writepage_end_io_hook(page, start,
3381 blocksize = inode->i_sb->s_blocksize;
3383 while (cur <= end) {
3387 if (cur >= i_size) {
3388 if (tree->ops && tree->ops->writepage_end_io_hook)
3389 tree->ops->writepage_end_io_hook(page, cur,
3393 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3395 if (IS_ERR_OR_NULL(em)) {
3397 ret = PTR_ERR_OR_ZERO(em);
3401 extent_offset = cur - em->start;
3402 em_end = extent_map_end(em);
3403 BUG_ON(em_end <= cur);
3405 iosize = min(em_end - cur, end - cur + 1);
3406 iosize = ALIGN(iosize, blocksize);
3407 offset = em->block_start + extent_offset;
3409 block_start = em->block_start;
3410 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3411 free_extent_map(em);
3415 * compressed and inline extents are written through other
3418 if (compressed || block_start == EXTENT_MAP_HOLE ||
3419 block_start == EXTENT_MAP_INLINE) {
3421 * end_io notification does not happen here for
3422 * compressed extents
3424 if (!compressed && tree->ops &&
3425 tree->ops->writepage_end_io_hook)
3426 tree->ops->writepage_end_io_hook(page, cur,
3429 else if (compressed) {
3430 /* we don't want to end_page_writeback on
3431 * a compressed extent. this happens
3438 pg_offset += iosize;
3442 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3443 if (!PageWriteback(page)) {
3444 btrfs_err(BTRFS_I(inode)->root->fs_info,
3445 "page %lu not writeback, cur %llu end %llu",
3446 page->index, cur, end);
3449 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3450 page, offset, iosize, pg_offset,
3452 end_bio_extent_writepage,
3456 if (PageWriteback(page))
3457 end_page_writeback(page);
3461 pg_offset += iosize;
3470 * the writepage semantics are similar to regular writepage. extent
3471 * records are inserted to lock ranges in the tree, and as dirty areas
3472 * are found, they are marked writeback. Then the lock bits are removed
3473 * and the end_io handler clears the writeback ranges
3475 * Return 0 if everything goes well.
3476 * Return <0 for error.
3478 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3479 struct extent_page_data *epd)
3481 struct inode *inode = page->mapping->host;
3482 u64 start = page_offset(page);
3483 u64 page_end = start + PAGE_SIZE - 1;
3486 size_t pg_offset = 0;
3487 loff_t i_size = i_size_read(inode);
3488 unsigned long end_index = i_size >> PAGE_SHIFT;
3489 unsigned int write_flags = 0;
3490 unsigned long nr_written = 0;
3492 write_flags = wbc_to_write_flags(wbc);
3494 trace___extent_writepage(page, inode, wbc);
3496 WARN_ON(!PageLocked(page));
3498 ClearPageError(page);
3500 pg_offset = i_size & (PAGE_SIZE - 1);
3501 if (page->index > end_index ||
3502 (page->index == end_index && !pg_offset)) {
3503 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3508 if (page->index == end_index) {
3511 userpage = kmap_atomic(page);
3512 memset(userpage + pg_offset, 0,
3513 PAGE_SIZE - pg_offset);
3514 kunmap_atomic(userpage);
3515 flush_dcache_page(page);
3520 set_page_extent_mapped(page);
3522 ret = writepage_delalloc(inode, page, wbc, epd, start, &nr_written);
3528 ret = __extent_writepage_io(inode, page, wbc, epd,
3529 i_size, nr_written, write_flags, &nr);
3535 /* make sure the mapping tag for page dirty gets cleared */
3536 set_page_writeback(page);
3537 end_page_writeback(page);
3539 if (PageError(page)) {
3540 ret = ret < 0 ? ret : -EIO;
3541 end_extent_writepage(page, ret, start, page_end);
3551 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3553 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3554 TASK_UNINTERRUPTIBLE);
3557 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3559 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3560 smp_mb__after_atomic();
3561 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3565 * Lock eb pages and flush the bio if we can't the locks
3567 * Return 0 if nothing went wrong
3568 * Return >0 is same as 0, except bio is not submitted
3569 * Return <0 if something went wrong, no page is locked
3571 static noinline_for_stack int
3572 lock_extent_buffer_for_io(struct extent_buffer *eb,
3573 struct btrfs_fs_info *fs_info,
3574 struct extent_page_data *epd)
3576 int i, num_pages, failed_page_nr;
3580 if (!btrfs_try_tree_write_lock(eb)) {
3581 ret = flush_write_bio(epd);
3585 btrfs_tree_lock(eb);
3588 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3589 btrfs_tree_unlock(eb);
3593 ret = flush_write_bio(epd);
3599 wait_on_extent_buffer_writeback(eb);
3600 btrfs_tree_lock(eb);
3601 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3603 btrfs_tree_unlock(eb);
3608 * We need to do this to prevent races in people who check if the eb is
3609 * under IO since we can end up having no IO bits set for a short period
3612 spin_lock(&eb->refs_lock);
3613 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3614 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3615 spin_unlock(&eb->refs_lock);
3616 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3617 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3619 fs_info->dirty_metadata_batch);
3622 spin_unlock(&eb->refs_lock);
3625 btrfs_tree_unlock(eb);
3630 num_pages = num_extent_pages(eb);
3631 for (i = 0; i < num_pages; i++) {
3632 struct page *p = eb->pages[i];
3634 if (!trylock_page(p)) {
3638 err = flush_write_bio(epd);
3652 /* Unlock already locked pages */
3653 for (i = 0; i < failed_page_nr; i++)
3654 unlock_page(eb->pages[i]);
3656 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3657 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3658 * be made and undo everything done before.
3660 btrfs_tree_lock(eb);
3661 spin_lock(&eb->refs_lock);
3662 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3663 end_extent_buffer_writeback(eb);
3664 spin_unlock(&eb->refs_lock);
3665 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3666 fs_info->dirty_metadata_batch);
3667 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3668 btrfs_tree_unlock(eb);
3672 static void set_btree_ioerr(struct page *page)
3674 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3677 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3681 * If writeback for a btree extent that doesn't belong to a log tree
3682 * failed, increment the counter transaction->eb_write_errors.
3683 * We do this because while the transaction is running and before it's
3684 * committing (when we call filemap_fdata[write|wait]_range against
3685 * the btree inode), we might have
3686 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3687 * returns an error or an error happens during writeback, when we're
3688 * committing the transaction we wouldn't know about it, since the pages
3689 * can be no longer dirty nor marked anymore for writeback (if a
3690 * subsequent modification to the extent buffer didn't happen before the
3691 * transaction commit), which makes filemap_fdata[write|wait]_range not
3692 * able to find the pages tagged with SetPageError at transaction
3693 * commit time. So if this happens we must abort the transaction,
3694 * otherwise we commit a super block with btree roots that point to
3695 * btree nodes/leafs whose content on disk is invalid - either garbage
3696 * or the content of some node/leaf from a past generation that got
3697 * cowed or deleted and is no longer valid.
3699 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3700 * not be enough - we need to distinguish between log tree extents vs
3701 * non-log tree extents, and the next filemap_fdatawait_range() call
3702 * will catch and clear such errors in the mapping - and that call might
3703 * be from a log sync and not from a transaction commit. Also, checking
3704 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3705 * not done and would not be reliable - the eb might have been released
3706 * from memory and reading it back again means that flag would not be
3707 * set (since it's a runtime flag, not persisted on disk).
3709 * Using the flags below in the btree inode also makes us achieve the
3710 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3711 * writeback for all dirty pages and before filemap_fdatawait_range()
3712 * is called, the writeback for all dirty pages had already finished
3713 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3714 * filemap_fdatawait_range() would return success, as it could not know
3715 * that writeback errors happened (the pages were no longer tagged for
3718 switch (eb->log_index) {
3720 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3723 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3726 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3729 BUG(); /* unexpected, logic error */
3733 static void end_bio_extent_buffer_writepage(struct bio *bio)
3735 struct bio_vec *bvec;
3736 struct extent_buffer *eb;
3739 ASSERT(!bio_flagged(bio, BIO_CLONED));
3740 bio_for_each_segment_all(bvec, bio, i) {
3741 struct page *page = bvec->bv_page;
3743 eb = (struct extent_buffer *)page->private;
3745 done = atomic_dec_and_test(&eb->io_pages);
3747 if (bio->bi_status ||
3748 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3749 ClearPageUptodate(page);
3750 set_btree_ioerr(page);
3753 end_page_writeback(page);
3758 end_extent_buffer_writeback(eb);
3764 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3765 struct btrfs_fs_info *fs_info,
3766 struct writeback_control *wbc,
3767 struct extent_page_data *epd)
3769 struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3770 struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3771 u64 offset = eb->start;
3774 unsigned long start, end;
3775 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3778 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3779 num_pages = num_extent_pages(eb);
3780 atomic_set(&eb->io_pages, num_pages);
3782 /* set btree blocks beyond nritems with 0 to avoid stale content. */
3783 nritems = btrfs_header_nritems(eb);
3784 if (btrfs_header_level(eb) > 0) {
3785 end = btrfs_node_key_ptr_offset(nritems);
3787 memzero_extent_buffer(eb, end, eb->len - end);
3791 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3793 start = btrfs_item_nr_offset(nritems);
3794 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, eb);
3795 memzero_extent_buffer(eb, start, end - start);
3798 for (i = 0; i < num_pages; i++) {
3799 struct page *p = eb->pages[i];
3801 clear_page_dirty_for_io(p);
3802 set_page_writeback(p);
3803 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3804 p, offset, PAGE_SIZE, 0, bdev,
3806 end_bio_extent_buffer_writepage,
3810 if (PageWriteback(p))
3811 end_page_writeback(p);
3812 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3813 end_extent_buffer_writeback(eb);
3817 offset += PAGE_SIZE;
3818 update_nr_written(wbc, 1);
3822 if (unlikely(ret)) {
3823 for (; i < num_pages; i++) {
3824 struct page *p = eb->pages[i];
3825 clear_page_dirty_for_io(p);
3833 int btree_write_cache_pages(struct address_space *mapping,
3834 struct writeback_control *wbc)
3836 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3837 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3838 struct extent_buffer *eb, *prev_eb = NULL;
3839 struct extent_page_data epd = {
3843 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3847 int nr_to_write_done = 0;
3848 struct pagevec pvec;
3851 pgoff_t end; /* Inclusive */
3855 pagevec_init(&pvec);
3856 if (wbc->range_cyclic) {
3857 index = mapping->writeback_index; /* Start from prev offset */
3860 index = wbc->range_start >> PAGE_SHIFT;
3861 end = wbc->range_end >> PAGE_SHIFT;
3864 if (wbc->sync_mode == WB_SYNC_ALL)
3865 tag = PAGECACHE_TAG_TOWRITE;
3867 tag = PAGECACHE_TAG_DIRTY;
3869 if (wbc->sync_mode == WB_SYNC_ALL)
3870 tag_pages_for_writeback(mapping, index, end);
3871 while (!done && !nr_to_write_done && (index <= end) &&
3872 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3877 for (i = 0; i < nr_pages; i++) {
3878 struct page *page = pvec.pages[i];
3880 if (!PagePrivate(page))
3883 spin_lock(&mapping->private_lock);
3884 if (!PagePrivate(page)) {
3885 spin_unlock(&mapping->private_lock);
3889 eb = (struct extent_buffer *)page->private;
3892 * Shouldn't happen and normally this would be a BUG_ON
3893 * but no sense in crashing the users box for something
3894 * we can survive anyway.
3897 spin_unlock(&mapping->private_lock);
3901 if (eb == prev_eb) {
3902 spin_unlock(&mapping->private_lock);
3906 ret = atomic_inc_not_zero(&eb->refs);
3907 spin_unlock(&mapping->private_lock);
3912 ret = lock_extent_buffer_for_io(eb, fs_info, &epd);
3914 free_extent_buffer(eb);
3916 } else if (ret < 0) {
3918 free_extent_buffer(eb);
3922 ret = write_one_eb(eb, fs_info, wbc, &epd);
3925 free_extent_buffer(eb);
3928 free_extent_buffer(eb);
3931 * the filesystem may choose to bump up nr_to_write.
3932 * We have to make sure to honor the new nr_to_write
3935 nr_to_write_done = wbc->nr_to_write <= 0;
3937 pagevec_release(&pvec);
3940 if (!scanned && !done) {
3942 * We hit the last page and there is more work to be done: wrap
3943 * back to the start of the file
3951 end_write_bio(&epd, ret);
3955 * If something went wrong, don't allow any metadata write bio to be
3958 * This would prevent use-after-free if we had dirty pages not
3959 * cleaned up, which can still happen by fuzzed images.
3962 * Allowing existing tree block to be allocated for other trees.
3964 * - Log tree operations
3965 * Exiting tree blocks get allocated to log tree, bumps its
3966 * generation, then get cleaned in tree re-balance.
3967 * Such tree block will not be written back, since it's clean,
3968 * thus no WRITTEN flag set.
3969 * And after log writes back, this tree block is not traced by
3970 * any dirty extent_io_tree.
3972 * - Offending tree block gets re-dirtied from its original owner
3973 * Since it has bumped generation, no WRITTEN flag, it can be
3974 * reused without COWing. This tree block will not be traced
3975 * by btrfs_transaction::dirty_pages.
3977 * Now such dirty tree block will not be cleaned by any dirty
3978 * extent io tree. Thus we don't want to submit such wild eb
3979 * if the fs already has error.
3981 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3982 ret = flush_write_bio(&epd);
3985 end_write_bio(&epd, ret);
3991 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
3992 * @mapping: address space structure to write
3993 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3994 * @data: data passed to __extent_writepage function
3996 * If a page is already under I/O, write_cache_pages() skips it, even
3997 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
3998 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
3999 * and msync() need to guarantee that all the data which was dirty at the time
4000 * the call was made get new I/O started against them. If wbc->sync_mode is
4001 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4002 * existing IO to complete.
4004 static int extent_write_cache_pages(struct address_space *mapping,
4005 struct writeback_control *wbc,
4006 struct extent_page_data *epd)
4008 struct inode *inode = mapping->host;
4011 int nr_to_write_done = 0;
4012 struct pagevec pvec;
4015 pgoff_t end; /* Inclusive */
4017 int range_whole = 0;
4022 * We have to hold onto the inode so that ordered extents can do their
4023 * work when the IO finishes. The alternative to this is failing to add
4024 * an ordered extent if the igrab() fails there and that is a huge pain
4025 * to deal with, so instead just hold onto the inode throughout the
4026 * writepages operation. If it fails here we are freeing up the inode
4027 * anyway and we'd rather not waste our time writing out stuff that is
4028 * going to be truncated anyway.
4033 pagevec_init(&pvec);
4034 if (wbc->range_cyclic) {
4035 index = mapping->writeback_index; /* Start from prev offset */
4038 index = wbc->range_start >> PAGE_SHIFT;
4039 end = wbc->range_end >> PAGE_SHIFT;
4040 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4046 * We do the tagged writepage as long as the snapshot flush bit is set
4047 * and we are the first one who do the filemap_flush() on this inode.
4049 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4050 * not race in and drop the bit.
4052 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4053 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4054 &BTRFS_I(inode)->runtime_flags))
4055 wbc->tagged_writepages = 1;
4057 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4058 tag = PAGECACHE_TAG_TOWRITE;
4060 tag = PAGECACHE_TAG_DIRTY;
4062 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4063 tag_pages_for_writeback(mapping, index, end);
4065 while (!done && !nr_to_write_done && (index <= end) &&
4066 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4067 &index, end, tag))) {
4071 for (i = 0; i < nr_pages; i++) {
4072 struct page *page = pvec.pages[i];
4074 done_index = page->index + 1;
4076 * At this point we hold neither the i_pages lock nor
4077 * the page lock: the page may be truncated or
4078 * invalidated (changing page->mapping to NULL),
4079 * or even swizzled back from swapper_space to
4080 * tmpfs file mapping
4082 if (!trylock_page(page)) {
4083 ret = flush_write_bio(epd);
4088 if (unlikely(page->mapping != mapping)) {
4093 if (wbc->sync_mode != WB_SYNC_NONE) {
4094 if (PageWriteback(page)) {
4095 ret = flush_write_bio(epd);
4098 wait_on_page_writeback(page);
4101 if (PageWriteback(page) ||
4102 !clear_page_dirty_for_io(page)) {
4107 ret = __extent_writepage(page, wbc, epd);
4109 if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
4119 * the filesystem may choose to bump up nr_to_write.
4120 * We have to make sure to honor the new nr_to_write
4123 nr_to_write_done = wbc->nr_to_write <= 0;
4125 pagevec_release(&pvec);
4128 if (!scanned && !done) {
4130 * We hit the last page and there is more work to be done: wrap
4131 * back to the start of the file
4137 * If we're looping we could run into a page that is locked by a
4138 * writer and that writer could be waiting on writeback for a
4139 * page in our current bio, and thus deadlock, so flush the
4142 ret = flush_write_bio(epd);
4147 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4148 mapping->writeback_index = done_index;
4150 btrfs_add_delayed_iput(inode);
4154 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4157 struct extent_page_data epd = {
4159 .tree = &BTRFS_I(page->mapping->host)->io_tree,
4161 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4164 ret = __extent_writepage(page, wbc, &epd);
4167 end_write_bio(&epd, ret);
4171 ret = flush_write_bio(&epd);
4176 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4181 struct address_space *mapping = inode->i_mapping;
4182 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4184 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4187 struct extent_page_data epd = {
4191 .sync_io = mode == WB_SYNC_ALL,
4193 struct writeback_control wbc_writepages = {
4195 .nr_to_write = nr_pages * 2,
4196 .range_start = start,
4197 .range_end = end + 1,
4200 while (start <= end) {
4201 page = find_get_page(mapping, start >> PAGE_SHIFT);
4202 if (clear_page_dirty_for_io(page))
4203 ret = __extent_writepage(page, &wbc_writepages, &epd);
4205 if (tree->ops && tree->ops->writepage_end_io_hook)
4206 tree->ops->writepage_end_io_hook(page, start,
4207 start + PAGE_SIZE - 1,
4215 flush_ret = flush_write_bio(&epd);
4216 BUG_ON(flush_ret < 0);
4220 int extent_writepages(struct address_space *mapping,
4221 struct writeback_control *wbc)
4225 struct extent_page_data epd = {
4227 .tree = &BTRFS_I(mapping->host)->io_tree,
4229 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4232 ret = extent_write_cache_pages(mapping, wbc, &epd);
4233 flush_ret = flush_write_bio(&epd);
4234 BUG_ON(flush_ret < 0);
4238 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4241 struct bio *bio = NULL;
4243 unsigned long bio_flags = 0;
4244 struct page *pagepool[16];
4246 struct extent_map *em_cached = NULL;
4247 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4249 u64 prev_em_start = (u64)-1;
4251 for (page_idx = 0; page_idx < nr_pages; page_idx++) {
4252 page = list_entry(pages->prev, struct page, lru);
4254 prefetchw(&page->flags);
4255 list_del(&page->lru);
4256 if (add_to_page_cache_lru(page, mapping,
4258 readahead_gfp_mask(mapping))) {
4263 pagepool[nr++] = page;
4264 if (nr < ARRAY_SIZE(pagepool))
4266 __extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4267 &bio_flags, &prev_em_start);
4271 __extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4272 &bio_flags, &prev_em_start);
4275 free_extent_map(em_cached);
4277 BUG_ON(!list_empty(pages));
4279 return submit_one_bio(bio, 0, bio_flags);
4284 * basic invalidatepage code, this waits on any locked or writeback
4285 * ranges corresponding to the page, and then deletes any extent state
4286 * records from the tree
4288 int extent_invalidatepage(struct extent_io_tree *tree,
4289 struct page *page, unsigned long offset)
4291 struct extent_state *cached_state = NULL;
4292 u64 start = page_offset(page);
4293 u64 end = start + PAGE_SIZE - 1;
4294 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4296 start += ALIGN(offset, blocksize);
4300 lock_extent_bits(tree, start, end, &cached_state);
4301 wait_on_page_writeback(page);
4302 clear_extent_bit(tree, start, end,
4303 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
4304 EXTENT_DO_ACCOUNTING,
4305 1, 1, &cached_state);
4310 * a helper for releasepage, this tests for areas of the page that
4311 * are locked or under IO and drops the related state bits if it is safe
4314 static int try_release_extent_state(struct extent_io_tree *tree,
4315 struct page *page, gfp_t mask)
4317 u64 start = page_offset(page);
4318 u64 end = start + PAGE_SIZE - 1;
4321 if (test_range_bit(tree, start, end,
4322 EXTENT_IOBITS, 0, NULL))
4326 * at this point we can safely clear everything except the
4327 * locked bit and the nodatasum bit
4329 ret = __clear_extent_bit(tree, start, end,
4330 ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4331 0, 0, NULL, mask, NULL);
4333 /* if clear_extent_bit failed for enomem reasons,
4334 * we can't allow the release to continue.
4345 * a helper for releasepage. As long as there are no locked extents
4346 * in the range corresponding to the page, both state records and extent
4347 * map records are removed
4349 int try_release_extent_mapping(struct page *page, gfp_t mask)
4351 struct extent_map *em;
4352 u64 start = page_offset(page);
4353 u64 end = start + PAGE_SIZE - 1;
4354 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4355 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4356 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4358 if (gfpflags_allow_blocking(mask) &&
4359 page->mapping->host->i_size > SZ_16M) {
4361 while (start <= end) {
4362 len = end - start + 1;
4363 write_lock(&map->lock);
4364 em = lookup_extent_mapping(map, start, len);
4366 write_unlock(&map->lock);
4369 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4370 em->start != start) {
4371 write_unlock(&map->lock);
4372 free_extent_map(em);
4375 if (!test_range_bit(tree, em->start,
4376 extent_map_end(em) - 1,
4377 EXTENT_LOCKED | EXTENT_WRITEBACK,
4379 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4380 &btrfs_inode->runtime_flags);
4381 remove_extent_mapping(map, em);
4382 /* once for the rb tree */
4383 free_extent_map(em);
4385 start = extent_map_end(em);
4386 write_unlock(&map->lock);
4389 free_extent_map(em);
4391 cond_resched(); /* Allow large-extent preemption. */
4394 return try_release_extent_state(tree, page, mask);
4398 * helper function for fiemap, which doesn't want to see any holes.
4399 * This maps until we find something past 'last'
4401 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4402 u64 offset, u64 last)
4404 u64 sectorsize = btrfs_inode_sectorsize(inode);
4405 struct extent_map *em;
4412 len = last - offset;
4415 len = ALIGN(len, sectorsize);
4416 em = btrfs_get_extent_fiemap(BTRFS_I(inode), NULL, 0, offset,
4418 if (IS_ERR_OR_NULL(em))
4421 /* if this isn't a hole return it */
4422 if (em->block_start != EXTENT_MAP_HOLE)
4425 /* this is a hole, advance to the next extent */
4426 offset = extent_map_end(em);
4427 free_extent_map(em);
4435 * To cache previous fiemap extent
4437 * Will be used for merging fiemap extent
4439 struct fiemap_cache {
4448 * Helper to submit fiemap extent.
4450 * Will try to merge current fiemap extent specified by @offset, @phys,
4451 * @len and @flags with cached one.
4452 * And only when we fails to merge, cached one will be submitted as
4455 * Return value is the same as fiemap_fill_next_extent().
4457 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4458 struct fiemap_cache *cache,
4459 u64 offset, u64 phys, u64 len, u32 flags)
4467 * Sanity check, extent_fiemap() should have ensured that new
4468 * fiemap extent won't overlap with cahced one.
4471 * NOTE: Physical address can overlap, due to compression
4473 if (cache->offset + cache->len > offset) {
4479 * Only merges fiemap extents if
4480 * 1) Their logical addresses are continuous
4482 * 2) Their physical addresses are continuous
4483 * So truly compressed (physical size smaller than logical size)
4484 * extents won't get merged with each other
4486 * 3) Share same flags except FIEMAP_EXTENT_LAST
4487 * So regular extent won't get merged with prealloc extent
4489 if (cache->offset + cache->len == offset &&
4490 cache->phys + cache->len == phys &&
4491 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4492 (flags & ~FIEMAP_EXTENT_LAST)) {
4494 cache->flags |= flags;
4495 goto try_submit_last;
4498 /* Not mergeable, need to submit cached one */
4499 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4500 cache->len, cache->flags);
4501 cache->cached = false;
4505 cache->cached = true;
4506 cache->offset = offset;
4509 cache->flags = flags;
4511 if (cache->flags & FIEMAP_EXTENT_LAST) {
4512 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4513 cache->phys, cache->len, cache->flags);
4514 cache->cached = false;
4520 * Emit last fiemap cache
4522 * The last fiemap cache may still be cached in the following case:
4524 * |<- Fiemap range ->|
4525 * |<------------ First extent ----------->|
4527 * In this case, the first extent range will be cached but not emitted.
4528 * So we must emit it before ending extent_fiemap().
4530 static int emit_last_fiemap_cache(struct btrfs_fs_info *fs_info,
4531 struct fiemap_extent_info *fieinfo,
4532 struct fiemap_cache *cache)
4539 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4540 cache->len, cache->flags);
4541 cache->cached = false;
4547 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4548 __u64 start, __u64 len)
4552 u64 max = start + len;
4556 u64 last_for_get_extent = 0;
4558 u64 isize = i_size_read(inode);
4559 struct btrfs_key found_key;
4560 struct extent_map *em = NULL;
4561 struct extent_state *cached_state = NULL;
4562 struct btrfs_path *path;
4563 struct btrfs_root *root = BTRFS_I(inode)->root;
4564 struct fiemap_cache cache = { 0 };
4573 path = btrfs_alloc_path();
4576 path->leave_spinning = 1;
4578 start = round_down(start, btrfs_inode_sectorsize(inode));
4579 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4582 * lookup the last file extent. We're not using i_size here
4583 * because there might be preallocation past i_size
4585 ret = btrfs_lookup_file_extent(NULL, root, path,
4586 btrfs_ino(BTRFS_I(inode)), -1, 0);
4588 btrfs_free_path(path);
4597 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4598 found_type = found_key.type;
4600 /* No extents, but there might be delalloc bits */
4601 if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4602 found_type != BTRFS_EXTENT_DATA_KEY) {
4603 /* have to trust i_size as the end */
4605 last_for_get_extent = isize;
4608 * remember the start of the last extent. There are a
4609 * bunch of different factors that go into the length of the
4610 * extent, so its much less complex to remember where it started
4612 last = found_key.offset;
4613 last_for_get_extent = last + 1;
4615 btrfs_release_path(path);
4618 * we might have some extents allocated but more delalloc past those
4619 * extents. so, we trust isize unless the start of the last extent is
4624 last_for_get_extent = isize;
4627 lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4630 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4639 u64 offset_in_extent = 0;
4641 /* break if the extent we found is outside the range */
4642 if (em->start >= max || extent_map_end(em) < off)
4646 * get_extent may return an extent that starts before our
4647 * requested range. We have to make sure the ranges
4648 * we return to fiemap always move forward and don't
4649 * overlap, so adjust the offsets here
4651 em_start = max(em->start, off);
4654 * record the offset from the start of the extent
4655 * for adjusting the disk offset below. Only do this if the
4656 * extent isn't compressed since our in ram offset may be past
4657 * what we have actually allocated on disk.
4659 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4660 offset_in_extent = em_start - em->start;
4661 em_end = extent_map_end(em);
4662 em_len = em_end - em_start;
4664 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4665 disko = em->block_start + offset_in_extent;
4670 * bump off for our next call to get_extent
4672 off = extent_map_end(em);
4676 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4678 flags |= FIEMAP_EXTENT_LAST;
4679 } else if (em->block_start == EXTENT_MAP_INLINE) {
4680 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4681 FIEMAP_EXTENT_NOT_ALIGNED);
4682 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4683 flags |= (FIEMAP_EXTENT_DELALLOC |
4684 FIEMAP_EXTENT_UNKNOWN);
4685 } else if (fieinfo->fi_extents_max) {
4686 u64 bytenr = em->block_start -
4687 (em->start - em->orig_start);
4690 * As btrfs supports shared space, this information
4691 * can be exported to userspace tools via
4692 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4693 * then we're just getting a count and we can skip the
4696 ret = btrfs_check_shared(root,
4697 btrfs_ino(BTRFS_I(inode)),
4702 flags |= FIEMAP_EXTENT_SHARED;
4705 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4706 flags |= FIEMAP_EXTENT_ENCODED;
4707 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4708 flags |= FIEMAP_EXTENT_UNWRITTEN;
4710 free_extent_map(em);
4712 if ((em_start >= last) || em_len == (u64)-1 ||
4713 (last == (u64)-1 && isize <= em_end)) {
4714 flags |= FIEMAP_EXTENT_LAST;
4718 /* now scan forward to see if this is really the last extent. */
4719 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4725 flags |= FIEMAP_EXTENT_LAST;
4728 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4738 ret = emit_last_fiemap_cache(root->fs_info, fieinfo, &cache);
4739 free_extent_map(em);
4741 btrfs_free_path(path);
4742 unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4747 static void __free_extent_buffer(struct extent_buffer *eb)
4749 btrfs_leak_debug_del(&eb->leak_list);
4750 kmem_cache_free(extent_buffer_cache, eb);
4753 int extent_buffer_under_io(struct extent_buffer *eb)
4755 return (atomic_read(&eb->io_pages) ||
4756 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4757 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4761 * Release all pages attached to the extent buffer.
4763 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4767 int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4769 BUG_ON(extent_buffer_under_io(eb));
4771 num_pages = num_extent_pages(eb);
4772 for (i = 0; i < num_pages; i++) {
4773 struct page *page = eb->pages[i];
4778 spin_lock(&page->mapping->private_lock);
4780 * We do this since we'll remove the pages after we've
4781 * removed the eb from the radix tree, so we could race
4782 * and have this page now attached to the new eb. So
4783 * only clear page_private if it's still connected to
4786 if (PagePrivate(page) &&
4787 page->private == (unsigned long)eb) {
4788 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4789 BUG_ON(PageDirty(page));
4790 BUG_ON(PageWriteback(page));
4792 * We need to make sure we haven't be attached
4795 ClearPagePrivate(page);
4796 set_page_private(page, 0);
4797 /* One for the page private */
4802 spin_unlock(&page->mapping->private_lock);
4804 /* One for when we allocated the page */
4810 * Helper for releasing the extent buffer.
4812 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4814 btrfs_release_extent_buffer_pages(eb);
4815 __free_extent_buffer(eb);
4818 static struct extent_buffer *
4819 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4822 struct extent_buffer *eb = NULL;
4824 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4827 eb->fs_info = fs_info;
4829 rwlock_init(&eb->lock);
4830 atomic_set(&eb->write_locks, 0);
4831 atomic_set(&eb->read_locks, 0);
4832 atomic_set(&eb->blocking_readers, 0);
4833 atomic_set(&eb->blocking_writers, 0);
4834 atomic_set(&eb->spinning_readers, 0);
4835 atomic_set(&eb->spinning_writers, 0);
4836 eb->lock_nested = 0;
4837 init_waitqueue_head(&eb->write_lock_wq);
4838 init_waitqueue_head(&eb->read_lock_wq);
4840 btrfs_leak_debug_add(&eb->leak_list, &buffers);
4842 spin_lock_init(&eb->refs_lock);
4843 atomic_set(&eb->refs, 1);
4844 atomic_set(&eb->io_pages, 0);
4847 * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4849 BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4850 > MAX_INLINE_EXTENT_BUFFER_SIZE);
4851 BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4856 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4860 struct extent_buffer *new;
4861 int num_pages = num_extent_pages(src);
4863 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4867 for (i = 0; i < num_pages; i++) {
4868 p = alloc_page(GFP_NOFS);
4870 btrfs_release_extent_buffer(new);
4873 attach_extent_buffer_page(new, p);
4874 WARN_ON(PageDirty(p));
4877 copy_page(page_address(p), page_address(src->pages[i]));
4880 set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4881 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4886 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4887 u64 start, unsigned long len)
4889 struct extent_buffer *eb;
4893 eb = __alloc_extent_buffer(fs_info, start, len);
4897 num_pages = num_extent_pages(eb);
4898 for (i = 0; i < num_pages; i++) {
4899 eb->pages[i] = alloc_page(GFP_NOFS);
4903 set_extent_buffer_uptodate(eb);
4904 btrfs_set_header_nritems(eb, 0);
4905 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4910 __free_page(eb->pages[i - 1]);
4911 __free_extent_buffer(eb);
4915 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4918 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4921 static void check_buffer_tree_ref(struct extent_buffer *eb)
4925 * The TREE_REF bit is first set when the extent_buffer is added
4926 * to the radix tree. It is also reset, if unset, when a new reference
4927 * is created by find_extent_buffer.
4929 * It is only cleared in two cases: freeing the last non-tree
4930 * reference to the extent_buffer when its STALE bit is set or
4931 * calling releasepage when the tree reference is the only reference.
4933 * In both cases, care is taken to ensure that the extent_buffer's
4934 * pages are not under io. However, releasepage can be concurrently
4935 * called with creating new references, which is prone to race
4936 * conditions between the calls to check_buffer_tree_ref in those
4937 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4939 * The actual lifetime of the extent_buffer in the radix tree is
4940 * adequately protected by the refcount, but the TREE_REF bit and
4941 * its corresponding reference are not. To protect against this
4942 * class of races, we call check_buffer_tree_ref from the codepaths
4943 * which trigger io after they set eb->io_pages. Note that once io is
4944 * initiated, TREE_REF can no longer be cleared, so that is the
4945 * moment at which any such race is best fixed.
4947 refs = atomic_read(&eb->refs);
4948 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4951 spin_lock(&eb->refs_lock);
4952 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4953 atomic_inc(&eb->refs);
4954 spin_unlock(&eb->refs_lock);
4957 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4958 struct page *accessed)
4962 check_buffer_tree_ref(eb);
4964 num_pages = num_extent_pages(eb);
4965 for (i = 0; i < num_pages; i++) {
4966 struct page *p = eb->pages[i];
4969 mark_page_accessed(p);
4973 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4976 struct extent_buffer *eb;
4979 eb = radix_tree_lookup(&fs_info->buffer_radix,
4980 start >> PAGE_SHIFT);
4981 if (eb && atomic_inc_not_zero(&eb->refs)) {
4984 * Lock our eb's refs_lock to avoid races with
4985 * free_extent_buffer. When we get our eb it might be flagged
4986 * with EXTENT_BUFFER_STALE and another task running
4987 * free_extent_buffer might have seen that flag set,
4988 * eb->refs == 2, that the buffer isn't under IO (dirty and
4989 * writeback flags not set) and it's still in the tree (flag
4990 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
4991 * of decrementing the extent buffer's reference count twice.
4992 * So here we could race and increment the eb's reference count,
4993 * clear its stale flag, mark it as dirty and drop our reference
4994 * before the other task finishes executing free_extent_buffer,
4995 * which would later result in an attempt to free an extent
4996 * buffer that is dirty.
4998 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4999 spin_lock(&eb->refs_lock);
5000 spin_unlock(&eb->refs_lock);
5002 mark_extent_buffer_accessed(eb, NULL);
5010 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5011 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5014 struct extent_buffer *eb, *exists = NULL;
5017 eb = find_extent_buffer(fs_info, start);
5020 eb = alloc_dummy_extent_buffer(fs_info, start);
5022 return ERR_PTR(-ENOMEM);
5023 eb->fs_info = fs_info;
5025 ret = radix_tree_preload(GFP_NOFS);
5027 exists = ERR_PTR(ret);
5030 spin_lock(&fs_info->buffer_lock);
5031 ret = radix_tree_insert(&fs_info->buffer_radix,
5032 start >> PAGE_SHIFT, eb);
5033 spin_unlock(&fs_info->buffer_lock);
5034 radix_tree_preload_end();
5035 if (ret == -EEXIST) {
5036 exists = find_extent_buffer(fs_info, start);
5042 check_buffer_tree_ref(eb);
5043 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5046 * We will free dummy extent buffer's if they come into
5047 * free_extent_buffer with a ref count of 2, but if we are using this we
5048 * want the buffers to stay in memory until we're done with them, so
5049 * bump the ref count again.
5051 atomic_inc(&eb->refs);
5054 btrfs_release_extent_buffer(eb);
5059 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5062 unsigned long len = fs_info->nodesize;
5065 unsigned long index = start >> PAGE_SHIFT;
5066 struct extent_buffer *eb;
5067 struct extent_buffer *exists = NULL;
5069 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5073 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5074 btrfs_err(fs_info, "bad tree block start %llu", start);
5075 return ERR_PTR(-EINVAL);
5078 eb = find_extent_buffer(fs_info, start);
5082 eb = __alloc_extent_buffer(fs_info, start, len);
5084 return ERR_PTR(-ENOMEM);
5086 num_pages = num_extent_pages(eb);
5087 for (i = 0; i < num_pages; i++, index++) {
5088 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5090 exists = ERR_PTR(-ENOMEM);
5094 spin_lock(&mapping->private_lock);
5095 if (PagePrivate(p)) {
5097 * We could have already allocated an eb for this page
5098 * and attached one so lets see if we can get a ref on
5099 * the existing eb, and if we can we know it's good and
5100 * we can just return that one, else we know we can just
5101 * overwrite page->private.
5103 exists = (struct extent_buffer *)p->private;
5104 if (atomic_inc_not_zero(&exists->refs)) {
5105 spin_unlock(&mapping->private_lock);
5108 mark_extent_buffer_accessed(exists, p);
5114 * Do this so attach doesn't complain and we need to
5115 * drop the ref the old guy had.
5117 ClearPagePrivate(p);
5118 WARN_ON(PageDirty(p));
5121 attach_extent_buffer_page(eb, p);
5122 spin_unlock(&mapping->private_lock);
5123 WARN_ON(PageDirty(p));
5125 if (!PageUptodate(p))
5129 * We can't unlock the pages just yet since the extent buffer
5130 * hasn't been properly inserted in the radix tree, this
5131 * opens a race with btree_releasepage which can free a page
5132 * while we are still filling in all pages for the buffer and
5137 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5139 ret = radix_tree_preload(GFP_NOFS);
5141 exists = ERR_PTR(ret);
5145 spin_lock(&fs_info->buffer_lock);
5146 ret = radix_tree_insert(&fs_info->buffer_radix,
5147 start >> PAGE_SHIFT, eb);
5148 spin_unlock(&fs_info->buffer_lock);
5149 radix_tree_preload_end();
5150 if (ret == -EEXIST) {
5151 exists = find_extent_buffer(fs_info, start);
5157 /* add one reference for the tree */
5158 check_buffer_tree_ref(eb);
5159 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5162 * Now it's safe to unlock the pages because any calls to
5163 * btree_releasepage will correctly detect that a page belongs to a
5164 * live buffer and won't free them prematurely.
5166 for (i = 0; i < num_pages; i++)
5167 unlock_page(eb->pages[i]);
5171 WARN_ON(!atomic_dec_and_test(&eb->refs));
5172 for (i = 0; i < num_pages; i++) {
5174 unlock_page(eb->pages[i]);
5177 btrfs_release_extent_buffer(eb);
5181 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5183 struct extent_buffer *eb =
5184 container_of(head, struct extent_buffer, rcu_head);
5186 __free_extent_buffer(eb);
5189 static int release_extent_buffer(struct extent_buffer *eb)
5191 lockdep_assert_held(&eb->refs_lock);
5193 WARN_ON(atomic_read(&eb->refs) == 0);
5194 if (atomic_dec_and_test(&eb->refs)) {
5195 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5196 struct btrfs_fs_info *fs_info = eb->fs_info;
5198 spin_unlock(&eb->refs_lock);
5200 spin_lock(&fs_info->buffer_lock);
5201 radix_tree_delete(&fs_info->buffer_radix,
5202 eb->start >> PAGE_SHIFT);
5203 spin_unlock(&fs_info->buffer_lock);
5205 spin_unlock(&eb->refs_lock);
5208 /* Should be safe to release our pages at this point */
5209 btrfs_release_extent_buffer_pages(eb);
5210 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5211 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5212 __free_extent_buffer(eb);
5216 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5219 spin_unlock(&eb->refs_lock);
5224 void free_extent_buffer(struct extent_buffer *eb)
5232 refs = atomic_read(&eb->refs);
5235 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5240 spin_lock(&eb->refs_lock);
5241 if (atomic_read(&eb->refs) == 2 &&
5242 test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))
5243 atomic_dec(&eb->refs);
5245 if (atomic_read(&eb->refs) == 2 &&
5246 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5247 !extent_buffer_under_io(eb) &&
5248 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5249 atomic_dec(&eb->refs);
5252 * I know this is terrible, but it's temporary until we stop tracking
5253 * the uptodate bits and such for the extent buffers.
5255 release_extent_buffer(eb);
5258 void free_extent_buffer_stale(struct extent_buffer *eb)
5263 spin_lock(&eb->refs_lock);
5264 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5266 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5267 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5268 atomic_dec(&eb->refs);
5269 release_extent_buffer(eb);
5272 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5278 num_pages = num_extent_pages(eb);
5280 for (i = 0; i < num_pages; i++) {
5281 page = eb->pages[i];
5282 if (!PageDirty(page))
5286 WARN_ON(!PagePrivate(page));
5288 clear_page_dirty_for_io(page);
5289 xa_lock_irq(&page->mapping->i_pages);
5290 if (!PageDirty(page)) {
5291 radix_tree_tag_clear(&page->mapping->i_pages,
5293 PAGECACHE_TAG_DIRTY);
5295 xa_unlock_irq(&page->mapping->i_pages);
5296 ClearPageError(page);
5299 WARN_ON(atomic_read(&eb->refs) == 0);
5302 int set_extent_buffer_dirty(struct extent_buffer *eb)
5308 check_buffer_tree_ref(eb);
5310 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5312 num_pages = num_extent_pages(eb);
5313 WARN_ON(atomic_read(&eb->refs) == 0);
5314 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5316 for (i = 0; i < num_pages; i++)
5317 set_page_dirty(eb->pages[i]);
5321 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5327 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5328 num_pages = num_extent_pages(eb);
5329 for (i = 0; i < num_pages; i++) {
5330 page = eb->pages[i];
5332 ClearPageUptodate(page);
5336 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5342 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5343 num_pages = num_extent_pages(eb);
5344 for (i = 0; i < num_pages; i++) {
5345 page = eb->pages[i];
5346 SetPageUptodate(page);
5350 int read_extent_buffer_pages(struct extent_io_tree *tree,
5351 struct extent_buffer *eb, int wait, int mirror_num)
5357 int locked_pages = 0;
5358 int all_uptodate = 1;
5360 unsigned long num_reads = 0;
5361 struct bio *bio = NULL;
5362 unsigned long bio_flags = 0;
5364 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5367 num_pages = num_extent_pages(eb);
5368 for (i = 0; i < num_pages; i++) {
5369 page = eb->pages[i];
5370 if (wait == WAIT_NONE) {
5371 if (!trylock_page(page))
5379 * We need to firstly lock all pages to make sure that
5380 * the uptodate bit of our pages won't be affected by
5381 * clear_extent_buffer_uptodate().
5383 for (i = 0; i < num_pages; i++) {
5384 page = eb->pages[i];
5385 if (!PageUptodate(page)) {
5392 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5396 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5397 eb->read_mirror = 0;
5398 atomic_set(&eb->io_pages, num_reads);
5400 * It is possible for releasepage to clear the TREE_REF bit before we
5401 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5403 check_buffer_tree_ref(eb);
5404 for (i = 0; i < num_pages; i++) {
5405 page = eb->pages[i];
5407 if (!PageUptodate(page)) {
5409 atomic_dec(&eb->io_pages);
5414 ClearPageError(page);
5415 err = __extent_read_full_page(tree, page,
5416 btree_get_extent, &bio,
5417 mirror_num, &bio_flags,
5422 * We use &bio in above __extent_read_full_page,
5423 * so we ensure that if it returns error, the
5424 * current page fails to add itself to bio and
5425 * it's been unlocked.
5427 * We must dec io_pages by ourselves.
5429 atomic_dec(&eb->io_pages);
5437 err = submit_one_bio(bio, mirror_num, bio_flags);
5442 if (ret || wait != WAIT_COMPLETE)
5445 for (i = 0; i < num_pages; i++) {
5446 page = eb->pages[i];
5447 wait_on_page_locked(page);
5448 if (!PageUptodate(page))
5455 while (locked_pages > 0) {
5457 page = eb->pages[locked_pages];
5463 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5464 unsigned long start, unsigned long len)
5470 char *dst = (char *)dstv;
5471 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5472 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5474 if (start + len > eb->len) {
5475 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5476 eb->start, eb->len, start, len);
5477 memset(dst, 0, len);
5481 offset = (start_offset + start) & (PAGE_SIZE - 1);
5484 page = eb->pages[i];
5486 cur = min(len, (PAGE_SIZE - offset));
5487 kaddr = page_address(page);
5488 memcpy(dst, kaddr + offset, cur);
5497 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5499 unsigned long start, unsigned long len)
5505 char __user *dst = (char __user *)dstv;
5506 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5507 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5510 WARN_ON(start > eb->len);
5511 WARN_ON(start + len > eb->start + eb->len);
5513 offset = (start_offset + start) & (PAGE_SIZE - 1);
5516 page = eb->pages[i];
5518 cur = min(len, (PAGE_SIZE - offset));
5519 kaddr = page_address(page);
5520 if (probe_user_write(dst, kaddr + offset, cur)) {
5535 * return 0 if the item is found within a page.
5536 * return 1 if the item spans two pages.
5537 * return -EINVAL otherwise.
5539 int map_private_extent_buffer(const struct extent_buffer *eb,
5540 unsigned long start, unsigned long min_len,
5541 char **map, unsigned long *map_start,
5542 unsigned long *map_len)
5544 size_t offset = start & (PAGE_SIZE - 1);
5547 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5548 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5549 unsigned long end_i = (start_offset + start + min_len - 1) >>
5552 if (start + min_len > eb->len) {
5553 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5554 eb->start, eb->len, start, min_len);
5562 offset = start_offset;
5566 *map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5570 kaddr = page_address(p);
5571 *map = kaddr + offset;
5572 *map_len = PAGE_SIZE - offset;
5576 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5577 unsigned long start, unsigned long len)
5583 char *ptr = (char *)ptrv;
5584 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5585 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5588 WARN_ON(start > eb->len);
5589 WARN_ON(start + len > eb->start + eb->len);
5591 offset = (start_offset + start) & (PAGE_SIZE - 1);
5594 page = eb->pages[i];
5596 cur = min(len, (PAGE_SIZE - offset));
5598 kaddr = page_address(page);
5599 ret = memcmp(ptr, kaddr + offset, cur);
5611 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5616 WARN_ON(!PageUptodate(eb->pages[0]));
5617 kaddr = page_address(eb->pages[0]);
5618 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5622 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5626 WARN_ON(!PageUptodate(eb->pages[0]));
5627 kaddr = page_address(eb->pages[0]);
5628 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5632 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5633 unsigned long start, unsigned long len)
5639 char *src = (char *)srcv;
5640 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5641 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5643 WARN_ON(start > eb->len);
5644 WARN_ON(start + len > eb->start + eb->len);
5646 offset = (start_offset + start) & (PAGE_SIZE - 1);
5649 page = eb->pages[i];
5650 WARN_ON(!PageUptodate(page));
5652 cur = min(len, PAGE_SIZE - offset);
5653 kaddr = page_address(page);
5654 memcpy(kaddr + offset, src, cur);
5663 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5670 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5671 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5673 WARN_ON(start > eb->len);
5674 WARN_ON(start + len > eb->start + eb->len);
5676 offset = (start_offset + start) & (PAGE_SIZE - 1);
5679 page = eb->pages[i];
5680 WARN_ON(!PageUptodate(page));
5682 cur = min(len, PAGE_SIZE - offset);
5683 kaddr = page_address(page);
5684 memset(kaddr + offset, 0, cur);
5692 void copy_extent_buffer_full(struct extent_buffer *dst,
5693 struct extent_buffer *src)
5698 ASSERT(dst->len == src->len);
5700 num_pages = num_extent_pages(dst);
5701 for (i = 0; i < num_pages; i++)
5702 copy_page(page_address(dst->pages[i]),
5703 page_address(src->pages[i]));
5706 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5707 unsigned long dst_offset, unsigned long src_offset,
5710 u64 dst_len = dst->len;
5715 size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5716 unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5718 WARN_ON(src->len != dst_len);
5720 offset = (start_offset + dst_offset) &
5724 page = dst->pages[i];
5725 WARN_ON(!PageUptodate(page));
5727 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5729 kaddr = page_address(page);
5730 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5740 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5742 * @eb: the extent buffer
5743 * @start: offset of the bitmap item in the extent buffer
5745 * @page_index: return index of the page in the extent buffer that contains the
5747 * @page_offset: return offset into the page given by page_index
5749 * This helper hides the ugliness of finding the byte in an extent buffer which
5750 * contains a given bit.
5752 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5753 unsigned long start, unsigned long nr,
5754 unsigned long *page_index,
5755 size_t *page_offset)
5757 size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5758 size_t byte_offset = BIT_BYTE(nr);
5762 * The byte we want is the offset of the extent buffer + the offset of
5763 * the bitmap item in the extent buffer + the offset of the byte in the
5766 offset = start_offset + start + byte_offset;
5768 *page_index = offset >> PAGE_SHIFT;
5769 *page_offset = offset & (PAGE_SIZE - 1);
5773 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5774 * @eb: the extent buffer
5775 * @start: offset of the bitmap item in the extent buffer
5776 * @nr: bit number to test
5778 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5786 eb_bitmap_offset(eb, start, nr, &i, &offset);
5787 page = eb->pages[i];
5788 WARN_ON(!PageUptodate(page));
5789 kaddr = page_address(page);
5790 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5794 * extent_buffer_bitmap_set - set an area of a bitmap
5795 * @eb: the extent buffer
5796 * @start: offset of the bitmap item in the extent buffer
5797 * @pos: bit number of the first bit
5798 * @len: number of bits to set
5800 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5801 unsigned long pos, unsigned long len)
5807 const unsigned int size = pos + len;
5808 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5809 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5811 eb_bitmap_offset(eb, start, pos, &i, &offset);
5812 page = eb->pages[i];
5813 WARN_ON(!PageUptodate(page));
5814 kaddr = page_address(page);
5816 while (len >= bits_to_set) {
5817 kaddr[offset] |= mask_to_set;
5819 bits_to_set = BITS_PER_BYTE;
5821 if (++offset >= PAGE_SIZE && len > 0) {
5823 page = eb->pages[++i];
5824 WARN_ON(!PageUptodate(page));
5825 kaddr = page_address(page);
5829 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5830 kaddr[offset] |= mask_to_set;
5836 * extent_buffer_bitmap_clear - clear an area of a bitmap
5837 * @eb: the extent buffer
5838 * @start: offset of the bitmap item in the extent buffer
5839 * @pos: bit number of the first bit
5840 * @len: number of bits to clear
5842 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5843 unsigned long pos, unsigned long len)
5849 const unsigned int size = pos + len;
5850 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5851 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5853 eb_bitmap_offset(eb, start, pos, &i, &offset);
5854 page = eb->pages[i];
5855 WARN_ON(!PageUptodate(page));
5856 kaddr = page_address(page);
5858 while (len >= bits_to_clear) {
5859 kaddr[offset] &= ~mask_to_clear;
5860 len -= bits_to_clear;
5861 bits_to_clear = BITS_PER_BYTE;
5863 if (++offset >= PAGE_SIZE && len > 0) {
5865 page = eb->pages[++i];
5866 WARN_ON(!PageUptodate(page));
5867 kaddr = page_address(page);
5871 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5872 kaddr[offset] &= ~mask_to_clear;
5876 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5878 unsigned long distance = (src > dst) ? src - dst : dst - src;
5879 return distance < len;
5882 static void copy_pages(struct page *dst_page, struct page *src_page,
5883 unsigned long dst_off, unsigned long src_off,
5886 char *dst_kaddr = page_address(dst_page);
5888 int must_memmove = 0;
5890 if (dst_page != src_page) {
5891 src_kaddr = page_address(src_page);
5893 src_kaddr = dst_kaddr;
5894 if (areas_overlap(src_off, dst_off, len))
5899 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5901 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5904 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5905 unsigned long src_offset, unsigned long len)
5907 struct btrfs_fs_info *fs_info = dst->fs_info;
5909 size_t dst_off_in_page;
5910 size_t src_off_in_page;
5911 size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5912 unsigned long dst_i;
5913 unsigned long src_i;
5915 if (src_offset + len > dst->len) {
5917 "memmove bogus src_offset %lu move len %lu dst len %lu",
5918 src_offset, len, dst->len);
5921 if (dst_offset + len > dst->len) {
5923 "memmove bogus dst_offset %lu move len %lu dst len %lu",
5924 dst_offset, len, dst->len);
5929 dst_off_in_page = (start_offset + dst_offset) &
5931 src_off_in_page = (start_offset + src_offset) &
5934 dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
5935 src_i = (start_offset + src_offset) >> PAGE_SHIFT;
5937 cur = min(len, (unsigned long)(PAGE_SIZE -
5939 cur = min_t(unsigned long, cur,
5940 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5942 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5943 dst_off_in_page, src_off_in_page, cur);
5951 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5952 unsigned long src_offset, unsigned long len)
5954 struct btrfs_fs_info *fs_info = dst->fs_info;
5956 size_t dst_off_in_page;
5957 size_t src_off_in_page;
5958 unsigned long dst_end = dst_offset + len - 1;
5959 unsigned long src_end = src_offset + len - 1;
5960 size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5961 unsigned long dst_i;
5962 unsigned long src_i;
5964 if (src_offset + len > dst->len) {
5966 "memmove bogus src_offset %lu move len %lu len %lu",
5967 src_offset, len, dst->len);
5970 if (dst_offset + len > dst->len) {
5972 "memmove bogus dst_offset %lu move len %lu len %lu",
5973 dst_offset, len, dst->len);
5976 if (dst_offset < src_offset) {
5977 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5981 dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
5982 src_i = (start_offset + src_end) >> PAGE_SHIFT;
5984 dst_off_in_page = (start_offset + dst_end) &
5986 src_off_in_page = (start_offset + src_end) &
5989 cur = min_t(unsigned long, len, src_off_in_page + 1);
5990 cur = min(cur, dst_off_in_page + 1);
5991 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5992 dst_off_in_page - cur + 1,
5993 src_off_in_page - cur + 1, cur);
6001 int try_release_extent_buffer(struct page *page)
6003 struct extent_buffer *eb;
6006 * We need to make sure nobody is attaching this page to an eb right
6009 spin_lock(&page->mapping->private_lock);
6010 if (!PagePrivate(page)) {
6011 spin_unlock(&page->mapping->private_lock);
6015 eb = (struct extent_buffer *)page->private;
6019 * This is a little awful but should be ok, we need to make sure that
6020 * the eb doesn't disappear out from under us while we're looking at
6023 spin_lock(&eb->refs_lock);
6024 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6025 spin_unlock(&eb->refs_lock);
6026 spin_unlock(&page->mapping->private_lock);
6029 spin_unlock(&page->mapping->private_lock);
6032 * If tree ref isn't set then we know the ref on this eb is a real ref,
6033 * so just return, this page will likely be freed soon anyway.
6035 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6036 spin_unlock(&eb->refs_lock);
6040 return release_extent_buffer(eb);