xref: /linux/fs/btrfs/extent_io.c (revision 997f9640c9238b991b6c8abf5420b37bbba5d867)
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 "extent_io.h"
18 #include "extent-io-tree.h"
19 #include "extent_map.h"
20 #include "ctree.h"
21 #include "btrfs_inode.h"
22 #include "bio.h"
23 #include "locking.h"
24 #include "backref.h"
25 #include "disk-io.h"
26 #include "subpage.h"
27 #include "zoned.h"
28 #include "block-group.h"
29 #include "compression.h"
30 #include "fs.h"
31 #include "accessors.h"
32 #include "file-item.h"
33 #include "file.h"
34 #include "dev-replace.h"
35 #include "super.h"
36 #include "transaction.h"
37 
38 static struct kmem_cache *extent_buffer_cache;
39 
40 #ifdef CONFIG_BTRFS_DEBUG
41 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
42 {
43 	struct btrfs_fs_info *fs_info = eb->fs_info;
44 	unsigned long flags;
45 
46 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
47 	list_add(&eb->leak_list, &fs_info->allocated_ebs);
48 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
49 }
50 
51 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
52 {
53 	struct btrfs_fs_info *fs_info = eb->fs_info;
54 	unsigned long flags;
55 
56 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
57 	list_del(&eb->leak_list);
58 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
59 }
60 
61 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
62 {
63 	struct extent_buffer *eb;
64 	unsigned long flags;
65 
66 	/*
67 	 * If we didn't get into open_ctree our allocated_ebs will not be
68 	 * initialized, so just skip this.
69 	 */
70 	if (!fs_info->allocated_ebs.next)
71 		return;
72 
73 	WARN_ON(!list_empty(&fs_info->allocated_ebs));
74 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
75 	while (!list_empty(&fs_info->allocated_ebs)) {
76 		eb = list_first_entry(&fs_info->allocated_ebs,
77 				      struct extent_buffer, leak_list);
78 		btrfs_err(fs_info,
79 		       "buffer leak start %llu len %u refs %d bflags %lu owner %llu",
80 		       eb->start, eb->len, refcount_read(&eb->refs), eb->bflags,
81 		       btrfs_header_owner(eb));
82 		list_del(&eb->leak_list);
83 		WARN_ON_ONCE(1);
84 		kmem_cache_free(extent_buffer_cache, eb);
85 	}
86 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
87 }
88 #else
89 #define btrfs_leak_debug_add_eb(eb)			do {} while (0)
90 #define btrfs_leak_debug_del_eb(eb)			do {} while (0)
91 #endif
92 
93 /*
94  * Structure to record info about the bio being assembled, and other info like
95  * how many bytes are there before stripe/ordered extent boundary.
96  */
97 struct btrfs_bio_ctrl {
98 	struct btrfs_bio *bbio;
99 	/* Last byte contained in bbio + 1 . */
100 	loff_t next_file_offset;
101 	enum btrfs_compression_type compress_type;
102 	u32 len_to_oe_boundary;
103 	blk_opf_t opf;
104 	/*
105 	 * For data read bios, we attempt to optimize csum lookups if the extent
106 	 * generation is older than the current one. To make this possible, we
107 	 * need to track the maximum generation of an extent in a bio_ctrl to
108 	 * make the decision when submitting the bio.
109 	 *
110 	 * The pattern between do_readpage(), submit_one_bio() and
111 	 * submit_extent_folio() is quite subtle, so tracking this is tricky.
112 	 *
113 	 * As we process extent E, we might submit a bio with existing built up
114 	 * extents before adding E to a new bio, or we might just add E to the
115 	 * bio. As a result, E's generation could apply to the current bio or
116 	 * to the next one, so we need to be careful to update the bio_ctrl's
117 	 * generation with E's only when we are sure E is added to bio_ctrl->bbio
118 	 * in submit_extent_folio().
119 	 *
120 	 * See the comment in btrfs_lookup_bio_sums() for more detail on the
121 	 * need for this optimization.
122 	 */
123 	u64 generation;
124 	btrfs_bio_end_io_t end_io_func;
125 	struct writeback_control *wbc;
126 
127 	/*
128 	 * The sectors of the page which are going to be submitted by
129 	 * extent_writepage_io().
130 	 * This is to avoid touching ranges covered by compression/inline.
131 	 */
132 	unsigned long submit_bitmap;
133 	struct readahead_control *ractl;
134 
135 	/*
136 	 * The start offset of the last used extent map by a read operation.
137 	 *
138 	 * This is for proper compressed read merge.
139 	 * U64_MAX means we are starting the read and have made no progress yet.
140 	 *
141 	 * The current btrfs_bio_is_contig() only uses disk_bytenr as
142 	 * the condition to check if the read can be merged with previous
143 	 * bio, which is not correct. E.g. two file extents pointing to the
144 	 * same extent but with different offset.
145 	 *
146 	 * So here we need to do extra checks to only merge reads that are
147 	 * covered by the same extent map.
148 	 * Just extent_map::start will be enough, as they are unique
149 	 * inside the same inode.
150 	 */
151 	u64 last_em_start;
152 };
153 
154 /*
155  * Helper to set the csum search commit root option for a bio_ctrl's bbio
156  * before submitting the bio.
157  *
158  * Only for use by submit_one_bio().
159  */
160 static void bio_set_csum_search_commit_root(struct btrfs_bio_ctrl *bio_ctrl)
161 {
162 	struct btrfs_bio *bbio = bio_ctrl->bbio;
163 
164 	ASSERT(bbio);
165 
166 	if (!(btrfs_op(&bbio->bio) == BTRFS_MAP_READ && is_data_inode(bbio->inode)))
167 		return;
168 
169 	bio_ctrl->bbio->csum_search_commit_root =
170 		(bio_ctrl->generation &&
171 		 bio_ctrl->generation < btrfs_get_fs_generation(bbio->inode->root->fs_info));
172 }
173 
174 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
175 {
176 	struct btrfs_bio *bbio = bio_ctrl->bbio;
177 
178 	if (!bbio)
179 		return;
180 
181 	/* Caller should ensure the bio has at least some range added */
182 	ASSERT(bbio->bio.bi_iter.bi_size);
183 
184 	bio_set_csum_search_commit_root(bio_ctrl);
185 
186 	if (btrfs_op(&bbio->bio) == BTRFS_MAP_READ &&
187 	    bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
188 		btrfs_submit_compressed_read(bbio);
189 	else
190 		btrfs_submit_bbio(bbio, 0);
191 
192 	/* The bbio is owned by the end_io handler now */
193 	bio_ctrl->bbio = NULL;
194 	/*
195 	 * We used the generation to decide whether to lookup csums in the
196 	 * commit_root or not when we called bio_set_csum_search_commit_root()
197 	 * above. Now, reset the generation for the next bio.
198 	 */
199 	bio_ctrl->generation = 0;
200 }
201 
202 /*
203  * Submit or fail the current bio in the bio_ctrl structure.
204  */
205 static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
206 {
207 	struct btrfs_bio *bbio = bio_ctrl->bbio;
208 
209 	if (!bbio)
210 		return;
211 
212 	if (ret) {
213 		ASSERT(ret < 0);
214 		btrfs_bio_end_io(bbio, errno_to_blk_status(ret));
215 		/* The bio is owned by the end_io handler now */
216 		bio_ctrl->bbio = NULL;
217 	} else {
218 		submit_one_bio(bio_ctrl);
219 	}
220 }
221 
222 int __init extent_buffer_init_cachep(void)
223 {
224 	extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
225 						sizeof(struct extent_buffer), 0, 0,
226 						NULL);
227 	if (!extent_buffer_cache)
228 		return -ENOMEM;
229 
230 	return 0;
231 }
232 
233 void __cold extent_buffer_free_cachep(void)
234 {
235 	/*
236 	 * Make sure all delayed rcu free are flushed before we
237 	 * destroy caches.
238 	 */
239 	rcu_barrier();
240 	kmem_cache_destroy(extent_buffer_cache);
241 }
242 
243 static void process_one_folio(struct btrfs_fs_info *fs_info,
244 			      struct folio *folio, const struct folio *locked_folio,
245 			      unsigned long page_ops, u64 start, u64 end)
246 {
247 	u32 len;
248 
249 	ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
250 	len = end + 1 - start;
251 
252 	if (page_ops & PAGE_SET_ORDERED)
253 		btrfs_folio_clamp_set_ordered(fs_info, folio, start, len);
254 	if (page_ops & PAGE_START_WRITEBACK) {
255 		btrfs_folio_clamp_clear_dirty(fs_info, folio, start, len);
256 		btrfs_folio_clamp_set_writeback(fs_info, folio, start, len);
257 	}
258 	if (page_ops & PAGE_END_WRITEBACK)
259 		btrfs_folio_clamp_clear_writeback(fs_info, folio, start, len);
260 
261 	if (folio != locked_folio && (page_ops & PAGE_UNLOCK))
262 		btrfs_folio_end_lock(fs_info, folio, start, len);
263 }
264 
265 static void __process_folios_contig(struct address_space *mapping,
266 				    const struct folio *locked_folio, u64 start,
267 				    u64 end, unsigned long page_ops)
268 {
269 	struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
270 	pgoff_t index = start >> PAGE_SHIFT;
271 	pgoff_t end_index = end >> PAGE_SHIFT;
272 	struct folio_batch fbatch;
273 	int i;
274 
275 	folio_batch_init(&fbatch);
276 	while (index <= end_index) {
277 		int found_folios;
278 
279 		found_folios = filemap_get_folios_contig(mapping, &index,
280 				end_index, &fbatch);
281 		for (i = 0; i < found_folios; i++) {
282 			struct folio *folio = fbatch.folios[i];
283 
284 			process_one_folio(fs_info, folio, locked_folio,
285 					  page_ops, start, end);
286 		}
287 		folio_batch_release(&fbatch);
288 		cond_resched();
289 	}
290 }
291 
292 static noinline void unlock_delalloc_folio(const struct inode *inode,
293 					   struct folio *locked_folio,
294 					   u64 start, u64 end)
295 {
296 	ASSERT(locked_folio);
297 
298 	__process_folios_contig(inode->i_mapping, locked_folio, start, end,
299 				PAGE_UNLOCK);
300 }
301 
302 static noinline int lock_delalloc_folios(struct inode *inode,
303 					 struct folio *locked_folio,
304 					 u64 start, u64 end)
305 {
306 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
307 	struct address_space *mapping = inode->i_mapping;
308 	pgoff_t index = start >> PAGE_SHIFT;
309 	pgoff_t end_index = end >> PAGE_SHIFT;
310 	u64 processed_end = start;
311 	struct folio_batch fbatch;
312 
313 	folio_batch_init(&fbatch);
314 	while (index <= end_index) {
315 		unsigned int found_folios, i;
316 
317 		found_folios = filemap_get_folios_contig(mapping, &index,
318 				end_index, &fbatch);
319 		if (found_folios == 0)
320 			goto out;
321 
322 		for (i = 0; i < found_folios; i++) {
323 			struct folio *folio = fbatch.folios[i];
324 			u64 range_start;
325 			u32 range_len;
326 
327 			if (folio == locked_folio)
328 				continue;
329 
330 			folio_lock(folio);
331 			if (!folio_test_dirty(folio) || folio->mapping != mapping) {
332 				folio_unlock(folio);
333 				goto out;
334 			}
335 			range_start = max_t(u64, folio_pos(folio), start);
336 			range_len = min_t(u64, folio_next_pos(folio), end + 1) - range_start;
337 			btrfs_folio_set_lock(fs_info, folio, range_start, range_len);
338 
339 			processed_end = range_start + range_len - 1;
340 		}
341 		folio_batch_release(&fbatch);
342 		cond_resched();
343 	}
344 
345 	return 0;
346 out:
347 	folio_batch_release(&fbatch);
348 	if (processed_end > start)
349 		unlock_delalloc_folio(inode, locked_folio, start, processed_end);
350 	return -EAGAIN;
351 }
352 
353 /*
354  * Find and lock a contiguous range of bytes in the file marked as delalloc, no
355  * more than @max_bytes.
356  *
357  * @start:	The original start bytenr to search.
358  *		Will store the extent range start bytenr.
359  * @end:	The original end bytenr of the search range
360  *		Will store the extent range end bytenr.
361  *
362  * Return true if we find a delalloc range which starts inside the original
363  * range, and @start/@end will store the delalloc range start/end.
364  *
365  * Return false if we can't find any delalloc range which starts inside the
366  * original range, and @start/@end will be the non-delalloc range start/end.
367  */
368 EXPORT_FOR_TESTS
369 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
370 						 struct folio *locked_folio,
371 						 u64 *start, u64 *end)
372 {
373 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
374 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
375 	const u64 orig_start = *start;
376 	const u64 orig_end = *end;
377 	u64 max_bytes = fs_info->max_extent_size;
378 	u64 delalloc_start;
379 	u64 delalloc_end;
380 	bool found;
381 	struct extent_state *cached_state = NULL;
382 	int ret;
383 	int loops = 0;
384 
385 	/* Caller should pass a valid @end to indicate the search range end */
386 	ASSERT(orig_end > orig_start);
387 
388 	/* The range should at least cover part of the folio */
389 	ASSERT(!(orig_start >= folio_next_pos(locked_folio) ||
390 		 orig_end <= folio_pos(locked_folio)));
391 again:
392 	/* step one, find a bunch of delalloc bytes starting at start */
393 	delalloc_start = *start;
394 	delalloc_end = 0;
395 
396 	/*
397 	 * If @max_bytes is smaller than a block, btrfs_find_delalloc_range() can
398 	 * return early without handling any dirty ranges.
399 	 */
400 	ASSERT(max_bytes >= fs_info->sectorsize);
401 
402 	found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
403 					  max_bytes, &cached_state);
404 	if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
405 		*start = delalloc_start;
406 
407 		/* @delalloc_end can be -1, never go beyond @orig_end */
408 		*end = min(delalloc_end, orig_end);
409 		btrfs_free_extent_state(cached_state);
410 		return false;
411 	}
412 
413 	/*
414 	 * start comes from the offset of locked_folio.  We have to lock
415 	 * folios in order, so we can't process delalloc bytes before
416 	 * locked_folio
417 	 */
418 	if (delalloc_start < *start)
419 		delalloc_start = *start;
420 
421 	/*
422 	 * make sure to limit the number of folios we try to lock down
423 	 */
424 	if (delalloc_end + 1 - delalloc_start > max_bytes)
425 		delalloc_end = delalloc_start + max_bytes - 1;
426 
427 	/* step two, lock all the folios after the folios that has start */
428 	ret = lock_delalloc_folios(inode, locked_folio, delalloc_start,
429 				   delalloc_end);
430 	ASSERT(!ret || ret == -EAGAIN);
431 	if (ret == -EAGAIN) {
432 		/*
433 		 * Some of the folios are gone, lets avoid looping by
434 		 * shortening the size of the delalloc range we're searching.
435 		 */
436 		btrfs_free_extent_state(cached_state);
437 		cached_state = NULL;
438 		if (!loops) {
439 			max_bytes = fs_info->sectorsize;
440 			loops = 1;
441 			goto again;
442 		} else {
443 			return false;
444 		}
445 	}
446 
447 	/* step three, lock the state bits for the whole range */
448 	btrfs_lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
449 
450 	/* then test to make sure it is all still delalloc */
451 	ret = btrfs_test_range_bit(tree, delalloc_start, delalloc_end,
452 				   EXTENT_DELALLOC, cached_state);
453 
454 	btrfs_unlock_extent(tree, delalloc_start, delalloc_end, &cached_state);
455 	if (!ret) {
456 		unlock_delalloc_folio(inode, locked_folio, delalloc_start,
457 				      delalloc_end);
458 		cond_resched();
459 		goto again;
460 	}
461 	*start = delalloc_start;
462 	*end = delalloc_end;
463 
464 	return found;
465 }
466 
467 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
468 				  const struct folio *locked_folio,
469 				  struct extent_state **cached,
470 				  u32 clear_bits, unsigned long page_ops)
471 {
472 	btrfs_clear_extent_bit(&inode->io_tree, start, end, clear_bits, cached);
473 
474 	__process_folios_contig(inode->vfs_inode.i_mapping, locked_folio, start,
475 				end, page_ops);
476 }
477 
478 static bool btrfs_verify_folio(struct fsverity_info *vi, struct folio *folio,
479 			       u64 start, u32 len)
480 {
481 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
482 
483 	if (!vi || btrfs_folio_test_uptodate(fs_info, folio, start, len))
484 		return true;
485 	return fsverity_verify_folio(vi, folio);
486 }
487 
488 static void end_folio_read(struct fsverity_info *vi, struct folio *folio,
489 			   bool uptodate, u64 start, u32 len)
490 {
491 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
492 
493 	ASSERT(folio_pos(folio) <= start &&
494 	       start + len <= folio_next_pos(folio));
495 
496 	if (uptodate && btrfs_verify_folio(vi, folio, start, len))
497 		btrfs_folio_set_uptodate(fs_info, folio, start, len);
498 	else
499 		btrfs_folio_clear_uptodate(fs_info, folio, start, len);
500 
501 	if (!btrfs_is_subpage(fs_info, folio))
502 		folio_unlock(folio);
503 	else
504 		btrfs_folio_end_lock(fs_info, folio, start, len);
505 }
506 
507 /*
508  * After a write IO is done, we need to:
509  *
510  * - clear the uptodate bits on error
511  * - clear the writeback bits in the extent tree for the range
512  * - filio_end_writeback()  if there is no more pending io for the folio
513  *
514  * Scheduling is not allowed, so the extent state tree is expected
515  * to have one and only one object corresponding to this IO.
516  */
517 static void end_bbio_data_write(struct btrfs_bio *bbio)
518 {
519 	struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
520 	struct bio *bio = &bbio->bio;
521 	int error = blk_status_to_errno(bio->bi_status);
522 	struct folio_iter fi;
523 	const u32 sectorsize = fs_info->sectorsize;
524 
525 	ASSERT(!bio_flagged(bio, BIO_CLONED));
526 	bio_for_each_folio_all(fi, bio) {
527 		struct folio *folio = fi.folio;
528 		u64 start = folio_pos(folio) + fi.offset;
529 		u32 len = fi.length;
530 
531 		/* Our read/write should always be sector aligned. */
532 		if (!IS_ALIGNED(fi.offset, sectorsize))
533 			btrfs_err(fs_info,
534 		"partial page write in btrfs with offset %zu and length %zu",
535 				  fi.offset, fi.length);
536 		else if (!IS_ALIGNED(fi.length, sectorsize))
537 			btrfs_info(fs_info,
538 		"incomplete page write with offset %zu and length %zu",
539 				   fi.offset, fi.length);
540 
541 		btrfs_finish_ordered_extent(bbio->ordered, folio, start, len,
542 					    !error);
543 		if (error)
544 			mapping_set_error(folio->mapping, error);
545 		btrfs_folio_clear_writeback(fs_info, folio, start, len);
546 	}
547 
548 	bio_put(bio);
549 }
550 
551 static void begin_folio_read(struct btrfs_fs_info *fs_info, struct folio *folio)
552 {
553 	ASSERT(folio_test_locked(folio));
554 	if (!btrfs_is_subpage(fs_info, folio))
555 		return;
556 
557 	ASSERT(folio_test_private(folio));
558 	btrfs_folio_set_lock(fs_info, folio, folio_pos(folio), folio_size(folio));
559 }
560 
561 /*
562  * After a data read IO is done, we need to:
563  *
564  * - clear the uptodate bits on error
565  * - set the uptodate bits if things worked
566  * - set the folio up to date if all extents in the tree are uptodate
567  * - clear the lock bit in the extent tree
568  * - unlock the folio if there are no other extents locked for it
569  *
570  * Scheduling is not allowed, so the extent state tree is expected
571  * to have one and only one object corresponding to this IO.
572  */
573 static void end_bbio_data_read(struct btrfs_bio *bbio)
574 {
575 	struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
576 	struct inode *inode = &bbio->inode->vfs_inode;
577 	struct bio *bio = &bbio->bio;
578 	struct fsverity_info *vi = NULL;
579 	struct folio_iter fi;
580 
581 	ASSERT(!bio_flagged(bio, BIO_CLONED));
582 
583 	if (bbio->file_offset < i_size_read(inode))
584 		vi = fsverity_get_info(inode);
585 
586 	bio_for_each_folio_all(fi, &bbio->bio) {
587 		bool uptodate = !bio->bi_status;
588 		struct folio *folio = fi.folio;
589 		u64 start = folio_pos(folio) + fi.offset;
590 
591 		btrfs_debug(fs_info,
592 			"%s: bi_sector=%llu, err=%d, mirror=%u",
593 			__func__, bio->bi_iter.bi_sector, bio->bi_status,
594 			bbio->mirror_num);
595 
596 
597 		if (likely(uptodate)) {
598 			u64 end = start + fi.length - 1;
599 			loff_t i_size = i_size_read(inode);
600 
601 			/*
602 			 * Zero out the remaining part if this range straddles
603 			 * i_size.
604 			 *
605 			 * Here we should only zero the range inside the folio,
606 			 * not touch anything else.
607 			 *
608 			 * NOTE: i_size is exclusive while end is inclusive and
609 			 * folio_contains() takes PAGE_SIZE units.
610 			 */
611 			if (folio_contains(folio, i_size >> PAGE_SHIFT) &&
612 			    i_size <= end) {
613 				u32 zero_start = max(offset_in_folio(folio, i_size),
614 						     offset_in_folio(folio, start));
615 				u32 zero_len = offset_in_folio(folio, end) + 1 -
616 					       zero_start;
617 
618 				folio_zero_range(folio, zero_start, zero_len);
619 			}
620 		}
621 
622 		/* Update page status and unlock. */
623 		end_folio_read(vi, folio, uptodate, start, fi.length);
624 	}
625 	bio_put(bio);
626 }
627 
628 /*
629  * Populate every free slot in a provided array with folios using GFP_NOFS.
630  *
631  * @nr_folios:   number of folios to allocate
632  * @order:	 the order of the folios to be allocated
633  * @folio_array: the array to fill with folios; any existing non-NULL entries in
634  *		 the array will be skipped
635  *
636  * Return: 0        if all folios were able to be allocated;
637  *         -ENOMEM  otherwise, the partially allocated folios would be freed and
638  *                  the array slots zeroed
639  */
640 int btrfs_alloc_folio_array(unsigned int nr_folios, unsigned int order,
641 			    struct folio **folio_array)
642 {
643 	for (int i = 0; i < nr_folios; i++) {
644 		if (folio_array[i])
645 			continue;
646 		folio_array[i] = folio_alloc(GFP_NOFS, order);
647 		if (!folio_array[i])
648 			goto error;
649 	}
650 	return 0;
651 error:
652 	for (int i = 0; i < nr_folios; i++) {
653 		if (folio_array[i])
654 			folio_put(folio_array[i]);
655 		folio_array[i] = NULL;
656 	}
657 	return -ENOMEM;
658 }
659 
660 /*
661  * Populate every free slot in a provided array with pages, using GFP_NOFS.
662  *
663  * @nr_pages:   number of pages to allocate
664  * @page_array: the array to fill with pages; any existing non-null entries in
665  *		the array will be skipped
666  * @nofail:	whether using __GFP_NOFAIL flag
667  *
668  * Return: 0        if all pages were able to be allocated;
669  *         -ENOMEM  otherwise, the partially allocated pages would be freed and
670  *                  the array slots zeroed
671  */
672 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
673 			   bool nofail)
674 {
675 	const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;
676 	unsigned int allocated;
677 
678 	for (allocated = 0; allocated < nr_pages;) {
679 		unsigned int last = allocated;
680 
681 		allocated = alloc_pages_bulk(gfp, nr_pages, page_array);
682 		if (unlikely(allocated == last)) {
683 			/* No progress, fail and do cleanup. */
684 			for (int i = 0; i < allocated; i++) {
685 				__free_page(page_array[i]);
686 				page_array[i] = NULL;
687 			}
688 			return -ENOMEM;
689 		}
690 	}
691 	return 0;
692 }
693 
694 /*
695  * Populate needed folios for the extent buffer.
696  *
697  * For now, the folios populated are always in order 0 (aka, single page).
698  */
699 static int alloc_eb_folio_array(struct extent_buffer *eb, bool nofail)
700 {
701 	struct page *page_array[INLINE_EXTENT_BUFFER_PAGES] = { 0 };
702 	int num_pages = num_extent_pages(eb);
703 	int ret;
704 
705 	ret = btrfs_alloc_page_array(num_pages, page_array, nofail);
706 	if (ret < 0)
707 		return ret;
708 
709 	for (int i = 0; i < num_pages; i++)
710 		eb->folios[i] = page_folio(page_array[i]);
711 	eb->folio_size = PAGE_SIZE;
712 	eb->folio_shift = PAGE_SHIFT;
713 	return 0;
714 }
715 
716 static bool btrfs_bio_is_contig(struct btrfs_bio_ctrl *bio_ctrl,
717 				u64 disk_bytenr, loff_t file_offset)
718 {
719 	struct bio *bio = &bio_ctrl->bbio->bio;
720 	const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
721 
722 	if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
723 		/*
724 		 * For compression, all IO should have its logical bytenr set
725 		 * to the starting bytenr of the compressed extent.
726 		 */
727 		return bio->bi_iter.bi_sector == sector;
728 	}
729 
730 	/*
731 	 * To merge into a bio both the disk sector and the logical offset in
732 	 * the file need to be contiguous.
733 	 */
734 	return bio_ctrl->next_file_offset == file_offset &&
735 		bio_end_sector(bio) == sector;
736 }
737 
738 static void alloc_new_bio(struct btrfs_inode *inode,
739 			  struct btrfs_bio_ctrl *bio_ctrl,
740 			  u64 disk_bytenr, u64 file_offset)
741 {
742 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
743 	struct btrfs_bio *bbio;
744 
745 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, bio_ctrl->opf, inode,
746 			       file_offset, bio_ctrl->end_io_func, NULL);
747 	bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
748 	bbio->bio.bi_write_hint = inode->vfs_inode.i_write_hint;
749 	bio_ctrl->bbio = bbio;
750 	bio_ctrl->len_to_oe_boundary = U32_MAX;
751 	bio_ctrl->next_file_offset = file_offset;
752 
753 	/* Limit data write bios to the ordered boundary. */
754 	if (bio_ctrl->wbc) {
755 		struct btrfs_ordered_extent *ordered;
756 
757 		ordered = btrfs_lookup_ordered_extent(inode, file_offset);
758 		if (ordered) {
759 			bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
760 					ordered->file_offset +
761 					ordered->disk_num_bytes - file_offset);
762 			bbio->ordered = ordered;
763 		}
764 
765 		/*
766 		 * Pick the last added device to support cgroup writeback.  For
767 		 * multi-device file systems this means blk-cgroup policies have
768 		 * to always be set on the last added/replaced device.
769 		 * This is a bit odd but has been like that for a long time.
770 		 */
771 		bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
772 		wbc_init_bio(bio_ctrl->wbc, &bbio->bio);
773 	}
774 }
775 
776 /*
777  * @disk_bytenr: logical bytenr where the write will be
778  * @page:	page to add to the bio
779  * @size:	portion of page that we want to write to
780  * @pg_offset:	offset of the new bio or to check whether we are adding
781  *              a contiguous page to the previous one
782  * @read_em_generation: generation of the extent_map we are submitting
783  *			(only used for read)
784  *
785  * The will either add the page into the existing @bio_ctrl->bbio, or allocate a
786  * new one in @bio_ctrl->bbio.
787  * The mirror number for this IO should already be initialized in
788  * @bio_ctrl->mirror_num.
789  */
790 static void submit_extent_folio(struct btrfs_bio_ctrl *bio_ctrl,
791 			       u64 disk_bytenr, struct folio *folio,
792 			       size_t size, unsigned long pg_offset,
793 			       u64 read_em_generation)
794 {
795 	struct btrfs_inode *inode = folio_to_inode(folio);
796 	loff_t file_offset = folio_pos(folio) + pg_offset;
797 
798 	ASSERT(pg_offset + size <= folio_size(folio));
799 	ASSERT(bio_ctrl->end_io_func);
800 
801 	if (bio_ctrl->bbio &&
802 	    !btrfs_bio_is_contig(bio_ctrl, disk_bytenr, file_offset))
803 		submit_one_bio(bio_ctrl);
804 
805 	do {
806 		u32 len = size;
807 
808 		/* Allocate new bio if needed */
809 		if (!bio_ctrl->bbio)
810 			alloc_new_bio(inode, bio_ctrl, disk_bytenr, file_offset);
811 
812 		/* Cap to the current ordered extent boundary if there is one. */
813 		if (len > bio_ctrl->len_to_oe_boundary) {
814 			ASSERT(bio_ctrl->compress_type == BTRFS_COMPRESS_NONE);
815 			ASSERT(is_data_inode(inode));
816 			len = bio_ctrl->len_to_oe_boundary;
817 		}
818 
819 		if (!bio_add_folio(&bio_ctrl->bbio->bio, folio, len, pg_offset)) {
820 			/* bio full: move on to a new one */
821 			submit_one_bio(bio_ctrl);
822 			continue;
823 		}
824 		/*
825 		 * Now that the folio is definitely added to the bio, include its
826 		 * generation in the max generation calculation.
827 		 */
828 		bio_ctrl->generation = max(bio_ctrl->generation, read_em_generation);
829 		bio_ctrl->next_file_offset += len;
830 
831 		if (bio_ctrl->wbc)
832 			wbc_account_cgroup_owner(bio_ctrl->wbc, folio, len);
833 
834 		size -= len;
835 		pg_offset += len;
836 		disk_bytenr += len;
837 		file_offset += len;
838 
839 		/*
840 		 * len_to_oe_boundary defaults to U32_MAX, which isn't folio or
841 		 * sector aligned.  alloc_new_bio() then sets it to the end of
842 		 * our ordered extent for writes into zoned devices.
843 		 *
844 		 * When len_to_oe_boundary is tracking an ordered extent, we
845 		 * trust the ordered extent code to align things properly, and
846 		 * the check above to cap our write to the ordered extent
847 		 * boundary is correct.
848 		 *
849 		 * When len_to_oe_boundary is U32_MAX, the cap above would
850 		 * result in a 4095 byte IO for the last folio right before
851 		 * we hit the bio limit of UINT_MAX.  bio_add_folio() has all
852 		 * the checks required to make sure we don't overflow the bio,
853 		 * and we should just ignore len_to_oe_boundary completely
854 		 * unless we're using it to track an ordered extent.
855 		 *
856 		 * It's pretty hard to make a bio sized U32_MAX, but it can
857 		 * happen when the page cache is able to feed us contiguous
858 		 * folios for large extents.
859 		 */
860 		if (bio_ctrl->len_to_oe_boundary != U32_MAX)
861 			bio_ctrl->len_to_oe_boundary -= len;
862 
863 		/* Ordered extent boundary: move on to a new bio. */
864 		if (bio_ctrl->len_to_oe_boundary == 0)
865 			submit_one_bio(bio_ctrl);
866 	} while (size);
867 }
868 
869 static int attach_extent_buffer_folio(struct extent_buffer *eb,
870 				      struct folio *folio,
871 				      struct btrfs_folio_state *prealloc)
872 {
873 	struct btrfs_fs_info *fs_info = eb->fs_info;
874 	int ret = 0;
875 
876 	/*
877 	 * If the page is mapped to btree inode, we should hold the private
878 	 * lock to prevent race.
879 	 * For cloned or dummy extent buffers, their pages are not mapped and
880 	 * will not race with any other ebs.
881 	 */
882 	if (folio->mapping)
883 		lockdep_assert_held(&folio->mapping->i_private_lock);
884 
885 	if (!btrfs_meta_is_subpage(fs_info)) {
886 		if (!folio_test_private(folio))
887 			folio_attach_private(folio, eb);
888 		else
889 			WARN_ON(folio_get_private(folio) != eb);
890 		return 0;
891 	}
892 
893 	/* Already mapped, just free prealloc */
894 	if (folio_test_private(folio)) {
895 		btrfs_free_folio_state(prealloc);
896 		return 0;
897 	}
898 
899 	if (prealloc)
900 		/* Has preallocated memory for subpage */
901 		folio_attach_private(folio, prealloc);
902 	else
903 		/* Do new allocation to attach subpage */
904 		ret = btrfs_attach_folio_state(fs_info, folio, BTRFS_SUBPAGE_METADATA);
905 	return ret;
906 }
907 
908 int set_folio_extent_mapped(struct folio *folio)
909 {
910 	struct btrfs_fs_info *fs_info;
911 
912 	ASSERT(folio->mapping);
913 
914 	if (folio_test_private(folio))
915 		return 0;
916 
917 	fs_info = folio_to_fs_info(folio);
918 
919 	if (btrfs_is_subpage(fs_info, folio))
920 		return btrfs_attach_folio_state(fs_info, folio, BTRFS_SUBPAGE_DATA);
921 
922 	folio_attach_private(folio, (void *)EXTENT_FOLIO_PRIVATE);
923 	return 0;
924 }
925 
926 void clear_folio_extent_mapped(struct folio *folio)
927 {
928 	struct btrfs_fs_info *fs_info;
929 
930 	ASSERT(folio->mapping);
931 
932 	if (!folio_test_private(folio))
933 		return;
934 
935 	fs_info = folio_to_fs_info(folio);
936 	if (btrfs_is_subpage(fs_info, folio))
937 		return btrfs_detach_folio_state(fs_info, folio, BTRFS_SUBPAGE_DATA);
938 
939 	folio_detach_private(folio);
940 }
941 
942 static struct extent_map *get_extent_map(struct btrfs_inode *inode,
943 					 struct folio *folio, u64 start,
944 					 u64 len, struct extent_map **em_cached)
945 {
946 	struct extent_map *em;
947 
948 	ASSERT(em_cached);
949 
950 	if (*em_cached) {
951 		em = *em_cached;
952 		if (btrfs_extent_map_in_tree(em) && start >= em->start &&
953 		    start < btrfs_extent_map_end(em)) {
954 			refcount_inc(&em->refs);
955 			return em;
956 		}
957 
958 		btrfs_free_extent_map(em);
959 		*em_cached = NULL;
960 	}
961 
962 	em = btrfs_get_extent(inode, folio, start, len);
963 	if (!IS_ERR(em)) {
964 		BUG_ON(*em_cached);
965 		refcount_inc(&em->refs);
966 		*em_cached = em;
967 	}
968 
969 	return em;
970 }
971 
972 static void btrfs_readahead_expand(struct readahead_control *ractl,
973 				   const struct extent_map *em)
974 {
975 	const u64 ra_pos = readahead_pos(ractl);
976 	const u64 ra_end = ra_pos + readahead_length(ractl);
977 	const u64 em_end = btrfs_extent_map_end(em);
978 
979 	/* No expansion for holes and inline extents. */
980 	if (em->disk_bytenr > EXTENT_MAP_LAST_BYTE)
981 		return;
982 
983 	ASSERT(em_end >= ra_pos,
984 	       "extent_map %llu %llu ends before current readahead position %llu",
985 	       em->start, em->len, ra_pos);
986 	if (em_end > ra_end)
987 		readahead_expand(ractl, ra_pos, em_end - ra_pos);
988 }
989 
990 /*
991  * basic readpage implementation.  Locked extent state structs are inserted
992  * into the tree that are removed when the IO is done (by the end_io
993  * handlers)
994  * XXX JDM: This needs looking at to ensure proper page locking
995  * return 0 on success, otherwise return error
996  */
997 static int btrfs_do_readpage(struct folio *folio, struct extent_map **em_cached,
998 			     struct btrfs_bio_ctrl *bio_ctrl,
999 			     struct fsverity_info *vi)
1000 {
1001 	struct inode *inode = folio->mapping->host;
1002 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
1003 	u64 start = folio_pos(folio);
1004 	const u64 end = start + folio_size(folio) - 1;
1005 	u64 extent_offset;
1006 	u64 locked_end;
1007 	u64 last_byte = i_size_read(inode);
1008 	struct extent_map *em;
1009 	int ret = 0;
1010 	const size_t blocksize = fs_info->sectorsize;
1011 
1012 	if (bio_ctrl->ractl)
1013 		locked_end = readahead_pos(bio_ctrl->ractl) + readahead_length(bio_ctrl->ractl) - 1;
1014 	else
1015 		locked_end = end;
1016 
1017 	ret = set_folio_extent_mapped(folio);
1018 	if (ret < 0) {
1019 		folio_unlock(folio);
1020 		return ret;
1021 	}
1022 
1023 	if (folio_contains(folio, last_byte >> PAGE_SHIFT)) {
1024 		size_t zero_offset = offset_in_folio(folio, last_byte);
1025 
1026 		if (zero_offset)
1027 			folio_zero_range(folio, zero_offset,
1028 					 folio_size(folio) - zero_offset);
1029 	}
1030 	bio_ctrl->end_io_func = end_bbio_data_read;
1031 	begin_folio_read(fs_info, folio);
1032 	for (u64 cur = start; cur <= end; cur += blocksize) {
1033 		enum btrfs_compression_type compress_type = BTRFS_COMPRESS_NONE;
1034 		unsigned long pg_offset = offset_in_folio(folio, cur);
1035 		bool force_bio_submit = false;
1036 		u64 disk_bytenr;
1037 		u64 block_start;
1038 		u64 em_gen;
1039 
1040 		ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1041 		if (cur >= last_byte) {
1042 			folio_zero_range(folio, pg_offset, end - cur + 1);
1043 			end_folio_read(vi, folio, true, cur, end - cur + 1);
1044 			break;
1045 		}
1046 		if (btrfs_folio_test_uptodate(fs_info, folio, cur, blocksize)) {
1047 			end_folio_read(vi, folio, true, cur, blocksize);
1048 			continue;
1049 		}
1050 		/*
1051 		 * Search extent map for the whole locked range.
1052 		 * This will allow btrfs_get_extent() to return a larger hole
1053 		 * when possible.
1054 		 * This can reduce duplicated btrfs_get_extent() calls for large
1055 		 * holes.
1056 		 */
1057 		em = get_extent_map(BTRFS_I(inode), folio, cur, locked_end - cur + 1, em_cached);
1058 		if (IS_ERR(em)) {
1059 			end_folio_read(vi, folio, false, cur, end + 1 - cur);
1060 			return PTR_ERR(em);
1061 		}
1062 		extent_offset = cur - em->start;
1063 		BUG_ON(btrfs_extent_map_end(em) <= cur);
1064 		BUG_ON(end < cur);
1065 
1066 		compress_type = btrfs_extent_map_compression(em);
1067 
1068 		/*
1069 		 * Only expand readahead for extents which are already creating
1070 		 * the pages anyway in add_ra_bio_pages, which is compressed
1071 		 * extents in the non subpage case.
1072 		 */
1073 		if (bio_ctrl->ractl &&
1074 		    !btrfs_is_subpage(fs_info, folio) &&
1075 		    compress_type != BTRFS_COMPRESS_NONE)
1076 			btrfs_readahead_expand(bio_ctrl->ractl, em);
1077 
1078 		if (compress_type != BTRFS_COMPRESS_NONE)
1079 			disk_bytenr = em->disk_bytenr;
1080 		else
1081 			disk_bytenr = btrfs_extent_map_block_start(em) + extent_offset;
1082 
1083 		if (em->flags & EXTENT_FLAG_PREALLOC)
1084 			block_start = EXTENT_MAP_HOLE;
1085 		else
1086 			block_start = btrfs_extent_map_block_start(em);
1087 
1088 		/*
1089 		 * If we have a file range that points to a compressed extent
1090 		 * and it's followed by a consecutive file range that points
1091 		 * to the same compressed extent (possibly with a different
1092 		 * offset and/or length, so it either points to the whole extent
1093 		 * or only part of it), we must make sure we do not submit a
1094 		 * single bio to populate the folios for the 2 ranges because
1095 		 * this makes the compressed extent read zero out the folios
1096 		 * belonging to the 2nd range. Imagine the following scenario:
1097 		 *
1098 		 *  File layout
1099 		 *  [0 - 8K]                     [8K - 24K]
1100 		 *    |                               |
1101 		 *    |                               |
1102 		 * points to extent X,         points to extent X,
1103 		 * offset 4K, length of 8K     offset 0, length 16K
1104 		 *
1105 		 * [extent X, compressed length = 4K uncompressed length = 16K]
1106 		 *
1107 		 * If the bio to read the compressed extent covers both ranges,
1108 		 * it will decompress extent X into the folios belonging to the
1109 		 * first range and then it will stop, zeroing out the remaining
1110 		 * folios that belong to the other range that points to extent X.
1111 		 * So here we make sure we submit 2 bios, one for the first
1112 		 * range and another one for the third range. Both will target
1113 		 * the same physical extent from disk, but we can't currently
1114 		 * make the compressed bio endio callback populate the folios
1115 		 * for both ranges because each compressed bio is tightly
1116 		 * coupled with a single extent map, and each range can have
1117 		 * an extent map with a different offset value relative to the
1118 		 * uncompressed data of our extent and different lengths. This
1119 		 * is a corner case so we prioritize correctness over
1120 		 * non-optimal behavior (submitting 2 bios for the same extent).
1121 		 */
1122 		if (compress_type != BTRFS_COMPRESS_NONE &&
1123 		    bio_ctrl->last_em_start != U64_MAX &&
1124 		    bio_ctrl->last_em_start != em->start)
1125 			force_bio_submit = true;
1126 
1127 		bio_ctrl->last_em_start = em->start;
1128 
1129 		em_gen = em->generation;
1130 		btrfs_free_extent_map(em);
1131 		em = NULL;
1132 
1133 		/* we've found a hole, just zero and go on */
1134 		if (block_start == EXTENT_MAP_HOLE) {
1135 			folio_zero_range(folio, pg_offset, blocksize);
1136 			end_folio_read(vi, folio, true, cur, blocksize);
1137 			continue;
1138 		}
1139 		/* the get_extent function already copied into the folio */
1140 		if (block_start == EXTENT_MAP_INLINE) {
1141 			end_folio_read(vi, folio, true, cur, blocksize);
1142 			continue;
1143 		}
1144 
1145 		if (bio_ctrl->compress_type != compress_type) {
1146 			submit_one_bio(bio_ctrl);
1147 			bio_ctrl->compress_type = compress_type;
1148 		}
1149 
1150 		if (force_bio_submit)
1151 			submit_one_bio(bio_ctrl);
1152 		submit_extent_folio(bio_ctrl, disk_bytenr, folio, blocksize,
1153 				    pg_offset, em_gen);
1154 	}
1155 	return 0;
1156 }
1157 
1158 /*
1159  * Check if we can skip waiting the @ordered extent covering the block at @fileoff.
1160  *
1161  * @fileoff:	Both input and output.
1162  *		Input as the file offset where the check should start at.
1163  *		Output as where the next check should start at,
1164  *		if the function returns true.
1165  *
1166  * Return true if we can skip to @fileoff. The caller needs to check the new
1167  * @fileoff value to make sure it covers the full range, before skipping the
1168  * full OE.
1169  *
1170  * Return false if we must wait for the ordered extent.
1171  */
1172 static bool can_skip_one_ordered_range(struct btrfs_inode *inode,
1173 				       struct btrfs_ordered_extent *ordered,
1174 				       u64 *fileoff)
1175 {
1176 	const struct btrfs_fs_info *fs_info = inode->root->fs_info;
1177 	struct folio *folio;
1178 	const u32 blocksize = fs_info->sectorsize;
1179 	u64 cur = *fileoff;
1180 	bool ret;
1181 
1182 	folio = filemap_get_folio(inode->vfs_inode.i_mapping, cur >> PAGE_SHIFT);
1183 
1184 	/*
1185 	 * We should have locked the folio(s) for range [start, end], thus
1186 	 * there must be a folio and it must be locked.
1187 	 */
1188 	ASSERT(!IS_ERR(folio));
1189 	ASSERT(folio_test_locked(folio));
1190 
1191 	/*
1192 	 * There are several cases for the folio and OE combination:
1193 	 *
1194 	 * 1) Folio has no private flag
1195 	 *    The OE has all its IO done but not yet finished, and folio got
1196 	 *    invalidated.
1197 	 *
1198 	 * Have we have to wait for the OE to finish, as it may contain the
1199 	 * to-be-inserted data checksum.
1200 	 * Without the data checksum inserted into the csum tree, read will
1201 	 * just fail with missing csum.
1202 	 */
1203 	if (!folio_test_private(folio)) {
1204 		ret = false;
1205 		goto out;
1206 	}
1207 
1208 	/*
1209 	 * 2) The first block is DIRTY.
1210 	 *
1211 	 * This means the OE is created by some other folios whose file pos is
1212 	 * before this one. And since we are holding the folio lock, the writeback
1213 	 * of this folio cannot start.
1214 	 *
1215 	 * We must skip the whole OE, because it will never start until we
1216 	 * finished our folio read and unlocked the folio.
1217 	 */
1218 	if (btrfs_folio_test_dirty(fs_info, folio, cur, blocksize)) {
1219 		u64 range_len = umin(folio_next_pos(folio),
1220 				    ordered->file_offset + ordered->num_bytes) - cur;
1221 
1222 		ret = true;
1223 		/*
1224 		 * At least inside the folio, all the remaining blocks should
1225 		 * also be dirty.
1226 		 */
1227 		ASSERT(btrfs_folio_test_dirty(fs_info, folio, cur, range_len));
1228 		*fileoff = ordered->file_offset + ordered->num_bytes;
1229 		goto out;
1230 	}
1231 
1232 	/*
1233 	 * 3) The first block is uptodate.
1234 	 *
1235 	 * At least the first block can be skipped, but we are still not fully
1236 	 * sure. E.g. if the OE has some other folios in the range that cannot
1237 	 * be skipped.
1238 	 * So we return true and update @next_ret to the OE/folio boundary.
1239 	 */
1240 	if (btrfs_folio_test_uptodate(fs_info, folio, cur, blocksize)) {
1241 		u64 range_len = umin(folio_next_pos(folio),
1242 				    ordered->file_offset + ordered->num_bytes) - cur;
1243 
1244 		/*
1245 		 * The whole range to the OE end or folio boundary should also
1246 		 * be uptodate.
1247 		 */
1248 		ASSERT(btrfs_folio_test_uptodate(fs_info, folio, cur, range_len));
1249 		ret = true;
1250 		*fileoff = cur + range_len;
1251 		goto out;
1252 	}
1253 
1254 	/*
1255 	 * 4) The first block is not uptodate.
1256 	 *
1257 	 * This means the folio is invalidated after the writeback was finished,
1258 	 * but by some other operations (e.g. block aligned buffered write) the
1259 	 * folio is inserted into filemap.
1260 	 * Very much the same as case 1).
1261 	 */
1262 	ret = false;
1263 out:
1264 	folio_put(folio);
1265 	return ret;
1266 }
1267 
1268 static bool can_skip_ordered_extent(struct btrfs_inode *inode,
1269 				    struct btrfs_ordered_extent *ordered,
1270 				    u64 start, u64 end)
1271 {
1272 	const u64 range_end = min(end, ordered->file_offset + ordered->num_bytes - 1);
1273 	u64 cur = max(start, ordered->file_offset);
1274 
1275 	while (cur < range_end) {
1276 		bool can_skip;
1277 
1278 		can_skip = can_skip_one_ordered_range(inode, ordered, &cur);
1279 		if (!can_skip)
1280 			return false;
1281 	}
1282 	return true;
1283 }
1284 
1285 /*
1286  * Locking helper to make sure we get a stable view of extent maps for the
1287  * involved range.
1288  *
1289  * This is for folio read paths (read and readahead), thus the involved range
1290  * should have all the folios locked.
1291  */
1292 static void lock_extents_for_read(struct btrfs_inode *inode, u64 start, u64 end,
1293 				  struct extent_state **cached_state)
1294 {
1295 	u64 cur_pos;
1296 
1297 	/* Caller must provide a valid @cached_state. */
1298 	ASSERT(cached_state);
1299 
1300 	/* The range must at least be page aligned, as all read paths are folio based. */
1301 	ASSERT(IS_ALIGNED(start, PAGE_SIZE));
1302 	ASSERT(IS_ALIGNED(end + 1, PAGE_SIZE));
1303 
1304 again:
1305 	btrfs_lock_extent(&inode->io_tree, start, end, cached_state);
1306 	cur_pos = start;
1307 	while (cur_pos < end) {
1308 		struct btrfs_ordered_extent *ordered;
1309 
1310 		ordered = btrfs_lookup_ordered_range(inode, cur_pos,
1311 						     end - cur_pos + 1);
1312 		/*
1313 		 * No ordered extents in the range, and we hold the extent lock,
1314 		 * no one can modify the extent maps in the range, we're safe to return.
1315 		 */
1316 		if (!ordered)
1317 			break;
1318 
1319 		/* Check if we can skip waiting for the whole OE. */
1320 		if (can_skip_ordered_extent(inode, ordered, start, end)) {
1321 			cur_pos = min(ordered->file_offset + ordered->num_bytes,
1322 				      end + 1);
1323 			btrfs_put_ordered_extent(ordered);
1324 			continue;
1325 		}
1326 
1327 		/* Now wait for the OE to finish. */
1328 		btrfs_unlock_extent(&inode->io_tree, start, end, cached_state);
1329 		btrfs_start_ordered_extent_nowriteback(ordered, start, end + 1 - start);
1330 		btrfs_put_ordered_extent(ordered);
1331 		/* We have unlocked the whole range, restart from the beginning. */
1332 		goto again;
1333 	}
1334 }
1335 
1336 int btrfs_read_folio(struct file *file, struct folio *folio)
1337 {
1338 	struct inode *vfs_inode = folio->mapping->host;
1339 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1340 	const u64 start = folio_pos(folio);
1341 	const u64 end = start + folio_size(folio) - 1;
1342 	struct extent_state *cached_state = NULL;
1343 	struct btrfs_bio_ctrl bio_ctrl = {
1344 		.opf = REQ_OP_READ,
1345 		.last_em_start = U64_MAX,
1346 	};
1347 	struct extent_map *em_cached = NULL;
1348 	struct fsverity_info *vi = NULL;
1349 	int ret;
1350 
1351 	lock_extents_for_read(inode, start, end, &cached_state);
1352 	if (folio_pos(folio) < i_size_read(vfs_inode))
1353 		vi = fsverity_get_info(vfs_inode);
1354 	ret = btrfs_do_readpage(folio, &em_cached, &bio_ctrl, vi);
1355 	btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
1356 
1357 	btrfs_free_extent_map(em_cached);
1358 
1359 	/*
1360 	 * If btrfs_do_readpage() failed we will want to submit the assembled
1361 	 * bio to do the cleanup.
1362 	 */
1363 	submit_one_bio(&bio_ctrl);
1364 	return ret;
1365 }
1366 
1367 static void set_delalloc_bitmap(struct folio *folio, unsigned long *delalloc_bitmap,
1368 				u64 start, u32 len)
1369 {
1370 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
1371 	const u64 folio_start = folio_pos(folio);
1372 	unsigned int start_bit;
1373 	unsigned int nbits;
1374 
1375 	ASSERT(start >= folio_start && start + len <= folio_start + folio_size(folio));
1376 	start_bit = (start - folio_start) >> fs_info->sectorsize_bits;
1377 	nbits = len >> fs_info->sectorsize_bits;
1378 	ASSERT(bitmap_test_range_all_zero(delalloc_bitmap, start_bit, nbits));
1379 	bitmap_set(delalloc_bitmap, start_bit, nbits);
1380 }
1381 
1382 static bool find_next_delalloc_bitmap(struct folio *folio,
1383 				      unsigned long *delalloc_bitmap, u64 start,
1384 				      u64 *found_start, u32 *found_len)
1385 {
1386 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
1387 	const u64 folio_start = folio_pos(folio);
1388 	const unsigned int bitmap_size = btrfs_blocks_per_folio(fs_info, folio);
1389 	unsigned int start_bit;
1390 	unsigned int first_zero;
1391 	unsigned int first_set;
1392 
1393 	ASSERT(start >= folio_start && start < folio_start + folio_size(folio));
1394 
1395 	start_bit = (start - folio_start) >> fs_info->sectorsize_bits;
1396 	first_set = find_next_bit(delalloc_bitmap, bitmap_size, start_bit);
1397 	if (first_set >= bitmap_size)
1398 		return false;
1399 
1400 	*found_start = folio_start + (first_set << fs_info->sectorsize_bits);
1401 	first_zero = find_next_zero_bit(delalloc_bitmap, bitmap_size, first_set);
1402 	*found_len = (first_zero - first_set) << fs_info->sectorsize_bits;
1403 	return true;
1404 }
1405 
1406 /*
1407  * Do all of the delayed allocation setup.
1408  *
1409  * Return >0 if all the dirty blocks are submitted async (compression) or inlined.
1410  * The @folio should no longer be touched (treat it as already unlocked).
1411  *
1412  * Return 0 if there is still dirty block that needs to be submitted through
1413  * extent_writepage_io().
1414  * bio_ctrl->submit_bitmap will indicate which blocks of the folio should be
1415  * submitted, and @folio is still kept locked.
1416  *
1417  * Return <0 if there is any error hit.
1418  * Any allocated ordered extent range covering this folio will be marked
1419  * finished (IOERR), and @folio is still kept locked.
1420  */
1421 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1422 						 struct folio *folio,
1423 						 struct btrfs_bio_ctrl *bio_ctrl)
1424 {
1425 	struct btrfs_fs_info *fs_info = inode_to_fs_info(&inode->vfs_inode);
1426 	struct writeback_control *wbc = bio_ctrl->wbc;
1427 	const bool is_subpage = btrfs_is_subpage(fs_info, folio);
1428 	const u64 page_start = folio_pos(folio);
1429 	const u64 page_end = page_start + folio_size(folio) - 1;
1430 	const unsigned int blocks_per_folio = btrfs_blocks_per_folio(fs_info, folio);
1431 	unsigned long delalloc_bitmap = 0;
1432 	/*
1433 	 * Save the last found delalloc end. As the delalloc end can go beyond
1434 	 * page boundary, thus we cannot rely on subpage bitmap to locate the
1435 	 * last delalloc end.
1436 	 */
1437 	u64 last_delalloc_end = 0;
1438 	/*
1439 	 * The range end (exclusive) of the last successfully finished delalloc
1440 	 * range.
1441 	 * Any range covered by ordered extent must either be manually marked
1442 	 * finished (error handling), or has IO submitted (and finish the
1443 	 * ordered extent normally).
1444 	 *
1445 	 * This records the end of ordered extent cleanup if we hit an error.
1446 	 */
1447 	u64 last_finished_delalloc_end = page_start;
1448 	u64 delalloc_start = page_start;
1449 	u64 delalloc_end = page_end;
1450 	u64 delalloc_to_write = 0;
1451 	unsigned int start_bit;
1452 	unsigned int end_bit;
1453 	int ret = 0;
1454 
1455 	/* Save the dirty bitmap as our submission bitmap will be a subset of it. */
1456 	if (btrfs_is_subpage(fs_info, folio)) {
1457 		ASSERT(blocks_per_folio > 1);
1458 		btrfs_get_subpage_dirty_bitmap(fs_info, folio, &bio_ctrl->submit_bitmap);
1459 	} else {
1460 		bio_ctrl->submit_bitmap = 1;
1461 	}
1462 
1463 	for_each_set_bitrange(start_bit, end_bit, &bio_ctrl->submit_bitmap,
1464 			      blocks_per_folio) {
1465 		u64 start = page_start + (start_bit << fs_info->sectorsize_bits);
1466 		u32 len = (end_bit - start_bit) << fs_info->sectorsize_bits;
1467 
1468 		btrfs_folio_set_lock(fs_info, folio, start, len);
1469 	}
1470 
1471 	/* Lock all (subpage) delalloc ranges inside the folio first. */
1472 	while (delalloc_start < page_end) {
1473 		delalloc_end = page_end;
1474 		if (!find_lock_delalloc_range(&inode->vfs_inode, folio,
1475 					      &delalloc_start, &delalloc_end)) {
1476 			delalloc_start = delalloc_end + 1;
1477 			continue;
1478 		}
1479 		set_delalloc_bitmap(folio, &delalloc_bitmap, delalloc_start,
1480 				    min(delalloc_end, page_end) + 1 - delalloc_start);
1481 		last_delalloc_end = delalloc_end;
1482 		delalloc_start = delalloc_end + 1;
1483 	}
1484 	delalloc_start = page_start;
1485 
1486 	if (!last_delalloc_end)
1487 		goto out;
1488 
1489 	/* Run the delalloc ranges for the above locked ranges. */
1490 	while (delalloc_start < page_end) {
1491 		u64 found_start;
1492 		u32 found_len;
1493 		bool found;
1494 
1495 		if (!is_subpage) {
1496 			/*
1497 			 * For non-subpage case, the found delalloc range must
1498 			 * cover this folio and there must be only one locked
1499 			 * delalloc range.
1500 			 */
1501 			found_start = page_start;
1502 			found_len = last_delalloc_end + 1 - found_start;
1503 			found = true;
1504 		} else {
1505 			found = find_next_delalloc_bitmap(folio, &delalloc_bitmap,
1506 					delalloc_start, &found_start, &found_len);
1507 		}
1508 		if (!found)
1509 			break;
1510 		/*
1511 		 * The subpage range covers the last sector, the delalloc range may
1512 		 * end beyond the folio boundary, use the saved delalloc_end
1513 		 * instead.
1514 		 */
1515 		if (found_start + found_len >= page_end)
1516 			found_len = last_delalloc_end + 1 - found_start;
1517 
1518 		if (ret >= 0) {
1519 			/*
1520 			 * Some delalloc range may be created by previous folios.
1521 			 * Thus we still need to clean up this range during error
1522 			 * handling.
1523 			 */
1524 			last_finished_delalloc_end = found_start;
1525 			/* No errors hit so far, run the current delalloc range. */
1526 			ret = btrfs_run_delalloc_range(inode, folio,
1527 						       found_start,
1528 						       found_start + found_len - 1,
1529 						       wbc);
1530 			if (ret >= 0)
1531 				last_finished_delalloc_end = found_start + found_len;
1532 			if (unlikely(ret < 0))
1533 				btrfs_err_rl(fs_info,
1534 "failed to run delalloc range, root=%lld ino=%llu folio=%llu submit_bitmap=%*pbl start=%llu len=%u: %d",
1535 					     btrfs_root_id(inode->root),
1536 					     btrfs_ino(inode),
1537 					     folio_pos(folio),
1538 					     blocks_per_folio,
1539 					     &bio_ctrl->submit_bitmap,
1540 					     found_start, found_len, ret);
1541 		} else {
1542 			/*
1543 			 * We've hit an error during previous delalloc range,
1544 			 * have to cleanup the remaining locked ranges.
1545 			 */
1546 			btrfs_unlock_extent(&inode->io_tree, found_start,
1547 					    found_start + found_len - 1, NULL);
1548 			unlock_delalloc_folio(&inode->vfs_inode, folio,
1549 					      found_start,
1550 					      found_start + found_len - 1);
1551 		}
1552 
1553 		/*
1554 		 * We have some ranges that's going to be submitted asynchronously
1555 		 * (compression or inline).  These range have their own control
1556 		 * on when to unlock the pages.  We should not touch them
1557 		 * anymore, so clear the range from the submission bitmap.
1558 		 */
1559 		if (ret > 0) {
1560 			unsigned int start_bit = (found_start - page_start) >>
1561 						 fs_info->sectorsize_bits;
1562 			unsigned int end_bit = (min(page_end + 1, found_start + found_len) -
1563 						page_start) >> fs_info->sectorsize_bits;
1564 			bitmap_clear(&bio_ctrl->submit_bitmap, start_bit, end_bit - start_bit);
1565 		}
1566 		/*
1567 		 * Above btrfs_run_delalloc_range() may have unlocked the folio,
1568 		 * thus for the last range, we cannot touch the folio anymore.
1569 		 */
1570 		if (found_start + found_len >= last_delalloc_end + 1)
1571 			break;
1572 
1573 		delalloc_start = found_start + found_len;
1574 	}
1575 	/*
1576 	 * It's possible we had some ordered extents created before we hit
1577 	 * an error, cleanup non-async successfully created delalloc ranges.
1578 	 */
1579 	if (unlikely(ret < 0)) {
1580 		unsigned int bitmap_size = min(
1581 				(last_finished_delalloc_end - page_start) >>
1582 				fs_info->sectorsize_bits,
1583 				blocks_per_folio);
1584 
1585 		for_each_set_bitrange(start_bit, end_bit, &bio_ctrl->submit_bitmap,
1586 				      bitmap_size) {
1587 			u64 start = page_start + (start_bit << fs_info->sectorsize_bits);
1588 			u32 len = (end_bit - start_bit) << fs_info->sectorsize_bits;
1589 
1590 			btrfs_mark_ordered_io_finished(inode, folio, start, len, false);
1591 		}
1592 		return ret;
1593 	}
1594 out:
1595 	if (last_delalloc_end)
1596 		delalloc_end = last_delalloc_end;
1597 	else
1598 		delalloc_end = page_end;
1599 	/*
1600 	 * delalloc_end is already one less than the total length, so
1601 	 * we don't subtract one from PAGE_SIZE.
1602 	 */
1603 	delalloc_to_write +=
1604 		DIV_ROUND_UP(delalloc_end + 1 - page_start, PAGE_SIZE);
1605 
1606 	/*
1607 	 * If all ranges are submitted asynchronously, we just need to account
1608 	 * for them here.
1609 	 */
1610 	if (bitmap_empty(&bio_ctrl->submit_bitmap, blocks_per_folio)) {
1611 		wbc->nr_to_write -= delalloc_to_write;
1612 		return 1;
1613 	}
1614 
1615 	if (wbc->nr_to_write < delalloc_to_write) {
1616 		int thresh = 8192;
1617 
1618 		if (delalloc_to_write < thresh * 2)
1619 			thresh = delalloc_to_write;
1620 		wbc->nr_to_write = min_t(u64, delalloc_to_write,
1621 					 thresh);
1622 	}
1623 
1624 	return 0;
1625 }
1626 
1627 /*
1628  * Return 0 if we have submitted or queued the sector for submission.
1629  * Return <0 for critical errors, and the involved sector will be cleaned up.
1630  *
1631  * Caller should make sure filepos < i_size and handle filepos >= i_size case.
1632  */
1633 static int submit_one_sector(struct btrfs_inode *inode,
1634 			     struct folio *folio,
1635 			     u64 filepos, struct btrfs_bio_ctrl *bio_ctrl,
1636 			     loff_t i_size)
1637 {
1638 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1639 	struct extent_map *em;
1640 	u64 block_start;
1641 	u64 disk_bytenr;
1642 	u64 extent_offset;
1643 	u64 em_end;
1644 	const u32 sectorsize = fs_info->sectorsize;
1645 
1646 	ASSERT(IS_ALIGNED(filepos, sectorsize));
1647 
1648 	/* @filepos >= i_size case should be handled by the caller. */
1649 	ASSERT(filepos < i_size);
1650 
1651 	em = btrfs_get_extent(inode, NULL, filepos, sectorsize);
1652 	if (IS_ERR(em)) {
1653 		/*
1654 		 * bio_ctrl may contain a bio crossing several folios.
1655 		 * Submit it immediately so that the bio has a chance
1656 		 * to finish normally, other than marked as error.
1657 		 */
1658 		submit_one_bio(bio_ctrl);
1659 
1660 		/*
1661 		 * When submission failed, we should still clear the folio dirty.
1662 		 * Or the folio will be written back again but without any
1663 		 * ordered extent.
1664 		 */
1665 		btrfs_folio_clear_dirty(fs_info, folio, filepos, sectorsize);
1666 		btrfs_folio_set_writeback(fs_info, folio, filepos, sectorsize);
1667 		btrfs_folio_clear_writeback(fs_info, folio, filepos, sectorsize);
1668 
1669 		/*
1670 		 * Since there is no bio submitted to finish the ordered
1671 		 * extent, we have to manually finish this sector.
1672 		 */
1673 		btrfs_mark_ordered_io_finished(inode, folio, filepos,
1674 					       fs_info->sectorsize, false);
1675 		return PTR_ERR(em);
1676 	}
1677 
1678 	extent_offset = filepos - em->start;
1679 	em_end = btrfs_extent_map_end(em);
1680 	ASSERT(filepos <= em_end);
1681 	ASSERT(IS_ALIGNED(em->start, sectorsize));
1682 	ASSERT(IS_ALIGNED(em->len, sectorsize));
1683 
1684 	block_start = btrfs_extent_map_block_start(em);
1685 	disk_bytenr = btrfs_extent_map_block_start(em) + extent_offset;
1686 
1687 	ASSERT(!btrfs_extent_map_is_compressed(em));
1688 	ASSERT(block_start != EXTENT_MAP_HOLE);
1689 	ASSERT(block_start != EXTENT_MAP_INLINE);
1690 
1691 	btrfs_free_extent_map(em);
1692 	em = NULL;
1693 
1694 	/*
1695 	 * Although the PageDirty bit is cleared before entering this
1696 	 * function, subpage dirty bit is not cleared.
1697 	 * So clear subpage dirty bit here so next time we won't submit
1698 	 * a folio for a range already written to disk.
1699 	 */
1700 	btrfs_folio_clear_dirty(fs_info, folio, filepos, sectorsize);
1701 	btrfs_folio_set_writeback(fs_info, folio, filepos, sectorsize);
1702 	/*
1703 	 * Above call should set the whole folio with writeback flag, even
1704 	 * just for a single subpage sector.
1705 	 * As long as the folio is properly locked and the range is correct,
1706 	 * we should always get the folio with writeback flag.
1707 	 */
1708 	ASSERT(folio_test_writeback(folio));
1709 
1710 	submit_extent_folio(bio_ctrl, disk_bytenr, folio,
1711 			    sectorsize, filepos - folio_pos(folio), 0);
1712 	return 0;
1713 }
1714 
1715 /*
1716  * Helper for extent_writepage().  This calls the writepage start hooks,
1717  * and does the loop to map the page into extents and bios.
1718  *
1719  * We return 1 if the IO is started and the page is unlocked,
1720  * 0 if all went well (page still locked)
1721  * < 0 if there were errors (page still locked)
1722  */
1723 static noinline_for_stack int extent_writepage_io(struct btrfs_inode *inode,
1724 						  struct folio *folio,
1725 						  u64 start, u32 len,
1726 						  struct btrfs_bio_ctrl *bio_ctrl,
1727 						  loff_t i_size)
1728 {
1729 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1730 	unsigned long range_bitmap = 0;
1731 	bool submitted_io = false;
1732 	int found_error = 0;
1733 	const u64 end = start + len;
1734 	const u64 folio_start = folio_pos(folio);
1735 	const u64 folio_end = folio_start + folio_size(folio);
1736 	const unsigned int blocks_per_folio = btrfs_blocks_per_folio(fs_info, folio);
1737 	u64 cur;
1738 	int bit;
1739 	int ret = 0;
1740 
1741 	ASSERT(start >= folio_start, "start=%llu folio_start=%llu", start, folio_start);
1742 	ASSERT(end <= folio_end, "start=%llu len=%u folio_start=%llu folio_size=%zu",
1743 	       start, len, folio_start, folio_size(folio));
1744 
1745 	ret = btrfs_writepage_cow_fixup(folio);
1746 	if (ret == -EAGAIN) {
1747 		/* Fixup worker will requeue */
1748 		folio_redirty_for_writepage(bio_ctrl->wbc, folio);
1749 		folio_unlock(folio);
1750 		return 1;
1751 	}
1752 	if (ret < 0) {
1753 		btrfs_folio_clear_dirty(fs_info, folio, start, len);
1754 		btrfs_folio_set_writeback(fs_info, folio, start, len);
1755 		btrfs_folio_clear_writeback(fs_info, folio, start, len);
1756 		return ret;
1757 	}
1758 
1759 	bitmap_set(&range_bitmap, (start - folio_pos(folio)) >> fs_info->sectorsize_bits,
1760 		   len >> fs_info->sectorsize_bits);
1761 	bitmap_and(&bio_ctrl->submit_bitmap, &bio_ctrl->submit_bitmap, &range_bitmap,
1762 		   blocks_per_folio);
1763 
1764 	bio_ctrl->end_io_func = end_bbio_data_write;
1765 
1766 	for_each_set_bit(bit, &bio_ctrl->submit_bitmap, blocks_per_folio) {
1767 		cur = folio_pos(folio) + (bit << fs_info->sectorsize_bits);
1768 
1769 		if (cur >= i_size) {
1770 			struct btrfs_ordered_extent *ordered;
1771 
1772 			ordered = btrfs_lookup_first_ordered_range(inode, cur,
1773 								   fs_info->sectorsize);
1774 			/*
1775 			 * We have just run delalloc before getting here, so
1776 			 * there must be an ordered extent.
1777 			 */
1778 			ASSERT(ordered != NULL);
1779 			spin_lock(&inode->ordered_tree_lock);
1780 			set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
1781 			ordered->truncated_len = min(ordered->truncated_len,
1782 						     cur - ordered->file_offset);
1783 			spin_unlock(&inode->ordered_tree_lock);
1784 			btrfs_put_ordered_extent(ordered);
1785 
1786 			btrfs_mark_ordered_io_finished(inode, folio, cur,
1787 						       fs_info->sectorsize, true);
1788 			/*
1789 			 * This range is beyond i_size, thus we don't need to
1790 			 * bother writing back.
1791 			 * But we still need to clear the dirty subpage bit, or
1792 			 * the next time the folio gets dirtied, we will try to
1793 			 * writeback the sectors with subpage dirty bits,
1794 			 * causing writeback without ordered extent.
1795 			 */
1796 			btrfs_folio_clear_dirty(fs_info, folio, cur, fs_info->sectorsize);
1797 			continue;
1798 		}
1799 		ret = submit_one_sector(inode, folio, cur, bio_ctrl, i_size);
1800 		if (unlikely(ret < 0)) {
1801 			if (!found_error)
1802 				found_error = ret;
1803 			continue;
1804 		}
1805 		submitted_io = true;
1806 	}
1807 
1808 	/*
1809 	 * If we didn't submitted any sector (>= i_size), folio dirty get
1810 	 * cleared but PAGECACHE_TAG_DIRTY is not cleared (only cleared
1811 	 * by folio_start_writeback() if the folio is not dirty).
1812 	 *
1813 	 * Here we set writeback and clear for the range. If the full folio
1814 	 * is no longer dirty then we clear the PAGECACHE_TAG_DIRTY tag.
1815 	 *
1816 	 * If we hit any error, the corresponding sector will have its dirty
1817 	 * flag cleared and writeback finished, thus no need to handle the error case.
1818 	 */
1819 	if (!submitted_io && !found_error) {
1820 		btrfs_folio_set_writeback(fs_info, folio, start, len);
1821 		btrfs_folio_clear_writeback(fs_info, folio, start, len);
1822 	}
1823 	return found_error;
1824 }
1825 
1826 /*
1827  * the writepage semantics are similar to regular writepage.  extent
1828  * records are inserted to lock ranges in the tree, and as dirty areas
1829  * are found, they are marked writeback.  Then the lock bits are removed
1830  * and the end_io handler clears the writeback ranges
1831  *
1832  * Return 0 if everything goes well.
1833  * Return <0 for error.
1834  */
1835 static int extent_writepage(struct folio *folio, struct btrfs_bio_ctrl *bio_ctrl)
1836 {
1837 	struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
1838 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1839 	int ret;
1840 	size_t pg_offset;
1841 	loff_t i_size = i_size_read(&inode->vfs_inode);
1842 	const pgoff_t end_index = i_size >> PAGE_SHIFT;
1843 	const unsigned int blocks_per_folio = btrfs_blocks_per_folio(fs_info, folio);
1844 
1845 	trace_extent_writepage(folio, &inode->vfs_inode, bio_ctrl->wbc);
1846 
1847 	WARN_ON(!folio_test_locked(folio));
1848 
1849 	pg_offset = offset_in_folio(folio, i_size);
1850 	if (folio->index > end_index ||
1851 	   (folio->index == end_index && !pg_offset)) {
1852 		folio_invalidate(folio, 0, folio_size(folio));
1853 		folio_unlock(folio);
1854 		return 0;
1855 	}
1856 
1857 	if (folio_contains(folio, end_index))
1858 		folio_zero_range(folio, pg_offset, folio_size(folio) - pg_offset);
1859 
1860 	/*
1861 	 * Default to unlock the whole folio.
1862 	 * The proper bitmap can only be initialized until writepage_delalloc().
1863 	 */
1864 	bio_ctrl->submit_bitmap = (unsigned long)-1;
1865 
1866 	/*
1867 	 * If the page is dirty but without private set, it's marked dirty
1868 	 * without informing the fs.
1869 	 * Nowadays that is a bug, since the introduction of
1870 	 * pin_user_pages*().
1871 	 *
1872 	 * So here we check if the page has private set to rule out such
1873 	 * case.
1874 	 * But we also have a long history of relying on the COW fixup,
1875 	 * so here we only enable this check for experimental builds until
1876 	 * we're sure it's safe.
1877 	 */
1878 	if (IS_ENABLED(CONFIG_BTRFS_EXPERIMENTAL) &&
1879 	    unlikely(!folio_test_private(folio))) {
1880 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
1881 		btrfs_err_rl(fs_info,
1882 	"root %lld ino %llu folio %llu is marked dirty without notifying the fs",
1883 			     btrfs_root_id(inode->root),
1884 			     btrfs_ino(inode), folio_pos(folio));
1885 		ret = -EUCLEAN;
1886 		goto done;
1887 	}
1888 
1889 	ret = set_folio_extent_mapped(folio);
1890 	if (ret < 0)
1891 		goto done;
1892 
1893 	ret = writepage_delalloc(inode, folio, bio_ctrl);
1894 	if (ret == 1)
1895 		return 0;
1896 	if (ret)
1897 		goto done;
1898 
1899 	ret = extent_writepage_io(inode, folio, folio_pos(folio),
1900 				  folio_size(folio), bio_ctrl, i_size);
1901 	if (ret == 1)
1902 		return 0;
1903 	if (unlikely(ret < 0))
1904 		btrfs_err_rl(fs_info,
1905 "failed to submit blocks, root=%lld inode=%llu folio=%llu submit_bitmap=%*pbl: %d",
1906 			     btrfs_root_id(inode->root), btrfs_ino(inode),
1907 			     folio_pos(folio), blocks_per_folio,
1908 			     &bio_ctrl->submit_bitmap, ret);
1909 
1910 	bio_ctrl->wbc->nr_to_write--;
1911 
1912 done:
1913 	if (ret < 0)
1914 		mapping_set_error(folio->mapping, ret);
1915 	/*
1916 	 * Only unlock ranges that are submitted. As there can be some async
1917 	 * submitted ranges inside the folio.
1918 	 */
1919 	btrfs_folio_end_lock_bitmap(fs_info, folio, bio_ctrl->submit_bitmap);
1920 	ASSERT(ret <= 0);
1921 	return ret;
1922 }
1923 
1924 /*
1925  * Lock extent buffer status and pages for writeback.
1926  *
1927  * Return %false if the extent buffer doesn't need to be submitted (e.g. the
1928  * extent buffer is not dirty)
1929  * Return %true is the extent buffer is submitted to bio.
1930  */
1931 static noinline_for_stack bool lock_extent_buffer_for_io(struct extent_buffer *eb,
1932 			  struct writeback_control *wbc)
1933 {
1934 	struct btrfs_fs_info *fs_info = eb->fs_info;
1935 	bool ret = false;
1936 
1937 	btrfs_tree_lock(eb);
1938 	while (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
1939 		btrfs_tree_unlock(eb);
1940 		if (wbc->sync_mode != WB_SYNC_ALL)
1941 			return false;
1942 		wait_on_extent_buffer_writeback(eb);
1943 		btrfs_tree_lock(eb);
1944 	}
1945 
1946 	/*
1947 	 * We need to do this to prevent races in people who check if the eb is
1948 	 * under IO since we can end up having no IO bits set for a short period
1949 	 * of time.
1950 	 */
1951 	spin_lock(&eb->refs_lock);
1952 	if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
1953 		XA_STATE(xas, &fs_info->buffer_tree, eb->start >> fs_info->nodesize_bits);
1954 		unsigned long flags;
1955 
1956 		set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
1957 		spin_unlock(&eb->refs_lock);
1958 
1959 		xas_lock_irqsave(&xas, flags);
1960 		xas_load(&xas);
1961 		xas_set_mark(&xas, PAGECACHE_TAG_WRITEBACK);
1962 		xas_clear_mark(&xas, PAGECACHE_TAG_DIRTY);
1963 		xas_clear_mark(&xas, PAGECACHE_TAG_TOWRITE);
1964 		xas_unlock_irqrestore(&xas, flags);
1965 
1966 		btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
1967 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1968 					 -eb->len,
1969 					 fs_info->dirty_metadata_batch);
1970 		ret = true;
1971 	} else {
1972 		spin_unlock(&eb->refs_lock);
1973 	}
1974 	btrfs_tree_unlock(eb);
1975 	return ret;
1976 }
1977 
1978 static void set_btree_ioerr(struct extent_buffer *eb)
1979 {
1980 	struct btrfs_fs_info *fs_info = eb->fs_info;
1981 
1982 	set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
1983 
1984 	/*
1985 	 * A read may stumble upon this buffer later, make sure that it gets an
1986 	 * error and knows there was an error.
1987 	 */
1988 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
1989 
1990 	/*
1991 	 * We need to set the mapping with the io error as well because a write
1992 	 * error will flip the file system readonly, and then syncfs() will
1993 	 * return a 0 because we are readonly if we don't modify the err seq for
1994 	 * the superblock.
1995 	 */
1996 	mapping_set_error(eb->fs_info->btree_inode->i_mapping, -EIO);
1997 
1998 	/*
1999 	 * If writeback for a btree extent that doesn't belong to a log tree
2000 	 * failed, increment the counter transaction->eb_write_errors.
2001 	 * We do this because while the transaction is running and before it's
2002 	 * committing (when we call filemap_fdata[write|wait]_range against
2003 	 * the btree inode), we might have
2004 	 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
2005 	 * returns an error or an error happens during writeback, when we're
2006 	 * committing the transaction we wouldn't know about it, since the pages
2007 	 * can be no longer dirty nor marked anymore for writeback (if a
2008 	 * subsequent modification to the extent buffer didn't happen before the
2009 	 * transaction commit), which makes filemap_fdata[write|wait]_range not
2010 	 * able to find the pages which contain errors at transaction
2011 	 * commit time. So if this happens we must abort the transaction,
2012 	 * otherwise we commit a super block with btree roots that point to
2013 	 * btree nodes/leafs whose content on disk is invalid - either garbage
2014 	 * or the content of some node/leaf from a past generation that got
2015 	 * cowed or deleted and is no longer valid.
2016 	 *
2017 	 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
2018 	 * not be enough - we need to distinguish between log tree extents vs
2019 	 * non-log tree extents, and the next filemap_fdatawait_range() call
2020 	 * will catch and clear such errors in the mapping - and that call might
2021 	 * be from a log sync and not from a transaction commit. Also, checking
2022 	 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
2023 	 * not done and would not be reliable - the eb might have been released
2024 	 * from memory and reading it back again means that flag would not be
2025 	 * set (since it's a runtime flag, not persisted on disk).
2026 	 *
2027 	 * Using the flags below in the btree inode also makes us achieve the
2028 	 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
2029 	 * writeback for all dirty pages and before filemap_fdatawait_range()
2030 	 * is called, the writeback for all dirty pages had already finished
2031 	 * with errors - because we were not using AS_EIO/AS_ENOSPC,
2032 	 * filemap_fdatawait_range() would return success, as it could not know
2033 	 * that writeback errors happened (the pages were no longer tagged for
2034 	 * writeback).
2035 	 */
2036 	switch (eb->log_index) {
2037 	case -1:
2038 		set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
2039 		break;
2040 	case 0:
2041 		set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2042 		break;
2043 	case 1:
2044 		set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2045 		break;
2046 	default:
2047 		BUG(); /* unexpected, logic error */
2048 	}
2049 }
2050 
2051 static void buffer_tree_set_mark(const struct extent_buffer *eb, xa_mark_t mark)
2052 {
2053 	struct btrfs_fs_info *fs_info = eb->fs_info;
2054 	XA_STATE(xas, &fs_info->buffer_tree, eb->start >> fs_info->nodesize_bits);
2055 	unsigned long flags;
2056 
2057 	xas_lock_irqsave(&xas, flags);
2058 	xas_load(&xas);
2059 	xas_set_mark(&xas, mark);
2060 	xas_unlock_irqrestore(&xas, flags);
2061 }
2062 
2063 static void buffer_tree_clear_mark(const struct extent_buffer *eb, xa_mark_t mark)
2064 {
2065 	struct btrfs_fs_info *fs_info = eb->fs_info;
2066 	XA_STATE(xas, &fs_info->buffer_tree, eb->start >> fs_info->nodesize_bits);
2067 	unsigned long flags;
2068 
2069 	xas_lock_irqsave(&xas, flags);
2070 	xas_load(&xas);
2071 	xas_clear_mark(&xas, mark);
2072 	xas_unlock_irqrestore(&xas, flags);
2073 }
2074 
2075 static void buffer_tree_tag_for_writeback(struct btrfs_fs_info *fs_info,
2076 					  unsigned long start, unsigned long end)
2077 {
2078 	XA_STATE(xas, &fs_info->buffer_tree, start);
2079 	unsigned int tagged = 0;
2080 	void *eb;
2081 
2082 	xas_lock_irq(&xas);
2083 	xas_for_each_marked(&xas, eb, end, PAGECACHE_TAG_DIRTY) {
2084 		xas_set_mark(&xas, PAGECACHE_TAG_TOWRITE);
2085 		if (++tagged % XA_CHECK_SCHED)
2086 			continue;
2087 		xas_pause(&xas);
2088 		xas_unlock_irq(&xas);
2089 		cond_resched();
2090 		xas_lock_irq(&xas);
2091 	}
2092 	xas_unlock_irq(&xas);
2093 }
2094 
2095 struct eb_batch {
2096 	unsigned int nr;
2097 	unsigned int cur;
2098 	struct extent_buffer *ebs[PAGEVEC_SIZE];
2099 };
2100 
2101 static inline bool eb_batch_add(struct eb_batch *batch, struct extent_buffer *eb)
2102 {
2103 	batch->ebs[batch->nr++] = eb;
2104 	return (batch->nr < PAGEVEC_SIZE);
2105 }
2106 
2107 static inline void eb_batch_init(struct eb_batch *batch)
2108 {
2109 	batch->nr = 0;
2110 	batch->cur = 0;
2111 }
2112 
2113 static inline struct extent_buffer *eb_batch_next(struct eb_batch *batch)
2114 {
2115 	if (batch->cur >= batch->nr)
2116 		return NULL;
2117 	return batch->ebs[batch->cur++];
2118 }
2119 
2120 static inline void eb_batch_release(struct eb_batch *batch)
2121 {
2122 	for (unsigned int i = 0; i < batch->nr; i++)
2123 		free_extent_buffer(batch->ebs[i]);
2124 	eb_batch_init(batch);
2125 }
2126 
2127 static inline struct extent_buffer *find_get_eb(struct xa_state *xas, unsigned long max,
2128 						xa_mark_t mark)
2129 {
2130 	struct extent_buffer *eb;
2131 
2132 retry:
2133 	eb = xas_find_marked(xas, max, mark);
2134 
2135 	if (xas_retry(xas, eb))
2136 		goto retry;
2137 
2138 	if (!eb)
2139 		return NULL;
2140 
2141 	if (!refcount_inc_not_zero(&eb->refs)) {
2142 		xas_reset(xas);
2143 		goto retry;
2144 	}
2145 
2146 	if (unlikely(eb != xas_reload(xas))) {
2147 		free_extent_buffer(eb);
2148 		xas_reset(xas);
2149 		goto retry;
2150 	}
2151 
2152 	return eb;
2153 }
2154 
2155 static unsigned int buffer_tree_get_ebs_tag(struct btrfs_fs_info *fs_info,
2156 					    unsigned long *start,
2157 					    unsigned long end, xa_mark_t tag,
2158 					    struct eb_batch *batch)
2159 {
2160 	XA_STATE(xas, &fs_info->buffer_tree, *start);
2161 	struct extent_buffer *eb;
2162 
2163 	rcu_read_lock();
2164 	while ((eb = find_get_eb(&xas, end, tag)) != NULL) {
2165 		if (!eb_batch_add(batch, eb)) {
2166 			*start = ((eb->start + eb->len) >> fs_info->nodesize_bits);
2167 			goto out;
2168 		}
2169 	}
2170 	if (end == ULONG_MAX)
2171 		*start = ULONG_MAX;
2172 	else
2173 		*start = end + 1;
2174 out:
2175 	rcu_read_unlock();
2176 
2177 	return batch->nr;
2178 }
2179 
2180 /*
2181  * The endio specific version which won't touch any unsafe spinlock in endio
2182  * context.
2183  */
2184 static struct extent_buffer *find_extent_buffer_nolock(
2185 		struct btrfs_fs_info *fs_info, u64 start)
2186 {
2187 	struct extent_buffer *eb;
2188 	unsigned long index = (start >> fs_info->nodesize_bits);
2189 
2190 	rcu_read_lock();
2191 	eb = xa_load(&fs_info->buffer_tree, index);
2192 	if (eb && !refcount_inc_not_zero(&eb->refs))
2193 		eb = NULL;
2194 	rcu_read_unlock();
2195 	return eb;
2196 }
2197 
2198 static void end_bbio_meta_write(struct btrfs_bio *bbio)
2199 {
2200 	struct extent_buffer *eb = bbio->private;
2201 	struct folio_iter fi;
2202 
2203 	if (bbio->bio.bi_status != BLK_STS_OK)
2204 		set_btree_ioerr(eb);
2205 
2206 	bio_for_each_folio_all(fi, &bbio->bio) {
2207 		btrfs_meta_folio_clear_writeback(fi.folio, eb);
2208 	}
2209 
2210 	buffer_tree_clear_mark(eb, PAGECACHE_TAG_WRITEBACK);
2211 	clear_and_wake_up_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2212 	bio_put(&bbio->bio);
2213 }
2214 
2215 static void prepare_eb_write(struct extent_buffer *eb)
2216 {
2217 	u32 nritems;
2218 	unsigned long start;
2219 	unsigned long end;
2220 
2221 	clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2222 
2223 	/* Set btree blocks beyond nritems with 0 to avoid stale content */
2224 	nritems = btrfs_header_nritems(eb);
2225 	if (btrfs_header_level(eb) > 0) {
2226 		end = btrfs_node_key_ptr_offset(eb, nritems);
2227 		memzero_extent_buffer(eb, end, eb->len - end);
2228 	} else {
2229 		/*
2230 		 * Leaf:
2231 		 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2232 		 */
2233 		start = btrfs_item_nr_offset(eb, nritems);
2234 		end = btrfs_item_nr_offset(eb, 0);
2235 		if (nritems == 0)
2236 			end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
2237 		else
2238 			end += btrfs_item_offset(eb, nritems - 1);
2239 		memzero_extent_buffer(eb, start, end - start);
2240 	}
2241 }
2242 
2243 static noinline_for_stack void write_one_eb(struct extent_buffer *eb,
2244 					    struct writeback_control *wbc)
2245 {
2246 	struct btrfs_fs_info *fs_info = eb->fs_info;
2247 	struct btrfs_bio *bbio;
2248 
2249 	prepare_eb_write(eb);
2250 
2251 	bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
2252 			       REQ_OP_WRITE | REQ_META | wbc_to_write_flags(wbc),
2253 			       BTRFS_I(fs_info->btree_inode), eb->start,
2254 			       end_bbio_meta_write, eb);
2255 	bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
2256 	bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
2257 	wbc_init_bio(wbc, &bbio->bio);
2258 	for (int i = 0; i < num_extent_folios(eb); i++) {
2259 		struct folio *folio = eb->folios[i];
2260 		u64 range_start = max_t(u64, eb->start, folio_pos(folio));
2261 		u32 range_len = min_t(u64, folio_next_pos(folio),
2262 				      eb->start + eb->len) - range_start;
2263 
2264 		folio_lock(folio);
2265 		btrfs_meta_folio_clear_dirty(folio, eb);
2266 		btrfs_meta_folio_set_writeback(folio, eb);
2267 		if (!folio_test_dirty(folio))
2268 			wbc->nr_to_write -= folio_nr_pages(folio);
2269 		bio_add_folio_nofail(&bbio->bio, folio, range_len,
2270 				     offset_in_folio(folio, range_start));
2271 		wbc_account_cgroup_owner(wbc, folio, range_len);
2272 		folio_unlock(folio);
2273 	}
2274 	/*
2275 	 * If the fs is already in error status, do not submit any writeback
2276 	 * but immediately finish it.
2277 	 */
2278 	if (unlikely(BTRFS_FS_ERROR(fs_info))) {
2279 		btrfs_bio_end_io(bbio, errno_to_blk_status(BTRFS_FS_ERROR(fs_info)));
2280 		return;
2281 	}
2282 	btrfs_submit_bbio(bbio, 0);
2283 }
2284 
2285 /*
2286  * Wait for all eb writeback in the given range to finish.
2287  *
2288  * @fs_info:	The fs_info for this file system.
2289  * @start:	The offset of the range to start waiting on writeback.
2290  * @end:	The end of the range, inclusive. This is meant to be used in
2291  *		conjunction with wait_marked_extents, so this will usually be
2292  *		the_next_eb->start - 1.
2293  */
2294 void btrfs_btree_wait_writeback_range(struct btrfs_fs_info *fs_info, u64 start,
2295 				      u64 end)
2296 {
2297 	struct eb_batch batch;
2298 	unsigned long start_index = (start >> fs_info->nodesize_bits);
2299 	unsigned long end_index = (end >> fs_info->nodesize_bits);
2300 
2301 	eb_batch_init(&batch);
2302 	while (start_index <= end_index) {
2303 		struct extent_buffer *eb;
2304 		unsigned int nr_ebs;
2305 
2306 		nr_ebs = buffer_tree_get_ebs_tag(fs_info, &start_index, end_index,
2307 						 PAGECACHE_TAG_WRITEBACK, &batch);
2308 		if (!nr_ebs)
2309 			break;
2310 
2311 		while ((eb = eb_batch_next(&batch)) != NULL)
2312 			wait_on_extent_buffer_writeback(eb);
2313 		eb_batch_release(&batch);
2314 		cond_resched();
2315 	}
2316 }
2317 
2318 int btree_writepages(struct address_space *mapping, struct writeback_control *wbc)
2319 {
2320 	struct btrfs_eb_write_context ctx = { .wbc = wbc };
2321 	struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
2322 	int ret = 0;
2323 	int done = 0;
2324 	int nr_to_write_done = 0;
2325 	struct eb_batch batch;
2326 	unsigned int nr_ebs;
2327 	unsigned long index;
2328 	unsigned long end;
2329 	int scanned = 0;
2330 	xa_mark_t tag;
2331 
2332 	eb_batch_init(&batch);
2333 	if (wbc->range_cyclic) {
2334 		index = ((mapping->writeback_index << PAGE_SHIFT) >> fs_info->nodesize_bits);
2335 		end = -1;
2336 
2337 		/*
2338 		 * Start from the beginning does not need to cycle over the
2339 		 * range, mark it as scanned.
2340 		 */
2341 		scanned = (index == 0);
2342 	} else {
2343 		index = (wbc->range_start >> fs_info->nodesize_bits);
2344 		end = (wbc->range_end >> fs_info->nodesize_bits);
2345 
2346 		scanned = 1;
2347 	}
2348 	if (wbc->sync_mode == WB_SYNC_ALL)
2349 		tag = PAGECACHE_TAG_TOWRITE;
2350 	else
2351 		tag = PAGECACHE_TAG_DIRTY;
2352 	btrfs_zoned_meta_io_lock(fs_info);
2353 retry:
2354 	if (wbc->sync_mode == WB_SYNC_ALL)
2355 		buffer_tree_tag_for_writeback(fs_info, index, end);
2356 	while (!done && !nr_to_write_done && (index <= end) &&
2357 	       (nr_ebs = buffer_tree_get_ebs_tag(fs_info, &index, end, tag, &batch))) {
2358 		struct extent_buffer *eb;
2359 
2360 		while ((eb = eb_batch_next(&batch)) != NULL) {
2361 			ctx.eb = eb;
2362 
2363 			ret = btrfs_check_meta_write_pointer(eb->fs_info, &ctx);
2364 			if (ret) {
2365 				if (ret == -EBUSY)
2366 					ret = 0;
2367 
2368 				if (ret) {
2369 					done = 1;
2370 					break;
2371 				}
2372 				continue;
2373 			}
2374 
2375 			if (!lock_extent_buffer_for_io(eb, wbc))
2376 				continue;
2377 
2378 			/* Implies write in zoned mode. */
2379 			if (ctx.zoned_bg) {
2380 				/* Mark the last eb in the block group. */
2381 				btrfs_schedule_zone_finish_bg(ctx.zoned_bg, eb);
2382 				ctx.zoned_bg->meta_write_pointer += eb->len;
2383 			}
2384 			write_one_eb(eb, wbc);
2385 		}
2386 		nr_to_write_done = (wbc->nr_to_write <= 0);
2387 		eb_batch_release(&batch);
2388 		cond_resched();
2389 	}
2390 	if (!scanned && !done) {
2391 		/*
2392 		 * We hit the last page and there is more work to be done: wrap
2393 		 * back to the start of the file
2394 		 */
2395 		scanned = 1;
2396 		index = 0;
2397 		goto retry;
2398 	}
2399 	/*
2400 	 * If something went wrong, don't allow any metadata write bio to be
2401 	 * submitted.
2402 	 *
2403 	 * This would prevent use-after-free if we had dirty pages not
2404 	 * cleaned up, which can still happen by fuzzed images.
2405 	 *
2406 	 * - Bad extent tree
2407 	 *   Allowing existing tree block to be allocated for other trees.
2408 	 *
2409 	 * - Log tree operations
2410 	 *   Exiting tree blocks get allocated to log tree, bumps its
2411 	 *   generation, then get cleaned in tree re-balance.
2412 	 *   Such tree block will not be written back, since it's clean,
2413 	 *   thus no WRITTEN flag set.
2414 	 *   And after log writes back, this tree block is not traced by
2415 	 *   any dirty extent_io_tree.
2416 	 *
2417 	 * - Offending tree block gets re-dirtied from its original owner
2418 	 *   Since it has bumped generation, no WRITTEN flag, it can be
2419 	 *   reused without COWing. This tree block will not be traced
2420 	 *   by btrfs_transaction::dirty_pages.
2421 	 *
2422 	 *   Now such dirty tree block will not be cleaned by any dirty
2423 	 *   extent io tree. Thus we don't want to submit such wild eb
2424 	 *   if the fs already has error.
2425 	 *
2426 	 * We can get ret > 0 from submit_extent_folio() indicating how many ebs
2427 	 * were submitted. Reset it to 0 to avoid false alerts for the caller.
2428 	 */
2429 	if (ret > 0)
2430 		ret = 0;
2431 	if (!ret && BTRFS_FS_ERROR(fs_info))
2432 		ret = -EROFS;
2433 
2434 	if (ctx.zoned_bg)
2435 		btrfs_put_block_group(ctx.zoned_bg);
2436 	btrfs_zoned_meta_io_unlock(fs_info);
2437 	return ret;
2438 }
2439 
2440 /*
2441  * Walk the list of dirty pages of the given address space and write all of them.
2442  *
2443  * @mapping:   address space structure to write
2444  * @wbc:       subtract the number of written pages from *@wbc->nr_to_write
2445  * @bio_ctrl:  holds context for the write, namely the bio
2446  *
2447  * If a page is already under I/O, write_cache_pages() skips it, even
2448  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
2449  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
2450  * and msync() need to guarantee that all the data which was dirty at the time
2451  * the call was made get new I/O started against them.  If wbc->sync_mode is
2452  * WB_SYNC_ALL then we were called for data integrity and we must wait for
2453  * existing IO to complete.
2454  */
2455 static int extent_write_cache_pages(struct address_space *mapping,
2456 			     struct btrfs_bio_ctrl *bio_ctrl)
2457 {
2458 	struct writeback_control *wbc = bio_ctrl->wbc;
2459 	struct inode *inode = mapping->host;
2460 	int ret = 0;
2461 	int done = 0;
2462 	int nr_to_write_done = 0;
2463 	struct folio_batch fbatch;
2464 	unsigned int nr_folios;
2465 	pgoff_t index;
2466 	pgoff_t end;		/* Inclusive */
2467 	pgoff_t done_index;
2468 	int range_whole = 0;
2469 	int scanned = 0;
2470 	xa_mark_t tag;
2471 
2472 	/*
2473 	 * We have to hold onto the inode so that ordered extents can do their
2474 	 * work when the IO finishes.  The alternative to this is failing to add
2475 	 * an ordered extent if the igrab() fails there and that is a huge pain
2476 	 * to deal with, so instead just hold onto the inode throughout the
2477 	 * writepages operation.  If it fails here we are freeing up the inode
2478 	 * anyway and we'd rather not waste our time writing out stuff that is
2479 	 * going to be truncated anyway.
2480 	 */
2481 	if (!igrab(inode))
2482 		return 0;
2483 
2484 	folio_batch_init(&fbatch);
2485 	if (wbc->range_cyclic) {
2486 		index = mapping->writeback_index; /* Start from prev offset */
2487 		end = -1;
2488 		/*
2489 		 * Start from the beginning does not need to cycle over the
2490 		 * range, mark it as scanned.
2491 		 */
2492 		scanned = (index == 0);
2493 	} else {
2494 		index = wbc->range_start >> PAGE_SHIFT;
2495 		end = wbc->range_end >> PAGE_SHIFT;
2496 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2497 			range_whole = 1;
2498 		scanned = 1;
2499 	}
2500 
2501 	/*
2502 	 * We do the tagged writepage as long as the snapshot flush bit is set
2503 	 * and we are the first one who do the filemap_flush() on this inode.
2504 	 *
2505 	 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
2506 	 * not race in and drop the bit.
2507 	 */
2508 	if (range_whole && wbc->nr_to_write == LONG_MAX &&
2509 	    test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
2510 			       &BTRFS_I(inode)->runtime_flags))
2511 		wbc->tagged_writepages = 1;
2512 
2513 	tag = wbc_to_tag(wbc);
2514 retry:
2515 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2516 		tag_pages_for_writeback(mapping, index, end);
2517 	done_index = index;
2518 	while (!done && !nr_to_write_done && (index <= end) &&
2519 			(nr_folios = filemap_get_folios_tag(mapping, &index,
2520 							end, tag, &fbatch))) {
2521 		unsigned i;
2522 
2523 		for (i = 0; i < nr_folios; i++) {
2524 			struct folio *folio = fbatch.folios[i];
2525 
2526 			done_index = folio_next_index(folio);
2527 			/*
2528 			 * At this point we hold neither the i_pages lock nor
2529 			 * the folio lock: the folio may be truncated or
2530 			 * invalidated (changing folio->mapping to NULL).
2531 			 */
2532 			if (!folio_trylock(folio)) {
2533 				submit_write_bio(bio_ctrl, 0);
2534 				folio_lock(folio);
2535 			}
2536 
2537 			if (unlikely(folio->mapping != mapping)) {
2538 				folio_unlock(folio);
2539 				continue;
2540 			}
2541 
2542 			if (!folio_test_dirty(folio)) {
2543 				/* Someone wrote it for us. */
2544 				folio_unlock(folio);
2545 				continue;
2546 			}
2547 
2548 			/*
2549 			 * For subpage case, compression can lead to mixed
2550 			 * writeback and dirty flags, e.g:
2551 			 * 0     32K    64K    96K    128K
2552 			 * |     |//////||/////|   |//|
2553 			 *
2554 			 * In above case, [32K, 96K) is asynchronously submitted
2555 			 * for compression, and [124K, 128K) needs to be written back.
2556 			 *
2557 			 * If we didn't wait writeback for page 64K, [128K, 128K)
2558 			 * won't be submitted as the page still has writeback flag
2559 			 * and will be skipped in the next check.
2560 			 *
2561 			 * This mixed writeback and dirty case is only possible for
2562 			 * subpage case.
2563 			 *
2564 			 * TODO: Remove this check after migrating compression to
2565 			 * regular submission.
2566 			 */
2567 			if (wbc->sync_mode != WB_SYNC_NONE ||
2568 			    btrfs_is_subpage(inode_to_fs_info(inode), folio)) {
2569 				if (folio_test_writeback(folio))
2570 					submit_write_bio(bio_ctrl, 0);
2571 				folio_wait_writeback(folio);
2572 			}
2573 
2574 			if (folio_test_writeback(folio) ||
2575 			    !folio_clear_dirty_for_io(folio)) {
2576 				folio_unlock(folio);
2577 				continue;
2578 			}
2579 
2580 			ret = extent_writepage(folio, bio_ctrl);
2581 			if (ret < 0) {
2582 				done = 1;
2583 				break;
2584 			}
2585 
2586 			/*
2587 			 * The filesystem may choose to bump up nr_to_write.
2588 			 * We have to make sure to honor the new nr_to_write
2589 			 * at any time.
2590 			 */
2591 			nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
2592 					    wbc->nr_to_write <= 0);
2593 		}
2594 		folio_batch_release(&fbatch);
2595 		cond_resched();
2596 	}
2597 	if (!scanned && !done) {
2598 		/*
2599 		 * We hit the last page and there is more work to be done: wrap
2600 		 * back to the start of the file
2601 		 */
2602 		scanned = 1;
2603 		index = 0;
2604 
2605 		/*
2606 		 * If we're looping we could run into a page that is locked by a
2607 		 * writer and that writer could be waiting on writeback for a
2608 		 * page in our current bio, and thus deadlock, so flush the
2609 		 * write bio here.
2610 		 */
2611 		submit_write_bio(bio_ctrl, 0);
2612 		goto retry;
2613 	}
2614 
2615 	if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
2616 		mapping->writeback_index = done_index;
2617 
2618 	btrfs_add_delayed_iput(BTRFS_I(inode));
2619 	return ret;
2620 }
2621 
2622 /*
2623  * Submit the pages in the range to bio for call sites which delalloc range has
2624  * already been ran (aka, ordered extent inserted) and all pages are still
2625  * locked.
2626  */
2627 void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio,
2628 			       u64 start, u64 end, struct writeback_control *wbc,
2629 			       bool pages_dirty)
2630 {
2631 	bool found_error = false;
2632 	int ret = 0;
2633 	struct address_space *mapping = inode->i_mapping;
2634 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2635 	const u32 sectorsize = fs_info->sectorsize;
2636 	loff_t i_size = i_size_read(inode);
2637 	u64 cur = start;
2638 	struct btrfs_bio_ctrl bio_ctrl = {
2639 		.wbc = wbc,
2640 		.opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2641 	};
2642 
2643 	if (wbc->no_cgroup_owner)
2644 		bio_ctrl.opf |= REQ_BTRFS_CGROUP_PUNT;
2645 
2646 	ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
2647 
2648 	while (cur <= end) {
2649 		u64 cur_end;
2650 		u32 cur_len;
2651 		struct folio *folio;
2652 
2653 		folio = filemap_get_folio(mapping, cur >> PAGE_SHIFT);
2654 
2655 		/*
2656 		 * This shouldn't happen, the pages are pinned and locked, this
2657 		 * code is just in case, but shouldn't actually be run.
2658 		 */
2659 		if (IS_ERR(folio)) {
2660 			cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
2661 			cur_len = cur_end + 1 - cur;
2662 			btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
2663 						       cur, cur_len, false);
2664 			mapping_set_error(mapping, PTR_ERR(folio));
2665 			cur = cur_end;
2666 			continue;
2667 		}
2668 
2669 		cur_end = min_t(u64, folio_next_pos(folio) - 1, end);
2670 		cur_len = cur_end + 1 - cur;
2671 
2672 		ASSERT(folio_test_locked(folio));
2673 		if (pages_dirty && folio != locked_folio)
2674 			ASSERT(folio_test_dirty(folio));
2675 
2676 		/*
2677 		 * Set the submission bitmap to submit all sectors.
2678 		 * extent_writepage_io() will do the truncation correctly.
2679 		 */
2680 		bio_ctrl.submit_bitmap = (unsigned long)-1;
2681 		ret = extent_writepage_io(BTRFS_I(inode), folio, cur, cur_len,
2682 					  &bio_ctrl, i_size);
2683 		if (ret == 1)
2684 			goto next_page;
2685 
2686 		if (ret)
2687 			mapping_set_error(mapping, ret);
2688 		btrfs_folio_end_lock(fs_info, folio, cur, cur_len);
2689 		if (ret < 0)
2690 			found_error = true;
2691 next_page:
2692 		folio_put(folio);
2693 		cur = cur_end + 1;
2694 	}
2695 
2696 	submit_write_bio(&bio_ctrl, found_error ? ret : 0);
2697 }
2698 
2699 int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
2700 {
2701 	struct inode *inode = mapping->host;
2702 	int ret = 0;
2703 	struct btrfs_bio_ctrl bio_ctrl = {
2704 		.wbc = wbc,
2705 		.opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
2706 	};
2707 
2708 	/*
2709 	 * Allow only a single thread to do the reloc work in zoned mode to
2710 	 * protect the write pointer updates.
2711 	 */
2712 	btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
2713 	ret = extent_write_cache_pages(mapping, &bio_ctrl);
2714 	submit_write_bio(&bio_ctrl, ret);
2715 	btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
2716 	return ret;
2717 }
2718 
2719 void btrfs_readahead(struct readahead_control *rac)
2720 {
2721 	struct btrfs_bio_ctrl bio_ctrl = {
2722 		.opf = REQ_OP_READ | REQ_RAHEAD,
2723 		.ractl = rac,
2724 		.last_em_start = U64_MAX,
2725 	};
2726 	struct folio *folio;
2727 	struct inode *vfs_inode = rac->mapping->host;
2728 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2729 	const u64 start = readahead_pos(rac);
2730 	const u64 end = start + readahead_length(rac) - 1;
2731 	struct extent_state *cached_state = NULL;
2732 	struct extent_map *em_cached = NULL;
2733 	struct fsverity_info *vi = NULL;
2734 
2735 	lock_extents_for_read(inode, start, end, &cached_state);
2736 	if (start < i_size_read(vfs_inode))
2737 		vi = fsverity_get_info(vfs_inode);
2738 	while ((folio = readahead_folio(rac)) != NULL)
2739 		btrfs_do_readpage(folio, &em_cached, &bio_ctrl, vi);
2740 
2741 	btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
2742 
2743 	if (em_cached)
2744 		btrfs_free_extent_map(em_cached);
2745 	submit_one_bio(&bio_ctrl);
2746 }
2747 
2748 /*
2749  * basic invalidate_folio code, this waits on any locked or writeback
2750  * ranges corresponding to the folio, and then deletes any extent state
2751  * records from the tree
2752  */
2753 int extent_invalidate_folio(struct extent_io_tree *tree,
2754 			  struct folio *folio, size_t offset)
2755 {
2756 	struct extent_state *cached_state = NULL;
2757 	u64 start = folio_pos(folio);
2758 	u64 end = start + folio_size(folio) - 1;
2759 	size_t blocksize = folio_to_fs_info(folio)->sectorsize;
2760 
2761 	/* This function is only called for the btree inode */
2762 	ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
2763 
2764 	start += ALIGN(offset, blocksize);
2765 	if (start > end)
2766 		return 0;
2767 
2768 	btrfs_lock_extent(tree, start, end, &cached_state);
2769 	folio_wait_writeback(folio);
2770 
2771 	/*
2772 	 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
2773 	 * so here we only need to unlock the extent range to free any
2774 	 * existing extent state.
2775 	 */
2776 	btrfs_unlock_extent(tree, start, end, &cached_state);
2777 	return 0;
2778 }
2779 
2780 /*
2781  * A helper for struct address_space_operations::release_folio, this tests for
2782  * areas of the folio that are locked or under IO and drops the related state
2783  * bits if it is safe to drop the folio.
2784  */
2785 static bool try_release_extent_state(struct extent_io_tree *tree,
2786 				     struct folio *folio)
2787 {
2788 	struct extent_state *cached_state = NULL;
2789 	u64 start = folio_pos(folio);
2790 	u64 end = start + folio_size(folio) - 1;
2791 	u32 range_bits;
2792 	u32 clear_bits;
2793 	bool ret = false;
2794 	int ret2;
2795 
2796 	btrfs_get_range_bits(tree, start, end, &range_bits, &cached_state);
2797 
2798 	/*
2799 	 * We can release the folio if it's locked only for ordered extent
2800 	 * completion, since that doesn't require using the folio.
2801 	 */
2802 	if ((range_bits & EXTENT_LOCKED) &&
2803 	    !(range_bits & EXTENT_FINISHING_ORDERED))
2804 		goto out;
2805 
2806 	clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW |
2807 		       EXTENT_CTLBITS | EXTENT_QGROUP_RESERVED |
2808 		       EXTENT_FINISHING_ORDERED);
2809 	/*
2810 	 * At this point we can safely clear everything except the locked,
2811 	 * nodatasum, delalloc new and finishing ordered bits. The delalloc new
2812 	 * bit will be cleared by ordered extent completion.
2813 	 */
2814 	ret2 = btrfs_clear_extent_bit(tree, start, end, clear_bits, &cached_state);
2815 	/*
2816 	 * If clear_extent_bit failed for enomem reasons, we can't allow the
2817 	 * release to continue.
2818 	 */
2819 	if (ret2 == 0)
2820 		ret = true;
2821 out:
2822 	btrfs_free_extent_state(cached_state);
2823 
2824 	return ret;
2825 }
2826 
2827 /*
2828  * a helper for release_folio.  As long as there are no locked extents
2829  * in the range corresponding to the page, both state records and extent
2830  * map records are removed
2831  */
2832 bool try_release_extent_mapping(struct folio *folio, gfp_t mask)
2833 {
2834 	u64 start = folio_pos(folio);
2835 	u64 end = start + folio_size(folio) - 1;
2836 	struct btrfs_inode *inode = folio_to_inode(folio);
2837 	struct extent_io_tree *io_tree = &inode->io_tree;
2838 
2839 	while (start <= end) {
2840 		const u64 cur_gen = btrfs_get_fs_generation(inode->root->fs_info);
2841 		const u64 len = end - start + 1;
2842 		struct extent_map_tree *extent_tree = &inode->extent_tree;
2843 		struct extent_map *em;
2844 
2845 		write_lock(&extent_tree->lock);
2846 		em = btrfs_lookup_extent_mapping(extent_tree, start, len);
2847 		if (!em) {
2848 			write_unlock(&extent_tree->lock);
2849 			break;
2850 		}
2851 		if ((em->flags & EXTENT_FLAG_PINNED) || em->start != start) {
2852 			write_unlock(&extent_tree->lock);
2853 			btrfs_free_extent_map(em);
2854 			break;
2855 		}
2856 		if (btrfs_test_range_bit_exists(io_tree, em->start,
2857 						btrfs_extent_map_end(em) - 1,
2858 						EXTENT_LOCKED))
2859 			goto next;
2860 		/*
2861 		 * If it's not in the list of modified extents, used by a fast
2862 		 * fsync, we can remove it. If it's being logged we can safely
2863 		 * remove it since fsync took an extra reference on the em.
2864 		 */
2865 		if (list_empty(&em->list) || (em->flags & EXTENT_FLAG_LOGGING))
2866 			goto remove_em;
2867 		/*
2868 		 * If it's in the list of modified extents, remove it only if
2869 		 * its generation is older then the current one, in which case
2870 		 * we don't need it for a fast fsync. Otherwise don't remove it,
2871 		 * we could be racing with an ongoing fast fsync that could miss
2872 		 * the new extent.
2873 		 */
2874 		if (em->generation >= cur_gen)
2875 			goto next;
2876 remove_em:
2877 		/*
2878 		 * We only remove extent maps that are not in the list of
2879 		 * modified extents or that are in the list but with a
2880 		 * generation lower then the current generation, so there is no
2881 		 * need to set the full fsync flag on the inode (it hurts the
2882 		 * fsync performance for workloads with a data size that exceeds
2883 		 * or is close to the system's memory).
2884 		 */
2885 		btrfs_remove_extent_mapping(inode, em);
2886 		/* Once for the inode's extent map tree. */
2887 		btrfs_free_extent_map(em);
2888 next:
2889 		start = btrfs_extent_map_end(em);
2890 		write_unlock(&extent_tree->lock);
2891 
2892 		/* Once for us, for the lookup_extent_mapping() reference. */
2893 		btrfs_free_extent_map(em);
2894 
2895 		if (need_resched()) {
2896 			/*
2897 			 * If we need to resched but we can't block just exit
2898 			 * and leave any remaining extent maps.
2899 			 */
2900 			if (!gfpflags_allow_blocking(mask))
2901 				break;
2902 
2903 			cond_resched();
2904 		}
2905 	}
2906 	return try_release_extent_state(io_tree, folio);
2907 }
2908 
2909 static int extent_buffer_under_io(const struct extent_buffer *eb)
2910 {
2911 	return (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
2912 		test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
2913 }
2914 
2915 static bool folio_range_has_eb(struct folio *folio)
2916 {
2917 	struct btrfs_folio_state *bfs;
2918 
2919 	lockdep_assert_held(&folio->mapping->i_private_lock);
2920 
2921 	if (folio_test_private(folio)) {
2922 		bfs = folio_get_private(folio);
2923 		if (atomic_read(&bfs->eb_refs))
2924 			return true;
2925 	}
2926 	return false;
2927 }
2928 
2929 static void detach_extent_buffer_folio(const struct extent_buffer *eb, struct folio *folio)
2930 {
2931 	struct btrfs_fs_info *fs_info = eb->fs_info;
2932 	struct address_space *mapping = folio->mapping;
2933 	const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
2934 
2935 	/*
2936 	 * For mapped eb, we're going to change the folio private, which should
2937 	 * be done under the i_private_lock.
2938 	 */
2939 	if (mapped)
2940 		spin_lock(&mapping->i_private_lock);
2941 
2942 	if (!folio_test_private(folio)) {
2943 		if (mapped)
2944 			spin_unlock(&mapping->i_private_lock);
2945 		return;
2946 	}
2947 
2948 	if (!btrfs_meta_is_subpage(fs_info)) {
2949 		/*
2950 		 * We do this since we'll remove the pages after we've removed
2951 		 * the eb from the xarray, so we could race and have this page
2952 		 * now attached to the new eb.  So only clear folio if it's
2953 		 * still connected to this eb.
2954 		 */
2955 		if (folio_test_private(folio) && folio_get_private(folio) == eb) {
2956 			BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
2957 			BUG_ON(folio_test_dirty(folio));
2958 			BUG_ON(folio_test_writeback(folio));
2959 			/* We need to make sure we haven't be attached to a new eb. */
2960 			folio_detach_private(folio);
2961 		}
2962 		if (mapped)
2963 			spin_unlock(&mapping->i_private_lock);
2964 		return;
2965 	}
2966 
2967 	/*
2968 	 * For subpage, we can have dummy eb with folio private attached.  In
2969 	 * this case, we can directly detach the private as such folio is only
2970 	 * attached to one dummy eb, no sharing.
2971 	 */
2972 	if (!mapped) {
2973 		btrfs_detach_folio_state(fs_info, folio, BTRFS_SUBPAGE_METADATA);
2974 		return;
2975 	}
2976 
2977 	btrfs_folio_dec_eb_refs(fs_info, folio);
2978 
2979 	/*
2980 	 * We can only detach the folio private if there are no other ebs in the
2981 	 * page range and no unfinished IO.
2982 	 */
2983 	if (!folio_range_has_eb(folio))
2984 		btrfs_detach_folio_state(fs_info, folio, BTRFS_SUBPAGE_METADATA);
2985 
2986 	spin_unlock(&mapping->i_private_lock);
2987 }
2988 
2989 /* Release all folios attached to the extent buffer */
2990 static void btrfs_release_extent_buffer_folios(const struct extent_buffer *eb)
2991 {
2992 	ASSERT(!extent_buffer_under_io(eb));
2993 
2994 	for (int i = 0; i < INLINE_EXTENT_BUFFER_PAGES; i++) {
2995 		struct folio *folio = eb->folios[i];
2996 
2997 		if (!folio)
2998 			continue;
2999 
3000 		detach_extent_buffer_folio(eb, folio);
3001 	}
3002 }
3003 
3004 /*
3005  * Helper for releasing the extent buffer.
3006  */
3007 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
3008 {
3009 	btrfs_release_extent_buffer_folios(eb);
3010 	btrfs_leak_debug_del_eb(eb);
3011 	kmem_cache_free(extent_buffer_cache, eb);
3012 }
3013 
3014 static struct extent_buffer *__alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3015 						   u64 start)
3016 {
3017 	struct extent_buffer *eb = NULL;
3018 
3019 	eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
3020 	eb->start = start;
3021 	eb->len = fs_info->nodesize;
3022 	eb->fs_info = fs_info;
3023 	init_rwsem(&eb->lock);
3024 
3025 	btrfs_leak_debug_add_eb(eb);
3026 
3027 	spin_lock_init(&eb->refs_lock);
3028 	refcount_set(&eb->refs, 1);
3029 
3030 	ASSERT(eb->len <= BTRFS_MAX_METADATA_BLOCKSIZE);
3031 
3032 	return eb;
3033 }
3034 
3035 /*
3036  * For use in eb allocation error cleanup paths, as btrfs_release_extent_buffer()
3037  * does not call folio_put(), and we need to set the folios to NULL so that
3038  * btrfs_release_extent_buffer() will not detach them a second time.
3039  */
3040 static void cleanup_extent_buffer_folios(struct extent_buffer *eb)
3041 {
3042 	const int num_folios = num_extent_folios(eb);
3043 
3044 	/* We cannot use num_extent_folios() as loop bound as eb->folios changes. */
3045 	for (int i = 0; i < num_folios; i++) {
3046 		ASSERT(eb->folios[i]);
3047 		detach_extent_buffer_folio(eb, eb->folios[i]);
3048 		folio_put(eb->folios[i]);
3049 		eb->folios[i] = NULL;
3050 	}
3051 }
3052 
3053 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
3054 {
3055 	struct extent_buffer *new;
3056 	int num_folios;
3057 	int ret;
3058 
3059 	new = __alloc_extent_buffer(src->fs_info, src->start);
3060 	if (new == NULL)
3061 		return NULL;
3062 
3063 	/*
3064 	 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
3065 	 * btrfs_release_extent_buffer() have different behavior for
3066 	 * UNMAPPED subpage extent buffer.
3067 	 */
3068 	set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
3069 
3070 	ret = alloc_eb_folio_array(new, false);
3071 	if (ret)
3072 		goto release_eb;
3073 
3074 	ASSERT(num_extent_folios(src) == num_extent_folios(new),
3075 	       "%d != %d", num_extent_folios(src), num_extent_folios(new));
3076 	/* Explicitly use the cached num_extent value from now on. */
3077 	num_folios = num_extent_folios(src);
3078 	for (int i = 0; i < num_folios; i++) {
3079 		struct folio *folio = new->folios[i];
3080 
3081 		ret = attach_extent_buffer_folio(new, folio, NULL);
3082 		if (ret < 0)
3083 			goto cleanup_folios;
3084 		WARN_ON(folio_test_dirty(folio));
3085 	}
3086 	for (int i = 0; i < num_folios; i++)
3087 		folio_put(new->folios[i]);
3088 
3089 	copy_extent_buffer_full(new, src);
3090 	set_extent_buffer_uptodate(new);
3091 
3092 	return new;
3093 
3094 cleanup_folios:
3095 	cleanup_extent_buffer_folios(new);
3096 release_eb:
3097 	btrfs_release_extent_buffer(new);
3098 	return NULL;
3099 }
3100 
3101 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
3102 						u64 start)
3103 {
3104 	struct extent_buffer *eb;
3105 	int ret;
3106 
3107 	eb = __alloc_extent_buffer(fs_info, start);
3108 	if (!eb)
3109 		return NULL;
3110 
3111 	ret = alloc_eb_folio_array(eb, false);
3112 	if (ret)
3113 		goto release_eb;
3114 
3115 	for (int i = 0; i < num_extent_folios(eb); i++) {
3116 		ret = attach_extent_buffer_folio(eb, eb->folios[i], NULL);
3117 		if (ret < 0)
3118 			goto cleanup_folios;
3119 	}
3120 	for (int i = 0; i < num_extent_folios(eb); i++)
3121 		folio_put(eb->folios[i]);
3122 
3123 	set_extent_buffer_uptodate(eb);
3124 	btrfs_set_header_nritems(eb, 0);
3125 	set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
3126 
3127 	return eb;
3128 
3129 cleanup_folios:
3130 	cleanup_extent_buffer_folios(eb);
3131 release_eb:
3132 	btrfs_release_extent_buffer(eb);
3133 	return NULL;
3134 }
3135 
3136 static void check_buffer_tree_ref(struct extent_buffer *eb)
3137 {
3138 	int refs;
3139 	/*
3140 	 * The TREE_REF bit is first set when the extent_buffer is added to the
3141 	 * xarray. It is also reset, if unset, when a new reference is created
3142 	 * by find_extent_buffer.
3143 	 *
3144 	 * It is only cleared in two cases: freeing the last non-tree
3145 	 * reference to the extent_buffer when its STALE bit is set or
3146 	 * calling release_folio when the tree reference is the only reference.
3147 	 *
3148 	 * In both cases, care is taken to ensure that the extent_buffer's
3149 	 * pages are not under io. However, release_folio can be concurrently
3150 	 * called with creating new references, which is prone to race
3151 	 * conditions between the calls to check_buffer_tree_ref in those
3152 	 * codepaths and clearing TREE_REF in try_release_extent_buffer.
3153 	 *
3154 	 * The actual lifetime of the extent_buffer in the xarray is adequately
3155 	 * protected by the refcount, but the TREE_REF bit and its corresponding
3156 	 * reference are not. To protect against this class of races, we call
3157 	 * check_buffer_tree_ref() from the code paths which trigger io. Note that
3158 	 * once io is initiated, TREE_REF can no longer be cleared, so that is
3159 	 * the moment at which any such race is best fixed.
3160 	 */
3161 	refs = refcount_read(&eb->refs);
3162 	if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3163 		return;
3164 
3165 	spin_lock(&eb->refs_lock);
3166 	if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3167 		refcount_inc(&eb->refs);
3168 	spin_unlock(&eb->refs_lock);
3169 }
3170 
3171 static void mark_extent_buffer_accessed(struct extent_buffer *eb)
3172 {
3173 	check_buffer_tree_ref(eb);
3174 
3175 	for (int i = 0; i < num_extent_folios(eb); i++)
3176 		folio_mark_accessed(eb->folios[i]);
3177 }
3178 
3179 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
3180 					 u64 start)
3181 {
3182 	struct extent_buffer *eb;
3183 
3184 	eb = find_extent_buffer_nolock(fs_info, start);
3185 	if (!eb)
3186 		return NULL;
3187 	/*
3188 	 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
3189 	 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
3190 	 * another task running free_extent_buffer() might have seen that flag
3191 	 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
3192 	 * writeback flags not set) and it's still in the tree (flag
3193 	 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
3194 	 * decrementing the extent buffer's reference count twice.  So here we
3195 	 * could race and increment the eb's reference count, clear its stale
3196 	 * flag, mark it as dirty and drop our reference before the other task
3197 	 * finishes executing free_extent_buffer, which would later result in
3198 	 * an attempt to free an extent buffer that is dirty.
3199 	 */
3200 	if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
3201 		spin_lock(&eb->refs_lock);
3202 		spin_unlock(&eb->refs_lock);
3203 	}
3204 	mark_extent_buffer_accessed(eb);
3205 	return eb;
3206 }
3207 
3208 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
3209 					u64 start)
3210 {
3211 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3212 	struct extent_buffer *eb, *exists = NULL;
3213 	int ret;
3214 
3215 	eb = find_extent_buffer(fs_info, start);
3216 	if (eb)
3217 		return eb;
3218 	eb = alloc_dummy_extent_buffer(fs_info, start);
3219 	if (!eb)
3220 		return ERR_PTR(-ENOMEM);
3221 	eb->fs_info = fs_info;
3222 again:
3223 	xa_lock_irq(&fs_info->buffer_tree);
3224 	exists = __xa_cmpxchg(&fs_info->buffer_tree, start >> fs_info->nodesize_bits,
3225 			      NULL, eb, GFP_NOFS);
3226 	if (xa_is_err(exists)) {
3227 		ret = xa_err(exists);
3228 		xa_unlock_irq(&fs_info->buffer_tree);
3229 		btrfs_release_extent_buffer(eb);
3230 		return ERR_PTR(ret);
3231 	}
3232 	if (exists) {
3233 		if (!refcount_inc_not_zero(&exists->refs)) {
3234 			/* The extent buffer is being freed, retry. */
3235 			xa_unlock_irq(&fs_info->buffer_tree);
3236 			goto again;
3237 		}
3238 		xa_unlock_irq(&fs_info->buffer_tree);
3239 		btrfs_release_extent_buffer(eb);
3240 		return exists;
3241 	}
3242 	xa_unlock_irq(&fs_info->buffer_tree);
3243 	check_buffer_tree_ref(eb);
3244 
3245 	return eb;
3246 #else
3247 	/* Stub to avoid linker error when compiled with optimizations turned off. */
3248 	return NULL;
3249 #endif
3250 }
3251 
3252 static struct extent_buffer *grab_extent_buffer(struct btrfs_fs_info *fs_info,
3253 						struct folio *folio)
3254 {
3255 	struct extent_buffer *exists;
3256 
3257 	lockdep_assert_held(&folio->mapping->i_private_lock);
3258 
3259 	/*
3260 	 * For subpage case, we completely rely on xarray to ensure we don't try
3261 	 * to insert two ebs for the same bytenr.  So here we always return NULL
3262 	 * and just continue.
3263 	 */
3264 	if (btrfs_meta_is_subpage(fs_info))
3265 		return NULL;
3266 
3267 	/* Page not yet attached to an extent buffer */
3268 	if (!folio_test_private(folio))
3269 		return NULL;
3270 
3271 	/*
3272 	 * We could have already allocated an eb for this folio and attached one
3273 	 * so lets see if we can get a ref on the existing eb, and if we can we
3274 	 * know it's good and we can just return that one, else we know we can
3275 	 * just overwrite folio private.
3276 	 */
3277 	exists = folio_get_private(folio);
3278 	if (refcount_inc_not_zero(&exists->refs))
3279 		return exists;
3280 
3281 	WARN_ON(folio_test_dirty(folio));
3282 	folio_detach_private(folio);
3283 	return NULL;
3284 }
3285 
3286 /*
3287  * Validate alignment constraints of eb at logical address @start.
3288  */
3289 static bool check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
3290 {
3291 	const u32 nodesize = fs_info->nodesize;
3292 
3293 	if (unlikely(!IS_ALIGNED(start, fs_info->sectorsize))) {
3294 		btrfs_err(fs_info, "bad tree block start %llu", start);
3295 		return true;
3296 	}
3297 
3298 	if (unlikely(nodesize < PAGE_SIZE && !IS_ALIGNED(start, nodesize))) {
3299 		btrfs_err(fs_info,
3300 		"tree block is not nodesize aligned, start %llu nodesize %u",
3301 			  start, nodesize);
3302 		return true;
3303 	}
3304 	if (unlikely(nodesize >= PAGE_SIZE && !PAGE_ALIGNED(start))) {
3305 		btrfs_err(fs_info,
3306 		"tree block is not page aligned, start %llu nodesize %u",
3307 			  start, nodesize);
3308 		return true;
3309 	}
3310 	if (unlikely(!IS_ALIGNED(start, nodesize) &&
3311 		     !test_and_set_bit(BTRFS_FS_UNALIGNED_TREE_BLOCK, &fs_info->flags))) {
3312 		btrfs_warn(fs_info,
3313 "tree block not nodesize aligned, start %llu nodesize %u, can be resolved by a full metadata balance",
3314 			      start, nodesize);
3315 	}
3316 	return false;
3317 }
3318 
3319 /*
3320  * Return 0 if eb->folios[i] is attached to btree inode successfully.
3321  * Return >0 if there is already another extent buffer for the range,
3322  * and @found_eb_ret would be updated.
3323  * Return -EAGAIN if the filemap has an existing folio but with different size
3324  * than @eb.
3325  * The caller needs to free the existing folios and retry using the same order.
3326  */
3327 static int attach_eb_folio_to_filemap(struct extent_buffer *eb, int i,
3328 				      struct btrfs_folio_state *prealloc,
3329 				      struct extent_buffer **found_eb_ret)
3330 {
3331 
3332 	struct btrfs_fs_info *fs_info = eb->fs_info;
3333 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
3334 	const pgoff_t index = eb->start >> PAGE_SHIFT;
3335 	struct folio *existing_folio;
3336 	int ret;
3337 
3338 	ASSERT(found_eb_ret);
3339 
3340 	/* Caller should ensure the folio exists. */
3341 	ASSERT(eb->folios[i]);
3342 
3343 retry:
3344 	existing_folio = NULL;
3345 	ret = filemap_add_folio(mapping, eb->folios[i], index + i,
3346 				GFP_NOFS | __GFP_NOFAIL);
3347 	if (!ret)
3348 		goto finish;
3349 
3350 	existing_folio = filemap_lock_folio(mapping, index + i);
3351 	/* The page cache only exists for a very short time, just retry. */
3352 	if (IS_ERR(existing_folio))
3353 		goto retry;
3354 
3355 	/* For now, we should only have single-page folios for btree inode. */
3356 	ASSERT(folio_nr_pages(existing_folio) == 1);
3357 
3358 	if (folio_size(existing_folio) != eb->folio_size) {
3359 		folio_unlock(existing_folio);
3360 		folio_put(existing_folio);
3361 		return -EAGAIN;
3362 	}
3363 
3364 finish:
3365 	spin_lock(&mapping->i_private_lock);
3366 	if (existing_folio && btrfs_meta_is_subpage(fs_info)) {
3367 		/* We're going to reuse the existing page, can drop our folio now. */
3368 		__free_page(folio_page(eb->folios[i], 0));
3369 		eb->folios[i] = existing_folio;
3370 	} else if (existing_folio) {
3371 		struct extent_buffer *existing_eb;
3372 
3373 		existing_eb = grab_extent_buffer(fs_info, existing_folio);
3374 		if (existing_eb) {
3375 			/* The extent buffer still exists, we can use it directly. */
3376 			*found_eb_ret = existing_eb;
3377 			spin_unlock(&mapping->i_private_lock);
3378 			folio_unlock(existing_folio);
3379 			folio_put(existing_folio);
3380 			return 1;
3381 		}
3382 		/* The extent buffer no longer exists, we can reuse the folio. */
3383 		__free_page(folio_page(eb->folios[i], 0));
3384 		eb->folios[i] = existing_folio;
3385 	}
3386 	eb->folio_size = folio_size(eb->folios[i]);
3387 	eb->folio_shift = folio_shift(eb->folios[i]);
3388 	/* Should not fail, as we have preallocated the memory. */
3389 	ret = attach_extent_buffer_folio(eb, eb->folios[i], prealloc);
3390 	ASSERT(!ret);
3391 	/*
3392 	 * To inform we have an extra eb under allocation, so that
3393 	 * detach_extent_buffer_page() won't release the folio private when the
3394 	 * eb hasn't been inserted into the xarray yet.
3395 	 *
3396 	 * The ref will be decreased when the eb releases the page, in
3397 	 * detach_extent_buffer_page().  Thus needs no special handling in the
3398 	 * error path.
3399 	 */
3400 	btrfs_folio_inc_eb_refs(fs_info, eb->folios[i]);
3401 	spin_unlock(&mapping->i_private_lock);
3402 	return 0;
3403 }
3404 
3405 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3406 					  u64 start, u64 owner_root, int level)
3407 {
3408 	int attached = 0;
3409 	struct extent_buffer *eb;
3410 	struct extent_buffer *existing_eb = NULL;
3411 	struct btrfs_folio_state *prealloc = NULL;
3412 	u64 lockdep_owner = owner_root;
3413 	bool page_contig = true;
3414 	int uptodate = 1;
3415 	int ret;
3416 
3417 	if (check_eb_alignment(fs_info, start))
3418 		return ERR_PTR(-EINVAL);
3419 
3420 #if BITS_PER_LONG == 32
3421 	if (start >= MAX_LFS_FILESIZE) {
3422 		btrfs_err_rl(fs_info,
3423 		"extent buffer %llu is beyond 32bit page cache limit", start);
3424 		btrfs_err_32bit_limit(fs_info);
3425 		return ERR_PTR(-EOVERFLOW);
3426 	}
3427 	if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
3428 		btrfs_warn_32bit_limit(fs_info);
3429 #endif
3430 
3431 	eb = find_extent_buffer(fs_info, start);
3432 	if (eb)
3433 		return eb;
3434 
3435 	eb = __alloc_extent_buffer(fs_info, start);
3436 	if (!eb)
3437 		return ERR_PTR(-ENOMEM);
3438 
3439 	/*
3440 	 * The reloc trees are just snapshots, so we need them to appear to be
3441 	 * just like any other fs tree WRT lockdep.
3442 	 */
3443 	if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
3444 		lockdep_owner = BTRFS_FS_TREE_OBJECTID;
3445 
3446 	btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
3447 
3448 	/*
3449 	 * Preallocate folio private for subpage case, so that we won't
3450 	 * allocate memory with i_private_lock nor page lock hold.
3451 	 *
3452 	 * The memory will be freed by attach_extent_buffer_page() or freed
3453 	 * manually if we exit earlier.
3454 	 */
3455 	if (btrfs_meta_is_subpage(fs_info)) {
3456 		prealloc = btrfs_alloc_folio_state(fs_info, PAGE_SIZE, BTRFS_SUBPAGE_METADATA);
3457 		if (IS_ERR(prealloc)) {
3458 			ret = PTR_ERR(prealloc);
3459 			goto out;
3460 		}
3461 	}
3462 
3463 reallocate:
3464 	/* Allocate all pages first. */
3465 	ret = alloc_eb_folio_array(eb, true);
3466 	if (ret < 0) {
3467 		btrfs_free_folio_state(prealloc);
3468 		goto out;
3469 	}
3470 
3471 	/* Attach all pages to the filemap. */
3472 	for (int i = 0; i < num_extent_folios(eb); i++) {
3473 		struct folio *folio;
3474 
3475 		ret = attach_eb_folio_to_filemap(eb, i, prealloc, &existing_eb);
3476 		if (ret > 0) {
3477 			ASSERT(existing_eb);
3478 			goto out;
3479 		}
3480 
3481 		/*
3482 		 * TODO: Special handling for a corner case where the order of
3483 		 * folios mismatch between the new eb and filemap.
3484 		 *
3485 		 * This happens when:
3486 		 *
3487 		 * - the new eb is using higher order folio
3488 		 *
3489 		 * - the filemap is still using 0-order folios for the range
3490 		 *   This can happen at the previous eb allocation, and we don't
3491 		 *   have higher order folio for the call.
3492 		 *
3493 		 * - the existing eb has already been freed
3494 		 *
3495 		 * In this case, we have to free the existing folios first, and
3496 		 * re-allocate using the same order.
3497 		 * Thankfully this is not going to happen yet, as we're still
3498 		 * using 0-order folios.
3499 		 */
3500 		if (unlikely(ret == -EAGAIN)) {
3501 			DEBUG_WARN("folio order mismatch between new eb and filemap");
3502 			goto reallocate;
3503 		}
3504 		attached++;
3505 
3506 		/*
3507 		 * Only after attach_eb_folio_to_filemap(), eb->folios[] is
3508 		 * reliable, as we may choose to reuse the existing page cache
3509 		 * and free the allocated page.
3510 		 */
3511 		folio = eb->folios[i];
3512 		WARN_ON(btrfs_meta_folio_test_dirty(folio, eb));
3513 
3514 		/*
3515 		 * Check if the current page is physically contiguous with previous eb
3516 		 * page.
3517 		 * At this stage, either we allocated a large folio, thus @i
3518 		 * would only be 0, or we fall back to per-page allocation.
3519 		 */
3520 		if (i && folio_page(eb->folios[i - 1], 0) + 1 != folio_page(folio, 0))
3521 			page_contig = false;
3522 
3523 		if (!btrfs_meta_folio_test_uptodate(folio, eb))
3524 			uptodate = 0;
3525 
3526 		/*
3527 		 * We can't unlock the pages just yet since the extent buffer
3528 		 * hasn't been properly inserted into the xarray, this opens a
3529 		 * race with btree_release_folio() which can free a page while we
3530 		 * are still filling in all pages for the buffer and we could crash.
3531 		 */
3532 	}
3533 	if (uptodate)
3534 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3535 	/* All pages are physically contiguous, can skip cross page handling. */
3536 	if (page_contig)
3537 		eb->addr = folio_address(eb->folios[0]) + offset_in_page(eb->start);
3538 again:
3539 	xa_lock_irq(&fs_info->buffer_tree);
3540 	existing_eb = __xa_cmpxchg(&fs_info->buffer_tree,
3541 				   start >> fs_info->nodesize_bits, NULL, eb,
3542 				   GFP_NOFS);
3543 	if (xa_is_err(existing_eb)) {
3544 		ret = xa_err(existing_eb);
3545 		xa_unlock_irq(&fs_info->buffer_tree);
3546 		goto out;
3547 	}
3548 	if (existing_eb) {
3549 		if (!refcount_inc_not_zero(&existing_eb->refs)) {
3550 			xa_unlock_irq(&fs_info->buffer_tree);
3551 			goto again;
3552 		}
3553 		xa_unlock_irq(&fs_info->buffer_tree);
3554 		goto out;
3555 	}
3556 	xa_unlock_irq(&fs_info->buffer_tree);
3557 
3558 	/* add one reference for the tree */
3559 	check_buffer_tree_ref(eb);
3560 
3561 	/*
3562 	 * Now it's safe to unlock the pages because any calls to
3563 	 * btree_release_folio will correctly detect that a page belongs to a
3564 	 * live buffer and won't free them prematurely.
3565 	 */
3566 	for (int i = 0; i < num_extent_folios(eb); i++) {
3567 		folio_unlock(eb->folios[i]);
3568 		/*
3569 		 * A folio that has been added to an address_space mapping
3570 		 * should not continue holding the refcount from its original
3571 		 * allocation indefinitely.
3572 		 */
3573 		folio_put(eb->folios[i]);
3574 	}
3575 	return eb;
3576 
3577 out:
3578 	WARN_ON(!refcount_dec_and_test(&eb->refs));
3579 
3580 	/*
3581 	 * Any attached folios need to be detached before we unlock them.  This
3582 	 * is because when we're inserting our new folios into the mapping, and
3583 	 * then attaching our eb to that folio.  If we fail to insert our folio
3584 	 * we'll lookup the folio for that index, and grab that EB.  We do not
3585 	 * want that to grab this eb, as we're getting ready to free it.  So we
3586 	 * have to detach it first and then unlock it.
3587 	 *
3588 	 * Note: the bounds is num_extent_pages() as we need to go through all slots.
3589 	 */
3590 	for (int i = 0; i < num_extent_pages(eb); i++) {
3591 		struct folio *folio = eb->folios[i];
3592 
3593 		if (i < attached) {
3594 			ASSERT(folio);
3595 			detach_extent_buffer_folio(eb, folio);
3596 			folio_unlock(folio);
3597 		} else if (!folio) {
3598 			continue;
3599 		}
3600 
3601 		folio_put(folio);
3602 		eb->folios[i] = NULL;
3603 	}
3604 	btrfs_release_extent_buffer(eb);
3605 	if (ret < 0)
3606 		return ERR_PTR(ret);
3607 	ASSERT(existing_eb);
3608 	return existing_eb;
3609 }
3610 
3611 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
3612 {
3613 	struct extent_buffer *eb =
3614 			container_of(head, struct extent_buffer, rcu_head);
3615 
3616 	kmem_cache_free(extent_buffer_cache, eb);
3617 }
3618 
3619 static int release_extent_buffer(struct extent_buffer *eb)
3620 	__releases(&eb->refs_lock)
3621 {
3622 	lockdep_assert_held(&eb->refs_lock);
3623 
3624 	if (refcount_dec_and_test(&eb->refs)) {
3625 		struct btrfs_fs_info *fs_info = eb->fs_info;
3626 
3627 		spin_unlock(&eb->refs_lock);
3628 
3629 		/*
3630 		 * We're erasing, theoretically there will be no allocations, so
3631 		 * just use GFP_ATOMIC.
3632 		 *
3633 		 * We use cmpxchg instead of erase because we do not know if
3634 		 * this eb is actually in the tree or not, we could be cleaning
3635 		 * up an eb that we allocated but never inserted into the tree.
3636 		 * Thus use cmpxchg to remove it from the tree if it is there,
3637 		 * or leave the other entry if this isn't in the tree.
3638 		 *
3639 		 * The documentation says that putting a NULL value is the same
3640 		 * as erase as long as XA_FLAGS_ALLOC is not set, which it isn't
3641 		 * in this case.
3642 		 */
3643 		xa_cmpxchg_irq(&fs_info->buffer_tree,
3644 			       eb->start >> fs_info->nodesize_bits, eb, NULL,
3645 			       GFP_ATOMIC);
3646 
3647 		btrfs_leak_debug_del_eb(eb);
3648 		/* Should be safe to release folios at this point. */
3649 		btrfs_release_extent_buffer_folios(eb);
3650 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3651 		if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
3652 			kmem_cache_free(extent_buffer_cache, eb);
3653 			return 1;
3654 		}
3655 #endif
3656 		call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
3657 		return 1;
3658 	}
3659 	spin_unlock(&eb->refs_lock);
3660 
3661 	return 0;
3662 }
3663 
3664 void free_extent_buffer(struct extent_buffer *eb)
3665 {
3666 	int refs;
3667 	if (!eb)
3668 		return;
3669 
3670 	refs = refcount_read(&eb->refs);
3671 	while (1) {
3672 		if (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags)) {
3673 			if (refs == 1)
3674 				break;
3675 		} else if (refs <= 3) {
3676 			break;
3677 		}
3678 
3679 		/* Optimization to avoid locking eb->refs_lock. */
3680 		if (atomic_try_cmpxchg(&eb->refs.refs, &refs, refs - 1))
3681 			return;
3682 	}
3683 
3684 	spin_lock(&eb->refs_lock);
3685 	if (refcount_read(&eb->refs) == 2 &&
3686 	    test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
3687 	    !extent_buffer_under_io(eb) &&
3688 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3689 		refcount_dec(&eb->refs);
3690 
3691 	/*
3692 	 * I know this is terrible, but it's temporary until we stop tracking
3693 	 * the uptodate bits and such for the extent buffers.
3694 	 */
3695 	release_extent_buffer(eb);
3696 }
3697 
3698 void free_extent_buffer_stale(struct extent_buffer *eb)
3699 {
3700 	if (!eb)
3701 		return;
3702 
3703 	spin_lock(&eb->refs_lock);
3704 	set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
3705 
3706 	if (refcount_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
3707 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
3708 		refcount_dec(&eb->refs);
3709 	release_extent_buffer(eb);
3710 }
3711 
3712 static void btree_clear_folio_dirty_tag(struct folio *folio)
3713 {
3714 	ASSERT(!folio_test_dirty(folio));
3715 	ASSERT(folio_test_locked(folio));
3716 	xa_lock_irq(&folio->mapping->i_pages);
3717 	if (!folio_test_dirty(folio))
3718 		__xa_clear_mark(&folio->mapping->i_pages, folio->index,
3719 				PAGECACHE_TAG_DIRTY);
3720 	xa_unlock_irq(&folio->mapping->i_pages);
3721 }
3722 
3723 void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
3724 			      struct extent_buffer *eb)
3725 {
3726 	struct btrfs_fs_info *fs_info = eb->fs_info;
3727 
3728 	btrfs_assert_tree_write_locked(eb);
3729 
3730 	if (trans && btrfs_header_generation(eb) != trans->transid)
3731 		return;
3732 
3733 	/*
3734 	 * Instead of clearing the dirty flag off of the buffer, mark it as
3735 	 * EXTENT_BUFFER_ZONED_ZEROOUT. This allows us to preserve
3736 	 * write-ordering in zoned mode, without the need to later re-dirty
3737 	 * the extent_buffer.
3738 	 *
3739 	 * The actual zeroout of the buffer will happen later in
3740 	 * btree_csum_one_bio.
3741 	 */
3742 	if (btrfs_is_zoned(fs_info) && test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3743 		set_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags);
3744 		return;
3745 	}
3746 
3747 	if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
3748 		return;
3749 
3750 	buffer_tree_clear_mark(eb, PAGECACHE_TAG_DIRTY);
3751 	percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
3752 				 fs_info->dirty_metadata_batch);
3753 
3754 	for (int i = 0; i < num_extent_folios(eb); i++) {
3755 		struct folio *folio = eb->folios[i];
3756 		bool last;
3757 
3758 		if (!folio_test_dirty(folio))
3759 			continue;
3760 		folio_lock(folio);
3761 		last = btrfs_meta_folio_clear_and_test_dirty(folio, eb);
3762 		if (last)
3763 			btree_clear_folio_dirty_tag(folio);
3764 		folio_unlock(folio);
3765 	}
3766 	WARN_ON(refcount_read(&eb->refs) == 0);
3767 }
3768 
3769 void set_extent_buffer_dirty(struct extent_buffer *eb)
3770 {
3771 	bool was_dirty;
3772 
3773 	check_buffer_tree_ref(eb);
3774 
3775 	was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3776 
3777 	WARN_ON(refcount_read(&eb->refs) == 0);
3778 	WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
3779 	WARN_ON(test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags));
3780 
3781 	if (!was_dirty) {
3782 		bool subpage = btrfs_meta_is_subpage(eb->fs_info);
3783 
3784 		/*
3785 		 * For subpage case, we can have other extent buffers in the
3786 		 * same page, and in clear_extent_buffer_dirty() we
3787 		 * have to clear page dirty without subpage lock held.
3788 		 * This can cause race where our page gets dirty cleared after
3789 		 * we just set it.
3790 		 *
3791 		 * Thankfully, clear_extent_buffer_dirty() has locked
3792 		 * its page for other reasons, we can use page lock to prevent
3793 		 * the above race.
3794 		 */
3795 		if (subpage)
3796 			folio_lock(eb->folios[0]);
3797 		for (int i = 0; i < num_extent_folios(eb); i++)
3798 			btrfs_meta_folio_set_dirty(eb->folios[i], eb);
3799 		buffer_tree_set_mark(eb, PAGECACHE_TAG_DIRTY);
3800 		if (subpage)
3801 			folio_unlock(eb->folios[0]);
3802 		percpu_counter_add_batch(&eb->fs_info->dirty_metadata_bytes,
3803 					 eb->len,
3804 					 eb->fs_info->dirty_metadata_batch);
3805 	}
3806 #ifdef CONFIG_BTRFS_DEBUG
3807 	for (int i = 0; i < num_extent_folios(eb); i++)
3808 		ASSERT(folio_test_dirty(eb->folios[i]));
3809 #endif
3810 }
3811 
3812 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
3813 {
3814 
3815 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3816 	for (int i = 0; i < num_extent_folios(eb); i++) {
3817 		struct folio *folio = eb->folios[i];
3818 
3819 		if (!folio)
3820 			continue;
3821 
3822 		btrfs_meta_folio_clear_uptodate(folio, eb);
3823 	}
3824 }
3825 
3826 void set_extent_buffer_uptodate(struct extent_buffer *eb)
3827 {
3828 
3829 	set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
3830 	for (int i = 0; i < num_extent_folios(eb); i++)
3831 		btrfs_meta_folio_set_uptodate(eb->folios[i], eb);
3832 }
3833 
3834 static void clear_extent_buffer_reading(struct extent_buffer *eb)
3835 {
3836 	clear_and_wake_up_bit(EXTENT_BUFFER_READING, &eb->bflags);
3837 }
3838 
3839 static void end_bbio_meta_read(struct btrfs_bio *bbio)
3840 {
3841 	struct extent_buffer *eb = bbio->private;
3842 	bool uptodate = !bbio->bio.bi_status;
3843 
3844 	/*
3845 	 * If the extent buffer is marked UPTODATE before the read operation
3846 	 * completes, other calls to read_extent_buffer_pages() will return
3847 	 * early without waiting for the read to finish, causing data races.
3848 	 */
3849 	WARN_ON(test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags));
3850 
3851 	eb->read_mirror = bbio->mirror_num;
3852 
3853 	if (uptodate &&
3854 	    btrfs_validate_extent_buffer(eb, &bbio->parent_check) < 0)
3855 		uptodate = false;
3856 
3857 	if (uptodate)
3858 		set_extent_buffer_uptodate(eb);
3859 	else
3860 		clear_extent_buffer_uptodate(eb);
3861 
3862 	clear_extent_buffer_reading(eb);
3863 	free_extent_buffer(eb);
3864 
3865 	bio_put(&bbio->bio);
3866 }
3867 
3868 int read_extent_buffer_pages_nowait(struct extent_buffer *eb, int mirror_num,
3869 				    const struct btrfs_tree_parent_check *check)
3870 {
3871 	struct btrfs_fs_info *fs_info = eb->fs_info;
3872 	struct btrfs_bio *bbio;
3873 
3874 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
3875 		return 0;
3876 
3877 	/*
3878 	 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
3879 	 * operation, which could potentially still be in flight.  In this case
3880 	 * we simply want to return an error.
3881 	 */
3882 	if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
3883 		return -EIO;
3884 
3885 	/* Someone else is already reading the buffer, just wait for it. */
3886 	if (test_and_set_bit(EXTENT_BUFFER_READING, &eb->bflags))
3887 		return 0;
3888 
3889 	/*
3890 	 * Between the initial test_bit(EXTENT_BUFFER_UPTODATE) and the above
3891 	 * test_and_set_bit(EXTENT_BUFFER_READING), someone else could have
3892 	 * started and finished reading the same eb.  In this case, UPTODATE
3893 	 * will now be set, and we shouldn't read it in again.
3894 	 */
3895 	if (unlikely(test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))) {
3896 		clear_extent_buffer_reading(eb);
3897 		return 0;
3898 	}
3899 
3900 	eb->read_mirror = 0;
3901 	check_buffer_tree_ref(eb);
3902 	refcount_inc(&eb->refs);
3903 
3904 	bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
3905 			       REQ_OP_READ | REQ_META, BTRFS_I(fs_info->btree_inode),
3906 			       eb->start, end_bbio_meta_read, eb);
3907 	bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
3908 	memcpy(&bbio->parent_check, check, sizeof(*check));
3909 	for (int i = 0; i < num_extent_folios(eb); i++) {
3910 		struct folio *folio = eb->folios[i];
3911 		u64 range_start = max_t(u64, eb->start, folio_pos(folio));
3912 		u32 range_len = min_t(u64, folio_next_pos(folio),
3913 				      eb->start + eb->len) - range_start;
3914 
3915 		bio_add_folio_nofail(&bbio->bio, folio, range_len,
3916 				     offset_in_folio(folio, range_start));
3917 	}
3918 	btrfs_submit_bbio(bbio, mirror_num);
3919 	return 0;
3920 }
3921 
3922 int read_extent_buffer_pages(struct extent_buffer *eb, int mirror_num,
3923 			     const struct btrfs_tree_parent_check *check)
3924 {
3925 	int ret;
3926 
3927 	ret = read_extent_buffer_pages_nowait(eb, mirror_num, check);
3928 	if (ret < 0)
3929 		return ret;
3930 
3931 	wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_READING, TASK_UNINTERRUPTIBLE);
3932 	if (unlikely(!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags)))
3933 		return -EIO;
3934 	return 0;
3935 }
3936 
3937 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
3938 			    unsigned long len)
3939 {
3940 	btrfs_warn(eb->fs_info,
3941 		"access to eb bytenr %llu len %u out of range start %lu len %lu",
3942 		eb->start, eb->len, start, len);
3943 	DEBUG_WARN();
3944 
3945 	return true;
3946 }
3947 
3948 /*
3949  * Check if the [start, start + len) range is valid before reading/writing
3950  * the eb.
3951  * NOTE: @start and @len are offset inside the eb, not logical address.
3952  *
3953  * Caller should not touch the dst/src memory if this function returns error.
3954  */
3955 static inline int check_eb_range(const struct extent_buffer *eb,
3956 				 unsigned long start, unsigned long len)
3957 {
3958 	unsigned long offset;
3959 
3960 	/* start, start + len should not go beyond eb->len nor overflow */
3961 	if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
3962 		return report_eb_range(eb, start, len);
3963 
3964 	return false;
3965 }
3966 
3967 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
3968 			unsigned long start, unsigned long len)
3969 {
3970 	const int unit_size = eb->folio_size;
3971 	size_t cur;
3972 	size_t offset;
3973 	char *dst = (char *)dstv;
3974 	unsigned long i = get_eb_folio_index(eb, start);
3975 
3976 	if (check_eb_range(eb, start, len)) {
3977 		/*
3978 		 * Invalid range hit, reset the memory, so callers won't get
3979 		 * some random garbage for their uninitialized memory.
3980 		 */
3981 		memset(dstv, 0, len);
3982 		return;
3983 	}
3984 
3985 	if (eb->addr) {
3986 		memcpy(dstv, eb->addr + start, len);
3987 		return;
3988 	}
3989 
3990 	offset = get_eb_offset_in_folio(eb, start);
3991 
3992 	while (len > 0) {
3993 		char *kaddr;
3994 
3995 		cur = min(len, unit_size - offset);
3996 		kaddr = folio_address(eb->folios[i]);
3997 		memcpy(dst, kaddr + offset, cur);
3998 
3999 		dst += cur;
4000 		len -= cur;
4001 		offset = 0;
4002 		i++;
4003 	}
4004 }
4005 
4006 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
4007 				       void __user *dstv,
4008 				       unsigned long start, unsigned long len)
4009 {
4010 	const int unit_size = eb->folio_size;
4011 	size_t cur;
4012 	size_t offset;
4013 	char __user *dst = (char __user *)dstv;
4014 	unsigned long i = get_eb_folio_index(eb, start);
4015 	int ret = 0;
4016 
4017 	WARN_ON(start > eb->len);
4018 	WARN_ON(start + len > eb->start + eb->len);
4019 
4020 	if (eb->addr) {
4021 		if (copy_to_user_nofault(dstv, eb->addr + start, len))
4022 			ret = -EFAULT;
4023 		return ret;
4024 	}
4025 
4026 	offset = get_eb_offset_in_folio(eb, start);
4027 
4028 	while (len > 0) {
4029 		char *kaddr;
4030 
4031 		cur = min(len, unit_size - offset);
4032 		kaddr = folio_address(eb->folios[i]);
4033 		if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
4034 			ret = -EFAULT;
4035 			break;
4036 		}
4037 
4038 		dst += cur;
4039 		len -= cur;
4040 		offset = 0;
4041 		i++;
4042 	}
4043 
4044 	return ret;
4045 }
4046 
4047 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
4048 			 unsigned long start, unsigned long len)
4049 {
4050 	const int unit_size = eb->folio_size;
4051 	size_t cur;
4052 	size_t offset;
4053 	char *kaddr;
4054 	char *ptr = (char *)ptrv;
4055 	unsigned long i = get_eb_folio_index(eb, start);
4056 	int ret = 0;
4057 
4058 	if (check_eb_range(eb, start, len))
4059 		return -EINVAL;
4060 
4061 	if (eb->addr)
4062 		return memcmp(ptrv, eb->addr + start, len);
4063 
4064 	offset = get_eb_offset_in_folio(eb, start);
4065 
4066 	while (len > 0) {
4067 		cur = min(len, unit_size - offset);
4068 		kaddr = folio_address(eb->folios[i]);
4069 		ret = memcmp(ptr, kaddr + offset, cur);
4070 		if (ret)
4071 			break;
4072 
4073 		ptr += cur;
4074 		len -= cur;
4075 		offset = 0;
4076 		i++;
4077 	}
4078 	return ret;
4079 }
4080 
4081 /*
4082  * Check that the extent buffer is uptodate.
4083  *
4084  * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
4085  * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
4086  */
4087 static void assert_eb_folio_uptodate(const struct extent_buffer *eb, int i)
4088 {
4089 	struct btrfs_fs_info *fs_info = eb->fs_info;
4090 	struct folio *folio = eb->folios[i];
4091 
4092 	ASSERT(folio);
4093 
4094 	/*
4095 	 * If we are using the commit root we could potentially clear a page
4096 	 * Uptodate while we're using the extent buffer that we've previously
4097 	 * looked up.  We don't want to complain in this case, as the page was
4098 	 * valid before, we just didn't write it out.  Instead we want to catch
4099 	 * the case where we didn't actually read the block properly, which
4100 	 * would have !PageUptodate and !EXTENT_BUFFER_WRITE_ERR.
4101 	 */
4102 	if (test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4103 		return;
4104 
4105 	if (btrfs_meta_is_subpage(fs_info)) {
4106 		folio = eb->folios[0];
4107 		ASSERT(i == 0);
4108 		if (WARN_ON(!btrfs_subpage_test_uptodate(fs_info, folio,
4109 							 eb->start, eb->len)))
4110 			btrfs_subpage_dump_bitmap(fs_info, folio, eb->start, eb->len);
4111 	} else {
4112 		WARN_ON(!folio_test_uptodate(folio));
4113 	}
4114 }
4115 
4116 static void __write_extent_buffer(const struct extent_buffer *eb,
4117 				  const void *srcv, unsigned long start,
4118 				  unsigned long len, bool use_memmove)
4119 {
4120 	const int unit_size = eb->folio_size;
4121 	size_t cur;
4122 	size_t offset;
4123 	char *kaddr;
4124 	const char *src = (const char *)srcv;
4125 	unsigned long i = get_eb_folio_index(eb, start);
4126 	/* For unmapped (dummy) ebs, no need to check their uptodate status. */
4127 	const bool check_uptodate = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4128 
4129 	if (check_eb_range(eb, start, len))
4130 		return;
4131 
4132 	if (eb->addr) {
4133 		if (use_memmove)
4134 			memmove(eb->addr + start, srcv, len);
4135 		else
4136 			memcpy(eb->addr + start, srcv, len);
4137 		return;
4138 	}
4139 
4140 	offset = get_eb_offset_in_folio(eb, start);
4141 
4142 	while (len > 0) {
4143 		if (check_uptodate)
4144 			assert_eb_folio_uptodate(eb, i);
4145 
4146 		cur = min(len, unit_size - offset);
4147 		kaddr = folio_address(eb->folios[i]);
4148 		if (use_memmove)
4149 			memmove(kaddr + offset, src, cur);
4150 		else
4151 			memcpy(kaddr + offset, src, cur);
4152 
4153 		src += cur;
4154 		len -= cur;
4155 		offset = 0;
4156 		i++;
4157 	}
4158 }
4159 
4160 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
4161 			 unsigned long start, unsigned long len)
4162 {
4163 	return __write_extent_buffer(eb, srcv, start, len, false);
4164 }
4165 
4166 static void memset_extent_buffer(const struct extent_buffer *eb, int c,
4167 				 unsigned long start, unsigned long len)
4168 {
4169 	const int unit_size = eb->folio_size;
4170 	unsigned long cur = start;
4171 
4172 	if (eb->addr) {
4173 		memset(eb->addr + start, c, len);
4174 		return;
4175 	}
4176 
4177 	while (cur < start + len) {
4178 		unsigned long index = get_eb_folio_index(eb, cur);
4179 		unsigned int offset = get_eb_offset_in_folio(eb, cur);
4180 		unsigned int cur_len = min(start + len - cur, unit_size - offset);
4181 
4182 		assert_eb_folio_uptodate(eb, index);
4183 		memset(folio_address(eb->folios[index]) + offset, c, cur_len);
4184 
4185 		cur += cur_len;
4186 	}
4187 }
4188 
4189 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
4190 			   unsigned long len)
4191 {
4192 	if (check_eb_range(eb, start, len))
4193 		return;
4194 	return memset_extent_buffer(eb, 0, start, len);
4195 }
4196 
4197 void copy_extent_buffer_full(const struct extent_buffer *dst,
4198 			     const struct extent_buffer *src)
4199 {
4200 	const int unit_size = src->folio_size;
4201 	unsigned long cur = 0;
4202 
4203 	ASSERT(dst->len == src->len);
4204 
4205 	while (cur < src->len) {
4206 		unsigned long index = get_eb_folio_index(src, cur);
4207 		unsigned long offset = get_eb_offset_in_folio(src, cur);
4208 		unsigned long cur_len = min(src->len, unit_size - offset);
4209 		void *addr = folio_address(src->folios[index]) + offset;
4210 
4211 		write_extent_buffer(dst, addr, cur, cur_len);
4212 
4213 		cur += cur_len;
4214 	}
4215 }
4216 
4217 void copy_extent_buffer(const struct extent_buffer *dst,
4218 			const struct extent_buffer *src,
4219 			unsigned long dst_offset, unsigned long src_offset,
4220 			unsigned long len)
4221 {
4222 	const int unit_size = dst->folio_size;
4223 	u64 dst_len = dst->len;
4224 	size_t cur;
4225 	size_t offset;
4226 	char *kaddr;
4227 	unsigned long i = get_eb_folio_index(dst, dst_offset);
4228 
4229 	if (check_eb_range(dst, dst_offset, len) ||
4230 	    check_eb_range(src, src_offset, len))
4231 		return;
4232 
4233 	WARN_ON(src->len != dst_len);
4234 
4235 	offset = get_eb_offset_in_folio(dst, dst_offset);
4236 
4237 	while (len > 0) {
4238 		assert_eb_folio_uptodate(dst, i);
4239 
4240 		cur = min(len, (unsigned long)(unit_size - offset));
4241 
4242 		kaddr = folio_address(dst->folios[i]);
4243 		read_extent_buffer(src, kaddr + offset, src_offset, cur);
4244 
4245 		src_offset += cur;
4246 		len -= cur;
4247 		offset = 0;
4248 		i++;
4249 	}
4250 }
4251 
4252 /*
4253  * Calculate the folio and offset of the byte containing the given bit number.
4254  *
4255  * @eb:           the extent buffer
4256  * @start:        offset of the bitmap item in the extent buffer
4257  * @nr:           bit number
4258  * @folio_index:  return index of the folio in the extent buffer that contains
4259  *                the given bit number
4260  * @folio_offset: return offset into the folio given by folio_index
4261  *
4262  * This helper hides the ugliness of finding the byte in an extent buffer which
4263  * contains a given bit.
4264  */
4265 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
4266 				    unsigned long start, unsigned long nr,
4267 				    unsigned long *folio_index,
4268 				    size_t *folio_offset)
4269 {
4270 	size_t byte_offset = BIT_BYTE(nr);
4271 	size_t offset;
4272 
4273 	/*
4274 	 * The byte we want is the offset of the extent buffer + the offset of
4275 	 * the bitmap item in the extent buffer + the offset of the byte in the
4276 	 * bitmap item.
4277 	 */
4278 	offset = start + offset_in_eb_folio(eb, eb->start) + byte_offset;
4279 
4280 	*folio_index = offset >> eb->folio_shift;
4281 	*folio_offset = offset_in_eb_folio(eb, offset);
4282 }
4283 
4284 /*
4285  * Determine whether a bit in a bitmap item is set.
4286  *
4287  * @eb:     the extent buffer
4288  * @start:  offset of the bitmap item in the extent buffer
4289  * @nr:     bit number to test
4290  */
4291 bool extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
4292 			    unsigned long nr)
4293 {
4294 	unsigned long i;
4295 	size_t offset;
4296 	u8 *kaddr;
4297 
4298 	eb_bitmap_offset(eb, start, nr, &i, &offset);
4299 	assert_eb_folio_uptodate(eb, i);
4300 	kaddr = folio_address(eb->folios[i]);
4301 	return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
4302 }
4303 
4304 static u8 *extent_buffer_get_byte(const struct extent_buffer *eb, unsigned long bytenr)
4305 {
4306 	unsigned long index = get_eb_folio_index(eb, bytenr);
4307 
4308 	if (check_eb_range(eb, bytenr, 1))
4309 		return NULL;
4310 	return folio_address(eb->folios[index]) + get_eb_offset_in_folio(eb, bytenr);
4311 }
4312 
4313 /*
4314  * Set an area of a bitmap to 1.
4315  *
4316  * @eb:     the extent buffer
4317  * @start:  offset of the bitmap item in the extent buffer
4318  * @pos:    bit number of the first bit
4319  * @len:    number of bits to set
4320  */
4321 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
4322 			      unsigned long pos, unsigned long len)
4323 {
4324 	unsigned int first_byte = start + BIT_BYTE(pos);
4325 	unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4326 	const bool same_byte = (first_byte == last_byte);
4327 	u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4328 	u8 *kaddr;
4329 
4330 	if (same_byte)
4331 		mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4332 
4333 	/* Handle the first byte. */
4334 	kaddr = extent_buffer_get_byte(eb, first_byte);
4335 	*kaddr |= mask;
4336 	if (same_byte)
4337 		return;
4338 
4339 	/* Handle the byte aligned part. */
4340 	ASSERT(first_byte + 1 <= last_byte);
4341 	memset_extent_buffer(eb, 0xff, first_byte + 1, last_byte - first_byte - 1);
4342 
4343 	/* Handle the last byte. */
4344 	kaddr = extent_buffer_get_byte(eb, last_byte);
4345 	*kaddr |= BITMAP_LAST_BYTE_MASK(pos + len);
4346 }
4347 
4348 
4349 /*
4350  * Clear an area of a bitmap.
4351  *
4352  * @eb:     the extent buffer
4353  * @start:  offset of the bitmap item in the extent buffer
4354  * @pos:    bit number of the first bit
4355  * @len:    number of bits to clear
4356  */
4357 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
4358 				unsigned long start, unsigned long pos,
4359 				unsigned long len)
4360 {
4361 	unsigned int first_byte = start + BIT_BYTE(pos);
4362 	unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
4363 	const bool same_byte = (first_byte == last_byte);
4364 	u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
4365 	u8 *kaddr;
4366 
4367 	if (same_byte)
4368 		mask &= BITMAP_LAST_BYTE_MASK(pos + len);
4369 
4370 	/* Handle the first byte. */
4371 	kaddr = extent_buffer_get_byte(eb, first_byte);
4372 	*kaddr &= ~mask;
4373 	if (same_byte)
4374 		return;
4375 
4376 	/* Handle the byte aligned part. */
4377 	ASSERT(first_byte + 1 <= last_byte);
4378 	memset_extent_buffer(eb, 0, first_byte + 1, last_byte - first_byte - 1);
4379 
4380 	/* Handle the last byte. */
4381 	kaddr = extent_buffer_get_byte(eb, last_byte);
4382 	*kaddr &= ~BITMAP_LAST_BYTE_MASK(pos + len);
4383 }
4384 
4385 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
4386 {
4387 	unsigned long distance = (src > dst) ? src - dst : dst - src;
4388 	return distance < len;
4389 }
4390 
4391 void memcpy_extent_buffer(const struct extent_buffer *dst,
4392 			  unsigned long dst_offset, unsigned long src_offset,
4393 			  unsigned long len)
4394 {
4395 	const int unit_size = dst->folio_size;
4396 	unsigned long cur_off = 0;
4397 
4398 	if (check_eb_range(dst, dst_offset, len) ||
4399 	    check_eb_range(dst, src_offset, len))
4400 		return;
4401 
4402 	if (dst->addr) {
4403 		const bool use_memmove = areas_overlap(src_offset, dst_offset, len);
4404 
4405 		if (use_memmove)
4406 			memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
4407 		else
4408 			memcpy(dst->addr + dst_offset, dst->addr + src_offset, len);
4409 		return;
4410 	}
4411 
4412 	while (cur_off < len) {
4413 		unsigned long cur_src = cur_off + src_offset;
4414 		unsigned long folio_index = get_eb_folio_index(dst, cur_src);
4415 		unsigned long folio_off = get_eb_offset_in_folio(dst, cur_src);
4416 		unsigned long cur_len = min(src_offset + len - cur_src,
4417 					    unit_size - folio_off);
4418 		void *src_addr = folio_address(dst->folios[folio_index]) + folio_off;
4419 		const bool use_memmove = areas_overlap(src_offset + cur_off,
4420 						       dst_offset + cur_off, cur_len);
4421 
4422 		__write_extent_buffer(dst, src_addr, dst_offset + cur_off, cur_len,
4423 				      use_memmove);
4424 		cur_off += cur_len;
4425 	}
4426 }
4427 
4428 void memmove_extent_buffer(const struct extent_buffer *dst,
4429 			   unsigned long dst_offset, unsigned long src_offset,
4430 			   unsigned long len)
4431 {
4432 	unsigned long dst_end = dst_offset + len - 1;
4433 	unsigned long src_end = src_offset + len - 1;
4434 
4435 	if (check_eb_range(dst, dst_offset, len) ||
4436 	    check_eb_range(dst, src_offset, len))
4437 		return;
4438 
4439 	if (dst_offset < src_offset) {
4440 		memcpy_extent_buffer(dst, dst_offset, src_offset, len);
4441 		return;
4442 	}
4443 
4444 	if (dst->addr) {
4445 		memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
4446 		return;
4447 	}
4448 
4449 	while (len > 0) {
4450 		unsigned long src_i;
4451 		size_t cur;
4452 		size_t dst_off_in_folio;
4453 		size_t src_off_in_folio;
4454 		void *src_addr;
4455 		bool use_memmove;
4456 
4457 		src_i = get_eb_folio_index(dst, src_end);
4458 
4459 		dst_off_in_folio = get_eb_offset_in_folio(dst, dst_end);
4460 		src_off_in_folio = get_eb_offset_in_folio(dst, src_end);
4461 
4462 		cur = min_t(unsigned long, len, src_off_in_folio + 1);
4463 		cur = min(cur, dst_off_in_folio + 1);
4464 
4465 		src_addr = folio_address(dst->folios[src_i]) + src_off_in_folio -
4466 					 cur + 1;
4467 		use_memmove = areas_overlap(src_end - cur + 1, dst_end - cur + 1,
4468 					    cur);
4469 
4470 		__write_extent_buffer(dst, src_addr, dst_end - cur + 1, cur,
4471 				      use_memmove);
4472 
4473 		dst_end -= cur;
4474 		src_end -= cur;
4475 		len -= cur;
4476 	}
4477 }
4478 
4479 static int try_release_subpage_extent_buffer(struct folio *folio)
4480 {
4481 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
4482 	struct extent_buffer *eb;
4483 	unsigned long start = (folio_pos(folio) >> fs_info->nodesize_bits);
4484 	unsigned long index = start;
4485 	unsigned long end = index + (PAGE_SIZE >> fs_info->nodesize_bits) - 1;
4486 	int ret;
4487 
4488 	rcu_read_lock();
4489 	xa_for_each_range(&fs_info->buffer_tree, index, eb, start, end) {
4490 		/*
4491 		 * The same as try_release_extent_buffer(), to ensure the eb
4492 		 * won't disappear out from under us.
4493 		 */
4494 		spin_lock(&eb->refs_lock);
4495 		rcu_read_unlock();
4496 
4497 		if (refcount_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4498 			spin_unlock(&eb->refs_lock);
4499 			rcu_read_lock();
4500 			continue;
4501 		}
4502 
4503 		/*
4504 		 * If tree ref isn't set then we know the ref on this eb is a
4505 		 * real ref, so just return, this eb will likely be freed soon
4506 		 * anyway.
4507 		 */
4508 		if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4509 			spin_unlock(&eb->refs_lock);
4510 			break;
4511 		}
4512 
4513 		/*
4514 		 * Here we don't care about the return value, we will always
4515 		 * check the folio private at the end.  And
4516 		 * release_extent_buffer() will release the refs_lock.
4517 		 */
4518 		release_extent_buffer(eb);
4519 		rcu_read_lock();
4520 	}
4521 	rcu_read_unlock();
4522 
4523 	/*
4524 	 * Finally to check if we have cleared folio private, as if we have
4525 	 * released all ebs in the page, the folio private should be cleared now.
4526 	 */
4527 	spin_lock(&folio->mapping->i_private_lock);
4528 	if (!folio_test_private(folio))
4529 		ret = 1;
4530 	else
4531 		ret = 0;
4532 	spin_unlock(&folio->mapping->i_private_lock);
4533 	return ret;
4534 }
4535 
4536 int try_release_extent_buffer(struct folio *folio)
4537 {
4538 	struct extent_buffer *eb;
4539 
4540 	if (btrfs_meta_is_subpage(folio_to_fs_info(folio)))
4541 		return try_release_subpage_extent_buffer(folio);
4542 
4543 	/*
4544 	 * We need to make sure nobody is changing folio private, as we rely on
4545 	 * folio private as the pointer to extent buffer.
4546 	 */
4547 	spin_lock(&folio->mapping->i_private_lock);
4548 	if (!folio_test_private(folio)) {
4549 		spin_unlock(&folio->mapping->i_private_lock);
4550 		return 1;
4551 	}
4552 
4553 	eb = folio_get_private(folio);
4554 	BUG_ON(!eb);
4555 
4556 	/*
4557 	 * This is a little awful but should be ok, we need to make sure that
4558 	 * the eb doesn't disappear out from under us while we're looking at
4559 	 * this page.
4560 	 */
4561 	spin_lock(&eb->refs_lock);
4562 	if (refcount_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
4563 		spin_unlock(&eb->refs_lock);
4564 		spin_unlock(&folio->mapping->i_private_lock);
4565 		return 0;
4566 	}
4567 	spin_unlock(&folio->mapping->i_private_lock);
4568 
4569 	/*
4570 	 * If tree ref isn't set then we know the ref on this eb is a real ref,
4571 	 * so just return, this page will likely be freed soon anyway.
4572 	 */
4573 	if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
4574 		spin_unlock(&eb->refs_lock);
4575 		return 0;
4576 	}
4577 
4578 	return release_extent_buffer(eb);
4579 }
4580 
4581 /*
4582  * Attempt to readahead a child block.
4583  *
4584  * @fs_info:	the fs_info
4585  * @bytenr:	bytenr to read
4586  * @owner_root: objectid of the root that owns this eb
4587  * @gen:	generation for the uptodate check, can be 0
4588  * @level:	level for the eb
4589  *
4590  * Attempt to readahead a tree block at @bytenr.  If @gen is 0 then we do a
4591  * normal uptodate check of the eb, without checking the generation.  If we have
4592  * to read the block we will not block on anything.
4593  */
4594 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
4595 				u64 bytenr, u64 owner_root, u64 gen, int level)
4596 {
4597 	struct btrfs_tree_parent_check check = {
4598 		.level = level,
4599 		.transid = gen
4600 	};
4601 	struct extent_buffer *eb;
4602 	int ret;
4603 
4604 	eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
4605 	if (IS_ERR(eb))
4606 		return;
4607 
4608 	if (btrfs_buffer_uptodate(eb, gen, true)) {
4609 		free_extent_buffer(eb);
4610 		return;
4611 	}
4612 
4613 	ret = read_extent_buffer_pages_nowait(eb, 0, &check);
4614 	if (ret < 0)
4615 		free_extent_buffer_stale(eb);
4616 	else
4617 		free_extent_buffer(eb);
4618 }
4619 
4620 /*
4621  * Readahead a node's child block.
4622  *
4623  * @node:	parent node we're reading from
4624  * @slot:	slot in the parent node for the child we want to read
4625  *
4626  * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
4627  * the slot in the node provided.
4628  */
4629 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
4630 {
4631 	btrfs_readahead_tree_block(node->fs_info,
4632 				   btrfs_node_blockptr(node, slot),
4633 				   btrfs_header_owner(node),
4634 				   btrfs_node_ptr_generation(node, slot),
4635 				   btrfs_header_level(node) - 1);
4636 }
4637