~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/extent_io.c

Version: ~ [ linux-5.3-rc5 ] ~ [ linux-5.2.9 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.67 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.139 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.189 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.189 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.72 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 #include <linux/bitops.h>
  2 #include <linux/slab.h>
  3 #include <linux/bio.h>
  4 #include <linux/mm.h>
  5 #include <linux/pagemap.h>
  6 #include <linux/page-flags.h>
  7 #include <linux/module.h>
  8 #include <linux/spinlock.h>
  9 #include <linux/blkdev.h>
 10 #include <linux/swap.h>
 11 #include <linux/writeback.h>
 12 #include <linux/pagevec.h>
 13 #include <linux/prefetch.h>
 14 #include <linux/cleancache.h>
 15 #include "extent_io.h"
 16 #include "extent_map.h"
 17 #include "compat.h"
 18 #include "ctree.h"
 19 #include "btrfs_inode.h"
 20 #include "volumes.h"
 21 #include "check-integrity.h"
 22 #include "locking.h"
 23 #include "rcu-string.h"
 24 
 25 static struct kmem_cache *extent_state_cache;
 26 static struct kmem_cache *extent_buffer_cache;
 27 
 28 static LIST_HEAD(buffers);
 29 static LIST_HEAD(states);
 30 
 31 #define LEAK_DEBUG 0
 32 #if LEAK_DEBUG
 33 static DEFINE_SPINLOCK(leak_lock);
 34 #endif
 35 
 36 #define BUFFER_LRU_MAX 64
 37 
 38 struct tree_entry {
 39         u64 start;
 40         u64 end;
 41         struct rb_node rb_node;
 42 };
 43 
 44 struct extent_page_data {
 45         struct bio *bio;
 46         struct extent_io_tree *tree;
 47         get_extent_t *get_extent;
 48         unsigned long bio_flags;
 49 
 50         /* tells writepage not to lock the state bits for this range
 51          * it still does the unlocking
 52          */
 53         unsigned int extent_locked:1;
 54 
 55         /* tells the submit_bio code to use a WRITE_SYNC */
 56         unsigned int sync_io:1;
 57 };
 58 
 59 static noinline void flush_write_bio(void *data);
 60 static inline struct btrfs_fs_info *
 61 tree_fs_info(struct extent_io_tree *tree)
 62 {
 63         return btrfs_sb(tree->mapping->host->i_sb);
 64 }
 65 
 66 int __init extent_io_init(void)
 67 {
 68         extent_state_cache = kmem_cache_create("btrfs_extent_state",
 69                         sizeof(struct extent_state), 0,
 70                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
 71         if (!extent_state_cache)
 72                 return -ENOMEM;
 73 
 74         extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
 75                         sizeof(struct extent_buffer), 0,
 76                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
 77         if (!extent_buffer_cache)
 78                 goto free_state_cache;
 79         return 0;
 80 
 81 free_state_cache:
 82         kmem_cache_destroy(extent_state_cache);
 83         return -ENOMEM;
 84 }
 85 
 86 void extent_io_exit(void)
 87 {
 88         struct extent_state *state;
 89         struct extent_buffer *eb;
 90 
 91         while (!list_empty(&states)) {
 92                 state = list_entry(states.next, struct extent_state, leak_list);
 93                 printk(KERN_ERR "btrfs state leak: start %llu end %llu "
 94                        "state %lu in tree %p refs %d\n",
 95                        (unsigned long long)state->start,
 96                        (unsigned long long)state->end,
 97                        state->state, state->tree, atomic_read(&state->refs));
 98                 list_del(&state->leak_list);
 99                 kmem_cache_free(extent_state_cache, state);
100 
101         }
102 
103         while (!list_empty(&buffers)) {
104                 eb = list_entry(buffers.next, struct extent_buffer, leak_list);
105                 printk(KERN_ERR "btrfs buffer leak start %llu len %lu "
106                        "refs %d\n", (unsigned long long)eb->start,
107                        eb->len, atomic_read(&eb->refs));
108                 list_del(&eb->leak_list);
109                 kmem_cache_free(extent_buffer_cache, eb);
110         }
111 
112         /*
113          * Make sure all delayed rcu free are flushed before we
114          * destroy caches.
115          */
116         rcu_barrier();
117         if (extent_state_cache)
118                 kmem_cache_destroy(extent_state_cache);
119         if (extent_buffer_cache)
120                 kmem_cache_destroy(extent_buffer_cache);
121 }
122 
123 void extent_io_tree_init(struct extent_io_tree *tree,
124                          struct address_space *mapping)
125 {
126         tree->state = RB_ROOT;
127         INIT_RADIX_TREE(&tree->buffer, GFP_ATOMIC);
128         tree->ops = NULL;
129         tree->dirty_bytes = 0;
130         spin_lock_init(&tree->lock);
131         spin_lock_init(&tree->buffer_lock);
132         tree->mapping = mapping;
133 }
134 
135 static struct extent_state *alloc_extent_state(gfp_t mask)
136 {
137         struct extent_state *state;
138 #if LEAK_DEBUG
139         unsigned long flags;
140 #endif
141 
142         state = kmem_cache_alloc(extent_state_cache, mask);
143         if (!state)
144                 return state;
145         state->state = 0;
146         state->private = 0;
147         state->tree = NULL;
148 #if LEAK_DEBUG
149         spin_lock_irqsave(&leak_lock, flags);
150         list_add(&state->leak_list, &states);
151         spin_unlock_irqrestore(&leak_lock, flags);
152 #endif
153         atomic_set(&state->refs, 1);
154         init_waitqueue_head(&state->wq);
155         trace_alloc_extent_state(state, mask, _RET_IP_);
156         return state;
157 }
158 
159 void free_extent_state(struct extent_state *state)
160 {
161         if (!state)
162                 return;
163         if (atomic_dec_and_test(&state->refs)) {
164 #if LEAK_DEBUG
165                 unsigned long flags;
166 #endif
167                 WARN_ON(state->tree);
168 #if LEAK_DEBUG
169                 spin_lock_irqsave(&leak_lock, flags);
170                 list_del(&state->leak_list);
171                 spin_unlock_irqrestore(&leak_lock, flags);
172 #endif
173                 trace_free_extent_state(state, _RET_IP_);
174                 kmem_cache_free(extent_state_cache, state);
175         }
176 }
177 
178 static struct rb_node *tree_insert(struct rb_root *root, u64 offset,
179                                    struct rb_node *node)
180 {
181         struct rb_node **p = &root->rb_node;
182         struct rb_node *parent = NULL;
183         struct tree_entry *entry;
184 
185         while (*p) {
186                 parent = *p;
187                 entry = rb_entry(parent, struct tree_entry, rb_node);
188 
189                 if (offset < entry->start)
190                         p = &(*p)->rb_left;
191                 else if (offset > entry->end)
192                         p = &(*p)->rb_right;
193                 else
194                         return parent;
195         }
196 
197         rb_link_node(node, parent, p);
198         rb_insert_color(node, root);
199         return NULL;
200 }
201 
202 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
203                                      struct rb_node **prev_ret,
204                                      struct rb_node **next_ret)
205 {
206         struct rb_root *root = &tree->state;
207         struct rb_node *n = root->rb_node;
208         struct rb_node *prev = NULL;
209         struct rb_node *orig_prev = NULL;
210         struct tree_entry *entry;
211         struct tree_entry *prev_entry = NULL;
212 
213         while (n) {
214                 entry = rb_entry(n, struct tree_entry, rb_node);
215                 prev = n;
216                 prev_entry = entry;
217 
218                 if (offset < entry->start)
219                         n = n->rb_left;
220                 else if (offset > entry->end)
221                         n = n->rb_right;
222                 else
223                         return n;
224         }
225 
226         if (prev_ret) {
227                 orig_prev = prev;
228                 while (prev && offset > prev_entry->end) {
229                         prev = rb_next(prev);
230                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
231                 }
232                 *prev_ret = prev;
233                 prev = orig_prev;
234         }
235 
236         if (next_ret) {
237                 prev_entry = rb_entry(prev, struct tree_entry, rb_node);
238                 while (prev && offset < prev_entry->start) {
239                         prev = rb_prev(prev);
240                         prev_entry = rb_entry(prev, struct tree_entry, rb_node);
241                 }
242                 *next_ret = prev;
243         }
244         return NULL;
245 }
246 
247 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
248                                           u64 offset)
249 {
250         struct rb_node *prev = NULL;
251         struct rb_node *ret;
252 
253         ret = __etree_search(tree, offset, &prev, NULL);
254         if (!ret)
255                 return prev;
256         return ret;
257 }
258 
259 static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
260                      struct extent_state *other)
261 {
262         if (tree->ops && tree->ops->merge_extent_hook)
263                 tree->ops->merge_extent_hook(tree->mapping->host, new,
264                                              other);
265 }
266 
267 /*
268  * utility function to look for merge candidates inside a given range.
269  * Any extents with matching state are merged together into a single
270  * extent in the tree.  Extents with EXTENT_IO in their state field
271  * are not merged because the end_io handlers need to be able to do
272  * operations on them without sleeping (or doing allocations/splits).
273  *
274  * This should be called with the tree lock held.
275  */
276 static void merge_state(struct extent_io_tree *tree,
277                         struct extent_state *state)
278 {
279         struct extent_state *other;
280         struct rb_node *other_node;
281 
282         if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
283                 return;
284 
285         other_node = rb_prev(&state->rb_node);
286         if (other_node) {
287                 other = rb_entry(other_node, struct extent_state, rb_node);
288                 if (other->end == state->start - 1 &&
289                     other->state == state->state) {
290                         merge_cb(tree, state, other);
291                         state->start = other->start;
292                         other->tree = NULL;
293                         rb_erase(&other->rb_node, &tree->state);
294                         free_extent_state(other);
295                 }
296         }
297         other_node = rb_next(&state->rb_node);
298         if (other_node) {
299                 other = rb_entry(other_node, struct extent_state, rb_node);
300                 if (other->start == state->end + 1 &&
301                     other->state == state->state) {
302                         merge_cb(tree, state, other);
303                         state->end = other->end;
304                         other->tree = NULL;
305                         rb_erase(&other->rb_node, &tree->state);
306                         free_extent_state(other);
307                 }
308         }
309 }
310 
311 static void set_state_cb(struct extent_io_tree *tree,
312                          struct extent_state *state, int *bits)
313 {
314         if (tree->ops && tree->ops->set_bit_hook)
315                 tree->ops->set_bit_hook(tree->mapping->host, state, bits);
316 }
317 
318 static void clear_state_cb(struct extent_io_tree *tree,
319                            struct extent_state *state, int *bits)
320 {
321         if (tree->ops && tree->ops->clear_bit_hook)
322                 tree->ops->clear_bit_hook(tree->mapping->host, state, bits);
323 }
324 
325 static void set_state_bits(struct extent_io_tree *tree,
326                            struct extent_state *state, int *bits);
327 
328 /*
329  * insert an extent_state struct into the tree.  'bits' are set on the
330  * struct before it is inserted.
331  *
332  * This may return -EEXIST if the extent is already there, in which case the
333  * state struct is freed.
334  *
335  * The tree lock is not taken internally.  This is a utility function and
336  * probably isn't what you want to call (see set/clear_extent_bit).
337  */
338 static int insert_state(struct extent_io_tree *tree,
339                         struct extent_state *state, u64 start, u64 end,
340                         int *bits)
341 {
342         struct rb_node *node;
343 
344         if (end < start)
345                 WARN(1, KERN_ERR "btrfs end < start %llu %llu\n",
346                        (unsigned long long)end,
347                        (unsigned long long)start);
348         state->start = start;
349         state->end = end;
350 
351         set_state_bits(tree, state, bits);
352 
353         node = tree_insert(&tree->state, end, &state->rb_node);
354         if (node) {
355                 struct extent_state *found;
356                 found = rb_entry(node, struct extent_state, rb_node);
357                 printk(KERN_ERR "btrfs found node %llu %llu on insert of "
358                        "%llu %llu\n", (unsigned long long)found->start,
359                        (unsigned long long)found->end,
360                        (unsigned long long)start, (unsigned long long)end);
361                 return -EEXIST;
362         }
363         state->tree = tree;
364         merge_state(tree, state);
365         return 0;
366 }
367 
368 static void split_cb(struct extent_io_tree *tree, struct extent_state *orig,
369                      u64 split)
370 {
371         if (tree->ops && tree->ops->split_extent_hook)
372                 tree->ops->split_extent_hook(tree->mapping->host, orig, split);
373 }
374 
375 /*
376  * split a given extent state struct in two, inserting the preallocated
377  * struct 'prealloc' as the newly created second half.  'split' indicates an
378  * offset inside 'orig' where it should be split.
379  *
380  * Before calling,
381  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
382  * are two extent state structs in the tree:
383  * prealloc: [orig->start, split - 1]
384  * orig: [ split, orig->end ]
385  *
386  * The tree locks are not taken by this function. They need to be held
387  * by the caller.
388  */
389 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
390                        struct extent_state *prealloc, u64 split)
391 {
392         struct rb_node *node;
393 
394         split_cb(tree, orig, split);
395 
396         prealloc->start = orig->start;
397         prealloc->end = split - 1;
398         prealloc->state = orig->state;
399         orig->start = split;
400 
401         node = tree_insert(&tree->state, prealloc->end, &prealloc->rb_node);
402         if (node) {
403                 free_extent_state(prealloc);
404                 return -EEXIST;
405         }
406         prealloc->tree = tree;
407         return 0;
408 }
409 
410 static struct extent_state *next_state(struct extent_state *state)
411 {
412         struct rb_node *next = rb_next(&state->rb_node);
413         if (next)
414                 return rb_entry(next, struct extent_state, rb_node);
415         else
416                 return NULL;
417 }
418 
419 /*
420  * utility function to clear some bits in an extent state struct.
421  * it will optionally wake up any one waiting on this state (wake == 1).
422  *
423  * If no bits are set on the state struct after clearing things, the
424  * struct is freed and removed from the tree
425  */
426 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
427                                             struct extent_state *state,
428                                             int *bits, int wake)
429 {
430         struct extent_state *next;
431         int bits_to_clear = *bits & ~EXTENT_CTLBITS;
432 
433         if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
434                 u64 range = state->end - state->start + 1;
435                 WARN_ON(range > tree->dirty_bytes);
436                 tree->dirty_bytes -= range;
437         }
438         clear_state_cb(tree, state, bits);
439         state->state &= ~bits_to_clear;
440         if (wake)
441                 wake_up(&state->wq);
442         if (state->state == 0) {
443                 next = next_state(state);
444                 if (state->tree) {
445                         rb_erase(&state->rb_node, &tree->state);
446                         state->tree = NULL;
447                         free_extent_state(state);
448                 } else {
449                         WARN_ON(1);
450                 }
451         } else {
452                 merge_state(tree, state);
453                 next = next_state(state);
454         }
455         return next;
456 }
457 
458 static struct extent_state *
459 alloc_extent_state_atomic(struct extent_state *prealloc)
460 {
461         if (!prealloc)
462                 prealloc = alloc_extent_state(GFP_ATOMIC);
463 
464         return prealloc;
465 }
466 
467 void extent_io_tree_panic(struct extent_io_tree *tree, int err)
468 {
469         btrfs_panic(tree_fs_info(tree), err, "Locking error: "
470                     "Extent tree was modified by another "
471                     "thread while locked.");
472 }
473 
474 /*
475  * clear some bits on a range in the tree.  This may require splitting
476  * or inserting elements in the tree, so the gfp mask is used to
477  * indicate which allocations or sleeping are allowed.
478  *
479  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
480  * the given range from the tree regardless of state (ie for truncate).
481  *
482  * the range [start, end] is inclusive.
483  *
484  * This takes the tree lock, and returns 0 on success and < 0 on error.
485  */
486 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
487                      int bits, int wake, int delete,
488                      struct extent_state **cached_state,
489                      gfp_t mask)
490 {
491         struct extent_state *state;
492         struct extent_state *cached;
493         struct extent_state *prealloc = NULL;
494         struct rb_node *node;
495         u64 last_end;
496         int err;
497         int clear = 0;
498 
499         if (delete)
500                 bits |= ~EXTENT_CTLBITS;
501         bits |= EXTENT_FIRST_DELALLOC;
502 
503         if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
504                 clear = 1;
505 again:
506         if (!prealloc && (mask & __GFP_WAIT)) {
507                 prealloc = alloc_extent_state(mask);
508                 if (!prealloc)
509                         return -ENOMEM;
510         }
511 
512         spin_lock(&tree->lock);
513         if (cached_state) {
514                 cached = *cached_state;
515 
516                 if (clear) {
517                         *cached_state = NULL;
518                         cached_state = NULL;
519                 }
520 
521                 if (cached && cached->tree && cached->start <= start &&
522                     cached->end > start) {
523                         if (clear)
524                                 atomic_dec(&cached->refs);
525                         state = cached;
526                         goto hit_next;
527                 }
528                 if (clear)
529                         free_extent_state(cached);
530         }
531         /*
532          * this search will find the extents that end after
533          * our range starts
534          */
535         node = tree_search(tree, start);
536         if (!node)
537                 goto out;
538         state = rb_entry(node, struct extent_state, rb_node);
539 hit_next:
540         if (state->start > end)
541                 goto out;
542         WARN_ON(state->end < start);
543         last_end = state->end;
544 
545         /* the state doesn't have the wanted bits, go ahead */
546         if (!(state->state & bits)) {
547                 state = next_state(state);
548                 goto next;
549         }
550 
551         /*
552          *     | ---- desired range ---- |
553          *  | state | or
554          *  | ------------- state -------------- |
555          *
556          * We need to split the extent we found, and may flip
557          * bits on second half.
558          *
559          * If the extent we found extends past our range, we
560          * just split and search again.  It'll get split again
561          * the next time though.
562          *
563          * If the extent we found is inside our range, we clear
564          * the desired bit on it.
565          */
566 
567         if (state->start < start) {
568                 prealloc = alloc_extent_state_atomic(prealloc);
569                 BUG_ON(!prealloc);
570                 err = split_state(tree, state, prealloc, start);
571                 if (err)
572                         extent_io_tree_panic(tree, err);
573 
574                 prealloc = NULL;
575                 if (err)
576                         goto out;
577                 if (state->end <= end) {
578                         state = clear_state_bit(tree, state, &bits, wake);
579                         goto next;
580                 }
581                 goto search_again;
582         }
583         /*
584          * | ---- desired range ---- |
585          *                        | state |
586          * We need to split the extent, and clear the bit
587          * on the first half
588          */
589         if (state->start <= end && state->end > end) {
590                 prealloc = alloc_extent_state_atomic(prealloc);
591                 BUG_ON(!prealloc);
592                 err = split_state(tree, state, prealloc, end + 1);
593                 if (err)
594                         extent_io_tree_panic(tree, err);
595 
596                 if (wake)
597                         wake_up(&state->wq);
598 
599                 clear_state_bit(tree, prealloc, &bits, wake);
600 
601                 prealloc = NULL;
602                 goto out;
603         }
604 
605         state = clear_state_bit(tree, state, &bits, wake);
606 next:
607         if (last_end == (u64)-1)
608                 goto out;
609         start = last_end + 1;
610         if (start <= end && state && !need_resched())
611                 goto hit_next;
612         goto search_again;
613 
614 out:
615         spin_unlock(&tree->lock);
616         if (prealloc)
617                 free_extent_state(prealloc);
618 
619         return 0;
620 
621 search_again:
622         if (start > end)
623                 goto out;
624         spin_unlock(&tree->lock);
625         if (mask & __GFP_WAIT)
626                 cond_resched();
627         goto again;
628 }
629 
630 static void wait_on_state(struct extent_io_tree *tree,
631                           struct extent_state *state)
632                 __releases(tree->lock)
633                 __acquires(tree->lock)
634 {
635         DEFINE_WAIT(wait);
636         prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
637         spin_unlock(&tree->lock);
638         schedule();
639         spin_lock(&tree->lock);
640         finish_wait(&state->wq, &wait);
641 }
642 
643 /*
644  * waits for one or more bits to clear on a range in the state tree.
645  * The range [start, end] is inclusive.
646  * The tree lock is taken by this function
647  */
648 void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, int bits)
649 {
650         struct extent_state *state;
651         struct rb_node *node;
652 
653         spin_lock(&tree->lock);
654 again:
655         while (1) {
656                 /*
657                  * this search will find all the extents that end after
658                  * our range starts
659                  */
660                 node = tree_search(tree, start);
661                 if (!node)
662                         break;
663 
664                 state = rb_entry(node, struct extent_state, rb_node);
665 
666                 if (state->start > end)
667                         goto out;
668 
669                 if (state->state & bits) {
670                         start = state->start;
671                         atomic_inc(&state->refs);
672                         wait_on_state(tree, state);
673                         free_extent_state(state);
674                         goto again;
675                 }
676                 start = state->end + 1;
677 
678                 if (start > end)
679                         break;
680 
681                 cond_resched_lock(&tree->lock);
682         }
683 out:
684         spin_unlock(&tree->lock);
685 }
686 
687 static void set_state_bits(struct extent_io_tree *tree,
688                            struct extent_state *state,
689                            int *bits)
690 {
691         int bits_to_set = *bits & ~EXTENT_CTLBITS;
692 
693         set_state_cb(tree, state, bits);
694         if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
695                 u64 range = state->end - state->start + 1;
696                 tree->dirty_bytes += range;
697         }
698         state->state |= bits_to_set;
699 }
700 
701 static void cache_state(struct extent_state *state,
702                         struct extent_state **cached_ptr)
703 {
704         if (cached_ptr && !(*cached_ptr)) {
705                 if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY)) {
706                         *cached_ptr = state;
707                         atomic_inc(&state->refs);
708                 }
709         }
710 }
711 
712 static void uncache_state(struct extent_state **cached_ptr)
713 {
714         if (cached_ptr && (*cached_ptr)) {
715                 struct extent_state *state = *cached_ptr;
716                 *cached_ptr = NULL;
717                 free_extent_state(state);
718         }
719 }
720 
721 /*
722  * set some bits on a range in the tree.  This may require allocations or
723  * sleeping, so the gfp mask is used to indicate what is allowed.
724  *
725  * If any of the exclusive bits are set, this will fail with -EEXIST if some
726  * part of the range already has the desired bits set.  The start of the
727  * existing range is returned in failed_start in this case.
728  *
729  * [start, end] is inclusive This takes the tree lock.
730  */
731 
732 static int __must_check
733 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
734                  int bits, int exclusive_bits, u64 *failed_start,
735                  struct extent_state **cached_state, gfp_t mask)
736 {
737         struct extent_state *state;
738         struct extent_state *prealloc = NULL;
739         struct rb_node *node;
740         int err = 0;
741         u64 last_start;
742         u64 last_end;
743 
744         bits |= EXTENT_FIRST_DELALLOC;
745 again:
746         if (!prealloc && (mask & __GFP_WAIT)) {
747                 prealloc = alloc_extent_state(mask);
748                 BUG_ON(!prealloc);
749         }
750 
751         spin_lock(&tree->lock);
752         if (cached_state && *cached_state) {
753                 state = *cached_state;
754                 if (state->start <= start && state->end > start &&
755                     state->tree) {
756                         node = &state->rb_node;
757                         goto hit_next;
758                 }
759         }
760         /*
761          * this search will find all the extents that end after
762          * our range starts.
763          */
764         node = tree_search(tree, start);
765         if (!node) {
766                 prealloc = alloc_extent_state_atomic(prealloc);
767                 BUG_ON(!prealloc);
768                 err = insert_state(tree, prealloc, start, end, &bits);
769                 if (err)
770                         extent_io_tree_panic(tree, err);
771 
772                 prealloc = NULL;
773                 goto out;
774         }
775         state = rb_entry(node, struct extent_state, rb_node);
776 hit_next:
777         last_start = state->start;
778         last_end = state->end;
779 
780         /*
781          * | ---- desired range ---- |
782          * | state |
783          *
784          * Just lock what we found and keep going
785          */
786         if (state->start == start && state->end <= end) {
787                 if (state->state & exclusive_bits) {
788                         *failed_start = state->start;
789                         err = -EEXIST;
790                         goto out;
791                 }
792 
793                 set_state_bits(tree, state, &bits);
794                 cache_state(state, cached_state);
795                 merge_state(tree, state);
796                 if (last_end == (u64)-1)
797                         goto out;
798                 start = last_end + 1;
799                 state = next_state(state);
800                 if (start < end && state && state->start == start &&
801                     !need_resched())
802                         goto hit_next;
803                 goto search_again;
804         }
805 
806         /*
807          *     | ---- desired range ---- |
808          * | state |
809          *   or
810          * | ------------- state -------------- |
811          *
812          * We need to split the extent we found, and may flip bits on
813          * second half.
814          *
815          * If the extent we found extends past our
816          * range, we just split and search again.  It'll get split
817          * again the next time though.
818          *
819          * If the extent we found is inside our range, we set the
820          * desired bit on it.
821          */
822         if (state->start < start) {
823                 if (state->state & exclusive_bits) {
824                         *failed_start = start;
825                         err = -EEXIST;
826                         goto out;
827                 }
828 
829                 prealloc = alloc_extent_state_atomic(prealloc);
830                 BUG_ON(!prealloc);
831                 err = split_state(tree, state, prealloc, start);
832                 if (err)
833                         extent_io_tree_panic(tree, err);
834 
835                 prealloc = NULL;
836                 if (err)
837                         goto out;
838                 if (state->end <= end) {
839                         set_state_bits(tree, state, &bits);
840                         cache_state(state, cached_state);
841                         merge_state(tree, state);
842                         if (last_end == (u64)-1)
843                                 goto out;
844                         start = last_end + 1;
845                         state = next_state(state);
846                         if (start < end && state && state->start == start &&
847                             !need_resched())
848                                 goto hit_next;
849                 }
850                 goto search_again;
851         }
852         /*
853          * | ---- desired range ---- |
854          *     | state | or               | state |
855          *
856          * There's a hole, we need to insert something in it and
857          * ignore the extent we found.
858          */
859         if (state->start > start) {
860                 u64 this_end;
861                 if (end < last_start)
862                         this_end = end;
863                 else
864                         this_end = last_start - 1;
865 
866                 prealloc = alloc_extent_state_atomic(prealloc);
867                 BUG_ON(!prealloc);
868 
869                 /*
870                  * Avoid to free 'prealloc' if it can be merged with
871                  * the later extent.
872                  */
873                 err = insert_state(tree, prealloc, start, this_end,
874                                    &bits);
875                 if (err)
876                         extent_io_tree_panic(tree, err);
877 
878                 cache_state(prealloc, cached_state);
879                 prealloc = NULL;
880                 start = this_end + 1;
881                 goto search_again;
882         }
883         /*
884          * | ---- desired range ---- |
885          *                        | state |
886          * We need to split the extent, and set the bit
887          * on the first half
888          */
889         if (state->start <= end && state->end > end) {
890                 if (state->state & exclusive_bits) {
891                         *failed_start = start;
892                         err = -EEXIST;
893                         goto out;
894                 }
895 
896                 prealloc = alloc_extent_state_atomic(prealloc);
897                 BUG_ON(!prealloc);
898                 err = split_state(tree, state, prealloc, end + 1);
899                 if (err)
900                         extent_io_tree_panic(tree, err);
901 
902                 set_state_bits(tree, prealloc, &bits);
903                 cache_state(prealloc, cached_state);
904                 merge_state(tree, prealloc);
905                 prealloc = NULL;
906                 goto out;
907         }
908 
909         goto search_again;
910 
911 out:
912         spin_unlock(&tree->lock);
913         if (prealloc)
914                 free_extent_state(prealloc);
915 
916         return err;
917 
918 search_again:
919         if (start > end)
920                 goto out;
921         spin_unlock(&tree->lock);
922         if (mask & __GFP_WAIT)
923                 cond_resched();
924         goto again;
925 }
926 
927 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, int bits,
928                    u64 *failed_start, struct extent_state **cached_state,
929                    gfp_t mask)
930 {
931         return __set_extent_bit(tree, start, end, bits, 0, failed_start,
932                                 cached_state, mask);
933 }
934 
935 
936 /**
937  * convert_extent_bit - convert all bits in a given range from one bit to
938  *                      another
939  * @tree:       the io tree to search
940  * @start:      the start offset in bytes
941  * @end:        the end offset in bytes (inclusive)
942  * @bits:       the bits to set in this range
943  * @clear_bits: the bits to clear in this range
944  * @cached_state:       state that we're going to cache
945  * @mask:       the allocation mask
946  *
947  * This will go through and set bits for the given range.  If any states exist
948  * already in this range they are set with the given bit and cleared of the
949  * clear_bits.  This is only meant to be used by things that are mergeable, ie
950  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
951  * boundary bits like LOCK.
952  */
953 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
954                        int bits, int clear_bits,
955                        struct extent_state **cached_state, gfp_t mask)
956 {
957         struct extent_state *state;
958         struct extent_state *prealloc = NULL;
959         struct rb_node *node;
960         int err = 0;
961         u64 last_start;
962         u64 last_end;
963 
964 again:
965         if (!prealloc && (mask & __GFP_WAIT)) {
966                 prealloc = alloc_extent_state(mask);
967                 if (!prealloc)
968                         return -ENOMEM;
969         }
970 
971         spin_lock(&tree->lock);
972         if (cached_state && *cached_state) {
973                 state = *cached_state;
974                 if (state->start <= start && state->end > start &&
975                     state->tree) {
976                         node = &state->rb_node;
977                         goto hit_next;
978                 }
979         }
980 
981         /*
982          * this search will find all the extents that end after
983          * our range starts.
984          */
985         node = tree_search(tree, start);
986         if (!node) {
987                 prealloc = alloc_extent_state_atomic(prealloc);
988                 if (!prealloc) {
989                         err = -ENOMEM;
990                         goto out;
991                 }
992                 err = insert_state(tree, prealloc, start, end, &bits);
993                 prealloc = NULL;
994                 if (err)
995                         extent_io_tree_panic(tree, err);
996                 goto out;
997         }
998         state = rb_entry(node, struct extent_state, rb_node);
999 hit_next:
1000         last_start = state->start;
1001         last_end = state->end;
1002 
1003         /*
1004          * | ---- desired range ---- |
1005          * | state |
1006          *
1007          * Just lock what we found and keep going
1008          */
1009         if (state->start == start && state->end <= end) {
1010                 set_state_bits(tree, state, &bits);
1011                 cache_state(state, cached_state);
1012                 state = clear_state_bit(tree, state, &clear_bits, 0);
1013                 if (last_end == (u64)-1)
1014                         goto out;
1015                 start = last_end + 1;
1016                 if (start < end && state && state->start == start &&
1017                     !need_resched())
1018                         goto hit_next;
1019                 goto search_again;
1020         }
1021 
1022         /*
1023          *     | ---- desired range ---- |
1024          * | state |
1025          *   or
1026          * | ------------- state -------------- |
1027          *
1028          * We need to split the extent we found, and may flip bits on
1029          * second half.
1030          *
1031          * If the extent we found extends past our
1032          * range, we just split and search again.  It'll get split
1033          * again the next time though.
1034          *
1035          * If the extent we found is inside our range, we set the
1036          * desired bit on it.
1037          */
1038         if (state->start < start) {
1039                 prealloc = alloc_extent_state_atomic(prealloc);
1040                 if (!prealloc) {
1041                         err = -ENOMEM;
1042                         goto out;
1043                 }
1044                 err = split_state(tree, state, prealloc, start);
1045                 if (err)
1046                         extent_io_tree_panic(tree, err);
1047                 prealloc = NULL;
1048                 if (err)
1049                         goto out;
1050                 if (state->end <= end) {
1051                         set_state_bits(tree, state, &bits);
1052                         cache_state(state, cached_state);
1053                         state = clear_state_bit(tree, state, &clear_bits, 0);
1054                         if (last_end == (u64)-1)
1055                                 goto out;
1056                         start = last_end + 1;
1057                         if (start < end && state && state->start == start &&
1058                             !need_resched())
1059                                 goto hit_next;
1060                 }
1061                 goto search_again;
1062         }
1063         /*
1064          * | ---- desired range ---- |
1065          *     | state | or               | state |
1066          *
1067          * There's a hole, we need to insert something in it and
1068          * ignore the extent we found.
1069          */
1070         if (state->start > start) {
1071                 u64 this_end;
1072                 if (end < last_start)
1073                         this_end = end;
1074                 else
1075                         this_end = last_start - 1;
1076 
1077                 prealloc = alloc_extent_state_atomic(prealloc);
1078                 if (!prealloc) {
1079                         err = -ENOMEM;
1080                         goto out;
1081                 }
1082 
1083                 /*
1084                  * Avoid to free 'prealloc' if it can be merged with
1085                  * the later extent.
1086                  */
1087                 err = insert_state(tree, prealloc, start, this_end,
1088                                    &bits);
1089                 if (err)
1090                         extent_io_tree_panic(tree, err);
1091                 cache_state(prealloc, cached_state);
1092                 prealloc = NULL;
1093                 start = this_end + 1;
1094                 goto search_again;
1095         }
1096         /*
1097          * | ---- desired range ---- |
1098          *                        | state |
1099          * We need to split the extent, and set the bit
1100          * on the first half
1101          */
1102         if (state->start <= end && state->end > end) {
1103                 prealloc = alloc_extent_state_atomic(prealloc);
1104                 if (!prealloc) {
1105                         err = -ENOMEM;
1106                         goto out;
1107                 }
1108 
1109                 err = split_state(tree, state, prealloc, end + 1);
1110                 if (err)
1111                         extent_io_tree_panic(tree, err);
1112 
1113                 set_state_bits(tree, prealloc, &bits);
1114                 cache_state(prealloc, cached_state);
1115                 clear_state_bit(tree, prealloc, &clear_bits, 0);
1116                 prealloc = NULL;
1117                 goto out;
1118         }
1119 
1120         goto search_again;
1121 
1122 out:
1123         spin_unlock(&tree->lock);
1124         if (prealloc)
1125                 free_extent_state(prealloc);
1126 
1127         return err;
1128 
1129 search_again:
1130         if (start > end)
1131                 goto out;
1132         spin_unlock(&tree->lock);
1133         if (mask & __GFP_WAIT)
1134                 cond_resched();
1135         goto again;
1136 }
1137 
1138 /* wrappers around set/clear extent bit */
1139 int set_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
1140                      gfp_t mask)
1141 {
1142         return set_extent_bit(tree, start, end, EXTENT_DIRTY, NULL,
1143                               NULL, mask);
1144 }
1145 
1146 int set_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1147                     int bits, gfp_t mask)
1148 {
1149         return set_extent_bit(tree, start, end, bits, NULL,
1150                               NULL, mask);
1151 }
1152 
1153 int clear_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1154                       int bits, gfp_t mask)
1155 {
1156         return clear_extent_bit(tree, start, end, bits, 0, 0, NULL, mask);
1157 }
1158 
1159 int set_extent_delalloc(struct extent_io_tree *tree, u64 start, u64 end,
1160                         struct extent_state **cached_state, gfp_t mask)
1161 {
1162         return set_extent_bit(tree, start, end,
1163                               EXTENT_DELALLOC | EXTENT_UPTODATE,
1164                               NULL, cached_state, mask);
1165 }
1166 
1167 int set_extent_defrag(struct extent_io_tree *tree, u64 start, u64 end,
1168                       struct extent_state **cached_state, gfp_t mask)
1169 {
1170         return set_extent_bit(tree, start, end,
1171                               EXTENT_DELALLOC | EXTENT_UPTODATE | EXTENT_DEFRAG,
1172                               NULL, cached_state, mask);
1173 }
1174 
1175 int clear_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
1176                        gfp_t mask)
1177 {
1178         return clear_extent_bit(tree, start, end,
1179                                 EXTENT_DIRTY | EXTENT_DELALLOC |
1180                                 EXTENT_DO_ACCOUNTING, 0, 0, NULL, mask);
1181 }
1182 
1183 int set_extent_new(struct extent_io_tree *tree, u64 start, u64 end,
1184                      gfp_t mask)
1185 {
1186         return set_extent_bit(tree, start, end, EXTENT_NEW, NULL,
1187                               NULL, mask);
1188 }
1189 
1190 int set_extent_uptodate(struct extent_io_tree *tree, u64 start, u64 end,
1191                         struct extent_state **cached_state, gfp_t mask)
1192 {
1193         return set_extent_bit(tree, start, end, EXTENT_UPTODATE, 0,
1194                               cached_state, mask);
1195 }
1196 
1197 int clear_extent_uptodate(struct extent_io_tree *tree, u64 start, u64 end,
1198                           struct extent_state **cached_state, gfp_t mask)
1199 {
1200         return clear_extent_bit(tree, start, end, EXTENT_UPTODATE, 0, 0,
1201                                 cached_state, mask);
1202 }
1203 
1204 /*
1205  * either insert or lock state struct between start and end use mask to tell
1206  * us if waiting is desired.
1207  */
1208 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1209                      int bits, struct extent_state **cached_state)
1210 {
1211         int err;
1212         u64 failed_start;
1213         while (1) {
1214                 err = __set_extent_bit(tree, start, end, EXTENT_LOCKED | bits,
1215                                        EXTENT_LOCKED, &failed_start,
1216                                        cached_state, GFP_NOFS);
1217                 if (err == -EEXIST) {
1218                         wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1219                         start = failed_start;
1220                 } else
1221                         break;
1222                 WARN_ON(start > end);
1223         }
1224         return err;
1225 }
1226 
1227 int lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1228 {
1229         return lock_extent_bits(tree, start, end, 0, NULL);
1230 }
1231 
1232 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1233 {
1234         int err;
1235         u64 failed_start;
1236 
1237         err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1238                                &failed_start, NULL, GFP_NOFS);
1239         if (err == -EEXIST) {
1240                 if (failed_start > start)
1241                         clear_extent_bit(tree, start, failed_start - 1,
1242                                          EXTENT_LOCKED, 1, 0, NULL, GFP_NOFS);
1243                 return 0;
1244         }
1245         return 1;
1246 }
1247 
1248 int unlock_extent_cached(struct extent_io_tree *tree, u64 start, u64 end,
1249                          struct extent_state **cached, gfp_t mask)
1250 {
1251         return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, cached,
1252                                 mask);
1253 }
1254 
1255 int unlock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1256 {
1257         return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, NULL,
1258                                 GFP_NOFS);
1259 }
1260 
1261 int extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1262 {
1263         unsigned long index = start >> PAGE_CACHE_SHIFT;
1264         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1265         struct page *page;
1266 
1267         while (index <= end_index) {
1268                 page = find_get_page(inode->i_mapping, index);
1269                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1270                 clear_page_dirty_for_io(page);
1271                 page_cache_release(page);
1272                 index++;
1273         }
1274         return 0;
1275 }
1276 
1277 int extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1278 {
1279         unsigned long index = start >> PAGE_CACHE_SHIFT;
1280         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1281         struct page *page;
1282 
1283         while (index <= end_index) {
1284                 page = find_get_page(inode->i_mapping, index);
1285                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1286                 account_page_redirty(page);
1287                 __set_page_dirty_nobuffers(page);
1288                 page_cache_release(page);
1289                 index++;
1290         }
1291         return 0;
1292 }
1293 
1294 /*
1295  * helper function to set both pages and extents in the tree writeback
1296  */
1297 static int set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
1298 {
1299         unsigned long index = start >> PAGE_CACHE_SHIFT;
1300         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1301         struct page *page;
1302 
1303         while (index <= end_index) {
1304                 page = find_get_page(tree->mapping, index);
1305                 BUG_ON(!page); /* Pages should be in the extent_io_tree */
1306                 set_page_writeback(page);
1307                 page_cache_release(page);
1308                 index++;
1309         }
1310         return 0;
1311 }
1312 
1313 /* find the first state struct with 'bits' set after 'start', and
1314  * return it.  tree->lock must be held.  NULL will returned if
1315  * nothing was found after 'start'
1316  */
1317 struct extent_state *find_first_extent_bit_state(struct extent_io_tree *tree,
1318                                                  u64 start, int bits)
1319 {
1320         struct rb_node *node;
1321         struct extent_state *state;
1322 
1323         /*
1324          * this search will find all the extents that end after
1325          * our range starts.
1326          */
1327         node = tree_search(tree, start);
1328         if (!node)
1329                 goto out;
1330 
1331         while (1) {
1332                 state = rb_entry(node, struct extent_state, rb_node);
1333                 if (state->end >= start && (state->state & bits))
1334                         return state;
1335 
1336                 node = rb_next(node);
1337                 if (!node)
1338                         break;
1339         }
1340 out:
1341         return NULL;
1342 }
1343 
1344 /*
1345  * find the first offset in the io tree with 'bits' set. zero is
1346  * returned if we find something, and *start_ret and *end_ret are
1347  * set to reflect the state struct that was found.
1348  *
1349  * If nothing was found, 1 is returned. If found something, return 0.
1350  */
1351 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1352                           u64 *start_ret, u64 *end_ret, int bits,
1353                           struct extent_state **cached_state)
1354 {
1355         struct extent_state *state;
1356         struct rb_node *n;
1357         int ret = 1;
1358 
1359         spin_lock(&tree->lock);
1360         if (cached_state && *cached_state) {
1361                 state = *cached_state;
1362                 if (state->end == start - 1 && state->tree) {
1363                         n = rb_next(&state->rb_node);
1364                         while (n) {
1365                                 state = rb_entry(n, struct extent_state,
1366                                                  rb_node);
1367                                 if (state->state & bits)
1368                                         goto got_it;
1369                                 n = rb_next(n);
1370                         }
1371                         free_extent_state(*cached_state);
1372                         *cached_state = NULL;
1373                         goto out;
1374                 }
1375                 free_extent_state(*cached_state);
1376                 *cached_state = NULL;
1377         }
1378 
1379         state = find_first_extent_bit_state(tree, start, bits);
1380 got_it:
1381         if (state) {
1382                 cache_state(state, cached_state);
1383                 *start_ret = state->start;
1384                 *end_ret = state->end;
1385                 ret = 0;
1386         }
1387 out:
1388         spin_unlock(&tree->lock);
1389         return ret;
1390 }
1391 
1392 /*
1393  * find a contiguous range of bytes in the file marked as delalloc, not
1394  * more than 'max_bytes'.  start and end are used to return the range,
1395  *
1396  * 1 is returned if we find something, 0 if nothing was in the tree
1397  */
1398 static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
1399                                         u64 *start, u64 *end, u64 max_bytes,
1400                                         struct extent_state **cached_state)
1401 {
1402         struct rb_node *node;
1403         struct extent_state *state;
1404         u64 cur_start = *start;
1405         u64 found = 0;
1406         u64 total_bytes = 0;
1407 
1408         spin_lock(&tree->lock);
1409 
1410         /*
1411          * this search will find all the extents that end after
1412          * our range starts.
1413          */
1414         node = tree_search(tree, cur_start);
1415         if (!node) {
1416                 if (!found)
1417                         *end = (u64)-1;
1418                 goto out;
1419         }
1420 
1421         while (1) {
1422                 state = rb_entry(node, struct extent_state, rb_node);
1423                 if (found && (state->start != cur_start ||
1424                               (state->state & EXTENT_BOUNDARY))) {
1425                         goto out;
1426                 }
1427                 if (!(state->state & EXTENT_DELALLOC)) {
1428                         if (!found)
1429                                 *end = state->end;
1430                         goto out;
1431                 }
1432                 if (!found) {
1433                         *start = state->start;
1434                         *cached_state = state;
1435                         atomic_inc(&state->refs);
1436                 }
1437                 found++;
1438                 *end = state->end;
1439                 cur_start = state->end + 1;
1440                 node = rb_next(node);
1441                 if (!node)
1442                         break;
1443                 total_bytes += state->end - state->start + 1;
1444                 if (total_bytes >= max_bytes)
1445                         break;
1446         }
1447 out:
1448         spin_unlock(&tree->lock);
1449         return found;
1450 }
1451 
1452 static noinline void __unlock_for_delalloc(struct inode *inode,
1453                                            struct page *locked_page,
1454                                            u64 start, u64 end)
1455 {
1456         int ret;
1457         struct page *pages[16];
1458         unsigned long index = start >> PAGE_CACHE_SHIFT;
1459         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1460         unsigned long nr_pages = end_index - index + 1;
1461         int i;
1462 
1463         if (index == locked_page->index && end_index == index)
1464                 return;
1465 
1466         while (nr_pages > 0) {
1467                 ret = find_get_pages_contig(inode->i_mapping, index,
1468                                      min_t(unsigned long, nr_pages,
1469                                      ARRAY_SIZE(pages)), pages);
1470                 for (i = 0; i < ret; i++) {
1471                         if (pages[i] != locked_page)
1472                                 unlock_page(pages[i]);
1473                         page_cache_release(pages[i]);
1474                 }
1475                 nr_pages -= ret;
1476                 index += ret;
1477                 cond_resched();
1478         }
1479 }
1480 
1481 static noinline int lock_delalloc_pages(struct inode *inode,
1482                                         struct page *locked_page,
1483                                         u64 delalloc_start,
1484                                         u64 delalloc_end)
1485 {
1486         unsigned long index = delalloc_start >> PAGE_CACHE_SHIFT;
1487         unsigned long start_index = index;
1488         unsigned long end_index = delalloc_end >> PAGE_CACHE_SHIFT;
1489         unsigned long pages_locked = 0;
1490         struct page *pages[16];
1491         unsigned long nrpages;
1492         int ret;
1493         int i;
1494 
1495         /* the caller is responsible for locking the start index */
1496         if (index == locked_page->index && index == end_index)
1497                 return 0;
1498 
1499         /* skip the page at the start index */
1500         nrpages = end_index - index + 1;
1501         while (nrpages > 0) {
1502                 ret = find_get_pages_contig(inode->i_mapping, index,
1503                                      min_t(unsigned long,
1504                                      nrpages, ARRAY_SIZE(pages)), pages);
1505                 if (ret == 0) {
1506                         ret = -EAGAIN;
1507                         goto done;
1508                 }
1509                 /* now we have an array of pages, lock them all */
1510                 for (i = 0; i < ret; i++) {
1511                         /*
1512                          * the caller is taking responsibility for
1513                          * locked_page
1514                          */
1515                         if (pages[i] != locked_page) {
1516                                 lock_page(pages[i]);
1517                                 if (!PageDirty(pages[i]) ||
1518                                     pages[i]->mapping != inode->i_mapping) {
1519                                         ret = -EAGAIN;
1520                                         unlock_page(pages[i]);
1521                                         page_cache_release(pages[i]);
1522                                         goto done;
1523                                 }
1524                         }
1525                         page_cache_release(pages[i]);
1526                         pages_locked++;
1527                 }
1528                 nrpages -= ret;
1529                 index += ret;
1530                 cond_resched();
1531         }
1532         ret = 0;
1533 done:
1534         if (ret && pages_locked) {
1535                 __unlock_for_delalloc(inode, locked_page,
1536                               delalloc_start,
1537                               ((u64)(start_index + pages_locked - 1)) <<
1538                               PAGE_CACHE_SHIFT);
1539         }
1540         return ret;
1541 }
1542 
1543 /*
1544  * find a contiguous range of bytes in the file marked as delalloc, not
1545  * more than 'max_bytes'.  start and end are used to return the range,
1546  *
1547  * 1 is returned if we find something, 0 if nothing was in the tree
1548  */
1549 static noinline u64 find_lock_delalloc_range(struct inode *inode,
1550                                              struct extent_io_tree *tree,
1551                                              struct page *locked_page,
1552                                              u64 *start, u64 *end,
1553                                              u64 max_bytes)
1554 {
1555         u64 delalloc_start;
1556         u64 delalloc_end;
1557         u64 found;
1558         struct extent_state *cached_state = NULL;
1559         int ret;
1560         int loops = 0;
1561 
1562 again:
1563         /* step one, find a bunch of delalloc bytes starting at start */
1564         delalloc_start = *start;
1565         delalloc_end = 0;
1566         found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1567                                     max_bytes, &cached_state);
1568         if (!found || delalloc_end <= *start) {
1569                 *start = delalloc_start;
1570                 *end = delalloc_end;
1571                 free_extent_state(cached_state);
1572                 return found;
1573         }
1574 
1575         /*
1576          * start comes from the offset of locked_page.  We have to lock
1577          * pages in order, so we can't process delalloc bytes before
1578          * locked_page
1579          */
1580         if (delalloc_start < *start)
1581                 delalloc_start = *start;
1582 
1583         /*
1584          * make sure to limit the number of pages we try to lock down
1585          * if we're looping.
1586          */
1587         if (delalloc_end + 1 - delalloc_start > max_bytes && loops)
1588                 delalloc_end = delalloc_start + PAGE_CACHE_SIZE - 1;
1589 
1590         /* step two, lock all the pages after the page that has start */
1591         ret = lock_delalloc_pages(inode, locked_page,
1592                                   delalloc_start, delalloc_end);
1593         if (ret == -EAGAIN) {
1594                 /* some of the pages are gone, lets avoid looping by
1595                  * shortening the size of the delalloc range we're searching
1596                  */
1597                 free_extent_state(cached_state);
1598                 if (!loops) {
1599                         unsigned long offset = (*start) & (PAGE_CACHE_SIZE - 1);
1600                         max_bytes = PAGE_CACHE_SIZE - offset;
1601                         loops = 1;
1602                         goto again;
1603                 } else {
1604                         found = 0;
1605                         goto out_failed;
1606                 }
1607         }
1608         BUG_ON(ret); /* Only valid values are 0 and -EAGAIN */
1609 
1610         /* step three, lock the state bits for the whole range */
1611         lock_extent_bits(tree, delalloc_start, delalloc_end, 0, &cached_state);
1612 
1613         /* then test to make sure it is all still delalloc */
1614         ret = test_range_bit(tree, delalloc_start, delalloc_end,
1615                              EXTENT_DELALLOC, 1, cached_state);
1616         if (!ret) {
1617                 unlock_extent_cached(tree, delalloc_start, delalloc_end,
1618                                      &cached_state, GFP_NOFS);
1619                 __unlock_for_delalloc(inode, locked_page,
1620                               delalloc_start, delalloc_end);
1621                 cond_resched();
1622                 goto again;
1623         }
1624         free_extent_state(cached_state);
1625         *start = delalloc_start;
1626         *end = delalloc_end;
1627 out_failed:
1628         return found;
1629 }
1630 
1631 int extent_clear_unlock_delalloc(struct inode *inode,
1632                                 struct extent_io_tree *tree,
1633                                 u64 start, u64 end, struct page *locked_page,
1634                                 unsigned long op)
1635 {
1636         int ret;
1637         struct page *pages[16];
1638         unsigned long index = start >> PAGE_CACHE_SHIFT;
1639         unsigned long end_index = end >> PAGE_CACHE_SHIFT;
1640         unsigned long nr_pages = end_index - index + 1;
1641         int i;
1642         int clear_bits = 0;
1643 
1644         if (op & EXTENT_CLEAR_UNLOCK)
1645                 clear_bits |= EXTENT_LOCKED;
1646         if (op & EXTENT_CLEAR_DIRTY)
1647                 clear_bits |= EXTENT_DIRTY;
1648 
1649         if (op & EXTENT_CLEAR_DELALLOC)
1650                 clear_bits |= EXTENT_DELALLOC;
1651 
1652         clear_extent_bit(tree, start, end, clear_bits, 1, 0, NULL, GFP_NOFS);
1653         if (!(op & (EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
1654                     EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK |
1655                     EXTENT_SET_PRIVATE2)))
1656                 return 0;
1657 
1658         while (nr_pages > 0) {
1659                 ret = find_get_pages_contig(inode->i_mapping, index,
1660                                      min_t(unsigned long,
1661                                      nr_pages, ARRAY_SIZE(pages)), pages);
1662                 for (i = 0; i < ret; i++) {
1663 
1664                         if (op & EXTENT_SET_PRIVATE2)
1665                                 SetPagePrivate2(pages[i]);
1666 
1667                         if (pages[i] == locked_page) {
1668                                 page_cache_release(pages[i]);
1669                                 continue;
1670                         }
1671                         if (op & EXTENT_CLEAR_DIRTY)
1672                                 clear_page_dirty_for_io(pages[i]);
1673                         if (op & EXTENT_SET_WRITEBACK)
1674                                 set_page_writeback(pages[i]);
1675                         if (op & EXTENT_END_WRITEBACK)
1676                                 end_page_writeback(pages[i]);
1677                         if (op & EXTENT_CLEAR_UNLOCK_PAGE)
1678                                 unlock_page(pages[i]);
1679                         page_cache_release(pages[i]);
1680                 }
1681                 nr_pages -= ret;
1682                 index += ret;
1683                 cond_resched();
1684         }
1685         return 0;
1686 }
1687 
1688 /*
1689  * count the number of bytes in the tree that have a given bit(s)
1690  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
1691  * cached.  The total number found is returned.
1692  */
1693 u64 count_range_bits(struct extent_io_tree *tree,
1694                      u64 *start, u64 search_end, u64 max_bytes,
1695                      unsigned long bits, int contig)
1696 {
1697         struct rb_node *node;
1698         struct extent_state *state;
1699         u64 cur_start = *start;
1700         u64 total_bytes = 0;
1701         u64 last = 0;
1702         int found = 0;
1703 
1704         if (search_end <= cur_start) {
1705                 WARN_ON(1);
1706                 return 0;
1707         }
1708 
1709         spin_lock(&tree->lock);
1710         if (cur_start == 0 && bits == EXTENT_DIRTY) {
1711                 total_bytes = tree->dirty_bytes;
1712                 goto out;
1713         }
1714         /*
1715          * this search will find all the extents that end after
1716          * our range starts.
1717          */
1718         node = tree_search(tree, cur_start);
1719         if (!node)
1720                 goto out;
1721 
1722         while (1) {
1723                 state = rb_entry(node, struct extent_state, rb_node);
1724                 if (state->start > search_end)
1725                         break;
1726                 if (contig && found && state->start > last + 1)
1727                         break;
1728                 if (state->end >= cur_start && (state->state & bits) == bits) {
1729                         total_bytes += min(search_end, state->end) + 1 -
1730                                        max(cur_start, state->start);
1731                         if (total_bytes >= max_bytes)
1732                                 break;
1733                         if (!found) {
1734                                 *start = max(cur_start, state->start);
1735                                 found = 1;
1736                         }
1737                         last = state->end;
1738                 } else if (contig && found) {
1739                         break;
1740                 }
1741                 node = rb_next(node);
1742                 if (!node)
1743                         break;
1744         }
1745 out:
1746         spin_unlock(&tree->lock);
1747         return total_bytes;
1748 }
1749 
1750 /*
1751  * set the private field for a given byte offset in the tree.  If there isn't
1752  * an extent_state there already, this does nothing.
1753  */
1754 int set_state_private(struct extent_io_tree *tree, u64 start, u64 private)
1755 {
1756         struct rb_node *node;
1757         struct extent_state *state;
1758         int ret = 0;
1759 
1760         spin_lock(&tree->lock);
1761         /*
1762          * this search will find all the extents that end after
1763          * our range starts.
1764          */
1765         node = tree_search(tree, start);
1766         if (!node) {
1767                 ret = -ENOENT;
1768                 goto out;
1769         }
1770         state = rb_entry(node, struct extent_state, rb_node);
1771         if (state->start != start) {
1772                 ret = -ENOENT;
1773                 goto out;
1774         }
1775         state->private = private;
1776 out:
1777         spin_unlock(&tree->lock);
1778         return ret;
1779 }
1780 
1781 int get_state_private(struct extent_io_tree *tree, u64 start, u64 *private)
1782 {
1783         struct rb_node *node;
1784         struct extent_state *state;
1785         int ret = 0;
1786 
1787         spin_lock(&tree->lock);
1788         /*
1789          * this search will find all the extents that end after
1790          * our range starts.
1791          */
1792         node = tree_search(tree, start);
1793         if (!node) {
1794                 ret = -ENOENT;
1795                 goto out;
1796         }
1797         state = rb_entry(node, struct extent_state, rb_node);
1798         if (state->start != start) {
1799                 ret = -ENOENT;
1800                 goto out;
1801         }
1802         *private = state->private;
1803 out:
1804         spin_unlock(&tree->lock);
1805         return ret;
1806 }
1807 
1808 /*
1809  * searches a range in the state tree for a given mask.
1810  * If 'filled' == 1, this returns 1 only if every extent in the tree
1811  * has the bits set.  Otherwise, 1 is returned if any bit in the
1812  * range is found set.
1813  */
1814 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1815                    int bits, int filled, struct extent_state *cached)
1816 {
1817         struct extent_state *state = NULL;
1818         struct rb_node *node;
1819         int bitset = 0;
1820 
1821         spin_lock(&tree->lock);
1822         if (cached && cached->tree && cached->start <= start &&
1823             cached->end > start)
1824                 node = &cached->rb_node;
1825         else
1826                 node = tree_search(tree, start);
1827         while (node && start <= end) {
1828                 state = rb_entry(node, struct extent_state, rb_node);
1829 
1830                 if (filled && state->start > start) {
1831                         bitset = 0;
1832                         break;
1833                 }
1834 
1835                 if (state->start > end)
1836                         break;
1837 
1838                 if (state->state & bits) {
1839                         bitset = 1;
1840                         if (!filled)
1841                                 break;
1842                 } else if (filled) {
1843                         bitset = 0;
1844                         break;
1845                 }
1846 
1847                 if (state->end == (u64)-1)
1848                         break;
1849 
1850                 start = state->end + 1;
1851                 if (start > end)
1852                         break;
1853                 node = rb_next(node);
1854                 if (!node) {
1855                         if (filled)
1856                                 bitset = 0;
1857                         break;
1858                 }
1859         }
1860         spin_unlock(&tree->lock);
1861         return bitset;
1862 }
1863 
1864 /*
1865  * helper function to set a given page up to date if all the
1866  * extents in the tree for that page are up to date
1867  */
1868 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1869 {
1870         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
1871         u64 end = start + PAGE_CACHE_SIZE - 1;
1872         if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1873                 SetPageUptodate(page);
1874 }
1875 
1876 /*
1877  * helper function to unlock a page if all the extents in the tree
1878  * for that page are unlocked
1879  */
1880 static void check_page_locked(struct extent_io_tree *tree, struct page *page)
1881 {
1882         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
1883         u64 end = start + PAGE_CACHE_SIZE - 1;
1884         if (!test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL))
1885                 unlock_page(page);
1886 }
1887 
1888 /*
1889  * helper function to end page writeback if all the extents
1890  * in the tree for that page are done with writeback
1891  */
1892 static void check_page_writeback(struct extent_io_tree *tree,
1893                                  struct page *page)
1894 {
1895         end_page_writeback(page);
1896 }
1897 
1898 /*
1899  * When IO fails, either with EIO or csum verification fails, we
1900  * try other mirrors that might have a good copy of the data.  This
1901  * io_failure_record is used to record state as we go through all the
1902  * mirrors.  If another mirror has good data, the page is set up to date
1903  * and things continue.  If a good mirror can't be found, the original
1904  * bio end_io callback is called to indicate things have failed.
1905  */
1906 struct io_failure_record {
1907         struct page *page;
1908         u64 start;
1909         u64 len;
1910         u64 logical;
1911         unsigned long bio_flags;
1912         int this_mirror;
1913         int failed_mirror;
1914         int in_validation;
1915 };
1916 
1917 static int free_io_failure(struct inode *inode, struct io_failure_record *rec,
1918                                 int did_repair)
1919 {
1920         int ret;
1921         int err = 0;
1922         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1923 
1924         set_state_private(failure_tree, rec->start, 0);
1925         ret = clear_extent_bits(failure_tree, rec->start,
1926                                 rec->start + rec->len - 1,
1927                                 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1928         if (ret)
1929                 err = ret;
1930 
1931         if (did_repair) {
1932                 ret = clear_extent_bits(&BTRFS_I(inode)->io_tree, rec->start,
1933                                         rec->start + rec->len - 1,
1934                                         EXTENT_DAMAGED, GFP_NOFS);
1935                 if (ret && !err)
1936                         err = ret;
1937         }
1938 
1939         kfree(rec);
1940         return err;
1941 }
1942 
1943 static void repair_io_failure_callback(struct bio *bio, int err)
1944 {
1945         complete(bio->bi_private);
1946 }
1947 
1948 /*
1949  * this bypasses the standard btrfs submit functions deliberately, as
1950  * the standard behavior is to write all copies in a raid setup. here we only
1951  * want to write the one bad copy. so we do the mapping for ourselves and issue
1952  * submit_bio directly.
1953  * to avoid any synchronization issues, wait for the data after writing, which
1954  * actually prevents the read that triggered the error from finishing.
1955  * currently, there can be no more than two copies of every data bit. thus,
1956  * exactly one rewrite is required.
1957  */
1958 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 start,
1959                         u64 length, u64 logical, struct page *page,
1960                         int mirror_num)
1961 {
1962         struct bio *bio;
1963         struct btrfs_device *dev;
1964         DECLARE_COMPLETION_ONSTACK(compl);
1965         u64 map_length = 0;
1966         u64 sector;
1967         struct btrfs_bio *bbio = NULL;
1968         int ret;
1969 
1970         BUG_ON(!mirror_num);
1971 
1972         bio = bio_alloc(GFP_NOFS, 1);
1973         if (!bio)
1974                 return -EIO;
1975         bio->bi_private = &compl;
1976         bio->bi_end_io = repair_io_failure_callback;
1977         bio->bi_size = 0;
1978         map_length = length;
1979 
1980         ret = btrfs_map_block(fs_info, WRITE, logical,
1981                               &map_length, &bbio, mirror_num);
1982         if (ret) {
1983                 bio_put(bio);
1984                 return -EIO;
1985         }
1986         BUG_ON(mirror_num != bbio->mirror_num);
1987         sector = bbio->stripes[mirror_num-1].physical >> 9;
1988         bio->bi_sector = sector;
1989         dev = bbio->stripes[mirror_num-1].dev;
1990         kfree(bbio);
1991         if (!dev || !dev->bdev || !dev->writeable) {
1992                 bio_put(bio);
1993                 return -EIO;
1994         }
1995         bio->bi_bdev = dev->bdev;
1996         bio_add_page(bio, page, length, start-page_offset(page));
1997         btrfsic_submit_bio(WRITE_SYNC, bio);
1998         wait_for_completion(&compl);
1999 
2000         if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2001                 /* try to remap that extent elsewhere? */
2002                 bio_put(bio);
2003                 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2004                 return -EIO;
2005         }
2006 
2007         printk_ratelimited_in_rcu(KERN_INFO "btrfs read error corrected: ino %lu off %llu "
2008                       "(dev %s sector %llu)\n", page->mapping->host->i_ino,
2009                       start, rcu_str_deref(dev->name), sector);
2010 
2011         bio_put(bio);
2012         return 0;
2013 }
2014 
2015 int repair_eb_io_failure(struct btrfs_root *root, struct extent_buffer *eb,
2016                          int mirror_num)
2017 {
2018         u64 start = eb->start;
2019         unsigned long i, num_pages = num_extent_pages(eb->start, eb->len);
2020         int ret = 0;
2021 
2022         for (i = 0; i < num_pages; i++) {
2023                 struct page *p = extent_buffer_page(eb, i);
2024                 ret = repair_io_failure(root->fs_info, start, PAGE_CACHE_SIZE,
2025                                         start, p, mirror_num);
2026                 if (ret)
2027                         break;
2028                 start += PAGE_CACHE_SIZE;
2029         }
2030 
2031         return ret;
2032 }
2033 
2034 /*
2035  * each time an IO finishes, we do a fast check in the IO failure tree
2036  * to see if we need to process or clean up an io_failure_record
2037  */
2038 static int clean_io_failure(u64 start, struct page *page)
2039 {
2040         u64 private;
2041         u64 private_failure;
2042         struct io_failure_record *failrec;
2043         struct btrfs_fs_info *fs_info;
2044         struct extent_state *state;
2045         int num_copies;
2046         int did_repair = 0;
2047         int ret;
2048         struct inode *inode = page->mapping->host;
2049 
2050         private = 0;
2051         ret = count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
2052                                 (u64)-1, 1, EXTENT_DIRTY, 0);
2053         if (!ret)
2054                 return 0;
2055 
2056         ret = get_state_private(&BTRFS_I(inode)->io_failure_tree, start,
2057                                 &private_failure);
2058         if (ret)
2059                 return 0;
2060 
2061         failrec = (struct io_failure_record *)(unsigned long) private_failure;
2062         BUG_ON(!failrec->this_mirror);
2063 
2064         if (failrec->in_validation) {
2065                 /* there was no real error, just free the record */
2066                 pr_debug("clean_io_failure: freeing dummy error at %llu\n",
2067                          failrec->start);
2068                 did_repair = 1;
2069                 goto out;
2070         }
2071 
2072         spin_lock(&BTRFS_I(inode)->io_tree.lock);
2073         state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
2074                                             failrec->start,
2075                                             EXTENT_LOCKED);
2076         spin_unlock(&BTRFS_I(inode)->io_tree.lock);
2077 
2078         if (state && state->start == failrec->start) {
2079                 fs_info = BTRFS_I(inode)->root->fs_info;
2080                 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2081                                               failrec->len);
2082                 if (num_copies > 1)  {
2083                         ret = repair_io_failure(fs_info, start, failrec->len,
2084                                                 failrec->logical, page,
2085                                                 failrec->failed_mirror);
2086                         did_repair = !ret;
2087                 }
2088         }
2089 
2090 out:
2091         if (!ret)
2092                 ret = free_io_failure(inode, failrec, did_repair);
2093 
2094         return ret;
2095 }
2096 
2097 /*
2098  * this is a generic handler for readpage errors (default
2099  * readpage_io_failed_hook). if other copies exist, read those and write back
2100  * good data to the failed position. does not investigate in remapping the
2101  * failed extent elsewhere, hoping the device will be smart enough to do this as
2102  * needed
2103  */
2104 
2105 static int bio_readpage_error(struct bio *failed_bio, struct page *page,
2106                                 u64 start, u64 end, int failed_mirror,
2107                                 struct extent_state *state)
2108 {
2109         struct io_failure_record *failrec = NULL;
2110         u64 private;
2111         struct extent_map *em;
2112         struct inode *inode = page->mapping->host;
2113         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2114         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2115         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2116         struct bio *bio;
2117         int num_copies;
2118         int ret;
2119         int read_mode;
2120         u64 logical;
2121 
2122         BUG_ON(failed_bio->bi_rw & REQ_WRITE);
2123 
2124         ret = get_state_private(failure_tree, start, &private);
2125         if (ret) {
2126                 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2127                 if (!failrec)
2128                         return -ENOMEM;
2129                 failrec->start = start;
2130                 failrec->len = end - start + 1;
2131                 failrec->this_mirror = 0;
2132                 failrec->bio_flags = 0;
2133                 failrec->in_validation = 0;
2134 
2135                 read_lock(&em_tree->lock);
2136                 em = lookup_extent_mapping(em_tree, start, failrec->len);
2137                 if (!em) {
2138                         read_unlock(&em_tree->lock);
2139                         kfree(failrec);
2140                         return -EIO;
2141                 }
2142 
2143                 if (em->start > start || em->start + em->len < start) {
2144                         free_extent_map(em);
2145                         em = NULL;
2146                 }
2147                 read_unlock(&em_tree->lock);
2148 
2149                 if (!em) {
2150                         kfree(failrec);
2151                         return -EIO;
2152                 }
2153                 logical = start - em->start;
2154                 logical = em->block_start + logical;
2155                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2156                         logical = em->block_start;
2157                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2158                         extent_set_compress_type(&failrec->bio_flags,
2159                                                  em->compress_type);
2160                 }
2161                 pr_debug("bio_readpage_error: (new) logical=%llu, start=%llu, "
2162                          "len=%llu\n", logical, start, failrec->len);
2163                 failrec->logical = logical;
2164                 free_extent_map(em);
2165 
2166                 /* set the bits in the private failure tree */
2167                 ret = set_extent_bits(failure_tree, start, end,
2168                                         EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
2169                 if (ret >= 0)
2170                         ret = set_state_private(failure_tree, start,
2171                                                 (u64)(unsigned long)failrec);
2172                 /* set the bits in the inode's tree */
2173                 if (ret >= 0)
2174                         ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED,
2175                                                 GFP_NOFS);
2176                 if (ret < 0) {
2177                         kfree(failrec);
2178                         return ret;
2179                 }
2180         } else {
2181                 failrec = (struct io_failure_record *)(unsigned long)private;
2182                 pr_debug("bio_readpage_error: (found) logical=%llu, "
2183                          "start=%llu, len=%llu, validation=%d\n",
2184                          failrec->logical, failrec->start, failrec->len,
2185                          failrec->in_validation);
2186                 /*
2187                  * when data can be on disk more than twice, add to failrec here
2188                  * (e.g. with a list for failed_mirror) to make
2189                  * clean_io_failure() clean all those errors at once.
2190                  */
2191         }
2192         num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
2193                                       failrec->logical, failrec->len);
2194         if (num_copies == 1) {
2195                 /*
2196                  * we only have a single copy of the data, so don't bother with
2197                  * all the retry and error correction code that follows. no
2198                  * matter what the error is, it is very likely to persist.
2199                  */
2200                 pr_debug("bio_readpage_error: cannot repair, num_copies == 1. "
2201                          "state=%p, num_copies=%d, next_mirror %d, "
2202                          "failed_mirror %d\n", state, num_copies,
2203                          failrec->this_mirror, failed_mirror);
2204                 free_io_failure(inode, failrec, 0);
2205                 return -EIO;
2206         }
2207 
2208         if (!state) {
2209                 spin_lock(&tree->lock);
2210                 state = find_first_extent_bit_state(tree, failrec->start,
2211                                                     EXTENT_LOCKED);
2212                 if (state && state->start != failrec->start)
2213                         state = NULL;
2214                 spin_unlock(&tree->lock);
2215         }
2216 
2217         /*
2218          * there are two premises:
2219          *      a) deliver good data to the caller
2220          *      b) correct the bad sectors on disk
2221          */
2222         if (failed_bio->bi_vcnt > 1) {
2223                 /*
2224                  * to fulfill b), we need to know the exact failing sectors, as
2225                  * we don't want to rewrite any more than the failed ones. thus,
2226                  * we need separate read requests for the failed bio
2227                  *
2228                  * if the following BUG_ON triggers, our validation request got
2229                  * merged. we need separate requests for our algorithm to work.
2230                  */
2231                 BUG_ON(failrec->in_validation);
2232                 failrec->in_validation = 1;
2233                 failrec->this_mirror = failed_mirror;
2234                 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
2235         } else {
2236                 /*
2237                  * we're ready to fulfill a) and b) alongside. get a good copy
2238                  * of the failed sector and if we succeed, we have setup
2239                  * everything for repair_io_failure to do the rest for us.
2240                  */
2241                 if (failrec->in_validation) {
2242                         BUG_ON(failrec->this_mirror != failed_mirror);
2243                         failrec->in_validation = 0;
2244                         failrec->this_mirror = 0;
2245                 }
2246                 failrec->failed_mirror = failed_mirror;
2247                 failrec->this_mirror++;
2248                 if (failrec->this_mirror == failed_mirror)
2249                         failrec->this_mirror++;
2250                 read_mode = READ_SYNC;
2251         }
2252 
2253         if (!state || failrec->this_mirror > num_copies) {
2254                 pr_debug("bio_readpage_error: (fail) state=%p, num_copies=%d, "
2255                          "next_mirror %d, failed_mirror %d\n", state,
2256                          num_copies, failrec->this_mirror, failed_mirror);
2257                 free_io_failure(inode, failrec, 0);
2258                 return -EIO;
2259         }
2260 
2261         bio = bio_alloc(GFP_NOFS, 1);
2262         if (!bio) {
2263                 free_io_failure(inode, failrec, 0);
2264                 return -EIO;
2265         }
2266         bio->bi_private = state;
2267         bio->bi_end_io = failed_bio->bi_end_io;
2268         bio->bi_sector = failrec->logical >> 9;
2269         bio->bi_bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
2270         bio->bi_size = 0;
2271 
2272         bio_add_page(bio, page, failrec->len, start - page_offset(page));
2273 
2274         pr_debug("bio_readpage_error: submitting new read[%#x] to "
2275                  "this_mirror=%d, num_copies=%d, in_validation=%d\n", read_mode,
2276                  failrec->this_mirror, num_copies, failrec->in_validation);
2277 
2278         ret = tree->ops->submit_bio_hook(inode, read_mode, bio,
2279                                          failrec->this_mirror,
2280                                          failrec->bio_flags, 0);
2281         return ret;
2282 }
2283 
2284 /* lots and lots of room for performance fixes in the end_bio funcs */
2285 
2286 int end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2287 {
2288         int uptodate = (err == 0);
2289         struct extent_io_tree *tree;
2290         int ret;
2291 
2292         tree = &BTRFS_I(page->mapping->host)->io_tree;
2293 
2294         if (tree->ops && tree->ops->writepage_end_io_hook) {
2295                 ret = tree->ops->writepage_end_io_hook(page, start,
2296                                                end, NULL, uptodate);
2297                 if (ret)
2298                         uptodate = 0;
2299         }
2300 
2301         if (!uptodate) {
2302                 ClearPageUptodate(page);
2303                 SetPageError(page);
2304         }
2305         return 0;
2306 }
2307 
2308 /*
2309  * after a writepage IO is done, we need to:
2310  * clear the uptodate bits on error
2311  * clear the writeback bits in the extent tree for this IO
2312  * end_page_writeback if the page has no more pending IO
2313  *
2314  * Scheduling is not allowed, so the extent state tree is expected
2315  * to have one and only one object corresponding to this IO.
2316  */
2317 static void end_bio_extent_writepage(struct bio *bio, int err)
2318 {
2319         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
2320         struct extent_io_tree *tree;
2321         u64 start;
2322         u64 end;
2323         int whole_page;
2324 
2325         do {
2326                 struct page *page = bvec->bv_page;
2327                 tree = &BTRFS_I(page->mapping->host)->io_tree;
2328 
2329                 start = ((u64)page->index << PAGE_CACHE_SHIFT) +
2330                          bvec->bv_offset;
2331                 end = start + bvec->bv_len - 1;
2332 
2333                 if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
2334                         whole_page = 1;
2335                 else
2336                         whole_page = 0;
2337 
2338                 if (--bvec >= bio->bi_io_vec)
2339                         prefetchw(&bvec->bv_page->flags);
2340 
2341                 if (end_extent_writepage(page, err, start, end))
2342                         continue;
2343 
2344                 if (whole_page)
2345                         end_page_writeback(page);
2346                 else
2347                         check_page_writeback(tree, page);
2348         } while (bvec >= bio->bi_io_vec);
2349 
2350         bio_put(bio);
2351 }
2352 
2353 /*
2354  * after a readpage IO is done, we need to:
2355  * clear the uptodate bits on error
2356  * set the uptodate bits if things worked
2357  * set the page up to date if all extents in the tree are uptodate
2358  * clear the lock bit in the extent tree
2359  * unlock the page if there are no other extents locked for it
2360  *
2361  * Scheduling is not allowed, so the extent state tree is expected
2362  * to have one and only one object corresponding to this IO.
2363  */
2364 static void end_bio_extent_readpage(struct bio *bio, int err)
2365 {
2366         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
2367         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
2368         struct bio_vec *bvec = bio->bi_io_vec;
2369         struct extent_io_tree *tree;
2370         u64 start;
2371         u64 end;
2372         int whole_page;
2373         int mirror;
2374         int ret;
2375 
2376         if (err)
2377                 uptodate = 0;
2378 
2379         do {
2380                 struct page *page = bvec->bv_page;
2381                 struct extent_state *cached = NULL;
2382                 struct extent_state *state;
2383 
2384                 pr_debug("end_bio_extent_readpage: bi_sector=%llu, err=%d, "
2385                          "mirror=%ld\n", (u64)bio->bi_sector, err,
2386                          (long int)bio->bi_bdev);
2387                 tree = &BTRFS_I(page->mapping->host)->io_tree;
2388 
2389                 start = ((u64)page->index << PAGE_CACHE_SHIFT) +
2390                         bvec->bv_offset;
2391                 end = start + bvec->bv_len - 1;
2392 
2393                 if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
2394                         whole_page = 1;
2395                 else
2396                         whole_page = 0;
2397 
2398                 if (++bvec <= bvec_end)
2399                         prefetchw(&bvec->bv_page->flags);
2400 
2401                 spin_lock(&tree->lock);
2402                 state = find_first_extent_bit_state(tree, start, EXTENT_LOCKED);
2403                 if (state && state->start == start) {
2404                         /*
2405                          * take a reference on the state, unlock will drop
2406                          * the ref
2407                          */
2408                         cache_state(state, &cached);
2409                 }
2410                 spin_unlock(&tree->lock);
2411 
2412                 mirror = (int)(unsigned long)bio->bi_bdev;
2413                 if (uptodate && tree->ops && tree->ops->readpage_end_io_hook) {
2414                         ret = tree->ops->readpage_end_io_hook(page, start, end,
2415                                                               state, mirror);
2416                         if (ret)
2417                                 uptodate = 0;
2418                         else
2419                                 clean_io_failure(start, page);
2420                 }
2421 
2422                 if (!uptodate && tree->ops && tree->ops->readpage_io_failed_hook) {
2423                         ret = tree->ops->readpage_io_failed_hook(page, mirror);
2424                         if (!ret && !err &&
2425                             test_bit(BIO_UPTODATE, &bio->bi_flags))
2426                                 uptodate = 1;
2427                 } else if (!uptodate) {
2428                         /*
2429                          * The generic bio_readpage_error handles errors the
2430                          * following way: If possible, new read requests are
2431                          * created and submitted and will end up in
2432                          * end_bio_extent_readpage as well (if we're lucky, not
2433                          * in the !uptodate case). In that case it returns 0 and
2434                          * we just go on with the next page in our bio. If it
2435                          * can't handle the error it will return -EIO and we
2436                          * remain responsible for that page.
2437                          */
2438                         ret = bio_readpage_error(bio, page, start, end, mirror, NULL);
2439                         if (ret == 0) {
2440                                 uptodate =
2441                                         test_bit(BIO_UPTODATE, &bio->bi_flags);
2442                                 if (err)
2443                                         uptodate = 0;
2444                                 uncache_state(&cached);
2445                                 continue;
2446                         }
2447                 }
2448 
2449                 if (uptodate && tree->track_uptodate) {
2450                         set_extent_uptodate(tree, start, end, &cached,
2451                                             GFP_ATOMIC);
2452                 }
2453                 unlock_extent_cached(tree, start, end, &cached, GFP_ATOMIC);
2454 
2455                 if (whole_page) {
2456                         if (uptodate) {
2457                                 SetPageUptodate(page);
2458                         } else {
2459                                 ClearPageUptodate(page);
2460                                 SetPageError(page);
2461                         }
2462                         unlock_page(page);
2463                 } else {
2464                         if (uptodate) {
2465                                 check_page_uptodate(tree, page);
2466                         } else {
2467                                 ClearPageUptodate(page);
2468                                 SetPageError(page);
2469                         }
2470                         check_page_locked(tree, page);
2471                 }
2472         } while (bvec <= bvec_end);
2473 
2474         bio_put(bio);
2475 }
2476 
2477 struct bio *
2478 btrfs_bio_alloc(struct block_device *bdev, u64 first_sector, int nr_vecs,
2479                 gfp_t gfp_flags)
2480 {
2481         struct bio *bio;
2482 
2483         bio = bio_alloc(gfp_flags, nr_vecs);
2484 
2485         if (bio == NULL && (current->flags & PF_MEMALLOC)) {
2486                 while (!bio && (nr_vecs /= 2))
2487                         bio = bio_alloc(gfp_flags, nr_vecs);
2488         }
2489 
2490         if (bio) {
2491                 bio->bi_size = 0;
2492                 bio->bi_bdev = bdev;
2493                 bio->bi_sector = first_sector;
2494         }
2495         return bio;
2496 }
2497 
2498 static int __must_check submit_one_bio(int rw, struct bio *bio,
2499                                        int mirror_num, unsigned long bio_flags)
2500 {
2501         int ret = 0;
2502         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
2503         struct page *page = bvec->bv_page;
2504         struct extent_io_tree *tree = bio->bi_private;
2505         u64 start;
2506 
2507         start = ((u64)page->index << PAGE_CACHE_SHIFT) + bvec->bv_offset;
2508 
2509         bio->bi_private = NULL;
2510 
2511         bio_get(bio);
2512 
2513         if (tree->ops && tree->ops->submit_bio_hook)
2514                 ret = tree->ops->submit_bio_hook(page->mapping->host, rw, bio,
2515                                            mirror_num, bio_flags, start);
2516         else
2517                 btrfsic_submit_bio(rw, bio);
2518 
2519         if (bio_flagged(bio, BIO_EOPNOTSUPP))
2520                 ret = -EOPNOTSUPP;
2521         bio_put(bio);
2522         return ret;
2523 }
2524 
2525 static int merge_bio(struct extent_io_tree *tree, struct page *page,
2526                      unsigned long offset, size_t size, struct bio *bio,
2527                      unsigned long bio_flags)
2528 {
2529         int ret = 0;
2530         if (tree->ops && tree->ops->merge_bio_hook)
2531                 ret = tree->ops->merge_bio_hook(page, offset, size, bio,
2532                                                 bio_flags);
2533         BUG_ON(ret < 0);
2534         return ret;
2535 
2536 }
2537 
2538 static int submit_extent_page(int rw, struct extent_io_tree *tree,
2539                               struct page *page, sector_t sector,
2540                               size_t size, unsigned long offset,
2541                               struct block_device *bdev,
2542                               struct bio **bio_ret,
2543                               unsigned long max_pages,
2544                               bio_end_io_t end_io_func,
2545                               int mirror_num,
2546                               unsigned long prev_bio_flags,
2547                               unsigned long bio_flags)
2548 {
2549         int ret = 0;
2550         struct bio *bio;
2551         int nr;
2552         int contig = 0;
2553         int this_compressed = bio_flags & EXTENT_BIO_COMPRESSED;
2554         int old_compressed = prev_bio_flags & EXTENT_BIO_COMPRESSED;
2555         size_t page_size = min_t(size_t, size, PAGE_CACHE_SIZE);
2556 
2557         if (bio_ret && *bio_ret) {
2558                 bio = *bio_ret;
2559                 if (old_compressed)
2560                         contig = bio->bi_sector == sector;
2561                 else
2562                         contig = bio->bi_sector + (bio->bi_size >> 9) ==
2563                                 sector;
2564 
2565                 if (prev_bio_flags != bio_flags || !contig ||
2566                     merge_bio(tree, page, offset, page_size, bio, bio_flags) ||
2567                     bio_add_page(bio, page, page_size, offset) < page_size) {
2568                         ret = submit_one_bio(rw, bio, mirror_num,
2569                                              prev_bio_flags);
2570                         if (ret < 0)
2571                                 return ret;
2572                         bio = NULL;
2573                 } else {
2574                         return 0;
2575                 }
2576         }
2577         if (this_compressed)
2578                 nr = BIO_MAX_PAGES;
2579         else
2580                 nr = bio_get_nr_vecs(bdev);
2581 
2582         bio = btrfs_bio_alloc(bdev, sector, nr, GFP_NOFS | __GFP_HIGH);
2583         if (!bio)
2584                 return -ENOMEM;
2585 
2586         bio_add_page(bio, page, page_size, offset);
2587         bio->bi_end_io = end_io_func;
2588         bio->bi_private = tree;
2589 
2590         if (bio_ret)
2591                 *bio_ret = bio;
2592         else
2593                 ret = submit_one_bio(rw, bio, mirror_num, bio_flags);
2594 
2595         return ret;
2596 }
2597 
2598 void attach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
2599 {
2600         if (!PagePrivate(page)) {
2601                 SetPagePrivate(page);
2602                 page_cache_get(page);
2603                 set_page_private(page, (unsigned long)eb);
2604         } else {
2605                 WARN_ON(page->private != (unsigned long)eb);
2606         }
2607 }
2608 
2609 void set_page_extent_mapped(struct page *page)
2610 {
2611         if (!PagePrivate(page)) {
2612                 SetPagePrivate(page);
2613                 page_cache_get(page);
2614                 set_page_private(page, EXTENT_PAGE_PRIVATE);
2615         }
2616 }
2617 
2618 /*
2619  * basic readpage implementation.  Locked extent state structs are inserted
2620  * into the tree that are removed when the IO is done (by the end_io
2621  * handlers)
2622  * XXX JDM: This needs looking at to ensure proper page locking
2623  */
2624 static int __extent_read_full_page(struct extent_io_tree *tree,
2625                                    struct page *page,
2626                                    get_extent_t *get_extent,
2627                                    struct bio **bio, int mirror_num,
2628                                    unsigned long *bio_flags)
2629 {
2630         struct inode *inode = page->mapping->host;
2631         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
2632         u64 page_end = start + PAGE_CACHE_SIZE - 1;
2633         u64 end;
2634         u64 cur = start;
2635         u64 extent_offset;
2636         u64 last_byte = i_size_read(inode);
2637         u64 block_start;
2638         u64 cur_end;
2639         sector_t sector;
2640         struct extent_map *em;
2641         struct block_device *bdev;
2642         struct btrfs_ordered_extent *ordered;
2643         int ret;
2644         int nr = 0;
2645         size_t pg_offset = 0;
2646         size_t iosize;
2647         size_t disk_io_size;
2648         size_t blocksize = inode->i_sb->s_blocksize;
2649         unsigned long this_bio_flag = 0;
2650 
2651         set_page_extent_mapped(page);
2652 
2653         if (!PageUptodate(page)) {
2654                 if (cleancache_get_page(page) == 0) {
2655                         BUG_ON(blocksize != PAGE_SIZE);
2656                         goto out;
2657                 }
2658         }
2659 
2660         end = page_end;
2661         while (1) {
2662                 lock_extent(tree, start, end);
2663                 ordered = btrfs_lookup_ordered_extent(inode, start);
2664                 if (!ordered)
2665                         break;
2666                 unlock_extent(tree, start, end);
2667                 btrfs_start_ordered_extent(inode, ordered, 1);
2668                 btrfs_put_ordered_extent(ordered);
2669         }
2670 
2671         if (page->index == last_byte >> PAGE_CACHE_SHIFT) {
2672                 char *userpage;
2673                 size_t zero_offset = last_byte & (PAGE_CACHE_SIZE - 1);
2674 
2675                 if (zero_offset) {
2676                         iosize = PAGE_CACHE_SIZE - zero_offset;
2677                         userpage = kmap_atomic(page);
2678                         memset(userpage + zero_offset, 0, iosize);
2679                         flush_dcache_page(page);
2680                         kunmap_atomic(userpage);
2681                 }
2682         }
2683         while (cur <= end) {
2684                 if (cur >= last_byte) {
2685                         char *userpage;
2686                         struct extent_state *cached = NULL;
2687 
2688                         iosize = PAGE_CACHE_SIZE - pg_offset;
2689                         userpage = kmap_atomic(page);
2690                         memset(userpage + pg_offset, 0, iosize);
2691                         flush_dcache_page(page);
2692                         kunmap_atomic(userpage);
2693                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2694                                             &cached, GFP_NOFS);
2695                         unlock_extent_cached(tree, cur, cur + iosize - 1,
2696                                              &cached, GFP_NOFS);
2697                         break;
2698                 }
2699                 em = get_extent(inode, page, pg_offset, cur,
2700                                 end - cur + 1, 0);
2701                 if (IS_ERR_OR_NULL(em)) {
2702                         SetPageError(page);
2703                         unlock_extent(tree, cur, end);
2704                         break;
2705                 }
2706                 extent_offset = cur - em->start;
2707                 BUG_ON(extent_map_end(em) <= cur);
2708                 BUG_ON(end < cur);
2709 
2710                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2711                         this_bio_flag = EXTENT_BIO_COMPRESSED;
2712                         extent_set_compress_type(&this_bio_flag,
2713                                                  em->compress_type);
2714                 }
2715 
2716                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
2717                 cur_end = min(extent_map_end(em) - 1, end);
2718                 iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
2719                 if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2720                         disk_io_size = em->block_len;
2721                         sector = em->block_start >> 9;
2722                 } else {
2723                         sector = (em->block_start + extent_offset) >> 9;
2724                         disk_io_size = iosize;
2725                 }
2726                 bdev = em->bdev;
2727                 block_start = em->block_start;
2728                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
2729                         block_start = EXTENT_MAP_HOLE;
2730                 free_extent_map(em);
2731                 em = NULL;
2732 
2733                 /* we've found a hole, just zero and go on */
2734                 if (block_start == EXTENT_MAP_HOLE) {
2735                         char *userpage;
2736                         struct extent_state *cached = NULL;
2737 
2738                         userpage = kmap_atomic(page);
2739                         memset(userpage + pg_offset, 0, iosize);
2740                         flush_dcache_page(page);
2741                         kunmap_atomic(userpage);
2742 
2743                         set_extent_uptodate(tree, cur, cur + iosize - 1,
2744                                             &cached, GFP_NOFS);
2745                         unlock_extent_cached(tree, cur, cur + iosize - 1,
2746                                              &cached, GFP_NOFS);
2747                         cur = cur + iosize;
2748                         pg_offset += iosize;
2749                         continue;
2750                 }
2751                 /* the get_extent function already copied into the page */
2752                 if (test_range_bit(tree, cur, cur_end,
2753                                    EXTENT_UPTODATE, 1, NULL)) {
2754                         check_page_uptodate(tree, page);
2755                         unlock_extent(tree, cur, cur + iosize - 1);
2756                         cur = cur + iosize;
2757                         pg_offset += iosize;
2758                         continue;
2759                 }
2760                 /* we have an inline extent but it didn't get marked up
2761                  * to date.  Error out
2762                  */
2763                 if (block_start == EXTENT_MAP_INLINE) {
2764                         SetPageError(page);
2765                         unlock_extent(tree, cur, cur + iosize - 1);
2766                         cur = cur + iosize;
2767                         pg_offset += iosize;
2768                         continue;
2769                 }
2770 
2771                 ret = 0;
2772                 if (tree->ops && tree->ops->readpage_io_hook) {
2773                         ret = tree->ops->readpage_io_hook(page, cur,
2774                                                           cur + iosize - 1);
2775                 }
2776                 if (!ret) {
2777                         unsigned long pnr = (last_byte >> PAGE_CACHE_SHIFT) + 1;
2778                         pnr -= page->index;
2779                         ret = submit_extent_page(READ, tree, page,
2780                                          sector, disk_io_size, pg_offset,
2781                                          bdev, bio, pnr,
2782                                          end_bio_extent_readpage, mirror_num,
2783                                          *bio_flags,
2784                                          this_bio_flag);
2785                         if (!ret) {
2786                                 nr++;
2787                                 *bio_flags = this_bio_flag;
2788                         }
2789                 }
2790                 if (ret) {
2791                         SetPageError(page);
2792                         unlock_extent(tree, cur, cur + iosize - 1);
2793                 }
2794                 cur = cur + iosize;
2795                 pg_offset += iosize;
2796         }
2797 out:
2798         if (!nr) {
2799                 if (!PageError(page))
2800                         SetPageUptodate(page);
2801                 unlock_page(page);
2802         }
2803         return 0;
2804 }
2805 
2806 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
2807                             get_extent_t *get_extent, int mirror_num)
2808 {
2809         struct bio *bio = NULL;
2810         unsigned long bio_flags = 0;
2811         int ret;
2812 
2813         ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
2814                                       &bio_flags);
2815         if (bio)
2816                 ret = submit_one_bio(READ, bio, mirror_num, bio_flags);
2817         return ret;
2818 }
2819 
2820 static noinline void update_nr_written(struct page *page,
2821                                       struct writeback_control *wbc,
2822                                       unsigned long nr_written)
2823 {
2824         wbc->nr_to_write -= nr_written;
2825         if (wbc->range_cyclic || (wbc->nr_to_write > 0 &&
2826             wbc->range_start == 0 && wbc->range_end == LLONG_MAX))
2827                 page->mapping->writeback_index = page->index + nr_written;
2828 }
2829 
2830 /*
2831  * the writepage semantics are similar to regular writepage.  extent
2832  * records are inserted to lock ranges in the tree, and as dirty areas
2833  * are found, they are marked writeback.  Then the lock bits are removed
2834  * and the end_io handler clears the writeback ranges
2835  */
2836 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2837                               void *data)
2838 {
2839         struct inode *inode = page->mapping->host;
2840         struct extent_page_data *epd = data;
2841         struct extent_io_tree *tree = epd->tree;
2842         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
2843         u64 delalloc_start;
2844         u64 page_end = start + PAGE_CACHE_SIZE - 1;
2845         u64 end;
2846         u64 cur = start;
2847         u64 extent_offset;
2848         u64 last_byte = i_size_read(inode);
2849         u64 block_start;
2850         u64 iosize;
2851         sector_t sector;
2852         struct extent_state *cached_state = NULL;
2853         struct extent_map *em;
2854         struct block_device *bdev;
2855         int ret;
2856         int nr = 0;
2857         size_t pg_offset = 0;
2858         size_t blocksize;
2859         loff_t i_size = i_size_read(inode);
2860         unsigned long end_index = i_size >> PAGE_CACHE_SHIFT;
2861         u64 nr_delalloc;
2862         u64 delalloc_end;
2863         int page_started;
2864         int compressed;
2865         int write_flags;
2866         unsigned long nr_written = 0;
2867         bool fill_delalloc = true;
2868 
2869         if (wbc->sync_mode == WB_SYNC_ALL)
2870                 write_flags = WRITE_SYNC;
2871         else
2872                 write_flags = WRITE;
2873 
2874         trace___extent_writepage(page, inode, wbc);
2875 
2876         WARN_ON(!PageLocked(page));
2877 
2878         ClearPageError(page);
2879 
2880         pg_offset = i_size & (PAGE_CACHE_SIZE - 1);
2881         if (page->index > end_index ||
2882            (page->index == end_index && !pg_offset)) {
2883                 page->mapping->a_ops->invalidatepage(page, 0);
2884                 unlock_page(page);
2885                 return 0;
2886         }
2887 
2888         if (page->index == end_index) {
2889                 char *userpage;
2890 
2891                 userpage = kmap_atomic(page);
2892                 memset(userpage + pg_offset, 0,
2893                        PAGE_CACHE_SIZE - pg_offset);
2894                 kunmap_atomic(userpage);
2895                 flush_dcache_page(page);
2896         }
2897         pg_offset = 0;
2898 
2899         set_page_extent_mapped(page);
2900 
2901         if (!tree->ops || !tree->ops->fill_delalloc)
2902                 fill_delalloc = false;
2903 
2904         delalloc_start = start;
2905         delalloc_end = 0;
2906         page_started = 0;
2907         if (!epd->extent_locked && fill_delalloc) {
2908                 u64 delalloc_to_write = 0;
2909                 /*
2910                  * make sure the wbc mapping index is at least updated
2911                  * to this page.
2912                  */
2913                 update_nr_written(page, wbc, 0);
2914 
2915                 while (delalloc_end < page_end) {
2916                         nr_delalloc = find_lock_delalloc_range(inode, tree,
2917                                                        page,
2918                                                        &delalloc_start,
2919                                                        &delalloc_end,
2920                                                        128 * 1024 * 1024);
2921                         if (nr_delalloc == 0) {
2922                                 delalloc_start = delalloc_end + 1;
2923                                 continue;
2924                         }
2925                         ret = tree->ops->fill_delalloc(inode, page,
2926                                                        delalloc_start,
2927                                                        delalloc_end,
2928                                                        &page_started,
2929                                                        &nr_written);
2930                         /* File system has been set read-only */
2931                         if (ret) {
2932                                 SetPageError(page);
2933                                 goto done;
2934                         }
2935                         /*
2936                          * delalloc_end is already one less than the total
2937                          * length, so we don't subtract one from
2938                          * PAGE_CACHE_SIZE
2939                          */
2940                         delalloc_to_write += (delalloc_end - delalloc_start +
2941                                               PAGE_CACHE_SIZE) >>
2942                                               PAGE_CACHE_SHIFT;
2943                         delalloc_start = delalloc_end + 1;
2944                 }
2945                 if (wbc->nr_to_write < delalloc_to_write) {
2946                         int thresh = 8192;
2947 
2948                         if (delalloc_to_write < thresh * 2)
2949                                 thresh = delalloc_to_write;
2950                         wbc->nr_to_write = min_t(u64, delalloc_to_write,
2951                                                  thresh);
2952                 }
2953 
2954                 /* did the fill delalloc function already unlock and start
2955                  * the IO?
2956                  */
2957                 if (page_started) {
2958                         ret = 0;
2959                         /*
2960                          * we've unlocked the page, so we can't update
2961                          * the mapping's writeback index, just update
2962                          * nr_to_write.
2963                          */
2964                         wbc->nr_to_write -= nr_written;
2965                         goto done_unlocked;
2966                 }
2967         }
2968         if (tree->ops && tree->ops->writepage_start_hook) {
2969                 ret = tree->ops->writepage_start_hook(page, start,
2970                                                       page_end);
2971                 if (ret) {
2972                         /* Fixup worker will requeue */
2973                         if (ret == -EBUSY)
2974                                 wbc->pages_skipped++;
2975                         else
2976                                 redirty_page_for_writepage(wbc, page);
2977                         update_nr_written(page, wbc, nr_written);
2978                         unlock_page(page);
2979                         ret = 0;
2980                         goto done_unlocked;
2981                 }
2982         }
2983 
2984         /*
2985          * we don't want to touch the inode after unlocking the page,
2986          * so we update the mapping writeback index now
2987          */
2988         update_nr_written(page, wbc, nr_written + 1);
2989 
2990         end = page_end;
2991         if (last_byte <= start) {
2992                 if (tree->ops && tree->ops->writepage_end_io_hook)
2993                         tree->ops->writepage_end_io_hook(page, start,
2994                                                          page_end, NULL, 1);
2995                 goto done;
2996         }
2997 
2998         blocksize = inode->i_sb->s_blocksize;
2999 
3000         while (cur <= end) {
3001                 if (cur >= last_byte) {
3002                         if (tree->ops && tree->ops->writepage_end_io_hook)
3003                                 tree->ops->writepage_end_io_hook(page, cur,
3004                                                          page_end, NULL, 1);
3005                         break;
3006                 }
3007                 em = epd->get_extent(inode, page, pg_offset, cur,
3008                                      end - cur + 1, 1);
3009                 if (IS_ERR_OR_NULL(em)) {
3010                         SetPageError(page);
3011                         break;
3012                 }
3013 
3014                 extent_offset = cur - em->start;
3015                 BUG_ON(extent_map_end(em) <= cur);
3016                 BUG_ON(end < cur);
3017                 iosize = min(extent_map_end(em) - cur, end - cur + 1);
3018                 iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
3019                 sector = (em->block_start + extent_offset) >> 9;
3020                 bdev = em->bdev;
3021                 block_start = em->block_start;
3022                 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3023                 free_extent_map(em);
3024                 em = NULL;
3025 
3026                 /*
3027                  * compressed and inline extents are written through other
3028                  * paths in the FS
3029                  */
3030                 if (compressed || block_start == EXTENT_MAP_HOLE ||
3031                     block_start == EXTENT_MAP_INLINE) {
3032                         /*
3033                          * end_io notification does not happen here for
3034                          * compressed extents
3035                          */
3036                         if (!compressed && tree->ops &&
3037                             tree->ops->writepage_end_io_hook)
3038                                 tree->ops->writepage_end_io_hook(page, cur,
3039                                                          cur + iosize - 1,
3040                                                          NULL, 1);
3041                         else if (compressed) {
3042                                 /* we don't want to end_page_writeback on
3043                                  * a compressed extent.  this happens
3044                                  * elsewhere
3045                                  */
3046                                 nr++;
3047                         }
3048 
3049                         cur += iosize;
3050                         pg_offset += iosize;
3051                         continue;
3052                 }
3053                 /* leave this out until we have a page_mkwrite call */
3054                 if (0 && !test_range_bit(tree, cur, cur + iosize - 1,
3055                                    EXTENT_DIRTY, 0, NULL)) {
3056                         cur = cur + iosize;
3057                         pg_offset += iosize;
3058                         continue;
3059                 }
3060 
3061                 if (tree->ops && tree->ops->writepage_io_hook) {
3062                         ret = tree->ops->writepage_io_hook(page, cur,
3063                                                 cur + iosize - 1);
3064                 } else {
3065                         ret = 0;
3066                 }
3067                 if (ret) {
3068                         SetPageError(page);
3069                 } else {
3070                         unsigned long max_nr = end_index + 1;
3071 
3072                         set_range_writeback(tree, cur, cur + iosize - 1);
3073                         if (!PageWriteback(page)) {
3074                                 printk(KERN_ERR "btrfs warning page %lu not "
3075                                        "writeback, cur %llu end %llu\n",
3076                                        page->index, (unsigned long long)cur,
3077                                        (unsigned long long)end);
3078                         }
3079 
3080                         ret = submit_extent_page(write_flags, tree, page,
3081                                                  sector, iosize, pg_offset,
3082                                                  bdev, &epd->bio, max_nr,
3083                                                  end_bio_extent_writepage,
3084                                                  0, 0, 0);
3085                         if (ret)
3086                                 SetPageError(page);
3087                 }
3088                 cur = cur + iosize;
3089                 pg_offset += iosize;
3090                 nr++;
3091         }
3092 done:
3093         if (nr == 0) {
3094                 /* make sure the mapping tag for page dirty gets cleared */
3095                 set_page_writeback(page);
3096                 end_page_writeback(page);
3097         }
3098         unlock_page(page);
3099 
3100 done_unlocked:
3101 
3102         /* drop our reference on any cached states */
3103         free_extent_state(cached_state);
3104         return 0;
3105 }
3106 
3107 static int eb_wait(void *word)
3108 {
3109         io_schedule();
3110         return 0;
3111 }
3112 
3113 static void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3114 {
3115         wait_on_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK, eb_wait,
3116                     TASK_UNINTERRUPTIBLE);
3117 }
3118 
3119 static int lock_extent_buffer_for_io(struct extent_buffer *eb,
3120                                      struct btrfs_fs_info *fs_info,
3121                                      struct extent_page_data *epd)
3122 {
3123         unsigned long i, num_pages;
3124         int flush = 0;
3125         int ret = 0;
3126 
3127         if (!btrfs_try_tree_write_lock(eb)) {
3128                 flush = 1;
3129                 flush_write_bio(epd);
3130                 btrfs_tree_lock(eb);
3131         }
3132 
3133         if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3134                 btrfs_tree_unlock(eb);
3135                 if (!epd->sync_io)
3136                         return 0;
3137                 if (!flush) {
3138                         flush_write_bio(epd);
3139                         flush = 1;
3140                 }
3141                 while (1) {
3142                         wait_on_extent_buffer_writeback(eb);
3143                         btrfs_tree_lock(eb);
3144                         if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3145                                 break;
3146                         btrfs_tree_unlock(eb);
3147                 }
3148         }
3149 
3150         /*
3151          * We need to do this to prevent races in people who check if the eb is
3152          * under IO since we can end up having no IO bits set for a short period
3153          * of time.
3154          */
3155         spin_lock(&eb->refs_lock);
3156         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3157                 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3158                 spin_unlock(&eb->refs_lock);
3159                 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3160                 spin_lock(&fs_info->delalloc_lock);
3161                 if (fs_info->dirty_metadata_bytes >= eb->len)
3162                         fs_info->dirty_metadata_bytes -= eb->len;
3163                 else
3164                         WARN_ON(1);
3165                 spin_unlock(&fs_info->delalloc_lock);
3166                 ret = 1;
3167         } else {
3168                 spin_unlock(&eb->refs_lock);
3169         }
3170 
3171         btrfs_tree_unlock(eb);
3172 
3173         if (!ret)
3174                 return ret;
3175 
3176         num_pages = num_extent_pages(eb->start, eb->len);
3177         for (i = 0; i < num_pages; i++) {
3178                 struct page *p = extent_buffer_page(eb, i);
3179 
3180                 if (!trylock_page(p)) {
3181                         if (!flush) {
3182                                 flush_write_bio(epd);
3183                                 flush = 1;
3184                         }
3185                         lock_page(p);
3186                 }
3187         }
3188 
3189         return ret;
3190 }
3191 
3192 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3193 {
3194         clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3195         smp_mb__after_clear_bit();
3196         wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3197 }
3198 
3199 static void end_bio_extent_buffer_writepage(struct bio *bio, int err)
3200 {
3201         int uptodate = err == 0;
3202         struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
3203         struct extent_buffer *eb;
3204         int done;
3205 
3206         do {
3207                 struct page *page = bvec->bv_page;
3208 
3209                 bvec--;
3210                 eb = (struct extent_buffer *)page->private;
3211                 BUG_ON(!eb);
3212                 done = atomic_dec_and_test(&eb->io_pages);
3213 
3214                 if (!uptodate || test_bit(EXTENT_BUFFER_IOERR, &eb->bflags)) {
3215                         set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3216                         ClearPageUptodate(page);
3217                         SetPageError(page);
3218                 }
3219 
3220                 end_page_writeback(page);
3221 
3222                 if (!done)
3223                         continue;
3224 
3225                 end_extent_buffer_writeback(eb);
3226         } while (bvec >= bio->bi_io_vec);
3227 
3228         bio_put(bio);
3229 
3230 }
3231 
3232 static int write_one_eb(struct extent_buffer *eb,
3233                         struct btrfs_fs_info *fs_info,
3234                         struct writeback_control *wbc,
3235                         struct extent_page_data *epd)
3236 {
3237         struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3238         u64 offset = eb->start;
3239         unsigned long i, num_pages;
3240         unsigned long bio_flags = 0;
3241         int rw = (epd->sync_io ? WRITE_SYNC : WRITE);
3242         int ret = 0;
3243 
3244         clear_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3245         num_pages = num_extent_pages(eb->start, eb->len);
3246         atomic_set(&eb->io_pages, num_pages);
3247         if (btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID)
3248                 bio_flags = EXTENT_BIO_TREE_LOG;
3249 
3250         for (i = 0; i < num_pages; i++) {
3251                 struct page *p = extent_buffer_page(eb, i);
3252 
3253                 clear_page_dirty_for_io(p);
3254                 set_page_writeback(p);
3255                 ret = submit_extent_page(rw, eb->tree, p, offset >> 9,
3256                                          PAGE_CACHE_SIZE, 0, bdev, &epd->bio,
3257                                          -1, end_bio_extent_buffer_writepage,
3258                                          0, epd->bio_flags, bio_flags);
3259                 epd->bio_flags = bio_flags;
3260                 if (ret) {
3261                         set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
3262                         SetPageError(p);
3263                         if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3264                                 end_extent_buffer_writeback(eb);
3265                         ret = -EIO;
3266                         break;
3267                 }
3268                 offset += PAGE_CACHE_SIZE;
3269                 update_nr_written(p, wbc, 1);
3270                 unlock_page(p);
3271         }
3272 
3273         if (unlikely(ret)) {
3274                 for (; i < num_pages; i++) {
3275                         struct page *p = extent_buffer_page(eb, i);
3276                         unlock_page(p);
3277                 }
3278         }
3279 
3280         return ret;
3281 }
3282 
3283 int btree_write_cache_pages(struct address_space *mapping,
3284                                    struct writeback_control *wbc)
3285 {
3286         struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3287         struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3288         struct extent_buffer *eb, *prev_eb = NULL;
3289         struct extent_page_data epd = {
3290                 .bio = NULL,
3291                 .tree = tree,
3292                 .extent_locked = 0,
3293                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3294                 .bio_flags = 0,
3295         };
3296         int ret = 0;
3297         int done = 0;
3298         int nr_to_write_done = 0;
3299         struct pagevec pvec;
3300         int nr_pages;
3301         pgoff_t index;
3302         pgoff_t end;            /* Inclusive */
3303         int scanned = 0;
3304         int tag;
3305 
3306         pagevec_init(&pvec, 0);
3307         if (wbc->range_cyclic) {
3308                 index = mapping->writeback_index; /* Start from prev offset */
3309                 end = -1;
3310         } else {
3311                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
3312                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
3313                 scanned = 1;
3314         }
3315         if (wbc->sync_mode == WB_SYNC_ALL)
3316                 tag = PAGECACHE_TAG_TOWRITE;
3317         else
3318                 tag = PAGECACHE_TAG_DIRTY;
3319 retry:
3320         if (wbc->sync_mode == WB_SYNC_ALL)
3321                 tag_pages_for_writeback(mapping, index, end);
3322         while (!done && !nr_to_write_done && (index <= end) &&
3323                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
3324                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
3325                 unsigned i;
3326 
3327                 scanned = 1;
3328                 for (i = 0; i < nr_pages; i++) {
3329                         struct page *page = pvec.pages[i];
3330 
3331                         if (!PagePrivate(page))
3332                                 continue;
3333 
3334                         if (!wbc->range_cyclic && page->index > end) {
3335                                 done = 1;
3336                                 break;
3337                         }
3338 
3339                         spin_lock(&mapping->private_lock);
3340                         if (!PagePrivate(page)) {
3341                                 spin_unlock(&mapping->private_lock);
3342                                 continue;
3343                         }
3344 
3345                         eb = (struct extent_buffer *)page->private;
3346 
3347                         /*
3348                          * Shouldn't happen and normally this would be a BUG_ON
3349                          * but no sense in crashing the users box for something
3350                          * we can survive anyway.
3351                          */
3352                         if (!eb) {
3353                                 spin_unlock(&mapping->private_lock);
3354                                 WARN_ON(1);
3355                                 continue;
3356                         }
3357 
3358                         if (eb == prev_eb) {
3359                                 spin_unlock(&mapping->private_lock);
3360                                 continue;
3361                         }
3362 
3363                         ret = atomic_inc_not_zero(&eb->refs);
3364                         spin_unlock(&mapping->private_lock);
3365                         if (!ret)
3366                                 continue;
3367 
3368                         prev_eb = eb;
3369                         ret = lock_extent_buffer_for_io(eb, fs_info, &epd);
3370                         if (!ret) {
3371                                 free_extent_buffer(eb);
3372                                 continue;
3373                         }
3374 
3375                         ret = write_one_eb(eb, fs_info, wbc, &epd);
3376                         if (ret) {
3377                                 done = 1;
3378                                 free_extent_buffer(eb);
3379                                 break;
3380                         }
3381                         free_extent_buffer(eb);
3382 
3383                         /*
3384                          * the filesystem may choose to bump up nr_to_write.
3385                          * We have to make sure to honor the new nr_to_write
3386                          * at any time
3387                          */
3388                         nr_to_write_done = wbc->nr_to_write <= 0;
3389                 }
3390                 pagevec_release(&pvec);
3391                 cond_resched();
3392         }
3393         if (!scanned && !done) {
3394                 /*
3395                  * We hit the last page and there is more work to be done: wrap
3396                  * back to the start of the file
3397                  */
3398                 scanned = 1;
3399                 index = 0;
3400                 goto retry;
3401         }
3402         flush_write_bio(&epd);
3403         return ret;
3404 }
3405 
3406 /**
3407  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
3408  * @mapping: address space structure to write
3409  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3410  * @writepage: function called for each page
3411  * @data: data passed to writepage function
3412  *
3413  * If a page is already under I/O, write_cache_pages() skips it, even
3414  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
3415  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
3416  * and msync() need to guarantee that all the data which was dirty at the time
3417  * the call was made get new I/O started against them.  If wbc->sync_mode is
3418  * WB_SYNC_ALL then we were called for data integrity and we must wait for
3419  * existing IO to complete.
3420  */
3421 static int extent_write_cache_pages(struct extent_io_tree *tree,
3422                              struct address_space *mapping,
3423                              struct writeback_control *wbc,
3424                              writepage_t writepage, void *data,
3425                              void (*flush_fn)(void *))
3426 {
3427         struct inode *inode = mapping->host;
3428         int ret = 0;
3429         int done = 0;
3430         int nr_to_write_done = 0;
3431         struct pagevec pvec;
3432         int nr_pages;
3433         pgoff_t index;
3434         pgoff_t end;            /* Inclusive */
3435         int scanned = 0;
3436         int tag;
3437 
3438         /*
3439          * We have to hold onto the inode so that ordered extents can do their
3440          * work when the IO finishes.  The alternative to this is failing to add
3441          * an ordered extent if the igrab() fails there and that is a huge pain
3442          * to deal with, so instead just hold onto the inode throughout the
3443          * writepages operation.  If it fails here we are freeing up the inode
3444          * anyway and we'd rather not waste our time writing out stuff that is
3445          * going to be truncated anyway.
3446          */
3447         if (!igrab(inode))
3448                 return 0;
3449 
3450         pagevec_init(&pvec, 0);
3451         if (wbc->range_cyclic) {
3452                 index = mapping->writeback_index; /* Start from prev offset */
3453                 end = -1;
3454         } else {
3455                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
3456                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
3457                 scanned = 1;
3458         }
3459         if (wbc->sync_mode == WB_SYNC_ALL)
3460                 tag = PAGECACHE_TAG_TOWRITE;
3461         else
3462                 tag = PAGECACHE_TAG_DIRTY;
3463 retry:
3464         if (wbc->sync_mode == WB_SYNC_ALL)
3465                 tag_pages_for_writeback(mapping, index, end);
3466         while (!done && !nr_to_write_done && (index <= end) &&
3467                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
3468                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
3469                 unsigned i;
3470 
3471                 scanned = 1;
3472                 for (i = 0; i < nr_pages; i++) {
3473                         struct page *page = pvec.pages[i];
3474 
3475                         /*
3476                          * At this point we hold neither mapping->tree_lock nor
3477                          * lock on the page itself: the page may be truncated or
3478                          * invalidated (changing page->mapping to NULL), or even
3479                          * swizzled back from swapper_space to tmpfs file
3480                          * mapping
3481                          */
3482                         if (tree->ops &&
3483                             tree->ops->write_cache_pages_lock_hook) {
3484                                 tree->ops->write_cache_pages_lock_hook(page,
3485                                                                data, flush_fn);
3486                         } else {
3487                                 if (!trylock_page(page)) {
3488                                         flush_fn(data);
3489                                         lock_page(page);
3490                                 }
3491                         }
3492 
3493                         if (unlikely(page->mapping != mapping)) {
3494                                 unlock_page(page);
3495                                 continue;
3496                         }
3497 
3498                         if (!wbc->range_cyclic && page->index > end) {
3499                                 done = 1;
3500                                 unlock_page(page);
3501                                 continue;
3502                         }
3503 
3504                         if (wbc->sync_mode != WB_SYNC_NONE) {
3505                                 if (PageWriteback(page))
3506                                         flush_fn(data);
3507                                 wait_on_page_writeback(page);
3508                         }
3509 
3510                         if (PageWriteback(page) ||
3511                             !clear_page_dirty_for_io(page)) {
3512                                 unlock_page(page);
3513                                 continue;
3514                         }
3515 
3516                         ret = (*writepage)(page, wbc, data);
3517 
3518                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
3519                                 unlock_page(page);
3520                                 ret = 0;
3521                         }
3522                         if (ret)
3523                                 done = 1;
3524 
3525                         /*
3526                          * the filesystem may choose to bump up nr_to_write.
3527                          * We have to make sure to honor the new nr_to_write
3528                          * at any time
3529                          */
3530                         nr_to_write_done = wbc->nr_to_write <= 0;
3531                 }
3532                 pagevec_release(&pvec);
3533                 cond_resched();
3534         }
3535         if (!scanned && !done) {
3536                 /*
3537                  * We hit the last page and there is more work to be done: wrap
3538                  * back to the start of the file
3539                  */
3540                 scanned = 1;
3541                 index = 0;
3542                 goto retry;
3543         }
3544         btrfs_add_delayed_iput(inode);
3545         return ret;
3546 }
3547 
3548 static void flush_epd_write_bio(struct extent_page_data *epd)
3549 {
3550         if (epd->bio) {
3551                 int rw = WRITE;
3552                 int ret;
3553 
3554                 if (epd->sync_io)
3555                         rw = WRITE_SYNC;
3556 
3557                 ret = submit_one_bio(rw, epd->bio, 0, epd->bio_flags);
3558                 BUG_ON(ret < 0); /* -ENOMEM */
3559                 epd->bio = NULL;
3560         }
3561 }
3562 
3563 static noinline void flush_write_bio(void *data)
3564 {
3565         struct extent_page_data *epd = data;
3566         flush_epd_write_bio(epd);
3567 }
3568 
3569 int extent_write_full_page(struct extent_io_tree *tree, struct page *page,
3570                           get_extent_t *get_extent,
3571                           struct writeback_control *wbc)
3572 {
3573         int ret;
3574         struct extent_page_data epd = {
3575                 .bio = NULL,
3576                 .tree = tree,
3577                 .get_extent = get_extent,
3578                 .extent_locked = 0,
3579                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3580                 .bio_flags = 0,
3581         };
3582 
3583         ret = __extent_writepage(page, wbc, &epd);
3584 
3585         flush_epd_write_bio(&epd);
3586         return ret;
3587 }
3588 
3589 int extent_write_locked_range(struct extent_io_tree *tree, struct inode *inode,
3590                               u64 start, u64 end, get_extent_t *get_extent,
3591                               int mode)
3592 {
3593         int ret = 0;
3594         struct address_space *mapping = inode->i_mapping;
3595         struct page *page;
3596         unsigned long nr_pages = (end - start + PAGE_CACHE_SIZE) >>
3597                 PAGE_CACHE_SHIFT;
3598 
3599         struct extent_page_data epd = {
3600                 .bio = NULL,
3601                 .tree = tree,
3602                 .get_extent = get_extent,
3603                 .extent_locked = 1,
3604                 .sync_io = mode == WB_SYNC_ALL,
3605                 .bio_flags = 0,
3606         };
3607         struct writeback_control wbc_writepages = {
3608                 .sync_mode      = mode,
3609                 .nr_to_write    = nr_pages * 2,
3610                 .range_start    = start,
3611                 .range_end      = end + 1,
3612         };
3613 
3614         while (start <= end) {
3615                 page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
3616                 if (clear_page_dirty_for_io(page))
3617                         ret = __extent_writepage(page, &wbc_writepages, &epd);
3618                 else {
3619                         if (tree->ops && tree->ops->writepage_end_io_hook)
3620                                 tree->ops->writepage_end_io_hook(page, start,
3621                                                  start + PAGE_CACHE_SIZE - 1,
3622                                                  NULL, 1);
3623                         unlock_page(page);
3624                 }
3625                 page_cache_release(page);
3626                 start += PAGE_CACHE_SIZE;
3627         }
3628 
3629         flush_epd_write_bio(&epd);
3630         return ret;
3631 }
3632 
3633 int extent_writepages(struct extent_io_tree *tree,
3634                       struct address_space *mapping,
3635                       get_extent_t *get_extent,
3636                       struct writeback_control *wbc)
3637 {
3638         int ret = 0;
3639         struct extent_page_data epd = {
3640                 .bio = NULL,
3641                 .tree = tree,
3642                 .get_extent = get_extent,
3643                 .extent_locked = 0,
3644                 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
3645                 .bio_flags = 0,
3646         };
3647 
3648         ret = extent_write_cache_pages(tree, mapping, wbc,
3649                                        __extent_writepage, &epd,
3650                                        flush_write_bio);
3651         flush_epd_write_bio(&epd);
3652         return ret;
3653 }
3654 
3655 int extent_readpages(struct extent_io_tree *tree,
3656                      struct address_space *mapping,
3657                      struct list_head *pages, unsigned nr_pages,
3658                      get_extent_t get_extent)
3659 {
3660         struct bio *bio = NULL;
3661         unsigned page_idx;
3662         unsigned long bio_flags = 0;
3663         struct page *pagepool[16];
3664         struct page *page;
3665         int i = 0;
3666         int nr = 0;
3667 
3668         for (page_idx = 0; page_idx < nr_pages; page_idx++) {
3669                 page = list_entry(pages->prev, struct page, lru);
3670 
3671                 prefetchw(&page->flags);
3672                 list_del(&page->lru);
3673                 if (add_to_page_cache_lru(page, mapping,
3674                                         page->index, GFP_NOFS)) {
3675                         page_cache_release(page);
3676                         continue;
3677                 }
3678 
3679                 pagepool[nr++] = page;
3680                 if (nr < ARRAY_SIZE(pagepool))
3681                         continue;
3682                 for (i = 0; i < nr; i++) {
3683                         __extent_read_full_page(tree, pagepool[i], get_extent,
3684                                         &bio, 0, &bio_flags);
3685                         page_cache_release(pagepool[i]);
3686                 }
3687                 nr = 0;
3688         }
3689         for (i = 0; i < nr; i++) {
3690                 __extent_read_full_page(tree, pagepool[i], get_extent,
3691                                         &bio, 0, &bio_flags);
3692                 page_cache_release(pagepool[i]);
3693         }
3694 
3695         BUG_ON(!list_empty(pages));
3696         if (bio)
3697                 return submit_one_bio(READ, bio, 0, bio_flags);
3698         return 0;
3699 }
3700 
3701 /*
3702  * basic invalidatepage code, this waits on any locked or writeback
3703  * ranges corresponding to the page, and then deletes any extent state
3704  * records from the tree
3705  */
3706 int extent_invalidatepage(struct extent_io_tree *tree,
3707                           struct page *page, unsigned long offset)
3708 {
3709         struct extent_state *cached_state = NULL;
3710         u64 start = ((u64)page->index << PAGE_CACHE_SHIFT);
3711         u64 end = start + PAGE_CACHE_SIZE - 1;
3712         size_t blocksize = page->mapping->host->i_sb->s_blocksize;
3713 
3714         start += (offset + blocksize - 1) & ~(blocksize - 1);
3715         if (start > end)
3716                 return 0;
3717 
3718         lock_extent_bits(tree, start, end, 0, &cached_state);
3719         wait_on_page_writeback(page);
3720         clear_extent_bit(tree, start, end,
3721                          EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
3722                          EXTENT_DO_ACCOUNTING,
3723                          1, 1, &cached_state, GFP_NOFS);
3724         return 0;
3725 }
3726 
3727 /*
3728  * a helper for releasepage, this tests for areas of the page that
3729  * are locked or under IO and drops the related state bits if it is safe
3730  * to drop the page.
3731  */
3732 int try_release_extent_state(struct extent_map_tree *map,
3733                              struct extent_io_tree *tree, struct page *page,
3734                              gfp_t mask)
3735 {
3736         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
3737         u64 end = start + PAGE_CACHE_SIZE - 1;
3738         int ret = 1;
3739 
3740         if (test_range_bit(tree, start, end,
3741                            EXTENT_IOBITS, 0, NULL))
3742                 ret = 0;
3743         else {
3744                 if ((mask & GFP_NOFS) == GFP_NOFS)
3745                         mask = GFP_NOFS;
3746                 /*
3747                  * at this point we can safely clear everything except the
3748                  * locked bit and the nodatasum bit
3749                  */
3750                 ret = clear_extent_bit(tree, start, end,
3751                                  ~(EXTENT_LOCKED | EXTENT_NODATASUM),
3752                                  0, 0, NULL, mask);
3753 
3754                 /* if clear_extent_bit failed for enomem reasons,
3755                  * we can't allow the release to continue.
3756                  */
3757                 if (ret < 0)
3758                         ret = 0;
3759                 else
3760                         ret = 1;
3761         }
3762         return ret;
3763 }
3764 
3765 /*
3766  * a helper for releasepage.  As long as there are no locked extents
3767  * in the range corresponding to the page, both state records and extent
3768  * map records are removed
3769  */
3770 int try_release_extent_mapping(struct extent_map_tree *map,
3771                                struct extent_io_tree *tree, struct page *page,
3772                                gfp_t mask)
3773 {
3774         struct extent_map *em;
3775         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
3776         u64 end = start + PAGE_CACHE_SIZE - 1;
3777 
3778         if ((mask & __GFP_WAIT) &&
3779             page->mapping->host->i_size > 16 * 1024 * 1024) {
3780                 u64 len;
3781                 while (start <= end) {
3782                         len = end - start + 1;
3783                         write_lock(&map->lock);
3784                         em = lookup_extent_mapping(map, start, len);
3785                         if (!em) {
3786                                 write_unlock(&map->lock);
3787                                 break;
3788                         }
3789                         if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3790                             em->start != start) {
3791                                 write_unlock(&map->lock);
3792                                 free_extent_map(em);
3793                                 break;
3794                         }
3795                         if (!test_range_bit(tree, em->start,
3796                                             extent_map_end(em) - 1,
3797                                             EXTENT_LOCKED | EXTENT_WRITEBACK,
3798                                             0, NULL)) {
3799                                 remove_extent_mapping(map, em);
3800                                 /* once for the rb tree */
3801                                 free_extent_map(em);
3802                         }
3803                         start = extent_map_end(em);
3804                         write_unlock(&map->lock);
3805 
3806                         /* once for us */
3807                         free_extent_map(em);
3808                 }
3809         }
3810         return try_release_extent_state(map, tree, page, mask);
3811 }
3812 
3813 /*
3814  * helper function for fiemap, which doesn't want to see any holes.
3815  * This maps until we find something past 'last'
3816  */
3817 static struct extent_map *get_extent_skip_holes(struct inode *inode,
3818                                                 u64 offset,
3819                                                 u64 last,
3820                                                 get_extent_t *get_extent)
3821 {
3822         u64 sectorsize = BTRFS_I(inode)->root->sectorsize;
3823         struct extent_map *em;
3824         u64 len;
3825 
3826         if (offset >= last)
3827                 return NULL;
3828 
3829         while(1) {
3830                 len = last - offset;
3831                 if (len == 0)
3832                         break;
3833                 len = (len + sectorsize - 1) & ~(sectorsize - 1);
3834                 em = get_extent(inode, NULL, 0, offset, len, 0);
3835                 if (IS_ERR_OR_NULL(em))
3836                         return em;
3837 
3838                 /* if this isn't a hole return it */
3839                 if (!test_bit(EXTENT_FLAG_VACANCY, &em->flags) &&
3840                     em->block_start != EXTENT_MAP_HOLE) {
3841                         return em;
3842                 }
3843 
3844                 /* this is a hole, advance to the next extent */
3845                 offset = extent_map_end(em);
3846                 free_extent_map(em);
3847                 if (offset >= last)
3848                         break;
3849         }
3850         return NULL;
3851 }
3852 
3853 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3854                 __u64 start, __u64 len, get_extent_t *get_extent)
3855 {
3856         int ret = 0;
3857         u64 off = start;
3858         u64 max = start + len;
3859         u32 flags = 0;
3860         u32 found_type;
3861         u64 last;
3862         u64 last_for_get_extent = 0;
3863         u64 disko = 0;
3864         u64 isize = i_size_read(inode);
3865         struct btrfs_key found_key;
3866         struct extent_map *em = NULL;
3867         struct extent_state *cached_state = NULL;
3868         struct btrfs_path *path;
3869         struct btrfs_file_extent_item *item;
3870         int end = 0;
3871         u64 em_start = 0;
3872         u64 em_len = 0;
3873         u64 em_end = 0;
3874         unsigned long emflags;
3875 
3876         if (len == 0)
3877                 return -EINVAL;
3878 
3879         path = btrfs_alloc_path();
3880         if (!path)
3881                 return -ENOMEM;
3882         path->leave_spinning = 1;
3883 
3884         start = ALIGN(start, BTRFS_I(inode)->root->sectorsize);
3885         len = ALIGN(len, BTRFS_I(inode)->root->sectorsize);
3886 
3887         /*
3888          * lookup the last file extent.  We're not using i_size here
3889          * because there might be preallocation past i_size
3890          */
3891         ret = btrfs_lookup_file_extent(NULL, BTRFS_I(inode)->root,
3892                                        path, btrfs_ino(inode), -1, 0);
3893         if (ret < 0) {
3894                 btrfs_free_path(path);
3895                 return ret;
3896         }
3897         WARN_ON(!ret);
3898         path->slots[0]--;
3899         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3900                               struct btrfs_file_extent_item);
3901         btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
3902         found_type = btrfs_key_type(&found_key);
3903 
3904         /* No extents, but there might be delalloc bits */
3905         if (found_key.objectid != btrfs_ino(inode) ||
3906             found_type != BTRFS_EXTENT_DATA_KEY) {
3907                 /* have to trust i_size as the end */
3908                 last = (u64)-1;
3909                 last_for_get_extent = isize;
3910         } else {
3911                 /*
3912                  * remember the start of the last extent.  There are a
3913                  * bunch of different factors that go into the length of the
3914                  * extent, so its much less complex to remember where it started
3915                  */
3916                 last = found_key.offset;
3917                 last_for_get_extent = last + 1;
3918         }
3919         btrfs_free_path(path);
3920 
3921         /*
3922          * we might have some extents allocated but more delalloc past those
3923          * extents.  so, we trust isize unless the start of the last extent is
3924          * beyond isize
3925          */
3926         if (last < isize) {
3927                 last = (u64)-1;
3928                 last_for_get_extent = isize;
3929         }
3930 
3931         lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len, 0,
3932                          &cached_state);
3933 
3934         em = get_extent_skip_holes(inode, start, last_for_get_extent,
3935                                    get_extent);
3936         if (!em)
3937                 goto out;
3938         if (IS_ERR(em)) {
3939                 ret = PTR_ERR(em);
3940                 goto out;
3941         }
3942 
3943         while (!end) {
3944                 u64 offset_in_extent;
3945 
3946                 /* break if the extent we found is outside the range */
3947                 if (em->start >= max || extent_map_end(em) < off)
3948                         break;
3949 
3950                 /*
3951                  * get_extent may return an extent that starts before our
3952                  * requested range.  We have to make sure the ranges
3953                  * we return to fiemap always move forward and don't
3954                  * overlap, so adjust the offsets here
3955                  */
3956                 em_start = max(em->start, off);
3957 
3958                 /*
3959                  * record the offset from the start of the extent
3960                  * for adjusting the disk offset below
3961                  */
3962                 offset_in_extent = em_start - em->start;
3963                 em_end = extent_map_end(em);
3964                 em_len = em_end - em_start;
3965                 emflags = em->flags;
3966                 disko = 0;
3967                 flags = 0;
3968 
3969                 /*
3970                  * bump off for our next call to get_extent
3971                  */
3972                 off = extent_map_end(em);
3973                 if (off >= max)
3974                         end = 1;
3975 
3976                 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
3977                         end = 1;
3978                         flags |= FIEMAP_EXTENT_LAST;
3979                 } else if (em->block_start == EXTENT_MAP_INLINE) {
3980                         flags |= (FIEMAP_EXTENT_DATA_INLINE |
3981                                   FIEMAP_EXTENT_NOT_ALIGNED);
3982                 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
3983                         flags |= (FIEMAP_EXTENT_DELALLOC |
3984                                   FIEMAP_EXTENT_UNKNOWN);
3985                 } else {
3986                         disko = em->block_start + offset_in_extent;
3987                 }
3988                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
3989                         flags |= FIEMAP_EXTENT_ENCODED;
3990 
3991                 free_extent_map(em);
3992                 em = NULL;
3993                 if ((em_start >= last) || em_len == (u64)-1 ||
3994                    (last == (u64)-1 && isize <= em_end)) {
3995                         flags |= FIEMAP_EXTENT_LAST;
3996                         end = 1;
3997                 }
3998 
3999                 /* now scan forward to see if this is really the last extent. */
4000                 em = get_extent_skip_holes(inode, off, last_for_get_extent,
4001                                            get_extent);
4002                 if (IS_ERR(em)) {
4003                         ret = PTR_ERR(em);
4004                         goto out;
4005                 }
4006                 if (!em) {
4007                         flags |= FIEMAP_EXTENT_LAST;
4008                         end = 1;
4009                 }
4010                 ret = fiemap_fill_next_extent(fieinfo, em_start, disko,
4011                                               em_len, flags);
4012                 if (ret)
4013                         goto out_free;
4014         }
4015 out_free:
4016         free_extent_map(em);
4017 out:
4018         unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len,
4019                              &cached_state, GFP_NOFS);
4020         return ret;
4021 }
4022 
4023 static void __free_extent_buffer(struct extent_buffer *eb)
4024 {
4025 #if LEAK_DEBUG
4026         unsigned long flags;
4027         spin_lock_irqsave(&leak_lock, flags);
4028         list_del(&eb->leak_list);
4029         spin_unlock_irqrestore(&leak_lock, flags);
4030 #endif
4031         if (eb->pages && eb->pages != eb->inline_pages)
4032                 kfree(eb->pages);
4033         kmem_cache_free(extent_buffer_cache, eb);
4034 }
4035 
4036 static struct extent_buffer *__alloc_extent_buffer(struct extent_io_tree *tree,
4037                                                    u64 start,
4038                                                    unsigned long len,
4039                                                    gfp_t mask)
4040 {
4041         struct extent_buffer *eb = NULL;
4042 #if LEAK_DEBUG
4043         unsigned long flags;
4044 #endif
4045 
4046         eb = kmem_cache_zalloc(extent_buffer_cache, mask);
4047         if (eb == NULL)
4048                 return NULL;
4049         eb->start = start;
4050         eb->len = len;
4051         eb->tree = tree;
4052         eb->bflags = 0;
4053         rwlock_init(&eb->lock);
4054         atomic_set(&eb->write_locks, 0);
4055         atomic_set(&eb->read_locks, 0);
4056         atomic_set(&eb->blocking_readers, 0);
4057         atomic_set(&eb->blocking_writers, 0);
4058         atomic_set(&eb->spinning_readers, 0);
4059         atomic_set(&eb->spinning_writers, 0);
4060         eb->lock_nested = 0;
4061         init_waitqueue_head(&eb->write_lock_wq);
4062         init_waitqueue_head(&eb->read_lock_wq);
4063 
4064 #if LEAK_DEBUG
4065         spin_lock_irqsave(&leak_lock, flags);
4066         list_add(&eb->leak_list, &buffers);
4067         spin_unlock_irqrestore(&leak_lock, flags);
4068 #endif
4069         spin_lock_init(&eb->refs_lock);
4070         atomic_set(&eb->refs, 1);
4071         atomic_set(&eb->io_pages, 0);
4072 
4073         if (len > MAX_INLINE_EXTENT_BUFFER_SIZE) {
4074                 struct page **pages;
4075                 int num_pages = (len + PAGE_CACHE_SIZE - 1) >>
4076                         PAGE_CACHE_SHIFT;
4077                 pages = kzalloc(num_pages, mask);
4078                 if (!pages) {
4079                         __free_extent_buffer(eb);
4080                         return NULL;
4081                 }
4082                 eb->pages = pages;
4083         } else {
4084                 eb->pages = eb->inline_pages;
4085         }
4086 
4087         return eb;
4088 }
4089 
4090 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4091 {
4092         unsigned long i;
4093         struct page *p;
4094         struct extent_buffer *new;
4095         unsigned long num_pages = num_extent_pages(src->start, src->len);
4096 
4097         new = __alloc_extent_buffer(NULL, src->start, src->len, GFP_ATOMIC);
4098         if (new == NULL)
4099                 return NULL;
4100 
4101         for (i = 0; i < num_pages; i++) {
4102                 p = alloc_page(GFP_ATOMIC);
4103                 BUG_ON(!p);
4104                 attach_extent_buffer_page(new, p);
4105                 WARN_ON(PageDirty(p));
4106                 SetPageUptodate(p);
4107                 new->pages[i] = p;
4108         }
4109 
4110         copy_extent_buffer(new, src, 0, 0, src->len);
4111         set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4112         set_bit(EXTENT_BUFFER_DUMMY, &new->bflags);
4113 
4114         return new;
4115 }
4116 
4117 struct extent_buffer *alloc_dummy_extent_buffer(u64 start, unsigned long len)
4118 {
4119         struct extent_buffer *eb;
4120         unsigned long num_pages = num_extent_pages(0, len);
4121         unsigned long i;
4122 
4123         eb = __alloc_extent_buffer(NULL, start, len, GFP_ATOMIC);
4124         if (!eb)
4125                 return NULL;
4126 
4127         for (i = 0; i < num_pages; i++) {
4128                 eb->pages[i] = alloc_page(GFP_ATOMIC);
4129                 if (!eb->pages[i])
4130                         goto err;
4131         }
4132         set_extent_buffer_uptodate(eb);
4133         btrfs_set_header_nritems(eb, 0);
4134         set_bit(EXTENT_BUFFER_DUMMY, &eb->bflags);
4135 
4136         return eb;
4137 err:
4138         for (; i > 0; i--)
4139                 __free_page(eb->pages[i - 1]);
4140         __free_extent_buffer(eb);
4141         return NULL;
4142 }
4143 
4144 static int extent_buffer_under_io(struct extent_buffer *eb)
4145 {
4146         return (atomic_read(&eb->io_pages) ||
4147                 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4148                 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4149 }
4150 
4151 /*
4152  * Helper for releasing extent buffer page.
4153  */
4154 static void btrfs_release_extent_buffer_page(struct extent_buffer *eb,
4155                                                 unsigned long start_idx)
4156 {
4157         unsigned long index;
4158         unsigned long num_pages;
4159         struct page *page;
4160         int mapped = !test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags);
4161 
4162         BUG_ON(extent_buffer_under_io(eb));
4163 
4164         num_pages = num_extent_pages(eb->start, eb->len);
4165         index = start_idx + num_pages;
4166         if (start_idx >= index)
4167                 return;
4168 
4169         do {
4170                 index--;
4171                 page = extent_buffer_page(eb, index);
4172                 if (page && mapped) {
4173                         spin_lock(&page->mapping->private_lock);
4174                         /*
4175                          * We do this since we'll remove the pages after we've
4176                          * removed the eb from the radix tree, so we could race
4177                          * and have this page now attached to the new eb.  So
4178                          * only clear page_private if it's still connected to
4179                          * this eb.
4180                          */
4181                         if (PagePrivate(page) &&
4182                             page->private == (unsigned long)eb) {
4183                                 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4184                                 BUG_ON(PageDirty(page));
4185                                 BUG_ON(PageWriteback(page));
4186                                 /*
4187                                  * We need to make sure we haven't be attached
4188                                  * to a new eb.
4189                                  */
4190                                 ClearPagePrivate(page);
4191                                 set_page_private(page, 0);
4192                                 /* One for the page private */
4193                                 page_cache_release(page);
4194                         }
4195                         spin_unlock(&page->mapping->private_lock);
4196 
4197                 }
4198                 if (page) {
4199                         /* One for when we alloced the page */
4200                         page_cache_release(page);
4201                 }
4202         } while (index != start_idx);
4203 }
4204 
4205 /*
4206  * Helper for releasing the extent buffer.
4207  */
4208 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4209 {
4210         btrfs_release_extent_buffer_page(eb, 0);
4211         __free_extent_buffer(eb);
4212 }
4213 
4214 static void check_buffer_tree_ref(struct extent_buffer *eb)
4215 {
4216         /* the ref bit is tricky.  We have to make sure it is set
4217          * if we have the buffer dirty.   Otherwise the
4218          * code to free a buffer can end up dropping a dirty
4219          * page
4220          *
4221          * Once the ref bit is set, it won't go away while the
4222          * buffer is dirty or in writeback, and it also won't
4223          * go away while we have the reference count on the
4224          * eb bumped.
4225          *
4226          * We can't just set the ref bit without bumping the
4227          * ref on the eb because free_extent_buffer might
4228          * see the ref bit and try to clear it.  If this happens
4229          * free_extent_buffer might end up dropping our original
4230          * ref by mistake and freeing the page before we are able
4231          * to add one more ref.
4232          *
4233          * So bump the ref count first, then set the bit.  If someone
4234          * beat us to it, drop the ref we added.
4235          */
4236         spin_lock(&eb->refs_lock);
4237         if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4238                 atomic_inc(&eb->refs);
4239         spin_unlock(&eb->refs_lock);
4240 }
4241 
4242 static void mark_extent_buffer_accessed(struct extent_buffer *eb)
4243 {
4244         unsigned long num_pages, i;
4245 
4246         check_buffer_tree_ref(eb);
4247 
4248         num_pages = num_extent_pages(eb->start, eb->len);
4249         for (i = 0; i < num_pages; i++) {
4250                 struct page *p = extent_buffer_page(eb, i);
4251                 mark_page_accessed(p);
4252         }
4253 }
4254 
4255 struct extent_buffer *alloc_extent_buffer(struct extent_io_tree *tree,
4256                                           u64 start, unsigned long len)
4257 {
4258         unsigned long num_pages = num_extent_pages(start, len);
4259         unsigned long i;
4260         unsigned long index = start >> PAGE_CACHE_SHIFT;
4261         struct extent_buffer *eb;
4262         struct extent_buffer *exists = NULL;
4263         struct page *p;
4264         struct address_space *mapping = tree->mapping;
4265         int uptodate = 1;
4266         int ret;
4267 
4268         rcu_read_lock();
4269         eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
4270         if (eb && atomic_inc_not_zero(&eb->refs)) {
4271                 rcu_read_unlock();
4272                 mark_extent_buffer_accessed(eb);
4273                 return eb;
4274         }
4275         rcu_read_unlock();
4276 
4277         eb = __alloc_extent_buffer(tree, start, len, GFP_NOFS);
4278         if (!eb)
4279                 return NULL;
4280 
4281         for (i = 0; i < num_pages; i++, index++) {
4282                 p = find_or_create_page(mapping, index, GFP_NOFS);
4283                 if (!p)
4284                         goto free_eb;
4285 
4286                 spin_lock(&mapping->private_lock);
4287                 if (PagePrivate(p)) {
4288                         /*
4289                          * We could have already allocated an eb for this page
4290                          * and attached one so lets see if we can get a ref on
4291                          * the existing eb, and if we can we know it's good and
4292                          * we can just return that one, else we know we can just
4293                          * overwrite page->private.
4294                          */
4295                         exists = (struct extent_buffer *)p->private;
4296                         if (atomic_inc_not_zero(&exists->refs)) {
4297                                 spin_unlock(&mapping->private_lock);
4298                                 unlock_page(p);
4299                                 page_cache_release(p);
4300                                 mark_extent_buffer_accessed(exists);
4301                                 goto free_eb;
4302                         }
4303 
4304                         /*
4305                          * Do this so attach doesn't complain and we need to
4306                          * drop the ref the old guy had.
4307                          */
4308                         ClearPagePrivate(p);
4309                         WARN_ON(PageDirty(p));
4310                         page_cache_release(p);
4311                 }
4312                 attach_extent_buffer_page(eb, p);
4313                 spin_unlock(&mapping->private_lock);
4314                 WARN_ON(PageDirty(p));
4315                 mark_page_accessed(p);
4316                 eb->pages[i] = p;
4317                 if (!PageUptodate(p))
4318                         uptodate = 0;
4319 
4320                 /*
4321                  * see below about how we avoid a nasty race with release page
4322                  * and why we unlock later
4323                  */
4324         }
4325         if (uptodate)
4326                 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4327 again:
4328         ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
4329         if (ret)
4330                 goto free_eb;
4331 
4332         spin_lock(&tree->buffer_lock);
4333         ret = radix_tree_insert(&tree->buffer, start >> PAGE_CACHE_SHIFT, eb);
4334         if (ret == -EEXIST) {
4335                 exists = radix_tree_lookup(&tree->buffer,
4336                                                 start >> PAGE_CACHE_SHIFT);
4337                 if (!atomic_inc_not_zero(&exists->refs)) {
4338                         spin_unlock(&tree->buffer_lock);
4339                         radix_tree_preload_end();
4340                         exists = NULL;
4341                         goto again;
4342                 }
4343                 spin_unlock(&tree->buffer_lock);
4344                 radix_tree_preload_end();
4345                 mark_extent_buffer_accessed(exists);
4346                 goto free_eb;
4347         }
4348         /* add one reference for the tree */
4349         check_buffer_tree_ref(eb);
4350         spin_unlock(&tree->buffer_lock);
4351         radix_tree_preload_end();
4352 
4353         /*
4354          * there is a race where release page may have
4355          * tried to find this extent buffer in the radix
4356          * but failed.  It will tell the VM it is safe to
4357          * reclaim the, and it will clear the page private bit.
4358          * We must make sure to set the page private bit properly
4359          * after the extent buffer is in the radix tree so
4360          * it doesn't get lost
4361          */
4362         SetPageChecked(eb->pages[0]);
4363         for (i = 1; i < num_pages; i++) {
4364                 p = extent_buffer_page(eb, i);
4365                 ClearPageChecked(p);
4366                 unlock_page(p);
4367         }
4368         unlock_page(eb->pages[0]);
4369         return eb;
4370 
4371 free_eb:
4372         for (i = 0; i < num_pages; i++) {
4373                 if (eb->pages[i])
4374                         unlock_page(eb->pages[i]);
4375         }
4376 
4377         WARN_ON(!atomic_dec_and_test(&eb->refs));
4378         btrfs_release_extent_buffer(eb);
4379         return exists;
4380 }
4381 
4382 struct extent_buffer *find_extent_buffer(struct extent_io_tree *tree,
4383                                          u64 start, unsigned long len)
4384 {
4385         struct extent_buffer *eb;
4386 
4387         rcu_read_lock();
4388         eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
4389         if (eb && atomic_inc_not_zero(&eb->refs)) {
4390                 rcu_read_unlock();
4391                 mark_extent_buffer_accessed(eb);
4392                 return eb;
4393         }
4394         rcu_read_unlock();
4395 
4396         return NULL;
4397 }
4398 
4399 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4400 {
4401         struct extent_buffer *eb =
4402                         container_of(head, struct extent_buffer, rcu_head);
4403 
4404         __free_extent_buffer(eb);
4405 }
4406 
4407 /* Expects to have eb->eb_lock already held */
4408 static int release_extent_buffer(struct extent_buffer *eb, gfp_t mask)
4409 {
4410         WARN_ON(atomic_read(&eb->refs) == 0);
4411         if (atomic_dec_and_test(&eb->refs)) {
4412                 if (test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags)) {
4413                         spin_unlock(&eb->refs_lock);
4414                 } else {
4415                         struct extent_io_tree *tree = eb->tree;
4416 
4417                         spin_unlock(&eb->refs_lock);
4418 
4419                         spin_lock(&tree->buffer_lock);
4420                         radix_tree_delete(&tree->buffer,
4421                                           eb->start >> PAGE_CACHE_SHIFT);
4422                         spin_unlock(&tree->buffer_lock);
4423                 }
4424 
4425                 /* Should be safe to release our pages at this point */
4426                 btrfs_release_extent_buffer_page(eb, 0);
4427                 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4428                 return 1;
4429         }
4430         spin_unlock(&eb->refs_lock);
4431 
4432         return 0;
4433 }
4434 
4435 void free_extent_buffer(struct extent_buffer *eb)
4436 {
4437         if (!eb)
4438                 return;
4439 
4440         spin_lock(&eb->refs_lock);
4441         if (atomic_read(&eb->refs) == 2 &&
4442             test_bit(EXTENT_BUFFER_DUMMY, &eb->bflags))
4443                 atomic_dec(&eb->refs);
4444 
4445         if (atomic_read(&eb->refs) == 2 &&
4446             test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4447             !extent_buffer_under_io(eb) &&
4448             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4449                 atomic_dec(&eb->refs);
4450 
4451         /*
4452          * I know this is terrible, but it's temporary until we stop tracking
4453          * the uptodate bits and such for the extent buffers.
4454          */
4455         release_extent_buffer(eb, GFP_ATOMIC);
4456 }
4457 
4458 void free_extent_buffer_stale(struct extent_buffer *eb)
4459 {
4460         if (!eb)
4461                 return;
4462 
4463         spin_lock(&eb->refs_lock);
4464         set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4465 
4466         if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4467             test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4468                 atomic_dec(&eb->refs);
4469         release_extent_buffer(eb, GFP_NOFS);
4470 }
4471 
4472 void clear_extent_buffer_dirty(struct extent_buffer *eb)
4473 {
4474         unsigned long i;
4475         unsigned long num_pages;
4476         struct page *page;
4477 
4478         num_pages = num_extent_pages(eb->start, eb->len);
4479 
4480         for (i = 0; i < num_pages; i++) {
4481                 page = extent_buffer_page(eb, i);
4482                 if (!PageDirty(page))
4483                         continue;
4484 
4485                 lock_page(page);
4486                 WARN_ON(!PagePrivate(page));
4487 
4488                 clear_page_dirty_for_io(page);
4489                 spin_lock_irq(&page->mapping->tree_lock);
4490                 if (!PageDirty(page)) {
4491                         radix_tree_tag_clear(&page->mapping->page_tree,
4492                                                 page_index(page),
4493                                                 PAGECACHE_TAG_DIRTY);
4494                 }
4495                 spin_unlock_irq(&page->mapping->tree_lock);
4496                 ClearPageError(page);
4497                 unlock_page(page);
4498         }
4499         WARN_ON(atomic_read(&eb->refs) == 0);
4500 }
4501 
4502 int set_extent_buffer_dirty(struct extent_buffer *eb)
4503 {
4504         unsigned long i;
4505         unsigned long num_pages;
4506         int was_dirty = 0;
4507 
4508         check_buffer_tree_ref(eb);
4509 
4510         was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4511 
4512         num_pages = num_extent_pages(eb->start, eb->len);
4513         WARN_ON(atomic_read(&eb->refs) == 0);
4514         WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4515 
4516         for (i = 0; i < num_pages; i++)
4517                 set_page_dirty(extent_buffer_page(eb, i));
4518         return was_dirty;
4519 }
4520 
4521 static int range_straddles_pages(u64 start, u64 len)
4522 {
4523         if (len < PAGE_CACHE_SIZE)
4524                 return 1;
4525         if (start & (PAGE_CACHE_SIZE - 1))
4526                 return 1;
4527         if ((start + len) & (PAGE_CACHE_SIZE - 1))
4528                 return 1;
4529         return 0;
4530 }
4531 
4532 int clear_extent_buffer_uptodate(struct extent_buffer *eb)
4533 {
4534         unsigned long i;
4535         struct page *page;
4536         unsigned long num_pages;
4537 
4538         clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4539         num_pages = num_extent_pages(eb->start, eb->len);
4540         for (i = 0; i < num_pages; i++) {
4541                 page = extent_buffer_page(eb, i);
4542                 if (page)
4543                         ClearPageUptodate(page);
4544         }
4545         return 0;
4546 }
4547 
4548 int set_extent_buffer_uptodate(struct extent_buffer *eb)
4549 {
4550         unsigned long i;
4551         struct page *page;
4552         unsigned long num_pages;
4553 
4554         set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4555         num_pages = num_extent_pages(eb->start, eb->len);
4556         for (i = 0; i < num_pages; i++) {
4557                 page = extent_buffer_page(eb, i);
4558                 SetPageUptodate(page);
4559         }
4560         return 0;
4561 }
4562 
4563 int extent_range_uptodate(struct extent_io_tree *tree,
4564                           u64 start, u64 end)
4565 {
4566         struct page *page;
4567         int ret;
4568         int pg_uptodate = 1;
4569         int uptodate;
4570         unsigned long index;
4571 
4572         if (range_straddles_pages(start, end - start + 1)) {
4573                 ret = test_range_bit(tree, start, end,
4574                                      EXTENT_UPTODATE, 1, NULL);
4575                 if (ret)
4576                         return 1;
4577         }
4578         while (start <= end) {
4579                 index = start >> PAGE_CACHE_SHIFT;
4580                 page = find_get_page(tree->mapping, index);
4581                 if (!page)
4582                         return 1;
4583                 uptodate = PageUptodate(page);
4584                 page_cache_release(page);
4585                 if (!uptodate) {
4586                         pg_uptodate = 0;
4587                         break;
4588                 }
4589                 start += PAGE_CACHE_SIZE;
4590         }
4591         return pg_uptodate;
4592 }
4593 
4594 int extent_buffer_uptodate(struct extent_buffer *eb)
4595 {
4596         return test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4597 }
4598 
4599 int read_extent_buffer_pages(struct extent_io_tree *tree,
4600                              struct extent_buffer *eb, u64 start, int wait,
4601                              get_extent_t *get_extent, int mirror_num)
4602 {
4603         unsigned long i;
4604         unsigned long start_i;
4605         struct page *page;
4606         int err;
4607         int ret = 0;
4608         int locked_pages = 0;
4609         int all_uptodate = 1;
4610         unsigned long num_pages;
4611         unsigned long num_reads = 0;
4612         struct bio *bio = NULL;
4613         unsigned long bio_flags = 0;
4614 
4615         if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
4616                 return 0;
4617 
4618         if (start) {
4619                 WARN_ON(start < eb->start);
4620                 start_i = (start >> PAGE_CACHE_SHIFT) -
4621                         (eb->start >> PAGE_CACHE_SHIFT);
4622         } else {
4623                 start_i = 0;
4624         }
4625 
4626         num_pages = num_extent_pages(eb->start, eb->len);
4627         for (i = start_i; i < num_pages; i++) {
4628                 page = extent_buffer_page(eb, i);
4629                 if (wait == WAIT_NONE) {
4630                         if (!trylock_page(page))
4631                                 goto unlock_exit;
4632                 } else {
4633                         lock_page(page);
4634                 }
4635                 locked_pages++;
4636                 if (!PageUptodate(page)) {
4637                         num_reads++;
4638                         all_uptodate = 0;
4639                 }
4640         }
4641         if (all_uptodate) {
4642                 if (start_i == 0)
4643                         set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4644                 goto unlock_exit;
4645         }
4646 
4647         clear_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
4648         eb->read_mirror = 0;
4649         atomic_set(&eb->io_pages, num_reads);
4650         for (i = start_i; i < num_pages; i++) {
4651                 page = extent_buffer_page(eb, i);
4652                 if (!PageUptodate(page)) {
4653                         ClearPageError(page);
4654                         err = __extent_read_full_page(tree, page,
4655                                                       get_extent, &bio,
4656                                                       mirror_num, &bio_flags);
4657                         if (err)
4658                                 ret = err;
4659                 } else {
4660                         unlock_page(page);
4661                 }
4662         }
4663 
4664         if (bio) {
4665                 err = submit_one_bio(READ, bio, mirror_num, bio_flags);
4666                 if (err)
4667                         return err;
4668         }
4669 
4670         if (ret || wait != WAIT_COMPLETE)
4671                 return ret;
4672 
4673         for (i = start_i; i < num_pages; i++) {
4674                 page = extent_buffer_page(eb, i);
4675                 wait_on_page_locked(page);
4676                 if (!PageUptodate(page))
4677                         ret = -EIO;
4678         }
4679 
4680         return ret;
4681 
4682 unlock_exit:
4683         i = start_i;
4684         while (locked_pages > 0) {
4685                 page = extent_buffer_page(eb, i);
4686                 i++;
4687                 unlock_page(page);
4688                 locked_pages--;
4689         }
4690         return ret;
4691 }
4692 
4693 void read_extent_buffer(struct extent_buffer *eb, void *dstv,
4694                         unsigned long start,
4695                         unsigned long len)
4696 {
4697         size_t cur;
4698         size_t offset;
4699         struct page *page;
4700         char *kaddr;
4701         char *dst = (char *)dstv;
4702         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4703         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4704 
4705         WARN_ON(start > eb->len);
4706         WARN_ON(start + len > eb->start + eb->len);
4707 
4708         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4709 
4710         while (len > 0) {
4711                 page = extent_buffer_page(eb, i);
4712 
4713                 cur = min(len, (PAGE_CACHE_SIZE - offset));
4714                 kaddr = page_address(page);
4715                 memcpy(dst, kaddr + offset, cur);
4716 
4717                 dst += cur;
4718                 len -= cur;
4719                 offset = 0;
4720                 i++;
4721         }
4722 }
4723 
4724 int map_private_extent_buffer(struct extent_buffer *eb, unsigned long start,
4725                                unsigned long min_len, char **map,
4726                                unsigned long *map_start,
4727                                unsigned long *map_len)
4728 {
4729         size_t offset = start & (PAGE_CACHE_SIZE - 1);
4730         char *kaddr;
4731         struct page *p;
4732         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4733         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4734         unsigned long end_i = (start_offset + start + min_len - 1) >>
4735                 PAGE_CACHE_SHIFT;
4736 
4737         if (i != end_i)
4738                 return -EINVAL;
4739 
4740         if (i == 0) {
4741                 offset = start_offset;
4742                 *map_start = 0;
4743         } else {
4744                 offset = 0;
4745                 *map_start = ((u64)i << PAGE_CACHE_SHIFT) - start_offset;
4746         }
4747 
4748         if (start + min_len > eb->len) {
4749                 WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, "
4750                        "wanted %lu %lu\n", (unsigned long long)eb->start,
4751                        eb->len, start, min_len);
4752                 return -EINVAL;
4753         }
4754 
4755         p = extent_buffer_page(eb, i);
4756         kaddr = page_address(p);
4757         *map = kaddr + offset;
4758         *map_len = PAGE_CACHE_SIZE - offset;
4759         return 0;
4760 }
4761 
4762 int memcmp_extent_buffer(struct extent_buffer *eb, const void *ptrv,
4763                           unsigned long start,
4764                           unsigned long len)
4765 {
4766         size_t cur;
4767         size_t offset;
4768         struct page *page;
4769         char *kaddr;
4770         char *ptr = (char *)ptrv;
4771         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4772         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4773         int ret = 0;
4774 
4775         WARN_ON(start > eb->len);
4776         WARN_ON(start + len > eb->start + eb->len);
4777 
4778         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4779 
4780         while (len > 0) {
4781                 page = extent_buffer_page(eb, i);
4782 
4783                 cur = min(len, (PAGE_CACHE_SIZE - offset));
4784 
4785                 kaddr = page_address(page);
4786                 ret = memcmp(ptr, kaddr + offset, cur);
4787                 if (ret)
4788                         break;
4789 
4790                 ptr += cur;
4791                 len -= cur;
4792                 offset = 0;
4793                 i++;
4794         }
4795         return ret;
4796 }
4797 
4798 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
4799                          unsigned long start, unsigned long len)
4800 {
4801         size_t cur;
4802         size_t offset;
4803         struct page *page;
4804         char *kaddr;
4805         char *src = (char *)srcv;
4806         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4807         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4808 
4809         WARN_ON(start > eb->len);
4810         WARN_ON(start + len > eb->start + eb->len);
4811 
4812         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4813 
4814         while (len > 0) {
4815                 page = extent_buffer_page(eb, i);
4816                 WARN_ON(!PageUptodate(page));
4817 
4818                 cur = min(len, PAGE_CACHE_SIZE - offset);
4819                 kaddr = page_address(page);
4820                 memcpy(kaddr + offset, src, cur);
4821 
4822                 src += cur;
4823                 len -= cur;
4824                 offset = 0;
4825                 i++;
4826         }
4827 }
4828 
4829 void memset_extent_buffer(struct extent_buffer *eb, char c,
4830                           unsigned long start, unsigned long len)
4831 {
4832         size_t cur;
4833         size_t offset;
4834         struct page *page;
4835         char *kaddr;
4836         size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
4837         unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
4838 
4839         WARN_ON(start > eb->len);
4840         WARN_ON(start + len > eb->start + eb->len);
4841 
4842         offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
4843 
4844         while (len > 0) {
4845                 page = extent_buffer_page(eb, i);
4846                 WARN_ON(!PageUptodate(page));
4847 
4848                 cur = min(len, PAGE_CACHE_SIZE - offset);
4849                 kaddr = page_address(page);
4850                 memset(kaddr + offset, c, cur);
4851 
4852                 len -= cur;
4853                 offset = 0;
4854                 i++;
4855         }
4856 }
4857 
4858 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
4859                         unsigned long dst_offset, unsigned long src_offset,
4860                         unsigned long len)
4861 {
4862         u64 dst_len = dst->len;
4863         size_t cur;
4864         size_t offset;
4865         struct page *page;
4866         char *kaddr;
4867         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4868         unsigned long i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
4869 
4870         WARN_ON(src->len != dst_len);
4871 
4872         offset = (start_offset + dst_offset) &
4873                 ((unsigned long)PAGE_CACHE_SIZE - 1);
4874 
4875         while (len > 0) {
4876                 page = extent_buffer_page(dst, i);
4877                 WARN_ON(!PageUptodate(page));
4878 
4879                 cur = min(len, (unsigned long)(PAGE_CACHE_SIZE - offset));
4880 
4881                 kaddr = page_address(page);
4882                 read_extent_buffer(src, kaddr + offset, src_offset, cur);
4883 
4884                 src_offset += cur;
4885                 len -= cur;
4886                 offset = 0;
4887                 i++;
4888         }
4889 }
4890 
4891 static void move_pages(struct page *dst_page, struct page *src_page,
4892                        unsigned long dst_off, unsigned long src_off,
4893                        unsigned long len)
4894 {
4895         char *dst_kaddr = page_address(dst_page);
4896         if (dst_page == src_page) {
4897                 memmove(dst_kaddr + dst_off, dst_kaddr + src_off, len);
4898         } else {
4899                 char *src_kaddr = page_address(src_page);
4900                 char *p = dst_kaddr + dst_off + len;
4901                 char *s = src_kaddr + src_off + len;
4902 
4903                 while (len--)
4904                         *--p = *--s;
4905         }
4906 }
4907 
4908 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4909 {
4910         unsigned long distance = (src > dst) ? src - dst : dst - src;
4911         return distance < len;
4912 }
4913 
4914 static void copy_pages(struct page *dst_page, struct page *src_page,
4915                        unsigned long dst_off, unsigned long src_off,
4916                        unsigned long len)
4917 {
4918         char *dst_kaddr = page_address(dst_page);
4919         char *src_kaddr;
4920         int must_memmove = 0;
4921 
4922         if (dst_page != src_page) {
4923                 src_kaddr = page_address(src_page);
4924         } else {
4925                 src_kaddr = dst_kaddr;
4926                 if (areas_overlap(src_off, dst_off, len))
4927                         must_memmove = 1;
4928         }
4929 
4930         if (must_memmove)
4931                 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
4932         else
4933                 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
4934 }
4935 
4936 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
4937                            unsigned long src_offset, unsigned long len)
4938 {
4939         size_t cur;
4940         size_t dst_off_in_page;
4941         size_t src_off_in_page;
4942         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4943         unsigned long dst_i;
4944         unsigned long src_i;
4945 
4946         if (src_offset + len > dst->len) {
4947                 printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
4948                        "len %lu dst len %lu\n", src_offset, len, dst->len);
4949                 BUG_ON(1);
4950         }
4951         if (dst_offset + len > dst->len) {
4952                 printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
4953                        "len %lu dst len %lu\n", dst_offset, len, dst->len);
4954                 BUG_ON(1);
4955         }
4956 
4957         while (len > 0) {
4958                 dst_off_in_page = (start_offset + dst_offset) &
4959                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4960                 src_off_in_page = (start_offset + src_offset) &
4961                         ((unsigned long)PAGE_CACHE_SIZE - 1);
4962 
4963                 dst_i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
4964                 src_i = (start_offset + src_offset) >> PAGE_CACHE_SHIFT;
4965 
4966                 cur = min(len, (unsigned long)(PAGE_CACHE_SIZE -
4967                                                src_off_in_page));
4968                 cur = min_t(unsigned long, cur,
4969                         (unsigned long)(PAGE_CACHE_SIZE - dst_off_in_page));
4970 
4971                 copy_pages(extent_buffer_page(dst, dst_i),
4972                            extent_buffer_page(dst, src_i),
4973                            dst_off_in_page, src_off_in_page, cur);
4974 
4975                 src_offset += cur;
4976                 dst_offset += cur;
4977                 len -= cur;
4978         }
4979 }
4980 
4981 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
4982                            unsigned long src_offset, unsigned long len)
4983 {
4984         size_t cur;
4985         size_t dst_off_in_page;
4986         size_t src_off_in_page;
4987         unsigned long dst_end = dst_offset + len - 1;
4988         unsigned long src_end = src_offset + len - 1;
4989         size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
4990         unsigned long dst_i;
4991         unsigned long src_i;
4992 
4993         if (src_offset + len > dst->len) {
4994                 printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
4995                        "len %lu len %lu\n", src_offset, len, dst->len);
4996                 BUG_ON(1);
4997         }
4998         if (dst_offset + len > dst->len) {
4999                 printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
5000                        "len %lu len %lu\n", dst_offset, len, dst->len);
5001                 BUG_ON(1);
5002         }
5003         if (dst_offset < src_offset) {
5004                 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5005                 return;
5006         }
5007         while (len > 0) {
5008                 dst_i = (start_offset + dst_end) >> PAGE_CACHE_SHIFT;
5009                 src_i = (start_offset + src_end) >> PAGE_CACHE_SHIFT;
5010 
5011                 dst_off_in_page = (start_offset + dst_end) &
5012                         ((unsigned long)PAGE_CACHE_SIZE - 1);
5013                 src_off_in_page = (start_offset + src_end) &
5014                         ((unsigned long)PAGE_CACHE_SIZE - 1);
5015 
5016                 cur = min_t(unsigned long, len, src_off_in_page + 1);
5017                 cur = min(cur, dst_off_in_page + 1);
5018                 move_pages(extent_buffer_page(dst, dst_i),
5019                            extent_buffer_page(dst, src_i),
5020                            dst_off_in_page - cur + 1,
5021                            src_off_in_page - cur + 1, cur);
5022 
5023                 dst_end -= cur;
5024                 src_end -= cur;
5025                 len -= cur;
5026         }
5027 }
5028 
5029 int try_release_extent_buffer(struct page *page, gfp_t mask)
5030 {
5031         struct extent_buffer *eb;
5032 
5033         /*
5034          * We need to make sure noboody is attaching this page to an eb right
5035          * now.
5036          */
5037         spin_lock(&page->mapping->private_lock);
5038         if (!PagePrivate(page)) {
5039                 spin_unlock(&page->mapping->private_lock);
5040                 return 1;
5041         }
5042 
5043         eb = (struct extent_buffer *)page->private;
5044         BUG_ON(!eb);
5045 
5046         /*
5047          * This is a little awful but should be ok, we need to make sure that
5048          * the eb doesn't disappear out from under us while we're looking at
5049          * this page.
5050          */
5051         spin_lock(&eb->refs_lock);
5052         if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5053                 spin_unlock(&eb->refs_lock);
5054                 spin_unlock(&page->mapping->private_lock);
5055                 return 0;
5056         }
5057         spin_unlock(&page->mapping->private_lock);
5058 
5059         if ((mask & GFP_NOFS) == GFP_NOFS)
5060                 mask = GFP_NOFS;
5061 
5062         /*
5063          * If tree ref isn't set then we know the ref on this eb is a real ref,
5064          * so just return, this page will likely be freed soon anyway.
5065          */
5066         if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5067                 spin_unlock(&eb->refs_lock);
5068                 return 0;
5069         }
5070 
5071         return release_extent_buffer(eb, mask);
5072 }
5073 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp