btrfs: improve messages when updating feature flags
[linux/fpc-iii.git] / fs / btrfs / extent_io.c
blob464e6b761a9c9fb078080ab0718e98bb501db936
1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
5 #include <linux/bio.h>
6 #include <linux/mm.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/cleancache.h>
16 #include "extent_io.h"
17 #include "extent_map.h"
18 #include "ctree.h"
19 #include "btrfs_inode.h"
20 #include "volumes.h"
21 #include "check-integrity.h"
22 #include "locking.h"
23 #include "rcu-string.h"
24 #include "backref.h"
25 #include "disk-io.h"
27 static struct kmem_cache *extent_state_cache;
28 static struct kmem_cache *extent_buffer_cache;
29 static struct bio_set btrfs_bioset;
31 static inline bool extent_state_in_tree(const struct extent_state *state)
33 return !RB_EMPTY_NODE(&state->rb_node);
36 #ifdef CONFIG_BTRFS_DEBUG
37 static LIST_HEAD(buffers);
38 static LIST_HEAD(states);
40 static DEFINE_SPINLOCK(leak_lock);
42 static inline
43 void btrfs_leak_debug_add(struct list_head *new, struct list_head *head)
45 unsigned long flags;
47 spin_lock_irqsave(&leak_lock, flags);
48 list_add(new, head);
49 spin_unlock_irqrestore(&leak_lock, flags);
52 static inline
53 void btrfs_leak_debug_del(struct list_head *entry)
55 unsigned long flags;
57 spin_lock_irqsave(&leak_lock, flags);
58 list_del(entry);
59 spin_unlock_irqrestore(&leak_lock, flags);
62 static inline
63 void btrfs_leak_debug_check(void)
65 struct extent_state *state;
66 struct extent_buffer *eb;
68 while (!list_empty(&states)) {
69 state = list_entry(states.next, struct extent_state, leak_list);
70 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
71 state->start, state->end, state->state,
72 extent_state_in_tree(state),
73 refcount_read(&state->refs));
74 list_del(&state->leak_list);
75 kmem_cache_free(extent_state_cache, state);
78 while (!list_empty(&buffers)) {
79 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
80 pr_err("BTRFS: buffer leak start %llu len %lu refs %d bflags %lu\n",
81 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags);
82 list_del(&eb->leak_list);
83 kmem_cache_free(extent_buffer_cache, eb);
87 #define btrfs_debug_check_extent_io_range(tree, start, end) \
88 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
89 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
90 struct extent_io_tree *tree, u64 start, u64 end)
92 struct inode *inode = tree->private_data;
93 u64 isize;
95 if (!inode || !is_data_inode(inode))
96 return;
98 isize = i_size_read(inode);
99 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
100 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
101 "%s: ino %llu isize %llu odd range [%llu,%llu]",
102 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
105 #else
106 #define btrfs_leak_debug_add(new, head) do {} while (0)
107 #define btrfs_leak_debug_del(entry) do {} while (0)
108 #define btrfs_leak_debug_check() do {} while (0)
109 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
110 #endif
112 struct tree_entry {
113 u64 start;
114 u64 end;
115 struct rb_node rb_node;
118 struct extent_page_data {
119 struct bio *bio;
120 struct extent_io_tree *tree;
121 /* tells writepage not to lock the state bits for this range
122 * it still does the unlocking
124 unsigned int extent_locked:1;
126 /* tells the submit_bio code to use REQ_SYNC */
127 unsigned int sync_io:1;
130 static int add_extent_changeset(struct extent_state *state, unsigned bits,
131 struct extent_changeset *changeset,
132 int set)
134 int ret;
136 if (!changeset)
137 return 0;
138 if (set && (state->state & bits) == bits)
139 return 0;
140 if (!set && (state->state & bits) == 0)
141 return 0;
142 changeset->bytes_changed += state->end - state->start + 1;
143 ret = ulist_add(&changeset->range_changed, state->start, state->end,
144 GFP_ATOMIC);
145 return ret;
148 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
149 unsigned long bio_flags)
151 blk_status_t ret = 0;
152 struct extent_io_tree *tree = bio->bi_private;
154 bio->bi_private = NULL;
156 if (tree->ops)
157 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
158 mirror_num, bio_flags);
159 else
160 btrfsic_submit_bio(bio);
162 return blk_status_to_errno(ret);
165 /* Cleanup unsubmitted bios */
166 static void end_write_bio(struct extent_page_data *epd, int ret)
168 if (epd->bio) {
169 epd->bio->bi_status = errno_to_blk_status(ret);
170 bio_endio(epd->bio);
171 epd->bio = NULL;
176 * Submit bio from extent page data via submit_one_bio
178 * Return 0 if everything is OK.
179 * Return <0 for error.
181 static int __must_check flush_write_bio(struct extent_page_data *epd)
183 int ret = 0;
185 if (epd->bio) {
186 ret = submit_one_bio(epd->bio, 0, 0);
188 * Clean up of epd->bio is handled by its endio function.
189 * And endio is either triggered by successful bio execution
190 * or the error handler of submit bio hook.
191 * So at this point, no matter what happened, we don't need
192 * to clean up epd->bio.
194 epd->bio = NULL;
196 return ret;
199 int __init extent_io_init(void)
201 extent_state_cache = kmem_cache_create("btrfs_extent_state",
202 sizeof(struct extent_state), 0,
203 SLAB_MEM_SPREAD, NULL);
204 if (!extent_state_cache)
205 return -ENOMEM;
207 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
208 sizeof(struct extent_buffer), 0,
209 SLAB_MEM_SPREAD, NULL);
210 if (!extent_buffer_cache)
211 goto free_state_cache;
213 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
214 offsetof(struct btrfs_io_bio, bio),
215 BIOSET_NEED_BVECS))
216 goto free_buffer_cache;
218 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
219 goto free_bioset;
221 return 0;
223 free_bioset:
224 bioset_exit(&btrfs_bioset);
226 free_buffer_cache:
227 kmem_cache_destroy(extent_buffer_cache);
228 extent_buffer_cache = NULL;
230 free_state_cache:
231 kmem_cache_destroy(extent_state_cache);
232 extent_state_cache = NULL;
233 return -ENOMEM;
236 void __cold extent_io_exit(void)
238 btrfs_leak_debug_check();
241 * Make sure all delayed rcu free are flushed before we
242 * destroy caches.
244 rcu_barrier();
245 kmem_cache_destroy(extent_state_cache);
246 kmem_cache_destroy(extent_buffer_cache);
247 bioset_exit(&btrfs_bioset);
250 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
251 struct extent_io_tree *tree, unsigned int owner,
252 void *private_data)
254 tree->fs_info = fs_info;
255 tree->state = RB_ROOT;
256 tree->ops = NULL;
257 tree->dirty_bytes = 0;
258 spin_lock_init(&tree->lock);
259 tree->private_data = private_data;
260 tree->owner = owner;
263 void extent_io_tree_release(struct extent_io_tree *tree)
265 spin_lock(&tree->lock);
267 * Do a single barrier for the waitqueue_active check here, the state
268 * of the waitqueue should not change once extent_io_tree_release is
269 * called.
271 smp_mb();
272 while (!RB_EMPTY_ROOT(&tree->state)) {
273 struct rb_node *node;
274 struct extent_state *state;
276 node = rb_first(&tree->state);
277 state = rb_entry(node, struct extent_state, rb_node);
278 rb_erase(&state->rb_node, &tree->state);
279 RB_CLEAR_NODE(&state->rb_node);
281 * btree io trees aren't supposed to have tasks waiting for
282 * changes in the flags of extent states ever.
284 ASSERT(!waitqueue_active(&state->wq));
285 free_extent_state(state);
287 cond_resched_lock(&tree->lock);
289 spin_unlock(&tree->lock);
292 static struct extent_state *alloc_extent_state(gfp_t mask)
294 struct extent_state *state;
297 * The given mask might be not appropriate for the slab allocator,
298 * drop the unsupported bits
300 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
301 state = kmem_cache_alloc(extent_state_cache, mask);
302 if (!state)
303 return state;
304 state->state = 0;
305 state->failrec = NULL;
306 RB_CLEAR_NODE(&state->rb_node);
307 btrfs_leak_debug_add(&state->leak_list, &states);
308 refcount_set(&state->refs, 1);
309 init_waitqueue_head(&state->wq);
310 trace_alloc_extent_state(state, mask, _RET_IP_);
311 return state;
314 void free_extent_state(struct extent_state *state)
316 if (!state)
317 return;
318 if (refcount_dec_and_test(&state->refs)) {
319 WARN_ON(extent_state_in_tree(state));
320 btrfs_leak_debug_del(&state->leak_list);
321 trace_free_extent_state(state, _RET_IP_);
322 kmem_cache_free(extent_state_cache, state);
326 static struct rb_node *tree_insert(struct rb_root *root,
327 struct rb_node *search_start,
328 u64 offset,
329 struct rb_node *node,
330 struct rb_node ***p_in,
331 struct rb_node **parent_in)
333 struct rb_node **p;
334 struct rb_node *parent = NULL;
335 struct tree_entry *entry;
337 if (p_in && parent_in) {
338 p = *p_in;
339 parent = *parent_in;
340 goto do_insert;
343 p = search_start ? &search_start : &root->rb_node;
344 while (*p) {
345 parent = *p;
346 entry = rb_entry(parent, struct tree_entry, rb_node);
348 if (offset < entry->start)
349 p = &(*p)->rb_left;
350 else if (offset > entry->end)
351 p = &(*p)->rb_right;
352 else
353 return parent;
356 do_insert:
357 rb_link_node(node, parent, p);
358 rb_insert_color(node, root);
359 return NULL;
363 * __etree_search - searche @tree for an entry that contains @offset. Such
364 * entry would have entry->start <= offset && entry->end >= offset.
366 * @tree - the tree to search
367 * @offset - offset that should fall within an entry in @tree
368 * @next_ret - pointer to the first entry whose range ends after @offset
369 * @prev - pointer to the first entry whose range begins before @offset
370 * @p_ret - pointer where new node should be anchored (used when inserting an
371 * entry in the tree)
372 * @parent_ret - points to entry which would have been the parent of the entry,
373 * containing @offset
375 * This function returns a pointer to the entry that contains @offset byte
376 * address. If no such entry exists, then NULL is returned and the other
377 * pointer arguments to the function are filled, otherwise the found entry is
378 * returned and other pointers are left untouched.
380 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
381 struct rb_node **next_ret,
382 struct rb_node **prev_ret,
383 struct rb_node ***p_ret,
384 struct rb_node **parent_ret)
386 struct rb_root *root = &tree->state;
387 struct rb_node **n = &root->rb_node;
388 struct rb_node *prev = NULL;
389 struct rb_node *orig_prev = NULL;
390 struct tree_entry *entry;
391 struct tree_entry *prev_entry = NULL;
393 while (*n) {
394 prev = *n;
395 entry = rb_entry(prev, struct tree_entry, rb_node);
396 prev_entry = entry;
398 if (offset < entry->start)
399 n = &(*n)->rb_left;
400 else if (offset > entry->end)
401 n = &(*n)->rb_right;
402 else
403 return *n;
406 if (p_ret)
407 *p_ret = n;
408 if (parent_ret)
409 *parent_ret = prev;
411 if (next_ret) {
412 orig_prev = prev;
413 while (prev && offset > prev_entry->end) {
414 prev = rb_next(prev);
415 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
417 *next_ret = prev;
418 prev = orig_prev;
421 if (prev_ret) {
422 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
423 while (prev && offset < prev_entry->start) {
424 prev = rb_prev(prev);
425 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
427 *prev_ret = prev;
429 return NULL;
432 static inline struct rb_node *
433 tree_search_for_insert(struct extent_io_tree *tree,
434 u64 offset,
435 struct rb_node ***p_ret,
436 struct rb_node **parent_ret)
438 struct rb_node *next= NULL;
439 struct rb_node *ret;
441 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
442 if (!ret)
443 return next;
444 return ret;
447 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
448 u64 offset)
450 return tree_search_for_insert(tree, offset, NULL, NULL);
454 * utility function to look for merge candidates inside a given range.
455 * Any extents with matching state are merged together into a single
456 * extent in the tree. Extents with EXTENT_IO in their state field
457 * are not merged because the end_io handlers need to be able to do
458 * operations on them without sleeping (or doing allocations/splits).
460 * This should be called with the tree lock held.
462 static void merge_state(struct extent_io_tree *tree,
463 struct extent_state *state)
465 struct extent_state *other;
466 struct rb_node *other_node;
468 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
469 return;
471 other_node = rb_prev(&state->rb_node);
472 if (other_node) {
473 other = rb_entry(other_node, struct extent_state, rb_node);
474 if (other->end == state->start - 1 &&
475 other->state == state->state) {
476 if (tree->private_data &&
477 is_data_inode(tree->private_data))
478 btrfs_merge_delalloc_extent(tree->private_data,
479 state, other);
480 state->start = other->start;
481 rb_erase(&other->rb_node, &tree->state);
482 RB_CLEAR_NODE(&other->rb_node);
483 free_extent_state(other);
486 other_node = rb_next(&state->rb_node);
487 if (other_node) {
488 other = rb_entry(other_node, struct extent_state, rb_node);
489 if (other->start == state->end + 1 &&
490 other->state == state->state) {
491 if (tree->private_data &&
492 is_data_inode(tree->private_data))
493 btrfs_merge_delalloc_extent(tree->private_data,
494 state, other);
495 state->end = other->end;
496 rb_erase(&other->rb_node, &tree->state);
497 RB_CLEAR_NODE(&other->rb_node);
498 free_extent_state(other);
503 static void set_state_bits(struct extent_io_tree *tree,
504 struct extent_state *state, unsigned *bits,
505 struct extent_changeset *changeset);
508 * insert an extent_state struct into the tree. 'bits' are set on the
509 * struct before it is inserted.
511 * This may return -EEXIST if the extent is already there, in which case the
512 * state struct is freed.
514 * The tree lock is not taken internally. This is a utility function and
515 * probably isn't what you want to call (see set/clear_extent_bit).
517 static int insert_state(struct extent_io_tree *tree,
518 struct extent_state *state, u64 start, u64 end,
519 struct rb_node ***p,
520 struct rb_node **parent,
521 unsigned *bits, struct extent_changeset *changeset)
523 struct rb_node *node;
525 if (end < start)
526 WARN(1, KERN_ERR "BTRFS: end < start %llu %llu\n",
527 end, start);
528 state->start = start;
529 state->end = end;
531 set_state_bits(tree, state, bits, changeset);
533 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
534 if (node) {
535 struct extent_state *found;
536 found = rb_entry(node, struct extent_state, rb_node);
537 pr_err("BTRFS: found node %llu %llu on insert of %llu %llu\n",
538 found->start, found->end, start, end);
539 return -EEXIST;
541 merge_state(tree, state);
542 return 0;
546 * split a given extent state struct in two, inserting the preallocated
547 * struct 'prealloc' as the newly created second half. 'split' indicates an
548 * offset inside 'orig' where it should be split.
550 * Before calling,
551 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
552 * are two extent state structs in the tree:
553 * prealloc: [orig->start, split - 1]
554 * orig: [ split, orig->end ]
556 * The tree locks are not taken by this function. They need to be held
557 * by the caller.
559 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
560 struct extent_state *prealloc, u64 split)
562 struct rb_node *node;
564 if (tree->private_data && is_data_inode(tree->private_data))
565 btrfs_split_delalloc_extent(tree->private_data, orig, split);
567 prealloc->start = orig->start;
568 prealloc->end = split - 1;
569 prealloc->state = orig->state;
570 orig->start = split;
572 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
573 &prealloc->rb_node, NULL, NULL);
574 if (node) {
575 free_extent_state(prealloc);
576 return -EEXIST;
578 return 0;
581 static struct extent_state *next_state(struct extent_state *state)
583 struct rb_node *next = rb_next(&state->rb_node);
584 if (next)
585 return rb_entry(next, struct extent_state, rb_node);
586 else
587 return NULL;
591 * utility function to clear some bits in an extent state struct.
592 * it will optionally wake up anyone waiting on this state (wake == 1).
594 * If no bits are set on the state struct after clearing things, the
595 * struct is freed and removed from the tree
597 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
598 struct extent_state *state,
599 unsigned *bits, int wake,
600 struct extent_changeset *changeset)
602 struct extent_state *next;
603 unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
604 int ret;
606 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
607 u64 range = state->end - state->start + 1;
608 WARN_ON(range > tree->dirty_bytes);
609 tree->dirty_bytes -= range;
612 if (tree->private_data && is_data_inode(tree->private_data))
613 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
615 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
616 BUG_ON(ret < 0);
617 state->state &= ~bits_to_clear;
618 if (wake)
619 wake_up(&state->wq);
620 if (state->state == 0) {
621 next = next_state(state);
622 if (extent_state_in_tree(state)) {
623 rb_erase(&state->rb_node, &tree->state);
624 RB_CLEAR_NODE(&state->rb_node);
625 free_extent_state(state);
626 } else {
627 WARN_ON(1);
629 } else {
630 merge_state(tree, state);
631 next = next_state(state);
633 return next;
636 static struct extent_state *
637 alloc_extent_state_atomic(struct extent_state *prealloc)
639 if (!prealloc)
640 prealloc = alloc_extent_state(GFP_ATOMIC);
642 return prealloc;
645 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
647 struct inode *inode = tree->private_data;
649 btrfs_panic(btrfs_sb(inode->i_sb), err,
650 "locking error: extent tree was modified by another thread while locked");
654 * clear some bits on a range in the tree. This may require splitting
655 * or inserting elements in the tree, so the gfp mask is used to
656 * indicate which allocations or sleeping are allowed.
658 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
659 * the given range from the tree regardless of state (ie for truncate).
661 * the range [start, end] is inclusive.
663 * This takes the tree lock, and returns 0 on success and < 0 on error.
665 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
666 unsigned bits, int wake, int delete,
667 struct extent_state **cached_state,
668 gfp_t mask, struct extent_changeset *changeset)
670 struct extent_state *state;
671 struct extent_state *cached;
672 struct extent_state *prealloc = NULL;
673 struct rb_node *node;
674 u64 last_end;
675 int err;
676 int clear = 0;
678 btrfs_debug_check_extent_io_range(tree, start, end);
679 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
681 if (bits & EXTENT_DELALLOC)
682 bits |= EXTENT_NORESERVE;
684 if (delete)
685 bits |= ~EXTENT_CTLBITS;
687 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
688 clear = 1;
689 again:
690 if (!prealloc && gfpflags_allow_blocking(mask)) {
692 * Don't care for allocation failure here because we might end
693 * up not needing the pre-allocated extent state at all, which
694 * is the case if we only have in the tree extent states that
695 * cover our input range and don't cover too any other range.
696 * If we end up needing a new extent state we allocate it later.
698 prealloc = alloc_extent_state(mask);
701 spin_lock(&tree->lock);
702 if (cached_state) {
703 cached = *cached_state;
705 if (clear) {
706 *cached_state = NULL;
707 cached_state = NULL;
710 if (cached && extent_state_in_tree(cached) &&
711 cached->start <= start && cached->end > start) {
712 if (clear)
713 refcount_dec(&cached->refs);
714 state = cached;
715 goto hit_next;
717 if (clear)
718 free_extent_state(cached);
721 * this search will find the extents that end after
722 * our range starts
724 node = tree_search(tree, start);
725 if (!node)
726 goto out;
727 state = rb_entry(node, struct extent_state, rb_node);
728 hit_next:
729 if (state->start > end)
730 goto out;
731 WARN_ON(state->end < start);
732 last_end = state->end;
734 /* the state doesn't have the wanted bits, go ahead */
735 if (!(state->state & bits)) {
736 state = next_state(state);
737 goto next;
741 * | ---- desired range ---- |
742 * | state | or
743 * | ------------- state -------------- |
745 * We need to split the extent we found, and may flip
746 * bits on second half.
748 * If the extent we found extends past our range, we
749 * just split and search again. It'll get split again
750 * the next time though.
752 * If the extent we found is inside our range, we clear
753 * the desired bit on it.
756 if (state->start < start) {
757 prealloc = alloc_extent_state_atomic(prealloc);
758 BUG_ON(!prealloc);
759 err = split_state(tree, state, prealloc, start);
760 if (err)
761 extent_io_tree_panic(tree, err);
763 prealloc = NULL;
764 if (err)
765 goto out;
766 if (state->end <= end) {
767 state = clear_state_bit(tree, state, &bits, wake,
768 changeset);
769 goto next;
771 goto search_again;
774 * | ---- desired range ---- |
775 * | state |
776 * We need to split the extent, and clear the bit
777 * on the first half
779 if (state->start <= end && state->end > end) {
780 prealloc = alloc_extent_state_atomic(prealloc);
781 BUG_ON(!prealloc);
782 err = split_state(tree, state, prealloc, end + 1);
783 if (err)
784 extent_io_tree_panic(tree, err);
786 if (wake)
787 wake_up(&state->wq);
789 clear_state_bit(tree, prealloc, &bits, wake, changeset);
791 prealloc = NULL;
792 goto out;
795 state = clear_state_bit(tree, state, &bits, wake, changeset);
796 next:
797 if (last_end == (u64)-1)
798 goto out;
799 start = last_end + 1;
800 if (start <= end && state && !need_resched())
801 goto hit_next;
803 search_again:
804 if (start > end)
805 goto out;
806 spin_unlock(&tree->lock);
807 if (gfpflags_allow_blocking(mask))
808 cond_resched();
809 goto again;
811 out:
812 spin_unlock(&tree->lock);
813 if (prealloc)
814 free_extent_state(prealloc);
816 return 0;
820 static void wait_on_state(struct extent_io_tree *tree,
821 struct extent_state *state)
822 __releases(tree->lock)
823 __acquires(tree->lock)
825 DEFINE_WAIT(wait);
826 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
827 spin_unlock(&tree->lock);
828 schedule();
829 spin_lock(&tree->lock);
830 finish_wait(&state->wq, &wait);
834 * waits for one or more bits to clear on a range in the state tree.
835 * The range [start, end] is inclusive.
836 * The tree lock is taken by this function
838 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
839 unsigned long bits)
841 struct extent_state *state;
842 struct rb_node *node;
844 btrfs_debug_check_extent_io_range(tree, start, end);
846 spin_lock(&tree->lock);
847 again:
848 while (1) {
850 * this search will find all the extents that end after
851 * our range starts
853 node = tree_search(tree, start);
854 process_node:
855 if (!node)
856 break;
858 state = rb_entry(node, struct extent_state, rb_node);
860 if (state->start > end)
861 goto out;
863 if (state->state & bits) {
864 start = state->start;
865 refcount_inc(&state->refs);
866 wait_on_state(tree, state);
867 free_extent_state(state);
868 goto again;
870 start = state->end + 1;
872 if (start > end)
873 break;
875 if (!cond_resched_lock(&tree->lock)) {
876 node = rb_next(node);
877 goto process_node;
880 out:
881 spin_unlock(&tree->lock);
884 static void set_state_bits(struct extent_io_tree *tree,
885 struct extent_state *state,
886 unsigned *bits, struct extent_changeset *changeset)
888 unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
889 int ret;
891 if (tree->private_data && is_data_inode(tree->private_data))
892 btrfs_set_delalloc_extent(tree->private_data, state, bits);
894 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
895 u64 range = state->end - state->start + 1;
896 tree->dirty_bytes += range;
898 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
899 BUG_ON(ret < 0);
900 state->state |= bits_to_set;
903 static void cache_state_if_flags(struct extent_state *state,
904 struct extent_state **cached_ptr,
905 unsigned flags)
907 if (cached_ptr && !(*cached_ptr)) {
908 if (!flags || (state->state & flags)) {
909 *cached_ptr = state;
910 refcount_inc(&state->refs);
915 static void cache_state(struct extent_state *state,
916 struct extent_state **cached_ptr)
918 return cache_state_if_flags(state, cached_ptr,
919 EXTENT_LOCKED | EXTENT_BOUNDARY);
923 * set some bits on a range in the tree. This may require allocations or
924 * sleeping, so the gfp mask is used to indicate what is allowed.
926 * If any of the exclusive bits are set, this will fail with -EEXIST if some
927 * part of the range already has the desired bits set. The start of the
928 * existing range is returned in failed_start in this case.
930 * [start, end] is inclusive This takes the tree lock.
933 static int __must_check
934 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
935 unsigned bits, unsigned exclusive_bits,
936 u64 *failed_start, struct extent_state **cached_state,
937 gfp_t mask, struct extent_changeset *changeset)
939 struct extent_state *state;
940 struct extent_state *prealloc = NULL;
941 struct rb_node *node;
942 struct rb_node **p;
943 struct rb_node *parent;
944 int err = 0;
945 u64 last_start;
946 u64 last_end;
948 btrfs_debug_check_extent_io_range(tree, start, end);
949 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
951 again:
952 if (!prealloc && gfpflags_allow_blocking(mask)) {
954 * Don't care for allocation failure here because we might end
955 * up not needing the pre-allocated extent state at all, which
956 * is the case if we only have in the tree extent states that
957 * cover our input range and don't cover too any other range.
958 * If we end up needing a new extent state we allocate it later.
960 prealloc = alloc_extent_state(mask);
963 spin_lock(&tree->lock);
964 if (cached_state && *cached_state) {
965 state = *cached_state;
966 if (state->start <= start && state->end > start &&
967 extent_state_in_tree(state)) {
968 node = &state->rb_node;
969 goto hit_next;
973 * this search will find all the extents that end after
974 * our range starts.
976 node = tree_search_for_insert(tree, start, &p, &parent);
977 if (!node) {
978 prealloc = alloc_extent_state_atomic(prealloc);
979 BUG_ON(!prealloc);
980 err = insert_state(tree, prealloc, start, end,
981 &p, &parent, &bits, changeset);
982 if (err)
983 extent_io_tree_panic(tree, err);
985 cache_state(prealloc, cached_state);
986 prealloc = NULL;
987 goto out;
989 state = rb_entry(node, struct extent_state, rb_node);
990 hit_next:
991 last_start = state->start;
992 last_end = state->end;
995 * | ---- desired range ---- |
996 * | state |
998 * Just lock what we found and keep going
1000 if (state->start == start && state->end <= end) {
1001 if (state->state & exclusive_bits) {
1002 *failed_start = state->start;
1003 err = -EEXIST;
1004 goto out;
1007 set_state_bits(tree, state, &bits, changeset);
1008 cache_state(state, cached_state);
1009 merge_state(tree, state);
1010 if (last_end == (u64)-1)
1011 goto out;
1012 start = last_end + 1;
1013 state = next_state(state);
1014 if (start < end && state && state->start == start &&
1015 !need_resched())
1016 goto hit_next;
1017 goto search_again;
1021 * | ---- desired range ---- |
1022 * | state |
1023 * or
1024 * | ------------- state -------------- |
1026 * We need to split the extent we found, and may flip bits on
1027 * second half.
1029 * If the extent we found extends past our
1030 * range, we just split and search again. It'll get split
1031 * again the next time though.
1033 * If the extent we found is inside our range, we set the
1034 * desired bit on it.
1036 if (state->start < start) {
1037 if (state->state & exclusive_bits) {
1038 *failed_start = start;
1039 err = -EEXIST;
1040 goto out;
1043 prealloc = alloc_extent_state_atomic(prealloc);
1044 BUG_ON(!prealloc);
1045 err = split_state(tree, state, prealloc, start);
1046 if (err)
1047 extent_io_tree_panic(tree, err);
1049 prealloc = NULL;
1050 if (err)
1051 goto out;
1052 if (state->end <= end) {
1053 set_state_bits(tree, state, &bits, changeset);
1054 cache_state(state, cached_state);
1055 merge_state(tree, state);
1056 if (last_end == (u64)-1)
1057 goto out;
1058 start = last_end + 1;
1059 state = next_state(state);
1060 if (start < end && state && state->start == start &&
1061 !need_resched())
1062 goto hit_next;
1064 goto search_again;
1067 * | ---- desired range ---- |
1068 * | state | or | state |
1070 * There's a hole, we need to insert something in it and
1071 * ignore the extent we found.
1073 if (state->start > start) {
1074 u64 this_end;
1075 if (end < last_start)
1076 this_end = end;
1077 else
1078 this_end = last_start - 1;
1080 prealloc = alloc_extent_state_atomic(prealloc);
1081 BUG_ON(!prealloc);
1084 * Avoid to free 'prealloc' if it can be merged with
1085 * the later extent.
1087 err = insert_state(tree, prealloc, start, this_end,
1088 NULL, NULL, &bits, changeset);
1089 if (err)
1090 extent_io_tree_panic(tree, err);
1092 cache_state(prealloc, cached_state);
1093 prealloc = NULL;
1094 start = this_end + 1;
1095 goto search_again;
1098 * | ---- desired range ---- |
1099 * | state |
1100 * We need to split the extent, and set the bit
1101 * on the first half
1103 if (state->start <= end && state->end > end) {
1104 if (state->state & exclusive_bits) {
1105 *failed_start = start;
1106 err = -EEXIST;
1107 goto out;
1110 prealloc = alloc_extent_state_atomic(prealloc);
1111 BUG_ON(!prealloc);
1112 err = split_state(tree, state, prealloc, end + 1);
1113 if (err)
1114 extent_io_tree_panic(tree, err);
1116 set_state_bits(tree, prealloc, &bits, changeset);
1117 cache_state(prealloc, cached_state);
1118 merge_state(tree, prealloc);
1119 prealloc = NULL;
1120 goto out;
1123 search_again:
1124 if (start > end)
1125 goto out;
1126 spin_unlock(&tree->lock);
1127 if (gfpflags_allow_blocking(mask))
1128 cond_resched();
1129 goto again;
1131 out:
1132 spin_unlock(&tree->lock);
1133 if (prealloc)
1134 free_extent_state(prealloc);
1136 return err;
1140 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1141 unsigned bits, u64 * failed_start,
1142 struct extent_state **cached_state, gfp_t mask)
1144 return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1145 cached_state, mask, NULL);
1150 * convert_extent_bit - convert all bits in a given range from one bit to
1151 * another
1152 * @tree: the io tree to search
1153 * @start: the start offset in bytes
1154 * @end: the end offset in bytes (inclusive)
1155 * @bits: the bits to set in this range
1156 * @clear_bits: the bits to clear in this range
1157 * @cached_state: state that we're going to cache
1159 * This will go through and set bits for the given range. If any states exist
1160 * already in this range they are set with the given bit and cleared of the
1161 * clear_bits. This is only meant to be used by things that are mergeable, ie
1162 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1163 * boundary bits like LOCK.
1165 * All allocations are done with GFP_NOFS.
1167 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1168 unsigned bits, unsigned clear_bits,
1169 struct extent_state **cached_state)
1171 struct extent_state *state;
1172 struct extent_state *prealloc = NULL;
1173 struct rb_node *node;
1174 struct rb_node **p;
1175 struct rb_node *parent;
1176 int err = 0;
1177 u64 last_start;
1178 u64 last_end;
1179 bool first_iteration = true;
1181 btrfs_debug_check_extent_io_range(tree, start, end);
1182 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1183 clear_bits);
1185 again:
1186 if (!prealloc) {
1188 * Best effort, don't worry if extent state allocation fails
1189 * here for the first iteration. We might have a cached state
1190 * that matches exactly the target range, in which case no
1191 * extent state allocations are needed. We'll only know this
1192 * after locking the tree.
1194 prealloc = alloc_extent_state(GFP_NOFS);
1195 if (!prealloc && !first_iteration)
1196 return -ENOMEM;
1199 spin_lock(&tree->lock);
1200 if (cached_state && *cached_state) {
1201 state = *cached_state;
1202 if (state->start <= start && state->end > start &&
1203 extent_state_in_tree(state)) {
1204 node = &state->rb_node;
1205 goto hit_next;
1210 * this search will find all the extents that end after
1211 * our range starts.
1213 node = tree_search_for_insert(tree, start, &p, &parent);
1214 if (!node) {
1215 prealloc = alloc_extent_state_atomic(prealloc);
1216 if (!prealloc) {
1217 err = -ENOMEM;
1218 goto out;
1220 err = insert_state(tree, prealloc, start, end,
1221 &p, &parent, &bits, NULL);
1222 if (err)
1223 extent_io_tree_panic(tree, err);
1224 cache_state(prealloc, cached_state);
1225 prealloc = NULL;
1226 goto out;
1228 state = rb_entry(node, struct extent_state, rb_node);
1229 hit_next:
1230 last_start = state->start;
1231 last_end = state->end;
1234 * | ---- desired range ---- |
1235 * | state |
1237 * Just lock what we found and keep going
1239 if (state->start == start && state->end <= end) {
1240 set_state_bits(tree, state, &bits, NULL);
1241 cache_state(state, cached_state);
1242 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1243 if (last_end == (u64)-1)
1244 goto out;
1245 start = last_end + 1;
1246 if (start < end && state && state->start == start &&
1247 !need_resched())
1248 goto hit_next;
1249 goto search_again;
1253 * | ---- desired range ---- |
1254 * | state |
1255 * or
1256 * | ------------- state -------------- |
1258 * We need to split the extent we found, and may flip bits on
1259 * second half.
1261 * If the extent we found extends past our
1262 * range, we just split and search again. It'll get split
1263 * again the next time though.
1265 * If the extent we found is inside our range, we set the
1266 * desired bit on it.
1268 if (state->start < start) {
1269 prealloc = alloc_extent_state_atomic(prealloc);
1270 if (!prealloc) {
1271 err = -ENOMEM;
1272 goto out;
1274 err = split_state(tree, state, prealloc, start);
1275 if (err)
1276 extent_io_tree_panic(tree, err);
1277 prealloc = NULL;
1278 if (err)
1279 goto out;
1280 if (state->end <= end) {
1281 set_state_bits(tree, state, &bits, NULL);
1282 cache_state(state, cached_state);
1283 state = clear_state_bit(tree, state, &clear_bits, 0,
1284 NULL);
1285 if (last_end == (u64)-1)
1286 goto out;
1287 start = last_end + 1;
1288 if (start < end && state && state->start == start &&
1289 !need_resched())
1290 goto hit_next;
1292 goto search_again;
1295 * | ---- desired range ---- |
1296 * | state | or | state |
1298 * There's a hole, we need to insert something in it and
1299 * ignore the extent we found.
1301 if (state->start > start) {
1302 u64 this_end;
1303 if (end < last_start)
1304 this_end = end;
1305 else
1306 this_end = last_start - 1;
1308 prealloc = alloc_extent_state_atomic(prealloc);
1309 if (!prealloc) {
1310 err = -ENOMEM;
1311 goto out;
1315 * Avoid to free 'prealloc' if it can be merged with
1316 * the later extent.
1318 err = insert_state(tree, prealloc, start, this_end,
1319 NULL, NULL, &bits, NULL);
1320 if (err)
1321 extent_io_tree_panic(tree, err);
1322 cache_state(prealloc, cached_state);
1323 prealloc = NULL;
1324 start = this_end + 1;
1325 goto search_again;
1328 * | ---- desired range ---- |
1329 * | state |
1330 * We need to split the extent, and set the bit
1331 * on the first half
1333 if (state->start <= end && state->end > end) {
1334 prealloc = alloc_extent_state_atomic(prealloc);
1335 if (!prealloc) {
1336 err = -ENOMEM;
1337 goto out;
1340 err = split_state(tree, state, prealloc, end + 1);
1341 if (err)
1342 extent_io_tree_panic(tree, err);
1344 set_state_bits(tree, prealloc, &bits, NULL);
1345 cache_state(prealloc, cached_state);
1346 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1347 prealloc = NULL;
1348 goto out;
1351 search_again:
1352 if (start > end)
1353 goto out;
1354 spin_unlock(&tree->lock);
1355 cond_resched();
1356 first_iteration = false;
1357 goto again;
1359 out:
1360 spin_unlock(&tree->lock);
1361 if (prealloc)
1362 free_extent_state(prealloc);
1364 return err;
1367 /* wrappers around set/clear extent bit */
1368 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1369 unsigned bits, struct extent_changeset *changeset)
1372 * We don't support EXTENT_LOCKED yet, as current changeset will
1373 * record any bits changed, so for EXTENT_LOCKED case, it will
1374 * either fail with -EEXIST or changeset will record the whole
1375 * range.
1377 BUG_ON(bits & EXTENT_LOCKED);
1379 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1380 changeset);
1383 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1384 unsigned bits)
1386 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1387 GFP_NOWAIT, NULL);
1390 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1391 unsigned bits, int wake, int delete,
1392 struct extent_state **cached)
1394 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1395 cached, GFP_NOFS, NULL);
1398 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1399 unsigned bits, struct extent_changeset *changeset)
1402 * Don't support EXTENT_LOCKED case, same reason as
1403 * set_record_extent_bits().
1405 BUG_ON(bits & EXTENT_LOCKED);
1407 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1408 changeset);
1412 * either insert or lock state struct between start and end use mask to tell
1413 * us if waiting is desired.
1415 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1416 struct extent_state **cached_state)
1418 int err;
1419 u64 failed_start;
1421 while (1) {
1422 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1423 EXTENT_LOCKED, &failed_start,
1424 cached_state, GFP_NOFS, NULL);
1425 if (err == -EEXIST) {
1426 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1427 start = failed_start;
1428 } else
1429 break;
1430 WARN_ON(start > end);
1432 return err;
1435 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1437 int err;
1438 u64 failed_start;
1440 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1441 &failed_start, NULL, GFP_NOFS, NULL);
1442 if (err == -EEXIST) {
1443 if (failed_start > start)
1444 clear_extent_bit(tree, start, failed_start - 1,
1445 EXTENT_LOCKED, 1, 0, NULL);
1446 return 0;
1448 return 1;
1451 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1453 unsigned long index = start >> PAGE_SHIFT;
1454 unsigned long end_index = end >> PAGE_SHIFT;
1455 struct page *page;
1457 while (index <= end_index) {
1458 page = find_get_page(inode->i_mapping, index);
1459 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1460 clear_page_dirty_for_io(page);
1461 put_page(page);
1462 index++;
1466 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1468 unsigned long index = start >> PAGE_SHIFT;
1469 unsigned long end_index = end >> PAGE_SHIFT;
1470 struct page *page;
1472 while (index <= end_index) {
1473 page = find_get_page(inode->i_mapping, index);
1474 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1475 __set_page_dirty_nobuffers(page);
1476 account_page_redirty(page);
1477 put_page(page);
1478 index++;
1482 /* find the first state struct with 'bits' set after 'start', and
1483 * return it. tree->lock must be held. NULL will returned if
1484 * nothing was found after 'start'
1486 static struct extent_state *
1487 find_first_extent_bit_state(struct extent_io_tree *tree,
1488 u64 start, unsigned bits)
1490 struct rb_node *node;
1491 struct extent_state *state;
1494 * this search will find all the extents that end after
1495 * our range starts.
1497 node = tree_search(tree, start);
1498 if (!node)
1499 goto out;
1501 while (1) {
1502 state = rb_entry(node, struct extent_state, rb_node);
1503 if (state->end >= start && (state->state & bits))
1504 return state;
1506 node = rb_next(node);
1507 if (!node)
1508 break;
1510 out:
1511 return NULL;
1515 * find the first offset in the io tree with 'bits' set. zero is
1516 * returned if we find something, and *start_ret and *end_ret are
1517 * set to reflect the state struct that was found.
1519 * If nothing was found, 1 is returned. If found something, return 0.
1521 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1522 u64 *start_ret, u64 *end_ret, unsigned bits,
1523 struct extent_state **cached_state)
1525 struct extent_state *state;
1526 int ret = 1;
1528 spin_lock(&tree->lock);
1529 if (cached_state && *cached_state) {
1530 state = *cached_state;
1531 if (state->end == start - 1 && extent_state_in_tree(state)) {
1532 while ((state = next_state(state)) != NULL) {
1533 if (state->state & bits)
1534 goto got_it;
1536 free_extent_state(*cached_state);
1537 *cached_state = NULL;
1538 goto out;
1540 free_extent_state(*cached_state);
1541 *cached_state = NULL;
1544 state = find_first_extent_bit_state(tree, start, bits);
1545 got_it:
1546 if (state) {
1547 cache_state_if_flags(state, cached_state, 0);
1548 *start_ret = state->start;
1549 *end_ret = state->end;
1550 ret = 0;
1552 out:
1553 spin_unlock(&tree->lock);
1554 return ret;
1558 * find_first_clear_extent_bit - find the first range that has @bits not set.
1559 * This range could start before @start.
1561 * @tree - the tree to search
1562 * @start - the offset at/after which the found extent should start
1563 * @start_ret - records the beginning of the range
1564 * @end_ret - records the end of the range (inclusive)
1565 * @bits - the set of bits which must be unset
1567 * Since unallocated range is also considered one which doesn't have the bits
1568 * set it's possible that @end_ret contains -1, this happens in case the range
1569 * spans (last_range_end, end of device]. In this case it's up to the caller to
1570 * trim @end_ret to the appropriate size.
1572 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1573 u64 *start_ret, u64 *end_ret, unsigned bits)
1575 struct extent_state *state;
1576 struct rb_node *node, *prev = NULL, *next;
1578 spin_lock(&tree->lock);
1580 /* Find first extent with bits cleared */
1581 while (1) {
1582 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1583 if (!node) {
1584 node = next;
1585 if (!node) {
1587 * We are past the last allocated chunk,
1588 * set start at the end of the last extent. The
1589 * device alloc tree should never be empty so
1590 * prev is always set.
1592 ASSERT(prev);
1593 state = rb_entry(prev, struct extent_state, rb_node);
1594 *start_ret = state->end + 1;
1595 *end_ret = -1;
1596 goto out;
1600 * At this point 'node' either contains 'start' or start is
1601 * before 'node'
1603 state = rb_entry(node, struct extent_state, rb_node);
1605 if (in_range(start, state->start, state->end - state->start + 1)) {
1606 if (state->state & bits) {
1608 * |--range with bits sets--|
1610 * start
1612 start = state->end + 1;
1613 } else {
1615 * 'start' falls within a range that doesn't
1616 * have the bits set, so take its start as
1617 * the beginning of the desired range
1619 * |--range with bits cleared----|
1621 * start
1623 *start_ret = state->start;
1624 break;
1626 } else {
1628 * |---prev range---|---hole/unset---|---node range---|
1630 * start
1632 * or
1634 * |---hole/unset--||--first node--|
1635 * 0 |
1636 * start
1638 if (prev) {
1639 state = rb_entry(prev, struct extent_state,
1640 rb_node);
1641 *start_ret = state->end + 1;
1642 } else {
1643 *start_ret = 0;
1645 break;
1650 * Find the longest stretch from start until an entry which has the
1651 * bits set
1653 while (1) {
1654 state = rb_entry(node, struct extent_state, rb_node);
1655 if (state->end >= start && !(state->state & bits)) {
1656 *end_ret = state->end;
1657 } else {
1658 *end_ret = state->start - 1;
1659 break;
1662 node = rb_next(node);
1663 if (!node)
1664 break;
1666 out:
1667 spin_unlock(&tree->lock);
1671 * find a contiguous range of bytes in the file marked as delalloc, not
1672 * more than 'max_bytes'. start and end are used to return the range,
1674 * true is returned if we find something, false if nothing was in the tree
1676 static noinline bool find_delalloc_range(struct extent_io_tree *tree,
1677 u64 *start, u64 *end, u64 max_bytes,
1678 struct extent_state **cached_state)
1680 struct rb_node *node;
1681 struct extent_state *state;
1682 u64 cur_start = *start;
1683 bool found = false;
1684 u64 total_bytes = 0;
1686 spin_lock(&tree->lock);
1689 * this search will find all the extents that end after
1690 * our range starts.
1692 node = tree_search(tree, cur_start);
1693 if (!node) {
1694 *end = (u64)-1;
1695 goto out;
1698 while (1) {
1699 state = rb_entry(node, struct extent_state, rb_node);
1700 if (found && (state->start != cur_start ||
1701 (state->state & EXTENT_BOUNDARY))) {
1702 goto out;
1704 if (!(state->state & EXTENT_DELALLOC)) {
1705 if (!found)
1706 *end = state->end;
1707 goto out;
1709 if (!found) {
1710 *start = state->start;
1711 *cached_state = state;
1712 refcount_inc(&state->refs);
1714 found = true;
1715 *end = state->end;
1716 cur_start = state->end + 1;
1717 node = rb_next(node);
1718 total_bytes += state->end - state->start + 1;
1719 if (total_bytes >= max_bytes)
1720 break;
1721 if (!node)
1722 break;
1724 out:
1725 spin_unlock(&tree->lock);
1726 return found;
1729 static int __process_pages_contig(struct address_space *mapping,
1730 struct page *locked_page,
1731 pgoff_t start_index, pgoff_t end_index,
1732 unsigned long page_ops, pgoff_t *index_ret);
1734 static noinline void __unlock_for_delalloc(struct inode *inode,
1735 struct page *locked_page,
1736 u64 start, u64 end)
1738 unsigned long index = start >> PAGE_SHIFT;
1739 unsigned long end_index = end >> PAGE_SHIFT;
1741 ASSERT(locked_page);
1742 if (index == locked_page->index && end_index == index)
1743 return;
1745 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1746 PAGE_UNLOCK, NULL);
1749 static noinline int lock_delalloc_pages(struct inode *inode,
1750 struct page *locked_page,
1751 u64 delalloc_start,
1752 u64 delalloc_end)
1754 unsigned long index = delalloc_start >> PAGE_SHIFT;
1755 unsigned long index_ret = index;
1756 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1757 int ret;
1759 ASSERT(locked_page);
1760 if (index == locked_page->index && index == end_index)
1761 return 0;
1763 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1764 end_index, PAGE_LOCK, &index_ret);
1765 if (ret == -EAGAIN)
1766 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1767 (u64)index_ret << PAGE_SHIFT);
1768 return ret;
1772 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1773 * more than @max_bytes. @Start and @end are used to return the range,
1775 * Return: true if we find something
1776 * false if nothing was in the tree
1778 EXPORT_FOR_TESTS
1779 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1780 struct extent_io_tree *tree,
1781 struct page *locked_page, u64 *start,
1782 u64 *end)
1784 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1785 u64 delalloc_start;
1786 u64 delalloc_end;
1787 bool found;
1788 struct extent_state *cached_state = NULL;
1789 int ret;
1790 int loops = 0;
1792 again:
1793 /* step one, find a bunch of delalloc bytes starting at start */
1794 delalloc_start = *start;
1795 delalloc_end = 0;
1796 found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1797 max_bytes, &cached_state);
1798 if (!found || delalloc_end <= *start) {
1799 *start = delalloc_start;
1800 *end = delalloc_end;
1801 free_extent_state(cached_state);
1802 return false;
1806 * start comes from the offset of locked_page. We have to lock
1807 * pages in order, so we can't process delalloc bytes before
1808 * locked_page
1810 if (delalloc_start < *start)
1811 delalloc_start = *start;
1814 * make sure to limit the number of pages we try to lock down
1816 if (delalloc_end + 1 - delalloc_start > max_bytes)
1817 delalloc_end = delalloc_start + max_bytes - 1;
1819 /* step two, lock all the pages after the page that has start */
1820 ret = lock_delalloc_pages(inode, locked_page,
1821 delalloc_start, delalloc_end);
1822 ASSERT(!ret || ret == -EAGAIN);
1823 if (ret == -EAGAIN) {
1824 /* some of the pages are gone, lets avoid looping by
1825 * shortening the size of the delalloc range we're searching
1827 free_extent_state(cached_state);
1828 cached_state = NULL;
1829 if (!loops) {
1830 max_bytes = PAGE_SIZE;
1831 loops = 1;
1832 goto again;
1833 } else {
1834 found = false;
1835 goto out_failed;
1839 /* step three, lock the state bits for the whole range */
1840 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1842 /* then test to make sure it is all still delalloc */
1843 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1844 EXTENT_DELALLOC, 1, cached_state);
1845 if (!ret) {
1846 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1847 &cached_state);
1848 __unlock_for_delalloc(inode, locked_page,
1849 delalloc_start, delalloc_end);
1850 cond_resched();
1851 goto again;
1853 free_extent_state(cached_state);
1854 *start = delalloc_start;
1855 *end = delalloc_end;
1856 out_failed:
1857 return found;
1860 static int __process_pages_contig(struct address_space *mapping,
1861 struct page *locked_page,
1862 pgoff_t start_index, pgoff_t end_index,
1863 unsigned long page_ops, pgoff_t *index_ret)
1865 unsigned long nr_pages = end_index - start_index + 1;
1866 unsigned long pages_locked = 0;
1867 pgoff_t index = start_index;
1868 struct page *pages[16];
1869 unsigned ret;
1870 int err = 0;
1871 int i;
1873 if (page_ops & PAGE_LOCK) {
1874 ASSERT(page_ops == PAGE_LOCK);
1875 ASSERT(index_ret && *index_ret == start_index);
1878 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1879 mapping_set_error(mapping, -EIO);
1881 while (nr_pages > 0) {
1882 ret = find_get_pages_contig(mapping, index,
1883 min_t(unsigned long,
1884 nr_pages, ARRAY_SIZE(pages)), pages);
1885 if (ret == 0) {
1887 * Only if we're going to lock these pages,
1888 * can we find nothing at @index.
1890 ASSERT(page_ops & PAGE_LOCK);
1891 err = -EAGAIN;
1892 goto out;
1895 for (i = 0; i < ret; i++) {
1896 if (page_ops & PAGE_SET_PRIVATE2)
1897 SetPagePrivate2(pages[i]);
1899 if (pages[i] == locked_page) {
1900 put_page(pages[i]);
1901 pages_locked++;
1902 continue;
1904 if (page_ops & PAGE_CLEAR_DIRTY)
1905 clear_page_dirty_for_io(pages[i]);
1906 if (page_ops & PAGE_SET_WRITEBACK)
1907 set_page_writeback(pages[i]);
1908 if (page_ops & PAGE_SET_ERROR)
1909 SetPageError(pages[i]);
1910 if (page_ops & PAGE_END_WRITEBACK)
1911 end_page_writeback(pages[i]);
1912 if (page_ops & PAGE_UNLOCK)
1913 unlock_page(pages[i]);
1914 if (page_ops & PAGE_LOCK) {
1915 lock_page(pages[i]);
1916 if (!PageDirty(pages[i]) ||
1917 pages[i]->mapping != mapping) {
1918 unlock_page(pages[i]);
1919 put_page(pages[i]);
1920 err = -EAGAIN;
1921 goto out;
1924 put_page(pages[i]);
1925 pages_locked++;
1927 nr_pages -= ret;
1928 index += ret;
1929 cond_resched();
1931 out:
1932 if (err && index_ret)
1933 *index_ret = start_index + pages_locked - 1;
1934 return err;
1937 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1938 u64 delalloc_end, struct page *locked_page,
1939 unsigned clear_bits,
1940 unsigned long page_ops)
1942 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1943 NULL);
1945 __process_pages_contig(inode->i_mapping, locked_page,
1946 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1947 page_ops, NULL);
1951 * count the number of bytes in the tree that have a given bit(s)
1952 * set. This can be fairly slow, except for EXTENT_DIRTY which is
1953 * cached. The total number found is returned.
1955 u64 count_range_bits(struct extent_io_tree *tree,
1956 u64 *start, u64 search_end, u64 max_bytes,
1957 unsigned bits, int contig)
1959 struct rb_node *node;
1960 struct extent_state *state;
1961 u64 cur_start = *start;
1962 u64 total_bytes = 0;
1963 u64 last = 0;
1964 int found = 0;
1966 if (WARN_ON(search_end <= cur_start))
1967 return 0;
1969 spin_lock(&tree->lock);
1970 if (cur_start == 0 && bits == EXTENT_DIRTY) {
1971 total_bytes = tree->dirty_bytes;
1972 goto out;
1975 * this search will find all the extents that end after
1976 * our range starts.
1978 node = tree_search(tree, cur_start);
1979 if (!node)
1980 goto out;
1982 while (1) {
1983 state = rb_entry(node, struct extent_state, rb_node);
1984 if (state->start > search_end)
1985 break;
1986 if (contig && found && state->start > last + 1)
1987 break;
1988 if (state->end >= cur_start && (state->state & bits) == bits) {
1989 total_bytes += min(search_end, state->end) + 1 -
1990 max(cur_start, state->start);
1991 if (total_bytes >= max_bytes)
1992 break;
1993 if (!found) {
1994 *start = max(cur_start, state->start);
1995 found = 1;
1997 last = state->end;
1998 } else if (contig && found) {
1999 break;
2001 node = rb_next(node);
2002 if (!node)
2003 break;
2005 out:
2006 spin_unlock(&tree->lock);
2007 return total_bytes;
2011 * set the private field for a given byte offset in the tree. If there isn't
2012 * an extent_state there already, this does nothing.
2014 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
2015 struct io_failure_record *failrec)
2017 struct rb_node *node;
2018 struct extent_state *state;
2019 int ret = 0;
2021 spin_lock(&tree->lock);
2023 * this search will find all the extents that end after
2024 * our range starts.
2026 node = tree_search(tree, start);
2027 if (!node) {
2028 ret = -ENOENT;
2029 goto out;
2031 state = rb_entry(node, struct extent_state, rb_node);
2032 if (state->start != start) {
2033 ret = -ENOENT;
2034 goto out;
2036 state->failrec = failrec;
2037 out:
2038 spin_unlock(&tree->lock);
2039 return ret;
2042 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
2043 struct io_failure_record **failrec)
2045 struct rb_node *node;
2046 struct extent_state *state;
2047 int ret = 0;
2049 spin_lock(&tree->lock);
2051 * this search will find all the extents that end after
2052 * our range starts.
2054 node = tree_search(tree, start);
2055 if (!node) {
2056 ret = -ENOENT;
2057 goto out;
2059 state = rb_entry(node, struct extent_state, rb_node);
2060 if (state->start != start) {
2061 ret = -ENOENT;
2062 goto out;
2064 *failrec = state->failrec;
2065 out:
2066 spin_unlock(&tree->lock);
2067 return ret;
2071 * searches a range in the state tree for a given mask.
2072 * If 'filled' == 1, this returns 1 only if every extent in the tree
2073 * has the bits set. Otherwise, 1 is returned if any bit in the
2074 * range is found set.
2076 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2077 unsigned bits, int filled, struct extent_state *cached)
2079 struct extent_state *state = NULL;
2080 struct rb_node *node;
2081 int bitset = 0;
2083 spin_lock(&tree->lock);
2084 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2085 cached->end > start)
2086 node = &cached->rb_node;
2087 else
2088 node = tree_search(tree, start);
2089 while (node && start <= end) {
2090 state = rb_entry(node, struct extent_state, rb_node);
2092 if (filled && state->start > start) {
2093 bitset = 0;
2094 break;
2097 if (state->start > end)
2098 break;
2100 if (state->state & bits) {
2101 bitset = 1;
2102 if (!filled)
2103 break;
2104 } else if (filled) {
2105 bitset = 0;
2106 break;
2109 if (state->end == (u64)-1)
2110 break;
2112 start = state->end + 1;
2113 if (start > end)
2114 break;
2115 node = rb_next(node);
2116 if (!node) {
2117 if (filled)
2118 bitset = 0;
2119 break;
2122 spin_unlock(&tree->lock);
2123 return bitset;
2127 * helper function to set a given page up to date if all the
2128 * extents in the tree for that page are up to date
2130 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2132 u64 start = page_offset(page);
2133 u64 end = start + PAGE_SIZE - 1;
2134 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2135 SetPageUptodate(page);
2138 int free_io_failure(struct extent_io_tree *failure_tree,
2139 struct extent_io_tree *io_tree,
2140 struct io_failure_record *rec)
2142 int ret;
2143 int err = 0;
2145 set_state_failrec(failure_tree, rec->start, NULL);
2146 ret = clear_extent_bits(failure_tree, rec->start,
2147 rec->start + rec->len - 1,
2148 EXTENT_LOCKED | EXTENT_DIRTY);
2149 if (ret)
2150 err = ret;
2152 ret = clear_extent_bits(io_tree, rec->start,
2153 rec->start + rec->len - 1,
2154 EXTENT_DAMAGED);
2155 if (ret && !err)
2156 err = ret;
2158 kfree(rec);
2159 return err;
2163 * this bypasses the standard btrfs submit functions deliberately, as
2164 * the standard behavior is to write all copies in a raid setup. here we only
2165 * want to write the one bad copy. so we do the mapping for ourselves and issue
2166 * submit_bio directly.
2167 * to avoid any synchronization issues, wait for the data after writing, which
2168 * actually prevents the read that triggered the error from finishing.
2169 * currently, there can be no more than two copies of every data bit. thus,
2170 * exactly one rewrite is required.
2172 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2173 u64 length, u64 logical, struct page *page,
2174 unsigned int pg_offset, int mirror_num)
2176 struct bio *bio;
2177 struct btrfs_device *dev;
2178 u64 map_length = 0;
2179 u64 sector;
2180 struct btrfs_bio *bbio = NULL;
2181 int ret;
2183 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2184 BUG_ON(!mirror_num);
2186 bio = btrfs_io_bio_alloc(1);
2187 bio->bi_iter.bi_size = 0;
2188 map_length = length;
2191 * Avoid races with device replace and make sure our bbio has devices
2192 * associated to its stripes that don't go away while we are doing the
2193 * read repair operation.
2195 btrfs_bio_counter_inc_blocked(fs_info);
2196 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2198 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2199 * to update all raid stripes, but here we just want to correct
2200 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2201 * stripe's dev and sector.
2203 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2204 &map_length, &bbio, 0);
2205 if (ret) {
2206 btrfs_bio_counter_dec(fs_info);
2207 bio_put(bio);
2208 return -EIO;
2210 ASSERT(bbio->mirror_num == 1);
2211 } else {
2212 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2213 &map_length, &bbio, mirror_num);
2214 if (ret) {
2215 btrfs_bio_counter_dec(fs_info);
2216 bio_put(bio);
2217 return -EIO;
2219 BUG_ON(mirror_num != bbio->mirror_num);
2222 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2223 bio->bi_iter.bi_sector = sector;
2224 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2225 btrfs_put_bbio(bbio);
2226 if (!dev || !dev->bdev ||
2227 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2228 btrfs_bio_counter_dec(fs_info);
2229 bio_put(bio);
2230 return -EIO;
2232 bio_set_dev(bio, dev->bdev);
2233 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2234 bio_add_page(bio, page, length, pg_offset);
2236 if (btrfsic_submit_bio_wait(bio)) {
2237 /* try to remap that extent elsewhere? */
2238 btrfs_bio_counter_dec(fs_info);
2239 bio_put(bio);
2240 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2241 return -EIO;
2244 btrfs_info_rl_in_rcu(fs_info,
2245 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2246 ino, start,
2247 rcu_str_deref(dev->name), sector);
2248 btrfs_bio_counter_dec(fs_info);
2249 bio_put(bio);
2250 return 0;
2253 int btrfs_repair_eb_io_failure(struct extent_buffer *eb, int mirror_num)
2255 struct btrfs_fs_info *fs_info = eb->fs_info;
2256 u64 start = eb->start;
2257 int i, num_pages = num_extent_pages(eb);
2258 int ret = 0;
2260 if (sb_rdonly(fs_info->sb))
2261 return -EROFS;
2263 for (i = 0; i < num_pages; i++) {
2264 struct page *p = eb->pages[i];
2266 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2267 start - page_offset(p), mirror_num);
2268 if (ret)
2269 break;
2270 start += PAGE_SIZE;
2273 return ret;
2277 * each time an IO finishes, we do a fast check in the IO failure tree
2278 * to see if we need to process or clean up an io_failure_record
2280 int clean_io_failure(struct btrfs_fs_info *fs_info,
2281 struct extent_io_tree *failure_tree,
2282 struct extent_io_tree *io_tree, u64 start,
2283 struct page *page, u64 ino, unsigned int pg_offset)
2285 u64 private;
2286 struct io_failure_record *failrec;
2287 struct extent_state *state;
2288 int num_copies;
2289 int ret;
2291 private = 0;
2292 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2293 EXTENT_DIRTY, 0);
2294 if (!ret)
2295 return 0;
2297 ret = get_state_failrec(failure_tree, start, &failrec);
2298 if (ret)
2299 return 0;
2301 BUG_ON(!failrec->this_mirror);
2303 if (failrec->in_validation) {
2304 /* there was no real error, just free the record */
2305 btrfs_debug(fs_info,
2306 "clean_io_failure: freeing dummy error at %llu",
2307 failrec->start);
2308 goto out;
2310 if (sb_rdonly(fs_info->sb))
2311 goto out;
2313 spin_lock(&io_tree->lock);
2314 state = find_first_extent_bit_state(io_tree,
2315 failrec->start,
2316 EXTENT_LOCKED);
2317 spin_unlock(&io_tree->lock);
2319 if (state && state->start <= failrec->start &&
2320 state->end >= failrec->start + failrec->len - 1) {
2321 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2322 failrec->len);
2323 if (num_copies > 1) {
2324 repair_io_failure(fs_info, ino, start, failrec->len,
2325 failrec->logical, page, pg_offset,
2326 failrec->failed_mirror);
2330 out:
2331 free_io_failure(failure_tree, io_tree, failrec);
2333 return 0;
2337 * Can be called when
2338 * - hold extent lock
2339 * - under ordered extent
2340 * - the inode is freeing
2342 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2344 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2345 struct io_failure_record *failrec;
2346 struct extent_state *state, *next;
2348 if (RB_EMPTY_ROOT(&failure_tree->state))
2349 return;
2351 spin_lock(&failure_tree->lock);
2352 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2353 while (state) {
2354 if (state->start > end)
2355 break;
2357 ASSERT(state->end <= end);
2359 next = next_state(state);
2361 failrec = state->failrec;
2362 free_extent_state(state);
2363 kfree(failrec);
2365 state = next;
2367 spin_unlock(&failure_tree->lock);
2370 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2371 struct io_failure_record **failrec_ret)
2373 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2374 struct io_failure_record *failrec;
2375 struct extent_map *em;
2376 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2377 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2378 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2379 int ret;
2380 u64 logical;
2382 ret = get_state_failrec(failure_tree, start, &failrec);
2383 if (ret) {
2384 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2385 if (!failrec)
2386 return -ENOMEM;
2388 failrec->start = start;
2389 failrec->len = end - start + 1;
2390 failrec->this_mirror = 0;
2391 failrec->bio_flags = 0;
2392 failrec->in_validation = 0;
2394 read_lock(&em_tree->lock);
2395 em = lookup_extent_mapping(em_tree, start, failrec->len);
2396 if (!em) {
2397 read_unlock(&em_tree->lock);
2398 kfree(failrec);
2399 return -EIO;
2402 if (em->start > start || em->start + em->len <= start) {
2403 free_extent_map(em);
2404 em = NULL;
2406 read_unlock(&em_tree->lock);
2407 if (!em) {
2408 kfree(failrec);
2409 return -EIO;
2412 logical = start - em->start;
2413 logical = em->block_start + logical;
2414 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2415 logical = em->block_start;
2416 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2417 extent_set_compress_type(&failrec->bio_flags,
2418 em->compress_type);
2421 btrfs_debug(fs_info,
2422 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2423 logical, start, failrec->len);
2425 failrec->logical = logical;
2426 free_extent_map(em);
2428 /* set the bits in the private failure tree */
2429 ret = set_extent_bits(failure_tree, start, end,
2430 EXTENT_LOCKED | EXTENT_DIRTY);
2431 if (ret >= 0)
2432 ret = set_state_failrec(failure_tree, start, failrec);
2433 /* set the bits in the inode's tree */
2434 if (ret >= 0)
2435 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2436 if (ret < 0) {
2437 kfree(failrec);
2438 return ret;
2440 } else {
2441 btrfs_debug(fs_info,
2442 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2443 failrec->logical, failrec->start, failrec->len,
2444 failrec->in_validation);
2446 * when data can be on disk more than twice, add to failrec here
2447 * (e.g. with a list for failed_mirror) to make
2448 * clean_io_failure() clean all those errors at once.
2452 *failrec_ret = failrec;
2454 return 0;
2457 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2458 struct io_failure_record *failrec, int failed_mirror)
2460 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2461 int num_copies;
2463 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2464 if (num_copies == 1) {
2466 * we only have a single copy of the data, so don't bother with
2467 * all the retry and error correction code that follows. no
2468 * matter what the error is, it is very likely to persist.
2470 btrfs_debug(fs_info,
2471 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2472 num_copies, failrec->this_mirror, failed_mirror);
2473 return false;
2477 * there are two premises:
2478 * a) deliver good data to the caller
2479 * b) correct the bad sectors on disk
2481 if (failed_bio_pages > 1) {
2483 * to fulfill b), we need to know the exact failing sectors, as
2484 * we don't want to rewrite any more than the failed ones. thus,
2485 * we need separate read requests for the failed bio
2487 * if the following BUG_ON triggers, our validation request got
2488 * merged. we need separate requests for our algorithm to work.
2490 BUG_ON(failrec->in_validation);
2491 failrec->in_validation = 1;
2492 failrec->this_mirror = failed_mirror;
2493 } else {
2495 * we're ready to fulfill a) and b) alongside. get a good copy
2496 * of the failed sector and if we succeed, we have setup
2497 * everything for repair_io_failure to do the rest for us.
2499 if (failrec->in_validation) {
2500 BUG_ON(failrec->this_mirror != failed_mirror);
2501 failrec->in_validation = 0;
2502 failrec->this_mirror = 0;
2504 failrec->failed_mirror = failed_mirror;
2505 failrec->this_mirror++;
2506 if (failrec->this_mirror == failed_mirror)
2507 failrec->this_mirror++;
2510 if (failrec->this_mirror > num_copies) {
2511 btrfs_debug(fs_info,
2512 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2513 num_copies, failrec->this_mirror, failed_mirror);
2514 return false;
2517 return true;
2521 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2522 struct io_failure_record *failrec,
2523 struct page *page, int pg_offset, int icsum,
2524 bio_end_io_t *endio_func, void *data)
2526 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2527 struct bio *bio;
2528 struct btrfs_io_bio *btrfs_failed_bio;
2529 struct btrfs_io_bio *btrfs_bio;
2531 bio = btrfs_io_bio_alloc(1);
2532 bio->bi_end_io = endio_func;
2533 bio->bi_iter.bi_sector = failrec->logical >> 9;
2534 bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2535 bio->bi_iter.bi_size = 0;
2536 bio->bi_private = data;
2538 btrfs_failed_bio = btrfs_io_bio(failed_bio);
2539 if (btrfs_failed_bio->csum) {
2540 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2542 btrfs_bio = btrfs_io_bio(bio);
2543 btrfs_bio->csum = btrfs_bio->csum_inline;
2544 icsum *= csum_size;
2545 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2546 csum_size);
2549 bio_add_page(bio, page, failrec->len, pg_offset);
2551 return bio;
2555 * This is a generic handler for readpage errors. If other copies exist, read
2556 * those and write back good data to the failed position. Does not investigate
2557 * in remapping the failed extent elsewhere, hoping the device will be smart
2558 * enough to do this as needed
2560 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2561 struct page *page, u64 start, u64 end,
2562 int failed_mirror)
2564 struct io_failure_record *failrec;
2565 struct inode *inode = page->mapping->host;
2566 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2567 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2568 struct bio *bio;
2569 int read_mode = 0;
2570 blk_status_t status;
2571 int ret;
2572 unsigned failed_bio_pages = failed_bio->bi_iter.bi_size >> PAGE_SHIFT;
2574 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2576 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2577 if (ret)
2578 return ret;
2580 if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2581 failed_mirror)) {
2582 free_io_failure(failure_tree, tree, failrec);
2583 return -EIO;
2586 if (failed_bio_pages > 1)
2587 read_mode |= REQ_FAILFAST_DEV;
2589 phy_offset >>= inode->i_sb->s_blocksize_bits;
2590 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2591 start - page_offset(page),
2592 (int)phy_offset, failed_bio->bi_end_io,
2593 NULL);
2594 bio->bi_opf = REQ_OP_READ | read_mode;
2596 btrfs_debug(btrfs_sb(inode->i_sb),
2597 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2598 read_mode, failrec->this_mirror, failrec->in_validation);
2600 status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2601 failrec->bio_flags);
2602 if (status) {
2603 free_io_failure(failure_tree, tree, failrec);
2604 bio_put(bio);
2605 ret = blk_status_to_errno(status);
2608 return ret;
2611 /* lots and lots of room for performance fixes in the end_bio funcs */
2613 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2615 int uptodate = (err == 0);
2616 int ret = 0;
2618 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2620 if (!uptodate) {
2621 ClearPageUptodate(page);
2622 SetPageError(page);
2623 ret = err < 0 ? err : -EIO;
2624 mapping_set_error(page->mapping, ret);
2629 * after a writepage IO is done, we need to:
2630 * clear the uptodate bits on error
2631 * clear the writeback bits in the extent tree for this IO
2632 * end_page_writeback if the page has no more pending IO
2634 * Scheduling is not allowed, so the extent state tree is expected
2635 * to have one and only one object corresponding to this IO.
2637 static void end_bio_extent_writepage(struct bio *bio)
2639 int error = blk_status_to_errno(bio->bi_status);
2640 struct bio_vec *bvec;
2641 u64 start;
2642 u64 end;
2643 struct bvec_iter_all iter_all;
2645 ASSERT(!bio_flagged(bio, BIO_CLONED));
2646 bio_for_each_segment_all(bvec, bio, iter_all) {
2647 struct page *page = bvec->bv_page;
2648 struct inode *inode = page->mapping->host;
2649 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2651 /* We always issue full-page reads, but if some block
2652 * in a page fails to read, blk_update_request() will
2653 * advance bv_offset and adjust bv_len to compensate.
2654 * Print a warning for nonzero offsets, and an error
2655 * if they don't add up to a full page. */
2656 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2657 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2658 btrfs_err(fs_info,
2659 "partial page write in btrfs with offset %u and length %u",
2660 bvec->bv_offset, bvec->bv_len);
2661 else
2662 btrfs_info(fs_info,
2663 "incomplete page write in btrfs with offset %u and length %u",
2664 bvec->bv_offset, bvec->bv_len);
2667 start = page_offset(page);
2668 end = start + bvec->bv_offset + bvec->bv_len - 1;
2670 end_extent_writepage(page, error, start, end);
2671 end_page_writeback(page);
2674 bio_put(bio);
2677 static void
2678 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2679 int uptodate)
2681 struct extent_state *cached = NULL;
2682 u64 end = start + len - 1;
2684 if (uptodate && tree->track_uptodate)
2685 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2686 unlock_extent_cached_atomic(tree, start, end, &cached);
2690 * after a readpage IO is done, we need to:
2691 * clear the uptodate bits on error
2692 * set the uptodate bits if things worked
2693 * set the page up to date if all extents in the tree are uptodate
2694 * clear the lock bit in the extent tree
2695 * unlock the page if there are no other extents locked for it
2697 * Scheduling is not allowed, so the extent state tree is expected
2698 * to have one and only one object corresponding to this IO.
2700 static void end_bio_extent_readpage(struct bio *bio)
2702 struct bio_vec *bvec;
2703 int uptodate = !bio->bi_status;
2704 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2705 struct extent_io_tree *tree, *failure_tree;
2706 u64 offset = 0;
2707 u64 start;
2708 u64 end;
2709 u64 len;
2710 u64 extent_start = 0;
2711 u64 extent_len = 0;
2712 int mirror;
2713 int ret;
2714 struct bvec_iter_all iter_all;
2716 ASSERT(!bio_flagged(bio, BIO_CLONED));
2717 bio_for_each_segment_all(bvec, bio, iter_all) {
2718 struct page *page = bvec->bv_page;
2719 struct inode *inode = page->mapping->host;
2720 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2721 bool data_inode = btrfs_ino(BTRFS_I(inode))
2722 != BTRFS_BTREE_INODE_OBJECTID;
2724 btrfs_debug(fs_info,
2725 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2726 (u64)bio->bi_iter.bi_sector, bio->bi_status,
2727 io_bio->mirror_num);
2728 tree = &BTRFS_I(inode)->io_tree;
2729 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2731 /* We always issue full-page reads, but if some block
2732 * in a page fails to read, blk_update_request() will
2733 * advance bv_offset and adjust bv_len to compensate.
2734 * Print a warning for nonzero offsets, and an error
2735 * if they don't add up to a full page. */
2736 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2737 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2738 btrfs_err(fs_info,
2739 "partial page read in btrfs with offset %u and length %u",
2740 bvec->bv_offset, bvec->bv_len);
2741 else
2742 btrfs_info(fs_info,
2743 "incomplete page read in btrfs with offset %u and length %u",
2744 bvec->bv_offset, bvec->bv_len);
2747 start = page_offset(page);
2748 end = start + bvec->bv_offset + bvec->bv_len - 1;
2749 len = bvec->bv_len;
2751 mirror = io_bio->mirror_num;
2752 if (likely(uptodate)) {
2753 ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2754 page, start, end,
2755 mirror);
2756 if (ret)
2757 uptodate = 0;
2758 else
2759 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2760 failure_tree, tree, start,
2761 page,
2762 btrfs_ino(BTRFS_I(inode)), 0);
2765 if (likely(uptodate))
2766 goto readpage_ok;
2768 if (data_inode) {
2771 * The generic bio_readpage_error handles errors the
2772 * following way: If possible, new read requests are
2773 * created and submitted and will end up in
2774 * end_bio_extent_readpage as well (if we're lucky,
2775 * not in the !uptodate case). In that case it returns
2776 * 0 and we just go on with the next page in our bio.
2777 * If it can't handle the error it will return -EIO and
2778 * we remain responsible for that page.
2780 ret = bio_readpage_error(bio, offset, page, start, end,
2781 mirror);
2782 if (ret == 0) {
2783 uptodate = !bio->bi_status;
2784 offset += len;
2785 continue;
2787 } else {
2788 struct extent_buffer *eb;
2790 eb = (struct extent_buffer *)page->private;
2791 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2792 eb->read_mirror = mirror;
2793 atomic_dec(&eb->io_pages);
2794 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2795 &eb->bflags))
2796 btree_readahead_hook(eb, -EIO);
2798 readpage_ok:
2799 if (likely(uptodate)) {
2800 loff_t i_size = i_size_read(inode);
2801 pgoff_t end_index = i_size >> PAGE_SHIFT;
2802 unsigned off;
2804 /* Zero out the end if this page straddles i_size */
2805 off = offset_in_page(i_size);
2806 if (page->index == end_index && off)
2807 zero_user_segment(page, off, PAGE_SIZE);
2808 SetPageUptodate(page);
2809 } else {
2810 ClearPageUptodate(page);
2811 SetPageError(page);
2813 unlock_page(page);
2814 offset += len;
2816 if (unlikely(!uptodate)) {
2817 if (extent_len) {
2818 endio_readpage_release_extent(tree,
2819 extent_start,
2820 extent_len, 1);
2821 extent_start = 0;
2822 extent_len = 0;
2824 endio_readpage_release_extent(tree, start,
2825 end - start + 1, 0);
2826 } else if (!extent_len) {
2827 extent_start = start;
2828 extent_len = end + 1 - start;
2829 } else if (extent_start + extent_len == start) {
2830 extent_len += end + 1 - start;
2831 } else {
2832 endio_readpage_release_extent(tree, extent_start,
2833 extent_len, uptodate);
2834 extent_start = start;
2835 extent_len = end + 1 - start;
2839 if (extent_len)
2840 endio_readpage_release_extent(tree, extent_start, extent_len,
2841 uptodate);
2842 btrfs_io_bio_free_csum(io_bio);
2843 bio_put(bio);
2847 * Initialize the members up to but not including 'bio'. Use after allocating a
2848 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2849 * 'bio' because use of __GFP_ZERO is not supported.
2851 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2853 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2857 * The following helpers allocate a bio. As it's backed by a bioset, it'll
2858 * never fail. We're returning a bio right now but you can call btrfs_io_bio
2859 * for the appropriate container_of magic
2861 struct bio *btrfs_bio_alloc(struct block_device *bdev, u64 first_byte)
2863 struct bio *bio;
2865 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2866 bio_set_dev(bio, bdev);
2867 bio->bi_iter.bi_sector = first_byte >> 9;
2868 btrfs_io_bio_init(btrfs_io_bio(bio));
2869 return bio;
2872 struct bio *btrfs_bio_clone(struct bio *bio)
2874 struct btrfs_io_bio *btrfs_bio;
2875 struct bio *new;
2877 /* Bio allocation backed by a bioset does not fail */
2878 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2879 btrfs_bio = btrfs_io_bio(new);
2880 btrfs_io_bio_init(btrfs_bio);
2881 btrfs_bio->iter = bio->bi_iter;
2882 return new;
2885 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2887 struct bio *bio;
2889 /* Bio allocation backed by a bioset does not fail */
2890 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2891 btrfs_io_bio_init(btrfs_io_bio(bio));
2892 return bio;
2895 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2897 struct bio *bio;
2898 struct btrfs_io_bio *btrfs_bio;
2900 /* this will never fail when it's backed by a bioset */
2901 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2902 ASSERT(bio);
2904 btrfs_bio = btrfs_io_bio(bio);
2905 btrfs_io_bio_init(btrfs_bio);
2907 bio_trim(bio, offset >> 9, size >> 9);
2908 btrfs_bio->iter = bio->bi_iter;
2909 return bio;
2913 * @opf: bio REQ_OP_* and REQ_* flags as one value
2914 * @tree: tree so we can call our merge_bio hook
2915 * @wbc: optional writeback control for io accounting
2916 * @page: page to add to the bio
2917 * @pg_offset: offset of the new bio or to check whether we are adding
2918 * a contiguous page to the previous one
2919 * @size: portion of page that we want to write
2920 * @offset: starting offset in the page
2921 * @bdev: attach newly created bios to this bdev
2922 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
2923 * @end_io_func: end_io callback for new bio
2924 * @mirror_num: desired mirror to read/write
2925 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
2926 * @bio_flags: flags of the current bio to see if we can merge them
2928 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2929 struct writeback_control *wbc,
2930 struct page *page, u64 offset,
2931 size_t size, unsigned long pg_offset,
2932 struct block_device *bdev,
2933 struct bio **bio_ret,
2934 bio_end_io_t end_io_func,
2935 int mirror_num,
2936 unsigned long prev_bio_flags,
2937 unsigned long bio_flags,
2938 bool force_bio_submit)
2940 int ret = 0;
2941 struct bio *bio;
2942 size_t page_size = min_t(size_t, size, PAGE_SIZE);
2943 sector_t sector = offset >> 9;
2945 ASSERT(bio_ret);
2947 if (*bio_ret) {
2948 bool contig;
2949 bool can_merge = true;
2951 bio = *bio_ret;
2952 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2953 contig = bio->bi_iter.bi_sector == sector;
2954 else
2955 contig = bio_end_sector(bio) == sector;
2957 ASSERT(tree->ops);
2958 if (btrfs_bio_fits_in_stripe(page, page_size, bio, bio_flags))
2959 can_merge = false;
2961 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2962 force_bio_submit ||
2963 bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2964 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2965 if (ret < 0) {
2966 *bio_ret = NULL;
2967 return ret;
2969 bio = NULL;
2970 } else {
2971 if (wbc)
2972 wbc_account_io(wbc, page, page_size);
2973 return 0;
2977 bio = btrfs_bio_alloc(bdev, offset);
2978 bio_add_page(bio, page, page_size, pg_offset);
2979 bio->bi_end_io = end_io_func;
2980 bio->bi_private = tree;
2981 bio->bi_write_hint = page->mapping->host->i_write_hint;
2982 bio->bi_opf = opf;
2983 if (wbc) {
2984 wbc_init_bio(wbc, bio);
2985 wbc_account_io(wbc, page, page_size);
2988 *bio_ret = bio;
2990 return ret;
2993 static void attach_extent_buffer_page(struct extent_buffer *eb,
2994 struct page *page)
2996 if (!PagePrivate(page)) {
2997 SetPagePrivate(page);
2998 get_page(page);
2999 set_page_private(page, (unsigned long)eb);
3000 } else {
3001 WARN_ON(page->private != (unsigned long)eb);
3005 void set_page_extent_mapped(struct page *page)
3007 if (!PagePrivate(page)) {
3008 SetPagePrivate(page);
3009 get_page(page);
3010 set_page_private(page, EXTENT_PAGE_PRIVATE);
3014 static struct extent_map *
3015 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3016 u64 start, u64 len, get_extent_t *get_extent,
3017 struct extent_map **em_cached)
3019 struct extent_map *em;
3021 if (em_cached && *em_cached) {
3022 em = *em_cached;
3023 if (extent_map_in_tree(em) && start >= em->start &&
3024 start < extent_map_end(em)) {
3025 refcount_inc(&em->refs);
3026 return em;
3029 free_extent_map(em);
3030 *em_cached = NULL;
3033 em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
3034 if (em_cached && !IS_ERR_OR_NULL(em)) {
3035 BUG_ON(*em_cached);
3036 refcount_inc(&em->refs);
3037 *em_cached = em;
3039 return em;
3042 * basic readpage implementation. Locked extent state structs are inserted
3043 * into the tree that are removed when the IO is done (by the end_io
3044 * handlers)
3045 * XXX JDM: This needs looking at to ensure proper page locking
3046 * return 0 on success, otherwise return error
3048 static int __do_readpage(struct extent_io_tree *tree,
3049 struct page *page,
3050 get_extent_t *get_extent,
3051 struct extent_map **em_cached,
3052 struct bio **bio, int mirror_num,
3053 unsigned long *bio_flags, unsigned int read_flags,
3054 u64 *prev_em_start)
3056 struct inode *inode = page->mapping->host;
3057 u64 start = page_offset(page);
3058 const u64 end = start + PAGE_SIZE - 1;
3059 u64 cur = start;
3060 u64 extent_offset;
3061 u64 last_byte = i_size_read(inode);
3062 u64 block_start;
3063 u64 cur_end;
3064 struct extent_map *em;
3065 struct block_device *bdev;
3066 int ret = 0;
3067 int nr = 0;
3068 size_t pg_offset = 0;
3069 size_t iosize;
3070 size_t disk_io_size;
3071 size_t blocksize = inode->i_sb->s_blocksize;
3072 unsigned long this_bio_flag = 0;
3074 set_page_extent_mapped(page);
3076 if (!PageUptodate(page)) {
3077 if (cleancache_get_page(page) == 0) {
3078 BUG_ON(blocksize != PAGE_SIZE);
3079 unlock_extent(tree, start, end);
3080 goto out;
3084 if (page->index == last_byte >> PAGE_SHIFT) {
3085 char *userpage;
3086 size_t zero_offset = offset_in_page(last_byte);
3088 if (zero_offset) {
3089 iosize = PAGE_SIZE - zero_offset;
3090 userpage = kmap_atomic(page);
3091 memset(userpage + zero_offset, 0, iosize);
3092 flush_dcache_page(page);
3093 kunmap_atomic(userpage);
3096 while (cur <= end) {
3097 bool force_bio_submit = false;
3098 u64 offset;
3100 if (cur >= last_byte) {
3101 char *userpage;
3102 struct extent_state *cached = NULL;
3104 iosize = PAGE_SIZE - pg_offset;
3105 userpage = kmap_atomic(page);
3106 memset(userpage + pg_offset, 0, iosize);
3107 flush_dcache_page(page);
3108 kunmap_atomic(userpage);
3109 set_extent_uptodate(tree, cur, cur + iosize - 1,
3110 &cached, GFP_NOFS);
3111 unlock_extent_cached(tree, cur,
3112 cur + iosize - 1, &cached);
3113 break;
3115 em = __get_extent_map(inode, page, pg_offset, cur,
3116 end - cur + 1, get_extent, em_cached);
3117 if (IS_ERR_OR_NULL(em)) {
3118 SetPageError(page);
3119 unlock_extent(tree, cur, end);
3120 break;
3122 extent_offset = cur - em->start;
3123 BUG_ON(extent_map_end(em) <= cur);
3124 BUG_ON(end < cur);
3126 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3127 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3128 extent_set_compress_type(&this_bio_flag,
3129 em->compress_type);
3132 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3133 cur_end = min(extent_map_end(em) - 1, end);
3134 iosize = ALIGN(iosize, blocksize);
3135 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
3136 disk_io_size = em->block_len;
3137 offset = em->block_start;
3138 } else {
3139 offset = em->block_start + extent_offset;
3140 disk_io_size = iosize;
3142 bdev = em->bdev;
3143 block_start = em->block_start;
3144 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3145 block_start = EXTENT_MAP_HOLE;
3148 * If we have a file range that points to a compressed extent
3149 * and it's followed by a consecutive file range that points to
3150 * to the same compressed extent (possibly with a different
3151 * offset and/or length, so it either points to the whole extent
3152 * or only part of it), we must make sure we do not submit a
3153 * single bio to populate the pages for the 2 ranges because
3154 * this makes the compressed extent read zero out the pages
3155 * belonging to the 2nd range. Imagine the following scenario:
3157 * File layout
3158 * [0 - 8K] [8K - 24K]
3159 * | |
3160 * | |
3161 * points to extent X, points to extent X,
3162 * offset 4K, length of 8K offset 0, length 16K
3164 * [extent X, compressed length = 4K uncompressed length = 16K]
3166 * If the bio to read the compressed extent covers both ranges,
3167 * it will decompress extent X into the pages belonging to the
3168 * first range and then it will stop, zeroing out the remaining
3169 * pages that belong to the other range that points to extent X.
3170 * So here we make sure we submit 2 bios, one for the first
3171 * range and another one for the third range. Both will target
3172 * the same physical extent from disk, but we can't currently
3173 * make the compressed bio endio callback populate the pages
3174 * for both ranges because each compressed bio is tightly
3175 * coupled with a single extent map, and each range can have
3176 * an extent map with a different offset value relative to the
3177 * uncompressed data of our extent and different lengths. This
3178 * is a corner case so we prioritize correctness over
3179 * non-optimal behavior (submitting 2 bios for the same extent).
3181 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3182 prev_em_start && *prev_em_start != (u64)-1 &&
3183 *prev_em_start != em->start)
3184 force_bio_submit = true;
3186 if (prev_em_start)
3187 *prev_em_start = em->start;
3189 free_extent_map(em);
3190 em = NULL;
3192 /* we've found a hole, just zero and go on */
3193 if (block_start == EXTENT_MAP_HOLE) {
3194 char *userpage;
3195 struct extent_state *cached = NULL;
3197 userpage = kmap_atomic(page);
3198 memset(userpage + pg_offset, 0, iosize);
3199 flush_dcache_page(page);
3200 kunmap_atomic(userpage);
3202 set_extent_uptodate(tree, cur, cur + iosize - 1,
3203 &cached, GFP_NOFS);
3204 unlock_extent_cached(tree, cur,
3205 cur + iosize - 1, &cached);
3206 cur = cur + iosize;
3207 pg_offset += iosize;
3208 continue;
3210 /* the get_extent function already copied into the page */
3211 if (test_range_bit(tree, cur, cur_end,
3212 EXTENT_UPTODATE, 1, NULL)) {
3213 check_page_uptodate(tree, page);
3214 unlock_extent(tree, cur, cur + iosize - 1);
3215 cur = cur + iosize;
3216 pg_offset += iosize;
3217 continue;
3219 /* we have an inline extent but it didn't get marked up
3220 * to date. Error out
3222 if (block_start == EXTENT_MAP_INLINE) {
3223 SetPageError(page);
3224 unlock_extent(tree, cur, cur + iosize - 1);
3225 cur = cur + iosize;
3226 pg_offset += iosize;
3227 continue;
3230 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3231 page, offset, disk_io_size,
3232 pg_offset, bdev, bio,
3233 end_bio_extent_readpage, mirror_num,
3234 *bio_flags,
3235 this_bio_flag,
3236 force_bio_submit);
3237 if (!ret) {
3238 nr++;
3239 *bio_flags = this_bio_flag;
3240 } else {
3241 SetPageError(page);
3242 unlock_extent(tree, cur, cur + iosize - 1);
3243 goto out;
3245 cur = cur + iosize;
3246 pg_offset += iosize;
3248 out:
3249 if (!nr) {
3250 if (!PageError(page))
3251 SetPageUptodate(page);
3252 unlock_page(page);
3254 return ret;
3257 static inline void contiguous_readpages(struct extent_io_tree *tree,
3258 struct page *pages[], int nr_pages,
3259 u64 start, u64 end,
3260 struct extent_map **em_cached,
3261 struct bio **bio,
3262 unsigned long *bio_flags,
3263 u64 *prev_em_start)
3265 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3266 int index;
3268 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3270 for (index = 0; index < nr_pages; index++) {
3271 __do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3272 bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3273 put_page(pages[index]);
3277 static int __extent_read_full_page(struct extent_io_tree *tree,
3278 struct page *page,
3279 get_extent_t *get_extent,
3280 struct bio **bio, int mirror_num,
3281 unsigned long *bio_flags,
3282 unsigned int read_flags)
3284 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3285 u64 start = page_offset(page);
3286 u64 end = start + PAGE_SIZE - 1;
3287 int ret;
3289 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3291 ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3292 bio_flags, read_flags, NULL);
3293 return ret;
3296 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3297 get_extent_t *get_extent, int mirror_num)
3299 struct bio *bio = NULL;
3300 unsigned long bio_flags = 0;
3301 int ret;
3303 ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3304 &bio_flags, 0);
3305 if (bio)
3306 ret = submit_one_bio(bio, mirror_num, bio_flags);
3307 return ret;
3310 static void update_nr_written(struct writeback_control *wbc,
3311 unsigned long nr_written)
3313 wbc->nr_to_write -= nr_written;
3317 * helper for __extent_writepage, doing all of the delayed allocation setup.
3319 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3320 * to write the page (copy into inline extent). In this case the IO has
3321 * been started and the page is already unlocked.
3323 * This returns 0 if all went well (page still locked)
3324 * This returns < 0 if there were errors (page still locked)
3326 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3327 struct page *page, struct writeback_control *wbc,
3328 u64 delalloc_start, unsigned long *nr_written)
3330 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3331 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3332 bool found;
3333 u64 delalloc_to_write = 0;
3334 u64 delalloc_end = 0;
3335 int ret;
3336 int page_started = 0;
3339 while (delalloc_end < page_end) {
3340 found = find_lock_delalloc_range(inode, tree,
3341 page,
3342 &delalloc_start,
3343 &delalloc_end);
3344 if (!found) {
3345 delalloc_start = delalloc_end + 1;
3346 continue;
3348 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3349 delalloc_end, &page_started, nr_written, wbc);
3350 if (ret) {
3351 SetPageError(page);
3353 * btrfs_run_delalloc_range should return < 0 for error
3354 * but just in case, we use > 0 here meaning the IO is
3355 * started, so we don't want to return > 0 unless
3356 * things are going well.
3358 ret = ret < 0 ? ret : -EIO;
3359 goto done;
3362 * delalloc_end is already one less than the total length, so
3363 * we don't subtract one from PAGE_SIZE
3365 delalloc_to_write += (delalloc_end - delalloc_start +
3366 PAGE_SIZE) >> PAGE_SHIFT;
3367 delalloc_start = delalloc_end + 1;
3369 if (wbc->nr_to_write < delalloc_to_write) {
3370 int thresh = 8192;
3372 if (delalloc_to_write < thresh * 2)
3373 thresh = delalloc_to_write;
3374 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3375 thresh);
3378 /* did the fill delalloc function already unlock and start
3379 * the IO?
3381 if (page_started) {
3383 * we've unlocked the page, so we can't update
3384 * the mapping's writeback index, just update
3385 * nr_to_write.
3387 wbc->nr_to_write -= *nr_written;
3388 return 1;
3391 ret = 0;
3393 done:
3394 return ret;
3398 * helper for __extent_writepage. This calls the writepage start hooks,
3399 * and does the loop to map the page into extents and bios.
3401 * We return 1 if the IO is started and the page is unlocked,
3402 * 0 if all went well (page still locked)
3403 * < 0 if there were errors (page still locked)
3405 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3406 struct page *page,
3407 struct writeback_control *wbc,
3408 struct extent_page_data *epd,
3409 loff_t i_size,
3410 unsigned long nr_written,
3411 unsigned int write_flags, int *nr_ret)
3413 struct extent_io_tree *tree = epd->tree;
3414 u64 start = page_offset(page);
3415 u64 page_end = start + PAGE_SIZE - 1;
3416 u64 end;
3417 u64 cur = start;
3418 u64 extent_offset;
3419 u64 block_start;
3420 u64 iosize;
3421 struct extent_map *em;
3422 struct block_device *bdev;
3423 size_t pg_offset = 0;
3424 size_t blocksize;
3425 int ret = 0;
3426 int nr = 0;
3427 bool compressed;
3429 ret = btrfs_writepage_cow_fixup(page, start, page_end);
3430 if (ret) {
3431 /* Fixup worker will requeue */
3432 if (ret == -EBUSY)
3433 wbc->pages_skipped++;
3434 else
3435 redirty_page_for_writepage(wbc, page);
3437 update_nr_written(wbc, nr_written);
3438 unlock_page(page);
3439 return 1;
3443 * we don't want to touch the inode after unlocking the page,
3444 * so we update the mapping writeback index now
3446 update_nr_written(wbc, nr_written + 1);
3448 end = page_end;
3449 if (i_size <= start) {
3450 btrfs_writepage_endio_finish_ordered(page, start, page_end, 1);
3451 goto done;
3454 blocksize = inode->i_sb->s_blocksize;
3456 while (cur <= end) {
3457 u64 em_end;
3458 u64 offset;
3460 if (cur >= i_size) {
3461 btrfs_writepage_endio_finish_ordered(page, cur,
3462 page_end, 1);
3463 break;
3465 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3466 end - cur + 1, 1);
3467 if (IS_ERR_OR_NULL(em)) {
3468 SetPageError(page);
3469 ret = PTR_ERR_OR_ZERO(em);
3470 break;
3473 extent_offset = cur - em->start;
3474 em_end = extent_map_end(em);
3475 BUG_ON(em_end <= cur);
3476 BUG_ON(end < cur);
3477 iosize = min(em_end - cur, end - cur + 1);
3478 iosize = ALIGN(iosize, blocksize);
3479 offset = em->block_start + extent_offset;
3480 bdev = em->bdev;
3481 block_start = em->block_start;
3482 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3483 free_extent_map(em);
3484 em = NULL;
3487 * compressed and inline extents are written through other
3488 * paths in the FS
3490 if (compressed || block_start == EXTENT_MAP_HOLE ||
3491 block_start == EXTENT_MAP_INLINE) {
3493 * end_io notification does not happen here for
3494 * compressed extents
3496 if (!compressed)
3497 btrfs_writepage_endio_finish_ordered(page, cur,
3498 cur + iosize - 1,
3500 else if (compressed) {
3501 /* we don't want to end_page_writeback on
3502 * a compressed extent. this happens
3503 * elsewhere
3505 nr++;
3508 cur += iosize;
3509 pg_offset += iosize;
3510 continue;
3513 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3514 if (!PageWriteback(page)) {
3515 btrfs_err(BTRFS_I(inode)->root->fs_info,
3516 "page %lu not writeback, cur %llu end %llu",
3517 page->index, cur, end);
3520 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3521 page, offset, iosize, pg_offset,
3522 bdev, &epd->bio,
3523 end_bio_extent_writepage,
3524 0, 0, 0, false);
3525 if (ret) {
3526 SetPageError(page);
3527 if (PageWriteback(page))
3528 end_page_writeback(page);
3531 cur = cur + iosize;
3532 pg_offset += iosize;
3533 nr++;
3535 done:
3536 *nr_ret = nr;
3537 return ret;
3541 * the writepage semantics are similar to regular writepage. extent
3542 * records are inserted to lock ranges in the tree, and as dirty areas
3543 * are found, they are marked writeback. Then the lock bits are removed
3544 * and the end_io handler clears the writeback ranges
3546 * Return 0 if everything goes well.
3547 * Return <0 for error.
3549 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3550 struct extent_page_data *epd)
3552 struct inode *inode = page->mapping->host;
3553 u64 start = page_offset(page);
3554 u64 page_end = start + PAGE_SIZE - 1;
3555 int ret;
3556 int nr = 0;
3557 size_t pg_offset = 0;
3558 loff_t i_size = i_size_read(inode);
3559 unsigned long end_index = i_size >> PAGE_SHIFT;
3560 unsigned int write_flags = 0;
3561 unsigned long nr_written = 0;
3563 write_flags = wbc_to_write_flags(wbc);
3565 trace___extent_writepage(page, inode, wbc);
3567 WARN_ON(!PageLocked(page));
3569 ClearPageError(page);
3571 pg_offset = offset_in_page(i_size);
3572 if (page->index > end_index ||
3573 (page->index == end_index && !pg_offset)) {
3574 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3575 unlock_page(page);
3576 return 0;
3579 if (page->index == end_index) {
3580 char *userpage;
3582 userpage = kmap_atomic(page);
3583 memset(userpage + pg_offset, 0,
3584 PAGE_SIZE - pg_offset);
3585 kunmap_atomic(userpage);
3586 flush_dcache_page(page);
3589 pg_offset = 0;
3591 set_page_extent_mapped(page);
3593 if (!epd->extent_locked) {
3594 ret = writepage_delalloc(inode, page, wbc, start, &nr_written);
3595 if (ret == 1)
3596 goto done_unlocked;
3597 if (ret)
3598 goto done;
3601 ret = __extent_writepage_io(inode, page, wbc, epd,
3602 i_size, nr_written, write_flags, &nr);
3603 if (ret == 1)
3604 goto done_unlocked;
3606 done:
3607 if (nr == 0) {
3608 /* make sure the mapping tag for page dirty gets cleared */
3609 set_page_writeback(page);
3610 end_page_writeback(page);
3612 if (PageError(page)) {
3613 ret = ret < 0 ? ret : -EIO;
3614 end_extent_writepage(page, ret, start, page_end);
3616 unlock_page(page);
3617 ASSERT(ret <= 0);
3618 return ret;
3620 done_unlocked:
3621 return 0;
3624 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3626 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3627 TASK_UNINTERRUPTIBLE);
3631 * Lock eb pages and flush the bio if we can't the locks
3633 * Return 0 if nothing went wrong
3634 * Return >0 is same as 0, except bio is not submitted
3635 * Return <0 if something went wrong, no page is locked
3637 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3638 struct extent_page_data *epd)
3640 struct btrfs_fs_info *fs_info = eb->fs_info;
3641 int i, num_pages, failed_page_nr;
3642 int flush = 0;
3643 int ret = 0;
3645 if (!btrfs_try_tree_write_lock(eb)) {
3646 ret = flush_write_bio(epd);
3647 if (ret < 0)
3648 return ret;
3649 flush = 1;
3650 btrfs_tree_lock(eb);
3653 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3654 btrfs_tree_unlock(eb);
3655 if (!epd->sync_io)
3656 return 0;
3657 if (!flush) {
3658 ret = flush_write_bio(epd);
3659 if (ret < 0)
3660 return ret;
3661 flush = 1;
3663 while (1) {
3664 wait_on_extent_buffer_writeback(eb);
3665 btrfs_tree_lock(eb);
3666 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3667 break;
3668 btrfs_tree_unlock(eb);
3673 * We need to do this to prevent races in people who check if the eb is
3674 * under IO since we can end up having no IO bits set for a short period
3675 * of time.
3677 spin_lock(&eb->refs_lock);
3678 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3679 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3680 spin_unlock(&eb->refs_lock);
3681 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3682 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3683 -eb->len,
3684 fs_info->dirty_metadata_batch);
3685 ret = 1;
3686 } else {
3687 spin_unlock(&eb->refs_lock);
3690 btrfs_tree_unlock(eb);
3692 if (!ret)
3693 return ret;
3695 num_pages = num_extent_pages(eb);
3696 for (i = 0; i < num_pages; i++) {
3697 struct page *p = eb->pages[i];
3699 if (!trylock_page(p)) {
3700 if (!flush) {
3701 ret = flush_write_bio(epd);
3702 if (ret < 0) {
3703 failed_page_nr = i;
3704 goto err_unlock;
3706 flush = 1;
3708 lock_page(p);
3712 return ret;
3713 err_unlock:
3714 /* Unlock already locked pages */
3715 for (i = 0; i < failed_page_nr; i++)
3716 unlock_page(eb->pages[i]);
3717 return ret;
3720 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3722 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3723 smp_mb__after_atomic();
3724 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3727 static void set_btree_ioerr(struct page *page)
3729 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3731 SetPageError(page);
3732 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3733 return;
3736 * If writeback for a btree extent that doesn't belong to a log tree
3737 * failed, increment the counter transaction->eb_write_errors.
3738 * We do this because while the transaction is running and before it's
3739 * committing (when we call filemap_fdata[write|wait]_range against
3740 * the btree inode), we might have
3741 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3742 * returns an error or an error happens during writeback, when we're
3743 * committing the transaction we wouldn't know about it, since the pages
3744 * can be no longer dirty nor marked anymore for writeback (if a
3745 * subsequent modification to the extent buffer didn't happen before the
3746 * transaction commit), which makes filemap_fdata[write|wait]_range not
3747 * able to find the pages tagged with SetPageError at transaction
3748 * commit time. So if this happens we must abort the transaction,
3749 * otherwise we commit a super block with btree roots that point to
3750 * btree nodes/leafs whose content on disk is invalid - either garbage
3751 * or the content of some node/leaf from a past generation that got
3752 * cowed or deleted and is no longer valid.
3754 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3755 * not be enough - we need to distinguish between log tree extents vs
3756 * non-log tree extents, and the next filemap_fdatawait_range() call
3757 * will catch and clear such errors in the mapping - and that call might
3758 * be from a log sync and not from a transaction commit. Also, checking
3759 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3760 * not done and would not be reliable - the eb might have been released
3761 * from memory and reading it back again means that flag would not be
3762 * set (since it's a runtime flag, not persisted on disk).
3764 * Using the flags below in the btree inode also makes us achieve the
3765 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3766 * writeback for all dirty pages and before filemap_fdatawait_range()
3767 * is called, the writeback for all dirty pages had already finished
3768 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3769 * filemap_fdatawait_range() would return success, as it could not know
3770 * that writeback errors happened (the pages were no longer tagged for
3771 * writeback).
3773 switch (eb->log_index) {
3774 case -1:
3775 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3776 break;
3777 case 0:
3778 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3779 break;
3780 case 1:
3781 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3782 break;
3783 default:
3784 BUG(); /* unexpected, logic error */
3788 static void end_bio_extent_buffer_writepage(struct bio *bio)
3790 struct bio_vec *bvec;
3791 struct extent_buffer *eb;
3792 int done;
3793 struct bvec_iter_all iter_all;
3795 ASSERT(!bio_flagged(bio, BIO_CLONED));
3796 bio_for_each_segment_all(bvec, bio, iter_all) {
3797 struct page *page = bvec->bv_page;
3799 eb = (struct extent_buffer *)page->private;
3800 BUG_ON(!eb);
3801 done = atomic_dec_and_test(&eb->io_pages);
3803 if (bio->bi_status ||
3804 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3805 ClearPageUptodate(page);
3806 set_btree_ioerr(page);
3809 end_page_writeback(page);
3811 if (!done)
3812 continue;
3814 end_extent_buffer_writeback(eb);
3817 bio_put(bio);
3820 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3821 struct writeback_control *wbc,
3822 struct extent_page_data *epd)
3824 struct btrfs_fs_info *fs_info = eb->fs_info;
3825 struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3826 struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3827 u64 offset = eb->start;
3828 u32 nritems;
3829 int i, num_pages;
3830 unsigned long start, end;
3831 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3832 int ret = 0;
3834 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3835 num_pages = num_extent_pages(eb);
3836 atomic_set(&eb->io_pages, num_pages);
3838 /* set btree blocks beyond nritems with 0 to avoid stale content. */
3839 nritems = btrfs_header_nritems(eb);
3840 if (btrfs_header_level(eb) > 0) {
3841 end = btrfs_node_key_ptr_offset(nritems);
3843 memzero_extent_buffer(eb, end, eb->len - end);
3844 } else {
3846 * leaf:
3847 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3849 start = btrfs_item_nr_offset(nritems);
3850 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
3851 memzero_extent_buffer(eb, start, end - start);
3854 for (i = 0; i < num_pages; i++) {
3855 struct page *p = eb->pages[i];
3857 clear_page_dirty_for_io(p);
3858 set_page_writeback(p);
3859 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3860 p, offset, PAGE_SIZE, 0, bdev,
3861 &epd->bio,
3862 end_bio_extent_buffer_writepage,
3863 0, 0, 0, false);
3864 if (ret) {
3865 set_btree_ioerr(p);
3866 if (PageWriteback(p))
3867 end_page_writeback(p);
3868 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3869 end_extent_buffer_writeback(eb);
3870 ret = -EIO;
3871 break;
3873 offset += PAGE_SIZE;
3874 update_nr_written(wbc, 1);
3875 unlock_page(p);
3878 if (unlikely(ret)) {
3879 for (; i < num_pages; i++) {
3880 struct page *p = eb->pages[i];
3881 clear_page_dirty_for_io(p);
3882 unlock_page(p);
3886 return ret;
3889 int btree_write_cache_pages(struct address_space *mapping,
3890 struct writeback_control *wbc)
3892 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3893 struct extent_buffer *eb, *prev_eb = NULL;
3894 struct extent_page_data epd = {
3895 .bio = NULL,
3896 .tree = tree,
3897 .extent_locked = 0,
3898 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3900 int ret = 0;
3901 int done = 0;
3902 int nr_to_write_done = 0;
3903 struct pagevec pvec;
3904 int nr_pages;
3905 pgoff_t index;
3906 pgoff_t end; /* Inclusive */
3907 int scanned = 0;
3908 xa_mark_t tag;
3910 pagevec_init(&pvec);
3911 if (wbc->range_cyclic) {
3912 index = mapping->writeback_index; /* Start from prev offset */
3913 end = -1;
3914 } else {
3915 index = wbc->range_start >> PAGE_SHIFT;
3916 end = wbc->range_end >> PAGE_SHIFT;
3917 scanned = 1;
3919 if (wbc->sync_mode == WB_SYNC_ALL)
3920 tag = PAGECACHE_TAG_TOWRITE;
3921 else
3922 tag = PAGECACHE_TAG_DIRTY;
3923 retry:
3924 if (wbc->sync_mode == WB_SYNC_ALL)
3925 tag_pages_for_writeback(mapping, index, end);
3926 while (!done && !nr_to_write_done && (index <= end) &&
3927 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3928 tag))) {
3929 unsigned i;
3931 scanned = 1;
3932 for (i = 0; i < nr_pages; i++) {
3933 struct page *page = pvec.pages[i];
3935 if (!PagePrivate(page))
3936 continue;
3938 spin_lock(&mapping->private_lock);
3939 if (!PagePrivate(page)) {
3940 spin_unlock(&mapping->private_lock);
3941 continue;
3944 eb = (struct extent_buffer *)page->private;
3947 * Shouldn't happen and normally this would be a BUG_ON
3948 * but no sense in crashing the users box for something
3949 * we can survive anyway.
3951 if (WARN_ON(!eb)) {
3952 spin_unlock(&mapping->private_lock);
3953 continue;
3956 if (eb == prev_eb) {
3957 spin_unlock(&mapping->private_lock);
3958 continue;
3961 ret = atomic_inc_not_zero(&eb->refs);
3962 spin_unlock(&mapping->private_lock);
3963 if (!ret)
3964 continue;
3966 prev_eb = eb;
3967 ret = lock_extent_buffer_for_io(eb, &epd);
3968 if (!ret) {
3969 free_extent_buffer(eb);
3970 continue;
3973 ret = write_one_eb(eb, wbc, &epd);
3974 if (ret) {
3975 done = 1;
3976 free_extent_buffer(eb);
3977 break;
3979 free_extent_buffer(eb);
3982 * the filesystem may choose to bump up nr_to_write.
3983 * We have to make sure to honor the new nr_to_write
3984 * at any time
3986 nr_to_write_done = wbc->nr_to_write <= 0;
3988 pagevec_release(&pvec);
3989 cond_resched();
3991 if (!scanned && !done) {
3993 * We hit the last page and there is more work to be done: wrap
3994 * back to the start of the file
3996 scanned = 1;
3997 index = 0;
3998 goto retry;
4000 ASSERT(ret <= 0);
4001 if (ret < 0) {
4002 end_write_bio(&epd, ret);
4003 return ret;
4005 ret = flush_write_bio(&epd);
4006 return ret;
4010 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
4011 * @mapping: address space structure to write
4012 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4013 * @data: data passed to __extent_writepage function
4015 * If a page is already under I/O, write_cache_pages() skips it, even
4016 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4017 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4018 * and msync() need to guarantee that all the data which was dirty at the time
4019 * the call was made get new I/O started against them. If wbc->sync_mode is
4020 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4021 * existing IO to complete.
4023 static int extent_write_cache_pages(struct address_space *mapping,
4024 struct writeback_control *wbc,
4025 struct extent_page_data *epd)
4027 struct inode *inode = mapping->host;
4028 int ret = 0;
4029 int done = 0;
4030 int nr_to_write_done = 0;
4031 struct pagevec pvec;
4032 int nr_pages;
4033 pgoff_t index;
4034 pgoff_t end; /* Inclusive */
4035 pgoff_t done_index;
4036 int range_whole = 0;
4037 int scanned = 0;
4038 xa_mark_t tag;
4041 * We have to hold onto the inode so that ordered extents can do their
4042 * work when the IO finishes. The alternative to this is failing to add
4043 * an ordered extent if the igrab() fails there and that is a huge pain
4044 * to deal with, so instead just hold onto the inode throughout the
4045 * writepages operation. If it fails here we are freeing up the inode
4046 * anyway and we'd rather not waste our time writing out stuff that is
4047 * going to be truncated anyway.
4049 if (!igrab(inode))
4050 return 0;
4052 pagevec_init(&pvec);
4053 if (wbc->range_cyclic) {
4054 index = mapping->writeback_index; /* Start from prev offset */
4055 end = -1;
4056 } else {
4057 index = wbc->range_start >> PAGE_SHIFT;
4058 end = wbc->range_end >> PAGE_SHIFT;
4059 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4060 range_whole = 1;
4061 scanned = 1;
4065 * We do the tagged writepage as long as the snapshot flush bit is set
4066 * and we are the first one who do the filemap_flush() on this inode.
4068 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4069 * not race in and drop the bit.
4071 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4072 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4073 &BTRFS_I(inode)->runtime_flags))
4074 wbc->tagged_writepages = 1;
4076 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4077 tag = PAGECACHE_TAG_TOWRITE;
4078 else
4079 tag = PAGECACHE_TAG_DIRTY;
4080 retry:
4081 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4082 tag_pages_for_writeback(mapping, index, end);
4083 done_index = index;
4084 while (!done && !nr_to_write_done && (index <= end) &&
4085 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4086 &index, end, tag))) {
4087 unsigned i;
4089 scanned = 1;
4090 for (i = 0; i < nr_pages; i++) {
4091 struct page *page = pvec.pages[i];
4093 done_index = page->index;
4095 * At this point we hold neither the i_pages lock nor
4096 * the page lock: the page may be truncated or
4097 * invalidated (changing page->mapping to NULL),
4098 * or even swizzled back from swapper_space to
4099 * tmpfs file mapping
4101 if (!trylock_page(page)) {
4102 ret = flush_write_bio(epd);
4103 BUG_ON(ret < 0);
4104 lock_page(page);
4107 if (unlikely(page->mapping != mapping)) {
4108 unlock_page(page);
4109 continue;
4112 if (wbc->sync_mode != WB_SYNC_NONE) {
4113 if (PageWriteback(page)) {
4114 ret = flush_write_bio(epd);
4115 BUG_ON(ret < 0);
4117 wait_on_page_writeback(page);
4120 if (PageWriteback(page) ||
4121 !clear_page_dirty_for_io(page)) {
4122 unlock_page(page);
4123 continue;
4126 ret = __extent_writepage(page, wbc, epd);
4127 if (ret < 0) {
4129 * done_index is set past this page,
4130 * so media errors will not choke
4131 * background writeout for the entire
4132 * file. This has consequences for
4133 * range_cyclic semantics (ie. it may
4134 * not be suitable for data integrity
4135 * writeout).
4137 done_index = page->index + 1;
4138 done = 1;
4139 break;
4143 * the filesystem may choose to bump up nr_to_write.
4144 * We have to make sure to honor the new nr_to_write
4145 * at any time
4147 nr_to_write_done = wbc->nr_to_write <= 0;
4149 pagevec_release(&pvec);
4150 cond_resched();
4152 if (!scanned && !done) {
4154 * We hit the last page and there is more work to be done: wrap
4155 * back to the start of the file
4157 scanned = 1;
4158 index = 0;
4159 goto retry;
4162 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4163 mapping->writeback_index = done_index;
4165 btrfs_add_delayed_iput(inode);
4166 return ret;
4169 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4171 int ret;
4172 struct extent_page_data epd = {
4173 .bio = NULL,
4174 .tree = &BTRFS_I(page->mapping->host)->io_tree,
4175 .extent_locked = 0,
4176 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4179 ret = __extent_writepage(page, wbc, &epd);
4180 ASSERT(ret <= 0);
4181 if (ret < 0) {
4182 end_write_bio(&epd, ret);
4183 return ret;
4186 ret = flush_write_bio(&epd);
4187 ASSERT(ret <= 0);
4188 return ret;
4191 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4192 int mode)
4194 int ret = 0;
4195 struct address_space *mapping = inode->i_mapping;
4196 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4197 struct page *page;
4198 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4199 PAGE_SHIFT;
4201 struct extent_page_data epd = {
4202 .bio = NULL,
4203 .tree = tree,
4204 .extent_locked = 1,
4205 .sync_io = mode == WB_SYNC_ALL,
4207 struct writeback_control wbc_writepages = {
4208 .sync_mode = mode,
4209 .nr_to_write = nr_pages * 2,
4210 .range_start = start,
4211 .range_end = end + 1,
4214 while (start <= end) {
4215 page = find_get_page(mapping, start >> PAGE_SHIFT);
4216 if (clear_page_dirty_for_io(page))
4217 ret = __extent_writepage(page, &wbc_writepages, &epd);
4218 else {
4219 btrfs_writepage_endio_finish_ordered(page, start,
4220 start + PAGE_SIZE - 1, 1);
4221 unlock_page(page);
4223 put_page(page);
4224 start += PAGE_SIZE;
4227 ASSERT(ret <= 0);
4228 if (ret < 0) {
4229 end_write_bio(&epd, ret);
4230 return ret;
4232 ret = flush_write_bio(&epd);
4233 return ret;
4236 int extent_writepages(struct address_space *mapping,
4237 struct writeback_control *wbc)
4239 int ret = 0;
4240 struct extent_page_data epd = {
4241 .bio = NULL,
4242 .tree = &BTRFS_I(mapping->host)->io_tree,
4243 .extent_locked = 0,
4244 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4247 ret = extent_write_cache_pages(mapping, wbc, &epd);
4248 ASSERT(ret <= 0);
4249 if (ret < 0) {
4250 end_write_bio(&epd, ret);
4251 return ret;
4253 ret = flush_write_bio(&epd);
4254 return ret;
4257 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4258 unsigned nr_pages)
4260 struct bio *bio = NULL;
4261 unsigned long bio_flags = 0;
4262 struct page *pagepool[16];
4263 struct extent_map *em_cached = NULL;
4264 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4265 int nr = 0;
4266 u64 prev_em_start = (u64)-1;
4268 while (!list_empty(pages)) {
4269 u64 contig_end = 0;
4271 for (nr = 0; nr < ARRAY_SIZE(pagepool) && !list_empty(pages);) {
4272 struct page *page = lru_to_page(pages);
4274 prefetchw(&page->flags);
4275 list_del(&page->lru);
4276 if (add_to_page_cache_lru(page, mapping, page->index,
4277 readahead_gfp_mask(mapping))) {
4278 put_page(page);
4279 break;
4282 pagepool[nr++] = page;
4283 contig_end = page_offset(page) + PAGE_SIZE - 1;
4286 if (nr) {
4287 u64 contig_start = page_offset(pagepool[0]);
4289 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4291 contiguous_readpages(tree, pagepool, nr, contig_start,
4292 contig_end, &em_cached, &bio, &bio_flags,
4293 &prev_em_start);
4297 if (em_cached)
4298 free_extent_map(em_cached);
4300 if (bio)
4301 return submit_one_bio(bio, 0, bio_flags);
4302 return 0;
4306 * basic invalidatepage code, this waits on any locked or writeback
4307 * ranges corresponding to the page, and then deletes any extent state
4308 * records from the tree
4310 int extent_invalidatepage(struct extent_io_tree *tree,
4311 struct page *page, unsigned long offset)
4313 struct extent_state *cached_state = NULL;
4314 u64 start = page_offset(page);
4315 u64 end = start + PAGE_SIZE - 1;
4316 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4318 start += ALIGN(offset, blocksize);
4319 if (start > end)
4320 return 0;
4322 lock_extent_bits(tree, start, end, &cached_state);
4323 wait_on_page_writeback(page);
4324 clear_extent_bit(tree, start, end,
4325 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
4326 EXTENT_DO_ACCOUNTING,
4327 1, 1, &cached_state);
4328 return 0;
4332 * a helper for releasepage, this tests for areas of the page that
4333 * are locked or under IO and drops the related state bits if it is safe
4334 * to drop the page.
4336 static int try_release_extent_state(struct extent_io_tree *tree,
4337 struct page *page, gfp_t mask)
4339 u64 start = page_offset(page);
4340 u64 end = start + PAGE_SIZE - 1;
4341 int ret = 1;
4343 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4344 ret = 0;
4345 } else {
4347 * at this point we can safely clear everything except the
4348 * locked bit and the nodatasum bit
4350 ret = __clear_extent_bit(tree, start, end,
4351 ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4352 0, 0, NULL, mask, NULL);
4354 /* if clear_extent_bit failed for enomem reasons,
4355 * we can't allow the release to continue.
4357 if (ret < 0)
4358 ret = 0;
4359 else
4360 ret = 1;
4362 return ret;
4366 * a helper for releasepage. As long as there are no locked extents
4367 * in the range corresponding to the page, both state records and extent
4368 * map records are removed
4370 int try_release_extent_mapping(struct page *page, gfp_t mask)
4372 struct extent_map *em;
4373 u64 start = page_offset(page);
4374 u64 end = start + PAGE_SIZE - 1;
4375 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4376 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4377 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4379 if (gfpflags_allow_blocking(mask) &&
4380 page->mapping->host->i_size > SZ_16M) {
4381 u64 len;
4382 while (start <= end) {
4383 len = end - start + 1;
4384 write_lock(&map->lock);
4385 em = lookup_extent_mapping(map, start, len);
4386 if (!em) {
4387 write_unlock(&map->lock);
4388 break;
4390 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4391 em->start != start) {
4392 write_unlock(&map->lock);
4393 free_extent_map(em);
4394 break;
4396 if (!test_range_bit(tree, em->start,
4397 extent_map_end(em) - 1,
4398 EXTENT_LOCKED, 0, NULL)) {
4399 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4400 &btrfs_inode->runtime_flags);
4401 remove_extent_mapping(map, em);
4402 /* once for the rb tree */
4403 free_extent_map(em);
4405 start = extent_map_end(em);
4406 write_unlock(&map->lock);
4408 /* once for us */
4409 free_extent_map(em);
4412 return try_release_extent_state(tree, page, mask);
4416 * helper function for fiemap, which doesn't want to see any holes.
4417 * This maps until we find something past 'last'
4419 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4420 u64 offset, u64 last)
4422 u64 sectorsize = btrfs_inode_sectorsize(inode);
4423 struct extent_map *em;
4424 u64 len;
4426 if (offset >= last)
4427 return NULL;
4429 while (1) {
4430 len = last - offset;
4431 if (len == 0)
4432 break;
4433 len = ALIGN(len, sectorsize);
4434 em = btrfs_get_extent_fiemap(BTRFS_I(inode), offset, len);
4435 if (IS_ERR_OR_NULL(em))
4436 return em;
4438 /* if this isn't a hole return it */
4439 if (em->block_start != EXTENT_MAP_HOLE)
4440 return em;
4442 /* this is a hole, advance to the next extent */
4443 offset = extent_map_end(em);
4444 free_extent_map(em);
4445 if (offset >= last)
4446 break;
4448 return NULL;
4452 * To cache previous fiemap extent
4454 * Will be used for merging fiemap extent
4456 struct fiemap_cache {
4457 u64 offset;
4458 u64 phys;
4459 u64 len;
4460 u32 flags;
4461 bool cached;
4465 * Helper to submit fiemap extent.
4467 * Will try to merge current fiemap extent specified by @offset, @phys,
4468 * @len and @flags with cached one.
4469 * And only when we fails to merge, cached one will be submitted as
4470 * fiemap extent.
4472 * Return value is the same as fiemap_fill_next_extent().
4474 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4475 struct fiemap_cache *cache,
4476 u64 offset, u64 phys, u64 len, u32 flags)
4478 int ret = 0;
4480 if (!cache->cached)
4481 goto assign;
4484 * Sanity check, extent_fiemap() should have ensured that new
4485 * fiemap extent won't overlap with cached one.
4486 * Not recoverable.
4488 * NOTE: Physical address can overlap, due to compression
4490 if (cache->offset + cache->len > offset) {
4491 WARN_ON(1);
4492 return -EINVAL;
4496 * Only merges fiemap extents if
4497 * 1) Their logical addresses are continuous
4499 * 2) Their physical addresses are continuous
4500 * So truly compressed (physical size smaller than logical size)
4501 * extents won't get merged with each other
4503 * 3) Share same flags except FIEMAP_EXTENT_LAST
4504 * So regular extent won't get merged with prealloc extent
4506 if (cache->offset + cache->len == offset &&
4507 cache->phys + cache->len == phys &&
4508 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4509 (flags & ~FIEMAP_EXTENT_LAST)) {
4510 cache->len += len;
4511 cache->flags |= flags;
4512 goto try_submit_last;
4515 /* Not mergeable, need to submit cached one */
4516 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4517 cache->len, cache->flags);
4518 cache->cached = false;
4519 if (ret)
4520 return ret;
4521 assign:
4522 cache->cached = true;
4523 cache->offset = offset;
4524 cache->phys = phys;
4525 cache->len = len;
4526 cache->flags = flags;
4527 try_submit_last:
4528 if (cache->flags & FIEMAP_EXTENT_LAST) {
4529 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4530 cache->phys, cache->len, cache->flags);
4531 cache->cached = false;
4533 return ret;
4537 * Emit last fiemap cache
4539 * The last fiemap cache may still be cached in the following case:
4540 * 0 4k 8k
4541 * |<- Fiemap range ->|
4542 * |<------------ First extent ----------->|
4544 * In this case, the first extent range will be cached but not emitted.
4545 * So we must emit it before ending extent_fiemap().
4547 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4548 struct fiemap_cache *cache)
4550 int ret;
4552 if (!cache->cached)
4553 return 0;
4555 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4556 cache->len, cache->flags);
4557 cache->cached = false;
4558 if (ret > 0)
4559 ret = 0;
4560 return ret;
4563 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4564 __u64 start, __u64 len)
4566 int ret = 0;
4567 u64 off = start;
4568 u64 max = start + len;
4569 u32 flags = 0;
4570 u32 found_type;
4571 u64 last;
4572 u64 last_for_get_extent = 0;
4573 u64 disko = 0;
4574 u64 isize = i_size_read(inode);
4575 struct btrfs_key found_key;
4576 struct extent_map *em = NULL;
4577 struct extent_state *cached_state = NULL;
4578 struct btrfs_path *path;
4579 struct btrfs_root *root = BTRFS_I(inode)->root;
4580 struct fiemap_cache cache = { 0 };
4581 struct ulist *roots;
4582 struct ulist *tmp_ulist;
4583 int end = 0;
4584 u64 em_start = 0;
4585 u64 em_len = 0;
4586 u64 em_end = 0;
4588 if (len == 0)
4589 return -EINVAL;
4591 path = btrfs_alloc_path();
4592 if (!path)
4593 return -ENOMEM;
4594 path->leave_spinning = 1;
4596 roots = ulist_alloc(GFP_KERNEL);
4597 tmp_ulist = ulist_alloc(GFP_KERNEL);
4598 if (!roots || !tmp_ulist) {
4599 ret = -ENOMEM;
4600 goto out_free_ulist;
4603 start = round_down(start, btrfs_inode_sectorsize(inode));
4604 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4607 * lookup the last file extent. We're not using i_size here
4608 * because there might be preallocation past i_size
4610 ret = btrfs_lookup_file_extent(NULL, root, path,
4611 btrfs_ino(BTRFS_I(inode)), -1, 0);
4612 if (ret < 0) {
4613 btrfs_free_path(path);
4614 goto out_free_ulist;
4615 } else {
4616 WARN_ON(!ret);
4617 if (ret == 1)
4618 ret = 0;
4621 path->slots[0]--;
4622 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4623 found_type = found_key.type;
4625 /* No extents, but there might be delalloc bits */
4626 if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4627 found_type != BTRFS_EXTENT_DATA_KEY) {
4628 /* have to trust i_size as the end */
4629 last = (u64)-1;
4630 last_for_get_extent = isize;
4631 } else {
4633 * remember the start of the last extent. There are a
4634 * bunch of different factors that go into the length of the
4635 * extent, so its much less complex to remember where it started
4637 last = found_key.offset;
4638 last_for_get_extent = last + 1;
4640 btrfs_release_path(path);
4643 * we might have some extents allocated but more delalloc past those
4644 * extents. so, we trust isize unless the start of the last extent is
4645 * beyond isize
4647 if (last < isize) {
4648 last = (u64)-1;
4649 last_for_get_extent = isize;
4652 lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4653 &cached_state);
4655 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4656 if (!em)
4657 goto out;
4658 if (IS_ERR(em)) {
4659 ret = PTR_ERR(em);
4660 goto out;
4663 while (!end) {
4664 u64 offset_in_extent = 0;
4666 /* break if the extent we found is outside the range */
4667 if (em->start >= max || extent_map_end(em) < off)
4668 break;
4671 * get_extent may return an extent that starts before our
4672 * requested range. We have to make sure the ranges
4673 * we return to fiemap always move forward and don't
4674 * overlap, so adjust the offsets here
4676 em_start = max(em->start, off);
4679 * record the offset from the start of the extent
4680 * for adjusting the disk offset below. Only do this if the
4681 * extent isn't compressed since our in ram offset may be past
4682 * what we have actually allocated on disk.
4684 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4685 offset_in_extent = em_start - em->start;
4686 em_end = extent_map_end(em);
4687 em_len = em_end - em_start;
4688 flags = 0;
4689 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4690 disko = em->block_start + offset_in_extent;
4691 else
4692 disko = 0;
4695 * bump off for our next call to get_extent
4697 off = extent_map_end(em);
4698 if (off >= max)
4699 end = 1;
4701 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4702 end = 1;
4703 flags |= FIEMAP_EXTENT_LAST;
4704 } else if (em->block_start == EXTENT_MAP_INLINE) {
4705 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4706 FIEMAP_EXTENT_NOT_ALIGNED);
4707 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4708 flags |= (FIEMAP_EXTENT_DELALLOC |
4709 FIEMAP_EXTENT_UNKNOWN);
4710 } else if (fieinfo->fi_extents_max) {
4711 u64 bytenr = em->block_start -
4712 (em->start - em->orig_start);
4715 * As btrfs supports shared space, this information
4716 * can be exported to userspace tools via
4717 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4718 * then we're just getting a count and we can skip the
4719 * lookup stuff.
4721 ret = btrfs_check_shared(root,
4722 btrfs_ino(BTRFS_I(inode)),
4723 bytenr, roots, tmp_ulist);
4724 if (ret < 0)
4725 goto out_free;
4726 if (ret)
4727 flags |= FIEMAP_EXTENT_SHARED;
4728 ret = 0;
4730 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4731 flags |= FIEMAP_EXTENT_ENCODED;
4732 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4733 flags |= FIEMAP_EXTENT_UNWRITTEN;
4735 free_extent_map(em);
4736 em = NULL;
4737 if ((em_start >= last) || em_len == (u64)-1 ||
4738 (last == (u64)-1 && isize <= em_end)) {
4739 flags |= FIEMAP_EXTENT_LAST;
4740 end = 1;
4743 /* now scan forward to see if this is really the last extent. */
4744 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4745 if (IS_ERR(em)) {
4746 ret = PTR_ERR(em);
4747 goto out;
4749 if (!em) {
4750 flags |= FIEMAP_EXTENT_LAST;
4751 end = 1;
4753 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4754 em_len, flags);
4755 if (ret) {
4756 if (ret == 1)
4757 ret = 0;
4758 goto out_free;
4761 out_free:
4762 if (!ret)
4763 ret = emit_last_fiemap_cache(fieinfo, &cache);
4764 free_extent_map(em);
4765 out:
4766 btrfs_free_path(path);
4767 unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4768 &cached_state);
4770 out_free_ulist:
4771 ulist_free(roots);
4772 ulist_free(tmp_ulist);
4773 return ret;
4776 static void __free_extent_buffer(struct extent_buffer *eb)
4778 btrfs_leak_debug_del(&eb->leak_list);
4779 kmem_cache_free(extent_buffer_cache, eb);
4782 int extent_buffer_under_io(struct extent_buffer *eb)
4784 return (atomic_read(&eb->io_pages) ||
4785 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4786 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4790 * Release all pages attached to the extent buffer.
4792 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4794 int i;
4795 int num_pages;
4796 int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4798 BUG_ON(extent_buffer_under_io(eb));
4800 num_pages = num_extent_pages(eb);
4801 for (i = 0; i < num_pages; i++) {
4802 struct page *page = eb->pages[i];
4804 if (!page)
4805 continue;
4806 if (mapped)
4807 spin_lock(&page->mapping->private_lock);
4809 * We do this since we'll remove the pages after we've
4810 * removed the eb from the radix tree, so we could race
4811 * and have this page now attached to the new eb. So
4812 * only clear page_private if it's still connected to
4813 * this eb.
4815 if (PagePrivate(page) &&
4816 page->private == (unsigned long)eb) {
4817 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4818 BUG_ON(PageDirty(page));
4819 BUG_ON(PageWriteback(page));
4821 * We need to make sure we haven't be attached
4822 * to a new eb.
4824 ClearPagePrivate(page);
4825 set_page_private(page, 0);
4826 /* One for the page private */
4827 put_page(page);
4830 if (mapped)
4831 spin_unlock(&page->mapping->private_lock);
4833 /* One for when we allocated the page */
4834 put_page(page);
4839 * Helper for releasing the extent buffer.
4841 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4843 btrfs_release_extent_buffer_pages(eb);
4844 __free_extent_buffer(eb);
4847 static struct extent_buffer *
4848 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4849 unsigned long len)
4851 struct extent_buffer *eb = NULL;
4853 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4854 eb->start = start;
4855 eb->len = len;
4856 eb->fs_info = fs_info;
4857 eb->bflags = 0;
4858 rwlock_init(&eb->lock);
4859 atomic_set(&eb->blocking_readers, 0);
4860 eb->blocking_writers = 0;
4861 eb->lock_nested = false;
4862 init_waitqueue_head(&eb->write_lock_wq);
4863 init_waitqueue_head(&eb->read_lock_wq);
4865 btrfs_leak_debug_add(&eb->leak_list, &buffers);
4867 spin_lock_init(&eb->refs_lock);
4868 atomic_set(&eb->refs, 1);
4869 atomic_set(&eb->io_pages, 0);
4872 * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4874 BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4875 > MAX_INLINE_EXTENT_BUFFER_SIZE);
4876 BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4878 #ifdef CONFIG_BTRFS_DEBUG
4879 eb->spinning_writers = 0;
4880 atomic_set(&eb->spinning_readers, 0);
4881 atomic_set(&eb->read_locks, 0);
4882 eb->write_locks = 0;
4883 #endif
4885 return eb;
4888 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4890 int i;
4891 struct page *p;
4892 struct extent_buffer *new;
4893 int num_pages = num_extent_pages(src);
4895 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4896 if (new == NULL)
4897 return NULL;
4899 for (i = 0; i < num_pages; i++) {
4900 p = alloc_page(GFP_NOFS);
4901 if (!p) {
4902 btrfs_release_extent_buffer(new);
4903 return NULL;
4905 attach_extent_buffer_page(new, p);
4906 WARN_ON(PageDirty(p));
4907 SetPageUptodate(p);
4908 new->pages[i] = p;
4909 copy_page(page_address(p), page_address(src->pages[i]));
4912 set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4913 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4915 return new;
4918 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4919 u64 start, unsigned long len)
4921 struct extent_buffer *eb;
4922 int num_pages;
4923 int i;
4925 eb = __alloc_extent_buffer(fs_info, start, len);
4926 if (!eb)
4927 return NULL;
4929 num_pages = num_extent_pages(eb);
4930 for (i = 0; i < num_pages; i++) {
4931 eb->pages[i] = alloc_page(GFP_NOFS);
4932 if (!eb->pages[i])
4933 goto err;
4935 set_extent_buffer_uptodate(eb);
4936 btrfs_set_header_nritems(eb, 0);
4937 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4939 return eb;
4940 err:
4941 for (; i > 0; i--)
4942 __free_page(eb->pages[i - 1]);
4943 __free_extent_buffer(eb);
4944 return NULL;
4947 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4948 u64 start)
4950 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4953 static void check_buffer_tree_ref(struct extent_buffer *eb)
4955 int refs;
4956 /* the ref bit is tricky. We have to make sure it is set
4957 * if we have the buffer dirty. Otherwise the
4958 * code to free a buffer can end up dropping a dirty
4959 * page
4961 * Once the ref bit is set, it won't go away while the
4962 * buffer is dirty or in writeback, and it also won't
4963 * go away while we have the reference count on the
4964 * eb bumped.
4966 * We can't just set the ref bit without bumping the
4967 * ref on the eb because free_extent_buffer might
4968 * see the ref bit and try to clear it. If this happens
4969 * free_extent_buffer might end up dropping our original
4970 * ref by mistake and freeing the page before we are able
4971 * to add one more ref.
4973 * So bump the ref count first, then set the bit. If someone
4974 * beat us to it, drop the ref we added.
4976 refs = atomic_read(&eb->refs);
4977 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4978 return;
4980 spin_lock(&eb->refs_lock);
4981 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4982 atomic_inc(&eb->refs);
4983 spin_unlock(&eb->refs_lock);
4986 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4987 struct page *accessed)
4989 int num_pages, i;
4991 check_buffer_tree_ref(eb);
4993 num_pages = num_extent_pages(eb);
4994 for (i = 0; i < num_pages; i++) {
4995 struct page *p = eb->pages[i];
4997 if (p != accessed)
4998 mark_page_accessed(p);
5002 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5003 u64 start)
5005 struct extent_buffer *eb;
5007 rcu_read_lock();
5008 eb = radix_tree_lookup(&fs_info->buffer_radix,
5009 start >> PAGE_SHIFT);
5010 if (eb && atomic_inc_not_zero(&eb->refs)) {
5011 rcu_read_unlock();
5013 * Lock our eb's refs_lock to avoid races with
5014 * free_extent_buffer. When we get our eb it might be flagged
5015 * with EXTENT_BUFFER_STALE and another task running
5016 * free_extent_buffer might have seen that flag set,
5017 * eb->refs == 2, that the buffer isn't under IO (dirty and
5018 * writeback flags not set) and it's still in the tree (flag
5019 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5020 * of decrementing the extent buffer's reference count twice.
5021 * So here we could race and increment the eb's reference count,
5022 * clear its stale flag, mark it as dirty and drop our reference
5023 * before the other task finishes executing free_extent_buffer,
5024 * which would later result in an attempt to free an extent
5025 * buffer that is dirty.
5027 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5028 spin_lock(&eb->refs_lock);
5029 spin_unlock(&eb->refs_lock);
5031 mark_extent_buffer_accessed(eb, NULL);
5032 return eb;
5034 rcu_read_unlock();
5036 return NULL;
5039 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5040 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5041 u64 start)
5043 struct extent_buffer *eb, *exists = NULL;
5044 int ret;
5046 eb = find_extent_buffer(fs_info, start);
5047 if (eb)
5048 return eb;
5049 eb = alloc_dummy_extent_buffer(fs_info, start);
5050 if (!eb)
5051 return NULL;
5052 eb->fs_info = fs_info;
5053 again:
5054 ret = radix_tree_preload(GFP_NOFS);
5055 if (ret)
5056 goto free_eb;
5057 spin_lock(&fs_info->buffer_lock);
5058 ret = radix_tree_insert(&fs_info->buffer_radix,
5059 start >> PAGE_SHIFT, eb);
5060 spin_unlock(&fs_info->buffer_lock);
5061 radix_tree_preload_end();
5062 if (ret == -EEXIST) {
5063 exists = find_extent_buffer(fs_info, start);
5064 if (exists)
5065 goto free_eb;
5066 else
5067 goto again;
5069 check_buffer_tree_ref(eb);
5070 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5072 return eb;
5073 free_eb:
5074 btrfs_release_extent_buffer(eb);
5075 return exists;
5077 #endif
5079 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5080 u64 start)
5082 unsigned long len = fs_info->nodesize;
5083 int num_pages;
5084 int i;
5085 unsigned long index = start >> PAGE_SHIFT;
5086 struct extent_buffer *eb;
5087 struct extent_buffer *exists = NULL;
5088 struct page *p;
5089 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5090 int uptodate = 1;
5091 int ret;
5093 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5094 btrfs_err(fs_info, "bad tree block start %llu", start);
5095 return ERR_PTR(-EINVAL);
5098 eb = find_extent_buffer(fs_info, start);
5099 if (eb)
5100 return eb;
5102 eb = __alloc_extent_buffer(fs_info, start, len);
5103 if (!eb)
5104 return ERR_PTR(-ENOMEM);
5106 num_pages = num_extent_pages(eb);
5107 for (i = 0; i < num_pages; i++, index++) {
5108 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5109 if (!p) {
5110 exists = ERR_PTR(-ENOMEM);
5111 goto free_eb;
5114 spin_lock(&mapping->private_lock);
5115 if (PagePrivate(p)) {
5117 * We could have already allocated an eb for this page
5118 * and attached one so lets see if we can get a ref on
5119 * the existing eb, and if we can we know it's good and
5120 * we can just return that one, else we know we can just
5121 * overwrite page->private.
5123 exists = (struct extent_buffer *)p->private;
5124 if (atomic_inc_not_zero(&exists->refs)) {
5125 spin_unlock(&mapping->private_lock);
5126 unlock_page(p);
5127 put_page(p);
5128 mark_extent_buffer_accessed(exists, p);
5129 goto free_eb;
5131 exists = NULL;
5134 * Do this so attach doesn't complain and we need to
5135 * drop the ref the old guy had.
5137 ClearPagePrivate(p);
5138 WARN_ON(PageDirty(p));
5139 put_page(p);
5141 attach_extent_buffer_page(eb, p);
5142 spin_unlock(&mapping->private_lock);
5143 WARN_ON(PageDirty(p));
5144 eb->pages[i] = p;
5145 if (!PageUptodate(p))
5146 uptodate = 0;
5149 * We can't unlock the pages just yet since the extent buffer
5150 * hasn't been properly inserted in the radix tree, this
5151 * opens a race with btree_releasepage which can free a page
5152 * while we are still filling in all pages for the buffer and
5153 * we could crash.
5156 if (uptodate)
5157 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5158 again:
5159 ret = radix_tree_preload(GFP_NOFS);
5160 if (ret) {
5161 exists = ERR_PTR(ret);
5162 goto free_eb;
5165 spin_lock(&fs_info->buffer_lock);
5166 ret = radix_tree_insert(&fs_info->buffer_radix,
5167 start >> PAGE_SHIFT, eb);
5168 spin_unlock(&fs_info->buffer_lock);
5169 radix_tree_preload_end();
5170 if (ret == -EEXIST) {
5171 exists = find_extent_buffer(fs_info, start);
5172 if (exists)
5173 goto free_eb;
5174 else
5175 goto again;
5177 /* add one reference for the tree */
5178 check_buffer_tree_ref(eb);
5179 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5182 * Now it's safe to unlock the pages because any calls to
5183 * btree_releasepage will correctly detect that a page belongs to a
5184 * live buffer and won't free them prematurely.
5186 for (i = 0; i < num_pages; i++)
5187 unlock_page(eb->pages[i]);
5188 return eb;
5190 free_eb:
5191 WARN_ON(!atomic_dec_and_test(&eb->refs));
5192 for (i = 0; i < num_pages; i++) {
5193 if (eb->pages[i])
5194 unlock_page(eb->pages[i]);
5197 btrfs_release_extent_buffer(eb);
5198 return exists;
5201 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5203 struct extent_buffer *eb =
5204 container_of(head, struct extent_buffer, rcu_head);
5206 __free_extent_buffer(eb);
5209 static int release_extent_buffer(struct extent_buffer *eb)
5211 lockdep_assert_held(&eb->refs_lock);
5213 WARN_ON(atomic_read(&eb->refs) == 0);
5214 if (atomic_dec_and_test(&eb->refs)) {
5215 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5216 struct btrfs_fs_info *fs_info = eb->fs_info;
5218 spin_unlock(&eb->refs_lock);
5220 spin_lock(&fs_info->buffer_lock);
5221 radix_tree_delete(&fs_info->buffer_radix,
5222 eb->start >> PAGE_SHIFT);
5223 spin_unlock(&fs_info->buffer_lock);
5224 } else {
5225 spin_unlock(&eb->refs_lock);
5228 /* Should be safe to release our pages at this point */
5229 btrfs_release_extent_buffer_pages(eb);
5230 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5231 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5232 __free_extent_buffer(eb);
5233 return 1;
5235 #endif
5236 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5237 return 1;
5239 spin_unlock(&eb->refs_lock);
5241 return 0;
5244 void free_extent_buffer(struct extent_buffer *eb)
5246 int refs;
5247 int old;
5248 if (!eb)
5249 return;
5251 while (1) {
5252 refs = atomic_read(&eb->refs);
5253 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5254 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5255 refs == 1))
5256 break;
5257 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5258 if (old == refs)
5259 return;
5262 spin_lock(&eb->refs_lock);
5263 if (atomic_read(&eb->refs) == 2 &&
5264 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5265 !extent_buffer_under_io(eb) &&
5266 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5267 atomic_dec(&eb->refs);
5270 * I know this is terrible, but it's temporary until we stop tracking
5271 * the uptodate bits and such for the extent buffers.
5273 release_extent_buffer(eb);
5276 void free_extent_buffer_stale(struct extent_buffer *eb)
5278 if (!eb)
5279 return;
5281 spin_lock(&eb->refs_lock);
5282 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5284 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5285 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5286 atomic_dec(&eb->refs);
5287 release_extent_buffer(eb);
5290 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5292 int i;
5293 int num_pages;
5294 struct page *page;
5296 num_pages = num_extent_pages(eb);
5298 for (i = 0; i < num_pages; i++) {
5299 page = eb->pages[i];
5300 if (!PageDirty(page))
5301 continue;
5303 lock_page(page);
5304 WARN_ON(!PagePrivate(page));
5306 clear_page_dirty_for_io(page);
5307 xa_lock_irq(&page->mapping->i_pages);
5308 if (!PageDirty(page))
5309 __xa_clear_mark(&page->mapping->i_pages,
5310 page_index(page), PAGECACHE_TAG_DIRTY);
5311 xa_unlock_irq(&page->mapping->i_pages);
5312 ClearPageError(page);
5313 unlock_page(page);
5315 WARN_ON(atomic_read(&eb->refs) == 0);
5318 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5320 int i;
5321 int num_pages;
5322 bool was_dirty;
5324 check_buffer_tree_ref(eb);
5326 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5328 num_pages = num_extent_pages(eb);
5329 WARN_ON(atomic_read(&eb->refs) == 0);
5330 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5332 if (!was_dirty)
5333 for (i = 0; i < num_pages; i++)
5334 set_page_dirty(eb->pages[i]);
5336 #ifdef CONFIG_BTRFS_DEBUG
5337 for (i = 0; i < num_pages; i++)
5338 ASSERT(PageDirty(eb->pages[i]));
5339 #endif
5341 return was_dirty;
5344 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5346 int i;
5347 struct page *page;
5348 int num_pages;
5350 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5351 num_pages = num_extent_pages(eb);
5352 for (i = 0; i < num_pages; i++) {
5353 page = eb->pages[i];
5354 if (page)
5355 ClearPageUptodate(page);
5359 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5361 int i;
5362 struct page *page;
5363 int num_pages;
5365 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5366 num_pages = num_extent_pages(eb);
5367 for (i = 0; i < num_pages; i++) {
5368 page = eb->pages[i];
5369 SetPageUptodate(page);
5373 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5375 int i;
5376 struct page *page;
5377 int err;
5378 int ret = 0;
5379 int locked_pages = 0;
5380 int all_uptodate = 1;
5381 int num_pages;
5382 unsigned long num_reads = 0;
5383 struct bio *bio = NULL;
5384 unsigned long bio_flags = 0;
5385 struct extent_io_tree *tree = &BTRFS_I(eb->fs_info->btree_inode)->io_tree;
5387 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5388 return 0;
5390 num_pages = num_extent_pages(eb);
5391 for (i = 0; i < num_pages; i++) {
5392 page = eb->pages[i];
5393 if (wait == WAIT_NONE) {
5394 if (!trylock_page(page))
5395 goto unlock_exit;
5396 } else {
5397 lock_page(page);
5399 locked_pages++;
5402 * We need to firstly lock all pages to make sure that
5403 * the uptodate bit of our pages won't be affected by
5404 * clear_extent_buffer_uptodate().
5406 for (i = 0; i < num_pages; i++) {
5407 page = eb->pages[i];
5408 if (!PageUptodate(page)) {
5409 num_reads++;
5410 all_uptodate = 0;
5414 if (all_uptodate) {
5415 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5416 goto unlock_exit;
5419 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5420 eb->read_mirror = 0;
5421 atomic_set(&eb->io_pages, num_reads);
5422 for (i = 0; i < num_pages; i++) {
5423 page = eb->pages[i];
5425 if (!PageUptodate(page)) {
5426 if (ret) {
5427 atomic_dec(&eb->io_pages);
5428 unlock_page(page);
5429 continue;
5432 ClearPageError(page);
5433 err = __extent_read_full_page(tree, page,
5434 btree_get_extent, &bio,
5435 mirror_num, &bio_flags,
5436 REQ_META);
5437 if (err) {
5438 ret = err;
5440 * We use &bio in above __extent_read_full_page,
5441 * so we ensure that if it returns error, the
5442 * current page fails to add itself to bio and
5443 * it's been unlocked.
5445 * We must dec io_pages by ourselves.
5447 atomic_dec(&eb->io_pages);
5449 } else {
5450 unlock_page(page);
5454 if (bio) {
5455 err = submit_one_bio(bio, mirror_num, bio_flags);
5456 if (err)
5457 return err;
5460 if (ret || wait != WAIT_COMPLETE)
5461 return ret;
5463 for (i = 0; i < num_pages; i++) {
5464 page = eb->pages[i];
5465 wait_on_page_locked(page);
5466 if (!PageUptodate(page))
5467 ret = -EIO;
5470 return ret;
5472 unlock_exit:
5473 while (locked_pages > 0) {
5474 locked_pages--;
5475 page = eb->pages[locked_pages];
5476 unlock_page(page);
5478 return ret;
5481 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5482 unsigned long start, unsigned long len)
5484 size_t cur;
5485 size_t offset;
5486 struct page *page;
5487 char *kaddr;
5488 char *dst = (char *)dstv;
5489 size_t start_offset = offset_in_page(eb->start);
5490 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5492 if (start + len > eb->len) {
5493 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5494 eb->start, eb->len, start, len);
5495 memset(dst, 0, len);
5496 return;
5499 offset = offset_in_page(start_offset + start);
5501 while (len > 0) {
5502 page = eb->pages[i];
5504 cur = min(len, (PAGE_SIZE - offset));
5505 kaddr = page_address(page);
5506 memcpy(dst, kaddr + offset, cur);
5508 dst += cur;
5509 len -= cur;
5510 offset = 0;
5511 i++;
5515 int read_extent_buffer_to_user(const struct extent_buffer *eb,
5516 void __user *dstv,
5517 unsigned long start, unsigned long len)
5519 size_t cur;
5520 size_t offset;
5521 struct page *page;
5522 char *kaddr;
5523 char __user *dst = (char __user *)dstv;
5524 size_t start_offset = offset_in_page(eb->start);
5525 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5526 int ret = 0;
5528 WARN_ON(start > eb->len);
5529 WARN_ON(start + len > eb->start + eb->len);
5531 offset = offset_in_page(start_offset + start);
5533 while (len > 0) {
5534 page = eb->pages[i];
5536 cur = min(len, (PAGE_SIZE - offset));
5537 kaddr = page_address(page);
5538 if (copy_to_user(dst, kaddr + offset, cur)) {
5539 ret = -EFAULT;
5540 break;
5543 dst += cur;
5544 len -= cur;
5545 offset = 0;
5546 i++;
5549 return ret;
5553 * return 0 if the item is found within a page.
5554 * return 1 if the item spans two pages.
5555 * return -EINVAL otherwise.
5557 int map_private_extent_buffer(const struct extent_buffer *eb,
5558 unsigned long start, unsigned long min_len,
5559 char **map, unsigned long *map_start,
5560 unsigned long *map_len)
5562 size_t offset;
5563 char *kaddr;
5564 struct page *p;
5565 size_t start_offset = offset_in_page(eb->start);
5566 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5567 unsigned long end_i = (start_offset + start + min_len - 1) >>
5568 PAGE_SHIFT;
5570 if (start + min_len > eb->len) {
5571 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5572 eb->start, eb->len, start, min_len);
5573 return -EINVAL;
5576 if (i != end_i)
5577 return 1;
5579 if (i == 0) {
5580 offset = start_offset;
5581 *map_start = 0;
5582 } else {
5583 offset = 0;
5584 *map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5587 p = eb->pages[i];
5588 kaddr = page_address(p);
5589 *map = kaddr + offset;
5590 *map_len = PAGE_SIZE - offset;
5591 return 0;
5594 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5595 unsigned long start, unsigned long len)
5597 size_t cur;
5598 size_t offset;
5599 struct page *page;
5600 char *kaddr;
5601 char *ptr = (char *)ptrv;
5602 size_t start_offset = offset_in_page(eb->start);
5603 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5604 int ret = 0;
5606 WARN_ON(start > eb->len);
5607 WARN_ON(start + len > eb->start + eb->len);
5609 offset = offset_in_page(start_offset + start);
5611 while (len > 0) {
5612 page = eb->pages[i];
5614 cur = min(len, (PAGE_SIZE - offset));
5616 kaddr = page_address(page);
5617 ret = memcmp(ptr, kaddr + offset, cur);
5618 if (ret)
5619 break;
5621 ptr += cur;
5622 len -= cur;
5623 offset = 0;
5624 i++;
5626 return ret;
5629 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5630 const void *srcv)
5632 char *kaddr;
5634 WARN_ON(!PageUptodate(eb->pages[0]));
5635 kaddr = page_address(eb->pages[0]);
5636 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5637 BTRFS_FSID_SIZE);
5640 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5642 char *kaddr;
5644 WARN_ON(!PageUptodate(eb->pages[0]));
5645 kaddr = page_address(eb->pages[0]);
5646 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5647 BTRFS_FSID_SIZE);
5650 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5651 unsigned long start, unsigned long len)
5653 size_t cur;
5654 size_t offset;
5655 struct page *page;
5656 char *kaddr;
5657 char *src = (char *)srcv;
5658 size_t start_offset = offset_in_page(eb->start);
5659 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5661 WARN_ON(start > eb->len);
5662 WARN_ON(start + len > eb->start + eb->len);
5664 offset = offset_in_page(start_offset + start);
5666 while (len > 0) {
5667 page = eb->pages[i];
5668 WARN_ON(!PageUptodate(page));
5670 cur = min(len, PAGE_SIZE - offset);
5671 kaddr = page_address(page);
5672 memcpy(kaddr + offset, src, cur);
5674 src += cur;
5675 len -= cur;
5676 offset = 0;
5677 i++;
5681 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5682 unsigned long len)
5684 size_t cur;
5685 size_t offset;
5686 struct page *page;
5687 char *kaddr;
5688 size_t start_offset = offset_in_page(eb->start);
5689 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5691 WARN_ON(start > eb->len);
5692 WARN_ON(start + len > eb->start + eb->len);
5694 offset = offset_in_page(start_offset + start);
5696 while (len > 0) {
5697 page = eb->pages[i];
5698 WARN_ON(!PageUptodate(page));
5700 cur = min(len, PAGE_SIZE - offset);
5701 kaddr = page_address(page);
5702 memset(kaddr + offset, 0, cur);
5704 len -= cur;
5705 offset = 0;
5706 i++;
5710 void copy_extent_buffer_full(struct extent_buffer *dst,
5711 struct extent_buffer *src)
5713 int i;
5714 int num_pages;
5716 ASSERT(dst->len == src->len);
5718 num_pages = num_extent_pages(dst);
5719 for (i = 0; i < num_pages; i++)
5720 copy_page(page_address(dst->pages[i]),
5721 page_address(src->pages[i]));
5724 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5725 unsigned long dst_offset, unsigned long src_offset,
5726 unsigned long len)
5728 u64 dst_len = dst->len;
5729 size_t cur;
5730 size_t offset;
5731 struct page *page;
5732 char *kaddr;
5733 size_t start_offset = offset_in_page(dst->start);
5734 unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5736 WARN_ON(src->len != dst_len);
5738 offset = offset_in_page(start_offset + dst_offset);
5740 while (len > 0) {
5741 page = dst->pages[i];
5742 WARN_ON(!PageUptodate(page));
5744 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5746 kaddr = page_address(page);
5747 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5749 src_offset += cur;
5750 len -= cur;
5751 offset = 0;
5752 i++;
5757 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5758 * given bit number
5759 * @eb: the extent buffer
5760 * @start: offset of the bitmap item in the extent buffer
5761 * @nr: bit number
5762 * @page_index: return index of the page in the extent buffer that contains the
5763 * given bit number
5764 * @page_offset: return offset into the page given by page_index
5766 * This helper hides the ugliness of finding the byte in an extent buffer which
5767 * contains a given bit.
5769 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5770 unsigned long start, unsigned long nr,
5771 unsigned long *page_index,
5772 size_t *page_offset)
5774 size_t start_offset = offset_in_page(eb->start);
5775 size_t byte_offset = BIT_BYTE(nr);
5776 size_t offset;
5779 * The byte we want is the offset of the extent buffer + the offset of
5780 * the bitmap item in the extent buffer + the offset of the byte in the
5781 * bitmap item.
5783 offset = start_offset + start + byte_offset;
5785 *page_index = offset >> PAGE_SHIFT;
5786 *page_offset = offset_in_page(offset);
5790 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5791 * @eb: the extent buffer
5792 * @start: offset of the bitmap item in the extent buffer
5793 * @nr: bit number to test
5795 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5796 unsigned long nr)
5798 u8 *kaddr;
5799 struct page *page;
5800 unsigned long i;
5801 size_t offset;
5803 eb_bitmap_offset(eb, start, nr, &i, &offset);
5804 page = eb->pages[i];
5805 WARN_ON(!PageUptodate(page));
5806 kaddr = page_address(page);
5807 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5811 * extent_buffer_bitmap_set - set an area of a bitmap
5812 * @eb: the extent buffer
5813 * @start: offset of the bitmap item in the extent buffer
5814 * @pos: bit number of the first bit
5815 * @len: number of bits to set
5817 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5818 unsigned long pos, unsigned long len)
5820 u8 *kaddr;
5821 struct page *page;
5822 unsigned long i;
5823 size_t offset;
5824 const unsigned int size = pos + len;
5825 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5826 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5828 eb_bitmap_offset(eb, start, pos, &i, &offset);
5829 page = eb->pages[i];
5830 WARN_ON(!PageUptodate(page));
5831 kaddr = page_address(page);
5833 while (len >= bits_to_set) {
5834 kaddr[offset] |= mask_to_set;
5835 len -= bits_to_set;
5836 bits_to_set = BITS_PER_BYTE;
5837 mask_to_set = ~0;
5838 if (++offset >= PAGE_SIZE && len > 0) {
5839 offset = 0;
5840 page = eb->pages[++i];
5841 WARN_ON(!PageUptodate(page));
5842 kaddr = page_address(page);
5845 if (len) {
5846 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5847 kaddr[offset] |= mask_to_set;
5853 * extent_buffer_bitmap_clear - clear an area of a bitmap
5854 * @eb: the extent buffer
5855 * @start: offset of the bitmap item in the extent buffer
5856 * @pos: bit number of the first bit
5857 * @len: number of bits to clear
5859 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5860 unsigned long pos, unsigned long len)
5862 u8 *kaddr;
5863 struct page *page;
5864 unsigned long i;
5865 size_t offset;
5866 const unsigned int size = pos + len;
5867 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5868 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5870 eb_bitmap_offset(eb, start, pos, &i, &offset);
5871 page = eb->pages[i];
5872 WARN_ON(!PageUptodate(page));
5873 kaddr = page_address(page);
5875 while (len >= bits_to_clear) {
5876 kaddr[offset] &= ~mask_to_clear;
5877 len -= bits_to_clear;
5878 bits_to_clear = BITS_PER_BYTE;
5879 mask_to_clear = ~0;
5880 if (++offset >= PAGE_SIZE && len > 0) {
5881 offset = 0;
5882 page = eb->pages[++i];
5883 WARN_ON(!PageUptodate(page));
5884 kaddr = page_address(page);
5887 if (len) {
5888 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5889 kaddr[offset] &= ~mask_to_clear;
5893 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5895 unsigned long distance = (src > dst) ? src - dst : dst - src;
5896 return distance < len;
5899 static void copy_pages(struct page *dst_page, struct page *src_page,
5900 unsigned long dst_off, unsigned long src_off,
5901 unsigned long len)
5903 char *dst_kaddr = page_address(dst_page);
5904 char *src_kaddr;
5905 int must_memmove = 0;
5907 if (dst_page != src_page) {
5908 src_kaddr = page_address(src_page);
5909 } else {
5910 src_kaddr = dst_kaddr;
5911 if (areas_overlap(src_off, dst_off, len))
5912 must_memmove = 1;
5915 if (must_memmove)
5916 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5917 else
5918 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5921 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5922 unsigned long src_offset, unsigned long len)
5924 struct btrfs_fs_info *fs_info = dst->fs_info;
5925 size_t cur;
5926 size_t dst_off_in_page;
5927 size_t src_off_in_page;
5928 size_t start_offset = offset_in_page(dst->start);
5929 unsigned long dst_i;
5930 unsigned long src_i;
5932 if (src_offset + len > dst->len) {
5933 btrfs_err(fs_info,
5934 "memmove bogus src_offset %lu move len %lu dst len %lu",
5935 src_offset, len, dst->len);
5936 BUG();
5938 if (dst_offset + len > dst->len) {
5939 btrfs_err(fs_info,
5940 "memmove bogus dst_offset %lu move len %lu dst len %lu",
5941 dst_offset, len, dst->len);
5942 BUG();
5945 while (len > 0) {
5946 dst_off_in_page = offset_in_page(start_offset + dst_offset);
5947 src_off_in_page = offset_in_page(start_offset + src_offset);
5949 dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
5950 src_i = (start_offset + src_offset) >> PAGE_SHIFT;
5952 cur = min(len, (unsigned long)(PAGE_SIZE -
5953 src_off_in_page));
5954 cur = min_t(unsigned long, cur,
5955 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5957 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5958 dst_off_in_page, src_off_in_page, cur);
5960 src_offset += cur;
5961 dst_offset += cur;
5962 len -= cur;
5966 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5967 unsigned long src_offset, unsigned long len)
5969 struct btrfs_fs_info *fs_info = dst->fs_info;
5970 size_t cur;
5971 size_t dst_off_in_page;
5972 size_t src_off_in_page;
5973 unsigned long dst_end = dst_offset + len - 1;
5974 unsigned long src_end = src_offset + len - 1;
5975 size_t start_offset = offset_in_page(dst->start);
5976 unsigned long dst_i;
5977 unsigned long src_i;
5979 if (src_offset + len > dst->len) {
5980 btrfs_err(fs_info,
5981 "memmove bogus src_offset %lu move len %lu len %lu",
5982 src_offset, len, dst->len);
5983 BUG();
5985 if (dst_offset + len > dst->len) {
5986 btrfs_err(fs_info,
5987 "memmove bogus dst_offset %lu move len %lu len %lu",
5988 dst_offset, len, dst->len);
5989 BUG();
5991 if (dst_offset < src_offset) {
5992 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5993 return;
5995 while (len > 0) {
5996 dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
5997 src_i = (start_offset + src_end) >> PAGE_SHIFT;
5999 dst_off_in_page = offset_in_page(start_offset + dst_end);
6000 src_off_in_page = offset_in_page(start_offset + src_end);
6002 cur = min_t(unsigned long, len, src_off_in_page + 1);
6003 cur = min(cur, dst_off_in_page + 1);
6004 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6005 dst_off_in_page - cur + 1,
6006 src_off_in_page - cur + 1, cur);
6008 dst_end -= cur;
6009 src_end -= cur;
6010 len -= cur;
6014 int try_release_extent_buffer(struct page *page)
6016 struct extent_buffer *eb;
6019 * We need to make sure nobody is attaching this page to an eb right
6020 * now.
6022 spin_lock(&page->mapping->private_lock);
6023 if (!PagePrivate(page)) {
6024 spin_unlock(&page->mapping->private_lock);
6025 return 1;
6028 eb = (struct extent_buffer *)page->private;
6029 BUG_ON(!eb);
6032 * This is a little awful but should be ok, we need to make sure that
6033 * the eb doesn't disappear out from under us while we're looking at
6034 * this page.
6036 spin_lock(&eb->refs_lock);
6037 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6038 spin_unlock(&eb->refs_lock);
6039 spin_unlock(&page->mapping->private_lock);
6040 return 0;
6042 spin_unlock(&page->mapping->private_lock);
6045 * If tree ref isn't set then we know the ref on this eb is a real ref,
6046 * so just return, this page will likely be freed soon anyway.
6048 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6049 spin_unlock(&eb->refs_lock);
6050 return 0;
6053 return release_extent_buffer(eb);