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