]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/extent_io.c
fs: push rcu_barrier() from deactivate_locked_super() to filesystems
[karo-tx-linux.git] / fs / btrfs / extent_io.c
1 #include <linux/bitops.h>
2 #include <linux/slab.h>
3 #include <linux/bio.h>
4 #include <linux/mm.h>
5 #include <linux/pagemap.h>
6 #include <linux/page-flags.h>
7 #include <linux/module.h>
8 #include <linux/spinlock.h>
9 #include <linux/blkdev.h>
10 #include <linux/swap.h>
11 #include <linux/writeback.h>
12 #include <linux/pagevec.h>
13 #include <linux/prefetch.h>
14 #include <linux/cleancache.h>
15 #include "extent_io.h"
16 #include "extent_map.h"
17 #include "compat.h"
18 #include "ctree.h"
19 #include "btrfs_inode.h"
20 #include "volumes.h"
21 #include "check-integrity.h"
22 #include "locking.h"
23 #include "rcu-string.h"
24
25 static struct kmem_cache *extent_state_cache;
26 static struct kmem_cache *extent_buffer_cache;
27
28 static LIST_HEAD(buffers);
29 static LIST_HEAD(states);
30
31 #define LEAK_DEBUG 0
32 #if LEAK_DEBUG
33 static DEFINE_SPINLOCK(leak_lock);
34 #endif
35
36 #define BUFFER_LRU_MAX 64
37
38 struct tree_entry {
39         u64 start;
40         u64 end;
41         struct rb_node rb_node;
42 };
43
44 struct extent_page_data {
45         struct bio *bio;
46         struct extent_io_tree *tree;
47         get_extent_t *get_extent;
48
49         /* tells writepage not to lock the state bits for this range
50          * it still does the unlocking
51          */
52         unsigned int extent_locked:1;
53
54         /* tells the submit_bio code to use a WRITE_SYNC */
55         unsigned int sync_io:1;
56 };
57
58 static noinline void flush_write_bio(void *data);
59 static inline struct btrfs_fs_info *
60 tree_fs_info(struct extent_io_tree *tree)
61 {
62         return btrfs_sb(tree->mapping->host->i_sb);
63 }
64
65 int __init extent_io_init(void)
66 {
67         extent_state_cache = kmem_cache_create("extent_state",
68                         sizeof(struct extent_state), 0,
69                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
70         if (!extent_state_cache)
71                 return -ENOMEM;
72
73         extent_buffer_cache = kmem_cache_create("extent_buffers",
74                         sizeof(struct extent_buffer), 0,
75                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
76         if (!extent_buffer_cache)
77                 goto free_state_cache;
78         return 0;
79
80 free_state_cache:
81         kmem_cache_destroy(extent_state_cache);
82         return -ENOMEM;
83 }
84
85 void extent_io_exit(void)
86 {
87         struct extent_state *state;
88         struct extent_buffer *eb;
89
90         while (!list_empty(&states)) {
91                 state = list_entry(states.next, struct extent_state, leak_list);
92                 printk(KERN_ERR "btrfs state leak: start %llu end %llu "
93                        "state %lu in tree %p refs %d\n",
94                        (unsigned long long)state->start,
95                        (unsigned long long)state->end,
96                        state->state, state->tree, atomic_read(&state->refs));
97                 list_del(&state->leak_list);
98                 kmem_cache_free(extent_state_cache, state);
99
100         }
101
102         while (!list_empty(&buffers)) {
103                 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
104                 printk(KERN_ERR "btrfs buffer leak start %llu len %lu "
105                        "refs %d\n", (unsigned long long)eb->start,
106                        eb->len, atomic_read(&eb->refs));
107                 list_del(&eb->leak_list);
108                 kmem_cache_free(extent_buffer_cache, eb);
109         }
110
111         /*
112          * Make sure all delayed rcu free are flushed before we
113          * destroy caches.
114          */
115         rcu_barrier();
116         if (extent_state_cache)
117                 kmem_cache_destroy(extent_state_cache);
118         if (extent_buffer_cache)
119                 kmem_cache_destroy(extent_buffer_cache);
120 }
121
122 void extent_io_tree_init(struct extent_io_tree *tree,
123                          struct address_space *mapping)
124 {
125         tree->state = RB_ROOT;
126         INIT_RADIX_TREE(&tree->buffer, GFP_ATOMIC);
127         tree->ops = NULL;
128         tree->dirty_bytes = 0;
129         spin_lock_init(&tree->lock);
130         spin_lock_init(&tree->buffer_lock);
131         tree->mapping = mapping;
132 }
133
134 static struct extent_state *alloc_extent_state(gfp_t mask)
135 {
136         struct extent_state *state;
137 #if LEAK_DEBUG
138         unsigned long flags;
139 #endif
140
141         state = kmem_cache_alloc(extent_state_cache, mask);
142         if (!state)
143                 return state;
144         state->state = 0;
145         state->private = 0;
146         state->tree = NULL;
147 #if LEAK_DEBUG
148         spin_lock_irqsave(&leak_lock, flags);
149         list_add(&state->leak_list, &states);
150         spin_unlock_irqrestore(&leak_lock, flags);
151 #endif
152         atomic_set(&state->refs, 1);
153         init_waitqueue_head(&state->wq);
154         trace_alloc_extent_state(state, mask, _RET_IP_);
155         return state;
156 }
157
158 void free_extent_state(struct extent_state *state)
159 {
160         if (!state)
161                 return;
162         if (atomic_dec_and_test(&state->refs)) {
163 #if LEAK_DEBUG
164                 unsigned long flags;
165 #endif
166                 WARN_ON(state->tree);
167 #if LEAK_DEBUG
168                 spin_lock_irqsave(&leak_lock, flags);
169                 list_del(&state->leak_list);
170                 spin_unlock_irqrestore(&leak_lock, flags);
171 #endif
172                 trace_free_extent_state(state, _RET_IP_);
173                 kmem_cache_free(extent_state_cache, state);
174         }
175 }
176
177 static struct rb_node *tree_insert(struct rb_root *root, u64 offset,
178                                    struct rb_node *node)
179 {
180         struct rb_node **p = &root->rb_node;
181         struct rb_node *parent = NULL;
182         struct tree_entry *entry;
183
184         while (*p) {
185                 parent = *p;
186                 entry = rb_entry(parent, struct tree_entry, rb_node);
187
188                 if (offset < entry->start)
189                         p = &(*p)->rb_left;
190                 else if (offset > entry->end)
191                         p = &(*p)->rb_right;
192                 else
193                         return parent;
194         }
195
196         rb_link_node(node, parent, p);
197         rb_insert_color(node, root);
198         return NULL;
199 }
200
201 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
202                                      struct rb_node **prev_ret,
203                                      struct rb_node **next_ret)
204 {
205         struct rb_root *root = &tree->state;
206         struct rb_node *n = root->rb_node;
207         struct rb_node *prev = NULL;
208         struct rb_node *orig_prev = NULL;
209         struct tree_entry *entry;
210         struct tree_entry *prev_entry = NULL;
211
212         while (n) {
213                 entry = rb_entry(n, struct tree_entry, rb_node);
214                 prev = n;
215                 prev_entry = entry;
216
217                 if (offset < entry->start)
218                         n = n->rb_left;
219                 else if (offset > entry->end)
220                         n = n->rb_right;
221                 else
222                         return n;
223         }
224
225         if (prev_ret) {
226                 orig_prev = prev;
227                 while (prev && offset > prev_entry->end) {
228                         prev = rb_next(prev);
229                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
230                 }
231                 *prev_ret = prev;
232                 prev = orig_prev;
233         }
234
235         if (next_ret) {
236                 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
237                 while (prev && offset < prev_entry->start) {
238                         prev = rb_prev(prev);
239                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
240                 }
241                 *next_ret = prev;
242         }
243         return NULL;
244 }
245
246 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
247                                           u64 offset)
248 {
249         struct rb_node *prev = NULL;
250         struct rb_node *ret;
251
252         ret = __etree_search(tree, offset, &prev, NULL);
253         if (!ret)
254                 return prev;
255         return ret;
256 }
257
258 static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
259                      struct extent_state *other)
260 {
261         if (tree->ops && tree->ops->merge_extent_hook)
262                 tree->ops->merge_extent_hook(tree->mapping->host, new,
263                                              other);
264 }
265
266 /*
267  * utility function to look for merge candidates inside a given range.
268  * Any extents with matching state are merged together into a single
269  * extent in the tree.  Extents with EXTENT_IO in their state field
270  * are not merged because the end_io handlers need to be able to do
271  * operations on them without sleeping (or doing allocations/splits).
272  *
273  * This should be called with the tree lock held.
274  */
275 static void merge_state(struct extent_io_tree *tree,
276                         struct extent_state *state)
277 {
278         struct extent_state *other;
279         struct rb_node *other_node;
280
281         if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
282                 return;
283
284         other_node = rb_prev(&state->rb_node);
285         if (other_node) {
286                 other = rb_entry(other_node, struct extent_state, rb_node);
287                 if (other->end == state->start - 1 &&
288                     other->state == state->state) {
289                         merge_cb(tree, state, other);
290                         state->start = other->start;
291                         other->tree = NULL;
292                         rb_erase(&other->rb_node, &tree->state);
293                         free_extent_state(other);
294                 }
295         }
296         other_node = rb_next(&state->rb_node);
297         if (other_node) {
298                 other = rb_entry(other_node, struct extent_state, rb_node);
299                 if (other->start == state->end + 1 &&
300                     other->state == state->state) {
301                         merge_cb(tree, state, other);
302                         state->end = other->end;
303                         other->tree = NULL;
304                         rb_erase(&other->rb_node, &tree->state);
305                         free_extent_state(other);
306                 }
307         }
308 }
309
310 static void set_state_cb(struct extent_io_tree *tree,
311                          struct extent_state *state, int *bits)
312 {
313         if (tree->ops && tree->ops->set_bit_hook)
314                 tree->ops->set_bit_hook(tree->mapping->host, state, bits);
315 }
316
317 static void clear_state_cb(struct extent_io_tree *tree,
318                            struct extent_state *state, int *bits)
319 {
320         if (tree->ops && tree->ops->clear_bit_hook)
321                 tree->ops->clear_bit_hook(tree->mapping->host, state, bits);
322 }
323
324 static void set_state_bits(struct extent_io_tree *tree,
325                            struct extent_state *state, int *bits);
326
327 /*
328  * insert an extent_state struct into the tree.  'bits' are set on the
329  * struct before it is inserted.
330  *
331  * This may return -EEXIST if the extent is already there, in which case the
332  * state struct is freed.
333  *
334  * The tree lock is not taken internally.  This is a utility function and
335  * probably isn't what you want to call (see set/clear_extent_bit).
336  */
337 static int insert_state(struct extent_io_tree *tree,
338                         struct extent_state *state, u64 start, u64 end,
339                         int *bits)
340 {
341         struct rb_node *node;
342
343         if (end < start) {
344                 printk(KERN_ERR "btrfs end < start %llu %llu\n",
345                        (unsigned long long)end,
346                        (unsigned long long)start);
347                 WARN_ON(1);
348         }
349         state->start = start;
350         state->end = end;
351
352         set_state_bits(tree, state, bits);
353
354         node = tree_insert(&tree->state, end, &state->rb_node);
355         if (node) {
356                 struct extent_state *found;
357                 found = rb_entry(node, struct extent_state, rb_node);
358                 printk(KERN_ERR "btrfs found node %llu %llu on insert of "
359                        "%llu %llu\n", (unsigned long long)found->start,
360                        (unsigned long long)found->end,
361                        (unsigned long long)start, (unsigned long long)end);
362                 return -EEXIST;
363         }
364         state->tree = tree;
365         merge_state(tree, state);
366         return 0;
367 }
368
369 static void split_cb(struct extent_io_tree *tree, struct extent_state *orig,
370                      u64 split)
371 {
372         if (tree->ops && tree->ops->split_extent_hook)
373                 tree->ops->split_extent_hook(tree->mapping->host, orig, split);
374 }
375
376 /*
377  * split a given extent state struct in two, inserting the preallocated
378  * struct 'prealloc' as the newly created second half.  'split' indicates an
379  * offset inside 'orig' where it should be split.
380  *
381  * Before calling,
382  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
383  * are two extent state structs in the tree:
384  * prealloc: [orig->start, split - 1]
385  * orig: [ split, orig->end ]
386  *
387  * The tree locks are not taken by this function. They need to be held
388  * by the caller.
389  */
390 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
391                        struct extent_state *prealloc, u64 split)
392 {
393         struct rb_node *node;
394
395         split_cb(tree, orig, split);
396
397         prealloc->start = orig->start;
398         prealloc->end = split - 1;
399         prealloc->state = orig->state;
400         orig->start = split;
401
402         node = tree_insert(&tree->state, prealloc->end, &prealloc->rb_node);
403         if (node) {
404                 free_extent_state(prealloc);
405                 return -EEXIST;
406         }
407         prealloc->tree = tree;
408         return 0;
409 }
410
411 static struct extent_state *next_state(struct extent_state *state)
412 {
413         struct rb_node *next = rb_next(&state->rb_node);
414         if (next)
415                 return rb_entry(next, struct extent_state, rb_node);
416         else
417                 return NULL;
418 }
419
420 /*
421  * utility function to clear some bits in an extent state struct.
422  * it will optionally wake up any one waiting on this state (wake == 1).
423  *
424  * If no bits are set on the state struct after clearing things, the
425  * struct is freed and removed from the tree
426  */
427 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
428                                             struct extent_state *state,
429                                             int *bits, int wake)
430 {
431         struct extent_state *next;
432         int bits_to_clear = *bits & ~EXTENT_CTLBITS;
433
434         if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
435                 u64 range = state->end - state->start + 1;
436                 WARN_ON(range > tree->dirty_bytes);
437                 tree->dirty_bytes -= range;
438         }
439         clear_state_cb(tree, state, bits);
440         state->state &= ~bits_to_clear;
441         if (wake)
442                 wake_up(&state->wq);
443         if (state->state == 0) {
444                 next = next_state(state);
445                 if (state->tree) {
446                         rb_erase(&state->rb_node, &tree->state);
447                         state->tree = NULL;
448                         free_extent_state(state);
449                 } else {
450                         WARN_ON(1);
451                 }
452         } else {
453                 merge_state(tree, state);
454                 next = next_state(state);
455         }
456         return next;
457 }
458
459 static struct extent_state *
460 alloc_extent_state_atomic(struct extent_state *prealloc)
461 {
462         if (!prealloc)
463                 prealloc = alloc_extent_state(GFP_ATOMIC);
464
465         return prealloc;
466 }
467
468 void extent_io_tree_panic(struct extent_io_tree *tree, int err)
469 {
470         btrfs_panic(tree_fs_info(tree), err, "Locking error: "
471                     "Extent tree was modified by another "
472                     "thread while locked.");
473 }
474
475 /*
476  * clear some bits on a range in the tree.  This may require splitting
477  * or inserting elements in the tree, so the gfp mask is used to
478  * indicate which allocations or sleeping are allowed.
479  *
480  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
481  * the given range from the tree regardless of state (ie for truncate).
482  *
483  * the range [start, end] is inclusive.
484  *
485  * This takes the tree lock, and returns 0 on success and < 0 on error.
486  */
487 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
488                      int bits, int wake, int delete,
489                      struct extent_state **cached_state,
490                      gfp_t mask)
491 {
492         struct extent_state *state;
493         struct extent_state *cached;
494         struct extent_state *prealloc = NULL;
495         struct rb_node *node;
496         u64 last_end;
497         int err;
498         int clear = 0;
499
500         if (delete)
501                 bits |= ~EXTENT_CTLBITS;
502         bits |= EXTENT_FIRST_DELALLOC;
503
504         if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
505                 clear = 1;
506 again:
507         if (!prealloc && (mask & __GFP_WAIT)) {
508                 prealloc = alloc_extent_state(mask);
509                 if (!prealloc)
510                         return -ENOMEM;
511         }
512
513         spin_lock(&tree->lock);
514         if (cached_state) {
515                 cached = *cached_state;
516
517                 if (clear) {
518                         *cached_state = NULL;
519                         cached_state = NULL;
520                 }
521
522                 if (cached && cached->tree && cached->start <= start &&
523                     cached->end > start) {
524                         if (clear)
525                                 atomic_dec(&cached->refs);
526                         state = cached;
527                         goto hit_next;
528                 }
529                 if (clear)
530                         free_extent_state(cached);
531         }
532         /*
533          * this search will find the extents that end after
534          * our range starts
535          */
536         node = tree_search(tree, start);
537         if (!node)
538                 goto out;
539         state = rb_entry(node, struct extent_state, rb_node);
540 hit_next:
541         if (state->start > end)
542                 goto out;
543         WARN_ON(state->end < start);
544         last_end = state->end;
545
546         /* the state doesn't have the wanted bits, go ahead */
547         if (!(state->state & bits)) {
548                 state = next_state(state);
549                 goto next;
550         }
551
552         /*
553          *     | ---- desired range ---- |
554          *  | state | or
555          *  | ------------- state -------------- |
556          *
557          * We need to split the extent we found, and may flip
558          * bits on second half.
559          *
560          * If the extent we found extends past our range, we
561          * just split and search again.  It'll get split again
562          * the next time though.
563          *
564          * If the extent we found is inside our range, we clear
565          * the desired bit on it.
566          */
567
568         if (state->start < start) {
569                 prealloc = alloc_extent_state_atomic(prealloc);
570                 BUG_ON(!prealloc);
571                 err = split_state(tree, state, prealloc, start);
572                 if (err)
573                         extent_io_tree_panic(tree, err);
574
575                 prealloc = NULL;
576                 if (err)
577                         goto out;
578                 if (state->end <= end) {
579                         state = clear_state_bit(tree, state, &bits, wake);
580                         goto next;
581                 }
582                 goto search_again;
583         }
584         /*
585          * | ---- desired range ---- |
586          *                        | state |
587          * We need to split the extent, and clear the bit
588          * on the first half
589          */
590         if (state->start <= end && state->end > end) {
591                 prealloc = alloc_extent_state_atomic(prealloc);
592                 BUG_ON(!prealloc);
593                 err = split_state(tree, state, prealloc, end + 1);
594                 if (err)
595                         extent_io_tree_panic(tree, err);
596
597                 if (wake)
598                         wake_up(&state->wq);
599
600                 clear_state_bit(tree, prealloc, &bits, wake);
601
602                 prealloc = NULL;
603                 goto out;
604         }
605
606         state = clear_state_bit(tree, state, &bits, wake);
607 next:
608         if (last_end == (u64)-1)
609                 goto out;
610         start = last_end + 1;
611         if (start <= end && state && !need_resched())
612                 goto hit_next;
613         goto search_again;
614
615 out:
616         spin_unlock(&tree->lock);
617         if (prealloc)
618                 free_extent_state(prealloc);
619
620         return 0;
621
622 search_again:
623         if (start > end)
624                 goto out;
625         spin_unlock(&tree->lock);
626         if (mask & __GFP_WAIT)
627                 cond_resched();
628         goto again;
629 }
630
631 static void wait_on_state(struct extent_io_tree *tree,
632                           struct extent_state *state)
633                 __releases(tree->lock)
634                 __acquires(tree->lock)
635 {
636         DEFINE_WAIT(wait);
637         prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
638         spin_unlock(&tree->lock);
639         schedule();
640         spin_lock(&tree->lock);
641         finish_wait(&state->wq, &wait);
642 }
643
644 /*
645  * waits for one or more bits to clear on a range in the state tree.
646  * The range [start, end] is inclusive.
647  * The tree lock is taken by this function
648  */
649 void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, int bits)
650 {
651         struct extent_state *state;
652         struct rb_node *node;
653
654         spin_lock(&tree->lock);
655 again:
656         while (1) {
657                 /*
658                  * this search will find all the extents that end after
659                  * our range starts
660                  */
661                 node = tree_search(tree, start);
662                 if (!node)
663                         break;
664
665                 state = rb_entry(node, struct extent_state, rb_node);
666
667                 if (state->start > end)
668                         goto out;
669
670                 if (state->state & bits) {
671                         start = state->start;
672                         atomic_inc(&state->refs);
673                         wait_on_state(tree, state);
674                         free_extent_state(state);
675                         goto again;
676                 }
677                 start = state->end + 1;
678
679                 if (start > end)
680                         break;
681
682                 cond_resched_lock(&tree->lock);
683         }
684 out:
685         spin_unlock(&tree->lock);
686 }
687
688 static void set_state_bits(struct extent_io_tree *tree,
689                            struct extent_state *state,
690                            int *bits)
691 {
692         int bits_to_set = *bits & ~EXTENT_CTLBITS;
693
694         set_state_cb(tree, state, bits);
695         if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
696                 u64 range = state->end - state->start + 1;
697                 tree->dirty_bytes += range;
698         }
699         state->state |= bits_to_set;
700 }
701
702 static void cache_state(struct extent_state *state,
703                         struct extent_state **cached_ptr)
704 {
705         if (cached_ptr && !(*cached_ptr)) {
706                 if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY)) {
707                         *cached_ptr = state;
708                         atomic_inc(&state->refs);
709                 }
710         }
711 }
712
713 static void uncache_state(struct extent_state **cached_ptr)
714 {
715         if (cached_ptr && (*cached_ptr)) {
716                 struct extent_state *state = *cached_ptr;
717                 *cached_ptr = NULL;
718                 free_extent_state(state);
719         }
720 }
721
722 /*
723  * set some bits on a range in the tree.  This may require allocations or
724  * sleeping, so the gfp mask is used to indicate what is allowed.
725  *
726  * If any of the exclusive bits are set, this will fail with -EEXIST if some
727  * part of the range already has the desired bits set.  The start of the
728  * existing range is returned in failed_start in this case.
729  *
730  * [start, end] is inclusive This takes the tree lock.
731  */
732
733 static int __must_check
734 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
735                  int bits, int exclusive_bits, u64 *failed_start,
736                  struct extent_state **cached_state, gfp_t mask)
737 {
738         struct extent_state *state;
739         struct extent_state *prealloc = NULL;
740         struct rb_node *node;
741         int err = 0;
742         u64 last_start;
743         u64 last_end;
744
745         bits |= EXTENT_FIRST_DELALLOC;
746 again:
747         if (!prealloc && (mask & __GFP_WAIT)) {
748                 prealloc = alloc_extent_state(mask);
749                 BUG_ON(!prealloc);
750         }
751
752         spin_lock(&tree->lock);
753         if (cached_state && *cached_state) {
754                 state = *cached_state;
755                 if (state->start <= start && state->end > start &&
756                     state->tree) {
757                         node = &state->rb_node;
758                         goto hit_next;
759                 }
760         }
761         /*
762          * this search will find all the extents that end after
763          * our range starts.
764          */
765         node = tree_search(tree, start);
766         if (!node) {
767                 prealloc = alloc_extent_state_atomic(prealloc);
768                 BUG_ON(!prealloc);
769                 err = insert_state(tree, prealloc, start, end, &bits);
770                 if (err)
771                         extent_io_tree_panic(tree, err);
772
773                 prealloc = NULL;
774                 goto out;
775         }
776         state = rb_entry(node, struct extent_state, rb_node);
777 hit_next:
778         last_start = state->start;
779         last_end = state->end;
780
781         /*
782          * | ---- desired range ---- |
783          * | state |
784          *
785          * Just lock what we found and keep going
786          */
787         if (state->start == start && state->end <= end) {
788                 if (state->state & exclusive_bits) {
789                         *failed_start = state->start;
790                         err = -EEXIST;
791                         goto out;
792                 }
793
794                 set_state_bits(tree, state, &bits);
795                 cache_state(state, cached_state);
796                 merge_state(tree, state);
797                 if (last_end == (u64)-1)
798                         goto out;
799                 start = last_end + 1;
800                 state = next_state(state);
801                 if (start < end && state && state->start == start &&
802                     !need_resched())
803                         goto hit_next;
804                 goto search_again;
805         }
806
807         /*
808          *     | ---- desired range ---- |
809          * | state |
810          *   or
811          * | ------------- state -------------- |
812          *
813          * We need to split the extent we found, and may flip bits on
814          * second half.
815          *
816          * If the extent we found extends past our
817          * range, we just split and search again.  It'll get split
818          * again the next time though.
819          *
820          * If the extent we found is inside our range, we set the
821          * desired bit on it.
822          */
823         if (state->start < start) {
824                 if (state->state & exclusive_bits) {
825                         *failed_start = start;
826                         err = -EEXIST;
827                         goto out;
828                 }
829
830                 prealloc = alloc_extent_state_atomic(prealloc);
831                 BUG_ON(!prealloc);
832                 err = split_state(tree, state, prealloc, start);
833                 if (err)
834                         extent_io_tree_panic(tree, err);
835
836                 prealloc = NULL;
837                 if (err)
838                         goto out;
839                 if (state->end <= end) {
840                         set_state_bits(tree, state, &bits);
841                         cache_state(state, cached_state);
842                         merge_state(tree, state);
843                         if (last_end == (u64)-1)
844                                 goto out;
845                         start = last_end + 1;
846                         state = next_state(state);
847                         if (start < end && state && state->start == start &&
848                             !need_resched())
849                                 goto hit_next;
850                 }
851                 goto search_again;
852         }
853         /*
854          * | ---- desired range ---- |
855          *     | state | or               | state |
856          *
857          * There's a hole, we need to insert something in it and
858          * ignore the extent we found.
859          */
860         if (state->start > start) {
861                 u64 this_end;
862                 if (end < last_start)
863                         this_end = end;
864                 else
865                         this_end = last_start - 1;
866
867                 prealloc = alloc_extent_state_atomic(prealloc);
868                 BUG_ON(!prealloc);
869
870                 /*
871                  * Avoid to free 'prealloc' if it can be merged with
872                  * the later extent.
873                  */
874                 err = insert_state(tree, prealloc, start, this_end,
875                                    &bits);
876                 if (err)
877                         extent_io_tree_panic(tree, err);
878
879                 cache_state(prealloc, cached_state);
880                 prealloc = NULL;
881                 start = this_end + 1;
882                 goto search_again;
883         }
884         /*
885          * | ---- desired range ---- |
886          *                        | state |
887          * We need to split the extent, and set the bit
888          * on the first half
889          */
890         if (state->start <= end && state->end > end) {
891                 if (state->state & exclusive_bits) {
892                         *failed_start = start;
893                         err = -EEXIST;
894                         goto out;
895                 }
896
897                 prealloc = alloc_extent_state_atomic(prealloc);
898                 BUG_ON(!prealloc);
899                 err = split_state(tree, state, prealloc, end + 1);
900                 if (err)
901                         extent_io_tree_panic(tree, err);
902
903                 set_state_bits(tree, prealloc, &bits);
904                 cache_state(prealloc, cached_state);
905                 merge_state(tree, prealloc);
906                 prealloc = NULL;
907                 goto out;
908         }
909
910         goto search_again;
911
912 out:
913         spin_unlock(&tree->lock);
914         if (prealloc)
915                 free_extent_state(prealloc);
916
917         return err;
918
919 search_again:
920         if (start > end)
921                 goto out;
922         spin_unlock(&tree->lock);
923         if (mask & __GFP_WAIT)
924                 cond_resched();
925         goto again;
926 }
927
928 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, int bits,
929                    u64 *failed_start, struct extent_state **cached_state,
930                    gfp_t mask)
931 {
932         return __set_extent_bit(tree, start, end, bits, 0, failed_start,
933                                 cached_state, mask);
934 }
935
936
937 /**
938  * convert_extent_bit - convert all bits in a given range from one bit to
939  *                      another
940  * @tree:       the io tree to search
941  * @start:      the start offset in bytes
942  * @end:        the end offset in bytes (inclusive)
943  * @bits:       the bits to set in this range
944  * @clear_bits: the bits to clear in this range
945  * @mask:       the allocation mask
946  *
947  * This will go through and set bits for the given range.  If any states exist
948  * already in this range they are set with the given bit and cleared of the
949  * clear_bits.  This is only meant to be used by things that are mergeable, ie
950  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
951  * boundary bits like LOCK.
952  */
953 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
954                        int bits, int clear_bits, gfp_t mask)
955 {
956         struct extent_state *state;
957         struct extent_state *prealloc = NULL;
958         struct rb_node *node;
959         int err = 0;
960         u64 last_start;
961         u64 last_end;
962
963 again:
964         if (!prealloc && (mask & __GFP_WAIT)) {
965                 prealloc = alloc_extent_state(mask);
966                 if (!prealloc)
967                         return -ENOMEM;
968         }
969
970         spin_lock(&tree->lock);
971         /*
972          * this search will find all the extents that end after
973          * our range starts.
974          */
975         node = tree_search(tree, start);
976         if (!node) {
977                 prealloc = alloc_extent_state_atomic(prealloc);
978                 if (!prealloc) {
979                         err = -ENOMEM;
980                         goto out;
981                 }
982                 err = insert_state(tree, prealloc, start, end, &bits);
983                 prealloc = NULL;
984                 if (err)
985                         extent_io_tree_panic(tree, err);
986                 goto out;
987         }
988         state = rb_entry(node, struct extent_state, rb_node);
989 hit_next:
990         last_start = state->start;
991         last_end = state->end;
992
993         /*
994          * | ---- desired range ---- |
995          * | state |
996          *
997          * Just lock what we found and keep going
998          */
999         if (state->start == start && state->end <= end) {
1000                 set_state_bits(tree, state, &bits);
1001                 state = clear_state_bit(tree, state, &clear_bits, 0);
1002                 if (last_end == (u64)-1)
1003                         goto out;
1004                 start = last_end + 1;
1005                 if (start < end && state && state->start == start &&
1006                     !need_resched())
1007                         goto hit_next;
1008                 goto search_again;
1009         }
1010
1011         /*
1012          *     | ---- desired range ---- |
1013          * | state |
1014          *   or
1015          * | ------------- state -------------- |
1016          *
1017          * We need to split the extent we found, and may flip bits on
1018          * second half.
1019          *
1020          * If the extent we found extends past our
1021          * range, we just split and search again.  It'll get split
1022          * again the next time though.
1023          *
1024          * If the extent we found is inside our range, we set the
1025          * desired bit on it.
1026          */
1027         if (state->start < start) {
1028                 prealloc = alloc_extent_state_atomic(prealloc);
1029                 if (!prealloc) {
1030                         err = -ENOMEM;
1031                         goto out;
1032                 }
1033                 err = split_state(tree, state, prealloc, start);
1034                 if (err)
1035                         extent_io_tree_panic(tree, err);
1036                 prealloc = NULL;
1037                 if (err)
1038                         goto out;
1039                 if (state->end <= end) {
1040                         set_state_bits(tree, state, &bits);
1041                         state = clear_state_bit(tree, state, &clear_bits, 0);
1042                         if (last_end == (u64)-1)
1043                                 goto out;
1044                         start = last_end + 1;
1045                         if (start < end && state && state->start == start &&
1046                             !need_resched())
1047                                 goto hit_next;
1048                 }
1049                 goto search_again;
1050         }
1051         /*
1052          * | ---- desired range ---- |
1053          *     | state | or               | state |
1054          *
1055          * There's a hole, we need to insert something in it and
1056          * ignore the extent we found.
1057          */
1058         if (state->start > start) {
1059                 u64 this_end;
1060                 if (end < last_start)
1061                         this_end = end;
1062                 else
1063                         this_end = last_start - 1;
1064
1065                 prealloc = alloc_extent_state_atomic(prealloc);
1066                 if (!prealloc) {
1067                         err = -ENOMEM;
1068                         goto out;
1069                 }
1070
1071                 /*
1072                  * Avoid to free 'prealloc' if it can be merged with
1073                  * the later extent.
1074                  */
1075                 err = insert_state(tree, prealloc, start, this_end,
1076                                    &bits);
1077                 if (err)
1078                         extent_io_tree_panic(tree, err);
1079                 prealloc = NULL;
1080                 start = this_end + 1;
1081                 goto search_again;
1082         }
1083         /*
1084          * | ---- desired range ---- |
1085          *                        | state |
1086          * We need to split the extent, and set the bit
1087          * on the first half
1088          */
1089         if (state->start <= end && state->end > end) {
1090                 prealloc = alloc_extent_state_atomic(prealloc);
1091                 if (!prealloc) {
1092                         err = -ENOMEM;
1093                         goto out;
1094                 }
1095
1096                 err = split_state(tree, state, prealloc, end + 1);
1097                 if (err)
1098                         extent_io_tree_panic(tree, err);
1099
1100                 set_state_bits(tree, prealloc, &bits);
1101                 clear_state_bit(tree, prealloc, &clear_bits, 0);
1102                 prealloc = NULL;
1103                 goto out;
1104         }
1105
1106         goto search_again;
1107
1108 out:
1109         spin_unlock(&tree->lock);
1110         if (prealloc)
1111                 free_extent_state(prealloc);
1112
1113         return err;
1114
1115 search_again:
1116         if (start > end)
1117                 goto out;
1118         spin_unlock(&tree->lock);
1119         if (mask & __GFP_WAIT)
1120                 cond_resched();
1121         goto again;
1122 }
1123
1124 /* wrappers around set/clear extent bit */
1125 int set_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
1126                      gfp_t mask)
1127 {
1128         return set_extent_bit(tree, start, end, EXTENT_DIRTY, NULL,
1129                               NULL, mask);
1130 }
1131
1132 int set_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1133                     int bits, gfp_t mask)
1134 {
1135         return set_extent_bit(tree, start, end, bits, NULL,
1136                               NULL, mask);
1137 }
1138
1139 int clear_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1140                       int bits, gfp_t mask)
1141 {
1142         return clear_extent_bit(tree, start, end, bits, 0, 0, NULL, mask);
1143 }
1144
1145 int set_extent_delalloc(struct extent_io_tree *tree, u64 start, u64 end,
1146                         struct extent_state **cached_state, gfp_t mask)
1147 {
1148         return set_extent_bit(tree, start, end,
1149                               EXTENT_DELALLOC | EXTENT_UPTODATE,
1150                               NULL, cached_state, mask);
1151 }
1152
1153 int clear_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
1154                        gfp_t mask)
1155 {
1156         return clear_extent_bit(tree, start, end,
1157                                 EXTENT_DIRTY | EXTENT_DELALLOC |
1158                                 EXTENT_DO_ACCOUNTING, 0, 0, NULL, mask);
1159 }
1160
1161 int set_extent_new(struct extent_io_tree *tree, u64 start, u64 end,
1162                      gfp_t mask)
1163 {
1164         return set_extent_bit(tree, start, end, EXTENT_NEW, NULL,
1165                               NULL, mask);
1166 }
1167
1168 int set_extent_uptodate(struct extent_io_tree *tree, u64 start, u64 end,
1169                         struct extent_state **cached_state, gfp_t mask)
1170 {
1171         return set_extent_bit(tree, start, end, EXTENT_UPTODATE, 0,
1172                               cached_state, mask);
1173 }
1174
1175 int clear_extent_uptodate(struct extent_io_tree *tree, u64 start, u64 end,
1176                           struct extent_state **cached_state, gfp_t mask)
1177 {
1178         return clear_extent_bit(tree, start, end, EXTENT_UPTODATE, 0, 0,
1179                                 cached_state, mask);
1180 }
1181
1182 /*
1183  * either insert or lock state struct between start and end use mask to tell
1184  * us if waiting is desired.
1185  */
1186 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1187                      int bits, struct extent_state **cached_state)
1188 {
1189         int err;
1190         u64 failed_start;
1191         while (1) {
1192                 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED | bits,
1193                                        EXTENT_LOCKED, &failed_start,
1194                                        cached_state, GFP_NOFS);
1195                 if (err == -EEXIST) {
1196                         wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1197                         start = failed_start;
1198                 } else
1199                         break;
1200                 WARN_ON(start > end);
1201         }
1202         return err;
1203 }
1204
1205 int lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1206 {
1207         return lock_extent_bits(tree, start, end, 0, NULL);
1208 }
1209
1210 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1211 {
1212         int err;
1213         u64 failed_start;
1214
1215         err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1216                                &failed_start, NULL, GFP_NOFS);
1217         if (err == -EEXIST) {
1218                 if (failed_start > start)
1219                         clear_extent_bit(tree, start, failed_start - 1,
1220                                          EXTENT_LOCKED, 1, 0, NULL, GFP_NOFS);
1221                 return 0;
1222         }
1223         return 1;
1224 }
1225
1226 int unlock_extent_cached(struct extent_io_tree *tree, u64 start, u64 end,
1227                          struct extent_state **cached, gfp_t mask)
1228 {
1229         return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, cached,
1230                                 mask);
1231 }
1232
1233 int unlock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1234 {
1235         return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, NULL,
1236                                 GFP_NOFS);
1237 }
1238
1239 /*
1240  * helper function to set both pages and extents in the tree writeback
1241  */
1242 static int set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
1243 {
1244         unsigned long index = start >> PAGE_CACHE_SHIFT;
1245         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1246         struct page *page;
1247
1248         while (index <= end_index) {
1249                 page = find_get_page(tree->mapping, index);
1250                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1251                 set_page_writeback(page);
1252                 page_cache_release(page);
1253                 index++;
1254         }
1255         return 0;
1256 }
1257
1258 /* find the first state struct with 'bits' set after 'start', and
1259  * return it.  tree->lock must be held.  NULL will returned if
1260  * nothing was found after 'start'
1261  */
1262 struct extent_state *find_first_extent_bit_state(struct extent_io_tree *tree,
1263                                                  u64 start, int bits)
1264 {
1265         struct rb_node *node;
1266         struct extent_state *state;
1267
1268         /*
1269          * this search will find all the extents that end after
1270          * our range starts.
1271          */
1272         node = tree_search(tree, start);
1273         if (!node)
1274                 goto out;
1275
1276         while (1) {
1277                 state = rb_entry(node, struct extent_state, rb_node);
1278                 if (state->end >= start && (state->state & bits))
1279                         return state;
1280
1281                 node = rb_next(node);
1282                 if (!node)
1283                         break;
1284         }
1285 out:
1286         return NULL;
1287 }
1288
1289 /*
1290  * find the first offset in the io tree with 'bits' set. zero is
1291  * returned if we find something, and *start_ret and *end_ret are
1292  * set to reflect the state struct that was found.
1293  *
1294  * If nothing was found, 1 is returned. If found something, return 0.
1295  */
1296 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1297                           u64 *start_ret, u64 *end_ret, int bits)
1298 {
1299         struct extent_state *state;
1300         int ret = 1;
1301
1302         spin_lock(&tree->lock);
1303         state = find_first_extent_bit_state(tree, start, bits);
1304         if (state) {
1305                 *start_ret = state->start;
1306                 *end_ret = state->end;
1307                 ret = 0;
1308         }
1309         spin_unlock(&tree->lock);
1310         return ret;
1311 }
1312
1313 /*
1314  * find a contiguous range of bytes in the file marked as delalloc, not
1315  * more than 'max_bytes'.  start and end are used to return the range,
1316  *
1317  * 1 is returned if we find something, 0 if nothing was in the tree
1318  */
1319 static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
1320                                         u64 *start, u64 *end, u64 max_bytes,
1321                                         struct extent_state **cached_state)
1322 {
1323         struct rb_node *node;
1324         struct extent_state *state;
1325         u64 cur_start = *start;
1326         u64 found = 0;
1327         u64 total_bytes = 0;
1328
1329         spin_lock(&tree->lock);
1330
1331         /*
1332          * this search will find all the extents that end after
1333          * our range starts.
1334          */
1335         node = tree_search(tree, cur_start);
1336         if (!node) {
1337                 if (!found)
1338                         *end = (u64)-1;
1339                 goto out;
1340         }
1341
1342         while (1) {
1343                 state = rb_entry(node, struct extent_state, rb_node);
1344                 if (found && (state->start != cur_start ||
1345                               (state->state & EXTENT_BOUNDARY))) {
1346                         goto out;
1347                 }
1348                 if (!(state->state & EXTENT_DELALLOC)) {
1349                         if (!found)
1350                                 *end = state->end;
1351                         goto out;
1352                 }
1353                 if (!found) {
1354                         *start = state->start;
1355                         *cached_state = state;
1356                         atomic_inc(&state->refs);
1357                 }
1358                 found++;
1359                 *end = state->end;
1360                 cur_start = state->end + 1;
1361                 node = rb_next(node);
1362                 if (!node)
1363                         break;
1364                 total_bytes += state->end - state->start + 1;
1365                 if (total_bytes >= max_bytes)
1366                         break;
1367         }
1368 out:
1369         spin_unlock(&tree->lock);
1370         return found;
1371 }
1372
1373 static noinline void __unlock_for_delalloc(struct inode *inode,
1374                                            struct page *locked_page,
1375                                            u64 start, u64 end)
1376 {
1377         int ret;
1378         struct page *pages[16];
1379         unsigned long index = start >> PAGE_CACHE_SHIFT;
1380         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1381         unsigned long nr_pages = end_index - index + 1;
1382         int i;
1383
1384         if (index == locked_page->index && end_index == index)
1385                 return;
1386
1387         while (nr_pages > 0) {
1388                 ret = find_get_pages_contig(inode->i_mapping, index,
1389                                      min_t(unsigned long, nr_pages,
1390                                      ARRAY_SIZE(pages)), pages);
1391                 for (i = 0; i < ret; i++) {
1392                         if (pages[i] != locked_page)
1393                                 unlock_page(pages[i]);
1394                         page_cache_release(pages[i]);
1395                 }
1396                 nr_pages -= ret;
1397                 index += ret;
1398                 cond_resched();
1399         }
1400 }
1401
1402 static noinline int lock_delalloc_pages(struct inode *inode,
1403                                         struct page *locked_page,
1404                                         u64 delalloc_start,
1405                                         u64 delalloc_end)
1406 {
1407         unsigned long index = delalloc_start >> PAGE_CACHE_SHIFT;
1408         unsigned long start_index = index;
1409         unsigned long end_index = delalloc_end >> PAGE_CACHE_SHIFT;
1410         unsigned long pages_locked = 0;
1411         struct page *pages[16];
1412         unsigned long nrpages;
1413         int ret;
1414         int i;
1415
1416         /* the caller is responsible for locking the start index */
1417         if (index == locked_page->index && index == end_index)
1418                 return 0;
1419
1420         /* skip the page at the start index */
1421         nrpages = end_index - index + 1;
1422         while (nrpages > 0) {
1423                 ret = find_get_pages_contig(inode->i_mapping, index,
1424                                      min_t(unsigned long,
1425                                      nrpages, ARRAY_SIZE(pages)), pages);
1426                 if (ret == 0) {
1427                         ret = -EAGAIN;
1428                         goto done;
1429                 }
1430                 /* now we have an array of pages, lock them all */
1431                 for (i = 0; i < ret; i++) {
1432                         /*
1433                          * the caller is taking responsibility for
1434                          * locked_page
1435                          */
1436                         if (pages[i] != locked_page) {
1437                                 lock_page(pages[i]);
1438                                 if (!PageDirty(pages[i]) ||
1439                                     pages[i]->mapping != inode->i_mapping) {
1440                                         ret = -EAGAIN;
1441                                         unlock_page(pages[i]);
1442                                         page_cache_release(pages[i]);
1443                                         goto done;
1444                                 }
1445                         }
1446                         page_cache_release(pages[i]);
1447                         pages_locked++;
1448                 }
1449                 nrpages -= ret;
1450                 index += ret;
1451                 cond_resched();
1452         }
1453         ret = 0;
1454 done:
1455         if (ret && pages_locked) {
1456                 __unlock_for_delalloc(inode, locked_page,
1457                               delalloc_start,
1458                               ((u64)(start_index + pages_locked - 1)) <<
1459                               PAGE_CACHE_SHIFT);
1460         }
1461         return ret;
1462 }
1463
1464 /*
1465  * find a contiguous range of bytes in the file marked as delalloc, not
1466  * more than 'max_bytes'.  start and end are used to return the range,
1467  *
1468  * 1 is returned if we find something, 0 if nothing was in the tree
1469  */
1470 static noinline u64 find_lock_delalloc_range(struct inode *inode,
1471                                              struct extent_io_tree *tree,
1472                                              struct page *locked_page,
1473                                              u64 *start, u64 *end,
1474                                              u64 max_bytes)
1475 {
1476         u64 delalloc_start;
1477         u64 delalloc_end;
1478         u64 found;
1479         struct extent_state *cached_state = NULL;
1480         int ret;
1481         int loops = 0;
1482
1483 again:
1484         /* step one, find a bunch of delalloc bytes starting at start */
1485         delalloc_start = *start;
1486         delalloc_end = 0;
1487         found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1488                                     max_bytes, &cached_state);
1489         if (!found || delalloc_end <= *start) {
1490                 *start = delalloc_start;
1491                 *end = delalloc_end;
1492                 free_extent_state(cached_state);
1493                 return found;
1494         }
1495
1496         /*
1497          * start comes from the offset of locked_page.  We have to lock
1498          * pages in order, so we can't process delalloc bytes before
1499          * locked_page
1500          */
1501         if (delalloc_start < *start)
1502                 delalloc_start = *start;
1503
1504         /*
1505          * make sure to limit the number of pages we try to lock down
1506          * if we're looping.
1507          */
1508         if (delalloc_end + 1 - delalloc_start > max_bytes && loops)
1509                 delalloc_end = delalloc_start + PAGE_CACHE_SIZE - 1;
1510
1511         /* step two, lock all the pages after the page that has start */
1512         ret = lock_delalloc_pages(inode, locked_page,
1513                                   delalloc_start, delalloc_end);
1514         if (ret == -EAGAIN) {
1515                 /* some of the pages are gone, lets avoid looping by
1516                  * shortening the size of the delalloc range we're searching
1517                  */
1518                 free_extent_state(cached_state);
1519                 if (!loops) {
1520                         unsigned long offset = (*start) & (PAGE_CACHE_SIZE - 1);
1521                         max_bytes = PAGE_CACHE_SIZE - offset;
1522                         loops = 1;
1523                         goto again;
1524                 } else {
1525                         found = 0;
1526                         goto out_failed;
1527                 }
1528         }
1529         BUG_ON(ret); /* Only valid values are 0 and -EAGAIN */
1530
1531         /* step three, lock the state bits for the whole range */
1532         lock_extent_bits(tree, delalloc_start, delalloc_end, 0, &cached_state);
1533
1534         /* then test to make sure it is all still delalloc */
1535         ret = test_range_bit(tree, delalloc_start, delalloc_end,
1536                              EXTENT_DELALLOC, 1, cached_state);
1537         if (!ret) {
1538                 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1539                                      &cached_state, GFP_NOFS);
1540                 __unlock_for_delalloc(inode, locked_page,
1541                               delalloc_start, delalloc_end);
1542                 cond_resched();
1543                 goto again;
1544         }
1545         free_extent_state(cached_state);
1546         *start = delalloc_start;
1547         *end = delalloc_end;
1548 out_failed:
1549         return found;
1550 }
1551
1552 int extent_clear_unlock_delalloc(struct inode *inode,
1553                                 struct extent_io_tree *tree,
1554                                 u64 start, u64 end, struct page *locked_page,
1555                                 unsigned long op)
1556 {
1557         int ret;
1558         struct page *pages[16];
1559         unsigned long index = start >> PAGE_CACHE_SHIFT;
1560         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1561         unsigned long nr_pages = end_index - index + 1;
1562         int i;
1563         int clear_bits = 0;
1564
1565         if (op & EXTENT_CLEAR_UNLOCK)
1566                 clear_bits |= EXTENT_LOCKED;
1567         if (op & EXTENT_CLEAR_DIRTY)
1568                 clear_bits |= EXTENT_DIRTY;
1569
1570         if (op & EXTENT_CLEAR_DELALLOC)
1571                 clear_bits |= EXTENT_DELALLOC;
1572
1573         clear_extent_bit(tree, start, end, clear_bits, 1, 0, NULL, GFP_NOFS);
1574         if (!(op & (EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
1575                     EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK |
1576                     EXTENT_SET_PRIVATE2)))
1577                 return 0;
1578
1579         while (nr_pages > 0) {
1580                 ret = find_get_pages_contig(inode->i_mapping, index,
1581                                      min_t(unsigned long,
1582                                      nr_pages, ARRAY_SIZE(pages)), pages);
1583                 for (i = 0; i < ret; i++) {
1584
1585                         if (op & EXTENT_SET_PRIVATE2)
1586                                 SetPagePrivate2(pages[i]);
1587
1588                         if (pages[i] == locked_page) {
1589                                 page_cache_release(pages[i]);
1590                                 continue;
1591                         }
1592                         if (op & EXTENT_CLEAR_DIRTY)
1593                                 clear_page_dirty_for_io(pages[i]);
1594                         if (op & EXTENT_SET_WRITEBACK)
1595                                 set_page_writeback(pages[i]);
1596                         if (op & EXTENT_END_WRITEBACK)
1597                                 end_page_writeback(pages[i]);
1598                         if (op & EXTENT_CLEAR_UNLOCK_PAGE)
1599                                 unlock_page(pages[i]);
1600                         page_cache_release(pages[i]);
1601                 }
1602                 nr_pages -= ret;
1603                 index += ret;
1604                 cond_resched();
1605         }
1606         return 0;
1607 }
1608
1609 /*
1610  * count the number of bytes in the tree that have a given bit(s)
1611  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
1612  * cached.  The total number found is returned.
1613  */
1614 u64 count_range_bits(struct extent_io_tree *tree,
1615                      u64 *start, u64 search_end, u64 max_bytes,
1616                      unsigned long bits, int contig)
1617 {
1618         struct rb_node *node;
1619         struct extent_state *state;
1620         u64 cur_start = *start;
1621         u64 total_bytes = 0;
1622         u64 last = 0;
1623         int found = 0;
1624
1625         if (search_end <= cur_start) {
1626                 WARN_ON(1);
1627                 return 0;
1628         }
1629
1630         spin_lock(&tree->lock);
1631         if (cur_start == 0 && bits == EXTENT_DIRTY) {
1632                 total_bytes = tree->dirty_bytes;
1633                 goto out;
1634         }
1635         /*
1636          * this search will find all the extents that end after
1637          * our range starts.
1638          */
1639         node = tree_search(tree, cur_start);
1640         if (!node)
1641                 goto out;
1642
1643         while (1) {
1644                 state = rb_entry(node, struct extent_state, rb_node);
1645                 if (state->start > search_end)
1646                         break;
1647                 if (contig && found && state->start > last + 1)
1648                         break;
1649                 if (state->end >= cur_start && (state->state & bits) == bits) {
1650                         total_bytes += min(search_end, state->end) + 1 -
1651                                        max(cur_start, state->start);
1652                         if (total_bytes >= max_bytes)
1653                                 break;
1654                         if (!found) {
1655                                 *start = max(cur_start, state->start);
1656                                 found = 1;
1657                         }
1658                         last = state->end;
1659                 } else if (contig && found) {
1660                         break;
1661                 }
1662                 node = rb_next(node);
1663                 if (!node)
1664                         break;
1665         }
1666 out:
1667         spin_unlock(&tree->lock);
1668         return total_bytes;
1669 }
1670
1671 /*
1672  * set the private field for a given byte offset in the tree.  If there isn't
1673  * an extent_state there already, this does nothing.
1674  */
1675 int set_state_private(struct extent_io_tree *tree, u64 start, u64 private)
1676 {
1677         struct rb_node *node;
1678         struct extent_state *state;
1679         int ret = 0;
1680
1681         spin_lock(&tree->lock);
1682         /*
1683          * this search will find all the extents that end after
1684          * our range starts.
1685          */
1686         node = tree_search(tree, start);
1687         if (!node) {
1688                 ret = -ENOENT;
1689                 goto out;
1690         }
1691         state = rb_entry(node, struct extent_state, rb_node);
1692         if (state->start != start) {
1693                 ret = -ENOENT;
1694                 goto out;
1695         }
1696         state->private = private;
1697 out:
1698         spin_unlock(&tree->lock);
1699         return ret;
1700 }
1701
1702 int get_state_private(struct extent_io_tree *tree, u64 start, u64 *private)
1703 {
1704         struct rb_node *node;
1705         struct extent_state *state;
1706         int ret = 0;
1707
1708         spin_lock(&tree->lock);
1709         /*
1710          * this search will find all the extents that end after
1711          * our range starts.
1712          */
1713         node = tree_search(tree, start);
1714         if (!node) {
1715                 ret = -ENOENT;
1716                 goto out;
1717         }
1718         state = rb_entry(node, struct extent_state, rb_node);
1719         if (state->start != start) {
1720                 ret = -ENOENT;
1721                 goto out;
1722         }
1723         *private = state->private;
1724 out:
1725         spin_unlock(&tree->lock);
1726         return ret;
1727 }
1728
1729 /*
1730  * searches a range in the state tree for a given mask.
1731  * If 'filled' == 1, this returns 1 only if every extent in the tree
1732  * has the bits set.  Otherwise, 1 is returned if any bit in the
1733  * range is found set.
1734  */
1735 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1736                    int bits, int filled, struct extent_state *cached)
1737 {
1738         struct extent_state *state = NULL;
1739         struct rb_node *node;
1740         int bitset = 0;
1741
1742         spin_lock(&tree->lock);
1743         if (cached && cached->tree && cached->start <= start &&
1744             cached->end > start)
1745                 node = &cached->rb_node;
1746         else
1747                 node = tree_search(tree, start);
1748         while (node && start <= end) {
1749                 state = rb_entry(node, struct extent_state, rb_node);
1750
1751                 if (filled && state->start > start) {
1752                         bitset = 0;
1753                         break;
1754                 }
1755
1756                 if (state->start > end)
1757                         break;
1758
1759                 if (state->state & bits) {
1760                         bitset = 1;
1761                         if (!filled)
1762                                 break;
1763                 } else if (filled) {
1764                         bitset = 0;
1765                         break;
1766                 }
1767
1768                 if (state->end == (u64)-1)
1769                         break;
1770
1771                 start = state->end + 1;
1772                 if (start > end)
1773                         break;
1774                 node = rb_next(node);
1775                 if (!node) {
1776                         if (filled)
1777                                 bitset = 0;
1778                         break;
1779                 }
1780         }
1781         spin_unlock(&tree->lock);
1782         return bitset;
1783 }
1784
1785 /*
1786  * helper function to set a given page up to date if all the
1787  * extents in the tree for that page are up to date
1788  */
1789 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1790 {
1791         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
1792         u64 end = start + PAGE_CACHE_SIZE - 1;
1793         if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1794                 SetPageUptodate(page);
1795 }
1796
1797 /*
1798  * helper function to unlock a page if all the extents in the tree
1799  * for that page are unlocked
1800  */
1801 static void check_page_locked(struct extent_io_tree *tree, struct page *page)
1802 {
1803         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
1804         u64 end = start + PAGE_CACHE_SIZE - 1;
1805         if (!test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL))
1806                 unlock_page(page);
1807 }
1808
1809 /*
1810  * helper function to end page writeback if all the extents
1811  * in the tree for that page are done with writeback
1812  */
1813 static void check_page_writeback(struct extent_io_tree *tree,
1814                                  struct page *page)
1815 {
1816         end_page_writeback(page);
1817 }
1818
1819 /*
1820  * When IO fails, either with EIO or csum verification fails, we
1821  * try other mirrors that might have a good copy of the data.  This
1822  * io_failure_record is used to record state as we go through all the
1823  * mirrors.  If another mirror has good data, the page is set up to date
1824  * and things continue.  If a good mirror can't be found, the original
1825  * bio end_io callback is called to indicate things have failed.
1826  */
1827 struct io_failure_record {
1828         struct page *page;
1829         u64 start;
1830         u64 len;
1831         u64 logical;
1832         unsigned long bio_flags;
1833         int this_mirror;
1834         int failed_mirror;
1835         int in_validation;
1836 };
1837
1838 static int free_io_failure(struct inode *inode, struct io_failure_record *rec,
1839                                 int did_repair)
1840 {
1841         int ret;
1842         int err = 0;
1843         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1844
1845         set_state_private(failure_tree, rec->start, 0);
1846         ret = clear_extent_bits(failure_tree, rec->start,
1847                                 rec->start + rec->len - 1,
1848                                 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1849         if (ret)
1850                 err = ret;
1851
1852         if (did_repair) {
1853                 ret = clear_extent_bits(&BTRFS_I(inode)->io_tree, rec->start,
1854                                         rec->start + rec->len - 1,
1855                                         EXTENT_DAMAGED, GFP_NOFS);
1856                 if (ret && !err)
1857                         err = ret;
1858         }
1859
1860         kfree(rec);
1861         return err;
1862 }
1863
1864 static void repair_io_failure_callback(struct bio *bio, int err)
1865 {
1866         complete(bio->bi_private);
1867 }
1868
1869 /*
1870  * this bypasses the standard btrfs submit functions deliberately, as
1871  * the standard behavior is to write all copies in a raid setup. here we only
1872  * want to write the one bad copy. so we do the mapping for ourselves and issue
1873  * submit_bio directly.
1874  * to avoid any synchonization issues, wait for the data after writing, which
1875  * actually prevents the read that triggered the error from finishing.
1876  * currently, there can be no more than two copies of every data bit. thus,
1877  * exactly one rewrite is required.
1878  */
1879 int repair_io_failure(struct btrfs_mapping_tree *map_tree, u64 start,
1880                         u64 length, u64 logical, struct page *page,
1881                         int mirror_num)
1882 {
1883         struct bio *bio;
1884         struct btrfs_device *dev;
1885         DECLARE_COMPLETION_ONSTACK(compl);
1886         u64 map_length = 0;
1887         u64 sector;
1888         struct btrfs_bio *bbio = NULL;
1889         int ret;
1890
1891         BUG_ON(!mirror_num);
1892
1893         bio = bio_alloc(GFP_NOFS, 1);
1894         if (!bio)
1895                 return -EIO;
1896         bio->bi_private = &compl;
1897         bio->bi_end_io = repair_io_failure_callback;
1898         bio->bi_size = 0;
1899         map_length = length;
1900
1901         ret = btrfs_map_block(map_tree, WRITE, logical,
1902                               &map_length, &bbio, mirror_num);
1903         if (ret) {
1904                 bio_put(bio);
1905                 return -EIO;
1906         }
1907         BUG_ON(mirror_num != bbio->mirror_num);
1908         sector = bbio->stripes[mirror_num-1].physical >> 9;
1909         bio->bi_sector = sector;
1910         dev = bbio->stripes[mirror_num-1].dev;
1911         kfree(bbio);
1912         if (!dev || !dev->bdev || !dev->writeable) {
1913                 bio_put(bio);
1914                 return -EIO;
1915         }
1916         bio->bi_bdev = dev->bdev;
1917         bio_add_page(bio, page, length, start-page_offset(page));
1918         btrfsic_submit_bio(WRITE_SYNC, bio);
1919         wait_for_completion(&compl);
1920
1921         if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
1922                 /* try to remap that extent elsewhere? */
1923                 bio_put(bio);
1924                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
1925                 return -EIO;
1926         }
1927
1928         printk_ratelimited_in_rcu(KERN_INFO "btrfs read error corrected: ino %lu off %llu "
1929                       "(dev %s sector %llu)\n", page->mapping->host->i_ino,
1930                       start, rcu_str_deref(dev->name), sector);
1931
1932         bio_put(bio);
1933         return 0;
1934 }
1935
1936 int repair_eb_io_failure(struct btrfs_root *root, struct extent_buffer *eb,
1937                          int mirror_num)
1938 {
1939         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1940         u64 start = eb->start;
1941         unsigned long i, num_pages = num_extent_pages(eb->start, eb->len);
1942         int ret = 0;
1943
1944         for (i = 0; i < num_pages; i++) {
1945                 struct page *p = extent_buffer_page(eb, i);
1946                 ret = repair_io_failure(map_tree, start, PAGE_CACHE_SIZE,
1947                                         start, p, mirror_num);
1948                 if (ret)
1949                         break;
1950                 start += PAGE_CACHE_SIZE;
1951         }
1952
1953         return ret;
1954 }
1955
1956 /*
1957  * each time an IO finishes, we do a fast check in the IO failure tree
1958  * to see if we need to process or clean up an io_failure_record
1959  */
1960 static int clean_io_failure(u64 start, struct page *page)
1961 {
1962         u64 private;
1963         u64 private_failure;
1964         struct io_failure_record *failrec;
1965         struct btrfs_mapping_tree *map_tree;
1966         struct extent_state *state;
1967         int num_copies;
1968         int did_repair = 0;
1969         int ret;
1970         struct inode *inode = page->mapping->host;
1971
1972         private = 0;
1973         ret = count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1974                                 (u64)-1, 1, EXTENT_DIRTY, 0);
1975         if (!ret)
1976                 return 0;
1977
1978         ret = get_state_private(&BTRFS_I(inode)->io_failure_tree, start,
1979                                 &private_failure);
1980         if (ret)
1981                 return 0;
1982
1983         failrec = (struct io_failure_record *)(unsigned long) private_failure;
1984         BUG_ON(!failrec->this_mirror);
1985
1986         if (failrec->in_validation) {
1987                 /* there was no real error, just free the record */
1988                 pr_debug("clean_io_failure: freeing dummy error at %llu\n",
1989                          failrec->start);
1990                 did_repair = 1;
1991                 goto out;
1992         }
1993
1994         spin_lock(&BTRFS_I(inode)->io_tree.lock);
1995         state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1996                                             failrec->start,
1997                                             EXTENT_LOCKED);
1998         spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1999
2000         if (state && state->start == failrec->start) {
2001                 map_tree = &BTRFS_I(inode)->root->fs_info->mapping_tree;
2002                 num_copies = btrfs_num_copies(map_tree, failrec->logical,
2003                                                 failrec->len);
2004                 if (num_copies > 1)  {
2005                         ret = repair_io_failure(map_tree, start, failrec->len,
2006                                                 failrec->logical, page,
2007                                                 failrec->failed_mirror);
2008                         did_repair = !ret;
2009                 }
2010         }
2011
2012 out:
2013         if (!ret)
2014                 ret = free_io_failure(inode, failrec, did_repair);
2015
2016         return ret;
2017 }
2018
2019 /*
2020  * this is a generic handler for readpage errors (default
2021  * readpage_io_failed_hook). if other copies exist, read those and write back
2022  * good data to the failed position. does not investigate in remapping the
2023  * failed extent elsewhere, hoping the device will be smart enough to do this as
2024  * needed
2025  */
2026
2027 static int bio_readpage_error(struct bio *failed_bio, struct page *page,
2028                                 u64 start, u64 end, int failed_mirror,
2029                                 struct extent_state *state)
2030 {
2031         struct io_failure_record *failrec = NULL;
2032         u64 private;
2033         struct extent_map *em;
2034         struct inode *inode = page->mapping->host;
2035         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2036         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2037         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2038         struct bio *bio;
2039         int num_copies;
2040         int ret;
2041         int read_mode;
2042         u64 logical;
2043
2044         BUG_ON(failed_bio->bi_rw & REQ_WRITE);
2045
2046         ret = get_state_private(failure_tree, start, &private);
2047         if (ret) {
2048                 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2049                 if (!failrec)
2050                         return -ENOMEM;
2051                 failrec->start = start;
2052                 failrec->len = end - start + 1;
2053                 failrec->this_mirror = 0;
2054                 failrec->bio_flags = 0;
2055                 failrec->in_validation = 0;
2056
2057                 read_lock(&em_tree->lock);
2058                 em = lookup_extent_mapping(em_tree, start, failrec->len);
2059                 if (!em) {
2060                         read_unlock(&em_tree->lock);
2061                         kfree(failrec);
2062                         return -EIO;
2063                 }
2064
2065                 if (em->start > start || em->start + em->len < start) {
2066                         free_extent_map(em);
2067                         em = NULL;
2068                 }
2069                 read_unlock(&em_tree->lock);
2070
2071                 if (!em || IS_ERR(em)) {
2072                         kfree(failrec);
2073                         return -EIO;
2074                 }
2075                 logical = start - em->start;
2076                 logical = em->block_start + logical;
2077                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2078                         logical = em->block_start;
2079                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2080                         extent_set_compress_type(&failrec->bio_flags,
2081                                                  em->compress_type);
2082                 }
2083                 pr_debug("bio_readpage_error: (new) logical=%llu, start=%llu, "
2084                          "len=%llu\n", logical, start, failrec->len);
2085                 failrec->logical = logical;
2086                 free_extent_map(em);
2087
2088                 /* set the bits in the private failure tree */
2089                 ret = set_extent_bits(failure_tree, start, end,
2090                                         EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
2091                 if (ret >= 0)
2092                         ret = set_state_private(failure_tree, start,
2093                                                 (u64)(unsigned long)failrec);
2094                 /* set the bits in the inode's tree */
2095                 if (ret >= 0)
2096                         ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED,
2097                                                 GFP_NOFS);
2098                 if (ret < 0) {
2099                         kfree(failrec);
2100                         return ret;
2101                 }
2102         } else {
2103                 failrec = (struct io_failure_record *)(unsigned long)private;
2104                 pr_debug("bio_readpage_error: (found) logical=%llu, "
2105                          "start=%llu, len=%llu, validation=%d\n",
2106                          failrec->logical, failrec->start, failrec->len,
2107                          failrec->in_validation);
2108                 /*
2109                  * when data can be on disk more than twice, add to failrec here
2110                  * (e.g. with a list for failed_mirror) to make
2111                  * clean_io_failure() clean all those errors at once.
2112                  */
2113         }
2114         num_copies = btrfs_num_copies(
2115                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
2116                               failrec->logical, failrec->len);
2117         if (num_copies == 1) {
2118                 /*
2119                  * we only have a single copy of the data, so don't bother with
2120                  * all the retry and error correction code that follows. no
2121                  * matter what the error is, it is very likely to persist.
2122                  */
2123                 pr_debug("bio_readpage_error: cannot repair, num_copies == 1. "
2124                          "state=%p, num_copies=%d, next_mirror %d, "
2125                          "failed_mirror %d\n", state, num_copies,
2126                          failrec->this_mirror, failed_mirror);
2127                 free_io_failure(inode, failrec, 0);
2128                 return -EIO;
2129         }
2130
2131         if (!state) {
2132                 spin_lock(&tree->lock);
2133                 state = find_first_extent_bit_state(tree, failrec->start,
2134                                                     EXTENT_LOCKED);
2135                 if (state && state->start != failrec->start)
2136                         state = NULL;
2137                 spin_unlock(&tree->lock);
2138         }
2139
2140         /*
2141          * there are two premises:
2142          *      a) deliver good data to the caller
2143          *      b) correct the bad sectors on disk
2144          */
2145         if (failed_bio->bi_vcnt > 1) {
2146                 /*
2147                  * to fulfill b), we need to know the exact failing sectors, as
2148                  * we don't want to rewrite any more than the failed ones. thus,
2149                  * we need separate read requests for the failed bio
2150                  *
2151                  * if the following BUG_ON triggers, our validation request got
2152                  * merged. we need separate requests for our algorithm to work.
2153                  */
2154                 BUG_ON(failrec->in_validation);
2155                 failrec->in_validation = 1;
2156                 failrec->this_mirror = failed_mirror;
2157                 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
2158         } else {
2159                 /*
2160                  * we're ready to fulfill a) and b) alongside. get a good copy
2161                  * of the failed sector and if we succeed, we have setup
2162                  * everything for repair_io_failure to do the rest for us.
2163                  */
2164                 if (failrec->in_validation) {
2165                         BUG_ON(failrec->this_mirror != failed_mirror);
2166                         failrec->in_validation = 0;
2167                         failrec->this_mirror = 0;
2168                 }
2169                 failrec->failed_mirror = failed_mirror;
2170                 failrec->this_mirror++;
2171                 if (failrec->this_mirror == failed_mirror)
2172                         failrec->this_mirror++;
2173                 read_mode = READ_SYNC;
2174         }
2175
2176         if (!state || failrec->this_mirror > num_copies) {
2177                 pr_debug("bio_readpage_error: (fail) state=%p, num_copies=%d, "
2178                          "next_mirror %d, failed_mirror %d\n", state,
2179                          num_copies, failrec->this_mirror, failed_mirror);
2180                 free_io_failure(inode, failrec, 0);
2181                 return -EIO;
2182         }
2183
2184         bio = bio_alloc(GFP_NOFS, 1);
2185         if (!bio) {
2186                 free_io_failure(inode, failrec, 0);
2187                 return -EIO;
2188         }
2189         bio->bi_private = state;
2190         bio->bi_end_io = failed_bio->bi_end_io;
2191         bio->bi_sector = failrec->logical >> 9;
2192         bio->bi_bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
2193         bio->bi_size = 0;
2194
2195         bio_add_page(bio, page, failrec->len, start - page_offset(page));
2196
2197         pr_debug("bio_readpage_error: submitting new read[%#x] to "
2198                  "this_mirror=%d, num_copies=%d, in_validation=%d\n", read_mode,
2199                  failrec->this_mirror, num_copies, failrec->in_validation);
2200
2201         ret = tree->ops->submit_bio_hook(inode, read_mode, bio,
2202                                          failrec->this_mirror,
2203                                          failrec->bio_flags, 0);
2204         return ret;
2205 }
2206
2207 /* lots and lots of room for performance fixes in the end_bio funcs */
2208
2209 int end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2210 {
2211         int uptodate = (err == 0);
2212         struct extent_io_tree *tree;
2213         int ret;
2214
2215         tree = &BTRFS_I(page->mapping->host)->io_tree;
2216
2217         if (tree->ops && tree->ops->writepage_end_io_hook) {
2218                 ret = tree->ops->writepage_end_io_hook(page, start,
2219                                                end, NULL, uptodate);
2220                 if (ret)
2221                         uptodate = 0;
2222         }
2223
2224         if (!uptodate) {
2225                 ClearPageUptodate(page);
2226                 SetPageError(page);
2227         }
2228         return 0;
2229 }
2230
2231 /*
2232  * after a writepage IO is done, we need to:
2233  * clear the uptodate bits on error
2234  * clear the writeback bits in the extent tree for this IO
2235  * end_page_writeback if the page has no more pending IO
2236  *
2237  * Scheduling is not allowed, so the extent state tree is expected
2238  * to have one and only one object corresponding to this IO.
2239  */
2240 static void end_bio_extent_writepage(struct bio *bio, int err)
2241 {
2242         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
2243         struct extent_io_tree *tree;
2244         u64 start;
2245         u64 end;
2246         int whole_page;
2247
2248         do {
2249                 struct page *page = bvec->bv_page;
2250                 tree = &BTRFS_I(page->mapping->host)->io_tree;
2251
2252                 start = ((u64)page->index << PAGE_CACHE_SHIFT) +
2253                          bvec->bv_offset;
2254                 end = start + bvec->bv_len - 1;
2255
2256                 if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
2257                         whole_page = 1;
2258                 else
2259                         whole_page = 0;
2260
2261                 if (--bvec >= bio->bi_io_vec)
2262                         prefetchw(&bvec->bv_page->flags);
2263
2264                 if (end_extent_writepage(page, err, start, end))
2265                         continue;
2266
2267                 if (whole_page)
2268                         end_page_writeback(page);
2269                 else
2270                         check_page_writeback(tree, page);
2271         } while (bvec >= bio->bi_io_vec);
2272
2273         bio_put(bio);
2274 }
2275
2276 /*
2277  * after a readpage IO is done, we need to:
2278  * clear the uptodate bits on error
2279  * set the uptodate bits if things worked
2280  * set the page up to date if all extents in the tree are uptodate
2281  * clear the lock bit in the extent tree
2282  * unlock the page if there are no other extents locked for it
2283  *
2284  * Scheduling is not allowed, so the extent state tree is expected
2285  * to have one and only one object corresponding to this IO.
2286  */
2287 static void end_bio_extent_readpage(struct bio *bio, int err)
2288 {
2289         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
2290         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
2291         struct bio_vec *bvec = bio->bi_io_vec;
2292         struct extent_io_tree *tree;
2293         u64 start;
2294         u64 end;
2295         int whole_page;
2296         int mirror;
2297         int ret;
2298
2299         if (err)
2300                 uptodate = 0;
2301
2302         do {
2303                 struct page *page = bvec->bv_page;
2304                 struct extent_state *cached = NULL;
2305                 struct extent_state *state;
2306
2307                 pr_debug("end_bio_extent_readpage: bi_vcnt=%d, idx=%d, err=%d, "
2308                          "mirror=%ld\n", bio->bi_vcnt, bio->bi_idx, err,
2309                          (long int)bio->bi_bdev);
2310                 tree = &BTRFS_I(page->mapping->host)->io_tree;
2311
2312                 start = ((u64)page->index << PAGE_CACHE_SHIFT) +
2313                         bvec->bv_offset;
2314                 end = start + bvec->bv_len - 1;
2315
2316                 if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
2317                         whole_page = 1;
2318                 else
2319                         whole_page = 0;
2320
2321                 if (++bvec <= bvec_end)
2322                         prefetchw(&bvec->bv_page->flags);
2323
2324                 spin_lock(&tree->lock);
2325                 state = find_first_extent_bit_state(tree, start, EXTENT_LOCKED);
2326                 if (state && state->start == start) {
2327                         /*
2328                          * take a reference on the state, unlock will drop
2329                          * the ref
2330                          */
2331                         cache_state(state, &cached);
2332                 }
2333                 spin_unlock(&tree->lock);
2334
2335                 mirror = (int)(unsigned long)bio->bi_bdev;
2336                 if (uptodate && tree->ops && tree->ops->readpage_end_io_hook) {
2337                         ret = tree->ops->readpage_end_io_hook(page, start, end,
2338                                                               state, mirror);
2339                         if (ret) {
2340                                 /* no IO indicated but software detected errors
2341                                  * in the block, either checksum errors or
2342                                  * issues with the contents */
2343                                 struct btrfs_root *root =
2344                                         BTRFS_I(page->mapping->host)->root;
2345                                 struct btrfs_device *device;
2346
2347                                 uptodate = 0;
2348                                 device = btrfs_find_device_for_logical(
2349                                                 root, start, mirror);
2350                                 if (device)
2351                                         btrfs_dev_stat_inc_and_print(device,
2352                                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
2353                         } else {
2354                                 clean_io_failure(start, page);
2355                         }
2356                 }
2357
2358                 if (!uptodate && tree->ops && tree->ops->readpage_io_failed_hook) {
2359                         ret = tree->ops->readpage_io_failed_hook(page, mirror);
2360                         if (!ret && !err &&
2361                             test_bit(BIO_UPTODATE, &bio->bi_flags))
2362                                 uptodate = 1;
2363                 } else if (!uptodate) {
2364                         /*
2365                          * The generic bio_readpage_error handles errors the
2366                          * following way: If possible, new read requests are
2367                          * created and submitted and will end up in
2368                          * end_bio_extent_readpage as well (if we're lucky, not
2369                          * in the !uptodate case). In that case it returns 0 and
2370                          * we just go on with the next page in our bio. If it
2371                          * can't handle the error it will return -EIO and we
2372                          * remain responsible for that page.
2373                          */
2374                         ret = bio_readpage_error(bio, page, start, end, mirror, NULL);
2375                         if (ret == 0) {
2376                                 uptodate =
2377                                         test_bit(BIO_UPTODATE, &bio->bi_flags);
2378                                 if (err)
2379                                         uptodate = 0;
2380                                 uncache_state(&cached);
2381                                 continue;
2382                         }
2383                 }
2384
2385                 if (uptodate && tree->track_uptodate) {
2386                         set_extent_uptodate(tree, start, end, &cached,
2387                                             GFP_ATOMIC);
2388                 }
2389                 unlock_extent_cached(tree, start, end, &cached, GFP_ATOMIC);
2390
2391                 if (whole_page) {
2392                         if (uptodate) {
2393                                 SetPageUptodate(page);
2394                         } else {
2395                                 ClearPageUptodate(page);
2396                                 SetPageError(page);
2397                         }
2398                         unlock_page(page);
2399                 } else {
2400                         if (uptodate) {
2401                                 check_page_uptodate(tree, page);
2402                         } else {
2403                                 ClearPageUptodate(page);
2404                                 SetPageError(page);
2405                         }
2406                         check_page_locked(tree, page);
2407                 }
2408         } while (bvec <= bvec_end);
2409
2410         bio_put(bio);
2411 }
2412
2413 struct bio *
2414 btrfs_bio_alloc(struct block_device *bdev, u64 first_sector, int nr_vecs,
2415                 gfp_t gfp_flags)
2416 {
2417         struct bio *bio;
2418
2419         bio = bio_alloc(gfp_flags, nr_vecs);
2420
2421         if (bio == NULL && (current->flags & PF_MEMALLOC)) {
2422                 while (!bio && (nr_vecs /= 2))
2423                         bio = bio_alloc(gfp_flags, nr_vecs);
2424         }
2425
2426         if (bio) {
2427                 bio->bi_size = 0;
2428                 bio->bi_bdev = bdev;
2429                 bio->bi_sector = first_sector;
2430         }
2431         return bio;
2432 }
2433
2434 /*
2435  * Since writes are async, they will only return -ENOMEM.
2436  * Reads can return the full range of I/O error conditions.
2437  */
2438 static int __must_check submit_one_bio(int rw, struct bio *bio,
2439                                        int mirror_num, unsigned long bio_flags)
2440 {
2441         int ret = 0;
2442         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
2443         struct page *page = bvec->bv_page;
2444         struct extent_io_tree *tree = bio->bi_private;
2445         u64 start;
2446
2447         start = ((u64)page->index << PAGE_CACHE_SHIFT) + bvec->bv_offset;
2448
2449         bio->bi_private = NULL;
2450
2451         bio_get(bio);
2452
2453         if (tree->ops && tree->ops->submit_bio_hook)
2454                 ret = tree->ops->submit_bio_hook(page->mapping->host, rw, bio,
2455                                            mirror_num, bio_flags, start);
2456         else
2457                 btrfsic_submit_bio(rw, bio);
2458
2459         if (bio_flagged(bio, BIO_EOPNOTSUPP))
2460                 ret = -EOPNOTSUPP;
2461         bio_put(bio);
2462         return ret;
2463 }
2464
2465 static int merge_bio(struct extent_io_tree *tree, struct page *page,
2466                      unsigned long offset, size_t size, struct bio *bio,
2467                      unsigned long bio_flags)
2468 {
2469         int ret = 0;
2470         if (tree->ops && tree->ops->merge_bio_hook)
2471                 ret = tree->ops->merge_bio_hook(page, offset, size, bio,
2472                                                 bio_flags);
2473         BUG_ON(ret < 0);
2474         return ret;
2475
2476 }
2477
2478 static int submit_extent_page(int rw, struct extent_io_tree *tree,
2479                               struct page *page, sector_t sector,
2480                               size_t size, unsigned long offset,
2481                               struct block_device *bdev,
2482                               struct bio **bio_ret,
2483                               unsigned long max_pages,
2484                               bio_end_io_t end_io_func,
2485                               int mirror_num,
2486                               unsigned long prev_bio_flags,
2487                               unsigned long bio_flags)
2488 {
2489         int ret = 0;
2490         struct bio *bio;
2491         int nr;
2492         int contig = 0;
2493         int this_compressed = bio_flags & EXTENT_BIO_COMPRESSED;
2494         int old_compressed = prev_bio_flags & EXTENT_BIO_COMPRESSED;
2495         size_t page_size = min_t(size_t, size, PAGE_CACHE_SIZE);
2496
2497         if (bio_ret && *bio_ret) {
2498                 bio = *bio_ret;
2499                 if (old_compressed)
2500                         contig = bio->bi_sector == sector;
2501                 else
2502                         contig = bio->bi_sector + (bio->bi_size >> 9) ==
2503                                 sector;
2504
2505                 if (prev_bio_flags != bio_flags || !contig ||
2506                     merge_bio(tree, page, offset, page_size, bio, bio_flags) ||
2507                     bio_add_page(bio, page, page_size, offset) < page_size) {
2508                         ret = submit_one_bio(rw, bio, mirror_num,
2509                                              prev_bio_flags);
2510                         if (ret < 0)
2511                                 return ret;
2512                         bio = NULL;
2513                 } else {
2514                         return 0;
2515                 }
2516         }
2517         if (this_compressed)
2518                 nr = BIO_MAX_PAGES;
2519         else
2520                 nr = bio_get_nr_vecs(bdev);
2521
2522         bio = btrfs_bio_alloc(bdev, sector, nr, GFP_NOFS | __GFP_HIGH);
2523         if (!bio)
2524                 return -ENOMEM;
2525
2526         bio_add_page(bio, page, page_size, offset);
2527         bio->bi_end_io = end_io_func;
2528         bio->bi_private = tree;
2529
2530         if (bio_ret)
2531                 *bio_ret = bio;
2532         else
2533                 ret = submit_one_bio(rw, bio, mirror_num, bio_flags);
2534
2535         return ret;
2536 }
2537
2538 void attach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
2539 {
2540         if (!PagePrivate(page)) {
2541                 SetPagePrivate(page);
2542                 page_cache_get(page);
2543                 set_page_private(page, (unsigned long)eb);
2544         } else {
2545                 WARN_ON(page->private != (unsigned long)eb);
2546         }
2547 }
2548
2549 void set_page_extent_mapped(struct page *page)
2550 {
2551         if (!PagePrivate(page)) {
2552                 SetPagePrivate(page);
2553                 page_cache_get(page);
2554                 set_page_private(page, EXTENT_PAGE_PRIVATE);
2555         }
2556 }
2557
2558 /*
2559  * basic readpage implementation.  Locked extent state structs are inserted
2560  * into the tree that are removed when the IO is done (by the end_io
2561  * handlers)
2562  * XXX JDM: This needs looking at to ensure proper page locking
2563  */
2564 static int __extent_read_full_page(struct extent_io_tree *tree,
2565                                    struct page *page,
2566                                    get_extent_t *get_extent,
2567                                    struct bio **bio, int mirror_num,
2568                                    unsigned long *bio_flags)
2569 {
2570         struct inode *inode = page->mapping->host;
2571         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
2572         u64 page_end = start + PAGE_CACHE_SIZE - 1;
2573         u64 end;
2574         u64 cur = start;
2575         u64 extent_offset;
2576         u64 last_byte = i_size_read(inode);
2577         u64 block_start;
2578         u64 cur_end;
2579         sector_t sector;
2580         struct extent_map *em;
2581         struct block_device *bdev;
2582         struct btrfs_ordered_extent *ordered;
2583         int ret;
2584         int nr = 0;
2585         size_t pg_offset = 0;
2586         size_t iosize;
2587         size_t disk_io_size;
2588         size_t blocksize = inode->i_sb->s_blocksize;
2589         unsigned long this_bio_flag = 0;
2590
2591         set_page_extent_mapped(page);
2592
2593         if (!PageUptodate(page)) {
2594                 if (cleancache_get_page(page) == 0) {
2595                         BUG_ON(blocksize != PAGE_SIZE);
2596                         goto out;
2597                 }
2598         }
2599
2600         end = page_end;
2601         while (1) {
2602                 lock_extent(tree, start, end);
2603                 ordered = btrfs_lookup_ordered_extent(inode, start);
2604                 if (!ordered)
2605                         break;
2606                 unlock_extent(tree, start, end);
2607                 btrfs_start_ordered_extent(inode, ordered, 1);
2608                 btrfs_put_ordered_extent(ordered);
2609         }
2610
2611         if (page->index == last_byte >> PAGE_CACHE_SHIFT) {
2612                 char *userpage;
2613                 size_t zero_offset = last_byte & (PAGE_CACHE_SIZE - 1);
2614
2615                 if (zero_offset) {
2616                         iosize = PAGE_CACHE_SIZE - zero_offset;
2617                         userpage = kmap_atomic(page);
2618                         memset(userpage + zero_offset, 0, iosize);
2619                         flush_dcache_page(page);
2620                         kunmap_atomic(userpage);
2621                 }
2622         }
2623         while (cur <= end) {
2624                 if (cur >= last_byte) {
2625                         char *userpage;
2626                         struct extent_state *cached = NULL;
2627
2628                         iosize = PAGE_CACHE_SIZE - pg_offset;
2629                         userpage = kmap_atomic(page);
2630                         memset(userpage + pg_offset, 0, iosize);
2631                         flush_dcache_page(page);
2632                         kunmap_atomic(userpage);
2633                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2634                                             &cached, GFP_NOFS);
2635                         unlock_extent_cached(tree, cur, cur + iosize - 1,
2636                                              &cached, GFP_NOFS);
2637                         break;
2638                 }
2639                 em = get_extent(inode, page, pg_offset, cur,
2640                                 end - cur + 1, 0);
2641                 if (IS_ERR_OR_NULL(em)) {
2642                         SetPageError(page);
2643                         unlock_extent(tree, cur, end);
2644                         break;
2645                 }
2646                 extent_offset = cur - em->start;
2647                 BUG_ON(extent_map_end(em) <= cur);
2648                 BUG_ON(end < cur);
2649
2650                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2651                         this_bio_flag = EXTENT_BIO_COMPRESSED;
2652                         extent_set_compress_type(&this_bio_flag,
2653                                                  em->compress_type);
2654                 }
2655
2656                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2657                 cur_end = min(extent_map_end(em) - 1, end);
2658                 iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
2659                 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2660                         disk_io_size = em->block_len;
2661                         sector = em->block_start >> 9;
2662                 } else {
2663                         sector = (em->block_start + extent_offset) >> 9;
2664                         disk_io_size = iosize;
2665                 }
2666                 bdev = em->bdev;
2667                 block_start = em->block_start;
2668                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
2669                         block_start = EXTENT_MAP_HOLE;
2670                 free_extent_map(em);
2671                 em = NULL;
2672
2673                 /* we've found a hole, just zero and go on */
2674                 if (block_start == EXTENT_MAP_HOLE) {
2675                         char *userpage;
2676                         struct extent_state *cached = NULL;
2677
2678                         userpage = kmap_atomic(page);
2679                         memset(userpage + pg_offset, 0, iosize);
2680                         flush_dcache_page(page);
2681                         kunmap_atomic(userpage);
2682
2683                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2684                                             &cached, GFP_NOFS);
2685                         unlock_extent_cached(tree, cur, cur + iosize - 1,
2686                                              &cached, GFP_NOFS);
2687                         cur = cur + iosize;
2688                         pg_offset += iosize;
2689                         continue;
2690                 }
2691                 /* the get_extent function already copied into the page */
2692                 if (test_range_bit(tree, cur, cur_end,
2693                                    EXTENT_UPTODATE, 1, NULL)) {
2694                         check_page_uptodate(tree, page);
2695                         unlock_extent(tree, cur, cur + iosize - 1);
2696                         cur = cur + iosize;
2697                         pg_offset += iosize;
2698                         continue;
2699                 }
2700                 /* we have an inline extent but it didn't get marked up
2701                  * to date.  Error out
2702                  */
2703                 if (block_start == EXTENT_MAP_INLINE) {
2704                         SetPageError(page);
2705                         unlock_extent(tree, cur, cur + iosize - 1);
2706                         cur = cur + iosize;
2707                         pg_offset += iosize;
2708                         continue;
2709                 }
2710
2711                 ret = 0;
2712                 if (tree->ops && tree->ops->readpage_io_hook) {
2713                         ret = tree->ops->readpage_io_hook(page, cur,
2714                                                           cur + iosize - 1);
2715                 }
2716                 if (!ret) {
2717                         unsigned long pnr = (last_byte >> PAGE_CACHE_SHIFT) + 1;
2718                         pnr -= page->index;
2719                         ret = submit_extent_page(READ, tree, page,
2720                                          sector, disk_io_size, pg_offset,
2721                                          bdev, bio, pnr,
2722                                          end_bio_extent_readpage, mirror_num,
2723                                          *bio_flags,
2724                                          this_bio_flag);
2725                         BUG_ON(ret == -ENOMEM);
2726                         nr++;
2727                         *bio_flags = this_bio_flag;
2728                 }
2729                 if (ret)
2730                         SetPageError(page);
2731                 cur = cur + iosize;
2732                 pg_offset += iosize;
2733         }
2734 out:
2735         if (!nr) {
2736                 if (!PageError(page))
2737                         SetPageUptodate(page);
2738                 unlock_page(page);
2739         }
2740         return 0;
2741 }
2742
2743 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
2744                             get_extent_t *get_extent, int mirror_num)
2745 {
2746         struct bio *bio = NULL;
2747         unsigned long bio_flags = 0;
2748         int ret;
2749
2750         ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
2751                                       &bio_flags);
2752         if (bio)
2753                 ret = submit_one_bio(READ, bio, mirror_num, bio_flags);
2754         return ret;
2755 }
2756
2757 static noinline void update_nr_written(struct page *page,
2758                                       struct writeback_control *wbc,
2759                                       unsigned long nr_written)
2760 {
2761         wbc->nr_to_write -= nr_written;
2762         if (wbc->range_cyclic || (wbc->nr_to_write > 0 &&
2763             wbc->range_start == 0 && wbc->range_end == LLONG_MAX))
2764                 page->mapping->writeback_index = page->index + nr_written;
2765 }
2766
2767 /*
2768  * the writepage semantics are similar to regular writepage.  extent
2769  * records are inserted to lock ranges in the tree, and as dirty areas
2770  * are found, they are marked writeback.  Then the lock bits are removed
2771  * and the end_io handler clears the writeback ranges
2772  */
2773 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2774                               void *data)
2775 {
2776         struct inode *inode = page->mapping->host;
2777         struct extent_page_data *epd = data;
2778         struct extent_io_tree *tree = epd->tree;
2779         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
2780         u64 delalloc_start;
2781         u64 page_end = start + PAGE_CACHE_SIZE - 1;
2782         u64 end;
2783         u64 cur = start;
2784         u64 extent_offset;
2785         u64 last_byte = i_size_read(inode);
2786         u64 block_start;
2787         u64 iosize;
2788         sector_t sector;
2789         struct extent_state *cached_state = NULL;
2790         struct extent_map *em;
2791         struct block_device *bdev;
2792         int ret;
2793         int nr = 0;
2794         size_t pg_offset = 0;
2795         size_t blocksize;
2796         loff_t i_size = i_size_read(inode);
2797         unsigned long end_index = i_size >> PAGE_CACHE_SHIFT;
2798         u64 nr_delalloc;
2799         u64 delalloc_end;
2800         int page_started;
2801         int compressed;
2802         int write_flags;
2803         unsigned long nr_written = 0;
2804         bool fill_delalloc = true;
2805
2806         if (wbc->sync_mode == WB_SYNC_ALL)
2807                 write_flags = WRITE_SYNC;
2808         else
2809                 write_flags = WRITE;
2810
2811         trace___extent_writepage(page, inode, wbc);
2812
2813         WARN_ON(!PageLocked(page));
2814
2815         ClearPageError(page);
2816
2817         pg_offset = i_size & (PAGE_CACHE_SIZE - 1);
2818         if (page->index > end_index ||
2819            (page->index == end_index && !pg_offset)) {
2820                 page->mapping->a_ops->invalidatepage(page, 0);
2821                 unlock_page(page);
2822                 return 0;
2823         }
2824
2825         if (page->index == end_index) {
2826                 char *userpage;
2827
2828                 userpage = kmap_atomic(page);
2829                 memset(userpage + pg_offset, 0,
2830                        PAGE_CACHE_SIZE - pg_offset);
2831                 kunmap_atomic(userpage);
2832                 flush_dcache_page(page);
2833         }
2834         pg_offset = 0;
2835
2836         set_page_extent_mapped(page);
2837
2838         if (!tree->ops || !tree->ops->fill_delalloc)
2839                 fill_delalloc = false;
2840
2841         delalloc_start = start;
2842         delalloc_end = 0;
2843         page_started = 0;
2844         if (!epd->extent_locked && fill_delalloc) {
2845                 u64 delalloc_to_write = 0;
2846                 /*
2847                  * make sure the wbc mapping index is at least updated
2848                  * to this page.
2849                  */
2850                 update_nr_written(page, wbc, 0);
2851
2852                 while (delalloc_end < page_end) {
2853                         nr_delalloc = find_lock_delalloc_range(inode, tree,
2854                                                        page,
2855                                                        &delalloc_start,
2856                                                        &delalloc_end,
2857                                                        128 * 1024 * 1024);
2858                         if (nr_delalloc == 0) {
2859                                 delalloc_start = delalloc_end + 1;
2860                                 continue;
2861                         }
2862                         ret = tree->ops->fill_delalloc(inode, page,
2863                                                        delalloc_start,
2864                                                        delalloc_end,
2865                                                        &page_started,
2866                                                        &nr_written);
2867                         /* File system has been set read-only */
2868                         if (ret) {
2869                                 SetPageError(page);
2870                                 goto done;
2871                         }
2872                         /*
2873                          * delalloc_end is already one less than the total
2874                          * length, so we don't subtract one from
2875                          * PAGE_CACHE_SIZE
2876                          */
2877                         delalloc_to_write += (delalloc_end - delalloc_start +
2878                                               PAGE_CACHE_SIZE) >>
2879                                               PAGE_CACHE_SHIFT;
2880                         delalloc_start = delalloc_end + 1;
2881                 }
2882                 if (wbc->nr_to_write < delalloc_to_write) {
2883                         int thresh = 8192;
2884
2885                         if (delalloc_to_write < thresh * 2)
2886                                 thresh = delalloc_to_write;
2887                         wbc->nr_to_write = min_t(u64, delalloc_to_write,
2888                                                  thresh);
2889                 }
2890
2891                 /* did the fill delalloc function already unlock and start
2892                  * the IO?
2893                  */
2894                 if (page_started) {
2895                         ret = 0;
2896                         /*
2897                          * we've unlocked the page, so we can't update
2898                          * the mapping's writeback index, just update
2899                          * nr_to_write.
2900                          */
2901                         wbc->nr_to_write -= nr_written;
2902                         goto done_unlocked;
2903                 }
2904         }
2905         if (tree->ops && tree->ops->writepage_start_hook) {
2906                 ret = tree->ops->writepage_start_hook(page, start,
2907                                                       page_end);
2908                 if (ret) {
2909                         /* Fixup worker will requeue */
2910                         if (ret == -EBUSY)
2911                                 wbc->pages_skipped++;
2912                         else
2913                                 redirty_page_for_writepage(wbc, page);
2914                         update_nr_written(page, wbc, nr_written);
2915                         unlock_page(page);
2916                         ret = 0;
2917                         goto done_unlocked;
2918                 }
2919         }
2920
2921         /*
2922          * we don't want to touch the inode after unlocking the page,
2923          * so we update the mapping writeback index now
2924          */
2925         update_nr_written(page, wbc, nr_written + 1);
2926
2927         end = page_end;
2928         if (last_byte <= start) {
2929                 if (tree->ops && tree->ops->writepage_end_io_hook)
2930                         tree->ops->writepage_end_io_hook(page, start,
2931                                                          page_end, NULL, 1);
2932                 goto done;
2933         }
2934
2935         blocksize = inode->i_sb->s_blocksize;
2936
2937         while (cur <= end) {
2938                 if (cur >= last_byte) {
2939                         if (tree->ops && tree->ops->writepage_end_io_hook)
2940                                 tree->ops->writepage_end_io_hook(page, cur,
2941                                                          page_end, NULL, 1);
2942                         break;
2943                 }
2944                 em = epd->get_extent(inode, page, pg_offset, cur,
2945                                      end - cur + 1, 1);
2946                 if (IS_ERR_OR_NULL(em)) {
2947                         SetPageError(page);
2948                         break;
2949                 }
2950
2951                 extent_offset = cur - em->start;
2952                 BUG_ON(extent_map_end(em) <= cur);
2953                 BUG_ON(end < cur);
2954                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2955                 iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
2956                 sector = (em->block_start + extent_offset) >> 9;
2957                 bdev = em->bdev;
2958                 block_start = em->block_start;
2959                 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
2960                 free_extent_map(em);
2961                 em = NULL;
2962
2963                 /*
2964                  * compressed and inline extents are written through other
2965                  * paths in the FS
2966                  */
2967                 if (compressed || block_start == EXTENT_MAP_HOLE ||
2968                     block_start == EXTENT_MAP_INLINE) {
2969                         /*
2970                          * end_io notification does not happen here for
2971                          * compressed extents
2972                          */
2973                         if (!compressed && tree->ops &&
2974                             tree->ops->writepage_end_io_hook)
2975                                 tree->ops->writepage_end_io_hook(page, cur,
2976                                                          cur + iosize - 1,
2977                                                          NULL, 1);
2978                         else if (compressed) {
2979                                 /* we don't want to end_page_writeback on
2980                                  * a compressed extent.  this happens
2981                                  * elsewhere
2982                                  */
2983                                 nr++;
2984                         }
2985
2986                         cur += iosize;
2987                         pg_offset += iosize;
2988                         continue;
2989                 }
2990                 /* leave this out until we have a page_mkwrite call */
2991                 if (0 && !test_range_bit(tree, cur, cur + iosize - 1,
2992                                    EXTENT_DIRTY, 0, NULL)) {
2993                         cur = cur + iosize;
2994                         pg_offset += iosize;
2995                         continue;
2996                 }
2997
2998                 if (tree->ops && tree->ops->writepage_io_hook) {
2999                         ret = tree->ops->writepage_io_hook(page, cur,
3000                                                 cur + iosize - 1);
3001                 } else {
3002                         ret = 0;
3003                 }
3004                 if (ret) {
3005                         SetPageError(page);
3006                 } else {
3007                         unsigned long max_nr = end_index + 1;
3008
3009                         set_range_writeback(tree, cur, cur + iosize - 1);
3010                         if (!PageWriteback(page)) {
3011                                 printk(KERN_ERR "btrfs warning page %lu not "
3012                                        "writeback, cur %llu end %llu\n",
3013                                        page->index, (unsigned long long)cur,
3014                                        (unsigned long long)end);
3015                         }
3016
3017                         ret = submit_extent_page(write_flags, tree, page,
3018                                                  sector, iosize, pg_offset,
3019                                                  bdev, &epd->bio, max_nr,
3020                                                  end_bio_extent_writepage,
3021                                                  0, 0, 0);
3022                         if (ret)
3023                                 SetPageError(page);
3024                 }
3025                 cur = cur + iosize;
3026                 pg_offset += iosize;
3027                 nr++;
3028         }
3029 done:
3030         if (nr == 0) {
3031                 /* make sure the mapping tag for page dirty gets cleared */
3032                 set_page_writeback(page);
3033                 end_page_writeback(page);
3034         }
3035         unlock_page(page);
3036
3037 done_unlocked:
3038
3039         /* drop our reference on any cached states */
3040         free_extent_state(cached_state);
3041         return 0;
3042 }
3043
3044 static int eb_wait(void *word)
3045 {
3046         io_schedule();
3047         return 0;
3048 }
3049
3050 static void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3051 {
3052         wait_on_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK, eb_wait,
3053                     TASK_UNINTERRUPTIBLE);
3054 }
3055
3056 static int lock_extent_buffer_for_io(struct extent_buffer *eb,
3057                                      struct btrfs_fs_info *fs_info,
3058                                      struct extent_page_data *epd)
3059 {
3060         unsigned long i, num_pages;
3061         int flush = 0;
3062         int ret = 0;
3063
3064         if (!btrfs_try_tree_write_lock(eb)) {
3065                 flush = 1;
3066                 flush_write_bio(epd);
3067                 btrfs_tree_lock(eb);
3068         }
3069
3070         if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3071                 btrfs_tree_unlock(eb);
3072                 if (!epd->sync_io)
3073                         return 0;
3074                 if (!flush) {
3075                         flush_write_bio(epd);
3076                         flush = 1;
3077                 }
3078                 while (1) {
3079                         wait_on_extent_buffer_writeback(eb);
3080                         btrfs_tree_lock(eb);
3081                         if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3082                                 break;
3083                         btrfs_tree_unlock(eb);
3084                 }
3085         }
3086
3087         /*
3088          * We need to do this to prevent races in people who check if the eb is
3089          * under IO since we can end up having no IO bits set for a short period
3090          * of time.
3091          */
3092         spin_lock(&eb->refs_lock);
3093         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3094                 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3095                 spin_unlock(&eb->refs_lock);
3096                 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3097                 spin_lock(&fs_info->delalloc_lock);
3098                 if (fs_info->dirty_metadata_bytes >= eb->len)
3099                         fs_info->dirty_metadata_bytes -= eb->len;
3100                 else
3101                         WARN_ON(1);
3102                 spin_unlock(&fs_info->delalloc_lock);
3103                 ret = 1;
3104         } else {
3105                 spin_unlock(&eb->refs_lock);
3106         }
3107
3108         btrfs_tree_unlock(eb);
3109
3110         if (!ret)
3111                 return ret;
3112
3113         num_pages = num_extent_pages(eb->start, eb->len);
3114         for (i = 0; i < num_pages; i++) {
3115                 struct page *p = extent_buffer_page(eb, i);
3116
3117                 if (!trylock_page(p)) {
3118                         if (!flush) {
3119                                 flush_write_bio(epd);
3120                                 flush = 1;
3121                         }
3122                         lock_page(p);
3123                 }
3124         }
3125
3126         return ret;
3127 }
3128
3129 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3130 {
3131         clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3132         smp_mb__after_clear_bit();
3133         wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3134 }
3135
3136 static void end_bio_extent_buffer_writepage(struct bio *bio, int err)
3137 {
3138         int uptodate = err == 0;
3139         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
3140         struct extent_buffer *eb;
3141         int done;
3142
3143         do {
3144                 struct page *page = bvec->bv_page;
3145
3146                 bvec--;
3147                 eb = (struct extent_buffer *)page->private;
3148                 BUG_ON(!eb);
3149                 done = atomic_dec_and_test(&eb->io_pages);
3150
3151                 if (!uptodate || test_bit(EXTENT_BUFFER_IOERR, &eb->bflags)) {
3152                         set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3153                         ClearPageUptodate(page);
3154                         SetPageError(page);
3155                 }
3156
3157                 end_page_writeback(page);
3158
3159                 if (!done)
3160                         continue;
3161
3162                 end_extent_buffer_writeback(eb);
3163         } while (bvec >= bio->bi_io_vec);
3164
3165         bio_put(bio);
3166
3167 }
3168
3169 static int write_one_eb(struct extent_buffer *eb,
3170                         struct btrfs_fs_info *fs_info,
3171                         struct writeback_control *wbc,
3172                         struct extent_page_data *epd)
3173 {
3174         struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3175         u64 offset = eb->start;
3176         unsigned long i, num_pages;
3177         int rw = (epd->sync_io ? WRITE_SYNC : WRITE);
3178         int ret = 0;
3179
3180         clear_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3181         num_pages = num_extent_pages(eb->start, eb->len);
3182         atomic_set(&eb->io_pages, num_pages);
3183         for (i = 0; i < num_pages; i++) {
3184                 struct page *p = extent_buffer_page(eb, i);
3185
3186                 clear_page_dirty_for_io(p);
3187                 set_page_writeback(p);
3188                 ret = submit_extent_page(rw, eb->tree, p, offset >> 9,
3189                                          PAGE_CACHE_SIZE, 0, bdev, &epd->bio,
3190                                          -1, end_bio_extent_buffer_writepage,
3191                                          0, 0, 0);
3192                 if (ret) {
3193                         set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3194                         SetPageError(p);
3195                         if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3196                                 end_extent_buffer_writeback(eb);
3197                         ret = -EIO;
3198                         break;
3199                 }
3200                 offset += PAGE_CACHE_SIZE;
3201                 update_nr_written(p, wbc, 1);
3202                 unlock_page(p);
3203         }
3204
3205         if (unlikely(ret)) {
3206                 for (; i < num_pages; i++) {
3207                         struct page *p = extent_buffer_page(eb, i);
3208                         unlock_page(p);
3209                 }
3210         }
3211
3212         return ret;
3213 }
3214
3215 int btree_write_cache_pages(struct address_space *mapping,
3216                                    struct writeback_control *wbc)
3217 {
3218         struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3219         struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3220         struct extent_buffer *eb, *prev_eb = NULL;
3221         struct extent_page_data epd = {
3222                 .bio = NULL,
3223                 .tree = tree,
3224                 .extent_locked = 0,
3225                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3226         };
3227         int ret = 0;
3228         int done = 0;
3229         int nr_to_write_done = 0;
3230         struct pagevec pvec;
3231         int nr_pages;
3232         pgoff_t index;
3233         pgoff_t end;            /* Inclusive */
3234         int scanned = 0;
3235         int tag;
3236
3237         pagevec_init(&pvec, 0);
3238         if (wbc->range_cyclic) {
3239                 index = mapping->writeback_index; /* Start from prev offset */
3240                 end = -1;
3241         } else {
3242                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
3243                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
3244                 scanned = 1;
3245         }
3246         if (wbc->sync_mode == WB_SYNC_ALL)
3247                 tag = PAGECACHE_TAG_TOWRITE;
3248         else
3249                 tag = PAGECACHE_TAG_DIRTY;
3250 retry:
3251         if (wbc->sync_mode == WB_SYNC_ALL)
3252                 tag_pages_for_writeback(mapping, index, end);
3253         while (!done && !nr_to_write_done && (index <= end) &&
3254                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
3255                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
3256                 unsigned i;
3257
3258                 scanned = 1;
3259                 for (i = 0; i < nr_pages; i++) {
3260                         struct page *page = pvec.pages[i];
3261
3262                         if (!PagePrivate(page))
3263                                 continue;
3264
3265                         if (!wbc->range_cyclic && page->index > end) {
3266                                 done = 1;
3267                                 break;
3268                         }
3269
3270                         eb = (struct extent_buffer *)page->private;
3271                         if (!eb) {
3272                                 WARN_ON(1);
3273                                 continue;
3274                         }
3275
3276                         if (eb == prev_eb)
3277                                 continue;
3278
3279                         if (!atomic_inc_not_zero(&eb->refs)) {
3280                                 WARN_ON(1);
3281                                 continue;
3282                         }
3283
3284                         prev_eb = eb;
3285                         ret = lock_extent_buffer_for_io(eb, fs_info, &epd);
3286                         if (!ret) {
3287                                 free_extent_buffer(eb);
3288                                 continue;
3289                         }
3290
3291                         ret = write_one_eb(eb, fs_info, wbc, &epd);
3292                         if (ret) {
3293                                 done = 1;
3294                                 free_extent_buffer(eb);
3295                                 break;
3296                         }
3297                         free_extent_buffer(eb);
3298
3299                         /*
3300                          * the filesystem may choose to bump up nr_to_write.
3301                          * We have to make sure to honor the new nr_to_write
3302                          * at any time
3303                          */
3304                         nr_to_write_done = wbc->nr_to_write <= 0;
3305                 }
3306                 pagevec_release(&pvec);
3307                 cond_resched();
3308         }
3309         if (!scanned && !done) {
3310                 /*
3311                  * We hit the last page and there is more work to be done: wrap
3312                  * back to the start of the file
3313                  */
3314                 scanned = 1;
3315                 index = 0;
3316                 goto retry;
3317         }
3318         flush_write_bio(&epd);
3319         return ret;
3320 }
3321
3322 /**
3323  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
3324  * @mapping: address space structure to write
3325  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3326  * @writepage: function called for each page
3327  * @data: data passed to writepage function
3328  *
3329  * If a page is already under I/O, write_cache_pages() skips it, even
3330  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
3331  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
3332  * and msync() need to guarantee that all the data which was dirty at the time
3333  * the call was made get new I/O started against them.  If wbc->sync_mode is
3334  * WB_SYNC_ALL then we were called for data integrity and we must wait for
3335  * existing IO to complete.
3336  */
3337 static int extent_write_cache_pages(struct extent_io_tree *tree,
3338                              struct address_space *mapping,
3339                              struct writeback_control *wbc,
3340                              writepage_t writepage, void *data,
3341                              void (*flush_fn)(void *))
3342 {
3343         struct inode *inode = mapping->host;
3344         int ret = 0;
3345         int done = 0;
3346         int nr_to_write_done = 0;
3347         struct pagevec pvec;
3348         int nr_pages;
3349         pgoff_t index;
3350         pgoff_t end;            /* Inclusive */
3351         int scanned = 0;
3352         int tag;
3353
3354         /*
3355          * We have to hold onto the inode so that ordered extents can do their
3356          * work when the IO finishes.  The alternative to this is failing to add
3357          * an ordered extent if the igrab() fails there and that is a huge pain
3358          * to deal with, so instead just hold onto the inode throughout the
3359          * writepages operation.  If it fails here we are freeing up the inode
3360          * anyway and we'd rather not waste our time writing out stuff that is
3361          * going to be truncated anyway.
3362          */
3363         if (!igrab(inode))
3364                 return 0;
3365
3366         pagevec_init(&pvec, 0);
3367         if (wbc->range_cyclic) {
3368                 index = mapping->writeback_index; /* Start from prev offset */
3369                 end = -1;
3370         } else {
3371                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
3372                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
3373                 scanned = 1;
3374         }
3375         if (wbc->sync_mode == WB_SYNC_ALL)
3376                 tag = PAGECACHE_TAG_TOWRITE;
3377         else
3378                 tag = PAGECACHE_TAG_DIRTY;
3379 retry:
3380         if (wbc->sync_mode == WB_SYNC_ALL)
3381                 tag_pages_for_writeback(mapping, index, end);
3382         while (!done && !nr_to_write_done && (index <= end) &&
3383                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
3384                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
3385                 unsigned i;
3386
3387                 scanned = 1;
3388                 for (i = 0; i < nr_pages; i++) {
3389                         struct page *page = pvec.pages[i];
3390
3391                         /*
3392                          * At this point we hold neither mapping->tree_lock nor
3393                          * lock on the page itself: the page may be truncated or
3394                          * invalidated (changing page->mapping to NULL), or even
3395                          * swizzled back from swapper_space to tmpfs file
3396                          * mapping
3397                          */
3398                         if (tree->ops &&
3399                             tree->ops->write_cache_pages_lock_hook) {
3400                                 tree->ops->write_cache_pages_lock_hook(page,
3401                                                                data, flush_fn);
3402                         } else {
3403                                 if (!trylock_page(page)) {
3404                                         flush_fn(data);
3405                                         lock_page(page);
3406                                 }
3407                         }
3408
3409                         if (unlikely(page->mapping != mapping)) {
3410                                 unlock_page(page);
3411                                 continue;
3412                         }
3413
3414                         if (!wbc->range_cyclic && page->index > end) {
3415                                 done = 1;
3416                                 unlock_page(page);
3417                                 continue;
3418                         }
3419
3420                         if (wbc->sync_mode != WB_SYNC_NONE) {
3421                                 if (PageWriteback(page))
3422                                         flush_fn(data);
3423                                 wait_on_page_writeback(page);
3424                         }
3425
3426                         if (PageWriteback(page) ||
3427                             !clear_page_dirty_for_io(page)) {
3428                                 unlock_page(page);
3429                                 continue;
3430                         }
3431
3432                         ret = (*writepage)(page, wbc, data);
3433
3434                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
3435                                 unlock_page(page);
3436                                 ret = 0;
3437                         }
3438                         if (ret)
3439                                 done = 1;
3440
3441                         /*
3442                          * the filesystem may choose to bump up nr_to_write.
3443                          * We have to make sure to honor the new nr_to_write
3444                          * at any time
3445                          */
3446                         nr_to_write_done = wbc->nr_to_write <= 0;
3447                 }
3448                 pagevec_release(&pvec);
3449                 cond_resched();
3450         }
3451         if (!scanned && !done) {
3452                 /*
3453                  * We hit the last page and there is more work to be done: wrap
3454                  * back to the start of the file
3455                  */
3456                 scanned = 1;
3457                 index = 0;
3458                 goto retry;
3459         }
3460         btrfs_add_delayed_iput(inode);
3461         return ret;
3462 }
3463
3464 static void flush_epd_write_bio(struct extent_page_data *epd)
3465 {
3466         if (epd->bio) {
3467                 int rw = WRITE;
3468                 int ret;
3469
3470                 if (epd->sync_io)
3471                         rw = WRITE_SYNC;
3472
3473                 ret = submit_one_bio(rw, epd->bio, 0, 0);
3474                 BUG_ON(ret < 0); /* -ENOMEM */
3475                 epd->bio = NULL;
3476         }
3477 }
3478
3479 static noinline void flush_write_bio(void *data)
3480 {
3481         struct extent_page_data *epd = data;
3482         flush_epd_write_bio(epd);
3483 }
3484
3485 int extent_write_full_page(struct extent_io_tree *tree, struct page *page,
3486                           get_extent_t *get_extent,
3487                           struct writeback_control *wbc)
3488 {
3489         int ret;
3490         struct extent_page_data epd = {
3491                 .bio = NULL,
3492                 .tree = tree,
3493                 .get_extent = get_extent,
3494                 .extent_locked = 0,
3495                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3496         };
3497
3498         ret = __extent_writepage(page, wbc, &epd);
3499
3500         flush_epd_write_bio(&epd);
3501         return ret;
3502 }
3503
3504 int extent_write_locked_range(struct extent_io_tree *tree, struct inode *inode,
3505                               u64 start, u64 end, get_extent_t *get_extent,
3506                               int mode)
3507 {
3508         int ret = 0;
3509         struct address_space *mapping = inode->i_mapping;
3510         struct page *page;
3511         unsigned long nr_pages = (end - start + PAGE_CACHE_SIZE) >>
3512                 PAGE_CACHE_SHIFT;
3513
3514         struct extent_page_data epd = {
3515                 .bio = NULL,
3516                 .tree = tree,
3517                 .get_extent = get_extent,
3518                 .extent_locked = 1,
3519                 .sync_io = mode == WB_SYNC_ALL,
3520         };
3521         struct writeback_control wbc_writepages = {
3522                 .sync_mode      = mode,
3523                 .nr_to_write    = nr_pages * 2,
3524                 .range_start    = start,
3525                 .range_end      = end + 1,
3526         };
3527
3528         while (start <= end) {
3529                 page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
3530                 if (clear_page_dirty_for_io(page))
3531                         ret = __extent_writepage(page, &wbc_writepages, &epd);
3532                 else {
3533                         if (tree->ops && tree->ops->writepage_end_io_hook)
3534                                 tree->ops->writepage_end_io_hook(page, start,
3535                                                  start + PAGE_CACHE_SIZE - 1,
3536                                                  NULL, 1);
3537                         unlock_page(page);
3538                 }
3539                 page_cache_release(page);
3540                 start += PAGE_CACHE_SIZE;
3541         }
3542
3543         flush_epd_write_bio(&epd);
3544         return ret;
3545 }
3546
3547 int extent_writepages(struct extent_io_tree *tree,
3548                       struct address_space *mapping,
3549                       get_extent_t *get_extent,
3550                       struct writeback_control *wbc)
3551 {
3552         int ret = 0;
3553         struct extent_page_data epd = {
3554                 .bio = NULL,
3555                 .tree = tree,
3556                 .get_extent = get_extent,
3557                 .extent_locked = 0,
3558                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3559         };
3560
3561         ret = extent_write_cache_pages(tree, mapping, wbc,
3562                                        __extent_writepage, &epd,
3563                                        flush_write_bio);
3564         flush_epd_write_bio(&epd);
3565         return ret;
3566 }
3567
3568 int extent_readpages(struct extent_io_tree *tree,
3569                      struct address_space *mapping,
3570                      struct list_head *pages, unsigned nr_pages,
3571                      get_extent_t get_extent)
3572 {
3573         struct bio *bio = NULL;
3574         unsigned page_idx;
3575         unsigned long bio_flags = 0;
3576         struct page *pagepool[16];
3577         struct page *page;
3578         int i = 0;
3579         int nr = 0;
3580
3581         for (page_idx = 0; page_idx < nr_pages; page_idx++) {
3582                 page = list_entry(pages->prev, struct page, lru);
3583
3584                 prefetchw(&page->flags);
3585                 list_del(&page->lru);
3586                 if (add_to_page_cache_lru(page, mapping,
3587                                         page->index, GFP_NOFS)) {
3588                         page_cache_release(page);
3589                         continue;
3590                 }
3591
3592                 pagepool[nr++] = page;
3593                 if (nr < ARRAY_SIZE(pagepool))
3594                         continue;
3595                 for (i = 0; i < nr; i++) {
3596                         __extent_read_full_page(tree, pagepool[i], get_extent,
3597                                         &bio, 0, &bio_flags);
3598                         page_cache_release(pagepool[i]);
3599                 }
3600                 nr = 0;
3601         }
3602         for (i = 0; i < nr; i++) {
3603                 __extent_read_full_page(tree, pagepool[i], get_extent,
3604                                         &bio, 0, &bio_flags);
3605                 page_cache_release(pagepool[i]);
3606         }
3607
3608         BUG_ON(!list_empty(pages));
3609         if (bio)
3610                 return submit_one_bio(READ, bio, 0, bio_flags);
3611         return 0;
3612 }
3613
3614 /*
3615  * basic invalidatepage code, this waits on any locked or writeback
3616  * ranges corresponding to the page, and then deletes any extent state
3617  * records from the tree
3618  */
3619 int extent_invalidatepage(struct extent_io_tree *tree,
3620                           struct page *page, unsigned long offset)
3621 {
3622         struct extent_state *cached_state = NULL;
3623         u64 start = ((u64)page->index << PAGE_CACHE_SHIFT);
3624         u64 end = start + PAGE_CACHE_SIZE - 1;
3625         size_t blocksize = page->mapping->host->i_sb->s_blocksize;
3626
3627         start += (offset + blocksize - 1) & ~(blocksize - 1);
3628         if (start > end)
3629                 return 0;
3630
3631         lock_extent_bits(tree, start, end, 0, &cached_state);
3632         wait_on_page_writeback(page);
3633         clear_extent_bit(tree, start, end,
3634                          EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
3635                          EXTENT_DO_ACCOUNTING,
3636                          1, 1, &cached_state, GFP_NOFS);
3637         return 0;
3638 }
3639
3640 /*
3641  * a helper for releasepage, this tests for areas of the page that
3642  * are locked or under IO and drops the related state bits if it is safe
3643  * to drop the page.
3644  */
3645 int try_release_extent_state(struct extent_map_tree *map,
3646                              struct extent_io_tree *tree, struct page *page,
3647                              gfp_t mask)
3648 {
3649         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
3650         u64 end = start + PAGE_CACHE_SIZE - 1;
3651         int ret = 1;
3652
3653         if (test_range_bit(tree, start, end,
3654                            EXTENT_IOBITS, 0, NULL))
3655                 ret = 0;
3656         else {
3657                 if ((mask & GFP_NOFS) == GFP_NOFS)
3658                         mask = GFP_NOFS;
3659                 /*
3660                  * at this point we can safely clear everything except the
3661                  * locked bit and the nodatasum bit
3662                  */
3663                 ret = clear_extent_bit(tree, start, end,
3664                                  ~(EXTENT_LOCKED | EXTENT_NODATASUM),
3665                                  0, 0, NULL, mask);
3666
3667                 /* if clear_extent_bit failed for enomem reasons,
3668                  * we can't allow the release to continue.
3669                  */
3670                 if (ret < 0)
3671                         ret = 0;
3672                 else
3673                         ret = 1;
3674         }
3675         return ret;
3676 }
3677
3678 /*
3679  * a helper for releasepage.  As long as there are no locked extents
3680  * in the range corresponding to the page, both state records and extent
3681  * map records are removed
3682  */
3683 int try_release_extent_mapping(struct extent_map_tree *map,
3684                                struct extent_io_tree *tree, struct page *page,
3685                                gfp_t mask)
3686 {
3687         struct extent_map *em;
3688         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
3689         u64 end = start + PAGE_CACHE_SIZE - 1;
3690
3691         if ((mask & __GFP_WAIT) &&
3692             page->mapping->host->i_size > 16 * 1024 * 1024) {
3693                 u64 len;
3694                 while (start <= end) {
3695                         len = end - start + 1;
3696                         write_lock(&map->lock);
3697                         em = lookup_extent_mapping(map, start, len);
3698                         if (!em) {
3699                                 write_unlock(&map->lock);
3700                                 break;
3701                         }
3702                         if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3703                             em->start != start) {
3704                                 write_unlock(&map->lock);
3705                                 free_extent_map(em);
3706                                 break;
3707                         }
3708                         if (!test_range_bit(tree, em->start,
3709                                             extent_map_end(em) - 1,
3710                                             EXTENT_LOCKED | EXTENT_WRITEBACK,
3711                                             0, NULL)) {
3712                                 remove_extent_mapping(map, em);
3713                                 /* once for the rb tree */
3714                                 free_extent_map(em);
3715                         }
3716                         start = extent_map_end(em);
3717                         write_unlock(&map->lock);
3718
3719                         /* once for us */
3720                         free_extent_map(em);
3721                 }
3722         }
3723         return try_release_extent_state(map, tree, page, mask);
3724 }
3725
3726 /*
3727  * helper function for fiemap, which doesn't want to see any holes.
3728  * This maps until we find something past 'last'
3729  */
3730 static struct extent_map *get_extent_skip_holes(struct inode *inode,
3731                                                 u64 offset,
3732                                                 u64 last,
3733                                                 get_extent_t *get_extent)
3734 {
3735         u64 sectorsize = BTRFS_I(inode)->root->sectorsize;
3736         struct extent_map *em;
3737         u64 len;
3738
3739         if (offset >= last)
3740                 return NULL;
3741
3742         while(1) {
3743                 len = last - offset;
3744                 if (len == 0)
3745                         break;
3746                 len = (len + sectorsize - 1) & ~(sectorsize - 1);
3747                 em = get_extent(inode, NULL, 0, offset, len, 0);
3748                 if (IS_ERR_OR_NULL(em))
3749                         return em;
3750
3751                 /* if this isn't a hole return it */
3752                 if (!test_bit(EXTENT_FLAG_VACANCY, &em->flags) &&
3753                     em->block_start != EXTENT_MAP_HOLE) {
3754                         return em;
3755                 }
3756
3757                 /* this is a hole, advance to the next extent */
3758                 offset = extent_map_end(em);
3759                 free_extent_map(em);
3760                 if (offset >= last)
3761                         break;
3762         }
3763         return NULL;
3764 }
3765
3766 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3767                 __u64 start, __u64 len, get_extent_t *get_extent)
3768 {
3769         int ret = 0;
3770         u64 off = start;
3771         u64 max = start + len;
3772         u32 flags = 0;
3773         u32 found_type;
3774         u64 last;
3775         u64 last_for_get_extent = 0;
3776         u64 disko = 0;
3777         u64 isize = i_size_read(inode);
3778         struct btrfs_key found_key;
3779         struct extent_map *em = NULL;
3780         struct extent_state *cached_state = NULL;
3781         struct btrfs_path *path;
3782         struct btrfs_file_extent_item *item;
3783         int end = 0;
3784         u64 em_start = 0;
3785         u64 em_len = 0;
3786         u64 em_end = 0;
3787         unsigned long emflags;
3788
3789         if (len == 0)
3790                 return -EINVAL;
3791
3792         path = btrfs_alloc_path();
3793         if (!path)
3794                 return -ENOMEM;
3795         path->leave_spinning = 1;
3796
3797         start = ALIGN(start, BTRFS_I(inode)->root->sectorsize);
3798         len = ALIGN(len, BTRFS_I(inode)->root->sectorsize);
3799
3800         /*
3801          * lookup the last file extent.  We're not using i_size here
3802          * because there might be preallocation past i_size
3803          */
3804         ret = btrfs_lookup_file_extent(NULL, BTRFS_I(inode)->root,
3805                                        path, btrfs_ino(inode), -1, 0);
3806         if (ret < 0) {
3807                 btrfs_free_path(path);
3808                 return ret;
3809         }
3810         WARN_ON(!ret);
3811         path->slots[0]--;
3812         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3813                               struct btrfs_file_extent_item);
3814         btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
3815         found_type = btrfs_key_type(&found_key);
3816
3817         /* No extents, but there might be delalloc bits */
3818         if (found_key.objectid != btrfs_ino(inode) ||
3819             found_type != BTRFS_EXTENT_DATA_KEY) {
3820                 /* have to trust i_size as the end */
3821                 last = (u64)-1;
3822                 last_for_get_extent = isize;
3823         } else {
3824                 /*
3825                  * remember the start of the last extent.  There are a
3826                  * bunch of different factors that go into the length of the
3827                  * extent, so its much less complex to remember where it started
3828                  */
3829                 last = found_key.offset;
3830                 last_for_get_extent = last + 1;
3831         }
3832         btrfs_free_path(path);
3833
3834         /*
3835          * we might have some extents allocated but more delalloc past those
3836          * extents.  so, we trust isize unless the start of the last extent is
3837          * beyond isize
3838          */
3839         if (last < isize) {
3840                 last = (u64)-1;
3841                 last_for_get_extent = isize;
3842         }
3843
3844         lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len, 0,
3845                          &cached_state);
3846
3847         em = get_extent_skip_holes(inode, start, last_for_get_extent,
3848                                    get_extent);
3849         if (!em)
3850                 goto out;
3851         if (IS_ERR(em)) {
3852                 ret = PTR_ERR(em);
3853                 goto out;
3854         }
3855
3856         while (!end) {
3857                 u64 offset_in_extent;
3858
3859                 /* break if the extent we found is outside the range */
3860                 if (em->start >= max || extent_map_end(em) < off)
3861                         break;
3862
3863                 /*
3864                  * get_extent may return an extent that starts before our
3865                  * requested range.  We have to make sure the ranges
3866                  * we return to fiemap always move forward and don't
3867                  * overlap, so adjust the offsets here
3868                  */
3869                 em_start = max(em->start, off);
3870
3871                 /*
3872                  * record the offset from the start of the extent
3873                  * for adjusting the disk offset below
3874                  */
3875                 offset_in_extent = em_start - em->start;
3876                 em_end = extent_map_end(em);
3877                 em_len = em_end - em_start;
3878                 emflags = em->flags;
3879                 disko = 0;
3880                 flags = 0;
3881
3882                 /*
3883                  * bump off for our next call to get_extent
3884                  */
3885                 off = extent_map_end(em);
3886                 if (off >= max)
3887                         end = 1;
3888
3889                 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
3890                         end = 1;
3891                         flags |= FIEMAP_EXTENT_LAST;
3892                 } else if (em->block_start == EXTENT_MAP_INLINE) {
3893                         flags |= (FIEMAP_EXTENT_DATA_INLINE |
3894                                   FIEMAP_EXTENT_NOT_ALIGNED);
3895                 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
3896                         flags |= (FIEMAP_EXTENT_DELALLOC |
3897                                   FIEMAP_EXTENT_UNKNOWN);
3898                 } else {
3899                         disko = em->block_start + offset_in_extent;
3900                 }
3901                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
3902                         flags |= FIEMAP_EXTENT_ENCODED;
3903
3904                 free_extent_map(em);
3905                 em = NULL;
3906                 if ((em_start >= last) || em_len == (u64)-1 ||
3907                    (last == (u64)-1 && isize <= em_end)) {
3908                         flags |= FIEMAP_EXTENT_LAST;
3909                         end = 1;
3910                 }
3911
3912                 /* now scan forward to see if this is really the last extent. */
3913                 em = get_extent_skip_holes(inode, off, last_for_get_extent,
3914                                            get_extent);
3915                 if (IS_ERR(em)) {
3916                         ret = PTR_ERR(em);
3917                         goto out;
3918                 }
3919                 if (!em) {
3920                         flags |= FIEMAP_EXTENT_LAST;
3921                         end = 1;
3922                 }
3923                 ret = fiemap_fill_next_extent(fieinfo, em_start, disko,
3924                                               em_len, flags);
3925                 if (ret)
3926                         goto out_free;
3927         }
3928 out_free:
3929         free_extent_map(em);
3930 out:
3931         unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len,
3932                              &cached_state, GFP_NOFS);
3933         return ret;
3934 }
3935
3936 inline struct page *extent_buffer_page(struct extent_buffer *eb,
3937                                               unsigned long i)
3938 {
3939         return eb->pages[i];
3940 }
3941
3942 inline unsigned long num_extent_pages(u64 start, u64 len)
3943 {
3944         return ((start + len + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT) -
3945                 (start >> PAGE_CACHE_SHIFT);
3946 }
3947
3948 static void __free_extent_buffer(struct extent_buffer *eb)
3949 {
3950 #if LEAK_DEBUG
3951         unsigned long flags;
3952         spin_lock_irqsave(&leak_lock, flags);
3953         list_del(&eb->leak_list);
3954         spin_unlock_irqrestore(&leak_lock, flags);
3955 #endif
3956         if (eb->pages && eb->pages != eb->inline_pages)
3957                 kfree(eb->pages);
3958         kmem_cache_free(extent_buffer_cache, eb);
3959 }
3960
3961 static struct extent_buffer *__alloc_extent_buffer(struct extent_io_tree *tree,
3962                                                    u64 start,
3963                                                    unsigned long len,
3964                                                    gfp_t mask)
3965 {
3966         struct extent_buffer *eb = NULL;
3967 #if LEAK_DEBUG
3968         unsigned long flags;
3969 #endif
3970
3971         eb = kmem_cache_zalloc(extent_buffer_cache, mask);
3972         if (eb == NULL)
3973                 return NULL;
3974         eb->start = start;
3975         eb->len = len;
3976         eb->tree = tree;
3977         eb->bflags = 0;
3978         rwlock_init(&eb->lock);
3979         atomic_set(&eb->write_locks, 0);
3980         atomic_set(&eb->read_locks, 0);
3981         atomic_set(&eb->blocking_readers, 0);
3982         atomic_set(&eb->blocking_writers, 0);
3983         atomic_set(&eb->spinning_readers, 0);
3984         atomic_set(&eb->spinning_writers, 0);
3985         eb->lock_nested = 0;
3986         init_waitqueue_head(&eb->write_lock_wq);
3987         init_waitqueue_head(&eb->read_lock_wq);
3988
3989 #if LEAK_DEBUG
3990         spin_lock_irqsave(&leak_lock, flags);
3991         list_add(&eb->leak_list, &buffers);
3992         spin_unlock_irqrestore(&leak_lock, flags);
3993 #endif
3994         spin_lock_init(&eb->refs_lock);
3995         atomic_set(&eb->refs, 1);
3996         atomic_set(&eb->io_pages, 0);
3997
3998         if (len > MAX_INLINE_EXTENT_BUFFER_SIZE) {
3999                 struct page **pages;
4000                 int num_pages = (len + PAGE_CACHE_SIZE - 1) >>
4001                         PAGE_CACHE_SHIFT;
4002                 pages = kzalloc(num_pages, mask);
4003                 if (!pages) {
4004                         __free_extent_buffer(eb);
4005                         return NULL;
4006                 }
4007                 eb->pages = pages;
4008         } else {
4009                 eb->pages = eb->inline_pages;
4010         }
4011
4012         return eb;
4013 }
4014
4015 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4016 {
4017         unsigned long i;
4018         struct page *p;
4019         struct extent_buffer *new;
4020         unsigned long num_pages = num_extent_pages(src->start, src->len);
4021
4022         new = __alloc_extent_buffer(NULL, src->start, src->len, GFP_ATOMIC);
4023         if (new == NULL)
4024                 return NULL;
4025
4026         for (i = 0; i < num_pages; i++) {
4027                 p = alloc_page(GFP_ATOMIC);
4028                 BUG_ON(!p);
4029                 attach_extent_buffer_page(new, p);
4030                 WARN_ON(PageDirty(p));
4031                 SetPageUptodate(p);
4032                 new->pages[i] = p;
4033         }
4034
4035         copy_extent_buffer(new, src, 0, 0, src->len);
4036         set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4037         set_bit(EXTENT_BUFFER_DUMMY, &new->bflags);
4038
4039         return new;
4040 }
4041
4042 struct extent_buffer *alloc_dummy_extent_buffer(u64 start, unsigned long len)
4043 {
4044         struct extent_buffer *eb;
4045         unsigned long num_pages = num_extent_pages(0, len);
4046         unsigned long i;
4047
4048         eb = __alloc_extent_buffer(NULL, start, len, GFP_ATOMIC);
4049         if (!eb)
4050                 return NULL;
4051
4052         for (i = 0; i < num_pages; i++) {
4053                 eb->pages[i] = alloc_page(GFP_ATOMIC);
4054                 if (!eb->pages[i])
4055                         goto err;
4056         }
4057         set_extent_buffer_uptodate(eb);
4058         btrfs_set_header_nritems(eb, 0);
4059         set_bit(EXTENT_BUFFER_DUMMY, &eb->bflags);
4060
4061         return eb;
4062 err:
4063         for (i--; i > 0; i--)
4064                 __free_page(eb->pages[i]);
4065         __free_extent_buffer(eb);
4066         return NULL;
4067 }
4068
4069 static int extent_buffer_under_io(struct extent_buffer *eb)
4070 {
4071         return (atomic_read(&eb->io_pages) ||
4072                 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4073                 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4074 }
4075
4076 /*
4077  * Helper for releasing extent buffer page.
4078  */
4079 static void btrfs_release_extent_buffer_page(struct extent_buffer *eb,
4080                                                 unsigned long start_idx)
4081 {
4082         unsigned long index;
4083         unsigned long num_pages;
4084         struct page *page;
4085         int mapped = !test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags);
4086
4087         BUG_ON(extent_buffer_under_io(eb));
4088
4089         num_pages = num_extent_pages(eb->start, eb->len);
4090         index = start_idx + num_pages;
4091         if (start_idx >= index)
4092                 return;
4093
4094         do {
4095                 index--;
4096                 page = extent_buffer_page(eb, index);
4097                 if (page && mapped) {
4098                         spin_lock(&page->mapping->private_lock);
4099                         /*
4100                          * We do this since we'll remove the pages after we've
4101                          * removed the eb from the radix tree, so we could race
4102                          * and have this page now attached to the new eb.  So
4103                          * only clear page_private if it's still connected to
4104                          * this eb.
4105                          */
4106                         if (PagePrivate(page) &&
4107                             page->private == (unsigned long)eb) {
4108                                 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4109                                 BUG_ON(PageDirty(page));
4110                                 BUG_ON(PageWriteback(page));
4111                                 /*
4112                                  * We need to make sure we haven't be attached
4113                                  * to a new eb.
4114                                  */
4115                                 ClearPagePrivate(page);
4116                                 set_page_private(page, 0);
4117                                 /* One for the page private */
4118                                 page_cache_release(page);
4119                         }
4120                         spin_unlock(&page->mapping->private_lock);
4121
4122                 }
4123                 if (page) {
4124                         /* One for when we alloced the page */
4125                         page_cache_release(page);
4126                 }
4127         } while (index != start_idx);
4128 }
4129
4130 /*
4131  * Helper for releasing the extent buffer.
4132  */
4133 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4134 {
4135         btrfs_release_extent_buffer_page(eb, 0);
4136         __free_extent_buffer(eb);
4137 }
4138
4139 static void check_buffer_tree_ref(struct extent_buffer *eb)
4140 {
4141         /* the ref bit is tricky.  We have to make sure it is set
4142          * if we have the buffer dirty.   Otherwise the
4143          * code to free a buffer can end up dropping a dirty
4144          * page
4145          *
4146          * Once the ref bit is set, it won't go away while the
4147          * buffer is dirty or in writeback, and it also won't
4148          * go away while we have the reference count on the
4149          * eb bumped.
4150          *
4151          * We can't just set the ref bit without bumping the
4152          * ref on the eb because free_extent_buffer might
4153          * see the ref bit and try to clear it.  If this happens
4154          * free_extent_buffer might end up dropping our original
4155          * ref by mistake and freeing the page before we are able
4156          * to add one more ref.
4157          *
4158          * So bump the ref count first, then set the bit.  If someone
4159          * beat us to it, drop the ref we added.
4160          */
4161         spin_lock(&eb->refs_lock);
4162         if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4163                 atomic_inc(&eb->refs);
4164         spin_unlock(&eb->refs_lock);
4165 }
4166
4167 static void mark_extent_buffer_accessed(struct extent_buffer *eb)
4168 {
4169         unsigned long num_pages, i;
4170
4171         check_buffer_tree_ref(eb);
4172
4173         num_pages = num_extent_pages(eb->start, eb->len);
4174         for (i = 0; i < num_pages; i++) {
4175                 struct page *p = extent_buffer_page(eb, i);
4176                 mark_page_accessed(p);
4177         }
4178 }
4179
4180 struct extent_buffer *alloc_extent_buffer(struct extent_io_tree *tree,
4181                                           u64 start, unsigned long len)
4182 {
4183         unsigned long num_pages = num_extent_pages(start, len);
4184         unsigned long i;
4185         unsigned long index = start >> PAGE_CACHE_SHIFT;
4186         struct extent_buffer *eb;
4187         struct extent_buffer *exists = NULL;
4188         struct page *p;
4189         struct address_space *mapping = tree->mapping;
4190         int uptodate = 1;
4191         int ret;
4192
4193         rcu_read_lock();
4194         eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
4195         if (eb && atomic_inc_not_zero(&eb->refs)) {
4196                 rcu_read_unlock();
4197                 mark_extent_buffer_accessed(eb);
4198                 return eb;
4199         }
4200         rcu_read_unlock();
4201
4202         eb = __alloc_extent_buffer(tree, start, len, GFP_NOFS);
4203         if (!eb)
4204                 return NULL;
4205
4206         for (i = 0; i < num_pages; i++, index++) {
4207                 p = find_or_create_page(mapping, index, GFP_NOFS);
4208                 if (!p) {
4209                         WARN_ON(1);
4210                         goto free_eb;
4211                 }
4212
4213                 spin_lock(&mapping->private_lock);
4214                 if (PagePrivate(p)) {
4215                         /*
4216                          * We could have already allocated an eb for this page
4217                          * and attached one so lets see if we can get a ref on
4218                          * the existing eb, and if we can we know it's good and
4219                          * we can just return that one, else we know we can just
4220                          * overwrite page->private.
4221                          */
4222                         exists = (struct extent_buffer *)p->private;
4223                         if (atomic_inc_not_zero(&exists->refs)) {
4224                                 spin_unlock(&mapping->private_lock);
4225                                 unlock_page(p);
4226                                 page_cache_release(p);
4227                                 mark_extent_buffer_accessed(exists);
4228                                 goto free_eb;
4229                         }
4230
4231                         /*
4232                          * Do this so attach doesn't complain and we need to
4233                          * drop the ref the old guy had.
4234                          */
4235                         ClearPagePrivate(p);
4236                         WARN_ON(PageDirty(p));
4237                         page_cache_release(p);
4238                 }
4239                 attach_extent_buffer_page(eb, p);
4240                 spin_unlock(&mapping->private_lock);
4241                 WARN_ON(PageDirty(p));
4242                 mark_page_accessed(p);
4243                 eb->pages[i] = p;
4244                 if (!PageUptodate(p))
4245                         uptodate = 0;
4246
4247                 /*
4248                  * see below about how we avoid a nasty race with release page
4249                  * and why we unlock later
4250                  */
4251         }
4252         if (uptodate)
4253                 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4254 again:
4255         ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
4256         if (ret)
4257                 goto free_eb;
4258
4259         spin_lock(&tree->buffer_lock);
4260         ret = radix_tree_insert(&tree->buffer, start >> PAGE_CACHE_SHIFT, eb);
4261         if (ret == -EEXIST) {
4262                 exists = radix_tree_lookup(&tree->buffer,
4263                                                 start >> PAGE_CACHE_SHIFT);
4264                 if (!atomic_inc_not_zero(&exists->refs)) {
4265                         spin_unlock(&tree->buffer_lock);
4266                         radix_tree_preload_end();
4267                         exists = NULL;
4268                         goto again;
4269                 }
4270                 spin_unlock(&tree->buffer_lock);
4271                 radix_tree_preload_end();
4272                 mark_extent_buffer_accessed(exists);
4273                 goto free_eb;
4274         }
4275         /* add one reference for the tree */
4276         check_buffer_tree_ref(eb);
4277         spin_unlock(&tree->buffer_lock);
4278         radix_tree_preload_end();
4279
4280         /*
4281          * there is a race where release page may have
4282          * tried to find this extent buffer in the radix
4283          * but failed.  It will tell the VM it is safe to
4284          * reclaim the, and it will clear the page private bit.
4285          * We must make sure to set the page private bit properly
4286          * after the extent buffer is in the radix tree so
4287          * it doesn't get lost
4288          */
4289         SetPageChecked(eb->pages[0]);
4290         for (i = 1; i < num_pages; i++) {
4291                 p = extent_buffer_page(eb, i);
4292                 ClearPageChecked(p);
4293                 unlock_page(p);
4294         }
4295         unlock_page(eb->pages[0]);
4296         return eb;
4297
4298 free_eb:
4299         for (i = 0; i < num_pages; i++) {
4300                 if (eb->pages[i])
4301                         unlock_page(eb->pages[i]);
4302         }
4303
4304         WARN_ON(!atomic_dec_and_test(&eb->refs));
4305         btrfs_release_extent_buffer(eb);
4306         return exists;
4307 }
4308
4309 struct extent_buffer *find_extent_buffer(struct extent_io_tree *tree,
4310                                          u64 start, unsigned long len)
4311 {
4312         struct extent_buffer *eb;
4313
4314         rcu_read_lock();
4315         eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
4316         if (eb && atomic_inc_not_zero(&eb->refs)) {
4317                 rcu_read_unlock();
4318                 mark_extent_buffer_accessed(eb);
4319                 return eb;
4320         }
4321         rcu_read_unlock();
4322
4323         return NULL;
4324 }
4325
4326 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4327 {
4328         struct extent_buffer *eb =
4329                         container_of(head, struct extent_buffer, rcu_head);
4330
4331         __free_extent_buffer(eb);
4332 }
4333
4334 /* Expects to have eb->eb_lock already held */
4335 static int release_extent_buffer(struct extent_buffer *eb, gfp_t mask)
4336 {
4337         WARN_ON(atomic_read(&eb->refs) == 0);
4338         if (atomic_dec_and_test(&eb->refs)) {
4339                 if (test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags)) {
4340                         spin_unlock(&eb->refs_lock);
4341                 } else {
4342                         struct extent_io_tree *tree = eb->tree;
4343
4344                         spin_unlock(&eb->refs_lock);
4345
4346                         spin_lock(&tree->buffer_lock);
4347                         radix_tree_delete(&tree->buffer,
4348                                           eb->start >> PAGE_CACHE_SHIFT);
4349                         spin_unlock(&tree->buffer_lock);
4350                 }
4351
4352                 /* Should be safe to release our pages at this point */
4353                 btrfs_release_extent_buffer_page(eb, 0);
4354
4355                 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4356                 return 1;
4357         }
4358         spin_unlock(&eb->refs_lock);
4359
4360         return 0;
4361 }
4362
4363 void free_extent_buffer(struct extent_buffer *eb)
4364 {
4365         if (!eb)
4366                 return;
4367
4368         spin_lock(&eb->refs_lock);
4369         if (atomic_read(&eb->refs) == 2 &&
4370             test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags))
4371                 atomic_dec(&eb->refs);
4372
4373         if (atomic_read(&eb->refs) == 2 &&
4374             test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4375             !extent_buffer_under_io(eb) &&
4376             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4377                 atomic_dec(&eb->refs);
4378
4379         /*
4380          * I know this is terrible, but it's temporary until we stop tracking
4381          * the uptodate bits and such for the extent buffers.
4382          */
4383         release_extent_buffer(eb, GFP_ATOMIC);
4384 }
4385
4386 void free_extent_buffer_stale(struct extent_buffer *eb)
4387 {
4388         if (!eb)
4389                 return;
4390
4391         spin_lock(&eb->refs_lock);
4392         set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4393
4394         if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4395             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4396                 atomic_dec(&eb->refs);
4397         release_extent_buffer(eb, GFP_NOFS);
4398 }
4399
4400 void clear_extent_buffer_dirty(struct extent_buffer *eb)
4401 {
4402         unsigned long i;
4403         unsigned long num_pages;
4404         struct page *page;
4405
4406         num_pages = num_extent_pages(eb->start, eb->len);
4407
4408         for (i = 0; i < num_pages; i++) {
4409                 page = extent_buffer_page(eb, i);
4410                 if (!PageDirty(page))
4411                         continue;
4412
4413                 lock_page(page);
4414                 WARN_ON(!PagePrivate(page));
4415
4416                 clear_page_dirty_for_io(page);
4417                 spin_lock_irq(&page->mapping->tree_lock);
4418                 if (!PageDirty(page)) {
4419                         radix_tree_tag_clear(&page->mapping->page_tree,
4420                                                 page_index(page),
4421                                                 PAGECACHE_TAG_DIRTY);
4422                 }
4423                 spin_unlock_irq(&page->mapping->tree_lock);
4424                 ClearPageError(page);
4425                 unlock_page(page);
4426         }
4427         WARN_ON(atomic_read(&eb->refs) == 0);
4428 }
4429
4430 int set_extent_buffer_dirty(struct extent_buffer *eb)
4431 {
4432         unsigned long i;
4433         unsigned long num_pages;
4434         int was_dirty = 0;
4435
4436         check_buffer_tree_ref(eb);
4437
4438         was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4439
4440         num_pages = num_extent_pages(eb->start, eb->len);
4441         WARN_ON(atomic_read(&eb->refs) == 0);
4442         WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4443
4444         for (i = 0; i < num_pages; i++)
4445                 set_page_dirty(extent_buffer_page(eb, i));
4446         return was_dirty;
4447 }
4448
4449 static int range_straddles_pages(u64 start, u64 len)
4450 {
4451         if (len < PAGE_CACHE_SIZE)
4452                 return 1;
4453         if (start & (PAGE_CACHE_SIZE - 1))
4454                 return 1;
4455         if ((start + len) & (PAGE_CACHE_SIZE - 1))
4456                 return 1;
4457         return 0;
4458 }
4459
4460 int clear_extent_buffer_uptodate(struct extent_buffer *eb)
4461 {
4462         unsigned long i;
4463         struct page *page;
4464         unsigned long num_pages;
4465
4466         clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4467         num_pages = num_extent_pages(eb->start, eb->len);
4468         for (i = 0; i < num_pages; i++) {
4469                 page = extent_buffer_page(eb, i);
4470                 if (page)
4471                         ClearPageUptodate(page);
4472         }
4473         return 0;
4474 }
4475
4476 int set_extent_buffer_uptodate(struct extent_buffer *eb)
4477 {
4478         unsigned long i;
4479         struct page *page;
4480         unsigned long num_pages;
4481
4482         set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4483         num_pages = num_extent_pages(eb->start, eb->len);
4484         for (i = 0; i < num_pages; i++) {
4485                 page = extent_buffer_page(eb, i);
4486                 SetPageUptodate(page);
4487         }
4488         return 0;
4489 }
4490
4491 int extent_range_uptodate(struct extent_io_tree *tree,
4492                           u64 start, u64 end)
4493 {
4494         struct page *page;
4495         int ret;
4496         int pg_uptodate = 1;
4497         int uptodate;
4498         unsigned long index;
4499
4500         if (range_straddles_pages(start, end - start + 1)) {
4501                 ret = test_range_bit(tree, start, end,
4502                                      EXTENT_UPTODATE, 1, NULL);
4503                 if (ret)
4504                         return 1;
4505         }
4506         while (start <= end) {
4507                 index = start >> PAGE_CACHE_SHIFT;
4508                 page = find_get_page(tree->mapping, index);
4509                 if (!page)
4510                         return 1;
4511                 uptodate = PageUptodate(page);
4512                 page_cache_release(page);
4513                 if (!uptodate) {
4514                         pg_uptodate = 0;
4515                         break;
4516                 }
4517                 start += PAGE_CACHE_SIZE;
4518         }
4519         return pg_uptodate;
4520 }
4521
4522 int extent_buffer_uptodate(struct extent_buffer *eb)
4523 {
4524         return test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4525 }
4526
4527 int read_extent_buffer_pages(struct extent_io_tree *tree,
4528                              struct extent_buffer *eb, u64 start, int wait,
4529                              get_extent_t *get_extent, int mirror_num)
4530 {
4531         unsigned long i;
4532         unsigned long start_i;
4533         struct page *page;
4534         int err;
4535         int ret = 0;
4536         int locked_pages = 0;
4537         int all_uptodate = 1;
4538         unsigned long num_pages;
4539         unsigned long num_reads = 0;
4540         struct bio *bio = NULL;
4541         unsigned long bio_flags = 0;
4542
4543         if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4544                 return 0;
4545
4546         if (start) {
4547                 WARN_ON(start < eb->start);
4548                 start_i = (start >> PAGE_CACHE_SHIFT) -
4549                         (eb->start >> PAGE_CACHE_SHIFT);
4550         } else {
4551                 start_i = 0;
4552         }
4553
4554         num_pages = num_extent_pages(eb->start, eb->len);
4555         for (i = start_i; i < num_pages; i++) {
4556                 page = extent_buffer_page(eb, i);
4557                 if (wait == WAIT_NONE) {
4558                         if (!trylock_page(page))
4559                                 goto unlock_exit;
4560                 } else {
4561                         lock_page(page);
4562                 }
4563                 locked_pages++;
4564                 if (!PageUptodate(page)) {
4565                         num_reads++;
4566                         all_uptodate = 0;
4567                 }
4568         }
4569         if (all_uptodate) {
4570                 if (start_i == 0)
4571                         set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4572                 goto unlock_exit;
4573         }
4574
4575         clear_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
4576         eb->read_mirror = 0;
4577         atomic_set(&eb->io_pages, num_reads);
4578         for (i = start_i; i < num_pages; i++) {
4579                 page = extent_buffer_page(eb, i);
4580                 if (!PageUptodate(page)) {
4581                         ClearPageError(page);
4582                         err = __extent_read_full_page(tree, page,
4583                                                       get_extent, &bio,
4584                                                       mirror_num, &bio_flags);
4585                         if (err)
4586                                 ret = err;
4587                 } else {
4588                         unlock_page(page);
4589                 }
4590         }
4591
4592         if (bio) {
4593                 err = submit_one_bio(READ, bio, mirror_num, bio_flags);
4594                 if (err)
4595                         return err;
4596         }
4597
4598         if (ret || wait != WAIT_COMPLETE)
4599                 return ret;
4600
4601         for (i = start_i; i < num_pages; i++) {
4602                 page = extent_buffer_page(eb, i);
4603                 wait_on_page_locked(page);
4604                 if (!PageUptodate(page))
4605                         ret = -EIO;
4606         }
4607
4608         return ret;
4609
4610 unlock_exit:
4611         i = start_i;
4612         while (locked_pages > 0) {
4613                 page = extent_buffer_page(eb, i);
4614                 i++;
4615                 unlock_page(page);
4616                 locked_pages--;
4617         }
4618         return ret;
4619 }
4620
4621 void read_extent_buffer(struct extent_buffer *eb, void *dstv,
4622                         unsigned long start,
4623                         unsigned long len)
4624 {
4625         size_t cur;
4626         size_t offset;
4627         struct page *page;
4628         char *kaddr;
4629         char *dst = (char *)dstv;
4630         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4631         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4632
4633         WARN_ON(start > eb->len);
4634         WARN_ON(start + len > eb->start + eb->len);
4635
4636         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4637
4638         while (len > 0) {
4639                 page = extent_buffer_page(eb, i);
4640
4641                 cur = min(len, (PAGE_CACHE_SIZE - offset));
4642                 kaddr = page_address(page);
4643                 memcpy(dst, kaddr + offset, cur);
4644
4645                 dst += cur;
4646                 len -= cur;
4647                 offset = 0;
4648                 i++;
4649         }
4650 }
4651
4652 int map_private_extent_buffer(struct extent_buffer *eb, unsigned long start,
4653                                unsigned long min_len, char **map,
4654                                unsigned long *map_start,
4655                                unsigned long *map_len)
4656 {
4657         size_t offset = start & (PAGE_CACHE_SIZE - 1);
4658         char *kaddr;
4659         struct page *p;
4660         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4661         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4662         unsigned long end_i = (start_offset + start + min_len - 1) >>
4663                 PAGE_CACHE_SHIFT;
4664
4665         if (i != end_i)
4666                 return -EINVAL;
4667
4668         if (i == 0) {
4669                 offset = start_offset;
4670                 *map_start = 0;
4671         } else {
4672                 offset = 0;
4673                 *map_start = ((u64)i << PAGE_CACHE_SHIFT) - start_offset;
4674         }
4675
4676         if (start + min_len > eb->len) {
4677                 printk(KERN_ERR "btrfs bad mapping eb start %llu len %lu, "
4678                        "wanted %lu %lu\n", (unsigned long long)eb->start,
4679                        eb->len, start, min_len);
4680                 WARN_ON(1);
4681                 return -EINVAL;
4682         }
4683
4684         p = extent_buffer_page(eb, i);
4685         kaddr = page_address(p);
4686         *map = kaddr + offset;
4687         *map_len = PAGE_CACHE_SIZE - offset;
4688         return 0;
4689 }
4690
4691 int memcmp_extent_buffer(struct extent_buffer *eb, const void *ptrv,
4692                           unsigned long start,
4693                           unsigned long len)
4694 {
4695         size_t cur;
4696         size_t offset;
4697         struct page *page;
4698         char *kaddr;
4699         char *ptr = (char *)ptrv;
4700         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4701         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4702         int ret = 0;
4703
4704         WARN_ON(start > eb->len);
4705         WARN_ON(start + len > eb->start + eb->len);
4706
4707         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4708
4709         while (len > 0) {
4710                 page = extent_buffer_page(eb, i);
4711
4712                 cur = min(len, (PAGE_CACHE_SIZE - offset));
4713
4714                 kaddr = page_address(page);
4715                 ret = memcmp(ptr, kaddr + offset, cur);
4716                 if (ret)
4717                         break;
4718
4719                 ptr += cur;
4720                 len -= cur;
4721                 offset = 0;
4722                 i++;
4723         }
4724         return ret;
4725 }
4726
4727 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
4728                          unsigned long start, unsigned long len)
4729 {
4730         size_t cur;
4731         size_t offset;
4732         struct page *page;
4733         char *kaddr;
4734         char *src = (char *)srcv;
4735         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4736         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4737
4738         WARN_ON(start > eb->len);
4739         WARN_ON(start + len > eb->start + eb->len);
4740
4741         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4742
4743         while (len > 0) {
4744                 page = extent_buffer_page(eb, i);
4745                 WARN_ON(!PageUptodate(page));
4746
4747                 cur = min(len, PAGE_CACHE_SIZE - offset);
4748                 kaddr = page_address(page);
4749                 memcpy(kaddr + offset, src, cur);
4750
4751                 src += cur;
4752                 len -= cur;
4753                 offset = 0;
4754                 i++;
4755         }
4756 }
4757
4758 void memset_extent_buffer(struct extent_buffer *eb, char c,
4759                           unsigned long start, unsigned long len)
4760 {
4761         size_t cur;
4762         size_t offset;
4763         struct page *page;
4764         char *kaddr;
4765         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4766         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4767
4768         WARN_ON(start > eb->len);
4769         WARN_ON(start + len > eb->start + eb->len);
4770
4771         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4772
4773         while (len > 0) {
4774                 page = extent_buffer_page(eb, i);
4775                 WARN_ON(!PageUptodate(page));
4776
4777                 cur = min(len, PAGE_CACHE_SIZE - offset);
4778                 kaddr = page_address(page);
4779                 memset(kaddr + offset, c, cur);
4780
4781                 len -= cur;
4782                 offset = 0;
4783                 i++;
4784         }
4785 }
4786
4787 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
4788                         unsigned long dst_offset, unsigned long src_offset,
4789                         unsigned long len)
4790 {
4791         u64 dst_len = dst->len;
4792         size_t cur;
4793         size_t offset;
4794         struct page *page;
4795         char *kaddr;
4796         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4797         unsigned long i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
4798
4799         WARN_ON(src->len != dst_len);
4800
4801         offset = (start_offset + dst_offset) &
4802                 ((unsigned long)PAGE_CACHE_SIZE - 1);
4803
4804         while (len > 0) {
4805                 page = extent_buffer_page(dst, i);
4806                 WARN_ON(!PageUptodate(page));
4807
4808                 cur = min(len, (unsigned long)(PAGE_CACHE_SIZE - offset));
4809
4810                 kaddr = page_address(page);
4811                 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4812
4813                 src_offset += cur;
4814                 len -= cur;
4815                 offset = 0;
4816                 i++;
4817         }
4818 }
4819
4820 static void move_pages(struct page *dst_page, struct page *src_page,
4821                        unsigned long dst_off, unsigned long src_off,
4822                        unsigned long len)
4823 {
4824         char *dst_kaddr = page_address(dst_page);
4825         if (dst_page == src_page) {
4826                 memmove(dst_kaddr + dst_off, dst_kaddr + src_off, len);
4827         } else {
4828                 char *src_kaddr = page_address(src_page);
4829                 char *p = dst_kaddr + dst_off + len;
4830                 char *s = src_kaddr + src_off + len;
4831
4832                 while (len--)
4833                         *--p = *--s;
4834         }
4835 }
4836
4837 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4838 {
4839         unsigned long distance = (src > dst) ? src - dst : dst - src;
4840         return distance < len;
4841 }
4842
4843 static void copy_pages(struct page *dst_page, struct page *src_page,
4844                        unsigned long dst_off, unsigned long src_off,
4845                        unsigned long len)
4846 {
4847         char *dst_kaddr = page_address(dst_page);
4848         char *src_kaddr;
4849         int must_memmove = 0;
4850
4851         if (dst_page != src_page) {
4852                 src_kaddr = page_address(src_page);
4853         } else {
4854                 src_kaddr = dst_kaddr;
4855                 if (areas_overlap(src_off, dst_off, len))
4856                         must_memmove = 1;
4857         }
4858
4859         if (must_memmove)
4860                 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
4861         else
4862                 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
4863 }
4864
4865 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
4866                            unsigned long src_offset, unsigned long len)
4867 {
4868         size_t cur;
4869         size_t dst_off_in_page;
4870         size_t src_off_in_page;
4871         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4872         unsigned long dst_i;
4873         unsigned long src_i;
4874
4875         if (src_offset + len > dst->len) {
4876                 printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
4877                        "len %lu dst len %lu\n", src_offset, len, dst->len);
4878                 BUG_ON(1);
4879         }
4880         if (dst_offset + len > dst->len) {
4881                 printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
4882                        "len %lu dst len %lu\n", dst_offset, len, dst->len);
4883                 BUG_ON(1);
4884         }
4885
4886         while (len > 0) {
4887                 dst_off_in_page = (start_offset + dst_offset) &
4888                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4889                 src_off_in_page = (start_offset + src_offset) &
4890                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4891
4892                 dst_i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
4893                 src_i = (start_offset + src_offset) >> PAGE_CACHE_SHIFT;
4894
4895                 cur = min(len, (unsigned long)(PAGE_CACHE_SIZE -
4896                                                src_off_in_page));
4897                 cur = min_t(unsigned long, cur,
4898                         (unsigned long)(PAGE_CACHE_SIZE - dst_off_in_page));
4899
4900                 copy_pages(extent_buffer_page(dst, dst_i),
4901                            extent_buffer_page(dst, src_i),
4902                            dst_off_in_page, src_off_in_page, cur);
4903
4904                 src_offset += cur;
4905                 dst_offset += cur;
4906                 len -= cur;
4907         }
4908 }
4909
4910 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
4911                            unsigned long src_offset, unsigned long len)
4912 {
4913         size_t cur;
4914         size_t dst_off_in_page;
4915         size_t src_off_in_page;
4916         unsigned long dst_end = dst_offset + len - 1;
4917         unsigned long src_end = src_offset + len - 1;
4918         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4919         unsigned long dst_i;
4920         unsigned long src_i;
4921
4922         if (src_offset + len > dst->len) {
4923                 printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
4924                        "len %lu len %lu\n", src_offset, len, dst->len);
4925                 BUG_ON(1);
4926         }
4927         if (dst_offset + len > dst->len) {
4928                 printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
4929                        "len %lu len %lu\n", dst_offset, len, dst->len);
4930                 BUG_ON(1);
4931         }
4932         if (dst_offset < src_offset) {
4933                 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
4934                 return;
4935         }
4936         while (len > 0) {
4937                 dst_i = (start_offset + dst_end) >> PAGE_CACHE_SHIFT;
4938                 src_i = (start_offset + src_end) >> PAGE_CACHE_SHIFT;
4939
4940                 dst_off_in_page = (start_offset + dst_end) &
4941                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4942                 src_off_in_page = (start_offset + src_end) &
4943                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4944
4945                 cur = min_t(unsigned long, len, src_off_in_page + 1);
4946                 cur = min(cur, dst_off_in_page + 1);
4947                 move_pages(extent_buffer_page(dst, dst_i),
4948                            extent_buffer_page(dst, src_i),
4949                            dst_off_in_page - cur + 1,
4950                            src_off_in_page - cur + 1, cur);
4951
4952                 dst_end -= cur;
4953                 src_end -= cur;
4954                 len -= cur;
4955         }
4956 }
4957
4958 int try_release_extent_buffer(struct page *page, gfp_t mask)
4959 {
4960         struct extent_buffer *eb;
4961
4962         /*
4963          * We need to make sure noboody is attaching this page to an eb right
4964          * now.
4965          */
4966         spin_lock(&page->mapping->private_lock);
4967         if (!PagePrivate(page)) {
4968                 spin_unlock(&page->mapping->private_lock);
4969                 return 1;
4970         }
4971
4972         eb = (struct extent_buffer *)page->private;
4973         BUG_ON(!eb);
4974
4975         /*
4976          * This is a little awful but should be ok, we need to make sure that
4977          * the eb doesn't disappear out from under us while we're looking at
4978          * this page.
4979          */
4980         spin_lock(&eb->refs_lock);
4981         if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4982                 spin_unlock(&eb->refs_lock);
4983                 spin_unlock(&page->mapping->private_lock);
4984                 return 0;
4985         }
4986         spin_unlock(&page->mapping->private_lock);
4987
4988         if ((mask & GFP_NOFS) == GFP_NOFS)
4989                 mask = GFP_NOFS;
4990
4991         /*
4992          * If tree ref isn't set then we know the ref on this eb is a real ref,
4993          * so just return, this page will likely be freed soon anyway.
4994          */
4995         if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4996                 spin_unlock(&eb->refs_lock);
4997                 return 0;
4998         }
4999
5000         return release_extent_buffer(eb, mask);
5001 }