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