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