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