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