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