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