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