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