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