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