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