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