1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/cleancache.h>
16 #include "extent_io.h"
17 #include "extent-io-tree.h"
18 #include "extent_map.h"
20 #include "btrfs_inode.h"
22 #include "check-integrity.h"
24 #include "rcu-string.h"
28 static struct kmem_cache *extent_state_cache;
29 static struct kmem_cache *extent_buffer_cache;
30 static struct bio_set btrfs_bioset;
32 static inline bool extent_state_in_tree(const struct extent_state *state)
34 return !RB_EMPTY_NODE(&state->rb_node);
37 #ifdef CONFIG_BTRFS_DEBUG
38 static LIST_HEAD(states);
39 static DEFINE_SPINLOCK(leak_lock);
41 static inline void btrfs_leak_debug_add(spinlock_t *lock,
42 struct list_head *new,
43 struct list_head *head)
47 spin_lock_irqsave(lock, flags);
49 spin_unlock_irqrestore(lock, flags);
52 static inline void btrfs_leak_debug_del(spinlock_t *lock,
53 struct list_head *entry)
57 spin_lock_irqsave(lock, flags);
59 spin_unlock_irqrestore(lock, flags);
62 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
64 struct extent_buffer *eb;
68 * If we didn't get into open_ctree our allocated_ebs will not be
69 * initialized, so just skip this.
71 if (!fs_info->allocated_ebs.next)
74 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
75 while (!list_empty(&fs_info->allocated_ebs)) {
76 eb = list_first_entry(&fs_info->allocated_ebs,
77 struct extent_buffer, leak_list);
79 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
80 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
81 btrfs_header_owner(eb));
82 list_del(&eb->leak_list);
83 kmem_cache_free(extent_buffer_cache, eb);
85 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
88 static inline void btrfs_extent_state_leak_debug_check(void)
90 struct extent_state *state;
92 while (!list_empty(&states)) {
93 state = list_entry(states.next, struct extent_state, leak_list);
94 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
95 state->start, state->end, state->state,
96 extent_state_in_tree(state),
97 refcount_read(&state->refs));
98 list_del(&state->leak_list);
99 kmem_cache_free(extent_state_cache, state);
103 #define btrfs_debug_check_extent_io_range(tree, start, end) \
104 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
105 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
106 struct extent_io_tree *tree, u64 start, u64 end)
108 struct inode *inode = tree->private_data;
111 if (!inode || !is_data_inode(inode))
114 isize = i_size_read(inode);
115 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
116 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
117 "%s: ino %llu isize %llu odd range [%llu,%llu]",
118 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
122 #define btrfs_leak_debug_add(lock, new, head) do {} while (0)
123 #define btrfs_leak_debug_del(lock, entry) do {} while (0)
124 #define btrfs_extent_state_leak_debug_check() do {} while (0)
125 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
131 struct rb_node rb_node;
134 struct extent_page_data {
136 /* tells writepage not to lock the state bits for this range
137 * it still does the unlocking
139 unsigned int extent_locked:1;
141 /* tells the submit_bio code to use REQ_SYNC */
142 unsigned int sync_io:1;
145 static int add_extent_changeset(struct extent_state *state, u32 bits,
146 struct extent_changeset *changeset,
153 if (set && (state->state & bits) == bits)
155 if (!set && (state->state & bits) == 0)
157 changeset->bytes_changed += state->end - state->start + 1;
158 ret = ulist_add(&changeset->range_changed, state->start, state->end,
163 int __must_check submit_one_bio(struct bio *bio, int mirror_num,
164 unsigned long bio_flags)
166 blk_status_t ret = 0;
167 struct extent_io_tree *tree = bio->bi_private;
169 bio->bi_private = NULL;
171 if (is_data_inode(tree->private_data))
172 ret = btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
175 ret = btrfs_submit_metadata_bio(tree->private_data, bio,
176 mirror_num, bio_flags);
178 return blk_status_to_errno(ret);
181 /* Cleanup unsubmitted bios */
182 static void end_write_bio(struct extent_page_data *epd, int ret)
185 epd->bio->bi_status = errno_to_blk_status(ret);
192 * Submit bio from extent page data via submit_one_bio
194 * Return 0 if everything is OK.
195 * Return <0 for error.
197 static int __must_check flush_write_bio(struct extent_page_data *epd)
202 ret = submit_one_bio(epd->bio, 0, 0);
204 * Clean up of epd->bio is handled by its endio function.
205 * And endio is either triggered by successful bio execution
206 * or the error handler of submit bio hook.
207 * So at this point, no matter what happened, we don't need
208 * to clean up epd->bio.
215 int __init extent_state_cache_init(void)
217 extent_state_cache = kmem_cache_create("btrfs_extent_state",
218 sizeof(struct extent_state), 0,
219 SLAB_MEM_SPREAD, NULL);
220 if (!extent_state_cache)
225 int __init extent_io_init(void)
227 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
228 sizeof(struct extent_buffer), 0,
229 SLAB_MEM_SPREAD, NULL);
230 if (!extent_buffer_cache)
233 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
234 offsetof(struct btrfs_io_bio, bio),
236 goto free_buffer_cache;
238 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
244 bioset_exit(&btrfs_bioset);
247 kmem_cache_destroy(extent_buffer_cache);
248 extent_buffer_cache = NULL;
252 void __cold extent_state_cache_exit(void)
254 btrfs_extent_state_leak_debug_check();
255 kmem_cache_destroy(extent_state_cache);
258 void __cold extent_io_exit(void)
261 * Make sure all delayed rcu free are flushed before we
265 kmem_cache_destroy(extent_buffer_cache);
266 bioset_exit(&btrfs_bioset);
270 * For the file_extent_tree, we want to hold the inode lock when we lookup and
271 * update the disk_i_size, but lockdep will complain because our io_tree we hold
272 * the tree lock and get the inode lock when setting delalloc. These two things
273 * are unrelated, so make a class for the file_extent_tree so we don't get the
274 * two locking patterns mixed up.
276 static struct lock_class_key file_extent_tree_class;
278 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
279 struct extent_io_tree *tree, unsigned int owner,
282 tree->fs_info = fs_info;
283 tree->state = RB_ROOT;
284 tree->dirty_bytes = 0;
285 spin_lock_init(&tree->lock);
286 tree->private_data = private_data;
288 if (owner == IO_TREE_INODE_FILE_EXTENT)
289 lockdep_set_class(&tree->lock, &file_extent_tree_class);
292 void extent_io_tree_release(struct extent_io_tree *tree)
294 spin_lock(&tree->lock);
296 * Do a single barrier for the waitqueue_active check here, the state
297 * of the waitqueue should not change once extent_io_tree_release is
301 while (!RB_EMPTY_ROOT(&tree->state)) {
302 struct rb_node *node;
303 struct extent_state *state;
305 node = rb_first(&tree->state);
306 state = rb_entry(node, struct extent_state, rb_node);
307 rb_erase(&state->rb_node, &tree->state);
308 RB_CLEAR_NODE(&state->rb_node);
310 * btree io trees aren't supposed to have tasks waiting for
311 * changes in the flags of extent states ever.
313 ASSERT(!waitqueue_active(&state->wq));
314 free_extent_state(state);
316 cond_resched_lock(&tree->lock);
318 spin_unlock(&tree->lock);
321 static struct extent_state *alloc_extent_state(gfp_t mask)
323 struct extent_state *state;
326 * The given mask might be not appropriate for the slab allocator,
327 * drop the unsupported bits
329 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
330 state = kmem_cache_alloc(extent_state_cache, mask);
334 state->failrec = NULL;
335 RB_CLEAR_NODE(&state->rb_node);
336 btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
337 refcount_set(&state->refs, 1);
338 init_waitqueue_head(&state->wq);
339 trace_alloc_extent_state(state, mask, _RET_IP_);
343 void free_extent_state(struct extent_state *state)
347 if (refcount_dec_and_test(&state->refs)) {
348 WARN_ON(extent_state_in_tree(state));
349 btrfs_leak_debug_del(&leak_lock, &state->leak_list);
350 trace_free_extent_state(state, _RET_IP_);
351 kmem_cache_free(extent_state_cache, state);
355 static struct rb_node *tree_insert(struct rb_root *root,
356 struct rb_node *search_start,
358 struct rb_node *node,
359 struct rb_node ***p_in,
360 struct rb_node **parent_in)
363 struct rb_node *parent = NULL;
364 struct tree_entry *entry;
366 if (p_in && parent_in) {
372 p = search_start ? &search_start : &root->rb_node;
375 entry = rb_entry(parent, struct tree_entry, rb_node);
377 if (offset < entry->start)
379 else if (offset > entry->end)
386 rb_link_node(node, parent, p);
387 rb_insert_color(node, root);
392 * Search @tree for an entry that contains @offset. Such entry would have
393 * entry->start <= offset && entry->end >= offset.
395 * @tree: the tree to search
396 * @offset: offset that should fall within an entry in @tree
397 * @next_ret: pointer to the first entry whose range ends after @offset
398 * @prev_ret: pointer to the first entry whose range begins before @offset
399 * @p_ret: pointer where new node should be anchored (used when inserting an
401 * @parent_ret: points to entry which would have been the parent of the entry,
404 * This function returns a pointer to the entry that contains @offset byte
405 * address. If no such entry exists, then NULL is returned and the other
406 * pointer arguments to the function are filled, otherwise the found entry is
407 * returned and other pointers are left untouched.
409 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
410 struct rb_node **next_ret,
411 struct rb_node **prev_ret,
412 struct rb_node ***p_ret,
413 struct rb_node **parent_ret)
415 struct rb_root *root = &tree->state;
416 struct rb_node **n = &root->rb_node;
417 struct rb_node *prev = NULL;
418 struct rb_node *orig_prev = NULL;
419 struct tree_entry *entry;
420 struct tree_entry *prev_entry = NULL;
424 entry = rb_entry(prev, struct tree_entry, rb_node);
427 if (offset < entry->start)
429 else if (offset > entry->end)
442 while (prev && offset > prev_entry->end) {
443 prev = rb_next(prev);
444 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
451 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
452 while (prev && offset < prev_entry->start) {
453 prev = rb_prev(prev);
454 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
461 static inline struct rb_node *
462 tree_search_for_insert(struct extent_io_tree *tree,
464 struct rb_node ***p_ret,
465 struct rb_node **parent_ret)
467 struct rb_node *next= NULL;
470 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
476 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
479 return tree_search_for_insert(tree, offset, NULL, NULL);
483 * utility function to look for merge candidates inside a given range.
484 * Any extents with matching state are merged together into a single
485 * extent in the tree. Extents with EXTENT_IO in their state field
486 * are not merged because the end_io handlers need to be able to do
487 * operations on them without sleeping (or doing allocations/splits).
489 * This should be called with the tree lock held.
491 static void merge_state(struct extent_io_tree *tree,
492 struct extent_state *state)
494 struct extent_state *other;
495 struct rb_node *other_node;
497 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
500 other_node = rb_prev(&state->rb_node);
502 other = rb_entry(other_node, struct extent_state, rb_node);
503 if (other->end == state->start - 1 &&
504 other->state == state->state) {
505 if (tree->private_data &&
506 is_data_inode(tree->private_data))
507 btrfs_merge_delalloc_extent(tree->private_data,
509 state->start = other->start;
510 rb_erase(&other->rb_node, &tree->state);
511 RB_CLEAR_NODE(&other->rb_node);
512 free_extent_state(other);
515 other_node = rb_next(&state->rb_node);
517 other = rb_entry(other_node, struct extent_state, rb_node);
518 if (other->start == state->end + 1 &&
519 other->state == state->state) {
520 if (tree->private_data &&
521 is_data_inode(tree->private_data))
522 btrfs_merge_delalloc_extent(tree->private_data,
524 state->end = other->end;
525 rb_erase(&other->rb_node, &tree->state);
526 RB_CLEAR_NODE(&other->rb_node);
527 free_extent_state(other);
532 static void set_state_bits(struct extent_io_tree *tree,
533 struct extent_state *state, u32 *bits,
534 struct extent_changeset *changeset);
537 * insert an extent_state struct into the tree. 'bits' are set on the
538 * struct before it is inserted.
540 * This may return -EEXIST if the extent is already there, in which case the
541 * state struct is freed.
543 * The tree lock is not taken internally. This is a utility function and
544 * probably isn't what you want to call (see set/clear_extent_bit).
546 static int insert_state(struct extent_io_tree *tree,
547 struct extent_state *state, u64 start, u64 end,
549 struct rb_node **parent,
550 u32 *bits, struct extent_changeset *changeset)
552 struct rb_node *node;
555 btrfs_err(tree->fs_info,
556 "insert state: end < start %llu %llu", end, start);
559 state->start = start;
562 set_state_bits(tree, state, bits, changeset);
564 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
566 struct extent_state *found;
567 found = rb_entry(node, struct extent_state, rb_node);
568 btrfs_err(tree->fs_info,
569 "found node %llu %llu on insert of %llu %llu",
570 found->start, found->end, start, end);
573 merge_state(tree, state);
578 * split a given extent state struct in two, inserting the preallocated
579 * struct 'prealloc' as the newly created second half. 'split' indicates an
580 * offset inside 'orig' where it should be split.
583 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
584 * are two extent state structs in the tree:
585 * prealloc: [orig->start, split - 1]
586 * orig: [ split, orig->end ]
588 * The tree locks are not taken by this function. They need to be held
591 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
592 struct extent_state *prealloc, u64 split)
594 struct rb_node *node;
596 if (tree->private_data && is_data_inode(tree->private_data))
597 btrfs_split_delalloc_extent(tree->private_data, orig, split);
599 prealloc->start = orig->start;
600 prealloc->end = split - 1;
601 prealloc->state = orig->state;
604 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
605 &prealloc->rb_node, NULL, NULL);
607 free_extent_state(prealloc);
613 static struct extent_state *next_state(struct extent_state *state)
615 struct rb_node *next = rb_next(&state->rb_node);
617 return rb_entry(next, struct extent_state, rb_node);
623 * utility function to clear some bits in an extent state struct.
624 * it will optionally wake up anyone waiting on this state (wake == 1).
626 * If no bits are set on the state struct after clearing things, the
627 * struct is freed and removed from the tree
629 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
630 struct extent_state *state,
632 struct extent_changeset *changeset)
634 struct extent_state *next;
635 u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
638 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
639 u64 range = state->end - state->start + 1;
640 WARN_ON(range > tree->dirty_bytes);
641 tree->dirty_bytes -= range;
644 if (tree->private_data && is_data_inode(tree->private_data))
645 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
647 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
649 state->state &= ~bits_to_clear;
652 if (state->state == 0) {
653 next = next_state(state);
654 if (extent_state_in_tree(state)) {
655 rb_erase(&state->rb_node, &tree->state);
656 RB_CLEAR_NODE(&state->rb_node);
657 free_extent_state(state);
662 merge_state(tree, state);
663 next = next_state(state);
668 static struct extent_state *
669 alloc_extent_state_atomic(struct extent_state *prealloc)
672 prealloc = alloc_extent_state(GFP_ATOMIC);
677 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
679 btrfs_panic(tree->fs_info, err,
680 "locking error: extent tree was modified by another thread while locked");
684 * clear some bits on a range in the tree. This may require splitting
685 * or inserting elements in the tree, so the gfp mask is used to
686 * indicate which allocations or sleeping are allowed.
688 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
689 * the given range from the tree regardless of state (ie for truncate).
691 * the range [start, end] is inclusive.
693 * This takes the tree lock, and returns 0 on success and < 0 on error.
695 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
696 u32 bits, int wake, int delete,
697 struct extent_state **cached_state,
698 gfp_t mask, struct extent_changeset *changeset)
700 struct extent_state *state;
701 struct extent_state *cached;
702 struct extent_state *prealloc = NULL;
703 struct rb_node *node;
708 btrfs_debug_check_extent_io_range(tree, start, end);
709 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
711 if (bits & EXTENT_DELALLOC)
712 bits |= EXTENT_NORESERVE;
715 bits |= ~EXTENT_CTLBITS;
717 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
720 if (!prealloc && gfpflags_allow_blocking(mask)) {
722 * Don't care for allocation failure here because we might end
723 * up not needing the pre-allocated extent state at all, which
724 * is the case if we only have in the tree extent states that
725 * cover our input range and don't cover too any other range.
726 * If we end up needing a new extent state we allocate it later.
728 prealloc = alloc_extent_state(mask);
731 spin_lock(&tree->lock);
733 cached = *cached_state;
736 *cached_state = NULL;
740 if (cached && extent_state_in_tree(cached) &&
741 cached->start <= start && cached->end > start) {
743 refcount_dec(&cached->refs);
748 free_extent_state(cached);
751 * this search will find the extents that end after
754 node = tree_search(tree, start);
757 state = rb_entry(node, struct extent_state, rb_node);
759 if (state->start > end)
761 WARN_ON(state->end < start);
762 last_end = state->end;
764 /* the state doesn't have the wanted bits, go ahead */
765 if (!(state->state & bits)) {
766 state = next_state(state);
771 * | ---- desired range ---- |
773 * | ------------- state -------------- |
775 * We need to split the extent we found, and may flip
776 * bits on second half.
778 * If the extent we found extends past our range, we
779 * just split and search again. It'll get split again
780 * the next time though.
782 * If the extent we found is inside our range, we clear
783 * the desired bit on it.
786 if (state->start < start) {
787 prealloc = alloc_extent_state_atomic(prealloc);
789 err = split_state(tree, state, prealloc, start);
791 extent_io_tree_panic(tree, err);
796 if (state->end <= end) {
797 state = clear_state_bit(tree, state, &bits, wake,
804 * | ---- desired range ---- |
806 * We need to split the extent, and clear the bit
809 if (state->start <= end && state->end > end) {
810 prealloc = alloc_extent_state_atomic(prealloc);
812 err = split_state(tree, state, prealloc, end + 1);
814 extent_io_tree_panic(tree, err);
819 clear_state_bit(tree, prealloc, &bits, wake, changeset);
825 state = clear_state_bit(tree, state, &bits, wake, changeset);
827 if (last_end == (u64)-1)
829 start = last_end + 1;
830 if (start <= end && state && !need_resched())
836 spin_unlock(&tree->lock);
837 if (gfpflags_allow_blocking(mask))
842 spin_unlock(&tree->lock);
844 free_extent_state(prealloc);
850 static void wait_on_state(struct extent_io_tree *tree,
851 struct extent_state *state)
852 __releases(tree->lock)
853 __acquires(tree->lock)
856 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
857 spin_unlock(&tree->lock);
859 spin_lock(&tree->lock);
860 finish_wait(&state->wq, &wait);
864 * waits for one or more bits to clear on a range in the state tree.
865 * The range [start, end] is inclusive.
866 * The tree lock is taken by this function
868 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
871 struct extent_state *state;
872 struct rb_node *node;
874 btrfs_debug_check_extent_io_range(tree, start, end);
876 spin_lock(&tree->lock);
880 * this search will find all the extents that end after
883 node = tree_search(tree, start);
888 state = rb_entry(node, struct extent_state, rb_node);
890 if (state->start > end)
893 if (state->state & bits) {
894 start = state->start;
895 refcount_inc(&state->refs);
896 wait_on_state(tree, state);
897 free_extent_state(state);
900 start = state->end + 1;
905 if (!cond_resched_lock(&tree->lock)) {
906 node = rb_next(node);
911 spin_unlock(&tree->lock);
914 static void set_state_bits(struct extent_io_tree *tree,
915 struct extent_state *state,
916 u32 *bits, struct extent_changeset *changeset)
918 u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
921 if (tree->private_data && is_data_inode(tree->private_data))
922 btrfs_set_delalloc_extent(tree->private_data, state, bits);
924 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
925 u64 range = state->end - state->start + 1;
926 tree->dirty_bytes += range;
928 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
930 state->state |= bits_to_set;
933 static void cache_state_if_flags(struct extent_state *state,
934 struct extent_state **cached_ptr,
937 if (cached_ptr && !(*cached_ptr)) {
938 if (!flags || (state->state & flags)) {
940 refcount_inc(&state->refs);
945 static void cache_state(struct extent_state *state,
946 struct extent_state **cached_ptr)
948 return cache_state_if_flags(state, cached_ptr,
949 EXTENT_LOCKED | EXTENT_BOUNDARY);
953 * set some bits on a range in the tree. This may require allocations or
954 * sleeping, so the gfp mask is used to indicate what is allowed.
956 * If any of the exclusive bits are set, this will fail with -EEXIST if some
957 * part of the range already has the desired bits set. The start of the
958 * existing range is returned in failed_start in this case.
960 * [start, end] is inclusive This takes the tree lock.
962 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
963 u32 exclusive_bits, u64 *failed_start,
964 struct extent_state **cached_state, gfp_t mask,
965 struct extent_changeset *changeset)
967 struct extent_state *state;
968 struct extent_state *prealloc = NULL;
969 struct rb_node *node;
971 struct rb_node *parent;
976 btrfs_debug_check_extent_io_range(tree, start, end);
977 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
980 ASSERT(failed_start);
982 ASSERT(failed_start == NULL);
984 if (!prealloc && gfpflags_allow_blocking(mask)) {
986 * Don't care for allocation failure here because we might end
987 * up not needing the pre-allocated extent state at all, which
988 * is the case if we only have in the tree extent states that
989 * cover our input range and don't cover too any other range.
990 * If we end up needing a new extent state we allocate it later.
992 prealloc = alloc_extent_state(mask);
995 spin_lock(&tree->lock);
996 if (cached_state && *cached_state) {
997 state = *cached_state;
998 if (state->start <= start && state->end > start &&
999 extent_state_in_tree(state)) {
1000 node = &state->rb_node;
1005 * this search will find all the extents that end after
1008 node = tree_search_for_insert(tree, start, &p, &parent);
1010 prealloc = alloc_extent_state_atomic(prealloc);
1012 err = insert_state(tree, prealloc, start, end,
1013 &p, &parent, &bits, changeset);
1015 extent_io_tree_panic(tree, err);
1017 cache_state(prealloc, cached_state);
1021 state = rb_entry(node, struct extent_state, rb_node);
1023 last_start = state->start;
1024 last_end = state->end;
1027 * | ---- desired range ---- |
1030 * Just lock what we found and keep going
1032 if (state->start == start && state->end <= end) {
1033 if (state->state & exclusive_bits) {
1034 *failed_start = state->start;
1039 set_state_bits(tree, state, &bits, changeset);
1040 cache_state(state, cached_state);
1041 merge_state(tree, state);
1042 if (last_end == (u64)-1)
1044 start = last_end + 1;
1045 state = next_state(state);
1046 if (start < end && state && state->start == start &&
1053 * | ---- desired range ---- |
1056 * | ------------- state -------------- |
1058 * We need to split the extent we found, and may flip bits on
1061 * If the extent we found extends past our
1062 * range, we just split and search again. It'll get split
1063 * again the next time though.
1065 * If the extent we found is inside our range, we set the
1066 * desired bit on it.
1068 if (state->start < start) {
1069 if (state->state & exclusive_bits) {
1070 *failed_start = start;
1076 * If this extent already has all the bits we want set, then
1077 * skip it, not necessary to split it or do anything with it.
1079 if ((state->state & bits) == bits) {
1080 start = state->end + 1;
1081 cache_state(state, cached_state);
1085 prealloc = alloc_extent_state_atomic(prealloc);
1087 err = split_state(tree, state, prealloc, start);
1089 extent_io_tree_panic(tree, err);
1094 if (state->end <= end) {
1095 set_state_bits(tree, state, &bits, changeset);
1096 cache_state(state, cached_state);
1097 merge_state(tree, state);
1098 if (last_end == (u64)-1)
1100 start = last_end + 1;
1101 state = next_state(state);
1102 if (start < end && state && state->start == start &&
1109 * | ---- desired range ---- |
1110 * | state | or | state |
1112 * There's a hole, we need to insert something in it and
1113 * ignore the extent we found.
1115 if (state->start > start) {
1117 if (end < last_start)
1120 this_end = last_start - 1;
1122 prealloc = alloc_extent_state_atomic(prealloc);
1126 * Avoid to free 'prealloc' if it can be merged with
1129 err = insert_state(tree, prealloc, start, this_end,
1130 NULL, NULL, &bits, changeset);
1132 extent_io_tree_panic(tree, err);
1134 cache_state(prealloc, cached_state);
1136 start = this_end + 1;
1140 * | ---- desired range ---- |
1142 * We need to split the extent, and set the bit
1145 if (state->start <= end && state->end > end) {
1146 if (state->state & exclusive_bits) {
1147 *failed_start = start;
1152 prealloc = alloc_extent_state_atomic(prealloc);
1154 err = split_state(tree, state, prealloc, end + 1);
1156 extent_io_tree_panic(tree, err);
1158 set_state_bits(tree, prealloc, &bits, changeset);
1159 cache_state(prealloc, cached_state);
1160 merge_state(tree, prealloc);
1168 spin_unlock(&tree->lock);
1169 if (gfpflags_allow_blocking(mask))
1174 spin_unlock(&tree->lock);
1176 free_extent_state(prealloc);
1183 * convert_extent_bit - convert all bits in a given range from one bit to
1185 * @tree: the io tree to search
1186 * @start: the start offset in bytes
1187 * @end: the end offset in bytes (inclusive)
1188 * @bits: the bits to set in this range
1189 * @clear_bits: the bits to clear in this range
1190 * @cached_state: state that we're going to cache
1192 * This will go through and set bits for the given range. If any states exist
1193 * already in this range they are set with the given bit and cleared of the
1194 * clear_bits. This is only meant to be used by things that are mergeable, ie
1195 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1196 * boundary bits like LOCK.
1198 * All allocations are done with GFP_NOFS.
1200 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1201 u32 bits, u32 clear_bits,
1202 struct extent_state **cached_state)
1204 struct extent_state *state;
1205 struct extent_state *prealloc = NULL;
1206 struct rb_node *node;
1208 struct rb_node *parent;
1212 bool first_iteration = true;
1214 btrfs_debug_check_extent_io_range(tree, start, end);
1215 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1221 * Best effort, don't worry if extent state allocation fails
1222 * here for the first iteration. We might have a cached state
1223 * that matches exactly the target range, in which case no
1224 * extent state allocations are needed. We'll only know this
1225 * after locking the tree.
1227 prealloc = alloc_extent_state(GFP_NOFS);
1228 if (!prealloc && !first_iteration)
1232 spin_lock(&tree->lock);
1233 if (cached_state && *cached_state) {
1234 state = *cached_state;
1235 if (state->start <= start && state->end > start &&
1236 extent_state_in_tree(state)) {
1237 node = &state->rb_node;
1243 * this search will find all the extents that end after
1246 node = tree_search_for_insert(tree, start, &p, &parent);
1248 prealloc = alloc_extent_state_atomic(prealloc);
1253 err = insert_state(tree, prealloc, start, end,
1254 &p, &parent, &bits, NULL);
1256 extent_io_tree_panic(tree, err);
1257 cache_state(prealloc, cached_state);
1261 state = rb_entry(node, struct extent_state, rb_node);
1263 last_start = state->start;
1264 last_end = state->end;
1267 * | ---- desired range ---- |
1270 * Just lock what we found and keep going
1272 if (state->start == start && state->end <= end) {
1273 set_state_bits(tree, state, &bits, NULL);
1274 cache_state(state, cached_state);
1275 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1276 if (last_end == (u64)-1)
1278 start = last_end + 1;
1279 if (start < end && state && state->start == start &&
1286 * | ---- desired range ---- |
1289 * | ------------- state -------------- |
1291 * We need to split the extent we found, and may flip bits on
1294 * If the extent we found extends past our
1295 * range, we just split and search again. It'll get split
1296 * again the next time though.
1298 * If the extent we found is inside our range, we set the
1299 * desired bit on it.
1301 if (state->start < start) {
1302 prealloc = alloc_extent_state_atomic(prealloc);
1307 err = split_state(tree, state, prealloc, start);
1309 extent_io_tree_panic(tree, err);
1313 if (state->end <= end) {
1314 set_state_bits(tree, state, &bits, NULL);
1315 cache_state(state, cached_state);
1316 state = clear_state_bit(tree, state, &clear_bits, 0,
1318 if (last_end == (u64)-1)
1320 start = last_end + 1;
1321 if (start < end && state && state->start == start &&
1328 * | ---- desired range ---- |
1329 * | state | or | state |
1331 * There's a hole, we need to insert something in it and
1332 * ignore the extent we found.
1334 if (state->start > start) {
1336 if (end < last_start)
1339 this_end = last_start - 1;
1341 prealloc = alloc_extent_state_atomic(prealloc);
1348 * Avoid to free 'prealloc' if it can be merged with
1351 err = insert_state(tree, prealloc, start, this_end,
1352 NULL, NULL, &bits, NULL);
1354 extent_io_tree_panic(tree, err);
1355 cache_state(prealloc, cached_state);
1357 start = this_end + 1;
1361 * | ---- desired range ---- |
1363 * We need to split the extent, and set the bit
1366 if (state->start <= end && state->end > end) {
1367 prealloc = alloc_extent_state_atomic(prealloc);
1373 err = split_state(tree, state, prealloc, end + 1);
1375 extent_io_tree_panic(tree, err);
1377 set_state_bits(tree, prealloc, &bits, NULL);
1378 cache_state(prealloc, cached_state);
1379 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1387 spin_unlock(&tree->lock);
1389 first_iteration = false;
1393 spin_unlock(&tree->lock);
1395 free_extent_state(prealloc);
1400 /* wrappers around set/clear extent bit */
1401 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1402 u32 bits, struct extent_changeset *changeset)
1405 * We don't support EXTENT_LOCKED yet, as current changeset will
1406 * record any bits changed, so for EXTENT_LOCKED case, it will
1407 * either fail with -EEXIST or changeset will record the whole
1410 BUG_ON(bits & EXTENT_LOCKED);
1412 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1416 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1419 return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1423 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1424 u32 bits, int wake, int delete,
1425 struct extent_state **cached)
1427 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1428 cached, GFP_NOFS, NULL);
1431 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1432 u32 bits, struct extent_changeset *changeset)
1435 * Don't support EXTENT_LOCKED case, same reason as
1436 * set_record_extent_bits().
1438 BUG_ON(bits & EXTENT_LOCKED);
1440 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1445 * either insert or lock state struct between start and end use mask to tell
1446 * us if waiting is desired.
1448 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1449 struct extent_state **cached_state)
1455 err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1456 EXTENT_LOCKED, &failed_start,
1457 cached_state, GFP_NOFS, NULL);
1458 if (err == -EEXIST) {
1459 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1460 start = failed_start;
1463 WARN_ON(start > end);
1468 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1473 err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1474 &failed_start, NULL, GFP_NOFS, NULL);
1475 if (err == -EEXIST) {
1476 if (failed_start > start)
1477 clear_extent_bit(tree, start, failed_start - 1,
1478 EXTENT_LOCKED, 1, 0, NULL);
1484 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1486 unsigned long index = start >> PAGE_SHIFT;
1487 unsigned long end_index = end >> PAGE_SHIFT;
1490 while (index <= end_index) {
1491 page = find_get_page(inode->i_mapping, index);
1492 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1493 clear_page_dirty_for_io(page);
1499 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1501 unsigned long index = start >> PAGE_SHIFT;
1502 unsigned long end_index = end >> PAGE_SHIFT;
1505 while (index <= end_index) {
1506 page = find_get_page(inode->i_mapping, index);
1507 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1508 __set_page_dirty_nobuffers(page);
1509 account_page_redirty(page);
1515 /* find the first state struct with 'bits' set after 'start', and
1516 * return it. tree->lock must be held. NULL will returned if
1517 * nothing was found after 'start'
1519 static struct extent_state *
1520 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1522 struct rb_node *node;
1523 struct extent_state *state;
1526 * this search will find all the extents that end after
1529 node = tree_search(tree, start);
1534 state = rb_entry(node, struct extent_state, rb_node);
1535 if (state->end >= start && (state->state & bits))
1538 node = rb_next(node);
1547 * Find the first offset in the io tree with one or more @bits set.
1549 * Note: If there are multiple bits set in @bits, any of them will match.
1551 * Return 0 if we find something, and update @start_ret and @end_ret.
1552 * Return 1 if we found nothing.
1554 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1555 u64 *start_ret, u64 *end_ret, u32 bits,
1556 struct extent_state **cached_state)
1558 struct extent_state *state;
1561 spin_lock(&tree->lock);
1562 if (cached_state && *cached_state) {
1563 state = *cached_state;
1564 if (state->end == start - 1 && extent_state_in_tree(state)) {
1565 while ((state = next_state(state)) != NULL) {
1566 if (state->state & bits)
1569 free_extent_state(*cached_state);
1570 *cached_state = NULL;
1573 free_extent_state(*cached_state);
1574 *cached_state = NULL;
1577 state = find_first_extent_bit_state(tree, start, bits);
1580 cache_state_if_flags(state, cached_state, 0);
1581 *start_ret = state->start;
1582 *end_ret = state->end;
1586 spin_unlock(&tree->lock);
1591 * Find a contiguous area of bits
1593 * @tree: io tree to check
1594 * @start: offset to start the search from
1595 * @start_ret: the first offset we found with the bits set
1596 * @end_ret: the final contiguous range of the bits that were set
1597 * @bits: bits to look for
1599 * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1600 * to set bits appropriately, and then merge them again. During this time it
1601 * will drop the tree->lock, so use this helper if you want to find the actual
1602 * contiguous area for given bits. We will search to the first bit we find, and
1603 * then walk down the tree until we find a non-contiguous area. The area
1604 * returned will be the full contiguous area with the bits set.
1606 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1607 u64 *start_ret, u64 *end_ret, u32 bits)
1609 struct extent_state *state;
1612 spin_lock(&tree->lock);
1613 state = find_first_extent_bit_state(tree, start, bits);
1615 *start_ret = state->start;
1616 *end_ret = state->end;
1617 while ((state = next_state(state)) != NULL) {
1618 if (state->start > (*end_ret + 1))
1620 *end_ret = state->end;
1624 spin_unlock(&tree->lock);
1629 * Find the first range that has @bits not set. This range could start before
1632 * @tree: the tree to search
1633 * @start: offset at/after which the found extent should start
1634 * @start_ret: records the beginning of the range
1635 * @end_ret: records the end of the range (inclusive)
1636 * @bits: the set of bits which must be unset
1638 * Since unallocated range is also considered one which doesn't have the bits
1639 * set it's possible that @end_ret contains -1, this happens in case the range
1640 * spans (last_range_end, end of device]. In this case it's up to the caller to
1641 * trim @end_ret to the appropriate size.
1643 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1644 u64 *start_ret, u64 *end_ret, u32 bits)
1646 struct extent_state *state;
1647 struct rb_node *node, *prev = NULL, *next;
1649 spin_lock(&tree->lock);
1651 /* Find first extent with bits cleared */
1653 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1654 if (!node && !next && !prev) {
1656 * Tree is completely empty, send full range and let
1657 * caller deal with it
1662 } else if (!node && !next) {
1664 * We are past the last allocated chunk, set start at
1665 * the end of the last extent.
1667 state = rb_entry(prev, struct extent_state, rb_node);
1668 *start_ret = state->end + 1;
1675 * At this point 'node' either contains 'start' or start is
1678 state = rb_entry(node, struct extent_state, rb_node);
1680 if (in_range(start, state->start, state->end - state->start + 1)) {
1681 if (state->state & bits) {
1683 * |--range with bits sets--|
1687 start = state->end + 1;
1690 * 'start' falls within a range that doesn't
1691 * have the bits set, so take its start as
1692 * the beginning of the desired range
1694 * |--range with bits cleared----|
1698 *start_ret = state->start;
1703 * |---prev range---|---hole/unset---|---node range---|
1709 * |---hole/unset--||--first node--|
1714 state = rb_entry(prev, struct extent_state,
1716 *start_ret = state->end + 1;
1725 * Find the longest stretch from start until an entry which has the
1729 state = rb_entry(node, struct extent_state, rb_node);
1730 if (state->end >= start && !(state->state & bits)) {
1731 *end_ret = state->end;
1733 *end_ret = state->start - 1;
1737 node = rb_next(node);
1742 spin_unlock(&tree->lock);
1746 * find a contiguous range of bytes in the file marked as delalloc, not
1747 * more than 'max_bytes'. start and end are used to return the range,
1749 * true is returned if we find something, false if nothing was in the tree
1751 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1752 u64 *end, u64 max_bytes,
1753 struct extent_state **cached_state)
1755 struct rb_node *node;
1756 struct extent_state *state;
1757 u64 cur_start = *start;
1759 u64 total_bytes = 0;
1761 spin_lock(&tree->lock);
1764 * this search will find all the extents that end after
1767 node = tree_search(tree, cur_start);
1774 state = rb_entry(node, struct extent_state, rb_node);
1775 if (found && (state->start != cur_start ||
1776 (state->state & EXTENT_BOUNDARY))) {
1779 if (!(state->state & EXTENT_DELALLOC)) {
1785 *start = state->start;
1786 *cached_state = state;
1787 refcount_inc(&state->refs);
1791 cur_start = state->end + 1;
1792 node = rb_next(node);
1793 total_bytes += state->end - state->start + 1;
1794 if (total_bytes >= max_bytes)
1800 spin_unlock(&tree->lock);
1804 static int __process_pages_contig(struct address_space *mapping,
1805 struct page *locked_page,
1806 pgoff_t start_index, pgoff_t end_index,
1807 unsigned long page_ops, pgoff_t *index_ret);
1809 static noinline void __unlock_for_delalloc(struct inode *inode,
1810 struct page *locked_page,
1813 unsigned long index = start >> PAGE_SHIFT;
1814 unsigned long end_index = end >> PAGE_SHIFT;
1816 ASSERT(locked_page);
1817 if (index == locked_page->index && end_index == index)
1820 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1824 static noinline int lock_delalloc_pages(struct inode *inode,
1825 struct page *locked_page,
1829 unsigned long index = delalloc_start >> PAGE_SHIFT;
1830 unsigned long index_ret = index;
1831 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1834 ASSERT(locked_page);
1835 if (index == locked_page->index && index == end_index)
1838 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1839 end_index, PAGE_LOCK, &index_ret);
1841 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1842 (u64)index_ret << PAGE_SHIFT);
1847 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1848 * more than @max_bytes. @Start and @end are used to return the range,
1850 * Return: true if we find something
1851 * false if nothing was in the tree
1854 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1855 struct page *locked_page, u64 *start,
1858 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1859 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1863 struct extent_state *cached_state = NULL;
1868 /* step one, find a bunch of delalloc bytes starting at start */
1869 delalloc_start = *start;
1871 found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1872 max_bytes, &cached_state);
1873 if (!found || delalloc_end <= *start) {
1874 *start = delalloc_start;
1875 *end = delalloc_end;
1876 free_extent_state(cached_state);
1881 * start comes from the offset of locked_page. We have to lock
1882 * pages in order, so we can't process delalloc bytes before
1885 if (delalloc_start < *start)
1886 delalloc_start = *start;
1889 * make sure to limit the number of pages we try to lock down
1891 if (delalloc_end + 1 - delalloc_start > max_bytes)
1892 delalloc_end = delalloc_start + max_bytes - 1;
1894 /* step two, lock all the pages after the page that has start */
1895 ret = lock_delalloc_pages(inode, locked_page,
1896 delalloc_start, delalloc_end);
1897 ASSERT(!ret || ret == -EAGAIN);
1898 if (ret == -EAGAIN) {
1899 /* some of the pages are gone, lets avoid looping by
1900 * shortening the size of the delalloc range we're searching
1902 free_extent_state(cached_state);
1903 cached_state = NULL;
1905 max_bytes = PAGE_SIZE;
1914 /* step three, lock the state bits for the whole range */
1915 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1917 /* then test to make sure it is all still delalloc */
1918 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1919 EXTENT_DELALLOC, 1, cached_state);
1921 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1923 __unlock_for_delalloc(inode, locked_page,
1924 delalloc_start, delalloc_end);
1928 free_extent_state(cached_state);
1929 *start = delalloc_start;
1930 *end = delalloc_end;
1935 static int __process_pages_contig(struct address_space *mapping,
1936 struct page *locked_page,
1937 pgoff_t start_index, pgoff_t end_index,
1938 unsigned long page_ops, pgoff_t *index_ret)
1940 unsigned long nr_pages = end_index - start_index + 1;
1941 unsigned long pages_processed = 0;
1942 pgoff_t index = start_index;
1943 struct page *pages[16];
1948 if (page_ops & PAGE_LOCK) {
1949 ASSERT(page_ops == PAGE_LOCK);
1950 ASSERT(index_ret && *index_ret == start_index);
1953 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1954 mapping_set_error(mapping, -EIO);
1956 while (nr_pages > 0) {
1957 ret = find_get_pages_contig(mapping, index,
1958 min_t(unsigned long,
1959 nr_pages, ARRAY_SIZE(pages)), pages);
1962 * Only if we're going to lock these pages,
1963 * can we find nothing at @index.
1965 ASSERT(page_ops & PAGE_LOCK);
1970 for (i = 0; i < ret; i++) {
1971 if (page_ops & PAGE_SET_PRIVATE2)
1972 SetPagePrivate2(pages[i]);
1974 if (locked_page && pages[i] == locked_page) {
1979 if (page_ops & PAGE_START_WRITEBACK) {
1980 clear_page_dirty_for_io(pages[i]);
1981 set_page_writeback(pages[i]);
1983 if (page_ops & PAGE_SET_ERROR)
1984 SetPageError(pages[i]);
1985 if (page_ops & PAGE_END_WRITEBACK)
1986 end_page_writeback(pages[i]);
1987 if (page_ops & PAGE_UNLOCK)
1988 unlock_page(pages[i]);
1989 if (page_ops & PAGE_LOCK) {
1990 lock_page(pages[i]);
1991 if (!PageDirty(pages[i]) ||
1992 pages[i]->mapping != mapping) {
1993 unlock_page(pages[i]);
1994 for (; i < ret; i++)
2008 if (err && index_ret)
2009 *index_ret = start_index + pages_processed - 1;
2013 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2014 struct page *locked_page,
2015 u32 clear_bits, unsigned long page_ops)
2017 clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2019 __process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2020 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
2025 * count the number of bytes in the tree that have a given bit(s)
2026 * set. This can be fairly slow, except for EXTENT_DIRTY which is
2027 * cached. The total number found is returned.
2029 u64 count_range_bits(struct extent_io_tree *tree,
2030 u64 *start, u64 search_end, u64 max_bytes,
2031 u32 bits, int contig)
2033 struct rb_node *node;
2034 struct extent_state *state;
2035 u64 cur_start = *start;
2036 u64 total_bytes = 0;
2040 if (WARN_ON(search_end <= cur_start))
2043 spin_lock(&tree->lock);
2044 if (cur_start == 0 && bits == EXTENT_DIRTY) {
2045 total_bytes = tree->dirty_bytes;
2049 * this search will find all the extents that end after
2052 node = tree_search(tree, cur_start);
2057 state = rb_entry(node, struct extent_state, rb_node);
2058 if (state->start > search_end)
2060 if (contig && found && state->start > last + 1)
2062 if (state->end >= cur_start && (state->state & bits) == bits) {
2063 total_bytes += min(search_end, state->end) + 1 -
2064 max(cur_start, state->start);
2065 if (total_bytes >= max_bytes)
2068 *start = max(cur_start, state->start);
2072 } else if (contig && found) {
2075 node = rb_next(node);
2080 spin_unlock(&tree->lock);
2085 * set the private field for a given byte offset in the tree. If there isn't
2086 * an extent_state there already, this does nothing.
2088 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2089 struct io_failure_record *failrec)
2091 struct rb_node *node;
2092 struct extent_state *state;
2095 spin_lock(&tree->lock);
2097 * this search will find all the extents that end after
2100 node = tree_search(tree, start);
2105 state = rb_entry(node, struct extent_state, rb_node);
2106 if (state->start != start) {
2110 state->failrec = failrec;
2112 spin_unlock(&tree->lock);
2116 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2118 struct rb_node *node;
2119 struct extent_state *state;
2120 struct io_failure_record *failrec;
2122 spin_lock(&tree->lock);
2124 * this search will find all the extents that end after
2127 node = tree_search(tree, start);
2129 failrec = ERR_PTR(-ENOENT);
2132 state = rb_entry(node, struct extent_state, rb_node);
2133 if (state->start != start) {
2134 failrec = ERR_PTR(-ENOENT);
2138 failrec = state->failrec;
2140 spin_unlock(&tree->lock);
2145 * searches a range in the state tree for a given mask.
2146 * If 'filled' == 1, this returns 1 only if every extent in the tree
2147 * has the bits set. Otherwise, 1 is returned if any bit in the
2148 * range is found set.
2150 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2151 u32 bits, int filled, struct extent_state *cached)
2153 struct extent_state *state = NULL;
2154 struct rb_node *node;
2157 spin_lock(&tree->lock);
2158 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2159 cached->end > start)
2160 node = &cached->rb_node;
2162 node = tree_search(tree, start);
2163 while (node && start <= end) {
2164 state = rb_entry(node, struct extent_state, rb_node);
2166 if (filled && state->start > start) {
2171 if (state->start > end)
2174 if (state->state & bits) {
2178 } else if (filled) {
2183 if (state->end == (u64)-1)
2186 start = state->end + 1;
2189 node = rb_next(node);
2196 spin_unlock(&tree->lock);
2201 * helper function to set a given page up to date if all the
2202 * extents in the tree for that page are up to date
2204 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2206 u64 start = page_offset(page);
2207 u64 end = start + PAGE_SIZE - 1;
2208 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2209 SetPageUptodate(page);
2212 int free_io_failure(struct extent_io_tree *failure_tree,
2213 struct extent_io_tree *io_tree,
2214 struct io_failure_record *rec)
2219 set_state_failrec(failure_tree, rec->start, NULL);
2220 ret = clear_extent_bits(failure_tree, rec->start,
2221 rec->start + rec->len - 1,
2222 EXTENT_LOCKED | EXTENT_DIRTY);
2226 ret = clear_extent_bits(io_tree, rec->start,
2227 rec->start + rec->len - 1,
2237 * this bypasses the standard btrfs submit functions deliberately, as
2238 * the standard behavior is to write all copies in a raid setup. here we only
2239 * want to write the one bad copy. so we do the mapping for ourselves and issue
2240 * submit_bio directly.
2241 * to avoid any synchronization issues, wait for the data after writing, which
2242 * actually prevents the read that triggered the error from finishing.
2243 * currently, there can be no more than two copies of every data bit. thus,
2244 * exactly one rewrite is required.
2246 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2247 u64 length, u64 logical, struct page *page,
2248 unsigned int pg_offset, int mirror_num)
2251 struct btrfs_device *dev;
2254 struct btrfs_bio *bbio = NULL;
2257 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2258 BUG_ON(!mirror_num);
2260 bio = btrfs_io_bio_alloc(1);
2261 bio->bi_iter.bi_size = 0;
2262 map_length = length;
2265 * Avoid races with device replace and make sure our bbio has devices
2266 * associated to its stripes that don't go away while we are doing the
2267 * read repair operation.
2269 btrfs_bio_counter_inc_blocked(fs_info);
2270 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2272 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2273 * to update all raid stripes, but here we just want to correct
2274 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2275 * stripe's dev and sector.
2277 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2278 &map_length, &bbio, 0);
2280 btrfs_bio_counter_dec(fs_info);
2284 ASSERT(bbio->mirror_num == 1);
2286 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2287 &map_length, &bbio, mirror_num);
2289 btrfs_bio_counter_dec(fs_info);
2293 BUG_ON(mirror_num != bbio->mirror_num);
2296 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2297 bio->bi_iter.bi_sector = sector;
2298 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2299 btrfs_put_bbio(bbio);
2300 if (!dev || !dev->bdev ||
2301 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2302 btrfs_bio_counter_dec(fs_info);
2306 bio_set_dev(bio, dev->bdev);
2307 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2308 bio_add_page(bio, page, length, pg_offset);
2310 if (btrfsic_submit_bio_wait(bio)) {
2311 /* try to remap that extent elsewhere? */
2312 btrfs_bio_counter_dec(fs_info);
2314 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2318 btrfs_info_rl_in_rcu(fs_info,
2319 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2321 rcu_str_deref(dev->name), sector);
2322 btrfs_bio_counter_dec(fs_info);
2327 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2329 struct btrfs_fs_info *fs_info = eb->fs_info;
2330 u64 start = eb->start;
2331 int i, num_pages = num_extent_pages(eb);
2334 if (sb_rdonly(fs_info->sb))
2337 for (i = 0; i < num_pages; i++) {
2338 struct page *p = eb->pages[i];
2340 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2341 start - page_offset(p), mirror_num);
2351 * each time an IO finishes, we do a fast check in the IO failure tree
2352 * to see if we need to process or clean up an io_failure_record
2354 int clean_io_failure(struct btrfs_fs_info *fs_info,
2355 struct extent_io_tree *failure_tree,
2356 struct extent_io_tree *io_tree, u64 start,
2357 struct page *page, u64 ino, unsigned int pg_offset)
2360 struct io_failure_record *failrec;
2361 struct extent_state *state;
2366 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2371 failrec = get_state_failrec(failure_tree, start);
2372 if (IS_ERR(failrec))
2375 BUG_ON(!failrec->this_mirror);
2377 if (failrec->in_validation) {
2378 /* there was no real error, just free the record */
2379 btrfs_debug(fs_info,
2380 "clean_io_failure: freeing dummy error at %llu",
2384 if (sb_rdonly(fs_info->sb))
2387 spin_lock(&io_tree->lock);
2388 state = find_first_extent_bit_state(io_tree,
2391 spin_unlock(&io_tree->lock);
2393 if (state && state->start <= failrec->start &&
2394 state->end >= failrec->start + failrec->len - 1) {
2395 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2397 if (num_copies > 1) {
2398 repair_io_failure(fs_info, ino, start, failrec->len,
2399 failrec->logical, page, pg_offset,
2400 failrec->failed_mirror);
2405 free_io_failure(failure_tree, io_tree, failrec);
2411 * Can be called when
2412 * - hold extent lock
2413 * - under ordered extent
2414 * - the inode is freeing
2416 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2418 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2419 struct io_failure_record *failrec;
2420 struct extent_state *state, *next;
2422 if (RB_EMPTY_ROOT(&failure_tree->state))
2425 spin_lock(&failure_tree->lock);
2426 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2428 if (state->start > end)
2431 ASSERT(state->end <= end);
2433 next = next_state(state);
2435 failrec = state->failrec;
2436 free_extent_state(state);
2441 spin_unlock(&failure_tree->lock);
2444 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2448 struct io_failure_record *failrec;
2449 struct extent_map *em;
2450 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2451 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2452 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2456 failrec = get_state_failrec(failure_tree, start);
2457 if (!IS_ERR(failrec)) {
2458 btrfs_debug(fs_info,
2459 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2460 failrec->logical, failrec->start, failrec->len,
2461 failrec->in_validation);
2463 * when data can be on disk more than twice, add to failrec here
2464 * (e.g. with a list for failed_mirror) to make
2465 * clean_io_failure() clean all those errors at once.
2471 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2473 return ERR_PTR(-ENOMEM);
2475 failrec->start = start;
2476 failrec->len = end - start + 1;
2477 failrec->this_mirror = 0;
2478 failrec->bio_flags = 0;
2479 failrec->in_validation = 0;
2481 read_lock(&em_tree->lock);
2482 em = lookup_extent_mapping(em_tree, start, failrec->len);
2484 read_unlock(&em_tree->lock);
2486 return ERR_PTR(-EIO);
2489 if (em->start > start || em->start + em->len <= start) {
2490 free_extent_map(em);
2493 read_unlock(&em_tree->lock);
2496 return ERR_PTR(-EIO);
2499 logical = start - em->start;
2500 logical = em->block_start + logical;
2501 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2502 logical = em->block_start;
2503 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2504 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2507 btrfs_debug(fs_info,
2508 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2509 logical, start, failrec->len);
2511 failrec->logical = logical;
2512 free_extent_map(em);
2514 /* Set the bits in the private failure tree */
2515 ret = set_extent_bits(failure_tree, start, end,
2516 EXTENT_LOCKED | EXTENT_DIRTY);
2518 ret = set_state_failrec(failure_tree, start, failrec);
2519 /* Set the bits in the inode's tree */
2520 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2521 } else if (ret < 0) {
2523 return ERR_PTR(ret);
2529 static bool btrfs_check_repairable(struct inode *inode, bool needs_validation,
2530 struct io_failure_record *failrec,
2533 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2536 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2537 if (num_copies == 1) {
2539 * we only have a single copy of the data, so don't bother with
2540 * all the retry and error correction code that follows. no
2541 * matter what the error is, it is very likely to persist.
2543 btrfs_debug(fs_info,
2544 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2545 num_copies, failrec->this_mirror, failed_mirror);
2550 * there are two premises:
2551 * a) deliver good data to the caller
2552 * b) correct the bad sectors on disk
2554 if (needs_validation) {
2556 * to fulfill b), we need to know the exact failing sectors, as
2557 * we don't want to rewrite any more than the failed ones. thus,
2558 * we need separate read requests for the failed bio
2560 * if the following BUG_ON triggers, our validation request got
2561 * merged. we need separate requests for our algorithm to work.
2563 BUG_ON(failrec->in_validation);
2564 failrec->in_validation = 1;
2565 failrec->this_mirror = failed_mirror;
2568 * we're ready to fulfill a) and b) alongside. get a good copy
2569 * of the failed sector and if we succeed, we have setup
2570 * everything for repair_io_failure to do the rest for us.
2572 if (failrec->in_validation) {
2573 BUG_ON(failrec->this_mirror != failed_mirror);
2574 failrec->in_validation = 0;
2575 failrec->this_mirror = 0;
2577 failrec->failed_mirror = failed_mirror;
2578 failrec->this_mirror++;
2579 if (failrec->this_mirror == failed_mirror)
2580 failrec->this_mirror++;
2583 if (failrec->this_mirror > num_copies) {
2584 btrfs_debug(fs_info,
2585 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2586 num_copies, failrec->this_mirror, failed_mirror);
2593 static bool btrfs_io_needs_validation(struct inode *inode, struct bio *bio)
2596 const u32 blocksize = inode->i_sb->s_blocksize;
2599 * If bi_status is BLK_STS_OK, then this was a checksum error, not an
2600 * I/O error. In this case, we already know exactly which sector was
2601 * bad, so we don't need to validate.
2603 if (bio->bi_status == BLK_STS_OK)
2607 * We need to validate each sector individually if the failed I/O was
2608 * for multiple sectors.
2610 * There are a few possible bios that can end up here:
2611 * 1. A buffered read bio, which is not cloned.
2612 * 2. A direct I/O read bio, which is cloned.
2613 * 3. A (buffered or direct) repair bio, which is not cloned.
2615 * For cloned bios (case 2), we can get the size from
2616 * btrfs_io_bio->iter; for non-cloned bios (cases 1 and 3), we can get
2617 * it from the bvecs.
2619 if (bio_flagged(bio, BIO_CLONED)) {
2620 if (btrfs_io_bio(bio)->iter.bi_size > blocksize)
2623 struct bio_vec *bvec;
2626 bio_for_each_bvec_all(bvec, bio, i) {
2627 len += bvec->bv_len;
2628 if (len > blocksize)
2635 blk_status_t btrfs_submit_read_repair(struct inode *inode,
2636 struct bio *failed_bio, u32 bio_offset,
2637 struct page *page, unsigned int pgoff,
2638 u64 start, u64 end, int failed_mirror,
2639 submit_bio_hook_t *submit_bio_hook)
2641 struct io_failure_record *failrec;
2642 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2643 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2644 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2645 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
2646 const int icsum = bio_offset >> fs_info->sectorsize_bits;
2647 bool need_validation;
2648 struct bio *repair_bio;
2649 struct btrfs_io_bio *repair_io_bio;
2650 blk_status_t status;
2652 btrfs_debug(fs_info,
2653 "repair read error: read error at %llu", start);
2655 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2657 failrec = btrfs_get_io_failure_record(inode, start, end);
2658 if (IS_ERR(failrec))
2659 return errno_to_blk_status(PTR_ERR(failrec));
2661 need_validation = btrfs_io_needs_validation(inode, failed_bio);
2663 if (!btrfs_check_repairable(inode, need_validation, failrec,
2665 free_io_failure(failure_tree, tree, failrec);
2666 return BLK_STS_IOERR;
2669 repair_bio = btrfs_io_bio_alloc(1);
2670 repair_io_bio = btrfs_io_bio(repair_bio);
2671 repair_bio->bi_opf = REQ_OP_READ;
2672 if (need_validation)
2673 repair_bio->bi_opf |= REQ_FAILFAST_DEV;
2674 repair_bio->bi_end_io = failed_bio->bi_end_io;
2675 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2676 repair_bio->bi_private = failed_bio->bi_private;
2678 if (failed_io_bio->csum) {
2679 const u32 csum_size = fs_info->csum_size;
2681 repair_io_bio->csum = repair_io_bio->csum_inline;
2682 memcpy(repair_io_bio->csum,
2683 failed_io_bio->csum + csum_size * icsum, csum_size);
2686 bio_add_page(repair_bio, page, failrec->len, pgoff);
2687 repair_io_bio->logical = failrec->start;
2688 repair_io_bio->iter = repair_bio->bi_iter;
2690 btrfs_debug(btrfs_sb(inode->i_sb),
2691 "repair read error: submitting new read to mirror %d, in_validation=%d",
2692 failrec->this_mirror, failrec->in_validation);
2694 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2695 failrec->bio_flags);
2697 free_io_failure(failure_tree, tree, failrec);
2698 bio_put(repair_bio);
2703 /* lots and lots of room for performance fixes in the end_bio funcs */
2705 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2707 int uptodate = (err == 0);
2710 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2713 ClearPageUptodate(page);
2715 ret = err < 0 ? err : -EIO;
2716 mapping_set_error(page->mapping, ret);
2721 * after a writepage IO is done, we need to:
2722 * clear the uptodate bits on error
2723 * clear the writeback bits in the extent tree for this IO
2724 * end_page_writeback if the page has no more pending IO
2726 * Scheduling is not allowed, so the extent state tree is expected
2727 * to have one and only one object corresponding to this IO.
2729 static void end_bio_extent_writepage(struct bio *bio)
2731 int error = blk_status_to_errno(bio->bi_status);
2732 struct bio_vec *bvec;
2735 struct bvec_iter_all iter_all;
2737 ASSERT(!bio_flagged(bio, BIO_CLONED));
2738 bio_for_each_segment_all(bvec, bio, iter_all) {
2739 struct page *page = bvec->bv_page;
2740 struct inode *inode = page->mapping->host;
2741 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2743 /* We always issue full-page reads, but if some block
2744 * in a page fails to read, blk_update_request() will
2745 * advance bv_offset and adjust bv_len to compensate.
2746 * Print a warning for nonzero offsets, and an error
2747 * if they don't add up to a full page. */
2748 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2749 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2751 "partial page write in btrfs with offset %u and length %u",
2752 bvec->bv_offset, bvec->bv_len);
2755 "incomplete page write in btrfs with offset %u and length %u",
2756 bvec->bv_offset, bvec->bv_len);
2759 start = page_offset(page);
2760 end = start + bvec->bv_offset + bvec->bv_len - 1;
2762 end_extent_writepage(page, error, start, end);
2763 end_page_writeback(page);
2770 * Record previously processed extent range
2772 * For endio_readpage_release_extent() to handle a full extent range, reducing
2773 * the extent io operations.
2775 struct processed_extent {
2776 struct btrfs_inode *inode;
2777 /* Start of the range in @inode */
2779 /* End of the range in @inode */
2785 * Try to release processed extent range
2787 * May not release the extent range right now if the current range is
2788 * contiguous to processed extent.
2790 * Will release processed extent when any of @inode, @uptodate, the range is
2791 * no longer contiguous to the processed range.
2793 * Passing @inode == NULL will force processed extent to be released.
2795 static void endio_readpage_release_extent(struct processed_extent *processed,
2796 struct btrfs_inode *inode, u64 start, u64 end,
2799 struct extent_state *cached = NULL;
2800 struct extent_io_tree *tree;
2802 /* The first extent, initialize @processed */
2803 if (!processed->inode)
2807 * Contiguous to processed extent, just uptodate the end.
2809 * Several things to notice:
2811 * - bio can be merged as long as on-disk bytenr is contiguous
2812 * This means we can have page belonging to other inodes, thus need to
2813 * check if the inode still matches.
2814 * - bvec can contain range beyond current page for multi-page bvec
2815 * Thus we need to do processed->end + 1 >= start check
2817 if (processed->inode == inode && processed->uptodate == uptodate &&
2818 processed->end + 1 >= start && end >= processed->end) {
2819 processed->end = end;
2823 tree = &processed->inode->io_tree;
2825 * Now we don't have range contiguous to the processed range, release
2826 * the processed range now.
2828 if (processed->uptodate && tree->track_uptodate)
2829 set_extent_uptodate(tree, processed->start, processed->end,
2830 &cached, GFP_ATOMIC);
2831 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2835 /* Update processed to current range */
2836 processed->inode = inode;
2837 processed->start = start;
2838 processed->end = end;
2839 processed->uptodate = uptodate;
2842 static void endio_readpage_update_page_status(struct page *page, bool uptodate)
2845 SetPageUptodate(page);
2847 ClearPageUptodate(page);
2854 * after a readpage IO is done, we need to:
2855 * clear the uptodate bits on error
2856 * set the uptodate bits if things worked
2857 * set the page up to date if all extents in the tree are uptodate
2858 * clear the lock bit in the extent tree
2859 * unlock the page if there are no other extents locked for it
2861 * Scheduling is not allowed, so the extent state tree is expected
2862 * to have one and only one object corresponding to this IO.
2864 static void end_bio_extent_readpage(struct bio *bio)
2866 struct bio_vec *bvec;
2867 int uptodate = !bio->bi_status;
2868 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2869 struct extent_io_tree *tree, *failure_tree;
2870 struct processed_extent processed = { 0 };
2872 * The offset to the beginning of a bio, since one bio can never be
2873 * larger than UINT_MAX, u32 here is enough.
2878 struct bvec_iter_all iter_all;
2880 ASSERT(!bio_flagged(bio, BIO_CLONED));
2881 bio_for_each_segment_all(bvec, bio, iter_all) {
2882 struct page *page = bvec->bv_page;
2883 struct inode *inode = page->mapping->host;
2884 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2885 const u32 sectorsize = fs_info->sectorsize;
2890 btrfs_debug(fs_info,
2891 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2892 bio->bi_iter.bi_sector, bio->bi_status,
2893 io_bio->mirror_num);
2894 tree = &BTRFS_I(inode)->io_tree;
2895 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2898 * We always issue full-sector reads, but if some block in a
2899 * page fails to read, blk_update_request() will advance
2900 * bv_offset and adjust bv_len to compensate. Print a warning
2901 * for unaligned offsets, and an error if they don't add up to
2904 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2906 "partial page read in btrfs with offset %u and length %u",
2907 bvec->bv_offset, bvec->bv_len);
2908 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
2911 "incomplete page read with offset %u and length %u",
2912 bvec->bv_offset, bvec->bv_len);
2914 start = page_offset(page) + bvec->bv_offset;
2915 end = start + bvec->bv_len - 1;
2918 mirror = io_bio->mirror_num;
2919 if (likely(uptodate)) {
2920 if (is_data_inode(inode))
2921 ret = btrfs_verify_data_csum(io_bio,
2922 bio_offset, page, start, end,
2925 ret = btrfs_validate_metadata_buffer(io_bio,
2926 page, start, end, mirror);
2930 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2931 failure_tree, tree, start,
2933 btrfs_ino(BTRFS_I(inode)), 0);
2936 if (likely(uptodate))
2939 if (is_data_inode(inode)) {
2942 * The generic bio_readpage_error handles errors the
2943 * following way: If possible, new read requests are
2944 * created and submitted and will end up in
2945 * end_bio_extent_readpage as well (if we're lucky,
2946 * not in the !uptodate case). In that case it returns
2947 * 0 and we just go on with the next page in our bio.
2948 * If it can't handle the error it will return -EIO and
2949 * we remain responsible for that page.
2951 if (!btrfs_submit_read_repair(inode, bio, bio_offset,
2953 start - page_offset(page),
2955 btrfs_submit_data_bio)) {
2956 uptodate = !bio->bi_status;
2957 ASSERT(bio_offset + len > bio_offset);
2962 struct extent_buffer *eb;
2964 eb = (struct extent_buffer *)page->private;
2965 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2966 eb->read_mirror = mirror;
2967 atomic_dec(&eb->io_pages);
2968 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2970 btree_readahead_hook(eb, -EIO);
2973 if (likely(uptodate)) {
2974 loff_t i_size = i_size_read(inode);
2975 pgoff_t end_index = i_size >> PAGE_SHIFT;
2978 /* Zero out the end if this page straddles i_size */
2979 off = offset_in_page(i_size);
2980 if (page->index == end_index && off)
2981 zero_user_segment(page, off, PAGE_SIZE);
2983 ASSERT(bio_offset + len > bio_offset);
2986 /* Update page status and unlock */
2987 endio_readpage_update_page_status(page, uptodate);
2988 endio_readpage_release_extent(&processed, BTRFS_I(inode),
2989 start, end, uptodate);
2991 /* Release the last extent */
2992 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
2993 btrfs_io_bio_free_csum(io_bio);
2998 * Initialize the members up to but not including 'bio'. Use after allocating a
2999 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3000 * 'bio' because use of __GFP_ZERO is not supported.
3002 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
3004 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3008 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3009 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3010 * for the appropriate container_of magic
3012 struct bio *btrfs_bio_alloc(u64 first_byte)
3016 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
3017 bio->bi_iter.bi_sector = first_byte >> 9;
3018 btrfs_io_bio_init(btrfs_io_bio(bio));
3022 struct bio *btrfs_bio_clone(struct bio *bio)
3024 struct btrfs_io_bio *btrfs_bio;
3027 /* Bio allocation backed by a bioset does not fail */
3028 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
3029 btrfs_bio = btrfs_io_bio(new);
3030 btrfs_io_bio_init(btrfs_bio);
3031 btrfs_bio->iter = bio->bi_iter;
3035 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
3039 /* Bio allocation backed by a bioset does not fail */
3040 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
3041 btrfs_io_bio_init(btrfs_io_bio(bio));
3045 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
3048 struct btrfs_io_bio *btrfs_bio;
3050 /* this will never fail when it's backed by a bioset */
3051 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
3054 btrfs_bio = btrfs_io_bio(bio);
3055 btrfs_io_bio_init(btrfs_bio);
3057 bio_trim(bio, offset >> 9, size >> 9);
3058 btrfs_bio->iter = bio->bi_iter;
3063 * @opf: bio REQ_OP_* and REQ_* flags as one value
3064 * @wbc: optional writeback control for io accounting
3065 * @page: page to add to the bio
3066 * @disk_bytenr: logical bytenr where the write will be
3067 * @size: portion of page that we want to write to
3068 * @pg_offset: offset of the new bio or to check whether we are adding
3069 * a contiguous page to the previous one
3070 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
3071 * @end_io_func: end_io callback for new bio
3072 * @mirror_num: desired mirror to read/write
3073 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3074 * @bio_flags: flags of the current bio to see if we can merge them
3076 static int submit_extent_page(unsigned int opf,
3077 struct writeback_control *wbc,
3078 struct page *page, u64 disk_bytenr,
3079 size_t size, unsigned long pg_offset,
3080 struct bio **bio_ret,
3081 bio_end_io_t end_io_func,
3083 unsigned long prev_bio_flags,
3084 unsigned long bio_flags,
3085 bool force_bio_submit)
3089 size_t io_size = min_t(size_t, size, PAGE_SIZE);
3090 sector_t sector = disk_bytenr >> 9;
3091 struct extent_io_tree *tree = &BTRFS_I(page->mapping->host)->io_tree;
3097 bool can_merge = true;
3100 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
3101 contig = bio->bi_iter.bi_sector == sector;
3103 contig = bio_end_sector(bio) == sector;
3105 if (btrfs_bio_fits_in_stripe(page, io_size, bio, bio_flags))
3108 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
3110 bio_add_page(bio, page, io_size, pg_offset) < io_size) {
3111 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
3119 wbc_account_cgroup_owner(wbc, page, io_size);
3124 bio = btrfs_bio_alloc(disk_bytenr);
3125 bio_add_page(bio, page, io_size, pg_offset);
3126 bio->bi_end_io = end_io_func;
3127 bio->bi_private = tree;
3128 bio->bi_write_hint = page->mapping->host->i_write_hint;
3131 struct block_device *bdev;
3133 bdev = BTRFS_I(page->mapping->host)->root->fs_info->fs_devices->latest_bdev;
3134 bio_set_dev(bio, bdev);
3135 wbc_init_bio(wbc, bio);
3136 wbc_account_cgroup_owner(wbc, page, io_size);
3144 static void attach_extent_buffer_page(struct extent_buffer *eb,
3148 * If the page is mapped to btree inode, we should hold the private
3149 * lock to prevent race.
3150 * For cloned or dummy extent buffers, their pages are not mapped and
3151 * will not race with any other ebs.
3154 lockdep_assert_held(&page->mapping->private_lock);
3156 if (!PagePrivate(page))
3157 attach_page_private(page, eb);
3159 WARN_ON(page->private != (unsigned long)eb);
3162 void set_page_extent_mapped(struct page *page)
3164 if (!PagePrivate(page))
3165 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3168 static struct extent_map *
3169 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3170 u64 start, u64 len, struct extent_map **em_cached)
3172 struct extent_map *em;
3174 if (em_cached && *em_cached) {
3176 if (extent_map_in_tree(em) && start >= em->start &&
3177 start < extent_map_end(em)) {
3178 refcount_inc(&em->refs);
3182 free_extent_map(em);
3186 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3187 if (em_cached && !IS_ERR_OR_NULL(em)) {
3189 refcount_inc(&em->refs);
3195 * basic readpage implementation. Locked extent state structs are inserted
3196 * into the tree that are removed when the IO is done (by the end_io
3198 * XXX JDM: This needs looking at to ensure proper page locking
3199 * return 0 on success, otherwise return error
3201 int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3202 struct bio **bio, unsigned long *bio_flags,
3203 unsigned int read_flags, u64 *prev_em_start)
3205 struct inode *inode = page->mapping->host;
3206 u64 start = page_offset(page);
3207 const u64 end = start + PAGE_SIZE - 1;
3210 u64 last_byte = i_size_read(inode);
3213 struct extent_map *em;
3216 size_t pg_offset = 0;
3218 size_t blocksize = inode->i_sb->s_blocksize;
3219 unsigned long this_bio_flag = 0;
3220 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3222 set_page_extent_mapped(page);
3224 if (!PageUptodate(page)) {
3225 if (cleancache_get_page(page) == 0) {
3226 BUG_ON(blocksize != PAGE_SIZE);
3227 unlock_extent(tree, start, end);
3232 if (page->index == last_byte >> PAGE_SHIFT) {
3234 size_t zero_offset = offset_in_page(last_byte);
3237 iosize = PAGE_SIZE - zero_offset;
3238 userpage = kmap_atomic(page);
3239 memset(userpage + zero_offset, 0, iosize);
3240 flush_dcache_page(page);
3241 kunmap_atomic(userpage);
3244 while (cur <= end) {
3245 bool force_bio_submit = false;
3248 if (cur >= last_byte) {
3250 struct extent_state *cached = NULL;
3252 iosize = PAGE_SIZE - pg_offset;
3253 userpage = kmap_atomic(page);
3254 memset(userpage + pg_offset, 0, iosize);
3255 flush_dcache_page(page);
3256 kunmap_atomic(userpage);
3257 set_extent_uptodate(tree, cur, cur + iosize - 1,
3259 unlock_extent_cached(tree, cur,
3260 cur + iosize - 1, &cached);
3263 em = __get_extent_map(inode, page, pg_offset, cur,
3264 end - cur + 1, em_cached);
3265 if (IS_ERR_OR_NULL(em)) {
3267 unlock_extent(tree, cur, end);
3270 extent_offset = cur - em->start;
3271 BUG_ON(extent_map_end(em) <= cur);
3274 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3275 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3276 extent_set_compress_type(&this_bio_flag,
3280 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3281 cur_end = min(extent_map_end(em) - 1, end);
3282 iosize = ALIGN(iosize, blocksize);
3283 if (this_bio_flag & EXTENT_BIO_COMPRESSED)
3284 disk_bytenr = em->block_start;
3286 disk_bytenr = em->block_start + extent_offset;
3287 block_start = em->block_start;
3288 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3289 block_start = EXTENT_MAP_HOLE;
3292 * If we have a file range that points to a compressed extent
3293 * and it's followed by a consecutive file range that points
3294 * to the same compressed extent (possibly with a different
3295 * offset and/or length, so it either points to the whole extent
3296 * or only part of it), we must make sure we do not submit a
3297 * single bio to populate the pages for the 2 ranges because
3298 * this makes the compressed extent read zero out the pages
3299 * belonging to the 2nd range. Imagine the following scenario:
3302 * [0 - 8K] [8K - 24K]
3305 * points to extent X, points to extent X,
3306 * offset 4K, length of 8K offset 0, length 16K
3308 * [extent X, compressed length = 4K uncompressed length = 16K]
3310 * If the bio to read the compressed extent covers both ranges,
3311 * it will decompress extent X into the pages belonging to the
3312 * first range and then it will stop, zeroing out the remaining
3313 * pages that belong to the other range that points to extent X.
3314 * So here we make sure we submit 2 bios, one for the first
3315 * range and another one for the third range. Both will target
3316 * the same physical extent from disk, but we can't currently
3317 * make the compressed bio endio callback populate the pages
3318 * for both ranges because each compressed bio is tightly
3319 * coupled with a single extent map, and each range can have
3320 * an extent map with a different offset value relative to the
3321 * uncompressed data of our extent and different lengths. This
3322 * is a corner case so we prioritize correctness over
3323 * non-optimal behavior (submitting 2 bios for the same extent).
3325 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3326 prev_em_start && *prev_em_start != (u64)-1 &&
3327 *prev_em_start != em->start)
3328 force_bio_submit = true;
3331 *prev_em_start = em->start;
3333 free_extent_map(em);
3336 /* we've found a hole, just zero and go on */
3337 if (block_start == EXTENT_MAP_HOLE) {
3339 struct extent_state *cached = NULL;
3341 userpage = kmap_atomic(page);
3342 memset(userpage + pg_offset, 0, iosize);
3343 flush_dcache_page(page);
3344 kunmap_atomic(userpage);
3346 set_extent_uptodate(tree, cur, cur + iosize - 1,
3348 unlock_extent_cached(tree, cur,
3349 cur + iosize - 1, &cached);
3351 pg_offset += iosize;
3354 /* the get_extent function already copied into the page */
3355 if (test_range_bit(tree, cur, cur_end,
3356 EXTENT_UPTODATE, 1, NULL)) {
3357 check_page_uptodate(tree, page);
3358 unlock_extent(tree, cur, cur + iosize - 1);
3360 pg_offset += iosize;
3363 /* we have an inline extent but it didn't get marked up
3364 * to date. Error out
3366 if (block_start == EXTENT_MAP_INLINE) {
3368 unlock_extent(tree, cur, cur + iosize - 1);
3370 pg_offset += iosize;
3374 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3375 page, disk_bytenr, iosize,
3377 end_bio_extent_readpage, 0,
3383 *bio_flags = this_bio_flag;
3386 unlock_extent(tree, cur, cur + iosize - 1);
3390 pg_offset += iosize;
3394 if (!PageError(page))
3395 SetPageUptodate(page);
3401 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3403 struct extent_map **em_cached,
3405 unsigned long *bio_flags,
3408 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3411 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3413 for (index = 0; index < nr_pages; index++) {
3414 btrfs_do_readpage(pages[index], em_cached, bio, bio_flags,
3415 REQ_RAHEAD, prev_em_start);
3416 put_page(pages[index]);
3420 static void update_nr_written(struct writeback_control *wbc,
3421 unsigned long nr_written)
3423 wbc->nr_to_write -= nr_written;
3427 * helper for __extent_writepage, doing all of the delayed allocation setup.
3429 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3430 * to write the page (copy into inline extent). In this case the IO has
3431 * been started and the page is already unlocked.
3433 * This returns 0 if all went well (page still locked)
3434 * This returns < 0 if there were errors (page still locked)
3436 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3437 struct page *page, struct writeback_control *wbc,
3438 u64 delalloc_start, unsigned long *nr_written)
3440 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3442 u64 delalloc_to_write = 0;
3443 u64 delalloc_end = 0;
3445 int page_started = 0;
3448 while (delalloc_end < page_end) {
3449 found = find_lock_delalloc_range(&inode->vfs_inode, page,
3453 delalloc_start = delalloc_end + 1;
3456 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3457 delalloc_end, &page_started, nr_written, wbc);
3461 * btrfs_run_delalloc_range should return < 0 for error
3462 * but just in case, we use > 0 here meaning the IO is
3463 * started, so we don't want to return > 0 unless
3464 * things are going well.
3466 return ret < 0 ? ret : -EIO;
3469 * delalloc_end is already one less than the total length, so
3470 * we don't subtract one from PAGE_SIZE
3472 delalloc_to_write += (delalloc_end - delalloc_start +
3473 PAGE_SIZE) >> PAGE_SHIFT;
3474 delalloc_start = delalloc_end + 1;
3476 if (wbc->nr_to_write < delalloc_to_write) {
3479 if (delalloc_to_write < thresh * 2)
3480 thresh = delalloc_to_write;
3481 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3485 /* did the fill delalloc function already unlock and start
3490 * we've unlocked the page, so we can't update
3491 * the mapping's writeback index, just update
3494 wbc->nr_to_write -= *nr_written;
3502 * helper for __extent_writepage. This calls the writepage start hooks,
3503 * and does the loop to map the page into extents and bios.
3505 * We return 1 if the IO is started and the page is unlocked,
3506 * 0 if all went well (page still locked)
3507 * < 0 if there were errors (page still locked)
3509 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3511 struct writeback_control *wbc,
3512 struct extent_page_data *epd,
3514 unsigned long nr_written,
3517 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3518 struct extent_io_tree *tree = &inode->io_tree;
3519 u64 start = page_offset(page);
3520 u64 end = start + PAGE_SIZE - 1;
3524 struct extent_map *em;
3527 const unsigned int write_flags = wbc_to_write_flags(wbc);
3530 ret = btrfs_writepage_cow_fixup(page, start, end);
3532 /* Fixup worker will requeue */
3533 redirty_page_for_writepage(wbc, page);
3534 update_nr_written(wbc, nr_written);
3540 * we don't want to touch the inode after unlocking the page,
3541 * so we update the mapping writeback index now
3543 update_nr_written(wbc, nr_written + 1);
3545 while (cur <= end) {
3550 if (cur >= i_size) {
3551 btrfs_writepage_endio_finish_ordered(page, cur, end, 1);
3554 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
3555 if (IS_ERR_OR_NULL(em)) {
3557 ret = PTR_ERR_OR_ZERO(em);
3561 extent_offset = cur - em->start;
3562 em_end = extent_map_end(em);
3563 ASSERT(cur <= em_end);
3565 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3566 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
3567 block_start = em->block_start;
3568 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3569 disk_bytenr = em->block_start + extent_offset;
3571 /* Note that em_end from extent_map_end() is exclusive */
3572 iosize = min(em_end, end + 1) - cur;
3573 free_extent_map(em);
3577 * compressed and inline extents are written through other
3580 if (compressed || block_start == EXTENT_MAP_HOLE ||
3581 block_start == EXTENT_MAP_INLINE) {
3585 btrfs_writepage_endio_finish_ordered(page, cur,
3586 cur + iosize - 1, 1);
3591 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3592 if (!PageWriteback(page)) {
3593 btrfs_err(inode->root->fs_info,
3594 "page %lu not writeback, cur %llu end %llu",
3595 page->index, cur, end);
3598 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
3599 page, disk_bytenr, iosize,
3600 cur - page_offset(page), &epd->bio,
3601 end_bio_extent_writepage,
3605 if (PageWriteback(page))
3606 end_page_writeback(page);
3617 * the writepage semantics are similar to regular writepage. extent
3618 * records are inserted to lock ranges in the tree, and as dirty areas
3619 * are found, they are marked writeback. Then the lock bits are removed
3620 * and the end_io handler clears the writeback ranges
3622 * Return 0 if everything goes well.
3623 * Return <0 for error.
3625 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3626 struct extent_page_data *epd)
3628 struct inode *inode = page->mapping->host;
3629 u64 start = page_offset(page);
3630 u64 page_end = start + PAGE_SIZE - 1;
3634 loff_t i_size = i_size_read(inode);
3635 unsigned long end_index = i_size >> PAGE_SHIFT;
3636 unsigned long nr_written = 0;
3638 trace___extent_writepage(page, inode, wbc);
3640 WARN_ON(!PageLocked(page));
3642 ClearPageError(page);
3644 pg_offset = offset_in_page(i_size);
3645 if (page->index > end_index ||
3646 (page->index == end_index && !pg_offset)) {
3647 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3652 if (page->index == end_index) {
3655 userpage = kmap_atomic(page);
3656 memset(userpage + pg_offset, 0,
3657 PAGE_SIZE - pg_offset);
3658 kunmap_atomic(userpage);
3659 flush_dcache_page(page);
3662 set_page_extent_mapped(page);
3664 if (!epd->extent_locked) {
3665 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3673 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3680 /* make sure the mapping tag for page dirty gets cleared */
3681 set_page_writeback(page);
3682 end_page_writeback(page);
3684 if (PageError(page)) {
3685 ret = ret < 0 ? ret : -EIO;
3686 end_extent_writepage(page, ret, start, page_end);
3693 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3695 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3696 TASK_UNINTERRUPTIBLE);
3699 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3701 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3702 smp_mb__after_atomic();
3703 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3707 * Lock extent buffer status and pages for writeback.
3709 * May try to flush write bio if we can't get the lock.
3711 * Return 0 if the extent buffer doesn't need to be submitted.
3712 * (E.g. the extent buffer is not dirty)
3713 * Return >0 is the extent buffer is submitted to bio.
3714 * Return <0 if something went wrong, no page is locked.
3716 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3717 struct extent_page_data *epd)
3719 struct btrfs_fs_info *fs_info = eb->fs_info;
3720 int i, num_pages, failed_page_nr;
3724 if (!btrfs_try_tree_write_lock(eb)) {
3725 ret = flush_write_bio(epd);
3729 btrfs_tree_lock(eb);
3732 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3733 btrfs_tree_unlock(eb);
3737 ret = flush_write_bio(epd);
3743 wait_on_extent_buffer_writeback(eb);
3744 btrfs_tree_lock(eb);
3745 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3747 btrfs_tree_unlock(eb);
3752 * We need to do this to prevent races in people who check if the eb is
3753 * under IO since we can end up having no IO bits set for a short period
3756 spin_lock(&eb->refs_lock);
3757 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3758 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3759 spin_unlock(&eb->refs_lock);
3760 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3761 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3763 fs_info->dirty_metadata_batch);
3766 spin_unlock(&eb->refs_lock);
3769 btrfs_tree_unlock(eb);
3774 num_pages = num_extent_pages(eb);
3775 for (i = 0; i < num_pages; i++) {
3776 struct page *p = eb->pages[i];
3778 if (!trylock_page(p)) {
3782 err = flush_write_bio(epd);
3796 /* Unlock already locked pages */
3797 for (i = 0; i < failed_page_nr; i++)
3798 unlock_page(eb->pages[i]);
3800 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3801 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3802 * be made and undo everything done before.
3804 btrfs_tree_lock(eb);
3805 spin_lock(&eb->refs_lock);
3806 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3807 end_extent_buffer_writeback(eb);
3808 spin_unlock(&eb->refs_lock);
3809 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3810 fs_info->dirty_metadata_batch);
3811 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3812 btrfs_tree_unlock(eb);
3816 static void set_btree_ioerr(struct page *page)
3818 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3819 struct btrfs_fs_info *fs_info;
3822 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3826 * If we error out, we should add back the dirty_metadata_bytes
3827 * to make it consistent.
3829 fs_info = eb->fs_info;
3830 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3831 eb->len, fs_info->dirty_metadata_batch);
3834 * If writeback for a btree extent that doesn't belong to a log tree
3835 * failed, increment the counter transaction->eb_write_errors.
3836 * We do this because while the transaction is running and before it's
3837 * committing (when we call filemap_fdata[write|wait]_range against
3838 * the btree inode), we might have
3839 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3840 * returns an error or an error happens during writeback, when we're
3841 * committing the transaction we wouldn't know about it, since the pages
3842 * can be no longer dirty nor marked anymore for writeback (if a
3843 * subsequent modification to the extent buffer didn't happen before the
3844 * transaction commit), which makes filemap_fdata[write|wait]_range not
3845 * able to find the pages tagged with SetPageError at transaction
3846 * commit time. So if this happens we must abort the transaction,
3847 * otherwise we commit a super block with btree roots that point to
3848 * btree nodes/leafs whose content on disk is invalid - either garbage
3849 * or the content of some node/leaf from a past generation that got
3850 * cowed or deleted and is no longer valid.
3852 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3853 * not be enough - we need to distinguish between log tree extents vs
3854 * non-log tree extents, and the next filemap_fdatawait_range() call
3855 * will catch and clear such errors in the mapping - and that call might
3856 * be from a log sync and not from a transaction commit. Also, checking
3857 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3858 * not done and would not be reliable - the eb might have been released
3859 * from memory and reading it back again means that flag would not be
3860 * set (since it's a runtime flag, not persisted on disk).
3862 * Using the flags below in the btree inode also makes us achieve the
3863 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3864 * writeback for all dirty pages and before filemap_fdatawait_range()
3865 * is called, the writeback for all dirty pages had already finished
3866 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3867 * filemap_fdatawait_range() would return success, as it could not know
3868 * that writeback errors happened (the pages were no longer tagged for
3871 switch (eb->log_index) {
3873 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3876 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3879 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3882 BUG(); /* unexpected, logic error */
3886 static void end_bio_extent_buffer_writepage(struct bio *bio)
3888 struct bio_vec *bvec;
3889 struct extent_buffer *eb;
3891 struct bvec_iter_all iter_all;
3893 ASSERT(!bio_flagged(bio, BIO_CLONED));
3894 bio_for_each_segment_all(bvec, bio, iter_all) {
3895 struct page *page = bvec->bv_page;
3897 eb = (struct extent_buffer *)page->private;
3899 done = atomic_dec_and_test(&eb->io_pages);
3901 if (bio->bi_status ||
3902 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3903 ClearPageUptodate(page);
3904 set_btree_ioerr(page);
3907 end_page_writeback(page);
3912 end_extent_buffer_writeback(eb);
3918 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3919 struct writeback_control *wbc,
3920 struct extent_page_data *epd)
3922 u64 disk_bytenr = eb->start;
3925 unsigned long start, end;
3926 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3929 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3930 num_pages = num_extent_pages(eb);
3931 atomic_set(&eb->io_pages, num_pages);
3933 /* set btree blocks beyond nritems with 0 to avoid stale content. */
3934 nritems = btrfs_header_nritems(eb);
3935 if (btrfs_header_level(eb) > 0) {
3936 end = btrfs_node_key_ptr_offset(nritems);
3938 memzero_extent_buffer(eb, end, eb->len - end);
3942 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3944 start = btrfs_item_nr_offset(nritems);
3945 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
3946 memzero_extent_buffer(eb, start, end - start);
3949 for (i = 0; i < num_pages; i++) {
3950 struct page *p = eb->pages[i];
3952 clear_page_dirty_for_io(p);
3953 set_page_writeback(p);
3954 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
3955 p, disk_bytenr, PAGE_SIZE, 0,
3957 end_bio_extent_buffer_writepage,
3961 if (PageWriteback(p))
3962 end_page_writeback(p);
3963 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3964 end_extent_buffer_writeback(eb);
3968 disk_bytenr += PAGE_SIZE;
3969 update_nr_written(wbc, 1);
3973 if (unlikely(ret)) {
3974 for (; i < num_pages; i++) {
3975 struct page *p = eb->pages[i];
3976 clear_page_dirty_for_io(p);
3985 * Submit all page(s) of one extent buffer.
3987 * @page: the page of one extent buffer
3988 * @eb_context: to determine if we need to submit this page, if current page
3989 * belongs to this eb, we don't need to submit
3991 * The caller should pass each page in their bytenr order, and here we use
3992 * @eb_context to determine if we have submitted pages of one extent buffer.
3994 * If we have, we just skip until we hit a new page that doesn't belong to
3995 * current @eb_context.
3997 * If not, we submit all the page(s) of the extent buffer.
3999 * Return >0 if we have submitted the extent buffer successfully.
4000 * Return 0 if we don't need to submit the page, as it's already submitted by
4002 * Return <0 for fatal error.
4004 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4005 struct extent_page_data *epd,
4006 struct extent_buffer **eb_context)
4008 struct address_space *mapping = page->mapping;
4009 struct extent_buffer *eb;
4012 if (!PagePrivate(page))
4015 spin_lock(&mapping->private_lock);
4016 if (!PagePrivate(page)) {
4017 spin_unlock(&mapping->private_lock);
4021 eb = (struct extent_buffer *)page->private;
4024 * Shouldn't happen and normally this would be a BUG_ON but no point
4025 * crashing the machine for something we can survive anyway.
4028 spin_unlock(&mapping->private_lock);
4032 if (eb == *eb_context) {
4033 spin_unlock(&mapping->private_lock);
4036 ret = atomic_inc_not_zero(&eb->refs);
4037 spin_unlock(&mapping->private_lock);
4043 ret = lock_extent_buffer_for_io(eb, epd);
4045 free_extent_buffer(eb);
4048 ret = write_one_eb(eb, wbc, epd);
4049 free_extent_buffer(eb);
4055 int btree_write_cache_pages(struct address_space *mapping,
4056 struct writeback_control *wbc)
4058 struct extent_buffer *eb_context = NULL;
4059 struct extent_page_data epd = {
4062 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4064 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4067 int nr_to_write_done = 0;
4068 struct pagevec pvec;
4071 pgoff_t end; /* Inclusive */
4075 pagevec_init(&pvec);
4076 if (wbc->range_cyclic) {
4077 index = mapping->writeback_index; /* Start from prev offset */
4080 * Start from the beginning does not need to cycle over the
4081 * range, mark it as scanned.
4083 scanned = (index == 0);
4085 index = wbc->range_start >> PAGE_SHIFT;
4086 end = wbc->range_end >> PAGE_SHIFT;
4089 if (wbc->sync_mode == WB_SYNC_ALL)
4090 tag = PAGECACHE_TAG_TOWRITE;
4092 tag = PAGECACHE_TAG_DIRTY;
4094 if (wbc->sync_mode == WB_SYNC_ALL)
4095 tag_pages_for_writeback(mapping, index, end);
4096 while (!done && !nr_to_write_done && (index <= end) &&
4097 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4101 for (i = 0; i < nr_pages; i++) {
4102 struct page *page = pvec.pages[i];
4104 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4113 * the filesystem may choose to bump up nr_to_write.
4114 * We have to make sure to honor the new nr_to_write
4117 nr_to_write_done = wbc->nr_to_write <= 0;
4119 pagevec_release(&pvec);
4122 if (!scanned && !done) {
4124 * We hit the last page and there is more work to be done: wrap
4125 * back to the start of the file
4132 end_write_bio(&epd, ret);
4136 * If something went wrong, don't allow any metadata write bio to be
4139 * This would prevent use-after-free if we had dirty pages not
4140 * cleaned up, which can still happen by fuzzed images.
4143 * Allowing existing tree block to be allocated for other trees.
4145 * - Log tree operations
4146 * Exiting tree blocks get allocated to log tree, bumps its
4147 * generation, then get cleaned in tree re-balance.
4148 * Such tree block will not be written back, since it's clean,
4149 * thus no WRITTEN flag set.
4150 * And after log writes back, this tree block is not traced by
4151 * any dirty extent_io_tree.
4153 * - Offending tree block gets re-dirtied from its original owner
4154 * Since it has bumped generation, no WRITTEN flag, it can be
4155 * reused without COWing. This tree block will not be traced
4156 * by btrfs_transaction::dirty_pages.
4158 * Now such dirty tree block will not be cleaned by any dirty
4159 * extent io tree. Thus we don't want to submit such wild eb
4160 * if the fs already has error.
4162 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4163 ret = flush_write_bio(&epd);
4166 end_write_bio(&epd, ret);
4172 * Walk the list of dirty pages of the given address space and write all of them.
4174 * @mapping: address space structure to write
4175 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4176 * @epd: holds context for the write, namely the bio
4178 * If a page is already under I/O, write_cache_pages() skips it, even
4179 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4180 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4181 * and msync() need to guarantee that all the data which was dirty at the time
4182 * the call was made get new I/O started against them. If wbc->sync_mode is
4183 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4184 * existing IO to complete.
4186 static int extent_write_cache_pages(struct address_space *mapping,
4187 struct writeback_control *wbc,
4188 struct extent_page_data *epd)
4190 struct inode *inode = mapping->host;
4193 int nr_to_write_done = 0;
4194 struct pagevec pvec;
4197 pgoff_t end; /* Inclusive */
4199 int range_whole = 0;
4204 * We have to hold onto the inode so that ordered extents can do their
4205 * work when the IO finishes. The alternative to this is failing to add
4206 * an ordered extent if the igrab() fails there and that is a huge pain
4207 * to deal with, so instead just hold onto the inode throughout the
4208 * writepages operation. If it fails here we are freeing up the inode
4209 * anyway and we'd rather not waste our time writing out stuff that is
4210 * going to be truncated anyway.
4215 pagevec_init(&pvec);
4216 if (wbc->range_cyclic) {
4217 index = mapping->writeback_index; /* Start from prev offset */
4220 * Start from the beginning does not need to cycle over the
4221 * range, mark it as scanned.
4223 scanned = (index == 0);
4225 index = wbc->range_start >> PAGE_SHIFT;
4226 end = wbc->range_end >> PAGE_SHIFT;
4227 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4233 * We do the tagged writepage as long as the snapshot flush bit is set
4234 * and we are the first one who do the filemap_flush() on this inode.
4236 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4237 * not race in and drop the bit.
4239 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4240 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4241 &BTRFS_I(inode)->runtime_flags))
4242 wbc->tagged_writepages = 1;
4244 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4245 tag = PAGECACHE_TAG_TOWRITE;
4247 tag = PAGECACHE_TAG_DIRTY;
4249 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4250 tag_pages_for_writeback(mapping, index, end);
4252 while (!done && !nr_to_write_done && (index <= end) &&
4253 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4254 &index, end, tag))) {
4257 for (i = 0; i < nr_pages; i++) {
4258 struct page *page = pvec.pages[i];
4260 done_index = page->index + 1;
4262 * At this point we hold neither the i_pages lock nor
4263 * the page lock: the page may be truncated or
4264 * invalidated (changing page->mapping to NULL),
4265 * or even swizzled back from swapper_space to
4266 * tmpfs file mapping
4268 if (!trylock_page(page)) {
4269 ret = flush_write_bio(epd);
4274 if (unlikely(page->mapping != mapping)) {
4279 if (wbc->sync_mode != WB_SYNC_NONE) {
4280 if (PageWriteback(page)) {
4281 ret = flush_write_bio(epd);
4284 wait_on_page_writeback(page);
4287 if (PageWriteback(page) ||
4288 !clear_page_dirty_for_io(page)) {
4293 ret = __extent_writepage(page, wbc, epd);
4300 * the filesystem may choose to bump up nr_to_write.
4301 * We have to make sure to honor the new nr_to_write
4304 nr_to_write_done = wbc->nr_to_write <= 0;
4306 pagevec_release(&pvec);
4309 if (!scanned && !done) {
4311 * We hit the last page and there is more work to be done: wrap
4312 * back to the start of the file
4318 * If we're looping we could run into a page that is locked by a
4319 * writer and that writer could be waiting on writeback for a
4320 * page in our current bio, and thus deadlock, so flush the
4323 ret = flush_write_bio(epd);
4328 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4329 mapping->writeback_index = done_index;
4331 btrfs_add_delayed_iput(inode);
4335 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4338 struct extent_page_data epd = {
4341 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4344 ret = __extent_writepage(page, wbc, &epd);
4347 end_write_bio(&epd, ret);
4351 ret = flush_write_bio(&epd);
4356 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4360 struct address_space *mapping = inode->i_mapping;
4362 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4365 struct extent_page_data epd = {
4368 .sync_io = mode == WB_SYNC_ALL,
4370 struct writeback_control wbc_writepages = {
4372 .nr_to_write = nr_pages * 2,
4373 .range_start = start,
4374 .range_end = end + 1,
4375 /* We're called from an async helper function */
4376 .punt_to_cgroup = 1,
4377 .no_cgroup_owner = 1,
4380 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
4381 while (start <= end) {
4382 page = find_get_page(mapping, start >> PAGE_SHIFT);
4383 if (clear_page_dirty_for_io(page))
4384 ret = __extent_writepage(page, &wbc_writepages, &epd);
4386 btrfs_writepage_endio_finish_ordered(page, start,
4387 start + PAGE_SIZE - 1, 1);
4396 ret = flush_write_bio(&epd);
4398 end_write_bio(&epd, ret);
4400 wbc_detach_inode(&wbc_writepages);
4404 int extent_writepages(struct address_space *mapping,
4405 struct writeback_control *wbc)
4408 struct extent_page_data epd = {
4411 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4414 ret = extent_write_cache_pages(mapping, wbc, &epd);
4417 end_write_bio(&epd, ret);
4420 ret = flush_write_bio(&epd);
4424 void extent_readahead(struct readahead_control *rac)
4426 struct bio *bio = NULL;
4427 unsigned long bio_flags = 0;
4428 struct page *pagepool[16];
4429 struct extent_map *em_cached = NULL;
4430 u64 prev_em_start = (u64)-1;
4433 while ((nr = readahead_page_batch(rac, pagepool))) {
4434 u64 contig_start = page_offset(pagepool[0]);
4435 u64 contig_end = page_offset(pagepool[nr - 1]) + PAGE_SIZE - 1;
4437 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4439 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4440 &em_cached, &bio, &bio_flags, &prev_em_start);
4444 free_extent_map(em_cached);
4447 if (submit_one_bio(bio, 0, bio_flags))
4453 * basic invalidatepage code, this waits on any locked or writeback
4454 * ranges corresponding to the page, and then deletes any extent state
4455 * records from the tree
4457 int extent_invalidatepage(struct extent_io_tree *tree,
4458 struct page *page, unsigned long offset)
4460 struct extent_state *cached_state = NULL;
4461 u64 start = page_offset(page);
4462 u64 end = start + PAGE_SIZE - 1;
4463 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4465 /* This function is only called for the btree inode */
4466 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
4468 start += ALIGN(offset, blocksize);
4472 lock_extent_bits(tree, start, end, &cached_state);
4473 wait_on_page_writeback(page);
4476 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
4477 * so here we only need to unlock the extent range to free any
4478 * existing extent state.
4480 unlock_extent_cached(tree, start, end, &cached_state);
4485 * a helper for releasepage, this tests for areas of the page that
4486 * are locked or under IO and drops the related state bits if it is safe
4489 static int try_release_extent_state(struct extent_io_tree *tree,
4490 struct page *page, gfp_t mask)
4492 u64 start = page_offset(page);
4493 u64 end = start + PAGE_SIZE - 1;
4496 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4500 * At this point we can safely clear everything except the
4501 * locked bit, the nodatasum bit and the delalloc new bit.
4502 * The delalloc new bit will be cleared by ordered extent
4505 ret = __clear_extent_bit(tree, start, end,
4506 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
4507 0, 0, NULL, mask, NULL);
4509 /* if clear_extent_bit failed for enomem reasons,
4510 * we can't allow the release to continue.
4521 * a helper for releasepage. As long as there are no locked extents
4522 * in the range corresponding to the page, both state records and extent
4523 * map records are removed
4525 int try_release_extent_mapping(struct page *page, gfp_t mask)
4527 struct extent_map *em;
4528 u64 start = page_offset(page);
4529 u64 end = start + PAGE_SIZE - 1;
4530 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4531 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4532 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4534 if (gfpflags_allow_blocking(mask) &&
4535 page->mapping->host->i_size > SZ_16M) {
4537 while (start <= end) {
4538 struct btrfs_fs_info *fs_info;
4541 len = end - start + 1;
4542 write_lock(&map->lock);
4543 em = lookup_extent_mapping(map, start, len);
4545 write_unlock(&map->lock);
4548 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4549 em->start != start) {
4550 write_unlock(&map->lock);
4551 free_extent_map(em);
4554 if (test_range_bit(tree, em->start,
4555 extent_map_end(em) - 1,
4556 EXTENT_LOCKED, 0, NULL))
4559 * If it's not in the list of modified extents, used
4560 * by a fast fsync, we can remove it. If it's being
4561 * logged we can safely remove it since fsync took an
4562 * extra reference on the em.
4564 if (list_empty(&em->list) ||
4565 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
4568 * If it's in the list of modified extents, remove it
4569 * only if its generation is older then the current one,
4570 * in which case we don't need it for a fast fsync.
4571 * Otherwise don't remove it, we could be racing with an
4572 * ongoing fast fsync that could miss the new extent.
4574 fs_info = btrfs_inode->root->fs_info;
4575 spin_lock(&fs_info->trans_lock);
4576 cur_gen = fs_info->generation;
4577 spin_unlock(&fs_info->trans_lock);
4578 if (em->generation >= cur_gen)
4582 * We only remove extent maps that are not in the list of
4583 * modified extents or that are in the list but with a
4584 * generation lower then the current generation, so there
4585 * is no need to set the full fsync flag on the inode (it
4586 * hurts the fsync performance for workloads with a data
4587 * size that exceeds or is close to the system's memory).
4589 remove_extent_mapping(map, em);
4590 /* once for the rb tree */
4591 free_extent_map(em);
4593 start = extent_map_end(em);
4594 write_unlock(&map->lock);
4597 free_extent_map(em);
4599 cond_resched(); /* Allow large-extent preemption. */
4602 return try_release_extent_state(tree, page, mask);
4606 * helper function for fiemap, which doesn't want to see any holes.
4607 * This maps until we find something past 'last'
4609 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
4610 u64 offset, u64 last)
4612 u64 sectorsize = btrfs_inode_sectorsize(inode);
4613 struct extent_map *em;
4620 len = last - offset;
4623 len = ALIGN(len, sectorsize);
4624 em = btrfs_get_extent_fiemap(inode, offset, len);
4625 if (IS_ERR_OR_NULL(em))
4628 /* if this isn't a hole return it */
4629 if (em->block_start != EXTENT_MAP_HOLE)
4632 /* this is a hole, advance to the next extent */
4633 offset = extent_map_end(em);
4634 free_extent_map(em);
4642 * To cache previous fiemap extent
4644 * Will be used for merging fiemap extent
4646 struct fiemap_cache {
4655 * Helper to submit fiemap extent.
4657 * Will try to merge current fiemap extent specified by @offset, @phys,
4658 * @len and @flags with cached one.
4659 * And only when we fails to merge, cached one will be submitted as
4662 * Return value is the same as fiemap_fill_next_extent().
4664 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4665 struct fiemap_cache *cache,
4666 u64 offset, u64 phys, u64 len, u32 flags)
4674 * Sanity check, extent_fiemap() should have ensured that new
4675 * fiemap extent won't overlap with cached one.
4678 * NOTE: Physical address can overlap, due to compression
4680 if (cache->offset + cache->len > offset) {
4686 * Only merges fiemap extents if
4687 * 1) Their logical addresses are continuous
4689 * 2) Their physical addresses are continuous
4690 * So truly compressed (physical size smaller than logical size)
4691 * extents won't get merged with each other
4693 * 3) Share same flags except FIEMAP_EXTENT_LAST
4694 * So regular extent won't get merged with prealloc extent
4696 if (cache->offset + cache->len == offset &&
4697 cache->phys + cache->len == phys &&
4698 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4699 (flags & ~FIEMAP_EXTENT_LAST)) {
4701 cache->flags |= flags;
4702 goto try_submit_last;
4705 /* Not mergeable, need to submit cached one */
4706 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4707 cache->len, cache->flags);
4708 cache->cached = false;
4712 cache->cached = true;
4713 cache->offset = offset;
4716 cache->flags = flags;
4718 if (cache->flags & FIEMAP_EXTENT_LAST) {
4719 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4720 cache->phys, cache->len, cache->flags);
4721 cache->cached = false;
4727 * Emit last fiemap cache
4729 * The last fiemap cache may still be cached in the following case:
4731 * |<- Fiemap range ->|
4732 * |<------------ First extent ----------->|
4734 * In this case, the first extent range will be cached but not emitted.
4735 * So we must emit it before ending extent_fiemap().
4737 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4738 struct fiemap_cache *cache)
4745 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4746 cache->len, cache->flags);
4747 cache->cached = false;
4753 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
4758 u64 max = start + len;
4762 u64 last_for_get_extent = 0;
4764 u64 isize = i_size_read(&inode->vfs_inode);
4765 struct btrfs_key found_key;
4766 struct extent_map *em = NULL;
4767 struct extent_state *cached_state = NULL;
4768 struct btrfs_path *path;
4769 struct btrfs_root *root = inode->root;
4770 struct fiemap_cache cache = { 0 };
4771 struct ulist *roots;
4772 struct ulist *tmp_ulist;
4781 path = btrfs_alloc_path();
4785 roots = ulist_alloc(GFP_KERNEL);
4786 tmp_ulist = ulist_alloc(GFP_KERNEL);
4787 if (!roots || !tmp_ulist) {
4789 goto out_free_ulist;
4792 start = round_down(start, btrfs_inode_sectorsize(inode));
4793 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4796 * lookup the last file extent. We're not using i_size here
4797 * because there might be preallocation past i_size
4799 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
4802 goto out_free_ulist;
4810 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4811 found_type = found_key.type;
4813 /* No extents, but there might be delalloc bits */
4814 if (found_key.objectid != btrfs_ino(inode) ||
4815 found_type != BTRFS_EXTENT_DATA_KEY) {
4816 /* have to trust i_size as the end */
4818 last_for_get_extent = isize;
4821 * remember the start of the last extent. There are a
4822 * bunch of different factors that go into the length of the
4823 * extent, so its much less complex to remember where it started
4825 last = found_key.offset;
4826 last_for_get_extent = last + 1;
4828 btrfs_release_path(path);
4831 * we might have some extents allocated but more delalloc past those
4832 * extents. so, we trust isize unless the start of the last extent is
4837 last_for_get_extent = isize;
4840 lock_extent_bits(&inode->io_tree, start, start + len - 1,
4843 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4852 u64 offset_in_extent = 0;
4854 /* break if the extent we found is outside the range */
4855 if (em->start >= max || extent_map_end(em) < off)
4859 * get_extent may return an extent that starts before our
4860 * requested range. We have to make sure the ranges
4861 * we return to fiemap always move forward and don't
4862 * overlap, so adjust the offsets here
4864 em_start = max(em->start, off);
4867 * record the offset from the start of the extent
4868 * for adjusting the disk offset below. Only do this if the
4869 * extent isn't compressed since our in ram offset may be past
4870 * what we have actually allocated on disk.
4872 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4873 offset_in_extent = em_start - em->start;
4874 em_end = extent_map_end(em);
4875 em_len = em_end - em_start;
4877 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4878 disko = em->block_start + offset_in_extent;
4883 * bump off for our next call to get_extent
4885 off = extent_map_end(em);
4889 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4891 flags |= FIEMAP_EXTENT_LAST;
4892 } else if (em->block_start == EXTENT_MAP_INLINE) {
4893 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4894 FIEMAP_EXTENT_NOT_ALIGNED);
4895 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4896 flags |= (FIEMAP_EXTENT_DELALLOC |
4897 FIEMAP_EXTENT_UNKNOWN);
4898 } else if (fieinfo->fi_extents_max) {
4899 u64 bytenr = em->block_start -
4900 (em->start - em->orig_start);
4903 * As btrfs supports shared space, this information
4904 * can be exported to userspace tools via
4905 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4906 * then we're just getting a count and we can skip the
4909 ret = btrfs_check_shared(root, btrfs_ino(inode),
4910 bytenr, roots, tmp_ulist);
4914 flags |= FIEMAP_EXTENT_SHARED;
4917 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4918 flags |= FIEMAP_EXTENT_ENCODED;
4919 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4920 flags |= FIEMAP_EXTENT_UNWRITTEN;
4922 free_extent_map(em);
4924 if ((em_start >= last) || em_len == (u64)-1 ||
4925 (last == (u64)-1 && isize <= em_end)) {
4926 flags |= FIEMAP_EXTENT_LAST;
4930 /* now scan forward to see if this is really the last extent. */
4931 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4937 flags |= FIEMAP_EXTENT_LAST;
4940 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4950 ret = emit_last_fiemap_cache(fieinfo, &cache);
4951 free_extent_map(em);
4953 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
4957 btrfs_free_path(path);
4959 ulist_free(tmp_ulist);
4963 static void __free_extent_buffer(struct extent_buffer *eb)
4965 kmem_cache_free(extent_buffer_cache, eb);
4968 int extent_buffer_under_io(const struct extent_buffer *eb)
4970 return (atomic_read(&eb->io_pages) ||
4971 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4972 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4976 * Release all pages attached to the extent buffer.
4978 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4982 int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4984 BUG_ON(extent_buffer_under_io(eb));
4986 num_pages = num_extent_pages(eb);
4987 for (i = 0; i < num_pages; i++) {
4988 struct page *page = eb->pages[i];
4993 spin_lock(&page->mapping->private_lock);
4995 * We do this since we'll remove the pages after we've
4996 * removed the eb from the radix tree, so we could race
4997 * and have this page now attached to the new eb. So
4998 * only clear page_private if it's still connected to
5001 if (PagePrivate(page) &&
5002 page->private == (unsigned long)eb) {
5003 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5004 BUG_ON(PageDirty(page));
5005 BUG_ON(PageWriteback(page));
5007 * We need to make sure we haven't be attached
5010 detach_page_private(page);
5014 spin_unlock(&page->mapping->private_lock);
5016 /* One for when we allocated the page */
5022 * Helper for releasing the extent buffer.
5024 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5026 btrfs_release_extent_buffer_pages(eb);
5027 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5028 __free_extent_buffer(eb);
5031 static struct extent_buffer *
5032 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5035 struct extent_buffer *eb = NULL;
5037 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5040 eb->fs_info = fs_info;
5042 init_rwsem(&eb->lock);
5044 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5045 &fs_info->allocated_ebs);
5047 spin_lock_init(&eb->refs_lock);
5048 atomic_set(&eb->refs, 1);
5049 atomic_set(&eb->io_pages, 0);
5051 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5056 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5060 struct extent_buffer *new;
5061 int num_pages = num_extent_pages(src);
5063 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5068 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5069 * btrfs_release_extent_buffer() have different behavior for
5070 * UNMAPPED subpage extent buffer.
5072 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5074 for (i = 0; i < num_pages; i++) {
5075 p = alloc_page(GFP_NOFS);
5077 btrfs_release_extent_buffer(new);
5080 attach_extent_buffer_page(new, p);
5081 WARN_ON(PageDirty(p));
5084 copy_page(page_address(p), page_address(src->pages[i]));
5086 set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
5091 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5092 u64 start, unsigned long len)
5094 struct extent_buffer *eb;
5098 eb = __alloc_extent_buffer(fs_info, start, len);
5102 num_pages = num_extent_pages(eb);
5103 for (i = 0; i < num_pages; i++) {
5104 eb->pages[i] = alloc_page(GFP_NOFS);
5108 set_extent_buffer_uptodate(eb);
5109 btrfs_set_header_nritems(eb, 0);
5110 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5115 __free_page(eb->pages[i - 1]);
5116 __free_extent_buffer(eb);
5120 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5123 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
5126 static void check_buffer_tree_ref(struct extent_buffer *eb)
5130 * The TREE_REF bit is first set when the extent_buffer is added
5131 * to the radix tree. It is also reset, if unset, when a new reference
5132 * is created by find_extent_buffer.
5134 * It is only cleared in two cases: freeing the last non-tree
5135 * reference to the extent_buffer when its STALE bit is set or
5136 * calling releasepage when the tree reference is the only reference.
5138 * In both cases, care is taken to ensure that the extent_buffer's
5139 * pages are not under io. However, releasepage can be concurrently
5140 * called with creating new references, which is prone to race
5141 * conditions between the calls to check_buffer_tree_ref in those
5142 * codepaths and clearing TREE_REF in try_release_extent_buffer.
5144 * The actual lifetime of the extent_buffer in the radix tree is
5145 * adequately protected by the refcount, but the TREE_REF bit and
5146 * its corresponding reference are not. To protect against this
5147 * class of races, we call check_buffer_tree_ref from the codepaths
5148 * which trigger io after they set eb->io_pages. Note that once io is
5149 * initiated, TREE_REF can no longer be cleared, so that is the
5150 * moment at which any such race is best fixed.
5152 refs = atomic_read(&eb->refs);
5153 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5156 spin_lock(&eb->refs_lock);
5157 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5158 atomic_inc(&eb->refs);
5159 spin_unlock(&eb->refs_lock);
5162 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5163 struct page *accessed)
5167 check_buffer_tree_ref(eb);
5169 num_pages = num_extent_pages(eb);
5170 for (i = 0; i < num_pages; i++) {
5171 struct page *p = eb->pages[i];
5174 mark_page_accessed(p);
5178 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5181 struct extent_buffer *eb;
5184 eb = radix_tree_lookup(&fs_info->buffer_radix,
5185 start >> fs_info->sectorsize_bits);
5186 if (eb && atomic_inc_not_zero(&eb->refs)) {
5189 * Lock our eb's refs_lock to avoid races with
5190 * free_extent_buffer. When we get our eb it might be flagged
5191 * with EXTENT_BUFFER_STALE and another task running
5192 * free_extent_buffer might have seen that flag set,
5193 * eb->refs == 2, that the buffer isn't under IO (dirty and
5194 * writeback flags not set) and it's still in the tree (flag
5195 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5196 * of decrementing the extent buffer's reference count twice.
5197 * So here we could race and increment the eb's reference count,
5198 * clear its stale flag, mark it as dirty and drop our reference
5199 * before the other task finishes executing free_extent_buffer,
5200 * which would later result in an attempt to free an extent
5201 * buffer that is dirty.
5203 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5204 spin_lock(&eb->refs_lock);
5205 spin_unlock(&eb->refs_lock);
5207 mark_extent_buffer_accessed(eb, NULL);
5215 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5216 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5219 struct extent_buffer *eb, *exists = NULL;
5222 eb = find_extent_buffer(fs_info, start);
5225 eb = alloc_dummy_extent_buffer(fs_info, start);
5227 return ERR_PTR(-ENOMEM);
5228 eb->fs_info = fs_info;
5230 ret = radix_tree_preload(GFP_NOFS);
5232 exists = ERR_PTR(ret);
5235 spin_lock(&fs_info->buffer_lock);
5236 ret = radix_tree_insert(&fs_info->buffer_radix,
5237 start >> fs_info->sectorsize_bits, eb);
5238 spin_unlock(&fs_info->buffer_lock);
5239 radix_tree_preload_end();
5240 if (ret == -EEXIST) {
5241 exists = find_extent_buffer(fs_info, start);
5247 check_buffer_tree_ref(eb);
5248 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5252 btrfs_release_extent_buffer(eb);
5257 static struct extent_buffer *grab_extent_buffer(struct page *page)
5259 struct extent_buffer *exists;
5261 /* Page not yet attached to an extent buffer */
5262 if (!PagePrivate(page))
5266 * We could have already allocated an eb for this page and attached one
5267 * so lets see if we can get a ref on the existing eb, and if we can we
5268 * know it's good and we can just return that one, else we know we can
5269 * just overwrite page->private.
5271 exists = (struct extent_buffer *)page->private;
5272 if (atomic_inc_not_zero(&exists->refs))
5275 WARN_ON(PageDirty(page));
5276 detach_page_private(page);
5280 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5281 u64 start, u64 owner_root, int level)
5283 unsigned long len = fs_info->nodesize;
5286 unsigned long index = start >> PAGE_SHIFT;
5287 struct extent_buffer *eb;
5288 struct extent_buffer *exists = NULL;
5290 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5294 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5295 btrfs_err(fs_info, "bad tree block start %llu", start);
5296 return ERR_PTR(-EINVAL);
5299 if (fs_info->sectorsize < PAGE_SIZE &&
5300 offset_in_page(start) + len > PAGE_SIZE) {
5302 "tree block crosses page boundary, start %llu nodesize %lu",
5304 return ERR_PTR(-EINVAL);
5307 eb = find_extent_buffer(fs_info, start);
5311 eb = __alloc_extent_buffer(fs_info, start, len);
5313 return ERR_PTR(-ENOMEM);
5314 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
5316 num_pages = num_extent_pages(eb);
5317 for (i = 0; i < num_pages; i++, index++) {
5318 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5320 exists = ERR_PTR(-ENOMEM);
5324 spin_lock(&mapping->private_lock);
5325 exists = grab_extent_buffer(p);
5327 spin_unlock(&mapping->private_lock);
5330 mark_extent_buffer_accessed(exists, p);
5333 attach_extent_buffer_page(eb, p);
5334 spin_unlock(&mapping->private_lock);
5335 WARN_ON(PageDirty(p));
5337 if (!PageUptodate(p))
5341 * We can't unlock the pages just yet since the extent buffer
5342 * hasn't been properly inserted in the radix tree, this
5343 * opens a race with btree_releasepage which can free a page
5344 * while we are still filling in all pages for the buffer and
5349 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5351 ret = radix_tree_preload(GFP_NOFS);
5353 exists = ERR_PTR(ret);
5357 spin_lock(&fs_info->buffer_lock);
5358 ret = radix_tree_insert(&fs_info->buffer_radix,
5359 start >> fs_info->sectorsize_bits, eb);
5360 spin_unlock(&fs_info->buffer_lock);
5361 radix_tree_preload_end();
5362 if (ret == -EEXIST) {
5363 exists = find_extent_buffer(fs_info, start);
5369 /* add one reference for the tree */
5370 check_buffer_tree_ref(eb);
5371 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5374 * Now it's safe to unlock the pages because any calls to
5375 * btree_releasepage will correctly detect that a page belongs to a
5376 * live buffer and won't free them prematurely.
5378 for (i = 0; i < num_pages; i++)
5379 unlock_page(eb->pages[i]);
5383 WARN_ON(!atomic_dec_and_test(&eb->refs));
5384 for (i = 0; i < num_pages; i++) {
5386 unlock_page(eb->pages[i]);
5389 btrfs_release_extent_buffer(eb);
5393 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5395 struct extent_buffer *eb =
5396 container_of(head, struct extent_buffer, rcu_head);
5398 __free_extent_buffer(eb);
5401 static int release_extent_buffer(struct extent_buffer *eb)
5402 __releases(&eb->refs_lock)
5404 lockdep_assert_held(&eb->refs_lock);
5406 WARN_ON(atomic_read(&eb->refs) == 0);
5407 if (atomic_dec_and_test(&eb->refs)) {
5408 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5409 struct btrfs_fs_info *fs_info = eb->fs_info;
5411 spin_unlock(&eb->refs_lock);
5413 spin_lock(&fs_info->buffer_lock);
5414 radix_tree_delete(&fs_info->buffer_radix,
5415 eb->start >> fs_info->sectorsize_bits);
5416 spin_unlock(&fs_info->buffer_lock);
5418 spin_unlock(&eb->refs_lock);
5421 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5422 /* Should be safe to release our pages at this point */
5423 btrfs_release_extent_buffer_pages(eb);
5424 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5425 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5426 __free_extent_buffer(eb);
5430 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5433 spin_unlock(&eb->refs_lock);
5438 void free_extent_buffer(struct extent_buffer *eb)
5446 refs = atomic_read(&eb->refs);
5447 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5448 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5451 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5456 spin_lock(&eb->refs_lock);
5457 if (atomic_read(&eb->refs) == 2 &&
5458 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5459 !extent_buffer_under_io(eb) &&
5460 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5461 atomic_dec(&eb->refs);
5464 * I know this is terrible, but it's temporary until we stop tracking
5465 * the uptodate bits and such for the extent buffers.
5467 release_extent_buffer(eb);
5470 void free_extent_buffer_stale(struct extent_buffer *eb)
5475 spin_lock(&eb->refs_lock);
5476 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5478 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5479 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5480 atomic_dec(&eb->refs);
5481 release_extent_buffer(eb);
5484 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
5490 num_pages = num_extent_pages(eb);
5492 for (i = 0; i < num_pages; i++) {
5493 page = eb->pages[i];
5494 if (!PageDirty(page))
5498 WARN_ON(!PagePrivate(page));
5500 clear_page_dirty_for_io(page);
5501 xa_lock_irq(&page->mapping->i_pages);
5502 if (!PageDirty(page))
5503 __xa_clear_mark(&page->mapping->i_pages,
5504 page_index(page), PAGECACHE_TAG_DIRTY);
5505 xa_unlock_irq(&page->mapping->i_pages);
5506 ClearPageError(page);
5509 WARN_ON(atomic_read(&eb->refs) == 0);
5512 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5518 check_buffer_tree_ref(eb);
5520 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5522 num_pages = num_extent_pages(eb);
5523 WARN_ON(atomic_read(&eb->refs) == 0);
5524 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5527 for (i = 0; i < num_pages; i++)
5528 set_page_dirty(eb->pages[i]);
5530 #ifdef CONFIG_BTRFS_DEBUG
5531 for (i = 0; i < num_pages; i++)
5532 ASSERT(PageDirty(eb->pages[i]));
5538 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5544 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5545 num_pages = num_extent_pages(eb);
5546 for (i = 0; i < num_pages; i++) {
5547 page = eb->pages[i];
5549 ClearPageUptodate(page);
5553 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5559 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5560 num_pages = num_extent_pages(eb);
5561 for (i = 0; i < num_pages; i++) {
5562 page = eb->pages[i];
5563 SetPageUptodate(page);
5567 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5573 int locked_pages = 0;
5574 int all_uptodate = 1;
5576 unsigned long num_reads = 0;
5577 struct bio *bio = NULL;
5578 unsigned long bio_flags = 0;
5580 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5583 num_pages = num_extent_pages(eb);
5584 for (i = 0; i < num_pages; i++) {
5585 page = eb->pages[i];
5586 if (wait == WAIT_NONE) {
5587 if (!trylock_page(page))
5595 * We need to firstly lock all pages to make sure that
5596 * the uptodate bit of our pages won't be affected by
5597 * clear_extent_buffer_uptodate().
5599 for (i = 0; i < num_pages; i++) {
5600 page = eb->pages[i];
5601 if (!PageUptodate(page)) {
5608 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5612 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5613 eb->read_mirror = 0;
5614 atomic_set(&eb->io_pages, num_reads);
5616 * It is possible for releasepage to clear the TREE_REF bit before we
5617 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5619 check_buffer_tree_ref(eb);
5620 for (i = 0; i < num_pages; i++) {
5621 page = eb->pages[i];
5623 if (!PageUptodate(page)) {
5625 atomic_dec(&eb->io_pages);
5630 ClearPageError(page);
5631 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
5632 page, page_offset(page), PAGE_SIZE, 0,
5633 &bio, end_bio_extent_readpage,
5634 mirror_num, 0, 0, false);
5637 * We failed to submit the bio so it's the
5638 * caller's responsibility to perform cleanup
5639 * i.e unlock page/set error bit.
5644 atomic_dec(&eb->io_pages);
5652 err = submit_one_bio(bio, mirror_num, bio_flags);
5657 if (ret || wait != WAIT_COMPLETE)
5660 for (i = 0; i < num_pages; i++) {
5661 page = eb->pages[i];
5662 wait_on_page_locked(page);
5663 if (!PageUptodate(page))
5670 while (locked_pages > 0) {
5672 page = eb->pages[locked_pages];
5678 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5681 btrfs_warn(eb->fs_info,
5682 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
5683 eb->start, eb->len, start, len);
5684 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5690 * Check if the [start, start + len) range is valid before reading/writing
5692 * NOTE: @start and @len are offset inside the eb, not logical address.
5694 * Caller should not touch the dst/src memory if this function returns error.
5696 static inline int check_eb_range(const struct extent_buffer *eb,
5697 unsigned long start, unsigned long len)
5699 unsigned long offset;
5701 /* start, start + len should not go beyond eb->len nor overflow */
5702 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5703 return report_eb_range(eb, start, len);
5708 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5709 unsigned long start, unsigned long len)
5715 char *dst = (char *)dstv;
5716 unsigned long i = get_eb_page_index(start);
5718 if (check_eb_range(eb, start, len))
5721 offset = get_eb_offset_in_page(eb, start);
5724 page = eb->pages[i];
5726 cur = min(len, (PAGE_SIZE - offset));
5727 kaddr = page_address(page);
5728 memcpy(dst, kaddr + offset, cur);
5737 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5739 unsigned long start, unsigned long len)
5745 char __user *dst = (char __user *)dstv;
5746 unsigned long i = get_eb_page_index(start);
5749 WARN_ON(start > eb->len);
5750 WARN_ON(start + len > eb->start + eb->len);
5752 offset = get_eb_offset_in_page(eb, start);
5755 page = eb->pages[i];
5757 cur = min(len, (PAGE_SIZE - offset));
5758 kaddr = page_address(page);
5759 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
5773 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5774 unsigned long start, unsigned long len)
5780 char *ptr = (char *)ptrv;
5781 unsigned long i = get_eb_page_index(start);
5784 if (check_eb_range(eb, start, len))
5787 offset = get_eb_offset_in_page(eb, start);
5790 page = eb->pages[i];
5792 cur = min(len, (PAGE_SIZE - offset));
5794 kaddr = page_address(page);
5795 ret = memcmp(ptr, kaddr + offset, cur);
5807 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
5812 WARN_ON(!PageUptodate(eb->pages[0]));
5813 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
5814 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5818 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
5822 WARN_ON(!PageUptodate(eb->pages[0]));
5823 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
5824 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5828 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
5829 unsigned long start, unsigned long len)
5835 char *src = (char *)srcv;
5836 unsigned long i = get_eb_page_index(start);
5838 if (check_eb_range(eb, start, len))
5841 offset = get_eb_offset_in_page(eb, start);
5844 page = eb->pages[i];
5845 WARN_ON(!PageUptodate(page));
5847 cur = min(len, PAGE_SIZE - offset);
5848 kaddr = page_address(page);
5849 memcpy(kaddr + offset, src, cur);
5858 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
5865 unsigned long i = get_eb_page_index(start);
5867 if (check_eb_range(eb, start, len))
5870 offset = get_eb_offset_in_page(eb, start);
5873 page = eb->pages[i];
5874 WARN_ON(!PageUptodate(page));
5876 cur = min(len, PAGE_SIZE - offset);
5877 kaddr = page_address(page);
5878 memset(kaddr + offset, 0, cur);
5886 void copy_extent_buffer_full(const struct extent_buffer *dst,
5887 const struct extent_buffer *src)
5892 ASSERT(dst->len == src->len);
5894 if (dst->fs_info->sectorsize == PAGE_SIZE) {
5895 num_pages = num_extent_pages(dst);
5896 for (i = 0; i < num_pages; i++)
5897 copy_page(page_address(dst->pages[i]),
5898 page_address(src->pages[i]));
5900 size_t src_offset = get_eb_offset_in_page(src, 0);
5901 size_t dst_offset = get_eb_offset_in_page(dst, 0);
5903 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
5904 memcpy(page_address(dst->pages[0]) + dst_offset,
5905 page_address(src->pages[0]) + src_offset,
5910 void copy_extent_buffer(const struct extent_buffer *dst,
5911 const struct extent_buffer *src,
5912 unsigned long dst_offset, unsigned long src_offset,
5915 u64 dst_len = dst->len;
5920 unsigned long i = get_eb_page_index(dst_offset);
5922 if (check_eb_range(dst, dst_offset, len) ||
5923 check_eb_range(src, src_offset, len))
5926 WARN_ON(src->len != dst_len);
5928 offset = get_eb_offset_in_page(dst, dst_offset);
5931 page = dst->pages[i];
5932 WARN_ON(!PageUptodate(page));
5934 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5936 kaddr = page_address(page);
5937 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5947 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5949 * @eb: the extent buffer
5950 * @start: offset of the bitmap item in the extent buffer
5952 * @page_index: return index of the page in the extent buffer that contains the
5954 * @page_offset: return offset into the page given by page_index
5956 * This helper hides the ugliness of finding the byte in an extent buffer which
5957 * contains a given bit.
5959 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
5960 unsigned long start, unsigned long nr,
5961 unsigned long *page_index,
5962 size_t *page_offset)
5964 size_t byte_offset = BIT_BYTE(nr);
5968 * The byte we want is the offset of the extent buffer + the offset of
5969 * the bitmap item in the extent buffer + the offset of the byte in the
5972 offset = start + offset_in_page(eb->start) + byte_offset;
5974 *page_index = offset >> PAGE_SHIFT;
5975 *page_offset = offset_in_page(offset);
5979 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5980 * @eb: the extent buffer
5981 * @start: offset of the bitmap item in the extent buffer
5982 * @nr: bit number to test
5984 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
5992 eb_bitmap_offset(eb, start, nr, &i, &offset);
5993 page = eb->pages[i];
5994 WARN_ON(!PageUptodate(page));
5995 kaddr = page_address(page);
5996 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6000 * extent_buffer_bitmap_set - set an area of a bitmap
6001 * @eb: the extent buffer
6002 * @start: offset of the bitmap item in the extent buffer
6003 * @pos: bit number of the first bit
6004 * @len: number of bits to set
6006 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
6007 unsigned long pos, unsigned long len)
6013 const unsigned int size = pos + len;
6014 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6015 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
6017 eb_bitmap_offset(eb, start, pos, &i, &offset);
6018 page = eb->pages[i];
6019 WARN_ON(!PageUptodate(page));
6020 kaddr = page_address(page);
6022 while (len >= bits_to_set) {
6023 kaddr[offset] |= mask_to_set;
6025 bits_to_set = BITS_PER_BYTE;
6027 if (++offset >= PAGE_SIZE && len > 0) {
6029 page = eb->pages[++i];
6030 WARN_ON(!PageUptodate(page));
6031 kaddr = page_address(page);
6035 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6036 kaddr[offset] |= mask_to_set;
6042 * extent_buffer_bitmap_clear - clear an area of a bitmap
6043 * @eb: the extent buffer
6044 * @start: offset of the bitmap item in the extent buffer
6045 * @pos: bit number of the first bit
6046 * @len: number of bits to clear
6048 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6049 unsigned long start, unsigned long pos,
6056 const unsigned int size = pos + len;
6057 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
6058 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
6060 eb_bitmap_offset(eb, start, pos, &i, &offset);
6061 page = eb->pages[i];
6062 WARN_ON(!PageUptodate(page));
6063 kaddr = page_address(page);
6065 while (len >= bits_to_clear) {
6066 kaddr[offset] &= ~mask_to_clear;
6067 len -= bits_to_clear;
6068 bits_to_clear = BITS_PER_BYTE;
6070 if (++offset >= PAGE_SIZE && len > 0) {
6072 page = eb->pages[++i];
6073 WARN_ON(!PageUptodate(page));
6074 kaddr = page_address(page);
6078 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6079 kaddr[offset] &= ~mask_to_clear;
6083 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6085 unsigned long distance = (src > dst) ? src - dst : dst - src;
6086 return distance < len;
6089 static void copy_pages(struct page *dst_page, struct page *src_page,
6090 unsigned long dst_off, unsigned long src_off,
6093 char *dst_kaddr = page_address(dst_page);
6095 int must_memmove = 0;
6097 if (dst_page != src_page) {
6098 src_kaddr = page_address(src_page);
6100 src_kaddr = dst_kaddr;
6101 if (areas_overlap(src_off, dst_off, len))
6106 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6108 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
6111 void memcpy_extent_buffer(const struct extent_buffer *dst,
6112 unsigned long dst_offset, unsigned long src_offset,
6116 size_t dst_off_in_page;
6117 size_t src_off_in_page;
6118 unsigned long dst_i;
6119 unsigned long src_i;
6121 if (check_eb_range(dst, dst_offset, len) ||
6122 check_eb_range(dst, src_offset, len))
6126 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6127 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
6129 dst_i = get_eb_page_index(dst_offset);
6130 src_i = get_eb_page_index(src_offset);
6132 cur = min(len, (unsigned long)(PAGE_SIZE -
6134 cur = min_t(unsigned long, cur,
6135 (unsigned long)(PAGE_SIZE - dst_off_in_page));
6137 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6138 dst_off_in_page, src_off_in_page, cur);
6146 void memmove_extent_buffer(const struct extent_buffer *dst,
6147 unsigned long dst_offset, unsigned long src_offset,
6151 size_t dst_off_in_page;
6152 size_t src_off_in_page;
6153 unsigned long dst_end = dst_offset + len - 1;
6154 unsigned long src_end = src_offset + len - 1;
6155 unsigned long dst_i;
6156 unsigned long src_i;
6158 if (check_eb_range(dst, dst_offset, len) ||
6159 check_eb_range(dst, src_offset, len))
6161 if (dst_offset < src_offset) {
6162 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6166 dst_i = get_eb_page_index(dst_end);
6167 src_i = get_eb_page_index(src_end);
6169 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6170 src_off_in_page = get_eb_offset_in_page(dst, src_end);
6172 cur = min_t(unsigned long, len, src_off_in_page + 1);
6173 cur = min(cur, dst_off_in_page + 1);
6174 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6175 dst_off_in_page - cur + 1,
6176 src_off_in_page - cur + 1, cur);
6184 int try_release_extent_buffer(struct page *page)
6186 struct extent_buffer *eb;
6189 * We need to make sure nobody is attaching this page to an eb right
6192 spin_lock(&page->mapping->private_lock);
6193 if (!PagePrivate(page)) {
6194 spin_unlock(&page->mapping->private_lock);
6198 eb = (struct extent_buffer *)page->private;
6202 * This is a little awful but should be ok, we need to make sure that
6203 * the eb doesn't disappear out from under us while we're looking at
6206 spin_lock(&eb->refs_lock);
6207 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6208 spin_unlock(&eb->refs_lock);
6209 spin_unlock(&page->mapping->private_lock);
6212 spin_unlock(&page->mapping->private_lock);
6215 * If tree ref isn't set then we know the ref on this eb is a real ref,
6216 * so just return, this page will likely be freed soon anyway.
6218 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6219 spin_unlock(&eb->refs_lock);
6223 return release_extent_buffer(eb);
6227 * btrfs_readahead_tree_block - attempt to readahead a child block
6228 * @fs_info: the fs_info
6229 * @bytenr: bytenr to read
6230 * @owner_root: objectid of the root that owns this eb
6231 * @gen: generation for the uptodate check, can be 0
6232 * @level: level for the eb
6234 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
6235 * normal uptodate check of the eb, without checking the generation. If we have
6236 * to read the block we will not block on anything.
6238 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
6239 u64 bytenr, u64 owner_root, u64 gen, int level)
6241 struct extent_buffer *eb;
6244 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
6248 if (btrfs_buffer_uptodate(eb, gen, 1)) {
6249 free_extent_buffer(eb);
6253 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
6255 free_extent_buffer_stale(eb);
6257 free_extent_buffer(eb);
6261 * btrfs_readahead_node_child - readahead a node's child block
6262 * @node: parent node we're reading from
6263 * @slot: slot in the parent node for the child we want to read
6265 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
6266 * the slot in the node provided.
6268 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
6270 btrfs_readahead_tree_block(node->fs_info,
6271 btrfs_node_blockptr(node, slot),
6272 btrfs_header_owner(node),
6273 btrfs_node_ptr_generation(node, slot),
6274 btrfs_header_level(node) - 1);