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