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