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