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