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