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