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