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