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