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