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