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