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 <linux/fsverity.h>
18 #include "extent_io.h"
19 #include "extent-io-tree.h"
20 #include "extent_map.h"
22 #include "btrfs_inode.h"
24 #include "check-integrity.h"
26 #include "rcu-string.h"
31 #include "block-group.h"
33 static struct kmem_cache *extent_state_cache;
34 static struct kmem_cache *extent_buffer_cache;
35 static struct bio_set btrfs_bioset;
37 static inline bool extent_state_in_tree(const struct extent_state *state)
39 return !RB_EMPTY_NODE(&state->rb_node);
42 #ifdef CONFIG_BTRFS_DEBUG
43 static LIST_HEAD(states);
44 static DEFINE_SPINLOCK(leak_lock);
46 static inline void btrfs_leak_debug_add(spinlock_t *lock,
47 struct list_head *new,
48 struct list_head *head)
52 spin_lock_irqsave(lock, flags);
54 spin_unlock_irqrestore(lock, flags);
57 static inline void btrfs_leak_debug_del(spinlock_t *lock,
58 struct list_head *entry)
62 spin_lock_irqsave(lock, flags);
64 spin_unlock_irqrestore(lock, flags);
67 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
69 struct extent_buffer *eb;
73 * If we didn't get into open_ctree our allocated_ebs will not be
74 * initialized, so just skip this.
76 if (!fs_info->allocated_ebs.next)
79 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
80 while (!list_empty(&fs_info->allocated_ebs)) {
81 eb = list_first_entry(&fs_info->allocated_ebs,
82 struct extent_buffer, leak_list);
84 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
85 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
86 btrfs_header_owner(eb));
87 list_del(&eb->leak_list);
88 kmem_cache_free(extent_buffer_cache, eb);
90 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
93 static inline void btrfs_extent_state_leak_debug_check(void)
95 struct extent_state *state;
97 while (!list_empty(&states)) {
98 state = list_entry(states.next, struct extent_state, leak_list);
99 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
100 state->start, state->end, state->state,
101 extent_state_in_tree(state),
102 refcount_read(&state->refs));
103 list_del(&state->leak_list);
104 kmem_cache_free(extent_state_cache, state);
108 #define btrfs_debug_check_extent_io_range(tree, start, end) \
109 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
110 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
111 struct extent_io_tree *tree, u64 start, u64 end)
113 struct inode *inode = tree->private_data;
116 if (!inode || !is_data_inode(inode))
119 isize = i_size_read(inode);
120 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
121 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
122 "%s: ino %llu isize %llu odd range [%llu,%llu]",
123 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
127 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
128 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
129 #define btrfs_extent_state_leak_debug_check() do {} while (0)
130 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
136 struct rb_node rb_node;
139 struct extent_page_data {
140 struct btrfs_bio_ctrl bio_ctrl;
141 /* tells writepage not to lock the state bits for this range
142 * it still does the unlocking
144 unsigned int extent_locked:1;
146 /* tells the submit_bio code to use REQ_SYNC */
147 unsigned int sync_io:1;
150 static int add_extent_changeset(struct extent_state *state, u32 bits,
151 struct extent_changeset *changeset,
158 if (set && (state->state & bits) == bits)
160 if (!set && (state->state & bits) == 0)
162 changeset->bytes_changed += state->end - state->start + 1;
163 ret = ulist_add(&changeset->range_changed, state->start, state->end,
168 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
169 unsigned long bio_flags)
171 blk_status_t ret = 0;
172 struct extent_io_tree *tree = bio->bi_private;
174 bio->bi_private = NULL;
176 /* Caller should ensure the bio has at least some range added */
177 ASSERT(bio->bi_iter.bi_size);
178 if (is_data_inode(tree->private_data))
179 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
182 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
183 mirror_num, bio_flags);
185 return blk_status_to_errno(ret);
188 /* Cleanup unsubmitted bios */
189 static void end_write_bio(struct extent_page_data *epd, int ret)
191 struct bio *bio = epd->bio_ctrl.bio;
194 bio->bi_status = errno_to_blk_status(ret);
196 epd->bio_ctrl.bio = NULL;
201 * Submit bio from extent page data via submit_one_bio
203 * Return 0 if everything is OK.
204 * Return <0 for error.
206 static int __must_check flush_write_bio(struct extent_page_data *epd)
209 struct bio *bio = epd->bio_ctrl.bio;
212 ret = submit_one_bio(bio, 0, 0);
214 * Clean up of epd->bio is handled by its endio function.
215 * And endio is either triggered by successful bio execution
216 * or the error handler of submit bio hook.
217 * So at this point, no matter what happened, we don't need
218 * to clean up epd->bio.
220 epd->bio_ctrl.bio = NULL;
225 int __init extent_state_cache_init(void)
227 extent_state_cache = kmem_cache_create("btrfs_extent_state",
228 sizeof(struct extent_state), 0,
229 SLAB_MEM_SPREAD, NULL);
230 if (!extent_state_cache)
235 int __init extent_io_init(void)
237 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
238 sizeof(struct extent_buffer), 0,
239 SLAB_MEM_SPREAD, NULL);
240 if (!extent_buffer_cache)
243 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
244 offsetof(struct btrfs_io_bio, bio),
246 goto free_buffer_cache;
248 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
254 bioset_exit(&btrfs_bioset);
257 kmem_cache_destroy(extent_buffer_cache);
258 extent_buffer_cache = NULL;
262 void __cold extent_state_cache_exit(void)
264 btrfs_extent_state_leak_debug_check();
265 kmem_cache_destroy(extent_state_cache);
268 void __cold extent_io_exit(void)
271 * Make sure all delayed rcu free are flushed before we
275 kmem_cache_destroy(extent_buffer_cache);
276 bioset_exit(&btrfs_bioset);
280 * For the file_extent_tree, we want to hold the inode lock when we lookup and
281 * update the disk_i_size, but lockdep will complain because our io_tree we hold
282 * the tree lock and get the inode lock when setting delalloc. These two things
283 * are unrelated, so make a class for the file_extent_tree so we don't get the
284 * two locking patterns mixed up.
286 static struct lock_class_key file_extent_tree_class;
288 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
289 struct extent_io_tree *tree, unsigned int owner,
292 tree->fs_info = fs_info;
293 tree->state = RB_ROOT;
294 tree->dirty_bytes = 0;
295 spin_lock_init(&tree->lock);
296 tree->private_data = private_data;
298 if (owner == IO_TREE_INODE_FILE_EXTENT)
299 lockdep_set_class(&tree->lock, &file_extent_tree_class);
302 void extent_io_tree_release(struct extent_io_tree *tree)
304 spin_lock(&tree->lock);
306 * Do a single barrier for the waitqueue_active check here, the state
307 * of the waitqueue should not change once extent_io_tree_release is
311 while (!RB_EMPTY_ROOT(&tree->state)) {
312 struct rb_node *node;
313 struct extent_state *state;
315 node = rb_first(&tree->state);
316 state = rb_entry(node, struct extent_state, rb_node);
317 rb_erase(&state->rb_node, &tree->state);
318 RB_CLEAR_NODE(&state->rb_node);
320 * btree io trees aren't supposed to have tasks waiting for
321 * changes in the flags of extent states ever.
323 ASSERT(!waitqueue_active(&state->wq));
324 free_extent_state(state);
326 cond_resched_lock(&tree->lock);
328 spin_unlock(&tree->lock);
331 static struct extent_state *alloc_extent_state(gfp_t mask)
333 struct extent_state *state;
336 * The given mask might be not appropriate for the slab allocator,
337 * drop the unsupported bits
339 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
340 state = kmem_cache_alloc(extent_state_cache, mask);
344 state->failrec = NULL;
345 RB_CLEAR_NODE(&state->rb_node);
346 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
347 refcount_set(&state->refs, 1);
348 init_waitqueue_head(&state->wq);
349 trace_alloc_extent_state(state, mask, _RET_IP_);
353 void free_extent_state(struct extent_state *state)
357 if (refcount_dec_and_test(&state->refs)) {
358 WARN_ON(extent_state_in_tree(state));
359 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
360 trace_free_extent_state(state, _RET_IP_);
361 kmem_cache_free(extent_state_cache, state);
365 static struct rb_node *tree_insert(struct rb_root *root,
366 struct rb_node *search_start,
368 struct rb_node *node,
369 struct rb_node ***p_in,
370 struct rb_node **parent_in)
373 struct rb_node *parent = NULL;
374 struct tree_entry *entry;
376 if (p_in && parent_in) {
382 p = search_start ? &search_start : &root->rb_node;
385 entry = rb_entry(parent, struct tree_entry, rb_node);
387 if (offset < entry->start)
389 else if (offset > entry->end)
396 rb_link_node(node, parent, p);
397 rb_insert_color(node, root);
402 * Search @tree for an entry that contains @offset. Such entry would have
403 * entry->start <= offset && entry->end >= offset.
405 * @tree: the tree to search
406 * @offset: offset that should fall within an entry in @tree
407 * @next_ret: pointer to the first entry whose range ends after @offset
408 * @prev_ret: pointer to the first entry whose range begins before @offset
409 * @p_ret: pointer where new node should be anchored (used when inserting an
411 * @parent_ret: points to entry which would have been the parent of the entry,
414 * This function returns a pointer to the entry that contains @offset byte
415 * address. If no such entry exists, then NULL is returned and the other
416 * pointer arguments to the function are filled, otherwise the found entry is
417 * returned and other pointers are left untouched.
419 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
420 struct rb_node **next_ret,
421 struct rb_node **prev_ret,
422 struct rb_node ***p_ret,
423 struct rb_node **parent_ret)
425 struct rb_root *root = &tree->state;
426 struct rb_node **n = &root->rb_node;
427 struct rb_node *prev = NULL;
428 struct rb_node *orig_prev = NULL;
429 struct tree_entry *entry;
430 struct tree_entry *prev_entry = NULL;
434 entry = rb_entry(prev, struct tree_entry, rb_node);
437 if (offset < entry->start)
439 else if (offset > entry->end)
452 while (prev && offset > prev_entry->end) {
453 prev = rb_next(prev);
454 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
461 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
462 while (prev && offset < prev_entry->start) {
463 prev = rb_prev(prev);
464 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
471 static inline struct rb_node *
472 tree_search_for_insert(struct extent_io_tree *tree,
474 struct rb_node ***p_ret,
475 struct rb_node **parent_ret)
477 struct rb_node *next= NULL;
480 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
486 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
489 return tree_search_for_insert(tree, offset, NULL, NULL);
493 * utility function to look for merge candidates inside a given range.
494 * Any extents with matching state are merged together into a single
495 * extent in the tree. Extents with EXTENT_IO in their state field
496 * are not merged because the end_io handlers need to be able to do
497 * operations on them without sleeping (or doing allocations/splits).
499 * This should be called with the tree lock held.
501 static void merge_state(struct extent_io_tree *tree,
502 struct extent_state *state)
504 struct extent_state *other;
505 struct rb_node *other_node;
507 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
510 other_node = rb_prev(&state->rb_node);
512 other = rb_entry(other_node, struct extent_state, rb_node);
513 if (other->end == state->start - 1 &&
514 other->state == state->state) {
515 if (tree->private_data &&
516 is_data_inode(tree->private_data))
517 btrfs_merge_delalloc_extent(tree->private_data,
519 state->start = other->start;
520 rb_erase(&other->rb_node, &tree->state);
521 RB_CLEAR_NODE(&other->rb_node);
522 free_extent_state(other);
525 other_node = rb_next(&state->rb_node);
527 other = rb_entry(other_node, struct extent_state, rb_node);
528 if (other->start == state->end + 1 &&
529 other->state == state->state) {
530 if (tree->private_data &&
531 is_data_inode(tree->private_data))
532 btrfs_merge_delalloc_extent(tree->private_data,
534 state->end = other->end;
535 rb_erase(&other->rb_node, &tree->state);
536 RB_CLEAR_NODE(&other->rb_node);
537 free_extent_state(other);
542 static void set_state_bits(struct extent_io_tree *tree,
543 struct extent_state *state, u32 *bits,
544 struct extent_changeset *changeset);
547 * insert an extent_state struct into the tree. 'bits' are set on the
548 * struct before it is inserted.
550 * This may return -EEXIST if the extent is already there, in which case the
551 * state struct is freed.
553 * The tree lock is not taken internally. This is a utility function and
554 * probably isn't what you want to call (see set/clear_extent_bit).
556 static int insert_state(struct extent_io_tree *tree,
557 struct extent_state *state, u64 start, u64 end,
559 struct rb_node **parent,
560 u32 *bits, struct extent_changeset *changeset)
562 struct rb_node *node;
565 btrfs_err(tree->fs_info,
566 "insert state: end < start %llu %llu", end, start);
569 state->start = start;
572 set_state_bits(tree, state, bits, changeset);
574 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
576 struct extent_state *found;
577 found = rb_entry(node, struct extent_state, rb_node);
578 btrfs_err(tree->fs_info,
579 "found node %llu %llu on insert of %llu %llu",
580 found->start, found->end, start, end);
583 merge_state(tree, state);
588 * split a given extent state struct in two, inserting the preallocated
589 * struct 'prealloc' as the newly created second half. 'split' indicates an
590 * offset inside 'orig' where it should be split.
593 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
594 * are two extent state structs in the tree:
595 * prealloc: [orig->start, split - 1]
596 * orig: [ split, orig->end ]
598 * The tree locks are not taken by this function. They need to be held
601 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
602 struct extent_state *prealloc, u64 split)
604 struct rb_node *node;
606 if (tree->private_data && is_data_inode(tree->private_data))
607 btrfs_split_delalloc_extent(tree->private_data, orig, split);
609 prealloc->start = orig->start;
610 prealloc->end = split - 1;
611 prealloc->state = orig->state;
614 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
615 &prealloc->rb_node, NULL, NULL);
617 free_extent_state(prealloc);
623 static struct extent_state *next_state(struct extent_state *state)
625 struct rb_node *next = rb_next(&state->rb_node);
627 return rb_entry(next, struct extent_state, rb_node);
633 * utility function to clear some bits in an extent state struct.
634 * it will optionally wake up anyone waiting on this state (wake == 1).
636 * If no bits are set on the state struct after clearing things, the
637 * struct is freed and removed from the tree
639 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
640 struct extent_state *state,
642 struct extent_changeset *changeset)
644 struct extent_state *next;
645 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
648 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
649 u64 range = state->end - state->start + 1;
650 WARN_ON(range > tree->dirty_bytes);
651 tree->dirty_bytes -= range;
654 if (tree->private_data && is_data_inode(tree->private_data))
655 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
657 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
659 state->state &= ~bits_to_clear;
662 if (state->state == 0) {
663 next = next_state(state);
664 if (extent_state_in_tree(state)) {
665 rb_erase(&state->rb_node, &tree->state);
666 RB_CLEAR_NODE(&state->rb_node);
667 free_extent_state(state);
672 merge_state(tree, state);
673 next = next_state(state);
678 static struct extent_state *
679 alloc_extent_state_atomic(struct extent_state *prealloc)
682 prealloc = alloc_extent_state(GFP_ATOMIC);
687 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
689 btrfs_panic(tree->fs_info, err,
690 "locking error: extent tree was modified by another thread while locked");
694 * clear some bits on a range in the tree. This may require splitting
695 * or inserting elements in the tree, so the gfp mask is used to
696 * indicate which allocations or sleeping are allowed.
698 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
699 * the given range from the tree regardless of state (ie for truncate).
701 * the range [start, end] is inclusive.
703 * This takes the tree lock, and returns 0 on success and < 0 on error.
705 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
706 u32 bits, int wake, int delete,
707 struct extent_state **cached_state,
708 gfp_t mask, struct extent_changeset *changeset)
710 struct extent_state *state;
711 struct extent_state *cached;
712 struct extent_state *prealloc = NULL;
713 struct rb_node *node;
718 btrfs_debug_check_extent_io_range(tree, start, end);
719 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
721 if (bits & EXTENT_DELALLOC)
722 bits |= EXTENT_NORESERVE;
725 bits |= ~EXTENT_CTLBITS;
727 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
730 if (!prealloc && gfpflags_allow_blocking(mask)) {
732 * Don't care for allocation failure here because we might end
733 * up not needing the pre-allocated extent state at all, which
734 * is the case if we only have in the tree extent states that
735 * cover our input range and don't cover too any other range.
736 * If we end up needing a new extent state we allocate it later.
738 prealloc = alloc_extent_state(mask);
741 spin_lock(&tree->lock);
743 cached = *cached_state;
746 *cached_state = NULL;
750 if (cached && extent_state_in_tree(cached) &&
751 cached->start <= start && cached->end > start) {
753 refcount_dec(&cached->refs);
758 free_extent_state(cached);
761 * this search will find the extents that end after
764 node = tree_search(tree, start);
767 state = rb_entry(node, struct extent_state, rb_node);
769 if (state->start > end)
771 WARN_ON(state->end < start);
772 last_end = state->end;
774 /* the state doesn't have the wanted bits, go ahead */
775 if (!(state->state & bits)) {
776 state = next_state(state);
781 * | ---- desired range ---- |
783 * | ------------- state -------------- |
785 * We need to split the extent we found, and may flip
786 * bits on second half.
788 * If the extent we found extends past our range, we
789 * just split and search again. It'll get split again
790 * the next time though.
792 * If the extent we found is inside our range, we clear
793 * the desired bit on it.
796 if (state->start < start) {
797 prealloc = alloc_extent_state_atomic(prealloc);
799 err = split_state(tree, state, prealloc, start);
801 extent_io_tree_panic(tree, err);
806 if (state->end <= end) {
807 state = clear_state_bit(tree, state, &bits, wake,
814 * | ---- desired range ---- |
816 * We need to split the extent, and clear the bit
819 if (state->start <= end && state->end > end) {
820 prealloc = alloc_extent_state_atomic(prealloc);
822 err = split_state(tree, state, prealloc, end + 1);
824 extent_io_tree_panic(tree, err);
829 clear_state_bit(tree, prealloc, &bits, wake, changeset);
835 state = clear_state_bit(tree, state, &bits, wake, changeset);
837 if (last_end == (u64)-1)
839 start = last_end + 1;
840 if (start <= end && state && !need_resched())
846 spin_unlock(&tree->lock);
847 if (gfpflags_allow_blocking(mask))
852 spin_unlock(&tree->lock);
854 free_extent_state(prealloc);
860 static void wait_on_state(struct extent_io_tree *tree,
861 struct extent_state *state)
862 __releases(tree->lock)
863 __acquires(tree->lock)
866 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
867 spin_unlock(&tree->lock);
869 spin_lock(&tree->lock);
870 finish_wait(&state->wq, &wait);
874 * waits for one or more bits to clear on a range in the state tree.
875 * The range [start, end] is inclusive.
876 * The tree lock is taken by this function
878 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
881 struct extent_state *state;
882 struct rb_node *node;
884 btrfs_debug_check_extent_io_range(tree, start, end);
886 spin_lock(&tree->lock);
890 * this search will find all the extents that end after
893 node = tree_search(tree, start);
898 state = rb_entry(node, struct extent_state, rb_node);
900 if (state->start > end)
903 if (state->state & bits) {
904 start = state->start;
905 refcount_inc(&state->refs);
906 wait_on_state(tree, state);
907 free_extent_state(state);
910 start = state->end + 1;
915 if (!cond_resched_lock(&tree->lock)) {
916 node = rb_next(node);
921 spin_unlock(&tree->lock);
924 static void set_state_bits(struct extent_io_tree *tree,
925 struct extent_state *state,
926 u32 *bits, struct extent_changeset *changeset)
928 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
931 if (tree->private_data && is_data_inode(tree->private_data))
932 btrfs_set_delalloc_extent(tree->private_data, state, bits);
934 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
935 u64 range = state->end - state->start + 1;
936 tree->dirty_bytes += range;
938 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
940 state->state |= bits_to_set;
943 static void cache_state_if_flags(struct extent_state *state,
944 struct extent_state **cached_ptr,
947 if (cached_ptr && !(*cached_ptr)) {
948 if (!flags || (state->state & flags)) {
950 refcount_inc(&state->refs);
955 static void cache_state(struct extent_state *state,
956 struct extent_state **cached_ptr)
958 return cache_state_if_flags(state, cached_ptr,
959 EXTENT_LOCKED | EXTENT_BOUNDARY);
963 * set some bits on a range in the tree. This may require allocations or
964 * sleeping, so the gfp mask is used to indicate what is allowed.
966 * If any of the exclusive bits are set, this will fail with -EEXIST if some
967 * part of the range already has the desired bits set. The start of the
968 * existing range is returned in failed_start in this case.
970 * [start, end] is inclusive This takes the tree lock.
972 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
973 u32 exclusive_bits, u64 *failed_start,
974 struct extent_state **cached_state, gfp_t mask,
975 struct extent_changeset *changeset)
977 struct extent_state *state;
978 struct extent_state *prealloc = NULL;
979 struct rb_node *node;
981 struct rb_node *parent;
986 btrfs_debug_check_extent_io_range(tree, start, end);
987 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
990 ASSERT(failed_start);
992 ASSERT(failed_start == NULL);
994 if (!prealloc && gfpflags_allow_blocking(mask)) {
996 * Don't care for allocation failure here because we might end
997 * up not needing the pre-allocated extent state at all, which
998 * is the case if we only have in the tree extent states that
999 * cover our input range and don't cover too any other range.
1000 * If we end up needing a new extent state we allocate it later.
1002 prealloc = alloc_extent_state(mask);
1005 spin_lock(&tree->lock);
1006 if (cached_state && *cached_state) {
1007 state = *cached_state;
1008 if (state->start <= start && state->end > start &&
1009 extent_state_in_tree(state)) {
1010 node = &state->rb_node;
1015 * this search will find all the extents that end after
1018 node = tree_search_for_insert(tree, start, &p, &parent);
1020 prealloc = alloc_extent_state_atomic(prealloc);
1022 err = insert_state(tree, prealloc, start, end,
1023 &p, &parent, &bits, changeset);
1025 extent_io_tree_panic(tree, err);
1027 cache_state(prealloc, cached_state);
1031 state = rb_entry(node, struct extent_state, rb_node);
1033 last_start = state->start;
1034 last_end = state->end;
1037 * | ---- desired range ---- |
1040 * Just lock what we found and keep going
1042 if (state->start == start && state->end <= end) {
1043 if (state->state & exclusive_bits) {
1044 *failed_start = state->start;
1049 set_state_bits(tree, state, &bits, changeset);
1050 cache_state(state, cached_state);
1051 merge_state(tree, state);
1052 if (last_end == (u64)-1)
1054 start = last_end + 1;
1055 state = next_state(state);
1056 if (start < end && state && state->start == start &&
1063 * | ---- desired range ---- |
1066 * | ------------- state -------------- |
1068 * We need to split the extent we found, and may flip bits on
1071 * If the extent we found extends past our
1072 * range, we just split and search again. It'll get split
1073 * again the next time though.
1075 * If the extent we found is inside our range, we set the
1076 * desired bit on it.
1078 if (state->start < start) {
1079 if (state->state & exclusive_bits) {
1080 *failed_start = start;
1086 * If this extent already has all the bits we want set, then
1087 * skip it, not necessary to split it or do anything with it.
1089 if ((state->state & bits) == bits) {
1090 start = state->end + 1;
1091 cache_state(state, cached_state);
1095 prealloc = alloc_extent_state_atomic(prealloc);
1097 err = split_state(tree, state, prealloc, start);
1099 extent_io_tree_panic(tree, err);
1104 if (state->end <= end) {
1105 set_state_bits(tree, state, &bits, changeset);
1106 cache_state(state, cached_state);
1107 merge_state(tree, state);
1108 if (last_end == (u64)-1)
1110 start = last_end + 1;
1111 state = next_state(state);
1112 if (start < end && state && state->start == start &&
1119 * | ---- desired range ---- |
1120 * | state | or | state |
1122 * There's a hole, we need to insert something in it and
1123 * ignore the extent we found.
1125 if (state->start > start) {
1127 if (end < last_start)
1130 this_end = last_start - 1;
1132 prealloc = alloc_extent_state_atomic(prealloc);
1136 * Avoid to free 'prealloc' if it can be merged with
1139 err = insert_state(tree, prealloc, start, this_end,
1140 NULL, NULL, &bits, changeset);
1142 extent_io_tree_panic(tree, err);
1144 cache_state(prealloc, cached_state);
1146 start = this_end + 1;
1150 * | ---- desired range ---- |
1152 * We need to split the extent, and set the bit
1155 if (state->start <= end && state->end > end) {
1156 if (state->state & exclusive_bits) {
1157 *failed_start = start;
1162 prealloc = alloc_extent_state_atomic(prealloc);
1164 err = split_state(tree, state, prealloc, end + 1);
1166 extent_io_tree_panic(tree, err);
1168 set_state_bits(tree, prealloc, &bits, changeset);
1169 cache_state(prealloc, cached_state);
1170 merge_state(tree, prealloc);
1178 spin_unlock(&tree->lock);
1179 if (gfpflags_allow_blocking(mask))
1184 spin_unlock(&tree->lock);
1186 free_extent_state(prealloc);
1193 * convert_extent_bit - convert all bits in a given range from one bit to
1195 * @tree: the io tree to search
1196 * @start: the start offset in bytes
1197 * @end: the end offset in bytes (inclusive)
1198 * @bits: the bits to set in this range
1199 * @clear_bits: the bits to clear in this range
1200 * @cached_state: state that we're going to cache
1202 * This will go through and set bits for the given range. If any states exist
1203 * already in this range they are set with the given bit and cleared of the
1204 * clear_bits. This is only meant to be used by things that are mergeable, ie
1205 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1206 * boundary bits like LOCK.
1208 * All allocations are done with GFP_NOFS.
1210 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1211 u32 bits, u32 clear_bits,
1212 struct extent_state **cached_state)
1214 struct extent_state *state;
1215 struct extent_state *prealloc = NULL;
1216 struct rb_node *node;
1218 struct rb_node *parent;
1222 bool first_iteration = true;
1224 btrfs_debug_check_extent_io_range(tree, start, end);
1225 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1231 * Best effort, don't worry if extent state allocation fails
1232 * here for the first iteration. We might have a cached state
1233 * that matches exactly the target range, in which case no
1234 * extent state allocations are needed. We'll only know this
1235 * after locking the tree.
1237 prealloc = alloc_extent_state(GFP_NOFS);
1238 if (!prealloc && !first_iteration)
1242 spin_lock(&tree->lock);
1243 if (cached_state && *cached_state) {
1244 state = *cached_state;
1245 if (state->start <= start && state->end > start &&
1246 extent_state_in_tree(state)) {
1247 node = &state->rb_node;
1253 * this search will find all the extents that end after
1256 node = tree_search_for_insert(tree, start, &p, &parent);
1258 prealloc = alloc_extent_state_atomic(prealloc);
1263 err = insert_state(tree, prealloc, start, end,
1264 &p, &parent, &bits, NULL);
1266 extent_io_tree_panic(tree, err);
1267 cache_state(prealloc, cached_state);
1271 state = rb_entry(node, struct extent_state, rb_node);
1273 last_start = state->start;
1274 last_end = state->end;
1277 * | ---- desired range ---- |
1280 * Just lock what we found and keep going
1282 if (state->start == start && state->end <= end) {
1283 set_state_bits(tree, state, &bits, NULL);
1284 cache_state(state, cached_state);
1285 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1286 if (last_end == (u64)-1)
1288 start = last_end + 1;
1289 if (start < end && state && state->start == start &&
1296 * | ---- desired range ---- |
1299 * | ------------- state -------------- |
1301 * We need to split the extent we found, and may flip bits on
1304 * If the extent we found extends past our
1305 * range, we just split and search again. It'll get split
1306 * again the next time though.
1308 * If the extent we found is inside our range, we set the
1309 * desired bit on it.
1311 if (state->start < start) {
1312 prealloc = alloc_extent_state_atomic(prealloc);
1317 err = split_state(tree, state, prealloc, start);
1319 extent_io_tree_panic(tree, err);
1323 if (state->end <= end) {
1324 set_state_bits(tree, state, &bits, NULL);
1325 cache_state(state, cached_state);
1326 state = clear_state_bit(tree, state, &clear_bits, 0,
1328 if (last_end == (u64)-1)
1330 start = last_end + 1;
1331 if (start < end && state && state->start == start &&
1338 * | ---- desired range ---- |
1339 * | state | or | state |
1341 * There's a hole, we need to insert something in it and
1342 * ignore the extent we found.
1344 if (state->start > start) {
1346 if (end < last_start)
1349 this_end = last_start - 1;
1351 prealloc = alloc_extent_state_atomic(prealloc);
1358 * Avoid to free 'prealloc' if it can be merged with
1361 err = insert_state(tree, prealloc, start, this_end,
1362 NULL, NULL, &bits, NULL);
1364 extent_io_tree_panic(tree, err);
1365 cache_state(prealloc, cached_state);
1367 start = this_end + 1;
1371 * | ---- desired range ---- |
1373 * We need to split the extent, and set the bit
1376 if (state->start <= end && state->end > end) {
1377 prealloc = alloc_extent_state_atomic(prealloc);
1383 err = split_state(tree, state, prealloc, end + 1);
1385 extent_io_tree_panic(tree, err);
1387 set_state_bits(tree, prealloc, &bits, NULL);
1388 cache_state(prealloc, cached_state);
1389 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1397 spin_unlock(&tree->lock);
1399 first_iteration = false;
1403 spin_unlock(&tree->lock);
1405 free_extent_state(prealloc);
1410 /* wrappers around set/clear extent bit */
1411 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1412 u32 bits, struct extent_changeset *changeset)
1415 * We don't support EXTENT_LOCKED yet, as current changeset will
1416 * record any bits changed, so for EXTENT_LOCKED case, it will
1417 * either fail with -EEXIST or changeset will record the whole
1420 BUG_ON(bits & EXTENT_LOCKED);
1422 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1426 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1429 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1433 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1434 u32 bits, int wake, int delete,
1435 struct extent_state **cached)
1437 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1438 cached, GFP_NOFS, NULL);
1441 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1442 u32 bits, struct extent_changeset *changeset)
1445 * Don't support EXTENT_LOCKED case, same reason as
1446 * set_record_extent_bits().
1448 BUG_ON(bits & EXTENT_LOCKED);
1450 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1455 * either insert or lock state struct between start and end use mask to tell
1456 * us if waiting is desired.
1458 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1459 struct extent_state **cached_state)
1465 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1466 EXTENT_LOCKED, &failed_start,
1467 cached_state, GFP_NOFS, NULL);
1468 if (err == -EEXIST) {
1469 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1470 start = failed_start;
1473 WARN_ON(start > end);
1478 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1483 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1484 &failed_start, NULL, GFP_NOFS, NULL);
1485 if (err == -EEXIST) {
1486 if (failed_start > start)
1487 clear_extent_bit(tree, start, failed_start - 1,
1488 EXTENT_LOCKED, 1, 0, NULL);
1494 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1496 unsigned long index = start >> PAGE_SHIFT;
1497 unsigned long end_index = end >> PAGE_SHIFT;
1500 while (index <= end_index) {
1501 page = find_get_page(inode->i_mapping, index);
1502 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1503 clear_page_dirty_for_io(page);
1509 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1511 unsigned long index = start >> PAGE_SHIFT;
1512 unsigned long end_index = end >> PAGE_SHIFT;
1515 while (index <= end_index) {
1516 page = find_get_page(inode->i_mapping, index);
1517 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1518 __set_page_dirty_nobuffers(page);
1519 account_page_redirty(page);
1525 /* find the first state struct with 'bits' set after 'start', and
1526 * return it. tree->lock must be held. NULL will returned if
1527 * nothing was found after 'start'
1529 static struct extent_state *
1530 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1532 struct rb_node *node;
1533 struct extent_state *state;
1536 * this search will find all the extents that end after
1539 node = tree_search(tree, start);
1544 state = rb_entry(node, struct extent_state, rb_node);
1545 if (state->end >= start && (state->state & bits))
1548 node = rb_next(node);
1557 * Find the first offset in the io tree with one or more @bits set.
1559 * Note: If there are multiple bits set in @bits, any of them will match.
1561 * Return 0 if we find something, and update @start_ret and @end_ret.
1562 * Return 1 if we found nothing.
1564 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1565 u64 *start_ret, u64 *end_ret, u32 bits,
1566 struct extent_state **cached_state)
1568 struct extent_state *state;
1571 spin_lock(&tree->lock);
1572 if (cached_state && *cached_state) {
1573 state = *cached_state;
1574 if (state->end == start - 1 && extent_state_in_tree(state)) {
1575 while ((state = next_state(state)) != NULL) {
1576 if (state->state & bits)
1579 free_extent_state(*cached_state);
1580 *cached_state = NULL;
1583 free_extent_state(*cached_state);
1584 *cached_state = NULL;
1587 state = find_first_extent_bit_state(tree, start, bits);
1590 cache_state_if_flags(state, cached_state, 0);
1591 *start_ret = state->start;
1592 *end_ret = state->end;
1596 spin_unlock(&tree->lock);
1601 * Find a contiguous area of bits
1603 * @tree: io tree to check
1604 * @start: offset to start the search from
1605 * @start_ret: the first offset we found with the bits set
1606 * @end_ret: the final contiguous range of the bits that were set
1607 * @bits: bits to look for
1609 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1610 * to set bits appropriately, and then merge them again. During this time it
1611 * will drop the tree->lock, so use this helper if you want to find the actual
1612 * contiguous area for given bits. We will search to the first bit we find, and
1613 * then walk down the tree until we find a non-contiguous area. The area
1614 * returned will be the full contiguous area with the bits set.
1616 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1617 u64 *start_ret, u64 *end_ret, u32 bits)
1619 struct extent_state *state;
1622 spin_lock(&tree->lock);
1623 state = find_first_extent_bit_state(tree, start, bits);
1625 *start_ret = state->start;
1626 *end_ret = state->end;
1627 while ((state = next_state(state)) != NULL) {
1628 if (state->start > (*end_ret + 1))
1630 *end_ret = state->end;
1634 spin_unlock(&tree->lock);
1639 * Find the first range that has @bits not set. This range could start before
1642 * @tree: the tree to search
1643 * @start: offset at/after which the found extent should start
1644 * @start_ret: records the beginning of the range
1645 * @end_ret: records the end of the range (inclusive)
1646 * @bits: the set of bits which must be unset
1648 * Since unallocated range is also considered one which doesn't have the bits
1649 * set it's possible that @end_ret contains -1, this happens in case the range
1650 * spans (last_range_end, end of device]. In this case it's up to the caller to
1651 * trim @end_ret to the appropriate size.
1653 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1654 u64 *start_ret, u64 *end_ret, u32 bits)
1656 struct extent_state *state;
1657 struct rb_node *node, *prev = NULL, *next;
1659 spin_lock(&tree->lock);
1661 /* Find first extent with bits cleared */
1663 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1664 if (!node && !next && !prev) {
1666 * Tree is completely empty, send full range and let
1667 * caller deal with it
1672 } else if (!node && !next) {
1674 * We are past the last allocated chunk, set start at
1675 * the end of the last extent.
1677 state = rb_entry(prev, struct extent_state, rb_node);
1678 *start_ret = state->end + 1;
1685 * At this point 'node' either contains 'start' or start is
1688 state = rb_entry(node, struct extent_state, rb_node);
1690 if (in_range(start, state->start, state->end - state->start + 1)) {
1691 if (state->state & bits) {
1693 * |--range with bits sets--|
1697 start = state->end + 1;
1700 * 'start' falls within a range that doesn't
1701 * have the bits set, so take its start as
1702 * the beginning of the desired range
1704 * |--range with bits cleared----|
1708 *start_ret = state->start;
1713 * |---prev range---|---hole/unset---|---node range---|
1719 * |---hole/unset--||--first node--|
1724 state = rb_entry(prev, struct extent_state,
1726 *start_ret = state->end + 1;
1735 * Find the longest stretch from start until an entry which has the
1739 state = rb_entry(node, struct extent_state, rb_node);
1740 if (state->end >= start && !(state->state & bits)) {
1741 *end_ret = state->end;
1743 *end_ret = state->start - 1;
1747 node = rb_next(node);
1752 spin_unlock(&tree->lock);
1756 * find a contiguous range of bytes in the file marked as delalloc, not
1757 * more than 'max_bytes'. start and end are used to return the range,
1759 * true is returned if we find something, false if nothing was in the tree
1761 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1762 u64 *end, u64 max_bytes,
1763 struct extent_state **cached_state)
1765 struct rb_node *node;
1766 struct extent_state *state;
1767 u64 cur_start = *start;
1769 u64 total_bytes = 0;
1771 spin_lock(&tree->lock);
1774 * this search will find all the extents that end after
1777 node = tree_search(tree, cur_start);
1784 state = rb_entry(node, struct extent_state, rb_node);
1785 if (found && (state->start != cur_start ||
1786 (state->state & EXTENT_BOUNDARY))) {
1789 if (!(state->state & EXTENT_DELALLOC)) {
1795 *start = state->start;
1796 *cached_state = state;
1797 refcount_inc(&state->refs);
1801 cur_start = state->end + 1;
1802 node = rb_next(node);
1803 total_bytes += state->end - state->start + 1;
1804 if (total_bytes >= max_bytes)
1810 spin_unlock(&tree->lock);
1815 * Process one page for __process_pages_contig().
1817 * Return >0 if we hit @page == @locked_page.
1818 * Return 0 if we updated the page status.
1819 * Return -EGAIN if the we need to try again.
1820 * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1822 static int process_one_page(struct btrfs_fs_info *fs_info,
1823 struct address_space *mapping,
1824 struct page *page, struct page *locked_page,
1825 unsigned long page_ops, u64 start, u64 end)
1829 ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1830 len = end + 1 - start;
1832 if (page_ops & PAGE_SET_ORDERED)
1833 btrfs_page_clamp_set_ordered(fs_info, page, start, len);
1834 if (page_ops & PAGE_SET_ERROR)
1835 btrfs_page_clamp_set_error(fs_info, page, start, len);
1836 if (page_ops & PAGE_START_WRITEBACK) {
1837 btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1838 btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1840 if (page_ops & PAGE_END_WRITEBACK)
1841 btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1843 if (page == locked_page)
1846 if (page_ops & PAGE_LOCK) {
1849 ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
1852 if (!PageDirty(page) || page->mapping != mapping) {
1853 btrfs_page_end_writer_lock(fs_info, page, start, len);
1857 if (page_ops & PAGE_UNLOCK)
1858 btrfs_page_end_writer_lock(fs_info, page, start, len);
1862 static int __process_pages_contig(struct address_space *mapping,
1863 struct page *locked_page,
1864 u64 start, u64 end, unsigned long page_ops,
1867 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1868 pgoff_t start_index = start >> PAGE_SHIFT;
1869 pgoff_t end_index = end >> PAGE_SHIFT;
1870 pgoff_t index = start_index;
1871 unsigned long nr_pages = end_index - start_index + 1;
1872 unsigned long pages_processed = 0;
1873 struct page *pages[16];
1877 if (page_ops & PAGE_LOCK) {
1878 ASSERT(page_ops == PAGE_LOCK);
1879 ASSERT(processed_end && *processed_end == start);
1882 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1883 mapping_set_error(mapping, -EIO);
1885 while (nr_pages > 0) {
1888 found_pages = find_get_pages_contig(mapping, index,
1889 min_t(unsigned long,
1890 nr_pages, ARRAY_SIZE(pages)), pages);
1891 if (found_pages == 0) {
1893 * Only if we're going to lock these pages, we can find
1894 * nothing at @index.
1896 ASSERT(page_ops & PAGE_LOCK);
1901 for (i = 0; i < found_pages; i++) {
1904 process_ret = process_one_page(fs_info, mapping,
1905 pages[i], locked_page, page_ops,
1907 if (process_ret < 0) {
1908 for (; i < found_pages; i++)
1916 nr_pages -= found_pages;
1917 index += found_pages;
1921 if (err && processed_end) {
1923 * Update @processed_end. I know this is awful since it has
1924 * two different return value patterns (inclusive vs exclusive).
1926 * But the exclusive pattern is necessary if @start is 0, or we
1927 * underflow and check against processed_end won't work as
1930 if (pages_processed)
1931 *processed_end = min(end,
1932 ((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1934 *processed_end = start;
1939 static noinline void __unlock_for_delalloc(struct inode *inode,
1940 struct page *locked_page,
1943 unsigned long index = start >> PAGE_SHIFT;
1944 unsigned long end_index = end >> PAGE_SHIFT;
1946 ASSERT(locked_page);
1947 if (index == locked_page->index && end_index == index)
1950 __process_pages_contig(inode->i_mapping, locked_page, start, end,
1954 static noinline int lock_delalloc_pages(struct inode *inode,
1955 struct page *locked_page,
1959 unsigned long index = delalloc_start >> PAGE_SHIFT;
1960 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1961 u64 processed_end = delalloc_start;
1964 ASSERT(locked_page);
1965 if (index == locked_page->index && index == end_index)
1968 ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1969 delalloc_end, PAGE_LOCK, &processed_end);
1970 if (ret == -EAGAIN && processed_end > delalloc_start)
1971 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1977 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1978 * more than @max_bytes. @Start and @end are used to return the range,
1980 * Return: true if we find something
1981 * false if nothing was in the tree
1984 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1985 struct page *locked_page, u64 *start,
1988 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1989 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1993 struct extent_state *cached_state = NULL;
1998 /* step one, find a bunch of delalloc bytes starting at start */
1999 delalloc_start = *start;
2001 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
2002 max_bytes, &cached_state);
2003 if (!found || delalloc_end <= *start) {
2004 *start = delalloc_start;
2005 *end = delalloc_end;
2006 free_extent_state(cached_state);
2011 * start comes from the offset of locked_page. We have to lock
2012 * pages in order, so we can't process delalloc bytes before
2015 if (delalloc_start < *start)
2016 delalloc_start = *start;
2019 * make sure to limit the number of pages we try to lock down
2021 if (delalloc_end + 1 - delalloc_start > max_bytes)
2022 delalloc_end = delalloc_start + max_bytes - 1;
2024 /* step two, lock all the pages after the page that has start */
2025 ret = lock_delalloc_pages(inode, locked_page,
2026 delalloc_start, delalloc_end);
2027 ASSERT(!ret || ret == -EAGAIN);
2028 if (ret == -EAGAIN) {
2029 /* some of the pages are gone, lets avoid looping by
2030 * shortening the size of the delalloc range we're searching
2032 free_extent_state(cached_state);
2033 cached_state = NULL;
2035 max_bytes = PAGE_SIZE;
2044 /* step three, lock the state bits for the whole range */
2045 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2047 /* then test to make sure it is all still delalloc */
2048 ret = test_range_bit(tree, delalloc_start, delalloc_end,
2049 EXTENT_DELALLOC, 1, cached_state);
2051 unlock_extent_cached(tree, delalloc_start, delalloc_end,
2053 __unlock_for_delalloc(inode, locked_page,
2054 delalloc_start, delalloc_end);
2058 free_extent_state(cached_state);
2059 *start = delalloc_start;
2060 *end = delalloc_end;
2065 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2066 struct page *locked_page,
2067 u32 clear_bits, unsigned long page_ops)
2069 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2071 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2072 start, end, page_ops, NULL);
2076 * count the number of bytes in the tree that have a given bit(s)
2077 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2078 * cached. The total number found is returned.
2080 u64 count_range_bits(struct extent_io_tree *tree,
2081 u64 *start, u64 search_end, u64 max_bytes,
2082 u32 bits, int contig)
2084 struct rb_node *node;
2085 struct extent_state *state;
2086 u64 cur_start = *start;
2087 u64 total_bytes = 0;
2091 if (WARN_ON(search_end <= cur_start))
2094 spin_lock(&tree->lock);
2095 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2096 total_bytes = tree->dirty_bytes;
2100 * this search will find all the extents that end after
2103 node = tree_search(tree, cur_start);
2108 state = rb_entry(node, struct extent_state, rb_node);
2109 if (state->start > search_end)
2111 if (contig && found && state->start > last + 1)
2113 if (state->end >= cur_start && (state->state & bits) == bits) {
2114 total_bytes += min(search_end, state->end) + 1 -
2115 max(cur_start, state->start);
2116 if (total_bytes >= max_bytes)
2119 *start = max(cur_start, state->start);
2123 } else if (contig && found) {
2126 node = rb_next(node);
2131 spin_unlock(&tree->lock);
2136 * set the private field for a given byte offset in the tree. If there isn't
2137 * an extent_state there already, this does nothing.
2139 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2140 struct io_failure_record *failrec)
2142 struct rb_node *node;
2143 struct extent_state *state;
2146 spin_lock(&tree->lock);
2148 * this search will find all the extents that end after
2151 node = tree_search(tree, start);
2156 state = rb_entry(node, struct extent_state, rb_node);
2157 if (state->start != start) {
2161 state->failrec = failrec;
2163 spin_unlock(&tree->lock);
2167 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2169 struct rb_node *node;
2170 struct extent_state *state;
2171 struct io_failure_record *failrec;
2173 spin_lock(&tree->lock);
2175 * this search will find all the extents that end after
2178 node = tree_search(tree, start);
2180 failrec = ERR_PTR(-ENOENT);
2183 state = rb_entry(node, struct extent_state, rb_node);
2184 if (state->start != start) {
2185 failrec = ERR_PTR(-ENOENT);
2189 failrec = state->failrec;
2191 spin_unlock(&tree->lock);
2196 * searches a range in the state tree for a given mask.
2197 * If 'filled' == 1, this returns 1 only if every extent in the tree
2198 * has the bits set. Otherwise, 1 is returned if any bit in the
2199 * range is found set.
2201 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2202 u32 bits, int filled, struct extent_state *cached)
2204 struct extent_state *state = NULL;
2205 struct rb_node *node;
2208 spin_lock(&tree->lock);
2209 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2210 cached->end > start)
2211 node = &cached->rb_node;
2213 node = tree_search(tree, start);
2214 while (node && start <= end) {
2215 state = rb_entry(node, struct extent_state, rb_node);
2217 if (filled && state->start > start) {
2222 if (state->start > end)
2225 if (state->state & bits) {
2229 } else if (filled) {
2234 if (state->end == (u64)-1)
2237 start = state->end + 1;
2240 node = rb_next(node);
2247 spin_unlock(&tree->lock);
2251 int free_io_failure(struct extent_io_tree *failure_tree,
2252 struct extent_io_tree *io_tree,
2253 struct io_failure_record *rec)
2258 set_state_failrec(failure_tree, rec->start, NULL);
2259 ret = clear_extent_bits(failure_tree, rec->start,
2260 rec->start + rec->len - 1,
2261 EXTENT_LOCKED | EXTENT_DIRTY);
2265 ret = clear_extent_bits(io_tree, rec->start,
2266 rec->start + rec->len - 1,
2276 * this bypasses the standard btrfs submit functions deliberately, as
2277 * the standard behavior is to write all copies in a raid setup. here we only
2278 * want to write the one bad copy. so we do the mapping for ourselves and issue
2279 * submit_bio directly.
2280 * to avoid any synchronization issues, wait for the data after writing, which
2281 * actually prevents the read that triggered the error from finishing.
2282 * currently, there can be no more than two copies of every data bit. thus,
2283 * exactly one rewrite is required.
2285 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2286 u64 length, u64 logical, struct page *page,
2287 unsigned int pg_offset, int mirror_num)
2290 struct btrfs_device *dev;
2293 struct btrfs_bio *bbio = NULL;
2296 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2297 BUG_ON(!mirror_num);
2299 if (btrfs_is_zoned(fs_info))
2300 return btrfs_repair_one_zone(fs_info, logical);
2302 bio = btrfs_io_bio_alloc(1);
2303 bio->bi_iter.bi_size = 0;
2304 map_length = length;
2307 * Avoid races with device replace and make sure our bbio has devices
2308 * associated to its stripes that don't go away while we are doing the
2309 * read repair operation.
2311 btrfs_bio_counter_inc_blocked(fs_info);
2312 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2314 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2315 * to update all raid stripes, but here we just want to correct
2316 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2317 * stripe's dev and sector.
2319 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2320 &map_length, &bbio, 0);
2322 btrfs_bio_counter_dec(fs_info);
2326 ASSERT(bbio->mirror_num == 1);
2328 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2329 &map_length, &bbio, mirror_num);
2331 btrfs_bio_counter_dec(fs_info);
2335 BUG_ON(mirror_num != bbio->mirror_num);
2338 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2339 bio->bi_iter.bi_sector = sector;
2340 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2341 btrfs_put_bbio(bbio);
2342 if (!dev || !dev->bdev ||
2343 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2344 btrfs_bio_counter_dec(fs_info);
2348 bio_set_dev(bio, dev->bdev);
2349 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2350 bio_add_page(bio, page, length, pg_offset);
2352 if (btrfsic_submit_bio_wait(bio)) {
2353 /* try to remap that extent elsewhere? */
2354 btrfs_bio_counter_dec(fs_info);
2356 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2360 btrfs_info_rl_in_rcu(fs_info,
2361 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2363 rcu_str_deref(dev->name), sector);
2364 btrfs_bio_counter_dec(fs_info);
2369 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2371 struct btrfs_fs_info *fs_info = eb->fs_info;
2372 u64 start = eb->start;
2373 int i, num_pages = num_extent_pages(eb);
2376 if (sb_rdonly(fs_info->sb))
2379 for (i = 0; i < num_pages; i++) {
2380 struct page *p = eb->pages[i];
2382 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2383 start - page_offset(p), mirror_num);
2393 * each time an IO finishes, we do a fast check in the IO failure tree
2394 * to see if we need to process or clean up an io_failure_record
2396 int clean_io_failure(struct btrfs_fs_info *fs_info,
2397 struct extent_io_tree *failure_tree,
2398 struct extent_io_tree *io_tree, u64 start,
2399 struct page *page, u64 ino, unsigned int pg_offset)
2402 struct io_failure_record *failrec;
2403 struct extent_state *state;
2408 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2413 failrec = get_state_failrec(failure_tree, start);
2414 if (IS_ERR(failrec))
2417 BUG_ON(!failrec->this_mirror);
2419 if (sb_rdonly(fs_info->sb))
2422 spin_lock(&io_tree->lock);
2423 state = find_first_extent_bit_state(io_tree,
2426 spin_unlock(&io_tree->lock);
2428 if (state && state->start <= failrec->start &&
2429 state->end >= failrec->start + failrec->len - 1) {
2430 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2432 if (num_copies > 1) {
2433 repair_io_failure(fs_info, ino, start, failrec->len,
2434 failrec->logical, page, pg_offset,
2435 failrec->failed_mirror);
2440 free_io_failure(failure_tree, io_tree, failrec);
2446 * Can be called when
2447 * - hold extent lock
2448 * - under ordered extent
2449 * - the inode is freeing
2451 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2453 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2454 struct io_failure_record *failrec;
2455 struct extent_state *state, *next;
2457 if (RB_EMPTY_ROOT(&failure_tree->state))
2460 spin_lock(&failure_tree->lock);
2461 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2463 if (state->start > end)
2466 ASSERT(state->end <= end);
2468 next = next_state(state);
2470 failrec = state->failrec;
2471 free_extent_state(state);
2476 spin_unlock(&failure_tree->lock);
2479 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2482 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2483 struct io_failure_record *failrec;
2484 struct extent_map *em;
2485 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2486 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2487 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2488 const u32 sectorsize = fs_info->sectorsize;
2492 failrec = get_state_failrec(failure_tree, start);
2493 if (!IS_ERR(failrec)) {
2494 btrfs_debug(fs_info,
2495 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2496 failrec->logical, failrec->start, failrec->len);
2498 * when data can be on disk more than twice, add to failrec here
2499 * (e.g. with a list for failed_mirror) to make
2500 * clean_io_failure() clean all those errors at once.
2506 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2508 return ERR_PTR(-ENOMEM);
2510 failrec->start = start;
2511 failrec->len = sectorsize;
2512 failrec->this_mirror = 0;
2513 failrec->bio_flags = 0;
2515 read_lock(&em_tree->lock);
2516 em = lookup_extent_mapping(em_tree, start, failrec->len);
2518 read_unlock(&em_tree->lock);
2520 return ERR_PTR(-EIO);
2523 if (em->start > start || em->start + em->len <= start) {
2524 free_extent_map(em);
2527 read_unlock(&em_tree->lock);
2530 return ERR_PTR(-EIO);
2533 logical = start - em->start;
2534 logical = em->block_start + logical;
2535 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2536 logical = em->block_start;
2537 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2538 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2541 btrfs_debug(fs_info,
2542 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2543 logical, start, failrec->len);
2545 failrec->logical = logical;
2546 free_extent_map(em);
2548 /* Set the bits in the private failure tree */
2549 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2550 EXTENT_LOCKED | EXTENT_DIRTY);
2552 ret = set_state_failrec(failure_tree, start, failrec);
2553 /* Set the bits in the inode's tree */
2554 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2556 } else if (ret < 0) {
2558 return ERR_PTR(ret);
2564 static bool btrfs_check_repairable(struct inode *inode,
2565 struct io_failure_record *failrec,
2568 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2571 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2572 if (num_copies == 1) {
2574 * we only have a single copy of the data, so don't bother with
2575 * all the retry and error correction code that follows. no
2576 * matter what the error is, it is very likely to persist.
2578 btrfs_debug(fs_info,
2579 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2580 num_copies, failrec->this_mirror, failed_mirror);
2584 /* The failure record should only contain one sector */
2585 ASSERT(failrec->len == fs_info->sectorsize);
2588 * There are two premises:
2589 * a) deliver good data to the caller
2590 * b) correct the bad sectors on disk
2592 * Since we're only doing repair for one sector, we only need to get
2593 * a good copy of the failed sector and if we succeed, we have setup
2594 * everything for repair_io_failure to do the rest for us.
2596 failrec->failed_mirror = failed_mirror;
2597 failrec->this_mirror++;
2598 if (failrec->this_mirror == failed_mirror)
2599 failrec->this_mirror++;
2601 if (failrec->this_mirror > num_copies) {
2602 btrfs_debug(fs_info,
2603 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2604 num_copies, failrec->this_mirror, failed_mirror);
2611 int btrfs_repair_one_sector(struct inode *inode,
2612 struct bio *failed_bio, u32 bio_offset,
2613 struct page *page, unsigned int pgoff,
2614 u64 start, int failed_mirror,
2615 submit_bio_hook_t *submit_bio_hook)
2617 struct io_failure_record *failrec;
2618 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2619 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2620 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2621 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2622 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2623 struct bio *repair_bio;
2624 struct btrfs_io_bio *repair_io_bio;
2625 blk_status_t status;
2627 btrfs_debug(fs_info,
2628 "repair read error: read error at %llu", start);
2630 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2632 failrec = btrfs_get_io_failure_record(inode, start);
2633 if (IS_ERR(failrec))
2634 return PTR_ERR(failrec);
2637 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2638 free_io_failure(failure_tree, tree, failrec);
2642 repair_bio = btrfs_io_bio_alloc(1);
2643 repair_io_bio = btrfs_io_bio(repair_bio);
2644 repair_bio->bi_opf = REQ_OP_READ;
2645 repair_bio->bi_end_io = failed_bio->bi_end_io;
2646 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2647 repair_bio->bi_private = failed_bio->bi_private;
2649 if (failed_io_bio->csum) {
2650 const u32 csum_size = fs_info->csum_size;
2652 repair_io_bio->csum = repair_io_bio->csum_inline;
2653 memcpy(repair_io_bio->csum,
2654 failed_io_bio->csum + csum_size * icsum, csum_size);
2657 bio_add_page(repair_bio, page, failrec->len, pgoff);
2658 repair_io_bio->logical = failrec->start;
2659 repair_io_bio->iter = repair_bio->bi_iter;
2661 btrfs_debug(btrfs_sb(inode->i_sb),
2662 "repair read error: submitting new read to mirror %d",
2663 failrec->this_mirror);
2665 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2666 failrec->bio_flags);
2668 free_io_failure(failure_tree, tree, failrec);
2669 bio_put(repair_bio);
2671 return blk_status_to_errno(status);
2674 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2676 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2678 ASSERT(page_offset(page) <= start &&
2679 start + len <= page_offset(page) + PAGE_SIZE);
2682 if (fsverity_active(page->mapping->host) &&
2684 !PageUptodate(page) &&
2685 start < i_size_read(page->mapping->host) &&
2686 !fsverity_verify_page(page)) {
2687 btrfs_page_set_error(fs_info, page, start, len);
2689 btrfs_page_set_uptodate(fs_info, page, start, len);
2692 btrfs_page_clear_uptodate(fs_info, page, start, len);
2693 btrfs_page_set_error(fs_info, page, start, len);
2696 if (fs_info->sectorsize == PAGE_SIZE)
2699 btrfs_subpage_end_reader(fs_info, page, start, len);
2702 static blk_status_t submit_read_repair(struct inode *inode,
2703 struct bio *failed_bio, u32 bio_offset,
2704 struct page *page, unsigned int pgoff,
2705 u64 start, u64 end, int failed_mirror,
2706 unsigned int error_bitmap,
2707 submit_bio_hook_t *submit_bio_hook)
2709 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2710 const u32 sectorsize = fs_info->sectorsize;
2711 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2715 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2717 /* We're here because we had some read errors or csum mismatch */
2718 ASSERT(error_bitmap);
2721 * We only get called on buffered IO, thus page must be mapped and bio
2722 * must not be cloned.
2724 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2726 /* Iterate through all the sectors in the range */
2727 for (i = 0; i < nr_bits; i++) {
2728 const unsigned int offset = i * sectorsize;
2729 struct extent_state *cached = NULL;
2730 bool uptodate = false;
2733 if (!(error_bitmap & (1U << i))) {
2735 * This sector has no error, just end the page read
2736 * and unlock the range.
2742 ret = btrfs_repair_one_sector(inode, failed_bio,
2743 bio_offset + offset,
2744 page, pgoff + offset, start + offset,
2745 failed_mirror, submit_bio_hook);
2748 * We have submitted the read repair, the page release
2749 * will be handled by the endio function of the
2750 * submitted repair bio.
2751 * Thus we don't need to do any thing here.
2756 * Repair failed, just record the error but still continue.
2757 * Or the remaining sectors will not be properly unlocked.
2762 end_page_read(page, uptodate, start + offset, sectorsize);
2764 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2766 start + offset + sectorsize - 1,
2767 &cached, GFP_ATOMIC);
2768 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2770 start + offset + sectorsize - 1,
2773 return errno_to_blk_status(error);
2776 /* lots and lots of room for performance fixes in the end_bio funcs */
2778 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2780 struct btrfs_inode *inode;
2781 const bool uptodate = (err == 0);
2784 ASSERT(page && page->mapping);
2785 inode = BTRFS_I(page->mapping->host);
2786 btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2789 const struct btrfs_fs_info *fs_info = inode->root->fs_info;
2792 ASSERT(end + 1 - start <= U32_MAX);
2793 len = end + 1 - start;
2795 btrfs_page_clear_uptodate(fs_info, page, start, len);
2796 btrfs_page_set_error(fs_info, page, start, len);
2797 ret = err < 0 ? err : -EIO;
2798 mapping_set_error(page->mapping, ret);
2803 * after a writepage IO is done, we need to:
2804 * clear the uptodate bits on error
2805 * clear the writeback bits in the extent tree for this IO
2806 * end_page_writeback if the page has no more pending IO
2808 * Scheduling is not allowed, so the extent state tree is expected
2809 * to have one and only one object corresponding to this IO.
2811 static void end_bio_extent_writepage(struct bio *bio)
2813 int error = blk_status_to_errno(bio->bi_status);
2814 struct bio_vec *bvec;
2817 struct bvec_iter_all iter_all;
2818 bool first_bvec = true;
2820 ASSERT(!bio_flagged(bio, BIO_CLONED));
2821 bio_for_each_segment_all(bvec, bio, iter_all) {
2822 struct page *page = bvec->bv_page;
2823 struct inode *inode = page->mapping->host;
2824 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2825 const u32 sectorsize = fs_info->sectorsize;
2827 /* Our read/write should always be sector aligned. */
2828 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2830 "partial page write in btrfs with offset %u and length %u",
2831 bvec->bv_offset, bvec->bv_len);
2832 else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2834 "incomplete page write with offset %u and length %u",
2835 bvec->bv_offset, bvec->bv_len);
2837 start = page_offset(page) + bvec->bv_offset;
2838 end = start + bvec->bv_len - 1;
2841 btrfs_record_physical_zoned(inode, start, bio);
2845 end_extent_writepage(page, error, start, end);
2847 btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2854 * Record previously processed extent range
2856 * For endio_readpage_release_extent() to handle a full extent range, reducing
2857 * the extent io operations.
2859 struct processed_extent {
2860 struct btrfs_inode *inode;
2861 /* Start of the range in @inode */
2863 /* End of the range in @inode */
2869 * Try to release processed extent range
2871 * May not release the extent range right now if the current range is
2872 * contiguous to processed extent.
2874 * Will release processed extent when any of @inode, @uptodate, the range is
2875 * no longer contiguous to the processed range.
2877 * Passing @inode == NULL will force processed extent to be released.
2879 static void endio_readpage_release_extent(struct processed_extent *processed,
2880 struct btrfs_inode *inode, u64 start, u64 end,
2883 struct extent_state *cached = NULL;
2884 struct extent_io_tree *tree;
2886 /* The first extent, initialize @processed */
2887 if (!processed->inode)
2891 * Contiguous to processed extent, just uptodate the end.
2893 * Several things to notice:
2895 * - bio can be merged as long as on-disk bytenr is contiguous
2896 * This means we can have page belonging to other inodes, thus need to
2897 * check if the inode still matches.
2898 * - bvec can contain range beyond current page for multi-page bvec
2899 * Thus we need to do processed->end + 1 >= start check
2901 if (processed->inode == inode && processed->uptodate == uptodate &&
2902 processed->end + 1 >= start && end >= processed->end) {
2903 processed->end = end;
2907 tree = &processed->inode->io_tree;
2909 * Now we don't have range contiguous to the processed range, release
2910 * the processed range now.
2912 if (processed->uptodate && tree->track_uptodate)
2913 set_extent_uptodate(tree, processed->start, processed->end,
2914 &cached, GFP_ATOMIC);
2915 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2919 /* Update processed to current range */
2920 processed->inode = inode;
2921 processed->start = start;
2922 processed->end = end;
2923 processed->uptodate = uptodate;
2926 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2928 ASSERT(PageLocked(page));
2929 if (fs_info->sectorsize == PAGE_SIZE)
2932 ASSERT(PagePrivate(page));
2933 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2937 * Find extent buffer for a givne bytenr.
2939 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2942 static struct extent_buffer *find_extent_buffer_readpage(
2943 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2945 struct extent_buffer *eb;
2948 * For regular sectorsize, we can use page->private to grab extent
2951 if (fs_info->sectorsize == PAGE_SIZE) {
2952 ASSERT(PagePrivate(page) && page->private);
2953 return (struct extent_buffer *)page->private;
2956 /* For subpage case, we need to lookup buffer radix tree */
2958 eb = radix_tree_lookup(&fs_info->buffer_radix,
2959 bytenr >> fs_info->sectorsize_bits);
2966 * after a readpage IO is done, we need to:
2967 * clear the uptodate bits on error
2968 * set the uptodate bits if things worked
2969 * set the page up to date if all extents in the tree are uptodate
2970 * clear the lock bit in the extent tree
2971 * unlock the page if there are no other extents locked for it
2973 * Scheduling is not allowed, so the extent state tree is expected
2974 * to have one and only one object corresponding to this IO.
2976 static void end_bio_extent_readpage(struct bio *bio)
2978 struct bio_vec *bvec;
2979 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2980 struct extent_io_tree *tree, *failure_tree;
2981 struct processed_extent processed = { 0 };
2983 * The offset to the beginning of a bio, since one bio can never be
2984 * larger than UINT_MAX, u32 here is enough.
2989 struct bvec_iter_all iter_all;
2991 ASSERT(!bio_flagged(bio, BIO_CLONED));
2992 bio_for_each_segment_all(bvec, bio, iter_all) {
2993 bool uptodate = !bio->bi_status;
2994 struct page *page = bvec->bv_page;
2995 struct inode *inode = page->mapping->host;
2996 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2997 const u32 sectorsize = fs_info->sectorsize;
2998 unsigned int error_bitmap = (unsigned int)-1;
3003 btrfs_debug(fs_info,
3004 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3005 bio->bi_iter.bi_sector, bio->bi_status,
3006 io_bio->mirror_num);
3007 tree = &BTRFS_I(inode)->io_tree;
3008 failure_tree = &BTRFS_I(inode)->io_failure_tree;
3011 * We always issue full-sector reads, but if some block in a
3012 * page fails to read, blk_update_request() will advance
3013 * bv_offset and adjust bv_len to compensate. Print a warning
3014 * for unaligned offsets, and an error if they don't add up to
3017 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3019 "partial page read in btrfs with offset %u and length %u",
3020 bvec->bv_offset, bvec->bv_len);
3021 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3024 "incomplete page read with offset %u and length %u",
3025 bvec->bv_offset, bvec->bv_len);
3027 start = page_offset(page) + bvec->bv_offset;
3028 end = start + bvec->bv_len - 1;
3031 mirror = io_bio->mirror_num;
3032 if (likely(uptodate)) {
3033 if (is_data_inode(inode)) {
3034 error_bitmap = btrfs_verify_data_csum(io_bio,
3035 bio_offset, page, start, end);
3038 ret = btrfs_validate_metadata_buffer(io_bio,
3039 page, start, end, mirror);
3044 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3045 failure_tree, tree, start,
3047 btrfs_ino(BTRFS_I(inode)), 0);
3050 if (likely(uptodate))
3053 if (is_data_inode(inode)) {
3055 * btrfs_submit_read_repair() will handle all the good
3056 * and bad sectors, we just continue to the next bvec.
3058 submit_read_repair(inode, bio, bio_offset, page,
3059 start - page_offset(page), start,
3060 end, mirror, error_bitmap,
3061 btrfs_submit_data_bio);
3063 ASSERT(bio_offset + len > bio_offset);
3067 struct extent_buffer *eb;
3069 eb = find_extent_buffer_readpage(fs_info, page, start);
3070 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3071 eb->read_mirror = mirror;
3072 atomic_dec(&eb->io_pages);
3073 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
3075 btree_readahead_hook(eb, -EIO);
3078 if (likely(uptodate)) {
3079 loff_t i_size = i_size_read(inode);
3080 pgoff_t end_index = i_size >> PAGE_SHIFT;
3083 * Zero out the remaining part if this range straddles
3086 * Here we should only zero the range inside the bvec,
3087 * not touch anything else.
3089 * NOTE: i_size is exclusive while end is inclusive.
3091 if (page->index == end_index && i_size <= end) {
3092 u32 zero_start = max(offset_in_page(i_size),
3093 offset_in_page(start));
3095 zero_user_segment(page, zero_start,
3096 offset_in_page(end) + 1);
3099 ASSERT(bio_offset + len > bio_offset);
3102 /* Update page status and unlock */
3103 end_page_read(page, uptodate, start, len);
3104 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3105 start, end, PageUptodate(page));
3107 /* Release the last extent */
3108 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3109 btrfs_io_bio_free_csum(io_bio);
3114 * Initialize the members up to but not including 'bio'. Use after allocating a
3115 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3116 * 'bio' because use of __GFP_ZERO is not supported.
3118 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3120 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3124 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3125 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3126 * for the appropriate container_of magic
3128 struct bio *btrfs_bio_alloc(u64 first_byte)
3132 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &btrfs_bioset);
3133 bio->bi_iter.bi_sector = first_byte >> 9;
3134 btrfs_io_bio_init(btrfs_io_bio(bio));
3138 struct bio *btrfs_bio_clone(struct bio *bio)
3140 struct btrfs_io_bio *btrfs_bio;
3143 /* Bio allocation backed by a bioset does not fail */
3144 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3145 btrfs_bio = btrfs_io_bio(new);
3146 btrfs_io_bio_init(btrfs_bio);
3147 btrfs_bio->iter = bio->bi_iter;
3151 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3155 /* Bio allocation backed by a bioset does not fail */
3156 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3157 btrfs_io_bio_init(btrfs_io_bio(bio));
3161 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
3164 struct btrfs_io_bio *btrfs_bio;
3166 ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
3168 /* this will never fail when it's backed by a bioset */
3169 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3172 btrfs_bio = btrfs_io_bio(bio);
3173 btrfs_io_bio_init(btrfs_bio);
3175 bio_trim(bio, offset >> 9, size >> 9);
3176 btrfs_bio->iter = bio->bi_iter;
3181 * Attempt to add a page to bio
3183 * @bio: destination bio
3184 * @page: page to add to the bio
3185 * @disk_bytenr: offset of the new bio or to check whether we are adding
3186 * a contiguous page to the previous one
3187 * @pg_offset: starting offset in the page
3188 * @size: portion of page that we want to write
3189 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3190 * @bio_flags: flags of the current bio to see if we can merge them
3192 * Attempt to add a page to bio considering stripe alignment etc.
3194 * Return >= 0 for the number of bytes added to the bio.
3195 * Can return 0 if the current bio is already at stripe/zone boundary.
3196 * Return <0 for error.
3198 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3200 u64 disk_bytenr, unsigned int size,
3201 unsigned int pg_offset,
3202 unsigned long bio_flags)
3204 struct bio *bio = bio_ctrl->bio;
3205 u32 bio_size = bio->bi_iter.bi_size;
3207 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3212 /* The limit should be calculated when bio_ctrl->bio is allocated */
3213 ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3214 if (bio_ctrl->bio_flags != bio_flags)
3217 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED)
3218 contig = bio->bi_iter.bi_sector == sector;
3220 contig = bio_end_sector(bio) == sector;
3224 real_size = min(bio_ctrl->len_to_oe_boundary,
3225 bio_ctrl->len_to_stripe_boundary) - bio_size;
3226 real_size = min(real_size, size);
3229 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
3230 * bio will still execute its endio function on the page!
3235 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3236 ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
3238 ret = bio_add_page(bio, page, real_size, pg_offset);
3243 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3244 struct btrfs_inode *inode, u64 file_offset)
3246 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3247 struct btrfs_io_geometry geom;
3248 struct btrfs_ordered_extent *ordered;
3249 struct extent_map *em;
3250 u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3254 * Pages for compressed extent are never submitted to disk directly,
3255 * thus it has no real boundary, just set them to U32_MAX.
3257 * The split happens for real compressed bio, which happens in
3258 * btrfs_submit_compressed_read/write().
3260 if (bio_ctrl->bio_flags & EXTENT_BIO_COMPRESSED) {
3261 bio_ctrl->len_to_oe_boundary = U32_MAX;
3262 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3265 em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3268 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3270 free_extent_map(em);
3274 if (geom.len > U32_MAX)
3275 bio_ctrl->len_to_stripe_boundary = U32_MAX;
3277 bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3279 if (!btrfs_is_zoned(fs_info) ||
3280 bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3281 bio_ctrl->len_to_oe_boundary = U32_MAX;
3285 /* Ordered extent not yet created, so we're good */
3286 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
3288 bio_ctrl->len_to_oe_boundary = U32_MAX;
3292 bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3293 ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3294 btrfs_put_ordered_extent(ordered);
3298 static int alloc_new_bio(struct btrfs_inode *inode,
3299 struct btrfs_bio_ctrl *bio_ctrl,
3300 struct writeback_control *wbc,
3302 bio_end_io_t end_io_func,
3303 u64 disk_bytenr, u32 offset, u64 file_offset,
3304 unsigned long bio_flags)
3306 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3311 * For compressed page range, its disk_bytenr is always @disk_bytenr
3312 * passed in, no matter if we have added any range into previous bio.
3314 if (bio_flags & EXTENT_BIO_COMPRESSED)
3315 bio = btrfs_bio_alloc(disk_bytenr);
3317 bio = btrfs_bio_alloc(disk_bytenr + offset);
3318 bio_ctrl->bio = bio;
3319 bio_ctrl->bio_flags = bio_flags;
3320 bio->bi_end_io = end_io_func;
3321 bio->bi_private = &inode->io_tree;
3322 bio->bi_write_hint = inode->vfs_inode.i_write_hint;
3324 ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
3328 struct block_device *bdev;
3330 bdev = fs_info->fs_devices->latest_bdev;
3331 bio_set_dev(bio, bdev);
3332 wbc_init_bio(wbc, bio);
3334 if (btrfs_is_zoned(fs_info) && bio_op(bio) == REQ_OP_ZONE_APPEND) {
3335 struct btrfs_device *device;
3337 device = btrfs_zoned_get_device(fs_info, disk_bytenr,
3338 fs_info->sectorsize);
3339 if (IS_ERR(device)) {
3340 ret = PTR_ERR(device);
3344 btrfs_io_bio(bio)->device = device;
3348 bio_ctrl->bio = NULL;
3349 bio->bi_status = errno_to_blk_status(ret);
3355 * @opf: bio REQ_OP_* and REQ_* flags as one value
3356 * @wbc: optional writeback control for io accounting
3357 * @page: page to add to the bio
3358 * @disk_bytenr: logical bytenr where the write will be
3359 * @size: portion of page that we want to write to
3360 * @pg_offset: offset of the new bio or to check whether we are adding
3361 * a contiguous page to the previous one
3362 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3363 * @end_io_func: end_io callback for new bio
3364 * @mirror_num: desired mirror to read/write
3365 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3366 * @bio_flags: flags of the current bio to see if we can merge them
3368 static int submit_extent_page(unsigned int opf,
3369 struct writeback_control *wbc,
3370 struct btrfs_bio_ctrl *bio_ctrl,
3371 struct page *page, u64 disk_bytenr,
3372 size_t size, unsigned long pg_offset,
3373 bio_end_io_t end_io_func,
3375 unsigned long bio_flags,
3376 bool force_bio_submit)
3379 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3380 unsigned int cur = pg_offset;
3384 ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3385 pg_offset + size <= PAGE_SIZE);
3386 if (force_bio_submit && bio_ctrl->bio) {
3387 ret = submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->bio_flags);
3388 bio_ctrl->bio = NULL;
3393 while (cur < pg_offset + size) {
3394 u32 offset = cur - pg_offset;
3397 /* Allocate new bio if needed */
3398 if (!bio_ctrl->bio) {
3399 ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
3400 end_io_func, disk_bytenr, offset,
3401 page_offset(page) + cur,
3407 * We must go through btrfs_bio_add_page() to ensure each
3408 * page range won't cross various boundaries.
3410 if (bio_flags & EXTENT_BIO_COMPRESSED)
3411 added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
3412 size - offset, pg_offset + offset,
3415 added = btrfs_bio_add_page(bio_ctrl, page,
3416 disk_bytenr + offset, size - offset,
3417 pg_offset + offset, bio_flags);
3419 /* Metadata page range should never be split */
3420 if (!is_data_inode(&inode->vfs_inode))
3421 ASSERT(added == 0 || added == size - offset);
3423 /* At least we added some page, update the account */
3425 wbc_account_cgroup_owner(wbc, page, added);
3427 /* We have reached boundary, submit right now */
3428 if (added < size - offset) {
3429 /* The bio should contain some page(s) */
3430 ASSERT(bio_ctrl->bio->bi_iter.bi_size);
3431 ret = submit_one_bio(bio_ctrl->bio, mirror_num,
3432 bio_ctrl->bio_flags);
3433 bio_ctrl->bio = NULL;
3442 static int attach_extent_buffer_page(struct extent_buffer *eb,
3444 struct btrfs_subpage *prealloc)
3446 struct btrfs_fs_info *fs_info = eb->fs_info;
3450 * If the page is mapped to btree inode, we should hold the private
3451 * lock to prevent race.
3452 * For cloned or dummy extent buffers, their pages are not mapped and
3453 * will not race with any other ebs.
3456 lockdep_assert_held(&page->mapping->private_lock);
3458 if (fs_info->sectorsize == PAGE_SIZE) {
3459 if (!PagePrivate(page))
3460 attach_page_private(page, eb);
3462 WARN_ON(page->private != (unsigned long)eb);
3466 /* Already mapped, just free prealloc */
3467 if (PagePrivate(page)) {
3468 btrfs_free_subpage(prealloc);
3473 /* Has preallocated memory for subpage */
3474 attach_page_private(page, prealloc);
3476 /* Do new allocation to attach subpage */
3477 ret = btrfs_attach_subpage(fs_info, page,
3478 BTRFS_SUBPAGE_METADATA);
3482 int set_page_extent_mapped(struct page *page)
3484 struct btrfs_fs_info *fs_info;
3486 ASSERT(page->mapping);
3488 if (PagePrivate(page))
3491 fs_info = btrfs_sb(page->mapping->host->i_sb);
3493 if (fs_info->sectorsize < PAGE_SIZE)
3494 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3496 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3500 void clear_page_extent_mapped(struct page *page)
3502 struct btrfs_fs_info *fs_info;
3504 ASSERT(page->mapping);
3506 if (!PagePrivate(page))
3509 fs_info = btrfs_sb(page->mapping->host->i_sb);
3510 if (fs_info->sectorsize < PAGE_SIZE)
3511 return btrfs_detach_subpage(fs_info, page);
3513 detach_page_private(page);
3516 static struct extent_map *
3517 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3518 u64 start, u64 len, struct extent_map **em_cached)
3520 struct extent_map *em;
3522 if (em_cached && *em_cached) {
3524 if (extent_map_in_tree(em) && start >= em->start &&
3525 start < extent_map_end(em)) {
3526 refcount_inc(&em->refs);
3530 free_extent_map(em);
3534 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3535 if (em_cached && !IS_ERR_OR_NULL(em)) {
3537 refcount_inc(&em->refs);
3543 * basic readpage implementation. Locked extent state structs are inserted
3544 * into the tree that are removed when the IO is done (by the end_io
3546 * XXX JDM: This needs looking at to ensure proper page locking
3547 * return 0 on success, otherwise return error
3549 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3550 struct btrfs_bio_ctrl *bio_ctrl,
3551 unsigned int read_flags, u64 *prev_em_start)
3553 struct inode *inode = page->mapping->host;
3554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3555 u64 start = page_offset(page);
3556 const u64 end = start + PAGE_SIZE - 1;
3559 u64 last_byte = i_size_read(inode);
3562 struct extent_map *em;
3565 size_t pg_offset = 0;
3567 size_t blocksize = inode->i_sb->s_blocksize;
3568 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3570 ret = set_page_extent_mapped(page);
3572 unlock_extent(tree, start, end);
3573 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3578 if (!PageUptodate(page)) {
3579 if (cleancache_get_page(page) == 0) {
3580 BUG_ON(blocksize != PAGE_SIZE);
3581 unlock_extent(tree, start, end);
3587 if (page->index == last_byte >> PAGE_SHIFT) {
3588 size_t zero_offset = offset_in_page(last_byte);
3591 iosize = PAGE_SIZE - zero_offset;
3592 memzero_page(page, zero_offset, iosize);
3593 flush_dcache_page(page);
3596 begin_page_read(fs_info, page);
3597 while (cur <= end) {
3598 unsigned long this_bio_flag = 0;
3599 bool force_bio_submit = false;
3602 if (cur >= last_byte) {
3603 struct extent_state *cached = NULL;
3605 iosize = PAGE_SIZE - pg_offset;
3606 memzero_page(page, pg_offset, iosize);
3607 flush_dcache_page(page);
3608 set_extent_uptodate(tree, cur, cur + iosize - 1,
3610 unlock_extent_cached(tree, cur,
3611 cur + iosize - 1, &cached);
3612 end_page_read(page, true, cur, iosize);
3615 em = __get_extent_map(inode, page, pg_offset, cur,
3616 end - cur + 1, em_cached);
3617 if (IS_ERR_OR_NULL(em)) {
3618 unlock_extent(tree, cur, end);
3619 end_page_read(page, false, cur, end + 1 - cur);
3622 extent_offset = cur - em->start;
3623 BUG_ON(extent_map_end(em) <= cur);
3626 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3627 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3628 extent_set_compress_type(&this_bio_flag,
3632 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3633 cur_end = min(extent_map_end(em) - 1, end);
3634 iosize = ALIGN(iosize, blocksize);
3635 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3636 disk_bytenr = em->block_start;
3638 disk_bytenr = em->block_start + extent_offset;
3639 block_start = em->block_start;
3640 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3641 block_start = EXTENT_MAP_HOLE;
3644 * If we have a file range that points to a compressed extent
3645 * and it's followed by a consecutive file range that points
3646 * to the same compressed extent (possibly with a different
3647 * offset and/or length, so it either points to the whole extent
3648 * or only part of it), we must make sure we do not submit a
3649 * single bio to populate the pages for the 2 ranges because
3650 * this makes the compressed extent read zero out the pages
3651 * belonging to the 2nd range. Imagine the following scenario:
3654 * [0 - 8K] [8K - 24K]
3657 * points to extent X, points to extent X,
3658 * offset 4K, length of 8K offset 0, length 16K
3660 * [extent X, compressed length = 4K uncompressed length = 16K]
3662 * If the bio to read the compressed extent covers both ranges,
3663 * it will decompress extent X into the pages belonging to the
3664 * first range and then it will stop, zeroing out the remaining
3665 * pages that belong to the other range that points to extent X.
3666 * So here we make sure we submit 2 bios, one for the first
3667 * range and another one for the third range. Both will target
3668 * the same physical extent from disk, but we can't currently
3669 * make the compressed bio endio callback populate the pages
3670 * for both ranges because each compressed bio is tightly
3671 * coupled with a single extent map, and each range can have
3672 * an extent map with a different offset value relative to the
3673 * uncompressed data of our extent and different lengths. This
3674 * is a corner case so we prioritize correctness over
3675 * non-optimal behavior (submitting 2 bios for the same extent).
3677 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3678 prev_em_start && *prev_em_start != (u64)-1 &&
3679 *prev_em_start != em->start)
3680 force_bio_submit = true;
3683 *prev_em_start = em->start;
3685 free_extent_map(em);
3688 /* we've found a hole, just zero and go on */
3689 if (block_start == EXTENT_MAP_HOLE) {
3690 struct extent_state *cached = NULL;
3692 memzero_page(page, pg_offset, iosize);
3693 flush_dcache_page(page);
3695 set_extent_uptodate(tree, cur, cur + iosize - 1,
3697 unlock_extent_cached(tree, cur,
3698 cur + iosize - 1, &cached);
3699 end_page_read(page, true, cur, iosize);
3701 pg_offset += iosize;
3704 /* the get_extent function already copied into the page */
3705 if (test_range_bit(tree, cur, cur_end,
3706 EXTENT_UPTODATE, 1, NULL)) {
3707 unlock_extent(tree, cur, cur + iosize - 1);
3708 end_page_read(page, true, cur, iosize);
3710 pg_offset += iosize;
3713 /* we have an inline extent but it didn't get marked up
3714 * to date. Error out
3716 if (block_start == EXTENT_MAP_INLINE) {
3717 unlock_extent(tree, cur, cur + iosize - 1);
3718 end_page_read(page, false, cur, iosize);
3720 pg_offset += iosize;
3724 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3725 bio_ctrl, page, disk_bytenr, iosize,
3727 end_bio_extent_readpage, 0,
3733 unlock_extent(tree, cur, cur + iosize - 1);
3734 end_page_read(page, false, cur, iosize);
3738 pg_offset += iosize;
3744 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3746 struct extent_map **em_cached,
3747 struct btrfs_bio_ctrl *bio_ctrl,
3750 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3753 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3755 for (index = 0; index < nr_pages; index++) {
3756 btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3757 REQ_RAHEAD, prev_em_start);
3758 put_page(pages[index]);
3762 static void update_nr_written(struct writeback_control *wbc,
3763 unsigned long nr_written)
3765 wbc->nr_to_write -= nr_written;
3769 * helper for __extent_writepage, doing all of the delayed allocation setup.
3771 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3772 * to write the page (copy into inline extent). In this case the IO has
3773 * been started and the page is already unlocked.
3775 * This returns 0 if all went well (page still locked)
3776 * This returns < 0 if there were errors (page still locked)
3778 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3779 struct page *page, struct writeback_control *wbc,
3780 u64 delalloc_start, unsigned long *nr_written)
3782 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3784 u64 delalloc_to_write = 0;
3785 u64 delalloc_end = 0;
3787 int page_started = 0;
3790 while (delalloc_end < page_end) {
3791 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3795 delalloc_start = delalloc_end + 1;
3798 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3799 delalloc_end, &page_started, nr_written, wbc);
3801 btrfs_page_set_error(inode->root->fs_info, page,
3802 page_offset(page), PAGE_SIZE);
3806 * delalloc_end is already one less than the total length, so
3807 * we don't subtract one from PAGE_SIZE
3809 delalloc_to_write += (delalloc_end - delalloc_start +
3810 PAGE_SIZE) >> PAGE_SHIFT;
3811 delalloc_start = delalloc_end + 1;
3813 if (wbc->nr_to_write < delalloc_to_write) {
3816 if (delalloc_to_write < thresh * 2)
3817 thresh = delalloc_to_write;
3818 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3822 /* did the fill delalloc function already unlock and start
3827 * we've unlocked the page, so we can't update
3828 * the mapping's writeback index, just update
3831 wbc->nr_to_write -= *nr_written;
3839 * Find the first byte we need to write.
3841 * For subpage, one page can contain several sectors, and
3842 * __extent_writepage_io() will just grab all extent maps in the page
3843 * range and try to submit all non-inline/non-compressed extents.
3845 * This is a big problem for subpage, we shouldn't re-submit already written
3847 * This function will lookup subpage dirty bit to find which range we really
3850 * Return the next dirty range in [@start, @end).
3851 * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
3853 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
3854 struct page *page, u64 *start, u64 *end)
3856 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
3857 struct btrfs_subpage_info *spi = fs_info->subpage_info;
3858 u64 orig_start = *start;
3859 /* Declare as unsigned long so we can use bitmap ops */
3860 unsigned long flags;
3861 int range_start_bit;
3865 * For regular sector size == page size case, since one page only
3866 * contains one sector, we return the page offset directly.
3868 if (fs_info->sectorsize == PAGE_SIZE) {
3869 *start = page_offset(page);
3870 *end = page_offset(page) + PAGE_SIZE;
3874 range_start_bit = spi->dirty_offset +
3875 (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
3877 /* We should have the page locked, but just in case */
3878 spin_lock_irqsave(&subpage->lock, flags);
3879 bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
3880 spi->dirty_offset + spi->bitmap_nr_bits);
3881 spin_unlock_irqrestore(&subpage->lock, flags);
3883 range_start_bit -= spi->dirty_offset;
3884 range_end_bit -= spi->dirty_offset;
3886 *start = page_offset(page) + range_start_bit * fs_info->sectorsize;
3887 *end = page_offset(page) + range_end_bit * fs_info->sectorsize;
3891 * helper for __extent_writepage. This calls the writepage start hooks,
3892 * and does the loop to map the page into extents and bios.
3894 * We return 1 if the IO is started and the page is unlocked,
3895 * 0 if all went well (page still locked)
3896 * < 0 if there were errors (page still locked)
3898 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3900 struct writeback_control *wbc,
3901 struct extent_page_data *epd,
3903 unsigned long nr_written,
3906 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3907 u64 cur = page_offset(page);
3908 u64 end = cur + PAGE_SIZE - 1;
3911 struct extent_map *em;
3914 u32 opf = REQ_OP_WRITE;
3915 const unsigned int write_flags = wbc_to_write_flags(wbc);
3918 ret = btrfs_writepage_cow_fixup(page);
3920 /* Fixup worker will requeue */
3921 redirty_page_for_writepage(wbc, page);
3922 update_nr_written(wbc, nr_written);
3928 * we don't want to touch the inode after unlocking the page,
3929 * so we update the mapping writeback index now
3931 update_nr_written(wbc, nr_written + 1);
3933 while (cur <= end) {
3936 u64 dirty_range_start = cur;
3937 u64 dirty_range_end;
3940 if (cur >= i_size) {
3941 btrfs_writepage_endio_finish_ordered(inode, page, cur,
3944 * This range is beyond i_size, thus we don't need to
3945 * bother writing back.
3946 * But we still need to clear the dirty subpage bit, or
3947 * the next time the page gets dirtied, we will try to
3948 * writeback the sectors with subpage dirty bits,
3949 * causing writeback without ordered extent.
3951 btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
3955 find_next_dirty_byte(fs_info, page, &dirty_range_start,
3957 if (cur < dirty_range_start) {
3958 cur = dirty_range_start;
3962 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3963 if (IS_ERR_OR_NULL(em)) {
3964 btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
3965 ret = PTR_ERR_OR_ZERO(em);
3969 extent_offset = cur - em->start;
3970 em_end = extent_map_end(em);
3971 ASSERT(cur <= em_end);
3973 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3974 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3975 block_start = em->block_start;
3976 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3977 disk_bytenr = em->block_start + extent_offset;
3980 * Note that em_end from extent_map_end() and dirty_range_end from
3981 * find_next_dirty_byte() are all exclusive
3983 iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
3985 if (btrfs_use_zone_append(inode, em->block_start))
3986 opf = REQ_OP_ZONE_APPEND;
3988 free_extent_map(em);
3992 * compressed and inline extents are written through other
3995 if (compressed || block_start == EXTENT_MAP_HOLE ||
3996 block_start == EXTENT_MAP_INLINE) {
4000 btrfs_writepage_endio_finish_ordered(inode,
4001 page, cur, cur + iosize - 1, true);
4002 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4007 btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
4008 if (!PageWriteback(page)) {
4009 btrfs_err(inode->root->fs_info,
4010 "page %lu not writeback, cur %llu end %llu",
4011 page->index, cur, end);
4015 * Although the PageDirty bit is cleared before entering this
4016 * function, subpage dirty bit is not cleared.
4017 * So clear subpage dirty bit here so next time we won't submit
4018 * page for range already written to disk.
4020 btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4022 ret = submit_extent_page(opf | write_flags, wbc,
4023 &epd->bio_ctrl, page,
4024 disk_bytenr, iosize,
4025 cur - page_offset(page),
4026 end_bio_extent_writepage,
4029 btrfs_page_set_error(fs_info, page, cur, iosize);
4030 if (PageWriteback(page))
4031 btrfs_page_clear_writeback(fs_info, page, cur,
4039 * If we finish without problem, we should not only clear page dirty,
4040 * but also empty subpage dirty bits
4043 btrfs_page_assert_not_dirty(fs_info, page);
4049 * the writepage semantics are similar to regular writepage. extent
4050 * records are inserted to lock ranges in the tree, and as dirty areas
4051 * are found, they are marked writeback. Then the lock bits are removed
4052 * and the end_io handler clears the writeback ranges
4054 * Return 0 if everything goes well.
4055 * Return <0 for error.
4057 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
4058 struct extent_page_data *epd)
4060 struct inode *inode = page->mapping->host;
4061 u64 start = page_offset(page);
4062 u64 page_end = start + PAGE_SIZE - 1;
4066 loff_t i_size = i_size_read(inode);
4067 unsigned long end_index = i_size >> PAGE_SHIFT;
4068 unsigned long nr_written = 0;
4070 trace___extent_writepage(page, inode, wbc);
4072 WARN_ON(!PageLocked(page));
4074 btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
4075 page_offset(page), PAGE_SIZE);
4077 pg_offset = offset_in_page(i_size);
4078 if (page->index > end_index ||
4079 (page->index == end_index && !pg_offset)) {
4080 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
4085 if (page->index == end_index) {
4086 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
4087 flush_dcache_page(page);
4090 ret = set_page_extent_mapped(page);
4096 if (!epd->extent_locked) {
4097 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
4105 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
4112 /* make sure the mapping tag for page dirty gets cleared */
4113 set_page_writeback(page);
4114 end_page_writeback(page);
4117 * Here we used to have a check for PageError() and then set @ret and
4118 * call end_extent_writepage().
4120 * But in fact setting @ret here will cause different error paths
4121 * between subpage and regular sectorsize.
4123 * For regular page size, we never submit current page, but only add
4124 * current page to current bio.
4125 * The bio submission can only happen in next page.
4126 * Thus if we hit the PageError() branch, @ret is already set to
4127 * non-zero value and will not get updated for regular sectorsize.
4129 * But for subpage case, it's possible we submit part of current page,
4130 * thus can get PageError() set by submitted bio of the same page,
4131 * while our @ret is still 0.
4133 * So here we unify the behavior and don't set @ret.
4134 * Error can still be properly passed to higher layer as page will
4135 * be set error, here we just don't handle the IO failure.
4137 * NOTE: This is just a hotfix for subpage.
4138 * The root fix will be properly ending ordered extent when we hit
4139 * an error during writeback.
4141 * But that needs a bigger refactoring, as we not only need to grab the
4142 * submitted OE, but also need to know exactly at which bytenr we hit
4144 * Currently the full page based __extent_writepage_io() is not
4147 if (PageError(page))
4148 end_extent_writepage(page, ret, start, page_end);
4154 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
4156 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
4157 TASK_UNINTERRUPTIBLE);
4160 static void end_extent_buffer_writeback(struct extent_buffer *eb)
4162 if (test_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags))
4163 btrfs_zone_finish_endio(eb->fs_info, eb->start, eb->len);
4165 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4166 smp_mb__after_atomic();
4167 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
4171 * Lock extent buffer status and pages for writeback.
4173 * May try to flush write bio if we can't get the lock.
4175 * Return 0 if the extent buffer doesn't need to be submitted.
4176 * (E.g. the extent buffer is not dirty)
4177 * Return >0 is the extent buffer is submitted to bio.
4178 * Return <0 if something went wrong, no page is locked.
4180 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4181 struct extent_page_data *epd)
4183 struct btrfs_fs_info *fs_info = eb->fs_info;
4184 int i, num_pages, failed_page_nr;
4188 if (!btrfs_try_tree_write_lock(eb)) {
4189 ret = flush_write_bio(epd);
4193 btrfs_tree_lock(eb);
4196 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4197 btrfs_tree_unlock(eb);
4201 ret = flush_write_bio(epd);
4207 wait_on_extent_buffer_writeback(eb);
4208 btrfs_tree_lock(eb);
4209 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4211 btrfs_tree_unlock(eb);
4216 * We need to do this to prevent races in people who check if the eb is
4217 * under IO since we can end up having no IO bits set for a short period
4220 spin_lock(&eb->refs_lock);
4221 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4222 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4223 spin_unlock(&eb->refs_lock);
4224 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4225 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4227 fs_info->dirty_metadata_batch);
4230 spin_unlock(&eb->refs_lock);
4233 btrfs_tree_unlock(eb);
4236 * Either we don't need to submit any tree block, or we're submitting
4238 * Subpage metadata doesn't use page locking at all, so we can skip
4241 if (!ret || fs_info->sectorsize < PAGE_SIZE)
4244 num_pages = num_extent_pages(eb);
4245 for (i = 0; i < num_pages; i++) {
4246 struct page *p = eb->pages[i];
4248 if (!trylock_page(p)) {
4252 err = flush_write_bio(epd);
4266 /* Unlock already locked pages */
4267 for (i = 0; i < failed_page_nr; i++)
4268 unlock_page(eb->pages[i]);
4270 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
4271 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
4272 * be made and undo everything done before.
4274 btrfs_tree_lock(eb);
4275 spin_lock(&eb->refs_lock);
4276 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4277 end_extent_buffer_writeback(eb);
4278 spin_unlock(&eb->refs_lock);
4279 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4280 fs_info->dirty_metadata_batch);
4281 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4282 btrfs_tree_unlock(eb);
4286 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4288 struct btrfs_fs_info *fs_info = eb->fs_info;
4290 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4291 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4295 * If we error out, we should add back the dirty_metadata_bytes
4296 * to make it consistent.
4298 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4299 eb->len, fs_info->dirty_metadata_batch);
4302 * If writeback for a btree extent that doesn't belong to a log tree
4303 * failed, increment the counter transaction->eb_write_errors.
4304 * We do this because while the transaction is running and before it's
4305 * committing (when we call filemap_fdata[write|wait]_range against
4306 * the btree inode), we might have
4307 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4308 * returns an error or an error happens during writeback, when we're
4309 * committing the transaction we wouldn't know about it, since the pages
4310 * can be no longer dirty nor marked anymore for writeback (if a
4311 * subsequent modification to the extent buffer didn't happen before the
4312 * transaction commit), which makes filemap_fdata[write|wait]_range not
4313 * able to find the pages tagged with SetPageError at transaction
4314 * commit time. So if this happens we must abort the transaction,
4315 * otherwise we commit a super block with btree roots that point to
4316 * btree nodes/leafs whose content on disk is invalid - either garbage
4317 * or the content of some node/leaf from a past generation that got
4318 * cowed or deleted and is no longer valid.
4320 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4321 * not be enough - we need to distinguish between log tree extents vs
4322 * non-log tree extents, and the next filemap_fdatawait_range() call
4323 * will catch and clear such errors in the mapping - and that call might
4324 * be from a log sync and not from a transaction commit. Also, checking
4325 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4326 * not done and would not be reliable - the eb might have been released
4327 * from memory and reading it back again means that flag would not be
4328 * set (since it's a runtime flag, not persisted on disk).
4330 * Using the flags below in the btree inode also makes us achieve the
4331 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4332 * writeback for all dirty pages and before filemap_fdatawait_range()
4333 * is called, the writeback for all dirty pages had already finished
4334 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4335 * filemap_fdatawait_range() would return success, as it could not know
4336 * that writeback errors happened (the pages were no longer tagged for
4339 switch (eb->log_index) {
4341 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4344 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4347 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4350 BUG(); /* unexpected, logic error */
4355 * The endio specific version which won't touch any unsafe spinlock in endio
4358 static struct extent_buffer *find_extent_buffer_nolock(
4359 struct btrfs_fs_info *fs_info, u64 start)
4361 struct extent_buffer *eb;
4364 eb = radix_tree_lookup(&fs_info->buffer_radix,
4365 start >> fs_info->sectorsize_bits);
4366 if (eb && atomic_inc_not_zero(&eb->refs)) {
4375 * The endio function for subpage extent buffer write.
4377 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4378 * after all extent buffers in the page has finished their writeback.
4380 static void end_bio_subpage_eb_writepage(struct bio *bio)
4382 struct btrfs_fs_info *fs_info;
4383 struct bio_vec *bvec;
4384 struct bvec_iter_all iter_all;
4386 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4387 ASSERT(fs_info->sectorsize < PAGE_SIZE);
4389 ASSERT(!bio_flagged(bio, BIO_CLONED));
4390 bio_for_each_segment_all(bvec, bio, iter_all) {
4391 struct page *page = bvec->bv_page;
4392 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4393 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4394 u64 cur_bytenr = bvec_start;
4396 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4398 /* Iterate through all extent buffers in the range */
4399 while (cur_bytenr <= bvec_end) {
4400 struct extent_buffer *eb;
4404 * Here we can't use find_extent_buffer(), as it may
4405 * try to lock eb->refs_lock, which is not safe in endio
4408 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4411 cur_bytenr = eb->start + eb->len;
4413 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4414 done = atomic_dec_and_test(&eb->io_pages);
4417 if (bio->bi_status ||
4418 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4419 ClearPageUptodate(page);
4420 set_btree_ioerr(page, eb);
4423 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4425 end_extent_buffer_writeback(eb);
4427 * free_extent_buffer() will grab spinlock which is not
4428 * safe in endio context. Thus here we manually dec
4431 atomic_dec(&eb->refs);
4437 static void end_bio_extent_buffer_writepage(struct bio *bio)
4439 struct bio_vec *bvec;
4440 struct extent_buffer *eb;
4442 struct bvec_iter_all iter_all;
4444 ASSERT(!bio_flagged(bio, BIO_CLONED));
4445 bio_for_each_segment_all(bvec, bio, iter_all) {
4446 struct page *page = bvec->bv_page;
4448 eb = (struct extent_buffer *)page->private;
4450 done = atomic_dec_and_test(&eb->io_pages);
4452 if (bio->bi_status ||
4453 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4454 ClearPageUptodate(page);
4455 set_btree_ioerr(page, eb);
4458 end_page_writeback(page);
4463 end_extent_buffer_writeback(eb);
4469 static void prepare_eb_write(struct extent_buffer *eb)
4472 unsigned long start;
4475 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4476 atomic_set(&eb->io_pages, num_extent_pages(eb));
4478 /* Set btree blocks beyond nritems with 0 to avoid stale content */
4479 nritems = btrfs_header_nritems(eb);
4480 if (btrfs_header_level(eb) > 0) {
4481 end = btrfs_node_key_ptr_offset(nritems);
4482 memzero_extent_buffer(eb, end, eb->len - end);
4486 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4488 start = btrfs_item_nr_offset(nritems);
4489 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4490 memzero_extent_buffer(eb, start, end - start);
4495 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4496 * Page locking is only utilized at minimum to keep the VMM code happy.
4498 static int write_one_subpage_eb(struct extent_buffer *eb,
4499 struct writeback_control *wbc,
4500 struct extent_page_data *epd)
4502 struct btrfs_fs_info *fs_info = eb->fs_info;
4503 struct page *page = eb->pages[0];
4504 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4505 bool no_dirty_ebs = false;
4508 prepare_eb_write(eb);
4510 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4512 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4514 /* Check if this is the last dirty bit to update nr_written */
4515 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4516 eb->start, eb->len);
4518 clear_page_dirty_for_io(page);
4520 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4521 &epd->bio_ctrl, page, eb->start, eb->len,
4522 eb->start - page_offset(page),
4523 end_bio_subpage_eb_writepage, 0, 0, false);
4525 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4526 set_btree_ioerr(page, eb);
4529 if (atomic_dec_and_test(&eb->io_pages))
4530 end_extent_buffer_writeback(eb);
4535 * Submission finished without problem, if no range of the page is
4536 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4539 update_nr_written(wbc, 1);
4543 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4544 struct writeback_control *wbc,
4545 struct extent_page_data *epd)
4547 u64 disk_bytenr = eb->start;
4549 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4552 prepare_eb_write(eb);
4554 num_pages = num_extent_pages(eb);
4555 for (i = 0; i < num_pages; i++) {
4556 struct page *p = eb->pages[i];
4558 clear_page_dirty_for_io(p);
4559 set_page_writeback(p);
4560 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4561 &epd->bio_ctrl, p, disk_bytenr,
4563 end_bio_extent_buffer_writepage,
4566 set_btree_ioerr(p, eb);
4567 if (PageWriteback(p))
4568 end_page_writeback(p);
4569 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4570 end_extent_buffer_writeback(eb);
4574 disk_bytenr += PAGE_SIZE;
4575 update_nr_written(wbc, 1);
4579 if (unlikely(ret)) {
4580 for (; i < num_pages; i++) {
4581 struct page *p = eb->pages[i];
4582 clear_page_dirty_for_io(p);
4591 * Submit one subpage btree page.
4593 * The main difference to submit_eb_page() is:
4595 * For subpage, we don't rely on page locking at all.
4598 * We only flush bio if we may be unable to fit current extent buffers into
4601 * Return >=0 for the number of submitted extent buffers.
4602 * Return <0 for fatal error.
4604 static int submit_eb_subpage(struct page *page,
4605 struct writeback_control *wbc,
4606 struct extent_page_data *epd)
4608 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4610 u64 page_start = page_offset(page);
4612 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4615 /* Lock and write each dirty extent buffers in the range */
4616 while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
4617 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4618 struct extent_buffer *eb;
4619 unsigned long flags;
4623 * Take private lock to ensure the subpage won't be detached
4626 spin_lock(&page->mapping->private_lock);
4627 if (!PagePrivate(page)) {
4628 spin_unlock(&page->mapping->private_lock);
4631 spin_lock_irqsave(&subpage->lock, flags);
4632 if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
4633 subpage->bitmaps)) {
4634 spin_unlock_irqrestore(&subpage->lock, flags);
4635 spin_unlock(&page->mapping->private_lock);
4640 start = page_start + bit_start * fs_info->sectorsize;
4641 bit_start += sectors_per_node;
4644 * Here we just want to grab the eb without touching extra
4645 * spin locks, so call find_extent_buffer_nolock().
4647 eb = find_extent_buffer_nolock(fs_info, start);
4648 spin_unlock_irqrestore(&subpage->lock, flags);
4649 spin_unlock(&page->mapping->private_lock);
4652 * The eb has already reached 0 refs thus find_extent_buffer()
4653 * doesn't return it. We don't need to write back such eb
4659 ret = lock_extent_buffer_for_io(eb, epd);
4661 free_extent_buffer(eb);
4665 free_extent_buffer(eb);
4668 ret = write_one_subpage_eb(eb, wbc, epd);
4669 free_extent_buffer(eb);
4677 /* We hit error, end bio for the submitted extent buffers */
4678 end_write_bio(epd, ret);
4683 * Submit all page(s) of one extent buffer.
4685 * @page: the page of one extent buffer
4686 * @eb_context: to determine if we need to submit this page, if current page
4687 * belongs to this eb, we don't need to submit
4689 * The caller should pass each page in their bytenr order, and here we use
4690 * @eb_context to determine if we have submitted pages of one extent buffer.
4692 * If we have, we just skip until we hit a new page that doesn't belong to
4693 * current @eb_context.
4695 * If not, we submit all the page(s) of the extent buffer.
4697 * Return >0 if we have submitted the extent buffer successfully.
4698 * Return 0 if we don't need to submit the page, as it's already submitted by
4700 * Return <0 for fatal error.
4702 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4703 struct extent_page_data *epd,
4704 struct extent_buffer **eb_context)
4706 struct address_space *mapping = page->mapping;
4707 struct btrfs_block_group *cache = NULL;
4708 struct extent_buffer *eb;
4711 if (!PagePrivate(page))
4714 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
4715 return submit_eb_subpage(page, wbc, epd);
4717 spin_lock(&mapping->private_lock);
4718 if (!PagePrivate(page)) {
4719 spin_unlock(&mapping->private_lock);
4723 eb = (struct extent_buffer *)page->private;
4726 * Shouldn't happen and normally this would be a BUG_ON but no point
4727 * crashing the machine for something we can survive anyway.
4730 spin_unlock(&mapping->private_lock);
4734 if (eb == *eb_context) {
4735 spin_unlock(&mapping->private_lock);
4738 ret = atomic_inc_not_zero(&eb->refs);
4739 spin_unlock(&mapping->private_lock);
4743 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4745 * If for_sync, this hole will be filled with
4746 * trasnsaction commit.
4748 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4752 free_extent_buffer(eb);
4758 ret = lock_extent_buffer_for_io(eb, epd);
4760 btrfs_revert_meta_write_pointer(cache, eb);
4762 btrfs_put_block_group(cache);
4763 free_extent_buffer(eb);
4767 /* Impiles write in zoned mode */
4768 btrfs_put_block_group(cache);
4769 /* Mark the last eb in a block group */
4770 if (cache->seq_zone && eb->start + eb->len == cache->zone_capacity)
4771 set_bit(EXTENT_BUFFER_ZONE_FINISH, &eb->bflags);
4773 ret = write_one_eb(eb, wbc, epd);
4774 free_extent_buffer(eb);
4780 int btree_write_cache_pages(struct address_space *mapping,
4781 struct writeback_control *wbc)
4783 struct extent_buffer *eb_context = NULL;
4784 struct extent_page_data epd = {
4787 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4789 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4792 int nr_to_write_done = 0;
4793 struct pagevec pvec;
4796 pgoff_t end; /* Inclusive */
4800 pagevec_init(&pvec);
4801 if (wbc->range_cyclic) {
4802 index = mapping->writeback_index; /* Start from prev offset */
4805 * Start from the beginning does not need to cycle over the
4806 * range, mark it as scanned.
4808 scanned = (index == 0);
4810 index = wbc->range_start >> PAGE_SHIFT;
4811 end = wbc->range_end >> PAGE_SHIFT;
4814 if (wbc->sync_mode == WB_SYNC_ALL)
4815 tag = PAGECACHE_TAG_TOWRITE;
4817 tag = PAGECACHE_TAG_DIRTY;
4818 btrfs_zoned_meta_io_lock(fs_info);
4820 if (wbc->sync_mode == WB_SYNC_ALL)
4821 tag_pages_for_writeback(mapping, index, end);
4822 while (!done && !nr_to_write_done && (index <= end) &&
4823 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4827 for (i = 0; i < nr_pages; i++) {
4828 struct page *page = pvec.pages[i];
4830 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4839 * the filesystem may choose to bump up nr_to_write.
4840 * We have to make sure to honor the new nr_to_write
4843 nr_to_write_done = wbc->nr_to_write <= 0;
4845 pagevec_release(&pvec);
4848 if (!scanned && !done) {
4850 * We hit the last page and there is more work to be done: wrap
4851 * back to the start of the file
4858 end_write_bio(&epd, ret);
4862 * If something went wrong, don't allow any metadata write bio to be
4865 * This would prevent use-after-free if we had dirty pages not
4866 * cleaned up, which can still happen by fuzzed images.
4869 * Allowing existing tree block to be allocated for other trees.
4871 * - Log tree operations
4872 * Exiting tree blocks get allocated to log tree, bumps its
4873 * generation, then get cleaned in tree re-balance.
4874 * Such tree block will not be written back, since it's clean,
4875 * thus no WRITTEN flag set.
4876 * And after log writes back, this tree block is not traced by
4877 * any dirty extent_io_tree.
4879 * - Offending tree block gets re-dirtied from its original owner
4880 * Since it has bumped generation, no WRITTEN flag, it can be
4881 * reused without COWing. This tree block will not be traced
4882 * by btrfs_transaction::dirty_pages.
4884 * Now such dirty tree block will not be cleaned by any dirty
4885 * extent io tree. Thus we don't want to submit such wild eb
4886 * if the fs already has error.
4888 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4889 ret = flush_write_bio(&epd);
4892 end_write_bio(&epd, ret);
4895 btrfs_zoned_meta_io_unlock(fs_info);
4900 * Walk the list of dirty pages of the given address space and write all of them.
4902 * @mapping: address space structure to write
4903 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4904 * @epd: holds context for the write, namely the bio
4906 * If a page is already under I/O, write_cache_pages() skips it, even
4907 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4908 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4909 * and msync() need to guarantee that all the data which was dirty at the time
4910 * the call was made get new I/O started against them. If wbc->sync_mode is
4911 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4912 * existing IO to complete.
4914 static int extent_write_cache_pages(struct address_space *mapping,
4915 struct writeback_control *wbc,
4916 struct extent_page_data *epd)
4918 struct inode *inode = mapping->host;
4921 int nr_to_write_done = 0;
4922 struct pagevec pvec;
4925 pgoff_t end; /* Inclusive */
4927 int range_whole = 0;
4932 * We have to hold onto the inode so that ordered extents can do their
4933 * work when the IO finishes. The alternative to this is failing to add
4934 * an ordered extent if the igrab() fails there and that is a huge pain
4935 * to deal with, so instead just hold onto the inode throughout the
4936 * writepages operation. If it fails here we are freeing up the inode
4937 * anyway and we'd rather not waste our time writing out stuff that is
4938 * going to be truncated anyway.
4943 pagevec_init(&pvec);
4944 if (wbc->range_cyclic) {
4945 index = mapping->writeback_index; /* Start from prev offset */
4948 * Start from the beginning does not need to cycle over the
4949 * range, mark it as scanned.
4951 scanned = (index == 0);
4953 index = wbc->range_start >> PAGE_SHIFT;
4954 end = wbc->range_end >> PAGE_SHIFT;
4955 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4961 * We do the tagged writepage as long as the snapshot flush bit is set
4962 * and we are the first one who do the filemap_flush() on this inode.
4964 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4965 * not race in and drop the bit.
4967 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4968 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4969 &BTRFS_I(inode)->runtime_flags))
4970 wbc->tagged_writepages = 1;
4972 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4973 tag = PAGECACHE_TAG_TOWRITE;
4975 tag = PAGECACHE_TAG_DIRTY;
4977 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4978 tag_pages_for_writeback(mapping, index, end);
4980 while (!done && !nr_to_write_done && (index <= end) &&
4981 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4982 &index, end, tag))) {
4985 for (i = 0; i < nr_pages; i++) {
4986 struct page *page = pvec.pages[i];
4988 done_index = page->index + 1;
4990 * At this point we hold neither the i_pages lock nor
4991 * the page lock: the page may be truncated or
4992 * invalidated (changing page->mapping to NULL),
4993 * or even swizzled back from swapper_space to
4994 * tmpfs file mapping
4996 if (!trylock_page(page)) {
4997 ret = flush_write_bio(epd);
5002 if (unlikely(page->mapping != mapping)) {
5007 if (wbc->sync_mode != WB_SYNC_NONE) {
5008 if (PageWriteback(page)) {
5009 ret = flush_write_bio(epd);
5012 wait_on_page_writeback(page);
5015 if (PageWriteback(page) ||
5016 !clear_page_dirty_for_io(page)) {
5021 ret = __extent_writepage(page, wbc, epd);
5028 * the filesystem may choose to bump up nr_to_write.
5029 * We have to make sure to honor the new nr_to_write
5032 nr_to_write_done = wbc->nr_to_write <= 0;
5034 pagevec_release(&pvec);
5037 if (!scanned && !done) {
5039 * We hit the last page and there is more work to be done: wrap
5040 * back to the start of the file
5046 * If we're looping we could run into a page that is locked by a
5047 * writer and that writer could be waiting on writeback for a
5048 * page in our current bio, and thus deadlock, so flush the
5051 ret = flush_write_bio(epd);
5056 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
5057 mapping->writeback_index = done_index;
5059 btrfs_add_delayed_iput(inode);
5063 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
5066 struct extent_page_data epd = {
5069 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5072 ret = __extent_writepage(page, wbc, &epd);
5075 end_write_bio(&epd, ret);
5079 ret = flush_write_bio(&epd);
5084 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
5088 struct address_space *mapping = inode->i_mapping;
5090 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
5093 struct extent_page_data epd = {
5096 .sync_io = mode == WB_SYNC_ALL,
5098 struct writeback_control wbc_writepages = {
5100 .nr_to_write = nr_pages * 2,
5101 .range_start = start,
5102 .range_end = end + 1,
5103 /* We're called from an async helper function */
5104 .punt_to_cgroup = 1,
5105 .no_cgroup_owner = 1,
5108 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
5109 while (start <= end) {
5110 page = find_get_page(mapping, start >> PAGE_SHIFT);
5111 if (clear_page_dirty_for_io(page))
5112 ret = __extent_writepage(page, &wbc_writepages, &epd);
5114 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode),
5115 page, start, start + PAGE_SIZE - 1, true);
5124 ret = flush_write_bio(&epd);
5126 end_write_bio(&epd, ret);
5128 wbc_detach_inode(&wbc_writepages);
5132 int extent_writepages(struct address_space *mapping,
5133 struct writeback_control *wbc)
5136 struct extent_page_data epd = {
5139 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
5142 ret = extent_write_cache_pages(mapping, wbc, &epd);
5145 end_write_bio(&epd, ret);
5148 ret = flush_write_bio(&epd);
5152 void extent_readahead(struct readahead_control *rac)
5154 struct btrfs_bio_ctrl bio_ctrl = { 0 };
5155 struct page *pagepool[16];
5156 struct extent_map *em_cached = NULL;
5157 u64 prev_em_start = (u64)-1;
5160 while ((nr = readahead_page_batch(rac, pagepool))) {
5161 u64 contig_start = readahead_pos(rac);
5162 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
5164 contiguous_readpages(pagepool, nr, contig_start, contig_end,
5165 &em_cached, &bio_ctrl, &prev_em_start);
5169 free_extent_map(em_cached);
5172 if (submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags))
5178 * basic invalidatepage code, this waits on any locked or writeback
5179 * ranges corresponding to the page, and then deletes any extent state
5180 * records from the tree
5182 int extent_invalidatepage(struct extent_io_tree *tree,
5183 struct page *page, unsigned long offset)
5185 struct extent_state *cached_state = NULL;
5186 u64 start = page_offset(page);
5187 u64 end = start + PAGE_SIZE - 1;
5188 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
5190 /* This function is only called for the btree inode */
5191 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5193 start += ALIGN(offset, blocksize);
5197 lock_extent_bits(tree, start, end, &cached_state);
5198 wait_on_page_writeback(page);
5201 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5202 * so here we only need to unlock the extent range to free any
5203 * existing extent state.
5205 unlock_extent_cached(tree, start, end, &cached_state);
5210 * a helper for releasepage, this tests for areas of the page that
5211 * are locked or under IO and drops the related state bits if it is safe
5214 static int try_release_extent_state(struct extent_io_tree *tree,
5215 struct page *page, gfp_t mask)
5217 u64 start = page_offset(page);
5218 u64 end = start + PAGE_SIZE - 1;
5221 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5225 * At this point we can safely clear everything except the
5226 * locked bit, the nodatasum bit and the delalloc new bit.
5227 * The delalloc new bit will be cleared by ordered extent
5230 ret = __clear_extent_bit(tree, start, end,
5231 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5232 0, 0, NULL, mask, NULL);
5234 /* if clear_extent_bit failed for enomem reasons,
5235 * we can't allow the release to continue.
5246 * a helper for releasepage. As long as there are no locked extents
5247 * in the range corresponding to the page, both state records and extent
5248 * map records are removed
5250 int try_release_extent_mapping(struct page *page, gfp_t mask)
5252 struct extent_map *em;
5253 u64 start = page_offset(page);
5254 u64 end = start + PAGE_SIZE - 1;
5255 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5256 struct extent_io_tree *tree = &btrfs_inode->io_tree;
5257 struct extent_map_tree *map = &btrfs_inode->extent_tree;
5259 if (gfpflags_allow_blocking(mask) &&
5260 page->mapping->host->i_size > SZ_16M) {
5262 while (start <= end) {
5263 struct btrfs_fs_info *fs_info;
5266 len = end - start + 1;
5267 write_lock(&map->lock);
5268 em = lookup_extent_mapping(map, start, len);
5270 write_unlock(&map->lock);
5273 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5274 em->start != start) {
5275 write_unlock(&map->lock);
5276 free_extent_map(em);
5279 if (test_range_bit(tree, em->start,
5280 extent_map_end(em) - 1,
5281 EXTENT_LOCKED, 0, NULL))
5284 * If it's not in the list of modified extents, used
5285 * by a fast fsync, we can remove it. If it's being
5286 * logged we can safely remove it since fsync took an
5287 * extra reference on the em.
5289 if (list_empty(&em->list) ||
5290 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5293 * If it's in the list of modified extents, remove it
5294 * only if its generation is older then the current one,
5295 * in which case we don't need it for a fast fsync.
5296 * Otherwise don't remove it, we could be racing with an
5297 * ongoing fast fsync that could miss the new extent.
5299 fs_info = btrfs_inode->root->fs_info;
5300 spin_lock(&fs_info->trans_lock);
5301 cur_gen = fs_info->generation;
5302 spin_unlock(&fs_info->trans_lock);
5303 if (em->generation >= cur_gen)
5307 * We only remove extent maps that are not in the list of
5308 * modified extents or that are in the list but with a
5309 * generation lower then the current generation, so there
5310 * is no need to set the full fsync flag on the inode (it
5311 * hurts the fsync performance for workloads with a data
5312 * size that exceeds or is close to the system's memory).
5314 remove_extent_mapping(map, em);
5315 /* once for the rb tree */
5316 free_extent_map(em);
5318 start = extent_map_end(em);
5319 write_unlock(&map->lock);
5322 free_extent_map(em);
5324 cond_resched(); /* Allow large-extent preemption. */
5327 return try_release_extent_state(tree, page, mask);
5331 * helper function for fiemap, which doesn't want to see any holes.
5332 * This maps until we find something past 'last'
5334 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5335 u64 offset, u64 last)
5337 u64 sectorsize = btrfs_inode_sectorsize(inode);
5338 struct extent_map *em;
5345 len = last - offset;
5348 len = ALIGN(len, sectorsize);
5349 em = btrfs_get_extent_fiemap(inode, offset, len);
5350 if (IS_ERR_OR_NULL(em))
5353 /* if this isn't a hole return it */
5354 if (em->block_start != EXTENT_MAP_HOLE)
5357 /* this is a hole, advance to the next extent */
5358 offset = extent_map_end(em);
5359 free_extent_map(em);
5367 * To cache previous fiemap extent
5369 * Will be used for merging fiemap extent
5371 struct fiemap_cache {
5380 * Helper to submit fiemap extent.
5382 * Will try to merge current fiemap extent specified by @offset, @phys,
5383 * @len and @flags with cached one.
5384 * And only when we fails to merge, cached one will be submitted as
5387 * Return value is the same as fiemap_fill_next_extent().
5389 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5390 struct fiemap_cache *cache,
5391 u64 offset, u64 phys, u64 len, u32 flags)
5399 * Sanity check, extent_fiemap() should have ensured that new
5400 * fiemap extent won't overlap with cached one.
5403 * NOTE: Physical address can overlap, due to compression
5405 if (cache->offset + cache->len > offset) {
5411 * Only merges fiemap extents if
5412 * 1) Their logical addresses are continuous
5414 * 2) Their physical addresses are continuous
5415 * So truly compressed (physical size smaller than logical size)
5416 * extents won't get merged with each other
5418 * 3) Share same flags except FIEMAP_EXTENT_LAST
5419 * So regular extent won't get merged with prealloc extent
5421 if (cache->offset + cache->len == offset &&
5422 cache->phys + cache->len == phys &&
5423 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5424 (flags & ~FIEMAP_EXTENT_LAST)) {
5426 cache->flags |= flags;
5427 goto try_submit_last;
5430 /* Not mergeable, need to submit cached one */
5431 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5432 cache->len, cache->flags);
5433 cache->cached = false;
5437 cache->cached = true;
5438 cache->offset = offset;
5441 cache->flags = flags;
5443 if (cache->flags & FIEMAP_EXTENT_LAST) {
5444 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5445 cache->phys, cache->len, cache->flags);
5446 cache->cached = false;
5452 * Emit last fiemap cache
5454 * The last fiemap cache may still be cached in the following case:
5456 * |<- Fiemap range ->|
5457 * |<------------ First extent ----------->|
5459 * In this case, the first extent range will be cached but not emitted.
5460 * So we must emit it before ending extent_fiemap().
5462 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5463 struct fiemap_cache *cache)
5470 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5471 cache->len, cache->flags);
5472 cache->cached = false;
5478 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5483 u64 max = start + len;
5487 u64 last_for_get_extent = 0;
5489 u64 isize = i_size_read(&inode->vfs_inode);
5490 struct btrfs_key found_key;
5491 struct extent_map *em = NULL;
5492 struct extent_state *cached_state = NULL;
5493 struct btrfs_path *path;
5494 struct btrfs_root *root = inode->root;
5495 struct fiemap_cache cache = { 0 };
5496 struct ulist *roots;
5497 struct ulist *tmp_ulist;
5506 path = btrfs_alloc_path();
5510 roots = ulist_alloc(GFP_KERNEL);
5511 tmp_ulist = ulist_alloc(GFP_KERNEL);
5512 if (!roots || !tmp_ulist) {
5514 goto out_free_ulist;
5518 * We can't initialize that to 'start' as this could miss extents due
5519 * to extent item merging
5522 start = round_down(start, btrfs_inode_sectorsize(inode));
5523 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5526 * lookup the last file extent. We're not using i_size here
5527 * because there might be preallocation past i_size
5529 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5532 goto out_free_ulist;
5540 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5541 found_type = found_key.type;
5543 /* No extents, but there might be delalloc bits */
5544 if (found_key.objectid != btrfs_ino(inode) ||
5545 found_type != BTRFS_EXTENT_DATA_KEY) {
5546 /* have to trust i_size as the end */
5548 last_for_get_extent = isize;
5551 * remember the start of the last extent. There are a
5552 * bunch of different factors that go into the length of the
5553 * extent, so its much less complex to remember where it started
5555 last = found_key.offset;
5556 last_for_get_extent = last + 1;
5558 btrfs_release_path(path);
5561 * we might have some extents allocated but more delalloc past those
5562 * extents. so, we trust isize unless the start of the last extent is
5567 last_for_get_extent = isize;
5570 lock_extent_bits(&inode->io_tree, start, start + len - 1,
5573 em = get_extent_skip_holes(inode, start, last_for_get_extent);
5582 u64 offset_in_extent = 0;
5584 /* break if the extent we found is outside the range */
5585 if (em->start >= max || extent_map_end(em) < off)
5589 * get_extent may return an extent that starts before our
5590 * requested range. We have to make sure the ranges
5591 * we return to fiemap always move forward and don't
5592 * overlap, so adjust the offsets here
5594 em_start = max(em->start, off);
5597 * record the offset from the start of the extent
5598 * for adjusting the disk offset below. Only do this if the
5599 * extent isn't compressed since our in ram offset may be past
5600 * what we have actually allocated on disk.
5602 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5603 offset_in_extent = em_start - em->start;
5604 em_end = extent_map_end(em);
5605 em_len = em_end - em_start;
5607 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5608 disko = em->block_start + offset_in_extent;
5613 * bump off for our next call to get_extent
5615 off = extent_map_end(em);
5619 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5621 flags |= FIEMAP_EXTENT_LAST;
5622 } else if (em->block_start == EXTENT_MAP_INLINE) {
5623 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5624 FIEMAP_EXTENT_NOT_ALIGNED);
5625 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
5626 flags |= (FIEMAP_EXTENT_DELALLOC |
5627 FIEMAP_EXTENT_UNKNOWN);
5628 } else if (fieinfo->fi_extents_max) {
5629 u64 bytenr = em->block_start -
5630 (em->start - em->orig_start);
5633 * As btrfs supports shared space, this information
5634 * can be exported to userspace tools via
5635 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5636 * then we're just getting a count and we can skip the
5639 ret = btrfs_check_shared(root, btrfs_ino(inode),
5640 bytenr, roots, tmp_ulist);
5644 flags |= FIEMAP_EXTENT_SHARED;
5647 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5648 flags |= FIEMAP_EXTENT_ENCODED;
5649 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5650 flags |= FIEMAP_EXTENT_UNWRITTEN;
5652 free_extent_map(em);
5654 if ((em_start >= last) || em_len == (u64)-1 ||
5655 (last == (u64)-1 && isize <= em_end)) {
5656 flags |= FIEMAP_EXTENT_LAST;
5660 /* now scan forward to see if this is really the last extent. */
5661 em = get_extent_skip_holes(inode, off, last_for_get_extent);
5667 flags |= FIEMAP_EXTENT_LAST;
5670 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5680 ret = emit_last_fiemap_cache(fieinfo, &cache);
5681 free_extent_map(em);
5683 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5687 btrfs_free_path(path);
5689 ulist_free(tmp_ulist);
5693 static void __free_extent_buffer(struct extent_buffer *eb)
5695 kmem_cache_free(extent_buffer_cache, eb);
5698 int extent_buffer_under_io(const struct extent_buffer *eb)
5700 return (atomic_read(&eb->io_pages) ||
5701 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5702 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5705 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5707 struct btrfs_subpage *subpage;
5709 lockdep_assert_held(&page->mapping->private_lock);
5711 if (PagePrivate(page)) {
5712 subpage = (struct btrfs_subpage *)page->private;
5713 if (atomic_read(&subpage->eb_refs))
5716 * Even there is no eb refs here, we may still have
5717 * end_page_read() call relying on page::private.
5719 if (atomic_read(&subpage->readers))
5725 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5727 struct btrfs_fs_info *fs_info = eb->fs_info;
5728 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5731 * For mapped eb, we're going to change the page private, which should
5732 * be done under the private_lock.
5735 spin_lock(&page->mapping->private_lock);
5737 if (!PagePrivate(page)) {
5739 spin_unlock(&page->mapping->private_lock);
5743 if (fs_info->sectorsize == PAGE_SIZE) {
5745 * We do this since we'll remove the pages after we've
5746 * removed the eb from the radix tree, so we could race
5747 * and have this page now attached to the new eb. So
5748 * only clear page_private if it's still connected to
5751 if (PagePrivate(page) &&
5752 page->private == (unsigned long)eb) {
5753 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5754 BUG_ON(PageDirty(page));
5755 BUG_ON(PageWriteback(page));
5757 * We need to make sure we haven't be attached
5760 detach_page_private(page);
5763 spin_unlock(&page->mapping->private_lock);
5768 * For subpage, we can have dummy eb with page private. In this case,
5769 * we can directly detach the private as such page is only attached to
5770 * one dummy eb, no sharing.
5773 btrfs_detach_subpage(fs_info, page);
5777 btrfs_page_dec_eb_refs(fs_info, page);
5780 * We can only detach the page private if there are no other ebs in the
5781 * page range and no unfinished IO.
5783 if (!page_range_has_eb(fs_info, page))
5784 btrfs_detach_subpage(fs_info, page);
5786 spin_unlock(&page->mapping->private_lock);
5789 /* Release all pages attached to the extent buffer */
5790 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5795 ASSERT(!extent_buffer_under_io(eb));
5797 num_pages = num_extent_pages(eb);
5798 for (i = 0; i < num_pages; i++) {
5799 struct page *page = eb->pages[i];
5804 detach_extent_buffer_page(eb, page);
5806 /* One for when we allocated the page */
5812 * Helper for releasing the extent buffer.
5814 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5816 btrfs_release_extent_buffer_pages(eb);
5817 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5818 __free_extent_buffer(eb);
5821 static struct extent_buffer *
5822 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5825 struct extent_buffer *eb = NULL;
5827 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5830 eb->fs_info = fs_info;
5832 init_rwsem(&eb->lock);
5834 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5835 &fs_info->allocated_ebs);
5836 INIT_LIST_HEAD(&eb->release_list);
5838 spin_lock_init(&eb->refs_lock);
5839 atomic_set(&eb->refs, 1);
5840 atomic_set(&eb->io_pages, 0);
5842 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5847 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5851 struct extent_buffer *new;
5852 int num_pages = num_extent_pages(src);
5854 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5859 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5860 * btrfs_release_extent_buffer() have different behavior for
5861 * UNMAPPED subpage extent buffer.
5863 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5865 for (i = 0; i < num_pages; i++) {
5868 p = alloc_page(GFP_NOFS);
5870 btrfs_release_extent_buffer(new);
5873 ret = attach_extent_buffer_page(new, p, NULL);
5876 btrfs_release_extent_buffer(new);
5879 WARN_ON(PageDirty(p));
5881 copy_page(page_address(p), page_address(src->pages[i]));
5883 set_extent_buffer_uptodate(new);
5888 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5889 u64 start, unsigned long len)
5891 struct extent_buffer *eb;
5895 eb = __alloc_extent_buffer(fs_info, start, len);
5899 num_pages = num_extent_pages(eb);
5900 for (i = 0; i < num_pages; i++) {
5903 eb->pages[i] = alloc_page(GFP_NOFS);
5906 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5910 set_extent_buffer_uptodate(eb);
5911 btrfs_set_header_nritems(eb, 0);
5912 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5916 for (; i > 0; i--) {
5917 detach_extent_buffer_page(eb, eb->pages[i - 1]);
5918 __free_page(eb->pages[i - 1]);
5920 __free_extent_buffer(eb);
5924 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5927 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5930 static void check_buffer_tree_ref(struct extent_buffer *eb)
5934 * The TREE_REF bit is first set when the extent_buffer is added
5935 * to the radix tree. It is also reset, if unset, when a new reference
5936 * is created by find_extent_buffer.
5938 * It is only cleared in two cases: freeing the last non-tree
5939 * reference to the extent_buffer when its STALE bit is set or
5940 * calling releasepage when the tree reference is the only reference.
5942 * In both cases, care is taken to ensure that the extent_buffer's
5943 * pages are not under io. However, releasepage can be concurrently
5944 * called with creating new references, which is prone to race
5945 * conditions between the calls to check_buffer_tree_ref in those
5946 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5948 * The actual lifetime of the extent_buffer in the radix tree is
5949 * adequately protected by the refcount, but the TREE_REF bit and
5950 * its corresponding reference are not. To protect against this
5951 * class of races, we call check_buffer_tree_ref from the codepaths
5952 * which trigger io after they set eb->io_pages. Note that once io is
5953 * initiated, TREE_REF can no longer be cleared, so that is the
5954 * moment at which any such race is best fixed.
5956 refs = atomic_read(&eb->refs);
5957 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5960 spin_lock(&eb->refs_lock);
5961 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5962 atomic_inc(&eb->refs);
5963 spin_unlock(&eb->refs_lock);
5966 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5967 struct page *accessed)
5971 check_buffer_tree_ref(eb);
5973 num_pages = num_extent_pages(eb);
5974 for (i = 0; i < num_pages; i++) {
5975 struct page *p = eb->pages[i];
5978 mark_page_accessed(p);
5982 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5985 struct extent_buffer *eb;
5987 eb = find_extent_buffer_nolock(fs_info, start);
5991 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
5992 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
5993 * another task running free_extent_buffer() might have seen that flag
5994 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
5995 * writeback flags not set) and it's still in the tree (flag
5996 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
5997 * decrementing the extent buffer's reference count twice. So here we
5998 * could race and increment the eb's reference count, clear its stale
5999 * flag, mark it as dirty and drop our reference before the other task
6000 * finishes executing free_extent_buffer, which would later result in
6001 * an attempt to free an extent buffer that is dirty.
6003 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
6004 spin_lock(&eb->refs_lock);
6005 spin_unlock(&eb->refs_lock);
6007 mark_extent_buffer_accessed(eb, NULL);
6011 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6012 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
6015 struct extent_buffer *eb, *exists = NULL;
6018 eb = find_extent_buffer(fs_info, start);
6021 eb = alloc_dummy_extent_buffer(fs_info, start);
6023 return ERR_PTR(-ENOMEM);
6024 eb->fs_info = fs_info;
6026 ret = radix_tree_preload(GFP_NOFS);
6028 exists = ERR_PTR(ret);
6031 spin_lock(&fs_info->buffer_lock);
6032 ret = radix_tree_insert(&fs_info->buffer_radix,
6033 start >> fs_info->sectorsize_bits, eb);
6034 spin_unlock(&fs_info->buffer_lock);
6035 radix_tree_preload_end();
6036 if (ret == -EEXIST) {
6037 exists = find_extent_buffer(fs_info, start);
6043 check_buffer_tree_ref(eb);
6044 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6048 btrfs_release_extent_buffer(eb);
6053 static struct extent_buffer *grab_extent_buffer(
6054 struct btrfs_fs_info *fs_info, struct page *page)
6056 struct extent_buffer *exists;
6059 * For subpage case, we completely rely on radix tree to ensure we
6060 * don't try to insert two ebs for the same bytenr. So here we always
6061 * return NULL and just continue.
6063 if (fs_info->sectorsize < PAGE_SIZE)
6066 /* Page not yet attached to an extent buffer */
6067 if (!PagePrivate(page))
6071 * We could have already allocated an eb for this page and attached one
6072 * so lets see if we can get a ref on the existing eb, and if we can we
6073 * know it's good and we can just return that one, else we know we can
6074 * just overwrite page->private.
6076 exists = (struct extent_buffer *)page->private;
6077 if (atomic_inc_not_zero(&exists->refs))
6080 WARN_ON(PageDirty(page));
6081 detach_page_private(page);
6085 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
6086 u64 start, u64 owner_root, int level)
6088 unsigned long len = fs_info->nodesize;
6091 unsigned long index = start >> PAGE_SHIFT;
6092 struct extent_buffer *eb;
6093 struct extent_buffer *exists = NULL;
6095 struct address_space *mapping = fs_info->btree_inode->i_mapping;
6099 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
6100 btrfs_err(fs_info, "bad tree block start %llu", start);
6101 return ERR_PTR(-EINVAL);
6104 #if BITS_PER_LONG == 32
6105 if (start >= MAX_LFS_FILESIZE) {
6106 btrfs_err_rl(fs_info,
6107 "extent buffer %llu is beyond 32bit page cache limit", start);
6108 btrfs_err_32bit_limit(fs_info);
6109 return ERR_PTR(-EOVERFLOW);
6111 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6112 btrfs_warn_32bit_limit(fs_info);
6115 if (fs_info->sectorsize < PAGE_SIZE &&
6116 offset_in_page(start) + len > PAGE_SIZE) {
6118 "tree block crosses page boundary, start %llu nodesize %lu",
6120 return ERR_PTR(-EINVAL);
6123 eb = find_extent_buffer(fs_info, start);
6127 eb = __alloc_extent_buffer(fs_info, start, len);
6129 return ERR_PTR(-ENOMEM);
6130 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
6132 num_pages = num_extent_pages(eb);
6133 for (i = 0; i < num_pages; i++, index++) {
6134 struct btrfs_subpage *prealloc = NULL;
6136 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
6138 exists = ERR_PTR(-ENOMEM);
6143 * Preallocate page->private for subpage case, so that we won't
6144 * allocate memory with private_lock hold. The memory will be
6145 * freed by attach_extent_buffer_page() or freed manually if
6148 * Although we have ensured one subpage eb can only have one
6149 * page, but it may change in the future for 16K page size
6150 * support, so we still preallocate the memory in the loop.
6152 if (fs_info->sectorsize < PAGE_SIZE) {
6153 prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
6154 if (IS_ERR(prealloc)) {
6155 ret = PTR_ERR(prealloc);
6158 exists = ERR_PTR(ret);
6163 spin_lock(&mapping->private_lock);
6164 exists = grab_extent_buffer(fs_info, p);
6166 spin_unlock(&mapping->private_lock);
6169 mark_extent_buffer_accessed(exists, p);
6170 btrfs_free_subpage(prealloc);
6173 /* Should not fail, as we have preallocated the memory */
6174 ret = attach_extent_buffer_page(eb, p, prealloc);
6177 * To inform we have extra eb under allocation, so that
6178 * detach_extent_buffer_page() won't release the page private
6179 * when the eb hasn't yet been inserted into radix tree.
6181 * The ref will be decreased when the eb released the page, in
6182 * detach_extent_buffer_page().
6183 * Thus needs no special handling in error path.
6185 btrfs_page_inc_eb_refs(fs_info, p);
6186 spin_unlock(&mapping->private_lock);
6188 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6190 if (!PageUptodate(p))
6194 * We can't unlock the pages just yet since the extent buffer
6195 * hasn't been properly inserted in the radix tree, this
6196 * opens a race with btree_releasepage which can free a page
6197 * while we are still filling in all pages for the buffer and
6202 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6204 ret = radix_tree_preload(GFP_NOFS);
6206 exists = ERR_PTR(ret);
6210 spin_lock(&fs_info->buffer_lock);
6211 ret = radix_tree_insert(&fs_info->buffer_radix,
6212 start >> fs_info->sectorsize_bits, eb);
6213 spin_unlock(&fs_info->buffer_lock);
6214 radix_tree_preload_end();
6215 if (ret == -EEXIST) {
6216 exists = find_extent_buffer(fs_info, start);
6222 /* add one reference for the tree */
6223 check_buffer_tree_ref(eb);
6224 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6227 * Now it's safe to unlock the pages because any calls to
6228 * btree_releasepage will correctly detect that a page belongs to a
6229 * live buffer and won't free them prematurely.
6231 for (i = 0; i < num_pages; i++)
6232 unlock_page(eb->pages[i]);
6236 WARN_ON(!atomic_dec_and_test(&eb->refs));
6237 for (i = 0; i < num_pages; i++) {
6239 unlock_page(eb->pages[i]);
6242 btrfs_release_extent_buffer(eb);
6246 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6248 struct extent_buffer *eb =
6249 container_of(head, struct extent_buffer, rcu_head);
6251 __free_extent_buffer(eb);
6254 static int release_extent_buffer(struct extent_buffer *eb)
6255 __releases(&eb->refs_lock)
6257 lockdep_assert_held(&eb->refs_lock);
6259 WARN_ON(atomic_read(&eb->refs) == 0);
6260 if (atomic_dec_and_test(&eb->refs)) {
6261 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6262 struct btrfs_fs_info *fs_info = eb->fs_info;
6264 spin_unlock(&eb->refs_lock);
6266 spin_lock(&fs_info->buffer_lock);
6267 radix_tree_delete(&fs_info->buffer_radix,
6268 eb->start >> fs_info->sectorsize_bits);
6269 spin_unlock(&fs_info->buffer_lock);
6271 spin_unlock(&eb->refs_lock);
6274 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6275 /* Should be safe to release our pages at this point */
6276 btrfs_release_extent_buffer_pages(eb);
6277 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6278 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6279 __free_extent_buffer(eb);
6283 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6286 spin_unlock(&eb->refs_lock);
6291 void free_extent_buffer(struct extent_buffer *eb)
6299 refs = atomic_read(&eb->refs);
6300 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6301 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6304 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6309 spin_lock(&eb->refs_lock);
6310 if (atomic_read(&eb->refs) == 2 &&
6311 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6312 !extent_buffer_under_io(eb) &&
6313 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6314 atomic_dec(&eb->refs);
6317 * I know this is terrible, but it's temporary until we stop tracking
6318 * the uptodate bits and such for the extent buffers.
6320 release_extent_buffer(eb);
6323 void free_extent_buffer_stale(struct extent_buffer *eb)
6328 spin_lock(&eb->refs_lock);
6329 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6331 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6332 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6333 atomic_dec(&eb->refs);
6334 release_extent_buffer(eb);
6337 static void btree_clear_page_dirty(struct page *page)
6339 ASSERT(PageDirty(page));
6340 ASSERT(PageLocked(page));
6341 clear_page_dirty_for_io(page);
6342 xa_lock_irq(&page->mapping->i_pages);
6343 if (!PageDirty(page))
6344 __xa_clear_mark(&page->mapping->i_pages,
6345 page_index(page), PAGECACHE_TAG_DIRTY);
6346 xa_unlock_irq(&page->mapping->i_pages);
6349 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6351 struct btrfs_fs_info *fs_info = eb->fs_info;
6352 struct page *page = eb->pages[0];
6355 /* btree_clear_page_dirty() needs page locked */
6357 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6360 btree_clear_page_dirty(page);
6362 WARN_ON(atomic_read(&eb->refs) == 0);
6365 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6371 if (eb->fs_info->sectorsize < PAGE_SIZE)
6372 return clear_subpage_extent_buffer_dirty(eb);
6374 num_pages = num_extent_pages(eb);
6376 for (i = 0; i < num_pages; i++) {
6377 page = eb->pages[i];
6378 if (!PageDirty(page))
6381 btree_clear_page_dirty(page);
6382 ClearPageError(page);
6385 WARN_ON(atomic_read(&eb->refs) == 0);
6388 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6394 check_buffer_tree_ref(eb);
6396 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6398 num_pages = num_extent_pages(eb);
6399 WARN_ON(atomic_read(&eb->refs) == 0);
6400 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6403 bool subpage = eb->fs_info->sectorsize < PAGE_SIZE;
6406 * For subpage case, we can have other extent buffers in the
6407 * same page, and in clear_subpage_extent_buffer_dirty() we
6408 * have to clear page dirty without subpage lock held.
6409 * This can cause race where our page gets dirty cleared after
6412 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6413 * its page for other reasons, we can use page lock to prevent
6417 lock_page(eb->pages[0]);
6418 for (i = 0; i < num_pages; i++)
6419 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6420 eb->start, eb->len);
6422 unlock_page(eb->pages[0]);
6424 #ifdef CONFIG_BTRFS_DEBUG
6425 for (i = 0; i < num_pages; i++)
6426 ASSERT(PageDirty(eb->pages[i]));
6432 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6434 struct btrfs_fs_info *fs_info = eb->fs_info;
6439 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6440 num_pages = num_extent_pages(eb);
6441 for (i = 0; i < num_pages; i++) {
6442 page = eb->pages[i];
6444 btrfs_page_clear_uptodate(fs_info, page,
6445 eb->start, eb->len);
6449 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6451 struct btrfs_fs_info *fs_info = eb->fs_info;
6456 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6457 num_pages = num_extent_pages(eb);
6458 for (i = 0; i < num_pages; i++) {
6459 page = eb->pages[i];
6460 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
6464 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6467 struct btrfs_fs_info *fs_info = eb->fs_info;
6468 struct extent_io_tree *io_tree;
6469 struct page *page = eb->pages[0];
6470 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6473 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6474 ASSERT(PagePrivate(page));
6475 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6477 if (wait == WAIT_NONE) {
6478 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6481 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6487 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6488 PageUptodate(page) ||
6489 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6490 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6491 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6495 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6496 eb->read_mirror = 0;
6497 atomic_set(&eb->io_pages, 1);
6498 check_buffer_tree_ref(eb);
6499 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6501 btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
6502 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6503 page, eb->start, eb->len,
6504 eb->start - page_offset(page),
6505 end_bio_extent_readpage, mirror_num, 0,
6509 * In the endio function, if we hit something wrong we will
6510 * increase the io_pages, so here we need to decrease it for
6513 atomic_dec(&eb->io_pages);
6518 tmp = submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6519 bio_ctrl.bio = NULL;
6523 if (ret || wait != WAIT_COMPLETE)
6526 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6527 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6532 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6538 int locked_pages = 0;
6539 int all_uptodate = 1;
6541 unsigned long num_reads = 0;
6542 struct btrfs_bio_ctrl bio_ctrl = { 0 };
6544 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6547 if (eb->fs_info->sectorsize < PAGE_SIZE)
6548 return read_extent_buffer_subpage(eb, wait, mirror_num);
6550 num_pages = num_extent_pages(eb);
6551 for (i = 0; i < num_pages; i++) {
6552 page = eb->pages[i];
6553 if (wait == WAIT_NONE) {
6555 * WAIT_NONE is only utilized by readahead. If we can't
6556 * acquire the lock atomically it means either the eb
6557 * is being read out or under modification.
6558 * Either way the eb will be or has been cached,
6559 * readahead can exit safely.
6561 if (!trylock_page(page))
6569 * We need to firstly lock all pages to make sure that
6570 * the uptodate bit of our pages won't be affected by
6571 * clear_extent_buffer_uptodate().
6573 for (i = 0; i < num_pages; i++) {
6574 page = eb->pages[i];
6575 if (!PageUptodate(page)) {
6582 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6586 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6587 eb->read_mirror = 0;
6588 atomic_set(&eb->io_pages, num_reads);
6590 * It is possible for releasepage to clear the TREE_REF bit before we
6591 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6593 check_buffer_tree_ref(eb);
6594 for (i = 0; i < num_pages; i++) {
6595 page = eb->pages[i];
6597 if (!PageUptodate(page)) {
6599 atomic_dec(&eb->io_pages);
6604 ClearPageError(page);
6605 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6606 &bio_ctrl, page, page_offset(page),
6607 PAGE_SIZE, 0, end_bio_extent_readpage,
6608 mirror_num, 0, false);
6611 * We failed to submit the bio so it's the
6612 * caller's responsibility to perform cleanup
6613 * i.e unlock page/set error bit.
6618 atomic_dec(&eb->io_pages);
6626 err = submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.bio_flags);
6627 bio_ctrl.bio = NULL;
6632 if (ret || wait != WAIT_COMPLETE)
6635 for (i = 0; i < num_pages; i++) {
6636 page = eb->pages[i];
6637 wait_on_page_locked(page);
6638 if (!PageUptodate(page))
6645 while (locked_pages > 0) {
6647 page = eb->pages[locked_pages];
6653 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6656 btrfs_warn(eb->fs_info,
6657 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6658 eb->start, eb->len, start, len);
6659 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6665 * Check if the [start, start + len) range is valid before reading/writing
6667 * NOTE: @start and @len are offset inside the eb, not logical address.
6669 * Caller should not touch the dst/src memory if this function returns error.
6671 static inline int check_eb_range(const struct extent_buffer *eb,
6672 unsigned long start, unsigned long len)
6674 unsigned long offset;
6676 /* start, start + len should not go beyond eb->len nor overflow */
6677 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6678 return report_eb_range(eb, start, len);
6683 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6684 unsigned long start, unsigned long len)
6690 char *dst = (char *)dstv;
6691 unsigned long i = get_eb_page_index(start);
6693 if (check_eb_range(eb, start, len))
6696 offset = get_eb_offset_in_page(eb, start);
6699 page = eb->pages[i];
6701 cur = min(len, (PAGE_SIZE - offset));
6702 kaddr = page_address(page);
6703 memcpy(dst, kaddr + offset, cur);
6712 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6714 unsigned long start, unsigned long len)
6720 char __user *dst = (char __user *)dstv;
6721 unsigned long i = get_eb_page_index(start);
6724 WARN_ON(start > eb->len);
6725 WARN_ON(start + len > eb->start + eb->len);
6727 offset = get_eb_offset_in_page(eb, start);
6730 page = eb->pages[i];
6732 cur = min(len, (PAGE_SIZE - offset));
6733 kaddr = page_address(page);
6734 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6748 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6749 unsigned long start, unsigned long len)
6755 char *ptr = (char *)ptrv;
6756 unsigned long i = get_eb_page_index(start);
6759 if (check_eb_range(eb, start, len))
6762 offset = get_eb_offset_in_page(eb, start);
6765 page = eb->pages[i];
6767 cur = min(len, (PAGE_SIZE - offset));
6769 kaddr = page_address(page);
6770 ret = memcmp(ptr, kaddr + offset, cur);
6783 * Check that the extent buffer is uptodate.
6785 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6786 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6788 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6791 struct btrfs_fs_info *fs_info = eb->fs_info;
6793 if (fs_info->sectorsize < PAGE_SIZE) {
6796 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6797 eb->start, eb->len);
6800 WARN_ON(!PageUptodate(page));
6804 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6809 assert_eb_page_uptodate(eb, eb->pages[0]);
6810 kaddr = page_address(eb->pages[0]) +
6811 get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6813 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6816 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6820 assert_eb_page_uptodate(eb, eb->pages[0]);
6821 kaddr = page_address(eb->pages[0]) +
6822 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6823 memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6826 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6827 unsigned long start, unsigned long len)
6833 char *src = (char *)srcv;
6834 unsigned long i = get_eb_page_index(start);
6836 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6838 if (check_eb_range(eb, start, len))
6841 offset = get_eb_offset_in_page(eb, start);
6844 page = eb->pages[i];
6845 assert_eb_page_uptodate(eb, page);
6847 cur = min(len, PAGE_SIZE - offset);
6848 kaddr = page_address(page);
6849 memcpy(kaddr + offset, src, cur);
6858 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
6865 unsigned long i = get_eb_page_index(start);
6867 if (check_eb_range(eb, start, len))
6870 offset = get_eb_offset_in_page(eb, start);
6873 page = eb->pages[i];
6874 assert_eb_page_uptodate(eb, page);
6876 cur = min(len, PAGE_SIZE - offset);
6877 kaddr = page_address(page);
6878 memset(kaddr + offset, 0, cur);
6886 void copy_extent_buffer_full(const struct extent_buffer *dst,
6887 const struct extent_buffer *src)
6892 ASSERT(dst->len == src->len);
6894 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6895 num_pages = num_extent_pages(dst);
6896 for (i = 0; i < num_pages; i++)
6897 copy_page(page_address(dst->pages[i]),
6898 page_address(src->pages[i]));
6900 size_t src_offset = get_eb_offset_in_page(src, 0);
6901 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6903 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6904 memcpy(page_address(dst->pages[0]) + dst_offset,
6905 page_address(src->pages[0]) + src_offset,
6910 void copy_extent_buffer(const struct extent_buffer *dst,
6911 const struct extent_buffer *src,
6912 unsigned long dst_offset, unsigned long src_offset,
6915 u64 dst_len = dst->len;
6920 unsigned long i = get_eb_page_index(dst_offset);
6922 if (check_eb_range(dst, dst_offset, len) ||
6923 check_eb_range(src, src_offset, len))
6926 WARN_ON(src->len != dst_len);
6928 offset = get_eb_offset_in_page(dst, dst_offset);
6931 page = dst->pages[i];
6932 assert_eb_page_uptodate(dst, page);
6934 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
6936 kaddr = page_address(page);
6937 read_extent_buffer(src, kaddr + offset, src_offset, cur);
6947 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6949 * @eb: the extent buffer
6950 * @start: offset of the bitmap item in the extent buffer
6952 * @page_index: return index of the page in the extent buffer that contains the
6954 * @page_offset: return offset into the page given by page_index
6956 * This helper hides the ugliness of finding the byte in an extent buffer which
6957 * contains a given bit.
6959 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
6960 unsigned long start, unsigned long nr,
6961 unsigned long *page_index,
6962 size_t *page_offset)
6964 size_t byte_offset = BIT_BYTE(nr);
6968 * The byte we want is the offset of the extent buffer + the offset of
6969 * the bitmap item in the extent buffer + the offset of the byte in the
6972 offset = start + offset_in_page(eb->start) + byte_offset;
6974 *page_index = offset >> PAGE_SHIFT;
6975 *page_offset = offset_in_page(offset);
6979 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6980 * @eb: the extent buffer
6981 * @start: offset of the bitmap item in the extent buffer
6982 * @nr: bit number to test
6984 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
6992 eb_bitmap_offset(eb, start, nr, &i, &offset);
6993 page = eb->pages[i];
6994 assert_eb_page_uptodate(eb, page);
6995 kaddr = page_address(page);
6996 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
7000 * extent_buffer_bitmap_set - set an area of a bitmap
7001 * @eb: the extent buffer
7002 * @start: offset of the bitmap item in the extent buffer
7003 * @pos: bit number of the first bit
7004 * @len: number of bits to set
7006 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
7007 unsigned long pos, unsigned long len)
7013 const unsigned int size = pos + len;
7014 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7015 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
7017 eb_bitmap_offset(eb, start, pos, &i, &offset);
7018 page = eb->pages[i];
7019 assert_eb_page_uptodate(eb, page);
7020 kaddr = page_address(page);
7022 while (len >= bits_to_set) {
7023 kaddr[offset] |= mask_to_set;
7025 bits_to_set = BITS_PER_BYTE;
7027 if (++offset >= PAGE_SIZE && len > 0) {
7029 page = eb->pages[++i];
7030 assert_eb_page_uptodate(eb, page);
7031 kaddr = page_address(page);
7035 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
7036 kaddr[offset] |= mask_to_set;
7042 * extent_buffer_bitmap_clear - clear an area of a bitmap
7043 * @eb: the extent buffer
7044 * @start: offset of the bitmap item in the extent buffer
7045 * @pos: bit number of the first bit
7046 * @len: number of bits to clear
7048 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
7049 unsigned long start, unsigned long pos,
7056 const unsigned int size = pos + len;
7057 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7058 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
7060 eb_bitmap_offset(eb, start, pos, &i, &offset);
7061 page = eb->pages[i];
7062 assert_eb_page_uptodate(eb, page);
7063 kaddr = page_address(page);
7065 while (len >= bits_to_clear) {
7066 kaddr[offset] &= ~mask_to_clear;
7067 len -= bits_to_clear;
7068 bits_to_clear = BITS_PER_BYTE;
7070 if (++offset >= PAGE_SIZE && len > 0) {
7072 page = eb->pages[++i];
7073 assert_eb_page_uptodate(eb, page);
7074 kaddr = page_address(page);
7078 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
7079 kaddr[offset] &= ~mask_to_clear;
7083 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
7085 unsigned long distance = (src > dst) ? src - dst : dst - src;
7086 return distance < len;
7089 static void copy_pages(struct page *dst_page, struct page *src_page,
7090 unsigned long dst_off, unsigned long src_off,
7093 char *dst_kaddr = page_address(dst_page);
7095 int must_memmove = 0;
7097 if (dst_page != src_page) {
7098 src_kaddr = page_address(src_page);
7100 src_kaddr = dst_kaddr;
7101 if (areas_overlap(src_off, dst_off, len))
7106 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
7108 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
7111 void memcpy_extent_buffer(const struct extent_buffer *dst,
7112 unsigned long dst_offset, unsigned long src_offset,
7116 size_t dst_off_in_page;
7117 size_t src_off_in_page;
7118 unsigned long dst_i;
7119 unsigned long src_i;
7121 if (check_eb_range(dst, dst_offset, len) ||
7122 check_eb_range(dst, src_offset, len))
7126 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
7127 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
7129 dst_i = get_eb_page_index(dst_offset);
7130 src_i = get_eb_page_index(src_offset);
7132 cur = min(len, (unsigned long)(PAGE_SIZE -
7134 cur = min_t(unsigned long, cur,
7135 (unsigned long)(PAGE_SIZE - dst_off_in_page));
7137 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7138 dst_off_in_page, src_off_in_page, cur);
7146 void memmove_extent_buffer(const struct extent_buffer *dst,
7147 unsigned long dst_offset, unsigned long src_offset,
7151 size_t dst_off_in_page;
7152 size_t src_off_in_page;
7153 unsigned long dst_end = dst_offset + len - 1;
7154 unsigned long src_end = src_offset + len - 1;
7155 unsigned long dst_i;
7156 unsigned long src_i;
7158 if (check_eb_range(dst, dst_offset, len) ||
7159 check_eb_range(dst, src_offset, len))
7161 if (dst_offset < src_offset) {
7162 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
7166 dst_i = get_eb_page_index(dst_end);
7167 src_i = get_eb_page_index(src_end);
7169 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
7170 src_off_in_page = get_eb_offset_in_page(dst, src_end);
7172 cur = min_t(unsigned long, len, src_off_in_page + 1);
7173 cur = min(cur, dst_off_in_page + 1);
7174 copy_pages(dst->pages[dst_i], dst->pages[src_i],
7175 dst_off_in_page - cur + 1,
7176 src_off_in_page - cur + 1, cur);
7184 #define GANG_LOOKUP_SIZE 16
7185 static struct extent_buffer *get_next_extent_buffer(
7186 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
7188 struct extent_buffer *gang[GANG_LOOKUP_SIZE];
7189 struct extent_buffer *found = NULL;
7190 u64 page_start = page_offset(page);
7191 u64 cur = page_start;
7193 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7194 lockdep_assert_held(&fs_info->buffer_lock);
7196 while (cur < page_start + PAGE_SIZE) {
7200 ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
7201 (void **)gang, cur >> fs_info->sectorsize_bits,
7202 min_t(unsigned int, GANG_LOOKUP_SIZE,
7203 PAGE_SIZE / fs_info->nodesize));
7206 for (i = 0; i < ret; i++) {
7207 /* Already beyond page end */
7208 if (gang[i]->start >= page_start + PAGE_SIZE)
7211 if (gang[i]->start >= bytenr) {
7216 cur = gang[ret - 1]->start + gang[ret - 1]->len;
7222 static int try_release_subpage_extent_buffer(struct page *page)
7224 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7225 u64 cur = page_offset(page);
7226 const u64 end = page_offset(page) + PAGE_SIZE;
7230 struct extent_buffer *eb = NULL;
7233 * Unlike try_release_extent_buffer() which uses page->private
7234 * to grab buffer, for subpage case we rely on radix tree, thus
7235 * we need to ensure radix tree consistency.
7237 * We also want an atomic snapshot of the radix tree, thus go
7238 * with spinlock rather than RCU.
7240 spin_lock(&fs_info->buffer_lock);
7241 eb = get_next_extent_buffer(fs_info, page, cur);
7243 /* No more eb in the page range after or at cur */
7244 spin_unlock(&fs_info->buffer_lock);
7247 cur = eb->start + eb->len;
7250 * The same as try_release_extent_buffer(), to ensure the eb
7251 * won't disappear out from under us.
7253 spin_lock(&eb->refs_lock);
7254 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7255 spin_unlock(&eb->refs_lock);
7256 spin_unlock(&fs_info->buffer_lock);
7259 spin_unlock(&fs_info->buffer_lock);
7262 * If tree ref isn't set then we know the ref on this eb is a
7263 * real ref, so just return, this eb will likely be freed soon
7266 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7267 spin_unlock(&eb->refs_lock);
7272 * Here we don't care about the return value, we will always
7273 * check the page private at the end. And
7274 * release_extent_buffer() will release the refs_lock.
7276 release_extent_buffer(eb);
7279 * Finally to check if we have cleared page private, as if we have
7280 * released all ebs in the page, the page private should be cleared now.
7282 spin_lock(&page->mapping->private_lock);
7283 if (!PagePrivate(page))
7287 spin_unlock(&page->mapping->private_lock);
7292 int try_release_extent_buffer(struct page *page)
7294 struct extent_buffer *eb;
7296 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
7297 return try_release_subpage_extent_buffer(page);
7300 * We need to make sure nobody is changing page->private, as we rely on
7301 * page->private as the pointer to extent buffer.
7303 spin_lock(&page->mapping->private_lock);
7304 if (!PagePrivate(page)) {
7305 spin_unlock(&page->mapping->private_lock);
7309 eb = (struct extent_buffer *)page->private;
7313 * This is a little awful but should be ok, we need to make sure that
7314 * the eb doesn't disappear out from under us while we're looking at
7317 spin_lock(&eb->refs_lock);
7318 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7319 spin_unlock(&eb->refs_lock);
7320 spin_unlock(&page->mapping->private_lock);
7323 spin_unlock(&page->mapping->private_lock);
7326 * If tree ref isn't set then we know the ref on this eb is a real ref,
7327 * so just return, this page will likely be freed soon anyway.
7329 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7330 spin_unlock(&eb->refs_lock);
7334 return release_extent_buffer(eb);
7338 * btrfs_readahead_tree_block - attempt to readahead a child block
7339 * @fs_info: the fs_info
7340 * @bytenr: bytenr to read
7341 * @owner_root: objectid of the root that owns this eb
7342 * @gen: generation for the uptodate check, can be 0
7343 * @level: level for the eb
7345 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7346 * normal uptodate check of the eb, without checking the generation. If we have
7347 * to read the block we will not block on anything.
7349 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7350 u64 bytenr, u64 owner_root, u64 gen, int level)
7352 struct extent_buffer *eb;
7355 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7359 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7360 free_extent_buffer(eb);
7364 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7366 free_extent_buffer_stale(eb);
7368 free_extent_buffer(eb);
7372 * btrfs_readahead_node_child - readahead a node's child block
7373 * @node: parent node we're reading from
7374 * @slot: slot in the parent node for the child we want to read
7376 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7377 * the slot in the node provided.
7379 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7381 btrfs_readahead_tree_block(node->fs_info,
7382 btrfs_node_blockptr(node, slot),
7383 btrfs_header_owner(node),
7384 btrfs_node_ptr_generation(node, slot),
7385 btrfs_header_level(node) - 1);