1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <asm/unaligned.h>
33 #include "transaction.h"
34 #include "btrfs_inode.h"
35 #include "print-tree.h"
36 #include "ordered-data.h"
40 #include "compression.h"
42 #include "free-space-cache.h"
43 #include "inode-map.h"
49 struct btrfs_iget_args {
50 struct btrfs_key *location;
51 struct btrfs_root *root;
54 struct btrfs_dio_data {
56 u64 unsubmitted_oe_range_start;
57 u64 unsubmitted_oe_range_end;
61 static const struct inode_operations btrfs_dir_inode_operations;
62 static const struct inode_operations btrfs_symlink_inode_operations;
63 static const struct inode_operations btrfs_dir_ro_inode_operations;
64 static const struct inode_operations btrfs_special_inode_operations;
65 static const struct inode_operations btrfs_file_inode_operations;
66 static const struct address_space_operations btrfs_aops;
67 static const struct file_operations btrfs_dir_file_operations;
68 static const struct extent_io_ops btrfs_extent_io_ops;
70 static struct kmem_cache *btrfs_inode_cachep;
71 struct kmem_cache *btrfs_trans_handle_cachep;
72 struct kmem_cache *btrfs_path_cachep;
73 struct kmem_cache *btrfs_free_space_cachep;
76 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
77 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
78 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
79 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
80 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
81 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
82 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
83 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
86 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
87 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
88 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
89 static noinline int cow_file_range(struct inode *inode,
90 struct page *locked_page,
91 u64 start, u64 end, u64 delalloc_end,
92 int *page_started, unsigned long *nr_written,
93 int unlock, struct btrfs_dedupe_hash *hash);
94 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
95 u64 orig_start, u64 block_start,
96 u64 block_len, u64 orig_block_len,
97 u64 ram_bytes, int compress_type,
100 static void __endio_write_update_ordered(struct inode *inode,
101 const u64 offset, const u64 bytes,
102 const bool uptodate);
105 * Cleanup all submitted ordered extents in specified range to handle errors
106 * from the fill_dellaloc() callback.
108 * NOTE: caller must ensure that when an error happens, it can not call
109 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
110 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
111 * to be released, which we want to happen only when finishing the ordered
112 * extent (btrfs_finish_ordered_io()). Also note that the caller of
113 * btrfs_run_delalloc_range already does proper cleanup for the first page of
114 * the range, that is, it invokes the callback writepage_end_io_hook() for the
115 * range of the first page.
117 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
121 unsigned long index = offset >> PAGE_SHIFT;
122 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
125 while (index <= end_index) {
126 page = find_get_page(inode->i_mapping, index);
130 ClearPagePrivate2(page);
133 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
134 bytes - PAGE_SIZE, false);
137 static int btrfs_dirty_inode(struct inode *inode);
139 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
140 void btrfs_test_inode_set_ops(struct inode *inode)
142 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
146 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
147 struct inode *inode, struct inode *dir,
148 const struct qstr *qstr)
152 err = btrfs_init_acl(trans, inode, dir);
154 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
159 * this does all the hard work for inserting an inline extent into
160 * the btree. The caller should have done a btrfs_drop_extents so that
161 * no overlapping inline items exist in the btree
163 static int insert_inline_extent(struct btrfs_trans_handle *trans,
164 struct btrfs_path *path, int extent_inserted,
165 struct btrfs_root *root, struct inode *inode,
166 u64 start, size_t size, size_t compressed_size,
168 struct page **compressed_pages)
170 struct extent_buffer *leaf;
171 struct page *page = NULL;
174 struct btrfs_file_extent_item *ei;
176 size_t cur_size = size;
177 unsigned long offset;
179 if (compressed_size && compressed_pages)
180 cur_size = compressed_size;
182 inode_add_bytes(inode, size);
184 if (!extent_inserted) {
185 struct btrfs_key key;
188 key.objectid = btrfs_ino(BTRFS_I(inode));
190 key.type = BTRFS_EXTENT_DATA_KEY;
192 datasize = btrfs_file_extent_calc_inline_size(cur_size);
193 path->leave_spinning = 1;
194 ret = btrfs_insert_empty_item(trans, root, path, &key,
199 leaf = path->nodes[0];
200 ei = btrfs_item_ptr(leaf, path->slots[0],
201 struct btrfs_file_extent_item);
202 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
203 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
204 btrfs_set_file_extent_encryption(leaf, ei, 0);
205 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
206 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
207 ptr = btrfs_file_extent_inline_start(ei);
209 if (compress_type != BTRFS_COMPRESS_NONE) {
212 while (compressed_size > 0) {
213 cpage = compressed_pages[i];
214 cur_size = min_t(unsigned long, compressed_size,
217 kaddr = kmap_atomic(cpage);
218 write_extent_buffer(leaf, kaddr, ptr, cur_size);
219 kunmap_atomic(kaddr);
223 compressed_size -= cur_size;
225 btrfs_set_file_extent_compression(leaf, ei,
228 page = find_get_page(inode->i_mapping,
229 start >> PAGE_SHIFT);
230 btrfs_set_file_extent_compression(leaf, ei, 0);
231 kaddr = kmap_atomic(page);
232 offset = start & (PAGE_SIZE - 1);
233 write_extent_buffer(leaf, kaddr + offset, ptr, size);
234 kunmap_atomic(kaddr);
237 btrfs_mark_buffer_dirty(leaf);
238 btrfs_release_path(path);
241 * we're an inline extent, so nobody can
242 * extend the file past i_size without locking
243 * a page we already have locked.
245 * We must do any isize and inode updates
246 * before we unlock the pages. Otherwise we
247 * could end up racing with unlink.
249 BTRFS_I(inode)->disk_i_size = inode->i_size;
250 ret = btrfs_update_inode(trans, root, inode);
258 * conditionally insert an inline extent into the file. This
259 * does the checks required to make sure the data is small enough
260 * to fit as an inline extent.
262 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
263 u64 end, size_t compressed_size,
265 struct page **compressed_pages)
267 struct btrfs_root *root = BTRFS_I(inode)->root;
268 struct btrfs_fs_info *fs_info = root->fs_info;
269 struct btrfs_trans_handle *trans;
270 u64 isize = i_size_read(inode);
271 u64 actual_end = min(end + 1, isize);
272 u64 inline_len = actual_end - start;
273 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
274 u64 data_len = inline_len;
276 struct btrfs_path *path;
277 int extent_inserted = 0;
278 u32 extent_item_size;
281 data_len = compressed_size;
284 actual_end > fs_info->sectorsize ||
285 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
287 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
289 data_len > fs_info->max_inline) {
293 path = btrfs_alloc_path();
297 trans = btrfs_join_transaction(root);
299 btrfs_free_path(path);
300 return PTR_ERR(trans);
302 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
304 if (compressed_size && compressed_pages)
305 extent_item_size = btrfs_file_extent_calc_inline_size(
308 extent_item_size = btrfs_file_extent_calc_inline_size(
311 ret = __btrfs_drop_extents(trans, root, inode, path,
312 start, aligned_end, NULL,
313 1, 1, extent_item_size, &extent_inserted);
315 btrfs_abort_transaction(trans, ret);
319 if (isize > actual_end)
320 inline_len = min_t(u64, isize, actual_end);
321 ret = insert_inline_extent(trans, path, extent_inserted,
323 inline_len, compressed_size,
324 compress_type, compressed_pages);
325 if (ret && ret != -ENOSPC) {
326 btrfs_abort_transaction(trans, ret);
328 } else if (ret == -ENOSPC) {
333 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
334 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
337 * Don't forget to free the reserved space, as for inlined extent
338 * it won't count as data extent, free them directly here.
339 * And at reserve time, it's always aligned to page size, so
340 * just free one page here.
342 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
343 btrfs_free_path(path);
344 btrfs_end_transaction(trans);
348 struct async_extent {
353 unsigned long nr_pages;
355 struct list_head list;
360 struct btrfs_root *root;
361 struct page *locked_page;
364 unsigned int write_flags;
365 struct list_head extents;
366 struct btrfs_work work;
369 static noinline int add_async_extent(struct async_cow *cow,
370 u64 start, u64 ram_size,
373 unsigned long nr_pages,
376 struct async_extent *async_extent;
378 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
379 BUG_ON(!async_extent); /* -ENOMEM */
380 async_extent->start = start;
381 async_extent->ram_size = ram_size;
382 async_extent->compressed_size = compressed_size;
383 async_extent->pages = pages;
384 async_extent->nr_pages = nr_pages;
385 async_extent->compress_type = compress_type;
386 list_add_tail(&async_extent->list, &cow->extents);
390 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
392 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
395 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
398 if (BTRFS_I(inode)->defrag_compress)
400 /* bad compression ratios */
401 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
403 if (btrfs_test_opt(fs_info, COMPRESS) ||
404 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
405 BTRFS_I(inode)->prop_compress)
406 return btrfs_compress_heuristic(inode, start, end);
410 static inline void inode_should_defrag(struct btrfs_inode *inode,
411 u64 start, u64 end, u64 num_bytes, u64 small_write)
413 /* If this is a small write inside eof, kick off a defrag */
414 if (num_bytes < small_write &&
415 (start > 0 || end + 1 < inode->disk_i_size))
416 btrfs_add_inode_defrag(NULL, inode);
420 * we create compressed extents in two phases. The first
421 * phase compresses a range of pages that have already been
422 * locked (both pages and state bits are locked).
424 * This is done inside an ordered work queue, and the compression
425 * is spread across many cpus. The actual IO submission is step
426 * two, and the ordered work queue takes care of making sure that
427 * happens in the same order things were put onto the queue by
428 * writepages and friends.
430 * If this code finds it can't get good compression, it puts an
431 * entry onto the work queue to write the uncompressed bytes. This
432 * makes sure that both compressed inodes and uncompressed inodes
433 * are written in the same order that the flusher thread sent them
436 static noinline void compress_file_range(struct inode *inode,
437 struct page *locked_page,
439 struct async_cow *async_cow,
442 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
443 u64 blocksize = fs_info->sectorsize;
445 u64 isize = i_size_read(inode);
447 struct page **pages = NULL;
448 unsigned long nr_pages;
449 unsigned long total_compressed = 0;
450 unsigned long total_in = 0;
453 int compress_type = fs_info->compress_type;
456 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
459 actual_end = min_t(u64, isize, end + 1);
462 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
463 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
464 nr_pages = min_t(unsigned long, nr_pages,
465 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
468 * we don't want to send crud past the end of i_size through
469 * compression, that's just a waste of CPU time. So, if the
470 * end of the file is before the start of our current
471 * requested range of bytes, we bail out to the uncompressed
472 * cleanup code that can deal with all of this.
474 * It isn't really the fastest way to fix things, but this is a
475 * very uncommon corner.
477 if (actual_end <= start)
478 goto cleanup_and_bail_uncompressed;
480 total_compressed = actual_end - start;
483 * skip compression for a small file range(<=blocksize) that
484 * isn't an inline extent, since it doesn't save disk space at all.
486 if (total_compressed <= blocksize &&
487 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
488 goto cleanup_and_bail_uncompressed;
490 total_compressed = min_t(unsigned long, total_compressed,
491 BTRFS_MAX_UNCOMPRESSED);
496 * we do compression for mount -o compress and when the
497 * inode has not been flagged as nocompress. This flag can
498 * change at any time if we discover bad compression ratios.
500 if (inode_need_compress(inode, start, end)) {
502 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
504 /* just bail out to the uncompressed code */
509 if (BTRFS_I(inode)->defrag_compress)
510 compress_type = BTRFS_I(inode)->defrag_compress;
511 else if (BTRFS_I(inode)->prop_compress)
512 compress_type = BTRFS_I(inode)->prop_compress;
515 * we need to call clear_page_dirty_for_io on each
516 * page in the range. Otherwise applications with the file
517 * mmap'd can wander in and change the page contents while
518 * we are compressing them.
520 * If the compression fails for any reason, we set the pages
521 * dirty again later on.
523 * Note that the remaining part is redirtied, the start pointer
524 * has moved, the end is the original one.
527 extent_range_clear_dirty_for_io(inode, start, end);
531 /* Compression level is applied here and only here */
532 ret = btrfs_compress_pages(
533 compress_type | (fs_info->compress_level << 4),
534 inode->i_mapping, start,
541 unsigned long offset = total_compressed &
543 struct page *page = pages[nr_pages - 1];
546 /* zero the tail end of the last page, we might be
547 * sending it down to disk
550 kaddr = kmap_atomic(page);
551 memset(kaddr + offset, 0,
553 kunmap_atomic(kaddr);
560 /* lets try to make an inline extent */
561 if (ret || total_in < actual_end) {
562 /* we didn't compress the entire range, try
563 * to make an uncompressed inline extent.
565 ret = cow_file_range_inline(inode, start, end, 0,
566 BTRFS_COMPRESS_NONE, NULL);
568 /* try making a compressed inline extent */
569 ret = cow_file_range_inline(inode, start, end,
571 compress_type, pages);
574 unsigned long clear_flags = EXTENT_DELALLOC |
575 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
576 EXTENT_DO_ACCOUNTING;
577 unsigned long page_error_op;
579 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
582 * inline extent creation worked or returned error,
583 * we don't need to create any more async work items.
584 * Unlock and free up our temp pages.
586 * We use DO_ACCOUNTING here because we need the
587 * delalloc_release_metadata to be done _after_ we drop
588 * our outstanding extent for clearing delalloc for this
591 extent_clear_unlock_delalloc(inode, start, end, end,
604 * we aren't doing an inline extent round the compressed size
605 * up to a block size boundary so the allocator does sane
608 total_compressed = ALIGN(total_compressed, blocksize);
611 * one last check to make sure the compression is really a
612 * win, compare the page count read with the blocks on disk,
613 * compression must free at least one sector size
615 total_in = ALIGN(total_in, PAGE_SIZE);
616 if (total_compressed + blocksize <= total_in) {
620 * The async work queues will take care of doing actual
621 * allocation on disk for these compressed pages, and
622 * will submit them to the elevator.
624 add_async_extent(async_cow, start, total_in,
625 total_compressed, pages, nr_pages,
628 if (start + total_in < end) {
639 * the compression code ran but failed to make things smaller,
640 * free any pages it allocated and our page pointer array
642 for (i = 0; i < nr_pages; i++) {
643 WARN_ON(pages[i]->mapping);
648 total_compressed = 0;
651 /* flag the file so we don't compress in the future */
652 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
653 !(BTRFS_I(inode)->prop_compress)) {
654 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
657 cleanup_and_bail_uncompressed:
659 * No compression, but we still need to write the pages in the file
660 * we've been given so far. redirty the locked page if it corresponds
661 * to our extent and set things up for the async work queue to run
662 * cow_file_range to do the normal delalloc dance.
664 if (page_offset(locked_page) >= start &&
665 page_offset(locked_page) <= end)
666 __set_page_dirty_nobuffers(locked_page);
667 /* unlocked later on in the async handlers */
670 extent_range_redirty_for_io(inode, start, end);
671 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
672 BTRFS_COMPRESS_NONE);
678 for (i = 0; i < nr_pages; i++) {
679 WARN_ON(pages[i]->mapping);
685 static void free_async_extent_pages(struct async_extent *async_extent)
689 if (!async_extent->pages)
692 for (i = 0; i < async_extent->nr_pages; i++) {
693 WARN_ON(async_extent->pages[i]->mapping);
694 put_page(async_extent->pages[i]);
696 kfree(async_extent->pages);
697 async_extent->nr_pages = 0;
698 async_extent->pages = NULL;
702 * phase two of compressed writeback. This is the ordered portion
703 * of the code, which only gets called in the order the work was
704 * queued. We walk all the async extents created by compress_file_range
705 * and send them down to the disk.
707 static noinline void submit_compressed_extents(struct inode *inode,
708 struct async_cow *async_cow)
710 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
711 struct async_extent *async_extent;
713 struct btrfs_key ins;
714 struct extent_map *em;
715 struct btrfs_root *root = BTRFS_I(inode)->root;
716 struct extent_io_tree *io_tree;
720 while (!list_empty(&async_cow->extents)) {
721 async_extent = list_entry(async_cow->extents.next,
722 struct async_extent, list);
723 list_del(&async_extent->list);
725 io_tree = &BTRFS_I(inode)->io_tree;
728 /* did the compression code fall back to uncompressed IO? */
729 if (!async_extent->pages) {
730 int page_started = 0;
731 unsigned long nr_written = 0;
733 lock_extent(io_tree, async_extent->start,
734 async_extent->start +
735 async_extent->ram_size - 1);
737 /* allocate blocks */
738 ret = cow_file_range(inode, async_cow->locked_page,
740 async_extent->start +
741 async_extent->ram_size - 1,
742 async_extent->start +
743 async_extent->ram_size - 1,
744 &page_started, &nr_written, 0,
750 * if page_started, cow_file_range inserted an
751 * inline extent and took care of all the unlocking
752 * and IO for us. Otherwise, we need to submit
753 * all those pages down to the drive.
755 if (!page_started && !ret)
756 extent_write_locked_range(inode,
758 async_extent->start +
759 async_extent->ram_size - 1,
762 unlock_page(async_cow->locked_page);
768 lock_extent(io_tree, async_extent->start,
769 async_extent->start + async_extent->ram_size - 1);
771 ret = btrfs_reserve_extent(root, async_extent->ram_size,
772 async_extent->compressed_size,
773 async_extent->compressed_size,
774 0, alloc_hint, &ins, 1, 1);
776 free_async_extent_pages(async_extent);
778 if (ret == -ENOSPC) {
779 unlock_extent(io_tree, async_extent->start,
780 async_extent->start +
781 async_extent->ram_size - 1);
784 * we need to redirty the pages if we decide to
785 * fallback to uncompressed IO, otherwise we
786 * will not submit these pages down to lower
789 extent_range_redirty_for_io(inode,
791 async_extent->start +
792 async_extent->ram_size - 1);
799 * here we're doing allocation and writeback of the
802 em = create_io_em(inode, async_extent->start,
803 async_extent->ram_size, /* len */
804 async_extent->start, /* orig_start */
805 ins.objectid, /* block_start */
806 ins.offset, /* block_len */
807 ins.offset, /* orig_block_len */
808 async_extent->ram_size, /* ram_bytes */
809 async_extent->compress_type,
810 BTRFS_ORDERED_COMPRESSED);
812 /* ret value is not necessary due to void function */
813 goto out_free_reserve;
816 ret = btrfs_add_ordered_extent_compress(inode,
819 async_extent->ram_size,
821 BTRFS_ORDERED_COMPRESSED,
822 async_extent->compress_type);
824 btrfs_drop_extent_cache(BTRFS_I(inode),
826 async_extent->start +
827 async_extent->ram_size - 1, 0);
828 goto out_free_reserve;
830 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
833 * clear dirty, set writeback and unlock the pages.
835 extent_clear_unlock_delalloc(inode, async_extent->start,
836 async_extent->start +
837 async_extent->ram_size - 1,
838 async_extent->start +
839 async_extent->ram_size - 1,
840 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
841 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
843 if (btrfs_submit_compressed_write(inode,
845 async_extent->ram_size,
847 ins.offset, async_extent->pages,
848 async_extent->nr_pages,
849 async_cow->write_flags)) {
850 struct page *p = async_extent->pages[0];
851 const u64 start = async_extent->start;
852 const u64 end = start + async_extent->ram_size - 1;
854 p->mapping = inode->i_mapping;
855 btrfs_writepage_endio_finish_ordered(p, start, end,
859 extent_clear_unlock_delalloc(inode, start, end, end,
863 free_async_extent_pages(async_extent);
865 alloc_hint = ins.objectid + ins.offset;
871 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
872 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
874 extent_clear_unlock_delalloc(inode, async_extent->start,
875 async_extent->start +
876 async_extent->ram_size - 1,
877 async_extent->start +
878 async_extent->ram_size - 1,
879 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
880 EXTENT_DELALLOC_NEW |
881 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
882 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
883 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
885 free_async_extent_pages(async_extent);
890 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
893 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
894 struct extent_map *em;
897 read_lock(&em_tree->lock);
898 em = search_extent_mapping(em_tree, start, num_bytes);
901 * if block start isn't an actual block number then find the
902 * first block in this inode and use that as a hint. If that
903 * block is also bogus then just don't worry about it.
905 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
907 em = search_extent_mapping(em_tree, 0, 0);
908 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
909 alloc_hint = em->block_start;
913 alloc_hint = em->block_start;
917 read_unlock(&em_tree->lock);
923 * when extent_io.c finds a delayed allocation range in the file,
924 * the call backs end up in this code. The basic idea is to
925 * allocate extents on disk for the range, and create ordered data structs
926 * in ram to track those extents.
928 * locked_page is the page that writepage had locked already. We use
929 * it to make sure we don't do extra locks or unlocks.
931 * *page_started is set to one if we unlock locked_page and do everything
932 * required to start IO on it. It may be clean and already done with
935 static noinline int cow_file_range(struct inode *inode,
936 struct page *locked_page,
937 u64 start, u64 end, u64 delalloc_end,
938 int *page_started, unsigned long *nr_written,
939 int unlock, struct btrfs_dedupe_hash *hash)
941 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
942 struct btrfs_root *root = BTRFS_I(inode)->root;
945 unsigned long ram_size;
946 u64 cur_alloc_size = 0;
947 u64 blocksize = fs_info->sectorsize;
948 struct btrfs_key ins;
949 struct extent_map *em;
951 unsigned long page_ops;
952 bool extent_reserved = false;
955 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
961 num_bytes = ALIGN(end - start + 1, blocksize);
962 num_bytes = max(blocksize, num_bytes);
963 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
965 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
968 /* lets try to make an inline extent */
969 ret = cow_file_range_inline(inode, start, end, 0,
970 BTRFS_COMPRESS_NONE, NULL);
973 * We use DO_ACCOUNTING here because we need the
974 * delalloc_release_metadata to be run _after_ we drop
975 * our outstanding extent for clearing delalloc for this
978 extent_clear_unlock_delalloc(inode, start, end,
980 EXTENT_LOCKED | EXTENT_DELALLOC |
981 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
982 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
983 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
985 *nr_written = *nr_written +
986 (end - start + PAGE_SIZE) / PAGE_SIZE;
989 } else if (ret < 0) {
994 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
995 btrfs_drop_extent_cache(BTRFS_I(inode), start,
996 start + num_bytes - 1, 0);
998 while (num_bytes > 0) {
999 cur_alloc_size = num_bytes;
1000 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1001 fs_info->sectorsize, 0, alloc_hint,
1005 cur_alloc_size = ins.offset;
1006 extent_reserved = true;
1008 ram_size = ins.offset;
1009 em = create_io_em(inode, start, ins.offset, /* len */
1010 start, /* orig_start */
1011 ins.objectid, /* block_start */
1012 ins.offset, /* block_len */
1013 ins.offset, /* orig_block_len */
1014 ram_size, /* ram_bytes */
1015 BTRFS_COMPRESS_NONE, /* compress_type */
1016 BTRFS_ORDERED_REGULAR /* type */);
1021 free_extent_map(em);
1023 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1024 ram_size, cur_alloc_size, 0);
1026 goto out_drop_extent_cache;
1028 if (root->root_key.objectid ==
1029 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1030 ret = btrfs_reloc_clone_csums(inode, start,
1033 * Only drop cache here, and process as normal.
1035 * We must not allow extent_clear_unlock_delalloc()
1036 * at out_unlock label to free meta of this ordered
1037 * extent, as its meta should be freed by
1038 * btrfs_finish_ordered_io().
1040 * So we must continue until @start is increased to
1041 * skip current ordered extent.
1044 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1045 start + ram_size - 1, 0);
1048 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1050 /* we're not doing compressed IO, don't unlock the first
1051 * page (which the caller expects to stay locked), don't
1052 * clear any dirty bits and don't set any writeback bits
1054 * Do set the Private2 bit so we know this page was properly
1055 * setup for writepage
1057 page_ops = unlock ? PAGE_UNLOCK : 0;
1058 page_ops |= PAGE_SET_PRIVATE2;
1060 extent_clear_unlock_delalloc(inode, start,
1061 start + ram_size - 1,
1062 delalloc_end, locked_page,
1063 EXTENT_LOCKED | EXTENT_DELALLOC,
1065 if (num_bytes < cur_alloc_size)
1068 num_bytes -= cur_alloc_size;
1069 alloc_hint = ins.objectid + ins.offset;
1070 start += cur_alloc_size;
1071 extent_reserved = false;
1074 * btrfs_reloc_clone_csums() error, since start is increased
1075 * extent_clear_unlock_delalloc() at out_unlock label won't
1076 * free metadata of current ordered extent, we're OK to exit.
1084 out_drop_extent_cache:
1085 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1087 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1088 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1090 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1091 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1092 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1095 * If we reserved an extent for our delalloc range (or a subrange) and
1096 * failed to create the respective ordered extent, then it means that
1097 * when we reserved the extent we decremented the extent's size from
1098 * the data space_info's bytes_may_use counter and incremented the
1099 * space_info's bytes_reserved counter by the same amount. We must make
1100 * sure extent_clear_unlock_delalloc() does not try to decrement again
1101 * the data space_info's bytes_may_use counter, therefore we do not pass
1102 * it the flag EXTENT_CLEAR_DATA_RESV.
1104 if (extent_reserved) {
1105 extent_clear_unlock_delalloc(inode, start,
1106 start + cur_alloc_size,
1107 start + cur_alloc_size,
1111 start += cur_alloc_size;
1115 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1117 clear_bits | EXTENT_CLEAR_DATA_RESV,
1123 * work queue call back to started compression on a file and pages
1125 static noinline void async_cow_start(struct btrfs_work *work)
1127 struct async_cow *async_cow;
1129 async_cow = container_of(work, struct async_cow, work);
1131 compress_file_range(async_cow->inode, async_cow->locked_page,
1132 async_cow->start, async_cow->end, async_cow,
1134 if (num_added == 0) {
1135 btrfs_add_delayed_iput(async_cow->inode);
1136 async_cow->inode = NULL;
1141 * work queue call back to submit previously compressed pages
1143 static noinline void async_cow_submit(struct btrfs_work *work)
1145 struct btrfs_fs_info *fs_info;
1146 struct async_cow *async_cow;
1147 struct btrfs_root *root;
1148 unsigned long nr_pages;
1150 async_cow = container_of(work, struct async_cow, work);
1152 root = async_cow->root;
1153 fs_info = root->fs_info;
1154 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1157 /* atomic_sub_return implies a barrier */
1158 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1160 cond_wake_up_nomb(&fs_info->async_submit_wait);
1162 if (async_cow->inode)
1163 submit_compressed_extents(async_cow->inode, async_cow);
1166 static noinline void async_cow_free(struct btrfs_work *work)
1168 struct async_cow *async_cow;
1169 async_cow = container_of(work, struct async_cow, work);
1170 if (async_cow->inode)
1171 btrfs_add_delayed_iput(async_cow->inode);
1175 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1176 u64 start, u64 end, int *page_started,
1177 unsigned long *nr_written,
1178 unsigned int write_flags)
1180 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1181 struct async_cow *async_cow;
1182 struct btrfs_root *root = BTRFS_I(inode)->root;
1183 unsigned long nr_pages;
1186 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1188 while (start < end) {
1189 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1190 BUG_ON(!async_cow); /* -ENOMEM */
1191 async_cow->inode = igrab(inode);
1192 async_cow->root = root;
1193 async_cow->locked_page = locked_page;
1194 async_cow->start = start;
1195 async_cow->write_flags = write_flags;
1197 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1198 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1201 cur_end = min(end, start + SZ_512K - 1);
1203 async_cow->end = cur_end;
1204 INIT_LIST_HEAD(&async_cow->extents);
1206 btrfs_init_work(&async_cow->work,
1207 btrfs_delalloc_helper,
1208 async_cow_start, async_cow_submit,
1211 nr_pages = (cur_end - start + PAGE_SIZE) >>
1213 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1215 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1217 *nr_written += nr_pages;
1218 start = cur_end + 1;
1224 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1225 u64 bytenr, u64 num_bytes)
1228 struct btrfs_ordered_sum *sums;
1231 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1232 bytenr + num_bytes - 1, &list, 0);
1233 if (ret == 0 && list_empty(&list))
1236 while (!list_empty(&list)) {
1237 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1238 list_del(&sums->list);
1247 * when nowcow writeback call back. This checks for snapshots or COW copies
1248 * of the extents that exist in the file, and COWs the file as required.
1250 * If no cow copies or snapshots exist, we write directly to the existing
1253 static noinline int run_delalloc_nocow(struct inode *inode,
1254 struct page *locked_page,
1255 u64 start, u64 end, int *page_started, int force,
1256 unsigned long *nr_written)
1258 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1259 struct btrfs_root *root = BTRFS_I(inode)->root;
1260 struct extent_buffer *leaf;
1261 struct btrfs_path *path;
1262 struct btrfs_file_extent_item *fi;
1263 struct btrfs_key found_key;
1264 struct extent_map *em;
1279 u64 ino = btrfs_ino(BTRFS_I(inode));
1281 path = btrfs_alloc_path();
1283 extent_clear_unlock_delalloc(inode, start, end, end,
1285 EXTENT_LOCKED | EXTENT_DELALLOC |
1286 EXTENT_DO_ACCOUNTING |
1287 EXTENT_DEFRAG, PAGE_UNLOCK |
1289 PAGE_SET_WRITEBACK |
1290 PAGE_END_WRITEBACK);
1294 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1296 cow_start = (u64)-1;
1299 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1303 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1304 leaf = path->nodes[0];
1305 btrfs_item_key_to_cpu(leaf, &found_key,
1306 path->slots[0] - 1);
1307 if (found_key.objectid == ino &&
1308 found_key.type == BTRFS_EXTENT_DATA_KEY)
1313 leaf = path->nodes[0];
1314 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1315 ret = btrfs_next_leaf(root, path);
1317 if (cow_start != (u64)-1)
1318 cur_offset = cow_start;
1323 leaf = path->nodes[0];
1329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1331 if (found_key.objectid > ino)
1333 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1334 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1338 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1339 found_key.offset > end)
1342 if (found_key.offset > cur_offset) {
1343 extent_end = found_key.offset;
1348 fi = btrfs_item_ptr(leaf, path->slots[0],
1349 struct btrfs_file_extent_item);
1350 extent_type = btrfs_file_extent_type(leaf, fi);
1352 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1353 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1354 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1355 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1356 extent_offset = btrfs_file_extent_offset(leaf, fi);
1357 extent_end = found_key.offset +
1358 btrfs_file_extent_num_bytes(leaf, fi);
1360 btrfs_file_extent_disk_num_bytes(leaf, fi);
1361 if (extent_end <= start) {
1365 if (disk_bytenr == 0)
1367 if (btrfs_file_extent_compression(leaf, fi) ||
1368 btrfs_file_extent_encryption(leaf, fi) ||
1369 btrfs_file_extent_other_encoding(leaf, fi))
1372 * Do the same check as in btrfs_cross_ref_exist but
1373 * without the unnecessary search.
1375 if (btrfs_file_extent_generation(leaf, fi) <=
1376 btrfs_root_last_snapshot(&root->root_item))
1378 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1380 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1382 ret = btrfs_cross_ref_exist(root, ino,
1384 extent_offset, disk_bytenr);
1387 * ret could be -EIO if the above fails to read
1391 if (cow_start != (u64)-1)
1392 cur_offset = cow_start;
1396 WARN_ON_ONCE(nolock);
1399 disk_bytenr += extent_offset;
1400 disk_bytenr += cur_offset - found_key.offset;
1401 num_bytes = min(end + 1, extent_end) - cur_offset;
1403 * if there are pending snapshots for this root,
1404 * we fall into common COW way.
1406 if (!nolock && atomic_read(&root->snapshot_force_cow))
1409 * force cow if csum exists in the range.
1410 * this ensure that csum for a given extent are
1411 * either valid or do not exist.
1413 ret = csum_exist_in_range(fs_info, disk_bytenr,
1417 * ret could be -EIO if the above fails to read
1421 if (cow_start != (u64)-1)
1422 cur_offset = cow_start;
1425 WARN_ON_ONCE(nolock);
1428 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1431 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1432 extent_end = found_key.offset +
1433 btrfs_file_extent_ram_bytes(leaf, fi);
1434 extent_end = ALIGN(extent_end,
1435 fs_info->sectorsize);
1440 if (extent_end <= start) {
1443 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1447 if (cow_start == (u64)-1)
1448 cow_start = cur_offset;
1449 cur_offset = extent_end;
1450 if (cur_offset > end)
1456 btrfs_release_path(path);
1457 if (cow_start != (u64)-1) {
1458 ret = cow_file_range(inode, locked_page,
1459 cow_start, found_key.offset - 1,
1460 end, page_started, nr_written, 1,
1464 btrfs_dec_nocow_writers(fs_info,
1468 cow_start = (u64)-1;
1471 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1472 u64 orig_start = found_key.offset - extent_offset;
1474 em = create_io_em(inode, cur_offset, num_bytes,
1476 disk_bytenr, /* block_start */
1477 num_bytes, /* block_len */
1478 disk_num_bytes, /* orig_block_len */
1479 ram_bytes, BTRFS_COMPRESS_NONE,
1480 BTRFS_ORDERED_PREALLOC);
1483 btrfs_dec_nocow_writers(fs_info,
1488 free_extent_map(em);
1491 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1492 type = BTRFS_ORDERED_PREALLOC;
1494 type = BTRFS_ORDERED_NOCOW;
1497 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1498 num_bytes, num_bytes, type);
1500 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1501 BUG_ON(ret); /* -ENOMEM */
1503 if (root->root_key.objectid ==
1504 BTRFS_DATA_RELOC_TREE_OBJECTID)
1506 * Error handled later, as we must prevent
1507 * extent_clear_unlock_delalloc() in error handler
1508 * from freeing metadata of created ordered extent.
1510 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1513 extent_clear_unlock_delalloc(inode, cur_offset,
1514 cur_offset + num_bytes - 1, end,
1515 locked_page, EXTENT_LOCKED |
1517 EXTENT_CLEAR_DATA_RESV,
1518 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1520 cur_offset = extent_end;
1523 * btrfs_reloc_clone_csums() error, now we're OK to call error
1524 * handler, as metadata for created ordered extent will only
1525 * be freed by btrfs_finish_ordered_io().
1529 if (cur_offset > end)
1532 btrfs_release_path(path);
1534 if (cur_offset <= end && cow_start == (u64)-1)
1535 cow_start = cur_offset;
1537 if (cow_start != (u64)-1) {
1539 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1540 page_started, nr_written, 1, NULL);
1546 if (ret && cur_offset < end)
1547 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1548 locked_page, EXTENT_LOCKED |
1549 EXTENT_DELALLOC | EXTENT_DEFRAG |
1550 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1552 PAGE_SET_WRITEBACK |
1553 PAGE_END_WRITEBACK);
1554 btrfs_free_path(path);
1558 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1561 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1562 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1566 * @defrag_bytes is a hint value, no spinlock held here,
1567 * if is not zero, it means the file is defragging.
1568 * Force cow if given extent needs to be defragged.
1570 if (BTRFS_I(inode)->defrag_bytes &&
1571 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1572 EXTENT_DEFRAG, 0, NULL))
1579 * Function to process delayed allocation (create CoW) for ranges which are
1580 * being touched for the first time.
1582 int btrfs_run_delalloc_range(void *private_data, struct page *locked_page,
1583 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1584 struct writeback_control *wbc)
1586 struct inode *inode = private_data;
1588 int force_cow = need_force_cow(inode, start, end);
1589 unsigned int write_flags = wbc_to_write_flags(wbc);
1591 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1592 ret = run_delalloc_nocow(inode, locked_page, start, end,
1593 page_started, 1, nr_written);
1594 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1595 ret = run_delalloc_nocow(inode, locked_page, start, end,
1596 page_started, 0, nr_written);
1597 } else if (!inode_need_compress(inode, start, end)) {
1598 ret = cow_file_range(inode, locked_page, start, end, end,
1599 page_started, nr_written, 1, NULL);
1601 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1602 &BTRFS_I(inode)->runtime_flags);
1603 ret = cow_file_range_async(inode, locked_page, start, end,
1604 page_started, nr_written,
1608 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1612 void btrfs_split_delalloc_extent(struct inode *inode,
1613 struct extent_state *orig, u64 split)
1617 /* not delalloc, ignore it */
1618 if (!(orig->state & EXTENT_DELALLOC))
1621 size = orig->end - orig->start + 1;
1622 if (size > BTRFS_MAX_EXTENT_SIZE) {
1627 * See the explanation in btrfs_merge_delalloc_extent, the same
1628 * applies here, just in reverse.
1630 new_size = orig->end - split + 1;
1631 num_extents = count_max_extents(new_size);
1632 new_size = split - orig->start;
1633 num_extents += count_max_extents(new_size);
1634 if (count_max_extents(size) >= num_extents)
1638 spin_lock(&BTRFS_I(inode)->lock);
1639 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1640 spin_unlock(&BTRFS_I(inode)->lock);
1644 * Handle merged delayed allocation extents so we can keep track of new extents
1645 * that are just merged onto old extents, such as when we are doing sequential
1646 * writes, so we can properly account for the metadata space we'll need.
1648 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1649 struct extent_state *other)
1651 u64 new_size, old_size;
1654 /* not delalloc, ignore it */
1655 if (!(other->state & EXTENT_DELALLOC))
1658 if (new->start > other->start)
1659 new_size = new->end - other->start + 1;
1661 new_size = other->end - new->start + 1;
1663 /* we're not bigger than the max, unreserve the space and go */
1664 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1665 spin_lock(&BTRFS_I(inode)->lock);
1666 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1667 spin_unlock(&BTRFS_I(inode)->lock);
1672 * We have to add up either side to figure out how many extents were
1673 * accounted for before we merged into one big extent. If the number of
1674 * extents we accounted for is <= the amount we need for the new range
1675 * then we can return, otherwise drop. Think of it like this
1679 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1680 * need 2 outstanding extents, on one side we have 1 and the other side
1681 * we have 1 so they are == and we can return. But in this case
1683 * [MAX_SIZE+4k][MAX_SIZE+4k]
1685 * Each range on their own accounts for 2 extents, but merged together
1686 * they are only 3 extents worth of accounting, so we need to drop in
1689 old_size = other->end - other->start + 1;
1690 num_extents = count_max_extents(old_size);
1691 old_size = new->end - new->start + 1;
1692 num_extents += count_max_extents(old_size);
1693 if (count_max_extents(new_size) >= num_extents)
1696 spin_lock(&BTRFS_I(inode)->lock);
1697 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1698 spin_unlock(&BTRFS_I(inode)->lock);
1701 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1702 struct inode *inode)
1704 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1706 spin_lock(&root->delalloc_lock);
1707 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1708 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1709 &root->delalloc_inodes);
1710 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1711 &BTRFS_I(inode)->runtime_flags);
1712 root->nr_delalloc_inodes++;
1713 if (root->nr_delalloc_inodes == 1) {
1714 spin_lock(&fs_info->delalloc_root_lock);
1715 BUG_ON(!list_empty(&root->delalloc_root));
1716 list_add_tail(&root->delalloc_root,
1717 &fs_info->delalloc_roots);
1718 spin_unlock(&fs_info->delalloc_root_lock);
1721 spin_unlock(&root->delalloc_lock);
1725 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1726 struct btrfs_inode *inode)
1728 struct btrfs_fs_info *fs_info = root->fs_info;
1730 if (!list_empty(&inode->delalloc_inodes)) {
1731 list_del_init(&inode->delalloc_inodes);
1732 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1733 &inode->runtime_flags);
1734 root->nr_delalloc_inodes--;
1735 if (!root->nr_delalloc_inodes) {
1736 ASSERT(list_empty(&root->delalloc_inodes));
1737 spin_lock(&fs_info->delalloc_root_lock);
1738 BUG_ON(list_empty(&root->delalloc_root));
1739 list_del_init(&root->delalloc_root);
1740 spin_unlock(&fs_info->delalloc_root_lock);
1745 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1746 struct btrfs_inode *inode)
1748 spin_lock(&root->delalloc_lock);
1749 __btrfs_del_delalloc_inode(root, inode);
1750 spin_unlock(&root->delalloc_lock);
1754 * Properly track delayed allocation bytes in the inode and to maintain the
1755 * list of inodes that have pending delalloc work to be done.
1757 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1760 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1762 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1765 * set_bit and clear bit hooks normally require _irqsave/restore
1766 * but in this case, we are only testing for the DELALLOC
1767 * bit, which is only set or cleared with irqs on
1769 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1770 struct btrfs_root *root = BTRFS_I(inode)->root;
1771 u64 len = state->end + 1 - state->start;
1772 u32 num_extents = count_max_extents(len);
1773 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1775 spin_lock(&BTRFS_I(inode)->lock);
1776 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1777 spin_unlock(&BTRFS_I(inode)->lock);
1779 /* For sanity tests */
1780 if (btrfs_is_testing(fs_info))
1783 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1784 fs_info->delalloc_batch);
1785 spin_lock(&BTRFS_I(inode)->lock);
1786 BTRFS_I(inode)->delalloc_bytes += len;
1787 if (*bits & EXTENT_DEFRAG)
1788 BTRFS_I(inode)->defrag_bytes += len;
1789 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1790 &BTRFS_I(inode)->runtime_flags))
1791 btrfs_add_delalloc_inodes(root, inode);
1792 spin_unlock(&BTRFS_I(inode)->lock);
1795 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1796 (*bits & EXTENT_DELALLOC_NEW)) {
1797 spin_lock(&BTRFS_I(inode)->lock);
1798 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1800 spin_unlock(&BTRFS_I(inode)->lock);
1805 * Once a range is no longer delalloc this function ensures that proper
1806 * accounting happens.
1808 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1809 struct extent_state *state, unsigned *bits)
1811 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1812 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1813 u64 len = state->end + 1 - state->start;
1814 u32 num_extents = count_max_extents(len);
1816 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1817 spin_lock(&inode->lock);
1818 inode->defrag_bytes -= len;
1819 spin_unlock(&inode->lock);
1823 * set_bit and clear bit hooks normally require _irqsave/restore
1824 * but in this case, we are only testing for the DELALLOC
1825 * bit, which is only set or cleared with irqs on
1827 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1828 struct btrfs_root *root = inode->root;
1829 bool do_list = !btrfs_is_free_space_inode(inode);
1831 spin_lock(&inode->lock);
1832 btrfs_mod_outstanding_extents(inode, -num_extents);
1833 spin_unlock(&inode->lock);
1836 * We don't reserve metadata space for space cache inodes so we
1837 * don't need to call dellalloc_release_metadata if there is an
1840 if (*bits & EXTENT_CLEAR_META_RESV &&
1841 root != fs_info->tree_root)
1842 btrfs_delalloc_release_metadata(inode, len, false);
1844 /* For sanity tests. */
1845 if (btrfs_is_testing(fs_info))
1848 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1849 do_list && !(state->state & EXTENT_NORESERVE) &&
1850 (*bits & EXTENT_CLEAR_DATA_RESV))
1851 btrfs_free_reserved_data_space_noquota(
1855 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1856 fs_info->delalloc_batch);
1857 spin_lock(&inode->lock);
1858 inode->delalloc_bytes -= len;
1859 if (do_list && inode->delalloc_bytes == 0 &&
1860 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1861 &inode->runtime_flags))
1862 btrfs_del_delalloc_inode(root, inode);
1863 spin_unlock(&inode->lock);
1866 if ((state->state & EXTENT_DELALLOC_NEW) &&
1867 (*bits & EXTENT_DELALLOC_NEW)) {
1868 spin_lock(&inode->lock);
1869 ASSERT(inode->new_delalloc_bytes >= len);
1870 inode->new_delalloc_bytes -= len;
1871 spin_unlock(&inode->lock);
1876 * Merge bio hook, this must check the chunk tree to make sure we don't create
1877 * bios that span stripes or chunks
1879 * return 1 if page cannot be merged to bio
1880 * return 0 if page can be merged to bio
1881 * return error otherwise
1883 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1884 size_t size, struct bio *bio,
1885 unsigned long bio_flags)
1887 struct inode *inode = page->mapping->host;
1888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1894 if (bio_flags & EXTENT_BIO_COMPRESSED)
1897 length = bio->bi_iter.bi_size;
1898 map_length = length;
1899 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1903 if (map_length < length + size)
1909 * in order to insert checksums into the metadata in large chunks,
1910 * we wait until bio submission time. All the pages in the bio are
1911 * checksummed and sums are attached onto the ordered extent record.
1913 * At IO completion time the cums attached on the ordered extent record
1914 * are inserted into the btree
1916 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1919 struct inode *inode = private_data;
1920 blk_status_t ret = 0;
1922 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1923 BUG_ON(ret); /* -ENOMEM */
1928 * in order to insert checksums into the metadata in large chunks,
1929 * we wait until bio submission time. All the pages in the bio are
1930 * checksummed and sums are attached onto the ordered extent record.
1932 * At IO completion time the cums attached on the ordered extent record
1933 * are inserted into the btree
1935 blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1938 struct inode *inode = private_data;
1939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1942 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1944 bio->bi_status = ret;
1951 * extent_io.c submission hook. This does the right thing for csum calculation
1952 * on write, or reading the csums from the tree before a read.
1954 * Rules about async/sync submit,
1955 * a) read: sync submit
1957 * b) write without checksum: sync submit
1959 * c) write with checksum:
1960 * c-1) if bio is issued by fsync: sync submit
1961 * (sync_writers != 0)
1963 * c-2) if root is reloc root: sync submit
1964 * (only in case of buffered IO)
1966 * c-3) otherwise: async submit
1968 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1969 int mirror_num, unsigned long bio_flags,
1972 struct inode *inode = private_data;
1973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1974 struct btrfs_root *root = BTRFS_I(inode)->root;
1975 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1976 blk_status_t ret = 0;
1978 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1980 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1982 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1983 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1985 if (bio_op(bio) != REQ_OP_WRITE) {
1986 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1990 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1991 ret = btrfs_submit_compressed_read(inode, bio,
1995 } else if (!skip_sum) {
1996 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2001 } else if (async && !skip_sum) {
2002 /* csum items have already been cloned */
2003 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2005 /* we're doing a write, do the async checksumming */
2006 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2008 btrfs_submit_bio_start);
2010 } else if (!skip_sum) {
2011 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2017 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2021 bio->bi_status = ret;
2028 * given a list of ordered sums record them in the inode. This happens
2029 * at IO completion time based on sums calculated at bio submission time.
2031 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2032 struct inode *inode, struct list_head *list)
2034 struct btrfs_ordered_sum *sum;
2037 list_for_each_entry(sum, list, list) {
2038 trans->adding_csums = true;
2039 ret = btrfs_csum_file_blocks(trans,
2040 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2041 trans->adding_csums = false;
2048 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2049 unsigned int extra_bits,
2050 struct extent_state **cached_state, int dedupe)
2052 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2053 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2054 extra_bits, cached_state);
2057 /* see btrfs_writepage_start_hook for details on why this is required */
2058 struct btrfs_writepage_fixup {
2060 struct btrfs_work work;
2063 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2065 struct btrfs_writepage_fixup *fixup;
2066 struct btrfs_ordered_extent *ordered;
2067 struct extent_state *cached_state = NULL;
2068 struct extent_changeset *data_reserved = NULL;
2070 struct inode *inode;
2075 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2079 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2080 ClearPageChecked(page);
2084 inode = page->mapping->host;
2085 page_start = page_offset(page);
2086 page_end = page_offset(page) + PAGE_SIZE - 1;
2088 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2091 /* already ordered? We're done */
2092 if (PagePrivate2(page))
2095 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2098 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2099 page_end, &cached_state);
2101 btrfs_start_ordered_extent(inode, ordered, 1);
2102 btrfs_put_ordered_extent(ordered);
2106 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2109 mapping_set_error(page->mapping, ret);
2110 end_extent_writepage(page, ret, page_start, page_end);
2111 ClearPageChecked(page);
2115 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2118 mapping_set_error(page->mapping, ret);
2119 end_extent_writepage(page, ret, page_start, page_end);
2120 ClearPageChecked(page);
2124 ClearPageChecked(page);
2125 set_page_dirty(page);
2126 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2128 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2134 extent_changeset_free(data_reserved);
2138 * There are a few paths in the higher layers of the kernel that directly
2139 * set the page dirty bit without asking the filesystem if it is a
2140 * good idea. This causes problems because we want to make sure COW
2141 * properly happens and the data=ordered rules are followed.
2143 * In our case any range that doesn't have the ORDERED bit set
2144 * hasn't been properly setup for IO. We kick off an async process
2145 * to fix it up. The async helper will wait for ordered extents, set
2146 * the delalloc bit and make it safe to write the page.
2148 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2150 struct inode *inode = page->mapping->host;
2151 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2152 struct btrfs_writepage_fixup *fixup;
2154 /* this page is properly in the ordered list */
2155 if (TestClearPagePrivate2(page))
2158 if (PageChecked(page))
2161 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2165 SetPageChecked(page);
2167 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2168 btrfs_writepage_fixup_worker, NULL, NULL);
2170 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2174 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2175 struct inode *inode, u64 file_pos,
2176 u64 disk_bytenr, u64 disk_num_bytes,
2177 u64 num_bytes, u64 ram_bytes,
2178 u8 compression, u8 encryption,
2179 u16 other_encoding, int extent_type)
2181 struct btrfs_root *root = BTRFS_I(inode)->root;
2182 struct btrfs_file_extent_item *fi;
2183 struct btrfs_path *path;
2184 struct extent_buffer *leaf;
2185 struct btrfs_key ins;
2187 int extent_inserted = 0;
2190 path = btrfs_alloc_path();
2195 * we may be replacing one extent in the tree with another.
2196 * The new extent is pinned in the extent map, and we don't want
2197 * to drop it from the cache until it is completely in the btree.
2199 * So, tell btrfs_drop_extents to leave this extent in the cache.
2200 * the caller is expected to unpin it and allow it to be merged
2203 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2204 file_pos + num_bytes, NULL, 0,
2205 1, sizeof(*fi), &extent_inserted);
2209 if (!extent_inserted) {
2210 ins.objectid = btrfs_ino(BTRFS_I(inode));
2211 ins.offset = file_pos;
2212 ins.type = BTRFS_EXTENT_DATA_KEY;
2214 path->leave_spinning = 1;
2215 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2220 leaf = path->nodes[0];
2221 fi = btrfs_item_ptr(leaf, path->slots[0],
2222 struct btrfs_file_extent_item);
2223 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2224 btrfs_set_file_extent_type(leaf, fi, extent_type);
2225 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2226 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2227 btrfs_set_file_extent_offset(leaf, fi, 0);
2228 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2229 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2230 btrfs_set_file_extent_compression(leaf, fi, compression);
2231 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2232 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2234 btrfs_mark_buffer_dirty(leaf);
2235 btrfs_release_path(path);
2237 inode_add_bytes(inode, num_bytes);
2239 ins.objectid = disk_bytenr;
2240 ins.offset = disk_num_bytes;
2241 ins.type = BTRFS_EXTENT_ITEM_KEY;
2244 * Release the reserved range from inode dirty range map, as it is
2245 * already moved into delayed_ref_head
2247 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2251 ret = btrfs_alloc_reserved_file_extent(trans, root,
2252 btrfs_ino(BTRFS_I(inode)),
2253 file_pos, qg_released, &ins);
2255 btrfs_free_path(path);
2260 /* snapshot-aware defrag */
2261 struct sa_defrag_extent_backref {
2262 struct rb_node node;
2263 struct old_sa_defrag_extent *old;
2272 struct old_sa_defrag_extent {
2273 struct list_head list;
2274 struct new_sa_defrag_extent *new;
2283 struct new_sa_defrag_extent {
2284 struct rb_root root;
2285 struct list_head head;
2286 struct btrfs_path *path;
2287 struct inode *inode;
2295 static int backref_comp(struct sa_defrag_extent_backref *b1,
2296 struct sa_defrag_extent_backref *b2)
2298 if (b1->root_id < b2->root_id)
2300 else if (b1->root_id > b2->root_id)
2303 if (b1->inum < b2->inum)
2305 else if (b1->inum > b2->inum)
2308 if (b1->file_pos < b2->file_pos)
2310 else if (b1->file_pos > b2->file_pos)
2314 * [------------------------------] ===> (a range of space)
2315 * |<--->| |<---->| =============> (fs/file tree A)
2316 * |<---------------------------->| ===> (fs/file tree B)
2318 * A range of space can refer to two file extents in one tree while
2319 * refer to only one file extent in another tree.
2321 * So we may process a disk offset more than one time(two extents in A)
2322 * and locate at the same extent(one extent in B), then insert two same
2323 * backrefs(both refer to the extent in B).
2328 static void backref_insert(struct rb_root *root,
2329 struct sa_defrag_extent_backref *backref)
2331 struct rb_node **p = &root->rb_node;
2332 struct rb_node *parent = NULL;
2333 struct sa_defrag_extent_backref *entry;
2338 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2340 ret = backref_comp(backref, entry);
2344 p = &(*p)->rb_right;
2347 rb_link_node(&backref->node, parent, p);
2348 rb_insert_color(&backref->node, root);
2352 * Note the backref might has changed, and in this case we just return 0.
2354 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2357 struct btrfs_file_extent_item *extent;
2358 struct old_sa_defrag_extent *old = ctx;
2359 struct new_sa_defrag_extent *new = old->new;
2360 struct btrfs_path *path = new->path;
2361 struct btrfs_key key;
2362 struct btrfs_root *root;
2363 struct sa_defrag_extent_backref *backref;
2364 struct extent_buffer *leaf;
2365 struct inode *inode = new->inode;
2366 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2372 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2373 inum == btrfs_ino(BTRFS_I(inode)))
2376 key.objectid = root_id;
2377 key.type = BTRFS_ROOT_ITEM_KEY;
2378 key.offset = (u64)-1;
2380 root = btrfs_read_fs_root_no_name(fs_info, &key);
2382 if (PTR_ERR(root) == -ENOENT)
2385 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2386 inum, offset, root_id);
2387 return PTR_ERR(root);
2390 key.objectid = inum;
2391 key.type = BTRFS_EXTENT_DATA_KEY;
2392 if (offset > (u64)-1 << 32)
2395 key.offset = offset;
2397 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2398 if (WARN_ON(ret < 0))
2405 leaf = path->nodes[0];
2406 slot = path->slots[0];
2408 if (slot >= btrfs_header_nritems(leaf)) {
2409 ret = btrfs_next_leaf(root, path);
2412 } else if (ret > 0) {
2421 btrfs_item_key_to_cpu(leaf, &key, slot);
2423 if (key.objectid > inum)
2426 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2429 extent = btrfs_item_ptr(leaf, slot,
2430 struct btrfs_file_extent_item);
2432 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2436 * 'offset' refers to the exact key.offset,
2437 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2438 * (key.offset - extent_offset).
2440 if (key.offset != offset)
2443 extent_offset = btrfs_file_extent_offset(leaf, extent);
2444 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2446 if (extent_offset >= old->extent_offset + old->offset +
2447 old->len || extent_offset + num_bytes <=
2448 old->extent_offset + old->offset)
2453 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2459 backref->root_id = root_id;
2460 backref->inum = inum;
2461 backref->file_pos = offset;
2462 backref->num_bytes = num_bytes;
2463 backref->extent_offset = extent_offset;
2464 backref->generation = btrfs_file_extent_generation(leaf, extent);
2466 backref_insert(&new->root, backref);
2469 btrfs_release_path(path);
2474 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2475 struct new_sa_defrag_extent *new)
2477 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2478 struct old_sa_defrag_extent *old, *tmp;
2483 list_for_each_entry_safe(old, tmp, &new->head, list) {
2484 ret = iterate_inodes_from_logical(old->bytenr +
2485 old->extent_offset, fs_info,
2486 path, record_one_backref,
2488 if (ret < 0 && ret != -ENOENT)
2491 /* no backref to be processed for this extent */
2493 list_del(&old->list);
2498 if (list_empty(&new->head))
2504 static int relink_is_mergable(struct extent_buffer *leaf,
2505 struct btrfs_file_extent_item *fi,
2506 struct new_sa_defrag_extent *new)
2508 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2511 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2514 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2517 if (btrfs_file_extent_encryption(leaf, fi) ||
2518 btrfs_file_extent_other_encoding(leaf, fi))
2525 * Note the backref might has changed, and in this case we just return 0.
2527 static noinline int relink_extent_backref(struct btrfs_path *path,
2528 struct sa_defrag_extent_backref *prev,
2529 struct sa_defrag_extent_backref *backref)
2531 struct btrfs_file_extent_item *extent;
2532 struct btrfs_file_extent_item *item;
2533 struct btrfs_ordered_extent *ordered;
2534 struct btrfs_trans_handle *trans;
2535 struct btrfs_root *root;
2536 struct btrfs_key key;
2537 struct extent_buffer *leaf;
2538 struct old_sa_defrag_extent *old = backref->old;
2539 struct new_sa_defrag_extent *new = old->new;
2540 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2541 struct inode *inode;
2542 struct extent_state *cached = NULL;
2551 if (prev && prev->root_id == backref->root_id &&
2552 prev->inum == backref->inum &&
2553 prev->file_pos + prev->num_bytes == backref->file_pos)
2556 /* step 1: get root */
2557 key.objectid = backref->root_id;
2558 key.type = BTRFS_ROOT_ITEM_KEY;
2559 key.offset = (u64)-1;
2561 index = srcu_read_lock(&fs_info->subvol_srcu);
2563 root = btrfs_read_fs_root_no_name(fs_info, &key);
2565 srcu_read_unlock(&fs_info->subvol_srcu, index);
2566 if (PTR_ERR(root) == -ENOENT)
2568 return PTR_ERR(root);
2571 if (btrfs_root_readonly(root)) {
2572 srcu_read_unlock(&fs_info->subvol_srcu, index);
2576 /* step 2: get inode */
2577 key.objectid = backref->inum;
2578 key.type = BTRFS_INODE_ITEM_KEY;
2581 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2582 if (IS_ERR(inode)) {
2583 srcu_read_unlock(&fs_info->subvol_srcu, index);
2587 srcu_read_unlock(&fs_info->subvol_srcu, index);
2589 /* step 3: relink backref */
2590 lock_start = backref->file_pos;
2591 lock_end = backref->file_pos + backref->num_bytes - 1;
2592 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2595 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2597 btrfs_put_ordered_extent(ordered);
2601 trans = btrfs_join_transaction(root);
2602 if (IS_ERR(trans)) {
2603 ret = PTR_ERR(trans);
2607 key.objectid = backref->inum;
2608 key.type = BTRFS_EXTENT_DATA_KEY;
2609 key.offset = backref->file_pos;
2611 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2614 } else if (ret > 0) {
2619 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2620 struct btrfs_file_extent_item);
2622 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2623 backref->generation)
2626 btrfs_release_path(path);
2628 start = backref->file_pos;
2629 if (backref->extent_offset < old->extent_offset + old->offset)
2630 start += old->extent_offset + old->offset -
2631 backref->extent_offset;
2633 len = min(backref->extent_offset + backref->num_bytes,
2634 old->extent_offset + old->offset + old->len);
2635 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2637 ret = btrfs_drop_extents(trans, root, inode, start,
2642 key.objectid = btrfs_ino(BTRFS_I(inode));
2643 key.type = BTRFS_EXTENT_DATA_KEY;
2646 path->leave_spinning = 1;
2648 struct btrfs_file_extent_item *fi;
2650 struct btrfs_key found_key;
2652 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2657 leaf = path->nodes[0];
2658 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2660 fi = btrfs_item_ptr(leaf, path->slots[0],
2661 struct btrfs_file_extent_item);
2662 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2664 if (extent_len + found_key.offset == start &&
2665 relink_is_mergable(leaf, fi, new)) {
2666 btrfs_set_file_extent_num_bytes(leaf, fi,
2668 btrfs_mark_buffer_dirty(leaf);
2669 inode_add_bytes(inode, len);
2675 btrfs_release_path(path);
2680 ret = btrfs_insert_empty_item(trans, root, path, &key,
2683 btrfs_abort_transaction(trans, ret);
2687 leaf = path->nodes[0];
2688 item = btrfs_item_ptr(leaf, path->slots[0],
2689 struct btrfs_file_extent_item);
2690 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2691 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2692 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2693 btrfs_set_file_extent_num_bytes(leaf, item, len);
2694 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2695 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2696 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2697 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2698 btrfs_set_file_extent_encryption(leaf, item, 0);
2699 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2701 btrfs_mark_buffer_dirty(leaf);
2702 inode_add_bytes(inode, len);
2703 btrfs_release_path(path);
2705 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2707 backref->root_id, backref->inum,
2708 new->file_pos); /* start - extent_offset */
2710 btrfs_abort_transaction(trans, ret);
2716 btrfs_release_path(path);
2717 path->leave_spinning = 0;
2718 btrfs_end_transaction(trans);
2720 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2726 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2728 struct old_sa_defrag_extent *old, *tmp;
2733 list_for_each_entry_safe(old, tmp, &new->head, list) {
2739 static void relink_file_extents(struct new_sa_defrag_extent *new)
2741 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2742 struct btrfs_path *path;
2743 struct sa_defrag_extent_backref *backref;
2744 struct sa_defrag_extent_backref *prev = NULL;
2745 struct rb_node *node;
2748 path = btrfs_alloc_path();
2752 if (!record_extent_backrefs(path, new)) {
2753 btrfs_free_path(path);
2756 btrfs_release_path(path);
2759 node = rb_first(&new->root);
2762 rb_erase(node, &new->root);
2764 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2766 ret = relink_extent_backref(path, prev, backref);
2779 btrfs_free_path(path);
2781 free_sa_defrag_extent(new);
2783 atomic_dec(&fs_info->defrag_running);
2784 wake_up(&fs_info->transaction_wait);
2787 static struct new_sa_defrag_extent *
2788 record_old_file_extents(struct inode *inode,
2789 struct btrfs_ordered_extent *ordered)
2791 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2792 struct btrfs_root *root = BTRFS_I(inode)->root;
2793 struct btrfs_path *path;
2794 struct btrfs_key key;
2795 struct old_sa_defrag_extent *old;
2796 struct new_sa_defrag_extent *new;
2799 new = kmalloc(sizeof(*new), GFP_NOFS);
2804 new->file_pos = ordered->file_offset;
2805 new->len = ordered->len;
2806 new->bytenr = ordered->start;
2807 new->disk_len = ordered->disk_len;
2808 new->compress_type = ordered->compress_type;
2809 new->root = RB_ROOT;
2810 INIT_LIST_HEAD(&new->head);
2812 path = btrfs_alloc_path();
2816 key.objectid = btrfs_ino(BTRFS_I(inode));
2817 key.type = BTRFS_EXTENT_DATA_KEY;
2818 key.offset = new->file_pos;
2820 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2823 if (ret > 0 && path->slots[0] > 0)
2826 /* find out all the old extents for the file range */
2828 struct btrfs_file_extent_item *extent;
2829 struct extent_buffer *l;
2838 slot = path->slots[0];
2840 if (slot >= btrfs_header_nritems(l)) {
2841 ret = btrfs_next_leaf(root, path);
2849 btrfs_item_key_to_cpu(l, &key, slot);
2851 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2853 if (key.type != BTRFS_EXTENT_DATA_KEY)
2855 if (key.offset >= new->file_pos + new->len)
2858 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2860 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2861 if (key.offset + num_bytes < new->file_pos)
2864 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2868 extent_offset = btrfs_file_extent_offset(l, extent);
2870 old = kmalloc(sizeof(*old), GFP_NOFS);
2874 offset = max(new->file_pos, key.offset);
2875 end = min(new->file_pos + new->len, key.offset + num_bytes);
2877 old->bytenr = disk_bytenr;
2878 old->extent_offset = extent_offset;
2879 old->offset = offset - key.offset;
2880 old->len = end - offset;
2883 list_add_tail(&old->list, &new->head);
2889 btrfs_free_path(path);
2890 atomic_inc(&fs_info->defrag_running);
2895 btrfs_free_path(path);
2897 free_sa_defrag_extent(new);
2901 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2904 struct btrfs_block_group_cache *cache;
2906 cache = btrfs_lookup_block_group(fs_info, start);
2909 spin_lock(&cache->lock);
2910 cache->delalloc_bytes -= len;
2911 spin_unlock(&cache->lock);
2913 btrfs_put_block_group(cache);
2916 /* as ordered data IO finishes, this gets called so we can finish
2917 * an ordered extent if the range of bytes in the file it covers are
2920 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2922 struct inode *inode = ordered_extent->inode;
2923 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2924 struct btrfs_root *root = BTRFS_I(inode)->root;
2925 struct btrfs_trans_handle *trans = NULL;
2926 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2927 struct extent_state *cached_state = NULL;
2928 struct new_sa_defrag_extent *new = NULL;
2929 int compress_type = 0;
2931 u64 logical_len = ordered_extent->len;
2933 bool truncated = false;
2934 bool range_locked = false;
2935 bool clear_new_delalloc_bytes = false;
2936 bool clear_reserved_extent = true;
2938 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2939 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2940 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2941 clear_new_delalloc_bytes = true;
2943 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2945 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2950 btrfs_free_io_failure_record(BTRFS_I(inode),
2951 ordered_extent->file_offset,
2952 ordered_extent->file_offset +
2953 ordered_extent->len - 1);
2955 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2957 logical_len = ordered_extent->truncated_len;
2958 /* Truncated the entire extent, don't bother adding */
2963 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2964 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2967 * For mwrite(mmap + memset to write) case, we still reserve
2968 * space for NOCOW range.
2969 * As NOCOW won't cause a new delayed ref, just free the space
2971 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2972 ordered_extent->len);
2973 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2975 trans = btrfs_join_transaction_nolock(root);
2977 trans = btrfs_join_transaction(root);
2978 if (IS_ERR(trans)) {
2979 ret = PTR_ERR(trans);
2983 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2984 ret = btrfs_update_inode_fallback(trans, root, inode);
2985 if (ret) /* -ENOMEM or corruption */
2986 btrfs_abort_transaction(trans, ret);
2990 range_locked = true;
2991 lock_extent_bits(io_tree, ordered_extent->file_offset,
2992 ordered_extent->file_offset + ordered_extent->len - 1,
2995 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2996 ordered_extent->file_offset + ordered_extent->len - 1,
2997 EXTENT_DEFRAG, 0, cached_state);
2999 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3000 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3001 /* the inode is shared */
3002 new = record_old_file_extents(inode, ordered_extent);
3004 clear_extent_bit(io_tree, ordered_extent->file_offset,
3005 ordered_extent->file_offset + ordered_extent->len - 1,
3006 EXTENT_DEFRAG, 0, 0, &cached_state);
3010 trans = btrfs_join_transaction_nolock(root);
3012 trans = btrfs_join_transaction(root);
3013 if (IS_ERR(trans)) {
3014 ret = PTR_ERR(trans);
3019 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3021 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3022 compress_type = ordered_extent->compress_type;
3023 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3024 BUG_ON(compress_type);
3025 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3026 ordered_extent->len);
3027 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3028 ordered_extent->file_offset,
3029 ordered_extent->file_offset +
3032 BUG_ON(root == fs_info->tree_root);
3033 ret = insert_reserved_file_extent(trans, inode,
3034 ordered_extent->file_offset,
3035 ordered_extent->start,
3036 ordered_extent->disk_len,
3037 logical_len, logical_len,
3038 compress_type, 0, 0,
3039 BTRFS_FILE_EXTENT_REG);
3041 clear_reserved_extent = false;
3042 btrfs_release_delalloc_bytes(fs_info,
3043 ordered_extent->start,
3044 ordered_extent->disk_len);
3047 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3048 ordered_extent->file_offset, ordered_extent->len,
3051 btrfs_abort_transaction(trans, ret);
3055 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3057 btrfs_abort_transaction(trans, ret);
3061 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3062 ret = btrfs_update_inode_fallback(trans, root, inode);
3063 if (ret) { /* -ENOMEM or corruption */
3064 btrfs_abort_transaction(trans, ret);
3069 if (range_locked || clear_new_delalloc_bytes) {
3070 unsigned int clear_bits = 0;
3073 clear_bits |= EXTENT_LOCKED;
3074 if (clear_new_delalloc_bytes)
3075 clear_bits |= EXTENT_DELALLOC_NEW;
3076 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3077 ordered_extent->file_offset,
3078 ordered_extent->file_offset +
3079 ordered_extent->len - 1,
3081 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3086 btrfs_end_transaction(trans);
3088 if (ret || truncated) {
3092 start = ordered_extent->file_offset + logical_len;
3094 start = ordered_extent->file_offset;
3095 end = ordered_extent->file_offset + ordered_extent->len - 1;
3096 clear_extent_uptodate(io_tree, start, end, NULL);
3098 /* Drop the cache for the part of the extent we didn't write. */
3099 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3102 * If the ordered extent had an IOERR or something else went
3103 * wrong we need to return the space for this ordered extent
3104 * back to the allocator. We only free the extent in the
3105 * truncated case if we didn't write out the extent at all.
3107 * If we made it past insert_reserved_file_extent before we
3108 * errored out then we don't need to do this as the accounting
3109 * has already been done.
3111 if ((ret || !logical_len) &&
3112 clear_reserved_extent &&
3113 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3114 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3115 btrfs_free_reserved_extent(fs_info,
3116 ordered_extent->start,
3117 ordered_extent->disk_len, 1);
3122 * This needs to be done to make sure anybody waiting knows we are done
3123 * updating everything for this ordered extent.
3125 btrfs_remove_ordered_extent(inode, ordered_extent);
3127 /* for snapshot-aware defrag */
3130 free_sa_defrag_extent(new);
3131 atomic_dec(&fs_info->defrag_running);
3133 relink_file_extents(new);
3138 btrfs_put_ordered_extent(ordered_extent);
3139 /* once for the tree */
3140 btrfs_put_ordered_extent(ordered_extent);
3142 /* Try to release some metadata so we don't get an OOM but don't wait */
3143 btrfs_btree_balance_dirty_nodelay(fs_info);
3148 static void finish_ordered_fn(struct btrfs_work *work)
3150 struct btrfs_ordered_extent *ordered_extent;
3151 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3152 btrfs_finish_ordered_io(ordered_extent);
3155 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start, u64 end,
3156 struct extent_state *state, int uptodate)
3158 struct inode *inode = page->mapping->host;
3159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3160 struct btrfs_ordered_extent *ordered_extent = NULL;
3161 struct btrfs_workqueue *wq;
3162 btrfs_work_func_t func;
3164 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3166 ClearPagePrivate2(page);
3167 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3168 end - start + 1, uptodate))
3171 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3172 wq = fs_info->endio_freespace_worker;
3173 func = btrfs_freespace_write_helper;
3175 wq = fs_info->endio_write_workers;
3176 func = btrfs_endio_write_helper;
3179 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3181 btrfs_queue_work(wq, &ordered_extent->work);
3184 static int __readpage_endio_check(struct inode *inode,
3185 struct btrfs_io_bio *io_bio,
3186 int icsum, struct page *page,
3187 int pgoff, u64 start, size_t len)
3193 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3195 kaddr = kmap_atomic(page);
3196 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3197 btrfs_csum_final(csum, (u8 *)&csum);
3198 if (csum != csum_expected)
3201 kunmap_atomic(kaddr);
3204 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3205 io_bio->mirror_num);
3206 memset(kaddr + pgoff, 1, len);
3207 flush_dcache_page(page);
3208 kunmap_atomic(kaddr);
3213 * when reads are done, we need to check csums to verify the data is correct
3214 * if there's a match, we allow the bio to finish. If not, the code in
3215 * extent_io.c will try to find good copies for us.
3217 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3218 u64 phy_offset, struct page *page,
3219 u64 start, u64 end, int mirror)
3221 size_t offset = start - page_offset(page);
3222 struct inode *inode = page->mapping->host;
3223 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3224 struct btrfs_root *root = BTRFS_I(inode)->root;
3226 if (PageChecked(page)) {
3227 ClearPageChecked(page);
3231 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3234 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3235 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3236 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3240 phy_offset >>= inode->i_sb->s_blocksize_bits;
3241 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3242 start, (size_t)(end - start + 1));
3246 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3248 * @inode: The inode we want to perform iput on
3250 * This function uses the generic vfs_inode::i_count to track whether we should
3251 * just decrement it (in case it's > 1) or if this is the last iput then link
3252 * the inode to the delayed iput machinery. Delayed iputs are processed at
3253 * transaction commit time/superblock commit/cleaner kthread.
3255 void btrfs_add_delayed_iput(struct inode *inode)
3257 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3258 struct btrfs_inode *binode = BTRFS_I(inode);
3260 if (atomic_add_unless(&inode->i_count, -1, 1))
3263 spin_lock(&fs_info->delayed_iput_lock);
3264 ASSERT(list_empty(&binode->delayed_iput));
3265 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3266 spin_unlock(&fs_info->delayed_iput_lock);
3269 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3272 spin_lock(&fs_info->delayed_iput_lock);
3273 while (!list_empty(&fs_info->delayed_iputs)) {
3274 struct btrfs_inode *inode;
3276 inode = list_first_entry(&fs_info->delayed_iputs,
3277 struct btrfs_inode, delayed_iput);
3278 list_del_init(&inode->delayed_iput);
3279 spin_unlock(&fs_info->delayed_iput_lock);
3280 iput(&inode->vfs_inode);
3281 spin_lock(&fs_info->delayed_iput_lock);
3283 spin_unlock(&fs_info->delayed_iput_lock);
3287 * This creates an orphan entry for the given inode in case something goes wrong
3288 * in the middle of an unlink.
3290 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3291 struct btrfs_inode *inode)
3295 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3296 if (ret && ret != -EEXIST) {
3297 btrfs_abort_transaction(trans, ret);
3305 * We have done the delete so we can go ahead and remove the orphan item for
3306 * this particular inode.
3308 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3309 struct btrfs_inode *inode)
3311 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3315 * this cleans up any orphans that may be left on the list from the last use
3318 int btrfs_orphan_cleanup(struct btrfs_root *root)
3320 struct btrfs_fs_info *fs_info = root->fs_info;
3321 struct btrfs_path *path;
3322 struct extent_buffer *leaf;
3323 struct btrfs_key key, found_key;
3324 struct btrfs_trans_handle *trans;
3325 struct inode *inode;
3326 u64 last_objectid = 0;
3327 int ret = 0, nr_unlink = 0;
3329 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3332 path = btrfs_alloc_path();
3337 path->reada = READA_BACK;
3339 key.objectid = BTRFS_ORPHAN_OBJECTID;
3340 key.type = BTRFS_ORPHAN_ITEM_KEY;
3341 key.offset = (u64)-1;
3344 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3349 * if ret == 0 means we found what we were searching for, which
3350 * is weird, but possible, so only screw with path if we didn't
3351 * find the key and see if we have stuff that matches
3355 if (path->slots[0] == 0)
3360 /* pull out the item */
3361 leaf = path->nodes[0];
3362 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3364 /* make sure the item matches what we want */
3365 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3367 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3370 /* release the path since we're done with it */
3371 btrfs_release_path(path);
3374 * this is where we are basically btrfs_lookup, without the
3375 * crossing root thing. we store the inode number in the
3376 * offset of the orphan item.
3379 if (found_key.offset == last_objectid) {
3381 "Error removing orphan entry, stopping orphan cleanup");
3386 last_objectid = found_key.offset;
3388 found_key.objectid = found_key.offset;
3389 found_key.type = BTRFS_INODE_ITEM_KEY;
3390 found_key.offset = 0;
3391 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3392 ret = PTR_ERR_OR_ZERO(inode);
3393 if (ret && ret != -ENOENT)
3396 if (ret == -ENOENT && root == fs_info->tree_root) {
3397 struct btrfs_root *dead_root;
3398 struct btrfs_fs_info *fs_info = root->fs_info;
3399 int is_dead_root = 0;
3402 * this is an orphan in the tree root. Currently these
3403 * could come from 2 sources:
3404 * a) a snapshot deletion in progress
3405 * b) a free space cache inode
3406 * We need to distinguish those two, as the snapshot
3407 * orphan must not get deleted.
3408 * find_dead_roots already ran before us, so if this
3409 * is a snapshot deletion, we should find the root
3410 * in the dead_roots list
3412 spin_lock(&fs_info->trans_lock);
3413 list_for_each_entry(dead_root, &fs_info->dead_roots,
3415 if (dead_root->root_key.objectid ==
3416 found_key.objectid) {
3421 spin_unlock(&fs_info->trans_lock);
3423 /* prevent this orphan from being found again */
3424 key.offset = found_key.objectid - 1;
3431 * If we have an inode with links, there are a couple of
3432 * possibilities. Old kernels (before v3.12) used to create an
3433 * orphan item for truncate indicating that there were possibly
3434 * extent items past i_size that needed to be deleted. In v3.12,
3435 * truncate was changed to update i_size in sync with the extent
3436 * items, but the (useless) orphan item was still created. Since
3437 * v4.18, we don't create the orphan item for truncate at all.
3439 * So, this item could mean that we need to do a truncate, but
3440 * only if this filesystem was last used on a pre-v3.12 kernel
3441 * and was not cleanly unmounted. The odds of that are quite
3442 * slim, and it's a pain to do the truncate now, so just delete
3445 * It's also possible that this orphan item was supposed to be
3446 * deleted but wasn't. The inode number may have been reused,
3447 * but either way, we can delete the orphan item.
3449 if (ret == -ENOENT || inode->i_nlink) {
3452 trans = btrfs_start_transaction(root, 1);
3453 if (IS_ERR(trans)) {
3454 ret = PTR_ERR(trans);
3457 btrfs_debug(fs_info, "auto deleting %Lu",
3458 found_key.objectid);
3459 ret = btrfs_del_orphan_item(trans, root,
3460 found_key.objectid);
3461 btrfs_end_transaction(trans);
3469 /* this will do delete_inode and everything for us */
3472 /* release the path since we're done with it */
3473 btrfs_release_path(path);
3475 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3477 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3478 trans = btrfs_join_transaction(root);
3480 btrfs_end_transaction(trans);
3484 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3488 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3489 btrfs_free_path(path);
3494 * very simple check to peek ahead in the leaf looking for xattrs. If we
3495 * don't find any xattrs, we know there can't be any acls.
3497 * slot is the slot the inode is in, objectid is the objectid of the inode
3499 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3500 int slot, u64 objectid,
3501 int *first_xattr_slot)
3503 u32 nritems = btrfs_header_nritems(leaf);
3504 struct btrfs_key found_key;
3505 static u64 xattr_access = 0;
3506 static u64 xattr_default = 0;
3509 if (!xattr_access) {
3510 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3511 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3512 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3513 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3517 *first_xattr_slot = -1;
3518 while (slot < nritems) {
3519 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3521 /* we found a different objectid, there must not be acls */
3522 if (found_key.objectid != objectid)
3525 /* we found an xattr, assume we've got an acl */
3526 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3527 if (*first_xattr_slot == -1)
3528 *first_xattr_slot = slot;
3529 if (found_key.offset == xattr_access ||
3530 found_key.offset == xattr_default)
3535 * we found a key greater than an xattr key, there can't
3536 * be any acls later on
3538 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3545 * it goes inode, inode backrefs, xattrs, extents,
3546 * so if there are a ton of hard links to an inode there can
3547 * be a lot of backrefs. Don't waste time searching too hard,
3548 * this is just an optimization
3553 /* we hit the end of the leaf before we found an xattr or
3554 * something larger than an xattr. We have to assume the inode
3557 if (*first_xattr_slot == -1)
3558 *first_xattr_slot = slot;
3563 * read an inode from the btree into the in-memory inode
3565 static int btrfs_read_locked_inode(struct inode *inode,
3566 struct btrfs_path *in_path)
3568 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3569 struct btrfs_path *path = in_path;
3570 struct extent_buffer *leaf;
3571 struct btrfs_inode_item *inode_item;
3572 struct btrfs_root *root = BTRFS_I(inode)->root;
3573 struct btrfs_key location;
3578 bool filled = false;
3579 int first_xattr_slot;
3581 ret = btrfs_fill_inode(inode, &rdev);
3586 path = btrfs_alloc_path();
3591 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3593 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3595 if (path != in_path)
3596 btrfs_free_path(path);
3600 leaf = path->nodes[0];
3605 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3606 struct btrfs_inode_item);
3607 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3608 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3609 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3610 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3611 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3613 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3614 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3616 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3617 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3619 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3620 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3622 BTRFS_I(inode)->i_otime.tv_sec =
3623 btrfs_timespec_sec(leaf, &inode_item->otime);
3624 BTRFS_I(inode)->i_otime.tv_nsec =
3625 btrfs_timespec_nsec(leaf, &inode_item->otime);
3627 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3628 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3629 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3631 inode_set_iversion_queried(inode,
3632 btrfs_inode_sequence(leaf, inode_item));
3633 inode->i_generation = BTRFS_I(inode)->generation;
3635 rdev = btrfs_inode_rdev(leaf, inode_item);
3637 BTRFS_I(inode)->index_cnt = (u64)-1;
3638 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3642 * If we were modified in the current generation and evicted from memory
3643 * and then re-read we need to do a full sync since we don't have any
3644 * idea about which extents were modified before we were evicted from
3647 * This is required for both inode re-read from disk and delayed inode
3648 * in delayed_nodes_tree.
3650 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3651 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3652 &BTRFS_I(inode)->runtime_flags);
3655 * We don't persist the id of the transaction where an unlink operation
3656 * against the inode was last made. So here we assume the inode might
3657 * have been evicted, and therefore the exact value of last_unlink_trans
3658 * lost, and set it to last_trans to avoid metadata inconsistencies
3659 * between the inode and its parent if the inode is fsync'ed and the log
3660 * replayed. For example, in the scenario:
3663 * ln mydir/foo mydir/bar
3666 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3667 * xfs_io -c fsync mydir/foo
3669 * mount fs, triggers fsync log replay
3671 * We must make sure that when we fsync our inode foo we also log its
3672 * parent inode, otherwise after log replay the parent still has the
3673 * dentry with the "bar" name but our inode foo has a link count of 1
3674 * and doesn't have an inode ref with the name "bar" anymore.
3676 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3677 * but it guarantees correctness at the expense of occasional full
3678 * transaction commits on fsync if our inode is a directory, or if our
3679 * inode is not a directory, logging its parent unnecessarily.
3681 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3684 if (inode->i_nlink != 1 ||
3685 path->slots[0] >= btrfs_header_nritems(leaf))
3688 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3689 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3692 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3693 if (location.type == BTRFS_INODE_REF_KEY) {
3694 struct btrfs_inode_ref *ref;
3696 ref = (struct btrfs_inode_ref *)ptr;
3697 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3698 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3699 struct btrfs_inode_extref *extref;
3701 extref = (struct btrfs_inode_extref *)ptr;
3702 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3707 * try to precache a NULL acl entry for files that don't have
3708 * any xattrs or acls
3710 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3711 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3712 if (first_xattr_slot != -1) {
3713 path->slots[0] = first_xattr_slot;
3714 ret = btrfs_load_inode_props(inode, path);
3717 "error loading props for ino %llu (root %llu): %d",
3718 btrfs_ino(BTRFS_I(inode)),
3719 root->root_key.objectid, ret);
3721 if (path != in_path)
3722 btrfs_free_path(path);
3725 cache_no_acl(inode);
3727 switch (inode->i_mode & S_IFMT) {
3729 inode->i_mapping->a_ops = &btrfs_aops;
3730 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3731 inode->i_fop = &btrfs_file_operations;
3732 inode->i_op = &btrfs_file_inode_operations;
3735 inode->i_fop = &btrfs_dir_file_operations;
3736 inode->i_op = &btrfs_dir_inode_operations;
3739 inode->i_op = &btrfs_symlink_inode_operations;
3740 inode_nohighmem(inode);
3741 inode->i_mapping->a_ops = &btrfs_aops;
3744 inode->i_op = &btrfs_special_inode_operations;
3745 init_special_inode(inode, inode->i_mode, rdev);
3749 btrfs_sync_inode_flags_to_i_flags(inode);
3754 * given a leaf and an inode, copy the inode fields into the leaf
3756 static void fill_inode_item(struct btrfs_trans_handle *trans,
3757 struct extent_buffer *leaf,
3758 struct btrfs_inode_item *item,
3759 struct inode *inode)
3761 struct btrfs_map_token token;
3763 btrfs_init_map_token(&token);
3765 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3766 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3767 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3769 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3770 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3772 btrfs_set_token_timespec_sec(leaf, &item->atime,
3773 inode->i_atime.tv_sec, &token);
3774 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3775 inode->i_atime.tv_nsec, &token);
3777 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3778 inode->i_mtime.tv_sec, &token);
3779 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3780 inode->i_mtime.tv_nsec, &token);
3782 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3783 inode->i_ctime.tv_sec, &token);
3784 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3785 inode->i_ctime.tv_nsec, &token);
3787 btrfs_set_token_timespec_sec(leaf, &item->otime,
3788 BTRFS_I(inode)->i_otime.tv_sec, &token);
3789 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3790 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3792 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3794 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3796 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3798 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3799 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3800 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3801 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3805 * copy everything in the in-memory inode into the btree.
3807 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3808 struct btrfs_root *root, struct inode *inode)
3810 struct btrfs_inode_item *inode_item;
3811 struct btrfs_path *path;
3812 struct extent_buffer *leaf;
3815 path = btrfs_alloc_path();
3819 path->leave_spinning = 1;
3820 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3828 leaf = path->nodes[0];
3829 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3830 struct btrfs_inode_item);
3832 fill_inode_item(trans, leaf, inode_item, inode);
3833 btrfs_mark_buffer_dirty(leaf);
3834 btrfs_set_inode_last_trans(trans, inode);
3837 btrfs_free_path(path);
3842 * copy everything in the in-memory inode into the btree.
3844 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3845 struct btrfs_root *root, struct inode *inode)
3847 struct btrfs_fs_info *fs_info = root->fs_info;
3851 * If the inode is a free space inode, we can deadlock during commit
3852 * if we put it into the delayed code.
3854 * The data relocation inode should also be directly updated
3857 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3858 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3859 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3860 btrfs_update_root_times(trans, root);
3862 ret = btrfs_delayed_update_inode(trans, root, inode);
3864 btrfs_set_inode_last_trans(trans, inode);
3868 return btrfs_update_inode_item(trans, root, inode);
3871 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3872 struct btrfs_root *root,
3873 struct inode *inode)
3877 ret = btrfs_update_inode(trans, root, inode);
3879 return btrfs_update_inode_item(trans, root, inode);
3884 * unlink helper that gets used here in inode.c and in the tree logging
3885 * recovery code. It remove a link in a directory with a given name, and
3886 * also drops the back refs in the inode to the directory
3888 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3889 struct btrfs_root *root,
3890 struct btrfs_inode *dir,
3891 struct btrfs_inode *inode,
3892 const char *name, int name_len)
3894 struct btrfs_fs_info *fs_info = root->fs_info;
3895 struct btrfs_path *path;
3897 struct extent_buffer *leaf;
3898 struct btrfs_dir_item *di;
3899 struct btrfs_key key;
3901 u64 ino = btrfs_ino(inode);
3902 u64 dir_ino = btrfs_ino(dir);
3904 path = btrfs_alloc_path();
3910 path->leave_spinning = 1;
3911 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3912 name, name_len, -1);
3913 if (IS_ERR_OR_NULL(di)) {
3914 ret = di ? PTR_ERR(di) : -ENOENT;
3917 leaf = path->nodes[0];
3918 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3919 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3922 btrfs_release_path(path);
3925 * If we don't have dir index, we have to get it by looking up
3926 * the inode ref, since we get the inode ref, remove it directly,
3927 * it is unnecessary to do delayed deletion.
3929 * But if we have dir index, needn't search inode ref to get it.
3930 * Since the inode ref is close to the inode item, it is better
3931 * that we delay to delete it, and just do this deletion when
3932 * we update the inode item.
3934 if (inode->dir_index) {
3935 ret = btrfs_delayed_delete_inode_ref(inode);
3937 index = inode->dir_index;
3942 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3946 "failed to delete reference to %.*s, inode %llu parent %llu",
3947 name_len, name, ino, dir_ino);
3948 btrfs_abort_transaction(trans, ret);
3952 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3954 btrfs_abort_transaction(trans, ret);
3958 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3960 if (ret != 0 && ret != -ENOENT) {
3961 btrfs_abort_transaction(trans, ret);
3965 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3970 btrfs_abort_transaction(trans, ret);
3972 btrfs_free_path(path);
3976 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3977 inode_inc_iversion(&inode->vfs_inode);
3978 inode_inc_iversion(&dir->vfs_inode);
3979 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3980 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3981 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3986 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3987 struct btrfs_root *root,
3988 struct btrfs_inode *dir, struct btrfs_inode *inode,
3989 const char *name, int name_len)
3992 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3994 drop_nlink(&inode->vfs_inode);
3995 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4001 * helper to start transaction for unlink and rmdir.
4003 * unlink and rmdir are special in btrfs, they do not always free space, so
4004 * if we cannot make our reservations the normal way try and see if there is
4005 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4006 * allow the unlink to occur.
4008 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4010 struct btrfs_root *root = BTRFS_I(dir)->root;
4013 * 1 for the possible orphan item
4014 * 1 for the dir item
4015 * 1 for the dir index
4016 * 1 for the inode ref
4019 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4022 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4024 struct btrfs_root *root = BTRFS_I(dir)->root;
4025 struct btrfs_trans_handle *trans;
4026 struct inode *inode = d_inode(dentry);
4029 trans = __unlink_start_trans(dir);
4031 return PTR_ERR(trans);
4033 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4036 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4037 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4038 dentry->d_name.len);
4042 if (inode->i_nlink == 0) {
4043 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4049 btrfs_end_transaction(trans);
4050 btrfs_btree_balance_dirty(root->fs_info);
4054 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4055 struct inode *dir, u64 objectid,
4056 const char *name, int name_len)
4058 struct btrfs_root *root = BTRFS_I(dir)->root;
4059 struct btrfs_path *path;
4060 struct extent_buffer *leaf;
4061 struct btrfs_dir_item *di;
4062 struct btrfs_key key;
4065 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4067 path = btrfs_alloc_path();
4071 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4072 name, name_len, -1);
4073 if (IS_ERR_OR_NULL(di)) {
4074 ret = di ? PTR_ERR(di) : -ENOENT;
4078 leaf = path->nodes[0];
4079 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4080 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4081 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4083 btrfs_abort_transaction(trans, ret);
4086 btrfs_release_path(path);
4088 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4089 dir_ino, &index, name, name_len);
4091 if (ret != -ENOENT) {
4092 btrfs_abort_transaction(trans, ret);
4095 di = btrfs_search_dir_index_item(root, path, dir_ino,
4097 if (IS_ERR_OR_NULL(di)) {
4102 btrfs_abort_transaction(trans, ret);
4106 leaf = path->nodes[0];
4107 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4110 btrfs_release_path(path);
4112 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4114 btrfs_abort_transaction(trans, ret);
4118 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4119 inode_inc_iversion(dir);
4120 dir->i_mtime = dir->i_ctime = current_time(dir);
4121 ret = btrfs_update_inode_fallback(trans, root, dir);
4123 btrfs_abort_transaction(trans, ret);
4125 btrfs_free_path(path);
4130 * Helper to check if the subvolume references other subvolumes or if it's
4133 static noinline int may_destroy_subvol(struct btrfs_root *root)
4135 struct btrfs_fs_info *fs_info = root->fs_info;
4136 struct btrfs_path *path;
4137 struct btrfs_dir_item *di;
4138 struct btrfs_key key;
4142 path = btrfs_alloc_path();
4146 /* Make sure this root isn't set as the default subvol */
4147 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4148 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4149 dir_id, "default", 7, 0);
4150 if (di && !IS_ERR(di)) {
4151 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4152 if (key.objectid == root->root_key.objectid) {
4155 "deleting default subvolume %llu is not allowed",
4159 btrfs_release_path(path);
4162 key.objectid = root->root_key.objectid;
4163 key.type = BTRFS_ROOT_REF_KEY;
4164 key.offset = (u64)-1;
4166 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4172 if (path->slots[0] > 0) {
4174 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4175 if (key.objectid == root->root_key.objectid &&
4176 key.type == BTRFS_ROOT_REF_KEY)
4180 btrfs_free_path(path);
4184 /* Delete all dentries for inodes belonging to the root */
4185 static void btrfs_prune_dentries(struct btrfs_root *root)
4187 struct btrfs_fs_info *fs_info = root->fs_info;
4188 struct rb_node *node;
4189 struct rb_node *prev;
4190 struct btrfs_inode *entry;
4191 struct inode *inode;
4194 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4195 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4197 spin_lock(&root->inode_lock);
4199 node = root->inode_tree.rb_node;
4203 entry = rb_entry(node, struct btrfs_inode, rb_node);
4205 if (objectid < btrfs_ino(entry))
4206 node = node->rb_left;
4207 else if (objectid > btrfs_ino(entry))
4208 node = node->rb_right;
4214 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4215 if (objectid <= btrfs_ino(entry)) {
4219 prev = rb_next(prev);
4223 entry = rb_entry(node, struct btrfs_inode, rb_node);
4224 objectid = btrfs_ino(entry) + 1;
4225 inode = igrab(&entry->vfs_inode);
4227 spin_unlock(&root->inode_lock);
4228 if (atomic_read(&inode->i_count) > 1)
4229 d_prune_aliases(inode);
4231 * btrfs_drop_inode will have it removed from the inode
4232 * cache when its usage count hits zero.
4236 spin_lock(&root->inode_lock);
4240 if (cond_resched_lock(&root->inode_lock))
4243 node = rb_next(node);
4245 spin_unlock(&root->inode_lock);
4248 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4250 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4251 struct btrfs_root *root = BTRFS_I(dir)->root;
4252 struct inode *inode = d_inode(dentry);
4253 struct btrfs_root *dest = BTRFS_I(inode)->root;
4254 struct btrfs_trans_handle *trans;
4255 struct btrfs_block_rsv block_rsv;
4261 * Don't allow to delete a subvolume with send in progress. This is
4262 * inside the inode lock so the error handling that has to drop the bit
4263 * again is not run concurrently.
4265 spin_lock(&dest->root_item_lock);
4266 if (dest->send_in_progress) {
4267 spin_unlock(&dest->root_item_lock);
4269 "attempt to delete subvolume %llu during send",
4270 dest->root_key.objectid);
4273 root_flags = btrfs_root_flags(&dest->root_item);
4274 btrfs_set_root_flags(&dest->root_item,
4275 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4276 spin_unlock(&dest->root_item_lock);
4278 down_write(&fs_info->subvol_sem);
4280 err = may_destroy_subvol(dest);
4284 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4286 * One for dir inode,
4287 * two for dir entries,
4288 * two for root ref/backref.
4290 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4294 trans = btrfs_start_transaction(root, 0);
4295 if (IS_ERR(trans)) {
4296 err = PTR_ERR(trans);
4299 trans->block_rsv = &block_rsv;
4300 trans->bytes_reserved = block_rsv.size;
4302 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4304 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4305 dentry->d_name.name, dentry->d_name.len);
4308 btrfs_abort_transaction(trans, ret);
4312 btrfs_record_root_in_trans(trans, dest);
4314 memset(&dest->root_item.drop_progress, 0,
4315 sizeof(dest->root_item.drop_progress));
4316 dest->root_item.drop_level = 0;
4317 btrfs_set_root_refs(&dest->root_item, 0);
4319 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4320 ret = btrfs_insert_orphan_item(trans,
4322 dest->root_key.objectid);
4324 btrfs_abort_transaction(trans, ret);
4330 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4331 BTRFS_UUID_KEY_SUBVOL,
4332 dest->root_key.objectid);
4333 if (ret && ret != -ENOENT) {
4334 btrfs_abort_transaction(trans, ret);
4338 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4339 ret = btrfs_uuid_tree_remove(trans,
4340 dest->root_item.received_uuid,
4341 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4342 dest->root_key.objectid);
4343 if (ret && ret != -ENOENT) {
4344 btrfs_abort_transaction(trans, ret);
4351 trans->block_rsv = NULL;
4352 trans->bytes_reserved = 0;
4353 ret = btrfs_end_transaction(trans);
4356 inode->i_flags |= S_DEAD;
4358 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4360 up_write(&fs_info->subvol_sem);
4362 spin_lock(&dest->root_item_lock);
4363 root_flags = btrfs_root_flags(&dest->root_item);
4364 btrfs_set_root_flags(&dest->root_item,
4365 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4366 spin_unlock(&dest->root_item_lock);
4368 d_invalidate(dentry);
4369 btrfs_prune_dentries(dest);
4370 ASSERT(dest->send_in_progress == 0);
4373 if (dest->ino_cache_inode) {
4374 iput(dest->ino_cache_inode);
4375 dest->ino_cache_inode = NULL;
4382 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4384 struct inode *inode = d_inode(dentry);
4386 struct btrfs_root *root = BTRFS_I(dir)->root;
4387 struct btrfs_trans_handle *trans;
4388 u64 last_unlink_trans;
4390 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4392 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4393 return btrfs_delete_subvolume(dir, dentry);
4395 trans = __unlink_start_trans(dir);
4397 return PTR_ERR(trans);
4399 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4400 err = btrfs_unlink_subvol(trans, dir,
4401 BTRFS_I(inode)->location.objectid,
4402 dentry->d_name.name,
4403 dentry->d_name.len);
4407 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4411 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4413 /* now the directory is empty */
4414 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4415 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4416 dentry->d_name.len);
4418 btrfs_i_size_write(BTRFS_I(inode), 0);
4420 * Propagate the last_unlink_trans value of the deleted dir to
4421 * its parent directory. This is to prevent an unrecoverable
4422 * log tree in the case we do something like this:
4424 * 2) create snapshot under dir foo
4425 * 3) delete the snapshot
4428 * 6) fsync foo or some file inside foo
4430 if (last_unlink_trans >= trans->transid)
4431 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4434 btrfs_end_transaction(trans);
4435 btrfs_btree_balance_dirty(root->fs_info);
4440 static int truncate_space_check(struct btrfs_trans_handle *trans,
4441 struct btrfs_root *root,
4444 struct btrfs_fs_info *fs_info = root->fs_info;
4448 * This is only used to apply pressure to the enospc system, we don't
4449 * intend to use this reservation at all.
4451 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4452 bytes_deleted *= fs_info->nodesize;
4453 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4454 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4456 trace_btrfs_space_reservation(fs_info, "transaction",
4459 trans->bytes_reserved += bytes_deleted;
4466 * Return this if we need to call truncate_block for the last bit of the
4469 #define NEED_TRUNCATE_BLOCK 1
4472 * this can truncate away extent items, csum items and directory items.
4473 * It starts at a high offset and removes keys until it can't find
4474 * any higher than new_size
4476 * csum items that cross the new i_size are truncated to the new size
4479 * min_type is the minimum key type to truncate down to. If set to 0, this
4480 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4482 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4483 struct btrfs_root *root,
4484 struct inode *inode,
4485 u64 new_size, u32 min_type)
4487 struct btrfs_fs_info *fs_info = root->fs_info;
4488 struct btrfs_path *path;
4489 struct extent_buffer *leaf;
4490 struct btrfs_file_extent_item *fi;
4491 struct btrfs_key key;
4492 struct btrfs_key found_key;
4493 u64 extent_start = 0;
4494 u64 extent_num_bytes = 0;
4495 u64 extent_offset = 0;
4497 u64 last_size = new_size;
4498 u32 found_type = (u8)-1;
4501 int pending_del_nr = 0;
4502 int pending_del_slot = 0;
4503 int extent_type = -1;
4505 u64 ino = btrfs_ino(BTRFS_I(inode));
4506 u64 bytes_deleted = 0;
4507 bool be_nice = false;
4508 bool should_throttle = false;
4509 bool should_end = false;
4511 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4514 * for non-free space inodes and ref cows, we want to back off from
4517 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4518 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4521 path = btrfs_alloc_path();
4524 path->reada = READA_BACK;
4527 * We want to drop from the next block forward in case this new size is
4528 * not block aligned since we will be keeping the last block of the
4529 * extent just the way it is.
4531 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4532 root == fs_info->tree_root)
4533 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4534 fs_info->sectorsize),
4538 * This function is also used to drop the items in the log tree before
4539 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4540 * it is used to drop the loged items. So we shouldn't kill the delayed
4543 if (min_type == 0 && root == BTRFS_I(inode)->root)
4544 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4547 key.offset = (u64)-1;
4552 * with a 16K leaf size and 128MB extents, you can actually queue
4553 * up a huge file in a single leaf. Most of the time that
4554 * bytes_deleted is > 0, it will be huge by the time we get here
4556 if (be_nice && bytes_deleted > SZ_32M &&
4557 btrfs_should_end_transaction(trans)) {
4562 path->leave_spinning = 1;
4563 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4569 /* there are no items in the tree for us to truncate, we're
4572 if (path->slots[0] == 0)
4579 leaf = path->nodes[0];
4580 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4581 found_type = found_key.type;
4583 if (found_key.objectid != ino)
4586 if (found_type < min_type)
4589 item_end = found_key.offset;
4590 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4591 fi = btrfs_item_ptr(leaf, path->slots[0],
4592 struct btrfs_file_extent_item);
4593 extent_type = btrfs_file_extent_type(leaf, fi);
4594 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4596 btrfs_file_extent_num_bytes(leaf, fi);
4598 trace_btrfs_truncate_show_fi_regular(
4599 BTRFS_I(inode), leaf, fi,
4601 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4602 item_end += btrfs_file_extent_ram_bytes(leaf,
4605 trace_btrfs_truncate_show_fi_inline(
4606 BTRFS_I(inode), leaf, fi, path->slots[0],
4611 if (found_type > min_type) {
4614 if (item_end < new_size)
4616 if (found_key.offset >= new_size)
4622 /* FIXME, shrink the extent if the ref count is only 1 */
4623 if (found_type != BTRFS_EXTENT_DATA_KEY)
4626 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4628 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4630 u64 orig_num_bytes =
4631 btrfs_file_extent_num_bytes(leaf, fi);
4632 extent_num_bytes = ALIGN(new_size -
4634 fs_info->sectorsize);
4635 btrfs_set_file_extent_num_bytes(leaf, fi,
4637 num_dec = (orig_num_bytes -
4639 if (test_bit(BTRFS_ROOT_REF_COWS,
4642 inode_sub_bytes(inode, num_dec);
4643 btrfs_mark_buffer_dirty(leaf);
4646 btrfs_file_extent_disk_num_bytes(leaf,
4648 extent_offset = found_key.offset -
4649 btrfs_file_extent_offset(leaf, fi);
4651 /* FIXME blocksize != 4096 */
4652 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4653 if (extent_start != 0) {
4655 if (test_bit(BTRFS_ROOT_REF_COWS,
4657 inode_sub_bytes(inode, num_dec);
4660 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4662 * we can't truncate inline items that have had
4666 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4667 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4668 btrfs_file_extent_compression(leaf, fi) == 0) {
4669 u32 size = (u32)(new_size - found_key.offset);
4671 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4672 size = btrfs_file_extent_calc_inline_size(size);
4673 btrfs_truncate_item(root->fs_info, path, size, 1);
4674 } else if (!del_item) {
4676 * We have to bail so the last_size is set to
4677 * just before this extent.
4679 ret = NEED_TRUNCATE_BLOCK;
4683 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4684 inode_sub_bytes(inode, item_end + 1 - new_size);
4688 last_size = found_key.offset;
4690 last_size = new_size;
4692 if (!pending_del_nr) {
4693 /* no pending yet, add ourselves */
4694 pending_del_slot = path->slots[0];
4696 } else if (pending_del_nr &&
4697 path->slots[0] + 1 == pending_del_slot) {
4698 /* hop on the pending chunk */
4700 pending_del_slot = path->slots[0];
4707 should_throttle = false;
4710 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4711 root == fs_info->tree_root)) {
4712 btrfs_set_path_blocking(path);
4713 bytes_deleted += extent_num_bytes;
4714 ret = btrfs_free_extent(trans, root, extent_start,
4715 extent_num_bytes, 0,
4716 btrfs_header_owner(leaf),
4717 ino, extent_offset);
4719 btrfs_abort_transaction(trans, ret);
4722 if (btrfs_should_throttle_delayed_refs(trans))
4723 btrfs_async_run_delayed_refs(fs_info,
4724 trans->delayed_ref_updates * 2,
4727 if (truncate_space_check(trans, root,
4728 extent_num_bytes)) {
4731 if (btrfs_should_throttle_delayed_refs(trans))
4732 should_throttle = true;
4736 if (found_type == BTRFS_INODE_ITEM_KEY)
4739 if (path->slots[0] == 0 ||
4740 path->slots[0] != pending_del_slot ||
4741 should_throttle || should_end) {
4742 if (pending_del_nr) {
4743 ret = btrfs_del_items(trans, root, path,
4747 btrfs_abort_transaction(trans, ret);
4752 btrfs_release_path(path);
4753 if (should_throttle) {
4754 unsigned long updates = trans->delayed_ref_updates;
4756 trans->delayed_ref_updates = 0;
4757 ret = btrfs_run_delayed_refs(trans,
4764 * if we failed to refill our space rsv, bail out
4765 * and let the transaction restart
4777 if (ret >= 0 && pending_del_nr) {
4780 err = btrfs_del_items(trans, root, path, pending_del_slot,
4783 btrfs_abort_transaction(trans, err);
4787 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4788 ASSERT(last_size >= new_size);
4789 if (!ret && last_size > new_size)
4790 last_size = new_size;
4791 btrfs_ordered_update_i_size(inode, last_size, NULL);
4794 btrfs_free_path(path);
4796 if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4797 unsigned long updates = trans->delayed_ref_updates;
4801 trans->delayed_ref_updates = 0;
4802 err = btrfs_run_delayed_refs(trans, updates * 2);
4811 * btrfs_truncate_block - read, zero a chunk and write a block
4812 * @inode - inode that we're zeroing
4813 * @from - the offset to start zeroing
4814 * @len - the length to zero, 0 to zero the entire range respective to the
4816 * @front - zero up to the offset instead of from the offset on
4818 * This will find the block for the "from" offset and cow the block and zero the
4819 * part we want to zero. This is used with truncate and hole punching.
4821 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4824 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4825 struct address_space *mapping = inode->i_mapping;
4826 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4827 struct btrfs_ordered_extent *ordered;
4828 struct extent_state *cached_state = NULL;
4829 struct extent_changeset *data_reserved = NULL;
4831 u32 blocksize = fs_info->sectorsize;
4832 pgoff_t index = from >> PAGE_SHIFT;
4833 unsigned offset = from & (blocksize - 1);
4835 gfp_t mask = btrfs_alloc_write_mask(mapping);
4840 if (IS_ALIGNED(offset, blocksize) &&
4841 (!len || IS_ALIGNED(len, blocksize)))
4844 block_start = round_down(from, blocksize);
4845 block_end = block_start + blocksize - 1;
4847 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4848 block_start, blocksize);
4853 page = find_or_create_page(mapping, index, mask);
4855 btrfs_delalloc_release_space(inode, data_reserved,
4856 block_start, blocksize, true);
4857 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4862 if (!PageUptodate(page)) {
4863 ret = btrfs_readpage(NULL, page);
4865 if (page->mapping != mapping) {
4870 if (!PageUptodate(page)) {
4875 wait_on_page_writeback(page);
4877 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4878 set_page_extent_mapped(page);
4880 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4882 unlock_extent_cached(io_tree, block_start, block_end,
4886 btrfs_start_ordered_extent(inode, ordered, 1);
4887 btrfs_put_ordered_extent(ordered);
4891 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4892 EXTENT_DIRTY | EXTENT_DELALLOC |
4893 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4894 0, 0, &cached_state);
4896 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4899 unlock_extent_cached(io_tree, block_start, block_end,
4904 if (offset != blocksize) {
4906 len = blocksize - offset;
4909 memset(kaddr + (block_start - page_offset(page)),
4912 memset(kaddr + (block_start - page_offset(page)) + offset,
4914 flush_dcache_page(page);
4917 ClearPageChecked(page);
4918 set_page_dirty(page);
4919 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4923 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4925 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4929 extent_changeset_free(data_reserved);
4933 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4934 u64 offset, u64 len)
4936 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4937 struct btrfs_trans_handle *trans;
4941 * Still need to make sure the inode looks like it's been updated so
4942 * that any holes get logged if we fsync.
4944 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4945 BTRFS_I(inode)->last_trans = fs_info->generation;
4946 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4947 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4952 * 1 - for the one we're dropping
4953 * 1 - for the one we're adding
4954 * 1 - for updating the inode.
4956 trans = btrfs_start_transaction(root, 3);
4958 return PTR_ERR(trans);
4960 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4962 btrfs_abort_transaction(trans, ret);
4963 btrfs_end_transaction(trans);
4967 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4968 offset, 0, 0, len, 0, len, 0, 0, 0);
4970 btrfs_abort_transaction(trans, ret);
4972 btrfs_update_inode(trans, root, inode);
4973 btrfs_end_transaction(trans);
4978 * This function puts in dummy file extents for the area we're creating a hole
4979 * for. So if we are truncating this file to a larger size we need to insert
4980 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4981 * the range between oldsize and size
4983 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4985 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4986 struct btrfs_root *root = BTRFS_I(inode)->root;
4987 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4988 struct extent_map *em = NULL;
4989 struct extent_state *cached_state = NULL;
4990 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4991 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4992 u64 block_end = ALIGN(size, fs_info->sectorsize);
4999 * If our size started in the middle of a block we need to zero out the
5000 * rest of the block before we expand the i_size, otherwise we could
5001 * expose stale data.
5003 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5007 if (size <= hole_start)
5011 struct btrfs_ordered_extent *ordered;
5013 lock_extent_bits(io_tree, hole_start, block_end - 1,
5015 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5016 block_end - hole_start);
5019 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5021 btrfs_start_ordered_extent(inode, ordered, 1);
5022 btrfs_put_ordered_extent(ordered);
5025 cur_offset = hole_start;
5027 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5028 block_end - cur_offset, 0);
5034 last_byte = min(extent_map_end(em), block_end);
5035 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5036 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5037 struct extent_map *hole_em;
5038 hole_size = last_byte - cur_offset;
5040 err = maybe_insert_hole(root, inode, cur_offset,
5044 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5045 cur_offset + hole_size - 1, 0);
5046 hole_em = alloc_extent_map();
5048 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5049 &BTRFS_I(inode)->runtime_flags);
5052 hole_em->start = cur_offset;
5053 hole_em->len = hole_size;
5054 hole_em->orig_start = cur_offset;
5056 hole_em->block_start = EXTENT_MAP_HOLE;
5057 hole_em->block_len = 0;
5058 hole_em->orig_block_len = 0;
5059 hole_em->ram_bytes = hole_size;
5060 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5061 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5062 hole_em->generation = fs_info->generation;
5065 write_lock(&em_tree->lock);
5066 err = add_extent_mapping(em_tree, hole_em, 1);
5067 write_unlock(&em_tree->lock);
5070 btrfs_drop_extent_cache(BTRFS_I(inode),
5075 free_extent_map(hole_em);
5078 free_extent_map(em);
5080 cur_offset = last_byte;
5081 if (cur_offset >= block_end)
5084 free_extent_map(em);
5085 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5089 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5091 struct btrfs_root *root = BTRFS_I(inode)->root;
5092 struct btrfs_trans_handle *trans;
5093 loff_t oldsize = i_size_read(inode);
5094 loff_t newsize = attr->ia_size;
5095 int mask = attr->ia_valid;
5099 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5100 * special case where we need to update the times despite not having
5101 * these flags set. For all other operations the VFS set these flags
5102 * explicitly if it wants a timestamp update.
5104 if (newsize != oldsize) {
5105 inode_inc_iversion(inode);
5106 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5107 inode->i_ctime = inode->i_mtime =
5108 current_time(inode);
5111 if (newsize > oldsize) {
5113 * Don't do an expanding truncate while snapshotting is ongoing.
5114 * This is to ensure the snapshot captures a fully consistent
5115 * state of this file - if the snapshot captures this expanding
5116 * truncation, it must capture all writes that happened before
5119 btrfs_wait_for_snapshot_creation(root);
5120 ret = btrfs_cont_expand(inode, oldsize, newsize);
5122 btrfs_end_write_no_snapshotting(root);
5126 trans = btrfs_start_transaction(root, 1);
5127 if (IS_ERR(trans)) {
5128 btrfs_end_write_no_snapshotting(root);
5129 return PTR_ERR(trans);
5132 i_size_write(inode, newsize);
5133 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5134 pagecache_isize_extended(inode, oldsize, newsize);
5135 ret = btrfs_update_inode(trans, root, inode);
5136 btrfs_end_write_no_snapshotting(root);
5137 btrfs_end_transaction(trans);
5141 * We're truncating a file that used to have good data down to
5142 * zero. Make sure it gets into the ordered flush list so that
5143 * any new writes get down to disk quickly.
5146 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5147 &BTRFS_I(inode)->runtime_flags);
5149 truncate_setsize(inode, newsize);
5151 /* Disable nonlocked read DIO to avoid the end less truncate */
5152 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5153 inode_dio_wait(inode);
5154 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5156 ret = btrfs_truncate(inode, newsize == oldsize);
5157 if (ret && inode->i_nlink) {
5161 * Truncate failed, so fix up the in-memory size. We
5162 * adjusted disk_i_size down as we removed extents, so
5163 * wait for disk_i_size to be stable and then update the
5164 * in-memory size to match.
5166 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5169 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5176 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5178 struct inode *inode = d_inode(dentry);
5179 struct btrfs_root *root = BTRFS_I(inode)->root;
5182 if (btrfs_root_readonly(root))
5185 err = setattr_prepare(dentry, attr);
5189 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5190 err = btrfs_setsize(inode, attr);
5195 if (attr->ia_valid) {
5196 setattr_copy(inode, attr);
5197 inode_inc_iversion(inode);
5198 err = btrfs_dirty_inode(inode);
5200 if (!err && attr->ia_valid & ATTR_MODE)
5201 err = posix_acl_chmod(inode, inode->i_mode);
5208 * While truncating the inode pages during eviction, we get the VFS calling
5209 * btrfs_invalidatepage() against each page of the inode. This is slow because
5210 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5211 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5212 * extent_state structures over and over, wasting lots of time.
5214 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5215 * those expensive operations on a per page basis and do only the ordered io
5216 * finishing, while we release here the extent_map and extent_state structures,
5217 * without the excessive merging and splitting.
5219 static void evict_inode_truncate_pages(struct inode *inode)
5221 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5222 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5223 struct rb_node *node;
5225 ASSERT(inode->i_state & I_FREEING);
5226 truncate_inode_pages_final(&inode->i_data);
5228 write_lock(&map_tree->lock);
5229 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5230 struct extent_map *em;
5232 node = rb_first_cached(&map_tree->map);
5233 em = rb_entry(node, struct extent_map, rb_node);
5234 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5235 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5236 remove_extent_mapping(map_tree, em);
5237 free_extent_map(em);
5238 if (need_resched()) {
5239 write_unlock(&map_tree->lock);
5241 write_lock(&map_tree->lock);
5244 write_unlock(&map_tree->lock);
5247 * Keep looping until we have no more ranges in the io tree.
5248 * We can have ongoing bios started by readpages (called from readahead)
5249 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5250 * still in progress (unlocked the pages in the bio but did not yet
5251 * unlocked the ranges in the io tree). Therefore this means some
5252 * ranges can still be locked and eviction started because before
5253 * submitting those bios, which are executed by a separate task (work
5254 * queue kthread), inode references (inode->i_count) were not taken
5255 * (which would be dropped in the end io callback of each bio).
5256 * Therefore here we effectively end up waiting for those bios and
5257 * anyone else holding locked ranges without having bumped the inode's
5258 * reference count - if we don't do it, when they access the inode's
5259 * io_tree to unlock a range it may be too late, leading to an
5260 * use-after-free issue.
5262 spin_lock(&io_tree->lock);
5263 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5264 struct extent_state *state;
5265 struct extent_state *cached_state = NULL;
5268 unsigned state_flags;
5270 node = rb_first(&io_tree->state);
5271 state = rb_entry(node, struct extent_state, rb_node);
5272 start = state->start;
5274 state_flags = state->state;
5275 spin_unlock(&io_tree->lock);
5277 lock_extent_bits(io_tree, start, end, &cached_state);
5280 * If still has DELALLOC flag, the extent didn't reach disk,
5281 * and its reserved space won't be freed by delayed_ref.
5282 * So we need to free its reserved space here.
5283 * (Refer to comment in btrfs_invalidatepage, case 2)
5285 * Note, end is the bytenr of last byte, so we need + 1 here.
5287 if (state_flags & EXTENT_DELALLOC)
5288 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5290 clear_extent_bit(io_tree, start, end,
5291 EXTENT_LOCKED | EXTENT_DIRTY |
5292 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5293 EXTENT_DEFRAG, 1, 1, &cached_state);
5296 spin_lock(&io_tree->lock);
5298 spin_unlock(&io_tree->lock);
5301 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5302 struct btrfs_block_rsv *rsv)
5304 struct btrfs_fs_info *fs_info = root->fs_info;
5305 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5309 struct btrfs_trans_handle *trans;
5312 ret = btrfs_block_rsv_refill(root, rsv, rsv->size,
5313 BTRFS_RESERVE_FLUSH_LIMIT);
5315 if (ret && ++failures > 2) {
5317 "could not allocate space for a delete; will truncate on mount");
5318 return ERR_PTR(-ENOSPC);
5321 trans = btrfs_join_transaction(root);
5322 if (IS_ERR(trans) || !ret)
5326 * Try to steal from the global reserve if there is space for
5329 if (!btrfs_check_space_for_delayed_refs(trans) &&
5330 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, false))
5333 /* If not, commit and try again. */
5334 ret = btrfs_commit_transaction(trans);
5336 return ERR_PTR(ret);
5340 void btrfs_evict_inode(struct inode *inode)
5342 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5343 struct btrfs_trans_handle *trans;
5344 struct btrfs_root *root = BTRFS_I(inode)->root;
5345 struct btrfs_block_rsv *rsv;
5348 trace_btrfs_inode_evict(inode);
5355 evict_inode_truncate_pages(inode);
5357 if (inode->i_nlink &&
5358 ((btrfs_root_refs(&root->root_item) != 0 &&
5359 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5360 btrfs_is_free_space_inode(BTRFS_I(inode))))
5363 if (is_bad_inode(inode))
5366 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5368 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5371 if (inode->i_nlink > 0) {
5372 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5373 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5377 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5381 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5384 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5387 btrfs_i_size_write(BTRFS_I(inode), 0);
5390 trans = evict_refill_and_join(root, rsv);
5394 trans->block_rsv = rsv;
5396 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5397 trans->block_rsv = &fs_info->trans_block_rsv;
5398 btrfs_end_transaction(trans);
5399 btrfs_btree_balance_dirty(fs_info);
5400 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5407 * Errors here aren't a big deal, it just means we leave orphan items in
5408 * the tree. They will be cleaned up on the next mount. If the inode
5409 * number gets reused, cleanup deletes the orphan item without doing
5410 * anything, and unlink reuses the existing orphan item.
5412 * If it turns out that we are dropping too many of these, we might want
5413 * to add a mechanism for retrying these after a commit.
5415 trans = evict_refill_and_join(root, rsv);
5416 if (!IS_ERR(trans)) {
5417 trans->block_rsv = rsv;
5418 btrfs_orphan_del(trans, BTRFS_I(inode));
5419 trans->block_rsv = &fs_info->trans_block_rsv;
5420 btrfs_end_transaction(trans);
5423 if (!(root == fs_info->tree_root ||
5424 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5425 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5428 btrfs_free_block_rsv(fs_info, rsv);
5431 * If we didn't successfully delete, the orphan item will still be in
5432 * the tree and we'll retry on the next mount. Again, we might also want
5433 * to retry these periodically in the future.
5435 btrfs_remove_delayed_node(BTRFS_I(inode));
5440 * this returns the key found in the dir entry in the location pointer.
5441 * If no dir entries were found, returns -ENOENT.
5442 * If found a corrupted location in dir entry, returns -EUCLEAN.
5444 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5445 struct btrfs_key *location)
5447 const char *name = dentry->d_name.name;
5448 int namelen = dentry->d_name.len;
5449 struct btrfs_dir_item *di;
5450 struct btrfs_path *path;
5451 struct btrfs_root *root = BTRFS_I(dir)->root;
5454 path = btrfs_alloc_path();
5458 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5460 if (IS_ERR_OR_NULL(di)) {
5461 ret = di ? PTR_ERR(di) : -ENOENT;
5465 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5466 if (location->type != BTRFS_INODE_ITEM_KEY &&
5467 location->type != BTRFS_ROOT_ITEM_KEY) {
5469 btrfs_warn(root->fs_info,
5470 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5471 __func__, name, btrfs_ino(BTRFS_I(dir)),
5472 location->objectid, location->type, location->offset);
5475 btrfs_free_path(path);
5480 * when we hit a tree root in a directory, the btrfs part of the inode
5481 * needs to be changed to reflect the root directory of the tree root. This
5482 * is kind of like crossing a mount point.
5484 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5486 struct dentry *dentry,
5487 struct btrfs_key *location,
5488 struct btrfs_root **sub_root)
5490 struct btrfs_path *path;
5491 struct btrfs_root *new_root;
5492 struct btrfs_root_ref *ref;
5493 struct extent_buffer *leaf;
5494 struct btrfs_key key;
5498 path = btrfs_alloc_path();
5505 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5506 key.type = BTRFS_ROOT_REF_KEY;
5507 key.offset = location->objectid;
5509 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5516 leaf = path->nodes[0];
5517 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5518 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5519 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5522 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5523 (unsigned long)(ref + 1),
5524 dentry->d_name.len);
5528 btrfs_release_path(path);
5530 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5531 if (IS_ERR(new_root)) {
5532 err = PTR_ERR(new_root);
5536 *sub_root = new_root;
5537 location->objectid = btrfs_root_dirid(&new_root->root_item);
5538 location->type = BTRFS_INODE_ITEM_KEY;
5539 location->offset = 0;
5542 btrfs_free_path(path);
5546 static void inode_tree_add(struct inode *inode)
5548 struct btrfs_root *root = BTRFS_I(inode)->root;
5549 struct btrfs_inode *entry;
5551 struct rb_node *parent;
5552 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5553 u64 ino = btrfs_ino(BTRFS_I(inode));
5555 if (inode_unhashed(inode))
5558 spin_lock(&root->inode_lock);
5559 p = &root->inode_tree.rb_node;
5562 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5564 if (ino < btrfs_ino(entry))
5565 p = &parent->rb_left;
5566 else if (ino > btrfs_ino(entry))
5567 p = &parent->rb_right;
5569 WARN_ON(!(entry->vfs_inode.i_state &
5570 (I_WILL_FREE | I_FREEING)));
5571 rb_replace_node(parent, new, &root->inode_tree);
5572 RB_CLEAR_NODE(parent);
5573 spin_unlock(&root->inode_lock);
5577 rb_link_node(new, parent, p);
5578 rb_insert_color(new, &root->inode_tree);
5579 spin_unlock(&root->inode_lock);
5582 static void inode_tree_del(struct inode *inode)
5584 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5585 struct btrfs_root *root = BTRFS_I(inode)->root;
5588 spin_lock(&root->inode_lock);
5589 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5590 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5591 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5592 empty = RB_EMPTY_ROOT(&root->inode_tree);
5594 spin_unlock(&root->inode_lock);
5596 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5597 synchronize_srcu(&fs_info->subvol_srcu);
5598 spin_lock(&root->inode_lock);
5599 empty = RB_EMPTY_ROOT(&root->inode_tree);
5600 spin_unlock(&root->inode_lock);
5602 btrfs_add_dead_root(root);
5607 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5609 struct btrfs_iget_args *args = p;
5610 inode->i_ino = args->location->objectid;
5611 memcpy(&BTRFS_I(inode)->location, args->location,
5612 sizeof(*args->location));
5613 BTRFS_I(inode)->root = args->root;
5617 static int btrfs_find_actor(struct inode *inode, void *opaque)
5619 struct btrfs_iget_args *args = opaque;
5620 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5621 args->root == BTRFS_I(inode)->root;
5624 static struct inode *btrfs_iget_locked(struct super_block *s,
5625 struct btrfs_key *location,
5626 struct btrfs_root *root)
5628 struct inode *inode;
5629 struct btrfs_iget_args args;
5630 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5632 args.location = location;
5635 inode = iget5_locked(s, hashval, btrfs_find_actor,
5636 btrfs_init_locked_inode,
5641 /* Get an inode object given its location and corresponding root.
5642 * Returns in *is_new if the inode was read from disk
5644 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5645 struct btrfs_root *root, int *new,
5646 struct btrfs_path *path)
5648 struct inode *inode;
5650 inode = btrfs_iget_locked(s, location, root);
5652 return ERR_PTR(-ENOMEM);
5654 if (inode->i_state & I_NEW) {
5657 ret = btrfs_read_locked_inode(inode, path);
5659 inode_tree_add(inode);
5660 unlock_new_inode(inode);
5666 * ret > 0 can come from btrfs_search_slot called by
5667 * btrfs_read_locked_inode, this means the inode item
5672 inode = ERR_PTR(ret);
5679 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5680 struct btrfs_root *root, int *new)
5682 return btrfs_iget_path(s, location, root, new, NULL);
5685 static struct inode *new_simple_dir(struct super_block *s,
5686 struct btrfs_key *key,
5687 struct btrfs_root *root)
5689 struct inode *inode = new_inode(s);
5692 return ERR_PTR(-ENOMEM);
5694 BTRFS_I(inode)->root = root;
5695 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5696 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5698 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5699 inode->i_op = &btrfs_dir_ro_inode_operations;
5700 inode->i_opflags &= ~IOP_XATTR;
5701 inode->i_fop = &simple_dir_operations;
5702 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5703 inode->i_mtime = current_time(inode);
5704 inode->i_atime = inode->i_mtime;
5705 inode->i_ctime = inode->i_mtime;
5706 BTRFS_I(inode)->i_otime = inode->i_mtime;
5711 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5713 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5714 struct inode *inode;
5715 struct btrfs_root *root = BTRFS_I(dir)->root;
5716 struct btrfs_root *sub_root = root;
5717 struct btrfs_key location;
5721 if (dentry->d_name.len > BTRFS_NAME_LEN)
5722 return ERR_PTR(-ENAMETOOLONG);
5724 ret = btrfs_inode_by_name(dir, dentry, &location);
5726 return ERR_PTR(ret);
5728 if (location.type == BTRFS_INODE_ITEM_KEY) {
5729 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5733 index = srcu_read_lock(&fs_info->subvol_srcu);
5734 ret = fixup_tree_root_location(fs_info, dir, dentry,
5735 &location, &sub_root);
5738 inode = ERR_PTR(ret);
5740 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5742 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5744 srcu_read_unlock(&fs_info->subvol_srcu, index);
5746 if (!IS_ERR(inode) && root != sub_root) {
5747 down_read(&fs_info->cleanup_work_sem);
5748 if (!sb_rdonly(inode->i_sb))
5749 ret = btrfs_orphan_cleanup(sub_root);
5750 up_read(&fs_info->cleanup_work_sem);
5753 inode = ERR_PTR(ret);
5760 static int btrfs_dentry_delete(const struct dentry *dentry)
5762 struct btrfs_root *root;
5763 struct inode *inode = d_inode(dentry);
5765 if (!inode && !IS_ROOT(dentry))
5766 inode = d_inode(dentry->d_parent);
5769 root = BTRFS_I(inode)->root;
5770 if (btrfs_root_refs(&root->root_item) == 0)
5773 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5779 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5782 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5784 if (inode == ERR_PTR(-ENOENT))
5786 return d_splice_alias(inode, dentry);
5789 unsigned char btrfs_filetype_table[] = {
5790 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5794 * All this infrastructure exists because dir_emit can fault, and we are holding
5795 * the tree lock when doing readdir. For now just allocate a buffer and copy
5796 * our information into that, and then dir_emit from the buffer. This is
5797 * similar to what NFS does, only we don't keep the buffer around in pagecache
5798 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5799 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5802 static int btrfs_opendir(struct inode *inode, struct file *file)
5804 struct btrfs_file_private *private;
5806 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5809 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5810 if (!private->filldir_buf) {
5814 file->private_data = private;
5825 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5828 struct dir_entry *entry = addr;
5829 char *name = (char *)(entry + 1);
5831 ctx->pos = get_unaligned(&entry->offset);
5832 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5833 get_unaligned(&entry->ino),
5834 get_unaligned(&entry->type)))
5836 addr += sizeof(struct dir_entry) +
5837 get_unaligned(&entry->name_len);
5843 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5845 struct inode *inode = file_inode(file);
5846 struct btrfs_root *root = BTRFS_I(inode)->root;
5847 struct btrfs_file_private *private = file->private_data;
5848 struct btrfs_dir_item *di;
5849 struct btrfs_key key;
5850 struct btrfs_key found_key;
5851 struct btrfs_path *path;
5853 struct list_head ins_list;
5854 struct list_head del_list;
5856 struct extent_buffer *leaf;
5863 struct btrfs_key location;
5865 if (!dir_emit_dots(file, ctx))
5868 path = btrfs_alloc_path();
5872 addr = private->filldir_buf;
5873 path->reada = READA_FORWARD;
5875 INIT_LIST_HEAD(&ins_list);
5876 INIT_LIST_HEAD(&del_list);
5877 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5880 key.type = BTRFS_DIR_INDEX_KEY;
5881 key.offset = ctx->pos;
5882 key.objectid = btrfs_ino(BTRFS_I(inode));
5884 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5889 struct dir_entry *entry;
5891 leaf = path->nodes[0];
5892 slot = path->slots[0];
5893 if (slot >= btrfs_header_nritems(leaf)) {
5894 ret = btrfs_next_leaf(root, path);
5902 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5904 if (found_key.objectid != key.objectid)
5906 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5908 if (found_key.offset < ctx->pos)
5910 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5912 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5913 name_len = btrfs_dir_name_len(leaf, di);
5914 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5916 btrfs_release_path(path);
5917 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5920 addr = private->filldir_buf;
5927 put_unaligned(name_len, &entry->name_len);
5928 name_ptr = (char *)(entry + 1);
5929 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5931 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
5933 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5934 put_unaligned(location.objectid, &entry->ino);
5935 put_unaligned(found_key.offset, &entry->offset);
5937 addr += sizeof(struct dir_entry) + name_len;
5938 total_len += sizeof(struct dir_entry) + name_len;
5942 btrfs_release_path(path);
5944 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5948 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5953 * Stop new entries from being returned after we return the last
5956 * New directory entries are assigned a strictly increasing
5957 * offset. This means that new entries created during readdir
5958 * are *guaranteed* to be seen in the future by that readdir.
5959 * This has broken buggy programs which operate on names as
5960 * they're returned by readdir. Until we re-use freed offsets
5961 * we have this hack to stop new entries from being returned
5962 * under the assumption that they'll never reach this huge
5965 * This is being careful not to overflow 32bit loff_t unless the
5966 * last entry requires it because doing so has broken 32bit apps
5969 if (ctx->pos >= INT_MAX)
5970 ctx->pos = LLONG_MAX;
5977 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5978 btrfs_free_path(path);
5983 * This is somewhat expensive, updating the tree every time the
5984 * inode changes. But, it is most likely to find the inode in cache.
5985 * FIXME, needs more benchmarking...there are no reasons other than performance
5986 * to keep or drop this code.
5988 static int btrfs_dirty_inode(struct inode *inode)
5990 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5991 struct btrfs_root *root = BTRFS_I(inode)->root;
5992 struct btrfs_trans_handle *trans;
5995 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5998 trans = btrfs_join_transaction(root);
6000 return PTR_ERR(trans);
6002 ret = btrfs_update_inode(trans, root, inode);
6003 if (ret && ret == -ENOSPC) {
6004 /* whoops, lets try again with the full transaction */
6005 btrfs_end_transaction(trans);
6006 trans = btrfs_start_transaction(root, 1);
6008 return PTR_ERR(trans);
6010 ret = btrfs_update_inode(trans, root, inode);
6012 btrfs_end_transaction(trans);
6013 if (BTRFS_I(inode)->delayed_node)
6014 btrfs_balance_delayed_items(fs_info);
6020 * This is a copy of file_update_time. We need this so we can return error on
6021 * ENOSPC for updating the inode in the case of file write and mmap writes.
6023 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6026 struct btrfs_root *root = BTRFS_I(inode)->root;
6027 bool dirty = flags & ~S_VERSION;
6029 if (btrfs_root_readonly(root))
6032 if (flags & S_VERSION)
6033 dirty |= inode_maybe_inc_iversion(inode, dirty);
6034 if (flags & S_CTIME)
6035 inode->i_ctime = *now;
6036 if (flags & S_MTIME)
6037 inode->i_mtime = *now;
6038 if (flags & S_ATIME)
6039 inode->i_atime = *now;
6040 return dirty ? btrfs_dirty_inode(inode) : 0;
6044 * find the highest existing sequence number in a directory
6045 * and then set the in-memory index_cnt variable to reflect
6046 * free sequence numbers
6048 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6050 struct btrfs_root *root = inode->root;
6051 struct btrfs_key key, found_key;
6052 struct btrfs_path *path;
6053 struct extent_buffer *leaf;
6056 key.objectid = btrfs_ino(inode);
6057 key.type = BTRFS_DIR_INDEX_KEY;
6058 key.offset = (u64)-1;
6060 path = btrfs_alloc_path();
6064 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6067 /* FIXME: we should be able to handle this */
6073 * MAGIC NUMBER EXPLANATION:
6074 * since we search a directory based on f_pos we have to start at 2
6075 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6076 * else has to start at 2
6078 if (path->slots[0] == 0) {
6079 inode->index_cnt = 2;
6085 leaf = path->nodes[0];
6086 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6088 if (found_key.objectid != btrfs_ino(inode) ||
6089 found_key.type != BTRFS_DIR_INDEX_KEY) {
6090 inode->index_cnt = 2;
6094 inode->index_cnt = found_key.offset + 1;
6096 btrfs_free_path(path);
6101 * helper to find a free sequence number in a given directory. This current
6102 * code is very simple, later versions will do smarter things in the btree
6104 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6108 if (dir->index_cnt == (u64)-1) {
6109 ret = btrfs_inode_delayed_dir_index_count(dir);
6111 ret = btrfs_set_inode_index_count(dir);
6117 *index = dir->index_cnt;
6123 static int btrfs_insert_inode_locked(struct inode *inode)
6125 struct btrfs_iget_args args;
6126 args.location = &BTRFS_I(inode)->location;
6127 args.root = BTRFS_I(inode)->root;
6129 return insert_inode_locked4(inode,
6130 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6131 btrfs_find_actor, &args);
6135 * Inherit flags from the parent inode.
6137 * Currently only the compression flags and the cow flags are inherited.
6139 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6146 flags = BTRFS_I(dir)->flags;
6148 if (flags & BTRFS_INODE_NOCOMPRESS) {
6149 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6150 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6151 } else if (flags & BTRFS_INODE_COMPRESS) {
6152 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6153 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6156 if (flags & BTRFS_INODE_NODATACOW) {
6157 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6158 if (S_ISREG(inode->i_mode))
6159 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6162 btrfs_sync_inode_flags_to_i_flags(inode);
6165 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6166 struct btrfs_root *root,
6168 const char *name, int name_len,
6169 u64 ref_objectid, u64 objectid,
6170 umode_t mode, u64 *index)
6172 struct btrfs_fs_info *fs_info = root->fs_info;
6173 struct inode *inode;
6174 struct btrfs_inode_item *inode_item;
6175 struct btrfs_key *location;
6176 struct btrfs_path *path;
6177 struct btrfs_inode_ref *ref;
6178 struct btrfs_key key[2];
6180 int nitems = name ? 2 : 1;
6184 path = btrfs_alloc_path();
6186 return ERR_PTR(-ENOMEM);
6188 inode = new_inode(fs_info->sb);
6190 btrfs_free_path(path);
6191 return ERR_PTR(-ENOMEM);
6195 * O_TMPFILE, set link count to 0, so that after this point,
6196 * we fill in an inode item with the correct link count.
6199 set_nlink(inode, 0);
6202 * we have to initialize this early, so we can reclaim the inode
6203 * number if we fail afterwards in this function.
6205 inode->i_ino = objectid;
6208 trace_btrfs_inode_request(dir);
6210 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6212 btrfs_free_path(path);
6214 return ERR_PTR(ret);
6220 * index_cnt is ignored for everything but a dir,
6221 * btrfs_set_inode_index_count has an explanation for the magic
6224 BTRFS_I(inode)->index_cnt = 2;
6225 BTRFS_I(inode)->dir_index = *index;
6226 BTRFS_I(inode)->root = root;
6227 BTRFS_I(inode)->generation = trans->transid;
6228 inode->i_generation = BTRFS_I(inode)->generation;
6231 * We could have gotten an inode number from somebody who was fsynced
6232 * and then removed in this same transaction, so let's just set full
6233 * sync since it will be a full sync anyway and this will blow away the
6234 * old info in the log.
6236 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6238 key[0].objectid = objectid;
6239 key[0].type = BTRFS_INODE_ITEM_KEY;
6242 sizes[0] = sizeof(struct btrfs_inode_item);
6246 * Start new inodes with an inode_ref. This is slightly more
6247 * efficient for small numbers of hard links since they will
6248 * be packed into one item. Extended refs will kick in if we
6249 * add more hard links than can fit in the ref item.
6251 key[1].objectid = objectid;
6252 key[1].type = BTRFS_INODE_REF_KEY;
6253 key[1].offset = ref_objectid;
6255 sizes[1] = name_len + sizeof(*ref);
6258 location = &BTRFS_I(inode)->location;
6259 location->objectid = objectid;
6260 location->offset = 0;
6261 location->type = BTRFS_INODE_ITEM_KEY;
6263 ret = btrfs_insert_inode_locked(inode);
6269 path->leave_spinning = 1;
6270 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6274 inode_init_owner(inode, dir, mode);
6275 inode_set_bytes(inode, 0);
6277 inode->i_mtime = current_time(inode);
6278 inode->i_atime = inode->i_mtime;
6279 inode->i_ctime = inode->i_mtime;
6280 BTRFS_I(inode)->i_otime = inode->i_mtime;
6282 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6283 struct btrfs_inode_item);
6284 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6285 sizeof(*inode_item));
6286 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6289 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6290 struct btrfs_inode_ref);
6291 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6292 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6293 ptr = (unsigned long)(ref + 1);
6294 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6297 btrfs_mark_buffer_dirty(path->nodes[0]);
6298 btrfs_free_path(path);
6300 btrfs_inherit_iflags(inode, dir);
6302 if (S_ISREG(mode)) {
6303 if (btrfs_test_opt(fs_info, NODATASUM))
6304 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6305 if (btrfs_test_opt(fs_info, NODATACOW))
6306 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6307 BTRFS_INODE_NODATASUM;
6310 inode_tree_add(inode);
6312 trace_btrfs_inode_new(inode);
6313 btrfs_set_inode_last_trans(trans, inode);
6315 btrfs_update_root_times(trans, root);
6317 ret = btrfs_inode_inherit_props(trans, inode, dir);
6320 "error inheriting props for ino %llu (root %llu): %d",
6321 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6326 discard_new_inode(inode);
6329 BTRFS_I(dir)->index_cnt--;
6330 btrfs_free_path(path);
6331 return ERR_PTR(ret);
6334 static inline u8 btrfs_inode_type(struct inode *inode)
6336 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6340 * utility function to add 'inode' into 'parent_inode' with
6341 * a give name and a given sequence number.
6342 * if 'add_backref' is true, also insert a backref from the
6343 * inode to the parent directory.
6345 int btrfs_add_link(struct btrfs_trans_handle *trans,
6346 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6347 const char *name, int name_len, int add_backref, u64 index)
6350 struct btrfs_key key;
6351 struct btrfs_root *root = parent_inode->root;
6352 u64 ino = btrfs_ino(inode);
6353 u64 parent_ino = btrfs_ino(parent_inode);
6355 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6356 memcpy(&key, &inode->root->root_key, sizeof(key));
6359 key.type = BTRFS_INODE_ITEM_KEY;
6363 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6364 ret = btrfs_add_root_ref(trans, key.objectid,
6365 root->root_key.objectid, parent_ino,
6366 index, name, name_len);
6367 } else if (add_backref) {
6368 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6372 /* Nothing to clean up yet */
6376 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6377 btrfs_inode_type(&inode->vfs_inode), index);
6378 if (ret == -EEXIST || ret == -EOVERFLOW)
6381 btrfs_abort_transaction(trans, ret);
6385 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6387 inode_inc_iversion(&parent_inode->vfs_inode);
6388 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6389 current_time(&parent_inode->vfs_inode);
6390 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6392 btrfs_abort_transaction(trans, ret);
6396 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6399 err = btrfs_del_root_ref(trans, key.objectid,
6400 root->root_key.objectid, parent_ino,
6401 &local_index, name, name_len);
6403 } else if (add_backref) {
6407 err = btrfs_del_inode_ref(trans, root, name, name_len,
6408 ino, parent_ino, &local_index);
6413 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6414 struct btrfs_inode *dir, struct dentry *dentry,
6415 struct btrfs_inode *inode, int backref, u64 index)
6417 int err = btrfs_add_link(trans, dir, inode,
6418 dentry->d_name.name, dentry->d_name.len,
6425 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6426 umode_t mode, dev_t rdev)
6428 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6429 struct btrfs_trans_handle *trans;
6430 struct btrfs_root *root = BTRFS_I(dir)->root;
6431 struct inode *inode = NULL;
6437 * 2 for inode item and ref
6439 * 1 for xattr if selinux is on
6441 trans = btrfs_start_transaction(root, 5);
6443 return PTR_ERR(trans);
6445 err = btrfs_find_free_ino(root, &objectid);
6449 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6450 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6452 if (IS_ERR(inode)) {
6453 err = PTR_ERR(inode);
6459 * If the active LSM wants to access the inode during
6460 * d_instantiate it needs these. Smack checks to see
6461 * if the filesystem supports xattrs by looking at the
6464 inode->i_op = &btrfs_special_inode_operations;
6465 init_special_inode(inode, inode->i_mode, rdev);
6467 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6471 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6476 btrfs_update_inode(trans, root, inode);
6477 d_instantiate_new(dentry, inode);
6480 btrfs_end_transaction(trans);
6481 btrfs_btree_balance_dirty(fs_info);
6483 inode_dec_link_count(inode);
6484 discard_new_inode(inode);
6489 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6490 umode_t mode, bool excl)
6492 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6493 struct btrfs_trans_handle *trans;
6494 struct btrfs_root *root = BTRFS_I(dir)->root;
6495 struct inode *inode = NULL;
6501 * 2 for inode item and ref
6503 * 1 for xattr if selinux is on
6505 trans = btrfs_start_transaction(root, 5);
6507 return PTR_ERR(trans);
6509 err = btrfs_find_free_ino(root, &objectid);
6513 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6514 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6516 if (IS_ERR(inode)) {
6517 err = PTR_ERR(inode);
6522 * If the active LSM wants to access the inode during
6523 * d_instantiate it needs these. Smack checks to see
6524 * if the filesystem supports xattrs by looking at the
6527 inode->i_fop = &btrfs_file_operations;
6528 inode->i_op = &btrfs_file_inode_operations;
6529 inode->i_mapping->a_ops = &btrfs_aops;
6531 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6535 err = btrfs_update_inode(trans, root, inode);
6539 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6544 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6545 d_instantiate_new(dentry, inode);
6548 btrfs_end_transaction(trans);
6550 inode_dec_link_count(inode);
6551 discard_new_inode(inode);
6553 btrfs_btree_balance_dirty(fs_info);
6557 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6558 struct dentry *dentry)
6560 struct btrfs_trans_handle *trans = NULL;
6561 struct btrfs_root *root = BTRFS_I(dir)->root;
6562 struct inode *inode = d_inode(old_dentry);
6563 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6568 /* do not allow sys_link's with other subvols of the same device */
6569 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6572 if (inode->i_nlink >= BTRFS_LINK_MAX)
6575 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6580 * 2 items for inode and inode ref
6581 * 2 items for dir items
6582 * 1 item for parent inode
6583 * 1 item for orphan item deletion if O_TMPFILE
6585 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6586 if (IS_ERR(trans)) {
6587 err = PTR_ERR(trans);
6592 /* There are several dir indexes for this inode, clear the cache. */
6593 BTRFS_I(inode)->dir_index = 0ULL;
6595 inode_inc_iversion(inode);
6596 inode->i_ctime = current_time(inode);
6598 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6600 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6606 struct dentry *parent = dentry->d_parent;
6609 err = btrfs_update_inode(trans, root, inode);
6612 if (inode->i_nlink == 1) {
6614 * If new hard link count is 1, it's a file created
6615 * with open(2) O_TMPFILE flag.
6617 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6621 d_instantiate(dentry, inode);
6622 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6624 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6625 err = btrfs_commit_transaction(trans);
6632 btrfs_end_transaction(trans);
6634 inode_dec_link_count(inode);
6637 btrfs_btree_balance_dirty(fs_info);
6641 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6643 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6644 struct inode *inode = NULL;
6645 struct btrfs_trans_handle *trans;
6646 struct btrfs_root *root = BTRFS_I(dir)->root;
6648 int drop_on_err = 0;
6653 * 2 items for inode and ref
6654 * 2 items for dir items
6655 * 1 for xattr if selinux is on
6657 trans = btrfs_start_transaction(root, 5);
6659 return PTR_ERR(trans);
6661 err = btrfs_find_free_ino(root, &objectid);
6665 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6666 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6667 S_IFDIR | mode, &index);
6668 if (IS_ERR(inode)) {
6669 err = PTR_ERR(inode);
6675 /* these must be set before we unlock the inode */
6676 inode->i_op = &btrfs_dir_inode_operations;
6677 inode->i_fop = &btrfs_dir_file_operations;
6679 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6683 btrfs_i_size_write(BTRFS_I(inode), 0);
6684 err = btrfs_update_inode(trans, root, inode);
6688 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6689 dentry->d_name.name,
6690 dentry->d_name.len, 0, index);
6694 d_instantiate_new(dentry, inode);
6698 btrfs_end_transaction(trans);
6700 inode_dec_link_count(inode);
6701 discard_new_inode(inode);
6703 btrfs_btree_balance_dirty(fs_info);
6707 static noinline int uncompress_inline(struct btrfs_path *path,
6709 size_t pg_offset, u64 extent_offset,
6710 struct btrfs_file_extent_item *item)
6713 struct extent_buffer *leaf = path->nodes[0];
6716 unsigned long inline_size;
6720 WARN_ON(pg_offset != 0);
6721 compress_type = btrfs_file_extent_compression(leaf, item);
6722 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6723 inline_size = btrfs_file_extent_inline_item_len(leaf,
6724 btrfs_item_nr(path->slots[0]));
6725 tmp = kmalloc(inline_size, GFP_NOFS);
6728 ptr = btrfs_file_extent_inline_start(item);
6730 read_extent_buffer(leaf, tmp, ptr, inline_size);
6732 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6733 ret = btrfs_decompress(compress_type, tmp, page,
6734 extent_offset, inline_size, max_size);
6737 * decompression code contains a memset to fill in any space between the end
6738 * of the uncompressed data and the end of max_size in case the decompressed
6739 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6740 * the end of an inline extent and the beginning of the next block, so we
6741 * cover that region here.
6744 if (max_size + pg_offset < PAGE_SIZE) {
6745 char *map = kmap(page);
6746 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6754 * a bit scary, this does extent mapping from logical file offset to the disk.
6755 * the ugly parts come from merging extents from the disk with the in-ram
6756 * representation. This gets more complex because of the data=ordered code,
6757 * where the in-ram extents might be locked pending data=ordered completion.
6759 * This also copies inline extents directly into the page.
6761 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6763 size_t pg_offset, u64 start, u64 len,
6766 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6769 u64 extent_start = 0;
6771 u64 objectid = btrfs_ino(inode);
6773 struct btrfs_path *path = NULL;
6774 struct btrfs_root *root = inode->root;
6775 struct btrfs_file_extent_item *item;
6776 struct extent_buffer *leaf;
6777 struct btrfs_key found_key;
6778 struct extent_map *em = NULL;
6779 struct extent_map_tree *em_tree = &inode->extent_tree;
6780 struct extent_io_tree *io_tree = &inode->io_tree;
6781 const bool new_inline = !page || create;
6783 read_lock(&em_tree->lock);
6784 em = lookup_extent_mapping(em_tree, start, len);
6786 em->bdev = fs_info->fs_devices->latest_bdev;
6787 read_unlock(&em_tree->lock);
6790 if (em->start > start || em->start + em->len <= start)
6791 free_extent_map(em);
6792 else if (em->block_start == EXTENT_MAP_INLINE && page)
6793 free_extent_map(em);
6797 em = alloc_extent_map();
6802 em->bdev = fs_info->fs_devices->latest_bdev;
6803 em->start = EXTENT_MAP_HOLE;
6804 em->orig_start = EXTENT_MAP_HOLE;
6806 em->block_len = (u64)-1;
6808 path = btrfs_alloc_path();
6814 /* Chances are we'll be called again, so go ahead and do readahead */
6815 path->reada = READA_FORWARD;
6818 * Unless we're going to uncompress the inline extent, no sleep would
6821 path->leave_spinning = 1;
6823 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6830 if (path->slots[0] == 0)
6835 leaf = path->nodes[0];
6836 item = btrfs_item_ptr(leaf, path->slots[0],
6837 struct btrfs_file_extent_item);
6838 /* are we inside the extent that was found? */
6839 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6840 found_type = found_key.type;
6841 if (found_key.objectid != objectid ||
6842 found_type != BTRFS_EXTENT_DATA_KEY) {
6844 * If we backup past the first extent we want to move forward
6845 * and see if there is an extent in front of us, otherwise we'll
6846 * say there is a hole for our whole search range which can
6853 found_type = btrfs_file_extent_type(leaf, item);
6854 extent_start = found_key.offset;
6855 if (found_type == BTRFS_FILE_EXTENT_REG ||
6856 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6857 extent_end = extent_start +
6858 btrfs_file_extent_num_bytes(leaf, item);
6860 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6862 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6865 size = btrfs_file_extent_ram_bytes(leaf, item);
6866 extent_end = ALIGN(extent_start + size,
6867 fs_info->sectorsize);
6869 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6874 if (start >= extent_end) {
6876 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6877 ret = btrfs_next_leaf(root, path);
6884 leaf = path->nodes[0];
6886 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6887 if (found_key.objectid != objectid ||
6888 found_key.type != BTRFS_EXTENT_DATA_KEY)
6890 if (start + len <= found_key.offset)
6892 if (start > found_key.offset)
6895 em->orig_start = start;
6896 em->len = found_key.offset - start;
6900 btrfs_extent_item_to_extent_map(inode, path, item,
6903 if (found_type == BTRFS_FILE_EXTENT_REG ||
6904 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6906 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6910 size_t extent_offset;
6916 size = btrfs_file_extent_ram_bytes(leaf, item);
6917 extent_offset = page_offset(page) + pg_offset - extent_start;
6918 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6919 size - extent_offset);
6920 em->start = extent_start + extent_offset;
6921 em->len = ALIGN(copy_size, fs_info->sectorsize);
6922 em->orig_block_len = em->len;
6923 em->orig_start = em->start;
6924 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6926 btrfs_set_path_blocking(path);
6927 if (!PageUptodate(page)) {
6928 if (btrfs_file_extent_compression(leaf, item) !=
6929 BTRFS_COMPRESS_NONE) {
6930 ret = uncompress_inline(path, page, pg_offset,
6931 extent_offset, item);
6938 read_extent_buffer(leaf, map + pg_offset, ptr,
6940 if (pg_offset + copy_size < PAGE_SIZE) {
6941 memset(map + pg_offset + copy_size, 0,
6942 PAGE_SIZE - pg_offset -
6947 flush_dcache_page(page);
6949 set_extent_uptodate(io_tree, em->start,
6950 extent_map_end(em) - 1, NULL, GFP_NOFS);
6955 em->orig_start = start;
6958 em->block_start = EXTENT_MAP_HOLE;
6960 btrfs_release_path(path);
6961 if (em->start > start || extent_map_end(em) <= start) {
6963 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6964 em->start, em->len, start, len);
6970 write_lock(&em_tree->lock);
6971 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6972 write_unlock(&em_tree->lock);
6974 btrfs_free_path(path);
6976 trace_btrfs_get_extent(root, inode, em);
6979 free_extent_map(em);
6980 return ERR_PTR(err);
6982 BUG_ON(!em); /* Error is always set */
6986 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6988 size_t pg_offset, u64 start, u64 len,
6991 struct extent_map *em;
6992 struct extent_map *hole_em = NULL;
6993 u64 range_start = start;
6999 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7003 * If our em maps to:
7005 * - a pre-alloc extent,
7006 * there might actually be delalloc bytes behind it.
7008 if (em->block_start != EXTENT_MAP_HOLE &&
7009 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7014 /* check to see if we've wrapped (len == -1 or similar) */
7023 /* ok, we didn't find anything, lets look for delalloc */
7024 found = count_range_bits(&inode->io_tree, &range_start,
7025 end, len, EXTENT_DELALLOC, 1);
7026 found_end = range_start + found;
7027 if (found_end < range_start)
7028 found_end = (u64)-1;
7031 * we didn't find anything useful, return
7032 * the original results from get_extent()
7034 if (range_start > end || found_end <= start) {
7040 /* adjust the range_start to make sure it doesn't
7041 * go backwards from the start they passed in
7043 range_start = max(start, range_start);
7044 found = found_end - range_start;
7047 u64 hole_start = start;
7050 em = alloc_extent_map();
7056 * when btrfs_get_extent can't find anything it
7057 * returns one huge hole
7059 * make sure what it found really fits our range, and
7060 * adjust to make sure it is based on the start from
7064 u64 calc_end = extent_map_end(hole_em);
7066 if (calc_end <= start || (hole_em->start > end)) {
7067 free_extent_map(hole_em);
7070 hole_start = max(hole_em->start, start);
7071 hole_len = calc_end - hole_start;
7075 if (hole_em && range_start > hole_start) {
7076 /* our hole starts before our delalloc, so we
7077 * have to return just the parts of the hole
7078 * that go until the delalloc starts
7080 em->len = min(hole_len,
7081 range_start - hole_start);
7082 em->start = hole_start;
7083 em->orig_start = hole_start;
7085 * don't adjust block start at all,
7086 * it is fixed at EXTENT_MAP_HOLE
7088 em->block_start = hole_em->block_start;
7089 em->block_len = hole_len;
7090 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7091 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7093 em->start = range_start;
7095 em->orig_start = range_start;
7096 em->block_start = EXTENT_MAP_DELALLOC;
7097 em->block_len = found;
7104 free_extent_map(hole_em);
7106 free_extent_map(em);
7107 return ERR_PTR(err);
7112 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7115 const u64 orig_start,
7116 const u64 block_start,
7117 const u64 block_len,
7118 const u64 orig_block_len,
7119 const u64 ram_bytes,
7122 struct extent_map *em = NULL;
7125 if (type != BTRFS_ORDERED_NOCOW) {
7126 em = create_io_em(inode, start, len, orig_start,
7127 block_start, block_len, orig_block_len,
7129 BTRFS_COMPRESS_NONE, /* compress_type */
7134 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7135 len, block_len, type);
7138 free_extent_map(em);
7139 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7140 start + len - 1, 0);
7149 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7152 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7153 struct btrfs_root *root = BTRFS_I(inode)->root;
7154 struct extent_map *em;
7155 struct btrfs_key ins;
7159 alloc_hint = get_extent_allocation_hint(inode, start, len);
7160 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7161 0, alloc_hint, &ins, 1, 1);
7163 return ERR_PTR(ret);
7165 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7166 ins.objectid, ins.offset, ins.offset,
7167 ins.offset, BTRFS_ORDERED_REGULAR);
7168 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7170 btrfs_free_reserved_extent(fs_info, ins.objectid,
7177 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7178 * block must be cow'd
7180 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7181 u64 *orig_start, u64 *orig_block_len,
7184 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7185 struct btrfs_path *path;
7187 struct extent_buffer *leaf;
7188 struct btrfs_root *root = BTRFS_I(inode)->root;
7189 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7190 struct btrfs_file_extent_item *fi;
7191 struct btrfs_key key;
7198 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7200 path = btrfs_alloc_path();
7204 ret = btrfs_lookup_file_extent(NULL, root, path,
7205 btrfs_ino(BTRFS_I(inode)), offset, 0);
7209 slot = path->slots[0];
7212 /* can't find the item, must cow */
7219 leaf = path->nodes[0];
7220 btrfs_item_key_to_cpu(leaf, &key, slot);
7221 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7222 key.type != BTRFS_EXTENT_DATA_KEY) {
7223 /* not our file or wrong item type, must cow */
7227 if (key.offset > offset) {
7228 /* Wrong offset, must cow */
7232 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7233 found_type = btrfs_file_extent_type(leaf, fi);
7234 if (found_type != BTRFS_FILE_EXTENT_REG &&
7235 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7236 /* not a regular extent, must cow */
7240 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7243 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7244 if (extent_end <= offset)
7247 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7248 if (disk_bytenr == 0)
7251 if (btrfs_file_extent_compression(leaf, fi) ||
7252 btrfs_file_extent_encryption(leaf, fi) ||
7253 btrfs_file_extent_other_encoding(leaf, fi))
7257 * Do the same check as in btrfs_cross_ref_exist but without the
7258 * unnecessary search.
7260 if (btrfs_file_extent_generation(leaf, fi) <=
7261 btrfs_root_last_snapshot(&root->root_item))
7264 backref_offset = btrfs_file_extent_offset(leaf, fi);
7267 *orig_start = key.offset - backref_offset;
7268 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7269 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7272 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7275 num_bytes = min(offset + *len, extent_end) - offset;
7276 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7279 range_end = round_up(offset + num_bytes,
7280 root->fs_info->sectorsize) - 1;
7281 ret = test_range_bit(io_tree, offset, range_end,
7282 EXTENT_DELALLOC, 0, NULL);
7289 btrfs_release_path(path);
7292 * look for other files referencing this extent, if we
7293 * find any we must cow
7296 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7297 key.offset - backref_offset, disk_bytenr);
7304 * adjust disk_bytenr and num_bytes to cover just the bytes
7305 * in this extent we are about to write. If there
7306 * are any csums in that range we have to cow in order
7307 * to keep the csums correct
7309 disk_bytenr += backref_offset;
7310 disk_bytenr += offset - key.offset;
7311 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7314 * all of the above have passed, it is safe to overwrite this extent
7320 btrfs_free_path(path);
7324 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7325 struct extent_state **cached_state, int writing)
7327 struct btrfs_ordered_extent *ordered;
7331 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7334 * We're concerned with the entire range that we're going to be
7335 * doing DIO to, so we need to make sure there's no ordered
7336 * extents in this range.
7338 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7339 lockend - lockstart + 1);
7342 * We need to make sure there are no buffered pages in this
7343 * range either, we could have raced between the invalidate in
7344 * generic_file_direct_write and locking the extent. The
7345 * invalidate needs to happen so that reads after a write do not
7349 (!writing || !filemap_range_has_page(inode->i_mapping,
7350 lockstart, lockend)))
7353 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7358 * If we are doing a DIO read and the ordered extent we
7359 * found is for a buffered write, we can not wait for it
7360 * to complete and retry, because if we do so we can
7361 * deadlock with concurrent buffered writes on page
7362 * locks. This happens only if our DIO read covers more
7363 * than one extent map, if at this point has already
7364 * created an ordered extent for a previous extent map
7365 * and locked its range in the inode's io tree, and a
7366 * concurrent write against that previous extent map's
7367 * range and this range started (we unlock the ranges
7368 * in the io tree only when the bios complete and
7369 * buffered writes always lock pages before attempting
7370 * to lock range in the io tree).
7373 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7374 btrfs_start_ordered_extent(inode, ordered, 1);
7377 btrfs_put_ordered_extent(ordered);
7380 * We could trigger writeback for this range (and wait
7381 * for it to complete) and then invalidate the pages for
7382 * this range (through invalidate_inode_pages2_range()),
7383 * but that can lead us to a deadlock with a concurrent
7384 * call to readpages() (a buffered read or a defrag call
7385 * triggered a readahead) on a page lock due to an
7386 * ordered dio extent we created before but did not have
7387 * yet a corresponding bio submitted (whence it can not
7388 * complete), which makes readpages() wait for that
7389 * ordered extent to complete while holding a lock on
7404 /* The callers of this must take lock_extent() */
7405 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7406 u64 orig_start, u64 block_start,
7407 u64 block_len, u64 orig_block_len,
7408 u64 ram_bytes, int compress_type,
7411 struct extent_map_tree *em_tree;
7412 struct extent_map *em;
7413 struct btrfs_root *root = BTRFS_I(inode)->root;
7416 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7417 type == BTRFS_ORDERED_COMPRESSED ||
7418 type == BTRFS_ORDERED_NOCOW ||
7419 type == BTRFS_ORDERED_REGULAR);
7421 em_tree = &BTRFS_I(inode)->extent_tree;
7422 em = alloc_extent_map();
7424 return ERR_PTR(-ENOMEM);
7427 em->orig_start = orig_start;
7429 em->block_len = block_len;
7430 em->block_start = block_start;
7431 em->bdev = root->fs_info->fs_devices->latest_bdev;
7432 em->orig_block_len = orig_block_len;
7433 em->ram_bytes = ram_bytes;
7434 em->generation = -1;
7435 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7436 if (type == BTRFS_ORDERED_PREALLOC) {
7437 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7438 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7439 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7440 em->compress_type = compress_type;
7444 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7445 em->start + em->len - 1, 0);
7446 write_lock(&em_tree->lock);
7447 ret = add_extent_mapping(em_tree, em, 1);
7448 write_unlock(&em_tree->lock);
7450 * The caller has taken lock_extent(), who could race with us
7453 } while (ret == -EEXIST);
7456 free_extent_map(em);
7457 return ERR_PTR(ret);
7460 /* em got 2 refs now, callers needs to do free_extent_map once. */
7465 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7466 struct buffer_head *bh_result,
7467 struct inode *inode,
7470 if (em->block_start == EXTENT_MAP_HOLE ||
7471 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7474 len = min(len, em->len - (start - em->start));
7476 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7478 bh_result->b_size = len;
7479 bh_result->b_bdev = em->bdev;
7480 set_buffer_mapped(bh_result);
7485 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7486 struct buffer_head *bh_result,
7487 struct inode *inode,
7488 struct btrfs_dio_data *dio_data,
7491 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7492 struct extent_map *em = *map;
7496 * We don't allocate a new extent in the following cases
7498 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7500 * 2) The extent is marked as PREALLOC. We're good to go here and can
7501 * just use the extent.
7504 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7505 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7506 em->block_start != EXTENT_MAP_HOLE)) {
7508 u64 block_start, orig_start, orig_block_len, ram_bytes;
7510 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7511 type = BTRFS_ORDERED_PREALLOC;
7513 type = BTRFS_ORDERED_NOCOW;
7514 len = min(len, em->len - (start - em->start));
7515 block_start = em->block_start + (start - em->start);
7517 if (can_nocow_extent(inode, start, &len, &orig_start,
7518 &orig_block_len, &ram_bytes) == 1 &&
7519 btrfs_inc_nocow_writers(fs_info, block_start)) {
7520 struct extent_map *em2;
7522 em2 = btrfs_create_dio_extent(inode, start, len,
7523 orig_start, block_start,
7524 len, orig_block_len,
7526 btrfs_dec_nocow_writers(fs_info, block_start);
7527 if (type == BTRFS_ORDERED_PREALLOC) {
7528 free_extent_map(em);
7532 if (em2 && IS_ERR(em2)) {
7537 * For inode marked NODATACOW or extent marked PREALLOC,
7538 * use the existing or preallocated extent, so does not
7539 * need to adjust btrfs_space_info's bytes_may_use.
7541 btrfs_free_reserved_data_space_noquota(inode, start,
7547 /* this will cow the extent */
7548 len = bh_result->b_size;
7549 free_extent_map(em);
7550 *map = em = btrfs_new_extent_direct(inode, start, len);
7556 len = min(len, em->len - (start - em->start));
7559 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7561 bh_result->b_size = len;
7562 bh_result->b_bdev = em->bdev;
7563 set_buffer_mapped(bh_result);
7565 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7566 set_buffer_new(bh_result);
7569 * Need to update the i_size under the extent lock so buffered
7570 * readers will get the updated i_size when we unlock.
7572 if (!dio_data->overwrite && start + len > i_size_read(inode))
7573 i_size_write(inode, start + len);
7575 WARN_ON(dio_data->reserve < len);
7576 dio_data->reserve -= len;
7577 dio_data->unsubmitted_oe_range_end = start + len;
7578 current->journal_info = dio_data;
7583 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7584 struct buffer_head *bh_result, int create)
7586 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7587 struct extent_map *em;
7588 struct extent_state *cached_state = NULL;
7589 struct btrfs_dio_data *dio_data = NULL;
7590 u64 start = iblock << inode->i_blkbits;
7591 u64 lockstart, lockend;
7592 u64 len = bh_result->b_size;
7593 int unlock_bits = EXTENT_LOCKED;
7597 unlock_bits |= EXTENT_DIRTY;
7599 len = min_t(u64, len, fs_info->sectorsize);
7602 lockend = start + len - 1;
7604 if (current->journal_info) {
7606 * Need to pull our outstanding extents and set journal_info to NULL so
7607 * that anything that needs to check if there's a transaction doesn't get
7610 dio_data = current->journal_info;
7611 current->journal_info = NULL;
7615 * If this errors out it's because we couldn't invalidate pagecache for
7616 * this range and we need to fallback to buffered.
7618 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7624 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7631 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7632 * io. INLINE is special, and we could probably kludge it in here, but
7633 * it's still buffered so for safety lets just fall back to the generic
7636 * For COMPRESSED we _have_ to read the entire extent in so we can
7637 * decompress it, so there will be buffering required no matter what we
7638 * do, so go ahead and fallback to buffered.
7640 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7641 * to buffered IO. Don't blame me, this is the price we pay for using
7644 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7645 em->block_start == EXTENT_MAP_INLINE) {
7646 free_extent_map(em);
7652 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7653 dio_data, start, len);
7657 /* clear and unlock the entire range */
7658 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7659 unlock_bits, 1, 0, &cached_state);
7661 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7663 /* Can be negative only if we read from a hole */
7666 free_extent_map(em);
7670 * We need to unlock only the end area that we aren't using.
7671 * The rest is going to be unlocked by the endio routine.
7673 lockstart = start + bh_result->b_size;
7674 if (lockstart < lockend) {
7675 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7676 lockend, unlock_bits, 1, 0,
7679 free_extent_state(cached_state);
7683 free_extent_map(em);
7688 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7689 unlock_bits, 1, 0, &cached_state);
7692 current->journal_info = dio_data;
7696 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7700 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7703 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7705 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7709 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7714 static int btrfs_check_dio_repairable(struct inode *inode,
7715 struct bio *failed_bio,
7716 struct io_failure_record *failrec,
7719 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7722 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7723 if (num_copies == 1) {
7725 * we only have a single copy of the data, so don't bother with
7726 * all the retry and error correction code that follows. no
7727 * matter what the error is, it is very likely to persist.
7729 btrfs_debug(fs_info,
7730 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7731 num_copies, failrec->this_mirror, failed_mirror);
7735 failrec->failed_mirror = failed_mirror;
7736 failrec->this_mirror++;
7737 if (failrec->this_mirror == failed_mirror)
7738 failrec->this_mirror++;
7740 if (failrec->this_mirror > num_copies) {
7741 btrfs_debug(fs_info,
7742 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7743 num_copies, failrec->this_mirror, failed_mirror);
7750 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7751 struct page *page, unsigned int pgoff,
7752 u64 start, u64 end, int failed_mirror,
7753 bio_end_io_t *repair_endio, void *repair_arg)
7755 struct io_failure_record *failrec;
7756 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7757 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7760 unsigned int read_mode = 0;
7763 blk_status_t status;
7764 struct bio_vec bvec;
7766 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7768 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7770 return errno_to_blk_status(ret);
7772 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7775 free_io_failure(failure_tree, io_tree, failrec);
7776 return BLK_STS_IOERR;
7779 segs = bio_segments(failed_bio);
7780 bio_get_first_bvec(failed_bio, &bvec);
7782 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7783 read_mode |= REQ_FAILFAST_DEV;
7785 isector = start - btrfs_io_bio(failed_bio)->logical;
7786 isector >>= inode->i_sb->s_blocksize_bits;
7787 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7788 pgoff, isector, repair_endio, repair_arg);
7789 bio->bi_opf = REQ_OP_READ | read_mode;
7791 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7792 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7793 read_mode, failrec->this_mirror, failrec->in_validation);
7795 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7797 free_io_failure(failure_tree, io_tree, failrec);
7804 struct btrfs_retry_complete {
7805 struct completion done;
7806 struct inode *inode;
7811 static void btrfs_retry_endio_nocsum(struct bio *bio)
7813 struct btrfs_retry_complete *done = bio->bi_private;
7814 struct inode *inode = done->inode;
7815 struct bio_vec *bvec;
7816 struct extent_io_tree *io_tree, *failure_tree;
7822 ASSERT(bio->bi_vcnt == 1);
7823 io_tree = &BTRFS_I(inode)->io_tree;
7824 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7825 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7828 ASSERT(!bio_flagged(bio, BIO_CLONED));
7829 bio_for_each_segment_all(bvec, bio, i)
7830 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7831 io_tree, done->start, bvec->bv_page,
7832 btrfs_ino(BTRFS_I(inode)), 0);
7834 complete(&done->done);
7838 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7839 struct btrfs_io_bio *io_bio)
7841 struct btrfs_fs_info *fs_info;
7842 struct bio_vec bvec;
7843 struct bvec_iter iter;
7844 struct btrfs_retry_complete done;
7850 blk_status_t err = BLK_STS_OK;
7852 fs_info = BTRFS_I(inode)->root->fs_info;
7853 sectorsize = fs_info->sectorsize;
7855 start = io_bio->logical;
7857 io_bio->bio.bi_iter = io_bio->iter;
7859 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7860 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7861 pgoff = bvec.bv_offset;
7863 next_block_or_try_again:
7866 init_completion(&done.done);
7868 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7869 pgoff, start, start + sectorsize - 1,
7871 btrfs_retry_endio_nocsum, &done);
7877 wait_for_completion_io(&done.done);
7879 if (!done.uptodate) {
7880 /* We might have another mirror, so try again */
7881 goto next_block_or_try_again;
7885 start += sectorsize;
7889 pgoff += sectorsize;
7890 ASSERT(pgoff < PAGE_SIZE);
7891 goto next_block_or_try_again;
7898 static void btrfs_retry_endio(struct bio *bio)
7900 struct btrfs_retry_complete *done = bio->bi_private;
7901 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7902 struct extent_io_tree *io_tree, *failure_tree;
7903 struct inode *inode = done->inode;
7904 struct bio_vec *bvec;
7914 ASSERT(bio->bi_vcnt == 1);
7915 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7917 io_tree = &BTRFS_I(inode)->io_tree;
7918 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7920 ASSERT(!bio_flagged(bio, BIO_CLONED));
7921 bio_for_each_segment_all(bvec, bio, i) {
7922 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7923 bvec->bv_offset, done->start,
7926 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7927 failure_tree, io_tree, done->start,
7929 btrfs_ino(BTRFS_I(inode)),
7935 done->uptodate = uptodate;
7937 complete(&done->done);
7941 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7942 struct btrfs_io_bio *io_bio, blk_status_t err)
7944 struct btrfs_fs_info *fs_info;
7945 struct bio_vec bvec;
7946 struct bvec_iter iter;
7947 struct btrfs_retry_complete done;
7954 bool uptodate = (err == 0);
7956 blk_status_t status;
7958 fs_info = BTRFS_I(inode)->root->fs_info;
7959 sectorsize = fs_info->sectorsize;
7962 start = io_bio->logical;
7964 io_bio->bio.bi_iter = io_bio->iter;
7966 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7967 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7969 pgoff = bvec.bv_offset;
7972 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7973 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7974 bvec.bv_page, pgoff, start, sectorsize);
7981 init_completion(&done.done);
7983 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7984 pgoff, start, start + sectorsize - 1,
7985 io_bio->mirror_num, btrfs_retry_endio,
7992 wait_for_completion_io(&done.done);
7994 if (!done.uptodate) {
7995 /* We might have another mirror, so try again */
7999 offset += sectorsize;
8000 start += sectorsize;
8006 pgoff += sectorsize;
8007 ASSERT(pgoff < PAGE_SIZE);
8015 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8016 struct btrfs_io_bio *io_bio, blk_status_t err)
8018 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8022 return __btrfs_correct_data_nocsum(inode, io_bio);
8026 return __btrfs_subio_endio_read(inode, io_bio, err);
8030 static void btrfs_endio_direct_read(struct bio *bio)
8032 struct btrfs_dio_private *dip = bio->bi_private;
8033 struct inode *inode = dip->inode;
8034 struct bio *dio_bio;
8035 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8036 blk_status_t err = bio->bi_status;
8038 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8039 err = btrfs_subio_endio_read(inode, io_bio, err);
8041 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8042 dip->logical_offset + dip->bytes - 1);
8043 dio_bio = dip->dio_bio;
8047 dio_bio->bi_status = err;
8048 dio_end_io(dio_bio);
8051 io_bio->end_io(io_bio, blk_status_to_errno(err));
8055 static void __endio_write_update_ordered(struct inode *inode,
8056 const u64 offset, const u64 bytes,
8057 const bool uptodate)
8059 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8060 struct btrfs_ordered_extent *ordered = NULL;
8061 struct btrfs_workqueue *wq;
8062 btrfs_work_func_t func;
8063 u64 ordered_offset = offset;
8064 u64 ordered_bytes = bytes;
8067 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8068 wq = fs_info->endio_freespace_worker;
8069 func = btrfs_freespace_write_helper;
8071 wq = fs_info->endio_write_workers;
8072 func = btrfs_endio_write_helper;
8075 while (ordered_offset < offset + bytes) {
8076 last_offset = ordered_offset;
8077 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8081 btrfs_init_work(&ordered->work, func,
8084 btrfs_queue_work(wq, &ordered->work);
8087 * If btrfs_dec_test_ordered_pending does not find any ordered
8088 * extent in the range, we can exit.
8090 if (ordered_offset == last_offset)
8093 * Our bio might span multiple ordered extents. In this case
8094 * we keep goin until we have accounted the whole dio.
8096 if (ordered_offset < offset + bytes) {
8097 ordered_bytes = offset + bytes - ordered_offset;
8103 static void btrfs_endio_direct_write(struct bio *bio)
8105 struct btrfs_dio_private *dip = bio->bi_private;
8106 struct bio *dio_bio = dip->dio_bio;
8108 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8109 dip->bytes, !bio->bi_status);
8113 dio_bio->bi_status = bio->bi_status;
8114 dio_end_io(dio_bio);
8118 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8119 struct bio *bio, u64 offset)
8121 struct inode *inode = private_data;
8123 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8124 BUG_ON(ret); /* -ENOMEM */
8128 static void btrfs_end_dio_bio(struct bio *bio)
8130 struct btrfs_dio_private *dip = bio->bi_private;
8131 blk_status_t err = bio->bi_status;
8134 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8135 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8136 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8138 (unsigned long long)bio->bi_iter.bi_sector,
8139 bio->bi_iter.bi_size, err);
8141 if (dip->subio_endio)
8142 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8146 * We want to perceive the errors flag being set before
8147 * decrementing the reference count. We don't need a barrier
8148 * since atomic operations with a return value are fully
8149 * ordered as per atomic_t.txt
8154 /* if there are more bios still pending for this dio, just exit */
8155 if (!atomic_dec_and_test(&dip->pending_bios))
8159 bio_io_error(dip->orig_bio);
8161 dip->dio_bio->bi_status = BLK_STS_OK;
8162 bio_endio(dip->orig_bio);
8168 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8169 struct btrfs_dio_private *dip,
8173 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8174 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8178 * We load all the csum data we need when we submit
8179 * the first bio to reduce the csum tree search and
8182 if (dip->logical_offset == file_offset) {
8183 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8189 if (bio == dip->orig_bio)
8192 file_offset -= dip->logical_offset;
8193 file_offset >>= inode->i_sb->s_blocksize_bits;
8194 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8199 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8200 struct inode *inode, u64 file_offset, int async_submit)
8202 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8203 struct btrfs_dio_private *dip = bio->bi_private;
8204 bool write = bio_op(bio) == REQ_OP_WRITE;
8207 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8209 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8212 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8217 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8220 if (write && async_submit) {
8221 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8223 btrfs_submit_bio_start_direct_io);
8227 * If we aren't doing async submit, calculate the csum of the
8230 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8234 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8240 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8245 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8247 struct inode *inode = dip->inode;
8248 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8250 struct bio *orig_bio = dip->orig_bio;
8251 u64 start_sector = orig_bio->bi_iter.bi_sector;
8252 u64 file_offset = dip->logical_offset;
8254 int async_submit = 0;
8256 int clone_offset = 0;
8259 blk_status_t status;
8261 map_length = orig_bio->bi_iter.bi_size;
8262 submit_len = map_length;
8263 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8264 &map_length, NULL, 0);
8268 if (map_length >= submit_len) {
8270 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8274 /* async crcs make it difficult to collect full stripe writes. */
8275 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8281 ASSERT(map_length <= INT_MAX);
8282 atomic_inc(&dip->pending_bios);
8284 clone_len = min_t(int, submit_len, map_length);
8287 * This will never fail as it's passing GPF_NOFS and
8288 * the allocation is backed by btrfs_bioset.
8290 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8292 bio->bi_private = dip;
8293 bio->bi_end_io = btrfs_end_dio_bio;
8294 btrfs_io_bio(bio)->logical = file_offset;
8296 ASSERT(submit_len >= clone_len);
8297 submit_len -= clone_len;
8298 if (submit_len == 0)
8302 * Increase the count before we submit the bio so we know
8303 * the end IO handler won't happen before we increase the
8304 * count. Otherwise, the dip might get freed before we're
8305 * done setting it up.
8307 atomic_inc(&dip->pending_bios);
8309 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8313 atomic_dec(&dip->pending_bios);
8317 clone_offset += clone_len;
8318 start_sector += clone_len >> 9;
8319 file_offset += clone_len;
8321 map_length = submit_len;
8322 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8323 start_sector << 9, &map_length, NULL, 0);
8326 } while (submit_len > 0);
8329 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8337 * Before atomic variable goto zero, we must make sure dip->errors is
8338 * perceived to be set. This ordering is ensured by the fact that an
8339 * atomic operations with a return value are fully ordered as per
8342 if (atomic_dec_and_test(&dip->pending_bios))
8343 bio_io_error(dip->orig_bio);
8345 /* bio_end_io() will handle error, so we needn't return it */
8349 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8352 struct btrfs_dio_private *dip = NULL;
8353 struct bio *bio = NULL;
8354 struct btrfs_io_bio *io_bio;
8355 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8358 bio = btrfs_bio_clone(dio_bio);
8360 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8366 dip->private = dio_bio->bi_private;
8368 dip->logical_offset = file_offset;
8369 dip->bytes = dio_bio->bi_iter.bi_size;
8370 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8371 bio->bi_private = dip;
8372 dip->orig_bio = bio;
8373 dip->dio_bio = dio_bio;
8374 atomic_set(&dip->pending_bios, 0);
8375 io_bio = btrfs_io_bio(bio);
8376 io_bio->logical = file_offset;
8379 bio->bi_end_io = btrfs_endio_direct_write;
8381 bio->bi_end_io = btrfs_endio_direct_read;
8382 dip->subio_endio = btrfs_subio_endio_read;
8386 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8387 * even if we fail to submit a bio, because in such case we do the
8388 * corresponding error handling below and it must not be done a second
8389 * time by btrfs_direct_IO().
8392 struct btrfs_dio_data *dio_data = current->journal_info;
8394 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8396 dio_data->unsubmitted_oe_range_start =
8397 dio_data->unsubmitted_oe_range_end;
8400 ret = btrfs_submit_direct_hook(dip);
8405 io_bio->end_io(io_bio, ret);
8409 * If we arrived here it means either we failed to submit the dip
8410 * or we either failed to clone the dio_bio or failed to allocate the
8411 * dip. If we cloned the dio_bio and allocated the dip, we can just
8412 * call bio_endio against our io_bio so that we get proper resource
8413 * cleanup if we fail to submit the dip, otherwise, we must do the
8414 * same as btrfs_endio_direct_[write|read] because we can't call these
8415 * callbacks - they require an allocated dip and a clone of dio_bio.
8420 * The end io callbacks free our dip, do the final put on bio
8421 * and all the cleanup and final put for dio_bio (through
8428 __endio_write_update_ordered(inode,
8430 dio_bio->bi_iter.bi_size,
8433 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8434 file_offset + dio_bio->bi_iter.bi_size - 1);
8436 dio_bio->bi_status = BLK_STS_IOERR;
8438 * Releases and cleans up our dio_bio, no need to bio_put()
8439 * nor bio_endio()/bio_io_error() against dio_bio.
8441 dio_end_io(dio_bio);
8448 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8449 const struct iov_iter *iter, loff_t offset)
8453 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8454 ssize_t retval = -EINVAL;
8456 if (offset & blocksize_mask)
8459 if (iov_iter_alignment(iter) & blocksize_mask)
8462 /* If this is a write we don't need to check anymore */
8463 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8466 * Check to make sure we don't have duplicate iov_base's in this
8467 * iovec, if so return EINVAL, otherwise we'll get csum errors
8468 * when reading back.
8470 for (seg = 0; seg < iter->nr_segs; seg++) {
8471 for (i = seg + 1; i < iter->nr_segs; i++) {
8472 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8481 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8483 struct file *file = iocb->ki_filp;
8484 struct inode *inode = file->f_mapping->host;
8485 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8486 struct btrfs_dio_data dio_data = { 0 };
8487 struct extent_changeset *data_reserved = NULL;
8488 loff_t offset = iocb->ki_pos;
8492 bool relock = false;
8495 if (check_direct_IO(fs_info, iter, offset))
8498 inode_dio_begin(inode);
8501 * The generic stuff only does filemap_write_and_wait_range, which
8502 * isn't enough if we've written compressed pages to this area, so
8503 * we need to flush the dirty pages again to make absolutely sure
8504 * that any outstanding dirty pages are on disk.
8506 count = iov_iter_count(iter);
8507 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8508 &BTRFS_I(inode)->runtime_flags))
8509 filemap_fdatawrite_range(inode->i_mapping, offset,
8510 offset + count - 1);
8512 if (iov_iter_rw(iter) == WRITE) {
8514 * If the write DIO is beyond the EOF, we need update
8515 * the isize, but it is protected by i_mutex. So we can
8516 * not unlock the i_mutex at this case.
8518 if (offset + count <= inode->i_size) {
8519 dio_data.overwrite = 1;
8520 inode_unlock(inode);
8522 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8526 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8532 * We need to know how many extents we reserved so that we can
8533 * do the accounting properly if we go over the number we
8534 * originally calculated. Abuse current->journal_info for this.
8536 dio_data.reserve = round_up(count,
8537 fs_info->sectorsize);
8538 dio_data.unsubmitted_oe_range_start = (u64)offset;
8539 dio_data.unsubmitted_oe_range_end = (u64)offset;
8540 current->journal_info = &dio_data;
8541 down_read(&BTRFS_I(inode)->dio_sem);
8542 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8543 &BTRFS_I(inode)->runtime_flags)) {
8544 inode_dio_end(inode);
8545 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8549 ret = __blockdev_direct_IO(iocb, inode,
8550 fs_info->fs_devices->latest_bdev,
8551 iter, btrfs_get_blocks_direct, NULL,
8552 btrfs_submit_direct, flags);
8553 if (iov_iter_rw(iter) == WRITE) {
8554 up_read(&BTRFS_I(inode)->dio_sem);
8555 current->journal_info = NULL;
8556 if (ret < 0 && ret != -EIOCBQUEUED) {
8557 if (dio_data.reserve)
8558 btrfs_delalloc_release_space(inode, data_reserved,
8559 offset, dio_data.reserve, true);
8561 * On error we might have left some ordered extents
8562 * without submitting corresponding bios for them, so
8563 * cleanup them up to avoid other tasks getting them
8564 * and waiting for them to complete forever.
8566 if (dio_data.unsubmitted_oe_range_start <
8567 dio_data.unsubmitted_oe_range_end)
8568 __endio_write_update_ordered(inode,
8569 dio_data.unsubmitted_oe_range_start,
8570 dio_data.unsubmitted_oe_range_end -
8571 dio_data.unsubmitted_oe_range_start,
8573 } else if (ret >= 0 && (size_t)ret < count)
8574 btrfs_delalloc_release_space(inode, data_reserved,
8575 offset, count - (size_t)ret, true);
8576 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8580 inode_dio_end(inode);
8584 extent_changeset_free(data_reserved);
8588 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8590 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8591 __u64 start, __u64 len)
8595 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8599 return extent_fiemap(inode, fieinfo, start, len);
8602 int btrfs_readpage(struct file *file, struct page *page)
8604 struct extent_io_tree *tree;
8605 tree = &BTRFS_I(page->mapping->host)->io_tree;
8606 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8609 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8611 struct inode *inode = page->mapping->host;
8614 if (current->flags & PF_MEMALLOC) {
8615 redirty_page_for_writepage(wbc, page);
8621 * If we are under memory pressure we will call this directly from the
8622 * VM, we need to make sure we have the inode referenced for the ordered
8623 * extent. If not just return like we didn't do anything.
8625 if (!igrab(inode)) {
8626 redirty_page_for_writepage(wbc, page);
8627 return AOP_WRITEPAGE_ACTIVATE;
8629 ret = extent_write_full_page(page, wbc);
8630 btrfs_add_delayed_iput(inode);
8634 static int btrfs_writepages(struct address_space *mapping,
8635 struct writeback_control *wbc)
8637 return extent_writepages(mapping, wbc);
8641 btrfs_readpages(struct file *file, struct address_space *mapping,
8642 struct list_head *pages, unsigned nr_pages)
8644 return extent_readpages(mapping, pages, nr_pages);
8647 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8649 int ret = try_release_extent_mapping(page, gfp_flags);
8651 ClearPagePrivate(page);
8652 set_page_private(page, 0);
8658 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8660 if (PageWriteback(page) || PageDirty(page))
8662 return __btrfs_releasepage(page, gfp_flags);
8665 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8666 unsigned int length)
8668 struct inode *inode = page->mapping->host;
8669 struct extent_io_tree *tree;
8670 struct btrfs_ordered_extent *ordered;
8671 struct extent_state *cached_state = NULL;
8672 u64 page_start = page_offset(page);
8673 u64 page_end = page_start + PAGE_SIZE - 1;
8676 int inode_evicting = inode->i_state & I_FREEING;
8679 * we have the page locked, so new writeback can't start,
8680 * and the dirty bit won't be cleared while we are here.
8682 * Wait for IO on this page so that we can safely clear
8683 * the PagePrivate2 bit and do ordered accounting
8685 wait_on_page_writeback(page);
8687 tree = &BTRFS_I(inode)->io_tree;
8689 btrfs_releasepage(page, GFP_NOFS);
8693 if (!inode_evicting)
8694 lock_extent_bits(tree, page_start, page_end, &cached_state);
8697 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8698 page_end - start + 1);
8700 end = min(page_end, ordered->file_offset + ordered->len - 1);
8702 * IO on this page will never be started, so we need
8703 * to account for any ordered extents now
8705 if (!inode_evicting)
8706 clear_extent_bit(tree, start, end,
8707 EXTENT_DIRTY | EXTENT_DELALLOC |
8708 EXTENT_DELALLOC_NEW |
8709 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8710 EXTENT_DEFRAG, 1, 0, &cached_state);
8712 * whoever cleared the private bit is responsible
8713 * for the finish_ordered_io
8715 if (TestClearPagePrivate2(page)) {
8716 struct btrfs_ordered_inode_tree *tree;
8719 tree = &BTRFS_I(inode)->ordered_tree;
8721 spin_lock_irq(&tree->lock);
8722 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8723 new_len = start - ordered->file_offset;
8724 if (new_len < ordered->truncated_len)
8725 ordered->truncated_len = new_len;
8726 spin_unlock_irq(&tree->lock);
8728 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8730 end - start + 1, 1))
8731 btrfs_finish_ordered_io(ordered);
8733 btrfs_put_ordered_extent(ordered);
8734 if (!inode_evicting) {
8735 cached_state = NULL;
8736 lock_extent_bits(tree, start, end,
8741 if (start < page_end)
8746 * Qgroup reserved space handler
8747 * Page here will be either
8748 * 1) Already written to disk
8749 * In this case, its reserved space is released from data rsv map
8750 * and will be freed by delayed_ref handler finally.
8751 * So even we call qgroup_free_data(), it won't decrease reserved
8753 * 2) Not written to disk
8754 * This means the reserved space should be freed here. However,
8755 * if a truncate invalidates the page (by clearing PageDirty)
8756 * and the page is accounted for while allocating extent
8757 * in btrfs_check_data_free_space() we let delayed_ref to
8758 * free the entire extent.
8760 if (PageDirty(page))
8761 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8762 if (!inode_evicting) {
8763 clear_extent_bit(tree, page_start, page_end,
8764 EXTENT_LOCKED | EXTENT_DIRTY |
8765 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8766 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8769 __btrfs_releasepage(page, GFP_NOFS);
8772 ClearPageChecked(page);
8773 if (PagePrivate(page)) {
8774 ClearPagePrivate(page);
8775 set_page_private(page, 0);
8781 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8782 * called from a page fault handler when a page is first dirtied. Hence we must
8783 * be careful to check for EOF conditions here. We set the page up correctly
8784 * for a written page which means we get ENOSPC checking when writing into
8785 * holes and correct delalloc and unwritten extent mapping on filesystems that
8786 * support these features.
8788 * We are not allowed to take the i_mutex here so we have to play games to
8789 * protect against truncate races as the page could now be beyond EOF. Because
8790 * truncate_setsize() writes the inode size before removing pages, once we have
8791 * the page lock we can determine safely if the page is beyond EOF. If it is not
8792 * beyond EOF, then the page is guaranteed safe against truncation until we
8795 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8797 struct page *page = vmf->page;
8798 struct inode *inode = file_inode(vmf->vma->vm_file);
8799 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8800 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8801 struct btrfs_ordered_extent *ordered;
8802 struct extent_state *cached_state = NULL;
8803 struct extent_changeset *data_reserved = NULL;
8805 unsigned long zero_start;
8815 reserved_space = PAGE_SIZE;
8817 sb_start_pagefault(inode->i_sb);
8818 page_start = page_offset(page);
8819 page_end = page_start + PAGE_SIZE - 1;
8823 * Reserving delalloc space after obtaining the page lock can lead to
8824 * deadlock. For example, if a dirty page is locked by this function
8825 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8826 * dirty page write out, then the btrfs_writepage() function could
8827 * end up waiting indefinitely to get a lock on the page currently
8828 * being processed by btrfs_page_mkwrite() function.
8830 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8833 ret2 = file_update_time(vmf->vma->vm_file);
8837 ret = vmf_error(ret2);
8843 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8846 size = i_size_read(inode);
8848 if ((page->mapping != inode->i_mapping) ||
8849 (page_start >= size)) {
8850 /* page got truncated out from underneath us */
8853 wait_on_page_writeback(page);
8855 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8856 set_page_extent_mapped(page);
8859 * we can't set the delalloc bits if there are pending ordered
8860 * extents. Drop our locks and wait for them to finish
8862 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8865 unlock_extent_cached(io_tree, page_start, page_end,
8868 btrfs_start_ordered_extent(inode, ordered, 1);
8869 btrfs_put_ordered_extent(ordered);
8873 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8874 reserved_space = round_up(size - page_start,
8875 fs_info->sectorsize);
8876 if (reserved_space < PAGE_SIZE) {
8877 end = page_start + reserved_space - 1;
8878 btrfs_delalloc_release_space(inode, data_reserved,
8879 page_start, PAGE_SIZE - reserved_space,
8885 * page_mkwrite gets called when the page is firstly dirtied after it's
8886 * faulted in, but write(2) could also dirty a page and set delalloc
8887 * bits, thus in this case for space account reason, we still need to
8888 * clear any delalloc bits within this page range since we have to
8889 * reserve data&meta space before lock_page() (see above comments).
8891 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8892 EXTENT_DIRTY | EXTENT_DELALLOC |
8893 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8894 0, 0, &cached_state);
8896 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8899 unlock_extent_cached(io_tree, page_start, page_end,
8901 ret = VM_FAULT_SIGBUS;
8906 /* page is wholly or partially inside EOF */
8907 if (page_start + PAGE_SIZE > size)
8908 zero_start = size & ~PAGE_MASK;
8910 zero_start = PAGE_SIZE;
8912 if (zero_start != PAGE_SIZE) {
8914 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8915 flush_dcache_page(page);
8918 ClearPageChecked(page);
8919 set_page_dirty(page);
8920 SetPageUptodate(page);
8922 BTRFS_I(inode)->last_trans = fs_info->generation;
8923 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8924 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8926 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8929 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8930 sb_end_pagefault(inode->i_sb);
8931 extent_changeset_free(data_reserved);
8932 return VM_FAULT_LOCKED;
8938 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8939 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8940 reserved_space, (ret != 0));
8942 sb_end_pagefault(inode->i_sb);
8943 extent_changeset_free(data_reserved);
8947 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8949 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8950 struct btrfs_root *root = BTRFS_I(inode)->root;
8951 struct btrfs_block_rsv *rsv;
8953 struct btrfs_trans_handle *trans;
8954 u64 mask = fs_info->sectorsize - 1;
8955 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
8957 if (!skip_writeback) {
8958 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8965 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8966 * things going on here:
8968 * 1) We need to reserve space to update our inode.
8970 * 2) We need to have something to cache all the space that is going to
8971 * be free'd up by the truncate operation, but also have some slack
8972 * space reserved in case it uses space during the truncate (thank you
8973 * very much snapshotting).
8975 * And we need these to be separate. The fact is we can use a lot of
8976 * space doing the truncate, and we have no earthly idea how much space
8977 * we will use, so we need the truncate reservation to be separate so it
8978 * doesn't end up using space reserved for updating the inode. We also
8979 * need to be able to stop the transaction and start a new one, which
8980 * means we need to be able to update the inode several times, and we
8981 * have no idea of knowing how many times that will be, so we can't just
8982 * reserve 1 item for the entirety of the operation, so that has to be
8983 * done separately as well.
8985 * So that leaves us with
8987 * 1) rsv - for the truncate reservation, which we will steal from the
8988 * transaction reservation.
8989 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8990 * updating the inode.
8992 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8995 rsv->size = min_size;
8999 * 1 for the truncate slack space
9000 * 1 for updating the inode.
9002 trans = btrfs_start_transaction(root, 2);
9003 if (IS_ERR(trans)) {
9004 ret = PTR_ERR(trans);
9008 /* Migrate the slack space for the truncate to our reserve */
9009 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9014 * So if we truncate and then write and fsync we normally would just
9015 * write the extents that changed, which is a problem if we need to
9016 * first truncate that entire inode. So set this flag so we write out
9017 * all of the extents in the inode to the sync log so we're completely
9020 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9021 trans->block_rsv = rsv;
9024 ret = btrfs_truncate_inode_items(trans, root, inode,
9026 BTRFS_EXTENT_DATA_KEY);
9027 trans->block_rsv = &fs_info->trans_block_rsv;
9028 if (ret != -ENOSPC && ret != -EAGAIN)
9031 ret = btrfs_update_inode(trans, root, inode);
9035 btrfs_end_transaction(trans);
9036 btrfs_btree_balance_dirty(fs_info);
9038 trans = btrfs_start_transaction(root, 2);
9039 if (IS_ERR(trans)) {
9040 ret = PTR_ERR(trans);
9045 btrfs_block_rsv_release(fs_info, rsv, -1);
9046 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9047 rsv, min_size, false);
9048 BUG_ON(ret); /* shouldn't happen */
9049 trans->block_rsv = rsv;
9053 * We can't call btrfs_truncate_block inside a trans handle as we could
9054 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9055 * we've truncated everything except the last little bit, and can do
9056 * btrfs_truncate_block and then update the disk_i_size.
9058 if (ret == NEED_TRUNCATE_BLOCK) {
9059 btrfs_end_transaction(trans);
9060 btrfs_btree_balance_dirty(fs_info);
9062 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9065 trans = btrfs_start_transaction(root, 1);
9066 if (IS_ERR(trans)) {
9067 ret = PTR_ERR(trans);
9070 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9076 trans->block_rsv = &fs_info->trans_block_rsv;
9077 ret2 = btrfs_update_inode(trans, root, inode);
9081 ret2 = btrfs_end_transaction(trans);
9084 btrfs_btree_balance_dirty(fs_info);
9087 btrfs_free_block_rsv(fs_info, rsv);
9093 * create a new subvolume directory/inode (helper for the ioctl).
9095 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9096 struct btrfs_root *new_root,
9097 struct btrfs_root *parent_root,
9100 struct inode *inode;
9104 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9105 new_dirid, new_dirid,
9106 S_IFDIR | (~current_umask() & S_IRWXUGO),
9109 return PTR_ERR(inode);
9110 inode->i_op = &btrfs_dir_inode_operations;
9111 inode->i_fop = &btrfs_dir_file_operations;
9113 set_nlink(inode, 1);
9114 btrfs_i_size_write(BTRFS_I(inode), 0);
9115 unlock_new_inode(inode);
9117 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9119 btrfs_err(new_root->fs_info,
9120 "error inheriting subvolume %llu properties: %d",
9121 new_root->root_key.objectid, err);
9123 err = btrfs_update_inode(trans, new_root, inode);
9129 struct inode *btrfs_alloc_inode(struct super_block *sb)
9131 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9132 struct btrfs_inode *ei;
9133 struct inode *inode;
9135 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9142 ei->last_sub_trans = 0;
9143 ei->logged_trans = 0;
9144 ei->delalloc_bytes = 0;
9145 ei->new_delalloc_bytes = 0;
9146 ei->defrag_bytes = 0;
9147 ei->disk_i_size = 0;
9150 ei->index_cnt = (u64)-1;
9152 ei->last_unlink_trans = 0;
9153 ei->last_log_commit = 0;
9155 spin_lock_init(&ei->lock);
9156 ei->outstanding_extents = 0;
9157 if (sb->s_magic != BTRFS_TEST_MAGIC)
9158 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9159 BTRFS_BLOCK_RSV_DELALLOC);
9160 ei->runtime_flags = 0;
9161 ei->prop_compress = BTRFS_COMPRESS_NONE;
9162 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9164 ei->delayed_node = NULL;
9166 ei->i_otime.tv_sec = 0;
9167 ei->i_otime.tv_nsec = 0;
9169 inode = &ei->vfs_inode;
9170 extent_map_tree_init(&ei->extent_tree);
9171 extent_io_tree_init(&ei->io_tree, inode);
9172 extent_io_tree_init(&ei->io_failure_tree, inode);
9173 ei->io_tree.track_uptodate = 1;
9174 ei->io_failure_tree.track_uptodate = 1;
9175 atomic_set(&ei->sync_writers, 0);
9176 mutex_init(&ei->log_mutex);
9177 mutex_init(&ei->delalloc_mutex);
9178 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9179 INIT_LIST_HEAD(&ei->delalloc_inodes);
9180 INIT_LIST_HEAD(&ei->delayed_iput);
9181 RB_CLEAR_NODE(&ei->rb_node);
9182 init_rwsem(&ei->dio_sem);
9187 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9188 void btrfs_test_destroy_inode(struct inode *inode)
9190 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9191 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9195 static void btrfs_i_callback(struct rcu_head *head)
9197 struct inode *inode = container_of(head, struct inode, i_rcu);
9198 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9201 void btrfs_destroy_inode(struct inode *inode)
9203 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9204 struct btrfs_ordered_extent *ordered;
9205 struct btrfs_root *root = BTRFS_I(inode)->root;
9207 WARN_ON(!hlist_empty(&inode->i_dentry));
9208 WARN_ON(inode->i_data.nrpages);
9209 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9210 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9211 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9212 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9213 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9214 WARN_ON(BTRFS_I(inode)->csum_bytes);
9215 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9218 * This can happen where we create an inode, but somebody else also
9219 * created the same inode and we need to destroy the one we already
9226 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9231 "found ordered extent %llu %llu on inode cleanup",
9232 ordered->file_offset, ordered->len);
9233 btrfs_remove_ordered_extent(inode, ordered);
9234 btrfs_put_ordered_extent(ordered);
9235 btrfs_put_ordered_extent(ordered);
9238 btrfs_qgroup_check_reserved_leak(inode);
9239 inode_tree_del(inode);
9240 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9242 call_rcu(&inode->i_rcu, btrfs_i_callback);
9245 int btrfs_drop_inode(struct inode *inode)
9247 struct btrfs_root *root = BTRFS_I(inode)->root;
9252 /* the snap/subvol tree is on deleting */
9253 if (btrfs_root_refs(&root->root_item) == 0)
9256 return generic_drop_inode(inode);
9259 static void init_once(void *foo)
9261 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9263 inode_init_once(&ei->vfs_inode);
9266 void __cold btrfs_destroy_cachep(void)
9269 * Make sure all delayed rcu free inodes are flushed before we
9273 kmem_cache_destroy(btrfs_inode_cachep);
9274 kmem_cache_destroy(btrfs_trans_handle_cachep);
9275 kmem_cache_destroy(btrfs_path_cachep);
9276 kmem_cache_destroy(btrfs_free_space_cachep);
9279 int __init btrfs_init_cachep(void)
9281 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9282 sizeof(struct btrfs_inode), 0,
9283 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9285 if (!btrfs_inode_cachep)
9288 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9289 sizeof(struct btrfs_trans_handle), 0,
9290 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9291 if (!btrfs_trans_handle_cachep)
9294 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9295 sizeof(struct btrfs_path), 0,
9296 SLAB_MEM_SPREAD, NULL);
9297 if (!btrfs_path_cachep)
9300 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9301 sizeof(struct btrfs_free_space), 0,
9302 SLAB_MEM_SPREAD, NULL);
9303 if (!btrfs_free_space_cachep)
9308 btrfs_destroy_cachep();
9312 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9313 u32 request_mask, unsigned int flags)
9316 struct inode *inode = d_inode(path->dentry);
9317 u32 blocksize = inode->i_sb->s_blocksize;
9318 u32 bi_flags = BTRFS_I(inode)->flags;
9320 stat->result_mask |= STATX_BTIME;
9321 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9322 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9323 if (bi_flags & BTRFS_INODE_APPEND)
9324 stat->attributes |= STATX_ATTR_APPEND;
9325 if (bi_flags & BTRFS_INODE_COMPRESS)
9326 stat->attributes |= STATX_ATTR_COMPRESSED;
9327 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9328 stat->attributes |= STATX_ATTR_IMMUTABLE;
9329 if (bi_flags & BTRFS_INODE_NODUMP)
9330 stat->attributes |= STATX_ATTR_NODUMP;
9332 stat->attributes_mask |= (STATX_ATTR_APPEND |
9333 STATX_ATTR_COMPRESSED |
9334 STATX_ATTR_IMMUTABLE |
9337 generic_fillattr(inode, stat);
9338 stat->dev = BTRFS_I(inode)->root->anon_dev;
9340 spin_lock(&BTRFS_I(inode)->lock);
9341 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9342 spin_unlock(&BTRFS_I(inode)->lock);
9343 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9344 ALIGN(delalloc_bytes, blocksize)) >> 9;
9348 static int btrfs_rename_exchange(struct inode *old_dir,
9349 struct dentry *old_dentry,
9350 struct inode *new_dir,
9351 struct dentry *new_dentry)
9353 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9354 struct btrfs_trans_handle *trans;
9355 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9356 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9357 struct inode *new_inode = new_dentry->d_inode;
9358 struct inode *old_inode = old_dentry->d_inode;
9359 struct timespec64 ctime = current_time(old_inode);
9360 struct dentry *parent;
9361 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9362 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9367 bool root_log_pinned = false;
9368 bool dest_log_pinned = false;
9369 struct btrfs_log_ctx ctx_root;
9370 struct btrfs_log_ctx ctx_dest;
9371 bool sync_log_root = false;
9372 bool sync_log_dest = false;
9373 bool commit_transaction = false;
9375 /* we only allow rename subvolume link between subvolumes */
9376 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9379 btrfs_init_log_ctx(&ctx_root, old_inode);
9380 btrfs_init_log_ctx(&ctx_dest, new_inode);
9382 /* close the race window with snapshot create/destroy ioctl */
9383 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9384 down_read(&fs_info->subvol_sem);
9385 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9386 down_read(&fs_info->subvol_sem);
9389 * We want to reserve the absolute worst case amount of items. So if
9390 * both inodes are subvols and we need to unlink them then that would
9391 * require 4 item modifications, but if they are both normal inodes it
9392 * would require 5 item modifications, so we'll assume their normal
9393 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9394 * should cover the worst case number of items we'll modify.
9396 trans = btrfs_start_transaction(root, 12);
9397 if (IS_ERR(trans)) {
9398 ret = PTR_ERR(trans);
9403 * We need to find a free sequence number both in the source and
9404 * in the destination directory for the exchange.
9406 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9409 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9413 BTRFS_I(old_inode)->dir_index = 0ULL;
9414 BTRFS_I(new_inode)->dir_index = 0ULL;
9416 /* Reference for the source. */
9417 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9418 /* force full log commit if subvolume involved. */
9419 btrfs_set_log_full_commit(fs_info, trans);
9421 btrfs_pin_log_trans(root);
9422 root_log_pinned = true;
9423 ret = btrfs_insert_inode_ref(trans, dest,
9424 new_dentry->d_name.name,
9425 new_dentry->d_name.len,
9427 btrfs_ino(BTRFS_I(new_dir)),
9433 /* And now for the dest. */
9434 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9435 /* force full log commit if subvolume involved. */
9436 btrfs_set_log_full_commit(fs_info, trans);
9438 btrfs_pin_log_trans(dest);
9439 dest_log_pinned = true;
9440 ret = btrfs_insert_inode_ref(trans, root,
9441 old_dentry->d_name.name,
9442 old_dentry->d_name.len,
9444 btrfs_ino(BTRFS_I(old_dir)),
9450 /* Update inode version and ctime/mtime. */
9451 inode_inc_iversion(old_dir);
9452 inode_inc_iversion(new_dir);
9453 inode_inc_iversion(old_inode);
9454 inode_inc_iversion(new_inode);
9455 old_dir->i_ctime = old_dir->i_mtime = ctime;
9456 new_dir->i_ctime = new_dir->i_mtime = ctime;
9457 old_inode->i_ctime = ctime;
9458 new_inode->i_ctime = ctime;
9460 if (old_dentry->d_parent != new_dentry->d_parent) {
9461 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9462 BTRFS_I(old_inode), 1);
9463 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9464 BTRFS_I(new_inode), 1);
9467 /* src is a subvolume */
9468 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9469 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9470 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9471 old_dentry->d_name.name,
9472 old_dentry->d_name.len);
9473 } else { /* src is an inode */
9474 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9475 BTRFS_I(old_dentry->d_inode),
9476 old_dentry->d_name.name,
9477 old_dentry->d_name.len);
9479 ret = btrfs_update_inode(trans, root, old_inode);
9482 btrfs_abort_transaction(trans, ret);
9486 /* dest is a subvolume */
9487 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9488 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9489 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9490 new_dentry->d_name.name,
9491 new_dentry->d_name.len);
9492 } else { /* dest is an inode */
9493 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9494 BTRFS_I(new_dentry->d_inode),
9495 new_dentry->d_name.name,
9496 new_dentry->d_name.len);
9498 ret = btrfs_update_inode(trans, dest, new_inode);
9501 btrfs_abort_transaction(trans, ret);
9505 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9506 new_dentry->d_name.name,
9507 new_dentry->d_name.len, 0, old_idx);
9509 btrfs_abort_transaction(trans, ret);
9513 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9514 old_dentry->d_name.name,
9515 old_dentry->d_name.len, 0, new_idx);
9517 btrfs_abort_transaction(trans, ret);
9521 if (old_inode->i_nlink == 1)
9522 BTRFS_I(old_inode)->dir_index = old_idx;
9523 if (new_inode->i_nlink == 1)
9524 BTRFS_I(new_inode)->dir_index = new_idx;
9526 if (root_log_pinned) {
9527 parent = new_dentry->d_parent;
9528 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9529 BTRFS_I(old_dir), parent,
9531 if (ret == BTRFS_NEED_LOG_SYNC)
9532 sync_log_root = true;
9533 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9534 commit_transaction = true;
9536 btrfs_end_log_trans(root);
9537 root_log_pinned = false;
9539 if (dest_log_pinned) {
9540 if (!commit_transaction) {
9541 parent = old_dentry->d_parent;
9542 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9543 BTRFS_I(new_dir), parent,
9545 if (ret == BTRFS_NEED_LOG_SYNC)
9546 sync_log_dest = true;
9547 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9548 commit_transaction = true;
9551 btrfs_end_log_trans(dest);
9552 dest_log_pinned = false;
9556 * If we have pinned a log and an error happened, we unpin tasks
9557 * trying to sync the log and force them to fallback to a transaction
9558 * commit if the log currently contains any of the inodes involved in
9559 * this rename operation (to ensure we do not persist a log with an
9560 * inconsistent state for any of these inodes or leading to any
9561 * inconsistencies when replayed). If the transaction was aborted, the
9562 * abortion reason is propagated to userspace when attempting to commit
9563 * the transaction. If the log does not contain any of these inodes, we
9564 * allow the tasks to sync it.
9566 if (ret && (root_log_pinned || dest_log_pinned)) {
9567 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9568 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9569 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9571 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9572 btrfs_set_log_full_commit(fs_info, trans);
9574 if (root_log_pinned) {
9575 btrfs_end_log_trans(root);
9576 root_log_pinned = false;
9578 if (dest_log_pinned) {
9579 btrfs_end_log_trans(dest);
9580 dest_log_pinned = false;
9583 if (!ret && sync_log_root && !commit_transaction) {
9584 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9587 commit_transaction = true;
9589 if (!ret && sync_log_dest && !commit_transaction) {
9590 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9593 commit_transaction = true;
9595 if (commit_transaction) {
9596 ret = btrfs_commit_transaction(trans);
9600 ret2 = btrfs_end_transaction(trans);
9601 ret = ret ? ret : ret2;
9604 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9605 up_read(&fs_info->subvol_sem);
9606 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9607 up_read(&fs_info->subvol_sem);
9612 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9613 struct btrfs_root *root,
9615 struct dentry *dentry)
9618 struct inode *inode;
9622 ret = btrfs_find_free_ino(root, &objectid);
9626 inode = btrfs_new_inode(trans, root, dir,
9627 dentry->d_name.name,
9629 btrfs_ino(BTRFS_I(dir)),
9631 S_IFCHR | WHITEOUT_MODE,
9634 if (IS_ERR(inode)) {
9635 ret = PTR_ERR(inode);
9639 inode->i_op = &btrfs_special_inode_operations;
9640 init_special_inode(inode, inode->i_mode,
9643 ret = btrfs_init_inode_security(trans, inode, dir,
9648 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9649 BTRFS_I(inode), 0, index);
9653 ret = btrfs_update_inode(trans, root, inode);
9655 unlock_new_inode(inode);
9657 inode_dec_link_count(inode);
9663 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9664 struct inode *new_dir, struct dentry *new_dentry,
9667 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9668 struct btrfs_trans_handle *trans;
9669 unsigned int trans_num_items;
9670 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9671 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9672 struct inode *new_inode = d_inode(new_dentry);
9673 struct inode *old_inode = d_inode(old_dentry);
9677 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9678 bool log_pinned = false;
9679 struct btrfs_log_ctx ctx;
9680 bool sync_log = false;
9681 bool commit_transaction = false;
9683 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9686 /* we only allow rename subvolume link between subvolumes */
9687 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9690 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9691 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9694 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9695 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9699 /* check for collisions, even if the name isn't there */
9700 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9701 new_dentry->d_name.name,
9702 new_dentry->d_name.len);
9705 if (ret == -EEXIST) {
9707 * eexist without a new_inode */
9708 if (WARN_ON(!new_inode)) {
9712 /* maybe -EOVERFLOW */
9719 * we're using rename to replace one file with another. Start IO on it
9720 * now so we don't add too much work to the end of the transaction
9722 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9723 filemap_flush(old_inode->i_mapping);
9725 /* close the racy window with snapshot create/destroy ioctl */
9726 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9727 down_read(&fs_info->subvol_sem);
9729 * We want to reserve the absolute worst case amount of items. So if
9730 * both inodes are subvols and we need to unlink them then that would
9731 * require 4 item modifications, but if they are both normal inodes it
9732 * would require 5 item modifications, so we'll assume they are normal
9733 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9734 * should cover the worst case number of items we'll modify.
9735 * If our rename has the whiteout flag, we need more 5 units for the
9736 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9737 * when selinux is enabled).
9739 trans_num_items = 11;
9740 if (flags & RENAME_WHITEOUT)
9741 trans_num_items += 5;
9742 trans = btrfs_start_transaction(root, trans_num_items);
9743 if (IS_ERR(trans)) {
9744 ret = PTR_ERR(trans);
9749 btrfs_record_root_in_trans(trans, dest);
9751 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9755 BTRFS_I(old_inode)->dir_index = 0ULL;
9756 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9757 /* force full log commit if subvolume involved. */
9758 btrfs_set_log_full_commit(fs_info, trans);
9760 btrfs_pin_log_trans(root);
9762 ret = btrfs_insert_inode_ref(trans, dest,
9763 new_dentry->d_name.name,
9764 new_dentry->d_name.len,
9766 btrfs_ino(BTRFS_I(new_dir)), index);
9771 inode_inc_iversion(old_dir);
9772 inode_inc_iversion(new_dir);
9773 inode_inc_iversion(old_inode);
9774 old_dir->i_ctime = old_dir->i_mtime =
9775 new_dir->i_ctime = new_dir->i_mtime =
9776 old_inode->i_ctime = current_time(old_dir);
9778 if (old_dentry->d_parent != new_dentry->d_parent)
9779 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9780 BTRFS_I(old_inode), 1);
9782 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9783 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9784 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9785 old_dentry->d_name.name,
9786 old_dentry->d_name.len);
9788 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9789 BTRFS_I(d_inode(old_dentry)),
9790 old_dentry->d_name.name,
9791 old_dentry->d_name.len);
9793 ret = btrfs_update_inode(trans, root, old_inode);
9796 btrfs_abort_transaction(trans, ret);
9801 inode_inc_iversion(new_inode);
9802 new_inode->i_ctime = current_time(new_inode);
9803 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9804 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9805 root_objectid = BTRFS_I(new_inode)->location.objectid;
9806 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9807 new_dentry->d_name.name,
9808 new_dentry->d_name.len);
9809 BUG_ON(new_inode->i_nlink == 0);
9811 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9812 BTRFS_I(d_inode(new_dentry)),
9813 new_dentry->d_name.name,
9814 new_dentry->d_name.len);
9816 if (!ret && new_inode->i_nlink == 0)
9817 ret = btrfs_orphan_add(trans,
9818 BTRFS_I(d_inode(new_dentry)));
9820 btrfs_abort_transaction(trans, ret);
9825 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9826 new_dentry->d_name.name,
9827 new_dentry->d_name.len, 0, index);
9829 btrfs_abort_transaction(trans, ret);
9833 if (old_inode->i_nlink == 1)
9834 BTRFS_I(old_inode)->dir_index = index;
9837 struct dentry *parent = new_dentry->d_parent;
9839 btrfs_init_log_ctx(&ctx, old_inode);
9840 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9841 BTRFS_I(old_dir), parent,
9843 if (ret == BTRFS_NEED_LOG_SYNC)
9845 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9846 commit_transaction = true;
9848 btrfs_end_log_trans(root);
9852 if (flags & RENAME_WHITEOUT) {
9853 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9857 btrfs_abort_transaction(trans, ret);
9863 * If we have pinned the log and an error happened, we unpin tasks
9864 * trying to sync the log and force them to fallback to a transaction
9865 * commit if the log currently contains any of the inodes involved in
9866 * this rename operation (to ensure we do not persist a log with an
9867 * inconsistent state for any of these inodes or leading to any
9868 * inconsistencies when replayed). If the transaction was aborted, the
9869 * abortion reason is propagated to userspace when attempting to commit
9870 * the transaction. If the log does not contain any of these inodes, we
9871 * allow the tasks to sync it.
9873 if (ret && log_pinned) {
9874 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9875 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9876 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9878 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9879 btrfs_set_log_full_commit(fs_info, trans);
9881 btrfs_end_log_trans(root);
9884 if (!ret && sync_log) {
9885 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9887 commit_transaction = true;
9889 if (commit_transaction) {
9890 ret = btrfs_commit_transaction(trans);
9894 ret2 = btrfs_end_transaction(trans);
9895 ret = ret ? ret : ret2;
9898 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9899 up_read(&fs_info->subvol_sem);
9904 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9905 struct inode *new_dir, struct dentry *new_dentry,
9908 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9911 if (flags & RENAME_EXCHANGE)
9912 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9915 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9918 struct btrfs_delalloc_work {
9919 struct inode *inode;
9920 struct completion completion;
9921 struct list_head list;
9922 struct btrfs_work work;
9925 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9927 struct btrfs_delalloc_work *delalloc_work;
9928 struct inode *inode;
9930 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9932 inode = delalloc_work->inode;
9933 filemap_flush(inode->i_mapping);
9934 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9935 &BTRFS_I(inode)->runtime_flags))
9936 filemap_flush(inode->i_mapping);
9939 complete(&delalloc_work->completion);
9942 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9944 struct btrfs_delalloc_work *work;
9946 work = kmalloc(sizeof(*work), GFP_NOFS);
9950 init_completion(&work->completion);
9951 INIT_LIST_HEAD(&work->list);
9952 work->inode = inode;
9953 WARN_ON_ONCE(!inode);
9954 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9955 btrfs_run_delalloc_work, NULL, NULL);
9961 * some fairly slow code that needs optimization. This walks the list
9962 * of all the inodes with pending delalloc and forces them to disk.
9964 static int start_delalloc_inodes(struct btrfs_root *root, int nr)
9966 struct btrfs_inode *binode;
9967 struct inode *inode;
9968 struct btrfs_delalloc_work *work, *next;
9969 struct list_head works;
9970 struct list_head splice;
9973 INIT_LIST_HEAD(&works);
9974 INIT_LIST_HEAD(&splice);
9976 mutex_lock(&root->delalloc_mutex);
9977 spin_lock(&root->delalloc_lock);
9978 list_splice_init(&root->delalloc_inodes, &splice);
9979 while (!list_empty(&splice)) {
9980 binode = list_entry(splice.next, struct btrfs_inode,
9983 list_move_tail(&binode->delalloc_inodes,
9984 &root->delalloc_inodes);
9985 inode = igrab(&binode->vfs_inode);
9987 cond_resched_lock(&root->delalloc_lock);
9990 spin_unlock(&root->delalloc_lock);
9992 work = btrfs_alloc_delalloc_work(inode);
9998 list_add_tail(&work->list, &works);
9999 btrfs_queue_work(root->fs_info->flush_workers,
10002 if (nr != -1 && ret >= nr)
10005 spin_lock(&root->delalloc_lock);
10007 spin_unlock(&root->delalloc_lock);
10010 list_for_each_entry_safe(work, next, &works, list) {
10011 list_del_init(&work->list);
10012 wait_for_completion(&work->completion);
10016 if (!list_empty(&splice)) {
10017 spin_lock(&root->delalloc_lock);
10018 list_splice_tail(&splice, &root->delalloc_inodes);
10019 spin_unlock(&root->delalloc_lock);
10021 mutex_unlock(&root->delalloc_mutex);
10025 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
10027 struct btrfs_fs_info *fs_info = root->fs_info;
10030 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10033 ret = start_delalloc_inodes(root, -1);
10039 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10041 struct btrfs_root *root;
10042 struct list_head splice;
10045 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10048 INIT_LIST_HEAD(&splice);
10050 mutex_lock(&fs_info->delalloc_root_mutex);
10051 spin_lock(&fs_info->delalloc_root_lock);
10052 list_splice_init(&fs_info->delalloc_roots, &splice);
10053 while (!list_empty(&splice) && nr) {
10054 root = list_first_entry(&splice, struct btrfs_root,
10056 root = btrfs_grab_fs_root(root);
10058 list_move_tail(&root->delalloc_root,
10059 &fs_info->delalloc_roots);
10060 spin_unlock(&fs_info->delalloc_root_lock);
10062 ret = start_delalloc_inodes(root, nr);
10063 btrfs_put_fs_root(root);
10071 spin_lock(&fs_info->delalloc_root_lock);
10073 spin_unlock(&fs_info->delalloc_root_lock);
10077 if (!list_empty(&splice)) {
10078 spin_lock(&fs_info->delalloc_root_lock);
10079 list_splice_tail(&splice, &fs_info->delalloc_roots);
10080 spin_unlock(&fs_info->delalloc_root_lock);
10082 mutex_unlock(&fs_info->delalloc_root_mutex);
10086 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10087 const char *symname)
10089 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10090 struct btrfs_trans_handle *trans;
10091 struct btrfs_root *root = BTRFS_I(dir)->root;
10092 struct btrfs_path *path;
10093 struct btrfs_key key;
10094 struct inode *inode = NULL;
10101 struct btrfs_file_extent_item *ei;
10102 struct extent_buffer *leaf;
10104 name_len = strlen(symname);
10105 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10106 return -ENAMETOOLONG;
10109 * 2 items for inode item and ref
10110 * 2 items for dir items
10111 * 1 item for updating parent inode item
10112 * 1 item for the inline extent item
10113 * 1 item for xattr if selinux is on
10115 trans = btrfs_start_transaction(root, 7);
10117 return PTR_ERR(trans);
10119 err = btrfs_find_free_ino(root, &objectid);
10123 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10124 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10125 objectid, S_IFLNK|S_IRWXUGO, &index);
10126 if (IS_ERR(inode)) {
10127 err = PTR_ERR(inode);
10133 * If the active LSM wants to access the inode during
10134 * d_instantiate it needs these. Smack checks to see
10135 * if the filesystem supports xattrs by looking at the
10138 inode->i_fop = &btrfs_file_operations;
10139 inode->i_op = &btrfs_file_inode_operations;
10140 inode->i_mapping->a_ops = &btrfs_aops;
10141 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10143 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10147 path = btrfs_alloc_path();
10152 key.objectid = btrfs_ino(BTRFS_I(inode));
10154 key.type = BTRFS_EXTENT_DATA_KEY;
10155 datasize = btrfs_file_extent_calc_inline_size(name_len);
10156 err = btrfs_insert_empty_item(trans, root, path, &key,
10159 btrfs_free_path(path);
10162 leaf = path->nodes[0];
10163 ei = btrfs_item_ptr(leaf, path->slots[0],
10164 struct btrfs_file_extent_item);
10165 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10166 btrfs_set_file_extent_type(leaf, ei,
10167 BTRFS_FILE_EXTENT_INLINE);
10168 btrfs_set_file_extent_encryption(leaf, ei, 0);
10169 btrfs_set_file_extent_compression(leaf, ei, 0);
10170 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10171 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10173 ptr = btrfs_file_extent_inline_start(ei);
10174 write_extent_buffer(leaf, symname, ptr, name_len);
10175 btrfs_mark_buffer_dirty(leaf);
10176 btrfs_free_path(path);
10178 inode->i_op = &btrfs_symlink_inode_operations;
10179 inode_nohighmem(inode);
10180 inode->i_mapping->a_ops = &btrfs_aops;
10181 inode_set_bytes(inode, name_len);
10182 btrfs_i_size_write(BTRFS_I(inode), name_len);
10183 err = btrfs_update_inode(trans, root, inode);
10185 * Last step, add directory indexes for our symlink inode. This is the
10186 * last step to avoid extra cleanup of these indexes if an error happens
10190 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10191 BTRFS_I(inode), 0, index);
10195 d_instantiate_new(dentry, inode);
10198 btrfs_end_transaction(trans);
10199 if (err && inode) {
10200 inode_dec_link_count(inode);
10201 discard_new_inode(inode);
10203 btrfs_btree_balance_dirty(fs_info);
10207 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10208 u64 start, u64 num_bytes, u64 min_size,
10209 loff_t actual_len, u64 *alloc_hint,
10210 struct btrfs_trans_handle *trans)
10212 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10213 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10214 struct extent_map *em;
10215 struct btrfs_root *root = BTRFS_I(inode)->root;
10216 struct btrfs_key ins;
10217 u64 cur_offset = start;
10220 u64 last_alloc = (u64)-1;
10222 bool own_trans = true;
10223 u64 end = start + num_bytes - 1;
10227 while (num_bytes > 0) {
10229 trans = btrfs_start_transaction(root, 3);
10230 if (IS_ERR(trans)) {
10231 ret = PTR_ERR(trans);
10236 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10237 cur_bytes = max(cur_bytes, min_size);
10239 * If we are severely fragmented we could end up with really
10240 * small allocations, so if the allocator is returning small
10241 * chunks lets make its job easier by only searching for those
10244 cur_bytes = min(cur_bytes, last_alloc);
10245 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10246 min_size, 0, *alloc_hint, &ins, 1, 0);
10249 btrfs_end_transaction(trans);
10252 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10254 last_alloc = ins.offset;
10255 ret = insert_reserved_file_extent(trans, inode,
10256 cur_offset, ins.objectid,
10257 ins.offset, ins.offset,
10258 ins.offset, 0, 0, 0,
10259 BTRFS_FILE_EXTENT_PREALLOC);
10261 btrfs_free_reserved_extent(fs_info, ins.objectid,
10263 btrfs_abort_transaction(trans, ret);
10265 btrfs_end_transaction(trans);
10269 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10270 cur_offset + ins.offset -1, 0);
10272 em = alloc_extent_map();
10274 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10275 &BTRFS_I(inode)->runtime_flags);
10279 em->start = cur_offset;
10280 em->orig_start = cur_offset;
10281 em->len = ins.offset;
10282 em->block_start = ins.objectid;
10283 em->block_len = ins.offset;
10284 em->orig_block_len = ins.offset;
10285 em->ram_bytes = ins.offset;
10286 em->bdev = fs_info->fs_devices->latest_bdev;
10287 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10288 em->generation = trans->transid;
10291 write_lock(&em_tree->lock);
10292 ret = add_extent_mapping(em_tree, em, 1);
10293 write_unlock(&em_tree->lock);
10294 if (ret != -EEXIST)
10296 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10297 cur_offset + ins.offset - 1,
10300 free_extent_map(em);
10302 num_bytes -= ins.offset;
10303 cur_offset += ins.offset;
10304 *alloc_hint = ins.objectid + ins.offset;
10306 inode_inc_iversion(inode);
10307 inode->i_ctime = current_time(inode);
10308 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10309 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10310 (actual_len > inode->i_size) &&
10311 (cur_offset > inode->i_size)) {
10312 if (cur_offset > actual_len)
10313 i_size = actual_len;
10315 i_size = cur_offset;
10316 i_size_write(inode, i_size);
10317 btrfs_ordered_update_i_size(inode, i_size, NULL);
10320 ret = btrfs_update_inode(trans, root, inode);
10323 btrfs_abort_transaction(trans, ret);
10325 btrfs_end_transaction(trans);
10330 btrfs_end_transaction(trans);
10332 if (cur_offset < end)
10333 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10334 end - cur_offset + 1);
10338 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10339 u64 start, u64 num_bytes, u64 min_size,
10340 loff_t actual_len, u64 *alloc_hint)
10342 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10343 min_size, actual_len, alloc_hint,
10347 int btrfs_prealloc_file_range_trans(struct inode *inode,
10348 struct btrfs_trans_handle *trans, int mode,
10349 u64 start, u64 num_bytes, u64 min_size,
10350 loff_t actual_len, u64 *alloc_hint)
10352 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10353 min_size, actual_len, alloc_hint, trans);
10356 static int btrfs_set_page_dirty(struct page *page)
10358 return __set_page_dirty_nobuffers(page);
10361 static int btrfs_permission(struct inode *inode, int mask)
10363 struct btrfs_root *root = BTRFS_I(inode)->root;
10364 umode_t mode = inode->i_mode;
10366 if (mask & MAY_WRITE &&
10367 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10368 if (btrfs_root_readonly(root))
10370 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10373 return generic_permission(inode, mask);
10376 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10378 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10379 struct btrfs_trans_handle *trans;
10380 struct btrfs_root *root = BTRFS_I(dir)->root;
10381 struct inode *inode = NULL;
10387 * 5 units required for adding orphan entry
10389 trans = btrfs_start_transaction(root, 5);
10391 return PTR_ERR(trans);
10393 ret = btrfs_find_free_ino(root, &objectid);
10397 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10398 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10399 if (IS_ERR(inode)) {
10400 ret = PTR_ERR(inode);
10405 inode->i_fop = &btrfs_file_operations;
10406 inode->i_op = &btrfs_file_inode_operations;
10408 inode->i_mapping->a_ops = &btrfs_aops;
10409 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10411 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10415 ret = btrfs_update_inode(trans, root, inode);
10418 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10423 * We set number of links to 0 in btrfs_new_inode(), and here we set
10424 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10427 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10429 set_nlink(inode, 1);
10430 d_tmpfile(dentry, inode);
10431 unlock_new_inode(inode);
10432 mark_inode_dirty(inode);
10434 btrfs_end_transaction(trans);
10436 discard_new_inode(inode);
10437 btrfs_btree_balance_dirty(fs_info);
10441 __attribute__((const))
10442 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10447 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10449 struct inode *inode = tree->private_data;
10450 unsigned long index = start >> PAGE_SHIFT;
10451 unsigned long end_index = end >> PAGE_SHIFT;
10454 while (index <= end_index) {
10455 page = find_get_page(inode->i_mapping, index);
10456 ASSERT(page); /* Pages should be in the extent_io_tree */
10457 set_page_writeback(page);
10463 static const struct inode_operations btrfs_dir_inode_operations = {
10464 .getattr = btrfs_getattr,
10465 .lookup = btrfs_lookup,
10466 .create = btrfs_create,
10467 .unlink = btrfs_unlink,
10468 .link = btrfs_link,
10469 .mkdir = btrfs_mkdir,
10470 .rmdir = btrfs_rmdir,
10471 .rename = btrfs_rename2,
10472 .symlink = btrfs_symlink,
10473 .setattr = btrfs_setattr,
10474 .mknod = btrfs_mknod,
10475 .listxattr = btrfs_listxattr,
10476 .permission = btrfs_permission,
10477 .get_acl = btrfs_get_acl,
10478 .set_acl = btrfs_set_acl,
10479 .update_time = btrfs_update_time,
10480 .tmpfile = btrfs_tmpfile,
10482 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10483 .lookup = btrfs_lookup,
10484 .permission = btrfs_permission,
10485 .update_time = btrfs_update_time,
10488 static const struct file_operations btrfs_dir_file_operations = {
10489 .llseek = generic_file_llseek,
10490 .read = generic_read_dir,
10491 .iterate_shared = btrfs_real_readdir,
10492 .open = btrfs_opendir,
10493 .unlocked_ioctl = btrfs_ioctl,
10494 #ifdef CONFIG_COMPAT
10495 .compat_ioctl = btrfs_compat_ioctl,
10497 .release = btrfs_release_file,
10498 .fsync = btrfs_sync_file,
10501 static const struct extent_io_ops btrfs_extent_io_ops = {
10502 /* mandatory callbacks */
10503 .submit_bio_hook = btrfs_submit_bio_hook,
10504 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10505 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10509 * btrfs doesn't support the bmap operation because swapfiles
10510 * use bmap to make a mapping of extents in the file. They assume
10511 * these extents won't change over the life of the file and they
10512 * use the bmap result to do IO directly to the drive.
10514 * the btrfs bmap call would return logical addresses that aren't
10515 * suitable for IO and they also will change frequently as COW
10516 * operations happen. So, swapfile + btrfs == corruption.
10518 * For now we're avoiding this by dropping bmap.
10520 static const struct address_space_operations btrfs_aops = {
10521 .readpage = btrfs_readpage,
10522 .writepage = btrfs_writepage,
10523 .writepages = btrfs_writepages,
10524 .readpages = btrfs_readpages,
10525 .direct_IO = btrfs_direct_IO,
10526 .invalidatepage = btrfs_invalidatepage,
10527 .releasepage = btrfs_releasepage,
10528 .set_page_dirty = btrfs_set_page_dirty,
10529 .error_remove_page = generic_error_remove_page,
10532 static const struct inode_operations btrfs_file_inode_operations = {
10533 .getattr = btrfs_getattr,
10534 .setattr = btrfs_setattr,
10535 .listxattr = btrfs_listxattr,
10536 .permission = btrfs_permission,
10537 .fiemap = btrfs_fiemap,
10538 .get_acl = btrfs_get_acl,
10539 .set_acl = btrfs_set_acl,
10540 .update_time = btrfs_update_time,
10542 static const struct inode_operations btrfs_special_inode_operations = {
10543 .getattr = btrfs_getattr,
10544 .setattr = btrfs_setattr,
10545 .permission = btrfs_permission,
10546 .listxattr = btrfs_listxattr,
10547 .get_acl = btrfs_get_acl,
10548 .set_acl = btrfs_set_acl,
10549 .update_time = btrfs_update_time,
10551 static const struct inode_operations btrfs_symlink_inode_operations = {
10552 .get_link = page_get_link,
10553 .getattr = btrfs_getattr,
10554 .setattr = btrfs_setattr,
10555 .permission = btrfs_permission,
10556 .listxattr = btrfs_listxattr,
10557 .update_time = btrfs_update_time,
10560 const struct dentry_operations btrfs_dentry_operations = {
10561 .d_delete = btrfs_dentry_delete,