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