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