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