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