1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/cleancache.h>
16 #include "extent_io.h"
17 #include "extent-io-tree.h"
18 #include "extent_map.h"
20 #include "btrfs_inode.h"
22 #include "check-integrity.h"
24 #include "rcu-string.h"
29 #include "block-group.h"
31 static struct kmem_cache *extent_state_cache;
32 static struct kmem_cache *extent_buffer_cache;
33 static struct bio_set btrfs_bioset;
35 static inline bool extent_state_in_tree(const struct extent_state *state)
37 return !RB_EMPTY_NODE(&state->rb_node);
40 #ifdef CONFIG_BTRFS_DEBUG
41 static LIST_HEAD(states);
42 static DEFINE_SPINLOCK(leak_lock);
44 static inline void btrfs_leak_debug_add(spinlock_t *lock,
45 struct list_head *new,
46 struct list_head *head)
50 spin_lock_irqsave(lock, flags);
52 spin_unlock_irqrestore(lock, flags);
55 static inline void btrfs_leak_debug_del(spinlock_t *lock,
56 struct list_head *entry)
60 spin_lock_irqsave(lock, flags);
62 spin_unlock_irqrestore(lock, flags);
65 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
67 struct extent_buffer *eb;
71 * If we didn't get into open_ctree our allocated_ebs will not be
72 * initialized, so just skip this.
74 if (!fs_info->allocated_ebs.next)
77 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
78 while (!list_empty(&fs_info->allocated_ebs)) {
79 eb = list_first_entry(&fs_info->allocated_ebs,
80 struct extent_buffer, leak_list);
82 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
83 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
84 btrfs_header_owner(eb));
85 list_del(&eb->leak_list);
86 kmem_cache_free(extent_buffer_cache, eb);
88 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
91 static inline void btrfs_extent_state_leak_debug_check(void)
93 struct extent_state *state;
95 while (!list_empty(&states)) {
96 state = list_entry(states.next, struct extent_state, leak_list);
97 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
98 state->start, state->end, state->state,
99 extent_state_in_tree(state),
100 refcount_read(&state->refs));
101 list_del(&state->leak_list);
102 kmem_cache_free(extent_state_cache, state);
106 #define btrfs_debug_check_extent_io_range(tree, start, end) \
107 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
108 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
109 struct extent_io_tree *tree, u64 start, u64 end)
111 struct inode *inode = tree->private_data;
114 if (!inode || !is_data_inode(inode))
117 isize = i_size_read(inode);
118 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
119 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
120 "%s: ino %llu isize %llu odd range [%llu,%llu]",
121 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
125 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
126 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
127 #define btrfs_extent_state_leak_debug_check() do {} while (0)
128 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
134 struct rb_node rb_node;
137 struct extent_page_data {
139 /* tells writepage not to lock the state bits for this range
140 * it still does the unlocking
142 unsigned int extent_locked:1;
144 /* tells the submit_bio code to use REQ_SYNC */
145 unsigned int sync_io:1;
148 static int add_extent_changeset(struct extent_state *state, u32 bits,
149 struct extent_changeset *changeset,
156 if (set && (state->state & bits) == bits)
158 if (!set && (state->state & bits) == 0)
160 changeset->bytes_changed += state->end - state->start + 1;
161 ret = ulist_add(&changeset->range_changed, state->start, state->end,
166 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
167 unsigned long bio_flags)
169 blk_status_t ret = 0;
170 struct extent_io_tree *tree = bio->bi_private;
172 bio->bi_private = NULL;
174 if (is_data_inode(tree->private_data))
175 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
178 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
179 mirror_num, bio_flags);
181 return blk_status_to_errno(ret);
184 /* Cleanup unsubmitted bios */
185 static void end_write_bio(struct extent_page_data *epd, int ret)
188 epd->bio->bi_status = errno_to_blk_status(ret);
195 * Submit bio from extent page data via submit_one_bio
197 * Return 0 if everything is OK.
198 * Return <0 for error.
200 static int __must_check flush_write_bio(struct extent_page_data *epd)
205 ret = submit_one_bio(epd->bio, 0, 0);
207 * Clean up of epd->bio is handled by its endio function.
208 * And endio is either triggered by successful bio execution
209 * or the error handler of submit bio hook.
210 * So at this point, no matter what happened, we don't need
211 * to clean up epd->bio.
218 int __init extent_state_cache_init(void)
220 extent_state_cache = kmem_cache_create("btrfs_extent_state",
221 sizeof(struct extent_state), 0,
222 SLAB_MEM_SPREAD, NULL);
223 if (!extent_state_cache)
228 int __init extent_io_init(void)
230 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
231 sizeof(struct extent_buffer), 0,
232 SLAB_MEM_SPREAD, NULL);
233 if (!extent_buffer_cache)
236 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
237 offsetof(struct btrfs_io_bio, bio),
239 goto free_buffer_cache;
241 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
247 bioset_exit(&btrfs_bioset);
250 kmem_cache_destroy(extent_buffer_cache);
251 extent_buffer_cache = NULL;
255 void __cold extent_state_cache_exit(void)
257 btrfs_extent_state_leak_debug_check();
258 kmem_cache_destroy(extent_state_cache);
261 void __cold extent_io_exit(void)
264 * Make sure all delayed rcu free are flushed before we
268 kmem_cache_destroy(extent_buffer_cache);
269 bioset_exit(&btrfs_bioset);
273 * For the file_extent_tree, we want to hold the inode lock when we lookup and
274 * update the disk_i_size, but lockdep will complain because our io_tree we hold
275 * the tree lock and get the inode lock when setting delalloc. These two things
276 * are unrelated, so make a class for the file_extent_tree so we don't get the
277 * two locking patterns mixed up.
279 static struct lock_class_key file_extent_tree_class;
281 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
282 struct extent_io_tree *tree, unsigned int owner,
285 tree->fs_info = fs_info;
286 tree->state = RB_ROOT;
287 tree->dirty_bytes = 0;
288 spin_lock_init(&tree->lock);
289 tree->private_data = private_data;
291 if (owner == IO_TREE_INODE_FILE_EXTENT)
292 lockdep_set_class(&tree->lock, &file_extent_tree_class);
295 void extent_io_tree_release(struct extent_io_tree *tree)
297 spin_lock(&tree->lock);
299 * Do a single barrier for the waitqueue_active check here, the state
300 * of the waitqueue should not change once extent_io_tree_release is
304 while (!RB_EMPTY_ROOT(&tree->state)) {
305 struct rb_node *node;
306 struct extent_state *state;
308 node = rb_first(&tree->state);
309 state = rb_entry(node, struct extent_state, rb_node);
310 rb_erase(&state->rb_node, &tree->state);
311 RB_CLEAR_NODE(&state->rb_node);
313 * btree io trees aren't supposed to have tasks waiting for
314 * changes in the flags of extent states ever.
316 ASSERT(!waitqueue_active(&state->wq));
317 free_extent_state(state);
319 cond_resched_lock(&tree->lock);
321 spin_unlock(&tree->lock);
324 static struct extent_state *alloc_extent_state(gfp_t mask)
326 struct extent_state *state;
329 * The given mask might be not appropriate for the slab allocator,
330 * drop the unsupported bits
332 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
333 state = kmem_cache_alloc(extent_state_cache, mask);
337 state->failrec = NULL;
338 RB_CLEAR_NODE(&state->rb_node);
339 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
340 refcount_set(&state->refs, 1);
341 init_waitqueue_head(&state->wq);
342 trace_alloc_extent_state(state, mask, _RET_IP_);
346 void free_extent_state(struct extent_state *state)
350 if (refcount_dec_and_test(&state->refs)) {
351 WARN_ON(extent_state_in_tree(state));
352 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
353 trace_free_extent_state(state, _RET_IP_);
354 kmem_cache_free(extent_state_cache, state);
358 static struct rb_node *tree_insert(struct rb_root *root,
359 struct rb_node *search_start,
361 struct rb_node *node,
362 struct rb_node ***p_in,
363 struct rb_node **parent_in)
366 struct rb_node *parent = NULL;
367 struct tree_entry *entry;
369 if (p_in && parent_in) {
375 p = search_start ? &search_start : &root->rb_node;
378 entry = rb_entry(parent, struct tree_entry, rb_node);
380 if (offset < entry->start)
382 else if (offset > entry->end)
389 rb_link_node(node, parent, p);
390 rb_insert_color(node, root);
395 * Search @tree for an entry that contains @offset. Such entry would have
396 * entry->start <= offset && entry->end >= offset.
398 * @tree: the tree to search
399 * @offset: offset that should fall within an entry in @tree
400 * @next_ret: pointer to the first entry whose range ends after @offset
401 * @prev_ret: pointer to the first entry whose range begins before @offset
402 * @p_ret: pointer where new node should be anchored (used when inserting an
404 * @parent_ret: points to entry which would have been the parent of the entry,
407 * This function returns a pointer to the entry that contains @offset byte
408 * address. If no such entry exists, then NULL is returned and the other
409 * pointer arguments to the function are filled, otherwise the found entry is
410 * returned and other pointers are left untouched.
412 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
413 struct rb_node **next_ret,
414 struct rb_node **prev_ret,
415 struct rb_node ***p_ret,
416 struct rb_node **parent_ret)
418 struct rb_root *root = &tree->state;
419 struct rb_node **n = &root->rb_node;
420 struct rb_node *prev = NULL;
421 struct rb_node *orig_prev = NULL;
422 struct tree_entry *entry;
423 struct tree_entry *prev_entry = NULL;
427 entry = rb_entry(prev, struct tree_entry, rb_node);
430 if (offset < entry->start)
432 else if (offset > entry->end)
445 while (prev && offset > prev_entry->end) {
446 prev = rb_next(prev);
447 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
454 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
455 while (prev && offset < prev_entry->start) {
456 prev = rb_prev(prev);
457 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
464 static inline struct rb_node *
465 tree_search_for_insert(struct extent_io_tree *tree,
467 struct rb_node ***p_ret,
468 struct rb_node **parent_ret)
470 struct rb_node *next= NULL;
473 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
479 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
482 return tree_search_for_insert(tree, offset, NULL, NULL);
486 * utility function to look for merge candidates inside a given range.
487 * Any extents with matching state are merged together into a single
488 * extent in the tree. Extents with EXTENT_IO in their state field
489 * are not merged because the end_io handlers need to be able to do
490 * operations on them without sleeping (or doing allocations/splits).
492 * This should be called with the tree lock held.
494 static void merge_state(struct extent_io_tree *tree,
495 struct extent_state *state)
497 struct extent_state *other;
498 struct rb_node *other_node;
500 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
503 other_node = rb_prev(&state->rb_node);
505 other = rb_entry(other_node, struct extent_state, rb_node);
506 if (other->end == state->start - 1 &&
507 other->state == state->state) {
508 if (tree->private_data &&
509 is_data_inode(tree->private_data))
510 btrfs_merge_delalloc_extent(tree->private_data,
512 state->start = other->start;
513 rb_erase(&other->rb_node, &tree->state);
514 RB_CLEAR_NODE(&other->rb_node);
515 free_extent_state(other);
518 other_node = rb_next(&state->rb_node);
520 other = rb_entry(other_node, struct extent_state, rb_node);
521 if (other->start == state->end + 1 &&
522 other->state == state->state) {
523 if (tree->private_data &&
524 is_data_inode(tree->private_data))
525 btrfs_merge_delalloc_extent(tree->private_data,
527 state->end = other->end;
528 rb_erase(&other->rb_node, &tree->state);
529 RB_CLEAR_NODE(&other->rb_node);
530 free_extent_state(other);
535 static void set_state_bits(struct extent_io_tree *tree,
536 struct extent_state *state, u32 *bits,
537 struct extent_changeset *changeset);
540 * insert an extent_state struct into the tree. 'bits' are set on the
541 * struct before it is inserted.
543 * This may return -EEXIST if the extent is already there, in which case the
544 * state struct is freed.
546 * The tree lock is not taken internally. This is a utility function and
547 * probably isn't what you want to call (see set/clear_extent_bit).
549 static int insert_state(struct extent_io_tree *tree,
550 struct extent_state *state, u64 start, u64 end,
552 struct rb_node **parent,
553 u32 *bits, struct extent_changeset *changeset)
555 struct rb_node *node;
558 btrfs_err(tree->fs_info,
559 "insert state: end < start %llu %llu", end, start);
562 state->start = start;
565 set_state_bits(tree, state, bits, changeset);
567 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
569 struct extent_state *found;
570 found = rb_entry(node, struct extent_state, rb_node);
571 btrfs_err(tree->fs_info,
572 "found node %llu %llu on insert of %llu %llu",
573 found->start, found->end, start, end);
576 merge_state(tree, state);
581 * split a given extent state struct in two, inserting the preallocated
582 * struct 'prealloc' as the newly created second half. 'split' indicates an
583 * offset inside 'orig' where it should be split.
586 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
587 * are two extent state structs in the tree:
588 * prealloc: [orig->start, split - 1]
589 * orig: [ split, orig->end ]
591 * The tree locks are not taken by this function. They need to be held
594 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
595 struct extent_state *prealloc, u64 split)
597 struct rb_node *node;
599 if (tree->private_data && is_data_inode(tree->private_data))
600 btrfs_split_delalloc_extent(tree->private_data, orig, split);
602 prealloc->start = orig->start;
603 prealloc->end = split - 1;
604 prealloc->state = orig->state;
607 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
608 &prealloc->rb_node, NULL, NULL);
610 free_extent_state(prealloc);
616 static struct extent_state *next_state(struct extent_state *state)
618 struct rb_node *next = rb_next(&state->rb_node);
620 return rb_entry(next, struct extent_state, rb_node);
626 * utility function to clear some bits in an extent state struct.
627 * it will optionally wake up anyone waiting on this state (wake == 1).
629 * If no bits are set on the state struct after clearing things, the
630 * struct is freed and removed from the tree
632 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
633 struct extent_state *state,
635 struct extent_changeset *changeset)
637 struct extent_state *next;
638 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
641 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
642 u64 range = state->end - state->start + 1;
643 WARN_ON(range > tree->dirty_bytes);
644 tree->dirty_bytes -= range;
647 if (tree->private_data && is_data_inode(tree->private_data))
648 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
650 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
652 state->state &= ~bits_to_clear;
655 if (state->state == 0) {
656 next = next_state(state);
657 if (extent_state_in_tree(state)) {
658 rb_erase(&state->rb_node, &tree->state);
659 RB_CLEAR_NODE(&state->rb_node);
660 free_extent_state(state);
665 merge_state(tree, state);
666 next = next_state(state);
671 static struct extent_state *
672 alloc_extent_state_atomic(struct extent_state *prealloc)
675 prealloc = alloc_extent_state(GFP_ATOMIC);
680 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
682 btrfs_panic(tree->fs_info, err,
683 "locking error: extent tree was modified by another thread while locked");
687 * clear some bits on a range in the tree. This may require splitting
688 * or inserting elements in the tree, so the gfp mask is used to
689 * indicate which allocations or sleeping are allowed.
691 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
692 * the given range from the tree regardless of state (ie for truncate).
694 * the range [start, end] is inclusive.
696 * This takes the tree lock, and returns 0 on success and < 0 on error.
698 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
699 u32 bits, int wake, int delete,
700 struct extent_state **cached_state,
701 gfp_t mask, struct extent_changeset *changeset)
703 struct extent_state *state;
704 struct extent_state *cached;
705 struct extent_state *prealloc = NULL;
706 struct rb_node *node;
711 btrfs_debug_check_extent_io_range(tree, start, end);
712 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
714 if (bits & EXTENT_DELALLOC)
715 bits |= EXTENT_NORESERVE;
718 bits |= ~EXTENT_CTLBITS;
720 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
723 if (!prealloc && gfpflags_allow_blocking(mask)) {
725 * Don't care for allocation failure here because we might end
726 * up not needing the pre-allocated extent state at all, which
727 * is the case if we only have in the tree extent states that
728 * cover our input range and don't cover too any other range.
729 * If we end up needing a new extent state we allocate it later.
731 prealloc = alloc_extent_state(mask);
734 spin_lock(&tree->lock);
736 cached = *cached_state;
739 *cached_state = NULL;
743 if (cached && extent_state_in_tree(cached) &&
744 cached->start <= start && cached->end > start) {
746 refcount_dec(&cached->refs);
751 free_extent_state(cached);
754 * this search will find the extents that end after
757 node = tree_search(tree, start);
760 state = rb_entry(node, struct extent_state, rb_node);
762 if (state->start > end)
764 WARN_ON(state->end < start);
765 last_end = state->end;
767 /* the state doesn't have the wanted bits, go ahead */
768 if (!(state->state & bits)) {
769 state = next_state(state);
774 * | ---- desired range ---- |
776 * | ------------- state -------------- |
778 * We need to split the extent we found, and may flip
779 * bits on second half.
781 * If the extent we found extends past our range, we
782 * just split and search again. It'll get split again
783 * the next time though.
785 * If the extent we found is inside our range, we clear
786 * the desired bit on it.
789 if (state->start < start) {
790 prealloc = alloc_extent_state_atomic(prealloc);
792 err = split_state(tree, state, prealloc, start);
794 extent_io_tree_panic(tree, err);
799 if (state->end <= end) {
800 state = clear_state_bit(tree, state, &bits, wake,
807 * | ---- desired range ---- |
809 * We need to split the extent, and clear the bit
812 if (state->start <= end && state->end > end) {
813 prealloc = alloc_extent_state_atomic(prealloc);
815 err = split_state(tree, state, prealloc, end + 1);
817 extent_io_tree_panic(tree, err);
822 clear_state_bit(tree, prealloc, &bits, wake, changeset);
828 state = clear_state_bit(tree, state, &bits, wake, changeset);
830 if (last_end == (u64)-1)
832 start = last_end + 1;
833 if (start <= end && state && !need_resched())
839 spin_unlock(&tree->lock);
840 if (gfpflags_allow_blocking(mask))
845 spin_unlock(&tree->lock);
847 free_extent_state(prealloc);
853 static void wait_on_state(struct extent_io_tree *tree,
854 struct extent_state *state)
855 __releases(tree->lock)
856 __acquires(tree->lock)
859 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
860 spin_unlock(&tree->lock);
862 spin_lock(&tree->lock);
863 finish_wait(&state->wq, &wait);
867 * waits for one or more bits to clear on a range in the state tree.
868 * The range [start, end] is inclusive.
869 * The tree lock is taken by this function
871 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
874 struct extent_state *state;
875 struct rb_node *node;
877 btrfs_debug_check_extent_io_range(tree, start, end);
879 spin_lock(&tree->lock);
883 * this search will find all the extents that end after
886 node = tree_search(tree, start);
891 state = rb_entry(node, struct extent_state, rb_node);
893 if (state->start > end)
896 if (state->state & bits) {
897 start = state->start;
898 refcount_inc(&state->refs);
899 wait_on_state(tree, state);
900 free_extent_state(state);
903 start = state->end + 1;
908 if (!cond_resched_lock(&tree->lock)) {
909 node = rb_next(node);
914 spin_unlock(&tree->lock);
917 static void set_state_bits(struct extent_io_tree *tree,
918 struct extent_state *state,
919 u32 *bits, struct extent_changeset *changeset)
921 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
924 if (tree->private_data && is_data_inode(tree->private_data))
925 btrfs_set_delalloc_extent(tree->private_data, state, bits);
927 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
928 u64 range = state->end - state->start + 1;
929 tree->dirty_bytes += range;
931 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
933 state->state |= bits_to_set;
936 static void cache_state_if_flags(struct extent_state *state,
937 struct extent_state **cached_ptr,
940 if (cached_ptr && !(*cached_ptr)) {
941 if (!flags || (state->state & flags)) {
943 refcount_inc(&state->refs);
948 static void cache_state(struct extent_state *state,
949 struct extent_state **cached_ptr)
951 return cache_state_if_flags(state, cached_ptr,
952 EXTENT_LOCKED | EXTENT_BOUNDARY);
956 * set some bits on a range in the tree. This may require allocations or
957 * sleeping, so the gfp mask is used to indicate what is allowed.
959 * If any of the exclusive bits are set, this will fail with -EEXIST if some
960 * part of the range already has the desired bits set. The start of the
961 * existing range is returned in failed_start in this case.
963 * [start, end] is inclusive This takes the tree lock.
965 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
966 u32 exclusive_bits, u64 *failed_start,
967 struct extent_state **cached_state, gfp_t mask,
968 struct extent_changeset *changeset)
970 struct extent_state *state;
971 struct extent_state *prealloc = NULL;
972 struct rb_node *node;
974 struct rb_node *parent;
979 btrfs_debug_check_extent_io_range(tree, start, end);
980 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
983 ASSERT(failed_start);
985 ASSERT(failed_start == NULL);
987 if (!prealloc && gfpflags_allow_blocking(mask)) {
989 * Don't care for allocation failure here because we might end
990 * up not needing the pre-allocated extent state at all, which
991 * is the case if we only have in the tree extent states that
992 * cover our input range and don't cover too any other range.
993 * If we end up needing a new extent state we allocate it later.
995 prealloc = alloc_extent_state(mask);
998 spin_lock(&tree->lock);
999 if (cached_state && *cached_state) {
1000 state = *cached_state;
1001 if (state->start <= start && state->end > start &&
1002 extent_state_in_tree(state)) {
1003 node = &state->rb_node;
1008 * this search will find all the extents that end after
1011 node = tree_search_for_insert(tree, start, &p, &parent);
1013 prealloc = alloc_extent_state_atomic(prealloc);
1015 err = insert_state(tree, prealloc, start, end,
1016 &p, &parent, &bits, changeset);
1018 extent_io_tree_panic(tree, err);
1020 cache_state(prealloc, cached_state);
1024 state = rb_entry(node, struct extent_state, rb_node);
1026 last_start = state->start;
1027 last_end = state->end;
1030 * | ---- desired range ---- |
1033 * Just lock what we found and keep going
1035 if (state->start == start && state->end <= end) {
1036 if (state->state & exclusive_bits) {
1037 *failed_start = state->start;
1042 set_state_bits(tree, state, &bits, changeset);
1043 cache_state(state, cached_state);
1044 merge_state(tree, state);
1045 if (last_end == (u64)-1)
1047 start = last_end + 1;
1048 state = next_state(state);
1049 if (start < end && state && state->start == start &&
1056 * | ---- desired range ---- |
1059 * | ------------- state -------------- |
1061 * We need to split the extent we found, and may flip bits on
1064 * If the extent we found extends past our
1065 * range, we just split and search again. It'll get split
1066 * again the next time though.
1068 * If the extent we found is inside our range, we set the
1069 * desired bit on it.
1071 if (state->start < start) {
1072 if (state->state & exclusive_bits) {
1073 *failed_start = start;
1079 * If this extent already has all the bits we want set, then
1080 * skip it, not necessary to split it or do anything with it.
1082 if ((state->state & bits) == bits) {
1083 start = state->end + 1;
1084 cache_state(state, cached_state);
1088 prealloc = alloc_extent_state_atomic(prealloc);
1090 err = split_state(tree, state, prealloc, start);
1092 extent_io_tree_panic(tree, err);
1097 if (state->end <= end) {
1098 set_state_bits(tree, state, &bits, changeset);
1099 cache_state(state, cached_state);
1100 merge_state(tree, state);
1101 if (last_end == (u64)-1)
1103 start = last_end + 1;
1104 state = next_state(state);
1105 if (start < end && state && state->start == start &&
1112 * | ---- desired range ---- |
1113 * | state | or | state |
1115 * There's a hole, we need to insert something in it and
1116 * ignore the extent we found.
1118 if (state->start > start) {
1120 if (end < last_start)
1123 this_end = last_start - 1;
1125 prealloc = alloc_extent_state_atomic(prealloc);
1129 * Avoid to free 'prealloc' if it can be merged with
1132 err = insert_state(tree, prealloc, start, this_end,
1133 NULL, NULL, &bits, changeset);
1135 extent_io_tree_panic(tree, err);
1137 cache_state(prealloc, cached_state);
1139 start = this_end + 1;
1143 * | ---- desired range ---- |
1145 * We need to split the extent, and set the bit
1148 if (state->start <= end && state->end > end) {
1149 if (state->state & exclusive_bits) {
1150 *failed_start = start;
1155 prealloc = alloc_extent_state_atomic(prealloc);
1157 err = split_state(tree, state, prealloc, end + 1);
1159 extent_io_tree_panic(tree, err);
1161 set_state_bits(tree, prealloc, &bits, changeset);
1162 cache_state(prealloc, cached_state);
1163 merge_state(tree, prealloc);
1171 spin_unlock(&tree->lock);
1172 if (gfpflags_allow_blocking(mask))
1177 spin_unlock(&tree->lock);
1179 free_extent_state(prealloc);
1186 * convert_extent_bit - convert all bits in a given range from one bit to
1188 * @tree: the io tree to search
1189 * @start: the start offset in bytes
1190 * @end: the end offset in bytes (inclusive)
1191 * @bits: the bits to set in this range
1192 * @clear_bits: the bits to clear in this range
1193 * @cached_state: state that we're going to cache
1195 * This will go through and set bits for the given range. If any states exist
1196 * already in this range they are set with the given bit and cleared of the
1197 * clear_bits. This is only meant to be used by things that are mergeable, ie
1198 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1199 * boundary bits like LOCK.
1201 * All allocations are done with GFP_NOFS.
1203 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1204 u32 bits, u32 clear_bits,
1205 struct extent_state **cached_state)
1207 struct extent_state *state;
1208 struct extent_state *prealloc = NULL;
1209 struct rb_node *node;
1211 struct rb_node *parent;
1215 bool first_iteration = true;
1217 btrfs_debug_check_extent_io_range(tree, start, end);
1218 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1224 * Best effort, don't worry if extent state allocation fails
1225 * here for the first iteration. We might have a cached state
1226 * that matches exactly the target range, in which case no
1227 * extent state allocations are needed. We'll only know this
1228 * after locking the tree.
1230 prealloc = alloc_extent_state(GFP_NOFS);
1231 if (!prealloc && !first_iteration)
1235 spin_lock(&tree->lock);
1236 if (cached_state && *cached_state) {
1237 state = *cached_state;
1238 if (state->start <= start && state->end > start &&
1239 extent_state_in_tree(state)) {
1240 node = &state->rb_node;
1246 * this search will find all the extents that end after
1249 node = tree_search_for_insert(tree, start, &p, &parent);
1251 prealloc = alloc_extent_state_atomic(prealloc);
1256 err = insert_state(tree, prealloc, start, end,
1257 &p, &parent, &bits, NULL);
1259 extent_io_tree_panic(tree, err);
1260 cache_state(prealloc, cached_state);
1264 state = rb_entry(node, struct extent_state, rb_node);
1266 last_start = state->start;
1267 last_end = state->end;
1270 * | ---- desired range ---- |
1273 * Just lock what we found and keep going
1275 if (state->start == start && state->end <= end) {
1276 set_state_bits(tree, state, &bits, NULL);
1277 cache_state(state, cached_state);
1278 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1279 if (last_end == (u64)-1)
1281 start = last_end + 1;
1282 if (start < end && state && state->start == start &&
1289 * | ---- desired range ---- |
1292 * | ------------- state -------------- |
1294 * We need to split the extent we found, and may flip bits on
1297 * If the extent we found extends past our
1298 * range, we just split and search again. It'll get split
1299 * again the next time though.
1301 * If the extent we found is inside our range, we set the
1302 * desired bit on it.
1304 if (state->start < start) {
1305 prealloc = alloc_extent_state_atomic(prealloc);
1310 err = split_state(tree, state, prealloc, start);
1312 extent_io_tree_panic(tree, err);
1316 if (state->end <= end) {
1317 set_state_bits(tree, state, &bits, NULL);
1318 cache_state(state, cached_state);
1319 state = clear_state_bit(tree, state, &clear_bits, 0,
1321 if (last_end == (u64)-1)
1323 start = last_end + 1;
1324 if (start < end && state && state->start == start &&
1331 * | ---- desired range ---- |
1332 * | state | or | state |
1334 * There's a hole, we need to insert something in it and
1335 * ignore the extent we found.
1337 if (state->start > start) {
1339 if (end < last_start)
1342 this_end = last_start - 1;
1344 prealloc = alloc_extent_state_atomic(prealloc);
1351 * Avoid to free 'prealloc' if it can be merged with
1354 err = insert_state(tree, prealloc, start, this_end,
1355 NULL, NULL, &bits, NULL);
1357 extent_io_tree_panic(tree, err);
1358 cache_state(prealloc, cached_state);
1360 start = this_end + 1;
1364 * | ---- desired range ---- |
1366 * We need to split the extent, and set the bit
1369 if (state->start <= end && state->end > end) {
1370 prealloc = alloc_extent_state_atomic(prealloc);
1376 err = split_state(tree, state, prealloc, end + 1);
1378 extent_io_tree_panic(tree, err);
1380 set_state_bits(tree, prealloc, &bits, NULL);
1381 cache_state(prealloc, cached_state);
1382 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1390 spin_unlock(&tree->lock);
1392 first_iteration = false;
1396 spin_unlock(&tree->lock);
1398 free_extent_state(prealloc);
1403 /* wrappers around set/clear extent bit */
1404 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1405 u32 bits, struct extent_changeset *changeset)
1408 * We don't support EXTENT_LOCKED yet, as current changeset will
1409 * record any bits changed, so for EXTENT_LOCKED case, it will
1410 * either fail with -EEXIST or changeset will record the whole
1413 BUG_ON(bits & EXTENT_LOCKED);
1415 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1419 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1422 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1426 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1427 u32 bits, int wake, int delete,
1428 struct extent_state **cached)
1430 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1431 cached, GFP_NOFS, NULL);
1434 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1435 u32 bits, struct extent_changeset *changeset)
1438 * Don't support EXTENT_LOCKED case, same reason as
1439 * set_record_extent_bits().
1441 BUG_ON(bits & EXTENT_LOCKED);
1443 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1448 * either insert or lock state struct between start and end use mask to tell
1449 * us if waiting is desired.
1451 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1452 struct extent_state **cached_state)
1458 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1459 EXTENT_LOCKED, &failed_start,
1460 cached_state, GFP_NOFS, NULL);
1461 if (err == -EEXIST) {
1462 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1463 start = failed_start;
1466 WARN_ON(start > end);
1471 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1476 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1477 &failed_start, NULL, GFP_NOFS, NULL);
1478 if (err == -EEXIST) {
1479 if (failed_start > start)
1480 clear_extent_bit(tree, start, failed_start - 1,
1481 EXTENT_LOCKED, 1, 0, NULL);
1487 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1489 unsigned long index = start >> PAGE_SHIFT;
1490 unsigned long end_index = end >> PAGE_SHIFT;
1493 while (index <= end_index) {
1494 page = find_get_page(inode->i_mapping, index);
1495 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1496 clear_page_dirty_for_io(page);
1502 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1504 unsigned long index = start >> PAGE_SHIFT;
1505 unsigned long end_index = end >> PAGE_SHIFT;
1508 while (index <= end_index) {
1509 page = find_get_page(inode->i_mapping, index);
1510 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1511 __set_page_dirty_nobuffers(page);
1512 account_page_redirty(page);
1518 /* find the first state struct with 'bits' set after 'start', and
1519 * return it. tree->lock must be held. NULL will returned if
1520 * nothing was found after 'start'
1522 static struct extent_state *
1523 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1525 struct rb_node *node;
1526 struct extent_state *state;
1529 * this search will find all the extents that end after
1532 node = tree_search(tree, start);
1537 state = rb_entry(node, struct extent_state, rb_node);
1538 if (state->end >= start && (state->state & bits))
1541 node = rb_next(node);
1550 * Find the first offset in the io tree with one or more @bits set.
1552 * Note: If there are multiple bits set in @bits, any of them will match.
1554 * Return 0 if we find something, and update @start_ret and @end_ret.
1555 * Return 1 if we found nothing.
1557 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1558 u64 *start_ret, u64 *end_ret, u32 bits,
1559 struct extent_state **cached_state)
1561 struct extent_state *state;
1564 spin_lock(&tree->lock);
1565 if (cached_state && *cached_state) {
1566 state = *cached_state;
1567 if (state->end == start - 1 && extent_state_in_tree(state)) {
1568 while ((state = next_state(state)) != NULL) {
1569 if (state->state & bits)
1572 free_extent_state(*cached_state);
1573 *cached_state = NULL;
1576 free_extent_state(*cached_state);
1577 *cached_state = NULL;
1580 state = find_first_extent_bit_state(tree, start, bits);
1583 cache_state_if_flags(state, cached_state, 0);
1584 *start_ret = state->start;
1585 *end_ret = state->end;
1589 spin_unlock(&tree->lock);
1594 * Find a contiguous area of bits
1596 * @tree: io tree to check
1597 * @start: offset to start the search from
1598 * @start_ret: the first offset we found with the bits set
1599 * @end_ret: the final contiguous range of the bits that were set
1600 * @bits: bits to look for
1602 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1603 * to set bits appropriately, and then merge them again. During this time it
1604 * will drop the tree->lock, so use this helper if you want to find the actual
1605 * contiguous area for given bits. We will search to the first bit we find, and
1606 * then walk down the tree until we find a non-contiguous area. The area
1607 * returned will be the full contiguous area with the bits set.
1609 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1610 u64 *start_ret, u64 *end_ret, u32 bits)
1612 struct extent_state *state;
1615 spin_lock(&tree->lock);
1616 state = find_first_extent_bit_state(tree, start, bits);
1618 *start_ret = state->start;
1619 *end_ret = state->end;
1620 while ((state = next_state(state)) != NULL) {
1621 if (state->start > (*end_ret + 1))
1623 *end_ret = state->end;
1627 spin_unlock(&tree->lock);
1632 * Find the first range that has @bits not set. This range could start before
1635 * @tree: the tree to search
1636 * @start: offset at/after which the found extent should start
1637 * @start_ret: records the beginning of the range
1638 * @end_ret: records the end of the range (inclusive)
1639 * @bits: the set of bits which must be unset
1641 * Since unallocated range is also considered one which doesn't have the bits
1642 * set it's possible that @end_ret contains -1, this happens in case the range
1643 * spans (last_range_end, end of device]. In this case it's up to the caller to
1644 * trim @end_ret to the appropriate size.
1646 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1647 u64 *start_ret, u64 *end_ret, u32 bits)
1649 struct extent_state *state;
1650 struct rb_node *node, *prev = NULL, *next;
1652 spin_lock(&tree->lock);
1654 /* Find first extent with bits cleared */
1656 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1657 if (!node && !next && !prev) {
1659 * Tree is completely empty, send full range and let
1660 * caller deal with it
1665 } else if (!node && !next) {
1667 * We are past the last allocated chunk, set start at
1668 * the end of the last extent.
1670 state = rb_entry(prev, struct extent_state, rb_node);
1671 *start_ret = state->end + 1;
1678 * At this point 'node' either contains 'start' or start is
1681 state = rb_entry(node, struct extent_state, rb_node);
1683 if (in_range(start, state->start, state->end - state->start + 1)) {
1684 if (state->state & bits) {
1686 * |--range with bits sets--|
1690 start = state->end + 1;
1693 * 'start' falls within a range that doesn't
1694 * have the bits set, so take its start as
1695 * the beginning of the desired range
1697 * |--range with bits cleared----|
1701 *start_ret = state->start;
1706 * |---prev range---|---hole/unset---|---node range---|
1712 * |---hole/unset--||--first node--|
1717 state = rb_entry(prev, struct extent_state,
1719 *start_ret = state->end + 1;
1728 * Find the longest stretch from start until an entry which has the
1732 state = rb_entry(node, struct extent_state, rb_node);
1733 if (state->end >= start && !(state->state & bits)) {
1734 *end_ret = state->end;
1736 *end_ret = state->start - 1;
1740 node = rb_next(node);
1745 spin_unlock(&tree->lock);
1749 * find a contiguous range of bytes in the file marked as delalloc, not
1750 * more than 'max_bytes'. start and end are used to return the range,
1752 * true is returned if we find something, false if nothing was in the tree
1754 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1755 u64 *end, u64 max_bytes,
1756 struct extent_state **cached_state)
1758 struct rb_node *node;
1759 struct extent_state *state;
1760 u64 cur_start = *start;
1762 u64 total_bytes = 0;
1764 spin_lock(&tree->lock);
1767 * this search will find all the extents that end after
1770 node = tree_search(tree, cur_start);
1777 state = rb_entry(node, struct extent_state, rb_node);
1778 if (found && (state->start != cur_start ||
1779 (state->state & EXTENT_BOUNDARY))) {
1782 if (!(state->state & EXTENT_DELALLOC)) {
1788 *start = state->start;
1789 *cached_state = state;
1790 refcount_inc(&state->refs);
1794 cur_start = state->end + 1;
1795 node = rb_next(node);
1796 total_bytes += state->end - state->start + 1;
1797 if (total_bytes >= max_bytes)
1803 spin_unlock(&tree->lock);
1807 static int __process_pages_contig(struct address_space *mapping,
1808 struct page *locked_page,
1809 pgoff_t start_index, pgoff_t end_index,
1810 unsigned long page_ops, pgoff_t *index_ret);
1812 static noinline void __unlock_for_delalloc(struct inode *inode,
1813 struct page *locked_page,
1816 unsigned long index = start >> PAGE_SHIFT;
1817 unsigned long end_index = end >> PAGE_SHIFT;
1819 ASSERT(locked_page);
1820 if (index == locked_page->index && end_index == index)
1823 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1827 static noinline int lock_delalloc_pages(struct inode *inode,
1828 struct page *locked_page,
1832 unsigned long index = delalloc_start >> PAGE_SHIFT;
1833 unsigned long index_ret = index;
1834 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1837 ASSERT(locked_page);
1838 if (index == locked_page->index && index == end_index)
1841 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1842 end_index, PAGE_LOCK, &index_ret);
1844 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1845 (u64)index_ret << PAGE_SHIFT);
1850 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1851 * more than @max_bytes. @Start and @end are used to return the range,
1853 * Return: true if we find something
1854 * false if nothing was in the tree
1857 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1858 struct page *locked_page, u64 *start,
1861 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1862 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1866 struct extent_state *cached_state = NULL;
1871 /* step one, find a bunch of delalloc bytes starting at start */
1872 delalloc_start = *start;
1874 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1875 max_bytes, &cached_state);
1876 if (!found || delalloc_end <= *start) {
1877 *start = delalloc_start;
1878 *end = delalloc_end;
1879 free_extent_state(cached_state);
1884 * start comes from the offset of locked_page. We have to lock
1885 * pages in order, so we can't process delalloc bytes before
1888 if (delalloc_start < *start)
1889 delalloc_start = *start;
1892 * make sure to limit the number of pages we try to lock down
1894 if (delalloc_end + 1 - delalloc_start > max_bytes)
1895 delalloc_end = delalloc_start + max_bytes - 1;
1897 /* step two, lock all the pages after the page that has start */
1898 ret = lock_delalloc_pages(inode, locked_page,
1899 delalloc_start, delalloc_end);
1900 ASSERT(!ret || ret == -EAGAIN);
1901 if (ret == -EAGAIN) {
1902 /* some of the pages are gone, lets avoid looping by
1903 * shortening the size of the delalloc range we're searching
1905 free_extent_state(cached_state);
1906 cached_state = NULL;
1908 max_bytes = PAGE_SIZE;
1917 /* step three, lock the state bits for the whole range */
1918 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1920 /* then test to make sure it is all still delalloc */
1921 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1922 EXTENT_DELALLOC, 1, cached_state);
1924 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1926 __unlock_for_delalloc(inode, locked_page,
1927 delalloc_start, delalloc_end);
1931 free_extent_state(cached_state);
1932 *start = delalloc_start;
1933 *end = delalloc_end;
1938 static int __process_pages_contig(struct address_space *mapping,
1939 struct page *locked_page,
1940 pgoff_t start_index, pgoff_t end_index,
1941 unsigned long page_ops, pgoff_t *index_ret)
1943 unsigned long nr_pages = end_index - start_index + 1;
1944 unsigned long pages_processed = 0;
1945 pgoff_t index = start_index;
1946 struct page *pages[16];
1951 if (page_ops & PAGE_LOCK) {
1952 ASSERT(page_ops == PAGE_LOCK);
1953 ASSERT(index_ret && *index_ret == start_index);
1956 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1957 mapping_set_error(mapping, -EIO);
1959 while (nr_pages > 0) {
1960 ret = find_get_pages_contig(mapping, index,
1961 min_t(unsigned long,
1962 nr_pages, ARRAY_SIZE(pages)), pages);
1965 * Only if we're going to lock these pages,
1966 * can we find nothing at @index.
1968 ASSERT(page_ops & PAGE_LOCK);
1973 for (i = 0; i < ret; i++) {
1974 if (page_ops & PAGE_SET_PRIVATE2)
1975 SetPagePrivate2(pages[i]);
1977 if (locked_page && pages[i] == locked_page) {
1982 if (page_ops & PAGE_START_WRITEBACK) {
1983 clear_page_dirty_for_io(pages[i]);
1984 set_page_writeback(pages[i]);
1986 if (page_ops & PAGE_SET_ERROR)
1987 SetPageError(pages[i]);
1988 if (page_ops & PAGE_END_WRITEBACK)
1989 end_page_writeback(pages[i]);
1990 if (page_ops & PAGE_UNLOCK)
1991 unlock_page(pages[i]);
1992 if (page_ops & PAGE_LOCK) {
1993 lock_page(pages[i]);
1994 if (!PageDirty(pages[i]) ||
1995 pages[i]->mapping != mapping) {
1996 unlock_page(pages[i]);
1997 for (; i < ret; i++)
2011 if (err && index_ret)
2012 *index_ret = start_index + pages_processed - 1;
2016 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2017 struct page *locked_page,
2018 u32 clear_bits, unsigned long page_ops)
2020 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2022 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2023 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
2028 * count the number of bytes in the tree that have a given bit(s)
2029 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2030 * cached. The total number found is returned.
2032 u64 count_range_bits(struct extent_io_tree *tree,
2033 u64 *start, u64 search_end, u64 max_bytes,
2034 u32 bits, int contig)
2036 struct rb_node *node;
2037 struct extent_state *state;
2038 u64 cur_start = *start;
2039 u64 total_bytes = 0;
2043 if (WARN_ON(search_end <= cur_start))
2046 spin_lock(&tree->lock);
2047 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2048 total_bytes = tree->dirty_bytes;
2052 * this search will find all the extents that end after
2055 node = tree_search(tree, cur_start);
2060 state = rb_entry(node, struct extent_state, rb_node);
2061 if (state->start > search_end)
2063 if (contig && found && state->start > last + 1)
2065 if (state->end >= cur_start && (state->state & bits) == bits) {
2066 total_bytes += min(search_end, state->end) + 1 -
2067 max(cur_start, state->start);
2068 if (total_bytes >= max_bytes)
2071 *start = max(cur_start, state->start);
2075 } else if (contig && found) {
2078 node = rb_next(node);
2083 spin_unlock(&tree->lock);
2088 * set the private field for a given byte offset in the tree. If there isn't
2089 * an extent_state there already, this does nothing.
2091 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2092 struct io_failure_record *failrec)
2094 struct rb_node *node;
2095 struct extent_state *state;
2098 spin_lock(&tree->lock);
2100 * this search will find all the extents that end after
2103 node = tree_search(tree, start);
2108 state = rb_entry(node, struct extent_state, rb_node);
2109 if (state->start != start) {
2113 state->failrec = failrec;
2115 spin_unlock(&tree->lock);
2119 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2121 struct rb_node *node;
2122 struct extent_state *state;
2123 struct io_failure_record *failrec;
2125 spin_lock(&tree->lock);
2127 * this search will find all the extents that end after
2130 node = tree_search(tree, start);
2132 failrec = ERR_PTR(-ENOENT);
2135 state = rb_entry(node, struct extent_state, rb_node);
2136 if (state->start != start) {
2137 failrec = ERR_PTR(-ENOENT);
2141 failrec = state->failrec;
2143 spin_unlock(&tree->lock);
2148 * searches a range in the state tree for a given mask.
2149 * If 'filled' == 1, this returns 1 only if every extent in the tree
2150 * has the bits set. Otherwise, 1 is returned if any bit in the
2151 * range is found set.
2153 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2154 u32 bits, int filled, struct extent_state *cached)
2156 struct extent_state *state = NULL;
2157 struct rb_node *node;
2160 spin_lock(&tree->lock);
2161 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2162 cached->end > start)
2163 node = &cached->rb_node;
2165 node = tree_search(tree, start);
2166 while (node && start <= end) {
2167 state = rb_entry(node, struct extent_state, rb_node);
2169 if (filled && state->start > start) {
2174 if (state->start > end)
2177 if (state->state & bits) {
2181 } else if (filled) {
2186 if (state->end == (u64)-1)
2189 start = state->end + 1;
2192 node = rb_next(node);
2199 spin_unlock(&tree->lock);
2204 * helper function to set a given page up to date if all the
2205 * extents in the tree for that page are up to date
2207 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2209 u64 start = page_offset(page);
2210 u64 end = start + PAGE_SIZE - 1;
2211 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2212 SetPageUptodate(page);
2215 int free_io_failure(struct extent_io_tree *failure_tree,
2216 struct extent_io_tree *io_tree,
2217 struct io_failure_record *rec)
2222 set_state_failrec(failure_tree, rec->start, NULL);
2223 ret = clear_extent_bits(failure_tree, rec->start,
2224 rec->start + rec->len - 1,
2225 EXTENT_LOCKED | EXTENT_DIRTY);
2229 ret = clear_extent_bits(io_tree, rec->start,
2230 rec->start + rec->len - 1,
2240 * this bypasses the standard btrfs submit functions deliberately, as
2241 * the standard behavior is to write all copies in a raid setup. here we only
2242 * want to write the one bad copy. so we do the mapping for ourselves and issue
2243 * submit_bio directly.
2244 * to avoid any synchronization issues, wait for the data after writing, which
2245 * actually prevents the read that triggered the error from finishing.
2246 * currently, there can be no more than two copies of every data bit. thus,
2247 * exactly one rewrite is required.
2249 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2250 u64 length, u64 logical, struct page *page,
2251 unsigned int pg_offset, int mirror_num)
2254 struct btrfs_device *dev;
2257 struct btrfs_bio *bbio = NULL;
2260 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2261 BUG_ON(!mirror_num);
2263 if (btrfs_is_zoned(fs_info))
2264 return btrfs_repair_one_zone(fs_info, logical);
2266 bio = btrfs_io_bio_alloc(1);
2267 bio->bi_iter.bi_size = 0;
2268 map_length = length;
2271 * Avoid races with device replace and make sure our bbio has devices
2272 * associated to its stripes that don't go away while we are doing the
2273 * read repair operation.
2275 btrfs_bio_counter_inc_blocked(fs_info);
2276 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2278 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2279 * to update all raid stripes, but here we just want to correct
2280 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2281 * stripe's dev and sector.
2283 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2284 &map_length, &bbio, 0);
2286 btrfs_bio_counter_dec(fs_info);
2290 ASSERT(bbio->mirror_num == 1);
2292 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2293 &map_length, &bbio, mirror_num);
2295 btrfs_bio_counter_dec(fs_info);
2299 BUG_ON(mirror_num != bbio->mirror_num);
2302 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2303 bio->bi_iter.bi_sector = sector;
2304 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2305 btrfs_put_bbio(bbio);
2306 if (!dev || !dev->bdev ||
2307 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2308 btrfs_bio_counter_dec(fs_info);
2312 bio_set_dev(bio, dev->bdev);
2313 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2314 bio_add_page(bio, page, length, pg_offset);
2316 if (btrfsic_submit_bio_wait(bio)) {
2317 /* try to remap that extent elsewhere? */
2318 btrfs_bio_counter_dec(fs_info);
2320 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2324 btrfs_info_rl_in_rcu(fs_info,
2325 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2327 rcu_str_deref(dev->name), sector);
2328 btrfs_bio_counter_dec(fs_info);
2333 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2335 struct btrfs_fs_info *fs_info = eb->fs_info;
2336 u64 start = eb->start;
2337 int i, num_pages = num_extent_pages(eb);
2340 if (sb_rdonly(fs_info->sb))
2343 for (i = 0; i < num_pages; i++) {
2344 struct page *p = eb->pages[i];
2346 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2347 start - page_offset(p), mirror_num);
2357 * each time an IO finishes, we do a fast check in the IO failure tree
2358 * to see if we need to process or clean up an io_failure_record
2360 int clean_io_failure(struct btrfs_fs_info *fs_info,
2361 struct extent_io_tree *failure_tree,
2362 struct extent_io_tree *io_tree, u64 start,
2363 struct page *page, u64 ino, unsigned int pg_offset)
2366 struct io_failure_record *failrec;
2367 struct extent_state *state;
2372 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2377 failrec = get_state_failrec(failure_tree, start);
2378 if (IS_ERR(failrec))
2381 BUG_ON(!failrec->this_mirror);
2383 if (failrec->in_validation) {
2384 /* there was no real error, just free the record */
2385 btrfs_debug(fs_info,
2386 "clean_io_failure: freeing dummy error at %llu",
2390 if (sb_rdonly(fs_info->sb))
2393 spin_lock(&io_tree->lock);
2394 state = find_first_extent_bit_state(io_tree,
2397 spin_unlock(&io_tree->lock);
2399 if (state && state->start <= failrec->start &&
2400 state->end >= failrec->start + failrec->len - 1) {
2401 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2403 if (num_copies > 1) {
2404 repair_io_failure(fs_info, ino, start, failrec->len,
2405 failrec->logical, page, pg_offset,
2406 failrec->failed_mirror);
2411 free_io_failure(failure_tree, io_tree, failrec);
2417 * Can be called when
2418 * - hold extent lock
2419 * - under ordered extent
2420 * - the inode is freeing
2422 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2424 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2425 struct io_failure_record *failrec;
2426 struct extent_state *state, *next;
2428 if (RB_EMPTY_ROOT(&failure_tree->state))
2431 spin_lock(&failure_tree->lock);
2432 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2434 if (state->start > end)
2437 ASSERT(state->end <= end);
2439 next = next_state(state);
2441 failrec = state->failrec;
2442 free_extent_state(state);
2447 spin_unlock(&failure_tree->lock);
2450 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2453 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2454 struct io_failure_record *failrec;
2455 struct extent_map *em;
2456 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2457 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2458 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2462 failrec = get_state_failrec(failure_tree, start);
2463 if (!IS_ERR(failrec)) {
2464 btrfs_debug(fs_info,
2465 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2466 failrec->logical, failrec->start, failrec->len,
2467 failrec->in_validation);
2469 * when data can be on disk more than twice, add to failrec here
2470 * (e.g. with a list for failed_mirror) to make
2471 * clean_io_failure() clean all those errors at once.
2477 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2479 return ERR_PTR(-ENOMEM);
2481 failrec->start = start;
2482 failrec->len = end - start + 1;
2483 failrec->this_mirror = 0;
2484 failrec->bio_flags = 0;
2485 failrec->in_validation = 0;
2487 read_lock(&em_tree->lock);
2488 em = lookup_extent_mapping(em_tree, start, failrec->len);
2490 read_unlock(&em_tree->lock);
2492 return ERR_PTR(-EIO);
2495 if (em->start > start || em->start + em->len <= start) {
2496 free_extent_map(em);
2499 read_unlock(&em_tree->lock);
2502 return ERR_PTR(-EIO);
2505 logical = start - em->start;
2506 logical = em->block_start + logical;
2507 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2508 logical = em->block_start;
2509 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2510 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2513 btrfs_debug(fs_info,
2514 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2515 logical, start, failrec->len);
2517 failrec->logical = logical;
2518 free_extent_map(em);
2520 /* Set the bits in the private failure tree */
2521 ret = set_extent_bits(failure_tree, start, end,
2522 EXTENT_LOCKED | EXTENT_DIRTY);
2524 ret = set_state_failrec(failure_tree, start, failrec);
2525 /* Set the bits in the inode's tree */
2526 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2527 } else if (ret < 0) {
2529 return ERR_PTR(ret);
2535 static bool btrfs_check_repairable(struct inode *inode, bool needs_validation,
2536 struct io_failure_record *failrec,
2539 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2542 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2543 if (num_copies == 1) {
2545 * we only have a single copy of the data, so don't bother with
2546 * all the retry and error correction code that follows. no
2547 * matter what the error is, it is very likely to persist.
2549 btrfs_debug(fs_info,
2550 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2551 num_copies, failrec->this_mirror, failed_mirror);
2556 * there are two premises:
2557 * a) deliver good data to the caller
2558 * b) correct the bad sectors on disk
2560 if (needs_validation) {
2562 * to fulfill b), we need to know the exact failing sectors, as
2563 * we don't want to rewrite any more than the failed ones. thus,
2564 * we need separate read requests for the failed bio
2566 * if the following BUG_ON triggers, our validation request got
2567 * merged. we need separate requests for our algorithm to work.
2569 BUG_ON(failrec->in_validation);
2570 failrec->in_validation = 1;
2571 failrec->this_mirror = failed_mirror;
2574 * we're ready to fulfill a) and b) alongside. get a good copy
2575 * of the failed sector and if we succeed, we have setup
2576 * everything for repair_io_failure to do the rest for us.
2578 if (failrec->in_validation) {
2579 BUG_ON(failrec->this_mirror != failed_mirror);
2580 failrec->in_validation = 0;
2581 failrec->this_mirror = 0;
2583 failrec->failed_mirror = failed_mirror;
2584 failrec->this_mirror++;
2585 if (failrec->this_mirror == failed_mirror)
2586 failrec->this_mirror++;
2589 if (failrec->this_mirror > num_copies) {
2590 btrfs_debug(fs_info,
2591 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2592 num_copies, failrec->this_mirror, failed_mirror);
2599 static bool btrfs_io_needs_validation(struct inode *inode, struct bio *bio)
2602 const u32 blocksize = inode->i_sb->s_blocksize;
2605 * If bi_status is BLK_STS_OK, then this was a checksum error, not an
2606 * I/O error. In this case, we already know exactly which sector was
2607 * bad, so we don't need to validate.
2609 if (bio->bi_status == BLK_STS_OK)
2613 * We need to validate each sector individually if the failed I/O was
2614 * for multiple sectors.
2616 * There are a few possible bios that can end up here:
2617 * 1. A buffered read bio, which is not cloned.
2618 * 2. A direct I/O read bio, which is cloned.
2619 * 3. A (buffered or direct) repair bio, which is not cloned.
2621 * For cloned bios (case 2), we can get the size from
2622 * btrfs_io_bio->iter; for non-cloned bios (cases 1 and 3), we can get
2623 * it from the bvecs.
2625 if (bio_flagged(bio, BIO_CLONED)) {
2626 if (btrfs_io_bio(bio)->iter.bi_size > blocksize)
2629 struct bio_vec *bvec;
2632 bio_for_each_bvec_all(bvec, bio, i) {
2633 len += bvec->bv_len;
2634 if (len > blocksize)
2641 blk_status_t btrfs_submit_read_repair(struct inode *inode,
2642 struct bio *failed_bio, u32 bio_offset,
2643 struct page *page, unsigned int pgoff,
2644 u64 start, u64 end, int failed_mirror,
2645 submit_bio_hook_t *submit_bio_hook)
2647 struct io_failure_record *failrec;
2648 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2649 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2650 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2651 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2652 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2653 bool need_validation;
2654 struct bio *repair_bio;
2655 struct btrfs_io_bio *repair_io_bio;
2656 blk_status_t status;
2658 btrfs_debug(fs_info,
2659 "repair read error: read error at %llu", start);
2661 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2663 failrec = btrfs_get_io_failure_record(inode, start, end);
2664 if (IS_ERR(failrec))
2665 return errno_to_blk_status(PTR_ERR(failrec));
2667 need_validation = btrfs_io_needs_validation(inode, failed_bio);
2669 if (!btrfs_check_repairable(inode, need_validation, failrec,
2671 free_io_failure(failure_tree, tree, failrec);
2672 return BLK_STS_IOERR;
2675 repair_bio = btrfs_io_bio_alloc(1);
2676 repair_io_bio = btrfs_io_bio(repair_bio);
2677 repair_bio->bi_opf = REQ_OP_READ;
2678 if (need_validation)
2679 repair_bio->bi_opf |= REQ_FAILFAST_DEV;
2680 repair_bio->bi_end_io = failed_bio->bi_end_io;
2681 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2682 repair_bio->bi_private = failed_bio->bi_private;
2684 if (failed_io_bio->csum) {
2685 const u32 csum_size = fs_info->csum_size;
2687 repair_io_bio->csum = repair_io_bio->csum_inline;
2688 memcpy(repair_io_bio->csum,
2689 failed_io_bio->csum + csum_size * icsum, csum_size);
2692 bio_add_page(repair_bio, page, failrec->len, pgoff);
2693 repair_io_bio->logical = failrec->start;
2694 repair_io_bio->iter = repair_bio->bi_iter;
2696 btrfs_debug(btrfs_sb(inode->i_sb),
2697 "repair read error: submitting new read to mirror %d, in_validation=%d",
2698 failrec->this_mirror, failrec->in_validation);
2700 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2701 failrec->bio_flags);
2703 free_io_failure(failure_tree, tree, failrec);
2704 bio_put(repair_bio);
2709 /* lots and lots of room for performance fixes in the end_bio funcs */
2711 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2713 int uptodate = (err == 0);
2716 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2719 ClearPageUptodate(page);
2721 ret = err < 0 ? err : -EIO;
2722 mapping_set_error(page->mapping, ret);
2727 * after a writepage IO is done, we need to:
2728 * clear the uptodate bits on error
2729 * clear the writeback bits in the extent tree for this IO
2730 * end_page_writeback if the page has no more pending IO
2732 * Scheduling is not allowed, so the extent state tree is expected
2733 * to have one and only one object corresponding to this IO.
2735 static void end_bio_extent_writepage(struct bio *bio)
2737 int error = blk_status_to_errno(bio->bi_status);
2738 struct bio_vec *bvec;
2741 struct bvec_iter_all iter_all;
2742 bool first_bvec = true;
2744 ASSERT(!bio_flagged(bio, BIO_CLONED));
2745 bio_for_each_segment_all(bvec, bio, iter_all) {
2746 struct page *page = bvec->bv_page;
2747 struct inode *inode = page->mapping->host;
2748 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2750 /* We always issue full-page reads, but if some block
2751 * in a page fails to read, blk_update_request() will
2752 * advance bv_offset and adjust bv_len to compensate.
2753 * Print a warning for nonzero offsets, and an error
2754 * if they don't add up to a full page. */
2755 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2756 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2758 "partial page write in btrfs with offset %u and length %u",
2759 bvec->bv_offset, bvec->bv_len);
2762 "incomplete page write in btrfs with offset %u and length %u",
2763 bvec->bv_offset, bvec->bv_len);
2766 start = page_offset(page);
2767 end = start + bvec->bv_offset + bvec->bv_len - 1;
2770 btrfs_record_physical_zoned(inode, start, bio);
2774 end_extent_writepage(page, error, start, end);
2775 end_page_writeback(page);
2782 * Record previously processed extent range
2784 * For endio_readpage_release_extent() to handle a full extent range, reducing
2785 * the extent io operations.
2787 struct processed_extent {
2788 struct btrfs_inode *inode;
2789 /* Start of the range in @inode */
2791 /* End of the range in @inode */
2797 * Try to release processed extent range
2799 * May not release the extent range right now if the current range is
2800 * contiguous to processed extent.
2802 * Will release processed extent when any of @inode, @uptodate, the range is
2803 * no longer contiguous to the processed range.
2805 * Passing @inode == NULL will force processed extent to be released.
2807 static void endio_readpage_release_extent(struct processed_extent *processed,
2808 struct btrfs_inode *inode, u64 start, u64 end,
2811 struct extent_state *cached = NULL;
2812 struct extent_io_tree *tree;
2814 /* The first extent, initialize @processed */
2815 if (!processed->inode)
2819 * Contiguous to processed extent, just uptodate the end.
2821 * Several things to notice:
2823 * - bio can be merged as long as on-disk bytenr is contiguous
2824 * This means we can have page belonging to other inodes, thus need to
2825 * check if the inode still matches.
2826 * - bvec can contain range beyond current page for multi-page bvec
2827 * Thus we need to do processed->end + 1 >= start check
2829 if (processed->inode == inode && processed->uptodate == uptodate &&
2830 processed->end + 1 >= start && end >= processed->end) {
2831 processed->end = end;
2835 tree = &processed->inode->io_tree;
2837 * Now we don't have range contiguous to the processed range, release
2838 * the processed range now.
2840 if (processed->uptodate && tree->track_uptodate)
2841 set_extent_uptodate(tree, processed->start, processed->end,
2842 &cached, GFP_ATOMIC);
2843 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2847 /* Update processed to current range */
2848 processed->inode = inode;
2849 processed->start = start;
2850 processed->end = end;
2851 processed->uptodate = uptodate;
2854 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2856 ASSERT(PageLocked(page));
2857 if (fs_info->sectorsize == PAGE_SIZE)
2860 ASSERT(PagePrivate(page));
2861 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2864 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2866 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2868 ASSERT(page_offset(page) <= start &&
2869 start + len <= page_offset(page) + PAGE_SIZE);
2872 btrfs_page_set_uptodate(fs_info, page, start, len);
2874 btrfs_page_clear_uptodate(fs_info, page, start, len);
2875 btrfs_page_set_error(fs_info, page, start, len);
2878 if (fs_info->sectorsize == PAGE_SIZE)
2880 else if (is_data_inode(page->mapping->host))
2882 * For subpage data, unlock the page if we're the last reader.
2883 * For subpage metadata, page lock is not utilized for read.
2885 btrfs_subpage_end_reader(fs_info, page, start, len);
2889 * Find extent buffer for a givne bytenr.
2891 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2894 static struct extent_buffer *find_extent_buffer_readpage(
2895 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2897 struct extent_buffer *eb;
2900 * For regular sectorsize, we can use page->private to grab extent
2903 if (fs_info->sectorsize == PAGE_SIZE) {
2904 ASSERT(PagePrivate(page) && page->private);
2905 return (struct extent_buffer *)page->private;
2908 /* For subpage case, we need to lookup buffer radix tree */
2910 eb = radix_tree_lookup(&fs_info->buffer_radix,
2911 bytenr >> fs_info->sectorsize_bits);
2918 * after a readpage IO is done, we need to:
2919 * clear the uptodate bits on error
2920 * set the uptodate bits if things worked
2921 * set the page up to date if all extents in the tree are uptodate
2922 * clear the lock bit in the extent tree
2923 * unlock the page if there are no other extents locked for it
2925 * Scheduling is not allowed, so the extent state tree is expected
2926 * to have one and only one object corresponding to this IO.
2928 static void end_bio_extent_readpage(struct bio *bio)
2930 struct bio_vec *bvec;
2931 int uptodate = !bio->bi_status;
2932 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2933 struct extent_io_tree *tree, *failure_tree;
2934 struct processed_extent processed = { 0 };
2936 * The offset to the beginning of a bio, since one bio can never be
2937 * larger than UINT_MAX, u32 here is enough.
2942 struct bvec_iter_all iter_all;
2944 ASSERT(!bio_flagged(bio, BIO_CLONED));
2945 bio_for_each_segment_all(bvec, bio, iter_all) {
2946 struct page *page = bvec->bv_page;
2947 struct inode *inode = page->mapping->host;
2948 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2949 const u32 sectorsize = fs_info->sectorsize;
2954 btrfs_debug(fs_info,
2955 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2956 bio->bi_iter.bi_sector, bio->bi_status,
2957 io_bio->mirror_num);
2958 tree = &BTRFS_I(inode)->io_tree;
2959 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2962 * We always issue full-sector reads, but if some block in a
2963 * page fails to read, blk_update_request() will advance
2964 * bv_offset and adjust bv_len to compensate. Print a warning
2965 * for unaligned offsets, and an error if they don't add up to
2968 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2970 "partial page read in btrfs with offset %u and length %u",
2971 bvec->bv_offset, bvec->bv_len);
2972 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
2975 "incomplete page read with offset %u and length %u",
2976 bvec->bv_offset, bvec->bv_len);
2978 start = page_offset(page) + bvec->bv_offset;
2979 end = start + bvec->bv_len - 1;
2982 mirror = io_bio->mirror_num;
2983 if (likely(uptodate)) {
2984 if (is_data_inode(inode))
2985 ret = btrfs_verify_data_csum(io_bio,
2986 bio_offset, page, start, end,
2989 ret = btrfs_validate_metadata_buffer(io_bio,
2990 page, start, end, mirror);
2994 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2995 failure_tree, tree, start,
2997 btrfs_ino(BTRFS_I(inode)), 0);
3000 if (likely(uptodate))
3003 if (is_data_inode(inode)) {
3006 * The generic bio_readpage_error handles errors the
3007 * following way: If possible, new read requests are
3008 * created and submitted and will end up in
3009 * end_bio_extent_readpage as well (if we're lucky,
3010 * not in the !uptodate case). In that case it returns
3011 * 0 and we just go on with the next page in our bio.
3012 * If it can't handle the error it will return -EIO and
3013 * we remain responsible for that page.
3015 if (!btrfs_submit_read_repair(inode, bio, bio_offset,
3017 start - page_offset(page),
3019 btrfs_submit_data_bio)) {
3020 uptodate = !bio->bi_status;
3021 ASSERT(bio_offset + len > bio_offset);
3026 struct extent_buffer *eb;
3028 eb = find_extent_buffer_readpage(fs_info, page, start);
3029 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3030 eb->read_mirror = mirror;
3031 atomic_dec(&eb->io_pages);
3032 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
3034 btree_readahead_hook(eb, -EIO);
3037 if (likely(uptodate)) {
3038 loff_t i_size = i_size_read(inode);
3039 pgoff_t end_index = i_size >> PAGE_SHIFT;
3042 * Zero out the remaining part if this range straddles
3045 * Here we should only zero the range inside the bvec,
3046 * not touch anything else.
3048 * NOTE: i_size is exclusive while end is inclusive.
3050 if (page->index == end_index && i_size <= end) {
3051 u32 zero_start = max(offset_in_page(i_size),
3052 offset_in_page(start));
3054 zero_user_segment(page, zero_start,
3055 offset_in_page(end) + 1);
3058 ASSERT(bio_offset + len > bio_offset);
3061 /* Update page status and unlock */
3062 end_page_read(page, uptodate, start, len);
3063 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3064 start, end, uptodate);
3066 /* Release the last extent */
3067 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3068 btrfs_io_bio_free_csum(io_bio);
3073 * Initialize the members up to but not including 'bio'. Use after allocating a
3074 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3075 * 'bio' because use of __GFP_ZERO is not supported.
3077 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3079 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3083 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3084 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3085 * for the appropriate container_of magic
3087 struct bio *btrfs_bio_alloc(u64 first_byte)
3091 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &btrfs_bioset);
3092 bio->bi_iter.bi_sector = first_byte >> 9;
3093 btrfs_io_bio_init(btrfs_io_bio(bio));
3097 struct bio *btrfs_bio_clone(struct bio *bio)
3099 struct btrfs_io_bio *btrfs_bio;
3102 /* Bio allocation backed by a bioset does not fail */
3103 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3104 btrfs_bio = btrfs_io_bio(new);
3105 btrfs_io_bio_init(btrfs_bio);
3106 btrfs_bio->iter = bio->bi_iter;
3110 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3114 /* Bio allocation backed by a bioset does not fail */
3115 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3116 btrfs_io_bio_init(btrfs_io_bio(bio));
3120 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
3123 struct btrfs_io_bio *btrfs_bio;
3125 /* this will never fail when it's backed by a bioset */
3126 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3129 btrfs_bio = btrfs_io_bio(bio);
3130 btrfs_io_bio_init(btrfs_bio);
3132 bio_trim(bio, offset >> 9, size >> 9);
3133 btrfs_bio->iter = bio->bi_iter;
3138 * Attempt to add a page to bio
3140 * @bio: destination bio
3141 * @page: page to add to the bio
3142 * @disk_bytenr: offset of the new bio or to check whether we are adding
3143 * a contiguous page to the previous one
3144 * @pg_offset: starting offset in the page
3145 * @size: portion of page that we want to write
3146 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3147 * @bio_flags: flags of the current bio to see if we can merge them
3148 * @return: true if page was added, false otherwise
3150 * Attempt to add a page to bio considering stripe alignment etc.
3152 * Return true if successfully page added. Otherwise, return false.
3154 static bool btrfs_bio_add_page(struct bio *bio, struct page *page,
3155 u64 disk_bytenr, unsigned int size,
3156 unsigned int pg_offset,
3157 unsigned long prev_bio_flags,
3158 unsigned long bio_flags)
3160 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3164 if (prev_bio_flags != bio_flags)
3167 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
3168 contig = bio->bi_iter.bi_sector == sector;
3170 contig = bio_end_sector(bio) == sector;
3174 if (btrfs_bio_fits_in_stripe(page, size, bio, bio_flags))
3177 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3178 struct page *first_page = bio_first_bvec_all(bio)->bv_page;
3180 if (!btrfs_bio_fits_in_ordered_extent(first_page, bio, size))
3182 ret = bio_add_zone_append_page(bio, page, size, pg_offset);
3184 ret = bio_add_page(bio, page, size, pg_offset);
3191 * @opf: bio REQ_OP_* and REQ_* flags as one value
3192 * @wbc: optional writeback control for io accounting
3193 * @page: page to add to the bio
3194 * @disk_bytenr: logical bytenr where the write will be
3195 * @size: portion of page that we want to write to
3196 * @pg_offset: offset of the new bio or to check whether we are adding
3197 * a contiguous page to the previous one
3198 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3199 * @end_io_func: end_io callback for new bio
3200 * @mirror_num: desired mirror to read/write
3201 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3202 * @bio_flags: flags of the current bio to see if we can merge them
3204 static int submit_extent_page(unsigned int opf,
3205 struct writeback_control *wbc,
3206 struct page *page, u64 disk_bytenr,
3207 size_t size, unsigned long pg_offset,
3208 struct bio **bio_ret,
3209 bio_end_io_t end_io_func,
3211 unsigned long prev_bio_flags,
3212 unsigned long bio_flags,
3213 bool force_bio_submit)
3217 size_t io_size = min_t(size_t, size, PAGE_SIZE);
3218 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3219 struct extent_io_tree *tree = &inode->io_tree;
3220 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3226 if (force_bio_submit ||
3227 !btrfs_bio_add_page(bio, page, disk_bytenr, io_size,
3228 pg_offset, prev_bio_flags, bio_flags)) {
3229 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
3237 wbc_account_cgroup_owner(wbc, page, io_size);
3242 bio = btrfs_bio_alloc(disk_bytenr);
3243 bio_add_page(bio, page, io_size, pg_offset);
3244 bio->bi_end_io = end_io_func;
3245 bio->bi_private = tree;
3246 bio->bi_write_hint = page->mapping->host->i_write_hint;
3249 struct block_device *bdev;
3251 bdev = fs_info->fs_devices->latest_bdev;
3252 bio_set_dev(bio, bdev);
3253 wbc_init_bio(wbc, bio);
3254 wbc_account_cgroup_owner(wbc, page, io_size);
3256 if (btrfs_is_zoned(fs_info) && bio_op(bio) == REQ_OP_ZONE_APPEND) {
3257 struct extent_map *em;
3258 struct map_lookup *map;
3260 em = btrfs_get_chunk_map(fs_info, disk_bytenr, io_size);
3264 map = em->map_lookup;
3265 /* We only support single profile for now */
3266 ASSERT(map->num_stripes == 1);
3267 btrfs_io_bio(bio)->device = map->stripes[0].dev;
3269 free_extent_map(em);
3277 static int attach_extent_buffer_page(struct extent_buffer *eb,
3279 struct btrfs_subpage *prealloc)
3281 struct btrfs_fs_info *fs_info = eb->fs_info;
3285 * If the page is mapped to btree inode, we should hold the private
3286 * lock to prevent race.
3287 * For cloned or dummy extent buffers, their pages are not mapped and
3288 * will not race with any other ebs.
3291 lockdep_assert_held(&page->mapping->private_lock);
3293 if (fs_info->sectorsize == PAGE_SIZE) {
3294 if (!PagePrivate(page))
3295 attach_page_private(page, eb);
3297 WARN_ON(page->private != (unsigned long)eb);
3301 /* Already mapped, just free prealloc */
3302 if (PagePrivate(page)) {
3303 btrfs_free_subpage(prealloc);
3308 /* Has preallocated memory for subpage */
3309 attach_page_private(page, prealloc);
3311 /* Do new allocation to attach subpage */
3312 ret = btrfs_attach_subpage(fs_info, page,
3313 BTRFS_SUBPAGE_METADATA);
3317 int set_page_extent_mapped(struct page *page)
3319 struct btrfs_fs_info *fs_info;
3321 ASSERT(page->mapping);
3323 if (PagePrivate(page))
3326 fs_info = btrfs_sb(page->mapping->host->i_sb);
3328 if (fs_info->sectorsize < PAGE_SIZE)
3329 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3331 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3335 void clear_page_extent_mapped(struct page *page)
3337 struct btrfs_fs_info *fs_info;
3339 ASSERT(page->mapping);
3341 if (!PagePrivate(page))
3344 fs_info = btrfs_sb(page->mapping->host->i_sb);
3345 if (fs_info->sectorsize < PAGE_SIZE)
3346 return btrfs_detach_subpage(fs_info, page);
3348 detach_page_private(page);
3351 static struct extent_map *
3352 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3353 u64 start, u64 len, struct extent_map **em_cached)
3355 struct extent_map *em;
3357 if (em_cached && *em_cached) {
3359 if (extent_map_in_tree(em) && start >= em->start &&
3360 start < extent_map_end(em)) {
3361 refcount_inc(&em->refs);
3365 free_extent_map(em);
3369 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3370 if (em_cached && !IS_ERR_OR_NULL(em)) {
3372 refcount_inc(&em->refs);
3378 * basic readpage implementation. Locked extent state structs are inserted
3379 * into the tree that are removed when the IO is done (by the end_io
3381 * XXX JDM: This needs looking at to ensure proper page locking
3382 * return 0 on success, otherwise return error
3384 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3385 struct bio **bio, unsigned long *bio_flags,
3386 unsigned int read_flags, u64 *prev_em_start)
3388 struct inode *inode = page->mapping->host;
3389 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3390 u64 start = page_offset(page);
3391 const u64 end = start + PAGE_SIZE - 1;
3394 u64 last_byte = i_size_read(inode);
3397 struct extent_map *em;
3400 size_t pg_offset = 0;
3402 size_t blocksize = inode->i_sb->s_blocksize;
3403 unsigned long this_bio_flag = 0;
3404 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3406 ret = set_page_extent_mapped(page);
3408 unlock_extent(tree, start, end);
3409 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3414 if (!PageUptodate(page)) {
3415 if (cleancache_get_page(page) == 0) {
3416 BUG_ON(blocksize != PAGE_SIZE);
3417 unlock_extent(tree, start, end);
3423 if (page->index == last_byte >> PAGE_SHIFT) {
3425 size_t zero_offset = offset_in_page(last_byte);
3428 iosize = PAGE_SIZE - zero_offset;
3429 userpage = kmap_atomic(page);
3430 memset(userpage + zero_offset, 0, iosize);
3431 flush_dcache_page(page);
3432 kunmap_atomic(userpage);
3435 begin_page_read(fs_info, page);
3436 while (cur <= end) {
3437 bool force_bio_submit = false;
3440 if (cur >= last_byte) {
3442 struct extent_state *cached = NULL;
3444 iosize = PAGE_SIZE - pg_offset;
3445 userpage = kmap_atomic(page);
3446 memset(userpage + pg_offset, 0, iosize);
3447 flush_dcache_page(page);
3448 kunmap_atomic(userpage);
3449 set_extent_uptodate(tree, cur, cur + iosize - 1,
3451 unlock_extent_cached(tree, cur,
3452 cur + iosize - 1, &cached);
3453 end_page_read(page, true, cur, iosize);
3456 em = __get_extent_map(inode, page, pg_offset, cur,
3457 end - cur + 1, em_cached);
3458 if (IS_ERR_OR_NULL(em)) {
3459 unlock_extent(tree, cur, end);
3460 end_page_read(page, false, cur, end + 1 - cur);
3463 extent_offset = cur - em->start;
3464 BUG_ON(extent_map_end(em) <= cur);
3467 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3468 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3469 extent_set_compress_type(&this_bio_flag,
3473 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3474 cur_end = min(extent_map_end(em) - 1, end);
3475 iosize = ALIGN(iosize, blocksize);
3476 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3477 disk_bytenr = em->block_start;
3479 disk_bytenr = em->block_start + extent_offset;
3480 block_start = em->block_start;
3481 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3482 block_start = EXTENT_MAP_HOLE;
3485 * If we have a file range that points to a compressed extent
3486 * and it's followed by a consecutive file range that points
3487 * to the same compressed extent (possibly with a different
3488 * offset and/or length, so it either points to the whole extent
3489 * or only part of it), we must make sure we do not submit a
3490 * single bio to populate the pages for the 2 ranges because
3491 * this makes the compressed extent read zero out the pages
3492 * belonging to the 2nd range. Imagine the following scenario:
3495 * [0 - 8K] [8K - 24K]
3498 * points to extent X, points to extent X,
3499 * offset 4K, length of 8K offset 0, length 16K
3501 * [extent X, compressed length = 4K uncompressed length = 16K]
3503 * If the bio to read the compressed extent covers both ranges,
3504 * it will decompress extent X into the pages belonging to the
3505 * first range and then it will stop, zeroing out the remaining
3506 * pages that belong to the other range that points to extent X.
3507 * So here we make sure we submit 2 bios, one for the first
3508 * range and another one for the third range. Both will target
3509 * the same physical extent from disk, but we can't currently
3510 * make the compressed bio endio callback populate the pages
3511 * for both ranges because each compressed bio is tightly
3512 * coupled with a single extent map, and each range can have
3513 * an extent map with a different offset value relative to the
3514 * uncompressed data of our extent and different lengths. This
3515 * is a corner case so we prioritize correctness over
3516 * non-optimal behavior (submitting 2 bios for the same extent).
3518 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3519 prev_em_start && *prev_em_start != (u64)-1 &&
3520 *prev_em_start != em->start)
3521 force_bio_submit = true;
3524 *prev_em_start = em->start;
3526 free_extent_map(em);
3529 /* we've found a hole, just zero and go on */
3530 if (block_start == EXTENT_MAP_HOLE) {
3532 struct extent_state *cached = NULL;
3534 userpage = kmap_atomic(page);
3535 memset(userpage + pg_offset, 0, iosize);
3536 flush_dcache_page(page);
3537 kunmap_atomic(userpage);
3539 set_extent_uptodate(tree, cur, cur + iosize - 1,
3541 unlock_extent_cached(tree, cur,
3542 cur + iosize - 1, &cached);
3543 end_page_read(page, true, cur, iosize);
3545 pg_offset += iosize;
3548 /* the get_extent function already copied into the page */
3549 if (test_range_bit(tree, cur, cur_end,
3550 EXTENT_UPTODATE, 1, NULL)) {
3551 check_page_uptodate(tree, page);
3552 unlock_extent(tree, cur, cur + iosize - 1);
3553 end_page_read(page, true, cur, iosize);
3555 pg_offset += iosize;
3558 /* we have an inline extent but it didn't get marked up
3559 * to date. Error out
3561 if (block_start == EXTENT_MAP_INLINE) {
3562 unlock_extent(tree, cur, cur + iosize - 1);
3563 end_page_read(page, false, cur, iosize);
3565 pg_offset += iosize;
3569 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3570 page, disk_bytenr, iosize,
3572 end_bio_extent_readpage, 0,
3578 *bio_flags = this_bio_flag;
3580 unlock_extent(tree, cur, cur + iosize - 1);
3581 end_page_read(page, false, cur, iosize);
3585 pg_offset += iosize;
3591 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3593 struct extent_map **em_cached,
3595 unsigned long *bio_flags,
3598 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3601 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3603 for (index = 0; index < nr_pages; index++) {
3604 btrfs_do_readpage(pages[index], em_cached, bio, bio_flags,
3605 REQ_RAHEAD, prev_em_start);
3606 put_page(pages[index]);
3610 static void update_nr_written(struct writeback_control *wbc,
3611 unsigned long nr_written)
3613 wbc->nr_to_write -= nr_written;
3617 * helper for __extent_writepage, doing all of the delayed allocation setup.
3619 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3620 * to write the page (copy into inline extent). In this case the IO has
3621 * been started and the page is already unlocked.
3623 * This returns 0 if all went well (page still locked)
3624 * This returns < 0 if there were errors (page still locked)
3626 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3627 struct page *page, struct writeback_control *wbc,
3628 u64 delalloc_start, unsigned long *nr_written)
3630 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3632 u64 delalloc_to_write = 0;
3633 u64 delalloc_end = 0;
3635 int page_started = 0;
3638 while (delalloc_end < page_end) {
3639 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3643 delalloc_start = delalloc_end + 1;
3646 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3647 delalloc_end, &page_started, nr_written, wbc);
3651 * btrfs_run_delalloc_range should return < 0 for error
3652 * but just in case, we use > 0 here meaning the IO is
3653 * started, so we don't want to return > 0 unless
3654 * things are going well.
3656 return ret < 0 ? ret : -EIO;
3659 * delalloc_end is already one less than the total length, so
3660 * we don't subtract one from PAGE_SIZE
3662 delalloc_to_write += (delalloc_end - delalloc_start +
3663 PAGE_SIZE) >> PAGE_SHIFT;
3664 delalloc_start = delalloc_end + 1;
3666 if (wbc->nr_to_write < delalloc_to_write) {
3669 if (delalloc_to_write < thresh * 2)
3670 thresh = delalloc_to_write;
3671 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3675 /* did the fill delalloc function already unlock and start
3680 * we've unlocked the page, so we can't update
3681 * the mapping's writeback index, just update
3684 wbc->nr_to_write -= *nr_written;
3692 * helper for __extent_writepage. This calls the writepage start hooks,
3693 * and does the loop to map the page into extents and bios.
3695 * We return 1 if the IO is started and the page is unlocked,
3696 * 0 if all went well (page still locked)
3697 * < 0 if there were errors (page still locked)
3699 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3701 struct writeback_control *wbc,
3702 struct extent_page_data *epd,
3704 unsigned long nr_written,
3707 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3708 struct extent_io_tree *tree = &inode->io_tree;
3709 u64 start = page_offset(page);
3710 u64 end = start + PAGE_SIZE - 1;
3714 struct extent_map *em;
3717 u32 opf = REQ_OP_WRITE;
3718 const unsigned int write_flags = wbc_to_write_flags(wbc);
3721 ret = btrfs_writepage_cow_fixup(page, start, end);
3723 /* Fixup worker will requeue */
3724 redirty_page_for_writepage(wbc, page);
3725 update_nr_written(wbc, nr_written);
3731 * we don't want to touch the inode after unlocking the page,
3732 * so we update the mapping writeback index now
3734 update_nr_written(wbc, nr_written + 1);
3736 while (cur <= end) {
3741 if (cur >= i_size) {
3742 btrfs_writepage_endio_finish_ordered(page, cur, end, 1);
3745 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3746 if (IS_ERR_OR_NULL(em)) {
3748 ret = PTR_ERR_OR_ZERO(em);
3752 extent_offset = cur - em->start;
3753 em_end = extent_map_end(em);
3754 ASSERT(cur <= em_end);
3756 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3757 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3758 block_start = em->block_start;
3759 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3760 disk_bytenr = em->block_start + extent_offset;
3762 /* Note that em_end from extent_map_end() is exclusive */
3763 iosize = min(em_end, end + 1) - cur;
3765 if (btrfs_use_zone_append(inode, em))
3766 opf = REQ_OP_ZONE_APPEND;
3768 free_extent_map(em);
3772 * compressed and inline extents are written through other
3775 if (compressed || block_start == EXTENT_MAP_HOLE ||
3776 block_start == EXTENT_MAP_INLINE) {
3780 btrfs_writepage_endio_finish_ordered(page, cur,
3781 cur + iosize - 1, 1);
3786 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3787 if (!PageWriteback(page)) {
3788 btrfs_err(inode->root->fs_info,
3789 "page %lu not writeback, cur %llu end %llu",
3790 page->index, cur, end);
3793 ret = submit_extent_page(opf | write_flags, wbc, page,
3794 disk_bytenr, iosize,
3795 cur - page_offset(page), &epd->bio,
3796 end_bio_extent_writepage,
3800 if (PageWriteback(page))
3801 end_page_writeback(page);
3812 * the writepage semantics are similar to regular writepage. extent
3813 * records are inserted to lock ranges in the tree, and as dirty areas
3814 * are found, they are marked writeback. Then the lock bits are removed
3815 * and the end_io handler clears the writeback ranges
3817 * Return 0 if everything goes well.
3818 * Return <0 for error.
3820 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3821 struct extent_page_data *epd)
3823 struct inode *inode = page->mapping->host;
3824 u64 start = page_offset(page);
3825 u64 page_end = start + PAGE_SIZE - 1;
3829 loff_t i_size = i_size_read(inode);
3830 unsigned long end_index = i_size >> PAGE_SHIFT;
3831 unsigned long nr_written = 0;
3833 trace___extent_writepage(page, inode, wbc);
3835 WARN_ON(!PageLocked(page));
3837 ClearPageError(page);
3839 pg_offset = offset_in_page(i_size);
3840 if (page->index > end_index ||
3841 (page->index == end_index && !pg_offset)) {
3842 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3847 if (page->index == end_index) {
3850 userpage = kmap_atomic(page);
3851 memset(userpage + pg_offset, 0,
3852 PAGE_SIZE - pg_offset);
3853 kunmap_atomic(userpage);
3854 flush_dcache_page(page);
3857 ret = set_page_extent_mapped(page);
3863 if (!epd->extent_locked) {
3864 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3872 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3879 /* make sure the mapping tag for page dirty gets cleared */
3880 set_page_writeback(page);
3881 end_page_writeback(page);
3883 if (PageError(page)) {
3884 ret = ret < 0 ? ret : -EIO;
3885 end_extent_writepage(page, ret, start, page_end);
3892 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3894 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3895 TASK_UNINTERRUPTIBLE);
3898 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3900 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3901 smp_mb__after_atomic();
3902 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3906 * Lock extent buffer status and pages for writeback.
3908 * May try to flush write bio if we can't get the lock.
3910 * Return 0 if the extent buffer doesn't need to be submitted.
3911 * (E.g. the extent buffer is not dirty)
3912 * Return >0 is the extent buffer is submitted to bio.
3913 * Return <0 if something went wrong, no page is locked.
3915 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3916 struct extent_page_data *epd)
3918 struct btrfs_fs_info *fs_info = eb->fs_info;
3919 int i, num_pages, failed_page_nr;
3923 if (!btrfs_try_tree_write_lock(eb)) {
3924 ret = flush_write_bio(epd);
3928 btrfs_tree_lock(eb);
3931 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3932 btrfs_tree_unlock(eb);
3936 ret = flush_write_bio(epd);
3942 wait_on_extent_buffer_writeback(eb);
3943 btrfs_tree_lock(eb);
3944 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3946 btrfs_tree_unlock(eb);
3951 * We need to do this to prevent races in people who check if the eb is
3952 * under IO since we can end up having no IO bits set for a short period
3955 spin_lock(&eb->refs_lock);
3956 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3957 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3958 spin_unlock(&eb->refs_lock);
3959 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3960 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3962 fs_info->dirty_metadata_batch);
3965 spin_unlock(&eb->refs_lock);
3968 btrfs_tree_unlock(eb);
3973 num_pages = num_extent_pages(eb);
3974 for (i = 0; i < num_pages; i++) {
3975 struct page *p = eb->pages[i];
3977 if (!trylock_page(p)) {
3981 err = flush_write_bio(epd);
3995 /* Unlock already locked pages */
3996 for (i = 0; i < failed_page_nr; i++)
3997 unlock_page(eb->pages[i]);
3999 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
4000 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
4001 * be made and undo everything done before.
4003 btrfs_tree_lock(eb);
4004 spin_lock(&eb->refs_lock);
4005 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4006 end_extent_buffer_writeback(eb);
4007 spin_unlock(&eb->refs_lock);
4008 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4009 fs_info->dirty_metadata_batch);
4010 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4011 btrfs_tree_unlock(eb);
4015 static void set_btree_ioerr(struct page *page)
4017 struct extent_buffer *eb = (struct extent_buffer *)page->private;
4018 struct btrfs_fs_info *fs_info;
4021 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4025 * If we error out, we should add back the dirty_metadata_bytes
4026 * to make it consistent.
4028 fs_info = eb->fs_info;
4029 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4030 eb->len, fs_info->dirty_metadata_batch);
4033 * If writeback for a btree extent that doesn't belong to a log tree
4034 * failed, increment the counter transaction->eb_write_errors.
4035 * We do this because while the transaction is running and before it's
4036 * committing (when we call filemap_fdata[write|wait]_range against
4037 * the btree inode), we might have
4038 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4039 * returns an error or an error happens during writeback, when we're
4040 * committing the transaction we wouldn't know about it, since the pages
4041 * can be no longer dirty nor marked anymore for writeback (if a
4042 * subsequent modification to the extent buffer didn't happen before the
4043 * transaction commit), which makes filemap_fdata[write|wait]_range not
4044 * able to find the pages tagged with SetPageError at transaction
4045 * commit time. So if this happens we must abort the transaction,
4046 * otherwise we commit a super block with btree roots that point to
4047 * btree nodes/leafs whose content on disk is invalid - either garbage
4048 * or the content of some node/leaf from a past generation that got
4049 * cowed or deleted and is no longer valid.
4051 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4052 * not be enough - we need to distinguish between log tree extents vs
4053 * non-log tree extents, and the next filemap_fdatawait_range() call
4054 * will catch and clear such errors in the mapping - and that call might
4055 * be from a log sync and not from a transaction commit. Also, checking
4056 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4057 * not done and would not be reliable - the eb might have been released
4058 * from memory and reading it back again means that flag would not be
4059 * set (since it's a runtime flag, not persisted on disk).
4061 * Using the flags below in the btree inode also makes us achieve the
4062 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4063 * writeback for all dirty pages and before filemap_fdatawait_range()
4064 * is called, the writeback for all dirty pages had already finished
4065 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4066 * filemap_fdatawait_range() would return success, as it could not know
4067 * that writeback errors happened (the pages were no longer tagged for
4070 switch (eb->log_index) {
4072 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
4075 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
4078 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
4081 BUG(); /* unexpected, logic error */
4085 static void end_bio_extent_buffer_writepage(struct bio *bio)
4087 struct bio_vec *bvec;
4088 struct extent_buffer *eb;
4090 struct bvec_iter_all iter_all;
4092 ASSERT(!bio_flagged(bio, BIO_CLONED));
4093 bio_for_each_segment_all(bvec, bio, iter_all) {
4094 struct page *page = bvec->bv_page;
4096 eb = (struct extent_buffer *)page->private;
4098 done = atomic_dec_and_test(&eb->io_pages);
4100 if (bio->bi_status ||
4101 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4102 ClearPageUptodate(page);
4103 set_btree_ioerr(page);
4106 end_page_writeback(page);
4111 end_extent_buffer_writeback(eb);
4117 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4118 struct writeback_control *wbc,
4119 struct extent_page_data *epd)
4121 u64 disk_bytenr = eb->start;
4124 unsigned long start, end;
4125 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4128 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4129 num_pages = num_extent_pages(eb);
4130 atomic_set(&eb->io_pages, num_pages);
4132 /* set btree blocks beyond nritems with 0 to avoid stale content. */
4133 nritems = btrfs_header_nritems(eb);
4134 if (btrfs_header_level(eb) > 0) {
4135 end = btrfs_node_key_ptr_offset(nritems);
4137 memzero_extent_buffer(eb, end, eb->len - end);
4141 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4143 start = btrfs_item_nr_offset(nritems);
4144 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4145 memzero_extent_buffer(eb, start, end - start);
4148 for (i = 0; i < num_pages; i++) {
4149 struct page *p = eb->pages[i];
4151 clear_page_dirty_for_io(p);
4152 set_page_writeback(p);
4153 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4154 p, disk_bytenr, PAGE_SIZE, 0,
4156 end_bio_extent_buffer_writepage,
4160 if (PageWriteback(p))
4161 end_page_writeback(p);
4162 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4163 end_extent_buffer_writeback(eb);
4167 disk_bytenr += PAGE_SIZE;
4168 update_nr_written(wbc, 1);
4172 if (unlikely(ret)) {
4173 for (; i < num_pages; i++) {
4174 struct page *p = eb->pages[i];
4175 clear_page_dirty_for_io(p);
4184 * Submit all page(s) of one extent buffer.
4186 * @page: the page of one extent buffer
4187 * @eb_context: to determine if we need to submit this page, if current page
4188 * belongs to this eb, we don't need to submit
4190 * The caller should pass each page in their bytenr order, and here we use
4191 * @eb_context to determine if we have submitted pages of one extent buffer.
4193 * If we have, we just skip until we hit a new page that doesn't belong to
4194 * current @eb_context.
4196 * If not, we submit all the page(s) of the extent buffer.
4198 * Return >0 if we have submitted the extent buffer successfully.
4199 * Return 0 if we don't need to submit the page, as it's already submitted by
4201 * Return <0 for fatal error.
4203 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4204 struct extent_page_data *epd,
4205 struct extent_buffer **eb_context)
4207 struct address_space *mapping = page->mapping;
4208 struct btrfs_block_group *cache = NULL;
4209 struct extent_buffer *eb;
4212 if (!PagePrivate(page))
4215 spin_lock(&mapping->private_lock);
4216 if (!PagePrivate(page)) {
4217 spin_unlock(&mapping->private_lock);
4221 eb = (struct extent_buffer *)page->private;
4224 * Shouldn't happen and normally this would be a BUG_ON but no point
4225 * crashing the machine for something we can survive anyway.
4228 spin_unlock(&mapping->private_lock);
4232 if (eb == *eb_context) {
4233 spin_unlock(&mapping->private_lock);
4236 ret = atomic_inc_not_zero(&eb->refs);
4237 spin_unlock(&mapping->private_lock);
4241 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4243 * If for_sync, this hole will be filled with
4244 * trasnsaction commit.
4246 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4250 free_extent_buffer(eb);
4256 ret = lock_extent_buffer_for_io(eb, epd);
4258 btrfs_revert_meta_write_pointer(cache, eb);
4260 btrfs_put_block_group(cache);
4261 free_extent_buffer(eb);
4265 btrfs_put_block_group(cache);
4266 ret = write_one_eb(eb, wbc, epd);
4267 free_extent_buffer(eb);
4273 int btree_write_cache_pages(struct address_space *mapping,
4274 struct writeback_control *wbc)
4276 struct extent_buffer *eb_context = NULL;
4277 struct extent_page_data epd = {
4280 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4282 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4285 int nr_to_write_done = 0;
4286 struct pagevec pvec;
4289 pgoff_t end; /* Inclusive */
4293 pagevec_init(&pvec);
4294 if (wbc->range_cyclic) {
4295 index = mapping->writeback_index; /* Start from prev offset */
4298 * Start from the beginning does not need to cycle over the
4299 * range, mark it as scanned.
4301 scanned = (index == 0);
4303 index = wbc->range_start >> PAGE_SHIFT;
4304 end = wbc->range_end >> PAGE_SHIFT;
4307 if (wbc->sync_mode == WB_SYNC_ALL)
4308 tag = PAGECACHE_TAG_TOWRITE;
4310 tag = PAGECACHE_TAG_DIRTY;
4311 btrfs_zoned_meta_io_lock(fs_info);
4313 if (wbc->sync_mode == WB_SYNC_ALL)
4314 tag_pages_for_writeback(mapping, index, end);
4315 while (!done && !nr_to_write_done && (index <= end) &&
4316 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4320 for (i = 0; i < nr_pages; i++) {
4321 struct page *page = pvec.pages[i];
4323 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4332 * the filesystem may choose to bump up nr_to_write.
4333 * We have to make sure to honor the new nr_to_write
4336 nr_to_write_done = wbc->nr_to_write <= 0;
4338 pagevec_release(&pvec);
4341 if (!scanned && !done) {
4343 * We hit the last page and there is more work to be done: wrap
4344 * back to the start of the file
4351 end_write_bio(&epd, ret);
4355 * If something went wrong, don't allow any metadata write bio to be
4358 * This would prevent use-after-free if we had dirty pages not
4359 * cleaned up, which can still happen by fuzzed images.
4362 * Allowing existing tree block to be allocated for other trees.
4364 * - Log tree operations
4365 * Exiting tree blocks get allocated to log tree, bumps its
4366 * generation, then get cleaned in tree re-balance.
4367 * Such tree block will not be written back, since it's clean,
4368 * thus no WRITTEN flag set.
4369 * And after log writes back, this tree block is not traced by
4370 * any dirty extent_io_tree.
4372 * - Offending tree block gets re-dirtied from its original owner
4373 * Since it has bumped generation, no WRITTEN flag, it can be
4374 * reused without COWing. This tree block will not be traced
4375 * by btrfs_transaction::dirty_pages.
4377 * Now such dirty tree block will not be cleaned by any dirty
4378 * extent io tree. Thus we don't want to submit such wild eb
4379 * if the fs already has error.
4381 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4382 ret = flush_write_bio(&epd);
4385 end_write_bio(&epd, ret);
4388 btrfs_zoned_meta_io_unlock(fs_info);
4393 * Walk the list of dirty pages of the given address space and write all of them.
4395 * @mapping: address space structure to write
4396 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4397 * @epd: holds context for the write, namely the bio
4399 * If a page is already under I/O, write_cache_pages() skips it, even
4400 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4401 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4402 * and msync() need to guarantee that all the data which was dirty at the time
4403 * the call was made get new I/O started against them. If wbc->sync_mode is
4404 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4405 * existing IO to complete.
4407 static int extent_write_cache_pages(struct address_space *mapping,
4408 struct writeback_control *wbc,
4409 struct extent_page_data *epd)
4411 struct inode *inode = mapping->host;
4414 int nr_to_write_done = 0;
4415 struct pagevec pvec;
4418 pgoff_t end; /* Inclusive */
4420 int range_whole = 0;
4425 * We have to hold onto the inode so that ordered extents can do their
4426 * work when the IO finishes. The alternative to this is failing to add
4427 * an ordered extent if the igrab() fails there and that is a huge pain
4428 * to deal with, so instead just hold onto the inode throughout the
4429 * writepages operation. If it fails here we are freeing up the inode
4430 * anyway and we'd rather not waste our time writing out stuff that is
4431 * going to be truncated anyway.
4436 pagevec_init(&pvec);
4437 if (wbc->range_cyclic) {
4438 index = mapping->writeback_index; /* Start from prev offset */
4441 * Start from the beginning does not need to cycle over the
4442 * range, mark it as scanned.
4444 scanned = (index == 0);
4446 index = wbc->range_start >> PAGE_SHIFT;
4447 end = wbc->range_end >> PAGE_SHIFT;
4448 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4454 * We do the tagged writepage as long as the snapshot flush bit is set
4455 * and we are the first one who do the filemap_flush() on this inode.
4457 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4458 * not race in and drop the bit.
4460 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4461 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4462 &BTRFS_I(inode)->runtime_flags))
4463 wbc->tagged_writepages = 1;
4465 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4466 tag = PAGECACHE_TAG_TOWRITE;
4468 tag = PAGECACHE_TAG_DIRTY;
4470 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4471 tag_pages_for_writeback(mapping, index, end);
4473 while (!done && !nr_to_write_done && (index <= end) &&
4474 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4475 &index, end, tag))) {
4478 for (i = 0; i < nr_pages; i++) {
4479 struct page *page = pvec.pages[i];
4481 done_index = page->index + 1;
4483 * At this point we hold neither the i_pages lock nor
4484 * the page lock: the page may be truncated or
4485 * invalidated (changing page->mapping to NULL),
4486 * or even swizzled back from swapper_space to
4487 * tmpfs file mapping
4489 if (!trylock_page(page)) {
4490 ret = flush_write_bio(epd);
4495 if (unlikely(page->mapping != mapping)) {
4500 if (wbc->sync_mode != WB_SYNC_NONE) {
4501 if (PageWriteback(page)) {
4502 ret = flush_write_bio(epd);
4505 wait_on_page_writeback(page);
4508 if (PageWriteback(page) ||
4509 !clear_page_dirty_for_io(page)) {
4514 ret = __extent_writepage(page, wbc, epd);
4521 * the filesystem may choose to bump up nr_to_write.
4522 * We have to make sure to honor the new nr_to_write
4525 nr_to_write_done = wbc->nr_to_write <= 0;
4527 pagevec_release(&pvec);
4530 if (!scanned && !done) {
4532 * We hit the last page and there is more work to be done: wrap
4533 * back to the start of the file
4539 * If we're looping we could run into a page that is locked by a
4540 * writer and that writer could be waiting on writeback for a
4541 * page in our current bio, and thus deadlock, so flush the
4544 ret = flush_write_bio(epd);
4549 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4550 mapping->writeback_index = done_index;
4552 btrfs_add_delayed_iput(inode);
4556 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4559 struct extent_page_data epd = {
4562 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4565 ret = __extent_writepage(page, wbc, &epd);
4568 end_write_bio(&epd, ret);
4572 ret = flush_write_bio(&epd);
4577 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4581 struct address_space *mapping = inode->i_mapping;
4583 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4586 struct extent_page_data epd = {
4589 .sync_io = mode == WB_SYNC_ALL,
4591 struct writeback_control wbc_writepages = {
4593 .nr_to_write = nr_pages * 2,
4594 .range_start = start,
4595 .range_end = end + 1,
4596 /* We're called from an async helper function */
4597 .punt_to_cgroup = 1,
4598 .no_cgroup_owner = 1,
4601 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
4602 while (start <= end) {
4603 page = find_get_page(mapping, start >> PAGE_SHIFT);
4604 if (clear_page_dirty_for_io(page))
4605 ret = __extent_writepage(page, &wbc_writepages, &epd);
4607 btrfs_writepage_endio_finish_ordered(page, start,
4608 start + PAGE_SIZE - 1, 1);
4617 ret = flush_write_bio(&epd);
4619 end_write_bio(&epd, ret);
4621 wbc_detach_inode(&wbc_writepages);
4625 int extent_writepages(struct address_space *mapping,
4626 struct writeback_control *wbc)
4629 struct extent_page_data epd = {
4632 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4635 ret = extent_write_cache_pages(mapping, wbc, &epd);
4638 end_write_bio(&epd, ret);
4641 ret = flush_write_bio(&epd);
4645 void extent_readahead(struct readahead_control *rac)
4647 struct bio *bio = NULL;
4648 unsigned long bio_flags = 0;
4649 struct page *pagepool[16];
4650 struct extent_map *em_cached = NULL;
4651 u64 prev_em_start = (u64)-1;
4654 while ((nr = readahead_page_batch(rac, pagepool))) {
4655 u64 contig_start = page_offset(pagepool[0]);
4656 u64 contig_end = page_offset(pagepool[nr - 1]) + PAGE_SIZE - 1;
4658 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4660 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4661 &em_cached, &bio, &bio_flags, &prev_em_start);
4665 free_extent_map(em_cached);
4668 if (submit_one_bio(bio, 0, bio_flags))
4674 * basic invalidatepage code, this waits on any locked or writeback
4675 * ranges corresponding to the page, and then deletes any extent state
4676 * records from the tree
4678 int extent_invalidatepage(struct extent_io_tree *tree,
4679 struct page *page, unsigned long offset)
4681 struct extent_state *cached_state = NULL;
4682 u64 start = page_offset(page);
4683 u64 end = start + PAGE_SIZE - 1;
4684 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4686 /* This function is only called for the btree inode */
4687 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
4689 start += ALIGN(offset, blocksize);
4693 lock_extent_bits(tree, start, end, &cached_state);
4694 wait_on_page_writeback(page);
4697 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
4698 * so here we only need to unlock the extent range to free any
4699 * existing extent state.
4701 unlock_extent_cached(tree, start, end, &cached_state);
4706 * a helper for releasepage, this tests for areas of the page that
4707 * are locked or under IO and drops the related state bits if it is safe
4710 static int try_release_extent_state(struct extent_io_tree *tree,
4711 struct page *page, gfp_t mask)
4713 u64 start = page_offset(page);
4714 u64 end = start + PAGE_SIZE - 1;
4717 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4721 * At this point we can safely clear everything except the
4722 * locked bit, the nodatasum bit and the delalloc new bit.
4723 * The delalloc new bit will be cleared by ordered extent
4726 ret = __clear_extent_bit(tree, start, end,
4727 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
4728 0, 0, NULL, mask, NULL);
4730 /* if clear_extent_bit failed for enomem reasons,
4731 * we can't allow the release to continue.
4742 * a helper for releasepage. As long as there are no locked extents
4743 * in the range corresponding to the page, both state records and extent
4744 * map records are removed
4746 int try_release_extent_mapping(struct page *page, gfp_t mask)
4748 struct extent_map *em;
4749 u64 start = page_offset(page);
4750 u64 end = start + PAGE_SIZE - 1;
4751 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4752 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4753 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4755 if (gfpflags_allow_blocking(mask) &&
4756 page->mapping->host->i_size > SZ_16M) {
4758 while (start <= end) {
4759 struct btrfs_fs_info *fs_info;
4762 len = end - start + 1;
4763 write_lock(&map->lock);
4764 em = lookup_extent_mapping(map, start, len);
4766 write_unlock(&map->lock);
4769 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4770 em->start != start) {
4771 write_unlock(&map->lock);
4772 free_extent_map(em);
4775 if (test_range_bit(tree, em->start,
4776 extent_map_end(em) - 1,
4777 EXTENT_LOCKED, 0, NULL))
4780 * If it's not in the list of modified extents, used
4781 * by a fast fsync, we can remove it. If it's being
4782 * logged we can safely remove it since fsync took an
4783 * extra reference on the em.
4785 if (list_empty(&em->list) ||
4786 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
4789 * If it's in the list of modified extents, remove it
4790 * only if its generation is older then the current one,
4791 * in which case we don't need it for a fast fsync.
4792 * Otherwise don't remove it, we could be racing with an
4793 * ongoing fast fsync that could miss the new extent.
4795 fs_info = btrfs_inode->root->fs_info;
4796 spin_lock(&fs_info->trans_lock);
4797 cur_gen = fs_info->generation;
4798 spin_unlock(&fs_info->trans_lock);
4799 if (em->generation >= cur_gen)
4803 * We only remove extent maps that are not in the list of
4804 * modified extents or that are in the list but with a
4805 * generation lower then the current generation, so there
4806 * is no need to set the full fsync flag on the inode (it
4807 * hurts the fsync performance for workloads with a data
4808 * size that exceeds or is close to the system's memory).
4810 remove_extent_mapping(map, em);
4811 /* once for the rb tree */
4812 free_extent_map(em);
4814 start = extent_map_end(em);
4815 write_unlock(&map->lock);
4818 free_extent_map(em);
4820 cond_resched(); /* Allow large-extent preemption. */
4823 return try_release_extent_state(tree, page, mask);
4827 * helper function for fiemap, which doesn't want to see any holes.
4828 * This maps until we find something past 'last'
4830 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
4831 u64 offset, u64 last)
4833 u64 sectorsize = btrfs_inode_sectorsize(inode);
4834 struct extent_map *em;
4841 len = last - offset;
4844 len = ALIGN(len, sectorsize);
4845 em = btrfs_get_extent_fiemap(inode, offset, len);
4846 if (IS_ERR_OR_NULL(em))
4849 /* if this isn't a hole return it */
4850 if (em->block_start != EXTENT_MAP_HOLE)
4853 /* this is a hole, advance to the next extent */
4854 offset = extent_map_end(em);
4855 free_extent_map(em);
4863 * To cache previous fiemap extent
4865 * Will be used for merging fiemap extent
4867 struct fiemap_cache {
4876 * Helper to submit fiemap extent.
4878 * Will try to merge current fiemap extent specified by @offset, @phys,
4879 * @len and @flags with cached one.
4880 * And only when we fails to merge, cached one will be submitted as
4883 * Return value is the same as fiemap_fill_next_extent().
4885 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4886 struct fiemap_cache *cache,
4887 u64 offset, u64 phys, u64 len, u32 flags)
4895 * Sanity check, extent_fiemap() should have ensured that new
4896 * fiemap extent won't overlap with cached one.
4899 * NOTE: Physical address can overlap, due to compression
4901 if (cache->offset + cache->len > offset) {
4907 * Only merges fiemap extents if
4908 * 1) Their logical addresses are continuous
4910 * 2) Their physical addresses are continuous
4911 * So truly compressed (physical size smaller than logical size)
4912 * extents won't get merged with each other
4914 * 3) Share same flags except FIEMAP_EXTENT_LAST
4915 * So regular extent won't get merged with prealloc extent
4917 if (cache->offset + cache->len == offset &&
4918 cache->phys + cache->len == phys &&
4919 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4920 (flags & ~FIEMAP_EXTENT_LAST)) {
4922 cache->flags |= flags;
4923 goto try_submit_last;
4926 /* Not mergeable, need to submit cached one */
4927 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4928 cache->len, cache->flags);
4929 cache->cached = false;
4933 cache->cached = true;
4934 cache->offset = offset;
4937 cache->flags = flags;
4939 if (cache->flags & FIEMAP_EXTENT_LAST) {
4940 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4941 cache->phys, cache->len, cache->flags);
4942 cache->cached = false;
4948 * Emit last fiemap cache
4950 * The last fiemap cache may still be cached in the following case:
4952 * |<- Fiemap range ->|
4953 * |<------------ First extent ----------->|
4955 * In this case, the first extent range will be cached but not emitted.
4956 * So we must emit it before ending extent_fiemap().
4958 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4959 struct fiemap_cache *cache)
4966 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4967 cache->len, cache->flags);
4968 cache->cached = false;
4974 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
4979 u64 max = start + len;
4983 u64 last_for_get_extent = 0;
4985 u64 isize = i_size_read(&inode->vfs_inode);
4986 struct btrfs_key found_key;
4987 struct extent_map *em = NULL;
4988 struct extent_state *cached_state = NULL;
4989 struct btrfs_path *path;
4990 struct btrfs_root *root = inode->root;
4991 struct fiemap_cache cache = { 0 };
4992 struct ulist *roots;
4993 struct ulist *tmp_ulist;
5002 path = btrfs_alloc_path();
5006 roots = ulist_alloc(GFP_KERNEL);
5007 tmp_ulist = ulist_alloc(GFP_KERNEL);
5008 if (!roots || !tmp_ulist) {
5010 goto out_free_ulist;
5013 start = round_down(start, btrfs_inode_sectorsize(inode));
5014 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5017 * lookup the last file extent. We're not using i_size here
5018 * because there might be preallocation past i_size
5020 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5023 goto out_free_ulist;
5031 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5032 found_type = found_key.type;
5034 /* No extents, but there might be delalloc bits */
5035 if (found_key.objectid != btrfs_ino(inode) ||
5036 found_type != BTRFS_EXTENT_DATA_KEY) {
5037 /* have to trust i_size as the end */
5039 last_for_get_extent = isize;
5042 * remember the start of the last extent. There are a
5043 * bunch of different factors that go into the length of the
5044 * extent, so its much less complex to remember where it started
5046 last = found_key.offset;
5047 last_for_get_extent = last + 1;
5049 btrfs_release_path(path);
5052 * we might have some extents allocated but more delalloc past those
5053 * extents. so, we trust isize unless the start of the last extent is
5058 last_for_get_extent = isize;
5061 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5064 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5073 u64 offset_in_extent = 0;
5075 /* break if the extent we found is outside the range */
5076 if (em->start >= max || extent_map_end(em) < off)
5080 * get_extent may return an extent that starts before our
5081 * requested range. We have to make sure the ranges
5082 * we return to fiemap always move forward and don't
5083 * overlap, so adjust the offsets here
5085 em_start = max(em->start, off);
5088 * record the offset from the start of the extent
5089 * for adjusting the disk offset below. Only do this if the
5090 * extent isn't compressed since our in ram offset may be past
5091 * what we have actually allocated on disk.
5093 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5094 offset_in_extent = em_start - em->start;
5095 em_end = extent_map_end(em);
5096 em_len = em_end - em_start;
5098 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5099 disko = em->block_start + offset_in_extent;
5104 * bump off for our next call to get_extent
5106 off = extent_map_end(em);
5110 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5112 flags |= FIEMAP_EXTENT_LAST;
5113 } else if (em->block_start == EXTENT_MAP_INLINE) {
5114 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5115 FIEMAP_EXTENT_NOT_ALIGNED);
5116 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5117 flags |= (FIEMAP_EXTENT_DELALLOC |
5118 FIEMAP_EXTENT_UNKNOWN);
5119 } else if (fieinfo->fi_extents_max) {
5120 u64 bytenr = em->block_start -
5121 (em->start - em->orig_start);
5124 * As btrfs supports shared space, this information
5125 * can be exported to userspace tools via
5126 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5127 * then we're just getting a count and we can skip the
5130 ret = btrfs_check_shared(root, btrfs_ino(inode),
5131 bytenr, roots, tmp_ulist);
5135 flags |= FIEMAP_EXTENT_SHARED;
5138 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5139 flags |= FIEMAP_EXTENT_ENCODED;
5140 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5141 flags |= FIEMAP_EXTENT_UNWRITTEN;
5143 free_extent_map(em);
5145 if ((em_start >= last) || em_len == (u64)-1 ||
5146 (last == (u64)-1 && isize <= em_end)) {
5147 flags |= FIEMAP_EXTENT_LAST;
5151 /* now scan forward to see if this is really the last extent. */
5152 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5158 flags |= FIEMAP_EXTENT_LAST;
5161 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5171 ret = emit_last_fiemap_cache(fieinfo, &cache);
5172 free_extent_map(em);
5174 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5178 btrfs_free_path(path);
5180 ulist_free(tmp_ulist);
5184 static void __free_extent_buffer(struct extent_buffer *eb)
5186 kmem_cache_free(extent_buffer_cache, eb);
5189 int extent_buffer_under_io(const struct extent_buffer *eb)
5191 return (atomic_read(&eb->io_pages) ||
5192 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5193 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5196 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5198 struct btrfs_subpage *subpage;
5200 lockdep_assert_held(&page->mapping->private_lock);
5202 if (PagePrivate(page)) {
5203 subpage = (struct btrfs_subpage *)page->private;
5204 if (atomic_read(&subpage->eb_refs))
5210 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5212 struct btrfs_fs_info *fs_info = eb->fs_info;
5213 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5216 * For mapped eb, we're going to change the page private, which should
5217 * be done under the private_lock.
5220 spin_lock(&page->mapping->private_lock);
5222 if (!PagePrivate(page)) {
5224 spin_unlock(&page->mapping->private_lock);
5228 if (fs_info->sectorsize == PAGE_SIZE) {
5230 * We do this since we'll remove the pages after we've
5231 * removed the eb from the radix tree, so we could race
5232 * and have this page now attached to the new eb. So
5233 * only clear page_private if it's still connected to
5236 if (PagePrivate(page) &&
5237 page->private == (unsigned long)eb) {
5238 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5239 BUG_ON(PageDirty(page));
5240 BUG_ON(PageWriteback(page));
5242 * We need to make sure we haven't be attached
5245 detach_page_private(page);
5248 spin_unlock(&page->mapping->private_lock);
5253 * For subpage, we can have dummy eb with page private. In this case,
5254 * we can directly detach the private as such page is only attached to
5255 * one dummy eb, no sharing.
5258 btrfs_detach_subpage(fs_info, page);
5262 btrfs_page_dec_eb_refs(fs_info, page);
5265 * We can only detach the page private if there are no other ebs in the
5268 if (!page_range_has_eb(fs_info, page))
5269 btrfs_detach_subpage(fs_info, page);
5271 spin_unlock(&page->mapping->private_lock);
5274 /* Release all pages attached to the extent buffer */
5275 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5280 ASSERT(!extent_buffer_under_io(eb));
5282 num_pages = num_extent_pages(eb);
5283 for (i = 0; i < num_pages; i++) {
5284 struct page *page = eb->pages[i];
5289 detach_extent_buffer_page(eb, page);
5291 /* One for when we allocated the page */
5297 * Helper for releasing the extent buffer.
5299 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5301 btrfs_release_extent_buffer_pages(eb);
5302 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5303 __free_extent_buffer(eb);
5306 static struct extent_buffer *
5307 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5310 struct extent_buffer *eb = NULL;
5312 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5315 eb->fs_info = fs_info;
5317 init_rwsem(&eb->lock);
5319 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5320 &fs_info->allocated_ebs);
5321 INIT_LIST_HEAD(&eb->release_list);
5323 spin_lock_init(&eb->refs_lock);
5324 atomic_set(&eb->refs, 1);
5325 atomic_set(&eb->io_pages, 0);
5327 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5332 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5336 struct extent_buffer *new;
5337 int num_pages = num_extent_pages(src);
5339 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5344 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5345 * btrfs_release_extent_buffer() have different behavior for
5346 * UNMAPPED subpage extent buffer.
5348 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5350 for (i = 0; i < num_pages; i++) {
5353 p = alloc_page(GFP_NOFS);
5355 btrfs_release_extent_buffer(new);
5358 ret = attach_extent_buffer_page(new, p, NULL);
5361 btrfs_release_extent_buffer(new);
5364 WARN_ON(PageDirty(p));
5366 copy_page(page_address(p), page_address(src->pages[i]));
5368 set_extent_buffer_uptodate(new);
5373 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5374 u64 start, unsigned long len)
5376 struct extent_buffer *eb;
5380 eb = __alloc_extent_buffer(fs_info, start, len);
5384 num_pages = num_extent_pages(eb);
5385 for (i = 0; i < num_pages; i++) {
5388 eb->pages[i] = alloc_page(GFP_NOFS);
5391 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5395 set_extent_buffer_uptodate(eb);
5396 btrfs_set_header_nritems(eb, 0);
5397 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5401 for (; i > 0; i--) {
5402 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5403 __free_page(eb->pages[i - 1]);
5405 __free_extent_buffer(eb);
5409 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5412 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5415 static void check_buffer_tree_ref(struct extent_buffer *eb)
5419 * The TREE_REF bit is first set when the extent_buffer is added
5420 * to the radix tree. It is also reset, if unset, when a new reference
5421 * is created by find_extent_buffer.
5423 * It is only cleared in two cases: freeing the last non-tree
5424 * reference to the extent_buffer when its STALE bit is set or
5425 * calling releasepage when the tree reference is the only reference.
5427 * In both cases, care is taken to ensure that the extent_buffer's
5428 * pages are not under io. However, releasepage can be concurrently
5429 * called with creating new references, which is prone to race
5430 * conditions between the calls to check_buffer_tree_ref in those
5431 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5433 * The actual lifetime of the extent_buffer in the radix tree is
5434 * adequately protected by the refcount, but the TREE_REF bit and
5435 * its corresponding reference are not. To protect against this
5436 * class of races, we call check_buffer_tree_ref from the codepaths
5437 * which trigger io after they set eb->io_pages. Note that once io is
5438 * initiated, TREE_REF can no longer be cleared, so that is the
5439 * moment at which any such race is best fixed.
5441 refs = atomic_read(&eb->refs);
5442 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5445 spin_lock(&eb->refs_lock);
5446 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5447 atomic_inc(&eb->refs);
5448 spin_unlock(&eb->refs_lock);
5451 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5452 struct page *accessed)
5456 check_buffer_tree_ref(eb);
5458 num_pages = num_extent_pages(eb);
5459 for (i = 0; i < num_pages; i++) {
5460 struct page *p = eb->pages[i];
5463 mark_page_accessed(p);
5467 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5470 struct extent_buffer *eb;
5473 eb = radix_tree_lookup(&fs_info->buffer_radix,
5474 start >> fs_info->sectorsize_bits);
5475 if (eb && atomic_inc_not_zero(&eb->refs)) {
5478 * Lock our eb's refs_lock to avoid races with
5479 * free_extent_buffer. When we get our eb it might be flagged
5480 * with EXTENT_BUFFER_STALE and another task running
5481 * free_extent_buffer might have seen that flag set,
5482 * eb->refs == 2, that the buffer isn't under IO (dirty and
5483 * writeback flags not set) and it's still in the tree (flag
5484 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5485 * of decrementing the extent buffer's reference count twice.
5486 * So here we could race and increment the eb's reference count,
5487 * clear its stale flag, mark it as dirty and drop our reference
5488 * before the other task finishes executing free_extent_buffer,
5489 * which would later result in an attempt to free an extent
5490 * buffer that is dirty.
5492 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5493 spin_lock(&eb->refs_lock);
5494 spin_unlock(&eb->refs_lock);
5496 mark_extent_buffer_accessed(eb, NULL);
5504 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5505 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5508 struct extent_buffer *eb, *exists = NULL;
5511 eb = find_extent_buffer(fs_info, start);
5514 eb = alloc_dummy_extent_buffer(fs_info, start);
5516 return ERR_PTR(-ENOMEM);
5517 eb->fs_info = fs_info;
5519 ret = radix_tree_preload(GFP_NOFS);
5521 exists = ERR_PTR(ret);
5524 spin_lock(&fs_info->buffer_lock);
5525 ret = radix_tree_insert(&fs_info->buffer_radix,
5526 start >> fs_info->sectorsize_bits, eb);
5527 spin_unlock(&fs_info->buffer_lock);
5528 radix_tree_preload_end();
5529 if (ret == -EEXIST) {
5530 exists = find_extent_buffer(fs_info, start);
5536 check_buffer_tree_ref(eb);
5537 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5541 btrfs_release_extent_buffer(eb);
5546 static struct extent_buffer *grab_extent_buffer(
5547 struct btrfs_fs_info *fs_info, struct page *page)
5549 struct extent_buffer *exists;
5552 * For subpage case, we completely rely on radix tree to ensure we
5553 * don't try to insert two ebs for the same bytenr. So here we always
5554 * return NULL and just continue.
5556 if (fs_info->sectorsize < PAGE_SIZE)
5559 /* Page not yet attached to an extent buffer */
5560 if (!PagePrivate(page))
5564 * We could have already allocated an eb for this page and attached one
5565 * so lets see if we can get a ref on the existing eb, and if we can we
5566 * know it's good and we can just return that one, else we know we can
5567 * just overwrite page->private.
5569 exists = (struct extent_buffer *)page->private;
5570 if (atomic_inc_not_zero(&exists->refs))
5573 WARN_ON(PageDirty(page));
5574 detach_page_private(page);
5578 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5579 u64 start, u64 owner_root, int level)
5581 unsigned long len = fs_info->nodesize;
5584 unsigned long index = start >> PAGE_SHIFT;
5585 struct extent_buffer *eb;
5586 struct extent_buffer *exists = NULL;
5588 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5592 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5593 btrfs_err(fs_info, "bad tree block start %llu", start);
5594 return ERR_PTR(-EINVAL);
5597 if (fs_info->sectorsize < PAGE_SIZE &&
5598 offset_in_page(start) + len > PAGE_SIZE) {
5600 "tree block crosses page boundary, start %llu nodesize %lu",
5602 return ERR_PTR(-EINVAL);
5605 eb = find_extent_buffer(fs_info, start);
5609 eb = __alloc_extent_buffer(fs_info, start, len);
5611 return ERR_PTR(-ENOMEM);
5612 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
5614 num_pages = num_extent_pages(eb);
5615 for (i = 0; i < num_pages; i++, index++) {
5616 struct btrfs_subpage *prealloc = NULL;
5618 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5620 exists = ERR_PTR(-ENOMEM);
5625 * Preallocate page->private for subpage case, so that we won't
5626 * allocate memory with private_lock hold. The memory will be
5627 * freed by attach_extent_buffer_page() or freed manually if
5630 * Although we have ensured one subpage eb can only have one
5631 * page, but it may change in the future for 16K page size
5632 * support, so we still preallocate the memory in the loop.
5634 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5635 BTRFS_SUBPAGE_METADATA);
5639 exists = ERR_PTR(ret);
5643 spin_lock(&mapping->private_lock);
5644 exists = grab_extent_buffer(fs_info, p);
5646 spin_unlock(&mapping->private_lock);
5649 mark_extent_buffer_accessed(exists, p);
5650 btrfs_free_subpage(prealloc);
5653 /* Should not fail, as we have preallocated the memory */
5654 ret = attach_extent_buffer_page(eb, p, prealloc);
5657 * To inform we have extra eb under allocation, so that
5658 * detach_extent_buffer_page() won't release the page private
5659 * when the eb hasn't yet been inserted into radix tree.
5661 * The ref will be decreased when the eb released the page, in
5662 * detach_extent_buffer_page().
5663 * Thus needs no special handling in error path.
5665 btrfs_page_inc_eb_refs(fs_info, p);
5666 spin_unlock(&mapping->private_lock);
5668 WARN_ON(PageDirty(p));
5670 if (!PageUptodate(p))
5674 * We can't unlock the pages just yet since the extent buffer
5675 * hasn't been properly inserted in the radix tree, this
5676 * opens a race with btree_releasepage which can free a page
5677 * while we are still filling in all pages for the buffer and
5682 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5684 ret = radix_tree_preload(GFP_NOFS);
5686 exists = ERR_PTR(ret);
5690 spin_lock(&fs_info->buffer_lock);
5691 ret = radix_tree_insert(&fs_info->buffer_radix,
5692 start >> fs_info->sectorsize_bits, eb);
5693 spin_unlock(&fs_info->buffer_lock);
5694 radix_tree_preload_end();
5695 if (ret == -EEXIST) {
5696 exists = find_extent_buffer(fs_info, start);
5702 /* add one reference for the tree */
5703 check_buffer_tree_ref(eb);
5704 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5707 * Now it's safe to unlock the pages because any calls to
5708 * btree_releasepage will correctly detect that a page belongs to a
5709 * live buffer and won't free them prematurely.
5711 for (i = 0; i < num_pages; i++)
5712 unlock_page(eb->pages[i]);
5716 WARN_ON(!atomic_dec_and_test(&eb->refs));
5717 for (i = 0; i < num_pages; i++) {
5719 unlock_page(eb->pages[i]);
5722 btrfs_release_extent_buffer(eb);
5726 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5728 struct extent_buffer *eb =
5729 container_of(head, struct extent_buffer, rcu_head);
5731 __free_extent_buffer(eb);
5734 static int release_extent_buffer(struct extent_buffer *eb)
5735 __releases(&eb->refs_lock)
5737 lockdep_assert_held(&eb->refs_lock);
5739 WARN_ON(atomic_read(&eb->refs) == 0);
5740 if (atomic_dec_and_test(&eb->refs)) {
5741 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5742 struct btrfs_fs_info *fs_info = eb->fs_info;
5744 spin_unlock(&eb->refs_lock);
5746 spin_lock(&fs_info->buffer_lock);
5747 radix_tree_delete(&fs_info->buffer_radix,
5748 eb->start >> fs_info->sectorsize_bits);
5749 spin_unlock(&fs_info->buffer_lock);
5751 spin_unlock(&eb->refs_lock);
5754 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5755 /* Should be safe to release our pages at this point */
5756 btrfs_release_extent_buffer_pages(eb);
5757 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5758 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5759 __free_extent_buffer(eb);
5763 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5766 spin_unlock(&eb->refs_lock);
5771 void free_extent_buffer(struct extent_buffer *eb)
5779 refs = atomic_read(&eb->refs);
5780 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5781 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5784 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5789 spin_lock(&eb->refs_lock);
5790 if (atomic_read(&eb->refs) == 2 &&
5791 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5792 !extent_buffer_under_io(eb) &&
5793 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5794 atomic_dec(&eb->refs);
5797 * I know this is terrible, but it's temporary until we stop tracking
5798 * the uptodate bits and such for the extent buffers.
5800 release_extent_buffer(eb);
5803 void free_extent_buffer_stale(struct extent_buffer *eb)
5808 spin_lock(&eb->refs_lock);
5809 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5811 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5812 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5813 atomic_dec(&eb->refs);
5814 release_extent_buffer(eb);
5817 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
5823 num_pages = num_extent_pages(eb);
5825 for (i = 0; i < num_pages; i++) {
5826 page = eb->pages[i];
5827 if (!PageDirty(page))
5831 WARN_ON(!PagePrivate(page));
5833 clear_page_dirty_for_io(page);
5834 xa_lock_irq(&page->mapping->i_pages);
5835 if (!PageDirty(page))
5836 __xa_clear_mark(&page->mapping->i_pages,
5837 page_index(page), PAGECACHE_TAG_DIRTY);
5838 xa_unlock_irq(&page->mapping->i_pages);
5839 ClearPageError(page);
5842 WARN_ON(atomic_read(&eb->refs) == 0);
5845 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5851 check_buffer_tree_ref(eb);
5853 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5855 num_pages = num_extent_pages(eb);
5856 WARN_ON(atomic_read(&eb->refs) == 0);
5857 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5860 for (i = 0; i < num_pages; i++)
5861 set_page_dirty(eb->pages[i]);
5863 #ifdef CONFIG_BTRFS_DEBUG
5864 for (i = 0; i < num_pages; i++)
5865 ASSERT(PageDirty(eb->pages[i]));
5871 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5873 struct btrfs_fs_info *fs_info = eb->fs_info;
5878 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5879 num_pages = num_extent_pages(eb);
5880 for (i = 0; i < num_pages; i++) {
5881 page = eb->pages[i];
5883 btrfs_page_clear_uptodate(fs_info, page,
5884 eb->start, eb->len);
5888 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5890 struct btrfs_fs_info *fs_info = eb->fs_info;
5895 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5896 num_pages = num_extent_pages(eb);
5897 for (i = 0; i < num_pages; i++) {
5898 page = eb->pages[i];
5899 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
5903 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
5906 struct btrfs_fs_info *fs_info = eb->fs_info;
5907 struct extent_io_tree *io_tree;
5908 struct page *page = eb->pages[0];
5909 struct bio *bio = NULL;
5912 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
5913 ASSERT(PagePrivate(page));
5914 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
5916 if (wait == WAIT_NONE) {
5917 ret = try_lock_extent(io_tree, eb->start,
5918 eb->start + eb->len - 1);
5922 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5928 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
5929 PageUptodate(page) ||
5930 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
5931 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5932 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5936 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5937 eb->read_mirror = 0;
5938 atomic_set(&eb->io_pages, 1);
5939 check_buffer_tree_ref(eb);
5940 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
5942 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, page, eb->start,
5943 eb->len, eb->start - page_offset(page), &bio,
5944 end_bio_extent_readpage, mirror_num, 0, 0,
5948 * In the endio function, if we hit something wrong we will
5949 * increase the io_pages, so here we need to decrease it for
5952 atomic_dec(&eb->io_pages);
5957 tmp = submit_one_bio(bio, mirror_num, 0);
5961 if (ret || wait != WAIT_COMPLETE)
5964 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
5965 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5970 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5976 int locked_pages = 0;
5977 int all_uptodate = 1;
5979 unsigned long num_reads = 0;
5980 struct bio *bio = NULL;
5981 unsigned long bio_flags = 0;
5983 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5986 if (eb->fs_info->sectorsize < PAGE_SIZE)
5987 return read_extent_buffer_subpage(eb, wait, mirror_num);
5989 num_pages = num_extent_pages(eb);
5990 for (i = 0; i < num_pages; i++) {
5991 page = eb->pages[i];
5992 if (wait == WAIT_NONE) {
5994 * WAIT_NONE is only utilized by readahead. If we can't
5995 * acquire the lock atomically it means either the eb
5996 * is being read out or under modification.
5997 * Either way the eb will be or has been cached,
5998 * readahead can exit safely.
6000 if (!trylock_page(page))
6008 * We need to firstly lock all pages to make sure that
6009 * the uptodate bit of our pages won't be affected by
6010 * clear_extent_buffer_uptodate().
6012 for (i = 0; i < num_pages; i++) {
6013 page = eb->pages[i];
6014 if (!PageUptodate(page)) {
6021 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6025 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6026 eb->read_mirror = 0;
6027 atomic_set(&eb->io_pages, num_reads);
6029 * It is possible for releasepage to clear the TREE_REF bit before we
6030 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6032 check_buffer_tree_ref(eb);
6033 for (i = 0; i < num_pages; i++) {
6034 page = eb->pages[i];
6036 if (!PageUptodate(page)) {
6038 atomic_dec(&eb->io_pages);
6043 ClearPageError(page);
6044 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6045 page, page_offset(page), PAGE_SIZE, 0,
6046 &bio, end_bio_extent_readpage,
6047 mirror_num, 0, 0, false);
6050 * We failed to submit the bio so it's the
6051 * caller's responsibility to perform cleanup
6052 * i.e unlock page/set error bit.
6057 atomic_dec(&eb->io_pages);
6065 err = submit_one_bio(bio, mirror_num, bio_flags);
6070 if (ret || wait != WAIT_COMPLETE)
6073 for (i = 0; i < num_pages; i++) {
6074 page = eb->pages[i];
6075 wait_on_page_locked(page);
6076 if (!PageUptodate(page))
6083 while (locked_pages > 0) {
6085 page = eb->pages[locked_pages];
6091 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6094 btrfs_warn(eb->fs_info,
6095 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6096 eb->start, eb->len, start, len);
6097 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6103 * Check if the [start, start + len) range is valid before reading/writing
6105 * NOTE: @start and @len are offset inside the eb, not logical address.
6107 * Caller should not touch the dst/src memory if this function returns error.
6109 static inline int check_eb_range(const struct extent_buffer *eb,
6110 unsigned long start, unsigned long len)
6112 unsigned long offset;
6114 /* start, start + len should not go beyond eb->len nor overflow */
6115 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6116 return report_eb_range(eb, start, len);
6121 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6122 unsigned long start, unsigned long len)
6128 char *dst = (char *)dstv;
6129 unsigned long i = get_eb_page_index(start);
6131 if (check_eb_range(eb, start, len))
6134 offset = get_eb_offset_in_page(eb, start);
6137 page = eb->pages[i];
6139 cur = min(len, (PAGE_SIZE - offset));
6140 kaddr = page_address(page);
6141 memcpy(dst, kaddr + offset, cur);
6150 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6152 unsigned long start, unsigned long len)
6158 char __user *dst = (char __user *)dstv;
6159 unsigned long i = get_eb_page_index(start);
6162 WARN_ON(start > eb->len);
6163 WARN_ON(start + len > eb->start + eb->len);
6165 offset = get_eb_offset_in_page(eb, start);
6168 page = eb->pages[i];
6170 cur = min(len, (PAGE_SIZE - offset));
6171 kaddr = page_address(page);
6172 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6186 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6187 unsigned long start, unsigned long len)
6193 char *ptr = (char *)ptrv;
6194 unsigned long i = get_eb_page_index(start);
6197 if (check_eb_range(eb, start, len))
6200 offset = get_eb_offset_in_page(eb, start);
6203 page = eb->pages[i];
6205 cur = min(len, (PAGE_SIZE - offset));
6207 kaddr = page_address(page);
6208 ret = memcmp(ptr, kaddr + offset, cur);
6220 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6225 WARN_ON(!PageUptodate(eb->pages[0]));
6226 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6227 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
6231 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6235 WARN_ON(!PageUptodate(eb->pages[0]));
6236 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
6237 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
6241 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6242 unsigned long start, unsigned long len)
6248 char *src = (char *)srcv;
6249 unsigned long i = get_eb_page_index(start);
6251 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6253 if (check_eb_range(eb, start, len))
6256 offset = get_eb_offset_in_page(eb, start);
6259 page = eb->pages[i];
6260 WARN_ON(!PageUptodate(page));
6262 cur = min(len, PAGE_SIZE - offset);
6263 kaddr = page_address(page);
6264 memcpy(kaddr + offset, src, cur);
6273 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6280 unsigned long i = get_eb_page_index(start);
6282 if (check_eb_range(eb, start, len))
6285 offset = get_eb_offset_in_page(eb, start);
6288 page = eb->pages[i];
6289 WARN_ON(!PageUptodate(page));
6291 cur = min(len, PAGE_SIZE - offset);
6292 kaddr = page_address(page);
6293 memset(kaddr + offset, 0, cur);
6301 void copy_extent_buffer_full(const struct extent_buffer *dst,
6302 const struct extent_buffer *src)
6307 ASSERT(dst->len == src->len);
6309 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6310 num_pages = num_extent_pages(dst);
6311 for (i = 0; i < num_pages; i++)
6312 copy_page(page_address(dst->pages[i]),
6313 page_address(src->pages[i]));
6315 size_t src_offset = get_eb_offset_in_page(src, 0);
6316 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6318 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6319 memcpy(page_address(dst->pages[0]) + dst_offset,
6320 page_address(src->pages[0]) + src_offset,
6325 void copy_extent_buffer(const struct extent_buffer *dst,
6326 const struct extent_buffer *src,
6327 unsigned long dst_offset, unsigned long src_offset,
6330 u64 dst_len = dst->len;
6335 unsigned long i = get_eb_page_index(dst_offset);
6337 if (check_eb_range(dst, dst_offset, len) ||
6338 check_eb_range(src, src_offset, len))
6341 WARN_ON(src->len != dst_len);
6343 offset = get_eb_offset_in_page(dst, dst_offset);
6346 page = dst->pages[i];
6347 WARN_ON(!PageUptodate(page));
6349 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
6351 kaddr = page_address(page);
6352 read_extent_buffer(src, kaddr + offset, src_offset, cur);
6362 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6364 * @eb: the extent buffer
6365 * @start: offset of the bitmap item in the extent buffer
6367 * @page_index: return index of the page in the extent buffer that contains the
6369 * @page_offset: return offset into the page given by page_index
6371 * This helper hides the ugliness of finding the byte in an extent buffer which
6372 * contains a given bit.
6374 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
6375 unsigned long start, unsigned long nr,
6376 unsigned long *page_index,
6377 size_t *page_offset)
6379 size_t byte_offset = BIT_BYTE(nr);
6383 * The byte we want is the offset of the extent buffer + the offset of
6384 * the bitmap item in the extent buffer + the offset of the byte in the
6387 offset = start + offset_in_page(eb->start) + byte_offset;
6389 *page_index = offset >> PAGE_SHIFT;
6390 *page_offset = offset_in_page(offset);
6394 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6395 * @eb: the extent buffer
6396 * @start: offset of the bitmap item in the extent buffer
6397 * @nr: bit number to test
6399 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
6407 eb_bitmap_offset(eb, start, nr, &i, &offset);
6408 page = eb->pages[i];
6409 WARN_ON(!PageUptodate(page));
6410 kaddr = page_address(page);
6411 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6415 * extent_buffer_bitmap_set - set an area of a bitmap
6416 * @eb: the extent buffer
6417 * @start: offset of the bitmap item in the extent buffer
6418 * @pos: bit number of the first bit
6419 * @len: number of bits to set
6421 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
6422 unsigned long pos, unsigned long len)
6428 const unsigned int size = pos + len;
6429 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6430 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
6432 eb_bitmap_offset(eb, start, pos, &i, &offset);
6433 page = eb->pages[i];
6434 WARN_ON(!PageUptodate(page));
6435 kaddr = page_address(page);
6437 while (len >= bits_to_set) {
6438 kaddr[offset] |= mask_to_set;
6440 bits_to_set = BITS_PER_BYTE;
6442 if (++offset >= PAGE_SIZE && len > 0) {
6444 page = eb->pages[++i];
6445 WARN_ON(!PageUptodate(page));
6446 kaddr = page_address(page);
6450 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6451 kaddr[offset] |= mask_to_set;
6457 * extent_buffer_bitmap_clear - clear an area of a bitmap
6458 * @eb: the extent buffer
6459 * @start: offset of the bitmap item in the extent buffer
6460 * @pos: bit number of the first bit
6461 * @len: number of bits to clear
6463 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6464 unsigned long start, unsigned long pos,
6471 const unsigned int size = pos + len;
6472 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6473 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
6475 eb_bitmap_offset(eb, start, pos, &i, &offset);
6476 page = eb->pages[i];
6477 WARN_ON(!PageUptodate(page));
6478 kaddr = page_address(page);
6480 while (len >= bits_to_clear) {
6481 kaddr[offset] &= ~mask_to_clear;
6482 len -= bits_to_clear;
6483 bits_to_clear = BITS_PER_BYTE;
6485 if (++offset >= PAGE_SIZE && len > 0) {
6487 page = eb->pages[++i];
6488 WARN_ON(!PageUptodate(page));
6489 kaddr = page_address(page);
6493 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6494 kaddr[offset] &= ~mask_to_clear;
6498 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6500 unsigned long distance = (src > dst) ? src - dst : dst - src;
6501 return distance < len;
6504 static void copy_pages(struct page *dst_page, struct page *src_page,
6505 unsigned long dst_off, unsigned long src_off,
6508 char *dst_kaddr = page_address(dst_page);
6510 int must_memmove = 0;
6512 if (dst_page != src_page) {
6513 src_kaddr = page_address(src_page);
6515 src_kaddr = dst_kaddr;
6516 if (areas_overlap(src_off, dst_off, len))
6521 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6523 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6526 void memcpy_extent_buffer(const struct extent_buffer *dst,
6527 unsigned long dst_offset, unsigned long src_offset,
6531 size_t dst_off_in_page;
6532 size_t src_off_in_page;
6533 unsigned long dst_i;
6534 unsigned long src_i;
6536 if (check_eb_range(dst, dst_offset, len) ||
6537 check_eb_range(dst, src_offset, len))
6541 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6542 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
6544 dst_i = get_eb_page_index(dst_offset);
6545 src_i = get_eb_page_index(src_offset);
6547 cur = min(len, (unsigned long)(PAGE_SIZE -
6549 cur = min_t(unsigned long, cur,
6550 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6552 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6553 dst_off_in_page, src_off_in_page, cur);
6561 void memmove_extent_buffer(const struct extent_buffer *dst,
6562 unsigned long dst_offset, unsigned long src_offset,
6566 size_t dst_off_in_page;
6567 size_t src_off_in_page;
6568 unsigned long dst_end = dst_offset + len - 1;
6569 unsigned long src_end = src_offset + len - 1;
6570 unsigned long dst_i;
6571 unsigned long src_i;
6573 if (check_eb_range(dst, dst_offset, len) ||
6574 check_eb_range(dst, src_offset, len))
6576 if (dst_offset < src_offset) {
6577 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6581 dst_i = get_eb_page_index(dst_end);
6582 src_i = get_eb_page_index(src_end);
6584 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6585 src_off_in_page = get_eb_offset_in_page(dst, src_end);
6587 cur = min_t(unsigned long, len, src_off_in_page + 1);
6588 cur = min(cur, dst_off_in_page + 1);
6589 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6590 dst_off_in_page - cur + 1,
6591 src_off_in_page - cur + 1, cur);
6599 static struct extent_buffer *get_next_extent_buffer(
6600 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6602 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6603 struct extent_buffer *found = NULL;
6604 u64 page_start = page_offset(page);
6608 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
6609 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
6610 lockdep_assert_held(&fs_info->buffer_lock);
6612 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
6613 bytenr >> fs_info->sectorsize_bits,
6614 PAGE_SIZE / fs_info->nodesize);
6615 for (i = 0; i < ret; i++) {
6616 /* Already beyond page end */
6617 if (gang[i]->start >= page_start + PAGE_SIZE)
6620 if (gang[i]->start >= bytenr) {
6628 static int try_release_subpage_extent_buffer(struct page *page)
6630 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
6631 u64 cur = page_offset(page);
6632 const u64 end = page_offset(page) + PAGE_SIZE;
6636 struct extent_buffer *eb = NULL;
6639 * Unlike try_release_extent_buffer() which uses page->private
6640 * to grab buffer, for subpage case we rely on radix tree, thus
6641 * we need to ensure radix tree consistency.
6643 * We also want an atomic snapshot of the radix tree, thus go
6644 * with spinlock rather than RCU.
6646 spin_lock(&fs_info->buffer_lock);
6647 eb = get_next_extent_buffer(fs_info, page, cur);
6649 /* No more eb in the page range after or at cur */
6650 spin_unlock(&fs_info->buffer_lock);
6653 cur = eb->start + eb->len;
6656 * The same as try_release_extent_buffer(), to ensure the eb
6657 * won't disappear out from under us.
6659 spin_lock(&eb->refs_lock);
6660 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6661 spin_unlock(&eb->refs_lock);
6662 spin_unlock(&fs_info->buffer_lock);
6665 spin_unlock(&fs_info->buffer_lock);
6668 * If tree ref isn't set then we know the ref on this eb is a
6669 * real ref, so just return, this eb will likely be freed soon
6672 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6673 spin_unlock(&eb->refs_lock);
6678 * Here we don't care about the return value, we will always
6679 * check the page private at the end. And
6680 * release_extent_buffer() will release the refs_lock.
6682 release_extent_buffer(eb);
6685 * Finally to check if we have cleared page private, as if we have
6686 * released all ebs in the page, the page private should be cleared now.
6688 spin_lock(&page->mapping->private_lock);
6689 if (!PagePrivate(page))
6693 spin_unlock(&page->mapping->private_lock);
6698 int try_release_extent_buffer(struct page *page)
6700 struct extent_buffer *eb;
6702 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
6703 return try_release_subpage_extent_buffer(page);
6706 * We need to make sure nobody is changing page->private, as we rely on
6707 * page->private as the pointer to extent buffer.
6709 spin_lock(&page->mapping->private_lock);
6710 if (!PagePrivate(page)) {
6711 spin_unlock(&page->mapping->private_lock);
6715 eb = (struct extent_buffer *)page->private;
6719 * This is a little awful but should be ok, we need to make sure that
6720 * the eb doesn't disappear out from under us while we're looking at
6723 spin_lock(&eb->refs_lock);
6724 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6725 spin_unlock(&eb->refs_lock);
6726 spin_unlock(&page->mapping->private_lock);
6729 spin_unlock(&page->mapping->private_lock);
6732 * If tree ref isn't set then we know the ref on this eb is a real ref,
6733 * so just return, this page will likely be freed soon anyway.
6735 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6736 spin_unlock(&eb->refs_lock);
6740 return release_extent_buffer(eb);
6744 * btrfs_readahead_tree_block - attempt to readahead a child block
6745 * @fs_info: the fs_info
6746 * @bytenr: bytenr to read
6747 * @owner_root: objectid of the root that owns this eb
6748 * @gen: generation for the uptodate check, can be 0
6749 * @level: level for the eb
6751 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
6752 * normal uptodate check of the eb, without checking the generation. If we have
6753 * to read the block we will not block on anything.
6755 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
6756 u64 bytenr, u64 owner_root, u64 gen, int level)
6758 struct extent_buffer *eb;
6761 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
6765 if (btrfs_buffer_uptodate(eb, gen, 1)) {
6766 free_extent_buffer(eb);
6770 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
6772 free_extent_buffer_stale(eb);
6774 free_extent_buffer(eb);
6778 * btrfs_readahead_node_child - readahead a node's child block
6779 * @node: parent node we're reading from
6780 * @slot: slot in the parent node for the child we want to read
6782 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
6783 * the slot in the node provided.
6785 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
6787 btrfs_readahead_tree_block(node->fs_info,
6788 btrfs_node_blockptr(node, slot),
6789 btrfs_header_owner(node),
6790 btrfs_node_ptr_generation(node, slot),
6791 btrfs_header_level(node) - 1);