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