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