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