]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - fs/btrfs/extent_io.c
btrfs: separate out the extent leak code
[mirror_ubuntu-hirsute-kernel.git] / fs / btrfs / extent_io.c
1 // SPDX-License-Identifier: GPL-2.0
2
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"
26
27 static struct kmem_cache *extent_state_cache;
28 static struct kmem_cache *extent_buffer_cache;
29 static struct bio_set btrfs_bioset;
30
31 static inline bool extent_state_in_tree(const struct extent_state *state)
32 {
33 return !RB_EMPTY_NODE(&state->rb_node);
34 }
35
36 #ifdef CONFIG_BTRFS_DEBUG
37 static LIST_HEAD(buffers);
38 static LIST_HEAD(states);
39
40 static DEFINE_SPINLOCK(leak_lock);
41
42 static inline
43 void btrfs_leak_debug_add(struct list_head *new, struct list_head *head)
44 {
45 unsigned long flags;
46
47 spin_lock_irqsave(&leak_lock, flags);
48 list_add(new, head);
49 spin_unlock_irqrestore(&leak_lock, flags);
50 }
51
52 static inline
53 void btrfs_leak_debug_del(struct list_head *entry)
54 {
55 unsigned long flags;
56
57 spin_lock_irqsave(&leak_lock, flags);
58 list_del(entry);
59 spin_unlock_irqrestore(&leak_lock, flags);
60 }
61
62 static inline void btrfs_extent_buffer_leak_debug_check(void)
63 {
64 struct extent_buffer *eb;
65
66 while (!list_empty(&buffers)) {
67 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
68 pr_err("BTRFS: buffer leak start %llu len %lu refs %d bflags %lu\n",
69 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags);
70 list_del(&eb->leak_list);
71 kmem_cache_free(extent_buffer_cache, eb);
72 }
73 }
74
75 static inline void btrfs_extent_state_leak_debug_check(void)
76 {
77 struct extent_state *state;
78
79 while (!list_empty(&states)) {
80 state = list_entry(states.next, struct extent_state, leak_list);
81 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
82 state->start, state->end, state->state,
83 extent_state_in_tree(state),
84 refcount_read(&state->refs));
85 list_del(&state->leak_list);
86 kmem_cache_free(extent_state_cache, state);
87 }
88 }
89
90 #define btrfs_debug_check_extent_io_range(tree, start, end) \
91 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
92 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
93 struct extent_io_tree *tree, u64 start, u64 end)
94 {
95 struct inode *inode = tree->private_data;
96 u64 isize;
97
98 if (!inode || !is_data_inode(inode))
99 return;
100
101 isize = i_size_read(inode);
102 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
103 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
104 "%s: ino %llu isize %llu odd range [%llu,%llu]",
105 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
106 }
107 }
108 #else
109 #define btrfs_leak_debug_add(new, head) do {} while (0)
110 #define btrfs_leak_debug_del(entry) do {} while (0)
111 #define btrfs_extent_buffer_leak_debug_check() do {} while (0)
112 #define btrfs_extent_state_leak_debug_check() do {} while (0)
113 #define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
114 #endif
115
116 struct tree_entry {
117 u64 start;
118 u64 end;
119 struct rb_node rb_node;
120 };
121
122 struct extent_page_data {
123 struct bio *bio;
124 struct extent_io_tree *tree;
125 /* tells writepage not to lock the state bits for this range
126 * it still does the unlocking
127 */
128 unsigned int extent_locked:1;
129
130 /* tells the submit_bio code to use REQ_SYNC */
131 unsigned int sync_io:1;
132 };
133
134 static int add_extent_changeset(struct extent_state *state, unsigned bits,
135 struct extent_changeset *changeset,
136 int set)
137 {
138 int ret;
139
140 if (!changeset)
141 return 0;
142 if (set && (state->state & bits) == bits)
143 return 0;
144 if (!set && (state->state & bits) == 0)
145 return 0;
146 changeset->bytes_changed += state->end - state->start + 1;
147 ret = ulist_add(&changeset->range_changed, state->start, state->end,
148 GFP_ATOMIC);
149 return ret;
150 }
151
152 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
153 unsigned long bio_flags)
154 {
155 blk_status_t ret = 0;
156 struct extent_io_tree *tree = bio->bi_private;
157
158 bio->bi_private = NULL;
159
160 if (tree->ops)
161 ret = tree->ops->submit_bio_hook(tree->private_data, bio,
162 mirror_num, bio_flags);
163 else
164 btrfsic_submit_bio(bio);
165
166 return blk_status_to_errno(ret);
167 }
168
169 /* Cleanup unsubmitted bios */
170 static void end_write_bio(struct extent_page_data *epd, int ret)
171 {
172 if (epd->bio) {
173 epd->bio->bi_status = errno_to_blk_status(ret);
174 bio_endio(epd->bio);
175 epd->bio = NULL;
176 }
177 }
178
179 /*
180 * Submit bio from extent page data via submit_one_bio
181 *
182 * Return 0 if everything is OK.
183 * Return <0 for error.
184 */
185 static int __must_check flush_write_bio(struct extent_page_data *epd)
186 {
187 int ret = 0;
188
189 if (epd->bio) {
190 ret = submit_one_bio(epd->bio, 0, 0);
191 /*
192 * Clean up of epd->bio is handled by its endio function.
193 * And endio is either triggered by successful bio execution
194 * or the error handler of submit bio hook.
195 * So at this point, no matter what happened, we don't need
196 * to clean up epd->bio.
197 */
198 epd->bio = NULL;
199 }
200 return ret;
201 }
202
203 int __init extent_io_init(void)
204 {
205 extent_state_cache = kmem_cache_create("btrfs_extent_state",
206 sizeof(struct extent_state), 0,
207 SLAB_MEM_SPREAD, NULL);
208 if (!extent_state_cache)
209 return -ENOMEM;
210
211 extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
212 sizeof(struct extent_buffer), 0,
213 SLAB_MEM_SPREAD, NULL);
214 if (!extent_buffer_cache)
215 goto free_state_cache;
216
217 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
218 offsetof(struct btrfs_io_bio, bio),
219 BIOSET_NEED_BVECS))
220 goto free_buffer_cache;
221
222 if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
223 goto free_bioset;
224
225 return 0;
226
227 free_bioset:
228 bioset_exit(&btrfs_bioset);
229
230 free_buffer_cache:
231 kmem_cache_destroy(extent_buffer_cache);
232 extent_buffer_cache = NULL;
233
234 free_state_cache:
235 kmem_cache_destroy(extent_state_cache);
236 extent_state_cache = NULL;
237 return -ENOMEM;
238 }
239
240 void __cold extent_io_exit(void)
241 {
242 btrfs_extent_buffer_leak_debug_check();
243 btrfs_extent_state_leak_debug_check();
244
245 /*
246 * Make sure all delayed rcu free are flushed before we
247 * destroy caches.
248 */
249 rcu_barrier();
250 kmem_cache_destroy(extent_state_cache);
251 kmem_cache_destroy(extent_buffer_cache);
252 bioset_exit(&btrfs_bioset);
253 }
254
255 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
256 struct extent_io_tree *tree, unsigned int owner,
257 void *private_data)
258 {
259 tree->fs_info = fs_info;
260 tree->state = RB_ROOT;
261 tree->ops = NULL;
262 tree->dirty_bytes = 0;
263 spin_lock_init(&tree->lock);
264 tree->private_data = private_data;
265 tree->owner = owner;
266 }
267
268 void extent_io_tree_release(struct extent_io_tree *tree)
269 {
270 spin_lock(&tree->lock);
271 /*
272 * Do a single barrier for the waitqueue_active check here, the state
273 * of the waitqueue should not change once extent_io_tree_release is
274 * called.
275 */
276 smp_mb();
277 while (!RB_EMPTY_ROOT(&tree->state)) {
278 struct rb_node *node;
279 struct extent_state *state;
280
281 node = rb_first(&tree->state);
282 state = rb_entry(node, struct extent_state, rb_node);
283 rb_erase(&state->rb_node, &tree->state);
284 RB_CLEAR_NODE(&state->rb_node);
285 /*
286 * btree io trees aren't supposed to have tasks waiting for
287 * changes in the flags of extent states ever.
288 */
289 ASSERT(!waitqueue_active(&state->wq));
290 free_extent_state(state);
291
292 cond_resched_lock(&tree->lock);
293 }
294 spin_unlock(&tree->lock);
295 }
296
297 static struct extent_state *alloc_extent_state(gfp_t mask)
298 {
299 struct extent_state *state;
300
301 /*
302 * The given mask might be not appropriate for the slab allocator,
303 * drop the unsupported bits
304 */
305 mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
306 state = kmem_cache_alloc(extent_state_cache, mask);
307 if (!state)
308 return state;
309 state->state = 0;
310 state->failrec = NULL;
311 RB_CLEAR_NODE(&state->rb_node);
312 btrfs_leak_debug_add(&state->leak_list, &states);
313 refcount_set(&state->refs, 1);
314 init_waitqueue_head(&state->wq);
315 trace_alloc_extent_state(state, mask, _RET_IP_);
316 return state;
317 }
318
319 void free_extent_state(struct extent_state *state)
320 {
321 if (!state)
322 return;
323 if (refcount_dec_and_test(&state->refs)) {
324 WARN_ON(extent_state_in_tree(state));
325 btrfs_leak_debug_del(&state->leak_list);
326 trace_free_extent_state(state, _RET_IP_);
327 kmem_cache_free(extent_state_cache, state);
328 }
329 }
330
331 static struct rb_node *tree_insert(struct rb_root *root,
332 struct rb_node *search_start,
333 u64 offset,
334 struct rb_node *node,
335 struct rb_node ***p_in,
336 struct rb_node **parent_in)
337 {
338 struct rb_node **p;
339 struct rb_node *parent = NULL;
340 struct tree_entry *entry;
341
342 if (p_in && parent_in) {
343 p = *p_in;
344 parent = *parent_in;
345 goto do_insert;
346 }
347
348 p = search_start ? &search_start : &root->rb_node;
349 while (*p) {
350 parent = *p;
351 entry = rb_entry(parent, struct tree_entry, rb_node);
352
353 if (offset < entry->start)
354 p = &(*p)->rb_left;
355 else if (offset > entry->end)
356 p = &(*p)->rb_right;
357 else
358 return parent;
359 }
360
361 do_insert:
362 rb_link_node(node, parent, p);
363 rb_insert_color(node, root);
364 return NULL;
365 }
366
367 /**
368 * __etree_search - searche @tree for an entry that contains @offset. Such
369 * entry would have entry->start <= offset && entry->end >= offset.
370 *
371 * @tree - the tree to search
372 * @offset - offset that should fall within an entry in @tree
373 * @next_ret - pointer to the first entry whose range ends after @offset
374 * @prev - pointer to the first entry whose range begins before @offset
375 * @p_ret - pointer where new node should be anchored (used when inserting an
376 * entry in the tree)
377 * @parent_ret - points to entry which would have been the parent of the entry,
378 * containing @offset
379 *
380 * This function returns a pointer to the entry that contains @offset byte
381 * address. If no such entry exists, then NULL is returned and the other
382 * pointer arguments to the function are filled, otherwise the found entry is
383 * returned and other pointers are left untouched.
384 */
385 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
386 struct rb_node **next_ret,
387 struct rb_node **prev_ret,
388 struct rb_node ***p_ret,
389 struct rb_node **parent_ret)
390 {
391 struct rb_root *root = &tree->state;
392 struct rb_node **n = &root->rb_node;
393 struct rb_node *prev = NULL;
394 struct rb_node *orig_prev = NULL;
395 struct tree_entry *entry;
396 struct tree_entry *prev_entry = NULL;
397
398 while (*n) {
399 prev = *n;
400 entry = rb_entry(prev, struct tree_entry, rb_node);
401 prev_entry = entry;
402
403 if (offset < entry->start)
404 n = &(*n)->rb_left;
405 else if (offset > entry->end)
406 n = &(*n)->rb_right;
407 else
408 return *n;
409 }
410
411 if (p_ret)
412 *p_ret = n;
413 if (parent_ret)
414 *parent_ret = prev;
415
416 if (next_ret) {
417 orig_prev = prev;
418 while (prev && offset > prev_entry->end) {
419 prev = rb_next(prev);
420 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
421 }
422 *next_ret = prev;
423 prev = orig_prev;
424 }
425
426 if (prev_ret) {
427 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
428 while (prev && offset < prev_entry->start) {
429 prev = rb_prev(prev);
430 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
431 }
432 *prev_ret = prev;
433 }
434 return NULL;
435 }
436
437 static inline struct rb_node *
438 tree_search_for_insert(struct extent_io_tree *tree,
439 u64 offset,
440 struct rb_node ***p_ret,
441 struct rb_node **parent_ret)
442 {
443 struct rb_node *next= NULL;
444 struct rb_node *ret;
445
446 ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
447 if (!ret)
448 return next;
449 return ret;
450 }
451
452 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
453 u64 offset)
454 {
455 return tree_search_for_insert(tree, offset, NULL, NULL);
456 }
457
458 /*
459 * utility function to look for merge candidates inside a given range.
460 * Any extents with matching state are merged together into a single
461 * extent in the tree. Extents with EXTENT_IO in their state field
462 * are not merged because the end_io handlers need to be able to do
463 * operations on them without sleeping (or doing allocations/splits).
464 *
465 * This should be called with the tree lock held.
466 */
467 static void merge_state(struct extent_io_tree *tree,
468 struct extent_state *state)
469 {
470 struct extent_state *other;
471 struct rb_node *other_node;
472
473 if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
474 return;
475
476 other_node = rb_prev(&state->rb_node);
477 if (other_node) {
478 other = rb_entry(other_node, struct extent_state, rb_node);
479 if (other->end == state->start - 1 &&
480 other->state == state->state) {
481 if (tree->private_data &&
482 is_data_inode(tree->private_data))
483 btrfs_merge_delalloc_extent(tree->private_data,
484 state, other);
485 state->start = other->start;
486 rb_erase(&other->rb_node, &tree->state);
487 RB_CLEAR_NODE(&other->rb_node);
488 free_extent_state(other);
489 }
490 }
491 other_node = rb_next(&state->rb_node);
492 if (other_node) {
493 other = rb_entry(other_node, struct extent_state, rb_node);
494 if (other->start == state->end + 1 &&
495 other->state == state->state) {
496 if (tree->private_data &&
497 is_data_inode(tree->private_data))
498 btrfs_merge_delalloc_extent(tree->private_data,
499 state, other);
500 state->end = other->end;
501 rb_erase(&other->rb_node, &tree->state);
502 RB_CLEAR_NODE(&other->rb_node);
503 free_extent_state(other);
504 }
505 }
506 }
507
508 static void set_state_bits(struct extent_io_tree *tree,
509 struct extent_state *state, unsigned *bits,
510 struct extent_changeset *changeset);
511
512 /*
513 * insert an extent_state struct into the tree. 'bits' are set on the
514 * struct before it is inserted.
515 *
516 * This may return -EEXIST if the extent is already there, in which case the
517 * state struct is freed.
518 *
519 * The tree lock is not taken internally. This is a utility function and
520 * probably isn't what you want to call (see set/clear_extent_bit).
521 */
522 static int insert_state(struct extent_io_tree *tree,
523 struct extent_state *state, u64 start, u64 end,
524 struct rb_node ***p,
525 struct rb_node **parent,
526 unsigned *bits, struct extent_changeset *changeset)
527 {
528 struct rb_node *node;
529
530 if (end < start) {
531 btrfs_err(tree->fs_info,
532 "insert state: end < start %llu %llu", end, start);
533 WARN_ON(1);
534 }
535 state->start = start;
536 state->end = end;
537
538 set_state_bits(tree, state, bits, changeset);
539
540 node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
541 if (node) {
542 struct extent_state *found;
543 found = rb_entry(node, struct extent_state, rb_node);
544 btrfs_err(tree->fs_info,
545 "found node %llu %llu on insert of %llu %llu",
546 found->start, found->end, start, end);
547 return -EEXIST;
548 }
549 merge_state(tree, state);
550 return 0;
551 }
552
553 /*
554 * split a given extent state struct in two, inserting the preallocated
555 * struct 'prealloc' as the newly created second half. 'split' indicates an
556 * offset inside 'orig' where it should be split.
557 *
558 * Before calling,
559 * the tree has 'orig' at [orig->start, orig->end]. After calling, there
560 * are two extent state structs in the tree:
561 * prealloc: [orig->start, split - 1]
562 * orig: [ split, orig->end ]
563 *
564 * The tree locks are not taken by this function. They need to be held
565 * by the caller.
566 */
567 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
568 struct extent_state *prealloc, u64 split)
569 {
570 struct rb_node *node;
571
572 if (tree->private_data && is_data_inode(tree->private_data))
573 btrfs_split_delalloc_extent(tree->private_data, orig, split);
574
575 prealloc->start = orig->start;
576 prealloc->end = split - 1;
577 prealloc->state = orig->state;
578 orig->start = split;
579
580 node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
581 &prealloc->rb_node, NULL, NULL);
582 if (node) {
583 free_extent_state(prealloc);
584 return -EEXIST;
585 }
586 return 0;
587 }
588
589 static struct extent_state *next_state(struct extent_state *state)
590 {
591 struct rb_node *next = rb_next(&state->rb_node);
592 if (next)
593 return rb_entry(next, struct extent_state, rb_node);
594 else
595 return NULL;
596 }
597
598 /*
599 * utility function to clear some bits in an extent state struct.
600 * it will optionally wake up anyone waiting on this state (wake == 1).
601 *
602 * If no bits are set on the state struct after clearing things, the
603 * struct is freed and removed from the tree
604 */
605 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
606 struct extent_state *state,
607 unsigned *bits, int wake,
608 struct extent_changeset *changeset)
609 {
610 struct extent_state *next;
611 unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
612 int ret;
613
614 if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
615 u64 range = state->end - state->start + 1;
616 WARN_ON(range > tree->dirty_bytes);
617 tree->dirty_bytes -= range;
618 }
619
620 if (tree->private_data && is_data_inode(tree->private_data))
621 btrfs_clear_delalloc_extent(tree->private_data, state, bits);
622
623 ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
624 BUG_ON(ret < 0);
625 state->state &= ~bits_to_clear;
626 if (wake)
627 wake_up(&state->wq);
628 if (state->state == 0) {
629 next = next_state(state);
630 if (extent_state_in_tree(state)) {
631 rb_erase(&state->rb_node, &tree->state);
632 RB_CLEAR_NODE(&state->rb_node);
633 free_extent_state(state);
634 } else {
635 WARN_ON(1);
636 }
637 } else {
638 merge_state(tree, state);
639 next = next_state(state);
640 }
641 return next;
642 }
643
644 static struct extent_state *
645 alloc_extent_state_atomic(struct extent_state *prealloc)
646 {
647 if (!prealloc)
648 prealloc = alloc_extent_state(GFP_ATOMIC);
649
650 return prealloc;
651 }
652
653 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
654 {
655 struct inode *inode = tree->private_data;
656
657 btrfs_panic(btrfs_sb(inode->i_sb), err,
658 "locking error: extent tree was modified by another thread while locked");
659 }
660
661 /*
662 * clear some bits on a range in the tree. This may require splitting
663 * or inserting elements in the tree, so the gfp mask is used to
664 * indicate which allocations or sleeping are allowed.
665 *
666 * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
667 * the given range from the tree regardless of state (ie for truncate).
668 *
669 * the range [start, end] is inclusive.
670 *
671 * This takes the tree lock, and returns 0 on success and < 0 on error.
672 */
673 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
674 unsigned bits, int wake, int delete,
675 struct extent_state **cached_state,
676 gfp_t mask, struct extent_changeset *changeset)
677 {
678 struct extent_state *state;
679 struct extent_state *cached;
680 struct extent_state *prealloc = NULL;
681 struct rb_node *node;
682 u64 last_end;
683 int err;
684 int clear = 0;
685
686 btrfs_debug_check_extent_io_range(tree, start, end);
687 trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
688
689 if (bits & EXTENT_DELALLOC)
690 bits |= EXTENT_NORESERVE;
691
692 if (delete)
693 bits |= ~EXTENT_CTLBITS;
694
695 if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
696 clear = 1;
697 again:
698 if (!prealloc && gfpflags_allow_blocking(mask)) {
699 /*
700 * Don't care for allocation failure here because we might end
701 * up not needing the pre-allocated extent state at all, which
702 * is the case if we only have in the tree extent states that
703 * cover our input range and don't cover too any other range.
704 * If we end up needing a new extent state we allocate it later.
705 */
706 prealloc = alloc_extent_state(mask);
707 }
708
709 spin_lock(&tree->lock);
710 if (cached_state) {
711 cached = *cached_state;
712
713 if (clear) {
714 *cached_state = NULL;
715 cached_state = NULL;
716 }
717
718 if (cached && extent_state_in_tree(cached) &&
719 cached->start <= start && cached->end > start) {
720 if (clear)
721 refcount_dec(&cached->refs);
722 state = cached;
723 goto hit_next;
724 }
725 if (clear)
726 free_extent_state(cached);
727 }
728 /*
729 * this search will find the extents that end after
730 * our range starts
731 */
732 node = tree_search(tree, start);
733 if (!node)
734 goto out;
735 state = rb_entry(node, struct extent_state, rb_node);
736 hit_next:
737 if (state->start > end)
738 goto out;
739 WARN_ON(state->end < start);
740 last_end = state->end;
741
742 /* the state doesn't have the wanted bits, go ahead */
743 if (!(state->state & bits)) {
744 state = next_state(state);
745 goto next;
746 }
747
748 /*
749 * | ---- desired range ---- |
750 * | state | or
751 * | ------------- state -------------- |
752 *
753 * We need to split the extent we found, and may flip
754 * bits on second half.
755 *
756 * If the extent we found extends past our range, we
757 * just split and search again. It'll get split again
758 * the next time though.
759 *
760 * If the extent we found is inside our range, we clear
761 * the desired bit on it.
762 */
763
764 if (state->start < start) {
765 prealloc = alloc_extent_state_atomic(prealloc);
766 BUG_ON(!prealloc);
767 err = split_state(tree, state, prealloc, start);
768 if (err)
769 extent_io_tree_panic(tree, err);
770
771 prealloc = NULL;
772 if (err)
773 goto out;
774 if (state->end <= end) {
775 state = clear_state_bit(tree, state, &bits, wake,
776 changeset);
777 goto next;
778 }
779 goto search_again;
780 }
781 /*
782 * | ---- desired range ---- |
783 * | state |
784 * We need to split the extent, and clear the bit
785 * on the first half
786 */
787 if (state->start <= end && state->end > end) {
788 prealloc = alloc_extent_state_atomic(prealloc);
789 BUG_ON(!prealloc);
790 err = split_state(tree, state, prealloc, end + 1);
791 if (err)
792 extent_io_tree_panic(tree, err);
793
794 if (wake)
795 wake_up(&state->wq);
796
797 clear_state_bit(tree, prealloc, &bits, wake, changeset);
798
799 prealloc = NULL;
800 goto out;
801 }
802
803 state = clear_state_bit(tree, state, &bits, wake, changeset);
804 next:
805 if (last_end == (u64)-1)
806 goto out;
807 start = last_end + 1;
808 if (start <= end && state && !need_resched())
809 goto hit_next;
810
811 search_again:
812 if (start > end)
813 goto out;
814 spin_unlock(&tree->lock);
815 if (gfpflags_allow_blocking(mask))
816 cond_resched();
817 goto again;
818
819 out:
820 spin_unlock(&tree->lock);
821 if (prealloc)
822 free_extent_state(prealloc);
823
824 return 0;
825
826 }
827
828 static void wait_on_state(struct extent_io_tree *tree,
829 struct extent_state *state)
830 __releases(tree->lock)
831 __acquires(tree->lock)
832 {
833 DEFINE_WAIT(wait);
834 prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
835 spin_unlock(&tree->lock);
836 schedule();
837 spin_lock(&tree->lock);
838 finish_wait(&state->wq, &wait);
839 }
840
841 /*
842 * waits for one or more bits to clear on a range in the state tree.
843 * The range [start, end] is inclusive.
844 * The tree lock is taken by this function
845 */
846 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
847 unsigned long bits)
848 {
849 struct extent_state *state;
850 struct rb_node *node;
851
852 btrfs_debug_check_extent_io_range(tree, start, end);
853
854 spin_lock(&tree->lock);
855 again:
856 while (1) {
857 /*
858 * this search will find all the extents that end after
859 * our range starts
860 */
861 node = tree_search(tree, start);
862 process_node:
863 if (!node)
864 break;
865
866 state = rb_entry(node, struct extent_state, rb_node);
867
868 if (state->start > end)
869 goto out;
870
871 if (state->state & bits) {
872 start = state->start;
873 refcount_inc(&state->refs);
874 wait_on_state(tree, state);
875 free_extent_state(state);
876 goto again;
877 }
878 start = state->end + 1;
879
880 if (start > end)
881 break;
882
883 if (!cond_resched_lock(&tree->lock)) {
884 node = rb_next(node);
885 goto process_node;
886 }
887 }
888 out:
889 spin_unlock(&tree->lock);
890 }
891
892 static void set_state_bits(struct extent_io_tree *tree,
893 struct extent_state *state,
894 unsigned *bits, struct extent_changeset *changeset)
895 {
896 unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
897 int ret;
898
899 if (tree->private_data && is_data_inode(tree->private_data))
900 btrfs_set_delalloc_extent(tree->private_data, state, bits);
901
902 if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
903 u64 range = state->end - state->start + 1;
904 tree->dirty_bytes += range;
905 }
906 ret = add_extent_changeset(state, bits_to_set, changeset, 1);
907 BUG_ON(ret < 0);
908 state->state |= bits_to_set;
909 }
910
911 static void cache_state_if_flags(struct extent_state *state,
912 struct extent_state **cached_ptr,
913 unsigned flags)
914 {
915 if (cached_ptr && !(*cached_ptr)) {
916 if (!flags || (state->state & flags)) {
917 *cached_ptr = state;
918 refcount_inc(&state->refs);
919 }
920 }
921 }
922
923 static void cache_state(struct extent_state *state,
924 struct extent_state **cached_ptr)
925 {
926 return cache_state_if_flags(state, cached_ptr,
927 EXTENT_LOCKED | EXTENT_BOUNDARY);
928 }
929
930 /*
931 * set some bits on a range in the tree. This may require allocations or
932 * sleeping, so the gfp mask is used to indicate what is allowed.
933 *
934 * If any of the exclusive bits are set, this will fail with -EEXIST if some
935 * part of the range already has the desired bits set. The start of the
936 * existing range is returned in failed_start in this case.
937 *
938 * [start, end] is inclusive This takes the tree lock.
939 */
940
941 static int __must_check
942 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
943 unsigned bits, unsigned exclusive_bits,
944 u64 *failed_start, struct extent_state **cached_state,
945 gfp_t mask, struct extent_changeset *changeset)
946 {
947 struct extent_state *state;
948 struct extent_state *prealloc = NULL;
949 struct rb_node *node;
950 struct rb_node **p;
951 struct rb_node *parent;
952 int err = 0;
953 u64 last_start;
954 u64 last_end;
955
956 btrfs_debug_check_extent_io_range(tree, start, end);
957 trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
958
959 again:
960 if (!prealloc && gfpflags_allow_blocking(mask)) {
961 /*
962 * Don't care for allocation failure here because we might end
963 * up not needing the pre-allocated extent state at all, which
964 * is the case if we only have in the tree extent states that
965 * cover our input range and don't cover too any other range.
966 * If we end up needing a new extent state we allocate it later.
967 */
968 prealloc = alloc_extent_state(mask);
969 }
970
971 spin_lock(&tree->lock);
972 if (cached_state && *cached_state) {
973 state = *cached_state;
974 if (state->start <= start && state->end > start &&
975 extent_state_in_tree(state)) {
976 node = &state->rb_node;
977 goto hit_next;
978 }
979 }
980 /*
981 * this search will find all the extents that end after
982 * our range starts.
983 */
984 node = tree_search_for_insert(tree, start, &p, &parent);
985 if (!node) {
986 prealloc = alloc_extent_state_atomic(prealloc);
987 BUG_ON(!prealloc);
988 err = insert_state(tree, prealloc, start, end,
989 &p, &parent, &bits, changeset);
990 if (err)
991 extent_io_tree_panic(tree, err);
992
993 cache_state(prealloc, cached_state);
994 prealloc = NULL;
995 goto out;
996 }
997 state = rb_entry(node, struct extent_state, rb_node);
998 hit_next:
999 last_start = state->start;
1000 last_end = state->end;
1001
1002 /*
1003 * | ---- desired range ---- |
1004 * | state |
1005 *
1006 * Just lock what we found and keep going
1007 */
1008 if (state->start == start && state->end <= end) {
1009 if (state->state & exclusive_bits) {
1010 *failed_start = state->start;
1011 err = -EEXIST;
1012 goto out;
1013 }
1014
1015 set_state_bits(tree, state, &bits, changeset);
1016 cache_state(state, cached_state);
1017 merge_state(tree, state);
1018 if (last_end == (u64)-1)
1019 goto out;
1020 start = last_end + 1;
1021 state = next_state(state);
1022 if (start < end && state && state->start == start &&
1023 !need_resched())
1024 goto hit_next;
1025 goto search_again;
1026 }
1027
1028 /*
1029 * | ---- desired range ---- |
1030 * | state |
1031 * or
1032 * | ------------- state -------------- |
1033 *
1034 * We need to split the extent we found, and may flip bits on
1035 * second half.
1036 *
1037 * If the extent we found extends past our
1038 * range, we just split and search again. It'll get split
1039 * again the next time though.
1040 *
1041 * If the extent we found is inside our range, we set the
1042 * desired bit on it.
1043 */
1044 if (state->start < start) {
1045 if (state->state & exclusive_bits) {
1046 *failed_start = start;
1047 err = -EEXIST;
1048 goto out;
1049 }
1050
1051 prealloc = alloc_extent_state_atomic(prealloc);
1052 BUG_ON(!prealloc);
1053 err = split_state(tree, state, prealloc, start);
1054 if (err)
1055 extent_io_tree_panic(tree, err);
1056
1057 prealloc = NULL;
1058 if (err)
1059 goto out;
1060 if (state->end <= end) {
1061 set_state_bits(tree, state, &bits, changeset);
1062 cache_state(state, cached_state);
1063 merge_state(tree, state);
1064 if (last_end == (u64)-1)
1065 goto out;
1066 start = last_end + 1;
1067 state = next_state(state);
1068 if (start < end && state && state->start == start &&
1069 !need_resched())
1070 goto hit_next;
1071 }
1072 goto search_again;
1073 }
1074 /*
1075 * | ---- desired range ---- |
1076 * | state | or | state |
1077 *
1078 * There's a hole, we need to insert something in it and
1079 * ignore the extent we found.
1080 */
1081 if (state->start > start) {
1082 u64 this_end;
1083 if (end < last_start)
1084 this_end = end;
1085 else
1086 this_end = last_start - 1;
1087
1088 prealloc = alloc_extent_state_atomic(prealloc);
1089 BUG_ON(!prealloc);
1090
1091 /*
1092 * Avoid to free 'prealloc' if it can be merged with
1093 * the later extent.
1094 */
1095 err = insert_state(tree, prealloc, start, this_end,
1096 NULL, NULL, &bits, changeset);
1097 if (err)
1098 extent_io_tree_panic(tree, err);
1099
1100 cache_state(prealloc, cached_state);
1101 prealloc = NULL;
1102 start = this_end + 1;
1103 goto search_again;
1104 }
1105 /*
1106 * | ---- desired range ---- |
1107 * | state |
1108 * We need to split the extent, and set the bit
1109 * on the first half
1110 */
1111 if (state->start <= end && state->end > end) {
1112 if (state->state & exclusive_bits) {
1113 *failed_start = start;
1114 err = -EEXIST;
1115 goto out;
1116 }
1117
1118 prealloc = alloc_extent_state_atomic(prealloc);
1119 BUG_ON(!prealloc);
1120 err = split_state(tree, state, prealloc, end + 1);
1121 if (err)
1122 extent_io_tree_panic(tree, err);
1123
1124 set_state_bits(tree, prealloc, &bits, changeset);
1125 cache_state(prealloc, cached_state);
1126 merge_state(tree, prealloc);
1127 prealloc = NULL;
1128 goto out;
1129 }
1130
1131 search_again:
1132 if (start > end)
1133 goto out;
1134 spin_unlock(&tree->lock);
1135 if (gfpflags_allow_blocking(mask))
1136 cond_resched();
1137 goto again;
1138
1139 out:
1140 spin_unlock(&tree->lock);
1141 if (prealloc)
1142 free_extent_state(prealloc);
1143
1144 return err;
1145
1146 }
1147
1148 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1149 unsigned bits, u64 * failed_start,
1150 struct extent_state **cached_state, gfp_t mask)
1151 {
1152 return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1153 cached_state, mask, NULL);
1154 }
1155
1156
1157 /**
1158 * convert_extent_bit - convert all bits in a given range from one bit to
1159 * another
1160 * @tree: the io tree to search
1161 * @start: the start offset in bytes
1162 * @end: the end offset in bytes (inclusive)
1163 * @bits: the bits to set in this range
1164 * @clear_bits: the bits to clear in this range
1165 * @cached_state: state that we're going to cache
1166 *
1167 * This will go through and set bits for the given range. If any states exist
1168 * already in this range they are set with the given bit and cleared of the
1169 * clear_bits. This is only meant to be used by things that are mergeable, ie
1170 * converting from say DELALLOC to DIRTY. This is not meant to be used with
1171 * boundary bits like LOCK.
1172 *
1173 * All allocations are done with GFP_NOFS.
1174 */
1175 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1176 unsigned bits, unsigned clear_bits,
1177 struct extent_state **cached_state)
1178 {
1179 struct extent_state *state;
1180 struct extent_state *prealloc = NULL;
1181 struct rb_node *node;
1182 struct rb_node **p;
1183 struct rb_node *parent;
1184 int err = 0;
1185 u64 last_start;
1186 u64 last_end;
1187 bool first_iteration = true;
1188
1189 btrfs_debug_check_extent_io_range(tree, start, end);
1190 trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1191 clear_bits);
1192
1193 again:
1194 if (!prealloc) {
1195 /*
1196 * Best effort, don't worry if extent state allocation fails
1197 * here for the first iteration. We might have a cached state
1198 * that matches exactly the target range, in which case no
1199 * extent state allocations are needed. We'll only know this
1200 * after locking the tree.
1201 */
1202 prealloc = alloc_extent_state(GFP_NOFS);
1203 if (!prealloc && !first_iteration)
1204 return -ENOMEM;
1205 }
1206
1207 spin_lock(&tree->lock);
1208 if (cached_state && *cached_state) {
1209 state = *cached_state;
1210 if (state->start <= start && state->end > start &&
1211 extent_state_in_tree(state)) {
1212 node = &state->rb_node;
1213 goto hit_next;
1214 }
1215 }
1216
1217 /*
1218 * this search will find all the extents that end after
1219 * our range starts.
1220 */
1221 node = tree_search_for_insert(tree, start, &p, &parent);
1222 if (!node) {
1223 prealloc = alloc_extent_state_atomic(prealloc);
1224 if (!prealloc) {
1225 err = -ENOMEM;
1226 goto out;
1227 }
1228 err = insert_state(tree, prealloc, start, end,
1229 &p, &parent, &bits, NULL);
1230 if (err)
1231 extent_io_tree_panic(tree, err);
1232 cache_state(prealloc, cached_state);
1233 prealloc = NULL;
1234 goto out;
1235 }
1236 state = rb_entry(node, struct extent_state, rb_node);
1237 hit_next:
1238 last_start = state->start;
1239 last_end = state->end;
1240
1241 /*
1242 * | ---- desired range ---- |
1243 * | state |
1244 *
1245 * Just lock what we found and keep going
1246 */
1247 if (state->start == start && state->end <= end) {
1248 set_state_bits(tree, state, &bits, NULL);
1249 cache_state(state, cached_state);
1250 state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1251 if (last_end == (u64)-1)
1252 goto out;
1253 start = last_end + 1;
1254 if (start < end && state && state->start == start &&
1255 !need_resched())
1256 goto hit_next;
1257 goto search_again;
1258 }
1259
1260 /*
1261 * | ---- desired range ---- |
1262 * | state |
1263 * or
1264 * | ------------- state -------------- |
1265 *
1266 * We need to split the extent we found, and may flip bits on
1267 * second half.
1268 *
1269 * If the extent we found extends past our
1270 * range, we just split and search again. It'll get split
1271 * again the next time though.
1272 *
1273 * If the extent we found is inside our range, we set the
1274 * desired bit on it.
1275 */
1276 if (state->start < start) {
1277 prealloc = alloc_extent_state_atomic(prealloc);
1278 if (!prealloc) {
1279 err = -ENOMEM;
1280 goto out;
1281 }
1282 err = split_state(tree, state, prealloc, start);
1283 if (err)
1284 extent_io_tree_panic(tree, err);
1285 prealloc = NULL;
1286 if (err)
1287 goto out;
1288 if (state->end <= end) {
1289 set_state_bits(tree, state, &bits, NULL);
1290 cache_state(state, cached_state);
1291 state = clear_state_bit(tree, state, &clear_bits, 0,
1292 NULL);
1293 if (last_end == (u64)-1)
1294 goto out;
1295 start = last_end + 1;
1296 if (start < end && state && state->start == start &&
1297 !need_resched())
1298 goto hit_next;
1299 }
1300 goto search_again;
1301 }
1302 /*
1303 * | ---- desired range ---- |
1304 * | state | or | state |
1305 *
1306 * There's a hole, we need to insert something in it and
1307 * ignore the extent we found.
1308 */
1309 if (state->start > start) {
1310 u64 this_end;
1311 if (end < last_start)
1312 this_end = end;
1313 else
1314 this_end = last_start - 1;
1315
1316 prealloc = alloc_extent_state_atomic(prealloc);
1317 if (!prealloc) {
1318 err = -ENOMEM;
1319 goto out;
1320 }
1321
1322 /*
1323 * Avoid to free 'prealloc' if it can be merged with
1324 * the later extent.
1325 */
1326 err = insert_state(tree, prealloc, start, this_end,
1327 NULL, NULL, &bits, NULL);
1328 if (err)
1329 extent_io_tree_panic(tree, err);
1330 cache_state(prealloc, cached_state);
1331 prealloc = NULL;
1332 start = this_end + 1;
1333 goto search_again;
1334 }
1335 /*
1336 * | ---- desired range ---- |
1337 * | state |
1338 * We need to split the extent, and set the bit
1339 * on the first half
1340 */
1341 if (state->start <= end && state->end > end) {
1342 prealloc = alloc_extent_state_atomic(prealloc);
1343 if (!prealloc) {
1344 err = -ENOMEM;
1345 goto out;
1346 }
1347
1348 err = split_state(tree, state, prealloc, end + 1);
1349 if (err)
1350 extent_io_tree_panic(tree, err);
1351
1352 set_state_bits(tree, prealloc, &bits, NULL);
1353 cache_state(prealloc, cached_state);
1354 clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1355 prealloc = NULL;
1356 goto out;
1357 }
1358
1359 search_again:
1360 if (start > end)
1361 goto out;
1362 spin_unlock(&tree->lock);
1363 cond_resched();
1364 first_iteration = false;
1365 goto again;
1366
1367 out:
1368 spin_unlock(&tree->lock);
1369 if (prealloc)
1370 free_extent_state(prealloc);
1371
1372 return err;
1373 }
1374
1375 /* wrappers around set/clear extent bit */
1376 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1377 unsigned bits, struct extent_changeset *changeset)
1378 {
1379 /*
1380 * We don't support EXTENT_LOCKED yet, as current changeset will
1381 * record any bits changed, so for EXTENT_LOCKED case, it will
1382 * either fail with -EEXIST or changeset will record the whole
1383 * range.
1384 */
1385 BUG_ON(bits & EXTENT_LOCKED);
1386
1387 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1388 changeset);
1389 }
1390
1391 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1392 unsigned bits)
1393 {
1394 return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1395 GFP_NOWAIT, NULL);
1396 }
1397
1398 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1399 unsigned bits, int wake, int delete,
1400 struct extent_state **cached)
1401 {
1402 return __clear_extent_bit(tree, start, end, bits, wake, delete,
1403 cached, GFP_NOFS, NULL);
1404 }
1405
1406 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1407 unsigned bits, struct extent_changeset *changeset)
1408 {
1409 /*
1410 * Don't support EXTENT_LOCKED case, same reason as
1411 * set_record_extent_bits().
1412 */
1413 BUG_ON(bits & EXTENT_LOCKED);
1414
1415 return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1416 changeset);
1417 }
1418
1419 /*
1420 * either insert or lock state struct between start and end use mask to tell
1421 * us if waiting is desired.
1422 */
1423 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1424 struct extent_state **cached_state)
1425 {
1426 int err;
1427 u64 failed_start;
1428
1429 while (1) {
1430 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1431 EXTENT_LOCKED, &failed_start,
1432 cached_state, GFP_NOFS, NULL);
1433 if (err == -EEXIST) {
1434 wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1435 start = failed_start;
1436 } else
1437 break;
1438 WARN_ON(start > end);
1439 }
1440 return err;
1441 }
1442
1443 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1444 {
1445 int err;
1446 u64 failed_start;
1447
1448 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1449 &failed_start, NULL, GFP_NOFS, NULL);
1450 if (err == -EEXIST) {
1451 if (failed_start > start)
1452 clear_extent_bit(tree, start, failed_start - 1,
1453 EXTENT_LOCKED, 1, 0, NULL);
1454 return 0;
1455 }
1456 return 1;
1457 }
1458
1459 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1460 {
1461 unsigned long index = start >> PAGE_SHIFT;
1462 unsigned long end_index = end >> PAGE_SHIFT;
1463 struct page *page;
1464
1465 while (index <= end_index) {
1466 page = find_get_page(inode->i_mapping, index);
1467 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1468 clear_page_dirty_for_io(page);
1469 put_page(page);
1470 index++;
1471 }
1472 }
1473
1474 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1475 {
1476 unsigned long index = start >> PAGE_SHIFT;
1477 unsigned long end_index = end >> PAGE_SHIFT;
1478 struct page *page;
1479
1480 while (index <= end_index) {
1481 page = find_get_page(inode->i_mapping, index);
1482 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1483 __set_page_dirty_nobuffers(page);
1484 account_page_redirty(page);
1485 put_page(page);
1486 index++;
1487 }
1488 }
1489
1490 /* find the first state struct with 'bits' set after 'start', and
1491 * return it. tree->lock must be held. NULL will returned if
1492 * nothing was found after 'start'
1493 */
1494 static struct extent_state *
1495 find_first_extent_bit_state(struct extent_io_tree *tree,
1496 u64 start, unsigned bits)
1497 {
1498 struct rb_node *node;
1499 struct extent_state *state;
1500
1501 /*
1502 * this search will find all the extents that end after
1503 * our range starts.
1504 */
1505 node = tree_search(tree, start);
1506 if (!node)
1507 goto out;
1508
1509 while (1) {
1510 state = rb_entry(node, struct extent_state, rb_node);
1511 if (state->end >= start && (state->state & bits))
1512 return state;
1513
1514 node = rb_next(node);
1515 if (!node)
1516 break;
1517 }
1518 out:
1519 return NULL;
1520 }
1521
1522 /*
1523 * find the first offset in the io tree with 'bits' set. zero is
1524 * returned if we find something, and *start_ret and *end_ret are
1525 * set to reflect the state struct that was found.
1526 *
1527 * If nothing was found, 1 is returned. If found something, return 0.
1528 */
1529 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1530 u64 *start_ret, u64 *end_ret, unsigned bits,
1531 struct extent_state **cached_state)
1532 {
1533 struct extent_state *state;
1534 int ret = 1;
1535
1536 spin_lock(&tree->lock);
1537 if (cached_state && *cached_state) {
1538 state = *cached_state;
1539 if (state->end == start - 1 && extent_state_in_tree(state)) {
1540 while ((state = next_state(state)) != NULL) {
1541 if (state->state & bits)
1542 goto got_it;
1543 }
1544 free_extent_state(*cached_state);
1545 *cached_state = NULL;
1546 goto out;
1547 }
1548 free_extent_state(*cached_state);
1549 *cached_state = NULL;
1550 }
1551
1552 state = find_first_extent_bit_state(tree, start, bits);
1553 got_it:
1554 if (state) {
1555 cache_state_if_flags(state, cached_state, 0);
1556 *start_ret = state->start;
1557 *end_ret = state->end;
1558 ret = 0;
1559 }
1560 out:
1561 spin_unlock(&tree->lock);
1562 return ret;
1563 }
1564
1565 /**
1566 * find_first_clear_extent_bit - find the first range that has @bits not set.
1567 * This range could start before @start.
1568 *
1569 * @tree - the tree to search
1570 * @start - the offset at/after which the found extent should start
1571 * @start_ret - records the beginning of the range
1572 * @end_ret - records the end of the range (inclusive)
1573 * @bits - the set of bits which must be unset
1574 *
1575 * Since unallocated range is also considered one which doesn't have the bits
1576 * set it's possible that @end_ret contains -1, this happens in case the range
1577 * spans (last_range_end, end of device]. In this case it's up to the caller to
1578 * trim @end_ret to the appropriate size.
1579 */
1580 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1581 u64 *start_ret, u64 *end_ret, unsigned bits)
1582 {
1583 struct extent_state *state;
1584 struct rb_node *node, *prev = NULL, *next;
1585
1586 spin_lock(&tree->lock);
1587
1588 /* Find first extent with bits cleared */
1589 while (1) {
1590 node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1591 if (!node) {
1592 node = next;
1593 if (!node) {
1594 /*
1595 * We are past the last allocated chunk,
1596 * set start at the end of the last extent. The
1597 * device alloc tree should never be empty so
1598 * prev is always set.
1599 */
1600 ASSERT(prev);
1601 state = rb_entry(prev, struct extent_state, rb_node);
1602 *start_ret = state->end + 1;
1603 *end_ret = -1;
1604 goto out;
1605 }
1606 }
1607 /*
1608 * At this point 'node' either contains 'start' or start is
1609 * before 'node'
1610 */
1611 state = rb_entry(node, struct extent_state, rb_node);
1612
1613 if (in_range(start, state->start, state->end - state->start + 1)) {
1614 if (state->state & bits) {
1615 /*
1616 * |--range with bits sets--|
1617 * |
1618 * start
1619 */
1620 start = state->end + 1;
1621 } else {
1622 /*
1623 * 'start' falls within a range that doesn't
1624 * have the bits set, so take its start as
1625 * the beginning of the desired range
1626 *
1627 * |--range with bits cleared----|
1628 * |
1629 * start
1630 */
1631 *start_ret = state->start;
1632 break;
1633 }
1634 } else {
1635 /*
1636 * |---prev range---|---hole/unset---|---node range---|
1637 * |
1638 * start
1639 *
1640 * or
1641 *
1642 * |---hole/unset--||--first node--|
1643 * 0 |
1644 * start
1645 */
1646 if (prev) {
1647 state = rb_entry(prev, struct extent_state,
1648 rb_node);
1649 *start_ret = state->end + 1;
1650 } else {
1651 *start_ret = 0;
1652 }
1653 break;
1654 }
1655 }
1656
1657 /*
1658 * Find the longest stretch from start until an entry which has the
1659 * bits set
1660 */
1661 while (1) {
1662 state = rb_entry(node, struct extent_state, rb_node);
1663 if (state->end >= start && !(state->state & bits)) {
1664 *end_ret = state->end;
1665 } else {
1666 *end_ret = state->start - 1;
1667 break;
1668 }
1669
1670 node = rb_next(node);
1671 if (!node)
1672 break;
1673 }
1674 out:
1675 spin_unlock(&tree->lock);
1676 }
1677
1678 /*
1679 * find a contiguous range of bytes in the file marked as delalloc, not
1680 * more than 'max_bytes'. start and end are used to return the range,
1681 *
1682 * true is returned if we find something, false if nothing was in the tree
1683 */
1684 static noinline bool find_delalloc_range(struct extent_io_tree *tree,
1685 u64 *start, u64 *end, u64 max_bytes,
1686 struct extent_state **cached_state)
1687 {
1688 struct rb_node *node;
1689 struct extent_state *state;
1690 u64 cur_start = *start;
1691 bool found = false;
1692 u64 total_bytes = 0;
1693
1694 spin_lock(&tree->lock);
1695
1696 /*
1697 * this search will find all the extents that end after
1698 * our range starts.
1699 */
1700 node = tree_search(tree, cur_start);
1701 if (!node) {
1702 *end = (u64)-1;
1703 goto out;
1704 }
1705
1706 while (1) {
1707 state = rb_entry(node, struct extent_state, rb_node);
1708 if (found && (state->start != cur_start ||
1709 (state->state & EXTENT_BOUNDARY))) {
1710 goto out;
1711 }
1712 if (!(state->state & EXTENT_DELALLOC)) {
1713 if (!found)
1714 *end = state->end;
1715 goto out;
1716 }
1717 if (!found) {
1718 *start = state->start;
1719 *cached_state = state;
1720 refcount_inc(&state->refs);
1721 }
1722 found = true;
1723 *end = state->end;
1724 cur_start = state->end + 1;
1725 node = rb_next(node);
1726 total_bytes += state->end - state->start + 1;
1727 if (total_bytes >= max_bytes)
1728 break;
1729 if (!node)
1730 break;
1731 }
1732 out:
1733 spin_unlock(&tree->lock);
1734 return found;
1735 }
1736
1737 static int __process_pages_contig(struct address_space *mapping,
1738 struct page *locked_page,
1739 pgoff_t start_index, pgoff_t end_index,
1740 unsigned long page_ops, pgoff_t *index_ret);
1741
1742 static noinline void __unlock_for_delalloc(struct inode *inode,
1743 struct page *locked_page,
1744 u64 start, u64 end)
1745 {
1746 unsigned long index = start >> PAGE_SHIFT;
1747 unsigned long end_index = end >> PAGE_SHIFT;
1748
1749 ASSERT(locked_page);
1750 if (index == locked_page->index && end_index == index)
1751 return;
1752
1753 __process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1754 PAGE_UNLOCK, NULL);
1755 }
1756
1757 static noinline int lock_delalloc_pages(struct inode *inode,
1758 struct page *locked_page,
1759 u64 delalloc_start,
1760 u64 delalloc_end)
1761 {
1762 unsigned long index = delalloc_start >> PAGE_SHIFT;
1763 unsigned long index_ret = index;
1764 unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1765 int ret;
1766
1767 ASSERT(locked_page);
1768 if (index == locked_page->index && index == end_index)
1769 return 0;
1770
1771 ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1772 end_index, PAGE_LOCK, &index_ret);
1773 if (ret == -EAGAIN)
1774 __unlock_for_delalloc(inode, locked_page, delalloc_start,
1775 (u64)index_ret << PAGE_SHIFT);
1776 return ret;
1777 }
1778
1779 /*
1780 * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1781 * more than @max_bytes. @Start and @end are used to return the range,
1782 *
1783 * Return: true if we find something
1784 * false if nothing was in the tree
1785 */
1786 EXPORT_FOR_TESTS
1787 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
1788 struct page *locked_page, u64 *start,
1789 u64 *end)
1790 {
1791 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1792 u64 max_bytes = BTRFS_MAX_EXTENT_SIZE;
1793 u64 delalloc_start;
1794 u64 delalloc_end;
1795 bool found;
1796 struct extent_state *cached_state = NULL;
1797 int ret;
1798 int loops = 0;
1799
1800 again:
1801 /* step one, find a bunch of delalloc bytes starting at start */
1802 delalloc_start = *start;
1803 delalloc_end = 0;
1804 found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1805 max_bytes, &cached_state);
1806 if (!found || delalloc_end <= *start) {
1807 *start = delalloc_start;
1808 *end = delalloc_end;
1809 free_extent_state(cached_state);
1810 return false;
1811 }
1812
1813 /*
1814 * start comes from the offset of locked_page. We have to lock
1815 * pages in order, so we can't process delalloc bytes before
1816 * locked_page
1817 */
1818 if (delalloc_start < *start)
1819 delalloc_start = *start;
1820
1821 /*
1822 * make sure to limit the number of pages we try to lock down
1823 */
1824 if (delalloc_end + 1 - delalloc_start > max_bytes)
1825 delalloc_end = delalloc_start + max_bytes - 1;
1826
1827 /* step two, lock all the pages after the page that has start */
1828 ret = lock_delalloc_pages(inode, locked_page,
1829 delalloc_start, delalloc_end);
1830 ASSERT(!ret || ret == -EAGAIN);
1831 if (ret == -EAGAIN) {
1832 /* some of the pages are gone, lets avoid looping by
1833 * shortening the size of the delalloc range we're searching
1834 */
1835 free_extent_state(cached_state);
1836 cached_state = NULL;
1837 if (!loops) {
1838 max_bytes = PAGE_SIZE;
1839 loops = 1;
1840 goto again;
1841 } else {
1842 found = false;
1843 goto out_failed;
1844 }
1845 }
1846
1847 /* step three, lock the state bits for the whole range */
1848 lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1849
1850 /* then test to make sure it is all still delalloc */
1851 ret = test_range_bit(tree, delalloc_start, delalloc_end,
1852 EXTENT_DELALLOC, 1, cached_state);
1853 if (!ret) {
1854 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1855 &cached_state);
1856 __unlock_for_delalloc(inode, locked_page,
1857 delalloc_start, delalloc_end);
1858 cond_resched();
1859 goto again;
1860 }
1861 free_extent_state(cached_state);
1862 *start = delalloc_start;
1863 *end = delalloc_end;
1864 out_failed:
1865 return found;
1866 }
1867
1868 static int __process_pages_contig(struct address_space *mapping,
1869 struct page *locked_page,
1870 pgoff_t start_index, pgoff_t end_index,
1871 unsigned long page_ops, pgoff_t *index_ret)
1872 {
1873 unsigned long nr_pages = end_index - start_index + 1;
1874 unsigned long pages_locked = 0;
1875 pgoff_t index = start_index;
1876 struct page *pages[16];
1877 unsigned ret;
1878 int err = 0;
1879 int i;
1880
1881 if (page_ops & PAGE_LOCK) {
1882 ASSERT(page_ops == PAGE_LOCK);
1883 ASSERT(index_ret && *index_ret == start_index);
1884 }
1885
1886 if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1887 mapping_set_error(mapping, -EIO);
1888
1889 while (nr_pages > 0) {
1890 ret = find_get_pages_contig(mapping, index,
1891 min_t(unsigned long,
1892 nr_pages, ARRAY_SIZE(pages)), pages);
1893 if (ret == 0) {
1894 /*
1895 * Only if we're going to lock these pages,
1896 * can we find nothing at @index.
1897 */
1898 ASSERT(page_ops & PAGE_LOCK);
1899 err = -EAGAIN;
1900 goto out;
1901 }
1902
1903 for (i = 0; i < ret; i++) {
1904 if (page_ops & PAGE_SET_PRIVATE2)
1905 SetPagePrivate2(pages[i]);
1906
1907 if (pages[i] == locked_page) {
1908 put_page(pages[i]);
1909 pages_locked++;
1910 continue;
1911 }
1912 if (page_ops & PAGE_CLEAR_DIRTY)
1913 clear_page_dirty_for_io(pages[i]);
1914 if (page_ops & PAGE_SET_WRITEBACK)
1915 set_page_writeback(pages[i]);
1916 if (page_ops & PAGE_SET_ERROR)
1917 SetPageError(pages[i]);
1918 if (page_ops & PAGE_END_WRITEBACK)
1919 end_page_writeback(pages[i]);
1920 if (page_ops & PAGE_UNLOCK)
1921 unlock_page(pages[i]);
1922 if (page_ops & PAGE_LOCK) {
1923 lock_page(pages[i]);
1924 if (!PageDirty(pages[i]) ||
1925 pages[i]->mapping != mapping) {
1926 unlock_page(pages[i]);
1927 put_page(pages[i]);
1928 err = -EAGAIN;
1929 goto out;
1930 }
1931 }
1932 put_page(pages[i]);
1933 pages_locked++;
1934 }
1935 nr_pages -= ret;
1936 index += ret;
1937 cond_resched();
1938 }
1939 out:
1940 if (err && index_ret)
1941 *index_ret = start_index + pages_locked - 1;
1942 return err;
1943 }
1944
1945 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1946 struct page *locked_page,
1947 unsigned clear_bits,
1948 unsigned long page_ops)
1949 {
1950 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1951 NULL);
1952
1953 __process_pages_contig(inode->i_mapping, locked_page,
1954 start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1955 page_ops, NULL);
1956 }
1957
1958 /*
1959 * count the number of bytes in the tree that have a given bit(s)
1960 * set. This can be fairly slow, except for EXTENT_DIRTY which is
1961 * cached. The total number found is returned.
1962 */
1963 u64 count_range_bits(struct extent_io_tree *tree,
1964 u64 *start, u64 search_end, u64 max_bytes,
1965 unsigned bits, int contig)
1966 {
1967 struct rb_node *node;
1968 struct extent_state *state;
1969 u64 cur_start = *start;
1970 u64 total_bytes = 0;
1971 u64 last = 0;
1972 int found = 0;
1973
1974 if (WARN_ON(search_end <= cur_start))
1975 return 0;
1976
1977 spin_lock(&tree->lock);
1978 if (cur_start == 0 && bits == EXTENT_DIRTY) {
1979 total_bytes = tree->dirty_bytes;
1980 goto out;
1981 }
1982 /*
1983 * this search will find all the extents that end after
1984 * our range starts.
1985 */
1986 node = tree_search(tree, cur_start);
1987 if (!node)
1988 goto out;
1989
1990 while (1) {
1991 state = rb_entry(node, struct extent_state, rb_node);
1992 if (state->start > search_end)
1993 break;
1994 if (contig && found && state->start > last + 1)
1995 break;
1996 if (state->end >= cur_start && (state->state & bits) == bits) {
1997 total_bytes += min(search_end, state->end) + 1 -
1998 max(cur_start, state->start);
1999 if (total_bytes >= max_bytes)
2000 break;
2001 if (!found) {
2002 *start = max(cur_start, state->start);
2003 found = 1;
2004 }
2005 last = state->end;
2006 } else if (contig && found) {
2007 break;
2008 }
2009 node = rb_next(node);
2010 if (!node)
2011 break;
2012 }
2013 out:
2014 spin_unlock(&tree->lock);
2015 return total_bytes;
2016 }
2017
2018 /*
2019 * set the private field for a given byte offset in the tree. If there isn't
2020 * an extent_state there already, this does nothing.
2021 */
2022 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
2023 struct io_failure_record *failrec)
2024 {
2025 struct rb_node *node;
2026 struct extent_state *state;
2027 int ret = 0;
2028
2029 spin_lock(&tree->lock);
2030 /*
2031 * this search will find all the extents that end after
2032 * our range starts.
2033 */
2034 node = tree_search(tree, start);
2035 if (!node) {
2036 ret = -ENOENT;
2037 goto out;
2038 }
2039 state = rb_entry(node, struct extent_state, rb_node);
2040 if (state->start != start) {
2041 ret = -ENOENT;
2042 goto out;
2043 }
2044 state->failrec = failrec;
2045 out:
2046 spin_unlock(&tree->lock);
2047 return ret;
2048 }
2049
2050 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
2051 struct io_failure_record **failrec)
2052 {
2053 struct rb_node *node;
2054 struct extent_state *state;
2055 int ret = 0;
2056
2057 spin_lock(&tree->lock);
2058 /*
2059 * this search will find all the extents that end after
2060 * our range starts.
2061 */
2062 node = tree_search(tree, start);
2063 if (!node) {
2064 ret = -ENOENT;
2065 goto out;
2066 }
2067 state = rb_entry(node, struct extent_state, rb_node);
2068 if (state->start != start) {
2069 ret = -ENOENT;
2070 goto out;
2071 }
2072 *failrec = state->failrec;
2073 out:
2074 spin_unlock(&tree->lock);
2075 return ret;
2076 }
2077
2078 /*
2079 * searches a range in the state tree for a given mask.
2080 * If 'filled' == 1, this returns 1 only if every extent in the tree
2081 * has the bits set. Otherwise, 1 is returned if any bit in the
2082 * range is found set.
2083 */
2084 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2085 unsigned bits, int filled, struct extent_state *cached)
2086 {
2087 struct extent_state *state = NULL;
2088 struct rb_node *node;
2089 int bitset = 0;
2090
2091 spin_lock(&tree->lock);
2092 if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2093 cached->end > start)
2094 node = &cached->rb_node;
2095 else
2096 node = tree_search(tree, start);
2097 while (node && start <= end) {
2098 state = rb_entry(node, struct extent_state, rb_node);
2099
2100 if (filled && state->start > start) {
2101 bitset = 0;
2102 break;
2103 }
2104
2105 if (state->start > end)
2106 break;
2107
2108 if (state->state & bits) {
2109 bitset = 1;
2110 if (!filled)
2111 break;
2112 } else if (filled) {
2113 bitset = 0;
2114 break;
2115 }
2116
2117 if (state->end == (u64)-1)
2118 break;
2119
2120 start = state->end + 1;
2121 if (start > end)
2122 break;
2123 node = rb_next(node);
2124 if (!node) {
2125 if (filled)
2126 bitset = 0;
2127 break;
2128 }
2129 }
2130 spin_unlock(&tree->lock);
2131 return bitset;
2132 }
2133
2134 /*
2135 * helper function to set a given page up to date if all the
2136 * extents in the tree for that page are up to date
2137 */
2138 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
2139 {
2140 u64 start = page_offset(page);
2141 u64 end = start + PAGE_SIZE - 1;
2142 if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
2143 SetPageUptodate(page);
2144 }
2145
2146 int free_io_failure(struct extent_io_tree *failure_tree,
2147 struct extent_io_tree *io_tree,
2148 struct io_failure_record *rec)
2149 {
2150 int ret;
2151 int err = 0;
2152
2153 set_state_failrec(failure_tree, rec->start, NULL);
2154 ret = clear_extent_bits(failure_tree, rec->start,
2155 rec->start + rec->len - 1,
2156 EXTENT_LOCKED | EXTENT_DIRTY);
2157 if (ret)
2158 err = ret;
2159
2160 ret = clear_extent_bits(io_tree, rec->start,
2161 rec->start + rec->len - 1,
2162 EXTENT_DAMAGED);
2163 if (ret && !err)
2164 err = ret;
2165
2166 kfree(rec);
2167 return err;
2168 }
2169
2170 /*
2171 * this bypasses the standard btrfs submit functions deliberately, as
2172 * the standard behavior is to write all copies in a raid setup. here we only
2173 * want to write the one bad copy. so we do the mapping for ourselves and issue
2174 * submit_bio directly.
2175 * to avoid any synchronization issues, wait for the data after writing, which
2176 * actually prevents the read that triggered the error from finishing.
2177 * currently, there can be no more than two copies of every data bit. thus,
2178 * exactly one rewrite is required.
2179 */
2180 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2181 u64 length, u64 logical, struct page *page,
2182 unsigned int pg_offset, int mirror_num)
2183 {
2184 struct bio *bio;
2185 struct btrfs_device *dev;
2186 u64 map_length = 0;
2187 u64 sector;
2188 struct btrfs_bio *bbio = NULL;
2189 int ret;
2190
2191 ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2192 BUG_ON(!mirror_num);
2193
2194 bio = btrfs_io_bio_alloc(1);
2195 bio->bi_iter.bi_size = 0;
2196 map_length = length;
2197
2198 /*
2199 * Avoid races with device replace and make sure our bbio has devices
2200 * associated to its stripes that don't go away while we are doing the
2201 * read repair operation.
2202 */
2203 btrfs_bio_counter_inc_blocked(fs_info);
2204 if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2205 /*
2206 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2207 * to update all raid stripes, but here we just want to correct
2208 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2209 * stripe's dev and sector.
2210 */
2211 ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2212 &map_length, &bbio, 0);
2213 if (ret) {
2214 btrfs_bio_counter_dec(fs_info);
2215 bio_put(bio);
2216 return -EIO;
2217 }
2218 ASSERT(bbio->mirror_num == 1);
2219 } else {
2220 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2221 &map_length, &bbio, mirror_num);
2222 if (ret) {
2223 btrfs_bio_counter_dec(fs_info);
2224 bio_put(bio);
2225 return -EIO;
2226 }
2227 BUG_ON(mirror_num != bbio->mirror_num);
2228 }
2229
2230 sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2231 bio->bi_iter.bi_sector = sector;
2232 dev = bbio->stripes[bbio->mirror_num - 1].dev;
2233 btrfs_put_bbio(bbio);
2234 if (!dev || !dev->bdev ||
2235 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2236 btrfs_bio_counter_dec(fs_info);
2237 bio_put(bio);
2238 return -EIO;
2239 }
2240 bio_set_dev(bio, dev->bdev);
2241 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2242 bio_add_page(bio, page, length, pg_offset);
2243
2244 if (btrfsic_submit_bio_wait(bio)) {
2245 /* try to remap that extent elsewhere? */
2246 btrfs_bio_counter_dec(fs_info);
2247 bio_put(bio);
2248 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2249 return -EIO;
2250 }
2251
2252 btrfs_info_rl_in_rcu(fs_info,
2253 "read error corrected: ino %llu off %llu (dev %s sector %llu)",
2254 ino, start,
2255 rcu_str_deref(dev->name), sector);
2256 btrfs_bio_counter_dec(fs_info);
2257 bio_put(bio);
2258 return 0;
2259 }
2260
2261 int btrfs_repair_eb_io_failure(struct extent_buffer *eb, int mirror_num)
2262 {
2263 struct btrfs_fs_info *fs_info = eb->fs_info;
2264 u64 start = eb->start;
2265 int i, num_pages = num_extent_pages(eb);
2266 int ret = 0;
2267
2268 if (sb_rdonly(fs_info->sb))
2269 return -EROFS;
2270
2271 for (i = 0; i < num_pages; i++) {
2272 struct page *p = eb->pages[i];
2273
2274 ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2275 start - page_offset(p), mirror_num);
2276 if (ret)
2277 break;
2278 start += PAGE_SIZE;
2279 }
2280
2281 return ret;
2282 }
2283
2284 /*
2285 * each time an IO finishes, we do a fast check in the IO failure tree
2286 * to see if we need to process or clean up an io_failure_record
2287 */
2288 int clean_io_failure(struct btrfs_fs_info *fs_info,
2289 struct extent_io_tree *failure_tree,
2290 struct extent_io_tree *io_tree, u64 start,
2291 struct page *page, u64 ino, unsigned int pg_offset)
2292 {
2293 u64 private;
2294 struct io_failure_record *failrec;
2295 struct extent_state *state;
2296 int num_copies;
2297 int ret;
2298
2299 private = 0;
2300 ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2301 EXTENT_DIRTY, 0);
2302 if (!ret)
2303 return 0;
2304
2305 ret = get_state_failrec(failure_tree, start, &failrec);
2306 if (ret)
2307 return 0;
2308
2309 BUG_ON(!failrec->this_mirror);
2310
2311 if (failrec->in_validation) {
2312 /* there was no real error, just free the record */
2313 btrfs_debug(fs_info,
2314 "clean_io_failure: freeing dummy error at %llu",
2315 failrec->start);
2316 goto out;
2317 }
2318 if (sb_rdonly(fs_info->sb))
2319 goto out;
2320
2321 spin_lock(&io_tree->lock);
2322 state = find_first_extent_bit_state(io_tree,
2323 failrec->start,
2324 EXTENT_LOCKED);
2325 spin_unlock(&io_tree->lock);
2326
2327 if (state && state->start <= failrec->start &&
2328 state->end >= failrec->start + failrec->len - 1) {
2329 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2330 failrec->len);
2331 if (num_copies > 1) {
2332 repair_io_failure(fs_info, ino, start, failrec->len,
2333 failrec->logical, page, pg_offset,
2334 failrec->failed_mirror);
2335 }
2336 }
2337
2338 out:
2339 free_io_failure(failure_tree, io_tree, failrec);
2340
2341 return 0;
2342 }
2343
2344 /*
2345 * Can be called when
2346 * - hold extent lock
2347 * - under ordered extent
2348 * - the inode is freeing
2349 */
2350 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2351 {
2352 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2353 struct io_failure_record *failrec;
2354 struct extent_state *state, *next;
2355
2356 if (RB_EMPTY_ROOT(&failure_tree->state))
2357 return;
2358
2359 spin_lock(&failure_tree->lock);
2360 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2361 while (state) {
2362 if (state->start > end)
2363 break;
2364
2365 ASSERT(state->end <= end);
2366
2367 next = next_state(state);
2368
2369 failrec = state->failrec;
2370 free_extent_state(state);
2371 kfree(failrec);
2372
2373 state = next;
2374 }
2375 spin_unlock(&failure_tree->lock);
2376 }
2377
2378 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2379 struct io_failure_record **failrec_ret)
2380 {
2381 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2382 struct io_failure_record *failrec;
2383 struct extent_map *em;
2384 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2385 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2386 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2387 int ret;
2388 u64 logical;
2389
2390 ret = get_state_failrec(failure_tree, start, &failrec);
2391 if (ret) {
2392 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2393 if (!failrec)
2394 return -ENOMEM;
2395
2396 failrec->start = start;
2397 failrec->len = end - start + 1;
2398 failrec->this_mirror = 0;
2399 failrec->bio_flags = 0;
2400 failrec->in_validation = 0;
2401
2402 read_lock(&em_tree->lock);
2403 em = lookup_extent_mapping(em_tree, start, failrec->len);
2404 if (!em) {
2405 read_unlock(&em_tree->lock);
2406 kfree(failrec);
2407 return -EIO;
2408 }
2409
2410 if (em->start > start || em->start + em->len <= start) {
2411 free_extent_map(em);
2412 em = NULL;
2413 }
2414 read_unlock(&em_tree->lock);
2415 if (!em) {
2416 kfree(failrec);
2417 return -EIO;
2418 }
2419
2420 logical = start - em->start;
2421 logical = em->block_start + logical;
2422 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2423 logical = em->block_start;
2424 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2425 extent_set_compress_type(&failrec->bio_flags,
2426 em->compress_type);
2427 }
2428
2429 btrfs_debug(fs_info,
2430 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2431 logical, start, failrec->len);
2432
2433 failrec->logical = logical;
2434 free_extent_map(em);
2435
2436 /* set the bits in the private failure tree */
2437 ret = set_extent_bits(failure_tree, start, end,
2438 EXTENT_LOCKED | EXTENT_DIRTY);
2439 if (ret >= 0)
2440 ret = set_state_failrec(failure_tree, start, failrec);
2441 /* set the bits in the inode's tree */
2442 if (ret >= 0)
2443 ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2444 if (ret < 0) {
2445 kfree(failrec);
2446 return ret;
2447 }
2448 } else {
2449 btrfs_debug(fs_info,
2450 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2451 failrec->logical, failrec->start, failrec->len,
2452 failrec->in_validation);
2453 /*
2454 * when data can be on disk more than twice, add to failrec here
2455 * (e.g. with a list for failed_mirror) to make
2456 * clean_io_failure() clean all those errors at once.
2457 */
2458 }
2459
2460 *failrec_ret = failrec;
2461
2462 return 0;
2463 }
2464
2465 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2466 struct io_failure_record *failrec, int failed_mirror)
2467 {
2468 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2469 int num_copies;
2470
2471 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2472 if (num_copies == 1) {
2473 /*
2474 * we only have a single copy of the data, so don't bother with
2475 * all the retry and error correction code that follows. no
2476 * matter what the error is, it is very likely to persist.
2477 */
2478 btrfs_debug(fs_info,
2479 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2480 num_copies, failrec->this_mirror, failed_mirror);
2481 return false;
2482 }
2483
2484 /*
2485 * there are two premises:
2486 * a) deliver good data to the caller
2487 * b) correct the bad sectors on disk
2488 */
2489 if (failed_bio_pages > 1) {
2490 /*
2491 * to fulfill b), we need to know the exact failing sectors, as
2492 * we don't want to rewrite any more than the failed ones. thus,
2493 * we need separate read requests for the failed bio
2494 *
2495 * if the following BUG_ON triggers, our validation request got
2496 * merged. we need separate requests for our algorithm to work.
2497 */
2498 BUG_ON(failrec->in_validation);
2499 failrec->in_validation = 1;
2500 failrec->this_mirror = failed_mirror;
2501 } else {
2502 /*
2503 * we're ready to fulfill a) and b) alongside. get a good copy
2504 * of the failed sector and if we succeed, we have setup
2505 * everything for repair_io_failure to do the rest for us.
2506 */
2507 if (failrec->in_validation) {
2508 BUG_ON(failrec->this_mirror != failed_mirror);
2509 failrec->in_validation = 0;
2510 failrec->this_mirror = 0;
2511 }
2512 failrec->failed_mirror = failed_mirror;
2513 failrec->this_mirror++;
2514 if (failrec->this_mirror == failed_mirror)
2515 failrec->this_mirror++;
2516 }
2517
2518 if (failrec->this_mirror > num_copies) {
2519 btrfs_debug(fs_info,
2520 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2521 num_copies, failrec->this_mirror, failed_mirror);
2522 return false;
2523 }
2524
2525 return true;
2526 }
2527
2528
2529 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2530 struct io_failure_record *failrec,
2531 struct page *page, int pg_offset, int icsum,
2532 bio_end_io_t *endio_func, void *data)
2533 {
2534 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2535 struct bio *bio;
2536 struct btrfs_io_bio *btrfs_failed_bio;
2537 struct btrfs_io_bio *btrfs_bio;
2538
2539 bio = btrfs_io_bio_alloc(1);
2540 bio->bi_end_io = endio_func;
2541 bio->bi_iter.bi_sector = failrec->logical >> 9;
2542 bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2543 bio->bi_iter.bi_size = 0;
2544 bio->bi_private = data;
2545
2546 btrfs_failed_bio = btrfs_io_bio(failed_bio);
2547 if (btrfs_failed_bio->csum) {
2548 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2549
2550 btrfs_bio = btrfs_io_bio(bio);
2551 btrfs_bio->csum = btrfs_bio->csum_inline;
2552 icsum *= csum_size;
2553 memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2554 csum_size);
2555 }
2556
2557 bio_add_page(bio, page, failrec->len, pg_offset);
2558
2559 return bio;
2560 }
2561
2562 /*
2563 * This is a generic handler for readpage errors. If other copies exist, read
2564 * those and write back good data to the failed position. Does not investigate
2565 * in remapping the failed extent elsewhere, hoping the device will be smart
2566 * enough to do this as needed
2567 */
2568 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2569 struct page *page, u64 start, u64 end,
2570 int failed_mirror)
2571 {
2572 struct io_failure_record *failrec;
2573 struct inode *inode = page->mapping->host;
2574 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2575 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2576 struct bio *bio;
2577 int read_mode = 0;
2578 blk_status_t status;
2579 int ret;
2580 unsigned failed_bio_pages = failed_bio->bi_iter.bi_size >> PAGE_SHIFT;
2581
2582 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2583
2584 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2585 if (ret)
2586 return ret;
2587
2588 if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2589 failed_mirror)) {
2590 free_io_failure(failure_tree, tree, failrec);
2591 return -EIO;
2592 }
2593
2594 if (failed_bio_pages > 1)
2595 read_mode |= REQ_FAILFAST_DEV;
2596
2597 phy_offset >>= inode->i_sb->s_blocksize_bits;
2598 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2599 start - page_offset(page),
2600 (int)phy_offset, failed_bio->bi_end_io,
2601 NULL);
2602 bio->bi_opf = REQ_OP_READ | read_mode;
2603
2604 btrfs_debug(btrfs_sb(inode->i_sb),
2605 "Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2606 read_mode, failrec->this_mirror, failrec->in_validation);
2607
2608 status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2609 failrec->bio_flags);
2610 if (status) {
2611 free_io_failure(failure_tree, tree, failrec);
2612 bio_put(bio);
2613 ret = blk_status_to_errno(status);
2614 }
2615
2616 return ret;
2617 }
2618
2619 /* lots and lots of room for performance fixes in the end_bio funcs */
2620
2621 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2622 {
2623 int uptodate = (err == 0);
2624 int ret = 0;
2625
2626 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
2627
2628 if (!uptodate) {
2629 ClearPageUptodate(page);
2630 SetPageError(page);
2631 ret = err < 0 ? err : -EIO;
2632 mapping_set_error(page->mapping, ret);
2633 }
2634 }
2635
2636 /*
2637 * after a writepage IO is done, we need to:
2638 * clear the uptodate bits on error
2639 * clear the writeback bits in the extent tree for this IO
2640 * end_page_writeback if the page has no more pending IO
2641 *
2642 * Scheduling is not allowed, so the extent state tree is expected
2643 * to have one and only one object corresponding to this IO.
2644 */
2645 static void end_bio_extent_writepage(struct bio *bio)
2646 {
2647 int error = blk_status_to_errno(bio->bi_status);
2648 struct bio_vec *bvec;
2649 u64 start;
2650 u64 end;
2651 struct bvec_iter_all iter_all;
2652
2653 ASSERT(!bio_flagged(bio, BIO_CLONED));
2654 bio_for_each_segment_all(bvec, bio, iter_all) {
2655 struct page *page = bvec->bv_page;
2656 struct inode *inode = page->mapping->host;
2657 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2658
2659 /* We always issue full-page reads, but if some block
2660 * in a page fails to read, blk_update_request() will
2661 * advance bv_offset and adjust bv_len to compensate.
2662 * Print a warning for nonzero offsets, and an error
2663 * if they don't add up to a full page. */
2664 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2665 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2666 btrfs_err(fs_info,
2667 "partial page write in btrfs with offset %u and length %u",
2668 bvec->bv_offset, bvec->bv_len);
2669 else
2670 btrfs_info(fs_info,
2671 "incomplete page write in btrfs with offset %u and length %u",
2672 bvec->bv_offset, bvec->bv_len);
2673 }
2674
2675 start = page_offset(page);
2676 end = start + bvec->bv_offset + bvec->bv_len - 1;
2677
2678 end_extent_writepage(page, error, start, end);
2679 end_page_writeback(page);
2680 }
2681
2682 bio_put(bio);
2683 }
2684
2685 static void
2686 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2687 int uptodate)
2688 {
2689 struct extent_state *cached = NULL;
2690 u64 end = start + len - 1;
2691
2692 if (uptodate && tree->track_uptodate)
2693 set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2694 unlock_extent_cached_atomic(tree, start, end, &cached);
2695 }
2696
2697 /*
2698 * after a readpage IO is done, we need to:
2699 * clear the uptodate bits on error
2700 * set the uptodate bits if things worked
2701 * set the page up to date if all extents in the tree are uptodate
2702 * clear the lock bit in the extent tree
2703 * unlock the page if there are no other extents locked for it
2704 *
2705 * Scheduling is not allowed, so the extent state tree is expected
2706 * to have one and only one object corresponding to this IO.
2707 */
2708 static void end_bio_extent_readpage(struct bio *bio)
2709 {
2710 struct bio_vec *bvec;
2711 int uptodate = !bio->bi_status;
2712 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2713 struct extent_io_tree *tree, *failure_tree;
2714 u64 offset = 0;
2715 u64 start;
2716 u64 end;
2717 u64 len;
2718 u64 extent_start = 0;
2719 u64 extent_len = 0;
2720 int mirror;
2721 int ret;
2722 struct bvec_iter_all iter_all;
2723
2724 ASSERT(!bio_flagged(bio, BIO_CLONED));
2725 bio_for_each_segment_all(bvec, bio, iter_all) {
2726 struct page *page = bvec->bv_page;
2727 struct inode *inode = page->mapping->host;
2728 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2729 bool data_inode = btrfs_ino(BTRFS_I(inode))
2730 != BTRFS_BTREE_INODE_OBJECTID;
2731
2732 btrfs_debug(fs_info,
2733 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2734 (u64)bio->bi_iter.bi_sector, bio->bi_status,
2735 io_bio->mirror_num);
2736 tree = &BTRFS_I(inode)->io_tree;
2737 failure_tree = &BTRFS_I(inode)->io_failure_tree;
2738
2739 /* We always issue full-page reads, but if some block
2740 * in a page fails to read, blk_update_request() will
2741 * advance bv_offset and adjust bv_len to compensate.
2742 * Print a warning for nonzero offsets, and an error
2743 * if they don't add up to a full page. */
2744 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2745 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2746 btrfs_err(fs_info,
2747 "partial page read in btrfs with offset %u and length %u",
2748 bvec->bv_offset, bvec->bv_len);
2749 else
2750 btrfs_info(fs_info,
2751 "incomplete page read in btrfs with offset %u and length %u",
2752 bvec->bv_offset, bvec->bv_len);
2753 }
2754
2755 start = page_offset(page);
2756 end = start + bvec->bv_offset + bvec->bv_len - 1;
2757 len = bvec->bv_len;
2758
2759 mirror = io_bio->mirror_num;
2760 if (likely(uptodate)) {
2761 ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2762 page, start, end,
2763 mirror);
2764 if (ret)
2765 uptodate = 0;
2766 else
2767 clean_io_failure(BTRFS_I(inode)->root->fs_info,
2768 failure_tree, tree, start,
2769 page,
2770 btrfs_ino(BTRFS_I(inode)), 0);
2771 }
2772
2773 if (likely(uptodate))
2774 goto readpage_ok;
2775
2776 if (data_inode) {
2777
2778 /*
2779 * The generic bio_readpage_error handles errors the
2780 * following way: If possible, new read requests are
2781 * created and submitted and will end up in
2782 * end_bio_extent_readpage as well (if we're lucky,
2783 * not in the !uptodate case). In that case it returns
2784 * 0 and we just go on with the next page in our bio.
2785 * If it can't handle the error it will return -EIO and
2786 * we remain responsible for that page.
2787 */
2788 ret = bio_readpage_error(bio, offset, page, start, end,
2789 mirror);
2790 if (ret == 0) {
2791 uptodate = !bio->bi_status;
2792 offset += len;
2793 continue;
2794 }
2795 } else {
2796 struct extent_buffer *eb;
2797
2798 eb = (struct extent_buffer *)page->private;
2799 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
2800 eb->read_mirror = mirror;
2801 atomic_dec(&eb->io_pages);
2802 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
2803 &eb->bflags))
2804 btree_readahead_hook(eb, -EIO);
2805 }
2806 readpage_ok:
2807 if (likely(uptodate)) {
2808 loff_t i_size = i_size_read(inode);
2809 pgoff_t end_index = i_size >> PAGE_SHIFT;
2810 unsigned off;
2811
2812 /* Zero out the end if this page straddles i_size */
2813 off = offset_in_page(i_size);
2814 if (page->index == end_index && off)
2815 zero_user_segment(page, off, PAGE_SIZE);
2816 SetPageUptodate(page);
2817 } else {
2818 ClearPageUptodate(page);
2819 SetPageError(page);
2820 }
2821 unlock_page(page);
2822 offset += len;
2823
2824 if (unlikely(!uptodate)) {
2825 if (extent_len) {
2826 endio_readpage_release_extent(tree,
2827 extent_start,
2828 extent_len, 1);
2829 extent_start = 0;
2830 extent_len = 0;
2831 }
2832 endio_readpage_release_extent(tree, start,
2833 end - start + 1, 0);
2834 } else if (!extent_len) {
2835 extent_start = start;
2836 extent_len = end + 1 - start;
2837 } else if (extent_start + extent_len == start) {
2838 extent_len += end + 1 - start;
2839 } else {
2840 endio_readpage_release_extent(tree, extent_start,
2841 extent_len, uptodate);
2842 extent_start = start;
2843 extent_len = end + 1 - start;
2844 }
2845 }
2846
2847 if (extent_len)
2848 endio_readpage_release_extent(tree, extent_start, extent_len,
2849 uptodate);
2850 btrfs_io_bio_free_csum(io_bio);
2851 bio_put(bio);
2852 }
2853
2854 /*
2855 * Initialize the members up to but not including 'bio'. Use after allocating a
2856 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2857 * 'bio' because use of __GFP_ZERO is not supported.
2858 */
2859 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2860 {
2861 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2862 }
2863
2864 /*
2865 * The following helpers allocate a bio. As it's backed by a bioset, it'll
2866 * never fail. We're returning a bio right now but you can call btrfs_io_bio
2867 * for the appropriate container_of magic
2868 */
2869 struct bio *btrfs_bio_alloc(u64 first_byte)
2870 {
2871 struct bio *bio;
2872
2873 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2874 bio->bi_iter.bi_sector = first_byte >> 9;
2875 btrfs_io_bio_init(btrfs_io_bio(bio));
2876 return bio;
2877 }
2878
2879 struct bio *btrfs_bio_clone(struct bio *bio)
2880 {
2881 struct btrfs_io_bio *btrfs_bio;
2882 struct bio *new;
2883
2884 /* Bio allocation backed by a bioset does not fail */
2885 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2886 btrfs_bio = btrfs_io_bio(new);
2887 btrfs_io_bio_init(btrfs_bio);
2888 btrfs_bio->iter = bio->bi_iter;
2889 return new;
2890 }
2891
2892 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2893 {
2894 struct bio *bio;
2895
2896 /* Bio allocation backed by a bioset does not fail */
2897 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2898 btrfs_io_bio_init(btrfs_io_bio(bio));
2899 return bio;
2900 }
2901
2902 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2903 {
2904 struct bio *bio;
2905 struct btrfs_io_bio *btrfs_bio;
2906
2907 /* this will never fail when it's backed by a bioset */
2908 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2909 ASSERT(bio);
2910
2911 btrfs_bio = btrfs_io_bio(bio);
2912 btrfs_io_bio_init(btrfs_bio);
2913
2914 bio_trim(bio, offset >> 9, size >> 9);
2915 btrfs_bio->iter = bio->bi_iter;
2916 return bio;
2917 }
2918
2919 /*
2920 * @opf: bio REQ_OP_* and REQ_* flags as one value
2921 * @tree: tree so we can call our merge_bio hook
2922 * @wbc: optional writeback control for io accounting
2923 * @page: page to add to the bio
2924 * @pg_offset: offset of the new bio or to check whether we are adding
2925 * a contiguous page to the previous one
2926 * @size: portion of page that we want to write
2927 * @offset: starting offset in the page
2928 * @bdev: attach newly created bios to this bdev
2929 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
2930 * @end_io_func: end_io callback for new bio
2931 * @mirror_num: desired mirror to read/write
2932 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
2933 * @bio_flags: flags of the current bio to see if we can merge them
2934 */
2935 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2936 struct writeback_control *wbc,
2937 struct page *page, u64 offset,
2938 size_t size, unsigned long pg_offset,
2939 struct block_device *bdev,
2940 struct bio **bio_ret,
2941 bio_end_io_t end_io_func,
2942 int mirror_num,
2943 unsigned long prev_bio_flags,
2944 unsigned long bio_flags,
2945 bool force_bio_submit)
2946 {
2947 int ret = 0;
2948 struct bio *bio;
2949 size_t page_size = min_t(size_t, size, PAGE_SIZE);
2950 sector_t sector = offset >> 9;
2951
2952 ASSERT(bio_ret);
2953
2954 if (*bio_ret) {
2955 bool contig;
2956 bool can_merge = true;
2957
2958 bio = *bio_ret;
2959 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2960 contig = bio->bi_iter.bi_sector == sector;
2961 else
2962 contig = bio_end_sector(bio) == sector;
2963
2964 ASSERT(tree->ops);
2965 if (btrfs_bio_fits_in_stripe(page, page_size, bio, bio_flags))
2966 can_merge = false;
2967
2968 if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2969 force_bio_submit ||
2970 bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2971 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2972 if (ret < 0) {
2973 *bio_ret = NULL;
2974 return ret;
2975 }
2976 bio = NULL;
2977 } else {
2978 if (wbc)
2979 wbc_account_cgroup_owner(wbc, page, page_size);
2980 return 0;
2981 }
2982 }
2983
2984 bio = btrfs_bio_alloc(offset);
2985 bio_set_dev(bio, bdev);
2986 bio_add_page(bio, page, page_size, pg_offset);
2987 bio->bi_end_io = end_io_func;
2988 bio->bi_private = tree;
2989 bio->bi_write_hint = page->mapping->host->i_write_hint;
2990 bio->bi_opf = opf;
2991 if (wbc) {
2992 wbc_init_bio(wbc, bio);
2993 wbc_account_cgroup_owner(wbc, page, page_size);
2994 }
2995
2996 *bio_ret = bio;
2997
2998 return ret;
2999 }
3000
3001 static void attach_extent_buffer_page(struct extent_buffer *eb,
3002 struct page *page)
3003 {
3004 if (!PagePrivate(page)) {
3005 SetPagePrivate(page);
3006 get_page(page);
3007 set_page_private(page, (unsigned long)eb);
3008 } else {
3009 WARN_ON(page->private != (unsigned long)eb);
3010 }
3011 }
3012
3013 void set_page_extent_mapped(struct page *page)
3014 {
3015 if (!PagePrivate(page)) {
3016 SetPagePrivate(page);
3017 get_page(page);
3018 set_page_private(page, EXTENT_PAGE_PRIVATE);
3019 }
3020 }
3021
3022 static struct extent_map *
3023 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3024 u64 start, u64 len, get_extent_t *get_extent,
3025 struct extent_map **em_cached)
3026 {
3027 struct extent_map *em;
3028
3029 if (em_cached && *em_cached) {
3030 em = *em_cached;
3031 if (extent_map_in_tree(em) && start >= em->start &&
3032 start < extent_map_end(em)) {
3033 refcount_inc(&em->refs);
3034 return em;
3035 }
3036
3037 free_extent_map(em);
3038 *em_cached = NULL;
3039 }
3040
3041 em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
3042 if (em_cached && !IS_ERR_OR_NULL(em)) {
3043 BUG_ON(*em_cached);
3044 refcount_inc(&em->refs);
3045 *em_cached = em;
3046 }
3047 return em;
3048 }
3049 /*
3050 * basic readpage implementation. Locked extent state structs are inserted
3051 * into the tree that are removed when the IO is done (by the end_io
3052 * handlers)
3053 * XXX JDM: This needs looking at to ensure proper page locking
3054 * return 0 on success, otherwise return error
3055 */
3056 static int __do_readpage(struct extent_io_tree *tree,
3057 struct page *page,
3058 get_extent_t *get_extent,
3059 struct extent_map **em_cached,
3060 struct bio **bio, int mirror_num,
3061 unsigned long *bio_flags, unsigned int read_flags,
3062 u64 *prev_em_start)
3063 {
3064 struct inode *inode = page->mapping->host;
3065 u64 start = page_offset(page);
3066 const u64 end = start + PAGE_SIZE - 1;
3067 u64 cur = start;
3068 u64 extent_offset;
3069 u64 last_byte = i_size_read(inode);
3070 u64 block_start;
3071 u64 cur_end;
3072 struct extent_map *em;
3073 struct block_device *bdev;
3074 int ret = 0;
3075 int nr = 0;
3076 size_t pg_offset = 0;
3077 size_t iosize;
3078 size_t disk_io_size;
3079 size_t blocksize = inode->i_sb->s_blocksize;
3080 unsigned long this_bio_flag = 0;
3081
3082 set_page_extent_mapped(page);
3083
3084 if (!PageUptodate(page)) {
3085 if (cleancache_get_page(page) == 0) {
3086 BUG_ON(blocksize != PAGE_SIZE);
3087 unlock_extent(tree, start, end);
3088 goto out;
3089 }
3090 }
3091
3092 if (page->index == last_byte >> PAGE_SHIFT) {
3093 char *userpage;
3094 size_t zero_offset = offset_in_page(last_byte);
3095
3096 if (zero_offset) {
3097 iosize = PAGE_SIZE - zero_offset;
3098 userpage = kmap_atomic(page);
3099 memset(userpage + zero_offset, 0, iosize);
3100 flush_dcache_page(page);
3101 kunmap_atomic(userpage);
3102 }
3103 }
3104 while (cur <= end) {
3105 bool force_bio_submit = false;
3106 u64 offset;
3107
3108 if (cur >= last_byte) {
3109 char *userpage;
3110 struct extent_state *cached = NULL;
3111
3112 iosize = PAGE_SIZE - pg_offset;
3113 userpage = kmap_atomic(page);
3114 memset(userpage + pg_offset, 0, iosize);
3115 flush_dcache_page(page);
3116 kunmap_atomic(userpage);
3117 set_extent_uptodate(tree, cur, cur + iosize - 1,
3118 &cached, GFP_NOFS);
3119 unlock_extent_cached(tree, cur,
3120 cur + iosize - 1, &cached);
3121 break;
3122 }
3123 em = __get_extent_map(inode, page, pg_offset, cur,
3124 end - cur + 1, get_extent, em_cached);
3125 if (IS_ERR_OR_NULL(em)) {
3126 SetPageError(page);
3127 unlock_extent(tree, cur, end);
3128 break;
3129 }
3130 extent_offset = cur - em->start;
3131 BUG_ON(extent_map_end(em) <= cur);
3132 BUG_ON(end < cur);
3133
3134 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
3135 this_bio_flag |= EXTENT_BIO_COMPRESSED;
3136 extent_set_compress_type(&this_bio_flag,
3137 em->compress_type);
3138 }
3139
3140 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3141 cur_end = min(extent_map_end(em) - 1, end);
3142 iosize = ALIGN(iosize, blocksize);
3143 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
3144 disk_io_size = em->block_len;
3145 offset = em->block_start;
3146 } else {
3147 offset = em->block_start + extent_offset;
3148 disk_io_size = iosize;
3149 }
3150 bdev = em->bdev;
3151 block_start = em->block_start;
3152 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3153 block_start = EXTENT_MAP_HOLE;
3154
3155 /*
3156 * If we have a file range that points to a compressed extent
3157 * and it's followed by a consecutive file range that points to
3158 * to the same compressed extent (possibly with a different
3159 * offset and/or length, so it either points to the whole extent
3160 * or only part of it), we must make sure we do not submit a
3161 * single bio to populate the pages for the 2 ranges because
3162 * this makes the compressed extent read zero out the pages
3163 * belonging to the 2nd range. Imagine the following scenario:
3164 *
3165 * File layout
3166 * [0 - 8K] [8K - 24K]
3167 * | |
3168 * | |
3169 * points to extent X, points to extent X,
3170 * offset 4K, length of 8K offset 0, length 16K
3171 *
3172 * [extent X, compressed length = 4K uncompressed length = 16K]
3173 *
3174 * If the bio to read the compressed extent covers both ranges,
3175 * it will decompress extent X into the pages belonging to the
3176 * first range and then it will stop, zeroing out the remaining
3177 * pages that belong to the other range that points to extent X.
3178 * So here we make sure we submit 2 bios, one for the first
3179 * range and another one for the third range. Both will target
3180 * the same physical extent from disk, but we can't currently
3181 * make the compressed bio endio callback populate the pages
3182 * for both ranges because each compressed bio is tightly
3183 * coupled with a single extent map, and each range can have
3184 * an extent map with a different offset value relative to the
3185 * uncompressed data of our extent and different lengths. This
3186 * is a corner case so we prioritize correctness over
3187 * non-optimal behavior (submitting 2 bios for the same extent).
3188 */
3189 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3190 prev_em_start && *prev_em_start != (u64)-1 &&
3191 *prev_em_start != em->start)
3192 force_bio_submit = true;
3193
3194 if (prev_em_start)
3195 *prev_em_start = em->start;
3196
3197 free_extent_map(em);
3198 em = NULL;
3199
3200 /* we've found a hole, just zero and go on */
3201 if (block_start == EXTENT_MAP_HOLE) {
3202 char *userpage;
3203 struct extent_state *cached = NULL;
3204
3205 userpage = kmap_atomic(page);
3206 memset(userpage + pg_offset, 0, iosize);
3207 flush_dcache_page(page);
3208 kunmap_atomic(userpage);
3209
3210 set_extent_uptodate(tree, cur, cur + iosize - 1,
3211 &cached, GFP_NOFS);
3212 unlock_extent_cached(tree, cur,
3213 cur + iosize - 1, &cached);
3214 cur = cur + iosize;
3215 pg_offset += iosize;
3216 continue;
3217 }
3218 /* the get_extent function already copied into the page */
3219 if (test_range_bit(tree, cur, cur_end,
3220 EXTENT_UPTODATE, 1, NULL)) {
3221 check_page_uptodate(tree, page);
3222 unlock_extent(tree, cur, cur + iosize - 1);
3223 cur = cur + iosize;
3224 pg_offset += iosize;
3225 continue;
3226 }
3227 /* we have an inline extent but it didn't get marked up
3228 * to date. Error out
3229 */
3230 if (block_start == EXTENT_MAP_INLINE) {
3231 SetPageError(page);
3232 unlock_extent(tree, cur, cur + iosize - 1);
3233 cur = cur + iosize;
3234 pg_offset += iosize;
3235 continue;
3236 }
3237
3238 ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3239 page, offset, disk_io_size,
3240 pg_offset, bdev, bio,
3241 end_bio_extent_readpage, mirror_num,
3242 *bio_flags,
3243 this_bio_flag,
3244 force_bio_submit);
3245 if (!ret) {
3246 nr++;
3247 *bio_flags = this_bio_flag;
3248 } else {
3249 SetPageError(page);
3250 unlock_extent(tree, cur, cur + iosize - 1);
3251 goto out;
3252 }
3253 cur = cur + iosize;
3254 pg_offset += iosize;
3255 }
3256 out:
3257 if (!nr) {
3258 if (!PageError(page))
3259 SetPageUptodate(page);
3260 unlock_page(page);
3261 }
3262 return ret;
3263 }
3264
3265 static inline void contiguous_readpages(struct extent_io_tree *tree,
3266 struct page *pages[], int nr_pages,
3267 u64 start, u64 end,
3268 struct extent_map **em_cached,
3269 struct bio **bio,
3270 unsigned long *bio_flags,
3271 u64 *prev_em_start)
3272 {
3273 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3274 int index;
3275
3276 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3277
3278 for (index = 0; index < nr_pages; index++) {
3279 __do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3280 bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3281 put_page(pages[index]);
3282 }
3283 }
3284
3285 static int __extent_read_full_page(struct extent_io_tree *tree,
3286 struct page *page,
3287 get_extent_t *get_extent,
3288 struct bio **bio, int mirror_num,
3289 unsigned long *bio_flags,
3290 unsigned int read_flags)
3291 {
3292 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3293 u64 start = page_offset(page);
3294 u64 end = start + PAGE_SIZE - 1;
3295 int ret;
3296
3297 btrfs_lock_and_flush_ordered_range(tree, inode, start, end, NULL);
3298
3299 ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3300 bio_flags, read_flags, NULL);
3301 return ret;
3302 }
3303
3304 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3305 get_extent_t *get_extent, int mirror_num)
3306 {
3307 struct bio *bio = NULL;
3308 unsigned long bio_flags = 0;
3309 int ret;
3310
3311 ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3312 &bio_flags, 0);
3313 if (bio)
3314 ret = submit_one_bio(bio, mirror_num, bio_flags);
3315 return ret;
3316 }
3317
3318 static void update_nr_written(struct writeback_control *wbc,
3319 unsigned long nr_written)
3320 {
3321 wbc->nr_to_write -= nr_written;
3322 }
3323
3324 /*
3325 * helper for __extent_writepage, doing all of the delayed allocation setup.
3326 *
3327 * This returns 1 if btrfs_run_delalloc_range function did all the work required
3328 * to write the page (copy into inline extent). In this case the IO has
3329 * been started and the page is already unlocked.
3330 *
3331 * This returns 0 if all went well (page still locked)
3332 * This returns < 0 if there were errors (page still locked)
3333 */
3334 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3335 struct page *page, struct writeback_control *wbc,
3336 u64 delalloc_start, unsigned long *nr_written)
3337 {
3338 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3339 bool found;
3340 u64 delalloc_to_write = 0;
3341 u64 delalloc_end = 0;
3342 int ret;
3343 int page_started = 0;
3344
3345
3346 while (delalloc_end < page_end) {
3347 found = find_lock_delalloc_range(inode, page,
3348 &delalloc_start,
3349 &delalloc_end);
3350 if (!found) {
3351 delalloc_start = delalloc_end + 1;
3352 continue;
3353 }
3354 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3355 delalloc_end, &page_started, nr_written, wbc);
3356 if (ret) {
3357 SetPageError(page);
3358 /*
3359 * btrfs_run_delalloc_range should return < 0 for error
3360 * but just in case, we use > 0 here meaning the IO is
3361 * started, so we don't want to return > 0 unless
3362 * things are going well.
3363 */
3364 ret = ret < 0 ? ret : -EIO;
3365 goto done;
3366 }
3367 /*
3368 * delalloc_end is already one less than the total length, so
3369 * we don't subtract one from PAGE_SIZE
3370 */
3371 delalloc_to_write += (delalloc_end - delalloc_start +
3372 PAGE_SIZE) >> PAGE_SHIFT;
3373 delalloc_start = delalloc_end + 1;
3374 }
3375 if (wbc->nr_to_write < delalloc_to_write) {
3376 int thresh = 8192;
3377
3378 if (delalloc_to_write < thresh * 2)
3379 thresh = delalloc_to_write;
3380 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3381 thresh);
3382 }
3383
3384 /* did the fill delalloc function already unlock and start
3385 * the IO?
3386 */
3387 if (page_started) {
3388 /*
3389 * we've unlocked the page, so we can't update
3390 * the mapping's writeback index, just update
3391 * nr_to_write.
3392 */
3393 wbc->nr_to_write -= *nr_written;
3394 return 1;
3395 }
3396
3397 ret = 0;
3398
3399 done:
3400 return ret;
3401 }
3402
3403 /*
3404 * helper for __extent_writepage. This calls the writepage start hooks,
3405 * and does the loop to map the page into extents and bios.
3406 *
3407 * We return 1 if the IO is started and the page is unlocked,
3408 * 0 if all went well (page still locked)
3409 * < 0 if there were errors (page still locked)
3410 */
3411 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3412 struct page *page,
3413 struct writeback_control *wbc,
3414 struct extent_page_data *epd,
3415 loff_t i_size,
3416 unsigned long nr_written,
3417 unsigned int write_flags, int *nr_ret)
3418 {
3419 struct extent_io_tree *tree = epd->tree;
3420 u64 start = page_offset(page);
3421 u64 page_end = start + PAGE_SIZE - 1;
3422 u64 end;
3423 u64 cur = start;
3424 u64 extent_offset;
3425 u64 block_start;
3426 u64 iosize;
3427 struct extent_map *em;
3428 struct block_device *bdev;
3429 size_t pg_offset = 0;
3430 size_t blocksize;
3431 int ret = 0;
3432 int nr = 0;
3433 bool compressed;
3434
3435 ret = btrfs_writepage_cow_fixup(page, start, page_end);
3436 if (ret) {
3437 /* Fixup worker will requeue */
3438 if (ret == -EBUSY)
3439 wbc->pages_skipped++;
3440 else
3441 redirty_page_for_writepage(wbc, page);
3442
3443 update_nr_written(wbc, nr_written);
3444 unlock_page(page);
3445 return 1;
3446 }
3447
3448 /*
3449 * we don't want to touch the inode after unlocking the page,
3450 * so we update the mapping writeback index now
3451 */
3452 update_nr_written(wbc, nr_written + 1);
3453
3454 end = page_end;
3455 if (i_size <= start) {
3456 btrfs_writepage_endio_finish_ordered(page, start, page_end, 1);
3457 goto done;
3458 }
3459
3460 blocksize = inode->i_sb->s_blocksize;
3461
3462 while (cur <= end) {
3463 u64 em_end;
3464 u64 offset;
3465
3466 if (cur >= i_size) {
3467 btrfs_writepage_endio_finish_ordered(page, cur,
3468 page_end, 1);
3469 break;
3470 }
3471 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3472 end - cur + 1, 1);
3473 if (IS_ERR_OR_NULL(em)) {
3474 SetPageError(page);
3475 ret = PTR_ERR_OR_ZERO(em);
3476 break;
3477 }
3478
3479 extent_offset = cur - em->start;
3480 em_end = extent_map_end(em);
3481 BUG_ON(em_end <= cur);
3482 BUG_ON(end < cur);
3483 iosize = min(em_end - cur, end - cur + 1);
3484 iosize = ALIGN(iosize, blocksize);
3485 offset = em->block_start + extent_offset;
3486 bdev = em->bdev;
3487 block_start = em->block_start;
3488 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3489 free_extent_map(em);
3490 em = NULL;
3491
3492 /*
3493 * compressed and inline extents are written through other
3494 * paths in the FS
3495 */
3496 if (compressed || block_start == EXTENT_MAP_HOLE ||
3497 block_start == EXTENT_MAP_INLINE) {
3498 /*
3499 * end_io notification does not happen here for
3500 * compressed extents
3501 */
3502 if (!compressed)
3503 btrfs_writepage_endio_finish_ordered(page, cur,
3504 cur + iosize - 1,
3505 1);
3506 else if (compressed) {
3507 /* we don't want to end_page_writeback on
3508 * a compressed extent. this happens
3509 * elsewhere
3510 */
3511 nr++;
3512 }
3513
3514 cur += iosize;
3515 pg_offset += iosize;
3516 continue;
3517 }
3518
3519 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3520 if (!PageWriteback(page)) {
3521 btrfs_err(BTRFS_I(inode)->root->fs_info,
3522 "page %lu not writeback, cur %llu end %llu",
3523 page->index, cur, end);
3524 }
3525
3526 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3527 page, offset, iosize, pg_offset,
3528 bdev, &epd->bio,
3529 end_bio_extent_writepage,
3530 0, 0, 0, false);
3531 if (ret) {
3532 SetPageError(page);
3533 if (PageWriteback(page))
3534 end_page_writeback(page);
3535 }
3536
3537 cur = cur + iosize;
3538 pg_offset += iosize;
3539 nr++;
3540 }
3541 done:
3542 *nr_ret = nr;
3543 return ret;
3544 }
3545
3546 /*
3547 * the writepage semantics are similar to regular writepage. extent
3548 * records are inserted to lock ranges in the tree, and as dirty areas
3549 * are found, they are marked writeback. Then the lock bits are removed
3550 * and the end_io handler clears the writeback ranges
3551 *
3552 * Return 0 if everything goes well.
3553 * Return <0 for error.
3554 */
3555 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3556 struct extent_page_data *epd)
3557 {
3558 struct inode *inode = page->mapping->host;
3559 u64 start = page_offset(page);
3560 u64 page_end = start + PAGE_SIZE - 1;
3561 int ret;
3562 int nr = 0;
3563 size_t pg_offset = 0;
3564 loff_t i_size = i_size_read(inode);
3565 unsigned long end_index = i_size >> PAGE_SHIFT;
3566 unsigned int write_flags = 0;
3567 unsigned long nr_written = 0;
3568
3569 write_flags = wbc_to_write_flags(wbc);
3570
3571 trace___extent_writepage(page, inode, wbc);
3572
3573 WARN_ON(!PageLocked(page));
3574
3575 ClearPageError(page);
3576
3577 pg_offset = offset_in_page(i_size);
3578 if (page->index > end_index ||
3579 (page->index == end_index && !pg_offset)) {
3580 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3581 unlock_page(page);
3582 return 0;
3583 }
3584
3585 if (page->index == end_index) {
3586 char *userpage;
3587
3588 userpage = kmap_atomic(page);
3589 memset(userpage + pg_offset, 0,
3590 PAGE_SIZE - pg_offset);
3591 kunmap_atomic(userpage);
3592 flush_dcache_page(page);
3593 }
3594
3595 pg_offset = 0;
3596
3597 set_page_extent_mapped(page);
3598
3599 if (!epd->extent_locked) {
3600 ret = writepage_delalloc(inode, page, wbc, start, &nr_written);
3601 if (ret == 1)
3602 goto done_unlocked;
3603 if (ret)
3604 goto done;
3605 }
3606
3607 ret = __extent_writepage_io(inode, page, wbc, epd,
3608 i_size, nr_written, write_flags, &nr);
3609 if (ret == 1)
3610 goto done_unlocked;
3611
3612 done:
3613 if (nr == 0) {
3614 /* make sure the mapping tag for page dirty gets cleared */
3615 set_page_writeback(page);
3616 end_page_writeback(page);
3617 }
3618 if (PageError(page)) {
3619 ret = ret < 0 ? ret : -EIO;
3620 end_extent_writepage(page, ret, start, page_end);
3621 }
3622 unlock_page(page);
3623 ASSERT(ret <= 0);
3624 return ret;
3625
3626 done_unlocked:
3627 return 0;
3628 }
3629
3630 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3631 {
3632 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3633 TASK_UNINTERRUPTIBLE);
3634 }
3635
3636 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3637 {
3638 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3639 smp_mb__after_atomic();
3640 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3641 }
3642
3643 /*
3644 * Lock eb pages and flush the bio if we can't the locks
3645 *
3646 * Return 0 if nothing went wrong
3647 * Return >0 is same as 0, except bio is not submitted
3648 * Return <0 if something went wrong, no page is locked
3649 */
3650 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
3651 struct extent_page_data *epd)
3652 {
3653 struct btrfs_fs_info *fs_info = eb->fs_info;
3654 int i, num_pages, failed_page_nr;
3655 int flush = 0;
3656 int ret = 0;
3657
3658 if (!btrfs_try_tree_write_lock(eb)) {
3659 ret = flush_write_bio(epd);
3660 if (ret < 0)
3661 return ret;
3662 flush = 1;
3663 btrfs_tree_lock(eb);
3664 }
3665
3666 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3667 btrfs_tree_unlock(eb);
3668 if (!epd->sync_io)
3669 return 0;
3670 if (!flush) {
3671 ret = flush_write_bio(epd);
3672 if (ret < 0)
3673 return ret;
3674 flush = 1;
3675 }
3676 while (1) {
3677 wait_on_extent_buffer_writeback(eb);
3678 btrfs_tree_lock(eb);
3679 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3680 break;
3681 btrfs_tree_unlock(eb);
3682 }
3683 }
3684
3685 /*
3686 * We need to do this to prevent races in people who check if the eb is
3687 * under IO since we can end up having no IO bits set for a short period
3688 * of time.
3689 */
3690 spin_lock(&eb->refs_lock);
3691 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3692 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3693 spin_unlock(&eb->refs_lock);
3694 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3695 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3696 -eb->len,
3697 fs_info->dirty_metadata_batch);
3698 ret = 1;
3699 } else {
3700 spin_unlock(&eb->refs_lock);
3701 }
3702
3703 btrfs_tree_unlock(eb);
3704
3705 if (!ret)
3706 return ret;
3707
3708 num_pages = num_extent_pages(eb);
3709 for (i = 0; i < num_pages; i++) {
3710 struct page *p = eb->pages[i];
3711
3712 if (!trylock_page(p)) {
3713 if (!flush) {
3714 int err;
3715
3716 err = flush_write_bio(epd);
3717 if (err < 0) {
3718 ret = err;
3719 failed_page_nr = i;
3720 goto err_unlock;
3721 }
3722 flush = 1;
3723 }
3724 lock_page(p);
3725 }
3726 }
3727
3728 return ret;
3729 err_unlock:
3730 /* Unlock already locked pages */
3731 for (i = 0; i < failed_page_nr; i++)
3732 unlock_page(eb->pages[i]);
3733 /*
3734 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3735 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3736 * be made and undo everything done before.
3737 */
3738 btrfs_tree_lock(eb);
3739 spin_lock(&eb->refs_lock);
3740 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3741 end_extent_buffer_writeback(eb);
3742 spin_unlock(&eb->refs_lock);
3743 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3744 fs_info->dirty_metadata_batch);
3745 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3746 btrfs_tree_unlock(eb);
3747 return ret;
3748 }
3749
3750 static void set_btree_ioerr(struct page *page)
3751 {
3752 struct extent_buffer *eb = (struct extent_buffer *)page->private;
3753 struct btrfs_fs_info *fs_info;
3754
3755 SetPageError(page);
3756 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3757 return;
3758
3759 /*
3760 * If we error out, we should add back the dirty_metadata_bytes
3761 * to make it consistent.
3762 */
3763 fs_info = eb->fs_info;
3764 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3765 eb->len, fs_info->dirty_metadata_batch);
3766
3767 /*
3768 * If writeback for a btree extent that doesn't belong to a log tree
3769 * failed, increment the counter transaction->eb_write_errors.
3770 * We do this because while the transaction is running and before it's
3771 * committing (when we call filemap_fdata[write|wait]_range against
3772 * the btree inode), we might have
3773 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3774 * returns an error or an error happens during writeback, when we're
3775 * committing the transaction we wouldn't know about it, since the pages
3776 * can be no longer dirty nor marked anymore for writeback (if a
3777 * subsequent modification to the extent buffer didn't happen before the
3778 * transaction commit), which makes filemap_fdata[write|wait]_range not
3779 * able to find the pages tagged with SetPageError at transaction
3780 * commit time. So if this happens we must abort the transaction,
3781 * otherwise we commit a super block with btree roots that point to
3782 * btree nodes/leafs whose content on disk is invalid - either garbage
3783 * or the content of some node/leaf from a past generation that got
3784 * cowed or deleted and is no longer valid.
3785 *
3786 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3787 * not be enough - we need to distinguish between log tree extents vs
3788 * non-log tree extents, and the next filemap_fdatawait_range() call
3789 * will catch and clear such errors in the mapping - and that call might
3790 * be from a log sync and not from a transaction commit. Also, checking
3791 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3792 * not done and would not be reliable - the eb might have been released
3793 * from memory and reading it back again means that flag would not be
3794 * set (since it's a runtime flag, not persisted on disk).
3795 *
3796 * Using the flags below in the btree inode also makes us achieve the
3797 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3798 * writeback for all dirty pages and before filemap_fdatawait_range()
3799 * is called, the writeback for all dirty pages had already finished
3800 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3801 * filemap_fdatawait_range() would return success, as it could not know
3802 * that writeback errors happened (the pages were no longer tagged for
3803 * writeback).
3804 */
3805 switch (eb->log_index) {
3806 case -1:
3807 set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3808 break;
3809 case 0:
3810 set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3811 break;
3812 case 1:
3813 set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3814 break;
3815 default:
3816 BUG(); /* unexpected, logic error */
3817 }
3818 }
3819
3820 static void end_bio_extent_buffer_writepage(struct bio *bio)
3821 {
3822 struct bio_vec *bvec;
3823 struct extent_buffer *eb;
3824 int done;
3825 struct bvec_iter_all iter_all;
3826
3827 ASSERT(!bio_flagged(bio, BIO_CLONED));
3828 bio_for_each_segment_all(bvec, bio, iter_all) {
3829 struct page *page = bvec->bv_page;
3830
3831 eb = (struct extent_buffer *)page->private;
3832 BUG_ON(!eb);
3833 done = atomic_dec_and_test(&eb->io_pages);
3834
3835 if (bio->bi_status ||
3836 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3837 ClearPageUptodate(page);
3838 set_btree_ioerr(page);
3839 }
3840
3841 end_page_writeback(page);
3842
3843 if (!done)
3844 continue;
3845
3846 end_extent_buffer_writeback(eb);
3847 }
3848
3849 bio_put(bio);
3850 }
3851
3852 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3853 struct writeback_control *wbc,
3854 struct extent_page_data *epd)
3855 {
3856 struct btrfs_fs_info *fs_info = eb->fs_info;
3857 struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3858 struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3859 u64 offset = eb->start;
3860 u32 nritems;
3861 int i, num_pages;
3862 unsigned long start, end;
3863 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3864 int ret = 0;
3865
3866 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3867 num_pages = num_extent_pages(eb);
3868 atomic_set(&eb->io_pages, num_pages);
3869
3870 /* set btree blocks beyond nritems with 0 to avoid stale content. */
3871 nritems = btrfs_header_nritems(eb);
3872 if (btrfs_header_level(eb) > 0) {
3873 end = btrfs_node_key_ptr_offset(nritems);
3874
3875 memzero_extent_buffer(eb, end, eb->len - end);
3876 } else {
3877 /*
3878 * leaf:
3879 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3880 */
3881 start = btrfs_item_nr_offset(nritems);
3882 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
3883 memzero_extent_buffer(eb, start, end - start);
3884 }
3885
3886 for (i = 0; i < num_pages; i++) {
3887 struct page *p = eb->pages[i];
3888
3889 clear_page_dirty_for_io(p);
3890 set_page_writeback(p);
3891 ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3892 p, offset, PAGE_SIZE, 0, bdev,
3893 &epd->bio,
3894 end_bio_extent_buffer_writepage,
3895 0, 0, 0, false);
3896 if (ret) {
3897 set_btree_ioerr(p);
3898 if (PageWriteback(p))
3899 end_page_writeback(p);
3900 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3901 end_extent_buffer_writeback(eb);
3902 ret = -EIO;
3903 break;
3904 }
3905 offset += PAGE_SIZE;
3906 update_nr_written(wbc, 1);
3907 unlock_page(p);
3908 }
3909
3910 if (unlikely(ret)) {
3911 for (; i < num_pages; i++) {
3912 struct page *p = eb->pages[i];
3913 clear_page_dirty_for_io(p);
3914 unlock_page(p);
3915 }
3916 }
3917
3918 return ret;
3919 }
3920
3921 int btree_write_cache_pages(struct address_space *mapping,
3922 struct writeback_control *wbc)
3923 {
3924 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3925 struct extent_buffer *eb, *prev_eb = NULL;
3926 struct extent_page_data epd = {
3927 .bio = NULL,
3928 .tree = tree,
3929 .extent_locked = 0,
3930 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3931 };
3932 int ret = 0;
3933 int done = 0;
3934 int nr_to_write_done = 0;
3935 struct pagevec pvec;
3936 int nr_pages;
3937 pgoff_t index;
3938 pgoff_t end; /* Inclusive */
3939 int scanned = 0;
3940 xa_mark_t tag;
3941
3942 pagevec_init(&pvec);
3943 if (wbc->range_cyclic) {
3944 index = mapping->writeback_index; /* Start from prev offset */
3945 end = -1;
3946 } else {
3947 index = wbc->range_start >> PAGE_SHIFT;
3948 end = wbc->range_end >> PAGE_SHIFT;
3949 scanned = 1;
3950 }
3951 if (wbc->sync_mode == WB_SYNC_ALL)
3952 tag = PAGECACHE_TAG_TOWRITE;
3953 else
3954 tag = PAGECACHE_TAG_DIRTY;
3955 retry:
3956 if (wbc->sync_mode == WB_SYNC_ALL)
3957 tag_pages_for_writeback(mapping, index, end);
3958 while (!done && !nr_to_write_done && (index <= end) &&
3959 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3960 tag))) {
3961 unsigned i;
3962
3963 scanned = 1;
3964 for (i = 0; i < nr_pages; i++) {
3965 struct page *page = pvec.pages[i];
3966
3967 if (!PagePrivate(page))
3968 continue;
3969
3970 spin_lock(&mapping->private_lock);
3971 if (!PagePrivate(page)) {
3972 spin_unlock(&mapping->private_lock);
3973 continue;
3974 }
3975
3976 eb = (struct extent_buffer *)page->private;
3977
3978 /*
3979 * Shouldn't happen and normally this would be a BUG_ON
3980 * but no sense in crashing the users box for something
3981 * we can survive anyway.
3982 */
3983 if (WARN_ON(!eb)) {
3984 spin_unlock(&mapping->private_lock);
3985 continue;
3986 }
3987
3988 if (eb == prev_eb) {
3989 spin_unlock(&mapping->private_lock);
3990 continue;
3991 }
3992
3993 ret = atomic_inc_not_zero(&eb->refs);
3994 spin_unlock(&mapping->private_lock);
3995 if (!ret)
3996 continue;
3997
3998 prev_eb = eb;
3999 ret = lock_extent_buffer_for_io(eb, &epd);
4000 if (!ret) {
4001 free_extent_buffer(eb);
4002 continue;
4003 } else if (ret < 0) {
4004 done = 1;
4005 free_extent_buffer(eb);
4006 break;
4007 }
4008
4009 ret = write_one_eb(eb, wbc, &epd);
4010 if (ret) {
4011 done = 1;
4012 free_extent_buffer(eb);
4013 break;
4014 }
4015 free_extent_buffer(eb);
4016
4017 /*
4018 * the filesystem may choose to bump up nr_to_write.
4019 * We have to make sure to honor the new nr_to_write
4020 * at any time
4021 */
4022 nr_to_write_done = wbc->nr_to_write <= 0;
4023 }
4024 pagevec_release(&pvec);
4025 cond_resched();
4026 }
4027 if (!scanned && !done) {
4028 /*
4029 * We hit the last page and there is more work to be done: wrap
4030 * back to the start of the file
4031 */
4032 scanned = 1;
4033 index = 0;
4034 goto retry;
4035 }
4036 ASSERT(ret <= 0);
4037 if (ret < 0) {
4038 end_write_bio(&epd, ret);
4039 return ret;
4040 }
4041 ret = flush_write_bio(&epd);
4042 return ret;
4043 }
4044
4045 /**
4046 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
4047 * @mapping: address space structure to write
4048 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4049 * @data: data passed to __extent_writepage function
4050 *
4051 * If a page is already under I/O, write_cache_pages() skips it, even
4052 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4053 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4054 * and msync() need to guarantee that all the data which was dirty at the time
4055 * the call was made get new I/O started against them. If wbc->sync_mode is
4056 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4057 * existing IO to complete.
4058 */
4059 static int extent_write_cache_pages(struct address_space *mapping,
4060 struct writeback_control *wbc,
4061 struct extent_page_data *epd)
4062 {
4063 struct inode *inode = mapping->host;
4064 int ret = 0;
4065 int done = 0;
4066 int nr_to_write_done = 0;
4067 struct pagevec pvec;
4068 int nr_pages;
4069 pgoff_t index;
4070 pgoff_t end; /* Inclusive */
4071 pgoff_t done_index;
4072 int range_whole = 0;
4073 int scanned = 0;
4074 xa_mark_t tag;
4075
4076 /*
4077 * We have to hold onto the inode so that ordered extents can do their
4078 * work when the IO finishes. The alternative to this is failing to add
4079 * an ordered extent if the igrab() fails there and that is a huge pain
4080 * to deal with, so instead just hold onto the inode throughout the
4081 * writepages operation. If it fails here we are freeing up the inode
4082 * anyway and we'd rather not waste our time writing out stuff that is
4083 * going to be truncated anyway.
4084 */
4085 if (!igrab(inode))
4086 return 0;
4087
4088 pagevec_init(&pvec);
4089 if (wbc->range_cyclic) {
4090 index = mapping->writeback_index; /* Start from prev offset */
4091 end = -1;
4092 } else {
4093 index = wbc->range_start >> PAGE_SHIFT;
4094 end = wbc->range_end >> PAGE_SHIFT;
4095 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4096 range_whole = 1;
4097 scanned = 1;
4098 }
4099
4100 /*
4101 * We do the tagged writepage as long as the snapshot flush bit is set
4102 * and we are the first one who do the filemap_flush() on this inode.
4103 *
4104 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4105 * not race in and drop the bit.
4106 */
4107 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4108 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4109 &BTRFS_I(inode)->runtime_flags))
4110 wbc->tagged_writepages = 1;
4111
4112 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4113 tag = PAGECACHE_TAG_TOWRITE;
4114 else
4115 tag = PAGECACHE_TAG_DIRTY;
4116 retry:
4117 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4118 tag_pages_for_writeback(mapping, index, end);
4119 done_index = index;
4120 while (!done && !nr_to_write_done && (index <= end) &&
4121 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4122 &index, end, tag))) {
4123 unsigned i;
4124
4125 scanned = 1;
4126 for (i = 0; i < nr_pages; i++) {
4127 struct page *page = pvec.pages[i];
4128
4129 done_index = page->index;
4130 /*
4131 * At this point we hold neither the i_pages lock nor
4132 * the page lock: the page may be truncated or
4133 * invalidated (changing page->mapping to NULL),
4134 * or even swizzled back from swapper_space to
4135 * tmpfs file mapping
4136 */
4137 if (!trylock_page(page)) {
4138 ret = flush_write_bio(epd);
4139 BUG_ON(ret < 0);
4140 lock_page(page);
4141 }
4142
4143 if (unlikely(page->mapping != mapping)) {
4144 unlock_page(page);
4145 continue;
4146 }
4147
4148 if (wbc->sync_mode != WB_SYNC_NONE) {
4149 if (PageWriteback(page)) {
4150 ret = flush_write_bio(epd);
4151 BUG_ON(ret < 0);
4152 }
4153 wait_on_page_writeback(page);
4154 }
4155
4156 if (PageWriteback(page) ||
4157 !clear_page_dirty_for_io(page)) {
4158 unlock_page(page);
4159 continue;
4160 }
4161
4162 ret = __extent_writepage(page, wbc, epd);
4163 if (ret < 0) {
4164 /*
4165 * done_index is set past this page,
4166 * so media errors will not choke
4167 * background writeout for the entire
4168 * file. This has consequences for
4169 * range_cyclic semantics (ie. it may
4170 * not be suitable for data integrity
4171 * writeout).
4172 */
4173 done_index = page->index + 1;
4174 done = 1;
4175 break;
4176 }
4177
4178 /*
4179 * the filesystem may choose to bump up nr_to_write.
4180 * We have to make sure to honor the new nr_to_write
4181 * at any time
4182 */
4183 nr_to_write_done = wbc->nr_to_write <= 0;
4184 }
4185 pagevec_release(&pvec);
4186 cond_resched();
4187 }
4188 if (!scanned && !done) {
4189 /*
4190 * We hit the last page and there is more work to be done: wrap
4191 * back to the start of the file
4192 */
4193 scanned = 1;
4194 index = 0;
4195 goto retry;
4196 }
4197
4198 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4199 mapping->writeback_index = done_index;
4200
4201 btrfs_add_delayed_iput(inode);
4202 return ret;
4203 }
4204
4205 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4206 {
4207 int ret;
4208 struct extent_page_data epd = {
4209 .bio = NULL,
4210 .tree = &BTRFS_I(page->mapping->host)->io_tree,
4211 .extent_locked = 0,
4212 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4213 };
4214
4215 ret = __extent_writepage(page, wbc, &epd);
4216 ASSERT(ret <= 0);
4217 if (ret < 0) {
4218 end_write_bio(&epd, ret);
4219 return ret;
4220 }
4221
4222 ret = flush_write_bio(&epd);
4223 ASSERT(ret <= 0);
4224 return ret;
4225 }
4226
4227 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4228 int mode)
4229 {
4230 int ret = 0;
4231 struct address_space *mapping = inode->i_mapping;
4232 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4233 struct page *page;
4234 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4235 PAGE_SHIFT;
4236
4237 struct extent_page_data epd = {
4238 .bio = NULL,
4239 .tree = tree,
4240 .extent_locked = 1,
4241 .sync_io = mode == WB_SYNC_ALL,
4242 };
4243 struct writeback_control wbc_writepages = {
4244 .sync_mode = mode,
4245 .nr_to_write = nr_pages * 2,
4246 .range_start = start,
4247 .range_end = end + 1,
4248 };
4249
4250 while (start <= end) {
4251 page = find_get_page(mapping, start >> PAGE_SHIFT);
4252 if (clear_page_dirty_for_io(page))
4253 ret = __extent_writepage(page, &wbc_writepages, &epd);
4254 else {
4255 btrfs_writepage_endio_finish_ordered(page, start,
4256 start + PAGE_SIZE - 1, 1);
4257 unlock_page(page);
4258 }
4259 put_page(page);
4260 start += PAGE_SIZE;
4261 }
4262
4263 ASSERT(ret <= 0);
4264 if (ret < 0) {
4265 end_write_bio(&epd, ret);
4266 return ret;
4267 }
4268 ret = flush_write_bio(&epd);
4269 return ret;
4270 }
4271
4272 int extent_writepages(struct address_space *mapping,
4273 struct writeback_control *wbc)
4274 {
4275 int ret = 0;
4276 struct extent_page_data epd = {
4277 .bio = NULL,
4278 .tree = &BTRFS_I(mapping->host)->io_tree,
4279 .extent_locked = 0,
4280 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4281 };
4282
4283 ret = extent_write_cache_pages(mapping, wbc, &epd);
4284 ASSERT(ret <= 0);
4285 if (ret < 0) {
4286 end_write_bio(&epd, ret);
4287 return ret;
4288 }
4289 ret = flush_write_bio(&epd);
4290 return ret;
4291 }
4292
4293 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4294 unsigned nr_pages)
4295 {
4296 struct bio *bio = NULL;
4297 unsigned long bio_flags = 0;
4298 struct page *pagepool[16];
4299 struct extent_map *em_cached = NULL;
4300 struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4301 int nr = 0;
4302 u64 prev_em_start = (u64)-1;
4303
4304 while (!list_empty(pages)) {
4305 u64 contig_end = 0;
4306
4307 for (nr = 0; nr < ARRAY_SIZE(pagepool) && !list_empty(pages);) {
4308 struct page *page = lru_to_page(pages);
4309
4310 prefetchw(&page->flags);
4311 list_del(&page->lru);
4312 if (add_to_page_cache_lru(page, mapping, page->index,
4313 readahead_gfp_mask(mapping))) {
4314 put_page(page);
4315 break;
4316 }
4317
4318 pagepool[nr++] = page;
4319 contig_end = page_offset(page) + PAGE_SIZE - 1;
4320 }
4321
4322 if (nr) {
4323 u64 contig_start = page_offset(pagepool[0]);
4324
4325 ASSERT(contig_start + nr * PAGE_SIZE - 1 == contig_end);
4326
4327 contiguous_readpages(tree, pagepool, nr, contig_start,
4328 contig_end, &em_cached, &bio, &bio_flags,
4329 &prev_em_start);
4330 }
4331 }
4332
4333 if (em_cached)
4334 free_extent_map(em_cached);
4335
4336 if (bio)
4337 return submit_one_bio(bio, 0, bio_flags);
4338 return 0;
4339 }
4340
4341 /*
4342 * basic invalidatepage code, this waits on any locked or writeback
4343 * ranges corresponding to the page, and then deletes any extent state
4344 * records from the tree
4345 */
4346 int extent_invalidatepage(struct extent_io_tree *tree,
4347 struct page *page, unsigned long offset)
4348 {
4349 struct extent_state *cached_state = NULL;
4350 u64 start = page_offset(page);
4351 u64 end = start + PAGE_SIZE - 1;
4352 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4353
4354 start += ALIGN(offset, blocksize);
4355 if (start > end)
4356 return 0;
4357
4358 lock_extent_bits(tree, start, end, &cached_state);
4359 wait_on_page_writeback(page);
4360 clear_extent_bit(tree, start, end, EXTENT_LOCKED | EXTENT_DELALLOC |
4361 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state);
4362 return 0;
4363 }
4364
4365 /*
4366 * a helper for releasepage, this tests for areas of the page that
4367 * are locked or under IO and drops the related state bits if it is safe
4368 * to drop the page.
4369 */
4370 static int try_release_extent_state(struct extent_io_tree *tree,
4371 struct page *page, gfp_t mask)
4372 {
4373 u64 start = page_offset(page);
4374 u64 end = start + PAGE_SIZE - 1;
4375 int ret = 1;
4376
4377 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
4378 ret = 0;
4379 } else {
4380 /*
4381 * at this point we can safely clear everything except the
4382 * locked bit and the nodatasum bit
4383 */
4384 ret = __clear_extent_bit(tree, start, end,
4385 ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4386 0, 0, NULL, mask, NULL);
4387
4388 /* if clear_extent_bit failed for enomem reasons,
4389 * we can't allow the release to continue.
4390 */
4391 if (ret < 0)
4392 ret = 0;
4393 else
4394 ret = 1;
4395 }
4396 return ret;
4397 }
4398
4399 /*
4400 * a helper for releasepage. As long as there are no locked extents
4401 * in the range corresponding to the page, both state records and extent
4402 * map records are removed
4403 */
4404 int try_release_extent_mapping(struct page *page, gfp_t mask)
4405 {
4406 struct extent_map *em;
4407 u64 start = page_offset(page);
4408 u64 end = start + PAGE_SIZE - 1;
4409 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4410 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4411 struct extent_map_tree *map = &btrfs_inode->extent_tree;
4412
4413 if (gfpflags_allow_blocking(mask) &&
4414 page->mapping->host->i_size > SZ_16M) {
4415 u64 len;
4416 while (start <= end) {
4417 len = end - start + 1;
4418 write_lock(&map->lock);
4419 em = lookup_extent_mapping(map, start, len);
4420 if (!em) {
4421 write_unlock(&map->lock);
4422 break;
4423 }
4424 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4425 em->start != start) {
4426 write_unlock(&map->lock);
4427 free_extent_map(em);
4428 break;
4429 }
4430 if (!test_range_bit(tree, em->start,
4431 extent_map_end(em) - 1,
4432 EXTENT_LOCKED, 0, NULL)) {
4433 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4434 &btrfs_inode->runtime_flags);
4435 remove_extent_mapping(map, em);
4436 /* once for the rb tree */
4437 free_extent_map(em);
4438 }
4439 start = extent_map_end(em);
4440 write_unlock(&map->lock);
4441
4442 /* once for us */
4443 free_extent_map(em);
4444 }
4445 }
4446 return try_release_extent_state(tree, page, mask);
4447 }
4448
4449 /*
4450 * helper function for fiemap, which doesn't want to see any holes.
4451 * This maps until we find something past 'last'
4452 */
4453 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4454 u64 offset, u64 last)
4455 {
4456 u64 sectorsize = btrfs_inode_sectorsize(inode);
4457 struct extent_map *em;
4458 u64 len;
4459
4460 if (offset >= last)
4461 return NULL;
4462
4463 while (1) {
4464 len = last - offset;
4465 if (len == 0)
4466 break;
4467 len = ALIGN(len, sectorsize);
4468 em = btrfs_get_extent_fiemap(BTRFS_I(inode), offset, len);
4469 if (IS_ERR_OR_NULL(em))
4470 return em;
4471
4472 /* if this isn't a hole return it */
4473 if (em->block_start != EXTENT_MAP_HOLE)
4474 return em;
4475
4476 /* this is a hole, advance to the next extent */
4477 offset = extent_map_end(em);
4478 free_extent_map(em);
4479 if (offset >= last)
4480 break;
4481 }
4482 return NULL;
4483 }
4484
4485 /*
4486 * To cache previous fiemap extent
4487 *
4488 * Will be used for merging fiemap extent
4489 */
4490 struct fiemap_cache {
4491 u64 offset;
4492 u64 phys;
4493 u64 len;
4494 u32 flags;
4495 bool cached;
4496 };
4497
4498 /*
4499 * Helper to submit fiemap extent.
4500 *
4501 * Will try to merge current fiemap extent specified by @offset, @phys,
4502 * @len and @flags with cached one.
4503 * And only when we fails to merge, cached one will be submitted as
4504 * fiemap extent.
4505 *
4506 * Return value is the same as fiemap_fill_next_extent().
4507 */
4508 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4509 struct fiemap_cache *cache,
4510 u64 offset, u64 phys, u64 len, u32 flags)
4511 {
4512 int ret = 0;
4513
4514 if (!cache->cached)
4515 goto assign;
4516
4517 /*
4518 * Sanity check, extent_fiemap() should have ensured that new
4519 * fiemap extent won't overlap with cached one.
4520 * Not recoverable.
4521 *
4522 * NOTE: Physical address can overlap, due to compression
4523 */
4524 if (cache->offset + cache->len > offset) {
4525 WARN_ON(1);
4526 return -EINVAL;
4527 }
4528
4529 /*
4530 * Only merges fiemap extents if
4531 * 1) Their logical addresses are continuous
4532 *
4533 * 2) Their physical addresses are continuous
4534 * So truly compressed (physical size smaller than logical size)
4535 * extents won't get merged with each other
4536 *
4537 * 3) Share same flags except FIEMAP_EXTENT_LAST
4538 * So regular extent won't get merged with prealloc extent
4539 */
4540 if (cache->offset + cache->len == offset &&
4541 cache->phys + cache->len == phys &&
4542 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4543 (flags & ~FIEMAP_EXTENT_LAST)) {
4544 cache->len += len;
4545 cache->flags |= flags;
4546 goto try_submit_last;
4547 }
4548
4549 /* Not mergeable, need to submit cached one */
4550 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4551 cache->len, cache->flags);
4552 cache->cached = false;
4553 if (ret)
4554 return ret;
4555 assign:
4556 cache->cached = true;
4557 cache->offset = offset;
4558 cache->phys = phys;
4559 cache->len = len;
4560 cache->flags = flags;
4561 try_submit_last:
4562 if (cache->flags & FIEMAP_EXTENT_LAST) {
4563 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4564 cache->phys, cache->len, cache->flags);
4565 cache->cached = false;
4566 }
4567 return ret;
4568 }
4569
4570 /*
4571 * Emit last fiemap cache
4572 *
4573 * The last fiemap cache may still be cached in the following case:
4574 * 0 4k 8k
4575 * |<- Fiemap range ->|
4576 * |<------------ First extent ----------->|
4577 *
4578 * In this case, the first extent range will be cached but not emitted.
4579 * So we must emit it before ending extent_fiemap().
4580 */
4581 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
4582 struct fiemap_cache *cache)
4583 {
4584 int ret;
4585
4586 if (!cache->cached)
4587 return 0;
4588
4589 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4590 cache->len, cache->flags);
4591 cache->cached = false;
4592 if (ret > 0)
4593 ret = 0;
4594 return ret;
4595 }
4596
4597 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4598 __u64 start, __u64 len)
4599 {
4600 int ret = 0;
4601 u64 off = start;
4602 u64 max = start + len;
4603 u32 flags = 0;
4604 u32 found_type;
4605 u64 last;
4606 u64 last_for_get_extent = 0;
4607 u64 disko = 0;
4608 u64 isize = i_size_read(inode);
4609 struct btrfs_key found_key;
4610 struct extent_map *em = NULL;
4611 struct extent_state *cached_state = NULL;
4612 struct btrfs_path *path;
4613 struct btrfs_root *root = BTRFS_I(inode)->root;
4614 struct fiemap_cache cache = { 0 };
4615 struct ulist *roots;
4616 struct ulist *tmp_ulist;
4617 int end = 0;
4618 u64 em_start = 0;
4619 u64 em_len = 0;
4620 u64 em_end = 0;
4621
4622 if (len == 0)
4623 return -EINVAL;
4624
4625 path = btrfs_alloc_path();
4626 if (!path)
4627 return -ENOMEM;
4628 path->leave_spinning = 1;
4629
4630 roots = ulist_alloc(GFP_KERNEL);
4631 tmp_ulist = ulist_alloc(GFP_KERNEL);
4632 if (!roots || !tmp_ulist) {
4633 ret = -ENOMEM;
4634 goto out_free_ulist;
4635 }
4636
4637 start = round_down(start, btrfs_inode_sectorsize(inode));
4638 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4639
4640 /*
4641 * lookup the last file extent. We're not using i_size here
4642 * because there might be preallocation past i_size
4643 */
4644 ret = btrfs_lookup_file_extent(NULL, root, path,
4645 btrfs_ino(BTRFS_I(inode)), -1, 0);
4646 if (ret < 0) {
4647 goto out_free_ulist;
4648 } else {
4649 WARN_ON(!ret);
4650 if (ret == 1)
4651 ret = 0;
4652 }
4653
4654 path->slots[0]--;
4655 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4656 found_type = found_key.type;
4657
4658 /* No extents, but there might be delalloc bits */
4659 if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4660 found_type != BTRFS_EXTENT_DATA_KEY) {
4661 /* have to trust i_size as the end */
4662 last = (u64)-1;
4663 last_for_get_extent = isize;
4664 } else {
4665 /*
4666 * remember the start of the last extent. There are a
4667 * bunch of different factors that go into the length of the
4668 * extent, so its much less complex to remember where it started
4669 */
4670 last = found_key.offset;
4671 last_for_get_extent = last + 1;
4672 }
4673 btrfs_release_path(path);
4674
4675 /*
4676 * we might have some extents allocated but more delalloc past those
4677 * extents. so, we trust isize unless the start of the last extent is
4678 * beyond isize
4679 */
4680 if (last < isize) {
4681 last = (u64)-1;
4682 last_for_get_extent = isize;
4683 }
4684
4685 lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4686 &cached_state);
4687
4688 em = get_extent_skip_holes(inode, start, last_for_get_extent);
4689 if (!em)
4690 goto out;
4691 if (IS_ERR(em)) {
4692 ret = PTR_ERR(em);
4693 goto out;
4694 }
4695
4696 while (!end) {
4697 u64 offset_in_extent = 0;
4698
4699 /* break if the extent we found is outside the range */
4700 if (em->start >= max || extent_map_end(em) < off)
4701 break;
4702
4703 /*
4704 * get_extent may return an extent that starts before our
4705 * requested range. We have to make sure the ranges
4706 * we return to fiemap always move forward and don't
4707 * overlap, so adjust the offsets here
4708 */
4709 em_start = max(em->start, off);
4710
4711 /*
4712 * record the offset from the start of the extent
4713 * for adjusting the disk offset below. Only do this if the
4714 * extent isn't compressed since our in ram offset may be past
4715 * what we have actually allocated on disk.
4716 */
4717 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4718 offset_in_extent = em_start - em->start;
4719 em_end = extent_map_end(em);
4720 em_len = em_end - em_start;
4721 flags = 0;
4722 if (em->block_start < EXTENT_MAP_LAST_BYTE)
4723 disko = em->block_start + offset_in_extent;
4724 else
4725 disko = 0;
4726
4727 /*
4728 * bump off for our next call to get_extent
4729 */
4730 off = extent_map_end(em);
4731 if (off >= max)
4732 end = 1;
4733
4734 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4735 end = 1;
4736 flags |= FIEMAP_EXTENT_LAST;
4737 } else if (em->block_start == EXTENT_MAP_INLINE) {
4738 flags |= (FIEMAP_EXTENT_DATA_INLINE |
4739 FIEMAP_EXTENT_NOT_ALIGNED);
4740 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
4741 flags |= (FIEMAP_EXTENT_DELALLOC |
4742 FIEMAP_EXTENT_UNKNOWN);
4743 } else if (fieinfo->fi_extents_max) {
4744 u64 bytenr = em->block_start -
4745 (em->start - em->orig_start);
4746
4747 /*
4748 * As btrfs supports shared space, this information
4749 * can be exported to userspace tools via
4750 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
4751 * then we're just getting a count and we can skip the
4752 * lookup stuff.
4753 */
4754 ret = btrfs_check_shared(root,
4755 btrfs_ino(BTRFS_I(inode)),
4756 bytenr, roots, tmp_ulist);
4757 if (ret < 0)
4758 goto out_free;
4759 if (ret)
4760 flags |= FIEMAP_EXTENT_SHARED;
4761 ret = 0;
4762 }
4763 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4764 flags |= FIEMAP_EXTENT_ENCODED;
4765 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4766 flags |= FIEMAP_EXTENT_UNWRITTEN;
4767
4768 free_extent_map(em);
4769 em = NULL;
4770 if ((em_start >= last) || em_len == (u64)-1 ||
4771 (last == (u64)-1 && isize <= em_end)) {
4772 flags |= FIEMAP_EXTENT_LAST;
4773 end = 1;
4774 }
4775
4776 /* now scan forward to see if this is really the last extent. */
4777 em = get_extent_skip_holes(inode, off, last_for_get_extent);
4778 if (IS_ERR(em)) {
4779 ret = PTR_ERR(em);
4780 goto out;
4781 }
4782 if (!em) {
4783 flags |= FIEMAP_EXTENT_LAST;
4784 end = 1;
4785 }
4786 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4787 em_len, flags);
4788 if (ret) {
4789 if (ret == 1)
4790 ret = 0;
4791 goto out_free;
4792 }
4793 }
4794 out_free:
4795 if (!ret)
4796 ret = emit_last_fiemap_cache(fieinfo, &cache);
4797 free_extent_map(em);
4798 out:
4799 unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4800 &cached_state);
4801
4802 out_free_ulist:
4803 btrfs_free_path(path);
4804 ulist_free(roots);
4805 ulist_free(tmp_ulist);
4806 return ret;
4807 }
4808
4809 static void __free_extent_buffer(struct extent_buffer *eb)
4810 {
4811 btrfs_leak_debug_del(&eb->leak_list);
4812 kmem_cache_free(extent_buffer_cache, eb);
4813 }
4814
4815 int extent_buffer_under_io(struct extent_buffer *eb)
4816 {
4817 return (atomic_read(&eb->io_pages) ||
4818 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4819 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4820 }
4821
4822 /*
4823 * Release all pages attached to the extent buffer.
4824 */
4825 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4826 {
4827 int i;
4828 int num_pages;
4829 int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4830
4831 BUG_ON(extent_buffer_under_io(eb));
4832
4833 num_pages = num_extent_pages(eb);
4834 for (i = 0; i < num_pages; i++) {
4835 struct page *page = eb->pages[i];
4836
4837 if (!page)
4838 continue;
4839 if (mapped)
4840 spin_lock(&page->mapping->private_lock);
4841 /*
4842 * We do this since we'll remove the pages after we've
4843 * removed the eb from the radix tree, so we could race
4844 * and have this page now attached to the new eb. So
4845 * only clear page_private if it's still connected to
4846 * this eb.
4847 */
4848 if (PagePrivate(page) &&
4849 page->private == (unsigned long)eb) {
4850 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4851 BUG_ON(PageDirty(page));
4852 BUG_ON(PageWriteback(page));
4853 /*
4854 * We need to make sure we haven't be attached
4855 * to a new eb.
4856 */
4857 ClearPagePrivate(page);
4858 set_page_private(page, 0);
4859 /* One for the page private */
4860 put_page(page);
4861 }
4862
4863 if (mapped)
4864 spin_unlock(&page->mapping->private_lock);
4865
4866 /* One for when we allocated the page */
4867 put_page(page);
4868 }
4869 }
4870
4871 /*
4872 * Helper for releasing the extent buffer.
4873 */
4874 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4875 {
4876 btrfs_release_extent_buffer_pages(eb);
4877 __free_extent_buffer(eb);
4878 }
4879
4880 static struct extent_buffer *
4881 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4882 unsigned long len)
4883 {
4884 struct extent_buffer *eb = NULL;
4885
4886 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4887 eb->start = start;
4888 eb->len = len;
4889 eb->fs_info = fs_info;
4890 eb->bflags = 0;
4891 rwlock_init(&eb->lock);
4892 atomic_set(&eb->blocking_readers, 0);
4893 eb->blocking_writers = 0;
4894 eb->lock_nested = false;
4895 init_waitqueue_head(&eb->write_lock_wq);
4896 init_waitqueue_head(&eb->read_lock_wq);
4897
4898 btrfs_leak_debug_add(&eb->leak_list, &buffers);
4899
4900 spin_lock_init(&eb->refs_lock);
4901 atomic_set(&eb->refs, 1);
4902 atomic_set(&eb->io_pages, 0);
4903
4904 /*
4905 * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4906 */
4907 BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4908 > MAX_INLINE_EXTENT_BUFFER_SIZE);
4909 BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4910
4911 #ifdef CONFIG_BTRFS_DEBUG
4912 eb->spinning_writers = 0;
4913 atomic_set(&eb->spinning_readers, 0);
4914 atomic_set(&eb->read_locks, 0);
4915 eb->write_locks = 0;
4916 #endif
4917
4918 return eb;
4919 }
4920
4921 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4922 {
4923 int i;
4924 struct page *p;
4925 struct extent_buffer *new;
4926 int num_pages = num_extent_pages(src);
4927
4928 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4929 if (new == NULL)
4930 return NULL;
4931
4932 for (i = 0; i < num_pages; i++) {
4933 p = alloc_page(GFP_NOFS);
4934 if (!p) {
4935 btrfs_release_extent_buffer(new);
4936 return NULL;
4937 }
4938 attach_extent_buffer_page(new, p);
4939 WARN_ON(PageDirty(p));
4940 SetPageUptodate(p);
4941 new->pages[i] = p;
4942 copy_page(page_address(p), page_address(src->pages[i]));
4943 }
4944
4945 set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4946 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4947
4948 return new;
4949 }
4950
4951 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4952 u64 start, unsigned long len)
4953 {
4954 struct extent_buffer *eb;
4955 int num_pages;
4956 int i;
4957
4958 eb = __alloc_extent_buffer(fs_info, start, len);
4959 if (!eb)
4960 return NULL;
4961
4962 num_pages = num_extent_pages(eb);
4963 for (i = 0; i < num_pages; i++) {
4964 eb->pages[i] = alloc_page(GFP_NOFS);
4965 if (!eb->pages[i])
4966 goto err;
4967 }
4968 set_extent_buffer_uptodate(eb);
4969 btrfs_set_header_nritems(eb, 0);
4970 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4971
4972 return eb;
4973 err:
4974 for (; i > 0; i--)
4975 __free_page(eb->pages[i - 1]);
4976 __free_extent_buffer(eb);
4977 return NULL;
4978 }
4979
4980 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4981 u64 start)
4982 {
4983 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4984 }
4985
4986 static void check_buffer_tree_ref(struct extent_buffer *eb)
4987 {
4988 int refs;
4989 /* the ref bit is tricky. We have to make sure it is set
4990 * if we have the buffer dirty. Otherwise the
4991 * code to free a buffer can end up dropping a dirty
4992 * page
4993 *
4994 * Once the ref bit is set, it won't go away while the
4995 * buffer is dirty or in writeback, and it also won't
4996 * go away while we have the reference count on the
4997 * eb bumped.
4998 *
4999 * We can't just set the ref bit without bumping the
5000 * ref on the eb because free_extent_buffer might
5001 * see the ref bit and try to clear it. If this happens
5002 * free_extent_buffer might end up dropping our original
5003 * ref by mistake and freeing the page before we are able
5004 * to add one more ref.
5005 *
5006 * So bump the ref count first, then set the bit. If someone
5007 * beat us to it, drop the ref we added.
5008 */
5009 refs = atomic_read(&eb->refs);
5010 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5011 return;
5012
5013 spin_lock(&eb->refs_lock);
5014 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5015 atomic_inc(&eb->refs);
5016 spin_unlock(&eb->refs_lock);
5017 }
5018
5019 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5020 struct page *accessed)
5021 {
5022 int num_pages, i;
5023
5024 check_buffer_tree_ref(eb);
5025
5026 num_pages = num_extent_pages(eb);
5027 for (i = 0; i < num_pages; i++) {
5028 struct page *p = eb->pages[i];
5029
5030 if (p != accessed)
5031 mark_page_accessed(p);
5032 }
5033 }
5034
5035 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5036 u64 start)
5037 {
5038 struct extent_buffer *eb;
5039
5040 rcu_read_lock();
5041 eb = radix_tree_lookup(&fs_info->buffer_radix,
5042 start >> PAGE_SHIFT);
5043 if (eb && atomic_inc_not_zero(&eb->refs)) {
5044 rcu_read_unlock();
5045 /*
5046 * Lock our eb's refs_lock to avoid races with
5047 * free_extent_buffer. When we get our eb it might be flagged
5048 * with EXTENT_BUFFER_STALE and another task running
5049 * free_extent_buffer might have seen that flag set,
5050 * eb->refs == 2, that the buffer isn't under IO (dirty and
5051 * writeback flags not set) and it's still in the tree (flag
5052 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5053 * of decrementing the extent buffer's reference count twice.
5054 * So here we could race and increment the eb's reference count,
5055 * clear its stale flag, mark it as dirty and drop our reference
5056 * before the other task finishes executing free_extent_buffer,
5057 * which would later result in an attempt to free an extent
5058 * buffer that is dirty.
5059 */
5060 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5061 spin_lock(&eb->refs_lock);
5062 spin_unlock(&eb->refs_lock);
5063 }
5064 mark_extent_buffer_accessed(eb, NULL);
5065 return eb;
5066 }
5067 rcu_read_unlock();
5068
5069 return NULL;
5070 }
5071
5072 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5073 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5074 u64 start)
5075 {
5076 struct extent_buffer *eb, *exists = NULL;
5077 int ret;
5078
5079 eb = find_extent_buffer(fs_info, start);
5080 if (eb)
5081 return eb;
5082 eb = alloc_dummy_extent_buffer(fs_info, start);
5083 if (!eb)
5084 return NULL;
5085 eb->fs_info = fs_info;
5086 again:
5087 ret = radix_tree_preload(GFP_NOFS);
5088 if (ret)
5089 goto free_eb;
5090 spin_lock(&fs_info->buffer_lock);
5091 ret = radix_tree_insert(&fs_info->buffer_radix,
5092 start >> PAGE_SHIFT, eb);
5093 spin_unlock(&fs_info->buffer_lock);
5094 radix_tree_preload_end();
5095 if (ret == -EEXIST) {
5096 exists = find_extent_buffer(fs_info, start);
5097 if (exists)
5098 goto free_eb;
5099 else
5100 goto again;
5101 }
5102 check_buffer_tree_ref(eb);
5103 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5104
5105 return eb;
5106 free_eb:
5107 btrfs_release_extent_buffer(eb);
5108 return exists;
5109 }
5110 #endif
5111
5112 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5113 u64 start)
5114 {
5115 unsigned long len = fs_info->nodesize;
5116 int num_pages;
5117 int i;
5118 unsigned long index = start >> PAGE_SHIFT;
5119 struct extent_buffer *eb;
5120 struct extent_buffer *exists = NULL;
5121 struct page *p;
5122 struct address_space *mapping = fs_info->btree_inode->i_mapping;
5123 int uptodate = 1;
5124 int ret;
5125
5126 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5127 btrfs_err(fs_info, "bad tree block start %llu", start);
5128 return ERR_PTR(-EINVAL);
5129 }
5130
5131 eb = find_extent_buffer(fs_info, start);
5132 if (eb)
5133 return eb;
5134
5135 eb = __alloc_extent_buffer(fs_info, start, len);
5136 if (!eb)
5137 return ERR_PTR(-ENOMEM);
5138
5139 num_pages = num_extent_pages(eb);
5140 for (i = 0; i < num_pages; i++, index++) {
5141 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5142 if (!p) {
5143 exists = ERR_PTR(-ENOMEM);
5144 goto free_eb;
5145 }
5146
5147 spin_lock(&mapping->private_lock);
5148 if (PagePrivate(p)) {
5149 /*
5150 * We could have already allocated an eb for this page
5151 * and attached one so lets see if we can get a ref on
5152 * the existing eb, and if we can we know it's good and
5153 * we can just return that one, else we know we can just
5154 * overwrite page->private.
5155 */
5156 exists = (struct extent_buffer *)p->private;
5157 if (atomic_inc_not_zero(&exists->refs)) {
5158 spin_unlock(&mapping->private_lock);
5159 unlock_page(p);
5160 put_page(p);
5161 mark_extent_buffer_accessed(exists, p);
5162 goto free_eb;
5163 }
5164 exists = NULL;
5165
5166 /*
5167 * Do this so attach doesn't complain and we need to
5168 * drop the ref the old guy had.
5169 */
5170 ClearPagePrivate(p);
5171 WARN_ON(PageDirty(p));
5172 put_page(p);
5173 }
5174 attach_extent_buffer_page(eb, p);
5175 spin_unlock(&mapping->private_lock);
5176 WARN_ON(PageDirty(p));
5177 eb->pages[i] = p;
5178 if (!PageUptodate(p))
5179 uptodate = 0;
5180
5181 /*
5182 * We can't unlock the pages just yet since the extent buffer
5183 * hasn't been properly inserted in the radix tree, this
5184 * opens a race with btree_releasepage which can free a page
5185 * while we are still filling in all pages for the buffer and
5186 * we could crash.
5187 */
5188 }
5189 if (uptodate)
5190 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5191 again:
5192 ret = radix_tree_preload(GFP_NOFS);
5193 if (ret) {
5194 exists = ERR_PTR(ret);
5195 goto free_eb;
5196 }
5197
5198 spin_lock(&fs_info->buffer_lock);
5199 ret = radix_tree_insert(&fs_info->buffer_radix,
5200 start >> PAGE_SHIFT, eb);
5201 spin_unlock(&fs_info->buffer_lock);
5202 radix_tree_preload_end();
5203 if (ret == -EEXIST) {
5204 exists = find_extent_buffer(fs_info, start);
5205 if (exists)
5206 goto free_eb;
5207 else
5208 goto again;
5209 }
5210 /* add one reference for the tree */
5211 check_buffer_tree_ref(eb);
5212 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5213
5214 /*
5215 * Now it's safe to unlock the pages because any calls to
5216 * btree_releasepage will correctly detect that a page belongs to a
5217 * live buffer and won't free them prematurely.
5218 */
5219 for (i = 0; i < num_pages; i++)
5220 unlock_page(eb->pages[i]);
5221 return eb;
5222
5223 free_eb:
5224 WARN_ON(!atomic_dec_and_test(&eb->refs));
5225 for (i = 0; i < num_pages; i++) {
5226 if (eb->pages[i])
5227 unlock_page(eb->pages[i]);
5228 }
5229
5230 btrfs_release_extent_buffer(eb);
5231 return exists;
5232 }
5233
5234 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5235 {
5236 struct extent_buffer *eb =
5237 container_of(head, struct extent_buffer, rcu_head);
5238
5239 __free_extent_buffer(eb);
5240 }
5241
5242 static int release_extent_buffer(struct extent_buffer *eb)
5243 {
5244 lockdep_assert_held(&eb->refs_lock);
5245
5246 WARN_ON(atomic_read(&eb->refs) == 0);
5247 if (atomic_dec_and_test(&eb->refs)) {
5248 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5249 struct btrfs_fs_info *fs_info = eb->fs_info;
5250
5251 spin_unlock(&eb->refs_lock);
5252
5253 spin_lock(&fs_info->buffer_lock);
5254 radix_tree_delete(&fs_info->buffer_radix,
5255 eb->start >> PAGE_SHIFT);
5256 spin_unlock(&fs_info->buffer_lock);
5257 } else {
5258 spin_unlock(&eb->refs_lock);
5259 }
5260
5261 /* Should be safe to release our pages at this point */
5262 btrfs_release_extent_buffer_pages(eb);
5263 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5264 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5265 __free_extent_buffer(eb);
5266 return 1;
5267 }
5268 #endif
5269 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5270 return 1;
5271 }
5272 spin_unlock(&eb->refs_lock);
5273
5274 return 0;
5275 }
5276
5277 void free_extent_buffer(struct extent_buffer *eb)
5278 {
5279 int refs;
5280 int old;
5281 if (!eb)
5282 return;
5283
5284 while (1) {
5285 refs = atomic_read(&eb->refs);
5286 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5287 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5288 refs == 1))
5289 break;
5290 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5291 if (old == refs)
5292 return;
5293 }
5294
5295 spin_lock(&eb->refs_lock);
5296 if (atomic_read(&eb->refs) == 2 &&
5297 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5298 !extent_buffer_under_io(eb) &&
5299 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5300 atomic_dec(&eb->refs);
5301
5302 /*
5303 * I know this is terrible, but it's temporary until we stop tracking
5304 * the uptodate bits and such for the extent buffers.
5305 */
5306 release_extent_buffer(eb);
5307 }
5308
5309 void free_extent_buffer_stale(struct extent_buffer *eb)
5310 {
5311 if (!eb)
5312 return;
5313
5314 spin_lock(&eb->refs_lock);
5315 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5316
5317 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5318 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5319 atomic_dec(&eb->refs);
5320 release_extent_buffer(eb);
5321 }
5322
5323 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5324 {
5325 int i;
5326 int num_pages;
5327 struct page *page;
5328
5329 num_pages = num_extent_pages(eb);
5330
5331 for (i = 0; i < num_pages; i++) {
5332 page = eb->pages[i];
5333 if (!PageDirty(page))
5334 continue;
5335
5336 lock_page(page);
5337 WARN_ON(!PagePrivate(page));
5338
5339 clear_page_dirty_for_io(page);
5340 xa_lock_irq(&page->mapping->i_pages);
5341 if (!PageDirty(page))
5342 __xa_clear_mark(&page->mapping->i_pages,
5343 page_index(page), PAGECACHE_TAG_DIRTY);
5344 xa_unlock_irq(&page->mapping->i_pages);
5345 ClearPageError(page);
5346 unlock_page(page);
5347 }
5348 WARN_ON(atomic_read(&eb->refs) == 0);
5349 }
5350
5351 bool set_extent_buffer_dirty(struct extent_buffer *eb)
5352 {
5353 int i;
5354 int num_pages;
5355 bool was_dirty;
5356
5357 check_buffer_tree_ref(eb);
5358
5359 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5360
5361 num_pages = num_extent_pages(eb);
5362 WARN_ON(atomic_read(&eb->refs) == 0);
5363 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5364
5365 if (!was_dirty)
5366 for (i = 0; i < num_pages; i++)
5367 set_page_dirty(eb->pages[i]);
5368
5369 #ifdef CONFIG_BTRFS_DEBUG
5370 for (i = 0; i < num_pages; i++)
5371 ASSERT(PageDirty(eb->pages[i]));
5372 #endif
5373
5374 return was_dirty;
5375 }
5376
5377 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5378 {
5379 int i;
5380 struct page *page;
5381 int num_pages;
5382
5383 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5384 num_pages = num_extent_pages(eb);
5385 for (i = 0; i < num_pages; i++) {
5386 page = eb->pages[i];
5387 if (page)
5388 ClearPageUptodate(page);
5389 }
5390 }
5391
5392 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5393 {
5394 int i;
5395 struct page *page;
5396 int num_pages;
5397
5398 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5399 num_pages = num_extent_pages(eb);
5400 for (i = 0; i < num_pages; i++) {
5401 page = eb->pages[i];
5402 SetPageUptodate(page);
5403 }
5404 }
5405
5406 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5407 {
5408 int i;
5409 struct page *page;
5410 int err;
5411 int ret = 0;
5412 int locked_pages = 0;
5413 int all_uptodate = 1;
5414 int num_pages;
5415 unsigned long num_reads = 0;
5416 struct bio *bio = NULL;
5417 unsigned long bio_flags = 0;
5418 struct extent_io_tree *tree = &BTRFS_I(eb->fs_info->btree_inode)->io_tree;
5419
5420 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5421 return 0;
5422
5423 num_pages = num_extent_pages(eb);
5424 for (i = 0; i < num_pages; i++) {
5425 page = eb->pages[i];
5426 if (wait == WAIT_NONE) {
5427 if (!trylock_page(page))
5428 goto unlock_exit;
5429 } else {
5430 lock_page(page);
5431 }
5432 locked_pages++;
5433 }
5434 /*
5435 * We need to firstly lock all pages to make sure that
5436 * the uptodate bit of our pages won't be affected by
5437 * clear_extent_buffer_uptodate().
5438 */
5439 for (i = 0; i < num_pages; i++) {
5440 page = eb->pages[i];
5441 if (!PageUptodate(page)) {
5442 num_reads++;
5443 all_uptodate = 0;
5444 }
5445 }
5446
5447 if (all_uptodate) {
5448 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5449 goto unlock_exit;
5450 }
5451
5452 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5453 eb->read_mirror = 0;
5454 atomic_set(&eb->io_pages, num_reads);
5455 for (i = 0; i < num_pages; i++) {
5456 page = eb->pages[i];
5457
5458 if (!PageUptodate(page)) {
5459 if (ret) {
5460 atomic_dec(&eb->io_pages);
5461 unlock_page(page);
5462 continue;
5463 }
5464
5465 ClearPageError(page);
5466 err = __extent_read_full_page(tree, page,
5467 btree_get_extent, &bio,
5468 mirror_num, &bio_flags,
5469 REQ_META);
5470 if (err) {
5471 ret = err;
5472 /*
5473 * We use &bio in above __extent_read_full_page,
5474 * so we ensure that if it returns error, the
5475 * current page fails to add itself to bio and
5476 * it's been unlocked.
5477 *
5478 * We must dec io_pages by ourselves.
5479 */
5480 atomic_dec(&eb->io_pages);
5481 }
5482 } else {
5483 unlock_page(page);
5484 }
5485 }
5486
5487 if (bio) {
5488 err = submit_one_bio(bio, mirror_num, bio_flags);
5489 if (err)
5490 return err;
5491 }
5492
5493 if (ret || wait != WAIT_COMPLETE)
5494 return ret;
5495
5496 for (i = 0; i < num_pages; i++) {
5497 page = eb->pages[i];
5498 wait_on_page_locked(page);
5499 if (!PageUptodate(page))
5500 ret = -EIO;
5501 }
5502
5503 return ret;
5504
5505 unlock_exit:
5506 while (locked_pages > 0) {
5507 locked_pages--;
5508 page = eb->pages[locked_pages];
5509 unlock_page(page);
5510 }
5511 return ret;
5512 }
5513
5514 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5515 unsigned long start, unsigned long len)
5516 {
5517 size_t cur;
5518 size_t offset;
5519 struct page *page;
5520 char *kaddr;
5521 char *dst = (char *)dstv;
5522 size_t start_offset = offset_in_page(eb->start);
5523 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5524
5525 if (start + len > eb->len) {
5526 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5527 eb->start, eb->len, start, len);
5528 memset(dst, 0, len);
5529 return;
5530 }
5531
5532 offset = offset_in_page(start_offset + start);
5533
5534 while (len > 0) {
5535 page = eb->pages[i];
5536
5537 cur = min(len, (PAGE_SIZE - offset));
5538 kaddr = page_address(page);
5539 memcpy(dst, kaddr + offset, cur);
5540
5541 dst += cur;
5542 len -= cur;
5543 offset = 0;
5544 i++;
5545 }
5546 }
5547
5548 int read_extent_buffer_to_user(const struct extent_buffer *eb,
5549 void __user *dstv,
5550 unsigned long start, unsigned long len)
5551 {
5552 size_t cur;
5553 size_t offset;
5554 struct page *page;
5555 char *kaddr;
5556 char __user *dst = (char __user *)dstv;
5557 size_t start_offset = offset_in_page(eb->start);
5558 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5559 int ret = 0;
5560
5561 WARN_ON(start > eb->len);
5562 WARN_ON(start + len > eb->start + eb->len);
5563
5564 offset = offset_in_page(start_offset + start);
5565
5566 while (len > 0) {
5567 page = eb->pages[i];
5568
5569 cur = min(len, (PAGE_SIZE - offset));
5570 kaddr = page_address(page);
5571 if (copy_to_user(dst, kaddr + offset, cur)) {
5572 ret = -EFAULT;
5573 break;
5574 }
5575
5576 dst += cur;
5577 len -= cur;
5578 offset = 0;
5579 i++;
5580 }
5581
5582 return ret;
5583 }
5584
5585 /*
5586 * return 0 if the item is found within a page.
5587 * return 1 if the item spans two pages.
5588 * return -EINVAL otherwise.
5589 */
5590 int map_private_extent_buffer(const struct extent_buffer *eb,
5591 unsigned long start, unsigned long min_len,
5592 char **map, unsigned long *map_start,
5593 unsigned long *map_len)
5594 {
5595 size_t offset;
5596 char *kaddr;
5597 struct page *p;
5598 size_t start_offset = offset_in_page(eb->start);
5599 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5600 unsigned long end_i = (start_offset + start + min_len - 1) >>
5601 PAGE_SHIFT;
5602
5603 if (start + min_len > eb->len) {
5604 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5605 eb->start, eb->len, start, min_len);
5606 return -EINVAL;
5607 }
5608
5609 if (i != end_i)
5610 return 1;
5611
5612 if (i == 0) {
5613 offset = start_offset;
5614 *map_start = 0;
5615 } else {
5616 offset = 0;
5617 *map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5618 }
5619
5620 p = eb->pages[i];
5621 kaddr = page_address(p);
5622 *map = kaddr + offset;
5623 *map_len = PAGE_SIZE - offset;
5624 return 0;
5625 }
5626
5627 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5628 unsigned long start, unsigned long len)
5629 {
5630 size_t cur;
5631 size_t offset;
5632 struct page *page;
5633 char *kaddr;
5634 char *ptr = (char *)ptrv;
5635 size_t start_offset = offset_in_page(eb->start);
5636 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5637 int ret = 0;
5638
5639 WARN_ON(start > eb->len);
5640 WARN_ON(start + len > eb->start + eb->len);
5641
5642 offset = offset_in_page(start_offset + start);
5643
5644 while (len > 0) {
5645 page = eb->pages[i];
5646
5647 cur = min(len, (PAGE_SIZE - offset));
5648
5649 kaddr = page_address(page);
5650 ret = memcmp(ptr, kaddr + offset, cur);
5651 if (ret)
5652 break;
5653
5654 ptr += cur;
5655 len -= cur;
5656 offset = 0;
5657 i++;
5658 }
5659 return ret;
5660 }
5661
5662 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5663 const void *srcv)
5664 {
5665 char *kaddr;
5666
5667 WARN_ON(!PageUptodate(eb->pages[0]));
5668 kaddr = page_address(eb->pages[0]);
5669 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5670 BTRFS_FSID_SIZE);
5671 }
5672
5673 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5674 {
5675 char *kaddr;
5676
5677 WARN_ON(!PageUptodate(eb->pages[0]));
5678 kaddr = page_address(eb->pages[0]);
5679 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5680 BTRFS_FSID_SIZE);
5681 }
5682
5683 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5684 unsigned long start, unsigned long len)
5685 {
5686 size_t cur;
5687 size_t offset;
5688 struct page *page;
5689 char *kaddr;
5690 char *src = (char *)srcv;
5691 size_t start_offset = offset_in_page(eb->start);
5692 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5693
5694 WARN_ON(start > eb->len);
5695 WARN_ON(start + len > eb->start + eb->len);
5696
5697 offset = offset_in_page(start_offset + start);
5698
5699 while (len > 0) {
5700 page = eb->pages[i];
5701 WARN_ON(!PageUptodate(page));
5702
5703 cur = min(len, PAGE_SIZE - offset);
5704 kaddr = page_address(page);
5705 memcpy(kaddr + offset, src, cur);
5706
5707 src += cur;
5708 len -= cur;
5709 offset = 0;
5710 i++;
5711 }
5712 }
5713
5714 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5715 unsigned long len)
5716 {
5717 size_t cur;
5718 size_t offset;
5719 struct page *page;
5720 char *kaddr;
5721 size_t start_offset = offset_in_page(eb->start);
5722 unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5723
5724 WARN_ON(start > eb->len);
5725 WARN_ON(start + len > eb->start + eb->len);
5726
5727 offset = offset_in_page(start_offset + start);
5728
5729 while (len > 0) {
5730 page = eb->pages[i];
5731 WARN_ON(!PageUptodate(page));
5732
5733 cur = min(len, PAGE_SIZE - offset);
5734 kaddr = page_address(page);
5735 memset(kaddr + offset, 0, cur);
5736
5737 len -= cur;
5738 offset = 0;
5739 i++;
5740 }
5741 }
5742
5743 void copy_extent_buffer_full(struct extent_buffer *dst,
5744 struct extent_buffer *src)
5745 {
5746 int i;
5747 int num_pages;
5748
5749 ASSERT(dst->len == src->len);
5750
5751 num_pages = num_extent_pages(dst);
5752 for (i = 0; i < num_pages; i++)
5753 copy_page(page_address(dst->pages[i]),
5754 page_address(src->pages[i]));
5755 }
5756
5757 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5758 unsigned long dst_offset, unsigned long src_offset,
5759 unsigned long len)
5760 {
5761 u64 dst_len = dst->len;
5762 size_t cur;
5763 size_t offset;
5764 struct page *page;
5765 char *kaddr;
5766 size_t start_offset = offset_in_page(dst->start);
5767 unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5768
5769 WARN_ON(src->len != dst_len);
5770
5771 offset = offset_in_page(start_offset + dst_offset);
5772
5773 while (len > 0) {
5774 page = dst->pages[i];
5775 WARN_ON(!PageUptodate(page));
5776
5777 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5778
5779 kaddr = page_address(page);
5780 read_extent_buffer(src, kaddr + offset, src_offset, cur);
5781
5782 src_offset += cur;
5783 len -= cur;
5784 offset = 0;
5785 i++;
5786 }
5787 }
5788
5789 /*
5790 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5791 * given bit number
5792 * @eb: the extent buffer
5793 * @start: offset of the bitmap item in the extent buffer
5794 * @nr: bit number
5795 * @page_index: return index of the page in the extent buffer that contains the
5796 * given bit number
5797 * @page_offset: return offset into the page given by page_index
5798 *
5799 * This helper hides the ugliness of finding the byte in an extent buffer which
5800 * contains a given bit.
5801 */
5802 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5803 unsigned long start, unsigned long nr,
5804 unsigned long *page_index,
5805 size_t *page_offset)
5806 {
5807 size_t start_offset = offset_in_page(eb->start);
5808 size_t byte_offset = BIT_BYTE(nr);
5809 size_t offset;
5810
5811 /*
5812 * The byte we want is the offset of the extent buffer + the offset of
5813 * the bitmap item in the extent buffer + the offset of the byte in the
5814 * bitmap item.
5815 */
5816 offset = start_offset + start + byte_offset;
5817
5818 *page_index = offset >> PAGE_SHIFT;
5819 *page_offset = offset_in_page(offset);
5820 }
5821
5822 /**
5823 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5824 * @eb: the extent buffer
5825 * @start: offset of the bitmap item in the extent buffer
5826 * @nr: bit number to test
5827 */
5828 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5829 unsigned long nr)
5830 {
5831 u8 *kaddr;
5832 struct page *page;
5833 unsigned long i;
5834 size_t offset;
5835
5836 eb_bitmap_offset(eb, start, nr, &i, &offset);
5837 page = eb->pages[i];
5838 WARN_ON(!PageUptodate(page));
5839 kaddr = page_address(page);
5840 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5841 }
5842
5843 /**
5844 * extent_buffer_bitmap_set - set an area of a bitmap
5845 * @eb: the extent buffer
5846 * @start: offset of the bitmap item in the extent buffer
5847 * @pos: bit number of the first bit
5848 * @len: number of bits to set
5849 */
5850 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5851 unsigned long pos, unsigned long len)
5852 {
5853 u8 *kaddr;
5854 struct page *page;
5855 unsigned long i;
5856 size_t offset;
5857 const unsigned int size = pos + len;
5858 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5859 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5860
5861 eb_bitmap_offset(eb, start, pos, &i, &offset);
5862 page = eb->pages[i];
5863 WARN_ON(!PageUptodate(page));
5864 kaddr = page_address(page);
5865
5866 while (len >= bits_to_set) {
5867 kaddr[offset] |= mask_to_set;
5868 len -= bits_to_set;
5869 bits_to_set = BITS_PER_BYTE;
5870 mask_to_set = ~0;
5871 if (++offset >= PAGE_SIZE && len > 0) {
5872 offset = 0;
5873 page = eb->pages[++i];
5874 WARN_ON(!PageUptodate(page));
5875 kaddr = page_address(page);
5876 }
5877 }
5878 if (len) {
5879 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5880 kaddr[offset] |= mask_to_set;
5881 }
5882 }
5883
5884
5885 /**
5886 * extent_buffer_bitmap_clear - clear an area of a bitmap
5887 * @eb: the extent buffer
5888 * @start: offset of the bitmap item in the extent buffer
5889 * @pos: bit number of the first bit
5890 * @len: number of bits to clear
5891 */
5892 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5893 unsigned long pos, unsigned long len)
5894 {
5895 u8 *kaddr;
5896 struct page *page;
5897 unsigned long i;
5898 size_t offset;
5899 const unsigned int size = pos + len;
5900 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5901 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5902
5903 eb_bitmap_offset(eb, start, pos, &i, &offset);
5904 page = eb->pages[i];
5905 WARN_ON(!PageUptodate(page));
5906 kaddr = page_address(page);
5907
5908 while (len >= bits_to_clear) {
5909 kaddr[offset] &= ~mask_to_clear;
5910 len -= bits_to_clear;
5911 bits_to_clear = BITS_PER_BYTE;
5912 mask_to_clear = ~0;
5913 if (++offset >= PAGE_SIZE && len > 0) {
5914 offset = 0;
5915 page = eb->pages[++i];
5916 WARN_ON(!PageUptodate(page));
5917 kaddr = page_address(page);
5918 }
5919 }
5920 if (len) {
5921 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5922 kaddr[offset] &= ~mask_to_clear;
5923 }
5924 }
5925
5926 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5927 {
5928 unsigned long distance = (src > dst) ? src - dst : dst - src;
5929 return distance < len;
5930 }
5931
5932 static void copy_pages(struct page *dst_page, struct page *src_page,
5933 unsigned long dst_off, unsigned long src_off,
5934 unsigned long len)
5935 {
5936 char *dst_kaddr = page_address(dst_page);
5937 char *src_kaddr;
5938 int must_memmove = 0;
5939
5940 if (dst_page != src_page) {
5941 src_kaddr = page_address(src_page);
5942 } else {
5943 src_kaddr = dst_kaddr;
5944 if (areas_overlap(src_off, dst_off, len))
5945 must_memmove = 1;
5946 }
5947
5948 if (must_memmove)
5949 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5950 else
5951 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5952 }
5953
5954 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5955 unsigned long src_offset, unsigned long len)
5956 {
5957 struct btrfs_fs_info *fs_info = dst->fs_info;
5958 size_t cur;
5959 size_t dst_off_in_page;
5960 size_t src_off_in_page;
5961 size_t start_offset = offset_in_page(dst->start);
5962 unsigned long dst_i;
5963 unsigned long src_i;
5964
5965 if (src_offset + len > dst->len) {
5966 btrfs_err(fs_info,
5967 "memmove bogus src_offset %lu move len %lu dst len %lu",
5968 src_offset, len, dst->len);
5969 BUG();
5970 }
5971 if (dst_offset + len > dst->len) {
5972 btrfs_err(fs_info,
5973 "memmove bogus dst_offset %lu move len %lu dst len %lu",
5974 dst_offset, len, dst->len);
5975 BUG();
5976 }
5977
5978 while (len > 0) {
5979 dst_off_in_page = offset_in_page(start_offset + dst_offset);
5980 src_off_in_page = offset_in_page(start_offset + src_offset);
5981
5982 dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
5983 src_i = (start_offset + src_offset) >> PAGE_SHIFT;
5984
5985 cur = min(len, (unsigned long)(PAGE_SIZE -
5986 src_off_in_page));
5987 cur = min_t(unsigned long, cur,
5988 (unsigned long)(PAGE_SIZE - dst_off_in_page));
5989
5990 copy_pages(dst->pages[dst_i], dst->pages[src_i],
5991 dst_off_in_page, src_off_in_page, cur);
5992
5993 src_offset += cur;
5994 dst_offset += cur;
5995 len -= cur;
5996 }
5997 }
5998
5999 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
6000 unsigned long src_offset, unsigned long len)
6001 {
6002 struct btrfs_fs_info *fs_info = dst->fs_info;
6003 size_t cur;
6004 size_t dst_off_in_page;
6005 size_t src_off_in_page;
6006 unsigned long dst_end = dst_offset + len - 1;
6007 unsigned long src_end = src_offset + len - 1;
6008 size_t start_offset = offset_in_page(dst->start);
6009 unsigned long dst_i;
6010 unsigned long src_i;
6011
6012 if (src_offset + len > dst->len) {
6013 btrfs_err(fs_info,
6014 "memmove bogus src_offset %lu move len %lu len %lu",
6015 src_offset, len, dst->len);
6016 BUG();
6017 }
6018 if (dst_offset + len > dst->len) {
6019 btrfs_err(fs_info,
6020 "memmove bogus dst_offset %lu move len %lu len %lu",
6021 dst_offset, len, dst->len);
6022 BUG();
6023 }
6024 if (dst_offset < src_offset) {
6025 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6026 return;
6027 }
6028 while (len > 0) {
6029 dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
6030 src_i = (start_offset + src_end) >> PAGE_SHIFT;
6031
6032 dst_off_in_page = offset_in_page(start_offset + dst_end);
6033 src_off_in_page = offset_in_page(start_offset + src_end);
6034
6035 cur = min_t(unsigned long, len, src_off_in_page + 1);
6036 cur = min(cur, dst_off_in_page + 1);
6037 copy_pages(dst->pages[dst_i], dst->pages[src_i],
6038 dst_off_in_page - cur + 1,
6039 src_off_in_page - cur + 1, cur);
6040
6041 dst_end -= cur;
6042 src_end -= cur;
6043 len -= cur;
6044 }
6045 }
6046
6047 int try_release_extent_buffer(struct page *page)
6048 {
6049 struct extent_buffer *eb;
6050
6051 /*
6052 * We need to make sure nobody is attaching this page to an eb right
6053 * now.
6054 */
6055 spin_lock(&page->mapping->private_lock);
6056 if (!PagePrivate(page)) {
6057 spin_unlock(&page->mapping->private_lock);
6058 return 1;
6059 }
6060
6061 eb = (struct extent_buffer *)page->private;
6062 BUG_ON(!eb);
6063
6064 /*
6065 * This is a little awful but should be ok, we need to make sure that
6066 * the eb doesn't disappear out from under us while we're looking at
6067 * this page.
6068 */
6069 spin_lock(&eb->refs_lock);
6070 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6071 spin_unlock(&eb->refs_lock);
6072 spin_unlock(&page->mapping->private_lock);
6073 return 0;
6074 }
6075 spin_unlock(&page->mapping->private_lock);
6076
6077 /*
6078 * If tree ref isn't set then we know the ref on this eb is a real ref,
6079 * so just return, this page will likely be freed soon anyway.
6080 */
6081 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6082 spin_unlock(&eb->refs_lock);
6083 return 0;
6084 }
6085
6086 return release_extent_buffer(eb);
6087 }