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