1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2007 Oracle. All rights reserved. 4 */ 5 6 #include <linux/kernel.h> 7 #include <linux/bio.h> 8 #include <linux/buffer_head.h> 9 #include <linux/file.h> 10 #include <linux/fs.h> 11 #include <linux/pagemap.h> 12 #include <linux/highmem.h> 13 #include <linux/time.h> 14 #include <linux/init.h> 15 #include <linux/string.h> 16 #include <linux/backing-dev.h> 17 #include <linux/writeback.h> 18 #include <linux/compat.h> 19 #include <linux/xattr.h> 20 #include <linux/posix_acl.h> 21 #include <linux/falloc.h> 22 #include <linux/slab.h> 23 #include <linux/ratelimit.h> 24 #include <linux/btrfs.h> 25 #include <linux/blkdev.h> 26 #include <linux/posix_acl_xattr.h> 27 #include <linux/uio.h> 28 #include <linux/magic.h> 29 #include <linux/iversion.h> 30 #include <linux/swap.h> 31 #include <linux/migrate.h> 32 #include <linux/sched/mm.h> 33 #include <asm/unaligned.h> 34 #include "misc.h" 35 #include "ctree.h" 36 #include "disk-io.h" 37 #include "transaction.h" 38 #include "btrfs_inode.h" 39 #include "print-tree.h" 40 #include "ordered-data.h" 41 #include "xattr.h" 42 #include "tree-log.h" 43 #include "volumes.h" 44 #include "compression.h" 45 #include "locking.h" 46 #include "free-space-cache.h" 47 #include "inode-map.h" 48 #include "props.h" 49 #include "qgroup.h" 50 #include "delalloc-space.h" 51 #include "block-group.h" 52 #include "space-info.h" 53 54 struct btrfs_iget_args { 55 u64 ino; 56 struct btrfs_root *root; 57 }; 58 59 struct btrfs_dio_data { 60 u64 reserve; 61 u64 unsubmitted_oe_range_start; 62 u64 unsubmitted_oe_range_end; 63 int overwrite; 64 }; 65 66 static const struct inode_operations btrfs_dir_inode_operations; 67 static const struct inode_operations btrfs_symlink_inode_operations; 68 static const struct inode_operations btrfs_special_inode_operations; 69 static const struct inode_operations btrfs_file_inode_operations; 70 static const struct address_space_operations btrfs_aops; 71 static const struct file_operations btrfs_dir_file_operations; 72 static const struct extent_io_ops btrfs_extent_io_ops; 73 74 static struct kmem_cache *btrfs_inode_cachep; 75 struct kmem_cache *btrfs_trans_handle_cachep; 76 struct kmem_cache *btrfs_path_cachep; 77 struct kmem_cache *btrfs_free_space_cachep; 78 struct kmem_cache *btrfs_free_space_bitmap_cachep; 79 80 static int btrfs_setsize(struct inode *inode, struct iattr *attr); 81 static int btrfs_truncate(struct inode *inode, bool skip_writeback); 82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent); 83 static noinline int cow_file_range(struct btrfs_inode *inode, 84 struct page *locked_page, 85 u64 start, u64 end, int *page_started, 86 unsigned long *nr_written, int unlock); 87 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start, 88 u64 len, u64 orig_start, u64 block_start, 89 u64 block_len, u64 orig_block_len, 90 u64 ram_bytes, int compress_type, 91 int type); 92 93 static void __endio_write_update_ordered(struct btrfs_inode *inode, 94 const u64 offset, const u64 bytes, 95 const bool uptodate); 96 97 /* 98 * Cleanup all submitted ordered extents in specified range to handle errors 99 * from the btrfs_run_delalloc_range() callback. 100 * 101 * NOTE: caller must ensure that when an error happens, it can not call 102 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING 103 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata 104 * to be released, which we want to happen only when finishing the ordered 105 * extent (btrfs_finish_ordered_io()). 106 */ 107 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode, 108 struct page *locked_page, 109 u64 offset, u64 bytes) 110 { 111 unsigned long index = offset >> PAGE_SHIFT; 112 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT; 113 u64 page_start = page_offset(locked_page); 114 u64 page_end = page_start + PAGE_SIZE - 1; 115 116 struct page *page; 117 118 while (index <= end_index) { 119 page = find_get_page(inode->vfs_inode.i_mapping, index); 120 index++; 121 if (!page) 122 continue; 123 ClearPagePrivate2(page); 124 put_page(page); 125 } 126 127 /* 128 * In case this page belongs to the delalloc range being instantiated 129 * then skip it, since the first page of a range is going to be 130 * properly cleaned up by the caller of run_delalloc_range 131 */ 132 if (page_start >= offset && page_end <= (offset + bytes - 1)) { 133 offset += PAGE_SIZE; 134 bytes -= PAGE_SIZE; 135 } 136 137 return __endio_write_update_ordered(inode, offset, bytes, false); 138 } 139 140 static int btrfs_dirty_inode(struct inode *inode); 141 142 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS 143 void btrfs_test_inode_set_ops(struct inode *inode) 144 { 145 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; 146 } 147 #endif 148 149 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans, 150 struct inode *inode, struct inode *dir, 151 const struct qstr *qstr) 152 { 153 int err; 154 155 err = btrfs_init_acl(trans, inode, dir); 156 if (!err) 157 err = btrfs_xattr_security_init(trans, inode, dir, qstr); 158 return err; 159 } 160 161 /* 162 * this does all the hard work for inserting an inline extent into 163 * the btree. The caller should have done a btrfs_drop_extents so that 164 * no overlapping inline items exist in the btree 165 */ 166 static int insert_inline_extent(struct btrfs_trans_handle *trans, 167 struct btrfs_path *path, int extent_inserted, 168 struct btrfs_root *root, struct inode *inode, 169 u64 start, size_t size, size_t compressed_size, 170 int compress_type, 171 struct page **compressed_pages) 172 { 173 struct extent_buffer *leaf; 174 struct page *page = NULL; 175 char *kaddr; 176 unsigned long ptr; 177 struct btrfs_file_extent_item *ei; 178 int ret; 179 size_t cur_size = size; 180 unsigned long offset; 181 182 ASSERT((compressed_size > 0 && compressed_pages) || 183 (compressed_size == 0 && !compressed_pages)); 184 185 if (compressed_size && compressed_pages) 186 cur_size = compressed_size; 187 188 inode_add_bytes(inode, size); 189 190 if (!extent_inserted) { 191 struct btrfs_key key; 192 size_t datasize; 193 194 key.objectid = btrfs_ino(BTRFS_I(inode)); 195 key.offset = start; 196 key.type = BTRFS_EXTENT_DATA_KEY; 197 198 datasize = btrfs_file_extent_calc_inline_size(cur_size); 199 path->leave_spinning = 1; 200 ret = btrfs_insert_empty_item(trans, root, path, &key, 201 datasize); 202 if (ret) 203 goto fail; 204 } 205 leaf = path->nodes[0]; 206 ei = btrfs_item_ptr(leaf, path->slots[0], 207 struct btrfs_file_extent_item); 208 btrfs_set_file_extent_generation(leaf, ei, trans->transid); 209 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); 210 btrfs_set_file_extent_encryption(leaf, ei, 0); 211 btrfs_set_file_extent_other_encoding(leaf, ei, 0); 212 btrfs_set_file_extent_ram_bytes(leaf, ei, size); 213 ptr = btrfs_file_extent_inline_start(ei); 214 215 if (compress_type != BTRFS_COMPRESS_NONE) { 216 struct page *cpage; 217 int i = 0; 218 while (compressed_size > 0) { 219 cpage = compressed_pages[i]; 220 cur_size = min_t(unsigned long, compressed_size, 221 PAGE_SIZE); 222 223 kaddr = kmap_atomic(cpage); 224 write_extent_buffer(leaf, kaddr, ptr, cur_size); 225 kunmap_atomic(kaddr); 226 227 i++; 228 ptr += cur_size; 229 compressed_size -= cur_size; 230 } 231 btrfs_set_file_extent_compression(leaf, ei, 232 compress_type); 233 } else { 234 page = find_get_page(inode->i_mapping, 235 start >> PAGE_SHIFT); 236 btrfs_set_file_extent_compression(leaf, ei, 0); 237 kaddr = kmap_atomic(page); 238 offset = offset_in_page(start); 239 write_extent_buffer(leaf, kaddr + offset, ptr, size); 240 kunmap_atomic(kaddr); 241 put_page(page); 242 } 243 btrfs_mark_buffer_dirty(leaf); 244 btrfs_release_path(path); 245 246 /* 247 * We align size to sectorsize for inline extents just for simplicity 248 * sake. 249 */ 250 size = ALIGN(size, root->fs_info->sectorsize); 251 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size); 252 if (ret) 253 goto fail; 254 255 /* 256 * we're an inline extent, so nobody can 257 * extend the file past i_size without locking 258 * a page we already have locked. 259 * 260 * We must do any isize and inode updates 261 * before we unlock the pages. Otherwise we 262 * could end up racing with unlink. 263 */ 264 BTRFS_I(inode)->disk_i_size = inode->i_size; 265 ret = btrfs_update_inode(trans, root, inode); 266 267 fail: 268 return ret; 269 } 270 271 272 /* 273 * conditionally insert an inline extent into the file. This 274 * does the checks required to make sure the data is small enough 275 * to fit as an inline extent. 276 */ 277 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start, 278 u64 end, size_t compressed_size, 279 int compress_type, 280 struct page **compressed_pages) 281 { 282 struct btrfs_root *root = inode->root; 283 struct btrfs_fs_info *fs_info = root->fs_info; 284 struct btrfs_trans_handle *trans; 285 u64 isize = i_size_read(&inode->vfs_inode); 286 u64 actual_end = min(end + 1, isize); 287 u64 inline_len = actual_end - start; 288 u64 aligned_end = ALIGN(end, fs_info->sectorsize); 289 u64 data_len = inline_len; 290 int ret; 291 struct btrfs_path *path; 292 int extent_inserted = 0; 293 u32 extent_item_size; 294 295 if (compressed_size) 296 data_len = compressed_size; 297 298 if (start > 0 || 299 actual_end > fs_info->sectorsize || 300 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) || 301 (!compressed_size && 302 (actual_end & (fs_info->sectorsize - 1)) == 0) || 303 end + 1 < isize || 304 data_len > fs_info->max_inline) { 305 return 1; 306 } 307 308 path = btrfs_alloc_path(); 309 if (!path) 310 return -ENOMEM; 311 312 trans = btrfs_join_transaction(root); 313 if (IS_ERR(trans)) { 314 btrfs_free_path(path); 315 return PTR_ERR(trans); 316 } 317 trans->block_rsv = &inode->block_rsv; 318 319 if (compressed_size && compressed_pages) 320 extent_item_size = btrfs_file_extent_calc_inline_size( 321 compressed_size); 322 else 323 extent_item_size = btrfs_file_extent_calc_inline_size( 324 inline_len); 325 326 ret = __btrfs_drop_extents(trans, root, inode, path, start, aligned_end, 327 NULL, 1, 1, extent_item_size, 328 &extent_inserted); 329 if (ret) { 330 btrfs_abort_transaction(trans, ret); 331 goto out; 332 } 333 334 if (isize > actual_end) 335 inline_len = min_t(u64, isize, actual_end); 336 ret = insert_inline_extent(trans, path, extent_inserted, 337 root, &inode->vfs_inode, start, 338 inline_len, compressed_size, 339 compress_type, compressed_pages); 340 if (ret && ret != -ENOSPC) { 341 btrfs_abort_transaction(trans, ret); 342 goto out; 343 } else if (ret == -ENOSPC) { 344 ret = 1; 345 goto out; 346 } 347 348 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags); 349 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0); 350 out: 351 /* 352 * Don't forget to free the reserved space, as for inlined extent 353 * it won't count as data extent, free them directly here. 354 * And at reserve time, it's always aligned to page size, so 355 * just free one page here. 356 */ 357 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE); 358 btrfs_free_path(path); 359 btrfs_end_transaction(trans); 360 return ret; 361 } 362 363 struct async_extent { 364 u64 start; 365 u64 ram_size; 366 u64 compressed_size; 367 struct page **pages; 368 unsigned long nr_pages; 369 int compress_type; 370 struct list_head list; 371 }; 372 373 struct async_chunk { 374 struct inode *inode; 375 struct page *locked_page; 376 u64 start; 377 u64 end; 378 unsigned int write_flags; 379 struct list_head extents; 380 struct cgroup_subsys_state *blkcg_css; 381 struct btrfs_work work; 382 atomic_t *pending; 383 }; 384 385 struct async_cow { 386 /* Number of chunks in flight; must be first in the structure */ 387 atomic_t num_chunks; 388 struct async_chunk chunks[]; 389 }; 390 391 static noinline int add_async_extent(struct async_chunk *cow, 392 u64 start, u64 ram_size, 393 u64 compressed_size, 394 struct page **pages, 395 unsigned long nr_pages, 396 int compress_type) 397 { 398 struct async_extent *async_extent; 399 400 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS); 401 BUG_ON(!async_extent); /* -ENOMEM */ 402 async_extent->start = start; 403 async_extent->ram_size = ram_size; 404 async_extent->compressed_size = compressed_size; 405 async_extent->pages = pages; 406 async_extent->nr_pages = nr_pages; 407 async_extent->compress_type = compress_type; 408 list_add_tail(&async_extent->list, &cow->extents); 409 return 0; 410 } 411 412 /* 413 * Check if the inode has flags compatible with compression 414 */ 415 static inline bool inode_can_compress(struct btrfs_inode *inode) 416 { 417 if (inode->flags & BTRFS_INODE_NODATACOW || 418 inode->flags & BTRFS_INODE_NODATASUM) 419 return false; 420 return true; 421 } 422 423 /* 424 * Check if the inode needs to be submitted to compression, based on mount 425 * options, defragmentation, properties or heuristics. 426 */ 427 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start, 428 u64 end) 429 { 430 struct btrfs_fs_info *fs_info = inode->root->fs_info; 431 432 if (!inode_can_compress(inode)) { 433 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG), 434 KERN_ERR "BTRFS: unexpected compression for ino %llu\n", 435 btrfs_ino(inode)); 436 return 0; 437 } 438 /* force compress */ 439 if (btrfs_test_opt(fs_info, FORCE_COMPRESS)) 440 return 1; 441 /* defrag ioctl */ 442 if (inode->defrag_compress) 443 return 1; 444 /* bad compression ratios */ 445 if (inode->flags & BTRFS_INODE_NOCOMPRESS) 446 return 0; 447 if (btrfs_test_opt(fs_info, COMPRESS) || 448 inode->flags & BTRFS_INODE_COMPRESS || 449 inode->prop_compress) 450 return btrfs_compress_heuristic(&inode->vfs_inode, start, end); 451 return 0; 452 } 453 454 static inline void inode_should_defrag(struct btrfs_inode *inode, 455 u64 start, u64 end, u64 num_bytes, u64 small_write) 456 { 457 /* If this is a small write inside eof, kick off a defrag */ 458 if (num_bytes < small_write && 459 (start > 0 || end + 1 < inode->disk_i_size)) 460 btrfs_add_inode_defrag(NULL, inode); 461 } 462 463 /* 464 * we create compressed extents in two phases. The first 465 * phase compresses a range of pages that have already been 466 * locked (both pages and state bits are locked). 467 * 468 * This is done inside an ordered work queue, and the compression 469 * is spread across many cpus. The actual IO submission is step 470 * two, and the ordered work queue takes care of making sure that 471 * happens in the same order things were put onto the queue by 472 * writepages and friends. 473 * 474 * If this code finds it can't get good compression, it puts an 475 * entry onto the work queue to write the uncompressed bytes. This 476 * makes sure that both compressed inodes and uncompressed inodes 477 * are written in the same order that the flusher thread sent them 478 * down. 479 */ 480 static noinline int compress_file_range(struct async_chunk *async_chunk) 481 { 482 struct inode *inode = async_chunk->inode; 483 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 484 u64 blocksize = fs_info->sectorsize; 485 u64 start = async_chunk->start; 486 u64 end = async_chunk->end; 487 u64 actual_end; 488 u64 i_size; 489 int ret = 0; 490 struct page **pages = NULL; 491 unsigned long nr_pages; 492 unsigned long total_compressed = 0; 493 unsigned long total_in = 0; 494 int i; 495 int will_compress; 496 int compress_type = fs_info->compress_type; 497 int compressed_extents = 0; 498 int redirty = 0; 499 500 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1, 501 SZ_16K); 502 503 /* 504 * We need to save i_size before now because it could change in between 505 * us evaluating the size and assigning it. This is because we lock and 506 * unlock the page in truncate and fallocate, and then modify the i_size 507 * later on. 508 * 509 * The barriers are to emulate READ_ONCE, remove that once i_size_read 510 * does that for us. 511 */ 512 barrier(); 513 i_size = i_size_read(inode); 514 barrier(); 515 actual_end = min_t(u64, i_size, end + 1); 516 again: 517 will_compress = 0; 518 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1; 519 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0); 520 nr_pages = min_t(unsigned long, nr_pages, 521 BTRFS_MAX_COMPRESSED / PAGE_SIZE); 522 523 /* 524 * we don't want to send crud past the end of i_size through 525 * compression, that's just a waste of CPU time. So, if the 526 * end of the file is before the start of our current 527 * requested range of bytes, we bail out to the uncompressed 528 * cleanup code that can deal with all of this. 529 * 530 * It isn't really the fastest way to fix things, but this is a 531 * very uncommon corner. 532 */ 533 if (actual_end <= start) 534 goto cleanup_and_bail_uncompressed; 535 536 total_compressed = actual_end - start; 537 538 /* 539 * skip compression for a small file range(<=blocksize) that 540 * isn't an inline extent, since it doesn't save disk space at all. 541 */ 542 if (total_compressed <= blocksize && 543 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) 544 goto cleanup_and_bail_uncompressed; 545 546 total_compressed = min_t(unsigned long, total_compressed, 547 BTRFS_MAX_UNCOMPRESSED); 548 total_in = 0; 549 ret = 0; 550 551 /* 552 * we do compression for mount -o compress and when the 553 * inode has not been flagged as nocompress. This flag can 554 * change at any time if we discover bad compression ratios. 555 */ 556 if (inode_need_compress(BTRFS_I(inode), start, end)) { 557 WARN_ON(pages); 558 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS); 559 if (!pages) { 560 /* just bail out to the uncompressed code */ 561 nr_pages = 0; 562 goto cont; 563 } 564 565 if (BTRFS_I(inode)->defrag_compress) 566 compress_type = BTRFS_I(inode)->defrag_compress; 567 else if (BTRFS_I(inode)->prop_compress) 568 compress_type = BTRFS_I(inode)->prop_compress; 569 570 /* 571 * we need to call clear_page_dirty_for_io on each 572 * page in the range. Otherwise applications with the file 573 * mmap'd can wander in and change the page contents while 574 * we are compressing them. 575 * 576 * If the compression fails for any reason, we set the pages 577 * dirty again later on. 578 * 579 * Note that the remaining part is redirtied, the start pointer 580 * has moved, the end is the original one. 581 */ 582 if (!redirty) { 583 extent_range_clear_dirty_for_io(inode, start, end); 584 redirty = 1; 585 } 586 587 /* Compression level is applied here and only here */ 588 ret = btrfs_compress_pages( 589 compress_type | (fs_info->compress_level << 4), 590 inode->i_mapping, start, 591 pages, 592 &nr_pages, 593 &total_in, 594 &total_compressed); 595 596 if (!ret) { 597 unsigned long offset = offset_in_page(total_compressed); 598 struct page *page = pages[nr_pages - 1]; 599 char *kaddr; 600 601 /* zero the tail end of the last page, we might be 602 * sending it down to disk 603 */ 604 if (offset) { 605 kaddr = kmap_atomic(page); 606 memset(kaddr + offset, 0, 607 PAGE_SIZE - offset); 608 kunmap_atomic(kaddr); 609 } 610 will_compress = 1; 611 } 612 } 613 cont: 614 if (start == 0) { 615 /* lets try to make an inline extent */ 616 if (ret || total_in < actual_end) { 617 /* we didn't compress the entire range, try 618 * to make an uncompressed inline extent. 619 */ 620 ret = cow_file_range_inline(BTRFS_I(inode), start, end, 621 0, BTRFS_COMPRESS_NONE, 622 NULL); 623 } else { 624 /* try making a compressed inline extent */ 625 ret = cow_file_range_inline(BTRFS_I(inode), start, end, 626 total_compressed, 627 compress_type, pages); 628 } 629 if (ret <= 0) { 630 unsigned long clear_flags = EXTENT_DELALLOC | 631 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | 632 EXTENT_DO_ACCOUNTING; 633 unsigned long page_error_op; 634 635 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0; 636 637 /* 638 * inline extent creation worked or returned error, 639 * we don't need to create any more async work items. 640 * Unlock and free up our temp pages. 641 * 642 * We use DO_ACCOUNTING here because we need the 643 * delalloc_release_metadata to be done _after_ we drop 644 * our outstanding extent for clearing delalloc for this 645 * range. 646 */ 647 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end, 648 NULL, 649 clear_flags, 650 PAGE_UNLOCK | 651 PAGE_CLEAR_DIRTY | 652 PAGE_SET_WRITEBACK | 653 page_error_op | 654 PAGE_END_WRITEBACK); 655 656 for (i = 0; i < nr_pages; i++) { 657 WARN_ON(pages[i]->mapping); 658 put_page(pages[i]); 659 } 660 kfree(pages); 661 662 return 0; 663 } 664 } 665 666 if (will_compress) { 667 /* 668 * we aren't doing an inline extent round the compressed size 669 * up to a block size boundary so the allocator does sane 670 * things 671 */ 672 total_compressed = ALIGN(total_compressed, blocksize); 673 674 /* 675 * one last check to make sure the compression is really a 676 * win, compare the page count read with the blocks on disk, 677 * compression must free at least one sector size 678 */ 679 total_in = ALIGN(total_in, PAGE_SIZE); 680 if (total_compressed + blocksize <= total_in) { 681 compressed_extents++; 682 683 /* 684 * The async work queues will take care of doing actual 685 * allocation on disk for these compressed pages, and 686 * will submit them to the elevator. 687 */ 688 add_async_extent(async_chunk, start, total_in, 689 total_compressed, pages, nr_pages, 690 compress_type); 691 692 if (start + total_in < end) { 693 start += total_in; 694 pages = NULL; 695 cond_resched(); 696 goto again; 697 } 698 return compressed_extents; 699 } 700 } 701 if (pages) { 702 /* 703 * the compression code ran but failed to make things smaller, 704 * free any pages it allocated and our page pointer array 705 */ 706 for (i = 0; i < nr_pages; i++) { 707 WARN_ON(pages[i]->mapping); 708 put_page(pages[i]); 709 } 710 kfree(pages); 711 pages = NULL; 712 total_compressed = 0; 713 nr_pages = 0; 714 715 /* flag the file so we don't compress in the future */ 716 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) && 717 !(BTRFS_I(inode)->prop_compress)) { 718 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; 719 } 720 } 721 cleanup_and_bail_uncompressed: 722 /* 723 * No compression, but we still need to write the pages in the file 724 * we've been given so far. redirty the locked page if it corresponds 725 * to our extent and set things up for the async work queue to run 726 * cow_file_range to do the normal delalloc dance. 727 */ 728 if (async_chunk->locked_page && 729 (page_offset(async_chunk->locked_page) >= start && 730 page_offset(async_chunk->locked_page)) <= end) { 731 __set_page_dirty_nobuffers(async_chunk->locked_page); 732 /* unlocked later on in the async handlers */ 733 } 734 735 if (redirty) 736 extent_range_redirty_for_io(inode, start, end); 737 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0, 738 BTRFS_COMPRESS_NONE); 739 compressed_extents++; 740 741 return compressed_extents; 742 } 743 744 static void free_async_extent_pages(struct async_extent *async_extent) 745 { 746 int i; 747 748 if (!async_extent->pages) 749 return; 750 751 for (i = 0; i < async_extent->nr_pages; i++) { 752 WARN_ON(async_extent->pages[i]->mapping); 753 put_page(async_extent->pages[i]); 754 } 755 kfree(async_extent->pages); 756 async_extent->nr_pages = 0; 757 async_extent->pages = NULL; 758 } 759 760 /* 761 * phase two of compressed writeback. This is the ordered portion 762 * of the code, which only gets called in the order the work was 763 * queued. We walk all the async extents created by compress_file_range 764 * and send them down to the disk. 765 */ 766 static noinline void submit_compressed_extents(struct async_chunk *async_chunk) 767 { 768 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode); 769 struct btrfs_fs_info *fs_info = inode->root->fs_info; 770 struct async_extent *async_extent; 771 u64 alloc_hint = 0; 772 struct btrfs_key ins; 773 struct extent_map *em; 774 struct btrfs_root *root = inode->root; 775 struct extent_io_tree *io_tree = &inode->io_tree; 776 int ret = 0; 777 778 again: 779 while (!list_empty(&async_chunk->extents)) { 780 async_extent = list_entry(async_chunk->extents.next, 781 struct async_extent, list); 782 list_del(&async_extent->list); 783 784 retry: 785 lock_extent(io_tree, async_extent->start, 786 async_extent->start + async_extent->ram_size - 1); 787 /* did the compression code fall back to uncompressed IO? */ 788 if (!async_extent->pages) { 789 int page_started = 0; 790 unsigned long nr_written = 0; 791 792 /* allocate blocks */ 793 ret = cow_file_range(inode, async_chunk->locked_page, 794 async_extent->start, 795 async_extent->start + 796 async_extent->ram_size - 1, 797 &page_started, &nr_written, 0); 798 799 /* JDM XXX */ 800 801 /* 802 * if page_started, cow_file_range inserted an 803 * inline extent and took care of all the unlocking 804 * and IO for us. Otherwise, we need to submit 805 * all those pages down to the drive. 806 */ 807 if (!page_started && !ret) 808 extent_write_locked_range(&inode->vfs_inode, 809 async_extent->start, 810 async_extent->start + 811 async_extent->ram_size - 1, 812 WB_SYNC_ALL); 813 else if (ret && async_chunk->locked_page) 814 unlock_page(async_chunk->locked_page); 815 kfree(async_extent); 816 cond_resched(); 817 continue; 818 } 819 820 ret = btrfs_reserve_extent(root, async_extent->ram_size, 821 async_extent->compressed_size, 822 async_extent->compressed_size, 823 0, alloc_hint, &ins, 1, 1); 824 if (ret) { 825 free_async_extent_pages(async_extent); 826 827 if (ret == -ENOSPC) { 828 unlock_extent(io_tree, async_extent->start, 829 async_extent->start + 830 async_extent->ram_size - 1); 831 832 /* 833 * we need to redirty the pages if we decide to 834 * fallback to uncompressed IO, otherwise we 835 * will not submit these pages down to lower 836 * layers. 837 */ 838 extent_range_redirty_for_io(&inode->vfs_inode, 839 async_extent->start, 840 async_extent->start + 841 async_extent->ram_size - 1); 842 843 goto retry; 844 } 845 goto out_free; 846 } 847 /* 848 * here we're doing allocation and writeback of the 849 * compressed pages 850 */ 851 em = create_io_em(inode, async_extent->start, 852 async_extent->ram_size, /* len */ 853 async_extent->start, /* orig_start */ 854 ins.objectid, /* block_start */ 855 ins.offset, /* block_len */ 856 ins.offset, /* orig_block_len */ 857 async_extent->ram_size, /* ram_bytes */ 858 async_extent->compress_type, 859 BTRFS_ORDERED_COMPRESSED); 860 if (IS_ERR(em)) 861 /* ret value is not necessary due to void function */ 862 goto out_free_reserve; 863 free_extent_map(em); 864 865 ret = btrfs_add_ordered_extent_compress(inode, 866 async_extent->start, 867 ins.objectid, 868 async_extent->ram_size, 869 ins.offset, 870 BTRFS_ORDERED_COMPRESSED, 871 async_extent->compress_type); 872 if (ret) { 873 btrfs_drop_extent_cache(inode, async_extent->start, 874 async_extent->start + 875 async_extent->ram_size - 1, 0); 876 goto out_free_reserve; 877 } 878 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 879 880 /* 881 * clear dirty, set writeback and unlock the pages. 882 */ 883 extent_clear_unlock_delalloc(inode, async_extent->start, 884 async_extent->start + 885 async_extent->ram_size - 1, 886 NULL, EXTENT_LOCKED | EXTENT_DELALLOC, 887 PAGE_UNLOCK | PAGE_CLEAR_DIRTY | 888 PAGE_SET_WRITEBACK); 889 if (btrfs_submit_compressed_write(inode, async_extent->start, 890 async_extent->ram_size, 891 ins.objectid, 892 ins.offset, async_extent->pages, 893 async_extent->nr_pages, 894 async_chunk->write_flags, 895 async_chunk->blkcg_css)) { 896 struct page *p = async_extent->pages[0]; 897 const u64 start = async_extent->start; 898 const u64 end = start + async_extent->ram_size - 1; 899 900 p->mapping = inode->vfs_inode.i_mapping; 901 btrfs_writepage_endio_finish_ordered(p, start, end, 0); 902 903 p->mapping = NULL; 904 extent_clear_unlock_delalloc(inode, start, end, NULL, 0, 905 PAGE_END_WRITEBACK | 906 PAGE_SET_ERROR); 907 free_async_extent_pages(async_extent); 908 } 909 alloc_hint = ins.objectid + ins.offset; 910 kfree(async_extent); 911 cond_resched(); 912 } 913 return; 914 out_free_reserve: 915 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 916 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1); 917 out_free: 918 extent_clear_unlock_delalloc(inode, async_extent->start, 919 async_extent->start + 920 async_extent->ram_size - 1, 921 NULL, EXTENT_LOCKED | EXTENT_DELALLOC | 922 EXTENT_DELALLOC_NEW | 923 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING, 924 PAGE_UNLOCK | PAGE_CLEAR_DIRTY | 925 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK | 926 PAGE_SET_ERROR); 927 free_async_extent_pages(async_extent); 928 kfree(async_extent); 929 goto again; 930 } 931 932 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start, 933 u64 num_bytes) 934 { 935 struct extent_map_tree *em_tree = &inode->extent_tree; 936 struct extent_map *em; 937 u64 alloc_hint = 0; 938 939 read_lock(&em_tree->lock); 940 em = search_extent_mapping(em_tree, start, num_bytes); 941 if (em) { 942 /* 943 * if block start isn't an actual block number then find the 944 * first block in this inode and use that as a hint. If that 945 * block is also bogus then just don't worry about it. 946 */ 947 if (em->block_start >= EXTENT_MAP_LAST_BYTE) { 948 free_extent_map(em); 949 em = search_extent_mapping(em_tree, 0, 0); 950 if (em && em->block_start < EXTENT_MAP_LAST_BYTE) 951 alloc_hint = em->block_start; 952 if (em) 953 free_extent_map(em); 954 } else { 955 alloc_hint = em->block_start; 956 free_extent_map(em); 957 } 958 } 959 read_unlock(&em_tree->lock); 960 961 return alloc_hint; 962 } 963 964 /* 965 * when extent_io.c finds a delayed allocation range in the file, 966 * the call backs end up in this code. The basic idea is to 967 * allocate extents on disk for the range, and create ordered data structs 968 * in ram to track those extents. 969 * 970 * locked_page is the page that writepage had locked already. We use 971 * it to make sure we don't do extra locks or unlocks. 972 * 973 * *page_started is set to one if we unlock locked_page and do everything 974 * required to start IO on it. It may be clean and already done with 975 * IO when we return. 976 */ 977 static noinline int cow_file_range(struct btrfs_inode *inode, 978 struct page *locked_page, 979 u64 start, u64 end, int *page_started, 980 unsigned long *nr_written, int unlock) 981 { 982 struct btrfs_root *root = inode->root; 983 struct btrfs_fs_info *fs_info = root->fs_info; 984 u64 alloc_hint = 0; 985 u64 num_bytes; 986 unsigned long ram_size; 987 u64 cur_alloc_size = 0; 988 u64 min_alloc_size; 989 u64 blocksize = fs_info->sectorsize; 990 struct btrfs_key ins; 991 struct extent_map *em; 992 unsigned clear_bits; 993 unsigned long page_ops; 994 bool extent_reserved = false; 995 int ret = 0; 996 997 if (btrfs_is_free_space_inode(inode)) { 998 WARN_ON_ONCE(1); 999 ret = -EINVAL; 1000 goto out_unlock; 1001 } 1002 1003 num_bytes = ALIGN(end - start + 1, blocksize); 1004 num_bytes = max(blocksize, num_bytes); 1005 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy)); 1006 1007 inode_should_defrag(inode, start, end, num_bytes, SZ_64K); 1008 1009 if (start == 0) { 1010 /* lets try to make an inline extent */ 1011 ret = cow_file_range_inline(inode, start, end, 0, 1012 BTRFS_COMPRESS_NONE, NULL); 1013 if (ret == 0) { 1014 /* 1015 * We use DO_ACCOUNTING here because we need the 1016 * delalloc_release_metadata to be run _after_ we drop 1017 * our outstanding extent for clearing delalloc for this 1018 * range. 1019 */ 1020 extent_clear_unlock_delalloc(inode, start, end, NULL, 1021 EXTENT_LOCKED | EXTENT_DELALLOC | 1022 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | 1023 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK | 1024 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | 1025 PAGE_END_WRITEBACK); 1026 *nr_written = *nr_written + 1027 (end - start + PAGE_SIZE) / PAGE_SIZE; 1028 *page_started = 1; 1029 goto out; 1030 } else if (ret < 0) { 1031 goto out_unlock; 1032 } 1033 } 1034 1035 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes); 1036 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0); 1037 1038 /* 1039 * Relocation relies on the relocated extents to have exactly the same 1040 * size as the original extents. Normally writeback for relocation data 1041 * extents follows a NOCOW path because relocation preallocates the 1042 * extents. However, due to an operation such as scrub turning a block 1043 * group to RO mode, it may fallback to COW mode, so we must make sure 1044 * an extent allocated during COW has exactly the requested size and can 1045 * not be split into smaller extents, otherwise relocation breaks and 1046 * fails during the stage where it updates the bytenr of file extent 1047 * items. 1048 */ 1049 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) 1050 min_alloc_size = num_bytes; 1051 else 1052 min_alloc_size = fs_info->sectorsize; 1053 1054 while (num_bytes > 0) { 1055 cur_alloc_size = num_bytes; 1056 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size, 1057 min_alloc_size, 0, alloc_hint, 1058 &ins, 1, 1); 1059 if (ret < 0) 1060 goto out_unlock; 1061 cur_alloc_size = ins.offset; 1062 extent_reserved = true; 1063 1064 ram_size = ins.offset; 1065 em = create_io_em(inode, start, ins.offset, /* len */ 1066 start, /* orig_start */ 1067 ins.objectid, /* block_start */ 1068 ins.offset, /* block_len */ 1069 ins.offset, /* orig_block_len */ 1070 ram_size, /* ram_bytes */ 1071 BTRFS_COMPRESS_NONE, /* compress_type */ 1072 BTRFS_ORDERED_REGULAR /* type */); 1073 if (IS_ERR(em)) { 1074 ret = PTR_ERR(em); 1075 goto out_reserve; 1076 } 1077 free_extent_map(em); 1078 1079 ret = btrfs_add_ordered_extent(inode, start, ins.objectid, 1080 ram_size, cur_alloc_size, 0); 1081 if (ret) 1082 goto out_drop_extent_cache; 1083 1084 if (root->root_key.objectid == 1085 BTRFS_DATA_RELOC_TREE_OBJECTID) { 1086 ret = btrfs_reloc_clone_csums(inode, start, 1087 cur_alloc_size); 1088 /* 1089 * Only drop cache here, and process as normal. 1090 * 1091 * We must not allow extent_clear_unlock_delalloc() 1092 * at out_unlock label to free meta of this ordered 1093 * extent, as its meta should be freed by 1094 * btrfs_finish_ordered_io(). 1095 * 1096 * So we must continue until @start is increased to 1097 * skip current ordered extent. 1098 */ 1099 if (ret) 1100 btrfs_drop_extent_cache(inode, start, 1101 start + ram_size - 1, 0); 1102 } 1103 1104 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 1105 1106 /* we're not doing compressed IO, don't unlock the first 1107 * page (which the caller expects to stay locked), don't 1108 * clear any dirty bits and don't set any writeback bits 1109 * 1110 * Do set the Private2 bit so we know this page was properly 1111 * setup for writepage 1112 */ 1113 page_ops = unlock ? PAGE_UNLOCK : 0; 1114 page_ops |= PAGE_SET_PRIVATE2; 1115 1116 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1, 1117 locked_page, 1118 EXTENT_LOCKED | EXTENT_DELALLOC, 1119 page_ops); 1120 if (num_bytes < cur_alloc_size) 1121 num_bytes = 0; 1122 else 1123 num_bytes -= cur_alloc_size; 1124 alloc_hint = ins.objectid + ins.offset; 1125 start += cur_alloc_size; 1126 extent_reserved = false; 1127 1128 /* 1129 * btrfs_reloc_clone_csums() error, since start is increased 1130 * extent_clear_unlock_delalloc() at out_unlock label won't 1131 * free metadata of current ordered extent, we're OK to exit. 1132 */ 1133 if (ret) 1134 goto out_unlock; 1135 } 1136 out: 1137 return ret; 1138 1139 out_drop_extent_cache: 1140 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0); 1141 out_reserve: 1142 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 1143 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1); 1144 out_unlock: 1145 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW | 1146 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV; 1147 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | 1148 PAGE_END_WRITEBACK; 1149 /* 1150 * If we reserved an extent for our delalloc range (or a subrange) and 1151 * failed to create the respective ordered extent, then it means that 1152 * when we reserved the extent we decremented the extent's size from 1153 * the data space_info's bytes_may_use counter and incremented the 1154 * space_info's bytes_reserved counter by the same amount. We must make 1155 * sure extent_clear_unlock_delalloc() does not try to decrement again 1156 * the data space_info's bytes_may_use counter, therefore we do not pass 1157 * it the flag EXTENT_CLEAR_DATA_RESV. 1158 */ 1159 if (extent_reserved) { 1160 extent_clear_unlock_delalloc(inode, start, 1161 start + cur_alloc_size - 1, 1162 locked_page, 1163 clear_bits, 1164 page_ops); 1165 start += cur_alloc_size; 1166 if (start >= end) 1167 goto out; 1168 } 1169 extent_clear_unlock_delalloc(inode, start, end, locked_page, 1170 clear_bits | EXTENT_CLEAR_DATA_RESV, 1171 page_ops); 1172 goto out; 1173 } 1174 1175 /* 1176 * work queue call back to started compression on a file and pages 1177 */ 1178 static noinline void async_cow_start(struct btrfs_work *work) 1179 { 1180 struct async_chunk *async_chunk; 1181 int compressed_extents; 1182 1183 async_chunk = container_of(work, struct async_chunk, work); 1184 1185 compressed_extents = compress_file_range(async_chunk); 1186 if (compressed_extents == 0) { 1187 btrfs_add_delayed_iput(async_chunk->inode); 1188 async_chunk->inode = NULL; 1189 } 1190 } 1191 1192 /* 1193 * work queue call back to submit previously compressed pages 1194 */ 1195 static noinline void async_cow_submit(struct btrfs_work *work) 1196 { 1197 struct async_chunk *async_chunk = container_of(work, struct async_chunk, 1198 work); 1199 struct btrfs_fs_info *fs_info = btrfs_work_owner(work); 1200 unsigned long nr_pages; 1201 1202 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >> 1203 PAGE_SHIFT; 1204 1205 /* atomic_sub_return implies a barrier */ 1206 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) < 1207 5 * SZ_1M) 1208 cond_wake_up_nomb(&fs_info->async_submit_wait); 1209 1210 /* 1211 * ->inode could be NULL if async_chunk_start has failed to compress, 1212 * in which case we don't have anything to submit, yet we need to 1213 * always adjust ->async_delalloc_pages as its paired with the init 1214 * happening in cow_file_range_async 1215 */ 1216 if (async_chunk->inode) 1217 submit_compressed_extents(async_chunk); 1218 } 1219 1220 static noinline void async_cow_free(struct btrfs_work *work) 1221 { 1222 struct async_chunk *async_chunk; 1223 1224 async_chunk = container_of(work, struct async_chunk, work); 1225 if (async_chunk->inode) 1226 btrfs_add_delayed_iput(async_chunk->inode); 1227 if (async_chunk->blkcg_css) 1228 css_put(async_chunk->blkcg_css); 1229 /* 1230 * Since the pointer to 'pending' is at the beginning of the array of 1231 * async_chunk's, freeing it ensures the whole array has been freed. 1232 */ 1233 if (atomic_dec_and_test(async_chunk->pending)) 1234 kvfree(async_chunk->pending); 1235 } 1236 1237 static int cow_file_range_async(struct btrfs_inode *inode, 1238 struct writeback_control *wbc, 1239 struct page *locked_page, 1240 u64 start, u64 end, int *page_started, 1241 unsigned long *nr_written) 1242 { 1243 struct btrfs_fs_info *fs_info = inode->root->fs_info; 1244 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc); 1245 struct async_cow *ctx; 1246 struct async_chunk *async_chunk; 1247 unsigned long nr_pages; 1248 u64 cur_end; 1249 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K); 1250 int i; 1251 bool should_compress; 1252 unsigned nofs_flag; 1253 const unsigned int write_flags = wbc_to_write_flags(wbc); 1254 1255 unlock_extent(&inode->io_tree, start, end); 1256 1257 if (inode->flags & BTRFS_INODE_NOCOMPRESS && 1258 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) { 1259 num_chunks = 1; 1260 should_compress = false; 1261 } else { 1262 should_compress = true; 1263 } 1264 1265 nofs_flag = memalloc_nofs_save(); 1266 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL); 1267 memalloc_nofs_restore(nofs_flag); 1268 1269 if (!ctx) { 1270 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | 1271 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | 1272 EXTENT_DO_ACCOUNTING; 1273 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | 1274 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK | 1275 PAGE_SET_ERROR; 1276 1277 extent_clear_unlock_delalloc(inode, start, end, locked_page, 1278 clear_bits, page_ops); 1279 return -ENOMEM; 1280 } 1281 1282 async_chunk = ctx->chunks; 1283 atomic_set(&ctx->num_chunks, num_chunks); 1284 1285 for (i = 0; i < num_chunks; i++) { 1286 if (should_compress) 1287 cur_end = min(end, start + SZ_512K - 1); 1288 else 1289 cur_end = end; 1290 1291 /* 1292 * igrab is called higher up in the call chain, take only the 1293 * lightweight reference for the callback lifetime 1294 */ 1295 ihold(&inode->vfs_inode); 1296 async_chunk[i].pending = &ctx->num_chunks; 1297 async_chunk[i].inode = &inode->vfs_inode; 1298 async_chunk[i].start = start; 1299 async_chunk[i].end = cur_end; 1300 async_chunk[i].write_flags = write_flags; 1301 INIT_LIST_HEAD(&async_chunk[i].extents); 1302 1303 /* 1304 * The locked_page comes all the way from writepage and its 1305 * the original page we were actually given. As we spread 1306 * this large delalloc region across multiple async_chunk 1307 * structs, only the first struct needs a pointer to locked_page 1308 * 1309 * This way we don't need racey decisions about who is supposed 1310 * to unlock it. 1311 */ 1312 if (locked_page) { 1313 /* 1314 * Depending on the compressibility, the pages might or 1315 * might not go through async. We want all of them to 1316 * be accounted against wbc once. Let's do it here 1317 * before the paths diverge. wbc accounting is used 1318 * only for foreign writeback detection and doesn't 1319 * need full accuracy. Just account the whole thing 1320 * against the first page. 1321 */ 1322 wbc_account_cgroup_owner(wbc, locked_page, 1323 cur_end - start); 1324 async_chunk[i].locked_page = locked_page; 1325 locked_page = NULL; 1326 } else { 1327 async_chunk[i].locked_page = NULL; 1328 } 1329 1330 if (blkcg_css != blkcg_root_css) { 1331 css_get(blkcg_css); 1332 async_chunk[i].blkcg_css = blkcg_css; 1333 } else { 1334 async_chunk[i].blkcg_css = NULL; 1335 } 1336 1337 btrfs_init_work(&async_chunk[i].work, async_cow_start, 1338 async_cow_submit, async_cow_free); 1339 1340 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE); 1341 atomic_add(nr_pages, &fs_info->async_delalloc_pages); 1342 1343 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work); 1344 1345 *nr_written += nr_pages; 1346 start = cur_end + 1; 1347 } 1348 *page_started = 1; 1349 return 0; 1350 } 1351 1352 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info, 1353 u64 bytenr, u64 num_bytes) 1354 { 1355 int ret; 1356 struct btrfs_ordered_sum *sums; 1357 LIST_HEAD(list); 1358 1359 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr, 1360 bytenr + num_bytes - 1, &list, 0); 1361 if (ret == 0 && list_empty(&list)) 1362 return 0; 1363 1364 while (!list_empty(&list)) { 1365 sums = list_entry(list.next, struct btrfs_ordered_sum, list); 1366 list_del(&sums->list); 1367 kfree(sums); 1368 } 1369 if (ret < 0) 1370 return ret; 1371 return 1; 1372 } 1373 1374 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page, 1375 const u64 start, const u64 end, 1376 int *page_started, unsigned long *nr_written) 1377 { 1378 const bool is_space_ino = btrfs_is_free_space_inode(inode); 1379 const bool is_reloc_ino = (inode->root->root_key.objectid == 1380 BTRFS_DATA_RELOC_TREE_OBJECTID); 1381 const u64 range_bytes = end + 1 - start; 1382 struct extent_io_tree *io_tree = &inode->io_tree; 1383 u64 range_start = start; 1384 u64 count; 1385 1386 /* 1387 * If EXTENT_NORESERVE is set it means that when the buffered write was 1388 * made we had not enough available data space and therefore we did not 1389 * reserve data space for it, since we though we could do NOCOW for the 1390 * respective file range (either there is prealloc extent or the inode 1391 * has the NOCOW bit set). 1392 * 1393 * However when we need to fallback to COW mode (because for example the 1394 * block group for the corresponding extent was turned to RO mode by a 1395 * scrub or relocation) we need to do the following: 1396 * 1397 * 1) We increment the bytes_may_use counter of the data space info. 1398 * If COW succeeds, it allocates a new data extent and after doing 1399 * that it decrements the space info's bytes_may_use counter and 1400 * increments its bytes_reserved counter by the same amount (we do 1401 * this at btrfs_add_reserved_bytes()). So we need to increment the 1402 * bytes_may_use counter to compensate (when space is reserved at 1403 * buffered write time, the bytes_may_use counter is incremented); 1404 * 1405 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so 1406 * that if the COW path fails for any reason, it decrements (through 1407 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the 1408 * data space info, which we incremented in the step above. 1409 * 1410 * If we need to fallback to cow and the inode corresponds to a free 1411 * space cache inode or an inode of the data relocation tree, we must 1412 * also increment bytes_may_use of the data space_info for the same 1413 * reason. Space caches and relocated data extents always get a prealloc 1414 * extent for them, however scrub or balance may have set the block 1415 * group that contains that extent to RO mode and therefore force COW 1416 * when starting writeback. 1417 */ 1418 count = count_range_bits(io_tree, &range_start, end, range_bytes, 1419 EXTENT_NORESERVE, 0); 1420 if (count > 0 || is_space_ino || is_reloc_ino) { 1421 u64 bytes = count; 1422 struct btrfs_fs_info *fs_info = inode->root->fs_info; 1423 struct btrfs_space_info *sinfo = fs_info->data_sinfo; 1424 1425 if (is_space_ino || is_reloc_ino) 1426 bytes = range_bytes; 1427 1428 spin_lock(&sinfo->lock); 1429 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes); 1430 spin_unlock(&sinfo->lock); 1431 1432 if (count > 0) 1433 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE, 1434 0, 0, NULL); 1435 } 1436 1437 return cow_file_range(inode, locked_page, start, end, page_started, 1438 nr_written, 1); 1439 } 1440 1441 /* 1442 * when nowcow writeback call back. This checks for snapshots or COW copies 1443 * of the extents that exist in the file, and COWs the file as required. 1444 * 1445 * If no cow copies or snapshots exist, we write directly to the existing 1446 * blocks on disk 1447 */ 1448 static noinline int run_delalloc_nocow(struct btrfs_inode *inode, 1449 struct page *locked_page, 1450 const u64 start, const u64 end, 1451 int *page_started, int force, 1452 unsigned long *nr_written) 1453 { 1454 struct btrfs_fs_info *fs_info = inode->root->fs_info; 1455 struct btrfs_root *root = inode->root; 1456 struct btrfs_path *path; 1457 u64 cow_start = (u64)-1; 1458 u64 cur_offset = start; 1459 int ret; 1460 bool check_prev = true; 1461 const bool freespace_inode = btrfs_is_free_space_inode(inode); 1462 u64 ino = btrfs_ino(inode); 1463 bool nocow = false; 1464 u64 disk_bytenr = 0; 1465 1466 path = btrfs_alloc_path(); 1467 if (!path) { 1468 extent_clear_unlock_delalloc(inode, start, end, locked_page, 1469 EXTENT_LOCKED | EXTENT_DELALLOC | 1470 EXTENT_DO_ACCOUNTING | 1471 EXTENT_DEFRAG, PAGE_UNLOCK | 1472 PAGE_CLEAR_DIRTY | 1473 PAGE_SET_WRITEBACK | 1474 PAGE_END_WRITEBACK); 1475 return -ENOMEM; 1476 } 1477 1478 while (1) { 1479 struct btrfs_key found_key; 1480 struct btrfs_file_extent_item *fi; 1481 struct extent_buffer *leaf; 1482 u64 extent_end; 1483 u64 extent_offset; 1484 u64 num_bytes = 0; 1485 u64 disk_num_bytes; 1486 u64 ram_bytes; 1487 int extent_type; 1488 1489 nocow = false; 1490 1491 ret = btrfs_lookup_file_extent(NULL, root, path, ino, 1492 cur_offset, 0); 1493 if (ret < 0) 1494 goto error; 1495 1496 /* 1497 * If there is no extent for our range when doing the initial 1498 * search, then go back to the previous slot as it will be the 1499 * one containing the search offset 1500 */ 1501 if (ret > 0 && path->slots[0] > 0 && check_prev) { 1502 leaf = path->nodes[0]; 1503 btrfs_item_key_to_cpu(leaf, &found_key, 1504 path->slots[0] - 1); 1505 if (found_key.objectid == ino && 1506 found_key.type == BTRFS_EXTENT_DATA_KEY) 1507 path->slots[0]--; 1508 } 1509 check_prev = false; 1510 next_slot: 1511 /* Go to next leaf if we have exhausted the current one */ 1512 leaf = path->nodes[0]; 1513 if (path->slots[0] >= btrfs_header_nritems(leaf)) { 1514 ret = btrfs_next_leaf(root, path); 1515 if (ret < 0) { 1516 if (cow_start != (u64)-1) 1517 cur_offset = cow_start; 1518 goto error; 1519 } 1520 if (ret > 0) 1521 break; 1522 leaf = path->nodes[0]; 1523 } 1524 1525 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 1526 1527 /* Didn't find anything for our INO */ 1528 if (found_key.objectid > ino) 1529 break; 1530 /* 1531 * Keep searching until we find an EXTENT_ITEM or there are no 1532 * more extents for this inode 1533 */ 1534 if (WARN_ON_ONCE(found_key.objectid < ino) || 1535 found_key.type < BTRFS_EXTENT_DATA_KEY) { 1536 path->slots[0]++; 1537 goto next_slot; 1538 } 1539 1540 /* Found key is not EXTENT_DATA_KEY or starts after req range */ 1541 if (found_key.type > BTRFS_EXTENT_DATA_KEY || 1542 found_key.offset > end) 1543 break; 1544 1545 /* 1546 * If the found extent starts after requested offset, then 1547 * adjust extent_end to be right before this extent begins 1548 */ 1549 if (found_key.offset > cur_offset) { 1550 extent_end = found_key.offset; 1551 extent_type = 0; 1552 goto out_check; 1553 } 1554 1555 /* 1556 * Found extent which begins before our range and potentially 1557 * intersect it 1558 */ 1559 fi = btrfs_item_ptr(leaf, path->slots[0], 1560 struct btrfs_file_extent_item); 1561 extent_type = btrfs_file_extent_type(leaf, fi); 1562 1563 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi); 1564 if (extent_type == BTRFS_FILE_EXTENT_REG || 1565 extent_type == BTRFS_FILE_EXTENT_PREALLOC) { 1566 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); 1567 extent_offset = btrfs_file_extent_offset(leaf, fi); 1568 extent_end = found_key.offset + 1569 btrfs_file_extent_num_bytes(leaf, fi); 1570 disk_num_bytes = 1571 btrfs_file_extent_disk_num_bytes(leaf, fi); 1572 /* 1573 * If the extent we got ends before our current offset, 1574 * skip to the next extent. 1575 */ 1576 if (extent_end <= cur_offset) { 1577 path->slots[0]++; 1578 goto next_slot; 1579 } 1580 /* Skip holes */ 1581 if (disk_bytenr == 0) 1582 goto out_check; 1583 /* Skip compressed/encrypted/encoded extents */ 1584 if (btrfs_file_extent_compression(leaf, fi) || 1585 btrfs_file_extent_encryption(leaf, fi) || 1586 btrfs_file_extent_other_encoding(leaf, fi)) 1587 goto out_check; 1588 /* 1589 * If extent is created before the last volume's snapshot 1590 * this implies the extent is shared, hence we can't do 1591 * nocow. This is the same check as in 1592 * btrfs_cross_ref_exist but without calling 1593 * btrfs_search_slot. 1594 */ 1595 if (!freespace_inode && 1596 btrfs_file_extent_generation(leaf, fi) <= 1597 btrfs_root_last_snapshot(&root->root_item)) 1598 goto out_check; 1599 if (extent_type == BTRFS_FILE_EXTENT_REG && !force) 1600 goto out_check; 1601 /* If extent is RO, we must COW it */ 1602 if (btrfs_extent_readonly(fs_info, disk_bytenr)) 1603 goto out_check; 1604 ret = btrfs_cross_ref_exist(root, ino, 1605 found_key.offset - 1606 extent_offset, disk_bytenr); 1607 if (ret) { 1608 /* 1609 * ret could be -EIO if the above fails to read 1610 * metadata. 1611 */ 1612 if (ret < 0) { 1613 if (cow_start != (u64)-1) 1614 cur_offset = cow_start; 1615 goto error; 1616 } 1617 1618 WARN_ON_ONCE(freespace_inode); 1619 goto out_check; 1620 } 1621 disk_bytenr += extent_offset; 1622 disk_bytenr += cur_offset - found_key.offset; 1623 num_bytes = min(end + 1, extent_end) - cur_offset; 1624 /* 1625 * If there are pending snapshots for this root, we 1626 * fall into common COW way 1627 */ 1628 if (!freespace_inode && atomic_read(&root->snapshot_force_cow)) 1629 goto out_check; 1630 /* 1631 * force cow if csum exists in the range. 1632 * this ensure that csum for a given extent are 1633 * either valid or do not exist. 1634 */ 1635 ret = csum_exist_in_range(fs_info, disk_bytenr, 1636 num_bytes); 1637 if (ret) { 1638 /* 1639 * ret could be -EIO if the above fails to read 1640 * metadata. 1641 */ 1642 if (ret < 0) { 1643 if (cow_start != (u64)-1) 1644 cur_offset = cow_start; 1645 goto error; 1646 } 1647 WARN_ON_ONCE(freespace_inode); 1648 goto out_check; 1649 } 1650 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) 1651 goto out_check; 1652 nocow = true; 1653 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 1654 extent_end = found_key.offset + ram_bytes; 1655 extent_end = ALIGN(extent_end, fs_info->sectorsize); 1656 /* Skip extents outside of our requested range */ 1657 if (extent_end <= start) { 1658 path->slots[0]++; 1659 goto next_slot; 1660 } 1661 } else { 1662 /* If this triggers then we have a memory corruption */ 1663 BUG(); 1664 } 1665 out_check: 1666 /* 1667 * If nocow is false then record the beginning of the range 1668 * that needs to be COWed 1669 */ 1670 if (!nocow) { 1671 if (cow_start == (u64)-1) 1672 cow_start = cur_offset; 1673 cur_offset = extent_end; 1674 if (cur_offset > end) 1675 break; 1676 path->slots[0]++; 1677 goto next_slot; 1678 } 1679 1680 btrfs_release_path(path); 1681 1682 /* 1683 * COW range from cow_start to found_key.offset - 1. As the key 1684 * will contain the beginning of the first extent that can be 1685 * NOCOW, following one which needs to be COW'ed 1686 */ 1687 if (cow_start != (u64)-1) { 1688 ret = fallback_to_cow(inode, locked_page, 1689 cow_start, found_key.offset - 1, 1690 page_started, nr_written); 1691 if (ret) 1692 goto error; 1693 cow_start = (u64)-1; 1694 } 1695 1696 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) { 1697 u64 orig_start = found_key.offset - extent_offset; 1698 struct extent_map *em; 1699 1700 em = create_io_em(inode, cur_offset, num_bytes, 1701 orig_start, 1702 disk_bytenr, /* block_start */ 1703 num_bytes, /* block_len */ 1704 disk_num_bytes, /* orig_block_len */ 1705 ram_bytes, BTRFS_COMPRESS_NONE, 1706 BTRFS_ORDERED_PREALLOC); 1707 if (IS_ERR(em)) { 1708 ret = PTR_ERR(em); 1709 goto error; 1710 } 1711 free_extent_map(em); 1712 ret = btrfs_add_ordered_extent(inode, cur_offset, 1713 disk_bytenr, num_bytes, 1714 num_bytes, 1715 BTRFS_ORDERED_PREALLOC); 1716 if (ret) { 1717 btrfs_drop_extent_cache(inode, cur_offset, 1718 cur_offset + num_bytes - 1, 1719 0); 1720 goto error; 1721 } 1722 } else { 1723 ret = btrfs_add_ordered_extent(inode, cur_offset, 1724 disk_bytenr, num_bytes, 1725 num_bytes, 1726 BTRFS_ORDERED_NOCOW); 1727 if (ret) 1728 goto error; 1729 } 1730 1731 if (nocow) 1732 btrfs_dec_nocow_writers(fs_info, disk_bytenr); 1733 nocow = false; 1734 1735 if (root->root_key.objectid == 1736 BTRFS_DATA_RELOC_TREE_OBJECTID) 1737 /* 1738 * Error handled later, as we must prevent 1739 * extent_clear_unlock_delalloc() in error handler 1740 * from freeing metadata of created ordered extent. 1741 */ 1742 ret = btrfs_reloc_clone_csums(inode, cur_offset, 1743 num_bytes); 1744 1745 extent_clear_unlock_delalloc(inode, cur_offset, 1746 cur_offset + num_bytes - 1, 1747 locked_page, EXTENT_LOCKED | 1748 EXTENT_DELALLOC | 1749 EXTENT_CLEAR_DATA_RESV, 1750 PAGE_UNLOCK | PAGE_SET_PRIVATE2); 1751 1752 cur_offset = extent_end; 1753 1754 /* 1755 * btrfs_reloc_clone_csums() error, now we're OK to call error 1756 * handler, as metadata for created ordered extent will only 1757 * be freed by btrfs_finish_ordered_io(). 1758 */ 1759 if (ret) 1760 goto error; 1761 if (cur_offset > end) 1762 break; 1763 } 1764 btrfs_release_path(path); 1765 1766 if (cur_offset <= end && cow_start == (u64)-1) 1767 cow_start = cur_offset; 1768 1769 if (cow_start != (u64)-1) { 1770 cur_offset = end; 1771 ret = fallback_to_cow(inode, locked_page, cow_start, end, 1772 page_started, nr_written); 1773 if (ret) 1774 goto error; 1775 } 1776 1777 error: 1778 if (nocow) 1779 btrfs_dec_nocow_writers(fs_info, disk_bytenr); 1780 1781 if (ret && cur_offset < end) 1782 extent_clear_unlock_delalloc(inode, cur_offset, end, 1783 locked_page, EXTENT_LOCKED | 1784 EXTENT_DELALLOC | EXTENT_DEFRAG | 1785 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK | 1786 PAGE_CLEAR_DIRTY | 1787 PAGE_SET_WRITEBACK | 1788 PAGE_END_WRITEBACK); 1789 btrfs_free_path(path); 1790 return ret; 1791 } 1792 1793 static inline int need_force_cow(struct btrfs_inode *inode, u64 start, u64 end) 1794 { 1795 1796 if (!(inode->flags & BTRFS_INODE_NODATACOW) && 1797 !(inode->flags & BTRFS_INODE_PREALLOC)) 1798 return 0; 1799 1800 /* 1801 * @defrag_bytes is a hint value, no spinlock held here, 1802 * if is not zero, it means the file is defragging. 1803 * Force cow if given extent needs to be defragged. 1804 */ 1805 if (inode->defrag_bytes && 1806 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG, 0, NULL)) 1807 return 1; 1808 1809 return 0; 1810 } 1811 1812 /* 1813 * Function to process delayed allocation (create CoW) for ranges which are 1814 * being touched for the first time. 1815 */ 1816 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page, 1817 u64 start, u64 end, int *page_started, unsigned long *nr_written, 1818 struct writeback_control *wbc) 1819 { 1820 int ret; 1821 int force_cow = need_force_cow(inode, start, end); 1822 1823 if (inode->flags & BTRFS_INODE_NODATACOW && !force_cow) { 1824 ret = run_delalloc_nocow(inode, locked_page, start, end, 1825 page_started, 1, nr_written); 1826 } else if (inode->flags & BTRFS_INODE_PREALLOC && !force_cow) { 1827 ret = run_delalloc_nocow(inode, locked_page, start, end, 1828 page_started, 0, nr_written); 1829 } else if (!inode_can_compress(inode) || 1830 !inode_need_compress(inode, start, end)) { 1831 ret = cow_file_range(inode, locked_page, start, end, 1832 page_started, nr_written, 1); 1833 } else { 1834 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags); 1835 ret = cow_file_range_async(inode, wbc, locked_page, start, end, 1836 page_started, nr_written); 1837 } 1838 if (ret) 1839 btrfs_cleanup_ordered_extents(inode, locked_page, start, 1840 end - start + 1); 1841 return ret; 1842 } 1843 1844 void btrfs_split_delalloc_extent(struct inode *inode, 1845 struct extent_state *orig, u64 split) 1846 { 1847 u64 size; 1848 1849 /* not delalloc, ignore it */ 1850 if (!(orig->state & EXTENT_DELALLOC)) 1851 return; 1852 1853 size = orig->end - orig->start + 1; 1854 if (size > BTRFS_MAX_EXTENT_SIZE) { 1855 u32 num_extents; 1856 u64 new_size; 1857 1858 /* 1859 * See the explanation in btrfs_merge_delalloc_extent, the same 1860 * applies here, just in reverse. 1861 */ 1862 new_size = orig->end - split + 1; 1863 num_extents = count_max_extents(new_size); 1864 new_size = split - orig->start; 1865 num_extents += count_max_extents(new_size); 1866 if (count_max_extents(size) >= num_extents) 1867 return; 1868 } 1869 1870 spin_lock(&BTRFS_I(inode)->lock); 1871 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1); 1872 spin_unlock(&BTRFS_I(inode)->lock); 1873 } 1874 1875 /* 1876 * Handle merged delayed allocation extents so we can keep track of new extents 1877 * that are just merged onto old extents, such as when we are doing sequential 1878 * writes, so we can properly account for the metadata space we'll need. 1879 */ 1880 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new, 1881 struct extent_state *other) 1882 { 1883 u64 new_size, old_size; 1884 u32 num_extents; 1885 1886 /* not delalloc, ignore it */ 1887 if (!(other->state & EXTENT_DELALLOC)) 1888 return; 1889 1890 if (new->start > other->start) 1891 new_size = new->end - other->start + 1; 1892 else 1893 new_size = other->end - new->start + 1; 1894 1895 /* we're not bigger than the max, unreserve the space and go */ 1896 if (new_size <= BTRFS_MAX_EXTENT_SIZE) { 1897 spin_lock(&BTRFS_I(inode)->lock); 1898 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1); 1899 spin_unlock(&BTRFS_I(inode)->lock); 1900 return; 1901 } 1902 1903 /* 1904 * We have to add up either side to figure out how many extents were 1905 * accounted for before we merged into one big extent. If the number of 1906 * extents we accounted for is <= the amount we need for the new range 1907 * then we can return, otherwise drop. Think of it like this 1908 * 1909 * [ 4k][MAX_SIZE] 1910 * 1911 * So we've grown the extent by a MAX_SIZE extent, this would mean we 1912 * need 2 outstanding extents, on one side we have 1 and the other side 1913 * we have 1 so they are == and we can return. But in this case 1914 * 1915 * [MAX_SIZE+4k][MAX_SIZE+4k] 1916 * 1917 * Each range on their own accounts for 2 extents, but merged together 1918 * they are only 3 extents worth of accounting, so we need to drop in 1919 * this case. 1920 */ 1921 old_size = other->end - other->start + 1; 1922 num_extents = count_max_extents(old_size); 1923 old_size = new->end - new->start + 1; 1924 num_extents += count_max_extents(old_size); 1925 if (count_max_extents(new_size) >= num_extents) 1926 return; 1927 1928 spin_lock(&BTRFS_I(inode)->lock); 1929 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1); 1930 spin_unlock(&BTRFS_I(inode)->lock); 1931 } 1932 1933 static void btrfs_add_delalloc_inodes(struct btrfs_root *root, 1934 struct inode *inode) 1935 { 1936 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 1937 1938 spin_lock(&root->delalloc_lock); 1939 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) { 1940 list_add_tail(&BTRFS_I(inode)->delalloc_inodes, 1941 &root->delalloc_inodes); 1942 set_bit(BTRFS_INODE_IN_DELALLOC_LIST, 1943 &BTRFS_I(inode)->runtime_flags); 1944 root->nr_delalloc_inodes++; 1945 if (root->nr_delalloc_inodes == 1) { 1946 spin_lock(&fs_info->delalloc_root_lock); 1947 BUG_ON(!list_empty(&root->delalloc_root)); 1948 list_add_tail(&root->delalloc_root, 1949 &fs_info->delalloc_roots); 1950 spin_unlock(&fs_info->delalloc_root_lock); 1951 } 1952 } 1953 spin_unlock(&root->delalloc_lock); 1954 } 1955 1956 1957 void __btrfs_del_delalloc_inode(struct btrfs_root *root, 1958 struct btrfs_inode *inode) 1959 { 1960 struct btrfs_fs_info *fs_info = root->fs_info; 1961 1962 if (!list_empty(&inode->delalloc_inodes)) { 1963 list_del_init(&inode->delalloc_inodes); 1964 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST, 1965 &inode->runtime_flags); 1966 root->nr_delalloc_inodes--; 1967 if (!root->nr_delalloc_inodes) { 1968 ASSERT(list_empty(&root->delalloc_inodes)); 1969 spin_lock(&fs_info->delalloc_root_lock); 1970 BUG_ON(list_empty(&root->delalloc_root)); 1971 list_del_init(&root->delalloc_root); 1972 spin_unlock(&fs_info->delalloc_root_lock); 1973 } 1974 } 1975 } 1976 1977 static void btrfs_del_delalloc_inode(struct btrfs_root *root, 1978 struct btrfs_inode *inode) 1979 { 1980 spin_lock(&root->delalloc_lock); 1981 __btrfs_del_delalloc_inode(root, inode); 1982 spin_unlock(&root->delalloc_lock); 1983 } 1984 1985 /* 1986 * Properly track delayed allocation bytes in the inode and to maintain the 1987 * list of inodes that have pending delalloc work to be done. 1988 */ 1989 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state, 1990 unsigned *bits) 1991 { 1992 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 1993 1994 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC)) 1995 WARN_ON(1); 1996 /* 1997 * set_bit and clear bit hooks normally require _irqsave/restore 1998 * but in this case, we are only testing for the DELALLOC 1999 * bit, which is only set or cleared with irqs on 2000 */ 2001 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { 2002 struct btrfs_root *root = BTRFS_I(inode)->root; 2003 u64 len = state->end + 1 - state->start; 2004 u32 num_extents = count_max_extents(len); 2005 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode)); 2006 2007 spin_lock(&BTRFS_I(inode)->lock); 2008 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents); 2009 spin_unlock(&BTRFS_I(inode)->lock); 2010 2011 /* For sanity tests */ 2012 if (btrfs_is_testing(fs_info)) 2013 return; 2014 2015 percpu_counter_add_batch(&fs_info->delalloc_bytes, len, 2016 fs_info->delalloc_batch); 2017 spin_lock(&BTRFS_I(inode)->lock); 2018 BTRFS_I(inode)->delalloc_bytes += len; 2019 if (*bits & EXTENT_DEFRAG) 2020 BTRFS_I(inode)->defrag_bytes += len; 2021 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST, 2022 &BTRFS_I(inode)->runtime_flags)) 2023 btrfs_add_delalloc_inodes(root, inode); 2024 spin_unlock(&BTRFS_I(inode)->lock); 2025 } 2026 2027 if (!(state->state & EXTENT_DELALLOC_NEW) && 2028 (*bits & EXTENT_DELALLOC_NEW)) { 2029 spin_lock(&BTRFS_I(inode)->lock); 2030 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 - 2031 state->start; 2032 spin_unlock(&BTRFS_I(inode)->lock); 2033 } 2034 } 2035 2036 /* 2037 * Once a range is no longer delalloc this function ensures that proper 2038 * accounting happens. 2039 */ 2040 void btrfs_clear_delalloc_extent(struct inode *vfs_inode, 2041 struct extent_state *state, unsigned *bits) 2042 { 2043 struct btrfs_inode *inode = BTRFS_I(vfs_inode); 2044 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb); 2045 u64 len = state->end + 1 - state->start; 2046 u32 num_extents = count_max_extents(len); 2047 2048 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) { 2049 spin_lock(&inode->lock); 2050 inode->defrag_bytes -= len; 2051 spin_unlock(&inode->lock); 2052 } 2053 2054 /* 2055 * set_bit and clear bit hooks normally require _irqsave/restore 2056 * but in this case, we are only testing for the DELALLOC 2057 * bit, which is only set or cleared with irqs on 2058 */ 2059 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { 2060 struct btrfs_root *root = inode->root; 2061 bool do_list = !btrfs_is_free_space_inode(inode); 2062 2063 spin_lock(&inode->lock); 2064 btrfs_mod_outstanding_extents(inode, -num_extents); 2065 spin_unlock(&inode->lock); 2066 2067 /* 2068 * We don't reserve metadata space for space cache inodes so we 2069 * don't need to call delalloc_release_metadata if there is an 2070 * error. 2071 */ 2072 if (*bits & EXTENT_CLEAR_META_RESV && 2073 root != fs_info->tree_root) 2074 btrfs_delalloc_release_metadata(inode, len, false); 2075 2076 /* For sanity tests. */ 2077 if (btrfs_is_testing(fs_info)) 2078 return; 2079 2080 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID && 2081 do_list && !(state->state & EXTENT_NORESERVE) && 2082 (*bits & EXTENT_CLEAR_DATA_RESV)) 2083 btrfs_free_reserved_data_space_noquota(fs_info, len); 2084 2085 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len, 2086 fs_info->delalloc_batch); 2087 spin_lock(&inode->lock); 2088 inode->delalloc_bytes -= len; 2089 if (do_list && inode->delalloc_bytes == 0 && 2090 test_bit(BTRFS_INODE_IN_DELALLOC_LIST, 2091 &inode->runtime_flags)) 2092 btrfs_del_delalloc_inode(root, inode); 2093 spin_unlock(&inode->lock); 2094 } 2095 2096 if ((state->state & EXTENT_DELALLOC_NEW) && 2097 (*bits & EXTENT_DELALLOC_NEW)) { 2098 spin_lock(&inode->lock); 2099 ASSERT(inode->new_delalloc_bytes >= len); 2100 inode->new_delalloc_bytes -= len; 2101 spin_unlock(&inode->lock); 2102 } 2103 } 2104 2105 /* 2106 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit 2107 * in a chunk's stripe. This function ensures that bios do not span a 2108 * stripe/chunk 2109 * 2110 * @page - The page we are about to add to the bio 2111 * @size - size we want to add to the bio 2112 * @bio - bio we want to ensure is smaller than a stripe 2113 * @bio_flags - flags of the bio 2114 * 2115 * return 1 if page cannot be added to the bio 2116 * return 0 if page can be added to the bio 2117 * return error otherwise 2118 */ 2119 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio, 2120 unsigned long bio_flags) 2121 { 2122 struct inode *inode = page->mapping->host; 2123 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2124 u64 logical = (u64)bio->bi_iter.bi_sector << 9; 2125 u64 length = 0; 2126 u64 map_length; 2127 int ret; 2128 struct btrfs_io_geometry geom; 2129 2130 if (bio_flags & EXTENT_BIO_COMPRESSED) 2131 return 0; 2132 2133 length = bio->bi_iter.bi_size; 2134 map_length = length; 2135 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length, 2136 &geom); 2137 if (ret < 0) 2138 return ret; 2139 2140 if (geom.len < length + size) 2141 return 1; 2142 return 0; 2143 } 2144 2145 /* 2146 * in order to insert checksums into the metadata in large chunks, 2147 * we wait until bio submission time. All the pages in the bio are 2148 * checksummed and sums are attached onto the ordered extent record. 2149 * 2150 * At IO completion time the cums attached on the ordered extent record 2151 * are inserted into the btree 2152 */ 2153 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio, 2154 u64 bio_offset) 2155 { 2156 struct inode *inode = private_data; 2157 blk_status_t ret = 0; 2158 2159 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0); 2160 BUG_ON(ret); /* -ENOMEM */ 2161 return 0; 2162 } 2163 2164 /* 2165 * extent_io.c submission hook. This does the right thing for csum calculation 2166 * on write, or reading the csums from the tree before a read. 2167 * 2168 * Rules about async/sync submit, 2169 * a) read: sync submit 2170 * 2171 * b) write without checksum: sync submit 2172 * 2173 * c) write with checksum: 2174 * c-1) if bio is issued by fsync: sync submit 2175 * (sync_writers != 0) 2176 * 2177 * c-2) if root is reloc root: sync submit 2178 * (only in case of buffered IO) 2179 * 2180 * c-3) otherwise: async submit 2181 */ 2182 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio, 2183 int mirror_num, 2184 unsigned long bio_flags) 2185 2186 { 2187 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2188 struct btrfs_root *root = BTRFS_I(inode)->root; 2189 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA; 2190 blk_status_t ret = 0; 2191 int skip_sum; 2192 int async = !atomic_read(&BTRFS_I(inode)->sync_writers); 2193 2194 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; 2195 2196 if (btrfs_is_free_space_inode(BTRFS_I(inode))) 2197 metadata = BTRFS_WQ_ENDIO_FREE_SPACE; 2198 2199 if (bio_op(bio) != REQ_OP_WRITE) { 2200 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata); 2201 if (ret) 2202 goto out; 2203 2204 if (bio_flags & EXTENT_BIO_COMPRESSED) { 2205 ret = btrfs_submit_compressed_read(inode, bio, 2206 mirror_num, 2207 bio_flags); 2208 goto out; 2209 } else if (!skip_sum) { 2210 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL); 2211 if (ret) 2212 goto out; 2213 } 2214 goto mapit; 2215 } else if (async && !skip_sum) { 2216 /* csum items have already been cloned */ 2217 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) 2218 goto mapit; 2219 /* we're doing a write, do the async checksumming */ 2220 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags, 2221 0, inode, btrfs_submit_bio_start); 2222 goto out; 2223 } else if (!skip_sum) { 2224 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0); 2225 if (ret) 2226 goto out; 2227 } 2228 2229 mapit: 2230 ret = btrfs_map_bio(fs_info, bio, mirror_num); 2231 2232 out: 2233 if (ret) { 2234 bio->bi_status = ret; 2235 bio_endio(bio); 2236 } 2237 return ret; 2238 } 2239 2240 /* 2241 * given a list of ordered sums record them in the inode. This happens 2242 * at IO completion time based on sums calculated at bio submission time. 2243 */ 2244 static noinline int add_pending_csums(struct btrfs_trans_handle *trans, 2245 struct inode *inode, struct list_head *list) 2246 { 2247 struct btrfs_ordered_sum *sum; 2248 int ret; 2249 2250 list_for_each_entry(sum, list, list) { 2251 trans->adding_csums = true; 2252 ret = btrfs_csum_file_blocks(trans, 2253 BTRFS_I(inode)->root->fs_info->csum_root, sum); 2254 trans->adding_csums = false; 2255 if (ret) 2256 return ret; 2257 } 2258 return 0; 2259 } 2260 2261 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end, 2262 unsigned int extra_bits, 2263 struct extent_state **cached_state) 2264 { 2265 WARN_ON(PAGE_ALIGNED(end)); 2266 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits, 2267 cached_state); 2268 } 2269 2270 /* see btrfs_writepage_start_hook for details on why this is required */ 2271 struct btrfs_writepage_fixup { 2272 struct page *page; 2273 struct inode *inode; 2274 struct btrfs_work work; 2275 }; 2276 2277 static void btrfs_writepage_fixup_worker(struct btrfs_work *work) 2278 { 2279 struct btrfs_writepage_fixup *fixup; 2280 struct btrfs_ordered_extent *ordered; 2281 struct extent_state *cached_state = NULL; 2282 struct extent_changeset *data_reserved = NULL; 2283 struct page *page; 2284 struct btrfs_inode *inode; 2285 u64 page_start; 2286 u64 page_end; 2287 int ret = 0; 2288 bool free_delalloc_space = true; 2289 2290 fixup = container_of(work, struct btrfs_writepage_fixup, work); 2291 page = fixup->page; 2292 inode = BTRFS_I(fixup->inode); 2293 page_start = page_offset(page); 2294 page_end = page_offset(page) + PAGE_SIZE - 1; 2295 2296 /* 2297 * This is similar to page_mkwrite, we need to reserve the space before 2298 * we take the page lock. 2299 */ 2300 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start, 2301 PAGE_SIZE); 2302 again: 2303 lock_page(page); 2304 2305 /* 2306 * Before we queued this fixup, we took a reference on the page. 2307 * page->mapping may go NULL, but it shouldn't be moved to a different 2308 * address space. 2309 */ 2310 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) { 2311 /* 2312 * Unfortunately this is a little tricky, either 2313 * 2314 * 1) We got here and our page had already been dealt with and 2315 * we reserved our space, thus ret == 0, so we need to just 2316 * drop our space reservation and bail. This can happen the 2317 * first time we come into the fixup worker, or could happen 2318 * while waiting for the ordered extent. 2319 * 2) Our page was already dealt with, but we happened to get an 2320 * ENOSPC above from the btrfs_delalloc_reserve_space. In 2321 * this case we obviously don't have anything to release, but 2322 * because the page was already dealt with we don't want to 2323 * mark the page with an error, so make sure we're resetting 2324 * ret to 0. This is why we have this check _before_ the ret 2325 * check, because we do not want to have a surprise ENOSPC 2326 * when the page was already properly dealt with. 2327 */ 2328 if (!ret) { 2329 btrfs_delalloc_release_extents(inode, PAGE_SIZE); 2330 btrfs_delalloc_release_space(inode, data_reserved, 2331 page_start, PAGE_SIZE, 2332 true); 2333 } 2334 ret = 0; 2335 goto out_page; 2336 } 2337 2338 /* 2339 * We can't mess with the page state unless it is locked, so now that 2340 * it is locked bail if we failed to make our space reservation. 2341 */ 2342 if (ret) 2343 goto out_page; 2344 2345 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state); 2346 2347 /* already ordered? We're done */ 2348 if (PagePrivate2(page)) 2349 goto out_reserved; 2350 2351 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE); 2352 if (ordered) { 2353 unlock_extent_cached(&inode->io_tree, page_start, page_end, 2354 &cached_state); 2355 unlock_page(page); 2356 btrfs_start_ordered_extent(&inode->vfs_inode, ordered, 1); 2357 btrfs_put_ordered_extent(ordered); 2358 goto again; 2359 } 2360 2361 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0, 2362 &cached_state); 2363 if (ret) 2364 goto out_reserved; 2365 2366 /* 2367 * Everything went as planned, we're now the owner of a dirty page with 2368 * delayed allocation bits set and space reserved for our COW 2369 * destination. 2370 * 2371 * The page was dirty when we started, nothing should have cleaned it. 2372 */ 2373 BUG_ON(!PageDirty(page)); 2374 free_delalloc_space = false; 2375 out_reserved: 2376 btrfs_delalloc_release_extents(inode, PAGE_SIZE); 2377 if (free_delalloc_space) 2378 btrfs_delalloc_release_space(inode, data_reserved, page_start, 2379 PAGE_SIZE, true); 2380 unlock_extent_cached(&inode->io_tree, page_start, page_end, 2381 &cached_state); 2382 out_page: 2383 if (ret) { 2384 /* 2385 * We hit ENOSPC or other errors. Update the mapping and page 2386 * to reflect the errors and clean the page. 2387 */ 2388 mapping_set_error(page->mapping, ret); 2389 end_extent_writepage(page, ret, page_start, page_end); 2390 clear_page_dirty_for_io(page); 2391 SetPageError(page); 2392 } 2393 ClearPageChecked(page); 2394 unlock_page(page); 2395 put_page(page); 2396 kfree(fixup); 2397 extent_changeset_free(data_reserved); 2398 /* 2399 * As a precaution, do a delayed iput in case it would be the last iput 2400 * that could need flushing space. Recursing back to fixup worker would 2401 * deadlock. 2402 */ 2403 btrfs_add_delayed_iput(&inode->vfs_inode); 2404 } 2405 2406 /* 2407 * There are a few paths in the higher layers of the kernel that directly 2408 * set the page dirty bit without asking the filesystem if it is a 2409 * good idea. This causes problems because we want to make sure COW 2410 * properly happens and the data=ordered rules are followed. 2411 * 2412 * In our case any range that doesn't have the ORDERED bit set 2413 * hasn't been properly setup for IO. We kick off an async process 2414 * to fix it up. The async helper will wait for ordered extents, set 2415 * the delalloc bit and make it safe to write the page. 2416 */ 2417 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end) 2418 { 2419 struct inode *inode = page->mapping->host; 2420 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2421 struct btrfs_writepage_fixup *fixup; 2422 2423 /* this page is properly in the ordered list */ 2424 if (TestClearPagePrivate2(page)) 2425 return 0; 2426 2427 /* 2428 * PageChecked is set below when we create a fixup worker for this page, 2429 * don't try to create another one if we're already PageChecked() 2430 * 2431 * The extent_io writepage code will redirty the page if we send back 2432 * EAGAIN. 2433 */ 2434 if (PageChecked(page)) 2435 return -EAGAIN; 2436 2437 fixup = kzalloc(sizeof(*fixup), GFP_NOFS); 2438 if (!fixup) 2439 return -EAGAIN; 2440 2441 /* 2442 * We are already holding a reference to this inode from 2443 * write_cache_pages. We need to hold it because the space reservation 2444 * takes place outside of the page lock, and we can't trust 2445 * page->mapping outside of the page lock. 2446 */ 2447 ihold(inode); 2448 SetPageChecked(page); 2449 get_page(page); 2450 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL); 2451 fixup->page = page; 2452 fixup->inode = inode; 2453 btrfs_queue_work(fs_info->fixup_workers, &fixup->work); 2454 2455 return -EAGAIN; 2456 } 2457 2458 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans, 2459 struct btrfs_inode *inode, u64 file_pos, 2460 struct btrfs_file_extent_item *stack_fi, 2461 u64 qgroup_reserved) 2462 { 2463 struct btrfs_root *root = inode->root; 2464 struct btrfs_path *path; 2465 struct extent_buffer *leaf; 2466 struct btrfs_key ins; 2467 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi); 2468 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi); 2469 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi); 2470 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi); 2471 int extent_inserted = 0; 2472 int ret; 2473 2474 path = btrfs_alloc_path(); 2475 if (!path) 2476 return -ENOMEM; 2477 2478 /* 2479 * we may be replacing one extent in the tree with another. 2480 * The new extent is pinned in the extent map, and we don't want 2481 * to drop it from the cache until it is completely in the btree. 2482 * 2483 * So, tell btrfs_drop_extents to leave this extent in the cache. 2484 * the caller is expected to unpin it and allow it to be merged 2485 * with the others. 2486 */ 2487 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos, 2488 file_pos + num_bytes, NULL, 0, 2489 1, sizeof(*stack_fi), &extent_inserted); 2490 if (ret) 2491 goto out; 2492 2493 if (!extent_inserted) { 2494 ins.objectid = btrfs_ino(inode); 2495 ins.offset = file_pos; 2496 ins.type = BTRFS_EXTENT_DATA_KEY; 2497 2498 path->leave_spinning = 1; 2499 ret = btrfs_insert_empty_item(trans, root, path, &ins, 2500 sizeof(*stack_fi)); 2501 if (ret) 2502 goto out; 2503 } 2504 leaf = path->nodes[0]; 2505 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid); 2506 write_extent_buffer(leaf, stack_fi, 2507 btrfs_item_ptr_offset(leaf, path->slots[0]), 2508 sizeof(struct btrfs_file_extent_item)); 2509 2510 btrfs_mark_buffer_dirty(leaf); 2511 btrfs_release_path(path); 2512 2513 inode_add_bytes(&inode->vfs_inode, num_bytes); 2514 2515 ins.objectid = disk_bytenr; 2516 ins.offset = disk_num_bytes; 2517 ins.type = BTRFS_EXTENT_ITEM_KEY; 2518 2519 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes); 2520 if (ret) 2521 goto out; 2522 2523 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode), 2524 file_pos, qgroup_reserved, &ins); 2525 out: 2526 btrfs_free_path(path); 2527 2528 return ret; 2529 } 2530 2531 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info, 2532 u64 start, u64 len) 2533 { 2534 struct btrfs_block_group *cache; 2535 2536 cache = btrfs_lookup_block_group(fs_info, start); 2537 ASSERT(cache); 2538 2539 spin_lock(&cache->lock); 2540 cache->delalloc_bytes -= len; 2541 spin_unlock(&cache->lock); 2542 2543 btrfs_put_block_group(cache); 2544 } 2545 2546 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans, 2547 struct inode *inode, 2548 struct btrfs_ordered_extent *oe) 2549 { 2550 struct btrfs_file_extent_item stack_fi; 2551 u64 logical_len; 2552 2553 memset(&stack_fi, 0, sizeof(stack_fi)); 2554 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG); 2555 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr); 2556 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, 2557 oe->disk_num_bytes); 2558 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) 2559 logical_len = oe->truncated_len; 2560 else 2561 logical_len = oe->num_bytes; 2562 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len); 2563 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len); 2564 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type); 2565 /* Encryption and other encoding is reserved and all 0 */ 2566 2567 return insert_reserved_file_extent(trans, BTRFS_I(inode), oe->file_offset, 2568 &stack_fi, oe->qgroup_rsv); 2569 } 2570 2571 /* 2572 * As ordered data IO finishes, this gets called so we can finish 2573 * an ordered extent if the range of bytes in the file it covers are 2574 * fully written. 2575 */ 2576 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent) 2577 { 2578 struct inode *inode = ordered_extent->inode; 2579 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2580 struct btrfs_root *root = BTRFS_I(inode)->root; 2581 struct btrfs_trans_handle *trans = NULL; 2582 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 2583 struct extent_state *cached_state = NULL; 2584 u64 start, end; 2585 int compress_type = 0; 2586 int ret = 0; 2587 u64 logical_len = ordered_extent->num_bytes; 2588 bool freespace_inode; 2589 bool truncated = false; 2590 bool range_locked = false; 2591 bool clear_new_delalloc_bytes = false; 2592 bool clear_reserved_extent = true; 2593 unsigned int clear_bits; 2594 2595 start = ordered_extent->file_offset; 2596 end = start + ordered_extent->num_bytes - 1; 2597 2598 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) && 2599 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) && 2600 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags)) 2601 clear_new_delalloc_bytes = true; 2602 2603 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode)); 2604 2605 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) { 2606 ret = -EIO; 2607 goto out; 2608 } 2609 2610 btrfs_free_io_failure_record(BTRFS_I(inode), start, end); 2611 2612 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) { 2613 truncated = true; 2614 logical_len = ordered_extent->truncated_len; 2615 /* Truncated the entire extent, don't bother adding */ 2616 if (!logical_len) 2617 goto out; 2618 } 2619 2620 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) { 2621 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */ 2622 2623 btrfs_inode_safe_disk_i_size_write(inode, 0); 2624 if (freespace_inode) 2625 trans = btrfs_join_transaction_spacecache(root); 2626 else 2627 trans = btrfs_join_transaction(root); 2628 if (IS_ERR(trans)) { 2629 ret = PTR_ERR(trans); 2630 trans = NULL; 2631 goto out; 2632 } 2633 trans->block_rsv = &BTRFS_I(inode)->block_rsv; 2634 ret = btrfs_update_inode_fallback(trans, root, inode); 2635 if (ret) /* -ENOMEM or corruption */ 2636 btrfs_abort_transaction(trans, ret); 2637 goto out; 2638 } 2639 2640 range_locked = true; 2641 lock_extent_bits(io_tree, start, end, &cached_state); 2642 2643 if (freespace_inode) 2644 trans = btrfs_join_transaction_spacecache(root); 2645 else 2646 trans = btrfs_join_transaction(root); 2647 if (IS_ERR(trans)) { 2648 ret = PTR_ERR(trans); 2649 trans = NULL; 2650 goto out; 2651 } 2652 2653 trans->block_rsv = &BTRFS_I(inode)->block_rsv; 2654 2655 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags)) 2656 compress_type = ordered_extent->compress_type; 2657 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) { 2658 BUG_ON(compress_type); 2659 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode), 2660 ordered_extent->file_offset, 2661 ordered_extent->file_offset + 2662 logical_len); 2663 } else { 2664 BUG_ON(root == fs_info->tree_root); 2665 ret = insert_ordered_extent_file_extent(trans, inode, 2666 ordered_extent); 2667 if (!ret) { 2668 clear_reserved_extent = false; 2669 btrfs_release_delalloc_bytes(fs_info, 2670 ordered_extent->disk_bytenr, 2671 ordered_extent->disk_num_bytes); 2672 } 2673 } 2674 unpin_extent_cache(&BTRFS_I(inode)->extent_tree, 2675 ordered_extent->file_offset, 2676 ordered_extent->num_bytes, trans->transid); 2677 if (ret < 0) { 2678 btrfs_abort_transaction(trans, ret); 2679 goto out; 2680 } 2681 2682 ret = add_pending_csums(trans, inode, &ordered_extent->list); 2683 if (ret) { 2684 btrfs_abort_transaction(trans, ret); 2685 goto out; 2686 } 2687 2688 btrfs_inode_safe_disk_i_size_write(inode, 0); 2689 ret = btrfs_update_inode_fallback(trans, root, inode); 2690 if (ret) { /* -ENOMEM or corruption */ 2691 btrfs_abort_transaction(trans, ret); 2692 goto out; 2693 } 2694 ret = 0; 2695 out: 2696 clear_bits = EXTENT_DEFRAG; 2697 if (range_locked) 2698 clear_bits |= EXTENT_LOCKED; 2699 if (clear_new_delalloc_bytes) 2700 clear_bits |= EXTENT_DELALLOC_NEW; 2701 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 2702 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0, 2703 &cached_state); 2704 2705 if (trans) 2706 btrfs_end_transaction(trans); 2707 2708 if (ret || truncated) { 2709 u64 unwritten_start = start; 2710 2711 if (truncated) 2712 unwritten_start += logical_len; 2713 clear_extent_uptodate(io_tree, unwritten_start, end, NULL); 2714 2715 /* Drop the cache for the part of the extent we didn't write. */ 2716 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0); 2717 2718 /* 2719 * If the ordered extent had an IOERR or something else went 2720 * wrong we need to return the space for this ordered extent 2721 * back to the allocator. We only free the extent in the 2722 * truncated case if we didn't write out the extent at all. 2723 * 2724 * If we made it past insert_reserved_file_extent before we 2725 * errored out then we don't need to do this as the accounting 2726 * has already been done. 2727 */ 2728 if ((ret || !logical_len) && 2729 clear_reserved_extent && 2730 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) && 2731 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) { 2732 /* 2733 * Discard the range before returning it back to the 2734 * free space pool 2735 */ 2736 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC)) 2737 btrfs_discard_extent(fs_info, 2738 ordered_extent->disk_bytenr, 2739 ordered_extent->disk_num_bytes, 2740 NULL); 2741 btrfs_free_reserved_extent(fs_info, 2742 ordered_extent->disk_bytenr, 2743 ordered_extent->disk_num_bytes, 1); 2744 } 2745 } 2746 2747 /* 2748 * This needs to be done to make sure anybody waiting knows we are done 2749 * updating everything for this ordered extent. 2750 */ 2751 btrfs_remove_ordered_extent(inode, ordered_extent); 2752 2753 /* once for us */ 2754 btrfs_put_ordered_extent(ordered_extent); 2755 /* once for the tree */ 2756 btrfs_put_ordered_extent(ordered_extent); 2757 2758 return ret; 2759 } 2760 2761 static void finish_ordered_fn(struct btrfs_work *work) 2762 { 2763 struct btrfs_ordered_extent *ordered_extent; 2764 ordered_extent = container_of(work, struct btrfs_ordered_extent, work); 2765 btrfs_finish_ordered_io(ordered_extent); 2766 } 2767 2768 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start, 2769 u64 end, int uptodate) 2770 { 2771 struct inode *inode = page->mapping->host; 2772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2773 struct btrfs_ordered_extent *ordered_extent = NULL; 2774 struct btrfs_workqueue *wq; 2775 2776 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate); 2777 2778 ClearPagePrivate2(page); 2779 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start, 2780 end - start + 1, uptodate)) 2781 return; 2782 2783 if (btrfs_is_free_space_inode(BTRFS_I(inode))) 2784 wq = fs_info->endio_freespace_worker; 2785 else 2786 wq = fs_info->endio_write_workers; 2787 2788 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL); 2789 btrfs_queue_work(wq, &ordered_extent->work); 2790 } 2791 2792 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio, 2793 int icsum, struct page *page, int pgoff, u64 start, 2794 size_t len) 2795 { 2796 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2797 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash); 2798 char *kaddr; 2799 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy); 2800 u8 *csum_expected; 2801 u8 csum[BTRFS_CSUM_SIZE]; 2802 2803 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size; 2804 2805 kaddr = kmap_atomic(page); 2806 shash->tfm = fs_info->csum_shash; 2807 2808 crypto_shash_digest(shash, kaddr + pgoff, len, csum); 2809 2810 if (memcmp(csum, csum_expected, csum_size)) 2811 goto zeroit; 2812 2813 kunmap_atomic(kaddr); 2814 return 0; 2815 zeroit: 2816 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected, 2817 io_bio->mirror_num); 2818 if (io_bio->device) 2819 btrfs_dev_stat_inc_and_print(io_bio->device, 2820 BTRFS_DEV_STAT_CORRUPTION_ERRS); 2821 memset(kaddr + pgoff, 1, len); 2822 flush_dcache_page(page); 2823 kunmap_atomic(kaddr); 2824 return -EIO; 2825 } 2826 2827 /* 2828 * when reads are done, we need to check csums to verify the data is correct 2829 * if there's a match, we allow the bio to finish. If not, the code in 2830 * extent_io.c will try to find good copies for us. 2831 */ 2832 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio, 2833 u64 phy_offset, struct page *page, 2834 u64 start, u64 end, int mirror) 2835 { 2836 size_t offset = start - page_offset(page); 2837 struct inode *inode = page->mapping->host; 2838 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 2839 struct btrfs_root *root = BTRFS_I(inode)->root; 2840 2841 if (PageChecked(page)) { 2842 ClearPageChecked(page); 2843 return 0; 2844 } 2845 2846 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) 2847 return 0; 2848 2849 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID && 2850 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) { 2851 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM); 2852 return 0; 2853 } 2854 2855 phy_offset >>= inode->i_sb->s_blocksize_bits; 2856 return check_data_csum(inode, io_bio, phy_offset, page, offset, start, 2857 (size_t)(end - start + 1)); 2858 } 2859 2860 /* 2861 * btrfs_add_delayed_iput - perform a delayed iput on @inode 2862 * 2863 * @inode: The inode we want to perform iput on 2864 * 2865 * This function uses the generic vfs_inode::i_count to track whether we should 2866 * just decrement it (in case it's > 1) or if this is the last iput then link 2867 * the inode to the delayed iput machinery. Delayed iputs are processed at 2868 * transaction commit time/superblock commit/cleaner kthread. 2869 */ 2870 void btrfs_add_delayed_iput(struct inode *inode) 2871 { 2872 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 2873 struct btrfs_inode *binode = BTRFS_I(inode); 2874 2875 if (atomic_add_unless(&inode->i_count, -1, 1)) 2876 return; 2877 2878 atomic_inc(&fs_info->nr_delayed_iputs); 2879 spin_lock(&fs_info->delayed_iput_lock); 2880 ASSERT(list_empty(&binode->delayed_iput)); 2881 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs); 2882 spin_unlock(&fs_info->delayed_iput_lock); 2883 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags)) 2884 wake_up_process(fs_info->cleaner_kthread); 2885 } 2886 2887 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info, 2888 struct btrfs_inode *inode) 2889 { 2890 list_del_init(&inode->delayed_iput); 2891 spin_unlock(&fs_info->delayed_iput_lock); 2892 iput(&inode->vfs_inode); 2893 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs)) 2894 wake_up(&fs_info->delayed_iputs_wait); 2895 spin_lock(&fs_info->delayed_iput_lock); 2896 } 2897 2898 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info, 2899 struct btrfs_inode *inode) 2900 { 2901 if (!list_empty(&inode->delayed_iput)) { 2902 spin_lock(&fs_info->delayed_iput_lock); 2903 if (!list_empty(&inode->delayed_iput)) 2904 run_delayed_iput_locked(fs_info, inode); 2905 spin_unlock(&fs_info->delayed_iput_lock); 2906 } 2907 } 2908 2909 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info) 2910 { 2911 2912 spin_lock(&fs_info->delayed_iput_lock); 2913 while (!list_empty(&fs_info->delayed_iputs)) { 2914 struct btrfs_inode *inode; 2915 2916 inode = list_first_entry(&fs_info->delayed_iputs, 2917 struct btrfs_inode, delayed_iput); 2918 run_delayed_iput_locked(fs_info, inode); 2919 } 2920 spin_unlock(&fs_info->delayed_iput_lock); 2921 } 2922 2923 /** 2924 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running 2925 * @fs_info - the fs_info for this fs 2926 * @return - EINTR if we were killed, 0 if nothing's pending 2927 * 2928 * This will wait on any delayed iputs that are currently running with KILLABLE 2929 * set. Once they are all done running we will return, unless we are killed in 2930 * which case we return EINTR. This helps in user operations like fallocate etc 2931 * that might get blocked on the iputs. 2932 */ 2933 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info) 2934 { 2935 int ret = wait_event_killable(fs_info->delayed_iputs_wait, 2936 atomic_read(&fs_info->nr_delayed_iputs) == 0); 2937 if (ret) 2938 return -EINTR; 2939 return 0; 2940 } 2941 2942 /* 2943 * This creates an orphan entry for the given inode in case something goes wrong 2944 * in the middle of an unlink. 2945 */ 2946 int btrfs_orphan_add(struct btrfs_trans_handle *trans, 2947 struct btrfs_inode *inode) 2948 { 2949 int ret; 2950 2951 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode)); 2952 if (ret && ret != -EEXIST) { 2953 btrfs_abort_transaction(trans, ret); 2954 return ret; 2955 } 2956 2957 return 0; 2958 } 2959 2960 /* 2961 * We have done the delete so we can go ahead and remove the orphan item for 2962 * this particular inode. 2963 */ 2964 static int btrfs_orphan_del(struct btrfs_trans_handle *trans, 2965 struct btrfs_inode *inode) 2966 { 2967 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode)); 2968 } 2969 2970 /* 2971 * this cleans up any orphans that may be left on the list from the last use 2972 * of this root. 2973 */ 2974 int btrfs_orphan_cleanup(struct btrfs_root *root) 2975 { 2976 struct btrfs_fs_info *fs_info = root->fs_info; 2977 struct btrfs_path *path; 2978 struct extent_buffer *leaf; 2979 struct btrfs_key key, found_key; 2980 struct btrfs_trans_handle *trans; 2981 struct inode *inode; 2982 u64 last_objectid = 0; 2983 int ret = 0, nr_unlink = 0; 2984 2985 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED)) 2986 return 0; 2987 2988 path = btrfs_alloc_path(); 2989 if (!path) { 2990 ret = -ENOMEM; 2991 goto out; 2992 } 2993 path->reada = READA_BACK; 2994 2995 key.objectid = BTRFS_ORPHAN_OBJECTID; 2996 key.type = BTRFS_ORPHAN_ITEM_KEY; 2997 key.offset = (u64)-1; 2998 2999 while (1) { 3000 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 3001 if (ret < 0) 3002 goto out; 3003 3004 /* 3005 * if ret == 0 means we found what we were searching for, which 3006 * is weird, but possible, so only screw with path if we didn't 3007 * find the key and see if we have stuff that matches 3008 */ 3009 if (ret > 0) { 3010 ret = 0; 3011 if (path->slots[0] == 0) 3012 break; 3013 path->slots[0]--; 3014 } 3015 3016 /* pull out the item */ 3017 leaf = path->nodes[0]; 3018 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 3019 3020 /* make sure the item matches what we want */ 3021 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID) 3022 break; 3023 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY) 3024 break; 3025 3026 /* release the path since we're done with it */ 3027 btrfs_release_path(path); 3028 3029 /* 3030 * this is where we are basically btrfs_lookup, without the 3031 * crossing root thing. we store the inode number in the 3032 * offset of the orphan item. 3033 */ 3034 3035 if (found_key.offset == last_objectid) { 3036 btrfs_err(fs_info, 3037 "Error removing orphan entry, stopping orphan cleanup"); 3038 ret = -EINVAL; 3039 goto out; 3040 } 3041 3042 last_objectid = found_key.offset; 3043 3044 found_key.objectid = found_key.offset; 3045 found_key.type = BTRFS_INODE_ITEM_KEY; 3046 found_key.offset = 0; 3047 inode = btrfs_iget(fs_info->sb, last_objectid, root); 3048 ret = PTR_ERR_OR_ZERO(inode); 3049 if (ret && ret != -ENOENT) 3050 goto out; 3051 3052 if (ret == -ENOENT && root == fs_info->tree_root) { 3053 struct btrfs_root *dead_root; 3054 struct btrfs_fs_info *fs_info = root->fs_info; 3055 int is_dead_root = 0; 3056 3057 /* 3058 * this is an orphan in the tree root. Currently these 3059 * could come from 2 sources: 3060 * a) a snapshot deletion in progress 3061 * b) a free space cache inode 3062 * We need to distinguish those two, as the snapshot 3063 * orphan must not get deleted. 3064 * find_dead_roots already ran before us, so if this 3065 * is a snapshot deletion, we should find the root 3066 * in the fs_roots radix tree. 3067 */ 3068 3069 spin_lock(&fs_info->fs_roots_radix_lock); 3070 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix, 3071 (unsigned long)found_key.objectid); 3072 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0) 3073 is_dead_root = 1; 3074 spin_unlock(&fs_info->fs_roots_radix_lock); 3075 3076 if (is_dead_root) { 3077 /* prevent this orphan from being found again */ 3078 key.offset = found_key.objectid - 1; 3079 continue; 3080 } 3081 3082 } 3083 3084 /* 3085 * If we have an inode with links, there are a couple of 3086 * possibilities. Old kernels (before v3.12) used to create an 3087 * orphan item for truncate indicating that there were possibly 3088 * extent items past i_size that needed to be deleted. In v3.12, 3089 * truncate was changed to update i_size in sync with the extent 3090 * items, but the (useless) orphan item was still created. Since 3091 * v4.18, we don't create the orphan item for truncate at all. 3092 * 3093 * So, this item could mean that we need to do a truncate, but 3094 * only if this filesystem was last used on a pre-v3.12 kernel 3095 * and was not cleanly unmounted. The odds of that are quite 3096 * slim, and it's a pain to do the truncate now, so just delete 3097 * the orphan item. 3098 * 3099 * It's also possible that this orphan item was supposed to be 3100 * deleted but wasn't. The inode number may have been reused, 3101 * but either way, we can delete the orphan item. 3102 */ 3103 if (ret == -ENOENT || inode->i_nlink) { 3104 if (!ret) 3105 iput(inode); 3106 trans = btrfs_start_transaction(root, 1); 3107 if (IS_ERR(trans)) { 3108 ret = PTR_ERR(trans); 3109 goto out; 3110 } 3111 btrfs_debug(fs_info, "auto deleting %Lu", 3112 found_key.objectid); 3113 ret = btrfs_del_orphan_item(trans, root, 3114 found_key.objectid); 3115 btrfs_end_transaction(trans); 3116 if (ret) 3117 goto out; 3118 continue; 3119 } 3120 3121 nr_unlink++; 3122 3123 /* this will do delete_inode and everything for us */ 3124 iput(inode); 3125 } 3126 /* release the path since we're done with it */ 3127 btrfs_release_path(path); 3128 3129 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE; 3130 3131 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) { 3132 trans = btrfs_join_transaction(root); 3133 if (!IS_ERR(trans)) 3134 btrfs_end_transaction(trans); 3135 } 3136 3137 if (nr_unlink) 3138 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink); 3139 3140 out: 3141 if (ret) 3142 btrfs_err(fs_info, "could not do orphan cleanup %d", ret); 3143 btrfs_free_path(path); 3144 return ret; 3145 } 3146 3147 /* 3148 * very simple check to peek ahead in the leaf looking for xattrs. If we 3149 * don't find any xattrs, we know there can't be any acls. 3150 * 3151 * slot is the slot the inode is in, objectid is the objectid of the inode 3152 */ 3153 static noinline int acls_after_inode_item(struct extent_buffer *leaf, 3154 int slot, u64 objectid, 3155 int *first_xattr_slot) 3156 { 3157 u32 nritems = btrfs_header_nritems(leaf); 3158 struct btrfs_key found_key; 3159 static u64 xattr_access = 0; 3160 static u64 xattr_default = 0; 3161 int scanned = 0; 3162 3163 if (!xattr_access) { 3164 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS, 3165 strlen(XATTR_NAME_POSIX_ACL_ACCESS)); 3166 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT, 3167 strlen(XATTR_NAME_POSIX_ACL_DEFAULT)); 3168 } 3169 3170 slot++; 3171 *first_xattr_slot = -1; 3172 while (slot < nritems) { 3173 btrfs_item_key_to_cpu(leaf, &found_key, slot); 3174 3175 /* we found a different objectid, there must not be acls */ 3176 if (found_key.objectid != objectid) 3177 return 0; 3178 3179 /* we found an xattr, assume we've got an acl */ 3180 if (found_key.type == BTRFS_XATTR_ITEM_KEY) { 3181 if (*first_xattr_slot == -1) 3182 *first_xattr_slot = slot; 3183 if (found_key.offset == xattr_access || 3184 found_key.offset == xattr_default) 3185 return 1; 3186 } 3187 3188 /* 3189 * we found a key greater than an xattr key, there can't 3190 * be any acls later on 3191 */ 3192 if (found_key.type > BTRFS_XATTR_ITEM_KEY) 3193 return 0; 3194 3195 slot++; 3196 scanned++; 3197 3198 /* 3199 * it goes inode, inode backrefs, xattrs, extents, 3200 * so if there are a ton of hard links to an inode there can 3201 * be a lot of backrefs. Don't waste time searching too hard, 3202 * this is just an optimization 3203 */ 3204 if (scanned >= 8) 3205 break; 3206 } 3207 /* we hit the end of the leaf before we found an xattr or 3208 * something larger than an xattr. We have to assume the inode 3209 * has acls 3210 */ 3211 if (*first_xattr_slot == -1) 3212 *first_xattr_slot = slot; 3213 return 1; 3214 } 3215 3216 /* 3217 * read an inode from the btree into the in-memory inode 3218 */ 3219 static int btrfs_read_locked_inode(struct inode *inode, 3220 struct btrfs_path *in_path) 3221 { 3222 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 3223 struct btrfs_path *path = in_path; 3224 struct extent_buffer *leaf; 3225 struct btrfs_inode_item *inode_item; 3226 struct btrfs_root *root = BTRFS_I(inode)->root; 3227 struct btrfs_key location; 3228 unsigned long ptr; 3229 int maybe_acls; 3230 u32 rdev; 3231 int ret; 3232 bool filled = false; 3233 int first_xattr_slot; 3234 3235 ret = btrfs_fill_inode(inode, &rdev); 3236 if (!ret) 3237 filled = true; 3238 3239 if (!path) { 3240 path = btrfs_alloc_path(); 3241 if (!path) 3242 return -ENOMEM; 3243 } 3244 3245 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location)); 3246 3247 ret = btrfs_lookup_inode(NULL, root, path, &location, 0); 3248 if (ret) { 3249 if (path != in_path) 3250 btrfs_free_path(path); 3251 return ret; 3252 } 3253 3254 leaf = path->nodes[0]; 3255 3256 if (filled) 3257 goto cache_index; 3258 3259 inode_item = btrfs_item_ptr(leaf, path->slots[0], 3260 struct btrfs_inode_item); 3261 inode->i_mode = btrfs_inode_mode(leaf, inode_item); 3262 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item)); 3263 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item)); 3264 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item)); 3265 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item)); 3266 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0, 3267 round_up(i_size_read(inode), fs_info->sectorsize)); 3268 3269 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime); 3270 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime); 3271 3272 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime); 3273 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime); 3274 3275 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime); 3276 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime); 3277 3278 BTRFS_I(inode)->i_otime.tv_sec = 3279 btrfs_timespec_sec(leaf, &inode_item->otime); 3280 BTRFS_I(inode)->i_otime.tv_nsec = 3281 btrfs_timespec_nsec(leaf, &inode_item->otime); 3282 3283 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item)); 3284 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item); 3285 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item); 3286 3287 inode_set_iversion_queried(inode, 3288 btrfs_inode_sequence(leaf, inode_item)); 3289 inode->i_generation = BTRFS_I(inode)->generation; 3290 inode->i_rdev = 0; 3291 rdev = btrfs_inode_rdev(leaf, inode_item); 3292 3293 BTRFS_I(inode)->index_cnt = (u64)-1; 3294 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item); 3295 3296 cache_index: 3297 /* 3298 * If we were modified in the current generation and evicted from memory 3299 * and then re-read we need to do a full sync since we don't have any 3300 * idea about which extents were modified before we were evicted from 3301 * cache. 3302 * 3303 * This is required for both inode re-read from disk and delayed inode 3304 * in delayed_nodes_tree. 3305 */ 3306 if (BTRFS_I(inode)->last_trans == fs_info->generation) 3307 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, 3308 &BTRFS_I(inode)->runtime_flags); 3309 3310 /* 3311 * We don't persist the id of the transaction where an unlink operation 3312 * against the inode was last made. So here we assume the inode might 3313 * have been evicted, and therefore the exact value of last_unlink_trans 3314 * lost, and set it to last_trans to avoid metadata inconsistencies 3315 * between the inode and its parent if the inode is fsync'ed and the log 3316 * replayed. For example, in the scenario: 3317 * 3318 * touch mydir/foo 3319 * ln mydir/foo mydir/bar 3320 * sync 3321 * unlink mydir/bar 3322 * echo 2 > /proc/sys/vm/drop_caches # evicts inode 3323 * xfs_io -c fsync mydir/foo 3324 * <power failure> 3325 * mount fs, triggers fsync log replay 3326 * 3327 * We must make sure that when we fsync our inode foo we also log its 3328 * parent inode, otherwise after log replay the parent still has the 3329 * dentry with the "bar" name but our inode foo has a link count of 1 3330 * and doesn't have an inode ref with the name "bar" anymore. 3331 * 3332 * Setting last_unlink_trans to last_trans is a pessimistic approach, 3333 * but it guarantees correctness at the expense of occasional full 3334 * transaction commits on fsync if our inode is a directory, or if our 3335 * inode is not a directory, logging its parent unnecessarily. 3336 */ 3337 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans; 3338 3339 /* 3340 * Same logic as for last_unlink_trans. We don't persist the generation 3341 * of the last transaction where this inode was used for a reflink 3342 * operation, so after eviction and reloading the inode we must be 3343 * pessimistic and assume the last transaction that modified the inode. 3344 */ 3345 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans; 3346 3347 path->slots[0]++; 3348 if (inode->i_nlink != 1 || 3349 path->slots[0] >= btrfs_header_nritems(leaf)) 3350 goto cache_acl; 3351 3352 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]); 3353 if (location.objectid != btrfs_ino(BTRFS_I(inode))) 3354 goto cache_acl; 3355 3356 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]); 3357 if (location.type == BTRFS_INODE_REF_KEY) { 3358 struct btrfs_inode_ref *ref; 3359 3360 ref = (struct btrfs_inode_ref *)ptr; 3361 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref); 3362 } else if (location.type == BTRFS_INODE_EXTREF_KEY) { 3363 struct btrfs_inode_extref *extref; 3364 3365 extref = (struct btrfs_inode_extref *)ptr; 3366 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf, 3367 extref); 3368 } 3369 cache_acl: 3370 /* 3371 * try to precache a NULL acl entry for files that don't have 3372 * any xattrs or acls 3373 */ 3374 maybe_acls = acls_after_inode_item(leaf, path->slots[0], 3375 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot); 3376 if (first_xattr_slot != -1) { 3377 path->slots[0] = first_xattr_slot; 3378 ret = btrfs_load_inode_props(inode, path); 3379 if (ret) 3380 btrfs_err(fs_info, 3381 "error loading props for ino %llu (root %llu): %d", 3382 btrfs_ino(BTRFS_I(inode)), 3383 root->root_key.objectid, ret); 3384 } 3385 if (path != in_path) 3386 btrfs_free_path(path); 3387 3388 if (!maybe_acls) 3389 cache_no_acl(inode); 3390 3391 switch (inode->i_mode & S_IFMT) { 3392 case S_IFREG: 3393 inode->i_mapping->a_ops = &btrfs_aops; 3394 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; 3395 inode->i_fop = &btrfs_file_operations; 3396 inode->i_op = &btrfs_file_inode_operations; 3397 break; 3398 case S_IFDIR: 3399 inode->i_fop = &btrfs_dir_file_operations; 3400 inode->i_op = &btrfs_dir_inode_operations; 3401 break; 3402 case S_IFLNK: 3403 inode->i_op = &btrfs_symlink_inode_operations; 3404 inode_nohighmem(inode); 3405 inode->i_mapping->a_ops = &btrfs_aops; 3406 break; 3407 default: 3408 inode->i_op = &btrfs_special_inode_operations; 3409 init_special_inode(inode, inode->i_mode, rdev); 3410 break; 3411 } 3412 3413 btrfs_sync_inode_flags_to_i_flags(inode); 3414 return 0; 3415 } 3416 3417 /* 3418 * given a leaf and an inode, copy the inode fields into the leaf 3419 */ 3420 static void fill_inode_item(struct btrfs_trans_handle *trans, 3421 struct extent_buffer *leaf, 3422 struct btrfs_inode_item *item, 3423 struct inode *inode) 3424 { 3425 struct btrfs_map_token token; 3426 3427 btrfs_init_map_token(&token, leaf); 3428 3429 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode)); 3430 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode)); 3431 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size); 3432 btrfs_set_token_inode_mode(&token, item, inode->i_mode); 3433 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink); 3434 3435 btrfs_set_token_timespec_sec(&token, &item->atime, 3436 inode->i_atime.tv_sec); 3437 btrfs_set_token_timespec_nsec(&token, &item->atime, 3438 inode->i_atime.tv_nsec); 3439 3440 btrfs_set_token_timespec_sec(&token, &item->mtime, 3441 inode->i_mtime.tv_sec); 3442 btrfs_set_token_timespec_nsec(&token, &item->mtime, 3443 inode->i_mtime.tv_nsec); 3444 3445 btrfs_set_token_timespec_sec(&token, &item->ctime, 3446 inode->i_ctime.tv_sec); 3447 btrfs_set_token_timespec_nsec(&token, &item->ctime, 3448 inode->i_ctime.tv_nsec); 3449 3450 btrfs_set_token_timespec_sec(&token, &item->otime, 3451 BTRFS_I(inode)->i_otime.tv_sec); 3452 btrfs_set_token_timespec_nsec(&token, &item->otime, 3453 BTRFS_I(inode)->i_otime.tv_nsec); 3454 3455 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode)); 3456 btrfs_set_token_inode_generation(&token, item, 3457 BTRFS_I(inode)->generation); 3458 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode)); 3459 btrfs_set_token_inode_transid(&token, item, trans->transid); 3460 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev); 3461 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags); 3462 btrfs_set_token_inode_block_group(&token, item, 0); 3463 } 3464 3465 /* 3466 * copy everything in the in-memory inode into the btree. 3467 */ 3468 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans, 3469 struct btrfs_root *root, struct inode *inode) 3470 { 3471 struct btrfs_inode_item *inode_item; 3472 struct btrfs_path *path; 3473 struct extent_buffer *leaf; 3474 int ret; 3475 3476 path = btrfs_alloc_path(); 3477 if (!path) 3478 return -ENOMEM; 3479 3480 path->leave_spinning = 1; 3481 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 3482 1); 3483 if (ret) { 3484 if (ret > 0) 3485 ret = -ENOENT; 3486 goto failed; 3487 } 3488 3489 leaf = path->nodes[0]; 3490 inode_item = btrfs_item_ptr(leaf, path->slots[0], 3491 struct btrfs_inode_item); 3492 3493 fill_inode_item(trans, leaf, inode_item, inode); 3494 btrfs_mark_buffer_dirty(leaf); 3495 btrfs_set_inode_last_trans(trans, BTRFS_I(inode)); 3496 ret = 0; 3497 failed: 3498 btrfs_free_path(path); 3499 return ret; 3500 } 3501 3502 /* 3503 * copy everything in the in-memory inode into the btree. 3504 */ 3505 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans, 3506 struct btrfs_root *root, struct inode *inode) 3507 { 3508 struct btrfs_fs_info *fs_info = root->fs_info; 3509 int ret; 3510 3511 /* 3512 * If the inode is a free space inode, we can deadlock during commit 3513 * if we put it into the delayed code. 3514 * 3515 * The data relocation inode should also be directly updated 3516 * without delay 3517 */ 3518 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) 3519 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID 3520 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) { 3521 btrfs_update_root_times(trans, root); 3522 3523 ret = btrfs_delayed_update_inode(trans, root, inode); 3524 if (!ret) 3525 btrfs_set_inode_last_trans(trans, BTRFS_I(inode)); 3526 return ret; 3527 } 3528 3529 return btrfs_update_inode_item(trans, root, inode); 3530 } 3531 3532 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans, 3533 struct btrfs_root *root, 3534 struct inode *inode) 3535 { 3536 int ret; 3537 3538 ret = btrfs_update_inode(trans, root, inode); 3539 if (ret == -ENOSPC) 3540 return btrfs_update_inode_item(trans, root, inode); 3541 return ret; 3542 } 3543 3544 /* 3545 * unlink helper that gets used here in inode.c and in the tree logging 3546 * recovery code. It remove a link in a directory with a given name, and 3547 * also drops the back refs in the inode to the directory 3548 */ 3549 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, 3550 struct btrfs_root *root, 3551 struct btrfs_inode *dir, 3552 struct btrfs_inode *inode, 3553 const char *name, int name_len) 3554 { 3555 struct btrfs_fs_info *fs_info = root->fs_info; 3556 struct btrfs_path *path; 3557 int ret = 0; 3558 struct btrfs_dir_item *di; 3559 u64 index; 3560 u64 ino = btrfs_ino(inode); 3561 u64 dir_ino = btrfs_ino(dir); 3562 3563 path = btrfs_alloc_path(); 3564 if (!path) { 3565 ret = -ENOMEM; 3566 goto out; 3567 } 3568 3569 path->leave_spinning = 1; 3570 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, 3571 name, name_len, -1); 3572 if (IS_ERR_OR_NULL(di)) { 3573 ret = di ? PTR_ERR(di) : -ENOENT; 3574 goto err; 3575 } 3576 ret = btrfs_delete_one_dir_name(trans, root, path, di); 3577 if (ret) 3578 goto err; 3579 btrfs_release_path(path); 3580 3581 /* 3582 * If we don't have dir index, we have to get it by looking up 3583 * the inode ref, since we get the inode ref, remove it directly, 3584 * it is unnecessary to do delayed deletion. 3585 * 3586 * But if we have dir index, needn't search inode ref to get it. 3587 * Since the inode ref is close to the inode item, it is better 3588 * that we delay to delete it, and just do this deletion when 3589 * we update the inode item. 3590 */ 3591 if (inode->dir_index) { 3592 ret = btrfs_delayed_delete_inode_ref(inode); 3593 if (!ret) { 3594 index = inode->dir_index; 3595 goto skip_backref; 3596 } 3597 } 3598 3599 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, 3600 dir_ino, &index); 3601 if (ret) { 3602 btrfs_info(fs_info, 3603 "failed to delete reference to %.*s, inode %llu parent %llu", 3604 name_len, name, ino, dir_ino); 3605 btrfs_abort_transaction(trans, ret); 3606 goto err; 3607 } 3608 skip_backref: 3609 ret = btrfs_delete_delayed_dir_index(trans, dir, index); 3610 if (ret) { 3611 btrfs_abort_transaction(trans, ret); 3612 goto err; 3613 } 3614 3615 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode, 3616 dir_ino); 3617 if (ret != 0 && ret != -ENOENT) { 3618 btrfs_abort_transaction(trans, ret); 3619 goto err; 3620 } 3621 3622 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir, 3623 index); 3624 if (ret == -ENOENT) 3625 ret = 0; 3626 else if (ret) 3627 btrfs_abort_transaction(trans, ret); 3628 3629 /* 3630 * If we have a pending delayed iput we could end up with the final iput 3631 * being run in btrfs-cleaner context. If we have enough of these built 3632 * up we can end up burning a lot of time in btrfs-cleaner without any 3633 * way to throttle the unlinks. Since we're currently holding a ref on 3634 * the inode we can run the delayed iput here without any issues as the 3635 * final iput won't be done until after we drop the ref we're currently 3636 * holding. 3637 */ 3638 btrfs_run_delayed_iput(fs_info, inode); 3639 err: 3640 btrfs_free_path(path); 3641 if (ret) 3642 goto out; 3643 3644 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2); 3645 inode_inc_iversion(&inode->vfs_inode); 3646 inode_inc_iversion(&dir->vfs_inode); 3647 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime = 3648 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode); 3649 ret = btrfs_update_inode(trans, root, &dir->vfs_inode); 3650 out: 3651 return ret; 3652 } 3653 3654 int btrfs_unlink_inode(struct btrfs_trans_handle *trans, 3655 struct btrfs_root *root, 3656 struct btrfs_inode *dir, struct btrfs_inode *inode, 3657 const char *name, int name_len) 3658 { 3659 int ret; 3660 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len); 3661 if (!ret) { 3662 drop_nlink(&inode->vfs_inode); 3663 ret = btrfs_update_inode(trans, root, &inode->vfs_inode); 3664 } 3665 return ret; 3666 } 3667 3668 /* 3669 * helper to start transaction for unlink and rmdir. 3670 * 3671 * unlink and rmdir are special in btrfs, they do not always free space, so 3672 * if we cannot make our reservations the normal way try and see if there is 3673 * plenty of slack room in the global reserve to migrate, otherwise we cannot 3674 * allow the unlink to occur. 3675 */ 3676 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir) 3677 { 3678 struct btrfs_root *root = BTRFS_I(dir)->root; 3679 3680 /* 3681 * 1 for the possible orphan item 3682 * 1 for the dir item 3683 * 1 for the dir index 3684 * 1 for the inode ref 3685 * 1 for the inode 3686 */ 3687 return btrfs_start_transaction_fallback_global_rsv(root, 5); 3688 } 3689 3690 static int btrfs_unlink(struct inode *dir, struct dentry *dentry) 3691 { 3692 struct btrfs_root *root = BTRFS_I(dir)->root; 3693 struct btrfs_trans_handle *trans; 3694 struct inode *inode = d_inode(dentry); 3695 int ret; 3696 3697 trans = __unlink_start_trans(dir); 3698 if (IS_ERR(trans)) 3699 return PTR_ERR(trans); 3700 3701 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)), 3702 0); 3703 3704 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir), 3705 BTRFS_I(d_inode(dentry)), dentry->d_name.name, 3706 dentry->d_name.len); 3707 if (ret) 3708 goto out; 3709 3710 if (inode->i_nlink == 0) { 3711 ret = btrfs_orphan_add(trans, BTRFS_I(inode)); 3712 if (ret) 3713 goto out; 3714 } 3715 3716 out: 3717 btrfs_end_transaction(trans); 3718 btrfs_btree_balance_dirty(root->fs_info); 3719 return ret; 3720 } 3721 3722 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans, 3723 struct inode *dir, struct dentry *dentry) 3724 { 3725 struct btrfs_root *root = BTRFS_I(dir)->root; 3726 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry)); 3727 struct btrfs_path *path; 3728 struct extent_buffer *leaf; 3729 struct btrfs_dir_item *di; 3730 struct btrfs_key key; 3731 const char *name = dentry->d_name.name; 3732 int name_len = dentry->d_name.len; 3733 u64 index; 3734 int ret; 3735 u64 objectid; 3736 u64 dir_ino = btrfs_ino(BTRFS_I(dir)); 3737 3738 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) { 3739 objectid = inode->root->root_key.objectid; 3740 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) { 3741 objectid = inode->location.objectid; 3742 } else { 3743 WARN_ON(1); 3744 return -EINVAL; 3745 } 3746 3747 path = btrfs_alloc_path(); 3748 if (!path) 3749 return -ENOMEM; 3750 3751 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, 3752 name, name_len, -1); 3753 if (IS_ERR_OR_NULL(di)) { 3754 ret = di ? PTR_ERR(di) : -ENOENT; 3755 goto out; 3756 } 3757 3758 leaf = path->nodes[0]; 3759 btrfs_dir_item_key_to_cpu(leaf, di, &key); 3760 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid); 3761 ret = btrfs_delete_one_dir_name(trans, root, path, di); 3762 if (ret) { 3763 btrfs_abort_transaction(trans, ret); 3764 goto out; 3765 } 3766 btrfs_release_path(path); 3767 3768 /* 3769 * This is a placeholder inode for a subvolume we didn't have a 3770 * reference to at the time of the snapshot creation. In the meantime 3771 * we could have renamed the real subvol link into our snapshot, so 3772 * depending on btrfs_del_root_ref to return -ENOENT here is incorret. 3773 * Instead simply lookup the dir_index_item for this entry so we can 3774 * remove it. Otherwise we know we have a ref to the root and we can 3775 * call btrfs_del_root_ref, and it _shouldn't_ fail. 3776 */ 3777 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) { 3778 di = btrfs_search_dir_index_item(root, path, dir_ino, 3779 name, name_len); 3780 if (IS_ERR_OR_NULL(di)) { 3781 if (!di) 3782 ret = -ENOENT; 3783 else 3784 ret = PTR_ERR(di); 3785 btrfs_abort_transaction(trans, ret); 3786 goto out; 3787 } 3788 3789 leaf = path->nodes[0]; 3790 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 3791 index = key.offset; 3792 btrfs_release_path(path); 3793 } else { 3794 ret = btrfs_del_root_ref(trans, objectid, 3795 root->root_key.objectid, dir_ino, 3796 &index, name, name_len); 3797 if (ret) { 3798 btrfs_abort_transaction(trans, ret); 3799 goto out; 3800 } 3801 } 3802 3803 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index); 3804 if (ret) { 3805 btrfs_abort_transaction(trans, ret); 3806 goto out; 3807 } 3808 3809 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2); 3810 inode_inc_iversion(dir); 3811 dir->i_mtime = dir->i_ctime = current_time(dir); 3812 ret = btrfs_update_inode_fallback(trans, root, dir); 3813 if (ret) 3814 btrfs_abort_transaction(trans, ret); 3815 out: 3816 btrfs_free_path(path); 3817 return ret; 3818 } 3819 3820 /* 3821 * Helper to check if the subvolume references other subvolumes or if it's 3822 * default. 3823 */ 3824 static noinline int may_destroy_subvol(struct btrfs_root *root) 3825 { 3826 struct btrfs_fs_info *fs_info = root->fs_info; 3827 struct btrfs_path *path; 3828 struct btrfs_dir_item *di; 3829 struct btrfs_key key; 3830 u64 dir_id; 3831 int ret; 3832 3833 path = btrfs_alloc_path(); 3834 if (!path) 3835 return -ENOMEM; 3836 3837 /* Make sure this root isn't set as the default subvol */ 3838 dir_id = btrfs_super_root_dir(fs_info->super_copy); 3839 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path, 3840 dir_id, "default", 7, 0); 3841 if (di && !IS_ERR(di)) { 3842 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key); 3843 if (key.objectid == root->root_key.objectid) { 3844 ret = -EPERM; 3845 btrfs_err(fs_info, 3846 "deleting default subvolume %llu is not allowed", 3847 key.objectid); 3848 goto out; 3849 } 3850 btrfs_release_path(path); 3851 } 3852 3853 key.objectid = root->root_key.objectid; 3854 key.type = BTRFS_ROOT_REF_KEY; 3855 key.offset = (u64)-1; 3856 3857 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0); 3858 if (ret < 0) 3859 goto out; 3860 BUG_ON(ret == 0); 3861 3862 ret = 0; 3863 if (path->slots[0] > 0) { 3864 path->slots[0]--; 3865 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); 3866 if (key.objectid == root->root_key.objectid && 3867 key.type == BTRFS_ROOT_REF_KEY) 3868 ret = -ENOTEMPTY; 3869 } 3870 out: 3871 btrfs_free_path(path); 3872 return ret; 3873 } 3874 3875 /* Delete all dentries for inodes belonging to the root */ 3876 static void btrfs_prune_dentries(struct btrfs_root *root) 3877 { 3878 struct btrfs_fs_info *fs_info = root->fs_info; 3879 struct rb_node *node; 3880 struct rb_node *prev; 3881 struct btrfs_inode *entry; 3882 struct inode *inode; 3883 u64 objectid = 0; 3884 3885 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) 3886 WARN_ON(btrfs_root_refs(&root->root_item) != 0); 3887 3888 spin_lock(&root->inode_lock); 3889 again: 3890 node = root->inode_tree.rb_node; 3891 prev = NULL; 3892 while (node) { 3893 prev = node; 3894 entry = rb_entry(node, struct btrfs_inode, rb_node); 3895 3896 if (objectid < btrfs_ino(entry)) 3897 node = node->rb_left; 3898 else if (objectid > btrfs_ino(entry)) 3899 node = node->rb_right; 3900 else 3901 break; 3902 } 3903 if (!node) { 3904 while (prev) { 3905 entry = rb_entry(prev, struct btrfs_inode, rb_node); 3906 if (objectid <= btrfs_ino(entry)) { 3907 node = prev; 3908 break; 3909 } 3910 prev = rb_next(prev); 3911 } 3912 } 3913 while (node) { 3914 entry = rb_entry(node, struct btrfs_inode, rb_node); 3915 objectid = btrfs_ino(entry) + 1; 3916 inode = igrab(&entry->vfs_inode); 3917 if (inode) { 3918 spin_unlock(&root->inode_lock); 3919 if (atomic_read(&inode->i_count) > 1) 3920 d_prune_aliases(inode); 3921 /* 3922 * btrfs_drop_inode will have it removed from the inode 3923 * cache when its usage count hits zero. 3924 */ 3925 iput(inode); 3926 cond_resched(); 3927 spin_lock(&root->inode_lock); 3928 goto again; 3929 } 3930 3931 if (cond_resched_lock(&root->inode_lock)) 3932 goto again; 3933 3934 node = rb_next(node); 3935 } 3936 spin_unlock(&root->inode_lock); 3937 } 3938 3939 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry) 3940 { 3941 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb); 3942 struct btrfs_root *root = BTRFS_I(dir)->root; 3943 struct inode *inode = d_inode(dentry); 3944 struct btrfs_root *dest = BTRFS_I(inode)->root; 3945 struct btrfs_trans_handle *trans; 3946 struct btrfs_block_rsv block_rsv; 3947 u64 root_flags; 3948 int ret; 3949 int err; 3950 3951 /* 3952 * Don't allow to delete a subvolume with send in progress. This is 3953 * inside the inode lock so the error handling that has to drop the bit 3954 * again is not run concurrently. 3955 */ 3956 spin_lock(&dest->root_item_lock); 3957 if (dest->send_in_progress) { 3958 spin_unlock(&dest->root_item_lock); 3959 btrfs_warn(fs_info, 3960 "attempt to delete subvolume %llu during send", 3961 dest->root_key.objectid); 3962 return -EPERM; 3963 } 3964 root_flags = btrfs_root_flags(&dest->root_item); 3965 btrfs_set_root_flags(&dest->root_item, 3966 root_flags | BTRFS_ROOT_SUBVOL_DEAD); 3967 spin_unlock(&dest->root_item_lock); 3968 3969 down_write(&fs_info->subvol_sem); 3970 3971 err = may_destroy_subvol(dest); 3972 if (err) 3973 goto out_up_write; 3974 3975 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP); 3976 /* 3977 * One for dir inode, 3978 * two for dir entries, 3979 * two for root ref/backref. 3980 */ 3981 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true); 3982 if (err) 3983 goto out_up_write; 3984 3985 trans = btrfs_start_transaction(root, 0); 3986 if (IS_ERR(trans)) { 3987 err = PTR_ERR(trans); 3988 goto out_release; 3989 } 3990 trans->block_rsv = &block_rsv; 3991 trans->bytes_reserved = block_rsv.size; 3992 3993 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir)); 3994 3995 ret = btrfs_unlink_subvol(trans, dir, dentry); 3996 if (ret) { 3997 err = ret; 3998 btrfs_abort_transaction(trans, ret); 3999 goto out_end_trans; 4000 } 4001 4002 btrfs_record_root_in_trans(trans, dest); 4003 4004 memset(&dest->root_item.drop_progress, 0, 4005 sizeof(dest->root_item.drop_progress)); 4006 dest->root_item.drop_level = 0; 4007 btrfs_set_root_refs(&dest->root_item, 0); 4008 4009 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) { 4010 ret = btrfs_insert_orphan_item(trans, 4011 fs_info->tree_root, 4012 dest->root_key.objectid); 4013 if (ret) { 4014 btrfs_abort_transaction(trans, ret); 4015 err = ret; 4016 goto out_end_trans; 4017 } 4018 } 4019 4020 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid, 4021 BTRFS_UUID_KEY_SUBVOL, 4022 dest->root_key.objectid); 4023 if (ret && ret != -ENOENT) { 4024 btrfs_abort_transaction(trans, ret); 4025 err = ret; 4026 goto out_end_trans; 4027 } 4028 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) { 4029 ret = btrfs_uuid_tree_remove(trans, 4030 dest->root_item.received_uuid, 4031 BTRFS_UUID_KEY_RECEIVED_SUBVOL, 4032 dest->root_key.objectid); 4033 if (ret && ret != -ENOENT) { 4034 btrfs_abort_transaction(trans, ret); 4035 err = ret; 4036 goto out_end_trans; 4037 } 4038 } 4039 4040 free_anon_bdev(dest->anon_dev); 4041 dest->anon_dev = 0; 4042 out_end_trans: 4043 trans->block_rsv = NULL; 4044 trans->bytes_reserved = 0; 4045 ret = btrfs_end_transaction(trans); 4046 if (ret && !err) 4047 err = ret; 4048 inode->i_flags |= S_DEAD; 4049 out_release: 4050 btrfs_subvolume_release_metadata(fs_info, &block_rsv); 4051 out_up_write: 4052 up_write(&fs_info->subvol_sem); 4053 if (err) { 4054 spin_lock(&dest->root_item_lock); 4055 root_flags = btrfs_root_flags(&dest->root_item); 4056 btrfs_set_root_flags(&dest->root_item, 4057 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD); 4058 spin_unlock(&dest->root_item_lock); 4059 } else { 4060 d_invalidate(dentry); 4061 btrfs_prune_dentries(dest); 4062 ASSERT(dest->send_in_progress == 0); 4063 4064 /* the last ref */ 4065 if (dest->ino_cache_inode) { 4066 iput(dest->ino_cache_inode); 4067 dest->ino_cache_inode = NULL; 4068 } 4069 } 4070 4071 return err; 4072 } 4073 4074 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry) 4075 { 4076 struct inode *inode = d_inode(dentry); 4077 int err = 0; 4078 struct btrfs_root *root = BTRFS_I(dir)->root; 4079 struct btrfs_trans_handle *trans; 4080 u64 last_unlink_trans; 4081 4082 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) 4083 return -ENOTEMPTY; 4084 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) 4085 return btrfs_delete_subvolume(dir, dentry); 4086 4087 trans = __unlink_start_trans(dir); 4088 if (IS_ERR(trans)) 4089 return PTR_ERR(trans); 4090 4091 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { 4092 err = btrfs_unlink_subvol(trans, dir, dentry); 4093 goto out; 4094 } 4095 4096 err = btrfs_orphan_add(trans, BTRFS_I(inode)); 4097 if (err) 4098 goto out; 4099 4100 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans; 4101 4102 /* now the directory is empty */ 4103 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir), 4104 BTRFS_I(d_inode(dentry)), dentry->d_name.name, 4105 dentry->d_name.len); 4106 if (!err) { 4107 btrfs_i_size_write(BTRFS_I(inode), 0); 4108 /* 4109 * Propagate the last_unlink_trans value of the deleted dir to 4110 * its parent directory. This is to prevent an unrecoverable 4111 * log tree in the case we do something like this: 4112 * 1) create dir foo 4113 * 2) create snapshot under dir foo 4114 * 3) delete the snapshot 4115 * 4) rmdir foo 4116 * 5) mkdir foo 4117 * 6) fsync foo or some file inside foo 4118 */ 4119 if (last_unlink_trans >= trans->transid) 4120 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans; 4121 } 4122 out: 4123 btrfs_end_transaction(trans); 4124 btrfs_btree_balance_dirty(root->fs_info); 4125 4126 return err; 4127 } 4128 4129 /* 4130 * Return this if we need to call truncate_block for the last bit of the 4131 * truncate. 4132 */ 4133 #define NEED_TRUNCATE_BLOCK 1 4134 4135 /* 4136 * this can truncate away extent items, csum items and directory items. 4137 * It starts at a high offset and removes keys until it can't find 4138 * any higher than new_size 4139 * 4140 * csum items that cross the new i_size are truncated to the new size 4141 * as well. 4142 * 4143 * min_type is the minimum key type to truncate down to. If set to 0, this 4144 * will kill all the items on this inode, including the INODE_ITEM_KEY. 4145 */ 4146 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, 4147 struct btrfs_root *root, 4148 struct inode *inode, 4149 u64 new_size, u32 min_type) 4150 { 4151 struct btrfs_fs_info *fs_info = root->fs_info; 4152 struct btrfs_path *path; 4153 struct extent_buffer *leaf; 4154 struct btrfs_file_extent_item *fi; 4155 struct btrfs_key key; 4156 struct btrfs_key found_key; 4157 u64 extent_start = 0; 4158 u64 extent_num_bytes = 0; 4159 u64 extent_offset = 0; 4160 u64 item_end = 0; 4161 u64 last_size = new_size; 4162 u32 found_type = (u8)-1; 4163 int found_extent; 4164 int del_item; 4165 int pending_del_nr = 0; 4166 int pending_del_slot = 0; 4167 int extent_type = -1; 4168 int ret; 4169 u64 ino = btrfs_ino(BTRFS_I(inode)); 4170 u64 bytes_deleted = 0; 4171 bool be_nice = false; 4172 bool should_throttle = false; 4173 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize); 4174 struct extent_state *cached_state = NULL; 4175 4176 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); 4177 4178 /* 4179 * For non-free space inodes and non-shareable roots, we want to back 4180 * off from time to time. This means all inodes in subvolume roots, 4181 * reloc roots, and data reloc roots. 4182 */ 4183 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) && 4184 test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) 4185 be_nice = true; 4186 4187 path = btrfs_alloc_path(); 4188 if (!path) 4189 return -ENOMEM; 4190 path->reada = READA_BACK; 4191 4192 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) { 4193 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1, 4194 &cached_state); 4195 4196 /* 4197 * We want to drop from the next block forward in case this 4198 * new size is not block aligned since we will be keeping the 4199 * last block of the extent just the way it is. 4200 */ 4201 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size, 4202 fs_info->sectorsize), 4203 (u64)-1, 0); 4204 } 4205 4206 /* 4207 * This function is also used to drop the items in the log tree before 4208 * we relog the inode, so if root != BTRFS_I(inode)->root, it means 4209 * it is used to drop the logged items. So we shouldn't kill the delayed 4210 * items. 4211 */ 4212 if (min_type == 0 && root == BTRFS_I(inode)->root) 4213 btrfs_kill_delayed_inode_items(BTRFS_I(inode)); 4214 4215 key.objectid = ino; 4216 key.offset = (u64)-1; 4217 key.type = (u8)-1; 4218 4219 search_again: 4220 /* 4221 * with a 16K leaf size and 128MB extents, you can actually queue 4222 * up a huge file in a single leaf. Most of the time that 4223 * bytes_deleted is > 0, it will be huge by the time we get here 4224 */ 4225 if (be_nice && bytes_deleted > SZ_32M && 4226 btrfs_should_end_transaction(trans)) { 4227 ret = -EAGAIN; 4228 goto out; 4229 } 4230 4231 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 4232 if (ret < 0) 4233 goto out; 4234 4235 if (ret > 0) { 4236 ret = 0; 4237 /* there are no items in the tree for us to truncate, we're 4238 * done 4239 */ 4240 if (path->slots[0] == 0) 4241 goto out; 4242 path->slots[0]--; 4243 } 4244 4245 while (1) { 4246 u64 clear_start = 0, clear_len = 0; 4247 4248 fi = NULL; 4249 leaf = path->nodes[0]; 4250 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 4251 found_type = found_key.type; 4252 4253 if (found_key.objectid != ino) 4254 break; 4255 4256 if (found_type < min_type) 4257 break; 4258 4259 item_end = found_key.offset; 4260 if (found_type == BTRFS_EXTENT_DATA_KEY) { 4261 fi = btrfs_item_ptr(leaf, path->slots[0], 4262 struct btrfs_file_extent_item); 4263 extent_type = btrfs_file_extent_type(leaf, fi); 4264 if (extent_type != BTRFS_FILE_EXTENT_INLINE) { 4265 item_end += 4266 btrfs_file_extent_num_bytes(leaf, fi); 4267 4268 trace_btrfs_truncate_show_fi_regular( 4269 BTRFS_I(inode), leaf, fi, 4270 found_key.offset); 4271 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 4272 item_end += btrfs_file_extent_ram_bytes(leaf, 4273 fi); 4274 4275 trace_btrfs_truncate_show_fi_inline( 4276 BTRFS_I(inode), leaf, fi, path->slots[0], 4277 found_key.offset); 4278 } 4279 item_end--; 4280 } 4281 if (found_type > min_type) { 4282 del_item = 1; 4283 } else { 4284 if (item_end < new_size) 4285 break; 4286 if (found_key.offset >= new_size) 4287 del_item = 1; 4288 else 4289 del_item = 0; 4290 } 4291 found_extent = 0; 4292 /* FIXME, shrink the extent if the ref count is only 1 */ 4293 if (found_type != BTRFS_EXTENT_DATA_KEY) 4294 goto delete; 4295 4296 if (extent_type != BTRFS_FILE_EXTENT_INLINE) { 4297 u64 num_dec; 4298 4299 clear_start = found_key.offset; 4300 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); 4301 if (!del_item) { 4302 u64 orig_num_bytes = 4303 btrfs_file_extent_num_bytes(leaf, fi); 4304 extent_num_bytes = ALIGN(new_size - 4305 found_key.offset, 4306 fs_info->sectorsize); 4307 clear_start = ALIGN(new_size, fs_info->sectorsize); 4308 btrfs_set_file_extent_num_bytes(leaf, fi, 4309 extent_num_bytes); 4310 num_dec = (orig_num_bytes - 4311 extent_num_bytes); 4312 if (test_bit(BTRFS_ROOT_SHAREABLE, 4313 &root->state) && 4314 extent_start != 0) 4315 inode_sub_bytes(inode, num_dec); 4316 btrfs_mark_buffer_dirty(leaf); 4317 } else { 4318 extent_num_bytes = 4319 btrfs_file_extent_disk_num_bytes(leaf, 4320 fi); 4321 extent_offset = found_key.offset - 4322 btrfs_file_extent_offset(leaf, fi); 4323 4324 /* FIXME blocksize != 4096 */ 4325 num_dec = btrfs_file_extent_num_bytes(leaf, fi); 4326 if (extent_start != 0) { 4327 found_extent = 1; 4328 if (test_bit(BTRFS_ROOT_SHAREABLE, 4329 &root->state)) 4330 inode_sub_bytes(inode, num_dec); 4331 } 4332 } 4333 clear_len = num_dec; 4334 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 4335 /* 4336 * we can't truncate inline items that have had 4337 * special encodings 4338 */ 4339 if (!del_item && 4340 btrfs_file_extent_encryption(leaf, fi) == 0 && 4341 btrfs_file_extent_other_encoding(leaf, fi) == 0 && 4342 btrfs_file_extent_compression(leaf, fi) == 0) { 4343 u32 size = (u32)(new_size - found_key.offset); 4344 4345 btrfs_set_file_extent_ram_bytes(leaf, fi, size); 4346 size = btrfs_file_extent_calc_inline_size(size); 4347 btrfs_truncate_item(path, size, 1); 4348 } else if (!del_item) { 4349 /* 4350 * We have to bail so the last_size is set to 4351 * just before this extent. 4352 */ 4353 ret = NEED_TRUNCATE_BLOCK; 4354 break; 4355 } else { 4356 /* 4357 * Inline extents are special, we just treat 4358 * them as a full sector worth in the file 4359 * extent tree just for simplicity sake. 4360 */ 4361 clear_len = fs_info->sectorsize; 4362 } 4363 4364 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) 4365 inode_sub_bytes(inode, item_end + 1 - new_size); 4366 } 4367 delete: 4368 /* 4369 * We use btrfs_truncate_inode_items() to clean up log trees for 4370 * multiple fsyncs, and in this case we don't want to clear the 4371 * file extent range because it's just the log. 4372 */ 4373 if (root == BTRFS_I(inode)->root) { 4374 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 4375 clear_start, clear_len); 4376 if (ret) { 4377 btrfs_abort_transaction(trans, ret); 4378 break; 4379 } 4380 } 4381 4382 if (del_item) 4383 last_size = found_key.offset; 4384 else 4385 last_size = new_size; 4386 if (del_item) { 4387 if (!pending_del_nr) { 4388 /* no pending yet, add ourselves */ 4389 pending_del_slot = path->slots[0]; 4390 pending_del_nr = 1; 4391 } else if (pending_del_nr && 4392 path->slots[0] + 1 == pending_del_slot) { 4393 /* hop on the pending chunk */ 4394 pending_del_nr++; 4395 pending_del_slot = path->slots[0]; 4396 } else { 4397 BUG(); 4398 } 4399 } else { 4400 break; 4401 } 4402 should_throttle = false; 4403 4404 if (found_extent && 4405 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) { 4406 struct btrfs_ref ref = { 0 }; 4407 4408 bytes_deleted += extent_num_bytes; 4409 4410 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, 4411 extent_start, extent_num_bytes, 0); 4412 ref.real_root = root->root_key.objectid; 4413 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf), 4414 ino, extent_offset); 4415 ret = btrfs_free_extent(trans, &ref); 4416 if (ret) { 4417 btrfs_abort_transaction(trans, ret); 4418 break; 4419 } 4420 if (be_nice) { 4421 if (btrfs_should_throttle_delayed_refs(trans)) 4422 should_throttle = true; 4423 } 4424 } 4425 4426 if (found_type == BTRFS_INODE_ITEM_KEY) 4427 break; 4428 4429 if (path->slots[0] == 0 || 4430 path->slots[0] != pending_del_slot || 4431 should_throttle) { 4432 if (pending_del_nr) { 4433 ret = btrfs_del_items(trans, root, path, 4434 pending_del_slot, 4435 pending_del_nr); 4436 if (ret) { 4437 btrfs_abort_transaction(trans, ret); 4438 break; 4439 } 4440 pending_del_nr = 0; 4441 } 4442 btrfs_release_path(path); 4443 4444 /* 4445 * We can generate a lot of delayed refs, so we need to 4446 * throttle every once and a while and make sure we're 4447 * adding enough space to keep up with the work we are 4448 * generating. Since we hold a transaction here we 4449 * can't flush, and we don't want to FLUSH_LIMIT because 4450 * we could have generated too many delayed refs to 4451 * actually allocate, so just bail if we're short and 4452 * let the normal reservation dance happen higher up. 4453 */ 4454 if (should_throttle) { 4455 ret = btrfs_delayed_refs_rsv_refill(fs_info, 4456 BTRFS_RESERVE_NO_FLUSH); 4457 if (ret) { 4458 ret = -EAGAIN; 4459 break; 4460 } 4461 } 4462 goto search_again; 4463 } else { 4464 path->slots[0]--; 4465 } 4466 } 4467 out: 4468 if (ret >= 0 && pending_del_nr) { 4469 int err; 4470 4471 err = btrfs_del_items(trans, root, path, pending_del_slot, 4472 pending_del_nr); 4473 if (err) { 4474 btrfs_abort_transaction(trans, err); 4475 ret = err; 4476 } 4477 } 4478 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) { 4479 ASSERT(last_size >= new_size); 4480 if (!ret && last_size > new_size) 4481 last_size = new_size; 4482 btrfs_inode_safe_disk_i_size_write(inode, last_size); 4483 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, 4484 (u64)-1, &cached_state); 4485 } 4486 4487 btrfs_free_path(path); 4488 return ret; 4489 } 4490 4491 /* 4492 * btrfs_truncate_block - read, zero a chunk and write a block 4493 * @inode - inode that we're zeroing 4494 * @from - the offset to start zeroing 4495 * @len - the length to zero, 0 to zero the entire range respective to the 4496 * offset 4497 * @front - zero up to the offset instead of from the offset on 4498 * 4499 * This will find the block for the "from" offset and cow the block and zero the 4500 * part we want to zero. This is used with truncate and hole punching. 4501 */ 4502 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len, 4503 int front) 4504 { 4505 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 4506 struct address_space *mapping = inode->i_mapping; 4507 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 4508 struct btrfs_ordered_extent *ordered; 4509 struct extent_state *cached_state = NULL; 4510 struct extent_changeset *data_reserved = NULL; 4511 char *kaddr; 4512 bool only_release_metadata = false; 4513 u32 blocksize = fs_info->sectorsize; 4514 pgoff_t index = from >> PAGE_SHIFT; 4515 unsigned offset = from & (blocksize - 1); 4516 struct page *page; 4517 gfp_t mask = btrfs_alloc_write_mask(mapping); 4518 size_t write_bytes = blocksize; 4519 int ret = 0; 4520 u64 block_start; 4521 u64 block_end; 4522 4523 if (IS_ALIGNED(offset, blocksize) && 4524 (!len || IS_ALIGNED(len, blocksize))) 4525 goto out; 4526 4527 block_start = round_down(from, blocksize); 4528 block_end = block_start + blocksize - 1; 4529 4530 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 4531 block_start, blocksize); 4532 if (ret < 0) { 4533 if (btrfs_check_nocow_lock(BTRFS_I(inode), block_start, 4534 &write_bytes) > 0) { 4535 /* For nocow case, no need to reserve data space */ 4536 only_release_metadata = true; 4537 } else { 4538 goto out; 4539 } 4540 } 4541 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), blocksize); 4542 if (ret < 0) { 4543 if (!only_release_metadata) 4544 btrfs_free_reserved_data_space(BTRFS_I(inode), 4545 data_reserved, block_start, blocksize); 4546 goto out; 4547 } 4548 again: 4549 page = find_or_create_page(mapping, index, mask); 4550 if (!page) { 4551 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, 4552 block_start, blocksize, true); 4553 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize); 4554 ret = -ENOMEM; 4555 goto out; 4556 } 4557 4558 if (!PageUptodate(page)) { 4559 ret = btrfs_readpage(NULL, page); 4560 lock_page(page); 4561 if (page->mapping != mapping) { 4562 unlock_page(page); 4563 put_page(page); 4564 goto again; 4565 } 4566 if (!PageUptodate(page)) { 4567 ret = -EIO; 4568 goto out_unlock; 4569 } 4570 } 4571 wait_on_page_writeback(page); 4572 4573 lock_extent_bits(io_tree, block_start, block_end, &cached_state); 4574 set_page_extent_mapped(page); 4575 4576 ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), block_start); 4577 if (ordered) { 4578 unlock_extent_cached(io_tree, block_start, block_end, 4579 &cached_state); 4580 unlock_page(page); 4581 put_page(page); 4582 btrfs_start_ordered_extent(inode, ordered, 1); 4583 btrfs_put_ordered_extent(ordered); 4584 goto again; 4585 } 4586 4587 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end, 4588 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 4589 0, 0, &cached_state); 4590 4591 ret = btrfs_set_extent_delalloc(BTRFS_I(inode), block_start, block_end, 0, 4592 &cached_state); 4593 if (ret) { 4594 unlock_extent_cached(io_tree, block_start, block_end, 4595 &cached_state); 4596 goto out_unlock; 4597 } 4598 4599 if (offset != blocksize) { 4600 if (!len) 4601 len = blocksize - offset; 4602 kaddr = kmap(page); 4603 if (front) 4604 memset(kaddr + (block_start - page_offset(page)), 4605 0, offset); 4606 else 4607 memset(kaddr + (block_start - page_offset(page)) + offset, 4608 0, len); 4609 flush_dcache_page(page); 4610 kunmap(page); 4611 } 4612 ClearPageChecked(page); 4613 set_page_dirty(page); 4614 unlock_extent_cached(io_tree, block_start, block_end, &cached_state); 4615 4616 if (only_release_metadata) 4617 set_extent_bit(&BTRFS_I(inode)->io_tree, block_start, 4618 block_end, EXTENT_NORESERVE, NULL, NULL, 4619 GFP_NOFS); 4620 4621 out_unlock: 4622 if (ret) { 4623 if (only_release_metadata) 4624 btrfs_delalloc_release_metadata(BTRFS_I(inode), 4625 blocksize, true); 4626 else 4627 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, 4628 block_start, blocksize, true); 4629 } 4630 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize); 4631 unlock_page(page); 4632 put_page(page); 4633 out: 4634 if (only_release_metadata) 4635 btrfs_check_nocow_unlock(BTRFS_I(inode)); 4636 extent_changeset_free(data_reserved); 4637 return ret; 4638 } 4639 4640 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode, 4641 u64 offset, u64 len) 4642 { 4643 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 4644 struct btrfs_trans_handle *trans; 4645 int ret; 4646 4647 /* 4648 * Still need to make sure the inode looks like it's been updated so 4649 * that any holes get logged if we fsync. 4650 */ 4651 if (btrfs_fs_incompat(fs_info, NO_HOLES)) { 4652 BTRFS_I(inode)->last_trans = fs_info->generation; 4653 BTRFS_I(inode)->last_sub_trans = root->log_transid; 4654 BTRFS_I(inode)->last_log_commit = root->last_log_commit; 4655 return 0; 4656 } 4657 4658 /* 4659 * 1 - for the one we're dropping 4660 * 1 - for the one we're adding 4661 * 1 - for updating the inode. 4662 */ 4663 trans = btrfs_start_transaction(root, 3); 4664 if (IS_ERR(trans)) 4665 return PTR_ERR(trans); 4666 4667 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1); 4668 if (ret) { 4669 btrfs_abort_transaction(trans, ret); 4670 btrfs_end_transaction(trans); 4671 return ret; 4672 } 4673 4674 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)), 4675 offset, 0, 0, len, 0, len, 0, 0, 0); 4676 if (ret) 4677 btrfs_abort_transaction(trans, ret); 4678 else 4679 btrfs_update_inode(trans, root, inode); 4680 btrfs_end_transaction(trans); 4681 return ret; 4682 } 4683 4684 /* 4685 * This function puts in dummy file extents for the area we're creating a hole 4686 * for. So if we are truncating this file to a larger size we need to insert 4687 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for 4688 * the range between oldsize and size 4689 */ 4690 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size) 4691 { 4692 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 4693 struct btrfs_root *root = BTRFS_I(inode)->root; 4694 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 4695 struct extent_map *em = NULL; 4696 struct extent_state *cached_state = NULL; 4697 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; 4698 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize); 4699 u64 block_end = ALIGN(size, fs_info->sectorsize); 4700 u64 last_byte; 4701 u64 cur_offset; 4702 u64 hole_size; 4703 int err = 0; 4704 4705 /* 4706 * If our size started in the middle of a block we need to zero out the 4707 * rest of the block before we expand the i_size, otherwise we could 4708 * expose stale data. 4709 */ 4710 err = btrfs_truncate_block(inode, oldsize, 0, 0); 4711 if (err) 4712 return err; 4713 4714 if (size <= hole_start) 4715 return 0; 4716 4717 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start, 4718 block_end - 1, &cached_state); 4719 cur_offset = hole_start; 4720 while (1) { 4721 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset, 4722 block_end - cur_offset); 4723 if (IS_ERR(em)) { 4724 err = PTR_ERR(em); 4725 em = NULL; 4726 break; 4727 } 4728 last_byte = min(extent_map_end(em), block_end); 4729 last_byte = ALIGN(last_byte, fs_info->sectorsize); 4730 hole_size = last_byte - cur_offset; 4731 4732 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { 4733 struct extent_map *hole_em; 4734 4735 err = maybe_insert_hole(root, inode, cur_offset, 4736 hole_size); 4737 if (err) 4738 break; 4739 4740 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode), 4741 cur_offset, hole_size); 4742 if (err) 4743 break; 4744 4745 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset, 4746 cur_offset + hole_size - 1, 0); 4747 hole_em = alloc_extent_map(); 4748 if (!hole_em) { 4749 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, 4750 &BTRFS_I(inode)->runtime_flags); 4751 goto next; 4752 } 4753 hole_em->start = cur_offset; 4754 hole_em->len = hole_size; 4755 hole_em->orig_start = cur_offset; 4756 4757 hole_em->block_start = EXTENT_MAP_HOLE; 4758 hole_em->block_len = 0; 4759 hole_em->orig_block_len = 0; 4760 hole_em->ram_bytes = hole_size; 4761 hole_em->compress_type = BTRFS_COMPRESS_NONE; 4762 hole_em->generation = fs_info->generation; 4763 4764 while (1) { 4765 write_lock(&em_tree->lock); 4766 err = add_extent_mapping(em_tree, hole_em, 1); 4767 write_unlock(&em_tree->lock); 4768 if (err != -EEXIST) 4769 break; 4770 btrfs_drop_extent_cache(BTRFS_I(inode), 4771 cur_offset, 4772 cur_offset + 4773 hole_size - 1, 0); 4774 } 4775 free_extent_map(hole_em); 4776 } else { 4777 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode), 4778 cur_offset, hole_size); 4779 if (err) 4780 break; 4781 } 4782 next: 4783 free_extent_map(em); 4784 em = NULL; 4785 cur_offset = last_byte; 4786 if (cur_offset >= block_end) 4787 break; 4788 } 4789 free_extent_map(em); 4790 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state); 4791 return err; 4792 } 4793 4794 static int btrfs_setsize(struct inode *inode, struct iattr *attr) 4795 { 4796 struct btrfs_root *root = BTRFS_I(inode)->root; 4797 struct btrfs_trans_handle *trans; 4798 loff_t oldsize = i_size_read(inode); 4799 loff_t newsize = attr->ia_size; 4800 int mask = attr->ia_valid; 4801 int ret; 4802 4803 /* 4804 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a 4805 * special case where we need to update the times despite not having 4806 * these flags set. For all other operations the VFS set these flags 4807 * explicitly if it wants a timestamp update. 4808 */ 4809 if (newsize != oldsize) { 4810 inode_inc_iversion(inode); 4811 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) 4812 inode->i_ctime = inode->i_mtime = 4813 current_time(inode); 4814 } 4815 4816 if (newsize > oldsize) { 4817 /* 4818 * Don't do an expanding truncate while snapshotting is ongoing. 4819 * This is to ensure the snapshot captures a fully consistent 4820 * state of this file - if the snapshot captures this expanding 4821 * truncation, it must capture all writes that happened before 4822 * this truncation. 4823 */ 4824 btrfs_drew_write_lock(&root->snapshot_lock); 4825 ret = btrfs_cont_expand(inode, oldsize, newsize); 4826 if (ret) { 4827 btrfs_drew_write_unlock(&root->snapshot_lock); 4828 return ret; 4829 } 4830 4831 trans = btrfs_start_transaction(root, 1); 4832 if (IS_ERR(trans)) { 4833 btrfs_drew_write_unlock(&root->snapshot_lock); 4834 return PTR_ERR(trans); 4835 } 4836 4837 i_size_write(inode, newsize); 4838 btrfs_inode_safe_disk_i_size_write(inode, 0); 4839 pagecache_isize_extended(inode, oldsize, newsize); 4840 ret = btrfs_update_inode(trans, root, inode); 4841 btrfs_drew_write_unlock(&root->snapshot_lock); 4842 btrfs_end_transaction(trans); 4843 } else { 4844 4845 /* 4846 * We're truncating a file that used to have good data down to 4847 * zero. Make sure it gets into the ordered flush list so that 4848 * any new writes get down to disk quickly. 4849 */ 4850 if (newsize == 0) 4851 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, 4852 &BTRFS_I(inode)->runtime_flags); 4853 4854 truncate_setsize(inode, newsize); 4855 4856 /* Disable nonlocked read DIO to avoid the endless truncate */ 4857 btrfs_inode_block_unlocked_dio(BTRFS_I(inode)); 4858 inode_dio_wait(inode); 4859 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode)); 4860 4861 ret = btrfs_truncate(inode, newsize == oldsize); 4862 if (ret && inode->i_nlink) { 4863 int err; 4864 4865 /* 4866 * Truncate failed, so fix up the in-memory size. We 4867 * adjusted disk_i_size down as we removed extents, so 4868 * wait for disk_i_size to be stable and then update the 4869 * in-memory size to match. 4870 */ 4871 err = btrfs_wait_ordered_range(inode, 0, (u64)-1); 4872 if (err) 4873 return err; 4874 i_size_write(inode, BTRFS_I(inode)->disk_i_size); 4875 } 4876 } 4877 4878 return ret; 4879 } 4880 4881 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr) 4882 { 4883 struct inode *inode = d_inode(dentry); 4884 struct btrfs_root *root = BTRFS_I(inode)->root; 4885 int err; 4886 4887 if (btrfs_root_readonly(root)) 4888 return -EROFS; 4889 4890 err = setattr_prepare(dentry, attr); 4891 if (err) 4892 return err; 4893 4894 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { 4895 err = btrfs_setsize(inode, attr); 4896 if (err) 4897 return err; 4898 } 4899 4900 if (attr->ia_valid) { 4901 setattr_copy(inode, attr); 4902 inode_inc_iversion(inode); 4903 err = btrfs_dirty_inode(inode); 4904 4905 if (!err && attr->ia_valid & ATTR_MODE) 4906 err = posix_acl_chmod(inode, inode->i_mode); 4907 } 4908 4909 return err; 4910 } 4911 4912 /* 4913 * While truncating the inode pages during eviction, we get the VFS calling 4914 * btrfs_invalidatepage() against each page of the inode. This is slow because 4915 * the calls to btrfs_invalidatepage() result in a huge amount of calls to 4916 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting 4917 * extent_state structures over and over, wasting lots of time. 4918 * 4919 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all 4920 * those expensive operations on a per page basis and do only the ordered io 4921 * finishing, while we release here the extent_map and extent_state structures, 4922 * without the excessive merging and splitting. 4923 */ 4924 static void evict_inode_truncate_pages(struct inode *inode) 4925 { 4926 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 4927 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree; 4928 struct rb_node *node; 4929 4930 ASSERT(inode->i_state & I_FREEING); 4931 truncate_inode_pages_final(&inode->i_data); 4932 4933 write_lock(&map_tree->lock); 4934 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) { 4935 struct extent_map *em; 4936 4937 node = rb_first_cached(&map_tree->map); 4938 em = rb_entry(node, struct extent_map, rb_node); 4939 clear_bit(EXTENT_FLAG_PINNED, &em->flags); 4940 clear_bit(EXTENT_FLAG_LOGGING, &em->flags); 4941 remove_extent_mapping(map_tree, em); 4942 free_extent_map(em); 4943 if (need_resched()) { 4944 write_unlock(&map_tree->lock); 4945 cond_resched(); 4946 write_lock(&map_tree->lock); 4947 } 4948 } 4949 write_unlock(&map_tree->lock); 4950 4951 /* 4952 * Keep looping until we have no more ranges in the io tree. 4953 * We can have ongoing bios started by readahead that have 4954 * their endio callback (extent_io.c:end_bio_extent_readpage) 4955 * still in progress (unlocked the pages in the bio but did not yet 4956 * unlocked the ranges in the io tree). Therefore this means some 4957 * ranges can still be locked and eviction started because before 4958 * submitting those bios, which are executed by a separate task (work 4959 * queue kthread), inode references (inode->i_count) were not taken 4960 * (which would be dropped in the end io callback of each bio). 4961 * Therefore here we effectively end up waiting for those bios and 4962 * anyone else holding locked ranges without having bumped the inode's 4963 * reference count - if we don't do it, when they access the inode's 4964 * io_tree to unlock a range it may be too late, leading to an 4965 * use-after-free issue. 4966 */ 4967 spin_lock(&io_tree->lock); 4968 while (!RB_EMPTY_ROOT(&io_tree->state)) { 4969 struct extent_state *state; 4970 struct extent_state *cached_state = NULL; 4971 u64 start; 4972 u64 end; 4973 unsigned state_flags; 4974 4975 node = rb_first(&io_tree->state); 4976 state = rb_entry(node, struct extent_state, rb_node); 4977 start = state->start; 4978 end = state->end; 4979 state_flags = state->state; 4980 spin_unlock(&io_tree->lock); 4981 4982 lock_extent_bits(io_tree, start, end, &cached_state); 4983 4984 /* 4985 * If still has DELALLOC flag, the extent didn't reach disk, 4986 * and its reserved space won't be freed by delayed_ref. 4987 * So we need to free its reserved space here. 4988 * (Refer to comment in btrfs_invalidatepage, case 2) 4989 * 4990 * Note, end is the bytenr of last byte, so we need + 1 here. 4991 */ 4992 if (state_flags & EXTENT_DELALLOC) 4993 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start, 4994 end - start + 1); 4995 4996 clear_extent_bit(io_tree, start, end, 4997 EXTENT_LOCKED | EXTENT_DELALLOC | 4998 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, 4999 &cached_state); 5000 5001 cond_resched(); 5002 spin_lock(&io_tree->lock); 5003 } 5004 spin_unlock(&io_tree->lock); 5005 } 5006 5007 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root, 5008 struct btrfs_block_rsv *rsv) 5009 { 5010 struct btrfs_fs_info *fs_info = root->fs_info; 5011 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv; 5012 struct btrfs_trans_handle *trans; 5013 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1); 5014 int ret; 5015 5016 /* 5017 * Eviction should be taking place at some place safe because of our 5018 * delayed iputs. However the normal flushing code will run delayed 5019 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock. 5020 * 5021 * We reserve the delayed_refs_extra here again because we can't use 5022 * btrfs_start_transaction(root, 0) for the same deadlocky reason as 5023 * above. We reserve our extra bit here because we generate a ton of 5024 * delayed refs activity by truncating. 5025 * 5026 * If we cannot make our reservation we'll attempt to steal from the 5027 * global reserve, because we really want to be able to free up space. 5028 */ 5029 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra, 5030 BTRFS_RESERVE_FLUSH_EVICT); 5031 if (ret) { 5032 /* 5033 * Try to steal from the global reserve if there is space for 5034 * it. 5035 */ 5036 if (btrfs_check_space_for_delayed_refs(fs_info) || 5037 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) { 5038 btrfs_warn(fs_info, 5039 "could not allocate space for delete; will truncate on mount"); 5040 return ERR_PTR(-ENOSPC); 5041 } 5042 delayed_refs_extra = 0; 5043 } 5044 5045 trans = btrfs_join_transaction(root); 5046 if (IS_ERR(trans)) 5047 return trans; 5048 5049 if (delayed_refs_extra) { 5050 trans->block_rsv = &fs_info->trans_block_rsv; 5051 trans->bytes_reserved = delayed_refs_extra; 5052 btrfs_block_rsv_migrate(rsv, trans->block_rsv, 5053 delayed_refs_extra, 1); 5054 } 5055 return trans; 5056 } 5057 5058 void btrfs_evict_inode(struct inode *inode) 5059 { 5060 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 5061 struct btrfs_trans_handle *trans; 5062 struct btrfs_root *root = BTRFS_I(inode)->root; 5063 struct btrfs_block_rsv *rsv; 5064 int ret; 5065 5066 trace_btrfs_inode_evict(inode); 5067 5068 if (!root) { 5069 clear_inode(inode); 5070 return; 5071 } 5072 5073 evict_inode_truncate_pages(inode); 5074 5075 if (inode->i_nlink && 5076 ((btrfs_root_refs(&root->root_item) != 0 && 5077 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) || 5078 btrfs_is_free_space_inode(BTRFS_I(inode)))) 5079 goto no_delete; 5080 5081 if (is_bad_inode(inode)) 5082 goto no_delete; 5083 5084 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1); 5085 5086 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) 5087 goto no_delete; 5088 5089 if (inode->i_nlink > 0) { 5090 BUG_ON(btrfs_root_refs(&root->root_item) != 0 && 5091 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID); 5092 goto no_delete; 5093 } 5094 5095 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode)); 5096 if (ret) 5097 goto no_delete; 5098 5099 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP); 5100 if (!rsv) 5101 goto no_delete; 5102 rsv->size = btrfs_calc_metadata_size(fs_info, 1); 5103 rsv->failfast = 1; 5104 5105 btrfs_i_size_write(BTRFS_I(inode), 0); 5106 5107 while (1) { 5108 trans = evict_refill_and_join(root, rsv); 5109 if (IS_ERR(trans)) 5110 goto free_rsv; 5111 5112 trans->block_rsv = rsv; 5113 5114 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0); 5115 trans->block_rsv = &fs_info->trans_block_rsv; 5116 btrfs_end_transaction(trans); 5117 btrfs_btree_balance_dirty(fs_info); 5118 if (ret && ret != -ENOSPC && ret != -EAGAIN) 5119 goto free_rsv; 5120 else if (!ret) 5121 break; 5122 } 5123 5124 /* 5125 * Errors here aren't a big deal, it just means we leave orphan items in 5126 * the tree. They will be cleaned up on the next mount. If the inode 5127 * number gets reused, cleanup deletes the orphan item without doing 5128 * anything, and unlink reuses the existing orphan item. 5129 * 5130 * If it turns out that we are dropping too many of these, we might want 5131 * to add a mechanism for retrying these after a commit. 5132 */ 5133 trans = evict_refill_and_join(root, rsv); 5134 if (!IS_ERR(trans)) { 5135 trans->block_rsv = rsv; 5136 btrfs_orphan_del(trans, BTRFS_I(inode)); 5137 trans->block_rsv = &fs_info->trans_block_rsv; 5138 btrfs_end_transaction(trans); 5139 } 5140 5141 if (!(root == fs_info->tree_root || 5142 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)) 5143 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode))); 5144 5145 free_rsv: 5146 btrfs_free_block_rsv(fs_info, rsv); 5147 no_delete: 5148 /* 5149 * If we didn't successfully delete, the orphan item will still be in 5150 * the tree and we'll retry on the next mount. Again, we might also want 5151 * to retry these periodically in the future. 5152 */ 5153 btrfs_remove_delayed_node(BTRFS_I(inode)); 5154 clear_inode(inode); 5155 } 5156 5157 /* 5158 * Return the key found in the dir entry in the location pointer, fill @type 5159 * with BTRFS_FT_*, and return 0. 5160 * 5161 * If no dir entries were found, returns -ENOENT. 5162 * If found a corrupted location in dir entry, returns -EUCLEAN. 5163 */ 5164 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry, 5165 struct btrfs_key *location, u8 *type) 5166 { 5167 const char *name = dentry->d_name.name; 5168 int namelen = dentry->d_name.len; 5169 struct btrfs_dir_item *di; 5170 struct btrfs_path *path; 5171 struct btrfs_root *root = BTRFS_I(dir)->root; 5172 int ret = 0; 5173 5174 path = btrfs_alloc_path(); 5175 if (!path) 5176 return -ENOMEM; 5177 5178 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)), 5179 name, namelen, 0); 5180 if (IS_ERR_OR_NULL(di)) { 5181 ret = di ? PTR_ERR(di) : -ENOENT; 5182 goto out; 5183 } 5184 5185 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location); 5186 if (location->type != BTRFS_INODE_ITEM_KEY && 5187 location->type != BTRFS_ROOT_ITEM_KEY) { 5188 ret = -EUCLEAN; 5189 btrfs_warn(root->fs_info, 5190 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))", 5191 __func__, name, btrfs_ino(BTRFS_I(dir)), 5192 location->objectid, location->type, location->offset); 5193 } 5194 if (!ret) 5195 *type = btrfs_dir_type(path->nodes[0], di); 5196 out: 5197 btrfs_free_path(path); 5198 return ret; 5199 } 5200 5201 /* 5202 * when we hit a tree root in a directory, the btrfs part of the inode 5203 * needs to be changed to reflect the root directory of the tree root. This 5204 * is kind of like crossing a mount point. 5205 */ 5206 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info, 5207 struct inode *dir, 5208 struct dentry *dentry, 5209 struct btrfs_key *location, 5210 struct btrfs_root **sub_root) 5211 { 5212 struct btrfs_path *path; 5213 struct btrfs_root *new_root; 5214 struct btrfs_root_ref *ref; 5215 struct extent_buffer *leaf; 5216 struct btrfs_key key; 5217 int ret; 5218 int err = 0; 5219 5220 path = btrfs_alloc_path(); 5221 if (!path) { 5222 err = -ENOMEM; 5223 goto out; 5224 } 5225 5226 err = -ENOENT; 5227 key.objectid = BTRFS_I(dir)->root->root_key.objectid; 5228 key.type = BTRFS_ROOT_REF_KEY; 5229 key.offset = location->objectid; 5230 5231 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0); 5232 if (ret) { 5233 if (ret < 0) 5234 err = ret; 5235 goto out; 5236 } 5237 5238 leaf = path->nodes[0]; 5239 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref); 5240 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) || 5241 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len) 5242 goto out; 5243 5244 ret = memcmp_extent_buffer(leaf, dentry->d_name.name, 5245 (unsigned long)(ref + 1), 5246 dentry->d_name.len); 5247 if (ret) 5248 goto out; 5249 5250 btrfs_release_path(path); 5251 5252 new_root = btrfs_get_fs_root(fs_info, location->objectid, true); 5253 if (IS_ERR(new_root)) { 5254 err = PTR_ERR(new_root); 5255 goto out; 5256 } 5257 5258 *sub_root = new_root; 5259 location->objectid = btrfs_root_dirid(&new_root->root_item); 5260 location->type = BTRFS_INODE_ITEM_KEY; 5261 location->offset = 0; 5262 err = 0; 5263 out: 5264 btrfs_free_path(path); 5265 return err; 5266 } 5267 5268 static void inode_tree_add(struct inode *inode) 5269 { 5270 struct btrfs_root *root = BTRFS_I(inode)->root; 5271 struct btrfs_inode *entry; 5272 struct rb_node **p; 5273 struct rb_node *parent; 5274 struct rb_node *new = &BTRFS_I(inode)->rb_node; 5275 u64 ino = btrfs_ino(BTRFS_I(inode)); 5276 5277 if (inode_unhashed(inode)) 5278 return; 5279 parent = NULL; 5280 spin_lock(&root->inode_lock); 5281 p = &root->inode_tree.rb_node; 5282 while (*p) { 5283 parent = *p; 5284 entry = rb_entry(parent, struct btrfs_inode, rb_node); 5285 5286 if (ino < btrfs_ino(entry)) 5287 p = &parent->rb_left; 5288 else if (ino > btrfs_ino(entry)) 5289 p = &parent->rb_right; 5290 else { 5291 WARN_ON(!(entry->vfs_inode.i_state & 5292 (I_WILL_FREE | I_FREEING))); 5293 rb_replace_node(parent, new, &root->inode_tree); 5294 RB_CLEAR_NODE(parent); 5295 spin_unlock(&root->inode_lock); 5296 return; 5297 } 5298 } 5299 rb_link_node(new, parent, p); 5300 rb_insert_color(new, &root->inode_tree); 5301 spin_unlock(&root->inode_lock); 5302 } 5303 5304 static void inode_tree_del(struct inode *inode) 5305 { 5306 struct btrfs_root *root = BTRFS_I(inode)->root; 5307 int empty = 0; 5308 5309 spin_lock(&root->inode_lock); 5310 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) { 5311 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree); 5312 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node); 5313 empty = RB_EMPTY_ROOT(&root->inode_tree); 5314 } 5315 spin_unlock(&root->inode_lock); 5316 5317 if (empty && btrfs_root_refs(&root->root_item) == 0) { 5318 spin_lock(&root->inode_lock); 5319 empty = RB_EMPTY_ROOT(&root->inode_tree); 5320 spin_unlock(&root->inode_lock); 5321 if (empty) 5322 btrfs_add_dead_root(root); 5323 } 5324 } 5325 5326 5327 static int btrfs_init_locked_inode(struct inode *inode, void *p) 5328 { 5329 struct btrfs_iget_args *args = p; 5330 5331 inode->i_ino = args->ino; 5332 BTRFS_I(inode)->location.objectid = args->ino; 5333 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY; 5334 BTRFS_I(inode)->location.offset = 0; 5335 BTRFS_I(inode)->root = btrfs_grab_root(args->root); 5336 BUG_ON(args->root && !BTRFS_I(inode)->root); 5337 return 0; 5338 } 5339 5340 static int btrfs_find_actor(struct inode *inode, void *opaque) 5341 { 5342 struct btrfs_iget_args *args = opaque; 5343 5344 return args->ino == BTRFS_I(inode)->location.objectid && 5345 args->root == BTRFS_I(inode)->root; 5346 } 5347 5348 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino, 5349 struct btrfs_root *root) 5350 { 5351 struct inode *inode; 5352 struct btrfs_iget_args args; 5353 unsigned long hashval = btrfs_inode_hash(ino, root); 5354 5355 args.ino = ino; 5356 args.root = root; 5357 5358 inode = iget5_locked(s, hashval, btrfs_find_actor, 5359 btrfs_init_locked_inode, 5360 (void *)&args); 5361 return inode; 5362 } 5363 5364 /* 5365 * Get an inode object given its inode number and corresponding root. 5366 * Path can be preallocated to prevent recursing back to iget through 5367 * allocator. NULL is also valid but may require an additional allocation 5368 * later. 5369 */ 5370 struct inode *btrfs_iget_path(struct super_block *s, u64 ino, 5371 struct btrfs_root *root, struct btrfs_path *path) 5372 { 5373 struct inode *inode; 5374 5375 inode = btrfs_iget_locked(s, ino, root); 5376 if (!inode) 5377 return ERR_PTR(-ENOMEM); 5378 5379 if (inode->i_state & I_NEW) { 5380 int ret; 5381 5382 ret = btrfs_read_locked_inode(inode, path); 5383 if (!ret) { 5384 inode_tree_add(inode); 5385 unlock_new_inode(inode); 5386 } else { 5387 iget_failed(inode); 5388 /* 5389 * ret > 0 can come from btrfs_search_slot called by 5390 * btrfs_read_locked_inode, this means the inode item 5391 * was not found. 5392 */ 5393 if (ret > 0) 5394 ret = -ENOENT; 5395 inode = ERR_PTR(ret); 5396 } 5397 } 5398 5399 return inode; 5400 } 5401 5402 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root) 5403 { 5404 return btrfs_iget_path(s, ino, root, NULL); 5405 } 5406 5407 static struct inode *new_simple_dir(struct super_block *s, 5408 struct btrfs_key *key, 5409 struct btrfs_root *root) 5410 { 5411 struct inode *inode = new_inode(s); 5412 5413 if (!inode) 5414 return ERR_PTR(-ENOMEM); 5415 5416 BTRFS_I(inode)->root = btrfs_grab_root(root); 5417 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key)); 5418 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags); 5419 5420 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID; 5421 /* 5422 * We only need lookup, the rest is read-only and there's no inode 5423 * associated with the dentry 5424 */ 5425 inode->i_op = &simple_dir_inode_operations; 5426 inode->i_opflags &= ~IOP_XATTR; 5427 inode->i_fop = &simple_dir_operations; 5428 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO; 5429 inode->i_mtime = current_time(inode); 5430 inode->i_atime = inode->i_mtime; 5431 inode->i_ctime = inode->i_mtime; 5432 BTRFS_I(inode)->i_otime = inode->i_mtime; 5433 5434 return inode; 5435 } 5436 5437 static inline u8 btrfs_inode_type(struct inode *inode) 5438 { 5439 /* 5440 * Compile-time asserts that generic FT_* types still match 5441 * BTRFS_FT_* types 5442 */ 5443 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN); 5444 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE); 5445 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR); 5446 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV); 5447 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV); 5448 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO); 5449 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK); 5450 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK); 5451 5452 return fs_umode_to_ftype(inode->i_mode); 5453 } 5454 5455 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry) 5456 { 5457 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 5458 struct inode *inode; 5459 struct btrfs_root *root = BTRFS_I(dir)->root; 5460 struct btrfs_root *sub_root = root; 5461 struct btrfs_key location; 5462 u8 di_type = 0; 5463 int ret = 0; 5464 5465 if (dentry->d_name.len > BTRFS_NAME_LEN) 5466 return ERR_PTR(-ENAMETOOLONG); 5467 5468 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type); 5469 if (ret < 0) 5470 return ERR_PTR(ret); 5471 5472 if (location.type == BTRFS_INODE_ITEM_KEY) { 5473 inode = btrfs_iget(dir->i_sb, location.objectid, root); 5474 if (IS_ERR(inode)) 5475 return inode; 5476 5477 /* Do extra check against inode mode with di_type */ 5478 if (btrfs_inode_type(inode) != di_type) { 5479 btrfs_crit(fs_info, 5480 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u", 5481 inode->i_mode, btrfs_inode_type(inode), 5482 di_type); 5483 iput(inode); 5484 return ERR_PTR(-EUCLEAN); 5485 } 5486 return inode; 5487 } 5488 5489 ret = fixup_tree_root_location(fs_info, dir, dentry, 5490 &location, &sub_root); 5491 if (ret < 0) { 5492 if (ret != -ENOENT) 5493 inode = ERR_PTR(ret); 5494 else 5495 inode = new_simple_dir(dir->i_sb, &location, sub_root); 5496 } else { 5497 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root); 5498 } 5499 if (root != sub_root) 5500 btrfs_put_root(sub_root); 5501 5502 if (!IS_ERR(inode) && root != sub_root) { 5503 down_read(&fs_info->cleanup_work_sem); 5504 if (!sb_rdonly(inode->i_sb)) 5505 ret = btrfs_orphan_cleanup(sub_root); 5506 up_read(&fs_info->cleanup_work_sem); 5507 if (ret) { 5508 iput(inode); 5509 inode = ERR_PTR(ret); 5510 } 5511 } 5512 5513 return inode; 5514 } 5515 5516 static int btrfs_dentry_delete(const struct dentry *dentry) 5517 { 5518 struct btrfs_root *root; 5519 struct inode *inode = d_inode(dentry); 5520 5521 if (!inode && !IS_ROOT(dentry)) 5522 inode = d_inode(dentry->d_parent); 5523 5524 if (inode) { 5525 root = BTRFS_I(inode)->root; 5526 if (btrfs_root_refs(&root->root_item) == 0) 5527 return 1; 5528 5529 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) 5530 return 1; 5531 } 5532 return 0; 5533 } 5534 5535 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry, 5536 unsigned int flags) 5537 { 5538 struct inode *inode = btrfs_lookup_dentry(dir, dentry); 5539 5540 if (inode == ERR_PTR(-ENOENT)) 5541 inode = NULL; 5542 return d_splice_alias(inode, dentry); 5543 } 5544 5545 /* 5546 * All this infrastructure exists because dir_emit can fault, and we are holding 5547 * the tree lock when doing readdir. For now just allocate a buffer and copy 5548 * our information into that, and then dir_emit from the buffer. This is 5549 * similar to what NFS does, only we don't keep the buffer around in pagecache 5550 * because I'm afraid I'll mess that up. Long term we need to make filldir do 5551 * copy_to_user_inatomic so we don't have to worry about page faulting under the 5552 * tree lock. 5553 */ 5554 static int btrfs_opendir(struct inode *inode, struct file *file) 5555 { 5556 struct btrfs_file_private *private; 5557 5558 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL); 5559 if (!private) 5560 return -ENOMEM; 5561 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL); 5562 if (!private->filldir_buf) { 5563 kfree(private); 5564 return -ENOMEM; 5565 } 5566 file->private_data = private; 5567 return 0; 5568 } 5569 5570 struct dir_entry { 5571 u64 ino; 5572 u64 offset; 5573 unsigned type; 5574 int name_len; 5575 }; 5576 5577 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx) 5578 { 5579 while (entries--) { 5580 struct dir_entry *entry = addr; 5581 char *name = (char *)(entry + 1); 5582 5583 ctx->pos = get_unaligned(&entry->offset); 5584 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len), 5585 get_unaligned(&entry->ino), 5586 get_unaligned(&entry->type))) 5587 return 1; 5588 addr += sizeof(struct dir_entry) + 5589 get_unaligned(&entry->name_len); 5590 ctx->pos++; 5591 } 5592 return 0; 5593 } 5594 5595 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx) 5596 { 5597 struct inode *inode = file_inode(file); 5598 struct btrfs_root *root = BTRFS_I(inode)->root; 5599 struct btrfs_file_private *private = file->private_data; 5600 struct btrfs_dir_item *di; 5601 struct btrfs_key key; 5602 struct btrfs_key found_key; 5603 struct btrfs_path *path; 5604 void *addr; 5605 struct list_head ins_list; 5606 struct list_head del_list; 5607 int ret; 5608 struct extent_buffer *leaf; 5609 int slot; 5610 char *name_ptr; 5611 int name_len; 5612 int entries = 0; 5613 int total_len = 0; 5614 bool put = false; 5615 struct btrfs_key location; 5616 5617 if (!dir_emit_dots(file, ctx)) 5618 return 0; 5619 5620 path = btrfs_alloc_path(); 5621 if (!path) 5622 return -ENOMEM; 5623 5624 addr = private->filldir_buf; 5625 path->reada = READA_FORWARD; 5626 5627 INIT_LIST_HEAD(&ins_list); 5628 INIT_LIST_HEAD(&del_list); 5629 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list); 5630 5631 again: 5632 key.type = BTRFS_DIR_INDEX_KEY; 5633 key.offset = ctx->pos; 5634 key.objectid = btrfs_ino(BTRFS_I(inode)); 5635 5636 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 5637 if (ret < 0) 5638 goto err; 5639 5640 while (1) { 5641 struct dir_entry *entry; 5642 5643 leaf = path->nodes[0]; 5644 slot = path->slots[0]; 5645 if (slot >= btrfs_header_nritems(leaf)) { 5646 ret = btrfs_next_leaf(root, path); 5647 if (ret < 0) 5648 goto err; 5649 else if (ret > 0) 5650 break; 5651 continue; 5652 } 5653 5654 btrfs_item_key_to_cpu(leaf, &found_key, slot); 5655 5656 if (found_key.objectid != key.objectid) 5657 break; 5658 if (found_key.type != BTRFS_DIR_INDEX_KEY) 5659 break; 5660 if (found_key.offset < ctx->pos) 5661 goto next; 5662 if (btrfs_should_delete_dir_index(&del_list, found_key.offset)) 5663 goto next; 5664 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item); 5665 name_len = btrfs_dir_name_len(leaf, di); 5666 if ((total_len + sizeof(struct dir_entry) + name_len) >= 5667 PAGE_SIZE) { 5668 btrfs_release_path(path); 5669 ret = btrfs_filldir(private->filldir_buf, entries, ctx); 5670 if (ret) 5671 goto nopos; 5672 addr = private->filldir_buf; 5673 entries = 0; 5674 total_len = 0; 5675 goto again; 5676 } 5677 5678 entry = addr; 5679 put_unaligned(name_len, &entry->name_len); 5680 name_ptr = (char *)(entry + 1); 5681 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1), 5682 name_len); 5683 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)), 5684 &entry->type); 5685 btrfs_dir_item_key_to_cpu(leaf, di, &location); 5686 put_unaligned(location.objectid, &entry->ino); 5687 put_unaligned(found_key.offset, &entry->offset); 5688 entries++; 5689 addr += sizeof(struct dir_entry) + name_len; 5690 total_len += sizeof(struct dir_entry) + name_len; 5691 next: 5692 path->slots[0]++; 5693 } 5694 btrfs_release_path(path); 5695 5696 ret = btrfs_filldir(private->filldir_buf, entries, ctx); 5697 if (ret) 5698 goto nopos; 5699 5700 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list); 5701 if (ret) 5702 goto nopos; 5703 5704 /* 5705 * Stop new entries from being returned after we return the last 5706 * entry. 5707 * 5708 * New directory entries are assigned a strictly increasing 5709 * offset. This means that new entries created during readdir 5710 * are *guaranteed* to be seen in the future by that readdir. 5711 * This has broken buggy programs which operate on names as 5712 * they're returned by readdir. Until we re-use freed offsets 5713 * we have this hack to stop new entries from being returned 5714 * under the assumption that they'll never reach this huge 5715 * offset. 5716 * 5717 * This is being careful not to overflow 32bit loff_t unless the 5718 * last entry requires it because doing so has broken 32bit apps 5719 * in the past. 5720 */ 5721 if (ctx->pos >= INT_MAX) 5722 ctx->pos = LLONG_MAX; 5723 else 5724 ctx->pos = INT_MAX; 5725 nopos: 5726 ret = 0; 5727 err: 5728 if (put) 5729 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list); 5730 btrfs_free_path(path); 5731 return ret; 5732 } 5733 5734 /* 5735 * This is somewhat expensive, updating the tree every time the 5736 * inode changes. But, it is most likely to find the inode in cache. 5737 * FIXME, needs more benchmarking...there are no reasons other than performance 5738 * to keep or drop this code. 5739 */ 5740 static int btrfs_dirty_inode(struct inode *inode) 5741 { 5742 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 5743 struct btrfs_root *root = BTRFS_I(inode)->root; 5744 struct btrfs_trans_handle *trans; 5745 int ret; 5746 5747 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) 5748 return 0; 5749 5750 trans = btrfs_join_transaction(root); 5751 if (IS_ERR(trans)) 5752 return PTR_ERR(trans); 5753 5754 ret = btrfs_update_inode(trans, root, inode); 5755 if (ret && ret == -ENOSPC) { 5756 /* whoops, lets try again with the full transaction */ 5757 btrfs_end_transaction(trans); 5758 trans = btrfs_start_transaction(root, 1); 5759 if (IS_ERR(trans)) 5760 return PTR_ERR(trans); 5761 5762 ret = btrfs_update_inode(trans, root, inode); 5763 } 5764 btrfs_end_transaction(trans); 5765 if (BTRFS_I(inode)->delayed_node) 5766 btrfs_balance_delayed_items(fs_info); 5767 5768 return ret; 5769 } 5770 5771 /* 5772 * This is a copy of file_update_time. We need this so we can return error on 5773 * ENOSPC for updating the inode in the case of file write and mmap writes. 5774 */ 5775 static int btrfs_update_time(struct inode *inode, struct timespec64 *now, 5776 int flags) 5777 { 5778 struct btrfs_root *root = BTRFS_I(inode)->root; 5779 bool dirty = flags & ~S_VERSION; 5780 5781 if (btrfs_root_readonly(root)) 5782 return -EROFS; 5783 5784 if (flags & S_VERSION) 5785 dirty |= inode_maybe_inc_iversion(inode, dirty); 5786 if (flags & S_CTIME) 5787 inode->i_ctime = *now; 5788 if (flags & S_MTIME) 5789 inode->i_mtime = *now; 5790 if (flags & S_ATIME) 5791 inode->i_atime = *now; 5792 return dirty ? btrfs_dirty_inode(inode) : 0; 5793 } 5794 5795 /* 5796 * find the highest existing sequence number in a directory 5797 * and then set the in-memory index_cnt variable to reflect 5798 * free sequence numbers 5799 */ 5800 static int btrfs_set_inode_index_count(struct btrfs_inode *inode) 5801 { 5802 struct btrfs_root *root = inode->root; 5803 struct btrfs_key key, found_key; 5804 struct btrfs_path *path; 5805 struct extent_buffer *leaf; 5806 int ret; 5807 5808 key.objectid = btrfs_ino(inode); 5809 key.type = BTRFS_DIR_INDEX_KEY; 5810 key.offset = (u64)-1; 5811 5812 path = btrfs_alloc_path(); 5813 if (!path) 5814 return -ENOMEM; 5815 5816 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 5817 if (ret < 0) 5818 goto out; 5819 /* FIXME: we should be able to handle this */ 5820 if (ret == 0) 5821 goto out; 5822 ret = 0; 5823 5824 /* 5825 * MAGIC NUMBER EXPLANATION: 5826 * since we search a directory based on f_pos we have to start at 2 5827 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody 5828 * else has to start at 2 5829 */ 5830 if (path->slots[0] == 0) { 5831 inode->index_cnt = 2; 5832 goto out; 5833 } 5834 5835 path->slots[0]--; 5836 5837 leaf = path->nodes[0]; 5838 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 5839 5840 if (found_key.objectid != btrfs_ino(inode) || 5841 found_key.type != BTRFS_DIR_INDEX_KEY) { 5842 inode->index_cnt = 2; 5843 goto out; 5844 } 5845 5846 inode->index_cnt = found_key.offset + 1; 5847 out: 5848 btrfs_free_path(path); 5849 return ret; 5850 } 5851 5852 /* 5853 * helper to find a free sequence number in a given directory. This current 5854 * code is very simple, later versions will do smarter things in the btree 5855 */ 5856 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index) 5857 { 5858 int ret = 0; 5859 5860 if (dir->index_cnt == (u64)-1) { 5861 ret = btrfs_inode_delayed_dir_index_count(dir); 5862 if (ret) { 5863 ret = btrfs_set_inode_index_count(dir); 5864 if (ret) 5865 return ret; 5866 } 5867 } 5868 5869 *index = dir->index_cnt; 5870 dir->index_cnt++; 5871 5872 return ret; 5873 } 5874 5875 static int btrfs_insert_inode_locked(struct inode *inode) 5876 { 5877 struct btrfs_iget_args args; 5878 5879 args.ino = BTRFS_I(inode)->location.objectid; 5880 args.root = BTRFS_I(inode)->root; 5881 5882 return insert_inode_locked4(inode, 5883 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root), 5884 btrfs_find_actor, &args); 5885 } 5886 5887 /* 5888 * Inherit flags from the parent inode. 5889 * 5890 * Currently only the compression flags and the cow flags are inherited. 5891 */ 5892 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir) 5893 { 5894 unsigned int flags; 5895 5896 if (!dir) 5897 return; 5898 5899 flags = BTRFS_I(dir)->flags; 5900 5901 if (flags & BTRFS_INODE_NOCOMPRESS) { 5902 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS; 5903 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; 5904 } else if (flags & BTRFS_INODE_COMPRESS) { 5905 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS; 5906 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS; 5907 } 5908 5909 if (flags & BTRFS_INODE_NODATACOW) { 5910 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW; 5911 if (S_ISREG(inode->i_mode)) 5912 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; 5913 } 5914 5915 btrfs_sync_inode_flags_to_i_flags(inode); 5916 } 5917 5918 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans, 5919 struct btrfs_root *root, 5920 struct inode *dir, 5921 const char *name, int name_len, 5922 u64 ref_objectid, u64 objectid, 5923 umode_t mode, u64 *index) 5924 { 5925 struct btrfs_fs_info *fs_info = root->fs_info; 5926 struct inode *inode; 5927 struct btrfs_inode_item *inode_item; 5928 struct btrfs_key *location; 5929 struct btrfs_path *path; 5930 struct btrfs_inode_ref *ref; 5931 struct btrfs_key key[2]; 5932 u32 sizes[2]; 5933 int nitems = name ? 2 : 1; 5934 unsigned long ptr; 5935 unsigned int nofs_flag; 5936 int ret; 5937 5938 path = btrfs_alloc_path(); 5939 if (!path) 5940 return ERR_PTR(-ENOMEM); 5941 5942 nofs_flag = memalloc_nofs_save(); 5943 inode = new_inode(fs_info->sb); 5944 memalloc_nofs_restore(nofs_flag); 5945 if (!inode) { 5946 btrfs_free_path(path); 5947 return ERR_PTR(-ENOMEM); 5948 } 5949 5950 /* 5951 * O_TMPFILE, set link count to 0, so that after this point, 5952 * we fill in an inode item with the correct link count. 5953 */ 5954 if (!name) 5955 set_nlink(inode, 0); 5956 5957 /* 5958 * we have to initialize this early, so we can reclaim the inode 5959 * number if we fail afterwards in this function. 5960 */ 5961 inode->i_ino = objectid; 5962 5963 if (dir && name) { 5964 trace_btrfs_inode_request(dir); 5965 5966 ret = btrfs_set_inode_index(BTRFS_I(dir), index); 5967 if (ret) { 5968 btrfs_free_path(path); 5969 iput(inode); 5970 return ERR_PTR(ret); 5971 } 5972 } else if (dir) { 5973 *index = 0; 5974 } 5975 /* 5976 * index_cnt is ignored for everything but a dir, 5977 * btrfs_set_inode_index_count has an explanation for the magic 5978 * number 5979 */ 5980 BTRFS_I(inode)->index_cnt = 2; 5981 BTRFS_I(inode)->dir_index = *index; 5982 BTRFS_I(inode)->root = btrfs_grab_root(root); 5983 BTRFS_I(inode)->generation = trans->transid; 5984 inode->i_generation = BTRFS_I(inode)->generation; 5985 5986 /* 5987 * We could have gotten an inode number from somebody who was fsynced 5988 * and then removed in this same transaction, so let's just set full 5989 * sync since it will be a full sync anyway and this will blow away the 5990 * old info in the log. 5991 */ 5992 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); 5993 5994 key[0].objectid = objectid; 5995 key[0].type = BTRFS_INODE_ITEM_KEY; 5996 key[0].offset = 0; 5997 5998 sizes[0] = sizeof(struct btrfs_inode_item); 5999 6000 if (name) { 6001 /* 6002 * Start new inodes with an inode_ref. This is slightly more 6003 * efficient for small numbers of hard links since they will 6004 * be packed into one item. Extended refs will kick in if we 6005 * add more hard links than can fit in the ref item. 6006 */ 6007 key[1].objectid = objectid; 6008 key[1].type = BTRFS_INODE_REF_KEY; 6009 key[1].offset = ref_objectid; 6010 6011 sizes[1] = name_len + sizeof(*ref); 6012 } 6013 6014 location = &BTRFS_I(inode)->location; 6015 location->objectid = objectid; 6016 location->offset = 0; 6017 location->type = BTRFS_INODE_ITEM_KEY; 6018 6019 ret = btrfs_insert_inode_locked(inode); 6020 if (ret < 0) { 6021 iput(inode); 6022 goto fail; 6023 } 6024 6025 path->leave_spinning = 1; 6026 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems); 6027 if (ret != 0) 6028 goto fail_unlock; 6029 6030 inode_init_owner(inode, dir, mode); 6031 inode_set_bytes(inode, 0); 6032 6033 inode->i_mtime = current_time(inode); 6034 inode->i_atime = inode->i_mtime; 6035 inode->i_ctime = inode->i_mtime; 6036 BTRFS_I(inode)->i_otime = inode->i_mtime; 6037 6038 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0], 6039 struct btrfs_inode_item); 6040 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item, 6041 sizeof(*inode_item)); 6042 fill_inode_item(trans, path->nodes[0], inode_item, inode); 6043 6044 if (name) { 6045 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1, 6046 struct btrfs_inode_ref); 6047 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len); 6048 btrfs_set_inode_ref_index(path->nodes[0], ref, *index); 6049 ptr = (unsigned long)(ref + 1); 6050 write_extent_buffer(path->nodes[0], name, ptr, name_len); 6051 } 6052 6053 btrfs_mark_buffer_dirty(path->nodes[0]); 6054 btrfs_free_path(path); 6055 6056 btrfs_inherit_iflags(inode, dir); 6057 6058 if (S_ISREG(mode)) { 6059 if (btrfs_test_opt(fs_info, NODATASUM)) 6060 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; 6061 if (btrfs_test_opt(fs_info, NODATACOW)) 6062 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | 6063 BTRFS_INODE_NODATASUM; 6064 } 6065 6066 inode_tree_add(inode); 6067 6068 trace_btrfs_inode_new(inode); 6069 btrfs_set_inode_last_trans(trans, BTRFS_I(inode)); 6070 6071 btrfs_update_root_times(trans, root); 6072 6073 ret = btrfs_inode_inherit_props(trans, inode, dir); 6074 if (ret) 6075 btrfs_err(fs_info, 6076 "error inheriting props for ino %llu (root %llu): %d", 6077 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret); 6078 6079 return inode; 6080 6081 fail_unlock: 6082 discard_new_inode(inode); 6083 fail: 6084 if (dir && name) 6085 BTRFS_I(dir)->index_cnt--; 6086 btrfs_free_path(path); 6087 return ERR_PTR(ret); 6088 } 6089 6090 /* 6091 * utility function to add 'inode' into 'parent_inode' with 6092 * a give name and a given sequence number. 6093 * if 'add_backref' is true, also insert a backref from the 6094 * inode to the parent directory. 6095 */ 6096 int btrfs_add_link(struct btrfs_trans_handle *trans, 6097 struct btrfs_inode *parent_inode, struct btrfs_inode *inode, 6098 const char *name, int name_len, int add_backref, u64 index) 6099 { 6100 int ret = 0; 6101 struct btrfs_key key; 6102 struct btrfs_root *root = parent_inode->root; 6103 u64 ino = btrfs_ino(inode); 6104 u64 parent_ino = btrfs_ino(parent_inode); 6105 6106 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { 6107 memcpy(&key, &inode->root->root_key, sizeof(key)); 6108 } else { 6109 key.objectid = ino; 6110 key.type = BTRFS_INODE_ITEM_KEY; 6111 key.offset = 0; 6112 } 6113 6114 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { 6115 ret = btrfs_add_root_ref(trans, key.objectid, 6116 root->root_key.objectid, parent_ino, 6117 index, name, name_len); 6118 } else if (add_backref) { 6119 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, 6120 parent_ino, index); 6121 } 6122 6123 /* Nothing to clean up yet */ 6124 if (ret) 6125 return ret; 6126 6127 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key, 6128 btrfs_inode_type(&inode->vfs_inode), index); 6129 if (ret == -EEXIST || ret == -EOVERFLOW) 6130 goto fail_dir_item; 6131 else if (ret) { 6132 btrfs_abort_transaction(trans, ret); 6133 return ret; 6134 } 6135 6136 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size + 6137 name_len * 2); 6138 inode_inc_iversion(&parent_inode->vfs_inode); 6139 /* 6140 * If we are replaying a log tree, we do not want to update the mtime 6141 * and ctime of the parent directory with the current time, since the 6142 * log replay procedure is responsible for setting them to their correct 6143 * values (the ones it had when the fsync was done). 6144 */ 6145 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) { 6146 struct timespec64 now = current_time(&parent_inode->vfs_inode); 6147 6148 parent_inode->vfs_inode.i_mtime = now; 6149 parent_inode->vfs_inode.i_ctime = now; 6150 } 6151 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode); 6152 if (ret) 6153 btrfs_abort_transaction(trans, ret); 6154 return ret; 6155 6156 fail_dir_item: 6157 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { 6158 u64 local_index; 6159 int err; 6160 err = btrfs_del_root_ref(trans, key.objectid, 6161 root->root_key.objectid, parent_ino, 6162 &local_index, name, name_len); 6163 if (err) 6164 btrfs_abort_transaction(trans, err); 6165 } else if (add_backref) { 6166 u64 local_index; 6167 int err; 6168 6169 err = btrfs_del_inode_ref(trans, root, name, name_len, 6170 ino, parent_ino, &local_index); 6171 if (err) 6172 btrfs_abort_transaction(trans, err); 6173 } 6174 6175 /* Return the original error code */ 6176 return ret; 6177 } 6178 6179 static int btrfs_add_nondir(struct btrfs_trans_handle *trans, 6180 struct btrfs_inode *dir, struct dentry *dentry, 6181 struct btrfs_inode *inode, int backref, u64 index) 6182 { 6183 int err = btrfs_add_link(trans, dir, inode, 6184 dentry->d_name.name, dentry->d_name.len, 6185 backref, index); 6186 if (err > 0) 6187 err = -EEXIST; 6188 return err; 6189 } 6190 6191 static int btrfs_mknod(struct inode *dir, struct dentry *dentry, 6192 umode_t mode, dev_t rdev) 6193 { 6194 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 6195 struct btrfs_trans_handle *trans; 6196 struct btrfs_root *root = BTRFS_I(dir)->root; 6197 struct inode *inode = NULL; 6198 int err; 6199 u64 objectid; 6200 u64 index = 0; 6201 6202 /* 6203 * 2 for inode item and ref 6204 * 2 for dir items 6205 * 1 for xattr if selinux is on 6206 */ 6207 trans = btrfs_start_transaction(root, 5); 6208 if (IS_ERR(trans)) 6209 return PTR_ERR(trans); 6210 6211 err = btrfs_find_free_ino(root, &objectid); 6212 if (err) 6213 goto out_unlock; 6214 6215 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, 6216 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid, 6217 mode, &index); 6218 if (IS_ERR(inode)) { 6219 err = PTR_ERR(inode); 6220 inode = NULL; 6221 goto out_unlock; 6222 } 6223 6224 /* 6225 * If the active LSM wants to access the inode during 6226 * d_instantiate it needs these. Smack checks to see 6227 * if the filesystem supports xattrs by looking at the 6228 * ops vector. 6229 */ 6230 inode->i_op = &btrfs_special_inode_operations; 6231 init_special_inode(inode, inode->i_mode, rdev); 6232 6233 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); 6234 if (err) 6235 goto out_unlock; 6236 6237 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode), 6238 0, index); 6239 if (err) 6240 goto out_unlock; 6241 6242 btrfs_update_inode(trans, root, inode); 6243 d_instantiate_new(dentry, inode); 6244 6245 out_unlock: 6246 btrfs_end_transaction(trans); 6247 btrfs_btree_balance_dirty(fs_info); 6248 if (err && inode) { 6249 inode_dec_link_count(inode); 6250 discard_new_inode(inode); 6251 } 6252 return err; 6253 } 6254 6255 static int btrfs_create(struct inode *dir, struct dentry *dentry, 6256 umode_t mode, bool excl) 6257 { 6258 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 6259 struct btrfs_trans_handle *trans; 6260 struct btrfs_root *root = BTRFS_I(dir)->root; 6261 struct inode *inode = NULL; 6262 int err; 6263 u64 objectid; 6264 u64 index = 0; 6265 6266 /* 6267 * 2 for inode item and ref 6268 * 2 for dir items 6269 * 1 for xattr if selinux is on 6270 */ 6271 trans = btrfs_start_transaction(root, 5); 6272 if (IS_ERR(trans)) 6273 return PTR_ERR(trans); 6274 6275 err = btrfs_find_free_ino(root, &objectid); 6276 if (err) 6277 goto out_unlock; 6278 6279 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, 6280 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid, 6281 mode, &index); 6282 if (IS_ERR(inode)) { 6283 err = PTR_ERR(inode); 6284 inode = NULL; 6285 goto out_unlock; 6286 } 6287 /* 6288 * If the active LSM wants to access the inode during 6289 * d_instantiate it needs these. Smack checks to see 6290 * if the filesystem supports xattrs by looking at the 6291 * ops vector. 6292 */ 6293 inode->i_fop = &btrfs_file_operations; 6294 inode->i_op = &btrfs_file_inode_operations; 6295 inode->i_mapping->a_ops = &btrfs_aops; 6296 6297 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); 6298 if (err) 6299 goto out_unlock; 6300 6301 err = btrfs_update_inode(trans, root, inode); 6302 if (err) 6303 goto out_unlock; 6304 6305 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode), 6306 0, index); 6307 if (err) 6308 goto out_unlock; 6309 6310 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; 6311 d_instantiate_new(dentry, inode); 6312 6313 out_unlock: 6314 btrfs_end_transaction(trans); 6315 if (err && inode) { 6316 inode_dec_link_count(inode); 6317 discard_new_inode(inode); 6318 } 6319 btrfs_btree_balance_dirty(fs_info); 6320 return err; 6321 } 6322 6323 static int btrfs_link(struct dentry *old_dentry, struct inode *dir, 6324 struct dentry *dentry) 6325 { 6326 struct btrfs_trans_handle *trans = NULL; 6327 struct btrfs_root *root = BTRFS_I(dir)->root; 6328 struct inode *inode = d_inode(old_dentry); 6329 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 6330 u64 index; 6331 int err; 6332 int drop_inode = 0; 6333 6334 /* do not allow sys_link's with other subvols of the same device */ 6335 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid) 6336 return -EXDEV; 6337 6338 if (inode->i_nlink >= BTRFS_LINK_MAX) 6339 return -EMLINK; 6340 6341 err = btrfs_set_inode_index(BTRFS_I(dir), &index); 6342 if (err) 6343 goto fail; 6344 6345 /* 6346 * 2 items for inode and inode ref 6347 * 2 items for dir items 6348 * 1 item for parent inode 6349 * 1 item for orphan item deletion if O_TMPFILE 6350 */ 6351 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6); 6352 if (IS_ERR(trans)) { 6353 err = PTR_ERR(trans); 6354 trans = NULL; 6355 goto fail; 6356 } 6357 6358 /* There are several dir indexes for this inode, clear the cache. */ 6359 BTRFS_I(inode)->dir_index = 0ULL; 6360 inc_nlink(inode); 6361 inode_inc_iversion(inode); 6362 inode->i_ctime = current_time(inode); 6363 ihold(inode); 6364 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags); 6365 6366 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode), 6367 1, index); 6368 6369 if (err) { 6370 drop_inode = 1; 6371 } else { 6372 struct dentry *parent = dentry->d_parent; 6373 int ret; 6374 6375 err = btrfs_update_inode(trans, root, inode); 6376 if (err) 6377 goto fail; 6378 if (inode->i_nlink == 1) { 6379 /* 6380 * If new hard link count is 1, it's a file created 6381 * with open(2) O_TMPFILE flag. 6382 */ 6383 err = btrfs_orphan_del(trans, BTRFS_I(inode)); 6384 if (err) 6385 goto fail; 6386 } 6387 d_instantiate(dentry, inode); 6388 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent, 6389 true, NULL); 6390 if (ret == BTRFS_NEED_TRANS_COMMIT) { 6391 err = btrfs_commit_transaction(trans); 6392 trans = NULL; 6393 } 6394 } 6395 6396 fail: 6397 if (trans) 6398 btrfs_end_transaction(trans); 6399 if (drop_inode) { 6400 inode_dec_link_count(inode); 6401 iput(inode); 6402 } 6403 btrfs_btree_balance_dirty(fs_info); 6404 return err; 6405 } 6406 6407 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) 6408 { 6409 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 6410 struct inode *inode = NULL; 6411 struct btrfs_trans_handle *trans; 6412 struct btrfs_root *root = BTRFS_I(dir)->root; 6413 int err = 0; 6414 u64 objectid = 0; 6415 u64 index = 0; 6416 6417 /* 6418 * 2 items for inode and ref 6419 * 2 items for dir items 6420 * 1 for xattr if selinux is on 6421 */ 6422 trans = btrfs_start_transaction(root, 5); 6423 if (IS_ERR(trans)) 6424 return PTR_ERR(trans); 6425 6426 err = btrfs_find_free_ino(root, &objectid); 6427 if (err) 6428 goto out_fail; 6429 6430 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, 6431 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid, 6432 S_IFDIR | mode, &index); 6433 if (IS_ERR(inode)) { 6434 err = PTR_ERR(inode); 6435 inode = NULL; 6436 goto out_fail; 6437 } 6438 6439 /* these must be set before we unlock the inode */ 6440 inode->i_op = &btrfs_dir_inode_operations; 6441 inode->i_fop = &btrfs_dir_file_operations; 6442 6443 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); 6444 if (err) 6445 goto out_fail; 6446 6447 btrfs_i_size_write(BTRFS_I(inode), 0); 6448 err = btrfs_update_inode(trans, root, inode); 6449 if (err) 6450 goto out_fail; 6451 6452 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), 6453 dentry->d_name.name, 6454 dentry->d_name.len, 0, index); 6455 if (err) 6456 goto out_fail; 6457 6458 d_instantiate_new(dentry, inode); 6459 6460 out_fail: 6461 btrfs_end_transaction(trans); 6462 if (err && inode) { 6463 inode_dec_link_count(inode); 6464 discard_new_inode(inode); 6465 } 6466 btrfs_btree_balance_dirty(fs_info); 6467 return err; 6468 } 6469 6470 static noinline int uncompress_inline(struct btrfs_path *path, 6471 struct page *page, 6472 size_t pg_offset, u64 extent_offset, 6473 struct btrfs_file_extent_item *item) 6474 { 6475 int ret; 6476 struct extent_buffer *leaf = path->nodes[0]; 6477 char *tmp; 6478 size_t max_size; 6479 unsigned long inline_size; 6480 unsigned long ptr; 6481 int compress_type; 6482 6483 WARN_ON(pg_offset != 0); 6484 compress_type = btrfs_file_extent_compression(leaf, item); 6485 max_size = btrfs_file_extent_ram_bytes(leaf, item); 6486 inline_size = btrfs_file_extent_inline_item_len(leaf, 6487 btrfs_item_nr(path->slots[0])); 6488 tmp = kmalloc(inline_size, GFP_NOFS); 6489 if (!tmp) 6490 return -ENOMEM; 6491 ptr = btrfs_file_extent_inline_start(item); 6492 6493 read_extent_buffer(leaf, tmp, ptr, inline_size); 6494 6495 max_size = min_t(unsigned long, PAGE_SIZE, max_size); 6496 ret = btrfs_decompress(compress_type, tmp, page, 6497 extent_offset, inline_size, max_size); 6498 6499 /* 6500 * decompression code contains a memset to fill in any space between the end 6501 * of the uncompressed data and the end of max_size in case the decompressed 6502 * data ends up shorter than ram_bytes. That doesn't cover the hole between 6503 * the end of an inline extent and the beginning of the next block, so we 6504 * cover that region here. 6505 */ 6506 6507 if (max_size + pg_offset < PAGE_SIZE) { 6508 char *map = kmap(page); 6509 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset); 6510 kunmap(page); 6511 } 6512 kfree(tmp); 6513 return ret; 6514 } 6515 6516 /** 6517 * btrfs_get_extent - Lookup the first extent overlapping a range in a file. 6518 * @inode: file to search in 6519 * @page: page to read extent data into if the extent is inline 6520 * @pg_offset: offset into @page to copy to 6521 * @start: file offset 6522 * @len: length of range starting at @start 6523 * 6524 * This returns the first &struct extent_map which overlaps with the given 6525 * range, reading it from the B-tree and caching it if necessary. Note that 6526 * there may be more extents which overlap the given range after the returned 6527 * extent_map. 6528 * 6529 * If @page is not NULL and the extent is inline, this also reads the extent 6530 * data directly into the page and marks the extent up to date in the io_tree. 6531 * 6532 * Return: ERR_PTR on error, non-NULL extent_map on success. 6533 */ 6534 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode, 6535 struct page *page, size_t pg_offset, 6536 u64 start, u64 len) 6537 { 6538 struct btrfs_fs_info *fs_info = inode->root->fs_info; 6539 int ret; 6540 int err = 0; 6541 u64 extent_start = 0; 6542 u64 extent_end = 0; 6543 u64 objectid = btrfs_ino(inode); 6544 int extent_type = -1; 6545 struct btrfs_path *path = NULL; 6546 struct btrfs_root *root = inode->root; 6547 struct btrfs_file_extent_item *item; 6548 struct extent_buffer *leaf; 6549 struct btrfs_key found_key; 6550 struct extent_map *em = NULL; 6551 struct extent_map_tree *em_tree = &inode->extent_tree; 6552 struct extent_io_tree *io_tree = &inode->io_tree; 6553 6554 read_lock(&em_tree->lock); 6555 em = lookup_extent_mapping(em_tree, start, len); 6556 read_unlock(&em_tree->lock); 6557 6558 if (em) { 6559 if (em->start > start || em->start + em->len <= start) 6560 free_extent_map(em); 6561 else if (em->block_start == EXTENT_MAP_INLINE && page) 6562 free_extent_map(em); 6563 else 6564 goto out; 6565 } 6566 em = alloc_extent_map(); 6567 if (!em) { 6568 err = -ENOMEM; 6569 goto out; 6570 } 6571 em->start = EXTENT_MAP_HOLE; 6572 em->orig_start = EXTENT_MAP_HOLE; 6573 em->len = (u64)-1; 6574 em->block_len = (u64)-1; 6575 6576 path = btrfs_alloc_path(); 6577 if (!path) { 6578 err = -ENOMEM; 6579 goto out; 6580 } 6581 6582 /* Chances are we'll be called again, so go ahead and do readahead */ 6583 path->reada = READA_FORWARD; 6584 6585 /* 6586 * Unless we're going to uncompress the inline extent, no sleep would 6587 * happen. 6588 */ 6589 path->leave_spinning = 1; 6590 6591 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0); 6592 if (ret < 0) { 6593 err = ret; 6594 goto out; 6595 } else if (ret > 0) { 6596 if (path->slots[0] == 0) 6597 goto not_found; 6598 path->slots[0]--; 6599 } 6600 6601 leaf = path->nodes[0]; 6602 item = btrfs_item_ptr(leaf, path->slots[0], 6603 struct btrfs_file_extent_item); 6604 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 6605 if (found_key.objectid != objectid || 6606 found_key.type != BTRFS_EXTENT_DATA_KEY) { 6607 /* 6608 * If we backup past the first extent we want to move forward 6609 * and see if there is an extent in front of us, otherwise we'll 6610 * say there is a hole for our whole search range which can 6611 * cause problems. 6612 */ 6613 extent_end = start; 6614 goto next; 6615 } 6616 6617 extent_type = btrfs_file_extent_type(leaf, item); 6618 extent_start = found_key.offset; 6619 extent_end = btrfs_file_extent_end(path); 6620 if (extent_type == BTRFS_FILE_EXTENT_REG || 6621 extent_type == BTRFS_FILE_EXTENT_PREALLOC) { 6622 /* Only regular file could have regular/prealloc extent */ 6623 if (!S_ISREG(inode->vfs_inode.i_mode)) { 6624 ret = -EUCLEAN; 6625 btrfs_crit(fs_info, 6626 "regular/prealloc extent found for non-regular inode %llu", 6627 btrfs_ino(inode)); 6628 goto out; 6629 } 6630 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item, 6631 extent_start); 6632 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 6633 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item, 6634 path->slots[0], 6635 extent_start); 6636 } 6637 next: 6638 if (start >= extent_end) { 6639 path->slots[0]++; 6640 if (path->slots[0] >= btrfs_header_nritems(leaf)) { 6641 ret = btrfs_next_leaf(root, path); 6642 if (ret < 0) { 6643 err = ret; 6644 goto out; 6645 } else if (ret > 0) { 6646 goto not_found; 6647 } 6648 leaf = path->nodes[0]; 6649 } 6650 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 6651 if (found_key.objectid != objectid || 6652 found_key.type != BTRFS_EXTENT_DATA_KEY) 6653 goto not_found; 6654 if (start + len <= found_key.offset) 6655 goto not_found; 6656 if (start > found_key.offset) 6657 goto next; 6658 6659 /* New extent overlaps with existing one */ 6660 em->start = start; 6661 em->orig_start = start; 6662 em->len = found_key.offset - start; 6663 em->block_start = EXTENT_MAP_HOLE; 6664 goto insert; 6665 } 6666 6667 btrfs_extent_item_to_extent_map(inode, path, item, !page, em); 6668 6669 if (extent_type == BTRFS_FILE_EXTENT_REG || 6670 extent_type == BTRFS_FILE_EXTENT_PREALLOC) { 6671 goto insert; 6672 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { 6673 unsigned long ptr; 6674 char *map; 6675 size_t size; 6676 size_t extent_offset; 6677 size_t copy_size; 6678 6679 if (!page) 6680 goto out; 6681 6682 size = btrfs_file_extent_ram_bytes(leaf, item); 6683 extent_offset = page_offset(page) + pg_offset - extent_start; 6684 copy_size = min_t(u64, PAGE_SIZE - pg_offset, 6685 size - extent_offset); 6686 em->start = extent_start + extent_offset; 6687 em->len = ALIGN(copy_size, fs_info->sectorsize); 6688 em->orig_block_len = em->len; 6689 em->orig_start = em->start; 6690 ptr = btrfs_file_extent_inline_start(item) + extent_offset; 6691 6692 btrfs_set_path_blocking(path); 6693 if (!PageUptodate(page)) { 6694 if (btrfs_file_extent_compression(leaf, item) != 6695 BTRFS_COMPRESS_NONE) { 6696 ret = uncompress_inline(path, page, pg_offset, 6697 extent_offset, item); 6698 if (ret) { 6699 err = ret; 6700 goto out; 6701 } 6702 } else { 6703 map = kmap(page); 6704 read_extent_buffer(leaf, map + pg_offset, ptr, 6705 copy_size); 6706 if (pg_offset + copy_size < PAGE_SIZE) { 6707 memset(map + pg_offset + copy_size, 0, 6708 PAGE_SIZE - pg_offset - 6709 copy_size); 6710 } 6711 kunmap(page); 6712 } 6713 flush_dcache_page(page); 6714 } 6715 set_extent_uptodate(io_tree, em->start, 6716 extent_map_end(em) - 1, NULL, GFP_NOFS); 6717 goto insert; 6718 } 6719 not_found: 6720 em->start = start; 6721 em->orig_start = start; 6722 em->len = len; 6723 em->block_start = EXTENT_MAP_HOLE; 6724 insert: 6725 btrfs_release_path(path); 6726 if (em->start > start || extent_map_end(em) <= start) { 6727 btrfs_err(fs_info, 6728 "bad extent! em: [%llu %llu] passed [%llu %llu]", 6729 em->start, em->len, start, len); 6730 err = -EIO; 6731 goto out; 6732 } 6733 6734 err = 0; 6735 write_lock(&em_tree->lock); 6736 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len); 6737 write_unlock(&em_tree->lock); 6738 out: 6739 btrfs_free_path(path); 6740 6741 trace_btrfs_get_extent(root, inode, em); 6742 6743 if (err) { 6744 free_extent_map(em); 6745 return ERR_PTR(err); 6746 } 6747 BUG_ON(!em); /* Error is always set */ 6748 return em; 6749 } 6750 6751 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode, 6752 u64 start, u64 len) 6753 { 6754 struct extent_map *em; 6755 struct extent_map *hole_em = NULL; 6756 u64 delalloc_start = start; 6757 u64 end; 6758 u64 delalloc_len; 6759 u64 delalloc_end; 6760 int err = 0; 6761 6762 em = btrfs_get_extent(inode, NULL, 0, start, len); 6763 if (IS_ERR(em)) 6764 return em; 6765 /* 6766 * If our em maps to: 6767 * - a hole or 6768 * - a pre-alloc extent, 6769 * there might actually be delalloc bytes behind it. 6770 */ 6771 if (em->block_start != EXTENT_MAP_HOLE && 6772 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) 6773 return em; 6774 else 6775 hole_em = em; 6776 6777 /* check to see if we've wrapped (len == -1 or similar) */ 6778 end = start + len; 6779 if (end < start) 6780 end = (u64)-1; 6781 else 6782 end -= 1; 6783 6784 em = NULL; 6785 6786 /* ok, we didn't find anything, lets look for delalloc */ 6787 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start, 6788 end, len, EXTENT_DELALLOC, 1); 6789 delalloc_end = delalloc_start + delalloc_len; 6790 if (delalloc_end < delalloc_start) 6791 delalloc_end = (u64)-1; 6792 6793 /* 6794 * We didn't find anything useful, return the original results from 6795 * get_extent() 6796 */ 6797 if (delalloc_start > end || delalloc_end <= start) { 6798 em = hole_em; 6799 hole_em = NULL; 6800 goto out; 6801 } 6802 6803 /* 6804 * Adjust the delalloc_start to make sure it doesn't go backwards from 6805 * the start they passed in 6806 */ 6807 delalloc_start = max(start, delalloc_start); 6808 delalloc_len = delalloc_end - delalloc_start; 6809 6810 if (delalloc_len > 0) { 6811 u64 hole_start; 6812 u64 hole_len; 6813 const u64 hole_end = extent_map_end(hole_em); 6814 6815 em = alloc_extent_map(); 6816 if (!em) { 6817 err = -ENOMEM; 6818 goto out; 6819 } 6820 6821 ASSERT(hole_em); 6822 /* 6823 * When btrfs_get_extent can't find anything it returns one 6824 * huge hole 6825 * 6826 * Make sure what it found really fits our range, and adjust to 6827 * make sure it is based on the start from the caller 6828 */ 6829 if (hole_end <= start || hole_em->start > end) { 6830 free_extent_map(hole_em); 6831 hole_em = NULL; 6832 } else { 6833 hole_start = max(hole_em->start, start); 6834 hole_len = hole_end - hole_start; 6835 } 6836 6837 if (hole_em && delalloc_start > hole_start) { 6838 /* 6839 * Our hole starts before our delalloc, so we have to 6840 * return just the parts of the hole that go until the 6841 * delalloc starts 6842 */ 6843 em->len = min(hole_len, delalloc_start - hole_start); 6844 em->start = hole_start; 6845 em->orig_start = hole_start; 6846 /* 6847 * Don't adjust block start at all, it is fixed at 6848 * EXTENT_MAP_HOLE 6849 */ 6850 em->block_start = hole_em->block_start; 6851 em->block_len = hole_len; 6852 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags)) 6853 set_bit(EXTENT_FLAG_PREALLOC, &em->flags); 6854 } else { 6855 /* 6856 * Hole is out of passed range or it starts after 6857 * delalloc range 6858 */ 6859 em->start = delalloc_start; 6860 em->len = delalloc_len; 6861 em->orig_start = delalloc_start; 6862 em->block_start = EXTENT_MAP_DELALLOC; 6863 em->block_len = delalloc_len; 6864 } 6865 } else { 6866 return hole_em; 6867 } 6868 out: 6869 6870 free_extent_map(hole_em); 6871 if (err) { 6872 free_extent_map(em); 6873 return ERR_PTR(err); 6874 } 6875 return em; 6876 } 6877 6878 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode, 6879 const u64 start, 6880 const u64 len, 6881 const u64 orig_start, 6882 const u64 block_start, 6883 const u64 block_len, 6884 const u64 orig_block_len, 6885 const u64 ram_bytes, 6886 const int type) 6887 { 6888 struct extent_map *em = NULL; 6889 int ret; 6890 6891 if (type != BTRFS_ORDERED_NOCOW) { 6892 em = create_io_em(inode, start, len, orig_start, block_start, 6893 block_len, orig_block_len, ram_bytes, 6894 BTRFS_COMPRESS_NONE, /* compress_type */ 6895 type); 6896 if (IS_ERR(em)) 6897 goto out; 6898 } 6899 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len, 6900 block_len, type); 6901 if (ret) { 6902 if (em) { 6903 free_extent_map(em); 6904 btrfs_drop_extent_cache(inode, start, start + len - 1, 0); 6905 } 6906 em = ERR_PTR(ret); 6907 } 6908 out: 6909 6910 return em; 6911 } 6912 6913 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode, 6914 u64 start, u64 len) 6915 { 6916 struct btrfs_root *root = inode->root; 6917 struct btrfs_fs_info *fs_info = root->fs_info; 6918 struct extent_map *em; 6919 struct btrfs_key ins; 6920 u64 alloc_hint; 6921 int ret; 6922 6923 alloc_hint = get_extent_allocation_hint(inode, start, len); 6924 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize, 6925 0, alloc_hint, &ins, 1, 1); 6926 if (ret) 6927 return ERR_PTR(ret); 6928 6929 em = btrfs_create_dio_extent(inode, start, ins.offset, start, 6930 ins.objectid, ins.offset, ins.offset, 6931 ins.offset, BTRFS_ORDERED_REGULAR); 6932 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 6933 if (IS_ERR(em)) 6934 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 6935 1); 6936 6937 return em; 6938 } 6939 6940 /* 6941 * Check if we can do nocow write into the range [@offset, @offset + @len) 6942 * 6943 * @offset: File offset 6944 * @len: The length to write, will be updated to the nocow writeable 6945 * range 6946 * @orig_start: (optional) Return the original file offset of the file extent 6947 * @orig_len: (optional) Return the original on-disk length of the file extent 6948 * @ram_bytes: (optional) Return the ram_bytes of the file extent 6949 * 6950 * This function will flush ordered extents in the range to ensure proper 6951 * nocow checks for (nowait == false) case. 6952 * 6953 * Return: 6954 * >0 and update @len if we can do nocow write 6955 * 0 if we can't do nocow write 6956 * <0 if error happened 6957 * 6958 * NOTE: This only checks the file extents, caller is responsible to wait for 6959 * any ordered extents. 6960 */ 6961 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len, 6962 u64 *orig_start, u64 *orig_block_len, 6963 u64 *ram_bytes) 6964 { 6965 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 6966 struct btrfs_path *path; 6967 int ret; 6968 struct extent_buffer *leaf; 6969 struct btrfs_root *root = BTRFS_I(inode)->root; 6970 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 6971 struct btrfs_file_extent_item *fi; 6972 struct btrfs_key key; 6973 u64 disk_bytenr; 6974 u64 backref_offset; 6975 u64 extent_end; 6976 u64 num_bytes; 6977 int slot; 6978 int found_type; 6979 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW); 6980 6981 path = btrfs_alloc_path(); 6982 if (!path) 6983 return -ENOMEM; 6984 6985 ret = btrfs_lookup_file_extent(NULL, root, path, 6986 btrfs_ino(BTRFS_I(inode)), offset, 0); 6987 if (ret < 0) 6988 goto out; 6989 6990 slot = path->slots[0]; 6991 if (ret == 1) { 6992 if (slot == 0) { 6993 /* can't find the item, must cow */ 6994 ret = 0; 6995 goto out; 6996 } 6997 slot--; 6998 } 6999 ret = 0; 7000 leaf = path->nodes[0]; 7001 btrfs_item_key_to_cpu(leaf, &key, slot); 7002 if (key.objectid != btrfs_ino(BTRFS_I(inode)) || 7003 key.type != BTRFS_EXTENT_DATA_KEY) { 7004 /* not our file or wrong item type, must cow */ 7005 goto out; 7006 } 7007 7008 if (key.offset > offset) { 7009 /* Wrong offset, must cow */ 7010 goto out; 7011 } 7012 7013 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); 7014 found_type = btrfs_file_extent_type(leaf, fi); 7015 if (found_type != BTRFS_FILE_EXTENT_REG && 7016 found_type != BTRFS_FILE_EXTENT_PREALLOC) { 7017 /* not a regular extent, must cow */ 7018 goto out; 7019 } 7020 7021 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG) 7022 goto out; 7023 7024 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); 7025 if (extent_end <= offset) 7026 goto out; 7027 7028 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); 7029 if (disk_bytenr == 0) 7030 goto out; 7031 7032 if (btrfs_file_extent_compression(leaf, fi) || 7033 btrfs_file_extent_encryption(leaf, fi) || 7034 btrfs_file_extent_other_encoding(leaf, fi)) 7035 goto out; 7036 7037 /* 7038 * Do the same check as in btrfs_cross_ref_exist but without the 7039 * unnecessary search. 7040 */ 7041 if (btrfs_file_extent_generation(leaf, fi) <= 7042 btrfs_root_last_snapshot(&root->root_item)) 7043 goto out; 7044 7045 backref_offset = btrfs_file_extent_offset(leaf, fi); 7046 7047 if (orig_start) { 7048 *orig_start = key.offset - backref_offset; 7049 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi); 7050 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi); 7051 } 7052 7053 if (btrfs_extent_readonly(fs_info, disk_bytenr)) 7054 goto out; 7055 7056 num_bytes = min(offset + *len, extent_end) - offset; 7057 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) { 7058 u64 range_end; 7059 7060 range_end = round_up(offset + num_bytes, 7061 root->fs_info->sectorsize) - 1; 7062 ret = test_range_bit(io_tree, offset, range_end, 7063 EXTENT_DELALLOC, 0, NULL); 7064 if (ret) { 7065 ret = -EAGAIN; 7066 goto out; 7067 } 7068 } 7069 7070 btrfs_release_path(path); 7071 7072 /* 7073 * look for other files referencing this extent, if we 7074 * find any we must cow 7075 */ 7076 7077 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)), 7078 key.offset - backref_offset, disk_bytenr); 7079 if (ret) { 7080 ret = 0; 7081 goto out; 7082 } 7083 7084 /* 7085 * adjust disk_bytenr and num_bytes to cover just the bytes 7086 * in this extent we are about to write. If there 7087 * are any csums in that range we have to cow in order 7088 * to keep the csums correct 7089 */ 7090 disk_bytenr += backref_offset; 7091 disk_bytenr += offset - key.offset; 7092 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes)) 7093 goto out; 7094 /* 7095 * all of the above have passed, it is safe to overwrite this extent 7096 * without cow 7097 */ 7098 *len = num_bytes; 7099 ret = 1; 7100 out: 7101 btrfs_free_path(path); 7102 return ret; 7103 } 7104 7105 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend, 7106 struct extent_state **cached_state, int writing) 7107 { 7108 struct btrfs_ordered_extent *ordered; 7109 int ret = 0; 7110 7111 while (1) { 7112 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 7113 cached_state); 7114 /* 7115 * We're concerned with the entire range that we're going to be 7116 * doing DIO to, so we need to make sure there's no ordered 7117 * extents in this range. 7118 */ 7119 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart, 7120 lockend - lockstart + 1); 7121 7122 /* 7123 * We need to make sure there are no buffered pages in this 7124 * range either, we could have raced between the invalidate in 7125 * generic_file_direct_write and locking the extent. The 7126 * invalidate needs to happen so that reads after a write do not 7127 * get stale data. 7128 */ 7129 if (!ordered && 7130 (!writing || !filemap_range_has_page(inode->i_mapping, 7131 lockstart, lockend))) 7132 break; 7133 7134 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, 7135 cached_state); 7136 7137 if (ordered) { 7138 /* 7139 * If we are doing a DIO read and the ordered extent we 7140 * found is for a buffered write, we can not wait for it 7141 * to complete and retry, because if we do so we can 7142 * deadlock with concurrent buffered writes on page 7143 * locks. This happens only if our DIO read covers more 7144 * than one extent map, if at this point has already 7145 * created an ordered extent for a previous extent map 7146 * and locked its range in the inode's io tree, and a 7147 * concurrent write against that previous extent map's 7148 * range and this range started (we unlock the ranges 7149 * in the io tree only when the bios complete and 7150 * buffered writes always lock pages before attempting 7151 * to lock range in the io tree). 7152 */ 7153 if (writing || 7154 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags)) 7155 btrfs_start_ordered_extent(inode, ordered, 1); 7156 else 7157 ret = -ENOTBLK; 7158 btrfs_put_ordered_extent(ordered); 7159 } else { 7160 /* 7161 * We could trigger writeback for this range (and wait 7162 * for it to complete) and then invalidate the pages for 7163 * this range (through invalidate_inode_pages2_range()), 7164 * but that can lead us to a deadlock with a concurrent 7165 * call to readahead (a buffered read or a defrag call 7166 * triggered a readahead) on a page lock due to an 7167 * ordered dio extent we created before but did not have 7168 * yet a corresponding bio submitted (whence it can not 7169 * complete), which makes readahead wait for that 7170 * ordered extent to complete while holding a lock on 7171 * that page. 7172 */ 7173 ret = -ENOTBLK; 7174 } 7175 7176 if (ret) 7177 break; 7178 7179 cond_resched(); 7180 } 7181 7182 return ret; 7183 } 7184 7185 /* The callers of this must take lock_extent() */ 7186 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start, 7187 u64 len, u64 orig_start, u64 block_start, 7188 u64 block_len, u64 orig_block_len, 7189 u64 ram_bytes, int compress_type, 7190 int type) 7191 { 7192 struct extent_map_tree *em_tree; 7193 struct extent_map *em; 7194 int ret; 7195 7196 ASSERT(type == BTRFS_ORDERED_PREALLOC || 7197 type == BTRFS_ORDERED_COMPRESSED || 7198 type == BTRFS_ORDERED_NOCOW || 7199 type == BTRFS_ORDERED_REGULAR); 7200 7201 em_tree = &inode->extent_tree; 7202 em = alloc_extent_map(); 7203 if (!em) 7204 return ERR_PTR(-ENOMEM); 7205 7206 em->start = start; 7207 em->orig_start = orig_start; 7208 em->len = len; 7209 em->block_len = block_len; 7210 em->block_start = block_start; 7211 em->orig_block_len = orig_block_len; 7212 em->ram_bytes = ram_bytes; 7213 em->generation = -1; 7214 set_bit(EXTENT_FLAG_PINNED, &em->flags); 7215 if (type == BTRFS_ORDERED_PREALLOC) { 7216 set_bit(EXTENT_FLAG_FILLING, &em->flags); 7217 } else if (type == BTRFS_ORDERED_COMPRESSED) { 7218 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); 7219 em->compress_type = compress_type; 7220 } 7221 7222 do { 7223 btrfs_drop_extent_cache(inode, em->start, 7224 em->start + em->len - 1, 0); 7225 write_lock(&em_tree->lock); 7226 ret = add_extent_mapping(em_tree, em, 1); 7227 write_unlock(&em_tree->lock); 7228 /* 7229 * The caller has taken lock_extent(), who could race with us 7230 * to add em? 7231 */ 7232 } while (ret == -EEXIST); 7233 7234 if (ret) { 7235 free_extent_map(em); 7236 return ERR_PTR(ret); 7237 } 7238 7239 /* em got 2 refs now, callers needs to do free_extent_map once. */ 7240 return em; 7241 } 7242 7243 7244 static int btrfs_get_blocks_direct_read(struct extent_map *em, 7245 struct buffer_head *bh_result, 7246 struct inode *inode, 7247 u64 start, u64 len) 7248 { 7249 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7250 7251 if (em->block_start == EXTENT_MAP_HOLE || 7252 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) 7253 return -ENOENT; 7254 7255 len = min(len, em->len - (start - em->start)); 7256 7257 bh_result->b_blocknr = (em->block_start + (start - em->start)) >> 7258 inode->i_blkbits; 7259 bh_result->b_size = len; 7260 bh_result->b_bdev = fs_info->fs_devices->latest_bdev; 7261 set_buffer_mapped(bh_result); 7262 7263 return 0; 7264 } 7265 7266 static int btrfs_get_blocks_direct_write(struct extent_map **map, 7267 struct buffer_head *bh_result, 7268 struct inode *inode, 7269 struct btrfs_dio_data *dio_data, 7270 u64 start, u64 len) 7271 { 7272 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7273 struct extent_map *em = *map; 7274 int ret = 0; 7275 7276 /* 7277 * We don't allocate a new extent in the following cases 7278 * 7279 * 1) The inode is marked as NODATACOW. In this case we'll just use the 7280 * existing extent. 7281 * 2) The extent is marked as PREALLOC. We're good to go here and can 7282 * just use the extent. 7283 * 7284 */ 7285 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) || 7286 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && 7287 em->block_start != EXTENT_MAP_HOLE)) { 7288 int type; 7289 u64 block_start, orig_start, orig_block_len, ram_bytes; 7290 7291 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) 7292 type = BTRFS_ORDERED_PREALLOC; 7293 else 7294 type = BTRFS_ORDERED_NOCOW; 7295 len = min(len, em->len - (start - em->start)); 7296 block_start = em->block_start + (start - em->start); 7297 7298 if (can_nocow_extent(inode, start, &len, &orig_start, 7299 &orig_block_len, &ram_bytes) == 1 && 7300 btrfs_inc_nocow_writers(fs_info, block_start)) { 7301 struct extent_map *em2; 7302 7303 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len, 7304 orig_start, block_start, 7305 len, orig_block_len, 7306 ram_bytes, type); 7307 btrfs_dec_nocow_writers(fs_info, block_start); 7308 if (type == BTRFS_ORDERED_PREALLOC) { 7309 free_extent_map(em); 7310 *map = em = em2; 7311 } 7312 7313 if (em2 && IS_ERR(em2)) { 7314 ret = PTR_ERR(em2); 7315 goto out; 7316 } 7317 /* 7318 * For inode marked NODATACOW or extent marked PREALLOC, 7319 * use the existing or preallocated extent, so does not 7320 * need to adjust btrfs_space_info's bytes_may_use. 7321 */ 7322 btrfs_free_reserved_data_space_noquota(fs_info, len); 7323 goto skip_cow; 7324 } 7325 } 7326 7327 /* this will cow the extent */ 7328 len = bh_result->b_size; 7329 free_extent_map(em); 7330 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len); 7331 if (IS_ERR(em)) { 7332 ret = PTR_ERR(em); 7333 goto out; 7334 } 7335 7336 len = min(len, em->len - (start - em->start)); 7337 7338 skip_cow: 7339 bh_result->b_blocknr = (em->block_start + (start - em->start)) >> 7340 inode->i_blkbits; 7341 bh_result->b_size = len; 7342 bh_result->b_bdev = fs_info->fs_devices->latest_bdev; 7343 set_buffer_mapped(bh_result); 7344 7345 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) 7346 set_buffer_new(bh_result); 7347 7348 /* 7349 * Need to update the i_size under the extent lock so buffered 7350 * readers will get the updated i_size when we unlock. 7351 */ 7352 if (!dio_data->overwrite && start + len > i_size_read(inode)) 7353 i_size_write(inode, start + len); 7354 7355 WARN_ON(dio_data->reserve < len); 7356 dio_data->reserve -= len; 7357 dio_data->unsubmitted_oe_range_end = start + len; 7358 current->journal_info = dio_data; 7359 out: 7360 return ret; 7361 } 7362 7363 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock, 7364 struct buffer_head *bh_result, int create) 7365 { 7366 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7367 struct extent_map *em; 7368 struct extent_state *cached_state = NULL; 7369 struct btrfs_dio_data *dio_data = NULL; 7370 u64 start = iblock << inode->i_blkbits; 7371 u64 lockstart, lockend; 7372 u64 len = bh_result->b_size; 7373 int ret = 0; 7374 7375 if (!create) 7376 len = min_t(u64, len, fs_info->sectorsize); 7377 7378 lockstart = start; 7379 lockend = start + len - 1; 7380 7381 if (current->journal_info) { 7382 /* 7383 * Need to pull our outstanding extents and set journal_info to NULL so 7384 * that anything that needs to check if there's a transaction doesn't get 7385 * confused. 7386 */ 7387 dio_data = current->journal_info; 7388 current->journal_info = NULL; 7389 } 7390 7391 /* 7392 * If this errors out it's because we couldn't invalidate pagecache for 7393 * this range and we need to fallback to buffered. 7394 */ 7395 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, 7396 create)) { 7397 ret = -ENOTBLK; 7398 goto err; 7399 } 7400 7401 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len); 7402 if (IS_ERR(em)) { 7403 ret = PTR_ERR(em); 7404 goto unlock_err; 7405 } 7406 7407 /* 7408 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered 7409 * io. INLINE is special, and we could probably kludge it in here, but 7410 * it's still buffered so for safety lets just fall back to the generic 7411 * buffered path. 7412 * 7413 * For COMPRESSED we _have_ to read the entire extent in so we can 7414 * decompress it, so there will be buffering required no matter what we 7415 * do, so go ahead and fallback to buffered. 7416 * 7417 * We return -ENOTBLK because that's what makes DIO go ahead and go back 7418 * to buffered IO. Don't blame me, this is the price we pay for using 7419 * the generic code. 7420 */ 7421 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) || 7422 em->block_start == EXTENT_MAP_INLINE) { 7423 free_extent_map(em); 7424 ret = -ENOTBLK; 7425 goto unlock_err; 7426 } 7427 7428 if (create) { 7429 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode, 7430 dio_data, start, len); 7431 if (ret < 0) 7432 goto unlock_err; 7433 7434 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, 7435 lockend, &cached_state); 7436 } else { 7437 ret = btrfs_get_blocks_direct_read(em, bh_result, inode, 7438 start, len); 7439 /* Can be negative only if we read from a hole */ 7440 if (ret < 0) { 7441 ret = 0; 7442 free_extent_map(em); 7443 goto unlock_err; 7444 } 7445 /* 7446 * We need to unlock only the end area that we aren't using. 7447 * The rest is going to be unlocked by the endio routine. 7448 */ 7449 lockstart = start + bh_result->b_size; 7450 if (lockstart < lockend) { 7451 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 7452 lockstart, lockend, &cached_state); 7453 } else { 7454 free_extent_state(cached_state); 7455 } 7456 } 7457 7458 free_extent_map(em); 7459 7460 return 0; 7461 7462 unlock_err: 7463 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, 7464 &cached_state); 7465 err: 7466 if (dio_data) 7467 current->journal_info = dio_data; 7468 return ret; 7469 } 7470 7471 static void btrfs_dio_private_put(struct btrfs_dio_private *dip) 7472 { 7473 /* 7474 * This implies a barrier so that stores to dio_bio->bi_status before 7475 * this and loads of dio_bio->bi_status after this are fully ordered. 7476 */ 7477 if (!refcount_dec_and_test(&dip->refs)) 7478 return; 7479 7480 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) { 7481 __endio_write_update_ordered(BTRFS_I(dip->inode), 7482 dip->logical_offset, 7483 dip->bytes, 7484 !dip->dio_bio->bi_status); 7485 } else { 7486 unlock_extent(&BTRFS_I(dip->inode)->io_tree, 7487 dip->logical_offset, 7488 dip->logical_offset + dip->bytes - 1); 7489 } 7490 7491 dio_end_io(dip->dio_bio); 7492 kfree(dip); 7493 } 7494 7495 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio, 7496 int mirror_num, 7497 unsigned long bio_flags) 7498 { 7499 struct btrfs_dio_private *dip = bio->bi_private; 7500 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7501 blk_status_t ret; 7502 7503 BUG_ON(bio_op(bio) == REQ_OP_WRITE); 7504 7505 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA); 7506 if (ret) 7507 return ret; 7508 7509 refcount_inc(&dip->refs); 7510 ret = btrfs_map_bio(fs_info, bio, mirror_num); 7511 if (ret) 7512 refcount_dec(&dip->refs); 7513 return ret; 7514 } 7515 7516 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode, 7517 struct btrfs_io_bio *io_bio, 7518 const bool uptodate) 7519 { 7520 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; 7521 const u32 sectorsize = fs_info->sectorsize; 7522 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree; 7523 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 7524 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM); 7525 struct bio_vec bvec; 7526 struct bvec_iter iter; 7527 u64 start = io_bio->logical; 7528 int icsum = 0; 7529 blk_status_t err = BLK_STS_OK; 7530 7531 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) { 7532 unsigned int i, nr_sectors, pgoff; 7533 7534 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len); 7535 pgoff = bvec.bv_offset; 7536 for (i = 0; i < nr_sectors; i++) { 7537 ASSERT(pgoff < PAGE_SIZE); 7538 if (uptodate && 7539 (!csum || !check_data_csum(inode, io_bio, icsum, 7540 bvec.bv_page, pgoff, 7541 start, sectorsize))) { 7542 clean_io_failure(fs_info, failure_tree, io_tree, 7543 start, bvec.bv_page, 7544 btrfs_ino(BTRFS_I(inode)), 7545 pgoff); 7546 } else { 7547 blk_status_t status; 7548 7549 status = btrfs_submit_read_repair(inode, 7550 &io_bio->bio, 7551 start - io_bio->logical, 7552 bvec.bv_page, pgoff, 7553 start, 7554 start + sectorsize - 1, 7555 io_bio->mirror_num, 7556 submit_dio_repair_bio); 7557 if (status) 7558 err = status; 7559 } 7560 start += sectorsize; 7561 icsum++; 7562 pgoff += sectorsize; 7563 } 7564 } 7565 return err; 7566 } 7567 7568 static void __endio_write_update_ordered(struct btrfs_inode *inode, 7569 const u64 offset, const u64 bytes, 7570 const bool uptodate) 7571 { 7572 struct btrfs_fs_info *fs_info = inode->root->fs_info; 7573 struct btrfs_ordered_extent *ordered = NULL; 7574 struct btrfs_workqueue *wq; 7575 u64 ordered_offset = offset; 7576 u64 ordered_bytes = bytes; 7577 u64 last_offset; 7578 7579 if (btrfs_is_free_space_inode(inode)) 7580 wq = fs_info->endio_freespace_worker; 7581 else 7582 wq = fs_info->endio_write_workers; 7583 7584 while (ordered_offset < offset + bytes) { 7585 last_offset = ordered_offset; 7586 if (btrfs_dec_test_first_ordered_pending(inode, &ordered, 7587 &ordered_offset, 7588 ordered_bytes, 7589 uptodate)) { 7590 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL, 7591 NULL); 7592 btrfs_queue_work(wq, &ordered->work); 7593 } 7594 /* 7595 * If btrfs_dec_test_ordered_pending does not find any ordered 7596 * extent in the range, we can exit. 7597 */ 7598 if (ordered_offset == last_offset) 7599 return; 7600 /* 7601 * Our bio might span multiple ordered extents. In this case 7602 * we keep going until we have accounted the whole dio. 7603 */ 7604 if (ordered_offset < offset + bytes) { 7605 ordered_bytes = offset + bytes - ordered_offset; 7606 ordered = NULL; 7607 } 7608 } 7609 } 7610 7611 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data, 7612 struct bio *bio, u64 offset) 7613 { 7614 struct inode *inode = private_data; 7615 blk_status_t ret; 7616 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, offset, 1); 7617 BUG_ON(ret); /* -ENOMEM */ 7618 return 0; 7619 } 7620 7621 static void btrfs_end_dio_bio(struct bio *bio) 7622 { 7623 struct btrfs_dio_private *dip = bio->bi_private; 7624 blk_status_t err = bio->bi_status; 7625 7626 if (err) 7627 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info, 7628 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d", 7629 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio), 7630 bio->bi_opf, 7631 (unsigned long long)bio->bi_iter.bi_sector, 7632 bio->bi_iter.bi_size, err); 7633 7634 if (bio_op(bio) == REQ_OP_READ) { 7635 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio), 7636 !err); 7637 } 7638 7639 if (err) 7640 dip->dio_bio->bi_status = err; 7641 7642 bio_put(bio); 7643 btrfs_dio_private_put(dip); 7644 } 7645 7646 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio, 7647 struct inode *inode, u64 file_offset, int async_submit) 7648 { 7649 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7650 struct btrfs_dio_private *dip = bio->bi_private; 7651 bool write = bio_op(bio) == REQ_OP_WRITE; 7652 blk_status_t ret; 7653 7654 /* Check btrfs_submit_bio_hook() for rules about async submit. */ 7655 if (async_submit) 7656 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers); 7657 7658 if (!write) { 7659 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA); 7660 if (ret) 7661 goto err; 7662 } 7663 7664 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) 7665 goto map; 7666 7667 if (write && async_submit) { 7668 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0, 7669 file_offset, inode, 7670 btrfs_submit_bio_start_direct_io); 7671 goto err; 7672 } else if (write) { 7673 /* 7674 * If we aren't doing async submit, calculate the csum of the 7675 * bio now. 7676 */ 7677 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1); 7678 if (ret) 7679 goto err; 7680 } else { 7681 u64 csum_offset; 7682 7683 csum_offset = file_offset - dip->logical_offset; 7684 csum_offset >>= inode->i_sb->s_blocksize_bits; 7685 csum_offset *= btrfs_super_csum_size(fs_info->super_copy); 7686 btrfs_io_bio(bio)->csum = dip->csums + csum_offset; 7687 } 7688 map: 7689 ret = btrfs_map_bio(fs_info, bio, 0); 7690 err: 7691 return ret; 7692 } 7693 7694 /* 7695 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked 7696 * or ordered extents whether or not we submit any bios. 7697 */ 7698 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio, 7699 struct inode *inode, 7700 loff_t file_offset) 7701 { 7702 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE); 7703 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM); 7704 size_t dip_size; 7705 struct btrfs_dio_private *dip; 7706 7707 dip_size = sizeof(*dip); 7708 if (!write && csum) { 7709 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7710 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy); 7711 size_t nblocks; 7712 7713 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits; 7714 dip_size += csum_size * nblocks; 7715 } 7716 7717 dip = kzalloc(dip_size, GFP_NOFS); 7718 if (!dip) 7719 return NULL; 7720 7721 dip->inode = inode; 7722 dip->logical_offset = file_offset; 7723 dip->bytes = dio_bio->bi_iter.bi_size; 7724 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9; 7725 dip->dio_bio = dio_bio; 7726 refcount_set(&dip->refs, 1); 7727 7728 if (write) { 7729 struct btrfs_dio_data *dio_data = current->journal_info; 7730 7731 /* 7732 * Setting range start and end to the same value means that 7733 * no cleanup will happen in btrfs_direct_IO 7734 */ 7735 dio_data->unsubmitted_oe_range_end = dip->logical_offset + 7736 dip->bytes; 7737 dio_data->unsubmitted_oe_range_start = 7738 dio_data->unsubmitted_oe_range_end; 7739 } 7740 return dip; 7741 } 7742 7743 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode, 7744 loff_t file_offset) 7745 { 7746 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE); 7747 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM); 7748 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7749 const bool raid56 = (btrfs_data_alloc_profile(fs_info) & 7750 BTRFS_BLOCK_GROUP_RAID56_MASK); 7751 struct btrfs_dio_private *dip; 7752 struct bio *bio; 7753 u64 start_sector; 7754 int async_submit = 0; 7755 u64 submit_len; 7756 int clone_offset = 0; 7757 int clone_len; 7758 int ret; 7759 blk_status_t status; 7760 struct btrfs_io_geometry geom; 7761 7762 dip = btrfs_create_dio_private(dio_bio, inode, file_offset); 7763 if (!dip) { 7764 if (!write) { 7765 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset, 7766 file_offset + dio_bio->bi_iter.bi_size - 1); 7767 } 7768 dio_bio->bi_status = BLK_STS_RESOURCE; 7769 dio_end_io(dio_bio); 7770 return; 7771 } 7772 7773 if (!write && csum) { 7774 /* 7775 * Load the csums up front to reduce csum tree searches and 7776 * contention when submitting bios. 7777 */ 7778 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset, 7779 dip->csums); 7780 if (status != BLK_STS_OK) 7781 goto out_err; 7782 } 7783 7784 start_sector = dio_bio->bi_iter.bi_sector; 7785 submit_len = dio_bio->bi_iter.bi_size; 7786 7787 do { 7788 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio), 7789 start_sector << 9, submit_len, 7790 &geom); 7791 if (ret) { 7792 status = errno_to_blk_status(ret); 7793 goto out_err; 7794 } 7795 ASSERT(geom.len <= INT_MAX); 7796 7797 clone_len = min_t(int, submit_len, geom.len); 7798 7799 /* 7800 * This will never fail as it's passing GPF_NOFS and 7801 * the allocation is backed by btrfs_bioset. 7802 */ 7803 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len); 7804 bio->bi_private = dip; 7805 bio->bi_end_io = btrfs_end_dio_bio; 7806 btrfs_io_bio(bio)->logical = file_offset; 7807 7808 ASSERT(submit_len >= clone_len); 7809 submit_len -= clone_len; 7810 7811 /* 7812 * Increase the count before we submit the bio so we know 7813 * the end IO handler won't happen before we increase the 7814 * count. Otherwise, the dip might get freed before we're 7815 * done setting it up. 7816 * 7817 * We transfer the initial reference to the last bio, so we 7818 * don't need to increment the reference count for the last one. 7819 */ 7820 if (submit_len > 0) { 7821 refcount_inc(&dip->refs); 7822 /* 7823 * If we are submitting more than one bio, submit them 7824 * all asynchronously. The exception is RAID 5 or 6, as 7825 * asynchronous checksums make it difficult to collect 7826 * full stripe writes. 7827 */ 7828 if (!raid56) 7829 async_submit = 1; 7830 } 7831 7832 status = btrfs_submit_dio_bio(bio, inode, file_offset, 7833 async_submit); 7834 if (status) { 7835 bio_put(bio); 7836 if (submit_len > 0) 7837 refcount_dec(&dip->refs); 7838 goto out_err; 7839 } 7840 7841 clone_offset += clone_len; 7842 start_sector += clone_len >> 9; 7843 file_offset += clone_len; 7844 } while (submit_len > 0); 7845 return; 7846 7847 out_err: 7848 dip->dio_bio->bi_status = status; 7849 btrfs_dio_private_put(dip); 7850 } 7851 7852 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info, 7853 const struct iov_iter *iter, loff_t offset) 7854 { 7855 int seg; 7856 int i; 7857 unsigned int blocksize_mask = fs_info->sectorsize - 1; 7858 ssize_t retval = -EINVAL; 7859 7860 if (offset & blocksize_mask) 7861 goto out; 7862 7863 if (iov_iter_alignment(iter) & blocksize_mask) 7864 goto out; 7865 7866 /* If this is a write we don't need to check anymore */ 7867 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter)) 7868 return 0; 7869 /* 7870 * Check to make sure we don't have duplicate iov_base's in this 7871 * iovec, if so return EINVAL, otherwise we'll get csum errors 7872 * when reading back. 7873 */ 7874 for (seg = 0; seg < iter->nr_segs; seg++) { 7875 for (i = seg + 1; i < iter->nr_segs; i++) { 7876 if (iter->iov[seg].iov_base == iter->iov[i].iov_base) 7877 goto out; 7878 } 7879 } 7880 retval = 0; 7881 out: 7882 return retval; 7883 } 7884 7885 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter) 7886 { 7887 struct file *file = iocb->ki_filp; 7888 struct inode *inode = file->f_mapping->host; 7889 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 7890 struct btrfs_dio_data dio_data = { 0 }; 7891 struct extent_changeset *data_reserved = NULL; 7892 loff_t offset = iocb->ki_pos; 7893 size_t count = 0; 7894 int flags = 0; 7895 bool wakeup = true; 7896 bool relock = false; 7897 ssize_t ret; 7898 7899 if (check_direct_IO(fs_info, iter, offset)) 7900 return 0; 7901 7902 inode_dio_begin(inode); 7903 7904 /* 7905 * The generic stuff only does filemap_write_and_wait_range, which 7906 * isn't enough if we've written compressed pages to this area, so 7907 * we need to flush the dirty pages again to make absolutely sure 7908 * that any outstanding dirty pages are on disk. 7909 */ 7910 count = iov_iter_count(iter); 7911 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, 7912 &BTRFS_I(inode)->runtime_flags)) 7913 filemap_fdatawrite_range(inode->i_mapping, offset, 7914 offset + count - 1); 7915 7916 if (iov_iter_rw(iter) == WRITE) { 7917 /* 7918 * If the write DIO is beyond the EOF, we need update 7919 * the isize, but it is protected by i_mutex. So we can 7920 * not unlock the i_mutex at this case. 7921 */ 7922 if (offset + count <= inode->i_size) { 7923 dio_data.overwrite = 1; 7924 inode_unlock(inode); 7925 relock = true; 7926 } 7927 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved, 7928 offset, count); 7929 if (ret) 7930 goto out; 7931 7932 /* 7933 * We need to know how many extents we reserved so that we can 7934 * do the accounting properly if we go over the number we 7935 * originally calculated. Abuse current->journal_info for this. 7936 */ 7937 dio_data.reserve = round_up(count, 7938 fs_info->sectorsize); 7939 dio_data.unsubmitted_oe_range_start = (u64)offset; 7940 dio_data.unsubmitted_oe_range_end = (u64)offset; 7941 current->journal_info = &dio_data; 7942 down_read(&BTRFS_I(inode)->dio_sem); 7943 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK, 7944 &BTRFS_I(inode)->runtime_flags)) { 7945 inode_dio_end(inode); 7946 flags = DIO_LOCKING | DIO_SKIP_HOLES; 7947 wakeup = false; 7948 } 7949 7950 ret = __blockdev_direct_IO(iocb, inode, 7951 fs_info->fs_devices->latest_bdev, 7952 iter, btrfs_get_blocks_direct, NULL, 7953 btrfs_submit_direct, flags); 7954 if (iov_iter_rw(iter) == WRITE) { 7955 up_read(&BTRFS_I(inode)->dio_sem); 7956 current->journal_info = NULL; 7957 if (ret < 0 && ret != -EIOCBQUEUED) { 7958 if (dio_data.reserve) 7959 btrfs_delalloc_release_space(BTRFS_I(inode), 7960 data_reserved, offset, dio_data.reserve, 7961 true); 7962 /* 7963 * On error we might have left some ordered extents 7964 * without submitting corresponding bios for them, so 7965 * cleanup them up to avoid other tasks getting them 7966 * and waiting for them to complete forever. 7967 */ 7968 if (dio_data.unsubmitted_oe_range_start < 7969 dio_data.unsubmitted_oe_range_end) 7970 __endio_write_update_ordered(BTRFS_I(inode), 7971 dio_data.unsubmitted_oe_range_start, 7972 dio_data.unsubmitted_oe_range_end - 7973 dio_data.unsubmitted_oe_range_start, 7974 false); 7975 } else if (ret >= 0 && (size_t)ret < count) 7976 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, 7977 offset, count - (size_t)ret, true); 7978 btrfs_delalloc_release_extents(BTRFS_I(inode), count); 7979 } 7980 out: 7981 if (wakeup) 7982 inode_dio_end(inode); 7983 if (relock) 7984 inode_lock(inode); 7985 7986 extent_changeset_free(data_reserved); 7987 return ret; 7988 } 7989 7990 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, 7991 u64 start, u64 len) 7992 { 7993 int ret; 7994 7995 ret = fiemap_prep(inode, fieinfo, start, &len, 0); 7996 if (ret) 7997 return ret; 7998 7999 return extent_fiemap(inode, fieinfo, start, len); 8000 } 8001 8002 int btrfs_readpage(struct file *file, struct page *page) 8003 { 8004 return extent_read_full_page(page, btrfs_get_extent, 0); 8005 } 8006 8007 static int btrfs_writepage(struct page *page, struct writeback_control *wbc) 8008 { 8009 struct inode *inode = page->mapping->host; 8010 int ret; 8011 8012 if (current->flags & PF_MEMALLOC) { 8013 redirty_page_for_writepage(wbc, page); 8014 unlock_page(page); 8015 return 0; 8016 } 8017 8018 /* 8019 * If we are under memory pressure we will call this directly from the 8020 * VM, we need to make sure we have the inode referenced for the ordered 8021 * extent. If not just return like we didn't do anything. 8022 */ 8023 if (!igrab(inode)) { 8024 redirty_page_for_writepage(wbc, page); 8025 return AOP_WRITEPAGE_ACTIVATE; 8026 } 8027 ret = extent_write_full_page(page, wbc); 8028 btrfs_add_delayed_iput(inode); 8029 return ret; 8030 } 8031 8032 static int btrfs_writepages(struct address_space *mapping, 8033 struct writeback_control *wbc) 8034 { 8035 return extent_writepages(mapping, wbc); 8036 } 8037 8038 static void btrfs_readahead(struct readahead_control *rac) 8039 { 8040 extent_readahead(rac); 8041 } 8042 8043 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags) 8044 { 8045 int ret = try_release_extent_mapping(page, gfp_flags); 8046 if (ret == 1) 8047 detach_page_private(page); 8048 return ret; 8049 } 8050 8051 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags) 8052 { 8053 if (PageWriteback(page) || PageDirty(page)) 8054 return 0; 8055 return __btrfs_releasepage(page, gfp_flags); 8056 } 8057 8058 #ifdef CONFIG_MIGRATION 8059 static int btrfs_migratepage(struct address_space *mapping, 8060 struct page *newpage, struct page *page, 8061 enum migrate_mode mode) 8062 { 8063 int ret; 8064 8065 ret = migrate_page_move_mapping(mapping, newpage, page, 0); 8066 if (ret != MIGRATEPAGE_SUCCESS) 8067 return ret; 8068 8069 if (page_has_private(page)) 8070 attach_page_private(newpage, detach_page_private(page)); 8071 8072 if (PagePrivate2(page)) { 8073 ClearPagePrivate2(page); 8074 SetPagePrivate2(newpage); 8075 } 8076 8077 if (mode != MIGRATE_SYNC_NO_COPY) 8078 migrate_page_copy(newpage, page); 8079 else 8080 migrate_page_states(newpage, page); 8081 return MIGRATEPAGE_SUCCESS; 8082 } 8083 #endif 8084 8085 static void btrfs_invalidatepage(struct page *page, unsigned int offset, 8086 unsigned int length) 8087 { 8088 struct inode *inode = page->mapping->host; 8089 struct extent_io_tree *tree; 8090 struct btrfs_ordered_extent *ordered; 8091 struct extent_state *cached_state = NULL; 8092 u64 page_start = page_offset(page); 8093 u64 page_end = page_start + PAGE_SIZE - 1; 8094 u64 start; 8095 u64 end; 8096 int inode_evicting = inode->i_state & I_FREEING; 8097 8098 /* 8099 * we have the page locked, so new writeback can't start, 8100 * and the dirty bit won't be cleared while we are here. 8101 * 8102 * Wait for IO on this page so that we can safely clear 8103 * the PagePrivate2 bit and do ordered accounting 8104 */ 8105 wait_on_page_writeback(page); 8106 8107 tree = &BTRFS_I(inode)->io_tree; 8108 if (offset) { 8109 btrfs_releasepage(page, GFP_NOFS); 8110 return; 8111 } 8112 8113 if (!inode_evicting) 8114 lock_extent_bits(tree, page_start, page_end, &cached_state); 8115 again: 8116 start = page_start; 8117 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start, 8118 page_end - start + 1); 8119 if (ordered) { 8120 end = min(page_end, 8121 ordered->file_offset + ordered->num_bytes - 1); 8122 /* 8123 * IO on this page will never be started, so we need 8124 * to account for any ordered extents now 8125 */ 8126 if (!inode_evicting) 8127 clear_extent_bit(tree, start, end, 8128 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW | 8129 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING | 8130 EXTENT_DEFRAG, 1, 0, &cached_state); 8131 /* 8132 * whoever cleared the private bit is responsible 8133 * for the finish_ordered_io 8134 */ 8135 if (TestClearPagePrivate2(page)) { 8136 struct btrfs_ordered_inode_tree *tree; 8137 u64 new_len; 8138 8139 tree = &BTRFS_I(inode)->ordered_tree; 8140 8141 spin_lock_irq(&tree->lock); 8142 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags); 8143 new_len = start - ordered->file_offset; 8144 if (new_len < ordered->truncated_len) 8145 ordered->truncated_len = new_len; 8146 spin_unlock_irq(&tree->lock); 8147 8148 if (btrfs_dec_test_ordered_pending(inode, &ordered, 8149 start, 8150 end - start + 1, 1)) 8151 btrfs_finish_ordered_io(ordered); 8152 } 8153 btrfs_put_ordered_extent(ordered); 8154 if (!inode_evicting) { 8155 cached_state = NULL; 8156 lock_extent_bits(tree, start, end, 8157 &cached_state); 8158 } 8159 8160 start = end + 1; 8161 if (start < page_end) 8162 goto again; 8163 } 8164 8165 /* 8166 * Qgroup reserved space handler 8167 * Page here will be either 8168 * 1) Already written to disk or ordered extent already submitted 8169 * Then its QGROUP_RESERVED bit in io_tree is already cleaned. 8170 * Qgroup will be handled by its qgroup_record then. 8171 * btrfs_qgroup_free_data() call will do nothing here. 8172 * 8173 * 2) Not written to disk yet 8174 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED 8175 * bit of its io_tree, and free the qgroup reserved data space. 8176 * Since the IO will never happen for this page. 8177 */ 8178 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, page_start, PAGE_SIZE); 8179 if (!inode_evicting) { 8180 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED | 8181 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW | 8182 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, 8183 &cached_state); 8184 8185 __btrfs_releasepage(page, GFP_NOFS); 8186 } 8187 8188 ClearPageChecked(page); 8189 detach_page_private(page); 8190 } 8191 8192 /* 8193 * btrfs_page_mkwrite() is not allowed to change the file size as it gets 8194 * called from a page fault handler when a page is first dirtied. Hence we must 8195 * be careful to check for EOF conditions here. We set the page up correctly 8196 * for a written page which means we get ENOSPC checking when writing into 8197 * holes and correct delalloc and unwritten extent mapping on filesystems that 8198 * support these features. 8199 * 8200 * We are not allowed to take the i_mutex here so we have to play games to 8201 * protect against truncate races as the page could now be beyond EOF. Because 8202 * truncate_setsize() writes the inode size before removing pages, once we have 8203 * the page lock we can determine safely if the page is beyond EOF. If it is not 8204 * beyond EOF, then the page is guaranteed safe against truncation until we 8205 * unlock the page. 8206 */ 8207 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf) 8208 { 8209 struct page *page = vmf->page; 8210 struct inode *inode = file_inode(vmf->vma->vm_file); 8211 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 8212 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 8213 struct btrfs_ordered_extent *ordered; 8214 struct extent_state *cached_state = NULL; 8215 struct extent_changeset *data_reserved = NULL; 8216 char *kaddr; 8217 unsigned long zero_start; 8218 loff_t size; 8219 vm_fault_t ret; 8220 int ret2; 8221 int reserved = 0; 8222 u64 reserved_space; 8223 u64 page_start; 8224 u64 page_end; 8225 u64 end; 8226 8227 reserved_space = PAGE_SIZE; 8228 8229 sb_start_pagefault(inode->i_sb); 8230 page_start = page_offset(page); 8231 page_end = page_start + PAGE_SIZE - 1; 8232 end = page_end; 8233 8234 /* 8235 * Reserving delalloc space after obtaining the page lock can lead to 8236 * deadlock. For example, if a dirty page is locked by this function 8237 * and the call to btrfs_delalloc_reserve_space() ends up triggering 8238 * dirty page write out, then the btrfs_writepage() function could 8239 * end up waiting indefinitely to get a lock on the page currently 8240 * being processed by btrfs_page_mkwrite() function. 8241 */ 8242 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved, 8243 page_start, reserved_space); 8244 if (!ret2) { 8245 ret2 = file_update_time(vmf->vma->vm_file); 8246 reserved = 1; 8247 } 8248 if (ret2) { 8249 ret = vmf_error(ret2); 8250 if (reserved) 8251 goto out; 8252 goto out_noreserve; 8253 } 8254 8255 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */ 8256 again: 8257 lock_page(page); 8258 size = i_size_read(inode); 8259 8260 if ((page->mapping != inode->i_mapping) || 8261 (page_start >= size)) { 8262 /* page got truncated out from underneath us */ 8263 goto out_unlock; 8264 } 8265 wait_on_page_writeback(page); 8266 8267 lock_extent_bits(io_tree, page_start, page_end, &cached_state); 8268 set_page_extent_mapped(page); 8269 8270 /* 8271 * we can't set the delalloc bits if there are pending ordered 8272 * extents. Drop our locks and wait for them to finish 8273 */ 8274 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start, 8275 PAGE_SIZE); 8276 if (ordered) { 8277 unlock_extent_cached(io_tree, page_start, page_end, 8278 &cached_state); 8279 unlock_page(page); 8280 btrfs_start_ordered_extent(inode, ordered, 1); 8281 btrfs_put_ordered_extent(ordered); 8282 goto again; 8283 } 8284 8285 if (page->index == ((size - 1) >> PAGE_SHIFT)) { 8286 reserved_space = round_up(size - page_start, 8287 fs_info->sectorsize); 8288 if (reserved_space < PAGE_SIZE) { 8289 end = page_start + reserved_space - 1; 8290 btrfs_delalloc_release_space(BTRFS_I(inode), 8291 data_reserved, page_start, 8292 PAGE_SIZE - reserved_space, true); 8293 } 8294 } 8295 8296 /* 8297 * page_mkwrite gets called when the page is firstly dirtied after it's 8298 * faulted in, but write(2) could also dirty a page and set delalloc 8299 * bits, thus in this case for space account reason, we still need to 8300 * clear any delalloc bits within this page range since we have to 8301 * reserve data&meta space before lock_page() (see above comments). 8302 */ 8303 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end, 8304 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | 8305 EXTENT_DEFRAG, 0, 0, &cached_state); 8306 8307 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0, 8308 &cached_state); 8309 if (ret2) { 8310 unlock_extent_cached(io_tree, page_start, page_end, 8311 &cached_state); 8312 ret = VM_FAULT_SIGBUS; 8313 goto out_unlock; 8314 } 8315 8316 /* page is wholly or partially inside EOF */ 8317 if (page_start + PAGE_SIZE > size) 8318 zero_start = offset_in_page(size); 8319 else 8320 zero_start = PAGE_SIZE; 8321 8322 if (zero_start != PAGE_SIZE) { 8323 kaddr = kmap(page); 8324 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start); 8325 flush_dcache_page(page); 8326 kunmap(page); 8327 } 8328 ClearPageChecked(page); 8329 set_page_dirty(page); 8330 SetPageUptodate(page); 8331 8332 BTRFS_I(inode)->last_trans = fs_info->generation; 8333 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid; 8334 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit; 8335 8336 unlock_extent_cached(io_tree, page_start, page_end, &cached_state); 8337 8338 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE); 8339 sb_end_pagefault(inode->i_sb); 8340 extent_changeset_free(data_reserved); 8341 return VM_FAULT_LOCKED; 8342 8343 out_unlock: 8344 unlock_page(page); 8345 out: 8346 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE); 8347 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start, 8348 reserved_space, (ret != 0)); 8349 out_noreserve: 8350 sb_end_pagefault(inode->i_sb); 8351 extent_changeset_free(data_reserved); 8352 return ret; 8353 } 8354 8355 static int btrfs_truncate(struct inode *inode, bool skip_writeback) 8356 { 8357 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 8358 struct btrfs_root *root = BTRFS_I(inode)->root; 8359 struct btrfs_block_rsv *rsv; 8360 int ret; 8361 struct btrfs_trans_handle *trans; 8362 u64 mask = fs_info->sectorsize - 1; 8363 u64 min_size = btrfs_calc_metadata_size(fs_info, 1); 8364 8365 if (!skip_writeback) { 8366 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask), 8367 (u64)-1); 8368 if (ret) 8369 return ret; 8370 } 8371 8372 /* 8373 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of 8374 * things going on here: 8375 * 8376 * 1) We need to reserve space to update our inode. 8377 * 8378 * 2) We need to have something to cache all the space that is going to 8379 * be free'd up by the truncate operation, but also have some slack 8380 * space reserved in case it uses space during the truncate (thank you 8381 * very much snapshotting). 8382 * 8383 * And we need these to be separate. The fact is we can use a lot of 8384 * space doing the truncate, and we have no earthly idea how much space 8385 * we will use, so we need the truncate reservation to be separate so it 8386 * doesn't end up using space reserved for updating the inode. We also 8387 * need to be able to stop the transaction and start a new one, which 8388 * means we need to be able to update the inode several times, and we 8389 * have no idea of knowing how many times that will be, so we can't just 8390 * reserve 1 item for the entirety of the operation, so that has to be 8391 * done separately as well. 8392 * 8393 * So that leaves us with 8394 * 8395 * 1) rsv - for the truncate reservation, which we will steal from the 8396 * transaction reservation. 8397 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for 8398 * updating the inode. 8399 */ 8400 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP); 8401 if (!rsv) 8402 return -ENOMEM; 8403 rsv->size = min_size; 8404 rsv->failfast = 1; 8405 8406 /* 8407 * 1 for the truncate slack space 8408 * 1 for updating the inode. 8409 */ 8410 trans = btrfs_start_transaction(root, 2); 8411 if (IS_ERR(trans)) { 8412 ret = PTR_ERR(trans); 8413 goto out; 8414 } 8415 8416 /* Migrate the slack space for the truncate to our reserve */ 8417 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv, 8418 min_size, false); 8419 BUG_ON(ret); 8420 8421 /* 8422 * So if we truncate and then write and fsync we normally would just 8423 * write the extents that changed, which is a problem if we need to 8424 * first truncate that entire inode. So set this flag so we write out 8425 * all of the extents in the inode to the sync log so we're completely 8426 * safe. 8427 */ 8428 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); 8429 trans->block_rsv = rsv; 8430 8431 while (1) { 8432 ret = btrfs_truncate_inode_items(trans, root, inode, 8433 inode->i_size, 8434 BTRFS_EXTENT_DATA_KEY); 8435 trans->block_rsv = &fs_info->trans_block_rsv; 8436 if (ret != -ENOSPC && ret != -EAGAIN) 8437 break; 8438 8439 ret = btrfs_update_inode(trans, root, inode); 8440 if (ret) 8441 break; 8442 8443 btrfs_end_transaction(trans); 8444 btrfs_btree_balance_dirty(fs_info); 8445 8446 trans = btrfs_start_transaction(root, 2); 8447 if (IS_ERR(trans)) { 8448 ret = PTR_ERR(trans); 8449 trans = NULL; 8450 break; 8451 } 8452 8453 btrfs_block_rsv_release(fs_info, rsv, -1, NULL); 8454 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, 8455 rsv, min_size, false); 8456 BUG_ON(ret); /* shouldn't happen */ 8457 trans->block_rsv = rsv; 8458 } 8459 8460 /* 8461 * We can't call btrfs_truncate_block inside a trans handle as we could 8462 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know 8463 * we've truncated everything except the last little bit, and can do 8464 * btrfs_truncate_block and then update the disk_i_size. 8465 */ 8466 if (ret == NEED_TRUNCATE_BLOCK) { 8467 btrfs_end_transaction(trans); 8468 btrfs_btree_balance_dirty(fs_info); 8469 8470 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0); 8471 if (ret) 8472 goto out; 8473 trans = btrfs_start_transaction(root, 1); 8474 if (IS_ERR(trans)) { 8475 ret = PTR_ERR(trans); 8476 goto out; 8477 } 8478 btrfs_inode_safe_disk_i_size_write(inode, 0); 8479 } 8480 8481 if (trans) { 8482 int ret2; 8483 8484 trans->block_rsv = &fs_info->trans_block_rsv; 8485 ret2 = btrfs_update_inode(trans, root, inode); 8486 if (ret2 && !ret) 8487 ret = ret2; 8488 8489 ret2 = btrfs_end_transaction(trans); 8490 if (ret2 && !ret) 8491 ret = ret2; 8492 btrfs_btree_balance_dirty(fs_info); 8493 } 8494 out: 8495 btrfs_free_block_rsv(fs_info, rsv); 8496 8497 return ret; 8498 } 8499 8500 /* 8501 * create a new subvolume directory/inode (helper for the ioctl). 8502 */ 8503 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans, 8504 struct btrfs_root *new_root, 8505 struct btrfs_root *parent_root, 8506 u64 new_dirid) 8507 { 8508 struct inode *inode; 8509 int err; 8510 u64 index = 0; 8511 8512 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, 8513 new_dirid, new_dirid, 8514 S_IFDIR | (~current_umask() & S_IRWXUGO), 8515 &index); 8516 if (IS_ERR(inode)) 8517 return PTR_ERR(inode); 8518 inode->i_op = &btrfs_dir_inode_operations; 8519 inode->i_fop = &btrfs_dir_file_operations; 8520 8521 set_nlink(inode, 1); 8522 btrfs_i_size_write(BTRFS_I(inode), 0); 8523 unlock_new_inode(inode); 8524 8525 err = btrfs_subvol_inherit_props(trans, new_root, parent_root); 8526 if (err) 8527 btrfs_err(new_root->fs_info, 8528 "error inheriting subvolume %llu properties: %d", 8529 new_root->root_key.objectid, err); 8530 8531 err = btrfs_update_inode(trans, new_root, inode); 8532 8533 iput(inode); 8534 return err; 8535 } 8536 8537 struct inode *btrfs_alloc_inode(struct super_block *sb) 8538 { 8539 struct btrfs_fs_info *fs_info = btrfs_sb(sb); 8540 struct btrfs_inode *ei; 8541 struct inode *inode; 8542 8543 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL); 8544 if (!ei) 8545 return NULL; 8546 8547 ei->root = NULL; 8548 ei->generation = 0; 8549 ei->last_trans = 0; 8550 ei->last_sub_trans = 0; 8551 ei->logged_trans = 0; 8552 ei->delalloc_bytes = 0; 8553 ei->new_delalloc_bytes = 0; 8554 ei->defrag_bytes = 0; 8555 ei->disk_i_size = 0; 8556 ei->flags = 0; 8557 ei->csum_bytes = 0; 8558 ei->index_cnt = (u64)-1; 8559 ei->dir_index = 0; 8560 ei->last_unlink_trans = 0; 8561 ei->last_reflink_trans = 0; 8562 ei->last_log_commit = 0; 8563 8564 spin_lock_init(&ei->lock); 8565 ei->outstanding_extents = 0; 8566 if (sb->s_magic != BTRFS_TEST_MAGIC) 8567 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv, 8568 BTRFS_BLOCK_RSV_DELALLOC); 8569 ei->runtime_flags = 0; 8570 ei->prop_compress = BTRFS_COMPRESS_NONE; 8571 ei->defrag_compress = BTRFS_COMPRESS_NONE; 8572 8573 ei->delayed_node = NULL; 8574 8575 ei->i_otime.tv_sec = 0; 8576 ei->i_otime.tv_nsec = 0; 8577 8578 inode = &ei->vfs_inode; 8579 extent_map_tree_init(&ei->extent_tree); 8580 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode); 8581 extent_io_tree_init(fs_info, &ei->io_failure_tree, 8582 IO_TREE_INODE_IO_FAILURE, inode); 8583 extent_io_tree_init(fs_info, &ei->file_extent_tree, 8584 IO_TREE_INODE_FILE_EXTENT, inode); 8585 ei->io_tree.track_uptodate = true; 8586 ei->io_failure_tree.track_uptodate = true; 8587 atomic_set(&ei->sync_writers, 0); 8588 mutex_init(&ei->log_mutex); 8589 btrfs_ordered_inode_tree_init(&ei->ordered_tree); 8590 INIT_LIST_HEAD(&ei->delalloc_inodes); 8591 INIT_LIST_HEAD(&ei->delayed_iput); 8592 RB_CLEAR_NODE(&ei->rb_node); 8593 init_rwsem(&ei->dio_sem); 8594 8595 return inode; 8596 } 8597 8598 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS 8599 void btrfs_test_destroy_inode(struct inode *inode) 8600 { 8601 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0); 8602 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); 8603 } 8604 #endif 8605 8606 void btrfs_free_inode(struct inode *inode) 8607 { 8608 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); 8609 } 8610 8611 void btrfs_destroy_inode(struct inode *inode) 8612 { 8613 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 8614 struct btrfs_ordered_extent *ordered; 8615 struct btrfs_root *root = BTRFS_I(inode)->root; 8616 8617 WARN_ON(!hlist_empty(&inode->i_dentry)); 8618 WARN_ON(inode->i_data.nrpages); 8619 WARN_ON(BTRFS_I(inode)->block_rsv.reserved); 8620 WARN_ON(BTRFS_I(inode)->block_rsv.size); 8621 WARN_ON(BTRFS_I(inode)->outstanding_extents); 8622 WARN_ON(BTRFS_I(inode)->delalloc_bytes); 8623 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes); 8624 WARN_ON(BTRFS_I(inode)->csum_bytes); 8625 WARN_ON(BTRFS_I(inode)->defrag_bytes); 8626 8627 /* 8628 * This can happen where we create an inode, but somebody else also 8629 * created the same inode and we need to destroy the one we already 8630 * created. 8631 */ 8632 if (!root) 8633 return; 8634 8635 while (1) { 8636 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1); 8637 if (!ordered) 8638 break; 8639 else { 8640 btrfs_err(fs_info, 8641 "found ordered extent %llu %llu on inode cleanup", 8642 ordered->file_offset, ordered->num_bytes); 8643 btrfs_remove_ordered_extent(inode, ordered); 8644 btrfs_put_ordered_extent(ordered); 8645 btrfs_put_ordered_extent(ordered); 8646 } 8647 } 8648 btrfs_qgroup_check_reserved_leak(BTRFS_I(inode)); 8649 inode_tree_del(inode); 8650 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0); 8651 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1); 8652 btrfs_put_root(BTRFS_I(inode)->root); 8653 } 8654 8655 int btrfs_drop_inode(struct inode *inode) 8656 { 8657 struct btrfs_root *root = BTRFS_I(inode)->root; 8658 8659 if (root == NULL) 8660 return 1; 8661 8662 /* the snap/subvol tree is on deleting */ 8663 if (btrfs_root_refs(&root->root_item) == 0) 8664 return 1; 8665 else 8666 return generic_drop_inode(inode); 8667 } 8668 8669 static void init_once(void *foo) 8670 { 8671 struct btrfs_inode *ei = (struct btrfs_inode *) foo; 8672 8673 inode_init_once(&ei->vfs_inode); 8674 } 8675 8676 void __cold btrfs_destroy_cachep(void) 8677 { 8678 /* 8679 * Make sure all delayed rcu free inodes are flushed before we 8680 * destroy cache. 8681 */ 8682 rcu_barrier(); 8683 kmem_cache_destroy(btrfs_inode_cachep); 8684 kmem_cache_destroy(btrfs_trans_handle_cachep); 8685 kmem_cache_destroy(btrfs_path_cachep); 8686 kmem_cache_destroy(btrfs_free_space_cachep); 8687 kmem_cache_destroy(btrfs_free_space_bitmap_cachep); 8688 } 8689 8690 int __init btrfs_init_cachep(void) 8691 { 8692 btrfs_inode_cachep = kmem_cache_create("btrfs_inode", 8693 sizeof(struct btrfs_inode), 0, 8694 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT, 8695 init_once); 8696 if (!btrfs_inode_cachep) 8697 goto fail; 8698 8699 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle", 8700 sizeof(struct btrfs_trans_handle), 0, 8701 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL); 8702 if (!btrfs_trans_handle_cachep) 8703 goto fail; 8704 8705 btrfs_path_cachep = kmem_cache_create("btrfs_path", 8706 sizeof(struct btrfs_path), 0, 8707 SLAB_MEM_SPREAD, NULL); 8708 if (!btrfs_path_cachep) 8709 goto fail; 8710 8711 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space", 8712 sizeof(struct btrfs_free_space), 0, 8713 SLAB_MEM_SPREAD, NULL); 8714 if (!btrfs_free_space_cachep) 8715 goto fail; 8716 8717 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap", 8718 PAGE_SIZE, PAGE_SIZE, 8719 SLAB_RED_ZONE, NULL); 8720 if (!btrfs_free_space_bitmap_cachep) 8721 goto fail; 8722 8723 return 0; 8724 fail: 8725 btrfs_destroy_cachep(); 8726 return -ENOMEM; 8727 } 8728 8729 static int btrfs_getattr(const struct path *path, struct kstat *stat, 8730 u32 request_mask, unsigned int flags) 8731 { 8732 u64 delalloc_bytes; 8733 struct inode *inode = d_inode(path->dentry); 8734 u32 blocksize = inode->i_sb->s_blocksize; 8735 u32 bi_flags = BTRFS_I(inode)->flags; 8736 8737 stat->result_mask |= STATX_BTIME; 8738 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec; 8739 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec; 8740 if (bi_flags & BTRFS_INODE_APPEND) 8741 stat->attributes |= STATX_ATTR_APPEND; 8742 if (bi_flags & BTRFS_INODE_COMPRESS) 8743 stat->attributes |= STATX_ATTR_COMPRESSED; 8744 if (bi_flags & BTRFS_INODE_IMMUTABLE) 8745 stat->attributes |= STATX_ATTR_IMMUTABLE; 8746 if (bi_flags & BTRFS_INODE_NODUMP) 8747 stat->attributes |= STATX_ATTR_NODUMP; 8748 8749 stat->attributes_mask |= (STATX_ATTR_APPEND | 8750 STATX_ATTR_COMPRESSED | 8751 STATX_ATTR_IMMUTABLE | 8752 STATX_ATTR_NODUMP); 8753 8754 generic_fillattr(inode, stat); 8755 stat->dev = BTRFS_I(inode)->root->anon_dev; 8756 8757 spin_lock(&BTRFS_I(inode)->lock); 8758 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes; 8759 spin_unlock(&BTRFS_I(inode)->lock); 8760 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) + 8761 ALIGN(delalloc_bytes, blocksize)) >> 9; 8762 return 0; 8763 } 8764 8765 static int btrfs_rename_exchange(struct inode *old_dir, 8766 struct dentry *old_dentry, 8767 struct inode *new_dir, 8768 struct dentry *new_dentry) 8769 { 8770 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb); 8771 struct btrfs_trans_handle *trans; 8772 struct btrfs_root *root = BTRFS_I(old_dir)->root; 8773 struct btrfs_root *dest = BTRFS_I(new_dir)->root; 8774 struct inode *new_inode = new_dentry->d_inode; 8775 struct inode *old_inode = old_dentry->d_inode; 8776 struct timespec64 ctime = current_time(old_inode); 8777 struct dentry *parent; 8778 u64 old_ino = btrfs_ino(BTRFS_I(old_inode)); 8779 u64 new_ino = btrfs_ino(BTRFS_I(new_inode)); 8780 u64 old_idx = 0; 8781 u64 new_idx = 0; 8782 int ret; 8783 bool root_log_pinned = false; 8784 bool dest_log_pinned = false; 8785 struct btrfs_log_ctx ctx_root; 8786 struct btrfs_log_ctx ctx_dest; 8787 bool sync_log_root = false; 8788 bool sync_log_dest = false; 8789 bool commit_transaction = false; 8790 8791 /* we only allow rename subvolume link between subvolumes */ 8792 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) 8793 return -EXDEV; 8794 8795 btrfs_init_log_ctx(&ctx_root, old_inode); 8796 btrfs_init_log_ctx(&ctx_dest, new_inode); 8797 8798 /* close the race window with snapshot create/destroy ioctl */ 8799 if (old_ino == BTRFS_FIRST_FREE_OBJECTID || 8800 new_ino == BTRFS_FIRST_FREE_OBJECTID) 8801 down_read(&fs_info->subvol_sem); 8802 8803 /* 8804 * We want to reserve the absolute worst case amount of items. So if 8805 * both inodes are subvols and we need to unlink them then that would 8806 * require 4 item modifications, but if they are both normal inodes it 8807 * would require 5 item modifications, so we'll assume their normal 8808 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items 8809 * should cover the worst case number of items we'll modify. 8810 */ 8811 trans = btrfs_start_transaction(root, 12); 8812 if (IS_ERR(trans)) { 8813 ret = PTR_ERR(trans); 8814 goto out_notrans; 8815 } 8816 8817 if (dest != root) 8818 btrfs_record_root_in_trans(trans, dest); 8819 8820 /* 8821 * We need to find a free sequence number both in the source and 8822 * in the destination directory for the exchange. 8823 */ 8824 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx); 8825 if (ret) 8826 goto out_fail; 8827 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx); 8828 if (ret) 8829 goto out_fail; 8830 8831 BTRFS_I(old_inode)->dir_index = 0ULL; 8832 BTRFS_I(new_inode)->dir_index = 0ULL; 8833 8834 /* Reference for the source. */ 8835 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) { 8836 /* force full log commit if subvolume involved. */ 8837 btrfs_set_log_full_commit(trans); 8838 } else { 8839 btrfs_pin_log_trans(root); 8840 root_log_pinned = true; 8841 ret = btrfs_insert_inode_ref(trans, dest, 8842 new_dentry->d_name.name, 8843 new_dentry->d_name.len, 8844 old_ino, 8845 btrfs_ino(BTRFS_I(new_dir)), 8846 old_idx); 8847 if (ret) 8848 goto out_fail; 8849 } 8850 8851 /* And now for the dest. */ 8852 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) { 8853 /* force full log commit if subvolume involved. */ 8854 btrfs_set_log_full_commit(trans); 8855 } else { 8856 btrfs_pin_log_trans(dest); 8857 dest_log_pinned = true; 8858 ret = btrfs_insert_inode_ref(trans, root, 8859 old_dentry->d_name.name, 8860 old_dentry->d_name.len, 8861 new_ino, 8862 btrfs_ino(BTRFS_I(old_dir)), 8863 new_idx); 8864 if (ret) 8865 goto out_fail; 8866 } 8867 8868 /* Update inode version and ctime/mtime. */ 8869 inode_inc_iversion(old_dir); 8870 inode_inc_iversion(new_dir); 8871 inode_inc_iversion(old_inode); 8872 inode_inc_iversion(new_inode); 8873 old_dir->i_ctime = old_dir->i_mtime = ctime; 8874 new_dir->i_ctime = new_dir->i_mtime = ctime; 8875 old_inode->i_ctime = ctime; 8876 new_inode->i_ctime = ctime; 8877 8878 if (old_dentry->d_parent != new_dentry->d_parent) { 8879 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir), 8880 BTRFS_I(old_inode), 1); 8881 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir), 8882 BTRFS_I(new_inode), 1); 8883 } 8884 8885 /* src is a subvolume */ 8886 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) { 8887 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry); 8888 } else { /* src is an inode */ 8889 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir), 8890 BTRFS_I(old_dentry->d_inode), 8891 old_dentry->d_name.name, 8892 old_dentry->d_name.len); 8893 if (!ret) 8894 ret = btrfs_update_inode(trans, root, old_inode); 8895 } 8896 if (ret) { 8897 btrfs_abort_transaction(trans, ret); 8898 goto out_fail; 8899 } 8900 8901 /* dest is a subvolume */ 8902 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) { 8903 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry); 8904 } else { /* dest is an inode */ 8905 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir), 8906 BTRFS_I(new_dentry->d_inode), 8907 new_dentry->d_name.name, 8908 new_dentry->d_name.len); 8909 if (!ret) 8910 ret = btrfs_update_inode(trans, dest, new_inode); 8911 } 8912 if (ret) { 8913 btrfs_abort_transaction(trans, ret); 8914 goto out_fail; 8915 } 8916 8917 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode), 8918 new_dentry->d_name.name, 8919 new_dentry->d_name.len, 0, old_idx); 8920 if (ret) { 8921 btrfs_abort_transaction(trans, ret); 8922 goto out_fail; 8923 } 8924 8925 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode), 8926 old_dentry->d_name.name, 8927 old_dentry->d_name.len, 0, new_idx); 8928 if (ret) { 8929 btrfs_abort_transaction(trans, ret); 8930 goto out_fail; 8931 } 8932 8933 if (old_inode->i_nlink == 1) 8934 BTRFS_I(old_inode)->dir_index = old_idx; 8935 if (new_inode->i_nlink == 1) 8936 BTRFS_I(new_inode)->dir_index = new_idx; 8937 8938 if (root_log_pinned) { 8939 parent = new_dentry->d_parent; 8940 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode), 8941 BTRFS_I(old_dir), parent, 8942 false, &ctx_root); 8943 if (ret == BTRFS_NEED_LOG_SYNC) 8944 sync_log_root = true; 8945 else if (ret == BTRFS_NEED_TRANS_COMMIT) 8946 commit_transaction = true; 8947 ret = 0; 8948 btrfs_end_log_trans(root); 8949 root_log_pinned = false; 8950 } 8951 if (dest_log_pinned) { 8952 if (!commit_transaction) { 8953 parent = old_dentry->d_parent; 8954 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode), 8955 BTRFS_I(new_dir), parent, 8956 false, &ctx_dest); 8957 if (ret == BTRFS_NEED_LOG_SYNC) 8958 sync_log_dest = true; 8959 else if (ret == BTRFS_NEED_TRANS_COMMIT) 8960 commit_transaction = true; 8961 ret = 0; 8962 } 8963 btrfs_end_log_trans(dest); 8964 dest_log_pinned = false; 8965 } 8966 out_fail: 8967 /* 8968 * If we have pinned a log and an error happened, we unpin tasks 8969 * trying to sync the log and force them to fallback to a transaction 8970 * commit if the log currently contains any of the inodes involved in 8971 * this rename operation (to ensure we do not persist a log with an 8972 * inconsistent state for any of these inodes or leading to any 8973 * inconsistencies when replayed). If the transaction was aborted, the 8974 * abortion reason is propagated to userspace when attempting to commit 8975 * the transaction. If the log does not contain any of these inodes, we 8976 * allow the tasks to sync it. 8977 */ 8978 if (ret && (root_log_pinned || dest_log_pinned)) { 8979 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) || 8980 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) || 8981 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) || 8982 (new_inode && 8983 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation))) 8984 btrfs_set_log_full_commit(trans); 8985 8986 if (root_log_pinned) { 8987 btrfs_end_log_trans(root); 8988 root_log_pinned = false; 8989 } 8990 if (dest_log_pinned) { 8991 btrfs_end_log_trans(dest); 8992 dest_log_pinned = false; 8993 } 8994 } 8995 if (!ret && sync_log_root && !commit_transaction) { 8996 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, 8997 &ctx_root); 8998 if (ret) 8999 commit_transaction = true; 9000 } 9001 if (!ret && sync_log_dest && !commit_transaction) { 9002 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root, 9003 &ctx_dest); 9004 if (ret) 9005 commit_transaction = true; 9006 } 9007 if (commit_transaction) { 9008 /* 9009 * We may have set commit_transaction when logging the new name 9010 * in the destination root, in which case we left the source 9011 * root context in the list of log contextes. So make sure we 9012 * remove it to avoid invalid memory accesses, since the context 9013 * was allocated in our stack frame. 9014 */ 9015 if (sync_log_root) { 9016 mutex_lock(&root->log_mutex); 9017 list_del_init(&ctx_root.list); 9018 mutex_unlock(&root->log_mutex); 9019 } 9020 ret = btrfs_commit_transaction(trans); 9021 } else { 9022 int ret2; 9023 9024 ret2 = btrfs_end_transaction(trans); 9025 ret = ret ? ret : ret2; 9026 } 9027 out_notrans: 9028 if (new_ino == BTRFS_FIRST_FREE_OBJECTID || 9029 old_ino == BTRFS_FIRST_FREE_OBJECTID) 9030 up_read(&fs_info->subvol_sem); 9031 9032 ASSERT(list_empty(&ctx_root.list)); 9033 ASSERT(list_empty(&ctx_dest.list)); 9034 9035 return ret; 9036 } 9037 9038 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans, 9039 struct btrfs_root *root, 9040 struct inode *dir, 9041 struct dentry *dentry) 9042 { 9043 int ret; 9044 struct inode *inode; 9045 u64 objectid; 9046 u64 index; 9047 9048 ret = btrfs_find_free_ino(root, &objectid); 9049 if (ret) 9050 return ret; 9051 9052 inode = btrfs_new_inode(trans, root, dir, 9053 dentry->d_name.name, 9054 dentry->d_name.len, 9055 btrfs_ino(BTRFS_I(dir)), 9056 objectid, 9057 S_IFCHR | WHITEOUT_MODE, 9058 &index); 9059 9060 if (IS_ERR(inode)) { 9061 ret = PTR_ERR(inode); 9062 return ret; 9063 } 9064 9065 inode->i_op = &btrfs_special_inode_operations; 9066 init_special_inode(inode, inode->i_mode, 9067 WHITEOUT_DEV); 9068 9069 ret = btrfs_init_inode_security(trans, inode, dir, 9070 &dentry->d_name); 9071 if (ret) 9072 goto out; 9073 9074 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, 9075 BTRFS_I(inode), 0, index); 9076 if (ret) 9077 goto out; 9078 9079 ret = btrfs_update_inode(trans, root, inode); 9080 out: 9081 unlock_new_inode(inode); 9082 if (ret) 9083 inode_dec_link_count(inode); 9084 iput(inode); 9085 9086 return ret; 9087 } 9088 9089 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, 9090 struct inode *new_dir, struct dentry *new_dentry, 9091 unsigned int flags) 9092 { 9093 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb); 9094 struct btrfs_trans_handle *trans; 9095 unsigned int trans_num_items; 9096 struct btrfs_root *root = BTRFS_I(old_dir)->root; 9097 struct btrfs_root *dest = BTRFS_I(new_dir)->root; 9098 struct inode *new_inode = d_inode(new_dentry); 9099 struct inode *old_inode = d_inode(old_dentry); 9100 u64 index = 0; 9101 int ret; 9102 u64 old_ino = btrfs_ino(BTRFS_I(old_inode)); 9103 bool log_pinned = false; 9104 struct btrfs_log_ctx ctx; 9105 bool sync_log = false; 9106 bool commit_transaction = false; 9107 9108 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) 9109 return -EPERM; 9110 9111 /* we only allow rename subvolume link between subvolumes */ 9112 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) 9113 return -EXDEV; 9114 9115 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || 9116 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID)) 9117 return -ENOTEMPTY; 9118 9119 if (S_ISDIR(old_inode->i_mode) && new_inode && 9120 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) 9121 return -ENOTEMPTY; 9122 9123 9124 /* check for collisions, even if the name isn't there */ 9125 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, 9126 new_dentry->d_name.name, 9127 new_dentry->d_name.len); 9128 9129 if (ret) { 9130 if (ret == -EEXIST) { 9131 /* we shouldn't get 9132 * eexist without a new_inode */ 9133 if (WARN_ON(!new_inode)) { 9134 return ret; 9135 } 9136 } else { 9137 /* maybe -EOVERFLOW */ 9138 return ret; 9139 } 9140 } 9141 ret = 0; 9142 9143 /* 9144 * we're using rename to replace one file with another. Start IO on it 9145 * now so we don't add too much work to the end of the transaction 9146 */ 9147 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size) 9148 filemap_flush(old_inode->i_mapping); 9149 9150 /* close the racy window with snapshot create/destroy ioctl */ 9151 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) 9152 down_read(&fs_info->subvol_sem); 9153 /* 9154 * We want to reserve the absolute worst case amount of items. So if 9155 * both inodes are subvols and we need to unlink them then that would 9156 * require 4 item modifications, but if they are both normal inodes it 9157 * would require 5 item modifications, so we'll assume they are normal 9158 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items 9159 * should cover the worst case number of items we'll modify. 9160 * If our rename has the whiteout flag, we need more 5 units for the 9161 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item 9162 * when selinux is enabled). 9163 */ 9164 trans_num_items = 11; 9165 if (flags & RENAME_WHITEOUT) 9166 trans_num_items += 5; 9167 trans = btrfs_start_transaction(root, trans_num_items); 9168 if (IS_ERR(trans)) { 9169 ret = PTR_ERR(trans); 9170 goto out_notrans; 9171 } 9172 9173 if (dest != root) 9174 btrfs_record_root_in_trans(trans, dest); 9175 9176 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index); 9177 if (ret) 9178 goto out_fail; 9179 9180 BTRFS_I(old_inode)->dir_index = 0ULL; 9181 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { 9182 /* force full log commit if subvolume involved. */ 9183 btrfs_set_log_full_commit(trans); 9184 } else { 9185 btrfs_pin_log_trans(root); 9186 log_pinned = true; 9187 ret = btrfs_insert_inode_ref(trans, dest, 9188 new_dentry->d_name.name, 9189 new_dentry->d_name.len, 9190 old_ino, 9191 btrfs_ino(BTRFS_I(new_dir)), index); 9192 if (ret) 9193 goto out_fail; 9194 } 9195 9196 inode_inc_iversion(old_dir); 9197 inode_inc_iversion(new_dir); 9198 inode_inc_iversion(old_inode); 9199 old_dir->i_ctime = old_dir->i_mtime = 9200 new_dir->i_ctime = new_dir->i_mtime = 9201 old_inode->i_ctime = current_time(old_dir); 9202 9203 if (old_dentry->d_parent != new_dentry->d_parent) 9204 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir), 9205 BTRFS_I(old_inode), 1); 9206 9207 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { 9208 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry); 9209 } else { 9210 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir), 9211 BTRFS_I(d_inode(old_dentry)), 9212 old_dentry->d_name.name, 9213 old_dentry->d_name.len); 9214 if (!ret) 9215 ret = btrfs_update_inode(trans, root, old_inode); 9216 } 9217 if (ret) { 9218 btrfs_abort_transaction(trans, ret); 9219 goto out_fail; 9220 } 9221 9222 if (new_inode) { 9223 inode_inc_iversion(new_inode); 9224 new_inode->i_ctime = current_time(new_inode); 9225 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) == 9226 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { 9227 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry); 9228 BUG_ON(new_inode->i_nlink == 0); 9229 } else { 9230 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir), 9231 BTRFS_I(d_inode(new_dentry)), 9232 new_dentry->d_name.name, 9233 new_dentry->d_name.len); 9234 } 9235 if (!ret && new_inode->i_nlink == 0) 9236 ret = btrfs_orphan_add(trans, 9237 BTRFS_I(d_inode(new_dentry))); 9238 if (ret) { 9239 btrfs_abort_transaction(trans, ret); 9240 goto out_fail; 9241 } 9242 } 9243 9244 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode), 9245 new_dentry->d_name.name, 9246 new_dentry->d_name.len, 0, index); 9247 if (ret) { 9248 btrfs_abort_transaction(trans, ret); 9249 goto out_fail; 9250 } 9251 9252 if (old_inode->i_nlink == 1) 9253 BTRFS_I(old_inode)->dir_index = index; 9254 9255 if (log_pinned) { 9256 struct dentry *parent = new_dentry->d_parent; 9257 9258 btrfs_init_log_ctx(&ctx, old_inode); 9259 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode), 9260 BTRFS_I(old_dir), parent, 9261 false, &ctx); 9262 if (ret == BTRFS_NEED_LOG_SYNC) 9263 sync_log = true; 9264 else if (ret == BTRFS_NEED_TRANS_COMMIT) 9265 commit_transaction = true; 9266 ret = 0; 9267 btrfs_end_log_trans(root); 9268 log_pinned = false; 9269 } 9270 9271 if (flags & RENAME_WHITEOUT) { 9272 ret = btrfs_whiteout_for_rename(trans, root, old_dir, 9273 old_dentry); 9274 9275 if (ret) { 9276 btrfs_abort_transaction(trans, ret); 9277 goto out_fail; 9278 } 9279 } 9280 out_fail: 9281 /* 9282 * If we have pinned the log and an error happened, we unpin tasks 9283 * trying to sync the log and force them to fallback to a transaction 9284 * commit if the log currently contains any of the inodes involved in 9285 * this rename operation (to ensure we do not persist a log with an 9286 * inconsistent state for any of these inodes or leading to any 9287 * inconsistencies when replayed). If the transaction was aborted, the 9288 * abortion reason is propagated to userspace when attempting to commit 9289 * the transaction. If the log does not contain any of these inodes, we 9290 * allow the tasks to sync it. 9291 */ 9292 if (ret && log_pinned) { 9293 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) || 9294 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) || 9295 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) || 9296 (new_inode && 9297 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation))) 9298 btrfs_set_log_full_commit(trans); 9299 9300 btrfs_end_log_trans(root); 9301 log_pinned = false; 9302 } 9303 if (!ret && sync_log) { 9304 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx); 9305 if (ret) 9306 commit_transaction = true; 9307 } else if (sync_log) { 9308 mutex_lock(&root->log_mutex); 9309 list_del(&ctx.list); 9310 mutex_unlock(&root->log_mutex); 9311 } 9312 if (commit_transaction) { 9313 ret = btrfs_commit_transaction(trans); 9314 } else { 9315 int ret2; 9316 9317 ret2 = btrfs_end_transaction(trans); 9318 ret = ret ? ret : ret2; 9319 } 9320 out_notrans: 9321 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) 9322 up_read(&fs_info->subvol_sem); 9323 9324 return ret; 9325 } 9326 9327 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry, 9328 struct inode *new_dir, struct dentry *new_dentry, 9329 unsigned int flags) 9330 { 9331 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) 9332 return -EINVAL; 9333 9334 if (flags & RENAME_EXCHANGE) 9335 return btrfs_rename_exchange(old_dir, old_dentry, new_dir, 9336 new_dentry); 9337 9338 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags); 9339 } 9340 9341 struct btrfs_delalloc_work { 9342 struct inode *inode; 9343 struct completion completion; 9344 struct list_head list; 9345 struct btrfs_work work; 9346 }; 9347 9348 static void btrfs_run_delalloc_work(struct btrfs_work *work) 9349 { 9350 struct btrfs_delalloc_work *delalloc_work; 9351 struct inode *inode; 9352 9353 delalloc_work = container_of(work, struct btrfs_delalloc_work, 9354 work); 9355 inode = delalloc_work->inode; 9356 filemap_flush(inode->i_mapping); 9357 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, 9358 &BTRFS_I(inode)->runtime_flags)) 9359 filemap_flush(inode->i_mapping); 9360 9361 iput(inode); 9362 complete(&delalloc_work->completion); 9363 } 9364 9365 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode) 9366 { 9367 struct btrfs_delalloc_work *work; 9368 9369 work = kmalloc(sizeof(*work), GFP_NOFS); 9370 if (!work) 9371 return NULL; 9372 9373 init_completion(&work->completion); 9374 INIT_LIST_HEAD(&work->list); 9375 work->inode = inode; 9376 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL); 9377 9378 return work; 9379 } 9380 9381 /* 9382 * some fairly slow code that needs optimization. This walks the list 9383 * of all the inodes with pending delalloc and forces them to disk. 9384 */ 9385 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot) 9386 { 9387 struct btrfs_inode *binode; 9388 struct inode *inode; 9389 struct btrfs_delalloc_work *work, *next; 9390 struct list_head works; 9391 struct list_head splice; 9392 int ret = 0; 9393 9394 INIT_LIST_HEAD(&works); 9395 INIT_LIST_HEAD(&splice); 9396 9397 mutex_lock(&root->delalloc_mutex); 9398 spin_lock(&root->delalloc_lock); 9399 list_splice_init(&root->delalloc_inodes, &splice); 9400 while (!list_empty(&splice)) { 9401 binode = list_entry(splice.next, struct btrfs_inode, 9402 delalloc_inodes); 9403 9404 list_move_tail(&binode->delalloc_inodes, 9405 &root->delalloc_inodes); 9406 inode = igrab(&binode->vfs_inode); 9407 if (!inode) { 9408 cond_resched_lock(&root->delalloc_lock); 9409 continue; 9410 } 9411 spin_unlock(&root->delalloc_lock); 9412 9413 if (snapshot) 9414 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH, 9415 &binode->runtime_flags); 9416 work = btrfs_alloc_delalloc_work(inode); 9417 if (!work) { 9418 iput(inode); 9419 ret = -ENOMEM; 9420 goto out; 9421 } 9422 list_add_tail(&work->list, &works); 9423 btrfs_queue_work(root->fs_info->flush_workers, 9424 &work->work); 9425 ret++; 9426 if (nr != -1 && ret >= nr) 9427 goto out; 9428 cond_resched(); 9429 spin_lock(&root->delalloc_lock); 9430 } 9431 spin_unlock(&root->delalloc_lock); 9432 9433 out: 9434 list_for_each_entry_safe(work, next, &works, list) { 9435 list_del_init(&work->list); 9436 wait_for_completion(&work->completion); 9437 kfree(work); 9438 } 9439 9440 if (!list_empty(&splice)) { 9441 spin_lock(&root->delalloc_lock); 9442 list_splice_tail(&splice, &root->delalloc_inodes); 9443 spin_unlock(&root->delalloc_lock); 9444 } 9445 mutex_unlock(&root->delalloc_mutex); 9446 return ret; 9447 } 9448 9449 int btrfs_start_delalloc_snapshot(struct btrfs_root *root) 9450 { 9451 struct btrfs_fs_info *fs_info = root->fs_info; 9452 int ret; 9453 9454 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) 9455 return -EROFS; 9456 9457 ret = start_delalloc_inodes(root, -1, true); 9458 if (ret > 0) 9459 ret = 0; 9460 return ret; 9461 } 9462 9463 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr) 9464 { 9465 struct btrfs_root *root; 9466 struct list_head splice; 9467 int ret; 9468 9469 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) 9470 return -EROFS; 9471 9472 INIT_LIST_HEAD(&splice); 9473 9474 mutex_lock(&fs_info->delalloc_root_mutex); 9475 spin_lock(&fs_info->delalloc_root_lock); 9476 list_splice_init(&fs_info->delalloc_roots, &splice); 9477 while (!list_empty(&splice) && nr) { 9478 root = list_first_entry(&splice, struct btrfs_root, 9479 delalloc_root); 9480 root = btrfs_grab_root(root); 9481 BUG_ON(!root); 9482 list_move_tail(&root->delalloc_root, 9483 &fs_info->delalloc_roots); 9484 spin_unlock(&fs_info->delalloc_root_lock); 9485 9486 ret = start_delalloc_inodes(root, nr, false); 9487 btrfs_put_root(root); 9488 if (ret < 0) 9489 goto out; 9490 9491 if (nr != -1) { 9492 nr -= ret; 9493 WARN_ON(nr < 0); 9494 } 9495 spin_lock(&fs_info->delalloc_root_lock); 9496 } 9497 spin_unlock(&fs_info->delalloc_root_lock); 9498 9499 ret = 0; 9500 out: 9501 if (!list_empty(&splice)) { 9502 spin_lock(&fs_info->delalloc_root_lock); 9503 list_splice_tail(&splice, &fs_info->delalloc_roots); 9504 spin_unlock(&fs_info->delalloc_root_lock); 9505 } 9506 mutex_unlock(&fs_info->delalloc_root_mutex); 9507 return ret; 9508 } 9509 9510 static int btrfs_symlink(struct inode *dir, struct dentry *dentry, 9511 const char *symname) 9512 { 9513 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 9514 struct btrfs_trans_handle *trans; 9515 struct btrfs_root *root = BTRFS_I(dir)->root; 9516 struct btrfs_path *path; 9517 struct btrfs_key key; 9518 struct inode *inode = NULL; 9519 int err; 9520 u64 objectid; 9521 u64 index = 0; 9522 int name_len; 9523 int datasize; 9524 unsigned long ptr; 9525 struct btrfs_file_extent_item *ei; 9526 struct extent_buffer *leaf; 9527 9528 name_len = strlen(symname); 9529 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info)) 9530 return -ENAMETOOLONG; 9531 9532 /* 9533 * 2 items for inode item and ref 9534 * 2 items for dir items 9535 * 1 item for updating parent inode item 9536 * 1 item for the inline extent item 9537 * 1 item for xattr if selinux is on 9538 */ 9539 trans = btrfs_start_transaction(root, 7); 9540 if (IS_ERR(trans)) 9541 return PTR_ERR(trans); 9542 9543 err = btrfs_find_free_ino(root, &objectid); 9544 if (err) 9545 goto out_unlock; 9546 9547 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, 9548 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), 9549 objectid, S_IFLNK|S_IRWXUGO, &index); 9550 if (IS_ERR(inode)) { 9551 err = PTR_ERR(inode); 9552 inode = NULL; 9553 goto out_unlock; 9554 } 9555 9556 /* 9557 * If the active LSM wants to access the inode during 9558 * d_instantiate it needs these. Smack checks to see 9559 * if the filesystem supports xattrs by looking at the 9560 * ops vector. 9561 */ 9562 inode->i_fop = &btrfs_file_operations; 9563 inode->i_op = &btrfs_file_inode_operations; 9564 inode->i_mapping->a_ops = &btrfs_aops; 9565 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; 9566 9567 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); 9568 if (err) 9569 goto out_unlock; 9570 9571 path = btrfs_alloc_path(); 9572 if (!path) { 9573 err = -ENOMEM; 9574 goto out_unlock; 9575 } 9576 key.objectid = btrfs_ino(BTRFS_I(inode)); 9577 key.offset = 0; 9578 key.type = BTRFS_EXTENT_DATA_KEY; 9579 datasize = btrfs_file_extent_calc_inline_size(name_len); 9580 err = btrfs_insert_empty_item(trans, root, path, &key, 9581 datasize); 9582 if (err) { 9583 btrfs_free_path(path); 9584 goto out_unlock; 9585 } 9586 leaf = path->nodes[0]; 9587 ei = btrfs_item_ptr(leaf, path->slots[0], 9588 struct btrfs_file_extent_item); 9589 btrfs_set_file_extent_generation(leaf, ei, trans->transid); 9590 btrfs_set_file_extent_type(leaf, ei, 9591 BTRFS_FILE_EXTENT_INLINE); 9592 btrfs_set_file_extent_encryption(leaf, ei, 0); 9593 btrfs_set_file_extent_compression(leaf, ei, 0); 9594 btrfs_set_file_extent_other_encoding(leaf, ei, 0); 9595 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len); 9596 9597 ptr = btrfs_file_extent_inline_start(ei); 9598 write_extent_buffer(leaf, symname, ptr, name_len); 9599 btrfs_mark_buffer_dirty(leaf); 9600 btrfs_free_path(path); 9601 9602 inode->i_op = &btrfs_symlink_inode_operations; 9603 inode_nohighmem(inode); 9604 inode_set_bytes(inode, name_len); 9605 btrfs_i_size_write(BTRFS_I(inode), name_len); 9606 err = btrfs_update_inode(trans, root, inode); 9607 /* 9608 * Last step, add directory indexes for our symlink inode. This is the 9609 * last step to avoid extra cleanup of these indexes if an error happens 9610 * elsewhere above. 9611 */ 9612 if (!err) 9613 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, 9614 BTRFS_I(inode), 0, index); 9615 if (err) 9616 goto out_unlock; 9617 9618 d_instantiate_new(dentry, inode); 9619 9620 out_unlock: 9621 btrfs_end_transaction(trans); 9622 if (err && inode) { 9623 inode_dec_link_count(inode); 9624 discard_new_inode(inode); 9625 } 9626 btrfs_btree_balance_dirty(fs_info); 9627 return err; 9628 } 9629 9630 static int insert_prealloc_file_extent(struct btrfs_trans_handle *trans, 9631 struct inode *inode, struct btrfs_key *ins, 9632 u64 file_offset) 9633 { 9634 struct btrfs_file_extent_item stack_fi; 9635 u64 start = ins->objectid; 9636 u64 len = ins->offset; 9637 int ret; 9638 9639 memset(&stack_fi, 0, sizeof(stack_fi)); 9640 9641 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC); 9642 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start); 9643 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len); 9644 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len); 9645 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len); 9646 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE); 9647 /* Encryption and other encoding is reserved and all 0 */ 9648 9649 ret = btrfs_qgroup_release_data(BTRFS_I(inode), file_offset, len); 9650 if (ret < 0) 9651 return ret; 9652 return insert_reserved_file_extent(trans, BTRFS_I(inode), file_offset, 9653 &stack_fi, ret); 9654 } 9655 static int __btrfs_prealloc_file_range(struct inode *inode, int mode, 9656 u64 start, u64 num_bytes, u64 min_size, 9657 loff_t actual_len, u64 *alloc_hint, 9658 struct btrfs_trans_handle *trans) 9659 { 9660 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); 9661 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; 9662 struct extent_map *em; 9663 struct btrfs_root *root = BTRFS_I(inode)->root; 9664 struct btrfs_key ins; 9665 u64 cur_offset = start; 9666 u64 clear_offset = start; 9667 u64 i_size; 9668 u64 cur_bytes; 9669 u64 last_alloc = (u64)-1; 9670 int ret = 0; 9671 bool own_trans = true; 9672 u64 end = start + num_bytes - 1; 9673 9674 if (trans) 9675 own_trans = false; 9676 while (num_bytes > 0) { 9677 if (own_trans) { 9678 trans = btrfs_start_transaction(root, 3); 9679 if (IS_ERR(trans)) { 9680 ret = PTR_ERR(trans); 9681 break; 9682 } 9683 } 9684 9685 cur_bytes = min_t(u64, num_bytes, SZ_256M); 9686 cur_bytes = max(cur_bytes, min_size); 9687 /* 9688 * If we are severely fragmented we could end up with really 9689 * small allocations, so if the allocator is returning small 9690 * chunks lets make its job easier by only searching for those 9691 * sized chunks. 9692 */ 9693 cur_bytes = min(cur_bytes, last_alloc); 9694 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes, 9695 min_size, 0, *alloc_hint, &ins, 1, 0); 9696 if (ret) { 9697 if (own_trans) 9698 btrfs_end_transaction(trans); 9699 break; 9700 } 9701 9702 /* 9703 * We've reserved this space, and thus converted it from 9704 * ->bytes_may_use to ->bytes_reserved. Any error that happens 9705 * from here on out we will only need to clear our reservation 9706 * for the remaining unreserved area, so advance our 9707 * clear_offset by our extent size. 9708 */ 9709 clear_offset += ins.offset; 9710 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 9711 9712 last_alloc = ins.offset; 9713 ret = insert_prealloc_file_extent(trans, inode, &ins, cur_offset); 9714 if (ret) { 9715 btrfs_free_reserved_extent(fs_info, ins.objectid, 9716 ins.offset, 0); 9717 btrfs_abort_transaction(trans, ret); 9718 if (own_trans) 9719 btrfs_end_transaction(trans); 9720 break; 9721 } 9722 9723 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset, 9724 cur_offset + ins.offset -1, 0); 9725 9726 em = alloc_extent_map(); 9727 if (!em) { 9728 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, 9729 &BTRFS_I(inode)->runtime_flags); 9730 goto next; 9731 } 9732 9733 em->start = cur_offset; 9734 em->orig_start = cur_offset; 9735 em->len = ins.offset; 9736 em->block_start = ins.objectid; 9737 em->block_len = ins.offset; 9738 em->orig_block_len = ins.offset; 9739 em->ram_bytes = ins.offset; 9740 set_bit(EXTENT_FLAG_PREALLOC, &em->flags); 9741 em->generation = trans->transid; 9742 9743 while (1) { 9744 write_lock(&em_tree->lock); 9745 ret = add_extent_mapping(em_tree, em, 1); 9746 write_unlock(&em_tree->lock); 9747 if (ret != -EEXIST) 9748 break; 9749 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset, 9750 cur_offset + ins.offset - 1, 9751 0); 9752 } 9753 free_extent_map(em); 9754 next: 9755 num_bytes -= ins.offset; 9756 cur_offset += ins.offset; 9757 *alloc_hint = ins.objectid + ins.offset; 9758 9759 inode_inc_iversion(inode); 9760 inode->i_ctime = current_time(inode); 9761 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC; 9762 if (!(mode & FALLOC_FL_KEEP_SIZE) && 9763 (actual_len > inode->i_size) && 9764 (cur_offset > inode->i_size)) { 9765 if (cur_offset > actual_len) 9766 i_size = actual_len; 9767 else 9768 i_size = cur_offset; 9769 i_size_write(inode, i_size); 9770 btrfs_inode_safe_disk_i_size_write(inode, 0); 9771 } 9772 9773 ret = btrfs_update_inode(trans, root, inode); 9774 9775 if (ret) { 9776 btrfs_abort_transaction(trans, ret); 9777 if (own_trans) 9778 btrfs_end_transaction(trans); 9779 break; 9780 } 9781 9782 if (own_trans) 9783 btrfs_end_transaction(trans); 9784 } 9785 if (clear_offset < end) 9786 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset, 9787 end - clear_offset + 1); 9788 return ret; 9789 } 9790 9791 int btrfs_prealloc_file_range(struct inode *inode, int mode, 9792 u64 start, u64 num_bytes, u64 min_size, 9793 loff_t actual_len, u64 *alloc_hint) 9794 { 9795 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, 9796 min_size, actual_len, alloc_hint, 9797 NULL); 9798 } 9799 9800 int btrfs_prealloc_file_range_trans(struct inode *inode, 9801 struct btrfs_trans_handle *trans, int mode, 9802 u64 start, u64 num_bytes, u64 min_size, 9803 loff_t actual_len, u64 *alloc_hint) 9804 { 9805 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, 9806 min_size, actual_len, alloc_hint, trans); 9807 } 9808 9809 static int btrfs_set_page_dirty(struct page *page) 9810 { 9811 return __set_page_dirty_nobuffers(page); 9812 } 9813 9814 static int btrfs_permission(struct inode *inode, int mask) 9815 { 9816 struct btrfs_root *root = BTRFS_I(inode)->root; 9817 umode_t mode = inode->i_mode; 9818 9819 if (mask & MAY_WRITE && 9820 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) { 9821 if (btrfs_root_readonly(root)) 9822 return -EROFS; 9823 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) 9824 return -EACCES; 9825 } 9826 return generic_permission(inode, mask); 9827 } 9828 9829 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode) 9830 { 9831 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); 9832 struct btrfs_trans_handle *trans; 9833 struct btrfs_root *root = BTRFS_I(dir)->root; 9834 struct inode *inode = NULL; 9835 u64 objectid; 9836 u64 index; 9837 int ret = 0; 9838 9839 /* 9840 * 5 units required for adding orphan entry 9841 */ 9842 trans = btrfs_start_transaction(root, 5); 9843 if (IS_ERR(trans)) 9844 return PTR_ERR(trans); 9845 9846 ret = btrfs_find_free_ino(root, &objectid); 9847 if (ret) 9848 goto out; 9849 9850 inode = btrfs_new_inode(trans, root, dir, NULL, 0, 9851 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index); 9852 if (IS_ERR(inode)) { 9853 ret = PTR_ERR(inode); 9854 inode = NULL; 9855 goto out; 9856 } 9857 9858 inode->i_fop = &btrfs_file_operations; 9859 inode->i_op = &btrfs_file_inode_operations; 9860 9861 inode->i_mapping->a_ops = &btrfs_aops; 9862 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; 9863 9864 ret = btrfs_init_inode_security(trans, inode, dir, NULL); 9865 if (ret) 9866 goto out; 9867 9868 ret = btrfs_update_inode(trans, root, inode); 9869 if (ret) 9870 goto out; 9871 ret = btrfs_orphan_add(trans, BTRFS_I(inode)); 9872 if (ret) 9873 goto out; 9874 9875 /* 9876 * We set number of links to 0 in btrfs_new_inode(), and here we set 9877 * it to 1 because d_tmpfile() will issue a warning if the count is 0, 9878 * through: 9879 * 9880 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink() 9881 */ 9882 set_nlink(inode, 1); 9883 d_tmpfile(dentry, inode); 9884 unlock_new_inode(inode); 9885 mark_inode_dirty(inode); 9886 out: 9887 btrfs_end_transaction(trans); 9888 if (ret && inode) 9889 discard_new_inode(inode); 9890 btrfs_btree_balance_dirty(fs_info); 9891 return ret; 9892 } 9893 9894 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end) 9895 { 9896 struct inode *inode = tree->private_data; 9897 unsigned long index = start >> PAGE_SHIFT; 9898 unsigned long end_index = end >> PAGE_SHIFT; 9899 struct page *page; 9900 9901 while (index <= end_index) { 9902 page = find_get_page(inode->i_mapping, index); 9903 ASSERT(page); /* Pages should be in the extent_io_tree */ 9904 set_page_writeback(page); 9905 put_page(page); 9906 index++; 9907 } 9908 } 9909 9910 #ifdef CONFIG_SWAP 9911 /* 9912 * Add an entry indicating a block group or device which is pinned by a 9913 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a 9914 * negative errno on failure. 9915 */ 9916 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr, 9917 bool is_block_group) 9918 { 9919 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; 9920 struct btrfs_swapfile_pin *sp, *entry; 9921 struct rb_node **p; 9922 struct rb_node *parent = NULL; 9923 9924 sp = kmalloc(sizeof(*sp), GFP_NOFS); 9925 if (!sp) 9926 return -ENOMEM; 9927 sp->ptr = ptr; 9928 sp->inode = inode; 9929 sp->is_block_group = is_block_group; 9930 9931 spin_lock(&fs_info->swapfile_pins_lock); 9932 p = &fs_info->swapfile_pins.rb_node; 9933 while (*p) { 9934 parent = *p; 9935 entry = rb_entry(parent, struct btrfs_swapfile_pin, node); 9936 if (sp->ptr < entry->ptr || 9937 (sp->ptr == entry->ptr && sp->inode < entry->inode)) { 9938 p = &(*p)->rb_left; 9939 } else if (sp->ptr > entry->ptr || 9940 (sp->ptr == entry->ptr && sp->inode > entry->inode)) { 9941 p = &(*p)->rb_right; 9942 } else { 9943 spin_unlock(&fs_info->swapfile_pins_lock); 9944 kfree(sp); 9945 return 1; 9946 } 9947 } 9948 rb_link_node(&sp->node, parent, p); 9949 rb_insert_color(&sp->node, &fs_info->swapfile_pins); 9950 spin_unlock(&fs_info->swapfile_pins_lock); 9951 return 0; 9952 } 9953 9954 /* Free all of the entries pinned by this swapfile. */ 9955 static void btrfs_free_swapfile_pins(struct inode *inode) 9956 { 9957 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; 9958 struct btrfs_swapfile_pin *sp; 9959 struct rb_node *node, *next; 9960 9961 spin_lock(&fs_info->swapfile_pins_lock); 9962 node = rb_first(&fs_info->swapfile_pins); 9963 while (node) { 9964 next = rb_next(node); 9965 sp = rb_entry(node, struct btrfs_swapfile_pin, node); 9966 if (sp->inode == inode) { 9967 rb_erase(&sp->node, &fs_info->swapfile_pins); 9968 if (sp->is_block_group) 9969 btrfs_put_block_group(sp->ptr); 9970 kfree(sp); 9971 } 9972 node = next; 9973 } 9974 spin_unlock(&fs_info->swapfile_pins_lock); 9975 } 9976 9977 struct btrfs_swap_info { 9978 u64 start; 9979 u64 block_start; 9980 u64 block_len; 9981 u64 lowest_ppage; 9982 u64 highest_ppage; 9983 unsigned long nr_pages; 9984 int nr_extents; 9985 }; 9986 9987 static int btrfs_add_swap_extent(struct swap_info_struct *sis, 9988 struct btrfs_swap_info *bsi) 9989 { 9990 unsigned long nr_pages; 9991 u64 first_ppage, first_ppage_reported, next_ppage; 9992 int ret; 9993 9994 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT; 9995 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len, 9996 PAGE_SIZE) >> PAGE_SHIFT; 9997 9998 if (first_ppage >= next_ppage) 9999 return 0; 10000 nr_pages = next_ppage - first_ppage; 10001 10002 first_ppage_reported = first_ppage; 10003 if (bsi->start == 0) 10004 first_ppage_reported++; 10005 if (bsi->lowest_ppage > first_ppage_reported) 10006 bsi->lowest_ppage = first_ppage_reported; 10007 if (bsi->highest_ppage < (next_ppage - 1)) 10008 bsi->highest_ppage = next_ppage - 1; 10009 10010 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage); 10011 if (ret < 0) 10012 return ret; 10013 bsi->nr_extents += ret; 10014 bsi->nr_pages += nr_pages; 10015 return 0; 10016 } 10017 10018 static void btrfs_swap_deactivate(struct file *file) 10019 { 10020 struct inode *inode = file_inode(file); 10021 10022 btrfs_free_swapfile_pins(inode); 10023 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles); 10024 } 10025 10026 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file, 10027 sector_t *span) 10028 { 10029 struct inode *inode = file_inode(file); 10030 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; 10031 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 10032 struct extent_state *cached_state = NULL; 10033 struct extent_map *em = NULL; 10034 struct btrfs_device *device = NULL; 10035 struct btrfs_swap_info bsi = { 10036 .lowest_ppage = (sector_t)-1ULL, 10037 }; 10038 int ret = 0; 10039 u64 isize; 10040 u64 start; 10041 10042 /* 10043 * If the swap file was just created, make sure delalloc is done. If the 10044 * file changes again after this, the user is doing something stupid and 10045 * we don't really care. 10046 */ 10047 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1); 10048 if (ret) 10049 return ret; 10050 10051 /* 10052 * The inode is locked, so these flags won't change after we check them. 10053 */ 10054 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) { 10055 btrfs_warn(fs_info, "swapfile must not be compressed"); 10056 return -EINVAL; 10057 } 10058 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) { 10059 btrfs_warn(fs_info, "swapfile must not be copy-on-write"); 10060 return -EINVAL; 10061 } 10062 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) { 10063 btrfs_warn(fs_info, "swapfile must not be checksummed"); 10064 return -EINVAL; 10065 } 10066 10067 /* 10068 * Balance or device remove/replace/resize can move stuff around from 10069 * under us. The EXCL_OP flag makes sure they aren't running/won't run 10070 * concurrently while we are mapping the swap extents, and 10071 * fs_info->swapfile_pins prevents them from running while the swap file 10072 * is active and moving the extents. Note that this also prevents a 10073 * concurrent device add which isn't actually necessary, but it's not 10074 * really worth the trouble to allow it. 10075 */ 10076 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { 10077 btrfs_warn(fs_info, 10078 "cannot activate swapfile while exclusive operation is running"); 10079 return -EBUSY; 10080 } 10081 /* 10082 * Snapshots can create extents which require COW even if NODATACOW is 10083 * set. We use this counter to prevent snapshots. We must increment it 10084 * before walking the extents because we don't want a concurrent 10085 * snapshot to run after we've already checked the extents. 10086 */ 10087 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles); 10088 10089 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize); 10090 10091 lock_extent_bits(io_tree, 0, isize - 1, &cached_state); 10092 start = 0; 10093 while (start < isize) { 10094 u64 logical_block_start, physical_block_start; 10095 struct btrfs_block_group *bg; 10096 u64 len = isize - start; 10097 10098 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len); 10099 if (IS_ERR(em)) { 10100 ret = PTR_ERR(em); 10101 goto out; 10102 } 10103 10104 if (em->block_start == EXTENT_MAP_HOLE) { 10105 btrfs_warn(fs_info, "swapfile must not have holes"); 10106 ret = -EINVAL; 10107 goto out; 10108 } 10109 if (em->block_start == EXTENT_MAP_INLINE) { 10110 /* 10111 * It's unlikely we'll ever actually find ourselves 10112 * here, as a file small enough to fit inline won't be 10113 * big enough to store more than the swap header, but in 10114 * case something changes in the future, let's catch it 10115 * here rather than later. 10116 */ 10117 btrfs_warn(fs_info, "swapfile must not be inline"); 10118 ret = -EINVAL; 10119 goto out; 10120 } 10121 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) { 10122 btrfs_warn(fs_info, "swapfile must not be compressed"); 10123 ret = -EINVAL; 10124 goto out; 10125 } 10126 10127 logical_block_start = em->block_start + (start - em->start); 10128 len = min(len, em->len - (start - em->start)); 10129 free_extent_map(em); 10130 em = NULL; 10131 10132 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL); 10133 if (ret < 0) { 10134 goto out; 10135 } else if (ret) { 10136 ret = 0; 10137 } else { 10138 btrfs_warn(fs_info, 10139 "swapfile must not be copy-on-write"); 10140 ret = -EINVAL; 10141 goto out; 10142 } 10143 10144 em = btrfs_get_chunk_map(fs_info, logical_block_start, len); 10145 if (IS_ERR(em)) { 10146 ret = PTR_ERR(em); 10147 goto out; 10148 } 10149 10150 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) { 10151 btrfs_warn(fs_info, 10152 "swapfile must have single data profile"); 10153 ret = -EINVAL; 10154 goto out; 10155 } 10156 10157 if (device == NULL) { 10158 device = em->map_lookup->stripes[0].dev; 10159 ret = btrfs_add_swapfile_pin(inode, device, false); 10160 if (ret == 1) 10161 ret = 0; 10162 else if (ret) 10163 goto out; 10164 } else if (device != em->map_lookup->stripes[0].dev) { 10165 btrfs_warn(fs_info, "swapfile must be on one device"); 10166 ret = -EINVAL; 10167 goto out; 10168 } 10169 10170 physical_block_start = (em->map_lookup->stripes[0].physical + 10171 (logical_block_start - em->start)); 10172 len = min(len, em->len - (logical_block_start - em->start)); 10173 free_extent_map(em); 10174 em = NULL; 10175 10176 bg = btrfs_lookup_block_group(fs_info, logical_block_start); 10177 if (!bg) { 10178 btrfs_warn(fs_info, 10179 "could not find block group containing swapfile"); 10180 ret = -EINVAL; 10181 goto out; 10182 } 10183 10184 ret = btrfs_add_swapfile_pin(inode, bg, true); 10185 if (ret) { 10186 btrfs_put_block_group(bg); 10187 if (ret == 1) 10188 ret = 0; 10189 else 10190 goto out; 10191 } 10192 10193 if (bsi.block_len && 10194 bsi.block_start + bsi.block_len == physical_block_start) { 10195 bsi.block_len += len; 10196 } else { 10197 if (bsi.block_len) { 10198 ret = btrfs_add_swap_extent(sis, &bsi); 10199 if (ret) 10200 goto out; 10201 } 10202 bsi.start = start; 10203 bsi.block_start = physical_block_start; 10204 bsi.block_len = len; 10205 } 10206 10207 start += len; 10208 } 10209 10210 if (bsi.block_len) 10211 ret = btrfs_add_swap_extent(sis, &bsi); 10212 10213 out: 10214 if (!IS_ERR_OR_NULL(em)) 10215 free_extent_map(em); 10216 10217 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state); 10218 10219 if (ret) 10220 btrfs_swap_deactivate(file); 10221 10222 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); 10223 10224 if (ret) 10225 return ret; 10226 10227 if (device) 10228 sis->bdev = device->bdev; 10229 *span = bsi.highest_ppage - bsi.lowest_ppage + 1; 10230 sis->max = bsi.nr_pages; 10231 sis->pages = bsi.nr_pages - 1; 10232 sis->highest_bit = bsi.nr_pages - 1; 10233 return bsi.nr_extents; 10234 } 10235 #else 10236 static void btrfs_swap_deactivate(struct file *file) 10237 { 10238 } 10239 10240 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file, 10241 sector_t *span) 10242 { 10243 return -EOPNOTSUPP; 10244 } 10245 #endif 10246 10247 static const struct inode_operations btrfs_dir_inode_operations = { 10248 .getattr = btrfs_getattr, 10249 .lookup = btrfs_lookup, 10250 .create = btrfs_create, 10251 .unlink = btrfs_unlink, 10252 .link = btrfs_link, 10253 .mkdir = btrfs_mkdir, 10254 .rmdir = btrfs_rmdir, 10255 .rename = btrfs_rename2, 10256 .symlink = btrfs_symlink, 10257 .setattr = btrfs_setattr, 10258 .mknod = btrfs_mknod, 10259 .listxattr = btrfs_listxattr, 10260 .permission = btrfs_permission, 10261 .get_acl = btrfs_get_acl, 10262 .set_acl = btrfs_set_acl, 10263 .update_time = btrfs_update_time, 10264 .tmpfile = btrfs_tmpfile, 10265 }; 10266 10267 static const struct file_operations btrfs_dir_file_operations = { 10268 .llseek = generic_file_llseek, 10269 .read = generic_read_dir, 10270 .iterate_shared = btrfs_real_readdir, 10271 .open = btrfs_opendir, 10272 .unlocked_ioctl = btrfs_ioctl, 10273 #ifdef CONFIG_COMPAT 10274 .compat_ioctl = btrfs_compat_ioctl, 10275 #endif 10276 .release = btrfs_release_file, 10277 .fsync = btrfs_sync_file, 10278 }; 10279 10280 static const struct extent_io_ops btrfs_extent_io_ops = { 10281 /* mandatory callbacks */ 10282 .submit_bio_hook = btrfs_submit_bio_hook, 10283 .readpage_end_io_hook = btrfs_readpage_end_io_hook, 10284 }; 10285 10286 /* 10287 * btrfs doesn't support the bmap operation because swapfiles 10288 * use bmap to make a mapping of extents in the file. They assume 10289 * these extents won't change over the life of the file and they 10290 * use the bmap result to do IO directly to the drive. 10291 * 10292 * the btrfs bmap call would return logical addresses that aren't 10293 * suitable for IO and they also will change frequently as COW 10294 * operations happen. So, swapfile + btrfs == corruption. 10295 * 10296 * For now we're avoiding this by dropping bmap. 10297 */ 10298 static const struct address_space_operations btrfs_aops = { 10299 .readpage = btrfs_readpage, 10300 .writepage = btrfs_writepage, 10301 .writepages = btrfs_writepages, 10302 .readahead = btrfs_readahead, 10303 .direct_IO = btrfs_direct_IO, 10304 .invalidatepage = btrfs_invalidatepage, 10305 .releasepage = btrfs_releasepage, 10306 #ifdef CONFIG_MIGRATION 10307 .migratepage = btrfs_migratepage, 10308 #endif 10309 .set_page_dirty = btrfs_set_page_dirty, 10310 .error_remove_page = generic_error_remove_page, 10311 .swap_activate = btrfs_swap_activate, 10312 .swap_deactivate = btrfs_swap_deactivate, 10313 }; 10314 10315 static const struct inode_operations btrfs_file_inode_operations = { 10316 .getattr = btrfs_getattr, 10317 .setattr = btrfs_setattr, 10318 .listxattr = btrfs_listxattr, 10319 .permission = btrfs_permission, 10320 .fiemap = btrfs_fiemap, 10321 .get_acl = btrfs_get_acl, 10322 .set_acl = btrfs_set_acl, 10323 .update_time = btrfs_update_time, 10324 }; 10325 static const struct inode_operations btrfs_special_inode_operations = { 10326 .getattr = btrfs_getattr, 10327 .setattr = btrfs_setattr, 10328 .permission = btrfs_permission, 10329 .listxattr = btrfs_listxattr, 10330 .get_acl = btrfs_get_acl, 10331 .set_acl = btrfs_set_acl, 10332 .update_time = btrfs_update_time, 10333 }; 10334 static const struct inode_operations btrfs_symlink_inode_operations = { 10335 .get_link = page_get_link, 10336 .getattr = btrfs_getattr, 10337 .setattr = btrfs_setattr, 10338 .permission = btrfs_permission, 10339 .listxattr = btrfs_listxattr, 10340 .update_time = btrfs_update_time, 10341 }; 10342 10343 const struct dentry_operations btrfs_dentry_operations = { 10344 .d_delete = btrfs_dentry_delete, 10345 }; 10346