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