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