1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2007 Oracle. All rights reserved. 4 */ 5 6 #include <linux/fs.h> 7 #include <linux/pagemap.h> 8 #include <linux/time.h> 9 #include <linux/init.h> 10 #include <linux/string.h> 11 #include <linux/backing-dev.h> 12 #include <linux/falloc.h> 13 #include <linux/writeback.h> 14 #include <linux/compat.h> 15 #include <linux/slab.h> 16 #include <linux/btrfs.h> 17 #include <linux/uio.h> 18 #include <linux/iversion.h> 19 #include <linux/fsverity.h> 20 #include "ctree.h" 21 #include "disk-io.h" 22 #include "transaction.h" 23 #include "btrfs_inode.h" 24 #include "print-tree.h" 25 #include "tree-log.h" 26 #include "locking.h" 27 #include "volumes.h" 28 #include "qgroup.h" 29 #include "compression.h" 30 #include "delalloc-space.h" 31 #include "reflink.h" 32 #include "subpage.h" 33 34 static struct kmem_cache *btrfs_inode_defrag_cachep; 35 /* 36 * when auto defrag is enabled we 37 * queue up these defrag structs to remember which 38 * inodes need defragging passes 39 */ 40 struct inode_defrag { 41 struct rb_node rb_node; 42 /* objectid */ 43 u64 ino; 44 /* 45 * transid where the defrag was added, we search for 46 * extents newer than this 47 */ 48 u64 transid; 49 50 /* root objectid */ 51 u64 root; 52 53 /* 54 * The extent size threshold for autodefrag. 55 * 56 * This value is different for compressed/non-compressed extents, 57 * thus needs to be passed from higher layer. 58 * (aka, inode_should_defrag()) 59 */ 60 u32 extent_thresh; 61 }; 62 63 static int __compare_inode_defrag(struct inode_defrag *defrag1, 64 struct inode_defrag *defrag2) 65 { 66 if (defrag1->root > defrag2->root) 67 return 1; 68 else if (defrag1->root < defrag2->root) 69 return -1; 70 else if (defrag1->ino > defrag2->ino) 71 return 1; 72 else if (defrag1->ino < defrag2->ino) 73 return -1; 74 else 75 return 0; 76 } 77 78 /* pop a record for an inode into the defrag tree. The lock 79 * must be held already 80 * 81 * If you're inserting a record for an older transid than an 82 * existing record, the transid already in the tree is lowered 83 * 84 * If an existing record is found the defrag item you 85 * pass in is freed 86 */ 87 static int __btrfs_add_inode_defrag(struct btrfs_inode *inode, 88 struct inode_defrag *defrag) 89 { 90 struct btrfs_fs_info *fs_info = inode->root->fs_info; 91 struct inode_defrag *entry; 92 struct rb_node **p; 93 struct rb_node *parent = NULL; 94 int ret; 95 96 p = &fs_info->defrag_inodes.rb_node; 97 while (*p) { 98 parent = *p; 99 entry = rb_entry(parent, struct inode_defrag, rb_node); 100 101 ret = __compare_inode_defrag(defrag, entry); 102 if (ret < 0) 103 p = &parent->rb_left; 104 else if (ret > 0) 105 p = &parent->rb_right; 106 else { 107 /* if we're reinserting an entry for 108 * an old defrag run, make sure to 109 * lower the transid of our existing record 110 */ 111 if (defrag->transid < entry->transid) 112 entry->transid = defrag->transid; 113 entry->extent_thresh = min(defrag->extent_thresh, 114 entry->extent_thresh); 115 return -EEXIST; 116 } 117 } 118 set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags); 119 rb_link_node(&defrag->rb_node, parent, p); 120 rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes); 121 return 0; 122 } 123 124 static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info) 125 { 126 if (!btrfs_test_opt(fs_info, AUTO_DEFRAG)) 127 return 0; 128 129 if (btrfs_fs_closing(fs_info)) 130 return 0; 131 132 return 1; 133 } 134 135 /* 136 * insert a defrag record for this inode if auto defrag is 137 * enabled 138 */ 139 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans, 140 struct btrfs_inode *inode, u32 extent_thresh) 141 { 142 struct btrfs_root *root = inode->root; 143 struct btrfs_fs_info *fs_info = root->fs_info; 144 struct inode_defrag *defrag; 145 u64 transid; 146 int ret; 147 148 if (!__need_auto_defrag(fs_info)) 149 return 0; 150 151 if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) 152 return 0; 153 154 if (trans) 155 transid = trans->transid; 156 else 157 transid = inode->root->last_trans; 158 159 defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS); 160 if (!defrag) 161 return -ENOMEM; 162 163 defrag->ino = btrfs_ino(inode); 164 defrag->transid = transid; 165 defrag->root = root->root_key.objectid; 166 defrag->extent_thresh = extent_thresh; 167 168 spin_lock(&fs_info->defrag_inodes_lock); 169 if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) { 170 /* 171 * If we set IN_DEFRAG flag and evict the inode from memory, 172 * and then re-read this inode, this new inode doesn't have 173 * IN_DEFRAG flag. At the case, we may find the existed defrag. 174 */ 175 ret = __btrfs_add_inode_defrag(inode, defrag); 176 if (ret) 177 kmem_cache_free(btrfs_inode_defrag_cachep, defrag); 178 } else { 179 kmem_cache_free(btrfs_inode_defrag_cachep, defrag); 180 } 181 spin_unlock(&fs_info->defrag_inodes_lock); 182 return 0; 183 } 184 185 /* 186 * pick the defragable inode that we want, if it doesn't exist, we will get 187 * the next one. 188 */ 189 static struct inode_defrag * 190 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino) 191 { 192 struct inode_defrag *entry = NULL; 193 struct inode_defrag tmp; 194 struct rb_node *p; 195 struct rb_node *parent = NULL; 196 int ret; 197 198 tmp.ino = ino; 199 tmp.root = root; 200 201 spin_lock(&fs_info->defrag_inodes_lock); 202 p = fs_info->defrag_inodes.rb_node; 203 while (p) { 204 parent = p; 205 entry = rb_entry(parent, struct inode_defrag, rb_node); 206 207 ret = __compare_inode_defrag(&tmp, entry); 208 if (ret < 0) 209 p = parent->rb_left; 210 else if (ret > 0) 211 p = parent->rb_right; 212 else 213 goto out; 214 } 215 216 if (parent && __compare_inode_defrag(&tmp, entry) > 0) { 217 parent = rb_next(parent); 218 if (parent) 219 entry = rb_entry(parent, struct inode_defrag, rb_node); 220 else 221 entry = NULL; 222 } 223 out: 224 if (entry) 225 rb_erase(parent, &fs_info->defrag_inodes); 226 spin_unlock(&fs_info->defrag_inodes_lock); 227 return entry; 228 } 229 230 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info) 231 { 232 struct inode_defrag *defrag; 233 struct rb_node *node; 234 235 spin_lock(&fs_info->defrag_inodes_lock); 236 node = rb_first(&fs_info->defrag_inodes); 237 while (node) { 238 rb_erase(node, &fs_info->defrag_inodes); 239 defrag = rb_entry(node, struct inode_defrag, rb_node); 240 kmem_cache_free(btrfs_inode_defrag_cachep, defrag); 241 242 cond_resched_lock(&fs_info->defrag_inodes_lock); 243 244 node = rb_first(&fs_info->defrag_inodes); 245 } 246 spin_unlock(&fs_info->defrag_inodes_lock); 247 } 248 249 #define BTRFS_DEFRAG_BATCH 1024 250 251 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info, 252 struct inode_defrag *defrag) 253 { 254 struct btrfs_root *inode_root; 255 struct inode *inode; 256 struct btrfs_ioctl_defrag_range_args range; 257 int ret = 0; 258 u64 cur = 0; 259 260 again: 261 if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state)) 262 goto cleanup; 263 if (!__need_auto_defrag(fs_info)) 264 goto cleanup; 265 266 /* get the inode */ 267 inode_root = btrfs_get_fs_root(fs_info, defrag->root, true); 268 if (IS_ERR(inode_root)) { 269 ret = PTR_ERR(inode_root); 270 goto cleanup; 271 } 272 273 inode = btrfs_iget(fs_info->sb, defrag->ino, inode_root); 274 btrfs_put_root(inode_root); 275 if (IS_ERR(inode)) { 276 ret = PTR_ERR(inode); 277 goto cleanup; 278 } 279 280 if (cur >= i_size_read(inode)) { 281 iput(inode); 282 goto cleanup; 283 } 284 285 /* do a chunk of defrag */ 286 clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags); 287 memset(&range, 0, sizeof(range)); 288 range.len = (u64)-1; 289 range.start = cur; 290 range.extent_thresh = defrag->extent_thresh; 291 292 sb_start_write(fs_info->sb); 293 ret = btrfs_defrag_file(inode, NULL, &range, defrag->transid, 294 BTRFS_DEFRAG_BATCH); 295 sb_end_write(fs_info->sb); 296 iput(inode); 297 298 if (ret < 0) 299 goto cleanup; 300 301 cur = max(cur + fs_info->sectorsize, range.start); 302 goto again; 303 304 cleanup: 305 kmem_cache_free(btrfs_inode_defrag_cachep, defrag); 306 return ret; 307 } 308 309 /* 310 * run through the list of inodes in the FS that need 311 * defragging 312 */ 313 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info) 314 { 315 struct inode_defrag *defrag; 316 u64 first_ino = 0; 317 u64 root_objectid = 0; 318 319 atomic_inc(&fs_info->defrag_running); 320 while (1) { 321 /* Pause the auto defragger. */ 322 if (test_bit(BTRFS_FS_STATE_REMOUNTING, 323 &fs_info->fs_state)) 324 break; 325 326 if (!__need_auto_defrag(fs_info)) 327 break; 328 329 /* find an inode to defrag */ 330 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid, 331 first_ino); 332 if (!defrag) { 333 if (root_objectid || first_ino) { 334 root_objectid = 0; 335 first_ino = 0; 336 continue; 337 } else { 338 break; 339 } 340 } 341 342 first_ino = defrag->ino + 1; 343 root_objectid = defrag->root; 344 345 __btrfs_run_defrag_inode(fs_info, defrag); 346 } 347 atomic_dec(&fs_info->defrag_running); 348 349 /* 350 * during unmount, we use the transaction_wait queue to 351 * wait for the defragger to stop 352 */ 353 wake_up(&fs_info->transaction_wait); 354 return 0; 355 } 356 357 /* simple helper to fault in pages and copy. This should go away 358 * and be replaced with calls into generic code. 359 */ 360 static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes, 361 struct page **prepared_pages, 362 struct iov_iter *i) 363 { 364 size_t copied = 0; 365 size_t total_copied = 0; 366 int pg = 0; 367 int offset = offset_in_page(pos); 368 369 while (write_bytes > 0) { 370 size_t count = min_t(size_t, 371 PAGE_SIZE - offset, write_bytes); 372 struct page *page = prepared_pages[pg]; 373 /* 374 * Copy data from userspace to the current page 375 */ 376 copied = copy_page_from_iter_atomic(page, offset, count, i); 377 378 /* Flush processor's dcache for this page */ 379 flush_dcache_page(page); 380 381 /* 382 * if we get a partial write, we can end up with 383 * partially up to date pages. These add 384 * a lot of complexity, so make sure they don't 385 * happen by forcing this copy to be retried. 386 * 387 * The rest of the btrfs_file_write code will fall 388 * back to page at a time copies after we return 0. 389 */ 390 if (unlikely(copied < count)) { 391 if (!PageUptodate(page)) { 392 iov_iter_revert(i, copied); 393 copied = 0; 394 } 395 if (!copied) 396 break; 397 } 398 399 write_bytes -= copied; 400 total_copied += copied; 401 offset += copied; 402 if (offset == PAGE_SIZE) { 403 pg++; 404 offset = 0; 405 } 406 } 407 return total_copied; 408 } 409 410 /* 411 * unlocks pages after btrfs_file_write is done with them 412 */ 413 static void btrfs_drop_pages(struct btrfs_fs_info *fs_info, 414 struct page **pages, size_t num_pages, 415 u64 pos, u64 copied) 416 { 417 size_t i; 418 u64 block_start = round_down(pos, fs_info->sectorsize); 419 u64 block_len = round_up(pos + copied, fs_info->sectorsize) - block_start; 420 421 ASSERT(block_len <= U32_MAX); 422 for (i = 0; i < num_pages; i++) { 423 /* page checked is some magic around finding pages that 424 * have been modified without going through btrfs_set_page_dirty 425 * clear it here. There should be no need to mark the pages 426 * accessed as prepare_pages should have marked them accessed 427 * in prepare_pages via find_or_create_page() 428 */ 429 btrfs_page_clamp_clear_checked(fs_info, pages[i], block_start, 430 block_len); 431 unlock_page(pages[i]); 432 put_page(pages[i]); 433 } 434 } 435 436 /* 437 * After btrfs_copy_from_user(), update the following things for delalloc: 438 * - Mark newly dirtied pages as DELALLOC in the io tree. 439 * Used to advise which range is to be written back. 440 * - Mark modified pages as Uptodate/Dirty and not needing COW fixup 441 * - Update inode size for past EOF write 442 */ 443 int btrfs_dirty_pages(struct btrfs_inode *inode, struct page **pages, 444 size_t num_pages, loff_t pos, size_t write_bytes, 445 struct extent_state **cached, bool noreserve) 446 { 447 struct btrfs_fs_info *fs_info = inode->root->fs_info; 448 int err = 0; 449 int i; 450 u64 num_bytes; 451 u64 start_pos; 452 u64 end_of_last_block; 453 u64 end_pos = pos + write_bytes; 454 loff_t isize = i_size_read(&inode->vfs_inode); 455 unsigned int extra_bits = 0; 456 457 if (write_bytes == 0) 458 return 0; 459 460 if (noreserve) 461 extra_bits |= EXTENT_NORESERVE; 462 463 start_pos = round_down(pos, fs_info->sectorsize); 464 num_bytes = round_up(write_bytes + pos - start_pos, 465 fs_info->sectorsize); 466 ASSERT(num_bytes <= U32_MAX); 467 468 end_of_last_block = start_pos + num_bytes - 1; 469 470 /* 471 * The pages may have already been dirty, clear out old accounting so 472 * we can set things up properly 473 */ 474 clear_extent_bit(&inode->io_tree, start_pos, end_of_last_block, 475 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 476 0, 0, cached); 477 478 err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block, 479 extra_bits, cached); 480 if (err) 481 return err; 482 483 for (i = 0; i < num_pages; i++) { 484 struct page *p = pages[i]; 485 486 btrfs_page_clamp_set_uptodate(fs_info, p, start_pos, num_bytes); 487 btrfs_page_clamp_clear_checked(fs_info, p, start_pos, num_bytes); 488 btrfs_page_clamp_set_dirty(fs_info, p, start_pos, num_bytes); 489 } 490 491 /* 492 * we've only changed i_size in ram, and we haven't updated 493 * the disk i_size. There is no need to log the inode 494 * at this time. 495 */ 496 if (end_pos > isize) 497 i_size_write(&inode->vfs_inode, end_pos); 498 return 0; 499 } 500 501 /* 502 * this drops all the extents in the cache that intersect the range 503 * [start, end]. Existing extents are split as required. 504 */ 505 void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end, 506 int skip_pinned) 507 { 508 struct extent_map *em; 509 struct extent_map *split = NULL; 510 struct extent_map *split2 = NULL; 511 struct extent_map_tree *em_tree = &inode->extent_tree; 512 u64 len = end - start + 1; 513 u64 gen; 514 int ret; 515 int testend = 1; 516 unsigned long flags; 517 int compressed = 0; 518 bool modified; 519 520 WARN_ON(end < start); 521 if (end == (u64)-1) { 522 len = (u64)-1; 523 testend = 0; 524 } 525 while (1) { 526 bool ends_after_range = false; 527 int no_splits = 0; 528 529 modified = false; 530 if (!split) 531 split = alloc_extent_map(); 532 if (!split2) 533 split2 = alloc_extent_map(); 534 if (!split || !split2) 535 no_splits = 1; 536 537 write_lock(&em_tree->lock); 538 em = lookup_extent_mapping(em_tree, start, len); 539 if (!em) { 540 write_unlock(&em_tree->lock); 541 break; 542 } 543 if (testend && em->start + em->len > start + len) 544 ends_after_range = true; 545 flags = em->flags; 546 gen = em->generation; 547 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) { 548 if (ends_after_range) { 549 free_extent_map(em); 550 write_unlock(&em_tree->lock); 551 break; 552 } 553 start = em->start + em->len; 554 if (testend) 555 len = start + len - (em->start + em->len); 556 free_extent_map(em); 557 write_unlock(&em_tree->lock); 558 continue; 559 } 560 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags); 561 clear_bit(EXTENT_FLAG_PINNED, &em->flags); 562 clear_bit(EXTENT_FLAG_LOGGING, &flags); 563 modified = !list_empty(&em->list); 564 if (no_splits) 565 goto next; 566 567 if (em->start < start) { 568 split->start = em->start; 569 split->len = start - em->start; 570 571 if (em->block_start < EXTENT_MAP_LAST_BYTE) { 572 split->orig_start = em->orig_start; 573 split->block_start = em->block_start; 574 575 if (compressed) 576 split->block_len = em->block_len; 577 else 578 split->block_len = split->len; 579 split->orig_block_len = max(split->block_len, 580 em->orig_block_len); 581 split->ram_bytes = em->ram_bytes; 582 } else { 583 split->orig_start = split->start; 584 split->block_len = 0; 585 split->block_start = em->block_start; 586 split->orig_block_len = 0; 587 split->ram_bytes = split->len; 588 } 589 590 split->generation = gen; 591 split->flags = flags; 592 split->compress_type = em->compress_type; 593 replace_extent_mapping(em_tree, em, split, modified); 594 free_extent_map(split); 595 split = split2; 596 split2 = NULL; 597 } 598 if (ends_after_range) { 599 u64 diff = start + len - em->start; 600 601 split->start = start + len; 602 split->len = em->start + em->len - (start + len); 603 split->flags = flags; 604 split->compress_type = em->compress_type; 605 split->generation = gen; 606 607 if (em->block_start < EXTENT_MAP_LAST_BYTE) { 608 split->orig_block_len = max(em->block_len, 609 em->orig_block_len); 610 611 split->ram_bytes = em->ram_bytes; 612 if (compressed) { 613 split->block_len = em->block_len; 614 split->block_start = em->block_start; 615 split->orig_start = em->orig_start; 616 } else { 617 split->block_len = split->len; 618 split->block_start = em->block_start 619 + diff; 620 split->orig_start = em->orig_start; 621 } 622 } else { 623 split->ram_bytes = split->len; 624 split->orig_start = split->start; 625 split->block_len = 0; 626 split->block_start = em->block_start; 627 split->orig_block_len = 0; 628 } 629 630 if (extent_map_in_tree(em)) { 631 replace_extent_mapping(em_tree, em, split, 632 modified); 633 } else { 634 ret = add_extent_mapping(em_tree, split, 635 modified); 636 /* Logic error, shouldn't happen. */ 637 ASSERT(ret == 0); 638 if (WARN_ON(ret != 0) && modified) 639 btrfs_set_inode_full_sync(inode); 640 } 641 free_extent_map(split); 642 split = NULL; 643 } 644 next: 645 if (extent_map_in_tree(em)) { 646 /* 647 * If the extent map is still in the tree it means that 648 * either of the following is true: 649 * 650 * 1) It fits entirely in our range (doesn't end beyond 651 * it or starts before it); 652 * 653 * 2) It starts before our range and/or ends after our 654 * range, and we were not able to allocate the extent 655 * maps for split operations, @split and @split2. 656 * 657 * If we are at case 2) then we just remove the entire 658 * extent map - this is fine since if anyone needs it to 659 * access the subranges outside our range, will just 660 * load it again from the subvolume tree's file extent 661 * item. However if the extent map was in the list of 662 * modified extents, then we must mark the inode for a 663 * full fsync, otherwise a fast fsync will miss this 664 * extent if it's new and needs to be logged. 665 */ 666 if ((em->start < start || ends_after_range) && modified) { 667 ASSERT(no_splits); 668 btrfs_set_inode_full_sync(inode); 669 } 670 remove_extent_mapping(em_tree, em); 671 } 672 write_unlock(&em_tree->lock); 673 674 /* once for us */ 675 free_extent_map(em); 676 /* once for the tree*/ 677 free_extent_map(em); 678 } 679 if (split) 680 free_extent_map(split); 681 if (split2) 682 free_extent_map(split2); 683 } 684 685 /* 686 * this is very complex, but the basic idea is to drop all extents 687 * in the range start - end. hint_block is filled in with a block number 688 * that would be a good hint to the block allocator for this file. 689 * 690 * If an extent intersects the range but is not entirely inside the range 691 * it is either truncated or split. Anything entirely inside the range 692 * is deleted from the tree. 693 * 694 * Note: the VFS' inode number of bytes is not updated, it's up to the caller 695 * to deal with that. We set the field 'bytes_found' of the arguments structure 696 * with the number of allocated bytes found in the target range, so that the 697 * caller can update the inode's number of bytes in an atomic way when 698 * replacing extents in a range to avoid races with stat(2). 699 */ 700 int btrfs_drop_extents(struct btrfs_trans_handle *trans, 701 struct btrfs_root *root, struct btrfs_inode *inode, 702 struct btrfs_drop_extents_args *args) 703 { 704 struct btrfs_fs_info *fs_info = root->fs_info; 705 struct extent_buffer *leaf; 706 struct btrfs_file_extent_item *fi; 707 struct btrfs_ref ref = { 0 }; 708 struct btrfs_key key; 709 struct btrfs_key new_key; 710 u64 ino = btrfs_ino(inode); 711 u64 search_start = args->start; 712 u64 disk_bytenr = 0; 713 u64 num_bytes = 0; 714 u64 extent_offset = 0; 715 u64 extent_end = 0; 716 u64 last_end = args->start; 717 int del_nr = 0; 718 int del_slot = 0; 719 int extent_type; 720 int recow; 721 int ret; 722 int modify_tree = -1; 723 int update_refs; 724 int found = 0; 725 struct btrfs_path *path = args->path; 726 727 args->bytes_found = 0; 728 args->extent_inserted = false; 729 730 /* Must always have a path if ->replace_extent is true */ 731 ASSERT(!(args->replace_extent && !args->path)); 732 733 if (!path) { 734 path = btrfs_alloc_path(); 735 if (!path) { 736 ret = -ENOMEM; 737 goto out; 738 } 739 } 740 741 if (args->drop_cache) 742 btrfs_drop_extent_cache(inode, args->start, args->end - 1, 0); 743 744 if (args->start >= inode->disk_i_size && !args->replace_extent) 745 modify_tree = 0; 746 747 update_refs = (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID); 748 while (1) { 749 recow = 0; 750 ret = btrfs_lookup_file_extent(trans, root, path, ino, 751 search_start, modify_tree); 752 if (ret < 0) 753 break; 754 if (ret > 0 && path->slots[0] > 0 && search_start == args->start) { 755 leaf = path->nodes[0]; 756 btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1); 757 if (key.objectid == ino && 758 key.type == BTRFS_EXTENT_DATA_KEY) 759 path->slots[0]--; 760 } 761 ret = 0; 762 next_slot: 763 leaf = path->nodes[0]; 764 if (path->slots[0] >= btrfs_header_nritems(leaf)) { 765 BUG_ON(del_nr > 0); 766 ret = btrfs_next_leaf(root, path); 767 if (ret < 0) 768 break; 769 if (ret > 0) { 770 ret = 0; 771 break; 772 } 773 leaf = path->nodes[0]; 774 recow = 1; 775 } 776 777 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 778 779 if (key.objectid > ino) 780 break; 781 if (WARN_ON_ONCE(key.objectid < ino) || 782 key.type < BTRFS_EXTENT_DATA_KEY) { 783 ASSERT(del_nr == 0); 784 path->slots[0]++; 785 goto next_slot; 786 } 787 if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end) 788 break; 789 790 fi = btrfs_item_ptr(leaf, path->slots[0], 791 struct btrfs_file_extent_item); 792 extent_type = btrfs_file_extent_type(leaf, fi); 793 794 if (extent_type == BTRFS_FILE_EXTENT_REG || 795 extent_type == BTRFS_FILE_EXTENT_PREALLOC) { 796 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); 797 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); 798 extent_offset = btrfs_file_extent_offset(leaf, fi); 799 extent_end = key.offset + 800 btrfs_file_extent_num_bytes(leaf, fi); 801 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 802 extent_end = key.offset + 803 btrfs_file_extent_ram_bytes(leaf, fi); 804 } else { 805 /* can't happen */ 806 BUG(); 807 } 808 809 /* 810 * Don't skip extent items representing 0 byte lengths. They 811 * used to be created (bug) if while punching holes we hit 812 * -ENOSPC condition. So if we find one here, just ensure we 813 * delete it, otherwise we would insert a new file extent item 814 * with the same key (offset) as that 0 bytes length file 815 * extent item in the call to setup_items_for_insert() later 816 * in this function. 817 */ 818 if (extent_end == key.offset && extent_end >= search_start) { 819 last_end = extent_end; 820 goto delete_extent_item; 821 } 822 823 if (extent_end <= search_start) { 824 path->slots[0]++; 825 goto next_slot; 826 } 827 828 found = 1; 829 search_start = max(key.offset, args->start); 830 if (recow || !modify_tree) { 831 modify_tree = -1; 832 btrfs_release_path(path); 833 continue; 834 } 835 836 /* 837 * | - range to drop - | 838 * | -------- extent -------- | 839 */ 840 if (args->start > key.offset && args->end < extent_end) { 841 BUG_ON(del_nr > 0); 842 if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 843 ret = -EOPNOTSUPP; 844 break; 845 } 846 847 memcpy(&new_key, &key, sizeof(new_key)); 848 new_key.offset = args->start; 849 ret = btrfs_duplicate_item(trans, root, path, 850 &new_key); 851 if (ret == -EAGAIN) { 852 btrfs_release_path(path); 853 continue; 854 } 855 if (ret < 0) 856 break; 857 858 leaf = path->nodes[0]; 859 fi = btrfs_item_ptr(leaf, path->slots[0] - 1, 860 struct btrfs_file_extent_item); 861 btrfs_set_file_extent_num_bytes(leaf, fi, 862 args->start - key.offset); 863 864 fi = btrfs_item_ptr(leaf, path->slots[0], 865 struct btrfs_file_extent_item); 866 867 extent_offset += args->start - key.offset; 868 btrfs_set_file_extent_offset(leaf, fi, extent_offset); 869 btrfs_set_file_extent_num_bytes(leaf, fi, 870 extent_end - args->start); 871 btrfs_mark_buffer_dirty(leaf); 872 873 if (update_refs && disk_bytenr > 0) { 874 btrfs_init_generic_ref(&ref, 875 BTRFS_ADD_DELAYED_REF, 876 disk_bytenr, num_bytes, 0); 877 btrfs_init_data_ref(&ref, 878 root->root_key.objectid, 879 new_key.objectid, 880 args->start - extent_offset, 881 0, false); 882 ret = btrfs_inc_extent_ref(trans, &ref); 883 BUG_ON(ret); /* -ENOMEM */ 884 } 885 key.offset = args->start; 886 } 887 /* 888 * From here on out we will have actually dropped something, so 889 * last_end can be updated. 890 */ 891 last_end = extent_end; 892 893 /* 894 * | ---- range to drop ----- | 895 * | -------- extent -------- | 896 */ 897 if (args->start <= key.offset && args->end < extent_end) { 898 if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 899 ret = -EOPNOTSUPP; 900 break; 901 } 902 903 memcpy(&new_key, &key, sizeof(new_key)); 904 new_key.offset = args->end; 905 btrfs_set_item_key_safe(fs_info, path, &new_key); 906 907 extent_offset += args->end - key.offset; 908 btrfs_set_file_extent_offset(leaf, fi, extent_offset); 909 btrfs_set_file_extent_num_bytes(leaf, fi, 910 extent_end - args->end); 911 btrfs_mark_buffer_dirty(leaf); 912 if (update_refs && disk_bytenr > 0) 913 args->bytes_found += args->end - key.offset; 914 break; 915 } 916 917 search_start = extent_end; 918 /* 919 * | ---- range to drop ----- | 920 * | -------- extent -------- | 921 */ 922 if (args->start > key.offset && args->end >= extent_end) { 923 BUG_ON(del_nr > 0); 924 if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 925 ret = -EOPNOTSUPP; 926 break; 927 } 928 929 btrfs_set_file_extent_num_bytes(leaf, fi, 930 args->start - key.offset); 931 btrfs_mark_buffer_dirty(leaf); 932 if (update_refs && disk_bytenr > 0) 933 args->bytes_found += extent_end - args->start; 934 if (args->end == extent_end) 935 break; 936 937 path->slots[0]++; 938 goto next_slot; 939 } 940 941 /* 942 * | ---- range to drop ----- | 943 * | ------ extent ------ | 944 */ 945 if (args->start <= key.offset && args->end >= extent_end) { 946 delete_extent_item: 947 if (del_nr == 0) { 948 del_slot = path->slots[0]; 949 del_nr = 1; 950 } else { 951 BUG_ON(del_slot + del_nr != path->slots[0]); 952 del_nr++; 953 } 954 955 if (update_refs && 956 extent_type == BTRFS_FILE_EXTENT_INLINE) { 957 args->bytes_found += extent_end - key.offset; 958 extent_end = ALIGN(extent_end, 959 fs_info->sectorsize); 960 } else if (update_refs && disk_bytenr > 0) { 961 btrfs_init_generic_ref(&ref, 962 BTRFS_DROP_DELAYED_REF, 963 disk_bytenr, num_bytes, 0); 964 btrfs_init_data_ref(&ref, 965 root->root_key.objectid, 966 key.objectid, 967 key.offset - extent_offset, 0, 968 false); 969 ret = btrfs_free_extent(trans, &ref); 970 BUG_ON(ret); /* -ENOMEM */ 971 args->bytes_found += extent_end - key.offset; 972 } 973 974 if (args->end == extent_end) 975 break; 976 977 if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) { 978 path->slots[0]++; 979 goto next_slot; 980 } 981 982 ret = btrfs_del_items(trans, root, path, del_slot, 983 del_nr); 984 if (ret) { 985 btrfs_abort_transaction(trans, ret); 986 break; 987 } 988 989 del_nr = 0; 990 del_slot = 0; 991 992 btrfs_release_path(path); 993 continue; 994 } 995 996 BUG(); 997 } 998 999 if (!ret && del_nr > 0) { 1000 /* 1001 * Set path->slots[0] to first slot, so that after the delete 1002 * if items are move off from our leaf to its immediate left or 1003 * right neighbor leafs, we end up with a correct and adjusted 1004 * path->slots[0] for our insertion (if args->replace_extent). 1005 */ 1006 path->slots[0] = del_slot; 1007 ret = btrfs_del_items(trans, root, path, del_slot, del_nr); 1008 if (ret) 1009 btrfs_abort_transaction(trans, ret); 1010 } 1011 1012 leaf = path->nodes[0]; 1013 /* 1014 * If btrfs_del_items() was called, it might have deleted a leaf, in 1015 * which case it unlocked our path, so check path->locks[0] matches a 1016 * write lock. 1017 */ 1018 if (!ret && args->replace_extent && 1019 path->locks[0] == BTRFS_WRITE_LOCK && 1020 btrfs_leaf_free_space(leaf) >= 1021 sizeof(struct btrfs_item) + args->extent_item_size) { 1022 1023 key.objectid = ino; 1024 key.type = BTRFS_EXTENT_DATA_KEY; 1025 key.offset = args->start; 1026 if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) { 1027 struct btrfs_key slot_key; 1028 1029 btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]); 1030 if (btrfs_comp_cpu_keys(&key, &slot_key) > 0) 1031 path->slots[0]++; 1032 } 1033 btrfs_setup_item_for_insert(root, path, &key, args->extent_item_size); 1034 args->extent_inserted = true; 1035 } 1036 1037 if (!args->path) 1038 btrfs_free_path(path); 1039 else if (!args->extent_inserted) 1040 btrfs_release_path(path); 1041 out: 1042 args->drop_end = found ? min(args->end, last_end) : args->end; 1043 1044 return ret; 1045 } 1046 1047 static int extent_mergeable(struct extent_buffer *leaf, int slot, 1048 u64 objectid, u64 bytenr, u64 orig_offset, 1049 u64 *start, u64 *end) 1050 { 1051 struct btrfs_file_extent_item *fi; 1052 struct btrfs_key key; 1053 u64 extent_end; 1054 1055 if (slot < 0 || slot >= btrfs_header_nritems(leaf)) 1056 return 0; 1057 1058 btrfs_item_key_to_cpu(leaf, &key, slot); 1059 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY) 1060 return 0; 1061 1062 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); 1063 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG || 1064 btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr || 1065 btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset || 1066 btrfs_file_extent_compression(leaf, fi) || 1067 btrfs_file_extent_encryption(leaf, fi) || 1068 btrfs_file_extent_other_encoding(leaf, fi)) 1069 return 0; 1070 1071 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); 1072 if ((*start && *start != key.offset) || (*end && *end != extent_end)) 1073 return 0; 1074 1075 *start = key.offset; 1076 *end = extent_end; 1077 return 1; 1078 } 1079 1080 /* 1081 * Mark extent in the range start - end as written. 1082 * 1083 * This changes extent type from 'pre-allocated' to 'regular'. If only 1084 * part of extent is marked as written, the extent will be split into 1085 * two or three. 1086 */ 1087 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans, 1088 struct btrfs_inode *inode, u64 start, u64 end) 1089 { 1090 struct btrfs_fs_info *fs_info = trans->fs_info; 1091 struct btrfs_root *root = inode->root; 1092 struct extent_buffer *leaf; 1093 struct btrfs_path *path; 1094 struct btrfs_file_extent_item *fi; 1095 struct btrfs_ref ref = { 0 }; 1096 struct btrfs_key key; 1097 struct btrfs_key new_key; 1098 u64 bytenr; 1099 u64 num_bytes; 1100 u64 extent_end; 1101 u64 orig_offset; 1102 u64 other_start; 1103 u64 other_end; 1104 u64 split; 1105 int del_nr = 0; 1106 int del_slot = 0; 1107 int recow; 1108 int ret = 0; 1109 u64 ino = btrfs_ino(inode); 1110 1111 path = btrfs_alloc_path(); 1112 if (!path) 1113 return -ENOMEM; 1114 again: 1115 recow = 0; 1116 split = start; 1117 key.objectid = ino; 1118 key.type = BTRFS_EXTENT_DATA_KEY; 1119 key.offset = split; 1120 1121 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 1122 if (ret < 0) 1123 goto out; 1124 if (ret > 0 && path->slots[0] > 0) 1125 path->slots[0]--; 1126 1127 leaf = path->nodes[0]; 1128 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 1129 if (key.objectid != ino || 1130 key.type != BTRFS_EXTENT_DATA_KEY) { 1131 ret = -EINVAL; 1132 btrfs_abort_transaction(trans, ret); 1133 goto out; 1134 } 1135 fi = btrfs_item_ptr(leaf, path->slots[0], 1136 struct btrfs_file_extent_item); 1137 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) { 1138 ret = -EINVAL; 1139 btrfs_abort_transaction(trans, ret); 1140 goto out; 1141 } 1142 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); 1143 if (key.offset > start || extent_end < end) { 1144 ret = -EINVAL; 1145 btrfs_abort_transaction(trans, ret); 1146 goto out; 1147 } 1148 1149 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); 1150 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); 1151 orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi); 1152 memcpy(&new_key, &key, sizeof(new_key)); 1153 1154 if (start == key.offset && end < extent_end) { 1155 other_start = 0; 1156 other_end = start; 1157 if (extent_mergeable(leaf, path->slots[0] - 1, 1158 ino, bytenr, orig_offset, 1159 &other_start, &other_end)) { 1160 new_key.offset = end; 1161 btrfs_set_item_key_safe(fs_info, path, &new_key); 1162 fi = btrfs_item_ptr(leaf, path->slots[0], 1163 struct btrfs_file_extent_item); 1164 btrfs_set_file_extent_generation(leaf, fi, 1165 trans->transid); 1166 btrfs_set_file_extent_num_bytes(leaf, fi, 1167 extent_end - end); 1168 btrfs_set_file_extent_offset(leaf, fi, 1169 end - orig_offset); 1170 fi = btrfs_item_ptr(leaf, path->slots[0] - 1, 1171 struct btrfs_file_extent_item); 1172 btrfs_set_file_extent_generation(leaf, fi, 1173 trans->transid); 1174 btrfs_set_file_extent_num_bytes(leaf, fi, 1175 end - other_start); 1176 btrfs_mark_buffer_dirty(leaf); 1177 goto out; 1178 } 1179 } 1180 1181 if (start > key.offset && end == extent_end) { 1182 other_start = end; 1183 other_end = 0; 1184 if (extent_mergeable(leaf, path->slots[0] + 1, 1185 ino, bytenr, orig_offset, 1186 &other_start, &other_end)) { 1187 fi = btrfs_item_ptr(leaf, path->slots[0], 1188 struct btrfs_file_extent_item); 1189 btrfs_set_file_extent_num_bytes(leaf, fi, 1190 start - key.offset); 1191 btrfs_set_file_extent_generation(leaf, fi, 1192 trans->transid); 1193 path->slots[0]++; 1194 new_key.offset = start; 1195 btrfs_set_item_key_safe(fs_info, path, &new_key); 1196 1197 fi = btrfs_item_ptr(leaf, path->slots[0], 1198 struct btrfs_file_extent_item); 1199 btrfs_set_file_extent_generation(leaf, fi, 1200 trans->transid); 1201 btrfs_set_file_extent_num_bytes(leaf, fi, 1202 other_end - start); 1203 btrfs_set_file_extent_offset(leaf, fi, 1204 start - orig_offset); 1205 btrfs_mark_buffer_dirty(leaf); 1206 goto out; 1207 } 1208 } 1209 1210 while (start > key.offset || end < extent_end) { 1211 if (key.offset == start) 1212 split = end; 1213 1214 new_key.offset = split; 1215 ret = btrfs_duplicate_item(trans, root, path, &new_key); 1216 if (ret == -EAGAIN) { 1217 btrfs_release_path(path); 1218 goto again; 1219 } 1220 if (ret < 0) { 1221 btrfs_abort_transaction(trans, ret); 1222 goto out; 1223 } 1224 1225 leaf = path->nodes[0]; 1226 fi = btrfs_item_ptr(leaf, path->slots[0] - 1, 1227 struct btrfs_file_extent_item); 1228 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 1229 btrfs_set_file_extent_num_bytes(leaf, fi, 1230 split - key.offset); 1231 1232 fi = btrfs_item_ptr(leaf, path->slots[0], 1233 struct btrfs_file_extent_item); 1234 1235 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 1236 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset); 1237 btrfs_set_file_extent_num_bytes(leaf, fi, 1238 extent_end - split); 1239 btrfs_mark_buffer_dirty(leaf); 1240 1241 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr, 1242 num_bytes, 0); 1243 btrfs_init_data_ref(&ref, root->root_key.objectid, ino, 1244 orig_offset, 0, false); 1245 ret = btrfs_inc_extent_ref(trans, &ref); 1246 if (ret) { 1247 btrfs_abort_transaction(trans, ret); 1248 goto out; 1249 } 1250 1251 if (split == start) { 1252 key.offset = start; 1253 } else { 1254 if (start != key.offset) { 1255 ret = -EINVAL; 1256 btrfs_abort_transaction(trans, ret); 1257 goto out; 1258 } 1259 path->slots[0]--; 1260 extent_end = end; 1261 } 1262 recow = 1; 1263 } 1264 1265 other_start = end; 1266 other_end = 0; 1267 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr, 1268 num_bytes, 0); 1269 btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset, 1270 0, false); 1271 if (extent_mergeable(leaf, path->slots[0] + 1, 1272 ino, bytenr, orig_offset, 1273 &other_start, &other_end)) { 1274 if (recow) { 1275 btrfs_release_path(path); 1276 goto again; 1277 } 1278 extent_end = other_end; 1279 del_slot = path->slots[0] + 1; 1280 del_nr++; 1281 ret = btrfs_free_extent(trans, &ref); 1282 if (ret) { 1283 btrfs_abort_transaction(trans, ret); 1284 goto out; 1285 } 1286 } 1287 other_start = 0; 1288 other_end = start; 1289 if (extent_mergeable(leaf, path->slots[0] - 1, 1290 ino, bytenr, orig_offset, 1291 &other_start, &other_end)) { 1292 if (recow) { 1293 btrfs_release_path(path); 1294 goto again; 1295 } 1296 key.offset = other_start; 1297 del_slot = path->slots[0]; 1298 del_nr++; 1299 ret = btrfs_free_extent(trans, &ref); 1300 if (ret) { 1301 btrfs_abort_transaction(trans, ret); 1302 goto out; 1303 } 1304 } 1305 if (del_nr == 0) { 1306 fi = btrfs_item_ptr(leaf, path->slots[0], 1307 struct btrfs_file_extent_item); 1308 btrfs_set_file_extent_type(leaf, fi, 1309 BTRFS_FILE_EXTENT_REG); 1310 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 1311 btrfs_mark_buffer_dirty(leaf); 1312 } else { 1313 fi = btrfs_item_ptr(leaf, del_slot - 1, 1314 struct btrfs_file_extent_item); 1315 btrfs_set_file_extent_type(leaf, fi, 1316 BTRFS_FILE_EXTENT_REG); 1317 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 1318 btrfs_set_file_extent_num_bytes(leaf, fi, 1319 extent_end - key.offset); 1320 btrfs_mark_buffer_dirty(leaf); 1321 1322 ret = btrfs_del_items(trans, root, path, del_slot, del_nr); 1323 if (ret < 0) { 1324 btrfs_abort_transaction(trans, ret); 1325 goto out; 1326 } 1327 } 1328 out: 1329 btrfs_free_path(path); 1330 return ret; 1331 } 1332 1333 /* 1334 * on error we return an unlocked page and the error value 1335 * on success we return a locked page and 0 1336 */ 1337 static int prepare_uptodate_page(struct inode *inode, 1338 struct page *page, u64 pos, 1339 bool force_uptodate) 1340 { 1341 struct folio *folio = page_folio(page); 1342 int ret = 0; 1343 1344 if (((pos & (PAGE_SIZE - 1)) || force_uptodate) && 1345 !PageUptodate(page)) { 1346 ret = btrfs_read_folio(NULL, folio); 1347 if (ret) 1348 return ret; 1349 lock_page(page); 1350 if (!PageUptodate(page)) { 1351 unlock_page(page); 1352 return -EIO; 1353 } 1354 1355 /* 1356 * Since btrfs_read_folio() will unlock the folio before it 1357 * returns, there is a window where btrfs_release_folio() can be 1358 * called to release the page. Here we check both inode 1359 * mapping and PagePrivate() to make sure the page was not 1360 * released. 1361 * 1362 * The private flag check is essential for subpage as we need 1363 * to store extra bitmap using page->private. 1364 */ 1365 if (page->mapping != inode->i_mapping || !PagePrivate(page)) { 1366 unlock_page(page); 1367 return -EAGAIN; 1368 } 1369 } 1370 return 0; 1371 } 1372 1373 /* 1374 * this just gets pages into the page cache and locks them down. 1375 */ 1376 static noinline int prepare_pages(struct inode *inode, struct page **pages, 1377 size_t num_pages, loff_t pos, 1378 size_t write_bytes, bool force_uptodate) 1379 { 1380 int i; 1381 unsigned long index = pos >> PAGE_SHIFT; 1382 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping); 1383 int err = 0; 1384 int faili; 1385 1386 for (i = 0; i < num_pages; i++) { 1387 again: 1388 pages[i] = find_or_create_page(inode->i_mapping, index + i, 1389 mask | __GFP_WRITE); 1390 if (!pages[i]) { 1391 faili = i - 1; 1392 err = -ENOMEM; 1393 goto fail; 1394 } 1395 1396 err = set_page_extent_mapped(pages[i]); 1397 if (err < 0) { 1398 faili = i; 1399 goto fail; 1400 } 1401 1402 if (i == 0) 1403 err = prepare_uptodate_page(inode, pages[i], pos, 1404 force_uptodate); 1405 if (!err && i == num_pages - 1) 1406 err = prepare_uptodate_page(inode, pages[i], 1407 pos + write_bytes, false); 1408 if (err) { 1409 put_page(pages[i]); 1410 if (err == -EAGAIN) { 1411 err = 0; 1412 goto again; 1413 } 1414 faili = i - 1; 1415 goto fail; 1416 } 1417 wait_on_page_writeback(pages[i]); 1418 } 1419 1420 return 0; 1421 fail: 1422 while (faili >= 0) { 1423 unlock_page(pages[faili]); 1424 put_page(pages[faili]); 1425 faili--; 1426 } 1427 return err; 1428 1429 } 1430 1431 /* 1432 * This function locks the extent and properly waits for data=ordered extents 1433 * to finish before allowing the pages to be modified if need. 1434 * 1435 * The return value: 1436 * 1 - the extent is locked 1437 * 0 - the extent is not locked, and everything is OK 1438 * -EAGAIN - need re-prepare the pages 1439 * the other < 0 number - Something wrong happens 1440 */ 1441 static noinline int 1442 lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages, 1443 size_t num_pages, loff_t pos, 1444 size_t write_bytes, 1445 u64 *lockstart, u64 *lockend, 1446 struct extent_state **cached_state) 1447 { 1448 struct btrfs_fs_info *fs_info = inode->root->fs_info; 1449 u64 start_pos; 1450 u64 last_pos; 1451 int i; 1452 int ret = 0; 1453 1454 start_pos = round_down(pos, fs_info->sectorsize); 1455 last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1; 1456 1457 if (start_pos < inode->vfs_inode.i_size) { 1458 struct btrfs_ordered_extent *ordered; 1459 1460 lock_extent_bits(&inode->io_tree, start_pos, last_pos, 1461 cached_state); 1462 ordered = btrfs_lookup_ordered_range(inode, start_pos, 1463 last_pos - start_pos + 1); 1464 if (ordered && 1465 ordered->file_offset + ordered->num_bytes > start_pos && 1466 ordered->file_offset <= last_pos) { 1467 unlock_extent_cached(&inode->io_tree, start_pos, 1468 last_pos, cached_state); 1469 for (i = 0; i < num_pages; i++) { 1470 unlock_page(pages[i]); 1471 put_page(pages[i]); 1472 } 1473 btrfs_start_ordered_extent(ordered, 1); 1474 btrfs_put_ordered_extent(ordered); 1475 return -EAGAIN; 1476 } 1477 if (ordered) 1478 btrfs_put_ordered_extent(ordered); 1479 1480 *lockstart = start_pos; 1481 *lockend = last_pos; 1482 ret = 1; 1483 } 1484 1485 /* 1486 * We should be called after prepare_pages() which should have locked 1487 * all pages in the range. 1488 */ 1489 for (i = 0; i < num_pages; i++) 1490 WARN_ON(!PageLocked(pages[i])); 1491 1492 return ret; 1493 } 1494 1495 /* 1496 * Check if we can do nocow write into the range [@pos, @pos + @write_bytes) 1497 * 1498 * @pos: File offset. 1499 * @write_bytes: The length to write, will be updated to the nocow writeable 1500 * range. 1501 * 1502 * This function will flush ordered extents in the range to ensure proper 1503 * nocow checks. 1504 * 1505 * Return: 1506 * > 0 If we can nocow, and updates @write_bytes. 1507 * 0 If we can't do a nocow write. 1508 * -EAGAIN If we can't do a nocow write because snapshoting of the inode's 1509 * root is in progress. 1510 * < 0 If an error happened. 1511 * 1512 * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0. 1513 */ 1514 int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos, 1515 size_t *write_bytes) 1516 { 1517 struct btrfs_fs_info *fs_info = inode->root->fs_info; 1518 struct btrfs_root *root = inode->root; 1519 u64 lockstart, lockend; 1520 u64 num_bytes; 1521 int ret; 1522 1523 if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC))) 1524 return 0; 1525 1526 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) 1527 return -EAGAIN; 1528 1529 lockstart = round_down(pos, fs_info->sectorsize); 1530 lockend = round_up(pos + *write_bytes, 1531 fs_info->sectorsize) - 1; 1532 num_bytes = lockend - lockstart + 1; 1533 1534 btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend, NULL); 1535 ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes, 1536 NULL, NULL, NULL, false); 1537 if (ret <= 0) { 1538 ret = 0; 1539 btrfs_drew_write_unlock(&root->snapshot_lock); 1540 } else { 1541 *write_bytes = min_t(size_t, *write_bytes , 1542 num_bytes - pos + lockstart); 1543 } 1544 unlock_extent(&inode->io_tree, lockstart, lockend); 1545 1546 return ret; 1547 } 1548 1549 void btrfs_check_nocow_unlock(struct btrfs_inode *inode) 1550 { 1551 btrfs_drew_write_unlock(&inode->root->snapshot_lock); 1552 } 1553 1554 static void update_time_for_write(struct inode *inode) 1555 { 1556 struct timespec64 now; 1557 1558 if (IS_NOCMTIME(inode)) 1559 return; 1560 1561 now = current_time(inode); 1562 if (!timespec64_equal(&inode->i_mtime, &now)) 1563 inode->i_mtime = now; 1564 1565 if (!timespec64_equal(&inode->i_ctime, &now)) 1566 inode->i_ctime = now; 1567 1568 if (IS_I_VERSION(inode)) 1569 inode_inc_iversion(inode); 1570 } 1571 1572 static int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from, 1573 size_t count) 1574 { 1575 struct file *file = iocb->ki_filp; 1576 struct inode *inode = file_inode(file); 1577 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 1578 loff_t pos = iocb->ki_pos; 1579 int ret; 1580 loff_t oldsize; 1581 loff_t start_pos; 1582 1583 /* 1584 * Quickly bail out on NOWAIT writes if we don't have the nodatacow or 1585 * prealloc flags, as without those flags we always have to COW. We will 1586 * later check if we can really COW into the target range (using 1587 * can_nocow_extent() at btrfs_get_blocks_direct_write()). 1588 */ 1589 if ((iocb->ki_flags & IOCB_NOWAIT) && 1590 !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC))) 1591 return -EAGAIN; 1592 1593 current->backing_dev_info = inode_to_bdi(inode); 1594 ret = file_remove_privs(file); 1595 if (ret) 1596 return ret; 1597 1598 /* 1599 * We reserve space for updating the inode when we reserve space for the 1600 * extent we are going to write, so we will enospc out there. We don't 1601 * need to start yet another transaction to update the inode as we will 1602 * update the inode when we finish writing whatever data we write. 1603 */ 1604 update_time_for_write(inode); 1605 1606 start_pos = round_down(pos, fs_info->sectorsize); 1607 oldsize = i_size_read(inode); 1608 if (start_pos > oldsize) { 1609 /* Expand hole size to cover write data, preventing empty gap */ 1610 loff_t end_pos = round_up(pos + count, fs_info->sectorsize); 1611 1612 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos); 1613 if (ret) { 1614 current->backing_dev_info = NULL; 1615 return ret; 1616 } 1617 } 1618 1619 return 0; 1620 } 1621 1622 static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb, 1623 struct iov_iter *i) 1624 { 1625 struct file *file = iocb->ki_filp; 1626 loff_t pos; 1627 struct inode *inode = file_inode(file); 1628 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 1629 struct page **pages = NULL; 1630 struct extent_changeset *data_reserved = NULL; 1631 u64 release_bytes = 0; 1632 u64 lockstart; 1633 u64 lockend; 1634 size_t num_written = 0; 1635 int nrptrs; 1636 ssize_t ret; 1637 bool only_release_metadata = false; 1638 bool force_page_uptodate = false; 1639 loff_t old_isize = i_size_read(inode); 1640 unsigned int ilock_flags = 0; 1641 1642 if (iocb->ki_flags & IOCB_NOWAIT) 1643 ilock_flags |= BTRFS_ILOCK_TRY; 1644 1645 ret = btrfs_inode_lock(inode, ilock_flags); 1646 if (ret < 0) 1647 return ret; 1648 1649 ret = generic_write_checks(iocb, i); 1650 if (ret <= 0) 1651 goto out; 1652 1653 ret = btrfs_write_check(iocb, i, ret); 1654 if (ret < 0) 1655 goto out; 1656 1657 pos = iocb->ki_pos; 1658 nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE), 1659 PAGE_SIZE / (sizeof(struct page *))); 1660 nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied); 1661 nrptrs = max(nrptrs, 8); 1662 pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL); 1663 if (!pages) { 1664 ret = -ENOMEM; 1665 goto out; 1666 } 1667 1668 while (iov_iter_count(i) > 0) { 1669 struct extent_state *cached_state = NULL; 1670 size_t offset = offset_in_page(pos); 1671 size_t sector_offset; 1672 size_t write_bytes = min(iov_iter_count(i), 1673 nrptrs * (size_t)PAGE_SIZE - 1674 offset); 1675 size_t num_pages; 1676 size_t reserve_bytes; 1677 size_t dirty_pages; 1678 size_t copied; 1679 size_t dirty_sectors; 1680 size_t num_sectors; 1681 int extents_locked; 1682 1683 /* 1684 * Fault pages before locking them in prepare_pages 1685 * to avoid recursive lock 1686 */ 1687 if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) { 1688 ret = -EFAULT; 1689 break; 1690 } 1691 1692 only_release_metadata = false; 1693 sector_offset = pos & (fs_info->sectorsize - 1); 1694 1695 extent_changeset_release(data_reserved); 1696 ret = btrfs_check_data_free_space(BTRFS_I(inode), 1697 &data_reserved, pos, 1698 write_bytes); 1699 if (ret < 0) { 1700 /* 1701 * If we don't have to COW at the offset, reserve 1702 * metadata only. write_bytes may get smaller than 1703 * requested here. 1704 */ 1705 if (btrfs_check_nocow_lock(BTRFS_I(inode), pos, 1706 &write_bytes) > 0) 1707 only_release_metadata = true; 1708 else 1709 break; 1710 } 1711 1712 num_pages = DIV_ROUND_UP(write_bytes + offset, PAGE_SIZE); 1713 WARN_ON(num_pages > nrptrs); 1714 reserve_bytes = round_up(write_bytes + sector_offset, 1715 fs_info->sectorsize); 1716 WARN_ON(reserve_bytes == 0); 1717 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), 1718 reserve_bytes, 1719 reserve_bytes, false); 1720 if (ret) { 1721 if (!only_release_metadata) 1722 btrfs_free_reserved_data_space(BTRFS_I(inode), 1723 data_reserved, pos, 1724 write_bytes); 1725 else 1726 btrfs_check_nocow_unlock(BTRFS_I(inode)); 1727 break; 1728 } 1729 1730 release_bytes = reserve_bytes; 1731 again: 1732 /* 1733 * This is going to setup the pages array with the number of 1734 * pages we want, so we don't really need to worry about the 1735 * contents of pages from loop to loop 1736 */ 1737 ret = prepare_pages(inode, pages, num_pages, 1738 pos, write_bytes, 1739 force_page_uptodate); 1740 if (ret) { 1741 btrfs_delalloc_release_extents(BTRFS_I(inode), 1742 reserve_bytes); 1743 break; 1744 } 1745 1746 extents_locked = lock_and_cleanup_extent_if_need( 1747 BTRFS_I(inode), pages, 1748 num_pages, pos, write_bytes, &lockstart, 1749 &lockend, &cached_state); 1750 if (extents_locked < 0) { 1751 if (extents_locked == -EAGAIN) 1752 goto again; 1753 btrfs_delalloc_release_extents(BTRFS_I(inode), 1754 reserve_bytes); 1755 ret = extents_locked; 1756 break; 1757 } 1758 1759 copied = btrfs_copy_from_user(pos, write_bytes, pages, i); 1760 1761 num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes); 1762 dirty_sectors = round_up(copied + sector_offset, 1763 fs_info->sectorsize); 1764 dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors); 1765 1766 /* 1767 * if we have trouble faulting in the pages, fall 1768 * back to one page at a time 1769 */ 1770 if (copied < write_bytes) 1771 nrptrs = 1; 1772 1773 if (copied == 0) { 1774 force_page_uptodate = true; 1775 dirty_sectors = 0; 1776 dirty_pages = 0; 1777 } else { 1778 force_page_uptodate = false; 1779 dirty_pages = DIV_ROUND_UP(copied + offset, 1780 PAGE_SIZE); 1781 } 1782 1783 if (num_sectors > dirty_sectors) { 1784 /* release everything except the sectors we dirtied */ 1785 release_bytes -= dirty_sectors << fs_info->sectorsize_bits; 1786 if (only_release_metadata) { 1787 btrfs_delalloc_release_metadata(BTRFS_I(inode), 1788 release_bytes, true); 1789 } else { 1790 u64 __pos; 1791 1792 __pos = round_down(pos, 1793 fs_info->sectorsize) + 1794 (dirty_pages << PAGE_SHIFT); 1795 btrfs_delalloc_release_space(BTRFS_I(inode), 1796 data_reserved, __pos, 1797 release_bytes, true); 1798 } 1799 } 1800 1801 release_bytes = round_up(copied + sector_offset, 1802 fs_info->sectorsize); 1803 1804 ret = btrfs_dirty_pages(BTRFS_I(inode), pages, 1805 dirty_pages, pos, copied, 1806 &cached_state, only_release_metadata); 1807 1808 /* 1809 * If we have not locked the extent range, because the range's 1810 * start offset is >= i_size, we might still have a non-NULL 1811 * cached extent state, acquired while marking the extent range 1812 * as delalloc through btrfs_dirty_pages(). Therefore free any 1813 * possible cached extent state to avoid a memory leak. 1814 */ 1815 if (extents_locked) 1816 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 1817 lockstart, lockend, &cached_state); 1818 else 1819 free_extent_state(cached_state); 1820 1821 btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes); 1822 if (ret) { 1823 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied); 1824 break; 1825 } 1826 1827 release_bytes = 0; 1828 if (only_release_metadata) 1829 btrfs_check_nocow_unlock(BTRFS_I(inode)); 1830 1831 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied); 1832 1833 cond_resched(); 1834 1835 balance_dirty_pages_ratelimited(inode->i_mapping); 1836 1837 pos += copied; 1838 num_written += copied; 1839 } 1840 1841 kfree(pages); 1842 1843 if (release_bytes) { 1844 if (only_release_metadata) { 1845 btrfs_check_nocow_unlock(BTRFS_I(inode)); 1846 btrfs_delalloc_release_metadata(BTRFS_I(inode), 1847 release_bytes, true); 1848 } else { 1849 btrfs_delalloc_release_space(BTRFS_I(inode), 1850 data_reserved, 1851 round_down(pos, fs_info->sectorsize), 1852 release_bytes, true); 1853 } 1854 } 1855 1856 extent_changeset_free(data_reserved); 1857 if (num_written > 0) { 1858 pagecache_isize_extended(inode, old_isize, iocb->ki_pos); 1859 iocb->ki_pos += num_written; 1860 } 1861 out: 1862 btrfs_inode_unlock(inode, ilock_flags); 1863 return num_written ? num_written : ret; 1864 } 1865 1866 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info, 1867 const struct iov_iter *iter, loff_t offset) 1868 { 1869 const u32 blocksize_mask = fs_info->sectorsize - 1; 1870 1871 if (offset & blocksize_mask) 1872 return -EINVAL; 1873 1874 if (iov_iter_alignment(iter) & blocksize_mask) 1875 return -EINVAL; 1876 1877 return 0; 1878 } 1879 1880 static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) 1881 { 1882 const bool is_sync_write = (iocb->ki_flags & IOCB_DSYNC); 1883 struct file *file = iocb->ki_filp; 1884 struct inode *inode = file_inode(file); 1885 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 1886 loff_t pos; 1887 ssize_t written = 0; 1888 ssize_t written_buffered; 1889 size_t prev_left = 0; 1890 loff_t endbyte; 1891 ssize_t err; 1892 unsigned int ilock_flags = 0; 1893 1894 if (iocb->ki_flags & IOCB_NOWAIT) 1895 ilock_flags |= BTRFS_ILOCK_TRY; 1896 1897 /* If the write DIO is within EOF, use a shared lock */ 1898 if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode)) 1899 ilock_flags |= BTRFS_ILOCK_SHARED; 1900 1901 relock: 1902 err = btrfs_inode_lock(inode, ilock_flags); 1903 if (err < 0) 1904 return err; 1905 1906 err = generic_write_checks(iocb, from); 1907 if (err <= 0) { 1908 btrfs_inode_unlock(inode, ilock_flags); 1909 return err; 1910 } 1911 1912 err = btrfs_write_check(iocb, from, err); 1913 if (err < 0) { 1914 btrfs_inode_unlock(inode, ilock_flags); 1915 goto out; 1916 } 1917 1918 pos = iocb->ki_pos; 1919 /* 1920 * Re-check since file size may have changed just before taking the 1921 * lock or pos may have changed because of O_APPEND in generic_write_check() 1922 */ 1923 if ((ilock_flags & BTRFS_ILOCK_SHARED) && 1924 pos + iov_iter_count(from) > i_size_read(inode)) { 1925 btrfs_inode_unlock(inode, ilock_flags); 1926 ilock_flags &= ~BTRFS_ILOCK_SHARED; 1927 goto relock; 1928 } 1929 1930 if (check_direct_IO(fs_info, from, pos)) { 1931 btrfs_inode_unlock(inode, ilock_flags); 1932 goto buffered; 1933 } 1934 1935 /* 1936 * We remove IOCB_DSYNC so that we don't deadlock when iomap_dio_rw() 1937 * calls generic_write_sync() (through iomap_dio_complete()), because 1938 * that results in calling fsync (btrfs_sync_file()) which will try to 1939 * lock the inode in exclusive/write mode. 1940 */ 1941 if (is_sync_write) 1942 iocb->ki_flags &= ~IOCB_DSYNC; 1943 1944 /* 1945 * The iov_iter can be mapped to the same file range we are writing to. 1946 * If that's the case, then we will deadlock in the iomap code, because 1947 * it first calls our callback btrfs_dio_iomap_begin(), which will create 1948 * an ordered extent, and after that it will fault in the pages that the 1949 * iov_iter refers to. During the fault in we end up in the readahead 1950 * pages code (starting at btrfs_readahead()), which will lock the range, 1951 * find that ordered extent and then wait for it to complete (at 1952 * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since 1953 * obviously the ordered extent can never complete as we didn't submit 1954 * yet the respective bio(s). This always happens when the buffer is 1955 * memory mapped to the same file range, since the iomap DIO code always 1956 * invalidates pages in the target file range (after starting and waiting 1957 * for any writeback). 1958 * 1959 * So here we disable page faults in the iov_iter and then retry if we 1960 * got -EFAULT, faulting in the pages before the retry. 1961 */ 1962 again: 1963 from->nofault = true; 1964 err = btrfs_dio_rw(iocb, from, written); 1965 from->nofault = false; 1966 1967 /* No increment (+=) because iomap returns a cumulative value. */ 1968 if (err > 0) 1969 written = err; 1970 1971 if (iov_iter_count(from) > 0 && (err == -EFAULT || err > 0)) { 1972 const size_t left = iov_iter_count(from); 1973 /* 1974 * We have more data left to write. Try to fault in as many as 1975 * possible of the remainder pages and retry. We do this without 1976 * releasing and locking again the inode, to prevent races with 1977 * truncate. 1978 * 1979 * Also, in case the iov refers to pages in the file range of the 1980 * file we want to write to (due to a mmap), we could enter an 1981 * infinite loop if we retry after faulting the pages in, since 1982 * iomap will invalidate any pages in the range early on, before 1983 * it tries to fault in the pages of the iov. So we keep track of 1984 * how much was left of iov in the previous EFAULT and fallback 1985 * to buffered IO in case we haven't made any progress. 1986 */ 1987 if (left == prev_left) { 1988 err = -ENOTBLK; 1989 } else { 1990 fault_in_iov_iter_readable(from, left); 1991 prev_left = left; 1992 goto again; 1993 } 1994 } 1995 1996 btrfs_inode_unlock(inode, ilock_flags); 1997 1998 /* 1999 * Add back IOCB_DSYNC. Our caller, btrfs_file_write_iter(), will do 2000 * the fsync (call generic_write_sync()). 2001 */ 2002 if (is_sync_write) 2003 iocb->ki_flags |= IOCB_DSYNC; 2004 2005 /* If 'err' is -ENOTBLK then it means we must fallback to buffered IO. */ 2006 if ((err < 0 && err != -ENOTBLK) || !iov_iter_count(from)) 2007 goto out; 2008 2009 buffered: 2010 pos = iocb->ki_pos; 2011 written_buffered = btrfs_buffered_write(iocb, from); 2012 if (written_buffered < 0) { 2013 err = written_buffered; 2014 goto out; 2015 } 2016 /* 2017 * Ensure all data is persisted. We want the next direct IO read to be 2018 * able to read what was just written. 2019 */ 2020 endbyte = pos + written_buffered - 1; 2021 err = btrfs_fdatawrite_range(inode, pos, endbyte); 2022 if (err) 2023 goto out; 2024 err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte); 2025 if (err) 2026 goto out; 2027 written += written_buffered; 2028 iocb->ki_pos = pos + written_buffered; 2029 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT, 2030 endbyte >> PAGE_SHIFT); 2031 out: 2032 return err < 0 ? err : written; 2033 } 2034 2035 static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from, 2036 const struct btrfs_ioctl_encoded_io_args *encoded) 2037 { 2038 struct file *file = iocb->ki_filp; 2039 struct inode *inode = file_inode(file); 2040 loff_t count; 2041 ssize_t ret; 2042 2043 btrfs_inode_lock(inode, 0); 2044 count = encoded->len; 2045 ret = generic_write_checks_count(iocb, &count); 2046 if (ret == 0 && count != encoded->len) { 2047 /* 2048 * The write got truncated by generic_write_checks_count(). We 2049 * can't do a partial encoded write. 2050 */ 2051 ret = -EFBIG; 2052 } 2053 if (ret || encoded->len == 0) 2054 goto out; 2055 2056 ret = btrfs_write_check(iocb, from, encoded->len); 2057 if (ret < 0) 2058 goto out; 2059 2060 ret = btrfs_do_encoded_write(iocb, from, encoded); 2061 out: 2062 btrfs_inode_unlock(inode, 0); 2063 return ret; 2064 } 2065 2066 ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from, 2067 const struct btrfs_ioctl_encoded_io_args *encoded) 2068 { 2069 struct file *file = iocb->ki_filp; 2070 struct btrfs_inode *inode = BTRFS_I(file_inode(file)); 2071 ssize_t num_written, num_sync; 2072 const bool sync = iocb->ki_flags & IOCB_DSYNC; 2073 2074 /* 2075 * If the fs flips readonly due to some impossible error, although we 2076 * have opened a file as writable, we have to stop this write operation 2077 * to ensure consistency. 2078 */ 2079 if (BTRFS_FS_ERROR(inode->root->fs_info)) 2080 return -EROFS; 2081 2082 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT)) 2083 return -EOPNOTSUPP; 2084 2085 if (sync) 2086 atomic_inc(&inode->sync_writers); 2087 2088 if (encoded) { 2089 num_written = btrfs_encoded_write(iocb, from, encoded); 2090 num_sync = encoded->len; 2091 } else if (iocb->ki_flags & IOCB_DIRECT) { 2092 num_written = num_sync = btrfs_direct_write(iocb, from); 2093 } else { 2094 num_written = num_sync = btrfs_buffered_write(iocb, from); 2095 } 2096 2097 btrfs_set_inode_last_sub_trans(inode); 2098 2099 if (num_sync > 0) { 2100 num_sync = generic_write_sync(iocb, num_sync); 2101 if (num_sync < 0) 2102 num_written = num_sync; 2103 } 2104 2105 if (sync) 2106 atomic_dec(&inode->sync_writers); 2107 2108 current->backing_dev_info = NULL; 2109 return num_written; 2110 } 2111 2112 static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from) 2113 { 2114 return btrfs_do_write_iter(iocb, from, NULL); 2115 } 2116 2117 int btrfs_release_file(struct inode *inode, struct file *filp) 2118 { 2119 struct btrfs_file_private *private = filp->private_data; 2120 2121 if (private && private->filldir_buf) 2122 kfree(private->filldir_buf); 2123 kfree(private); 2124 filp->private_data = NULL; 2125 2126 /* 2127 * Set by setattr when we are about to truncate a file from a non-zero 2128 * size to a zero size. This tries to flush down new bytes that may 2129 * have been written if the application were using truncate to replace 2130 * a file in place. 2131 */ 2132 if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE, 2133 &BTRFS_I(inode)->runtime_flags)) 2134 filemap_flush(inode->i_mapping); 2135 return 0; 2136 } 2137 2138 static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end) 2139 { 2140 int ret; 2141 struct blk_plug plug; 2142 2143 /* 2144 * This is only called in fsync, which would do synchronous writes, so 2145 * a plug can merge adjacent IOs as much as possible. Esp. in case of 2146 * multiple disks using raid profile, a large IO can be split to 2147 * several segments of stripe length (currently 64K). 2148 */ 2149 blk_start_plug(&plug); 2150 atomic_inc(&BTRFS_I(inode)->sync_writers); 2151 ret = btrfs_fdatawrite_range(inode, start, end); 2152 atomic_dec(&BTRFS_I(inode)->sync_writers); 2153 blk_finish_plug(&plug); 2154 2155 return ret; 2156 } 2157 2158 static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx) 2159 { 2160 struct btrfs_inode *inode = BTRFS_I(ctx->inode); 2161 struct btrfs_fs_info *fs_info = inode->root->fs_info; 2162 2163 if (btrfs_inode_in_log(inode, fs_info->generation) && 2164 list_empty(&ctx->ordered_extents)) 2165 return true; 2166 2167 /* 2168 * If we are doing a fast fsync we can not bail out if the inode's 2169 * last_trans is <= then the last committed transaction, because we only 2170 * update the last_trans of the inode during ordered extent completion, 2171 * and for a fast fsync we don't wait for that, we only wait for the 2172 * writeback to complete. 2173 */ 2174 if (inode->last_trans <= fs_info->last_trans_committed && 2175 (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) || 2176 list_empty(&ctx->ordered_extents))) 2177 return true; 2178 2179 return false; 2180 } 2181 2182 /* 2183 * fsync call for both files and directories. This logs the inode into 2184 * the tree log instead of forcing full commits whenever possible. 2185 * 2186 * It needs to call filemap_fdatawait so that all ordered extent updates are 2187 * in the metadata btree are up to date for copying to the log. 2188 * 2189 * It drops the inode mutex before doing the tree log commit. This is an 2190 * important optimization for directories because holding the mutex prevents 2191 * new operations on the dir while we write to disk. 2192 */ 2193 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync) 2194 { 2195 struct dentry *dentry = file_dentry(file); 2196 struct inode *inode = d_inode(dentry); 2197 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2198 struct btrfs_root *root = BTRFS_I(inode)->root; 2199 struct btrfs_trans_handle *trans; 2200 struct btrfs_log_ctx ctx; 2201 int ret = 0, err; 2202 u64 len; 2203 bool full_sync; 2204 2205 trace_btrfs_sync_file(file, datasync); 2206 2207 btrfs_init_log_ctx(&ctx, inode); 2208 2209 /* 2210 * Always set the range to a full range, otherwise we can get into 2211 * several problems, from missing file extent items to represent holes 2212 * when not using the NO_HOLES feature, to log tree corruption due to 2213 * races between hole detection during logging and completion of ordered 2214 * extents outside the range, to missing checksums due to ordered extents 2215 * for which we flushed only a subset of their pages. 2216 */ 2217 start = 0; 2218 end = LLONG_MAX; 2219 len = (u64)LLONG_MAX + 1; 2220 2221 /* 2222 * We write the dirty pages in the range and wait until they complete 2223 * out of the ->i_mutex. If so, we can flush the dirty pages by 2224 * multi-task, and make the performance up. See 2225 * btrfs_wait_ordered_range for an explanation of the ASYNC check. 2226 */ 2227 ret = start_ordered_ops(inode, start, end); 2228 if (ret) 2229 goto out; 2230 2231 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP); 2232 2233 atomic_inc(&root->log_batch); 2234 2235 /* 2236 * Before we acquired the inode's lock and the mmap lock, someone may 2237 * have dirtied more pages in the target range. We need to make sure 2238 * that writeback for any such pages does not start while we are logging 2239 * the inode, because if it does, any of the following might happen when 2240 * we are not doing a full inode sync: 2241 * 2242 * 1) We log an extent after its writeback finishes but before its 2243 * checksums are added to the csum tree, leading to -EIO errors 2244 * when attempting to read the extent after a log replay. 2245 * 2246 * 2) We can end up logging an extent before its writeback finishes. 2247 * Therefore after the log replay we will have a file extent item 2248 * pointing to an unwritten extent (and no data checksums as well). 2249 * 2250 * So trigger writeback for any eventual new dirty pages and then we 2251 * wait for all ordered extents to complete below. 2252 */ 2253 ret = start_ordered_ops(inode, start, end); 2254 if (ret) { 2255 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 2256 goto out; 2257 } 2258 2259 /* 2260 * Always check for the full sync flag while holding the inode's lock, 2261 * to avoid races with other tasks. The flag must be either set all the 2262 * time during logging or always off all the time while logging. 2263 * We check the flag here after starting delalloc above, because when 2264 * running delalloc the full sync flag may be set if we need to drop 2265 * extra extent map ranges due to temporary memory allocation failures. 2266 */ 2267 full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, 2268 &BTRFS_I(inode)->runtime_flags); 2269 2270 /* 2271 * We have to do this here to avoid the priority inversion of waiting on 2272 * IO of a lower priority task while holding a transaction open. 2273 * 2274 * For a full fsync we wait for the ordered extents to complete while 2275 * for a fast fsync we wait just for writeback to complete, and then 2276 * attach the ordered extents to the transaction so that a transaction 2277 * commit waits for their completion, to avoid data loss if we fsync, 2278 * the current transaction commits before the ordered extents complete 2279 * and a power failure happens right after that. 2280 * 2281 * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the 2282 * logical address recorded in the ordered extent may change. We need 2283 * to wait for the IO to stabilize the logical address. 2284 */ 2285 if (full_sync || btrfs_is_zoned(fs_info)) { 2286 ret = btrfs_wait_ordered_range(inode, start, len); 2287 } else { 2288 /* 2289 * Get our ordered extents as soon as possible to avoid doing 2290 * checksum lookups in the csum tree, and use instead the 2291 * checksums attached to the ordered extents. 2292 */ 2293 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode), 2294 &ctx.ordered_extents); 2295 ret = filemap_fdatawait_range(inode->i_mapping, start, end); 2296 } 2297 2298 if (ret) 2299 goto out_release_extents; 2300 2301 atomic_inc(&root->log_batch); 2302 2303 smp_mb(); 2304 if (skip_inode_logging(&ctx)) { 2305 /* 2306 * We've had everything committed since the last time we were 2307 * modified so clear this flag in case it was set for whatever 2308 * reason, it's no longer relevant. 2309 */ 2310 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC, 2311 &BTRFS_I(inode)->runtime_flags); 2312 /* 2313 * An ordered extent might have started before and completed 2314 * already with io errors, in which case the inode was not 2315 * updated and we end up here. So check the inode's mapping 2316 * for any errors that might have happened since we last 2317 * checked called fsync. 2318 */ 2319 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err); 2320 goto out_release_extents; 2321 } 2322 2323 /* 2324 * We use start here because we will need to wait on the IO to complete 2325 * in btrfs_sync_log, which could require joining a transaction (for 2326 * example checking cross references in the nocow path). If we use join 2327 * here we could get into a situation where we're waiting on IO to 2328 * happen that is blocked on a transaction trying to commit. With start 2329 * we inc the extwriter counter, so we wait for all extwriters to exit 2330 * before we start blocking joiners. This comment is to keep somebody 2331 * from thinking they are super smart and changing this to 2332 * btrfs_join_transaction *cough*Josef*cough*. 2333 */ 2334 trans = btrfs_start_transaction(root, 0); 2335 if (IS_ERR(trans)) { 2336 ret = PTR_ERR(trans); 2337 goto out_release_extents; 2338 } 2339 trans->in_fsync = true; 2340 2341 ret = btrfs_log_dentry_safe(trans, dentry, &ctx); 2342 btrfs_release_log_ctx_extents(&ctx); 2343 if (ret < 0) { 2344 /* Fallthrough and commit/free transaction. */ 2345 ret = BTRFS_LOG_FORCE_COMMIT; 2346 } 2347 2348 /* we've logged all the items and now have a consistent 2349 * version of the file in the log. It is possible that 2350 * someone will come in and modify the file, but that's 2351 * fine because the log is consistent on disk, and we 2352 * have references to all of the file's extents 2353 * 2354 * It is possible that someone will come in and log the 2355 * file again, but that will end up using the synchronization 2356 * inside btrfs_sync_log to keep things safe. 2357 */ 2358 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 2359 2360 if (ret == BTRFS_NO_LOG_SYNC) { 2361 ret = btrfs_end_transaction(trans); 2362 goto out; 2363 } 2364 2365 /* We successfully logged the inode, attempt to sync the log. */ 2366 if (!ret) { 2367 ret = btrfs_sync_log(trans, root, &ctx); 2368 if (!ret) { 2369 ret = btrfs_end_transaction(trans); 2370 goto out; 2371 } 2372 } 2373 2374 /* 2375 * At this point we need to commit the transaction because we had 2376 * btrfs_need_log_full_commit() or some other error. 2377 * 2378 * If we didn't do a full sync we have to stop the trans handle, wait on 2379 * the ordered extents, start it again and commit the transaction. If 2380 * we attempt to wait on the ordered extents here we could deadlock with 2381 * something like fallocate() that is holding the extent lock trying to 2382 * start a transaction while some other thread is trying to commit the 2383 * transaction while we (fsync) are currently holding the transaction 2384 * open. 2385 */ 2386 if (!full_sync) { 2387 ret = btrfs_end_transaction(trans); 2388 if (ret) 2389 goto out; 2390 ret = btrfs_wait_ordered_range(inode, start, len); 2391 if (ret) 2392 goto out; 2393 2394 /* 2395 * This is safe to use here because we're only interested in 2396 * making sure the transaction that had the ordered extents is 2397 * committed. We aren't waiting on anything past this point, 2398 * we're purely getting the transaction and committing it. 2399 */ 2400 trans = btrfs_attach_transaction_barrier(root); 2401 if (IS_ERR(trans)) { 2402 ret = PTR_ERR(trans); 2403 2404 /* 2405 * We committed the transaction and there's no currently 2406 * running transaction, this means everything we care 2407 * about made it to disk and we are done. 2408 */ 2409 if (ret == -ENOENT) 2410 ret = 0; 2411 goto out; 2412 } 2413 } 2414 2415 ret = btrfs_commit_transaction(trans); 2416 out: 2417 ASSERT(list_empty(&ctx.list)); 2418 err = file_check_and_advance_wb_err(file); 2419 if (!ret) 2420 ret = err; 2421 return ret > 0 ? -EIO : ret; 2422 2423 out_release_extents: 2424 btrfs_release_log_ctx_extents(&ctx); 2425 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 2426 goto out; 2427 } 2428 2429 static const struct vm_operations_struct btrfs_file_vm_ops = { 2430 .fault = filemap_fault, 2431 .map_pages = filemap_map_pages, 2432 .page_mkwrite = btrfs_page_mkwrite, 2433 }; 2434 2435 static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma) 2436 { 2437 struct address_space *mapping = filp->f_mapping; 2438 2439 if (!mapping->a_ops->read_folio) 2440 return -ENOEXEC; 2441 2442 file_accessed(filp); 2443 vma->vm_ops = &btrfs_file_vm_ops; 2444 2445 return 0; 2446 } 2447 2448 static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf, 2449 int slot, u64 start, u64 end) 2450 { 2451 struct btrfs_file_extent_item *fi; 2452 struct btrfs_key key; 2453 2454 if (slot < 0 || slot >= btrfs_header_nritems(leaf)) 2455 return 0; 2456 2457 btrfs_item_key_to_cpu(leaf, &key, slot); 2458 if (key.objectid != btrfs_ino(inode) || 2459 key.type != BTRFS_EXTENT_DATA_KEY) 2460 return 0; 2461 2462 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); 2463 2464 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG) 2465 return 0; 2466 2467 if (btrfs_file_extent_disk_bytenr(leaf, fi)) 2468 return 0; 2469 2470 if (key.offset == end) 2471 return 1; 2472 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start) 2473 return 1; 2474 return 0; 2475 } 2476 2477 static int fill_holes(struct btrfs_trans_handle *trans, 2478 struct btrfs_inode *inode, 2479 struct btrfs_path *path, u64 offset, u64 end) 2480 { 2481 struct btrfs_fs_info *fs_info = trans->fs_info; 2482 struct btrfs_root *root = inode->root; 2483 struct extent_buffer *leaf; 2484 struct btrfs_file_extent_item *fi; 2485 struct extent_map *hole_em; 2486 struct extent_map_tree *em_tree = &inode->extent_tree; 2487 struct btrfs_key key; 2488 int ret; 2489 2490 if (btrfs_fs_incompat(fs_info, NO_HOLES)) 2491 goto out; 2492 2493 key.objectid = btrfs_ino(inode); 2494 key.type = BTRFS_EXTENT_DATA_KEY; 2495 key.offset = offset; 2496 2497 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 2498 if (ret <= 0) { 2499 /* 2500 * We should have dropped this offset, so if we find it then 2501 * something has gone horribly wrong. 2502 */ 2503 if (ret == 0) 2504 ret = -EINVAL; 2505 return ret; 2506 } 2507 2508 leaf = path->nodes[0]; 2509 if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) { 2510 u64 num_bytes; 2511 2512 path->slots[0]--; 2513 fi = btrfs_item_ptr(leaf, path->slots[0], 2514 struct btrfs_file_extent_item); 2515 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + 2516 end - offset; 2517 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes); 2518 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes); 2519 btrfs_set_file_extent_offset(leaf, fi, 0); 2520 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 2521 btrfs_mark_buffer_dirty(leaf); 2522 goto out; 2523 } 2524 2525 if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) { 2526 u64 num_bytes; 2527 2528 key.offset = offset; 2529 btrfs_set_item_key_safe(fs_info, path, &key); 2530 fi = btrfs_item_ptr(leaf, path->slots[0], 2531 struct btrfs_file_extent_item); 2532 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end - 2533 offset; 2534 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes); 2535 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes); 2536 btrfs_set_file_extent_offset(leaf, fi, 0); 2537 btrfs_set_file_extent_generation(leaf, fi, trans->transid); 2538 btrfs_mark_buffer_dirty(leaf); 2539 goto out; 2540 } 2541 btrfs_release_path(path); 2542 2543 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), 2544 offset, 0, 0, end - offset, 0, end - offset, 0, 0, 0); 2545 if (ret) 2546 return ret; 2547 2548 out: 2549 btrfs_release_path(path); 2550 2551 hole_em = alloc_extent_map(); 2552 if (!hole_em) { 2553 btrfs_drop_extent_cache(inode, offset, end - 1, 0); 2554 btrfs_set_inode_full_sync(inode); 2555 } else { 2556 hole_em->start = offset; 2557 hole_em->len = end - offset; 2558 hole_em->ram_bytes = hole_em->len; 2559 hole_em->orig_start = offset; 2560 2561 hole_em->block_start = EXTENT_MAP_HOLE; 2562 hole_em->block_len = 0; 2563 hole_em->orig_block_len = 0; 2564 hole_em->compress_type = BTRFS_COMPRESS_NONE; 2565 hole_em->generation = trans->transid; 2566 2567 do { 2568 btrfs_drop_extent_cache(inode, offset, end - 1, 0); 2569 write_lock(&em_tree->lock); 2570 ret = add_extent_mapping(em_tree, hole_em, 1); 2571 write_unlock(&em_tree->lock); 2572 } while (ret == -EEXIST); 2573 free_extent_map(hole_em); 2574 if (ret) 2575 btrfs_set_inode_full_sync(inode); 2576 } 2577 2578 return 0; 2579 } 2580 2581 /* 2582 * Find a hole extent on given inode and change start/len to the end of hole 2583 * extent.(hole/vacuum extent whose em->start <= start && 2584 * em->start + em->len > start) 2585 * When a hole extent is found, return 1 and modify start/len. 2586 */ 2587 static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len) 2588 { 2589 struct btrfs_fs_info *fs_info = inode->root->fs_info; 2590 struct extent_map *em; 2591 int ret = 0; 2592 2593 em = btrfs_get_extent(inode, NULL, 0, 2594 round_down(*start, fs_info->sectorsize), 2595 round_up(*len, fs_info->sectorsize)); 2596 if (IS_ERR(em)) 2597 return PTR_ERR(em); 2598 2599 /* Hole or vacuum extent(only exists in no-hole mode) */ 2600 if (em->block_start == EXTENT_MAP_HOLE) { 2601 ret = 1; 2602 *len = em->start + em->len > *start + *len ? 2603 0 : *start + *len - em->start - em->len; 2604 *start = em->start + em->len; 2605 } 2606 free_extent_map(em); 2607 return ret; 2608 } 2609 2610 static void btrfs_punch_hole_lock_range(struct inode *inode, 2611 const u64 lockstart, 2612 const u64 lockend, 2613 struct extent_state **cached_state) 2614 { 2615 /* 2616 * For subpage case, if the range is not at page boundary, we could 2617 * have pages at the leading/tailing part of the range. 2618 * This could lead to dead loop since filemap_range_has_page() 2619 * will always return true. 2620 * So here we need to do extra page alignment for 2621 * filemap_range_has_page(). 2622 */ 2623 const u64 page_lockstart = round_up(lockstart, PAGE_SIZE); 2624 const u64 page_lockend = round_down(lockend + 1, PAGE_SIZE) - 1; 2625 2626 while (1) { 2627 truncate_pagecache_range(inode, lockstart, lockend); 2628 2629 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 2630 cached_state); 2631 /* 2632 * We can't have ordered extents in the range, nor dirty/writeback 2633 * pages, because we have locked the inode's VFS lock in exclusive 2634 * mode, we have locked the inode's i_mmap_lock in exclusive mode, 2635 * we have flushed all delalloc in the range and we have waited 2636 * for any ordered extents in the range to complete. 2637 * We can race with anyone reading pages from this range, so after 2638 * locking the range check if we have pages in the range, and if 2639 * we do, unlock the range and retry. 2640 */ 2641 if (!filemap_range_has_page(inode->i_mapping, page_lockstart, 2642 page_lockend)) 2643 break; 2644 2645 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, 2646 lockend, cached_state); 2647 } 2648 2649 btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend); 2650 } 2651 2652 static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans, 2653 struct btrfs_inode *inode, 2654 struct btrfs_path *path, 2655 struct btrfs_replace_extent_info *extent_info, 2656 const u64 replace_len, 2657 const u64 bytes_to_drop) 2658 { 2659 struct btrfs_fs_info *fs_info = trans->fs_info; 2660 struct btrfs_root *root = inode->root; 2661 struct btrfs_file_extent_item *extent; 2662 struct extent_buffer *leaf; 2663 struct btrfs_key key; 2664 int slot; 2665 struct btrfs_ref ref = { 0 }; 2666 int ret; 2667 2668 if (replace_len == 0) 2669 return 0; 2670 2671 if (extent_info->disk_offset == 0 && 2672 btrfs_fs_incompat(fs_info, NO_HOLES)) { 2673 btrfs_update_inode_bytes(inode, 0, bytes_to_drop); 2674 return 0; 2675 } 2676 2677 key.objectid = btrfs_ino(inode); 2678 key.type = BTRFS_EXTENT_DATA_KEY; 2679 key.offset = extent_info->file_offset; 2680 ret = btrfs_insert_empty_item(trans, root, path, &key, 2681 sizeof(struct btrfs_file_extent_item)); 2682 if (ret) 2683 return ret; 2684 leaf = path->nodes[0]; 2685 slot = path->slots[0]; 2686 write_extent_buffer(leaf, extent_info->extent_buf, 2687 btrfs_item_ptr_offset(leaf, slot), 2688 sizeof(struct btrfs_file_extent_item)); 2689 extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); 2690 ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE); 2691 btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset); 2692 btrfs_set_file_extent_num_bytes(leaf, extent, replace_len); 2693 if (extent_info->is_new_extent) 2694 btrfs_set_file_extent_generation(leaf, extent, trans->transid); 2695 btrfs_mark_buffer_dirty(leaf); 2696 btrfs_release_path(path); 2697 2698 ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset, 2699 replace_len); 2700 if (ret) 2701 return ret; 2702 2703 /* If it's a hole, nothing more needs to be done. */ 2704 if (extent_info->disk_offset == 0) { 2705 btrfs_update_inode_bytes(inode, 0, bytes_to_drop); 2706 return 0; 2707 } 2708 2709 btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop); 2710 2711 if (extent_info->is_new_extent && extent_info->insertions == 0) { 2712 key.objectid = extent_info->disk_offset; 2713 key.type = BTRFS_EXTENT_ITEM_KEY; 2714 key.offset = extent_info->disk_len; 2715 ret = btrfs_alloc_reserved_file_extent(trans, root, 2716 btrfs_ino(inode), 2717 extent_info->file_offset, 2718 extent_info->qgroup_reserved, 2719 &key); 2720 } else { 2721 u64 ref_offset; 2722 2723 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, 2724 extent_info->disk_offset, 2725 extent_info->disk_len, 0); 2726 ref_offset = extent_info->file_offset - extent_info->data_offset; 2727 btrfs_init_data_ref(&ref, root->root_key.objectid, 2728 btrfs_ino(inode), ref_offset, 0, false); 2729 ret = btrfs_inc_extent_ref(trans, &ref); 2730 } 2731 2732 extent_info->insertions++; 2733 2734 return ret; 2735 } 2736 2737 /* 2738 * The respective range must have been previously locked, as well as the inode. 2739 * The end offset is inclusive (last byte of the range). 2740 * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing 2741 * the file range with an extent. 2742 * When not punching a hole, we don't want to end up in a state where we dropped 2743 * extents without inserting a new one, so we must abort the transaction to avoid 2744 * a corruption. 2745 */ 2746 int btrfs_replace_file_extents(struct btrfs_inode *inode, 2747 struct btrfs_path *path, const u64 start, 2748 const u64 end, 2749 struct btrfs_replace_extent_info *extent_info, 2750 struct btrfs_trans_handle **trans_out) 2751 { 2752 struct btrfs_drop_extents_args drop_args = { 0 }; 2753 struct btrfs_root *root = inode->root; 2754 struct btrfs_fs_info *fs_info = root->fs_info; 2755 u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1); 2756 u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize); 2757 struct btrfs_trans_handle *trans = NULL; 2758 struct btrfs_block_rsv *rsv; 2759 unsigned int rsv_count; 2760 u64 cur_offset; 2761 u64 len = end - start; 2762 int ret = 0; 2763 2764 if (end <= start) 2765 return -EINVAL; 2766 2767 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP); 2768 if (!rsv) { 2769 ret = -ENOMEM; 2770 goto out; 2771 } 2772 rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1); 2773 rsv->failfast = 1; 2774 2775 /* 2776 * 1 - update the inode 2777 * 1 - removing the extents in the range 2778 * 1 - adding the hole extent if no_holes isn't set or if we are 2779 * replacing the range with a new extent 2780 */ 2781 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info) 2782 rsv_count = 3; 2783 else 2784 rsv_count = 2; 2785 2786 trans = btrfs_start_transaction(root, rsv_count); 2787 if (IS_ERR(trans)) { 2788 ret = PTR_ERR(trans); 2789 trans = NULL; 2790 goto out_free; 2791 } 2792 2793 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv, 2794 min_size, false); 2795 if (WARN_ON(ret)) 2796 goto out_trans; 2797 trans->block_rsv = rsv; 2798 2799 cur_offset = start; 2800 drop_args.path = path; 2801 drop_args.end = end + 1; 2802 drop_args.drop_cache = true; 2803 while (cur_offset < end) { 2804 drop_args.start = cur_offset; 2805 ret = btrfs_drop_extents(trans, root, inode, &drop_args); 2806 /* If we are punching a hole decrement the inode's byte count */ 2807 if (!extent_info) 2808 btrfs_update_inode_bytes(inode, 0, 2809 drop_args.bytes_found); 2810 if (ret != -ENOSPC) { 2811 /* 2812 * The only time we don't want to abort is if we are 2813 * attempting to clone a partial inline extent, in which 2814 * case we'll get EOPNOTSUPP. However if we aren't 2815 * clone we need to abort no matter what, because if we 2816 * got EOPNOTSUPP via prealloc then we messed up and 2817 * need to abort. 2818 */ 2819 if (ret && 2820 (ret != -EOPNOTSUPP || 2821 (extent_info && extent_info->is_new_extent))) 2822 btrfs_abort_transaction(trans, ret); 2823 break; 2824 } 2825 2826 trans->block_rsv = &fs_info->trans_block_rsv; 2827 2828 if (!extent_info && cur_offset < drop_args.drop_end && 2829 cur_offset < ino_size) { 2830 ret = fill_holes(trans, inode, path, cur_offset, 2831 drop_args.drop_end); 2832 if (ret) { 2833 /* 2834 * If we failed then we didn't insert our hole 2835 * entries for the area we dropped, so now the 2836 * fs is corrupted, so we must abort the 2837 * transaction. 2838 */ 2839 btrfs_abort_transaction(trans, ret); 2840 break; 2841 } 2842 } else if (!extent_info && cur_offset < drop_args.drop_end) { 2843 /* 2844 * We are past the i_size here, but since we didn't 2845 * insert holes we need to clear the mapped area so we 2846 * know to not set disk_i_size in this area until a new 2847 * file extent is inserted here. 2848 */ 2849 ret = btrfs_inode_clear_file_extent_range(inode, 2850 cur_offset, 2851 drop_args.drop_end - cur_offset); 2852 if (ret) { 2853 /* 2854 * We couldn't clear our area, so we could 2855 * presumably adjust up and corrupt the fs, so 2856 * we need to abort. 2857 */ 2858 btrfs_abort_transaction(trans, ret); 2859 break; 2860 } 2861 } 2862 2863 if (extent_info && 2864 drop_args.drop_end > extent_info->file_offset) { 2865 u64 replace_len = drop_args.drop_end - 2866 extent_info->file_offset; 2867 2868 ret = btrfs_insert_replace_extent(trans, inode, path, 2869 extent_info, replace_len, 2870 drop_args.bytes_found); 2871 if (ret) { 2872 btrfs_abort_transaction(trans, ret); 2873 break; 2874 } 2875 extent_info->data_len -= replace_len; 2876 extent_info->data_offset += replace_len; 2877 extent_info->file_offset += replace_len; 2878 } 2879 2880 /* 2881 * We are releasing our handle on the transaction, balance the 2882 * dirty pages of the btree inode and flush delayed items, and 2883 * then get a new transaction handle, which may now point to a 2884 * new transaction in case someone else may have committed the 2885 * transaction we used to replace/drop file extent items. So 2886 * bump the inode's iversion and update mtime and ctime except 2887 * if we are called from a dedupe context. This is because a 2888 * power failure/crash may happen after the transaction is 2889 * committed and before we finish replacing/dropping all the 2890 * file extent items we need. 2891 */ 2892 inode_inc_iversion(&inode->vfs_inode); 2893 2894 if (!extent_info || extent_info->update_times) { 2895 inode->vfs_inode.i_mtime = current_time(&inode->vfs_inode); 2896 inode->vfs_inode.i_ctime = inode->vfs_inode.i_mtime; 2897 } 2898 2899 ret = btrfs_update_inode(trans, root, inode); 2900 if (ret) 2901 break; 2902 2903 btrfs_end_transaction(trans); 2904 btrfs_btree_balance_dirty(fs_info); 2905 2906 trans = btrfs_start_transaction(root, rsv_count); 2907 if (IS_ERR(trans)) { 2908 ret = PTR_ERR(trans); 2909 trans = NULL; 2910 break; 2911 } 2912 2913 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, 2914 rsv, min_size, false); 2915 if (WARN_ON(ret)) 2916 break; 2917 trans->block_rsv = rsv; 2918 2919 cur_offset = drop_args.drop_end; 2920 len = end - cur_offset; 2921 if (!extent_info && len) { 2922 ret = find_first_non_hole(inode, &cur_offset, &len); 2923 if (unlikely(ret < 0)) 2924 break; 2925 if (ret && !len) { 2926 ret = 0; 2927 break; 2928 } 2929 } 2930 } 2931 2932 /* 2933 * If we were cloning, force the next fsync to be a full one since we 2934 * we replaced (or just dropped in the case of cloning holes when 2935 * NO_HOLES is enabled) file extent items and did not setup new extent 2936 * maps for the replacement extents (or holes). 2937 */ 2938 if (extent_info && !extent_info->is_new_extent) 2939 btrfs_set_inode_full_sync(inode); 2940 2941 if (ret) 2942 goto out_trans; 2943 2944 trans->block_rsv = &fs_info->trans_block_rsv; 2945 /* 2946 * If we are using the NO_HOLES feature we might have had already an 2947 * hole that overlaps a part of the region [lockstart, lockend] and 2948 * ends at (or beyond) lockend. Since we have no file extent items to 2949 * represent holes, drop_end can be less than lockend and so we must 2950 * make sure we have an extent map representing the existing hole (the 2951 * call to __btrfs_drop_extents() might have dropped the existing extent 2952 * map representing the existing hole), otherwise the fast fsync path 2953 * will not record the existence of the hole region 2954 * [existing_hole_start, lockend]. 2955 */ 2956 if (drop_args.drop_end <= end) 2957 drop_args.drop_end = end + 1; 2958 /* 2959 * Don't insert file hole extent item if it's for a range beyond eof 2960 * (because it's useless) or if it represents a 0 bytes range (when 2961 * cur_offset == drop_end). 2962 */ 2963 if (!extent_info && cur_offset < ino_size && 2964 cur_offset < drop_args.drop_end) { 2965 ret = fill_holes(trans, inode, path, cur_offset, 2966 drop_args.drop_end); 2967 if (ret) { 2968 /* Same comment as above. */ 2969 btrfs_abort_transaction(trans, ret); 2970 goto out_trans; 2971 } 2972 } else if (!extent_info && cur_offset < drop_args.drop_end) { 2973 /* See the comment in the loop above for the reasoning here. */ 2974 ret = btrfs_inode_clear_file_extent_range(inode, cur_offset, 2975 drop_args.drop_end - cur_offset); 2976 if (ret) { 2977 btrfs_abort_transaction(trans, ret); 2978 goto out_trans; 2979 } 2980 2981 } 2982 if (extent_info) { 2983 ret = btrfs_insert_replace_extent(trans, inode, path, 2984 extent_info, extent_info->data_len, 2985 drop_args.bytes_found); 2986 if (ret) { 2987 btrfs_abort_transaction(trans, ret); 2988 goto out_trans; 2989 } 2990 } 2991 2992 out_trans: 2993 if (!trans) 2994 goto out_free; 2995 2996 trans->block_rsv = &fs_info->trans_block_rsv; 2997 if (ret) 2998 btrfs_end_transaction(trans); 2999 else 3000 *trans_out = trans; 3001 out_free: 3002 btrfs_free_block_rsv(fs_info, rsv); 3003 out: 3004 return ret; 3005 } 3006 3007 static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len) 3008 { 3009 struct inode *inode = file_inode(file); 3010 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 3011 struct btrfs_root *root = BTRFS_I(inode)->root; 3012 struct extent_state *cached_state = NULL; 3013 struct btrfs_path *path; 3014 struct btrfs_trans_handle *trans = NULL; 3015 u64 lockstart; 3016 u64 lockend; 3017 u64 tail_start; 3018 u64 tail_len; 3019 u64 orig_start = offset; 3020 int ret = 0; 3021 bool same_block; 3022 u64 ino_size; 3023 bool truncated_block = false; 3024 bool updated_inode = false; 3025 3026 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP); 3027 3028 ret = btrfs_wait_ordered_range(inode, offset, len); 3029 if (ret) 3030 goto out_only_mutex; 3031 3032 ino_size = round_up(inode->i_size, fs_info->sectorsize); 3033 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len); 3034 if (ret < 0) 3035 goto out_only_mutex; 3036 if (ret && !len) { 3037 /* Already in a large hole */ 3038 ret = 0; 3039 goto out_only_mutex; 3040 } 3041 3042 ret = file_modified(file); 3043 if (ret) 3044 goto out_only_mutex; 3045 3046 lockstart = round_up(offset, btrfs_inode_sectorsize(BTRFS_I(inode))); 3047 lockend = round_down(offset + len, 3048 btrfs_inode_sectorsize(BTRFS_I(inode))) - 1; 3049 same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset)) 3050 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)); 3051 /* 3052 * We needn't truncate any block which is beyond the end of the file 3053 * because we are sure there is no data there. 3054 */ 3055 /* 3056 * Only do this if we are in the same block and we aren't doing the 3057 * entire block. 3058 */ 3059 if (same_block && len < fs_info->sectorsize) { 3060 if (offset < ino_size) { 3061 truncated_block = true; 3062 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len, 3063 0); 3064 } else { 3065 ret = 0; 3066 } 3067 goto out_only_mutex; 3068 } 3069 3070 /* zero back part of the first block */ 3071 if (offset < ino_size) { 3072 truncated_block = true; 3073 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0); 3074 if (ret) { 3075 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 3076 return ret; 3077 } 3078 } 3079 3080 /* Check the aligned pages after the first unaligned page, 3081 * if offset != orig_start, which means the first unaligned page 3082 * including several following pages are already in holes, 3083 * the extra check can be skipped */ 3084 if (offset == orig_start) { 3085 /* after truncate page, check hole again */ 3086 len = offset + len - lockstart; 3087 offset = lockstart; 3088 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len); 3089 if (ret < 0) 3090 goto out_only_mutex; 3091 if (ret && !len) { 3092 ret = 0; 3093 goto out_only_mutex; 3094 } 3095 lockstart = offset; 3096 } 3097 3098 /* Check the tail unaligned part is in a hole */ 3099 tail_start = lockend + 1; 3100 tail_len = offset + len - tail_start; 3101 if (tail_len) { 3102 ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len); 3103 if (unlikely(ret < 0)) 3104 goto out_only_mutex; 3105 if (!ret) { 3106 /* zero the front end of the last page */ 3107 if (tail_start + tail_len < ino_size) { 3108 truncated_block = true; 3109 ret = btrfs_truncate_block(BTRFS_I(inode), 3110 tail_start + tail_len, 3111 0, 1); 3112 if (ret) 3113 goto out_only_mutex; 3114 } 3115 } 3116 } 3117 3118 if (lockend < lockstart) { 3119 ret = 0; 3120 goto out_only_mutex; 3121 } 3122 3123 btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state); 3124 3125 path = btrfs_alloc_path(); 3126 if (!path) { 3127 ret = -ENOMEM; 3128 goto out; 3129 } 3130 3131 ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart, 3132 lockend, NULL, &trans); 3133 btrfs_free_path(path); 3134 if (ret) 3135 goto out; 3136 3137 ASSERT(trans != NULL); 3138 inode_inc_iversion(inode); 3139 inode->i_mtime = inode->i_ctime = current_time(inode); 3140 ret = btrfs_update_inode(trans, root, BTRFS_I(inode)); 3141 updated_inode = true; 3142 btrfs_end_transaction(trans); 3143 btrfs_btree_balance_dirty(fs_info); 3144 out: 3145 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, 3146 &cached_state); 3147 out_only_mutex: 3148 if (!updated_inode && truncated_block && !ret) { 3149 /* 3150 * If we only end up zeroing part of a page, we still need to 3151 * update the inode item, so that all the time fields are 3152 * updated as well as the necessary btrfs inode in memory fields 3153 * for detecting, at fsync time, if the inode isn't yet in the 3154 * log tree or it's there but not up to date. 3155 */ 3156 struct timespec64 now = current_time(inode); 3157 3158 inode_inc_iversion(inode); 3159 inode->i_mtime = now; 3160 inode->i_ctime = now; 3161 trans = btrfs_start_transaction(root, 1); 3162 if (IS_ERR(trans)) { 3163 ret = PTR_ERR(trans); 3164 } else { 3165 int ret2; 3166 3167 ret = btrfs_update_inode(trans, root, BTRFS_I(inode)); 3168 ret2 = btrfs_end_transaction(trans); 3169 if (!ret) 3170 ret = ret2; 3171 } 3172 } 3173 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 3174 return ret; 3175 } 3176 3177 /* Helper structure to record which range is already reserved */ 3178 struct falloc_range { 3179 struct list_head list; 3180 u64 start; 3181 u64 len; 3182 }; 3183 3184 /* 3185 * Helper function to add falloc range 3186 * 3187 * Caller should have locked the larger range of extent containing 3188 * [start, len) 3189 */ 3190 static int add_falloc_range(struct list_head *head, u64 start, u64 len) 3191 { 3192 struct falloc_range *range = NULL; 3193 3194 if (!list_empty(head)) { 3195 /* 3196 * As fallocate iterates by bytenr order, we only need to check 3197 * the last range. 3198 */ 3199 range = list_last_entry(head, struct falloc_range, list); 3200 if (range->start + range->len == start) { 3201 range->len += len; 3202 return 0; 3203 } 3204 } 3205 3206 range = kmalloc(sizeof(*range), GFP_KERNEL); 3207 if (!range) 3208 return -ENOMEM; 3209 range->start = start; 3210 range->len = len; 3211 list_add_tail(&range->list, head); 3212 return 0; 3213 } 3214 3215 static int btrfs_fallocate_update_isize(struct inode *inode, 3216 const u64 end, 3217 const int mode) 3218 { 3219 struct btrfs_trans_handle *trans; 3220 struct btrfs_root *root = BTRFS_I(inode)->root; 3221 int ret; 3222 int ret2; 3223 3224 if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode)) 3225 return 0; 3226 3227 trans = btrfs_start_transaction(root, 1); 3228 if (IS_ERR(trans)) 3229 return PTR_ERR(trans); 3230 3231 inode->i_ctime = current_time(inode); 3232 i_size_write(inode, end); 3233 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0); 3234 ret = btrfs_update_inode(trans, root, BTRFS_I(inode)); 3235 ret2 = btrfs_end_transaction(trans); 3236 3237 return ret ? ret : ret2; 3238 } 3239 3240 enum { 3241 RANGE_BOUNDARY_WRITTEN_EXTENT, 3242 RANGE_BOUNDARY_PREALLOC_EXTENT, 3243 RANGE_BOUNDARY_HOLE, 3244 }; 3245 3246 static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode, 3247 u64 offset) 3248 { 3249 const u64 sectorsize = btrfs_inode_sectorsize(inode); 3250 struct extent_map *em; 3251 int ret; 3252 3253 offset = round_down(offset, sectorsize); 3254 em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize); 3255 if (IS_ERR(em)) 3256 return PTR_ERR(em); 3257 3258 if (em->block_start == EXTENT_MAP_HOLE) 3259 ret = RANGE_BOUNDARY_HOLE; 3260 else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) 3261 ret = RANGE_BOUNDARY_PREALLOC_EXTENT; 3262 else 3263 ret = RANGE_BOUNDARY_WRITTEN_EXTENT; 3264 3265 free_extent_map(em); 3266 return ret; 3267 } 3268 3269 static int btrfs_zero_range(struct inode *inode, 3270 loff_t offset, 3271 loff_t len, 3272 const int mode) 3273 { 3274 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; 3275 struct extent_map *em; 3276 struct extent_changeset *data_reserved = NULL; 3277 int ret; 3278 u64 alloc_hint = 0; 3279 const u64 sectorsize = btrfs_inode_sectorsize(BTRFS_I(inode)); 3280 u64 alloc_start = round_down(offset, sectorsize); 3281 u64 alloc_end = round_up(offset + len, sectorsize); 3282 u64 bytes_to_reserve = 0; 3283 bool space_reserved = false; 3284 3285 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start, 3286 alloc_end - alloc_start); 3287 if (IS_ERR(em)) { 3288 ret = PTR_ERR(em); 3289 goto out; 3290 } 3291 3292 /* 3293 * Avoid hole punching and extent allocation for some cases. More cases 3294 * could be considered, but these are unlikely common and we keep things 3295 * as simple as possible for now. Also, intentionally, if the target 3296 * range contains one or more prealloc extents together with regular 3297 * extents and holes, we drop all the existing extents and allocate a 3298 * new prealloc extent, so that we get a larger contiguous disk extent. 3299 */ 3300 if (em->start <= alloc_start && 3301 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { 3302 const u64 em_end = em->start + em->len; 3303 3304 if (em_end >= offset + len) { 3305 /* 3306 * The whole range is already a prealloc extent, 3307 * do nothing except updating the inode's i_size if 3308 * needed. 3309 */ 3310 free_extent_map(em); 3311 ret = btrfs_fallocate_update_isize(inode, offset + len, 3312 mode); 3313 goto out; 3314 } 3315 /* 3316 * Part of the range is already a prealloc extent, so operate 3317 * only on the remaining part of the range. 3318 */ 3319 alloc_start = em_end; 3320 ASSERT(IS_ALIGNED(alloc_start, sectorsize)); 3321 len = offset + len - alloc_start; 3322 offset = alloc_start; 3323 alloc_hint = em->block_start + em->len; 3324 } 3325 free_extent_map(em); 3326 3327 if (BTRFS_BYTES_TO_BLKS(fs_info, offset) == 3328 BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) { 3329 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start, 3330 sectorsize); 3331 if (IS_ERR(em)) { 3332 ret = PTR_ERR(em); 3333 goto out; 3334 } 3335 3336 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { 3337 free_extent_map(em); 3338 ret = btrfs_fallocate_update_isize(inode, offset + len, 3339 mode); 3340 goto out; 3341 } 3342 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) { 3343 free_extent_map(em); 3344 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len, 3345 0); 3346 if (!ret) 3347 ret = btrfs_fallocate_update_isize(inode, 3348 offset + len, 3349 mode); 3350 return ret; 3351 } 3352 free_extent_map(em); 3353 alloc_start = round_down(offset, sectorsize); 3354 alloc_end = alloc_start + sectorsize; 3355 goto reserve_space; 3356 } 3357 3358 alloc_start = round_up(offset, sectorsize); 3359 alloc_end = round_down(offset + len, sectorsize); 3360 3361 /* 3362 * For unaligned ranges, check the pages at the boundaries, they might 3363 * map to an extent, in which case we need to partially zero them, or 3364 * they might map to a hole, in which case we need our allocation range 3365 * to cover them. 3366 */ 3367 if (!IS_ALIGNED(offset, sectorsize)) { 3368 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode), 3369 offset); 3370 if (ret < 0) 3371 goto out; 3372 if (ret == RANGE_BOUNDARY_HOLE) { 3373 alloc_start = round_down(offset, sectorsize); 3374 ret = 0; 3375 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) { 3376 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0); 3377 if (ret) 3378 goto out; 3379 } else { 3380 ret = 0; 3381 } 3382 } 3383 3384 if (!IS_ALIGNED(offset + len, sectorsize)) { 3385 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode), 3386 offset + len); 3387 if (ret < 0) 3388 goto out; 3389 if (ret == RANGE_BOUNDARY_HOLE) { 3390 alloc_end = round_up(offset + len, sectorsize); 3391 ret = 0; 3392 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) { 3393 ret = btrfs_truncate_block(BTRFS_I(inode), offset + len, 3394 0, 1); 3395 if (ret) 3396 goto out; 3397 } else { 3398 ret = 0; 3399 } 3400 } 3401 3402 reserve_space: 3403 if (alloc_start < alloc_end) { 3404 struct extent_state *cached_state = NULL; 3405 const u64 lockstart = alloc_start; 3406 const u64 lockend = alloc_end - 1; 3407 3408 bytes_to_reserve = alloc_end - alloc_start; 3409 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), 3410 bytes_to_reserve); 3411 if (ret < 0) 3412 goto out; 3413 space_reserved = true; 3414 btrfs_punch_hole_lock_range(inode, lockstart, lockend, 3415 &cached_state); 3416 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved, 3417 alloc_start, bytes_to_reserve); 3418 if (ret) { 3419 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, 3420 lockend, &cached_state); 3421 goto out; 3422 } 3423 ret = btrfs_prealloc_file_range(inode, mode, alloc_start, 3424 alloc_end - alloc_start, 3425 i_blocksize(inode), 3426 offset + len, &alloc_hint); 3427 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, 3428 lockend, &cached_state); 3429 /* btrfs_prealloc_file_range releases reserved space on error */ 3430 if (ret) { 3431 space_reserved = false; 3432 goto out; 3433 } 3434 } 3435 ret = btrfs_fallocate_update_isize(inode, offset + len, mode); 3436 out: 3437 if (ret && space_reserved) 3438 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved, 3439 alloc_start, bytes_to_reserve); 3440 extent_changeset_free(data_reserved); 3441 3442 return ret; 3443 } 3444 3445 static long btrfs_fallocate(struct file *file, int mode, 3446 loff_t offset, loff_t len) 3447 { 3448 struct inode *inode = file_inode(file); 3449 struct extent_state *cached_state = NULL; 3450 struct extent_changeset *data_reserved = NULL; 3451 struct falloc_range *range; 3452 struct falloc_range *tmp; 3453 struct list_head reserve_list; 3454 u64 cur_offset; 3455 u64 last_byte; 3456 u64 alloc_start; 3457 u64 alloc_end; 3458 u64 alloc_hint = 0; 3459 u64 locked_end; 3460 u64 actual_end = 0; 3461 u64 data_space_needed = 0; 3462 u64 data_space_reserved = 0; 3463 u64 qgroup_reserved = 0; 3464 struct extent_map *em; 3465 int blocksize = btrfs_inode_sectorsize(BTRFS_I(inode)); 3466 int ret; 3467 3468 /* Do not allow fallocate in ZONED mode */ 3469 if (btrfs_is_zoned(btrfs_sb(inode->i_sb))) 3470 return -EOPNOTSUPP; 3471 3472 alloc_start = round_down(offset, blocksize); 3473 alloc_end = round_up(offset + len, blocksize); 3474 cur_offset = alloc_start; 3475 3476 /* Make sure we aren't being give some crap mode */ 3477 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | 3478 FALLOC_FL_ZERO_RANGE)) 3479 return -EOPNOTSUPP; 3480 3481 if (mode & FALLOC_FL_PUNCH_HOLE) 3482 return btrfs_punch_hole(file, offset, len); 3483 3484 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP); 3485 3486 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) { 3487 ret = inode_newsize_ok(inode, offset + len); 3488 if (ret) 3489 goto out; 3490 } 3491 3492 ret = file_modified(file); 3493 if (ret) 3494 goto out; 3495 3496 /* 3497 * TODO: Move these two operations after we have checked 3498 * accurate reserved space, or fallocate can still fail but 3499 * with page truncated or size expanded. 3500 * 3501 * But that's a minor problem and won't do much harm BTW. 3502 */ 3503 if (alloc_start > inode->i_size) { 3504 ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode), 3505 alloc_start); 3506 if (ret) 3507 goto out; 3508 } else if (offset + len > inode->i_size) { 3509 /* 3510 * If we are fallocating from the end of the file onward we 3511 * need to zero out the end of the block if i_size lands in the 3512 * middle of a block. 3513 */ 3514 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0); 3515 if (ret) 3516 goto out; 3517 } 3518 3519 /* 3520 * We have locked the inode at the VFS level (in exclusive mode) and we 3521 * have locked the i_mmap_lock lock (in exclusive mode). Now before 3522 * locking the file range, flush all dealloc in the range and wait for 3523 * all ordered extents in the range to complete. After this we can lock 3524 * the file range and, due to the previous locking we did, we know there 3525 * can't be more delalloc or ordered extents in the range. 3526 */ 3527 ret = btrfs_wait_ordered_range(inode, alloc_start, 3528 alloc_end - alloc_start); 3529 if (ret) 3530 goto out; 3531 3532 if (mode & FALLOC_FL_ZERO_RANGE) { 3533 ret = btrfs_zero_range(inode, offset, len, mode); 3534 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 3535 return ret; 3536 } 3537 3538 locked_end = alloc_end - 1; 3539 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start, locked_end, 3540 &cached_state); 3541 3542 btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end); 3543 3544 /* First, check if we exceed the qgroup limit */ 3545 INIT_LIST_HEAD(&reserve_list); 3546 while (cur_offset < alloc_end) { 3547 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset, 3548 alloc_end - cur_offset); 3549 if (IS_ERR(em)) { 3550 ret = PTR_ERR(em); 3551 break; 3552 } 3553 last_byte = min(extent_map_end(em), alloc_end); 3554 actual_end = min_t(u64, extent_map_end(em), offset + len); 3555 last_byte = ALIGN(last_byte, blocksize); 3556 if (em->block_start == EXTENT_MAP_HOLE || 3557 (cur_offset >= inode->i_size && 3558 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) { 3559 const u64 range_len = last_byte - cur_offset; 3560 3561 ret = add_falloc_range(&reserve_list, cur_offset, range_len); 3562 if (ret < 0) { 3563 free_extent_map(em); 3564 break; 3565 } 3566 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), 3567 &data_reserved, cur_offset, range_len); 3568 if (ret < 0) { 3569 free_extent_map(em); 3570 break; 3571 } 3572 qgroup_reserved += range_len; 3573 data_space_needed += range_len; 3574 } 3575 free_extent_map(em); 3576 cur_offset = last_byte; 3577 } 3578 3579 if (!ret && data_space_needed > 0) { 3580 /* 3581 * We are safe to reserve space here as we can't have delalloc 3582 * in the range, see above. 3583 */ 3584 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), 3585 data_space_needed); 3586 if (!ret) 3587 data_space_reserved = data_space_needed; 3588 } 3589 3590 /* 3591 * If ret is still 0, means we're OK to fallocate. 3592 * Or just cleanup the list and exit. 3593 */ 3594 list_for_each_entry_safe(range, tmp, &reserve_list, list) { 3595 if (!ret) { 3596 ret = btrfs_prealloc_file_range(inode, mode, 3597 range->start, 3598 range->len, i_blocksize(inode), 3599 offset + len, &alloc_hint); 3600 /* 3601 * btrfs_prealloc_file_range() releases space even 3602 * if it returns an error. 3603 */ 3604 data_space_reserved -= range->len; 3605 qgroup_reserved -= range->len; 3606 } else if (data_space_reserved > 0) { 3607 btrfs_free_reserved_data_space(BTRFS_I(inode), 3608 data_reserved, range->start, 3609 range->len); 3610 data_space_reserved -= range->len; 3611 qgroup_reserved -= range->len; 3612 } else if (qgroup_reserved > 0) { 3613 btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved, 3614 range->start, range->len); 3615 qgroup_reserved -= range->len; 3616 } 3617 list_del(&range->list); 3618 kfree(range); 3619 } 3620 if (ret < 0) 3621 goto out_unlock; 3622 3623 /* 3624 * We didn't need to allocate any more space, but we still extended the 3625 * size of the file so we need to update i_size and the inode item. 3626 */ 3627 ret = btrfs_fallocate_update_isize(inode, actual_end, mode); 3628 out_unlock: 3629 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end, 3630 &cached_state); 3631 out: 3632 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP); 3633 extent_changeset_free(data_reserved); 3634 return ret; 3635 } 3636 3637 static loff_t find_desired_extent(struct btrfs_inode *inode, loff_t offset, 3638 int whence) 3639 { 3640 struct btrfs_fs_info *fs_info = inode->root->fs_info; 3641 struct extent_map *em = NULL; 3642 struct extent_state *cached_state = NULL; 3643 loff_t i_size = inode->vfs_inode.i_size; 3644 u64 lockstart; 3645 u64 lockend; 3646 u64 start; 3647 u64 len; 3648 int ret = 0; 3649 3650 if (i_size == 0 || offset >= i_size) 3651 return -ENXIO; 3652 3653 /* 3654 * offset can be negative, in this case we start finding DATA/HOLE from 3655 * the very start of the file. 3656 */ 3657 start = max_t(loff_t, 0, offset); 3658 3659 lockstart = round_down(start, fs_info->sectorsize); 3660 lockend = round_up(i_size, fs_info->sectorsize); 3661 if (lockend <= lockstart) 3662 lockend = lockstart + fs_info->sectorsize; 3663 lockend--; 3664 len = lockend - lockstart + 1; 3665 3666 lock_extent_bits(&inode->io_tree, lockstart, lockend, &cached_state); 3667 3668 while (start < i_size) { 3669 em = btrfs_get_extent_fiemap(inode, start, len); 3670 if (IS_ERR(em)) { 3671 ret = PTR_ERR(em); 3672 em = NULL; 3673 break; 3674 } 3675 3676 if (whence == SEEK_HOLE && 3677 (em->block_start == EXTENT_MAP_HOLE || 3678 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) 3679 break; 3680 else if (whence == SEEK_DATA && 3681 (em->block_start != EXTENT_MAP_HOLE && 3682 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) 3683 break; 3684 3685 start = em->start + em->len; 3686 free_extent_map(em); 3687 em = NULL; 3688 cond_resched(); 3689 } 3690 free_extent_map(em); 3691 unlock_extent_cached(&inode->io_tree, lockstart, lockend, 3692 &cached_state); 3693 if (ret) { 3694 offset = ret; 3695 } else { 3696 if (whence == SEEK_DATA && start >= i_size) 3697 offset = -ENXIO; 3698 else 3699 offset = min_t(loff_t, start, i_size); 3700 } 3701 3702 return offset; 3703 } 3704 3705 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence) 3706 { 3707 struct inode *inode = file->f_mapping->host; 3708 3709 switch (whence) { 3710 default: 3711 return generic_file_llseek(file, offset, whence); 3712 case SEEK_DATA: 3713 case SEEK_HOLE: 3714 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED); 3715 offset = find_desired_extent(BTRFS_I(inode), offset, whence); 3716 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); 3717 break; 3718 } 3719 3720 if (offset < 0) 3721 return offset; 3722 3723 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes); 3724 } 3725 3726 static int btrfs_file_open(struct inode *inode, struct file *filp) 3727 { 3728 int ret; 3729 3730 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC; 3731 3732 ret = fsverity_file_open(inode, filp); 3733 if (ret) 3734 return ret; 3735 return generic_file_open(inode, filp); 3736 } 3737 3738 static int check_direct_read(struct btrfs_fs_info *fs_info, 3739 const struct iov_iter *iter, loff_t offset) 3740 { 3741 int ret; 3742 int i, seg; 3743 3744 ret = check_direct_IO(fs_info, iter, offset); 3745 if (ret < 0) 3746 return ret; 3747 3748 if (!iter_is_iovec(iter)) 3749 return 0; 3750 3751 for (seg = 0; seg < iter->nr_segs; seg++) 3752 for (i = seg + 1; i < iter->nr_segs; i++) 3753 if (iter->iov[seg].iov_base == iter->iov[i].iov_base) 3754 return -EINVAL; 3755 return 0; 3756 } 3757 3758 static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to) 3759 { 3760 struct inode *inode = file_inode(iocb->ki_filp); 3761 size_t prev_left = 0; 3762 ssize_t read = 0; 3763 ssize_t ret; 3764 3765 if (fsverity_active(inode)) 3766 return 0; 3767 3768 if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos)) 3769 return 0; 3770 3771 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED); 3772 again: 3773 /* 3774 * This is similar to what we do for direct IO writes, see the comment 3775 * at btrfs_direct_write(), but we also disable page faults in addition 3776 * to disabling them only at the iov_iter level. This is because when 3777 * reading from a hole or prealloc extent, iomap calls iov_iter_zero(), 3778 * which can still trigger page fault ins despite having set ->nofault 3779 * to true of our 'to' iov_iter. 3780 * 3781 * The difference to direct IO writes is that we deadlock when trying 3782 * to lock the extent range in the inode's tree during he page reads 3783 * triggered by the fault in (while for writes it is due to waiting for 3784 * our own ordered extent). This is because for direct IO reads, 3785 * btrfs_dio_iomap_begin() returns with the extent range locked, which 3786 * is only unlocked in the endio callback (end_bio_extent_readpage()). 3787 */ 3788 pagefault_disable(); 3789 to->nofault = true; 3790 ret = btrfs_dio_rw(iocb, to, read); 3791 to->nofault = false; 3792 pagefault_enable(); 3793 3794 /* No increment (+=) because iomap returns a cumulative value. */ 3795 if (ret > 0) 3796 read = ret; 3797 3798 if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) { 3799 const size_t left = iov_iter_count(to); 3800 3801 if (left == prev_left) { 3802 /* 3803 * We didn't make any progress since the last attempt, 3804 * fallback to a buffered read for the remainder of the 3805 * range. This is just to avoid any possibility of looping 3806 * for too long. 3807 */ 3808 ret = read; 3809 } else { 3810 /* 3811 * We made some progress since the last retry or this is 3812 * the first time we are retrying. Fault in as many pages 3813 * as possible and retry. 3814 */ 3815 fault_in_iov_iter_writeable(to, left); 3816 prev_left = left; 3817 goto again; 3818 } 3819 } 3820 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); 3821 return ret < 0 ? ret : read; 3822 } 3823 3824 static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) 3825 { 3826 ssize_t ret = 0; 3827 3828 if (iocb->ki_flags & IOCB_DIRECT) { 3829 ret = btrfs_direct_read(iocb, to); 3830 if (ret < 0 || !iov_iter_count(to) || 3831 iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp))) 3832 return ret; 3833 } 3834 3835 return filemap_read(iocb, to, ret); 3836 } 3837 3838 const struct file_operations btrfs_file_operations = { 3839 .llseek = btrfs_file_llseek, 3840 .read_iter = btrfs_file_read_iter, 3841 .splice_read = generic_file_splice_read, 3842 .write_iter = btrfs_file_write_iter, 3843 .splice_write = iter_file_splice_write, 3844 .mmap = btrfs_file_mmap, 3845 .open = btrfs_file_open, 3846 .release = btrfs_release_file, 3847 .get_unmapped_area = thp_get_unmapped_area, 3848 .fsync = btrfs_sync_file, 3849 .fallocate = btrfs_fallocate, 3850 .unlocked_ioctl = btrfs_ioctl, 3851 #ifdef CONFIG_COMPAT 3852 .compat_ioctl = btrfs_compat_ioctl, 3853 #endif 3854 .remap_file_range = btrfs_remap_file_range, 3855 }; 3856 3857 void __cold btrfs_auto_defrag_exit(void) 3858 { 3859 kmem_cache_destroy(btrfs_inode_defrag_cachep); 3860 } 3861 3862 int __init btrfs_auto_defrag_init(void) 3863 { 3864 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag", 3865 sizeof(struct inode_defrag), 0, 3866 SLAB_MEM_SPREAD, 3867 NULL); 3868 if (!btrfs_inode_defrag_cachep) 3869 return -ENOMEM; 3870 3871 return 0; 3872 } 3873 3874 int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end) 3875 { 3876 int ret; 3877 3878 /* 3879 * So with compression we will find and lock a dirty page and clear the 3880 * first one as dirty, setup an async extent, and immediately return 3881 * with the entire range locked but with nobody actually marked with 3882 * writeback. So we can't just filemap_write_and_wait_range() and 3883 * expect it to work since it will just kick off a thread to do the 3884 * actual work. So we need to call filemap_fdatawrite_range _again_ 3885 * since it will wait on the page lock, which won't be unlocked until 3886 * after the pages have been marked as writeback and so we're good to go 3887 * from there. We have to do this otherwise we'll miss the ordered 3888 * extents and that results in badness. Please Josef, do not think you 3889 * know better and pull this out at some point in the future, it is 3890 * right and you are wrong. 3891 */ 3892 ret = filemap_fdatawrite_range(inode->i_mapping, start, end); 3893 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, 3894 &BTRFS_I(inode)->runtime_flags)) 3895 ret = filemap_fdatawrite_range(inode->i_mapping, start, end); 3896 3897 return ret; 3898 } 3899
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.