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