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 <linux/swap.h>
31 #include <asm/unaligned.h>
34 #include "transaction.h"
35 #include "btrfs_inode.h"
36 #include "print-tree.h"
37 #include "ordered-data.h"
41 #include "compression.h"
43 #include "free-space-cache.h"
44 #include "inode-map.h"
50 struct btrfs_iget_args {
51 struct btrfs_key *location;
52 struct btrfs_root *root;
55 struct btrfs_dio_data {
57 u64 unsubmitted_oe_range_start;
58 u64 unsubmitted_oe_range_end;
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct file_operations btrfs_dir_file_operations;
69 static const struct extent_io_ops btrfs_extent_io_ops;
71 static struct kmem_cache *btrfs_inode_cachep;
72 struct kmem_cache *btrfs_trans_handle_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74 struct kmem_cache *btrfs_free_space_cachep;
77 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
79 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
80 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
81 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
82 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
83 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
84 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
87 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
88 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
89 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
90 static noinline int cow_file_range(struct inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, u64 delalloc_end,
93 int *page_started, unsigned long *nr_written,
94 int unlock, struct btrfs_dedupe_hash *hash);
95 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
96 u64 orig_start, u64 block_start,
97 u64 block_len, u64 orig_block_len,
98 u64 ram_bytes, int compress_type,
101 static void __endio_write_update_ordered(struct inode *inode,
102 const u64 offset, const u64 bytes,
103 const bool uptodate);
106 * Cleanup all submitted ordered extents in specified range to handle errors
107 * from the fill_dellaloc() callback.
109 * NOTE: caller must ensure that when an error happens, it can not call
110 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
111 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
112 * to be released, which we want to happen only when finishing the ordered
113 * extent (btrfs_finish_ordered_io()).
115 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
116 struct page *locked_page,
117 u64 offset, u64 bytes)
119 unsigned long index = offset >> PAGE_SHIFT;
120 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
121 u64 page_start = page_offset(locked_page);
122 u64 page_end = page_start + PAGE_SIZE - 1;
126 while (index <= end_index) {
127 page = find_get_page(inode->i_mapping, index);
131 ClearPagePrivate2(page);
136 * In case this page belongs to the delalloc range being instantiated
137 * then skip it, since the first page of a range is going to be
138 * properly cleaned up by the caller of run_delalloc_range
140 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
145 return __endio_write_update_ordered(inode, offset, bytes, false);
148 static int btrfs_dirty_inode(struct inode *inode);
150 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
151 void btrfs_test_inode_set_ops(struct inode *inode)
153 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
157 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
158 struct inode *inode, struct inode *dir,
159 const struct qstr *qstr)
163 err = btrfs_init_acl(trans, inode, dir);
165 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
170 * this does all the hard work for inserting an inline extent into
171 * the btree. The caller should have done a btrfs_drop_extents so that
172 * no overlapping inline items exist in the btree
174 static int insert_inline_extent(struct btrfs_trans_handle *trans,
175 struct btrfs_path *path, int extent_inserted,
176 struct btrfs_root *root, struct inode *inode,
177 u64 start, size_t size, size_t compressed_size,
179 struct page **compressed_pages)
181 struct extent_buffer *leaf;
182 struct page *page = NULL;
185 struct btrfs_file_extent_item *ei;
187 size_t cur_size = size;
188 unsigned long offset;
190 if (compressed_size && compressed_pages)
191 cur_size = compressed_size;
193 inode_add_bytes(inode, size);
195 if (!extent_inserted) {
196 struct btrfs_key key;
199 key.objectid = btrfs_ino(BTRFS_I(inode));
201 key.type = BTRFS_EXTENT_DATA_KEY;
203 datasize = btrfs_file_extent_calc_inline_size(cur_size);
204 path->leave_spinning = 1;
205 ret = btrfs_insert_empty_item(trans, root, path, &key,
210 leaf = path->nodes[0];
211 ei = btrfs_item_ptr(leaf, path->slots[0],
212 struct btrfs_file_extent_item);
213 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
214 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
215 btrfs_set_file_extent_encryption(leaf, ei, 0);
216 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
217 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
218 ptr = btrfs_file_extent_inline_start(ei);
220 if (compress_type != BTRFS_COMPRESS_NONE) {
223 while (compressed_size > 0) {
224 cpage = compressed_pages[i];
225 cur_size = min_t(unsigned long, compressed_size,
228 kaddr = kmap_atomic(cpage);
229 write_extent_buffer(leaf, kaddr, ptr, cur_size);
230 kunmap_atomic(kaddr);
234 compressed_size -= cur_size;
236 btrfs_set_file_extent_compression(leaf, ei,
239 page = find_get_page(inode->i_mapping,
240 start >> PAGE_SHIFT);
241 btrfs_set_file_extent_compression(leaf, ei, 0);
242 kaddr = kmap_atomic(page);
243 offset = start & (PAGE_SIZE - 1);
244 write_extent_buffer(leaf, kaddr + offset, ptr, size);
245 kunmap_atomic(kaddr);
248 btrfs_mark_buffer_dirty(leaf);
249 btrfs_release_path(path);
252 * we're an inline extent, so nobody can
253 * extend the file past i_size without locking
254 * a page we already have locked.
256 * We must do any isize and inode updates
257 * before we unlock the pages. Otherwise we
258 * could end up racing with unlink.
260 BTRFS_I(inode)->disk_i_size = inode->i_size;
261 ret = btrfs_update_inode(trans, root, inode);
269 * conditionally insert an inline extent into the file. This
270 * does the checks required to make sure the data is small enough
271 * to fit as an inline extent.
273 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
274 u64 end, size_t compressed_size,
276 struct page **compressed_pages)
278 struct btrfs_root *root = BTRFS_I(inode)->root;
279 struct btrfs_fs_info *fs_info = root->fs_info;
280 struct btrfs_trans_handle *trans;
281 u64 isize = i_size_read(inode);
282 u64 actual_end = min(end + 1, isize);
283 u64 inline_len = actual_end - start;
284 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
285 u64 data_len = inline_len;
287 struct btrfs_path *path;
288 int extent_inserted = 0;
289 u32 extent_item_size;
292 data_len = compressed_size;
295 actual_end > fs_info->sectorsize ||
296 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
298 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
300 data_len > fs_info->max_inline) {
304 path = btrfs_alloc_path();
308 trans = btrfs_join_transaction(root);
310 btrfs_free_path(path);
311 return PTR_ERR(trans);
313 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
315 if (compressed_size && compressed_pages)
316 extent_item_size = btrfs_file_extent_calc_inline_size(
319 extent_item_size = btrfs_file_extent_calc_inline_size(
322 ret = __btrfs_drop_extents(trans, root, inode, path,
323 start, aligned_end, NULL,
324 1, 1, extent_item_size, &extent_inserted);
326 btrfs_abort_transaction(trans, ret);
330 if (isize > actual_end)
331 inline_len = min_t(u64, isize, actual_end);
332 ret = insert_inline_extent(trans, path, extent_inserted,
334 inline_len, compressed_size,
335 compress_type, compressed_pages);
336 if (ret && ret != -ENOSPC) {
337 btrfs_abort_transaction(trans, ret);
339 } else if (ret == -ENOSPC) {
344 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
345 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
348 * Don't forget to free the reserved space, as for inlined extent
349 * it won't count as data extent, free them directly here.
350 * And at reserve time, it's always aligned to page size, so
351 * just free one page here.
353 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
354 btrfs_free_path(path);
355 btrfs_end_transaction(trans);
359 struct async_extent {
364 unsigned long nr_pages;
366 struct list_head list;
371 struct btrfs_fs_info *fs_info;
372 struct page *locked_page;
375 unsigned int write_flags;
376 struct list_head extents;
377 struct btrfs_work work;
380 static noinline int add_async_extent(struct async_cow *cow,
381 u64 start, u64 ram_size,
384 unsigned long nr_pages,
387 struct async_extent *async_extent;
389 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
390 BUG_ON(!async_extent); /* -ENOMEM */
391 async_extent->start = start;
392 async_extent->ram_size = ram_size;
393 async_extent->compressed_size = compressed_size;
394 async_extent->pages = pages;
395 async_extent->nr_pages = nr_pages;
396 async_extent->compress_type = compress_type;
397 list_add_tail(&async_extent->list, &cow->extents);
401 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
403 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
406 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
409 if (BTRFS_I(inode)->defrag_compress)
411 /* bad compression ratios */
412 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
414 if (btrfs_test_opt(fs_info, COMPRESS) ||
415 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
416 BTRFS_I(inode)->prop_compress)
417 return btrfs_compress_heuristic(inode, start, end);
421 static inline void inode_should_defrag(struct btrfs_inode *inode,
422 u64 start, u64 end, u64 num_bytes, u64 small_write)
424 /* If this is a small write inside eof, kick off a defrag */
425 if (num_bytes < small_write &&
426 (start > 0 || end + 1 < inode->disk_i_size))
427 btrfs_add_inode_defrag(NULL, inode);
431 * we create compressed extents in two phases. The first
432 * phase compresses a range of pages that have already been
433 * locked (both pages and state bits are locked).
435 * This is done inside an ordered work queue, and the compression
436 * is spread across many cpus. The actual IO submission is step
437 * two, and the ordered work queue takes care of making sure that
438 * happens in the same order things were put onto the queue by
439 * writepages and friends.
441 * If this code finds it can't get good compression, it puts an
442 * entry onto the work queue to write the uncompressed bytes. This
443 * makes sure that both compressed inodes and uncompressed inodes
444 * are written in the same order that the flusher thread sent them
447 static noinline void compress_file_range(struct inode *inode,
448 struct page *locked_page,
450 struct async_cow *async_cow,
453 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
454 u64 blocksize = fs_info->sectorsize;
456 u64 isize = i_size_read(inode);
458 struct page **pages = NULL;
459 unsigned long nr_pages;
460 unsigned long total_compressed = 0;
461 unsigned long total_in = 0;
464 int compress_type = fs_info->compress_type;
467 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
470 actual_end = min_t(u64, isize, end + 1);
473 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
474 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
475 nr_pages = min_t(unsigned long, nr_pages,
476 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
479 * we don't want to send crud past the end of i_size through
480 * compression, that's just a waste of CPU time. So, if the
481 * end of the file is before the start of our current
482 * requested range of bytes, we bail out to the uncompressed
483 * cleanup code that can deal with all of this.
485 * It isn't really the fastest way to fix things, but this is a
486 * very uncommon corner.
488 if (actual_end <= start)
489 goto cleanup_and_bail_uncompressed;
491 total_compressed = actual_end - start;
494 * skip compression for a small file range(<=blocksize) that
495 * isn't an inline extent, since it doesn't save disk space at all.
497 if (total_compressed <= blocksize &&
498 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
499 goto cleanup_and_bail_uncompressed;
501 total_compressed = min_t(unsigned long, total_compressed,
502 BTRFS_MAX_UNCOMPRESSED);
507 * we do compression for mount -o compress and when the
508 * inode has not been flagged as nocompress. This flag can
509 * change at any time if we discover bad compression ratios.
511 if (inode_need_compress(inode, start, end)) {
513 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
515 /* just bail out to the uncompressed code */
520 if (BTRFS_I(inode)->defrag_compress)
521 compress_type = BTRFS_I(inode)->defrag_compress;
522 else if (BTRFS_I(inode)->prop_compress)
523 compress_type = BTRFS_I(inode)->prop_compress;
526 * we need to call clear_page_dirty_for_io on each
527 * page in the range. Otherwise applications with the file
528 * mmap'd can wander in and change the page contents while
529 * we are compressing them.
531 * If the compression fails for any reason, we set the pages
532 * dirty again later on.
534 * Note that the remaining part is redirtied, the start pointer
535 * has moved, the end is the original one.
538 extent_range_clear_dirty_for_io(inode, start, end);
542 /* Compression level is applied here and only here */
543 ret = btrfs_compress_pages(
544 compress_type | (fs_info->compress_level << 4),
545 inode->i_mapping, start,
552 unsigned long offset = total_compressed &
554 struct page *page = pages[nr_pages - 1];
557 /* zero the tail end of the last page, we might be
558 * sending it down to disk
561 kaddr = kmap_atomic(page);
562 memset(kaddr + offset, 0,
564 kunmap_atomic(kaddr);
571 /* lets try to make an inline extent */
572 if (ret || total_in < actual_end) {
573 /* we didn't compress the entire range, try
574 * to make an uncompressed inline extent.
576 ret = cow_file_range_inline(inode, start, end, 0,
577 BTRFS_COMPRESS_NONE, NULL);
579 /* try making a compressed inline extent */
580 ret = cow_file_range_inline(inode, start, end,
582 compress_type, pages);
585 unsigned long clear_flags = EXTENT_DELALLOC |
586 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
587 EXTENT_DO_ACCOUNTING;
588 unsigned long page_error_op;
590 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
593 * inline extent creation worked or returned error,
594 * we don't need to create any more async work items.
595 * Unlock and free up our temp pages.
597 * We use DO_ACCOUNTING here because we need the
598 * delalloc_release_metadata to be done _after_ we drop
599 * our outstanding extent for clearing delalloc for this
602 extent_clear_unlock_delalloc(inode, start, end, end,
615 * we aren't doing an inline extent round the compressed size
616 * up to a block size boundary so the allocator does sane
619 total_compressed = ALIGN(total_compressed, blocksize);
622 * one last check to make sure the compression is really a
623 * win, compare the page count read with the blocks on disk,
624 * compression must free at least one sector size
626 total_in = ALIGN(total_in, PAGE_SIZE);
627 if (total_compressed + blocksize <= total_in) {
631 * The async work queues will take care of doing actual
632 * allocation on disk for these compressed pages, and
633 * will submit them to the elevator.
635 add_async_extent(async_cow, start, total_in,
636 total_compressed, pages, nr_pages,
639 if (start + total_in < end) {
650 * the compression code ran but failed to make things smaller,
651 * free any pages it allocated and our page pointer array
653 for (i = 0; i < nr_pages; i++) {
654 WARN_ON(pages[i]->mapping);
659 total_compressed = 0;
662 /* flag the file so we don't compress in the future */
663 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
664 !(BTRFS_I(inode)->prop_compress)) {
665 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
668 cleanup_and_bail_uncompressed:
670 * No compression, but we still need to write the pages in the file
671 * we've been given so far. redirty the locked page if it corresponds
672 * to our extent and set things up for the async work queue to run
673 * cow_file_range to do the normal delalloc dance.
675 if (page_offset(locked_page) >= start &&
676 page_offset(locked_page) <= end)
677 __set_page_dirty_nobuffers(locked_page);
678 /* unlocked later on in the async handlers */
681 extent_range_redirty_for_io(inode, start, end);
682 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
683 BTRFS_COMPRESS_NONE);
689 for (i = 0; i < nr_pages; i++) {
690 WARN_ON(pages[i]->mapping);
696 static void free_async_extent_pages(struct async_extent *async_extent)
700 if (!async_extent->pages)
703 for (i = 0; i < async_extent->nr_pages; i++) {
704 WARN_ON(async_extent->pages[i]->mapping);
705 put_page(async_extent->pages[i]);
707 kfree(async_extent->pages);
708 async_extent->nr_pages = 0;
709 async_extent->pages = NULL;
713 * phase two of compressed writeback. This is the ordered portion
714 * of the code, which only gets called in the order the work was
715 * queued. We walk all the async extents created by compress_file_range
716 * and send them down to the disk.
718 static noinline void submit_compressed_extents(struct inode *inode,
719 struct async_cow *async_cow)
721 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
722 struct async_extent *async_extent;
724 struct btrfs_key ins;
725 struct extent_map *em;
726 struct btrfs_root *root = BTRFS_I(inode)->root;
727 struct extent_io_tree *io_tree;
731 while (!list_empty(&async_cow->extents)) {
732 async_extent = list_entry(async_cow->extents.next,
733 struct async_extent, list);
734 list_del(&async_extent->list);
736 io_tree = &BTRFS_I(inode)->io_tree;
739 /* did the compression code fall back to uncompressed IO? */
740 if (!async_extent->pages) {
741 int page_started = 0;
742 unsigned long nr_written = 0;
744 lock_extent(io_tree, async_extent->start,
745 async_extent->start +
746 async_extent->ram_size - 1);
748 /* allocate blocks */
749 ret = cow_file_range(inode, async_cow->locked_page,
751 async_extent->start +
752 async_extent->ram_size - 1,
753 async_extent->start +
754 async_extent->ram_size - 1,
755 &page_started, &nr_written, 0,
761 * if page_started, cow_file_range inserted an
762 * inline extent and took care of all the unlocking
763 * and IO for us. Otherwise, we need to submit
764 * all those pages down to the drive.
766 if (!page_started && !ret)
767 extent_write_locked_range(inode,
769 async_extent->start +
770 async_extent->ram_size - 1,
773 unlock_page(async_cow->locked_page);
779 lock_extent(io_tree, async_extent->start,
780 async_extent->start + async_extent->ram_size - 1);
782 ret = btrfs_reserve_extent(root, async_extent->ram_size,
783 async_extent->compressed_size,
784 async_extent->compressed_size,
785 0, alloc_hint, &ins, 1, 1);
787 free_async_extent_pages(async_extent);
789 if (ret == -ENOSPC) {
790 unlock_extent(io_tree, async_extent->start,
791 async_extent->start +
792 async_extent->ram_size - 1);
795 * we need to redirty the pages if we decide to
796 * fallback to uncompressed IO, otherwise we
797 * will not submit these pages down to lower
800 extent_range_redirty_for_io(inode,
802 async_extent->start +
803 async_extent->ram_size - 1);
810 * here we're doing allocation and writeback of the
813 em = create_io_em(inode, async_extent->start,
814 async_extent->ram_size, /* len */
815 async_extent->start, /* orig_start */
816 ins.objectid, /* block_start */
817 ins.offset, /* block_len */
818 ins.offset, /* orig_block_len */
819 async_extent->ram_size, /* ram_bytes */
820 async_extent->compress_type,
821 BTRFS_ORDERED_COMPRESSED);
823 /* ret value is not necessary due to void function */
824 goto out_free_reserve;
827 ret = btrfs_add_ordered_extent_compress(inode,
830 async_extent->ram_size,
832 BTRFS_ORDERED_COMPRESSED,
833 async_extent->compress_type);
835 btrfs_drop_extent_cache(BTRFS_I(inode),
837 async_extent->start +
838 async_extent->ram_size - 1, 0);
839 goto out_free_reserve;
841 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
844 * clear dirty, set writeback and unlock the pages.
846 extent_clear_unlock_delalloc(inode, async_extent->start,
847 async_extent->start +
848 async_extent->ram_size - 1,
849 async_extent->start +
850 async_extent->ram_size - 1,
851 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
852 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
854 if (btrfs_submit_compressed_write(inode,
856 async_extent->ram_size,
858 ins.offset, async_extent->pages,
859 async_extent->nr_pages,
860 async_cow->write_flags)) {
861 struct page *p = async_extent->pages[0];
862 const u64 start = async_extent->start;
863 const u64 end = start + async_extent->ram_size - 1;
865 p->mapping = inode->i_mapping;
866 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
869 extent_clear_unlock_delalloc(inode, start, end, end,
873 free_async_extent_pages(async_extent);
875 alloc_hint = ins.objectid + ins.offset;
881 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
882 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
884 extent_clear_unlock_delalloc(inode, async_extent->start,
885 async_extent->start +
886 async_extent->ram_size - 1,
887 async_extent->start +
888 async_extent->ram_size - 1,
889 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
890 EXTENT_DELALLOC_NEW |
891 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
892 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
893 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
895 free_async_extent_pages(async_extent);
900 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
903 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
904 struct extent_map *em;
907 read_lock(&em_tree->lock);
908 em = search_extent_mapping(em_tree, start, num_bytes);
911 * if block start isn't an actual block number then find the
912 * first block in this inode and use that as a hint. If that
913 * block is also bogus then just don't worry about it.
915 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
917 em = search_extent_mapping(em_tree, 0, 0);
918 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
919 alloc_hint = em->block_start;
923 alloc_hint = em->block_start;
927 read_unlock(&em_tree->lock);
933 * when extent_io.c finds a delayed allocation range in the file,
934 * the call backs end up in this code. The basic idea is to
935 * allocate extents on disk for the range, and create ordered data structs
936 * in ram to track those extents.
938 * locked_page is the page that writepage had locked already. We use
939 * it to make sure we don't do extra locks or unlocks.
941 * *page_started is set to one if we unlock locked_page and do everything
942 * required to start IO on it. It may be clean and already done with
945 static noinline int cow_file_range(struct inode *inode,
946 struct page *locked_page,
947 u64 start, u64 end, u64 delalloc_end,
948 int *page_started, unsigned long *nr_written,
949 int unlock, struct btrfs_dedupe_hash *hash)
951 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
952 struct btrfs_root *root = BTRFS_I(inode)->root;
955 unsigned long ram_size;
956 u64 cur_alloc_size = 0;
957 u64 blocksize = fs_info->sectorsize;
958 struct btrfs_key ins;
959 struct extent_map *em;
961 unsigned long page_ops;
962 bool extent_reserved = false;
965 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
971 num_bytes = ALIGN(end - start + 1, blocksize);
972 num_bytes = max(blocksize, num_bytes);
973 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
975 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
978 /* lets try to make an inline extent */
979 ret = cow_file_range_inline(inode, start, end, 0,
980 BTRFS_COMPRESS_NONE, NULL);
983 * We use DO_ACCOUNTING here because we need the
984 * delalloc_release_metadata to be run _after_ we drop
985 * our outstanding extent for clearing delalloc for this
988 extent_clear_unlock_delalloc(inode, start, end,
990 EXTENT_LOCKED | EXTENT_DELALLOC |
991 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
992 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
993 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
995 *nr_written = *nr_written +
996 (end - start + PAGE_SIZE) / PAGE_SIZE;
999 } else if (ret < 0) {
1004 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1005 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1006 start + num_bytes - 1, 0);
1008 while (num_bytes > 0) {
1009 cur_alloc_size = num_bytes;
1010 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1011 fs_info->sectorsize, 0, alloc_hint,
1015 cur_alloc_size = ins.offset;
1016 extent_reserved = true;
1018 ram_size = ins.offset;
1019 em = create_io_em(inode, start, ins.offset, /* len */
1020 start, /* orig_start */
1021 ins.objectid, /* block_start */
1022 ins.offset, /* block_len */
1023 ins.offset, /* orig_block_len */
1024 ram_size, /* ram_bytes */
1025 BTRFS_COMPRESS_NONE, /* compress_type */
1026 BTRFS_ORDERED_REGULAR /* type */);
1031 free_extent_map(em);
1033 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1034 ram_size, cur_alloc_size, 0);
1036 goto out_drop_extent_cache;
1038 if (root->root_key.objectid ==
1039 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1040 ret = btrfs_reloc_clone_csums(inode, start,
1043 * Only drop cache here, and process as normal.
1045 * We must not allow extent_clear_unlock_delalloc()
1046 * at out_unlock label to free meta of this ordered
1047 * extent, as its meta should be freed by
1048 * btrfs_finish_ordered_io().
1050 * So we must continue until @start is increased to
1051 * skip current ordered extent.
1054 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1055 start + ram_size - 1, 0);
1058 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1060 /* we're not doing compressed IO, don't unlock the first
1061 * page (which the caller expects to stay locked), don't
1062 * clear any dirty bits and don't set any writeback bits
1064 * Do set the Private2 bit so we know this page was properly
1065 * setup for writepage
1067 page_ops = unlock ? PAGE_UNLOCK : 0;
1068 page_ops |= PAGE_SET_PRIVATE2;
1070 extent_clear_unlock_delalloc(inode, start,
1071 start + ram_size - 1,
1072 delalloc_end, locked_page,
1073 EXTENT_LOCKED | EXTENT_DELALLOC,
1075 if (num_bytes < cur_alloc_size)
1078 num_bytes -= cur_alloc_size;
1079 alloc_hint = ins.objectid + ins.offset;
1080 start += cur_alloc_size;
1081 extent_reserved = false;
1084 * btrfs_reloc_clone_csums() error, since start is increased
1085 * extent_clear_unlock_delalloc() at out_unlock label won't
1086 * free metadata of current ordered extent, we're OK to exit.
1094 out_drop_extent_cache:
1095 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1097 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1098 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1100 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1101 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1102 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1105 * If we reserved an extent for our delalloc range (or a subrange) and
1106 * failed to create the respective ordered extent, then it means that
1107 * when we reserved the extent we decremented the extent's size from
1108 * the data space_info's bytes_may_use counter and incremented the
1109 * space_info's bytes_reserved counter by the same amount. We must make
1110 * sure extent_clear_unlock_delalloc() does not try to decrement again
1111 * the data space_info's bytes_may_use counter, therefore we do not pass
1112 * it the flag EXTENT_CLEAR_DATA_RESV.
1114 if (extent_reserved) {
1115 extent_clear_unlock_delalloc(inode, start,
1116 start + cur_alloc_size,
1117 start + cur_alloc_size,
1121 start += cur_alloc_size;
1125 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1127 clear_bits | EXTENT_CLEAR_DATA_RESV,
1133 * work queue call back to started compression on a file and pages
1135 static noinline void async_cow_start(struct btrfs_work *work)
1137 struct async_cow *async_cow;
1139 async_cow = container_of(work, struct async_cow, work);
1141 compress_file_range(async_cow->inode, async_cow->locked_page,
1142 async_cow->start, async_cow->end, async_cow,
1144 if (num_added == 0) {
1145 btrfs_add_delayed_iput(async_cow->inode);
1146 async_cow->inode = NULL;
1151 * work queue call back to submit previously compressed pages
1153 static noinline void async_cow_submit(struct btrfs_work *work)
1155 struct btrfs_fs_info *fs_info;
1156 struct async_cow *async_cow;
1157 unsigned long nr_pages;
1159 async_cow = container_of(work, struct async_cow, work);
1161 fs_info = async_cow->fs_info;
1162 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1165 /* atomic_sub_return implies a barrier */
1166 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1168 cond_wake_up_nomb(&fs_info->async_submit_wait);
1170 if (async_cow->inode)
1171 submit_compressed_extents(async_cow->inode, async_cow);
1174 static noinline void async_cow_free(struct btrfs_work *work)
1176 struct async_cow *async_cow;
1177 async_cow = container_of(work, struct async_cow, work);
1178 if (async_cow->inode)
1179 btrfs_add_delayed_iput(async_cow->inode);
1183 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1184 u64 start, u64 end, int *page_started,
1185 unsigned long *nr_written,
1186 unsigned int write_flags)
1188 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1189 struct async_cow *async_cow;
1190 unsigned long nr_pages;
1193 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1195 while (start < end) {
1196 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1197 BUG_ON(!async_cow); /* -ENOMEM */
1198 async_cow->inode = igrab(inode);
1199 async_cow->fs_info = fs_info;
1200 async_cow->locked_page = locked_page;
1201 async_cow->start = start;
1202 async_cow->write_flags = write_flags;
1204 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1205 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1208 cur_end = min(end, start + SZ_512K - 1);
1210 async_cow->end = cur_end;
1211 INIT_LIST_HEAD(&async_cow->extents);
1213 btrfs_init_work(&async_cow->work,
1214 btrfs_delalloc_helper,
1215 async_cow_start, async_cow_submit,
1218 nr_pages = (cur_end - start + PAGE_SIZE) >>
1220 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1222 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1224 *nr_written += nr_pages;
1225 start = cur_end + 1;
1231 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1232 u64 bytenr, u64 num_bytes)
1235 struct btrfs_ordered_sum *sums;
1238 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1239 bytenr + num_bytes - 1, &list, 0);
1240 if (ret == 0 && list_empty(&list))
1243 while (!list_empty(&list)) {
1244 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1245 list_del(&sums->list);
1254 * when nowcow writeback call back. This checks for snapshots or COW copies
1255 * of the extents that exist in the file, and COWs the file as required.
1257 * If no cow copies or snapshots exist, we write directly to the existing
1260 static noinline int run_delalloc_nocow(struct inode *inode,
1261 struct page *locked_page,
1262 u64 start, u64 end, int *page_started, int force,
1263 unsigned long *nr_written)
1265 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1266 struct btrfs_root *root = BTRFS_I(inode)->root;
1267 struct extent_buffer *leaf;
1268 struct btrfs_path *path;
1269 struct btrfs_file_extent_item *fi;
1270 struct btrfs_key found_key;
1271 struct extent_map *em;
1286 u64 ino = btrfs_ino(BTRFS_I(inode));
1288 path = btrfs_alloc_path();
1290 extent_clear_unlock_delalloc(inode, start, end, end,
1292 EXTENT_LOCKED | EXTENT_DELALLOC |
1293 EXTENT_DO_ACCOUNTING |
1294 EXTENT_DEFRAG, PAGE_UNLOCK |
1296 PAGE_SET_WRITEBACK |
1297 PAGE_END_WRITEBACK);
1301 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1303 cow_start = (u64)-1;
1306 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1310 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1311 leaf = path->nodes[0];
1312 btrfs_item_key_to_cpu(leaf, &found_key,
1313 path->slots[0] - 1);
1314 if (found_key.objectid == ino &&
1315 found_key.type == BTRFS_EXTENT_DATA_KEY)
1320 leaf = path->nodes[0];
1321 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1322 ret = btrfs_next_leaf(root, path);
1324 if (cow_start != (u64)-1)
1325 cur_offset = cow_start;
1330 leaf = path->nodes[0];
1336 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1338 if (found_key.objectid > ino)
1340 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1341 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1345 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1346 found_key.offset > end)
1349 if (found_key.offset > cur_offset) {
1350 extent_end = found_key.offset;
1355 fi = btrfs_item_ptr(leaf, path->slots[0],
1356 struct btrfs_file_extent_item);
1357 extent_type = btrfs_file_extent_type(leaf, fi);
1359 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1360 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1361 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1362 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1363 extent_offset = btrfs_file_extent_offset(leaf, fi);
1364 extent_end = found_key.offset +
1365 btrfs_file_extent_num_bytes(leaf, fi);
1367 btrfs_file_extent_disk_num_bytes(leaf, fi);
1368 if (extent_end <= start) {
1372 if (disk_bytenr == 0)
1374 if (btrfs_file_extent_compression(leaf, fi) ||
1375 btrfs_file_extent_encryption(leaf, fi) ||
1376 btrfs_file_extent_other_encoding(leaf, fi))
1379 * Do the same check as in btrfs_cross_ref_exist but
1380 * without the unnecessary search.
1383 btrfs_file_extent_generation(leaf, fi) <=
1384 btrfs_root_last_snapshot(&root->root_item))
1386 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1388 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1390 ret = btrfs_cross_ref_exist(root, ino,
1392 extent_offset, disk_bytenr);
1395 * ret could be -EIO if the above fails to read
1399 if (cow_start != (u64)-1)
1400 cur_offset = cow_start;
1404 WARN_ON_ONCE(nolock);
1407 disk_bytenr += extent_offset;
1408 disk_bytenr += cur_offset - found_key.offset;
1409 num_bytes = min(end + 1, extent_end) - cur_offset;
1411 * if there are pending snapshots for this root,
1412 * we fall into common COW way.
1414 if (!nolock && atomic_read(&root->snapshot_force_cow))
1417 * force cow if csum exists in the range.
1418 * this ensure that csum for a given extent are
1419 * either valid or do not exist.
1421 ret = csum_exist_in_range(fs_info, disk_bytenr,
1425 * ret could be -EIO if the above fails to read
1429 if (cow_start != (u64)-1)
1430 cur_offset = cow_start;
1433 WARN_ON_ONCE(nolock);
1436 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1439 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1440 extent_end = found_key.offset +
1441 btrfs_file_extent_ram_bytes(leaf, fi);
1442 extent_end = ALIGN(extent_end,
1443 fs_info->sectorsize);
1448 if (extent_end <= start) {
1451 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1455 if (cow_start == (u64)-1)
1456 cow_start = cur_offset;
1457 cur_offset = extent_end;
1458 if (cur_offset > end)
1464 btrfs_release_path(path);
1465 if (cow_start != (u64)-1) {
1466 ret = cow_file_range(inode, locked_page,
1467 cow_start, found_key.offset - 1,
1468 end, page_started, nr_written, 1,
1472 btrfs_dec_nocow_writers(fs_info,
1476 cow_start = (u64)-1;
1479 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1480 u64 orig_start = found_key.offset - extent_offset;
1482 em = create_io_em(inode, cur_offset, num_bytes,
1484 disk_bytenr, /* block_start */
1485 num_bytes, /* block_len */
1486 disk_num_bytes, /* orig_block_len */
1487 ram_bytes, BTRFS_COMPRESS_NONE,
1488 BTRFS_ORDERED_PREALLOC);
1491 btrfs_dec_nocow_writers(fs_info,
1496 free_extent_map(em);
1499 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1500 type = BTRFS_ORDERED_PREALLOC;
1502 type = BTRFS_ORDERED_NOCOW;
1505 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1506 num_bytes, num_bytes, type);
1508 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1509 BUG_ON(ret); /* -ENOMEM */
1511 if (root->root_key.objectid ==
1512 BTRFS_DATA_RELOC_TREE_OBJECTID)
1514 * Error handled later, as we must prevent
1515 * extent_clear_unlock_delalloc() in error handler
1516 * from freeing metadata of created ordered extent.
1518 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1521 extent_clear_unlock_delalloc(inode, cur_offset,
1522 cur_offset + num_bytes - 1, end,
1523 locked_page, EXTENT_LOCKED |
1525 EXTENT_CLEAR_DATA_RESV,
1526 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1528 cur_offset = extent_end;
1531 * btrfs_reloc_clone_csums() error, now we're OK to call error
1532 * handler, as metadata for created ordered extent will only
1533 * be freed by btrfs_finish_ordered_io().
1537 if (cur_offset > end)
1540 btrfs_release_path(path);
1542 if (cur_offset <= end && cow_start == (u64)-1)
1543 cow_start = cur_offset;
1545 if (cow_start != (u64)-1) {
1547 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1548 page_started, nr_written, 1, NULL);
1554 if (ret && cur_offset < end)
1555 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1556 locked_page, EXTENT_LOCKED |
1557 EXTENT_DELALLOC | EXTENT_DEFRAG |
1558 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1560 PAGE_SET_WRITEBACK |
1561 PAGE_END_WRITEBACK);
1562 btrfs_free_path(path);
1566 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1569 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1570 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1574 * @defrag_bytes is a hint value, no spinlock held here,
1575 * if is not zero, it means the file is defragging.
1576 * Force cow if given extent needs to be defragged.
1578 if (BTRFS_I(inode)->defrag_bytes &&
1579 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1580 EXTENT_DEFRAG, 0, NULL))
1587 * Function to process delayed allocation (create CoW) for ranges which are
1588 * being touched for the first time.
1590 int btrfs_run_delalloc_range(void *private_data, struct page *locked_page,
1591 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1592 struct writeback_control *wbc)
1594 struct inode *inode = private_data;
1596 int force_cow = need_force_cow(inode, start, end);
1597 unsigned int write_flags = wbc_to_write_flags(wbc);
1599 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1600 ret = run_delalloc_nocow(inode, locked_page, start, end,
1601 page_started, 1, nr_written);
1602 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1603 ret = run_delalloc_nocow(inode, locked_page, start, end,
1604 page_started, 0, nr_written);
1605 } else if (!inode_need_compress(inode, start, end)) {
1606 ret = cow_file_range(inode, locked_page, start, end, end,
1607 page_started, nr_written, 1, NULL);
1609 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1610 &BTRFS_I(inode)->runtime_flags);
1611 ret = cow_file_range_async(inode, locked_page, start, end,
1612 page_started, nr_written,
1616 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1621 void btrfs_split_delalloc_extent(struct inode *inode,
1622 struct extent_state *orig, u64 split)
1626 /* not delalloc, ignore it */
1627 if (!(orig->state & EXTENT_DELALLOC))
1630 size = orig->end - orig->start + 1;
1631 if (size > BTRFS_MAX_EXTENT_SIZE) {
1636 * See the explanation in btrfs_merge_delalloc_extent, the same
1637 * applies here, just in reverse.
1639 new_size = orig->end - split + 1;
1640 num_extents = count_max_extents(new_size);
1641 new_size = split - orig->start;
1642 num_extents += count_max_extents(new_size);
1643 if (count_max_extents(size) >= num_extents)
1647 spin_lock(&BTRFS_I(inode)->lock);
1648 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1649 spin_unlock(&BTRFS_I(inode)->lock);
1653 * Handle merged delayed allocation extents so we can keep track of new extents
1654 * that are just merged onto old extents, such as when we are doing sequential
1655 * writes, so we can properly account for the metadata space we'll need.
1657 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1658 struct extent_state *other)
1660 u64 new_size, old_size;
1663 /* not delalloc, ignore it */
1664 if (!(other->state & EXTENT_DELALLOC))
1667 if (new->start > other->start)
1668 new_size = new->end - other->start + 1;
1670 new_size = other->end - new->start + 1;
1672 /* we're not bigger than the max, unreserve the space and go */
1673 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1674 spin_lock(&BTRFS_I(inode)->lock);
1675 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1676 spin_unlock(&BTRFS_I(inode)->lock);
1681 * We have to add up either side to figure out how many extents were
1682 * accounted for before we merged into one big extent. If the number of
1683 * extents we accounted for is <= the amount we need for the new range
1684 * then we can return, otherwise drop. Think of it like this
1688 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1689 * need 2 outstanding extents, on one side we have 1 and the other side
1690 * we have 1 so they are == and we can return. But in this case
1692 * [MAX_SIZE+4k][MAX_SIZE+4k]
1694 * Each range on their own accounts for 2 extents, but merged together
1695 * they are only 3 extents worth of accounting, so we need to drop in
1698 old_size = other->end - other->start + 1;
1699 num_extents = count_max_extents(old_size);
1700 old_size = new->end - new->start + 1;
1701 num_extents += count_max_extents(old_size);
1702 if (count_max_extents(new_size) >= num_extents)
1705 spin_lock(&BTRFS_I(inode)->lock);
1706 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1707 spin_unlock(&BTRFS_I(inode)->lock);
1710 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1711 struct inode *inode)
1713 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1715 spin_lock(&root->delalloc_lock);
1716 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1717 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1718 &root->delalloc_inodes);
1719 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1720 &BTRFS_I(inode)->runtime_flags);
1721 root->nr_delalloc_inodes++;
1722 if (root->nr_delalloc_inodes == 1) {
1723 spin_lock(&fs_info->delalloc_root_lock);
1724 BUG_ON(!list_empty(&root->delalloc_root));
1725 list_add_tail(&root->delalloc_root,
1726 &fs_info->delalloc_roots);
1727 spin_unlock(&fs_info->delalloc_root_lock);
1730 spin_unlock(&root->delalloc_lock);
1734 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1735 struct btrfs_inode *inode)
1737 struct btrfs_fs_info *fs_info = root->fs_info;
1739 if (!list_empty(&inode->delalloc_inodes)) {
1740 list_del_init(&inode->delalloc_inodes);
1741 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1742 &inode->runtime_flags);
1743 root->nr_delalloc_inodes--;
1744 if (!root->nr_delalloc_inodes) {
1745 ASSERT(list_empty(&root->delalloc_inodes));
1746 spin_lock(&fs_info->delalloc_root_lock);
1747 BUG_ON(list_empty(&root->delalloc_root));
1748 list_del_init(&root->delalloc_root);
1749 spin_unlock(&fs_info->delalloc_root_lock);
1754 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1755 struct btrfs_inode *inode)
1757 spin_lock(&root->delalloc_lock);
1758 __btrfs_del_delalloc_inode(root, inode);
1759 spin_unlock(&root->delalloc_lock);
1763 * Properly track delayed allocation bytes in the inode and to maintain the
1764 * list of inodes that have pending delalloc work to be done.
1766 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1769 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1771 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1774 * set_bit and clear bit hooks normally require _irqsave/restore
1775 * but in this case, we are only testing for the DELALLOC
1776 * bit, which is only set or cleared with irqs on
1778 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1779 struct btrfs_root *root = BTRFS_I(inode)->root;
1780 u64 len = state->end + 1 - state->start;
1781 u32 num_extents = count_max_extents(len);
1782 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1784 spin_lock(&BTRFS_I(inode)->lock);
1785 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1786 spin_unlock(&BTRFS_I(inode)->lock);
1788 /* For sanity tests */
1789 if (btrfs_is_testing(fs_info))
1792 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1793 fs_info->delalloc_batch);
1794 spin_lock(&BTRFS_I(inode)->lock);
1795 BTRFS_I(inode)->delalloc_bytes += len;
1796 if (*bits & EXTENT_DEFRAG)
1797 BTRFS_I(inode)->defrag_bytes += len;
1798 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1799 &BTRFS_I(inode)->runtime_flags))
1800 btrfs_add_delalloc_inodes(root, inode);
1801 spin_unlock(&BTRFS_I(inode)->lock);
1804 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1805 (*bits & EXTENT_DELALLOC_NEW)) {
1806 spin_lock(&BTRFS_I(inode)->lock);
1807 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1809 spin_unlock(&BTRFS_I(inode)->lock);
1814 * Once a range is no longer delalloc this function ensures that proper
1815 * accounting happens.
1817 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1818 struct extent_state *state, unsigned *bits)
1820 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1821 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1822 u64 len = state->end + 1 - state->start;
1823 u32 num_extents = count_max_extents(len);
1825 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1826 spin_lock(&inode->lock);
1827 inode->defrag_bytes -= len;
1828 spin_unlock(&inode->lock);
1832 * set_bit and clear bit hooks normally require _irqsave/restore
1833 * but in this case, we are only testing for the DELALLOC
1834 * bit, which is only set or cleared with irqs on
1836 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1837 struct btrfs_root *root = inode->root;
1838 bool do_list = !btrfs_is_free_space_inode(inode);
1840 spin_lock(&inode->lock);
1841 btrfs_mod_outstanding_extents(inode, -num_extents);
1842 spin_unlock(&inode->lock);
1845 * We don't reserve metadata space for space cache inodes so we
1846 * don't need to call dellalloc_release_metadata if there is an
1849 if (*bits & EXTENT_CLEAR_META_RESV &&
1850 root != fs_info->tree_root)
1851 btrfs_delalloc_release_metadata(inode, len, false);
1853 /* For sanity tests. */
1854 if (btrfs_is_testing(fs_info))
1857 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1858 do_list && !(state->state & EXTENT_NORESERVE) &&
1859 (*bits & EXTENT_CLEAR_DATA_RESV))
1860 btrfs_free_reserved_data_space_noquota(
1864 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1865 fs_info->delalloc_batch);
1866 spin_lock(&inode->lock);
1867 inode->delalloc_bytes -= len;
1868 if (do_list && inode->delalloc_bytes == 0 &&
1869 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1870 &inode->runtime_flags))
1871 btrfs_del_delalloc_inode(root, inode);
1872 spin_unlock(&inode->lock);
1875 if ((state->state & EXTENT_DELALLOC_NEW) &&
1876 (*bits & EXTENT_DELALLOC_NEW)) {
1877 spin_lock(&inode->lock);
1878 ASSERT(inode->new_delalloc_bytes >= len);
1879 inode->new_delalloc_bytes -= len;
1880 spin_unlock(&inode->lock);
1885 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1886 * in a chunk's stripe. This function ensures that bios do not span a
1889 * @page - The page we are about to add to the bio
1890 * @size - size we want to add to the bio
1891 * @bio - bio we want to ensure is smaller than a stripe
1892 * @bio_flags - flags of the bio
1894 * return 1 if page cannot be added to the bio
1895 * return 0 if page can be added to the bio
1896 * return error otherwise
1898 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1899 unsigned long bio_flags)
1901 struct inode *inode = page->mapping->host;
1902 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1903 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1908 if (bio_flags & EXTENT_BIO_COMPRESSED)
1911 length = bio->bi_iter.bi_size;
1912 map_length = length;
1913 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1917 if (map_length < length + size)
1923 * in order to insert checksums into the metadata in large chunks,
1924 * we wait until bio submission time. All the pages in the bio are
1925 * checksummed and sums are attached onto the ordered extent record.
1927 * At IO completion time the cums attached on the ordered extent record
1928 * are inserted into the btree
1930 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1933 struct inode *inode = private_data;
1934 blk_status_t ret = 0;
1936 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1937 BUG_ON(ret); /* -ENOMEM */
1942 * extent_io.c submission hook. This does the right thing for csum calculation
1943 * on write, or reading the csums from the tree before a read.
1945 * Rules about async/sync submit,
1946 * a) read: sync submit
1948 * b) write without checksum: sync submit
1950 * c) write with checksum:
1951 * c-1) if bio is issued by fsync: sync submit
1952 * (sync_writers != 0)
1954 * c-2) if root is reloc root: sync submit
1955 * (only in case of buffered IO)
1957 * c-3) otherwise: async submit
1959 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1960 int mirror_num, unsigned long bio_flags,
1963 struct inode *inode = private_data;
1964 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1965 struct btrfs_root *root = BTRFS_I(inode)->root;
1966 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1967 blk_status_t ret = 0;
1969 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1971 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1973 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1974 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1976 if (bio_op(bio) != REQ_OP_WRITE) {
1977 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1981 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1982 ret = btrfs_submit_compressed_read(inode, bio,
1986 } else if (!skip_sum) {
1987 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1992 } else if (async && !skip_sum) {
1993 /* csum items have already been cloned */
1994 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1996 /* we're doing a write, do the async checksumming */
1997 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1999 btrfs_submit_bio_start);
2001 } else if (!skip_sum) {
2002 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2008 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2012 bio->bi_status = ret;
2019 * given a list of ordered sums record them in the inode. This happens
2020 * at IO completion time based on sums calculated at bio submission time.
2022 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2023 struct inode *inode, struct list_head *list)
2025 struct btrfs_ordered_sum *sum;
2028 list_for_each_entry(sum, list, list) {
2029 trans->adding_csums = true;
2030 ret = btrfs_csum_file_blocks(trans,
2031 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2032 trans->adding_csums = false;
2039 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2040 unsigned int extra_bits,
2041 struct extent_state **cached_state, int dedupe)
2043 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2044 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2045 extra_bits, cached_state);
2048 /* see btrfs_writepage_start_hook for details on why this is required */
2049 struct btrfs_writepage_fixup {
2051 struct btrfs_work work;
2054 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2056 struct btrfs_writepage_fixup *fixup;
2057 struct btrfs_ordered_extent *ordered;
2058 struct extent_state *cached_state = NULL;
2059 struct extent_changeset *data_reserved = NULL;
2061 struct inode *inode;
2066 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2070 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2071 ClearPageChecked(page);
2075 inode = page->mapping->host;
2076 page_start = page_offset(page);
2077 page_end = page_offset(page) + PAGE_SIZE - 1;
2079 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2082 /* already ordered? We're done */
2083 if (PagePrivate2(page))
2086 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2089 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2090 page_end, &cached_state);
2092 btrfs_start_ordered_extent(inode, ordered, 1);
2093 btrfs_put_ordered_extent(ordered);
2097 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2100 mapping_set_error(page->mapping, ret);
2101 end_extent_writepage(page, ret, page_start, page_end);
2102 ClearPageChecked(page);
2106 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2109 mapping_set_error(page->mapping, ret);
2110 end_extent_writepage(page, ret, page_start, page_end);
2111 ClearPageChecked(page);
2115 ClearPageChecked(page);
2116 set_page_dirty(page);
2117 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2119 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2125 extent_changeset_free(data_reserved);
2129 * There are a few paths in the higher layers of the kernel that directly
2130 * set the page dirty bit without asking the filesystem if it is a
2131 * good idea. This causes problems because we want to make sure COW
2132 * properly happens and the data=ordered rules are followed.
2134 * In our case any range that doesn't have the ORDERED bit set
2135 * hasn't been properly setup for IO. We kick off an async process
2136 * to fix it up. The async helper will wait for ordered extents, set
2137 * the delalloc bit and make it safe to write the page.
2139 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2141 struct inode *inode = page->mapping->host;
2142 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2143 struct btrfs_writepage_fixup *fixup;
2145 /* this page is properly in the ordered list */
2146 if (TestClearPagePrivate2(page))
2149 if (PageChecked(page))
2152 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2156 SetPageChecked(page);
2158 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2159 btrfs_writepage_fixup_worker, NULL, NULL);
2161 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2165 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2166 struct inode *inode, u64 file_pos,
2167 u64 disk_bytenr, u64 disk_num_bytes,
2168 u64 num_bytes, u64 ram_bytes,
2169 u8 compression, u8 encryption,
2170 u16 other_encoding, int extent_type)
2172 struct btrfs_root *root = BTRFS_I(inode)->root;
2173 struct btrfs_file_extent_item *fi;
2174 struct btrfs_path *path;
2175 struct extent_buffer *leaf;
2176 struct btrfs_key ins;
2178 int extent_inserted = 0;
2181 path = btrfs_alloc_path();
2186 * we may be replacing one extent in the tree with another.
2187 * The new extent is pinned in the extent map, and we don't want
2188 * to drop it from the cache until it is completely in the btree.
2190 * So, tell btrfs_drop_extents to leave this extent in the cache.
2191 * the caller is expected to unpin it and allow it to be merged
2194 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2195 file_pos + num_bytes, NULL, 0,
2196 1, sizeof(*fi), &extent_inserted);
2200 if (!extent_inserted) {
2201 ins.objectid = btrfs_ino(BTRFS_I(inode));
2202 ins.offset = file_pos;
2203 ins.type = BTRFS_EXTENT_DATA_KEY;
2205 path->leave_spinning = 1;
2206 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2211 leaf = path->nodes[0];
2212 fi = btrfs_item_ptr(leaf, path->slots[0],
2213 struct btrfs_file_extent_item);
2214 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2215 btrfs_set_file_extent_type(leaf, fi, extent_type);
2216 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2217 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2218 btrfs_set_file_extent_offset(leaf, fi, 0);
2219 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2220 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2221 btrfs_set_file_extent_compression(leaf, fi, compression);
2222 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2223 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2225 btrfs_mark_buffer_dirty(leaf);
2226 btrfs_release_path(path);
2228 inode_add_bytes(inode, num_bytes);
2230 ins.objectid = disk_bytenr;
2231 ins.offset = disk_num_bytes;
2232 ins.type = BTRFS_EXTENT_ITEM_KEY;
2235 * Release the reserved range from inode dirty range map, as it is
2236 * already moved into delayed_ref_head
2238 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2242 ret = btrfs_alloc_reserved_file_extent(trans, root,
2243 btrfs_ino(BTRFS_I(inode)),
2244 file_pos, qg_released, &ins);
2246 btrfs_free_path(path);
2251 /* snapshot-aware defrag */
2252 struct sa_defrag_extent_backref {
2253 struct rb_node node;
2254 struct old_sa_defrag_extent *old;
2263 struct old_sa_defrag_extent {
2264 struct list_head list;
2265 struct new_sa_defrag_extent *new;
2274 struct new_sa_defrag_extent {
2275 struct rb_root root;
2276 struct list_head head;
2277 struct btrfs_path *path;
2278 struct inode *inode;
2286 static int backref_comp(struct sa_defrag_extent_backref *b1,
2287 struct sa_defrag_extent_backref *b2)
2289 if (b1->root_id < b2->root_id)
2291 else if (b1->root_id > b2->root_id)
2294 if (b1->inum < b2->inum)
2296 else if (b1->inum > b2->inum)
2299 if (b1->file_pos < b2->file_pos)
2301 else if (b1->file_pos > b2->file_pos)
2305 * [------------------------------] ===> (a range of space)
2306 * |<--->| |<---->| =============> (fs/file tree A)
2307 * |<---------------------------->| ===> (fs/file tree B)
2309 * A range of space can refer to two file extents in one tree while
2310 * refer to only one file extent in another tree.
2312 * So we may process a disk offset more than one time(two extents in A)
2313 * and locate at the same extent(one extent in B), then insert two same
2314 * backrefs(both refer to the extent in B).
2319 static void backref_insert(struct rb_root *root,
2320 struct sa_defrag_extent_backref *backref)
2322 struct rb_node **p = &root->rb_node;
2323 struct rb_node *parent = NULL;
2324 struct sa_defrag_extent_backref *entry;
2329 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2331 ret = backref_comp(backref, entry);
2335 p = &(*p)->rb_right;
2338 rb_link_node(&backref->node, parent, p);
2339 rb_insert_color(&backref->node, root);
2343 * Note the backref might has changed, and in this case we just return 0.
2345 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2348 struct btrfs_file_extent_item *extent;
2349 struct old_sa_defrag_extent *old = ctx;
2350 struct new_sa_defrag_extent *new = old->new;
2351 struct btrfs_path *path = new->path;
2352 struct btrfs_key key;
2353 struct btrfs_root *root;
2354 struct sa_defrag_extent_backref *backref;
2355 struct extent_buffer *leaf;
2356 struct inode *inode = new->inode;
2357 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2363 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2364 inum == btrfs_ino(BTRFS_I(inode)))
2367 key.objectid = root_id;
2368 key.type = BTRFS_ROOT_ITEM_KEY;
2369 key.offset = (u64)-1;
2371 root = btrfs_read_fs_root_no_name(fs_info, &key);
2373 if (PTR_ERR(root) == -ENOENT)
2376 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2377 inum, offset, root_id);
2378 return PTR_ERR(root);
2381 key.objectid = inum;
2382 key.type = BTRFS_EXTENT_DATA_KEY;
2383 if (offset > (u64)-1 << 32)
2386 key.offset = offset;
2388 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2389 if (WARN_ON(ret < 0))
2396 leaf = path->nodes[0];
2397 slot = path->slots[0];
2399 if (slot >= btrfs_header_nritems(leaf)) {
2400 ret = btrfs_next_leaf(root, path);
2403 } else if (ret > 0) {
2412 btrfs_item_key_to_cpu(leaf, &key, slot);
2414 if (key.objectid > inum)
2417 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2420 extent = btrfs_item_ptr(leaf, slot,
2421 struct btrfs_file_extent_item);
2423 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2427 * 'offset' refers to the exact key.offset,
2428 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2429 * (key.offset - extent_offset).
2431 if (key.offset != offset)
2434 extent_offset = btrfs_file_extent_offset(leaf, extent);
2435 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2437 if (extent_offset >= old->extent_offset + old->offset +
2438 old->len || extent_offset + num_bytes <=
2439 old->extent_offset + old->offset)
2444 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2450 backref->root_id = root_id;
2451 backref->inum = inum;
2452 backref->file_pos = offset;
2453 backref->num_bytes = num_bytes;
2454 backref->extent_offset = extent_offset;
2455 backref->generation = btrfs_file_extent_generation(leaf, extent);
2457 backref_insert(&new->root, backref);
2460 btrfs_release_path(path);
2465 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2466 struct new_sa_defrag_extent *new)
2468 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2469 struct old_sa_defrag_extent *old, *tmp;
2474 list_for_each_entry_safe(old, tmp, &new->head, list) {
2475 ret = iterate_inodes_from_logical(old->bytenr +
2476 old->extent_offset, fs_info,
2477 path, record_one_backref,
2479 if (ret < 0 && ret != -ENOENT)
2482 /* no backref to be processed for this extent */
2484 list_del(&old->list);
2489 if (list_empty(&new->head))
2495 static int relink_is_mergable(struct extent_buffer *leaf,
2496 struct btrfs_file_extent_item *fi,
2497 struct new_sa_defrag_extent *new)
2499 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2502 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2505 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2508 if (btrfs_file_extent_encryption(leaf, fi) ||
2509 btrfs_file_extent_other_encoding(leaf, fi))
2516 * Note the backref might has changed, and in this case we just return 0.
2518 static noinline int relink_extent_backref(struct btrfs_path *path,
2519 struct sa_defrag_extent_backref *prev,
2520 struct sa_defrag_extent_backref *backref)
2522 struct btrfs_file_extent_item *extent;
2523 struct btrfs_file_extent_item *item;
2524 struct btrfs_ordered_extent *ordered;
2525 struct btrfs_trans_handle *trans;
2526 struct btrfs_root *root;
2527 struct btrfs_key key;
2528 struct extent_buffer *leaf;
2529 struct old_sa_defrag_extent *old = backref->old;
2530 struct new_sa_defrag_extent *new = old->new;
2531 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2532 struct inode *inode;
2533 struct extent_state *cached = NULL;
2542 if (prev && prev->root_id == backref->root_id &&
2543 prev->inum == backref->inum &&
2544 prev->file_pos + prev->num_bytes == backref->file_pos)
2547 /* step 1: get root */
2548 key.objectid = backref->root_id;
2549 key.type = BTRFS_ROOT_ITEM_KEY;
2550 key.offset = (u64)-1;
2552 index = srcu_read_lock(&fs_info->subvol_srcu);
2554 root = btrfs_read_fs_root_no_name(fs_info, &key);
2556 srcu_read_unlock(&fs_info->subvol_srcu, index);
2557 if (PTR_ERR(root) == -ENOENT)
2559 return PTR_ERR(root);
2562 if (btrfs_root_readonly(root)) {
2563 srcu_read_unlock(&fs_info->subvol_srcu, index);
2567 /* step 2: get inode */
2568 key.objectid = backref->inum;
2569 key.type = BTRFS_INODE_ITEM_KEY;
2572 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2573 if (IS_ERR(inode)) {
2574 srcu_read_unlock(&fs_info->subvol_srcu, index);
2578 srcu_read_unlock(&fs_info->subvol_srcu, index);
2580 /* step 3: relink backref */
2581 lock_start = backref->file_pos;
2582 lock_end = backref->file_pos + backref->num_bytes - 1;
2583 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2586 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2588 btrfs_put_ordered_extent(ordered);
2592 trans = btrfs_join_transaction(root);
2593 if (IS_ERR(trans)) {
2594 ret = PTR_ERR(trans);
2598 key.objectid = backref->inum;
2599 key.type = BTRFS_EXTENT_DATA_KEY;
2600 key.offset = backref->file_pos;
2602 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2605 } else if (ret > 0) {
2610 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2611 struct btrfs_file_extent_item);
2613 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2614 backref->generation)
2617 btrfs_release_path(path);
2619 start = backref->file_pos;
2620 if (backref->extent_offset < old->extent_offset + old->offset)
2621 start += old->extent_offset + old->offset -
2622 backref->extent_offset;
2624 len = min(backref->extent_offset + backref->num_bytes,
2625 old->extent_offset + old->offset + old->len);
2626 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2628 ret = btrfs_drop_extents(trans, root, inode, start,
2633 key.objectid = btrfs_ino(BTRFS_I(inode));
2634 key.type = BTRFS_EXTENT_DATA_KEY;
2637 path->leave_spinning = 1;
2639 struct btrfs_file_extent_item *fi;
2641 struct btrfs_key found_key;
2643 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2648 leaf = path->nodes[0];
2649 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2651 fi = btrfs_item_ptr(leaf, path->slots[0],
2652 struct btrfs_file_extent_item);
2653 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2655 if (extent_len + found_key.offset == start &&
2656 relink_is_mergable(leaf, fi, new)) {
2657 btrfs_set_file_extent_num_bytes(leaf, fi,
2659 btrfs_mark_buffer_dirty(leaf);
2660 inode_add_bytes(inode, len);
2666 btrfs_release_path(path);
2671 ret = btrfs_insert_empty_item(trans, root, path, &key,
2674 btrfs_abort_transaction(trans, ret);
2678 leaf = path->nodes[0];
2679 item = btrfs_item_ptr(leaf, path->slots[0],
2680 struct btrfs_file_extent_item);
2681 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2682 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2683 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2684 btrfs_set_file_extent_num_bytes(leaf, item, len);
2685 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2686 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2687 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2688 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2689 btrfs_set_file_extent_encryption(leaf, item, 0);
2690 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2692 btrfs_mark_buffer_dirty(leaf);
2693 inode_add_bytes(inode, len);
2694 btrfs_release_path(path);
2696 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2698 backref->root_id, backref->inum,
2699 new->file_pos); /* start - extent_offset */
2701 btrfs_abort_transaction(trans, ret);
2707 btrfs_release_path(path);
2708 path->leave_spinning = 0;
2709 btrfs_end_transaction(trans);
2711 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2717 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2719 struct old_sa_defrag_extent *old, *tmp;
2724 list_for_each_entry_safe(old, tmp, &new->head, list) {
2730 static void relink_file_extents(struct new_sa_defrag_extent *new)
2732 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2733 struct btrfs_path *path;
2734 struct sa_defrag_extent_backref *backref;
2735 struct sa_defrag_extent_backref *prev = NULL;
2736 struct rb_node *node;
2739 path = btrfs_alloc_path();
2743 if (!record_extent_backrefs(path, new)) {
2744 btrfs_free_path(path);
2747 btrfs_release_path(path);
2750 node = rb_first(&new->root);
2753 rb_erase(node, &new->root);
2755 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2757 ret = relink_extent_backref(path, prev, backref);
2770 btrfs_free_path(path);
2772 free_sa_defrag_extent(new);
2774 atomic_dec(&fs_info->defrag_running);
2775 wake_up(&fs_info->transaction_wait);
2778 static struct new_sa_defrag_extent *
2779 record_old_file_extents(struct inode *inode,
2780 struct btrfs_ordered_extent *ordered)
2782 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2783 struct btrfs_root *root = BTRFS_I(inode)->root;
2784 struct btrfs_path *path;
2785 struct btrfs_key key;
2786 struct old_sa_defrag_extent *old;
2787 struct new_sa_defrag_extent *new;
2790 new = kmalloc(sizeof(*new), GFP_NOFS);
2795 new->file_pos = ordered->file_offset;
2796 new->len = ordered->len;
2797 new->bytenr = ordered->start;
2798 new->disk_len = ordered->disk_len;
2799 new->compress_type = ordered->compress_type;
2800 new->root = RB_ROOT;
2801 INIT_LIST_HEAD(&new->head);
2803 path = btrfs_alloc_path();
2807 key.objectid = btrfs_ino(BTRFS_I(inode));
2808 key.type = BTRFS_EXTENT_DATA_KEY;
2809 key.offset = new->file_pos;
2811 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2814 if (ret > 0 && path->slots[0] > 0)
2817 /* find out all the old extents for the file range */
2819 struct btrfs_file_extent_item *extent;
2820 struct extent_buffer *l;
2829 slot = path->slots[0];
2831 if (slot >= btrfs_header_nritems(l)) {
2832 ret = btrfs_next_leaf(root, path);
2840 btrfs_item_key_to_cpu(l, &key, slot);
2842 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2844 if (key.type != BTRFS_EXTENT_DATA_KEY)
2846 if (key.offset >= new->file_pos + new->len)
2849 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2851 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2852 if (key.offset + num_bytes < new->file_pos)
2855 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2859 extent_offset = btrfs_file_extent_offset(l, extent);
2861 old = kmalloc(sizeof(*old), GFP_NOFS);
2865 offset = max(new->file_pos, key.offset);
2866 end = min(new->file_pos + new->len, key.offset + num_bytes);
2868 old->bytenr = disk_bytenr;
2869 old->extent_offset = extent_offset;
2870 old->offset = offset - key.offset;
2871 old->len = end - offset;
2874 list_add_tail(&old->list, &new->head);
2880 btrfs_free_path(path);
2881 atomic_inc(&fs_info->defrag_running);
2886 btrfs_free_path(path);
2888 free_sa_defrag_extent(new);
2892 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2895 struct btrfs_block_group_cache *cache;
2897 cache = btrfs_lookup_block_group(fs_info, start);
2900 spin_lock(&cache->lock);
2901 cache->delalloc_bytes -= len;
2902 spin_unlock(&cache->lock);
2904 btrfs_put_block_group(cache);
2907 /* as ordered data IO finishes, this gets called so we can finish
2908 * an ordered extent if the range of bytes in the file it covers are
2911 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2913 struct inode *inode = ordered_extent->inode;
2914 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2915 struct btrfs_root *root = BTRFS_I(inode)->root;
2916 struct btrfs_trans_handle *trans = NULL;
2917 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2918 struct extent_state *cached_state = NULL;
2919 struct new_sa_defrag_extent *new = NULL;
2920 int compress_type = 0;
2922 u64 logical_len = ordered_extent->len;
2924 bool truncated = false;
2925 bool range_locked = false;
2926 bool clear_new_delalloc_bytes = false;
2927 bool clear_reserved_extent = true;
2929 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2930 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2931 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2932 clear_new_delalloc_bytes = true;
2934 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2936 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2941 btrfs_free_io_failure_record(BTRFS_I(inode),
2942 ordered_extent->file_offset,
2943 ordered_extent->file_offset +
2944 ordered_extent->len - 1);
2946 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2948 logical_len = ordered_extent->truncated_len;
2949 /* Truncated the entire extent, don't bother adding */
2954 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2955 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2958 * For mwrite(mmap + memset to write) case, we still reserve
2959 * space for NOCOW range.
2960 * As NOCOW won't cause a new delayed ref, just free the space
2962 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2963 ordered_extent->len);
2964 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2966 trans = btrfs_join_transaction_nolock(root);
2968 trans = btrfs_join_transaction(root);
2969 if (IS_ERR(trans)) {
2970 ret = PTR_ERR(trans);
2974 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2975 ret = btrfs_update_inode_fallback(trans, root, inode);
2976 if (ret) /* -ENOMEM or corruption */
2977 btrfs_abort_transaction(trans, ret);
2981 range_locked = true;
2982 lock_extent_bits(io_tree, ordered_extent->file_offset,
2983 ordered_extent->file_offset + ordered_extent->len - 1,
2986 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2987 ordered_extent->file_offset + ordered_extent->len - 1,
2988 EXTENT_DEFRAG, 0, cached_state);
2990 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2991 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2992 /* the inode is shared */
2993 new = record_old_file_extents(inode, ordered_extent);
2995 clear_extent_bit(io_tree, ordered_extent->file_offset,
2996 ordered_extent->file_offset + ordered_extent->len - 1,
2997 EXTENT_DEFRAG, 0, 0, &cached_state);
3001 trans = btrfs_join_transaction_nolock(root);
3003 trans = btrfs_join_transaction(root);
3004 if (IS_ERR(trans)) {
3005 ret = PTR_ERR(trans);
3010 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3012 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3013 compress_type = ordered_extent->compress_type;
3014 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3015 BUG_ON(compress_type);
3016 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3017 ordered_extent->len);
3018 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3019 ordered_extent->file_offset,
3020 ordered_extent->file_offset +
3023 BUG_ON(root == fs_info->tree_root);
3024 ret = insert_reserved_file_extent(trans, inode,
3025 ordered_extent->file_offset,
3026 ordered_extent->start,
3027 ordered_extent->disk_len,
3028 logical_len, logical_len,
3029 compress_type, 0, 0,
3030 BTRFS_FILE_EXTENT_REG);
3032 clear_reserved_extent = false;
3033 btrfs_release_delalloc_bytes(fs_info,
3034 ordered_extent->start,
3035 ordered_extent->disk_len);
3038 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3039 ordered_extent->file_offset, ordered_extent->len,
3042 btrfs_abort_transaction(trans, ret);
3046 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3048 btrfs_abort_transaction(trans, ret);
3052 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3053 ret = btrfs_update_inode_fallback(trans, root, inode);
3054 if (ret) { /* -ENOMEM or corruption */
3055 btrfs_abort_transaction(trans, ret);
3060 if (range_locked || clear_new_delalloc_bytes) {
3061 unsigned int clear_bits = 0;
3064 clear_bits |= EXTENT_LOCKED;
3065 if (clear_new_delalloc_bytes)
3066 clear_bits |= EXTENT_DELALLOC_NEW;
3067 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3068 ordered_extent->file_offset,
3069 ordered_extent->file_offset +
3070 ordered_extent->len - 1,
3072 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3077 btrfs_end_transaction(trans);
3079 if (ret || truncated) {
3083 start = ordered_extent->file_offset + logical_len;
3085 start = ordered_extent->file_offset;
3086 end = ordered_extent->file_offset + ordered_extent->len - 1;
3087 clear_extent_uptodate(io_tree, start, end, NULL);
3089 /* Drop the cache for the part of the extent we didn't write. */
3090 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3093 * If the ordered extent had an IOERR or something else went
3094 * wrong we need to return the space for this ordered extent
3095 * back to the allocator. We only free the extent in the
3096 * truncated case if we didn't write out the extent at all.
3098 * If we made it past insert_reserved_file_extent before we
3099 * errored out then we don't need to do this as the accounting
3100 * has already been done.
3102 if ((ret || !logical_len) &&
3103 clear_reserved_extent &&
3104 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3105 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3106 btrfs_free_reserved_extent(fs_info,
3107 ordered_extent->start,
3108 ordered_extent->disk_len, 1);
3113 * This needs to be done to make sure anybody waiting knows we are done
3114 * updating everything for this ordered extent.
3116 btrfs_remove_ordered_extent(inode, ordered_extent);
3118 /* for snapshot-aware defrag */
3121 free_sa_defrag_extent(new);
3122 atomic_dec(&fs_info->defrag_running);
3124 relink_file_extents(new);
3129 btrfs_put_ordered_extent(ordered_extent);
3130 /* once for the tree */
3131 btrfs_put_ordered_extent(ordered_extent);
3133 /* Try to release some metadata so we don't get an OOM but don't wait */
3134 btrfs_btree_balance_dirty_nodelay(fs_info);
3139 static void finish_ordered_fn(struct btrfs_work *work)
3141 struct btrfs_ordered_extent *ordered_extent;
3142 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3143 btrfs_finish_ordered_io(ordered_extent);
3146 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3147 u64 end, int uptodate)
3149 struct inode *inode = page->mapping->host;
3150 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3151 struct btrfs_ordered_extent *ordered_extent = NULL;
3152 struct btrfs_workqueue *wq;
3153 btrfs_work_func_t func;
3155 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3157 ClearPagePrivate2(page);
3158 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3159 end - start + 1, uptodate))
3162 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3163 wq = fs_info->endio_freespace_worker;
3164 func = btrfs_freespace_write_helper;
3166 wq = fs_info->endio_write_workers;
3167 func = btrfs_endio_write_helper;
3170 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3172 btrfs_queue_work(wq, &ordered_extent->work);
3175 static int __readpage_endio_check(struct inode *inode,
3176 struct btrfs_io_bio *io_bio,
3177 int icsum, struct page *page,
3178 int pgoff, u64 start, size_t len)
3184 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3186 kaddr = kmap_atomic(page);
3187 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3188 btrfs_csum_final(csum, (u8 *)&csum);
3189 if (csum != csum_expected)
3192 kunmap_atomic(kaddr);
3195 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3196 io_bio->mirror_num);
3197 memset(kaddr + pgoff, 1, len);
3198 flush_dcache_page(page);
3199 kunmap_atomic(kaddr);
3204 * when reads are done, we need to check csums to verify the data is correct
3205 * if there's a match, we allow the bio to finish. If not, the code in
3206 * extent_io.c will try to find good copies for us.
3208 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3209 u64 phy_offset, struct page *page,
3210 u64 start, u64 end, int mirror)
3212 size_t offset = start - page_offset(page);
3213 struct inode *inode = page->mapping->host;
3214 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3215 struct btrfs_root *root = BTRFS_I(inode)->root;
3217 if (PageChecked(page)) {
3218 ClearPageChecked(page);
3222 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3225 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3226 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3227 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3231 phy_offset >>= inode->i_sb->s_blocksize_bits;
3232 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3233 start, (size_t)(end - start + 1));
3237 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3239 * @inode: The inode we want to perform iput on
3241 * This function uses the generic vfs_inode::i_count to track whether we should
3242 * just decrement it (in case it's > 1) or if this is the last iput then link
3243 * the inode to the delayed iput machinery. Delayed iputs are processed at
3244 * transaction commit time/superblock commit/cleaner kthread.
3246 void btrfs_add_delayed_iput(struct inode *inode)
3248 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3249 struct btrfs_inode *binode = BTRFS_I(inode);
3251 if (atomic_add_unless(&inode->i_count, -1, 1))
3254 spin_lock(&fs_info->delayed_iput_lock);
3255 ASSERT(list_empty(&binode->delayed_iput));
3256 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3257 spin_unlock(&fs_info->delayed_iput_lock);
3260 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3263 spin_lock(&fs_info->delayed_iput_lock);
3264 while (!list_empty(&fs_info->delayed_iputs)) {
3265 struct btrfs_inode *inode;
3267 inode = list_first_entry(&fs_info->delayed_iputs,
3268 struct btrfs_inode, delayed_iput);
3269 list_del_init(&inode->delayed_iput);
3270 spin_unlock(&fs_info->delayed_iput_lock);
3271 iput(&inode->vfs_inode);
3272 spin_lock(&fs_info->delayed_iput_lock);
3274 spin_unlock(&fs_info->delayed_iput_lock);
3278 * This creates an orphan entry for the given inode in case something goes wrong
3279 * in the middle of an unlink.
3281 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3282 struct btrfs_inode *inode)
3286 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3287 if (ret && ret != -EEXIST) {
3288 btrfs_abort_transaction(trans, ret);
3296 * We have done the delete so we can go ahead and remove the orphan item for
3297 * this particular inode.
3299 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3300 struct btrfs_inode *inode)
3302 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3306 * this cleans up any orphans that may be left on the list from the last use
3309 int btrfs_orphan_cleanup(struct btrfs_root *root)
3311 struct btrfs_fs_info *fs_info = root->fs_info;
3312 struct btrfs_path *path;
3313 struct extent_buffer *leaf;
3314 struct btrfs_key key, found_key;
3315 struct btrfs_trans_handle *trans;
3316 struct inode *inode;
3317 u64 last_objectid = 0;
3318 int ret = 0, nr_unlink = 0;
3320 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3323 path = btrfs_alloc_path();
3328 path->reada = READA_BACK;
3330 key.objectid = BTRFS_ORPHAN_OBJECTID;
3331 key.type = BTRFS_ORPHAN_ITEM_KEY;
3332 key.offset = (u64)-1;
3335 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3340 * if ret == 0 means we found what we were searching for, which
3341 * is weird, but possible, so only screw with path if we didn't
3342 * find the key and see if we have stuff that matches
3346 if (path->slots[0] == 0)
3351 /* pull out the item */
3352 leaf = path->nodes[0];
3353 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3355 /* make sure the item matches what we want */
3356 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3358 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3361 /* release the path since we're done with it */
3362 btrfs_release_path(path);
3365 * this is where we are basically btrfs_lookup, without the
3366 * crossing root thing. we store the inode number in the
3367 * offset of the orphan item.
3370 if (found_key.offset == last_objectid) {
3372 "Error removing orphan entry, stopping orphan cleanup");
3377 last_objectid = found_key.offset;
3379 found_key.objectid = found_key.offset;
3380 found_key.type = BTRFS_INODE_ITEM_KEY;
3381 found_key.offset = 0;
3382 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3383 ret = PTR_ERR_OR_ZERO(inode);
3384 if (ret && ret != -ENOENT)
3387 if (ret == -ENOENT && root == fs_info->tree_root) {
3388 struct btrfs_root *dead_root;
3389 struct btrfs_fs_info *fs_info = root->fs_info;
3390 int is_dead_root = 0;
3393 * this is an orphan in the tree root. Currently these
3394 * could come from 2 sources:
3395 * a) a snapshot deletion in progress
3396 * b) a free space cache inode
3397 * We need to distinguish those two, as the snapshot
3398 * orphan must not get deleted.
3399 * find_dead_roots already ran before us, so if this
3400 * is a snapshot deletion, we should find the root
3401 * in the dead_roots list
3403 spin_lock(&fs_info->trans_lock);
3404 list_for_each_entry(dead_root, &fs_info->dead_roots,
3406 if (dead_root->root_key.objectid ==
3407 found_key.objectid) {
3412 spin_unlock(&fs_info->trans_lock);
3414 /* prevent this orphan from being found again */
3415 key.offset = found_key.objectid - 1;
3422 * If we have an inode with links, there are a couple of
3423 * possibilities. Old kernels (before v3.12) used to create an
3424 * orphan item for truncate indicating that there were possibly
3425 * extent items past i_size that needed to be deleted. In v3.12,
3426 * truncate was changed to update i_size in sync with the extent
3427 * items, but the (useless) orphan item was still created. Since
3428 * v4.18, we don't create the orphan item for truncate at all.
3430 * So, this item could mean that we need to do a truncate, but
3431 * only if this filesystem was last used on a pre-v3.12 kernel
3432 * and was not cleanly unmounted. The odds of that are quite
3433 * slim, and it's a pain to do the truncate now, so just delete
3436 * It's also possible that this orphan item was supposed to be
3437 * deleted but wasn't. The inode number may have been reused,
3438 * but either way, we can delete the orphan item.
3440 if (ret == -ENOENT || inode->i_nlink) {
3443 trans = btrfs_start_transaction(root, 1);
3444 if (IS_ERR(trans)) {
3445 ret = PTR_ERR(trans);
3448 btrfs_debug(fs_info, "auto deleting %Lu",
3449 found_key.objectid);
3450 ret = btrfs_del_orphan_item(trans, root,
3451 found_key.objectid);
3452 btrfs_end_transaction(trans);
3460 /* this will do delete_inode and everything for us */
3463 /* release the path since we're done with it */
3464 btrfs_release_path(path);
3466 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3468 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3469 trans = btrfs_join_transaction(root);
3471 btrfs_end_transaction(trans);
3475 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3479 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3480 btrfs_free_path(path);
3485 * very simple check to peek ahead in the leaf looking for xattrs. If we
3486 * don't find any xattrs, we know there can't be any acls.
3488 * slot is the slot the inode is in, objectid is the objectid of the inode
3490 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3491 int slot, u64 objectid,
3492 int *first_xattr_slot)
3494 u32 nritems = btrfs_header_nritems(leaf);
3495 struct btrfs_key found_key;
3496 static u64 xattr_access = 0;
3497 static u64 xattr_default = 0;
3500 if (!xattr_access) {
3501 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3502 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3503 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3504 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3508 *first_xattr_slot = -1;
3509 while (slot < nritems) {
3510 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3512 /* we found a different objectid, there must not be acls */
3513 if (found_key.objectid != objectid)
3516 /* we found an xattr, assume we've got an acl */
3517 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3518 if (*first_xattr_slot == -1)
3519 *first_xattr_slot = slot;
3520 if (found_key.offset == xattr_access ||
3521 found_key.offset == xattr_default)
3526 * we found a key greater than an xattr key, there can't
3527 * be any acls later on
3529 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3536 * it goes inode, inode backrefs, xattrs, extents,
3537 * so if there are a ton of hard links to an inode there can
3538 * be a lot of backrefs. Don't waste time searching too hard,
3539 * this is just an optimization
3544 /* we hit the end of the leaf before we found an xattr or
3545 * something larger than an xattr. We have to assume the inode
3548 if (*first_xattr_slot == -1)
3549 *first_xattr_slot = slot;
3554 * read an inode from the btree into the in-memory inode
3556 static int btrfs_read_locked_inode(struct inode *inode,
3557 struct btrfs_path *in_path)
3559 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3560 struct btrfs_path *path = in_path;
3561 struct extent_buffer *leaf;
3562 struct btrfs_inode_item *inode_item;
3563 struct btrfs_root *root = BTRFS_I(inode)->root;
3564 struct btrfs_key location;
3569 bool filled = false;
3570 int first_xattr_slot;
3572 ret = btrfs_fill_inode(inode, &rdev);
3577 path = btrfs_alloc_path();
3582 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3584 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3586 if (path != in_path)
3587 btrfs_free_path(path);
3591 leaf = path->nodes[0];
3596 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3597 struct btrfs_inode_item);
3598 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3599 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3600 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3601 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3602 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3604 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3605 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3607 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3608 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3610 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3611 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3613 BTRFS_I(inode)->i_otime.tv_sec =
3614 btrfs_timespec_sec(leaf, &inode_item->otime);
3615 BTRFS_I(inode)->i_otime.tv_nsec =
3616 btrfs_timespec_nsec(leaf, &inode_item->otime);
3618 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3619 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3620 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3622 inode_set_iversion_queried(inode,
3623 btrfs_inode_sequence(leaf, inode_item));
3624 inode->i_generation = BTRFS_I(inode)->generation;
3626 rdev = btrfs_inode_rdev(leaf, inode_item);
3628 BTRFS_I(inode)->index_cnt = (u64)-1;
3629 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3633 * If we were modified in the current generation and evicted from memory
3634 * and then re-read we need to do a full sync since we don't have any
3635 * idea about which extents were modified before we were evicted from
3638 * This is required for both inode re-read from disk and delayed inode
3639 * in delayed_nodes_tree.
3641 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3642 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3643 &BTRFS_I(inode)->runtime_flags);
3646 * We don't persist the id of the transaction where an unlink operation
3647 * against the inode was last made. So here we assume the inode might
3648 * have been evicted, and therefore the exact value of last_unlink_trans
3649 * lost, and set it to last_trans to avoid metadata inconsistencies
3650 * between the inode and its parent if the inode is fsync'ed and the log
3651 * replayed. For example, in the scenario:
3654 * ln mydir/foo mydir/bar
3657 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3658 * xfs_io -c fsync mydir/foo
3660 * mount fs, triggers fsync log replay
3662 * We must make sure that when we fsync our inode foo we also log its
3663 * parent inode, otherwise after log replay the parent still has the
3664 * dentry with the "bar" name but our inode foo has a link count of 1
3665 * and doesn't have an inode ref with the name "bar" anymore.
3667 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3668 * but it guarantees correctness at the expense of occasional full
3669 * transaction commits on fsync if our inode is a directory, or if our
3670 * inode is not a directory, logging its parent unnecessarily.
3672 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3674 * Similar reasoning for last_link_trans, needs to be set otherwise
3675 * for a case like the following:
3680 * echo 2 > /proc/sys/vm/drop_caches
3684 * Would result in link bar and directory A not existing after the power
3687 BTRFS_I(inode)->last_link_trans = BTRFS_I(inode)->last_trans;
3690 if (inode->i_nlink != 1 ||
3691 path->slots[0] >= btrfs_header_nritems(leaf))
3694 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3695 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3698 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3699 if (location.type == BTRFS_INODE_REF_KEY) {
3700 struct btrfs_inode_ref *ref;
3702 ref = (struct btrfs_inode_ref *)ptr;
3703 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3704 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3705 struct btrfs_inode_extref *extref;
3707 extref = (struct btrfs_inode_extref *)ptr;
3708 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3713 * try to precache a NULL acl entry for files that don't have
3714 * any xattrs or acls
3716 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3717 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3718 if (first_xattr_slot != -1) {
3719 path->slots[0] = first_xattr_slot;
3720 ret = btrfs_load_inode_props(inode, path);
3723 "error loading props for ino %llu (root %llu): %d",
3724 btrfs_ino(BTRFS_I(inode)),
3725 root->root_key.objectid, ret);
3727 if (path != in_path)
3728 btrfs_free_path(path);
3731 cache_no_acl(inode);
3733 switch (inode->i_mode & S_IFMT) {
3735 inode->i_mapping->a_ops = &btrfs_aops;
3736 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3737 inode->i_fop = &btrfs_file_operations;
3738 inode->i_op = &btrfs_file_inode_operations;
3741 inode->i_fop = &btrfs_dir_file_operations;
3742 inode->i_op = &btrfs_dir_inode_operations;
3745 inode->i_op = &btrfs_symlink_inode_operations;
3746 inode_nohighmem(inode);
3747 inode->i_mapping->a_ops = &btrfs_aops;
3750 inode->i_op = &btrfs_special_inode_operations;
3751 init_special_inode(inode, inode->i_mode, rdev);
3755 btrfs_sync_inode_flags_to_i_flags(inode);
3760 * given a leaf and an inode, copy the inode fields into the leaf
3762 static void fill_inode_item(struct btrfs_trans_handle *trans,
3763 struct extent_buffer *leaf,
3764 struct btrfs_inode_item *item,
3765 struct inode *inode)
3767 struct btrfs_map_token token;
3769 btrfs_init_map_token(&token);
3771 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3772 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3773 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3775 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3776 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3778 btrfs_set_token_timespec_sec(leaf, &item->atime,
3779 inode->i_atime.tv_sec, &token);
3780 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3781 inode->i_atime.tv_nsec, &token);
3783 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3784 inode->i_mtime.tv_sec, &token);
3785 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3786 inode->i_mtime.tv_nsec, &token);
3788 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3789 inode->i_ctime.tv_sec, &token);
3790 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3791 inode->i_ctime.tv_nsec, &token);
3793 btrfs_set_token_timespec_sec(leaf, &item->otime,
3794 BTRFS_I(inode)->i_otime.tv_sec, &token);
3795 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3796 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3798 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3800 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3802 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3804 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3805 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3806 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3807 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3811 * copy everything in the in-memory inode into the btree.
3813 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3814 struct btrfs_root *root, struct inode *inode)
3816 struct btrfs_inode_item *inode_item;
3817 struct btrfs_path *path;
3818 struct extent_buffer *leaf;
3821 path = btrfs_alloc_path();
3825 path->leave_spinning = 1;
3826 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3834 leaf = path->nodes[0];
3835 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3836 struct btrfs_inode_item);
3838 fill_inode_item(trans, leaf, inode_item, inode);
3839 btrfs_mark_buffer_dirty(leaf);
3840 btrfs_set_inode_last_trans(trans, inode);
3843 btrfs_free_path(path);
3848 * copy everything in the in-memory inode into the btree.
3850 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3851 struct btrfs_root *root, struct inode *inode)
3853 struct btrfs_fs_info *fs_info = root->fs_info;
3857 * If the inode is a free space inode, we can deadlock during commit
3858 * if we put it into the delayed code.
3860 * The data relocation inode should also be directly updated
3863 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3864 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3865 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3866 btrfs_update_root_times(trans, root);
3868 ret = btrfs_delayed_update_inode(trans, root, inode);
3870 btrfs_set_inode_last_trans(trans, inode);
3874 return btrfs_update_inode_item(trans, root, inode);
3877 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3878 struct btrfs_root *root,
3879 struct inode *inode)
3883 ret = btrfs_update_inode(trans, root, inode);
3885 return btrfs_update_inode_item(trans, root, inode);
3890 * unlink helper that gets used here in inode.c and in the tree logging
3891 * recovery code. It remove a link in a directory with a given name, and
3892 * also drops the back refs in the inode to the directory
3894 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3895 struct btrfs_root *root,
3896 struct btrfs_inode *dir,
3897 struct btrfs_inode *inode,
3898 const char *name, int name_len)
3900 struct btrfs_fs_info *fs_info = root->fs_info;
3901 struct btrfs_path *path;
3903 struct extent_buffer *leaf;
3904 struct btrfs_dir_item *di;
3905 struct btrfs_key key;
3907 u64 ino = btrfs_ino(inode);
3908 u64 dir_ino = btrfs_ino(dir);
3910 path = btrfs_alloc_path();
3916 path->leave_spinning = 1;
3917 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3918 name, name_len, -1);
3919 if (IS_ERR_OR_NULL(di)) {
3920 ret = di ? PTR_ERR(di) : -ENOENT;
3923 leaf = path->nodes[0];
3924 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3925 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3928 btrfs_release_path(path);
3931 * If we don't have dir index, we have to get it by looking up
3932 * the inode ref, since we get the inode ref, remove it directly,
3933 * it is unnecessary to do delayed deletion.
3935 * But if we have dir index, needn't search inode ref to get it.
3936 * Since the inode ref is close to the inode item, it is better
3937 * that we delay to delete it, and just do this deletion when
3938 * we update the inode item.
3940 if (inode->dir_index) {
3941 ret = btrfs_delayed_delete_inode_ref(inode);
3943 index = inode->dir_index;
3948 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3952 "failed to delete reference to %.*s, inode %llu parent %llu",
3953 name_len, name, ino, dir_ino);
3954 btrfs_abort_transaction(trans, ret);
3958 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3960 btrfs_abort_transaction(trans, ret);
3964 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3966 if (ret != 0 && ret != -ENOENT) {
3967 btrfs_abort_transaction(trans, ret);
3971 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3976 btrfs_abort_transaction(trans, ret);
3978 btrfs_free_path(path);
3982 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3983 inode_inc_iversion(&inode->vfs_inode);
3984 inode_inc_iversion(&dir->vfs_inode);
3985 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3986 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3987 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3992 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3993 struct btrfs_root *root,
3994 struct btrfs_inode *dir, struct btrfs_inode *inode,
3995 const char *name, int name_len)
3998 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4000 drop_nlink(&inode->vfs_inode);
4001 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4007 * helper to start transaction for unlink and rmdir.
4009 * unlink and rmdir are special in btrfs, they do not always free space, so
4010 * if we cannot make our reservations the normal way try and see if there is
4011 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4012 * allow the unlink to occur.
4014 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4016 struct btrfs_root *root = BTRFS_I(dir)->root;
4019 * 1 for the possible orphan item
4020 * 1 for the dir item
4021 * 1 for the dir index
4022 * 1 for the inode ref
4025 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4028 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4030 struct btrfs_root *root = BTRFS_I(dir)->root;
4031 struct btrfs_trans_handle *trans;
4032 struct inode *inode = d_inode(dentry);
4035 trans = __unlink_start_trans(dir);
4037 return PTR_ERR(trans);
4039 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4042 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4043 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4044 dentry->d_name.len);
4048 if (inode->i_nlink == 0) {
4049 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4055 btrfs_end_transaction(trans);
4056 btrfs_btree_balance_dirty(root->fs_info);
4060 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4061 struct inode *dir, u64 objectid,
4062 const char *name, int name_len)
4064 struct btrfs_root *root = BTRFS_I(dir)->root;
4065 struct btrfs_path *path;
4066 struct extent_buffer *leaf;
4067 struct btrfs_dir_item *di;
4068 struct btrfs_key key;
4071 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4073 path = btrfs_alloc_path();
4077 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4078 name, name_len, -1);
4079 if (IS_ERR_OR_NULL(di)) {
4080 ret = di ? PTR_ERR(di) : -ENOENT;
4084 leaf = path->nodes[0];
4085 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4086 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4087 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4089 btrfs_abort_transaction(trans, ret);
4092 btrfs_release_path(path);
4094 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4095 dir_ino, &index, name, name_len);
4097 if (ret != -ENOENT) {
4098 btrfs_abort_transaction(trans, ret);
4101 di = btrfs_search_dir_index_item(root, path, dir_ino,
4103 if (IS_ERR_OR_NULL(di)) {
4108 btrfs_abort_transaction(trans, ret);
4112 leaf = path->nodes[0];
4113 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4116 btrfs_release_path(path);
4118 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4120 btrfs_abort_transaction(trans, ret);
4124 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4125 inode_inc_iversion(dir);
4126 dir->i_mtime = dir->i_ctime = current_time(dir);
4127 ret = btrfs_update_inode_fallback(trans, root, dir);
4129 btrfs_abort_transaction(trans, ret);
4131 btrfs_free_path(path);
4136 * Helper to check if the subvolume references other subvolumes or if it's
4139 static noinline int may_destroy_subvol(struct btrfs_root *root)
4141 struct btrfs_fs_info *fs_info = root->fs_info;
4142 struct btrfs_path *path;
4143 struct btrfs_dir_item *di;
4144 struct btrfs_key key;
4148 path = btrfs_alloc_path();
4152 /* Make sure this root isn't set as the default subvol */
4153 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4154 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4155 dir_id, "default", 7, 0);
4156 if (di && !IS_ERR(di)) {
4157 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4158 if (key.objectid == root->root_key.objectid) {
4161 "deleting default subvolume %llu is not allowed",
4165 btrfs_release_path(path);
4168 key.objectid = root->root_key.objectid;
4169 key.type = BTRFS_ROOT_REF_KEY;
4170 key.offset = (u64)-1;
4172 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4178 if (path->slots[0] > 0) {
4180 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4181 if (key.objectid == root->root_key.objectid &&
4182 key.type == BTRFS_ROOT_REF_KEY)
4186 btrfs_free_path(path);
4190 /* Delete all dentries for inodes belonging to the root */
4191 static void btrfs_prune_dentries(struct btrfs_root *root)
4193 struct btrfs_fs_info *fs_info = root->fs_info;
4194 struct rb_node *node;
4195 struct rb_node *prev;
4196 struct btrfs_inode *entry;
4197 struct inode *inode;
4200 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4201 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4203 spin_lock(&root->inode_lock);
4205 node = root->inode_tree.rb_node;
4209 entry = rb_entry(node, struct btrfs_inode, rb_node);
4211 if (objectid < btrfs_ino(entry))
4212 node = node->rb_left;
4213 else if (objectid > btrfs_ino(entry))
4214 node = node->rb_right;
4220 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4221 if (objectid <= btrfs_ino(entry)) {
4225 prev = rb_next(prev);
4229 entry = rb_entry(node, struct btrfs_inode, rb_node);
4230 objectid = btrfs_ino(entry) + 1;
4231 inode = igrab(&entry->vfs_inode);
4233 spin_unlock(&root->inode_lock);
4234 if (atomic_read(&inode->i_count) > 1)
4235 d_prune_aliases(inode);
4237 * btrfs_drop_inode will have it removed from the inode
4238 * cache when its usage count hits zero.
4242 spin_lock(&root->inode_lock);
4246 if (cond_resched_lock(&root->inode_lock))
4249 node = rb_next(node);
4251 spin_unlock(&root->inode_lock);
4254 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4256 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4257 struct btrfs_root *root = BTRFS_I(dir)->root;
4258 struct inode *inode = d_inode(dentry);
4259 struct btrfs_root *dest = BTRFS_I(inode)->root;
4260 struct btrfs_trans_handle *trans;
4261 struct btrfs_block_rsv block_rsv;
4267 * Don't allow to delete a subvolume with send in progress. This is
4268 * inside the inode lock so the error handling that has to drop the bit
4269 * again is not run concurrently.
4271 spin_lock(&dest->root_item_lock);
4272 if (dest->send_in_progress) {
4273 spin_unlock(&dest->root_item_lock);
4275 "attempt to delete subvolume %llu during send",
4276 dest->root_key.objectid);
4279 root_flags = btrfs_root_flags(&dest->root_item);
4280 btrfs_set_root_flags(&dest->root_item,
4281 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4282 spin_unlock(&dest->root_item_lock);
4284 down_write(&fs_info->subvol_sem);
4286 err = may_destroy_subvol(dest);
4290 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4292 * One for dir inode,
4293 * two for dir entries,
4294 * two for root ref/backref.
4296 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4300 trans = btrfs_start_transaction(root, 0);
4301 if (IS_ERR(trans)) {
4302 err = PTR_ERR(trans);
4305 trans->block_rsv = &block_rsv;
4306 trans->bytes_reserved = block_rsv.size;
4308 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4310 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4311 dentry->d_name.name, dentry->d_name.len);
4314 btrfs_abort_transaction(trans, ret);
4318 btrfs_record_root_in_trans(trans, dest);
4320 memset(&dest->root_item.drop_progress, 0,
4321 sizeof(dest->root_item.drop_progress));
4322 dest->root_item.drop_level = 0;
4323 btrfs_set_root_refs(&dest->root_item, 0);
4325 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4326 ret = btrfs_insert_orphan_item(trans,
4328 dest->root_key.objectid);
4330 btrfs_abort_transaction(trans, ret);
4336 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4337 BTRFS_UUID_KEY_SUBVOL,
4338 dest->root_key.objectid);
4339 if (ret && ret != -ENOENT) {
4340 btrfs_abort_transaction(trans, ret);
4344 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4345 ret = btrfs_uuid_tree_remove(trans,
4346 dest->root_item.received_uuid,
4347 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4348 dest->root_key.objectid);
4349 if (ret && ret != -ENOENT) {
4350 btrfs_abort_transaction(trans, ret);
4357 trans->block_rsv = NULL;
4358 trans->bytes_reserved = 0;
4359 ret = btrfs_end_transaction(trans);
4362 inode->i_flags |= S_DEAD;
4364 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4366 up_write(&fs_info->subvol_sem);
4368 spin_lock(&dest->root_item_lock);
4369 root_flags = btrfs_root_flags(&dest->root_item);
4370 btrfs_set_root_flags(&dest->root_item,
4371 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4372 spin_unlock(&dest->root_item_lock);
4374 d_invalidate(dentry);
4375 btrfs_prune_dentries(dest);
4376 ASSERT(dest->send_in_progress == 0);
4379 if (dest->ino_cache_inode) {
4380 iput(dest->ino_cache_inode);
4381 dest->ino_cache_inode = NULL;
4388 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4390 struct inode *inode = d_inode(dentry);
4392 struct btrfs_root *root = BTRFS_I(dir)->root;
4393 struct btrfs_trans_handle *trans;
4394 u64 last_unlink_trans;
4396 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4398 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4399 return btrfs_delete_subvolume(dir, dentry);
4401 trans = __unlink_start_trans(dir);
4403 return PTR_ERR(trans);
4405 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4406 err = btrfs_unlink_subvol(trans, dir,
4407 BTRFS_I(inode)->location.objectid,
4408 dentry->d_name.name,
4409 dentry->d_name.len);
4413 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4417 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4419 /* now the directory is empty */
4420 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4421 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4422 dentry->d_name.len);
4424 btrfs_i_size_write(BTRFS_I(inode), 0);
4426 * Propagate the last_unlink_trans value of the deleted dir to
4427 * its parent directory. This is to prevent an unrecoverable
4428 * log tree in the case we do something like this:
4430 * 2) create snapshot under dir foo
4431 * 3) delete the snapshot
4434 * 6) fsync foo or some file inside foo
4436 if (last_unlink_trans >= trans->transid)
4437 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4440 btrfs_end_transaction(trans);
4441 btrfs_btree_balance_dirty(root->fs_info);
4446 static int truncate_space_check(struct btrfs_trans_handle *trans,
4447 struct btrfs_root *root,
4450 struct btrfs_fs_info *fs_info = root->fs_info;
4454 * This is only used to apply pressure to the enospc system, we don't
4455 * intend to use this reservation at all.
4457 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4458 bytes_deleted *= fs_info->nodesize;
4459 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4460 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4462 trace_btrfs_space_reservation(fs_info, "transaction",
4465 trans->bytes_reserved += bytes_deleted;
4472 * Return this if we need to call truncate_block for the last bit of the
4475 #define NEED_TRUNCATE_BLOCK 1
4478 * this can truncate away extent items, csum items and directory items.
4479 * It starts at a high offset and removes keys until it can't find
4480 * any higher than new_size
4482 * csum items that cross the new i_size are truncated to the new size
4485 * min_type is the minimum key type to truncate down to. If set to 0, this
4486 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4488 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4489 struct btrfs_root *root,
4490 struct inode *inode,
4491 u64 new_size, u32 min_type)
4493 struct btrfs_fs_info *fs_info = root->fs_info;
4494 struct btrfs_path *path;
4495 struct extent_buffer *leaf;
4496 struct btrfs_file_extent_item *fi;
4497 struct btrfs_key key;
4498 struct btrfs_key found_key;
4499 u64 extent_start = 0;
4500 u64 extent_num_bytes = 0;
4501 u64 extent_offset = 0;
4503 u64 last_size = new_size;
4504 u32 found_type = (u8)-1;
4507 int pending_del_nr = 0;
4508 int pending_del_slot = 0;
4509 int extent_type = -1;
4511 u64 ino = btrfs_ino(BTRFS_I(inode));
4512 u64 bytes_deleted = 0;
4513 bool be_nice = false;
4514 bool should_throttle = false;
4515 bool should_end = false;
4517 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4520 * for non-free space inodes and ref cows, we want to back off from
4523 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4524 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4527 path = btrfs_alloc_path();
4530 path->reada = READA_BACK;
4533 * We want to drop from the next block forward in case this new size is
4534 * not block aligned since we will be keeping the last block of the
4535 * extent just the way it is.
4537 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4538 root == fs_info->tree_root)
4539 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4540 fs_info->sectorsize),
4544 * This function is also used to drop the items in the log tree before
4545 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4546 * it is used to drop the loged items. So we shouldn't kill the delayed
4549 if (min_type == 0 && root == BTRFS_I(inode)->root)
4550 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4553 key.offset = (u64)-1;
4558 * with a 16K leaf size and 128MB extents, you can actually queue
4559 * up a huge file in a single leaf. Most of the time that
4560 * bytes_deleted is > 0, it will be huge by the time we get here
4562 if (be_nice && bytes_deleted > SZ_32M &&
4563 btrfs_should_end_transaction(trans)) {
4568 path->leave_spinning = 1;
4569 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4575 /* there are no items in the tree for us to truncate, we're
4578 if (path->slots[0] == 0)
4585 leaf = path->nodes[0];
4586 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4587 found_type = found_key.type;
4589 if (found_key.objectid != ino)
4592 if (found_type < min_type)
4595 item_end = found_key.offset;
4596 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4597 fi = btrfs_item_ptr(leaf, path->slots[0],
4598 struct btrfs_file_extent_item);
4599 extent_type = btrfs_file_extent_type(leaf, fi);
4600 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4602 btrfs_file_extent_num_bytes(leaf, fi);
4604 trace_btrfs_truncate_show_fi_regular(
4605 BTRFS_I(inode), leaf, fi,
4607 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4608 item_end += btrfs_file_extent_ram_bytes(leaf,
4611 trace_btrfs_truncate_show_fi_inline(
4612 BTRFS_I(inode), leaf, fi, path->slots[0],
4617 if (found_type > min_type) {
4620 if (item_end < new_size)
4622 if (found_key.offset >= new_size)
4628 /* FIXME, shrink the extent if the ref count is only 1 */
4629 if (found_type != BTRFS_EXTENT_DATA_KEY)
4632 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4634 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4636 u64 orig_num_bytes =
4637 btrfs_file_extent_num_bytes(leaf, fi);
4638 extent_num_bytes = ALIGN(new_size -
4640 fs_info->sectorsize);
4641 btrfs_set_file_extent_num_bytes(leaf, fi,
4643 num_dec = (orig_num_bytes -
4645 if (test_bit(BTRFS_ROOT_REF_COWS,
4648 inode_sub_bytes(inode, num_dec);
4649 btrfs_mark_buffer_dirty(leaf);
4652 btrfs_file_extent_disk_num_bytes(leaf,
4654 extent_offset = found_key.offset -
4655 btrfs_file_extent_offset(leaf, fi);
4657 /* FIXME blocksize != 4096 */
4658 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4659 if (extent_start != 0) {
4661 if (test_bit(BTRFS_ROOT_REF_COWS,
4663 inode_sub_bytes(inode, num_dec);
4666 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4668 * we can't truncate inline items that have had
4672 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4673 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4674 btrfs_file_extent_compression(leaf, fi) == 0) {
4675 u32 size = (u32)(new_size - found_key.offset);
4677 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4678 size = btrfs_file_extent_calc_inline_size(size);
4679 btrfs_truncate_item(root->fs_info, path, size, 1);
4680 } else if (!del_item) {
4682 * We have to bail so the last_size is set to
4683 * just before this extent.
4685 ret = NEED_TRUNCATE_BLOCK;
4689 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4690 inode_sub_bytes(inode, item_end + 1 - new_size);
4694 last_size = found_key.offset;
4696 last_size = new_size;
4698 if (!pending_del_nr) {
4699 /* no pending yet, add ourselves */
4700 pending_del_slot = path->slots[0];
4702 } else if (pending_del_nr &&
4703 path->slots[0] + 1 == pending_del_slot) {
4704 /* hop on the pending chunk */
4706 pending_del_slot = path->slots[0];
4713 should_throttle = false;
4716 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4717 root == fs_info->tree_root)) {
4718 btrfs_set_path_blocking(path);
4719 bytes_deleted += extent_num_bytes;
4720 ret = btrfs_free_extent(trans, root, extent_start,
4721 extent_num_bytes, 0,
4722 btrfs_header_owner(leaf),
4723 ino, extent_offset);
4725 btrfs_abort_transaction(trans, ret);
4728 if (btrfs_should_throttle_delayed_refs(trans))
4729 btrfs_async_run_delayed_refs(fs_info,
4730 trans->delayed_ref_updates * 2,
4733 if (truncate_space_check(trans, root,
4734 extent_num_bytes)) {
4737 if (btrfs_should_throttle_delayed_refs(trans))
4738 should_throttle = true;
4742 if (found_type == BTRFS_INODE_ITEM_KEY)
4745 if (path->slots[0] == 0 ||
4746 path->slots[0] != pending_del_slot ||
4747 should_throttle || should_end) {
4748 if (pending_del_nr) {
4749 ret = btrfs_del_items(trans, root, path,
4753 btrfs_abort_transaction(trans, ret);
4758 btrfs_release_path(path);
4759 if (should_throttle) {
4760 unsigned long updates = trans->delayed_ref_updates;
4762 trans->delayed_ref_updates = 0;
4763 ret = btrfs_run_delayed_refs(trans,
4770 * if we failed to refill our space rsv, bail out
4771 * and let the transaction restart
4783 if (ret >= 0 && pending_del_nr) {
4786 err = btrfs_del_items(trans, root, path, pending_del_slot,
4789 btrfs_abort_transaction(trans, err);
4793 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4794 ASSERT(last_size >= new_size);
4795 if (!ret && last_size > new_size)
4796 last_size = new_size;
4797 btrfs_ordered_update_i_size(inode, last_size, NULL);
4800 btrfs_free_path(path);
4802 if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4803 unsigned long updates = trans->delayed_ref_updates;
4807 trans->delayed_ref_updates = 0;
4808 err = btrfs_run_delayed_refs(trans, updates * 2);
4817 * btrfs_truncate_block - read, zero a chunk and write a block
4818 * @inode - inode that we're zeroing
4819 * @from - the offset to start zeroing
4820 * @len - the length to zero, 0 to zero the entire range respective to the
4822 * @front - zero up to the offset instead of from the offset on
4824 * This will find the block for the "from" offset and cow the block and zero the
4825 * part we want to zero. This is used with truncate and hole punching.
4827 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4830 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4831 struct address_space *mapping = inode->i_mapping;
4832 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4833 struct btrfs_ordered_extent *ordered;
4834 struct extent_state *cached_state = NULL;
4835 struct extent_changeset *data_reserved = NULL;
4837 u32 blocksize = fs_info->sectorsize;
4838 pgoff_t index = from >> PAGE_SHIFT;
4839 unsigned offset = from & (blocksize - 1);
4841 gfp_t mask = btrfs_alloc_write_mask(mapping);
4846 if (IS_ALIGNED(offset, blocksize) &&
4847 (!len || IS_ALIGNED(len, blocksize)))
4850 block_start = round_down(from, blocksize);
4851 block_end = block_start + blocksize - 1;
4853 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4854 block_start, blocksize);
4859 page = find_or_create_page(mapping, index, mask);
4861 btrfs_delalloc_release_space(inode, data_reserved,
4862 block_start, blocksize, true);
4863 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4868 if (!PageUptodate(page)) {
4869 ret = btrfs_readpage(NULL, page);
4871 if (page->mapping != mapping) {
4876 if (!PageUptodate(page)) {
4881 wait_on_page_writeback(page);
4883 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4884 set_page_extent_mapped(page);
4886 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4888 unlock_extent_cached(io_tree, block_start, block_end,
4892 btrfs_start_ordered_extent(inode, ordered, 1);
4893 btrfs_put_ordered_extent(ordered);
4897 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4898 EXTENT_DIRTY | EXTENT_DELALLOC |
4899 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4900 0, 0, &cached_state);
4902 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4905 unlock_extent_cached(io_tree, block_start, block_end,
4910 if (offset != blocksize) {
4912 len = blocksize - offset;
4915 memset(kaddr + (block_start - page_offset(page)),
4918 memset(kaddr + (block_start - page_offset(page)) + offset,
4920 flush_dcache_page(page);
4923 ClearPageChecked(page);
4924 set_page_dirty(page);
4925 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4929 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4931 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4935 extent_changeset_free(data_reserved);
4939 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4940 u64 offset, u64 len)
4942 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4943 struct btrfs_trans_handle *trans;
4947 * Still need to make sure the inode looks like it's been updated so
4948 * that any holes get logged if we fsync.
4950 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4951 BTRFS_I(inode)->last_trans = fs_info->generation;
4952 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4953 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4958 * 1 - for the one we're dropping
4959 * 1 - for the one we're adding
4960 * 1 - for updating the inode.
4962 trans = btrfs_start_transaction(root, 3);
4964 return PTR_ERR(trans);
4966 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4968 btrfs_abort_transaction(trans, ret);
4969 btrfs_end_transaction(trans);
4973 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4974 offset, 0, 0, len, 0, len, 0, 0, 0);
4976 btrfs_abort_transaction(trans, ret);
4978 btrfs_update_inode(trans, root, inode);
4979 btrfs_end_transaction(trans);
4984 * This function puts in dummy file extents for the area we're creating a hole
4985 * for. So if we are truncating this file to a larger size we need to insert
4986 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4987 * the range between oldsize and size
4989 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4991 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4992 struct btrfs_root *root = BTRFS_I(inode)->root;
4993 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4994 struct extent_map *em = NULL;
4995 struct extent_state *cached_state = NULL;
4996 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4997 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4998 u64 block_end = ALIGN(size, fs_info->sectorsize);
5005 * If our size started in the middle of a block we need to zero out the
5006 * rest of the block before we expand the i_size, otherwise we could
5007 * expose stale data.
5009 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5013 if (size <= hole_start)
5017 struct btrfs_ordered_extent *ordered;
5019 lock_extent_bits(io_tree, hole_start, block_end - 1,
5021 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5022 block_end - hole_start);
5025 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5027 btrfs_start_ordered_extent(inode, ordered, 1);
5028 btrfs_put_ordered_extent(ordered);
5031 cur_offset = hole_start;
5033 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5034 block_end - cur_offset, 0);
5040 last_byte = min(extent_map_end(em), block_end);
5041 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5042 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5043 struct extent_map *hole_em;
5044 hole_size = last_byte - cur_offset;
5046 err = maybe_insert_hole(root, inode, cur_offset,
5050 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5051 cur_offset + hole_size - 1, 0);
5052 hole_em = alloc_extent_map();
5054 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5055 &BTRFS_I(inode)->runtime_flags);
5058 hole_em->start = cur_offset;
5059 hole_em->len = hole_size;
5060 hole_em->orig_start = cur_offset;
5062 hole_em->block_start = EXTENT_MAP_HOLE;
5063 hole_em->block_len = 0;
5064 hole_em->orig_block_len = 0;
5065 hole_em->ram_bytes = hole_size;
5066 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5067 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5068 hole_em->generation = fs_info->generation;
5071 write_lock(&em_tree->lock);
5072 err = add_extent_mapping(em_tree, hole_em, 1);
5073 write_unlock(&em_tree->lock);
5076 btrfs_drop_extent_cache(BTRFS_I(inode),
5081 free_extent_map(hole_em);
5084 free_extent_map(em);
5086 cur_offset = last_byte;
5087 if (cur_offset >= block_end)
5090 free_extent_map(em);
5091 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5095 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5097 struct btrfs_root *root = BTRFS_I(inode)->root;
5098 struct btrfs_trans_handle *trans;
5099 loff_t oldsize = i_size_read(inode);
5100 loff_t newsize = attr->ia_size;
5101 int mask = attr->ia_valid;
5105 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5106 * special case where we need to update the times despite not having
5107 * these flags set. For all other operations the VFS set these flags
5108 * explicitly if it wants a timestamp update.
5110 if (newsize != oldsize) {
5111 inode_inc_iversion(inode);
5112 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5113 inode->i_ctime = inode->i_mtime =
5114 current_time(inode);
5117 if (newsize > oldsize) {
5119 * Don't do an expanding truncate while snapshotting is ongoing.
5120 * This is to ensure the snapshot captures a fully consistent
5121 * state of this file - if the snapshot captures this expanding
5122 * truncation, it must capture all writes that happened before
5125 btrfs_wait_for_snapshot_creation(root);
5126 ret = btrfs_cont_expand(inode, oldsize, newsize);
5128 btrfs_end_write_no_snapshotting(root);
5132 trans = btrfs_start_transaction(root, 1);
5133 if (IS_ERR(trans)) {
5134 btrfs_end_write_no_snapshotting(root);
5135 return PTR_ERR(trans);
5138 i_size_write(inode, newsize);
5139 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5140 pagecache_isize_extended(inode, oldsize, newsize);
5141 ret = btrfs_update_inode(trans, root, inode);
5142 btrfs_end_write_no_snapshotting(root);
5143 btrfs_end_transaction(trans);
5147 * We're truncating a file that used to have good data down to
5148 * zero. Make sure it gets into the ordered flush list so that
5149 * any new writes get down to disk quickly.
5152 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5153 &BTRFS_I(inode)->runtime_flags);
5155 truncate_setsize(inode, newsize);
5157 /* Disable nonlocked read DIO to avoid the end less truncate */
5158 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5159 inode_dio_wait(inode);
5160 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5162 ret = btrfs_truncate(inode, newsize == oldsize);
5163 if (ret && inode->i_nlink) {
5167 * Truncate failed, so fix up the in-memory size. We
5168 * adjusted disk_i_size down as we removed extents, so
5169 * wait for disk_i_size to be stable and then update the
5170 * in-memory size to match.
5172 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5175 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5182 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5184 struct inode *inode = d_inode(dentry);
5185 struct btrfs_root *root = BTRFS_I(inode)->root;
5188 if (btrfs_root_readonly(root))
5191 err = setattr_prepare(dentry, attr);
5195 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5196 err = btrfs_setsize(inode, attr);
5201 if (attr->ia_valid) {
5202 setattr_copy(inode, attr);
5203 inode_inc_iversion(inode);
5204 err = btrfs_dirty_inode(inode);
5206 if (!err && attr->ia_valid & ATTR_MODE)
5207 err = posix_acl_chmod(inode, inode->i_mode);
5214 * While truncating the inode pages during eviction, we get the VFS calling
5215 * btrfs_invalidatepage() against each page of the inode. This is slow because
5216 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5217 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5218 * extent_state structures over and over, wasting lots of time.
5220 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5221 * those expensive operations on a per page basis and do only the ordered io
5222 * finishing, while we release here the extent_map and extent_state structures,
5223 * without the excessive merging and splitting.
5225 static void evict_inode_truncate_pages(struct inode *inode)
5227 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5228 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5229 struct rb_node *node;
5231 ASSERT(inode->i_state & I_FREEING);
5232 truncate_inode_pages_final(&inode->i_data);
5234 write_lock(&map_tree->lock);
5235 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5236 struct extent_map *em;
5238 node = rb_first_cached(&map_tree->map);
5239 em = rb_entry(node, struct extent_map, rb_node);
5240 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5241 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5242 remove_extent_mapping(map_tree, em);
5243 free_extent_map(em);
5244 if (need_resched()) {
5245 write_unlock(&map_tree->lock);
5247 write_lock(&map_tree->lock);
5250 write_unlock(&map_tree->lock);
5253 * Keep looping until we have no more ranges in the io tree.
5254 * We can have ongoing bios started by readpages (called from readahead)
5255 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5256 * still in progress (unlocked the pages in the bio but did not yet
5257 * unlocked the ranges in the io tree). Therefore this means some
5258 * ranges can still be locked and eviction started because before
5259 * submitting those bios, which are executed by a separate task (work
5260 * queue kthread), inode references (inode->i_count) were not taken
5261 * (which would be dropped in the end io callback of each bio).
5262 * Therefore here we effectively end up waiting for those bios and
5263 * anyone else holding locked ranges without having bumped the inode's
5264 * reference count - if we don't do it, when they access the inode's
5265 * io_tree to unlock a range it may be too late, leading to an
5266 * use-after-free issue.
5268 spin_lock(&io_tree->lock);
5269 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5270 struct extent_state *state;
5271 struct extent_state *cached_state = NULL;
5274 unsigned state_flags;
5276 node = rb_first(&io_tree->state);
5277 state = rb_entry(node, struct extent_state, rb_node);
5278 start = state->start;
5280 state_flags = state->state;
5281 spin_unlock(&io_tree->lock);
5283 lock_extent_bits(io_tree, start, end, &cached_state);
5286 * If still has DELALLOC flag, the extent didn't reach disk,
5287 * and its reserved space won't be freed by delayed_ref.
5288 * So we need to free its reserved space here.
5289 * (Refer to comment in btrfs_invalidatepage, case 2)
5291 * Note, end is the bytenr of last byte, so we need + 1 here.
5293 if (state_flags & EXTENT_DELALLOC)
5294 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5296 clear_extent_bit(io_tree, start, end,
5297 EXTENT_LOCKED | EXTENT_DIRTY |
5298 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5299 EXTENT_DEFRAG, 1, 1, &cached_state);
5302 spin_lock(&io_tree->lock);
5304 spin_unlock(&io_tree->lock);
5307 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5308 struct btrfs_block_rsv *rsv)
5310 struct btrfs_fs_info *fs_info = root->fs_info;
5311 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5315 struct btrfs_trans_handle *trans;
5318 ret = btrfs_block_rsv_refill(root, rsv, rsv->size,
5319 BTRFS_RESERVE_FLUSH_LIMIT);
5321 if (ret && ++failures > 2) {
5323 "could not allocate space for a delete; will truncate on mount");
5324 return ERR_PTR(-ENOSPC);
5327 trans = btrfs_join_transaction(root);
5328 if (IS_ERR(trans) || !ret)
5332 * Try to steal from the global reserve if there is space for
5335 if (!btrfs_check_space_for_delayed_refs(trans) &&
5336 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, false))
5339 /* If not, commit and try again. */
5340 ret = btrfs_commit_transaction(trans);
5342 return ERR_PTR(ret);
5346 void btrfs_evict_inode(struct inode *inode)
5348 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5349 struct btrfs_trans_handle *trans;
5350 struct btrfs_root *root = BTRFS_I(inode)->root;
5351 struct btrfs_block_rsv *rsv;
5354 trace_btrfs_inode_evict(inode);
5361 evict_inode_truncate_pages(inode);
5363 if (inode->i_nlink &&
5364 ((btrfs_root_refs(&root->root_item) != 0 &&
5365 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5366 btrfs_is_free_space_inode(BTRFS_I(inode))))
5369 if (is_bad_inode(inode))
5372 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5374 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5377 if (inode->i_nlink > 0) {
5378 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5379 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5383 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5387 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5390 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5393 btrfs_i_size_write(BTRFS_I(inode), 0);
5396 trans = evict_refill_and_join(root, rsv);
5400 trans->block_rsv = rsv;
5402 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5403 trans->block_rsv = &fs_info->trans_block_rsv;
5404 btrfs_end_transaction(trans);
5405 btrfs_btree_balance_dirty(fs_info);
5406 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5413 * Errors here aren't a big deal, it just means we leave orphan items in
5414 * the tree. They will be cleaned up on the next mount. If the inode
5415 * number gets reused, cleanup deletes the orphan item without doing
5416 * anything, and unlink reuses the existing orphan item.
5418 * If it turns out that we are dropping too many of these, we might want
5419 * to add a mechanism for retrying these after a commit.
5421 trans = evict_refill_and_join(root, rsv);
5422 if (!IS_ERR(trans)) {
5423 trans->block_rsv = rsv;
5424 btrfs_orphan_del(trans, BTRFS_I(inode));
5425 trans->block_rsv = &fs_info->trans_block_rsv;
5426 btrfs_end_transaction(trans);
5429 if (!(root == fs_info->tree_root ||
5430 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5431 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5434 btrfs_free_block_rsv(fs_info, rsv);
5437 * If we didn't successfully delete, the orphan item will still be in
5438 * the tree and we'll retry on the next mount. Again, we might also want
5439 * to retry these periodically in the future.
5441 btrfs_remove_delayed_node(BTRFS_I(inode));
5446 * this returns the key found in the dir entry in the location pointer.
5447 * If no dir entries were found, returns -ENOENT.
5448 * If found a corrupted location in dir entry, returns -EUCLEAN.
5450 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5451 struct btrfs_key *location)
5453 const char *name = dentry->d_name.name;
5454 int namelen = dentry->d_name.len;
5455 struct btrfs_dir_item *di;
5456 struct btrfs_path *path;
5457 struct btrfs_root *root = BTRFS_I(dir)->root;
5460 path = btrfs_alloc_path();
5464 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5466 if (IS_ERR_OR_NULL(di)) {
5467 ret = di ? PTR_ERR(di) : -ENOENT;
5471 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5472 if (location->type != BTRFS_INODE_ITEM_KEY &&
5473 location->type != BTRFS_ROOT_ITEM_KEY) {
5475 btrfs_warn(root->fs_info,
5476 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5477 __func__, name, btrfs_ino(BTRFS_I(dir)),
5478 location->objectid, location->type, location->offset);
5481 btrfs_free_path(path);
5486 * when we hit a tree root in a directory, the btrfs part of the inode
5487 * needs to be changed to reflect the root directory of the tree root. This
5488 * is kind of like crossing a mount point.
5490 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5492 struct dentry *dentry,
5493 struct btrfs_key *location,
5494 struct btrfs_root **sub_root)
5496 struct btrfs_path *path;
5497 struct btrfs_root *new_root;
5498 struct btrfs_root_ref *ref;
5499 struct extent_buffer *leaf;
5500 struct btrfs_key key;
5504 path = btrfs_alloc_path();
5511 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5512 key.type = BTRFS_ROOT_REF_KEY;
5513 key.offset = location->objectid;
5515 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5522 leaf = path->nodes[0];
5523 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5524 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5525 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5528 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5529 (unsigned long)(ref + 1),
5530 dentry->d_name.len);
5534 btrfs_release_path(path);
5536 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5537 if (IS_ERR(new_root)) {
5538 err = PTR_ERR(new_root);
5542 *sub_root = new_root;
5543 location->objectid = btrfs_root_dirid(&new_root->root_item);
5544 location->type = BTRFS_INODE_ITEM_KEY;
5545 location->offset = 0;
5548 btrfs_free_path(path);
5552 static void inode_tree_add(struct inode *inode)
5554 struct btrfs_root *root = BTRFS_I(inode)->root;
5555 struct btrfs_inode *entry;
5557 struct rb_node *parent;
5558 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5559 u64 ino = btrfs_ino(BTRFS_I(inode));
5561 if (inode_unhashed(inode))
5564 spin_lock(&root->inode_lock);
5565 p = &root->inode_tree.rb_node;
5568 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5570 if (ino < btrfs_ino(entry))
5571 p = &parent->rb_left;
5572 else if (ino > btrfs_ino(entry))
5573 p = &parent->rb_right;
5575 WARN_ON(!(entry->vfs_inode.i_state &
5576 (I_WILL_FREE | I_FREEING)));
5577 rb_replace_node(parent, new, &root->inode_tree);
5578 RB_CLEAR_NODE(parent);
5579 spin_unlock(&root->inode_lock);
5583 rb_link_node(new, parent, p);
5584 rb_insert_color(new, &root->inode_tree);
5585 spin_unlock(&root->inode_lock);
5588 static void inode_tree_del(struct inode *inode)
5590 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5591 struct btrfs_root *root = BTRFS_I(inode)->root;
5594 spin_lock(&root->inode_lock);
5595 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5596 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5597 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5598 empty = RB_EMPTY_ROOT(&root->inode_tree);
5600 spin_unlock(&root->inode_lock);
5602 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5603 synchronize_srcu(&fs_info->subvol_srcu);
5604 spin_lock(&root->inode_lock);
5605 empty = RB_EMPTY_ROOT(&root->inode_tree);
5606 spin_unlock(&root->inode_lock);
5608 btrfs_add_dead_root(root);
5613 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5615 struct btrfs_iget_args *args = p;
5616 inode->i_ino = args->location->objectid;
5617 memcpy(&BTRFS_I(inode)->location, args->location,
5618 sizeof(*args->location));
5619 BTRFS_I(inode)->root = args->root;
5623 static int btrfs_find_actor(struct inode *inode, void *opaque)
5625 struct btrfs_iget_args *args = opaque;
5626 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5627 args->root == BTRFS_I(inode)->root;
5630 static struct inode *btrfs_iget_locked(struct super_block *s,
5631 struct btrfs_key *location,
5632 struct btrfs_root *root)
5634 struct inode *inode;
5635 struct btrfs_iget_args args;
5636 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5638 args.location = location;
5641 inode = iget5_locked(s, hashval, btrfs_find_actor,
5642 btrfs_init_locked_inode,
5647 /* Get an inode object given its location and corresponding root.
5648 * Returns in *is_new if the inode was read from disk
5650 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5651 struct btrfs_root *root, int *new,
5652 struct btrfs_path *path)
5654 struct inode *inode;
5656 inode = btrfs_iget_locked(s, location, root);
5658 return ERR_PTR(-ENOMEM);
5660 if (inode->i_state & I_NEW) {
5663 ret = btrfs_read_locked_inode(inode, path);
5665 inode_tree_add(inode);
5666 unlock_new_inode(inode);
5672 * ret > 0 can come from btrfs_search_slot called by
5673 * btrfs_read_locked_inode, this means the inode item
5678 inode = ERR_PTR(ret);
5685 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5686 struct btrfs_root *root, int *new)
5688 return btrfs_iget_path(s, location, root, new, NULL);
5691 static struct inode *new_simple_dir(struct super_block *s,
5692 struct btrfs_key *key,
5693 struct btrfs_root *root)
5695 struct inode *inode = new_inode(s);
5698 return ERR_PTR(-ENOMEM);
5700 BTRFS_I(inode)->root = root;
5701 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5702 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5704 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5705 inode->i_op = &btrfs_dir_ro_inode_operations;
5706 inode->i_opflags &= ~IOP_XATTR;
5707 inode->i_fop = &simple_dir_operations;
5708 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5709 inode->i_mtime = current_time(inode);
5710 inode->i_atime = inode->i_mtime;
5711 inode->i_ctime = inode->i_mtime;
5712 BTRFS_I(inode)->i_otime = inode->i_mtime;
5717 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5719 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5720 struct inode *inode;
5721 struct btrfs_root *root = BTRFS_I(dir)->root;
5722 struct btrfs_root *sub_root = root;
5723 struct btrfs_key location;
5727 if (dentry->d_name.len > BTRFS_NAME_LEN)
5728 return ERR_PTR(-ENAMETOOLONG);
5730 ret = btrfs_inode_by_name(dir, dentry, &location);
5732 return ERR_PTR(ret);
5734 if (location.type == BTRFS_INODE_ITEM_KEY) {
5735 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5739 index = srcu_read_lock(&fs_info->subvol_srcu);
5740 ret = fixup_tree_root_location(fs_info, dir, dentry,
5741 &location, &sub_root);
5744 inode = ERR_PTR(ret);
5746 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5748 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5750 srcu_read_unlock(&fs_info->subvol_srcu, index);
5752 if (!IS_ERR(inode) && root != sub_root) {
5753 down_read(&fs_info->cleanup_work_sem);
5754 if (!sb_rdonly(inode->i_sb))
5755 ret = btrfs_orphan_cleanup(sub_root);
5756 up_read(&fs_info->cleanup_work_sem);
5759 inode = ERR_PTR(ret);
5766 static int btrfs_dentry_delete(const struct dentry *dentry)
5768 struct btrfs_root *root;
5769 struct inode *inode = d_inode(dentry);
5771 if (!inode && !IS_ROOT(dentry))
5772 inode = d_inode(dentry->d_parent);
5775 root = BTRFS_I(inode)->root;
5776 if (btrfs_root_refs(&root->root_item) == 0)
5779 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5785 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5788 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5790 if (inode == ERR_PTR(-ENOENT))
5792 return d_splice_alias(inode, dentry);
5795 unsigned char btrfs_filetype_table[] = {
5796 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5800 * All this infrastructure exists because dir_emit can fault, and we are holding
5801 * the tree lock when doing readdir. For now just allocate a buffer and copy
5802 * our information into that, and then dir_emit from the buffer. This is
5803 * similar to what NFS does, only we don't keep the buffer around in pagecache
5804 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5805 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5808 static int btrfs_opendir(struct inode *inode, struct file *file)
5810 struct btrfs_file_private *private;
5812 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5815 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5816 if (!private->filldir_buf) {
5820 file->private_data = private;
5831 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5834 struct dir_entry *entry = addr;
5835 char *name = (char *)(entry + 1);
5837 ctx->pos = get_unaligned(&entry->offset);
5838 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5839 get_unaligned(&entry->ino),
5840 get_unaligned(&entry->type)))
5842 addr += sizeof(struct dir_entry) +
5843 get_unaligned(&entry->name_len);
5849 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5851 struct inode *inode = file_inode(file);
5852 struct btrfs_root *root = BTRFS_I(inode)->root;
5853 struct btrfs_file_private *private = file->private_data;
5854 struct btrfs_dir_item *di;
5855 struct btrfs_key key;
5856 struct btrfs_key found_key;
5857 struct btrfs_path *path;
5859 struct list_head ins_list;
5860 struct list_head del_list;
5862 struct extent_buffer *leaf;
5869 struct btrfs_key location;
5871 if (!dir_emit_dots(file, ctx))
5874 path = btrfs_alloc_path();
5878 addr = private->filldir_buf;
5879 path->reada = READA_FORWARD;
5881 INIT_LIST_HEAD(&ins_list);
5882 INIT_LIST_HEAD(&del_list);
5883 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5886 key.type = BTRFS_DIR_INDEX_KEY;
5887 key.offset = ctx->pos;
5888 key.objectid = btrfs_ino(BTRFS_I(inode));
5890 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5895 struct dir_entry *entry;
5897 leaf = path->nodes[0];
5898 slot = path->slots[0];
5899 if (slot >= btrfs_header_nritems(leaf)) {
5900 ret = btrfs_next_leaf(root, path);
5908 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5910 if (found_key.objectid != key.objectid)
5912 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5914 if (found_key.offset < ctx->pos)
5916 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5918 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5919 name_len = btrfs_dir_name_len(leaf, di);
5920 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5922 btrfs_release_path(path);
5923 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5926 addr = private->filldir_buf;
5933 put_unaligned(name_len, &entry->name_len);
5934 name_ptr = (char *)(entry + 1);
5935 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5937 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
5939 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5940 put_unaligned(location.objectid, &entry->ino);
5941 put_unaligned(found_key.offset, &entry->offset);
5943 addr += sizeof(struct dir_entry) + name_len;
5944 total_len += sizeof(struct dir_entry) + name_len;
5948 btrfs_release_path(path);
5950 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5954 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5959 * Stop new entries from being returned after we return the last
5962 * New directory entries are assigned a strictly increasing
5963 * offset. This means that new entries created during readdir
5964 * are *guaranteed* to be seen in the future by that readdir.
5965 * This has broken buggy programs which operate on names as
5966 * they're returned by readdir. Until we re-use freed offsets
5967 * we have this hack to stop new entries from being returned
5968 * under the assumption that they'll never reach this huge
5971 * This is being careful not to overflow 32bit loff_t unless the
5972 * last entry requires it because doing so has broken 32bit apps
5975 if (ctx->pos >= INT_MAX)
5976 ctx->pos = LLONG_MAX;
5983 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5984 btrfs_free_path(path);
5989 * This is somewhat expensive, updating the tree every time the
5990 * inode changes. But, it is most likely to find the inode in cache.
5991 * FIXME, needs more benchmarking...there are no reasons other than performance
5992 * to keep or drop this code.
5994 static int btrfs_dirty_inode(struct inode *inode)
5996 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5997 struct btrfs_root *root = BTRFS_I(inode)->root;
5998 struct btrfs_trans_handle *trans;
6001 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6004 trans = btrfs_join_transaction(root);
6006 return PTR_ERR(trans);
6008 ret = btrfs_update_inode(trans, root, inode);
6009 if (ret && ret == -ENOSPC) {
6010 /* whoops, lets try again with the full transaction */
6011 btrfs_end_transaction(trans);
6012 trans = btrfs_start_transaction(root, 1);
6014 return PTR_ERR(trans);
6016 ret = btrfs_update_inode(trans, root, inode);
6018 btrfs_end_transaction(trans);
6019 if (BTRFS_I(inode)->delayed_node)
6020 btrfs_balance_delayed_items(fs_info);
6026 * This is a copy of file_update_time. We need this so we can return error on
6027 * ENOSPC for updating the inode in the case of file write and mmap writes.
6029 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6032 struct btrfs_root *root = BTRFS_I(inode)->root;
6033 bool dirty = flags & ~S_VERSION;
6035 if (btrfs_root_readonly(root))
6038 if (flags & S_VERSION)
6039 dirty |= inode_maybe_inc_iversion(inode, dirty);
6040 if (flags & S_CTIME)
6041 inode->i_ctime = *now;
6042 if (flags & S_MTIME)
6043 inode->i_mtime = *now;
6044 if (flags & S_ATIME)
6045 inode->i_atime = *now;
6046 return dirty ? btrfs_dirty_inode(inode) : 0;
6050 * find the highest existing sequence number in a directory
6051 * and then set the in-memory index_cnt variable to reflect
6052 * free sequence numbers
6054 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6056 struct btrfs_root *root = inode->root;
6057 struct btrfs_key key, found_key;
6058 struct btrfs_path *path;
6059 struct extent_buffer *leaf;
6062 key.objectid = btrfs_ino(inode);
6063 key.type = BTRFS_DIR_INDEX_KEY;
6064 key.offset = (u64)-1;
6066 path = btrfs_alloc_path();
6070 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6073 /* FIXME: we should be able to handle this */
6079 * MAGIC NUMBER EXPLANATION:
6080 * since we search a directory based on f_pos we have to start at 2
6081 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6082 * else has to start at 2
6084 if (path->slots[0] == 0) {
6085 inode->index_cnt = 2;
6091 leaf = path->nodes[0];
6092 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6094 if (found_key.objectid != btrfs_ino(inode) ||
6095 found_key.type != BTRFS_DIR_INDEX_KEY) {
6096 inode->index_cnt = 2;
6100 inode->index_cnt = found_key.offset + 1;
6102 btrfs_free_path(path);
6107 * helper to find a free sequence number in a given directory. This current
6108 * code is very simple, later versions will do smarter things in the btree
6110 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6114 if (dir->index_cnt == (u64)-1) {
6115 ret = btrfs_inode_delayed_dir_index_count(dir);
6117 ret = btrfs_set_inode_index_count(dir);
6123 *index = dir->index_cnt;
6129 static int btrfs_insert_inode_locked(struct inode *inode)
6131 struct btrfs_iget_args args;
6132 args.location = &BTRFS_I(inode)->location;
6133 args.root = BTRFS_I(inode)->root;
6135 return insert_inode_locked4(inode,
6136 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6137 btrfs_find_actor, &args);
6141 * Inherit flags from the parent inode.
6143 * Currently only the compression flags and the cow flags are inherited.
6145 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6152 flags = BTRFS_I(dir)->flags;
6154 if (flags & BTRFS_INODE_NOCOMPRESS) {
6155 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6156 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6157 } else if (flags & BTRFS_INODE_COMPRESS) {
6158 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6159 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6162 if (flags & BTRFS_INODE_NODATACOW) {
6163 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6164 if (S_ISREG(inode->i_mode))
6165 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6168 btrfs_sync_inode_flags_to_i_flags(inode);
6171 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6172 struct btrfs_root *root,
6174 const char *name, int name_len,
6175 u64 ref_objectid, u64 objectid,
6176 umode_t mode, u64 *index)
6178 struct btrfs_fs_info *fs_info = root->fs_info;
6179 struct inode *inode;
6180 struct btrfs_inode_item *inode_item;
6181 struct btrfs_key *location;
6182 struct btrfs_path *path;
6183 struct btrfs_inode_ref *ref;
6184 struct btrfs_key key[2];
6186 int nitems = name ? 2 : 1;
6190 path = btrfs_alloc_path();
6192 return ERR_PTR(-ENOMEM);
6194 inode = new_inode(fs_info->sb);
6196 btrfs_free_path(path);
6197 return ERR_PTR(-ENOMEM);
6201 * O_TMPFILE, set link count to 0, so that after this point,
6202 * we fill in an inode item with the correct link count.
6205 set_nlink(inode, 0);
6208 * we have to initialize this early, so we can reclaim the inode
6209 * number if we fail afterwards in this function.
6211 inode->i_ino = objectid;
6214 trace_btrfs_inode_request(dir);
6216 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6218 btrfs_free_path(path);
6220 return ERR_PTR(ret);
6226 * index_cnt is ignored for everything but a dir,
6227 * btrfs_set_inode_index_count has an explanation for the magic
6230 BTRFS_I(inode)->index_cnt = 2;
6231 BTRFS_I(inode)->dir_index = *index;
6232 BTRFS_I(inode)->root = root;
6233 BTRFS_I(inode)->generation = trans->transid;
6234 inode->i_generation = BTRFS_I(inode)->generation;
6237 * We could have gotten an inode number from somebody who was fsynced
6238 * and then removed in this same transaction, so let's just set full
6239 * sync since it will be a full sync anyway and this will blow away the
6240 * old info in the log.
6242 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6244 key[0].objectid = objectid;
6245 key[0].type = BTRFS_INODE_ITEM_KEY;
6248 sizes[0] = sizeof(struct btrfs_inode_item);
6252 * Start new inodes with an inode_ref. This is slightly more
6253 * efficient for small numbers of hard links since they will
6254 * be packed into one item. Extended refs will kick in if we
6255 * add more hard links than can fit in the ref item.
6257 key[1].objectid = objectid;
6258 key[1].type = BTRFS_INODE_REF_KEY;
6259 key[1].offset = ref_objectid;
6261 sizes[1] = name_len + sizeof(*ref);
6264 location = &BTRFS_I(inode)->location;
6265 location->objectid = objectid;
6266 location->offset = 0;
6267 location->type = BTRFS_INODE_ITEM_KEY;
6269 ret = btrfs_insert_inode_locked(inode);
6275 path->leave_spinning = 1;
6276 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6280 inode_init_owner(inode, dir, mode);
6281 inode_set_bytes(inode, 0);
6283 inode->i_mtime = current_time(inode);
6284 inode->i_atime = inode->i_mtime;
6285 inode->i_ctime = inode->i_mtime;
6286 BTRFS_I(inode)->i_otime = inode->i_mtime;
6288 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6289 struct btrfs_inode_item);
6290 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6291 sizeof(*inode_item));
6292 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6295 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6296 struct btrfs_inode_ref);
6297 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6298 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6299 ptr = (unsigned long)(ref + 1);
6300 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6303 btrfs_mark_buffer_dirty(path->nodes[0]);
6304 btrfs_free_path(path);
6306 btrfs_inherit_iflags(inode, dir);
6308 if (S_ISREG(mode)) {
6309 if (btrfs_test_opt(fs_info, NODATASUM))
6310 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6311 if (btrfs_test_opt(fs_info, NODATACOW))
6312 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6313 BTRFS_INODE_NODATASUM;
6316 inode_tree_add(inode);
6318 trace_btrfs_inode_new(inode);
6319 btrfs_set_inode_last_trans(trans, inode);
6321 btrfs_update_root_times(trans, root);
6323 ret = btrfs_inode_inherit_props(trans, inode, dir);
6326 "error inheriting props for ino %llu (root %llu): %d",
6327 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6332 discard_new_inode(inode);
6335 BTRFS_I(dir)->index_cnt--;
6336 btrfs_free_path(path);
6337 return ERR_PTR(ret);
6340 static inline u8 btrfs_inode_type(struct inode *inode)
6342 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6346 * utility function to add 'inode' into 'parent_inode' with
6347 * a give name and a given sequence number.
6348 * if 'add_backref' is true, also insert a backref from the
6349 * inode to the parent directory.
6351 int btrfs_add_link(struct btrfs_trans_handle *trans,
6352 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6353 const char *name, int name_len, int add_backref, u64 index)
6356 struct btrfs_key key;
6357 struct btrfs_root *root = parent_inode->root;
6358 u64 ino = btrfs_ino(inode);
6359 u64 parent_ino = btrfs_ino(parent_inode);
6361 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6362 memcpy(&key, &inode->root->root_key, sizeof(key));
6365 key.type = BTRFS_INODE_ITEM_KEY;
6369 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6370 ret = btrfs_add_root_ref(trans, key.objectid,
6371 root->root_key.objectid, parent_ino,
6372 index, name, name_len);
6373 } else if (add_backref) {
6374 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6378 /* Nothing to clean up yet */
6382 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6383 btrfs_inode_type(&inode->vfs_inode), index);
6384 if (ret == -EEXIST || ret == -EOVERFLOW)
6387 btrfs_abort_transaction(trans, ret);
6391 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6393 inode_inc_iversion(&parent_inode->vfs_inode);
6394 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6395 current_time(&parent_inode->vfs_inode);
6396 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6398 btrfs_abort_transaction(trans, ret);
6402 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6405 err = btrfs_del_root_ref(trans, key.objectid,
6406 root->root_key.objectid, parent_ino,
6407 &local_index, name, name_len);
6409 } else if (add_backref) {
6413 err = btrfs_del_inode_ref(trans, root, name, name_len,
6414 ino, parent_ino, &local_index);
6419 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6420 struct btrfs_inode *dir, struct dentry *dentry,
6421 struct btrfs_inode *inode, int backref, u64 index)
6423 int err = btrfs_add_link(trans, dir, inode,
6424 dentry->d_name.name, dentry->d_name.len,
6431 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6432 umode_t mode, dev_t rdev)
6434 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6435 struct btrfs_trans_handle *trans;
6436 struct btrfs_root *root = BTRFS_I(dir)->root;
6437 struct inode *inode = NULL;
6443 * 2 for inode item and ref
6445 * 1 for xattr if selinux is on
6447 trans = btrfs_start_transaction(root, 5);
6449 return PTR_ERR(trans);
6451 err = btrfs_find_free_ino(root, &objectid);
6455 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6456 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6458 if (IS_ERR(inode)) {
6459 err = PTR_ERR(inode);
6465 * If the active LSM wants to access the inode during
6466 * d_instantiate it needs these. Smack checks to see
6467 * if the filesystem supports xattrs by looking at the
6470 inode->i_op = &btrfs_special_inode_operations;
6471 init_special_inode(inode, inode->i_mode, rdev);
6473 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6477 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6482 btrfs_update_inode(trans, root, inode);
6483 d_instantiate_new(dentry, inode);
6486 btrfs_end_transaction(trans);
6487 btrfs_btree_balance_dirty(fs_info);
6489 inode_dec_link_count(inode);
6490 discard_new_inode(inode);
6495 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6496 umode_t mode, bool excl)
6498 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6499 struct btrfs_trans_handle *trans;
6500 struct btrfs_root *root = BTRFS_I(dir)->root;
6501 struct inode *inode = NULL;
6507 * 2 for inode item and ref
6509 * 1 for xattr if selinux is on
6511 trans = btrfs_start_transaction(root, 5);
6513 return PTR_ERR(trans);
6515 err = btrfs_find_free_ino(root, &objectid);
6519 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6520 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6522 if (IS_ERR(inode)) {
6523 err = PTR_ERR(inode);
6528 * If the active LSM wants to access the inode during
6529 * d_instantiate it needs these. Smack checks to see
6530 * if the filesystem supports xattrs by looking at the
6533 inode->i_fop = &btrfs_file_operations;
6534 inode->i_op = &btrfs_file_inode_operations;
6535 inode->i_mapping->a_ops = &btrfs_aops;
6537 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6541 err = btrfs_update_inode(trans, root, inode);
6545 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6550 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6551 d_instantiate_new(dentry, inode);
6554 btrfs_end_transaction(trans);
6556 inode_dec_link_count(inode);
6557 discard_new_inode(inode);
6559 btrfs_btree_balance_dirty(fs_info);
6563 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6564 struct dentry *dentry)
6566 struct btrfs_trans_handle *trans = NULL;
6567 struct btrfs_root *root = BTRFS_I(dir)->root;
6568 struct inode *inode = d_inode(old_dentry);
6569 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6574 /* do not allow sys_link's with other subvols of the same device */
6575 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6578 if (inode->i_nlink >= BTRFS_LINK_MAX)
6581 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6586 * 2 items for inode and inode ref
6587 * 2 items for dir items
6588 * 1 item for parent inode
6589 * 1 item for orphan item deletion if O_TMPFILE
6591 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6592 if (IS_ERR(trans)) {
6593 err = PTR_ERR(trans);
6598 /* There are several dir indexes for this inode, clear the cache. */
6599 BTRFS_I(inode)->dir_index = 0ULL;
6601 inode_inc_iversion(inode);
6602 inode->i_ctime = current_time(inode);
6604 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6606 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6612 struct dentry *parent = dentry->d_parent;
6615 err = btrfs_update_inode(trans, root, inode);
6618 if (inode->i_nlink == 1) {
6620 * If new hard link count is 1, it's a file created
6621 * with open(2) O_TMPFILE flag.
6623 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6627 BTRFS_I(inode)->last_link_trans = trans->transid;
6628 d_instantiate(dentry, inode);
6629 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6631 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6632 err = btrfs_commit_transaction(trans);
6639 btrfs_end_transaction(trans);
6641 inode_dec_link_count(inode);
6644 btrfs_btree_balance_dirty(fs_info);
6648 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6650 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6651 struct inode *inode = NULL;
6652 struct btrfs_trans_handle *trans;
6653 struct btrfs_root *root = BTRFS_I(dir)->root;
6659 * 2 items for inode and ref
6660 * 2 items for dir items
6661 * 1 for xattr if selinux is on
6663 trans = btrfs_start_transaction(root, 5);
6665 return PTR_ERR(trans);
6667 err = btrfs_find_free_ino(root, &objectid);
6671 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6672 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6673 S_IFDIR | mode, &index);
6674 if (IS_ERR(inode)) {
6675 err = PTR_ERR(inode);
6680 /* these must be set before we unlock the inode */
6681 inode->i_op = &btrfs_dir_inode_operations;
6682 inode->i_fop = &btrfs_dir_file_operations;
6684 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6688 btrfs_i_size_write(BTRFS_I(inode), 0);
6689 err = btrfs_update_inode(trans, root, inode);
6693 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6694 dentry->d_name.name,
6695 dentry->d_name.len, 0, index);
6699 d_instantiate_new(dentry, inode);
6702 btrfs_end_transaction(trans);
6704 inode_dec_link_count(inode);
6705 discard_new_inode(inode);
6707 btrfs_btree_balance_dirty(fs_info);
6711 static noinline int uncompress_inline(struct btrfs_path *path,
6713 size_t pg_offset, u64 extent_offset,
6714 struct btrfs_file_extent_item *item)
6717 struct extent_buffer *leaf = path->nodes[0];
6720 unsigned long inline_size;
6724 WARN_ON(pg_offset != 0);
6725 compress_type = btrfs_file_extent_compression(leaf, item);
6726 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6727 inline_size = btrfs_file_extent_inline_item_len(leaf,
6728 btrfs_item_nr(path->slots[0]));
6729 tmp = kmalloc(inline_size, GFP_NOFS);
6732 ptr = btrfs_file_extent_inline_start(item);
6734 read_extent_buffer(leaf, tmp, ptr, inline_size);
6736 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6737 ret = btrfs_decompress(compress_type, tmp, page,
6738 extent_offset, inline_size, max_size);
6741 * decompression code contains a memset to fill in any space between the end
6742 * of the uncompressed data and the end of max_size in case the decompressed
6743 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6744 * the end of an inline extent and the beginning of the next block, so we
6745 * cover that region here.
6748 if (max_size + pg_offset < PAGE_SIZE) {
6749 char *map = kmap(page);
6750 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6758 * a bit scary, this does extent mapping from logical file offset to the disk.
6759 * the ugly parts come from merging extents from the disk with the in-ram
6760 * representation. This gets more complex because of the data=ordered code,
6761 * where the in-ram extents might be locked pending data=ordered completion.
6763 * This also copies inline extents directly into the page.
6765 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6767 size_t pg_offset, u64 start, u64 len,
6770 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6773 u64 extent_start = 0;
6775 u64 objectid = btrfs_ino(inode);
6777 struct btrfs_path *path = NULL;
6778 struct btrfs_root *root = inode->root;
6779 struct btrfs_file_extent_item *item;
6780 struct extent_buffer *leaf;
6781 struct btrfs_key found_key;
6782 struct extent_map *em = NULL;
6783 struct extent_map_tree *em_tree = &inode->extent_tree;
6784 struct extent_io_tree *io_tree = &inode->io_tree;
6785 const bool new_inline = !page || create;
6787 read_lock(&em_tree->lock);
6788 em = lookup_extent_mapping(em_tree, start, len);
6790 em->bdev = fs_info->fs_devices->latest_bdev;
6791 read_unlock(&em_tree->lock);
6794 if (em->start > start || em->start + em->len <= start)
6795 free_extent_map(em);
6796 else if (em->block_start == EXTENT_MAP_INLINE && page)
6797 free_extent_map(em);
6801 em = alloc_extent_map();
6806 em->bdev = fs_info->fs_devices->latest_bdev;
6807 em->start = EXTENT_MAP_HOLE;
6808 em->orig_start = EXTENT_MAP_HOLE;
6810 em->block_len = (u64)-1;
6812 path = btrfs_alloc_path();
6818 /* Chances are we'll be called again, so go ahead and do readahead */
6819 path->reada = READA_FORWARD;
6822 * Unless we're going to uncompress the inline extent, no sleep would
6825 path->leave_spinning = 1;
6827 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6834 if (path->slots[0] == 0)
6839 leaf = path->nodes[0];
6840 item = btrfs_item_ptr(leaf, path->slots[0],
6841 struct btrfs_file_extent_item);
6842 /* are we inside the extent that was found? */
6843 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6844 found_type = found_key.type;
6845 if (found_key.objectid != objectid ||
6846 found_type != BTRFS_EXTENT_DATA_KEY) {
6848 * If we backup past the first extent we want to move forward
6849 * and see if there is an extent in front of us, otherwise we'll
6850 * say there is a hole for our whole search range which can
6857 found_type = btrfs_file_extent_type(leaf, item);
6858 extent_start = found_key.offset;
6859 if (found_type == BTRFS_FILE_EXTENT_REG ||
6860 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6861 extent_end = extent_start +
6862 btrfs_file_extent_num_bytes(leaf, item);
6864 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6866 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6869 size = btrfs_file_extent_ram_bytes(leaf, item);
6870 extent_end = ALIGN(extent_start + size,
6871 fs_info->sectorsize);
6873 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6878 if (start >= extent_end) {
6880 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6881 ret = btrfs_next_leaf(root, path);
6888 leaf = path->nodes[0];
6890 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6891 if (found_key.objectid != objectid ||
6892 found_key.type != BTRFS_EXTENT_DATA_KEY)
6894 if (start + len <= found_key.offset)
6896 if (start > found_key.offset)
6899 em->orig_start = start;
6900 em->len = found_key.offset - start;
6904 btrfs_extent_item_to_extent_map(inode, path, item,
6907 if (found_type == BTRFS_FILE_EXTENT_REG ||
6908 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6910 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6914 size_t extent_offset;
6920 size = btrfs_file_extent_ram_bytes(leaf, item);
6921 extent_offset = page_offset(page) + pg_offset - extent_start;
6922 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6923 size - extent_offset);
6924 em->start = extent_start + extent_offset;
6925 em->len = ALIGN(copy_size, fs_info->sectorsize);
6926 em->orig_block_len = em->len;
6927 em->orig_start = em->start;
6928 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6930 btrfs_set_path_blocking(path);
6931 if (!PageUptodate(page)) {
6932 if (btrfs_file_extent_compression(leaf, item) !=
6933 BTRFS_COMPRESS_NONE) {
6934 ret = uncompress_inline(path, page, pg_offset,
6935 extent_offset, item);
6942 read_extent_buffer(leaf, map + pg_offset, ptr,
6944 if (pg_offset + copy_size < PAGE_SIZE) {
6945 memset(map + pg_offset + copy_size, 0,
6946 PAGE_SIZE - pg_offset -
6951 flush_dcache_page(page);
6953 set_extent_uptodate(io_tree, em->start,
6954 extent_map_end(em) - 1, NULL, GFP_NOFS);
6959 em->orig_start = start;
6962 em->block_start = EXTENT_MAP_HOLE;
6964 btrfs_release_path(path);
6965 if (em->start > start || extent_map_end(em) <= start) {
6967 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6968 em->start, em->len, start, len);
6974 write_lock(&em_tree->lock);
6975 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6976 write_unlock(&em_tree->lock);
6978 btrfs_free_path(path);
6980 trace_btrfs_get_extent(root, inode, em);
6983 free_extent_map(em);
6984 return ERR_PTR(err);
6986 BUG_ON(!em); /* Error is always set */
6990 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6992 size_t pg_offset, u64 start, u64 len,
6995 struct extent_map *em;
6996 struct extent_map *hole_em = NULL;
6997 u64 range_start = start;
7003 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7007 * If our em maps to:
7009 * - a pre-alloc extent,
7010 * there might actually be delalloc bytes behind it.
7012 if (em->block_start != EXTENT_MAP_HOLE &&
7013 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7018 /* check to see if we've wrapped (len == -1 or similar) */
7027 /* ok, we didn't find anything, lets look for delalloc */
7028 found = count_range_bits(&inode->io_tree, &range_start,
7029 end, len, EXTENT_DELALLOC, 1);
7030 found_end = range_start + found;
7031 if (found_end < range_start)
7032 found_end = (u64)-1;
7035 * we didn't find anything useful, return
7036 * the original results from get_extent()
7038 if (range_start > end || found_end <= start) {
7044 /* adjust the range_start to make sure it doesn't
7045 * go backwards from the start they passed in
7047 range_start = max(start, range_start);
7048 found = found_end - range_start;
7051 u64 hole_start = start;
7054 em = alloc_extent_map();
7060 * when btrfs_get_extent can't find anything it
7061 * returns one huge hole
7063 * make sure what it found really fits our range, and
7064 * adjust to make sure it is based on the start from
7068 u64 calc_end = extent_map_end(hole_em);
7070 if (calc_end <= start || (hole_em->start > end)) {
7071 free_extent_map(hole_em);
7074 hole_start = max(hole_em->start, start);
7075 hole_len = calc_end - hole_start;
7079 if (hole_em && range_start > hole_start) {
7080 /* our hole starts before our delalloc, so we
7081 * have to return just the parts of the hole
7082 * that go until the delalloc starts
7084 em->len = min(hole_len,
7085 range_start - hole_start);
7086 em->start = hole_start;
7087 em->orig_start = hole_start;
7089 * don't adjust block start at all,
7090 * it is fixed at EXTENT_MAP_HOLE
7092 em->block_start = hole_em->block_start;
7093 em->block_len = hole_len;
7094 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7095 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7097 em->start = range_start;
7099 em->orig_start = range_start;
7100 em->block_start = EXTENT_MAP_DELALLOC;
7101 em->block_len = found;
7108 free_extent_map(hole_em);
7110 free_extent_map(em);
7111 return ERR_PTR(err);
7116 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7119 const u64 orig_start,
7120 const u64 block_start,
7121 const u64 block_len,
7122 const u64 orig_block_len,
7123 const u64 ram_bytes,
7126 struct extent_map *em = NULL;
7129 if (type != BTRFS_ORDERED_NOCOW) {
7130 em = create_io_em(inode, start, len, orig_start,
7131 block_start, block_len, orig_block_len,
7133 BTRFS_COMPRESS_NONE, /* compress_type */
7138 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7139 len, block_len, type);
7142 free_extent_map(em);
7143 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7144 start + len - 1, 0);
7153 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7156 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7157 struct btrfs_root *root = BTRFS_I(inode)->root;
7158 struct extent_map *em;
7159 struct btrfs_key ins;
7163 alloc_hint = get_extent_allocation_hint(inode, start, len);
7164 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7165 0, alloc_hint, &ins, 1, 1);
7167 return ERR_PTR(ret);
7169 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7170 ins.objectid, ins.offset, ins.offset,
7171 ins.offset, BTRFS_ORDERED_REGULAR);
7172 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7174 btrfs_free_reserved_extent(fs_info, ins.objectid,
7181 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7182 * block must be cow'd
7184 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7185 u64 *orig_start, u64 *orig_block_len,
7188 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7189 struct btrfs_path *path;
7191 struct extent_buffer *leaf;
7192 struct btrfs_root *root = BTRFS_I(inode)->root;
7193 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7194 struct btrfs_file_extent_item *fi;
7195 struct btrfs_key key;
7202 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7204 path = btrfs_alloc_path();
7208 ret = btrfs_lookup_file_extent(NULL, root, path,
7209 btrfs_ino(BTRFS_I(inode)), offset, 0);
7213 slot = path->slots[0];
7216 /* can't find the item, must cow */
7223 leaf = path->nodes[0];
7224 btrfs_item_key_to_cpu(leaf, &key, slot);
7225 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7226 key.type != BTRFS_EXTENT_DATA_KEY) {
7227 /* not our file or wrong item type, must cow */
7231 if (key.offset > offset) {
7232 /* Wrong offset, must cow */
7236 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7237 found_type = btrfs_file_extent_type(leaf, fi);
7238 if (found_type != BTRFS_FILE_EXTENT_REG &&
7239 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7240 /* not a regular extent, must cow */
7244 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7247 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7248 if (extent_end <= offset)
7251 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7252 if (disk_bytenr == 0)
7255 if (btrfs_file_extent_compression(leaf, fi) ||
7256 btrfs_file_extent_encryption(leaf, fi) ||
7257 btrfs_file_extent_other_encoding(leaf, fi))
7261 * Do the same check as in btrfs_cross_ref_exist but without the
7262 * unnecessary search.
7264 if (btrfs_file_extent_generation(leaf, fi) <=
7265 btrfs_root_last_snapshot(&root->root_item))
7268 backref_offset = btrfs_file_extent_offset(leaf, fi);
7271 *orig_start = key.offset - backref_offset;
7272 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7273 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7276 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7279 num_bytes = min(offset + *len, extent_end) - offset;
7280 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7283 range_end = round_up(offset + num_bytes,
7284 root->fs_info->sectorsize) - 1;
7285 ret = test_range_bit(io_tree, offset, range_end,
7286 EXTENT_DELALLOC, 0, NULL);
7293 btrfs_release_path(path);
7296 * look for other files referencing this extent, if we
7297 * find any we must cow
7300 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7301 key.offset - backref_offset, disk_bytenr);
7308 * adjust disk_bytenr and num_bytes to cover just the bytes
7309 * in this extent we are about to write. If there
7310 * are any csums in that range we have to cow in order
7311 * to keep the csums correct
7313 disk_bytenr += backref_offset;
7314 disk_bytenr += offset - key.offset;
7315 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7318 * all of the above have passed, it is safe to overwrite this extent
7324 btrfs_free_path(path);
7328 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7329 struct extent_state **cached_state, int writing)
7331 struct btrfs_ordered_extent *ordered;
7335 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7338 * We're concerned with the entire range that we're going to be
7339 * doing DIO to, so we need to make sure there's no ordered
7340 * extents in this range.
7342 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7343 lockend - lockstart + 1);
7346 * We need to make sure there are no buffered pages in this
7347 * range either, we could have raced between the invalidate in
7348 * generic_file_direct_write and locking the extent. The
7349 * invalidate needs to happen so that reads after a write do not
7353 (!writing || !filemap_range_has_page(inode->i_mapping,
7354 lockstart, lockend)))
7357 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7362 * If we are doing a DIO read and the ordered extent we
7363 * found is for a buffered write, we can not wait for it
7364 * to complete and retry, because if we do so we can
7365 * deadlock with concurrent buffered writes on page
7366 * locks. This happens only if our DIO read covers more
7367 * than one extent map, if at this point has already
7368 * created an ordered extent for a previous extent map
7369 * and locked its range in the inode's io tree, and a
7370 * concurrent write against that previous extent map's
7371 * range and this range started (we unlock the ranges
7372 * in the io tree only when the bios complete and
7373 * buffered writes always lock pages before attempting
7374 * to lock range in the io tree).
7377 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7378 btrfs_start_ordered_extent(inode, ordered, 1);
7381 btrfs_put_ordered_extent(ordered);
7384 * We could trigger writeback for this range (and wait
7385 * for it to complete) and then invalidate the pages for
7386 * this range (through invalidate_inode_pages2_range()),
7387 * but that can lead us to a deadlock with a concurrent
7388 * call to readpages() (a buffered read or a defrag call
7389 * triggered a readahead) on a page lock due to an
7390 * ordered dio extent we created before but did not have
7391 * yet a corresponding bio submitted (whence it can not
7392 * complete), which makes readpages() wait for that
7393 * ordered extent to complete while holding a lock on
7408 /* The callers of this must take lock_extent() */
7409 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7410 u64 orig_start, u64 block_start,
7411 u64 block_len, u64 orig_block_len,
7412 u64 ram_bytes, int compress_type,
7415 struct extent_map_tree *em_tree;
7416 struct extent_map *em;
7417 struct btrfs_root *root = BTRFS_I(inode)->root;
7420 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7421 type == BTRFS_ORDERED_COMPRESSED ||
7422 type == BTRFS_ORDERED_NOCOW ||
7423 type == BTRFS_ORDERED_REGULAR);
7425 em_tree = &BTRFS_I(inode)->extent_tree;
7426 em = alloc_extent_map();
7428 return ERR_PTR(-ENOMEM);
7431 em->orig_start = orig_start;
7433 em->block_len = block_len;
7434 em->block_start = block_start;
7435 em->bdev = root->fs_info->fs_devices->latest_bdev;
7436 em->orig_block_len = orig_block_len;
7437 em->ram_bytes = ram_bytes;
7438 em->generation = -1;
7439 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7440 if (type == BTRFS_ORDERED_PREALLOC) {
7441 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7442 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7443 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7444 em->compress_type = compress_type;
7448 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7449 em->start + em->len - 1, 0);
7450 write_lock(&em_tree->lock);
7451 ret = add_extent_mapping(em_tree, em, 1);
7452 write_unlock(&em_tree->lock);
7454 * The caller has taken lock_extent(), who could race with us
7457 } while (ret == -EEXIST);
7460 free_extent_map(em);
7461 return ERR_PTR(ret);
7464 /* em got 2 refs now, callers needs to do free_extent_map once. */
7469 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7470 struct buffer_head *bh_result,
7471 struct inode *inode,
7474 if (em->block_start == EXTENT_MAP_HOLE ||
7475 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7478 len = min(len, em->len - (start - em->start));
7480 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7482 bh_result->b_size = len;
7483 bh_result->b_bdev = em->bdev;
7484 set_buffer_mapped(bh_result);
7489 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7490 struct buffer_head *bh_result,
7491 struct inode *inode,
7492 struct btrfs_dio_data *dio_data,
7495 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7496 struct extent_map *em = *map;
7500 * We don't allocate a new extent in the following cases
7502 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7504 * 2) The extent is marked as PREALLOC. We're good to go here and can
7505 * just use the extent.
7508 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7509 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7510 em->block_start != EXTENT_MAP_HOLE)) {
7512 u64 block_start, orig_start, orig_block_len, ram_bytes;
7514 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7515 type = BTRFS_ORDERED_PREALLOC;
7517 type = BTRFS_ORDERED_NOCOW;
7518 len = min(len, em->len - (start - em->start));
7519 block_start = em->block_start + (start - em->start);
7521 if (can_nocow_extent(inode, start, &len, &orig_start,
7522 &orig_block_len, &ram_bytes) == 1 &&
7523 btrfs_inc_nocow_writers(fs_info, block_start)) {
7524 struct extent_map *em2;
7526 em2 = btrfs_create_dio_extent(inode, start, len,
7527 orig_start, block_start,
7528 len, orig_block_len,
7530 btrfs_dec_nocow_writers(fs_info, block_start);
7531 if (type == BTRFS_ORDERED_PREALLOC) {
7532 free_extent_map(em);
7536 if (em2 && IS_ERR(em2)) {
7541 * For inode marked NODATACOW or extent marked PREALLOC,
7542 * use the existing or preallocated extent, so does not
7543 * need to adjust btrfs_space_info's bytes_may_use.
7545 btrfs_free_reserved_data_space_noquota(inode, start,
7551 /* this will cow the extent */
7552 len = bh_result->b_size;
7553 free_extent_map(em);
7554 *map = em = btrfs_new_extent_direct(inode, start, len);
7560 len = min(len, em->len - (start - em->start));
7563 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7565 bh_result->b_size = len;
7566 bh_result->b_bdev = em->bdev;
7567 set_buffer_mapped(bh_result);
7569 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7570 set_buffer_new(bh_result);
7573 * Need to update the i_size under the extent lock so buffered
7574 * readers will get the updated i_size when we unlock.
7576 if (!dio_data->overwrite && start + len > i_size_read(inode))
7577 i_size_write(inode, start + len);
7579 WARN_ON(dio_data->reserve < len);
7580 dio_data->reserve -= len;
7581 dio_data->unsubmitted_oe_range_end = start + len;
7582 current->journal_info = dio_data;
7587 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7588 struct buffer_head *bh_result, int create)
7590 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7591 struct extent_map *em;
7592 struct extent_state *cached_state = NULL;
7593 struct btrfs_dio_data *dio_data = NULL;
7594 u64 start = iblock << inode->i_blkbits;
7595 u64 lockstart, lockend;
7596 u64 len = bh_result->b_size;
7597 int unlock_bits = EXTENT_LOCKED;
7601 unlock_bits |= EXTENT_DIRTY;
7603 len = min_t(u64, len, fs_info->sectorsize);
7606 lockend = start + len - 1;
7608 if (current->journal_info) {
7610 * Need to pull our outstanding extents and set journal_info to NULL so
7611 * that anything that needs to check if there's a transaction doesn't get
7614 dio_data = current->journal_info;
7615 current->journal_info = NULL;
7619 * If this errors out it's because we couldn't invalidate pagecache for
7620 * this range and we need to fallback to buffered.
7622 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7628 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7635 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7636 * io. INLINE is special, and we could probably kludge it in here, but
7637 * it's still buffered so for safety lets just fall back to the generic
7640 * For COMPRESSED we _have_ to read the entire extent in so we can
7641 * decompress it, so there will be buffering required no matter what we
7642 * do, so go ahead and fallback to buffered.
7644 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7645 * to buffered IO. Don't blame me, this is the price we pay for using
7648 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7649 em->block_start == EXTENT_MAP_INLINE) {
7650 free_extent_map(em);
7656 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7657 dio_data, start, len);
7661 /* clear and unlock the entire range */
7662 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7663 unlock_bits, 1, 0, &cached_state);
7665 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7667 /* Can be negative only if we read from a hole */
7670 free_extent_map(em);
7674 * We need to unlock only the end area that we aren't using.
7675 * The rest is going to be unlocked by the endio routine.
7677 lockstart = start + bh_result->b_size;
7678 if (lockstart < lockend) {
7679 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7680 lockend, unlock_bits, 1, 0,
7683 free_extent_state(cached_state);
7687 free_extent_map(em);
7692 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7693 unlock_bits, 1, 0, &cached_state);
7696 current->journal_info = dio_data;
7700 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7704 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7707 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7709 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7713 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7718 static int btrfs_check_dio_repairable(struct inode *inode,
7719 struct bio *failed_bio,
7720 struct io_failure_record *failrec,
7723 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7726 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7727 if (num_copies == 1) {
7729 * we only have a single copy of the data, so don't bother with
7730 * all the retry and error correction code that follows. no
7731 * matter what the error is, it is very likely to persist.
7733 btrfs_debug(fs_info,
7734 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7735 num_copies, failrec->this_mirror, failed_mirror);
7739 failrec->failed_mirror = failed_mirror;
7740 failrec->this_mirror++;
7741 if (failrec->this_mirror == failed_mirror)
7742 failrec->this_mirror++;
7744 if (failrec->this_mirror > num_copies) {
7745 btrfs_debug(fs_info,
7746 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7747 num_copies, failrec->this_mirror, failed_mirror);
7754 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7755 struct page *page, unsigned int pgoff,
7756 u64 start, u64 end, int failed_mirror,
7757 bio_end_io_t *repair_endio, void *repair_arg)
7759 struct io_failure_record *failrec;
7760 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7761 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7764 unsigned int read_mode = 0;
7767 blk_status_t status;
7768 struct bio_vec bvec;
7770 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7772 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7774 return errno_to_blk_status(ret);
7776 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7779 free_io_failure(failure_tree, io_tree, failrec);
7780 return BLK_STS_IOERR;
7783 segs = bio_segments(failed_bio);
7784 bio_get_first_bvec(failed_bio, &bvec);
7786 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7787 read_mode |= REQ_FAILFAST_DEV;
7789 isector = start - btrfs_io_bio(failed_bio)->logical;
7790 isector >>= inode->i_sb->s_blocksize_bits;
7791 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7792 pgoff, isector, repair_endio, repair_arg);
7793 bio->bi_opf = REQ_OP_READ | read_mode;
7795 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7796 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7797 read_mode, failrec->this_mirror, failrec->in_validation);
7799 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7801 free_io_failure(failure_tree, io_tree, failrec);
7808 struct btrfs_retry_complete {
7809 struct completion done;
7810 struct inode *inode;
7815 static void btrfs_retry_endio_nocsum(struct bio *bio)
7817 struct btrfs_retry_complete *done = bio->bi_private;
7818 struct inode *inode = done->inode;
7819 struct bio_vec *bvec;
7820 struct extent_io_tree *io_tree, *failure_tree;
7826 ASSERT(bio->bi_vcnt == 1);
7827 io_tree = &BTRFS_I(inode)->io_tree;
7828 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7829 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7832 ASSERT(!bio_flagged(bio, BIO_CLONED));
7833 bio_for_each_segment_all(bvec, bio, i)
7834 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7835 io_tree, done->start, bvec->bv_page,
7836 btrfs_ino(BTRFS_I(inode)), 0);
7838 complete(&done->done);
7842 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7843 struct btrfs_io_bio *io_bio)
7845 struct btrfs_fs_info *fs_info;
7846 struct bio_vec bvec;
7847 struct bvec_iter iter;
7848 struct btrfs_retry_complete done;
7854 blk_status_t err = BLK_STS_OK;
7856 fs_info = BTRFS_I(inode)->root->fs_info;
7857 sectorsize = fs_info->sectorsize;
7859 start = io_bio->logical;
7861 io_bio->bio.bi_iter = io_bio->iter;
7863 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7864 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7865 pgoff = bvec.bv_offset;
7867 next_block_or_try_again:
7870 init_completion(&done.done);
7872 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7873 pgoff, start, start + sectorsize - 1,
7875 btrfs_retry_endio_nocsum, &done);
7881 wait_for_completion_io(&done.done);
7883 if (!done.uptodate) {
7884 /* We might have another mirror, so try again */
7885 goto next_block_or_try_again;
7889 start += sectorsize;
7893 pgoff += sectorsize;
7894 ASSERT(pgoff < PAGE_SIZE);
7895 goto next_block_or_try_again;
7902 static void btrfs_retry_endio(struct bio *bio)
7904 struct btrfs_retry_complete *done = bio->bi_private;
7905 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7906 struct extent_io_tree *io_tree, *failure_tree;
7907 struct inode *inode = done->inode;
7908 struct bio_vec *bvec;
7918 ASSERT(bio->bi_vcnt == 1);
7919 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7921 io_tree = &BTRFS_I(inode)->io_tree;
7922 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7924 ASSERT(!bio_flagged(bio, BIO_CLONED));
7925 bio_for_each_segment_all(bvec, bio, i) {
7926 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7927 bvec->bv_offset, done->start,
7930 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7931 failure_tree, io_tree, done->start,
7933 btrfs_ino(BTRFS_I(inode)),
7939 done->uptodate = uptodate;
7941 complete(&done->done);
7945 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7946 struct btrfs_io_bio *io_bio, blk_status_t err)
7948 struct btrfs_fs_info *fs_info;
7949 struct bio_vec bvec;
7950 struct bvec_iter iter;
7951 struct btrfs_retry_complete done;
7958 bool uptodate = (err == 0);
7960 blk_status_t status;
7962 fs_info = BTRFS_I(inode)->root->fs_info;
7963 sectorsize = fs_info->sectorsize;
7966 start = io_bio->logical;
7968 io_bio->bio.bi_iter = io_bio->iter;
7970 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7971 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7973 pgoff = bvec.bv_offset;
7976 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7977 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7978 bvec.bv_page, pgoff, start, sectorsize);
7985 init_completion(&done.done);
7987 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7988 pgoff, start, start + sectorsize - 1,
7989 io_bio->mirror_num, btrfs_retry_endio,
7996 wait_for_completion_io(&done.done);
7998 if (!done.uptodate) {
7999 /* We might have another mirror, so try again */
8003 offset += sectorsize;
8004 start += sectorsize;
8010 pgoff += sectorsize;
8011 ASSERT(pgoff < PAGE_SIZE);
8019 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8020 struct btrfs_io_bio *io_bio, blk_status_t err)
8022 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8026 return __btrfs_correct_data_nocsum(inode, io_bio);
8030 return __btrfs_subio_endio_read(inode, io_bio, err);
8034 static void btrfs_endio_direct_read(struct bio *bio)
8036 struct btrfs_dio_private *dip = bio->bi_private;
8037 struct inode *inode = dip->inode;
8038 struct bio *dio_bio;
8039 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8040 blk_status_t err = bio->bi_status;
8042 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8043 err = btrfs_subio_endio_read(inode, io_bio, err);
8045 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8046 dip->logical_offset + dip->bytes - 1);
8047 dio_bio = dip->dio_bio;
8051 dio_bio->bi_status = err;
8052 dio_end_io(dio_bio);
8053 btrfs_io_bio_free_csum(io_bio);
8057 static void __endio_write_update_ordered(struct inode *inode,
8058 const u64 offset, const u64 bytes,
8059 const bool uptodate)
8061 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8062 struct btrfs_ordered_extent *ordered = NULL;
8063 struct btrfs_workqueue *wq;
8064 btrfs_work_func_t func;
8065 u64 ordered_offset = offset;
8066 u64 ordered_bytes = bytes;
8069 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8070 wq = fs_info->endio_freespace_worker;
8071 func = btrfs_freespace_write_helper;
8073 wq = fs_info->endio_write_workers;
8074 func = btrfs_endio_write_helper;
8077 while (ordered_offset < offset + bytes) {
8078 last_offset = ordered_offset;
8079 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8083 btrfs_init_work(&ordered->work, func,
8086 btrfs_queue_work(wq, &ordered->work);
8089 * If btrfs_dec_test_ordered_pending does not find any ordered
8090 * extent in the range, we can exit.
8092 if (ordered_offset == last_offset)
8095 * Our bio might span multiple ordered extents. In this case
8096 * we keep goin until we have accounted the whole dio.
8098 if (ordered_offset < offset + bytes) {
8099 ordered_bytes = offset + bytes - ordered_offset;
8105 static void btrfs_endio_direct_write(struct bio *bio)
8107 struct btrfs_dio_private *dip = bio->bi_private;
8108 struct bio *dio_bio = dip->dio_bio;
8110 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8111 dip->bytes, !bio->bi_status);
8115 dio_bio->bi_status = bio->bi_status;
8116 dio_end_io(dio_bio);
8120 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8121 struct bio *bio, u64 offset)
8123 struct inode *inode = private_data;
8125 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8126 BUG_ON(ret); /* -ENOMEM */
8130 static void btrfs_end_dio_bio(struct bio *bio)
8132 struct btrfs_dio_private *dip = bio->bi_private;
8133 blk_status_t err = bio->bi_status;
8136 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8137 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8138 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8140 (unsigned long long)bio->bi_iter.bi_sector,
8141 bio->bi_iter.bi_size, err);
8143 if (dip->subio_endio)
8144 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8148 * We want to perceive the errors flag being set before
8149 * decrementing the reference count. We don't need a barrier
8150 * since atomic operations with a return value are fully
8151 * ordered as per atomic_t.txt
8156 /* if there are more bios still pending for this dio, just exit */
8157 if (!atomic_dec_and_test(&dip->pending_bios))
8161 bio_io_error(dip->orig_bio);
8163 dip->dio_bio->bi_status = BLK_STS_OK;
8164 bio_endio(dip->orig_bio);
8170 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8171 struct btrfs_dio_private *dip,
8175 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8176 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8180 * We load all the csum data we need when we submit
8181 * the first bio to reduce the csum tree search and
8184 if (dip->logical_offset == file_offset) {
8185 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8191 if (bio == dip->orig_bio)
8194 file_offset -= dip->logical_offset;
8195 file_offset >>= inode->i_sb->s_blocksize_bits;
8196 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8201 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8202 struct inode *inode, u64 file_offset, int async_submit)
8204 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8205 struct btrfs_dio_private *dip = bio->bi_private;
8206 bool write = bio_op(bio) == REQ_OP_WRITE;
8209 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8211 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8214 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8219 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8222 if (write && async_submit) {
8223 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8225 btrfs_submit_bio_start_direct_io);
8229 * If we aren't doing async submit, calculate the csum of the
8232 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8236 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8242 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8247 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8249 struct inode *inode = dip->inode;
8250 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8252 struct bio *orig_bio = dip->orig_bio;
8253 u64 start_sector = orig_bio->bi_iter.bi_sector;
8254 u64 file_offset = dip->logical_offset;
8256 int async_submit = 0;
8258 int clone_offset = 0;
8261 blk_status_t status;
8263 map_length = orig_bio->bi_iter.bi_size;
8264 submit_len = map_length;
8265 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8266 &map_length, NULL, 0);
8270 if (map_length >= submit_len) {
8272 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8276 /* async crcs make it difficult to collect full stripe writes. */
8277 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8283 ASSERT(map_length <= INT_MAX);
8284 atomic_inc(&dip->pending_bios);
8286 clone_len = min_t(int, submit_len, map_length);
8289 * This will never fail as it's passing GPF_NOFS and
8290 * the allocation is backed by btrfs_bioset.
8292 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8294 bio->bi_private = dip;
8295 bio->bi_end_io = btrfs_end_dio_bio;
8296 btrfs_io_bio(bio)->logical = file_offset;
8298 ASSERT(submit_len >= clone_len);
8299 submit_len -= clone_len;
8300 if (submit_len == 0)
8304 * Increase the count before we submit the bio so we know
8305 * the end IO handler won't happen before we increase the
8306 * count. Otherwise, the dip might get freed before we're
8307 * done setting it up.
8309 atomic_inc(&dip->pending_bios);
8311 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8315 atomic_dec(&dip->pending_bios);
8319 clone_offset += clone_len;
8320 start_sector += clone_len >> 9;
8321 file_offset += clone_len;
8323 map_length = submit_len;
8324 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8325 start_sector << 9, &map_length, NULL, 0);
8328 } while (submit_len > 0);
8331 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8339 * Before atomic variable goto zero, we must make sure dip->errors is
8340 * perceived to be set. This ordering is ensured by the fact that an
8341 * atomic operations with a return value are fully ordered as per
8344 if (atomic_dec_and_test(&dip->pending_bios))
8345 bio_io_error(dip->orig_bio);
8347 /* bio_end_io() will handle error, so we needn't return it */
8351 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8354 struct btrfs_dio_private *dip = NULL;
8355 struct bio *bio = NULL;
8356 struct btrfs_io_bio *io_bio;
8357 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8360 bio = btrfs_bio_clone(dio_bio);
8362 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8368 dip->private = dio_bio->bi_private;
8370 dip->logical_offset = file_offset;
8371 dip->bytes = dio_bio->bi_iter.bi_size;
8372 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8373 bio->bi_private = dip;
8374 dip->orig_bio = bio;
8375 dip->dio_bio = dio_bio;
8376 atomic_set(&dip->pending_bios, 0);
8377 io_bio = btrfs_io_bio(bio);
8378 io_bio->logical = file_offset;
8381 bio->bi_end_io = btrfs_endio_direct_write;
8383 bio->bi_end_io = btrfs_endio_direct_read;
8384 dip->subio_endio = btrfs_subio_endio_read;
8388 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8389 * even if we fail to submit a bio, because in such case we do the
8390 * corresponding error handling below and it must not be done a second
8391 * time by btrfs_direct_IO().
8394 struct btrfs_dio_data *dio_data = current->journal_info;
8396 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8398 dio_data->unsubmitted_oe_range_start =
8399 dio_data->unsubmitted_oe_range_end;
8402 ret = btrfs_submit_direct_hook(dip);
8406 btrfs_io_bio_free_csum(io_bio);
8410 * If we arrived here it means either we failed to submit the dip
8411 * or we either failed to clone the dio_bio or failed to allocate the
8412 * dip. If we cloned the dio_bio and allocated the dip, we can just
8413 * call bio_endio against our io_bio so that we get proper resource
8414 * cleanup if we fail to submit the dip, otherwise, we must do the
8415 * same as btrfs_endio_direct_[write|read] because we can't call these
8416 * callbacks - they require an allocated dip and a clone of dio_bio.
8421 * The end io callbacks free our dip, do the final put on bio
8422 * and all the cleanup and final put for dio_bio (through
8429 __endio_write_update_ordered(inode,
8431 dio_bio->bi_iter.bi_size,
8434 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8435 file_offset + dio_bio->bi_iter.bi_size - 1);
8437 dio_bio->bi_status = BLK_STS_IOERR;
8439 * Releases and cleans up our dio_bio, no need to bio_put()
8440 * nor bio_endio()/bio_io_error() against dio_bio.
8442 dio_end_io(dio_bio);
8449 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8450 const struct iov_iter *iter, loff_t offset)
8454 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8455 ssize_t retval = -EINVAL;
8457 if (offset & blocksize_mask)
8460 if (iov_iter_alignment(iter) & blocksize_mask)
8463 /* If this is a write we don't need to check anymore */
8464 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8467 * Check to make sure we don't have duplicate iov_base's in this
8468 * iovec, if so return EINVAL, otherwise we'll get csum errors
8469 * when reading back.
8471 for (seg = 0; seg < iter->nr_segs; seg++) {
8472 for (i = seg + 1; i < iter->nr_segs; i++) {
8473 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8482 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8484 struct file *file = iocb->ki_filp;
8485 struct inode *inode = file->f_mapping->host;
8486 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8487 struct btrfs_dio_data dio_data = { 0 };
8488 struct extent_changeset *data_reserved = NULL;
8489 loff_t offset = iocb->ki_pos;
8493 bool relock = false;
8496 if (check_direct_IO(fs_info, iter, offset))
8499 inode_dio_begin(inode);
8502 * The generic stuff only does filemap_write_and_wait_range, which
8503 * isn't enough if we've written compressed pages to this area, so
8504 * we need to flush the dirty pages again to make absolutely sure
8505 * that any outstanding dirty pages are on disk.
8507 count = iov_iter_count(iter);
8508 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8509 &BTRFS_I(inode)->runtime_flags))
8510 filemap_fdatawrite_range(inode->i_mapping, offset,
8511 offset + count - 1);
8513 if (iov_iter_rw(iter) == WRITE) {
8515 * If the write DIO is beyond the EOF, we need update
8516 * the isize, but it is protected by i_mutex. So we can
8517 * not unlock the i_mutex at this case.
8519 if (offset + count <= inode->i_size) {
8520 dio_data.overwrite = 1;
8521 inode_unlock(inode);
8523 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8527 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8533 * We need to know how many extents we reserved so that we can
8534 * do the accounting properly if we go over the number we
8535 * originally calculated. Abuse current->journal_info for this.
8537 dio_data.reserve = round_up(count,
8538 fs_info->sectorsize);
8539 dio_data.unsubmitted_oe_range_start = (u64)offset;
8540 dio_data.unsubmitted_oe_range_end = (u64)offset;
8541 current->journal_info = &dio_data;
8542 down_read(&BTRFS_I(inode)->dio_sem);
8543 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8544 &BTRFS_I(inode)->runtime_flags)) {
8545 inode_dio_end(inode);
8546 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8550 ret = __blockdev_direct_IO(iocb, inode,
8551 fs_info->fs_devices->latest_bdev,
8552 iter, btrfs_get_blocks_direct, NULL,
8553 btrfs_submit_direct, flags);
8554 if (iov_iter_rw(iter) == WRITE) {
8555 up_read(&BTRFS_I(inode)->dio_sem);
8556 current->journal_info = NULL;
8557 if (ret < 0 && ret != -EIOCBQUEUED) {
8558 if (dio_data.reserve)
8559 btrfs_delalloc_release_space(inode, data_reserved,
8560 offset, dio_data.reserve, true);
8562 * On error we might have left some ordered extents
8563 * without submitting corresponding bios for them, so
8564 * cleanup them up to avoid other tasks getting them
8565 * and waiting for them to complete forever.
8567 if (dio_data.unsubmitted_oe_range_start <
8568 dio_data.unsubmitted_oe_range_end)
8569 __endio_write_update_ordered(inode,
8570 dio_data.unsubmitted_oe_range_start,
8571 dio_data.unsubmitted_oe_range_end -
8572 dio_data.unsubmitted_oe_range_start,
8574 } else if (ret >= 0 && (size_t)ret < count)
8575 btrfs_delalloc_release_space(inode, data_reserved,
8576 offset, count - (size_t)ret, true);
8577 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8581 inode_dio_end(inode);
8585 extent_changeset_free(data_reserved);
8589 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8591 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8592 __u64 start, __u64 len)
8596 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8600 return extent_fiemap(inode, fieinfo, start, len);
8603 int btrfs_readpage(struct file *file, struct page *page)
8605 struct extent_io_tree *tree;
8606 tree = &BTRFS_I(page->mapping->host)->io_tree;
8607 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8610 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8612 struct inode *inode = page->mapping->host;
8615 if (current->flags & PF_MEMALLOC) {
8616 redirty_page_for_writepage(wbc, page);
8622 * If we are under memory pressure we will call this directly from the
8623 * VM, we need to make sure we have the inode referenced for the ordered
8624 * extent. If not just return like we didn't do anything.
8626 if (!igrab(inode)) {
8627 redirty_page_for_writepage(wbc, page);
8628 return AOP_WRITEPAGE_ACTIVATE;
8630 ret = extent_write_full_page(page, wbc);
8631 btrfs_add_delayed_iput(inode);
8635 static int btrfs_writepages(struct address_space *mapping,
8636 struct writeback_control *wbc)
8638 return extent_writepages(mapping, wbc);
8642 btrfs_readpages(struct file *file, struct address_space *mapping,
8643 struct list_head *pages, unsigned nr_pages)
8645 return extent_readpages(mapping, pages, nr_pages);
8648 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8650 int ret = try_release_extent_mapping(page, gfp_flags);
8652 ClearPagePrivate(page);
8653 set_page_private(page, 0);
8659 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8661 if (PageWriteback(page) || PageDirty(page))
8663 return __btrfs_releasepage(page, gfp_flags);
8666 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8667 unsigned int length)
8669 struct inode *inode = page->mapping->host;
8670 struct extent_io_tree *tree;
8671 struct btrfs_ordered_extent *ordered;
8672 struct extent_state *cached_state = NULL;
8673 u64 page_start = page_offset(page);
8674 u64 page_end = page_start + PAGE_SIZE - 1;
8677 int inode_evicting = inode->i_state & I_FREEING;
8680 * we have the page locked, so new writeback can't start,
8681 * and the dirty bit won't be cleared while we are here.
8683 * Wait for IO on this page so that we can safely clear
8684 * the PagePrivate2 bit and do ordered accounting
8686 wait_on_page_writeback(page);
8688 tree = &BTRFS_I(inode)->io_tree;
8690 btrfs_releasepage(page, GFP_NOFS);
8694 if (!inode_evicting)
8695 lock_extent_bits(tree, page_start, page_end, &cached_state);
8698 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8699 page_end - start + 1);
8701 end = min(page_end, ordered->file_offset + ordered->len - 1);
8703 * IO on this page will never be started, so we need
8704 * to account for any ordered extents now
8706 if (!inode_evicting)
8707 clear_extent_bit(tree, start, end,
8708 EXTENT_DIRTY | EXTENT_DELALLOC |
8709 EXTENT_DELALLOC_NEW |
8710 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8711 EXTENT_DEFRAG, 1, 0, &cached_state);
8713 * whoever cleared the private bit is responsible
8714 * for the finish_ordered_io
8716 if (TestClearPagePrivate2(page)) {
8717 struct btrfs_ordered_inode_tree *tree;
8720 tree = &BTRFS_I(inode)->ordered_tree;
8722 spin_lock_irq(&tree->lock);
8723 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8724 new_len = start - ordered->file_offset;
8725 if (new_len < ordered->truncated_len)
8726 ordered->truncated_len = new_len;
8727 spin_unlock_irq(&tree->lock);
8729 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8731 end - start + 1, 1))
8732 btrfs_finish_ordered_io(ordered);
8734 btrfs_put_ordered_extent(ordered);
8735 if (!inode_evicting) {
8736 cached_state = NULL;
8737 lock_extent_bits(tree, start, end,
8742 if (start < page_end)
8747 * Qgroup reserved space handler
8748 * Page here will be either
8749 * 1) Already written to disk
8750 * In this case, its reserved space is released from data rsv map
8751 * and will be freed by delayed_ref handler finally.
8752 * So even we call qgroup_free_data(), it won't decrease reserved
8754 * 2) Not written to disk
8755 * This means the reserved space should be freed here. However,
8756 * if a truncate invalidates the page (by clearing PageDirty)
8757 * and the page is accounted for while allocating extent
8758 * in btrfs_check_data_free_space() we let delayed_ref to
8759 * free the entire extent.
8761 if (PageDirty(page))
8762 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8763 if (!inode_evicting) {
8764 clear_extent_bit(tree, page_start, page_end,
8765 EXTENT_LOCKED | EXTENT_DIRTY |
8766 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8767 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8770 __btrfs_releasepage(page, GFP_NOFS);
8773 ClearPageChecked(page);
8774 if (PagePrivate(page)) {
8775 ClearPagePrivate(page);
8776 set_page_private(page, 0);
8782 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8783 * called from a page fault handler when a page is first dirtied. Hence we must
8784 * be careful to check for EOF conditions here. We set the page up correctly
8785 * for a written page which means we get ENOSPC checking when writing into
8786 * holes and correct delalloc and unwritten extent mapping on filesystems that
8787 * support these features.
8789 * We are not allowed to take the i_mutex here so we have to play games to
8790 * protect against truncate races as the page could now be beyond EOF. Because
8791 * truncate_setsize() writes the inode size before removing pages, once we have
8792 * the page lock we can determine safely if the page is beyond EOF. If it is not
8793 * beyond EOF, then the page is guaranteed safe against truncation until we
8796 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8798 struct page *page = vmf->page;
8799 struct inode *inode = file_inode(vmf->vma->vm_file);
8800 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8801 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8802 struct btrfs_ordered_extent *ordered;
8803 struct extent_state *cached_state = NULL;
8804 struct extent_changeset *data_reserved = NULL;
8806 unsigned long zero_start;
8816 reserved_space = PAGE_SIZE;
8818 sb_start_pagefault(inode->i_sb);
8819 page_start = page_offset(page);
8820 page_end = page_start + PAGE_SIZE - 1;
8824 * Reserving delalloc space after obtaining the page lock can lead to
8825 * deadlock. For example, if a dirty page is locked by this function
8826 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8827 * dirty page write out, then the btrfs_writepage() function could
8828 * end up waiting indefinitely to get a lock on the page currently
8829 * being processed by btrfs_page_mkwrite() function.
8831 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8834 ret2 = file_update_time(vmf->vma->vm_file);
8838 ret = vmf_error(ret2);
8844 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8847 size = i_size_read(inode);
8849 if ((page->mapping != inode->i_mapping) ||
8850 (page_start >= size)) {
8851 /* page got truncated out from underneath us */
8854 wait_on_page_writeback(page);
8856 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8857 set_page_extent_mapped(page);
8860 * we can't set the delalloc bits if there are pending ordered
8861 * extents. Drop our locks and wait for them to finish
8863 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8866 unlock_extent_cached(io_tree, page_start, page_end,
8869 btrfs_start_ordered_extent(inode, ordered, 1);
8870 btrfs_put_ordered_extent(ordered);
8874 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8875 reserved_space = round_up(size - page_start,
8876 fs_info->sectorsize);
8877 if (reserved_space < PAGE_SIZE) {
8878 end = page_start + reserved_space - 1;
8879 btrfs_delalloc_release_space(inode, data_reserved,
8880 page_start, PAGE_SIZE - reserved_space,
8886 * page_mkwrite gets called when the page is firstly dirtied after it's
8887 * faulted in, but write(2) could also dirty a page and set delalloc
8888 * bits, thus in this case for space account reason, we still need to
8889 * clear any delalloc bits within this page range since we have to
8890 * reserve data&meta space before lock_page() (see above comments).
8892 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8893 EXTENT_DIRTY | EXTENT_DELALLOC |
8894 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8895 0, 0, &cached_state);
8897 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8900 unlock_extent_cached(io_tree, page_start, page_end,
8902 ret = VM_FAULT_SIGBUS;
8907 /* page is wholly or partially inside EOF */
8908 if (page_start + PAGE_SIZE > size)
8909 zero_start = size & ~PAGE_MASK;
8911 zero_start = PAGE_SIZE;
8913 if (zero_start != PAGE_SIZE) {
8915 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8916 flush_dcache_page(page);
8919 ClearPageChecked(page);
8920 set_page_dirty(page);
8921 SetPageUptodate(page);
8923 BTRFS_I(inode)->last_trans = fs_info->generation;
8924 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8925 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8927 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8930 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8931 sb_end_pagefault(inode->i_sb);
8932 extent_changeset_free(data_reserved);
8933 return VM_FAULT_LOCKED;
8939 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8940 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8941 reserved_space, (ret != 0));
8943 sb_end_pagefault(inode->i_sb);
8944 extent_changeset_free(data_reserved);
8948 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8950 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8951 struct btrfs_root *root = BTRFS_I(inode)->root;
8952 struct btrfs_block_rsv *rsv;
8954 struct btrfs_trans_handle *trans;
8955 u64 mask = fs_info->sectorsize - 1;
8956 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
8958 if (!skip_writeback) {
8959 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8966 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8967 * things going on here:
8969 * 1) We need to reserve space to update our inode.
8971 * 2) We need to have something to cache all the space that is going to
8972 * be free'd up by the truncate operation, but also have some slack
8973 * space reserved in case it uses space during the truncate (thank you
8974 * very much snapshotting).
8976 * And we need these to be separate. The fact is we can use a lot of
8977 * space doing the truncate, and we have no earthly idea how much space
8978 * we will use, so we need the truncate reservation to be separate so it
8979 * doesn't end up using space reserved for updating the inode. We also
8980 * need to be able to stop the transaction and start a new one, which
8981 * means we need to be able to update the inode several times, and we
8982 * have no idea of knowing how many times that will be, so we can't just
8983 * reserve 1 item for the entirety of the operation, so that has to be
8984 * done separately as well.
8986 * So that leaves us with
8988 * 1) rsv - for the truncate reservation, which we will steal from the
8989 * transaction reservation.
8990 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8991 * updating the inode.
8993 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8996 rsv->size = min_size;
9000 * 1 for the truncate slack space
9001 * 1 for updating the inode.
9003 trans = btrfs_start_transaction(root, 2);
9004 if (IS_ERR(trans)) {
9005 ret = PTR_ERR(trans);
9009 /* Migrate the slack space for the truncate to our reserve */
9010 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9015 * So if we truncate and then write and fsync we normally would just
9016 * write the extents that changed, which is a problem if we need to
9017 * first truncate that entire inode. So set this flag so we write out
9018 * all of the extents in the inode to the sync log so we're completely
9021 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9022 trans->block_rsv = rsv;
9025 ret = btrfs_truncate_inode_items(trans, root, inode,
9027 BTRFS_EXTENT_DATA_KEY);
9028 trans->block_rsv = &fs_info->trans_block_rsv;
9029 if (ret != -ENOSPC && ret != -EAGAIN)
9032 ret = btrfs_update_inode(trans, root, inode);
9036 btrfs_end_transaction(trans);
9037 btrfs_btree_balance_dirty(fs_info);
9039 trans = btrfs_start_transaction(root, 2);
9040 if (IS_ERR(trans)) {
9041 ret = PTR_ERR(trans);
9046 btrfs_block_rsv_release(fs_info, rsv, -1);
9047 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9048 rsv, min_size, false);
9049 BUG_ON(ret); /* shouldn't happen */
9050 trans->block_rsv = rsv;
9054 * We can't call btrfs_truncate_block inside a trans handle as we could
9055 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9056 * we've truncated everything except the last little bit, and can do
9057 * btrfs_truncate_block and then update the disk_i_size.
9059 if (ret == NEED_TRUNCATE_BLOCK) {
9060 btrfs_end_transaction(trans);
9061 btrfs_btree_balance_dirty(fs_info);
9063 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9066 trans = btrfs_start_transaction(root, 1);
9067 if (IS_ERR(trans)) {
9068 ret = PTR_ERR(trans);
9071 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9077 trans->block_rsv = &fs_info->trans_block_rsv;
9078 ret2 = btrfs_update_inode(trans, root, inode);
9082 ret2 = btrfs_end_transaction(trans);
9085 btrfs_btree_balance_dirty(fs_info);
9088 btrfs_free_block_rsv(fs_info, rsv);
9094 * create a new subvolume directory/inode (helper for the ioctl).
9096 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9097 struct btrfs_root *new_root,
9098 struct btrfs_root *parent_root,
9101 struct inode *inode;
9105 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9106 new_dirid, new_dirid,
9107 S_IFDIR | (~current_umask() & S_IRWXUGO),
9110 return PTR_ERR(inode);
9111 inode->i_op = &btrfs_dir_inode_operations;
9112 inode->i_fop = &btrfs_dir_file_operations;
9114 set_nlink(inode, 1);
9115 btrfs_i_size_write(BTRFS_I(inode), 0);
9116 unlock_new_inode(inode);
9118 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9120 btrfs_err(new_root->fs_info,
9121 "error inheriting subvolume %llu properties: %d",
9122 new_root->root_key.objectid, err);
9124 err = btrfs_update_inode(trans, new_root, inode);
9130 struct inode *btrfs_alloc_inode(struct super_block *sb)
9132 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9133 struct btrfs_inode *ei;
9134 struct inode *inode;
9136 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9143 ei->last_sub_trans = 0;
9144 ei->logged_trans = 0;
9145 ei->delalloc_bytes = 0;
9146 ei->new_delalloc_bytes = 0;
9147 ei->defrag_bytes = 0;
9148 ei->disk_i_size = 0;
9151 ei->index_cnt = (u64)-1;
9153 ei->last_unlink_trans = 0;
9154 ei->last_link_trans = 0;
9155 ei->last_log_commit = 0;
9157 spin_lock_init(&ei->lock);
9158 ei->outstanding_extents = 0;
9159 if (sb->s_magic != BTRFS_TEST_MAGIC)
9160 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9161 BTRFS_BLOCK_RSV_DELALLOC);
9162 ei->runtime_flags = 0;
9163 ei->prop_compress = BTRFS_COMPRESS_NONE;
9164 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9166 ei->delayed_node = NULL;
9168 ei->i_otime.tv_sec = 0;
9169 ei->i_otime.tv_nsec = 0;
9171 inode = &ei->vfs_inode;
9172 extent_map_tree_init(&ei->extent_tree);
9173 extent_io_tree_init(&ei->io_tree, inode);
9174 extent_io_tree_init(&ei->io_failure_tree, inode);
9175 ei->io_tree.track_uptodate = 1;
9176 ei->io_failure_tree.track_uptodate = 1;
9177 atomic_set(&ei->sync_writers, 0);
9178 mutex_init(&ei->log_mutex);
9179 mutex_init(&ei->delalloc_mutex);
9180 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9181 INIT_LIST_HEAD(&ei->delalloc_inodes);
9182 INIT_LIST_HEAD(&ei->delayed_iput);
9183 RB_CLEAR_NODE(&ei->rb_node);
9184 init_rwsem(&ei->dio_sem);
9189 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9190 void btrfs_test_destroy_inode(struct inode *inode)
9192 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9193 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9197 static void btrfs_i_callback(struct rcu_head *head)
9199 struct inode *inode = container_of(head, struct inode, i_rcu);
9200 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9203 void btrfs_destroy_inode(struct inode *inode)
9205 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9206 struct btrfs_ordered_extent *ordered;
9207 struct btrfs_root *root = BTRFS_I(inode)->root;
9209 WARN_ON(!hlist_empty(&inode->i_dentry));
9210 WARN_ON(inode->i_data.nrpages);
9211 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9212 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9213 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9214 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9215 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9216 WARN_ON(BTRFS_I(inode)->csum_bytes);
9217 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9220 * This can happen where we create an inode, but somebody else also
9221 * created the same inode and we need to destroy the one we already
9228 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9233 "found ordered extent %llu %llu on inode cleanup",
9234 ordered->file_offset, ordered->len);
9235 btrfs_remove_ordered_extent(inode, ordered);
9236 btrfs_put_ordered_extent(ordered);
9237 btrfs_put_ordered_extent(ordered);
9240 btrfs_qgroup_check_reserved_leak(inode);
9241 inode_tree_del(inode);
9242 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9244 call_rcu(&inode->i_rcu, btrfs_i_callback);
9247 int btrfs_drop_inode(struct inode *inode)
9249 struct btrfs_root *root = BTRFS_I(inode)->root;
9254 /* the snap/subvol tree is on deleting */
9255 if (btrfs_root_refs(&root->root_item) == 0)
9258 return generic_drop_inode(inode);
9261 static void init_once(void *foo)
9263 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9265 inode_init_once(&ei->vfs_inode);
9268 void __cold btrfs_destroy_cachep(void)
9271 * Make sure all delayed rcu free inodes are flushed before we
9275 kmem_cache_destroy(btrfs_inode_cachep);
9276 kmem_cache_destroy(btrfs_trans_handle_cachep);
9277 kmem_cache_destroy(btrfs_path_cachep);
9278 kmem_cache_destroy(btrfs_free_space_cachep);
9281 int __init btrfs_init_cachep(void)
9283 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9284 sizeof(struct btrfs_inode), 0,
9285 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9287 if (!btrfs_inode_cachep)
9290 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9291 sizeof(struct btrfs_trans_handle), 0,
9292 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9293 if (!btrfs_trans_handle_cachep)
9296 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9297 sizeof(struct btrfs_path), 0,
9298 SLAB_MEM_SPREAD, NULL);
9299 if (!btrfs_path_cachep)
9302 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9303 sizeof(struct btrfs_free_space), 0,
9304 SLAB_MEM_SPREAD, NULL);
9305 if (!btrfs_free_space_cachep)
9310 btrfs_destroy_cachep();
9314 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9315 u32 request_mask, unsigned int flags)
9318 struct inode *inode = d_inode(path->dentry);
9319 u32 blocksize = inode->i_sb->s_blocksize;
9320 u32 bi_flags = BTRFS_I(inode)->flags;
9322 stat->result_mask |= STATX_BTIME;
9323 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9324 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9325 if (bi_flags & BTRFS_INODE_APPEND)
9326 stat->attributes |= STATX_ATTR_APPEND;
9327 if (bi_flags & BTRFS_INODE_COMPRESS)
9328 stat->attributes |= STATX_ATTR_COMPRESSED;
9329 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9330 stat->attributes |= STATX_ATTR_IMMUTABLE;
9331 if (bi_flags & BTRFS_INODE_NODUMP)
9332 stat->attributes |= STATX_ATTR_NODUMP;
9334 stat->attributes_mask |= (STATX_ATTR_APPEND |
9335 STATX_ATTR_COMPRESSED |
9336 STATX_ATTR_IMMUTABLE |
9339 generic_fillattr(inode, stat);
9340 stat->dev = BTRFS_I(inode)->root->anon_dev;
9342 spin_lock(&BTRFS_I(inode)->lock);
9343 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9344 spin_unlock(&BTRFS_I(inode)->lock);
9345 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9346 ALIGN(delalloc_bytes, blocksize)) >> 9;
9350 static int btrfs_rename_exchange(struct inode *old_dir,
9351 struct dentry *old_dentry,
9352 struct inode *new_dir,
9353 struct dentry *new_dentry)
9355 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9356 struct btrfs_trans_handle *trans;
9357 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9358 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9359 struct inode *new_inode = new_dentry->d_inode;
9360 struct inode *old_inode = old_dentry->d_inode;
9361 struct timespec64 ctime = current_time(old_inode);
9362 struct dentry *parent;
9363 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9364 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9369 bool root_log_pinned = false;
9370 bool dest_log_pinned = false;
9371 struct btrfs_log_ctx ctx_root;
9372 struct btrfs_log_ctx ctx_dest;
9373 bool sync_log_root = false;
9374 bool sync_log_dest = false;
9375 bool commit_transaction = false;
9377 /* we only allow rename subvolume link between subvolumes */
9378 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9381 btrfs_init_log_ctx(&ctx_root, old_inode);
9382 btrfs_init_log_ctx(&ctx_dest, new_inode);
9384 /* close the race window with snapshot create/destroy ioctl */
9385 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9386 down_read(&fs_info->subvol_sem);
9387 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9388 down_read(&fs_info->subvol_sem);
9391 * We want to reserve the absolute worst case amount of items. So if
9392 * both inodes are subvols and we need to unlink them then that would
9393 * require 4 item modifications, but if they are both normal inodes it
9394 * would require 5 item modifications, so we'll assume their normal
9395 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9396 * should cover the worst case number of items we'll modify.
9398 trans = btrfs_start_transaction(root, 12);
9399 if (IS_ERR(trans)) {
9400 ret = PTR_ERR(trans);
9405 * We need to find a free sequence number both in the source and
9406 * in the destination directory for the exchange.
9408 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9411 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9415 BTRFS_I(old_inode)->dir_index = 0ULL;
9416 BTRFS_I(new_inode)->dir_index = 0ULL;
9418 /* Reference for the source. */
9419 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9420 /* force full log commit if subvolume involved. */
9421 btrfs_set_log_full_commit(fs_info, trans);
9423 btrfs_pin_log_trans(root);
9424 root_log_pinned = true;
9425 ret = btrfs_insert_inode_ref(trans, dest,
9426 new_dentry->d_name.name,
9427 new_dentry->d_name.len,
9429 btrfs_ino(BTRFS_I(new_dir)),
9435 /* And now for the dest. */
9436 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9437 /* force full log commit if subvolume involved. */
9438 btrfs_set_log_full_commit(fs_info, trans);
9440 btrfs_pin_log_trans(dest);
9441 dest_log_pinned = true;
9442 ret = btrfs_insert_inode_ref(trans, root,
9443 old_dentry->d_name.name,
9444 old_dentry->d_name.len,
9446 btrfs_ino(BTRFS_I(old_dir)),
9452 /* Update inode version and ctime/mtime. */
9453 inode_inc_iversion(old_dir);
9454 inode_inc_iversion(new_dir);
9455 inode_inc_iversion(old_inode);
9456 inode_inc_iversion(new_inode);
9457 old_dir->i_ctime = old_dir->i_mtime = ctime;
9458 new_dir->i_ctime = new_dir->i_mtime = ctime;
9459 old_inode->i_ctime = ctime;
9460 new_inode->i_ctime = ctime;
9462 if (old_dentry->d_parent != new_dentry->d_parent) {
9463 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9464 BTRFS_I(old_inode), 1);
9465 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9466 BTRFS_I(new_inode), 1);
9469 /* src is a subvolume */
9470 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9471 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9472 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9473 old_dentry->d_name.name,
9474 old_dentry->d_name.len);
9475 } else { /* src is an inode */
9476 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9477 BTRFS_I(old_dentry->d_inode),
9478 old_dentry->d_name.name,
9479 old_dentry->d_name.len);
9481 ret = btrfs_update_inode(trans, root, old_inode);
9484 btrfs_abort_transaction(trans, ret);
9488 /* dest is a subvolume */
9489 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9490 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9491 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9492 new_dentry->d_name.name,
9493 new_dentry->d_name.len);
9494 } else { /* dest is an inode */
9495 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9496 BTRFS_I(new_dentry->d_inode),
9497 new_dentry->d_name.name,
9498 new_dentry->d_name.len);
9500 ret = btrfs_update_inode(trans, dest, new_inode);
9503 btrfs_abort_transaction(trans, ret);
9507 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9508 new_dentry->d_name.name,
9509 new_dentry->d_name.len, 0, old_idx);
9511 btrfs_abort_transaction(trans, ret);
9515 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9516 old_dentry->d_name.name,
9517 old_dentry->d_name.len, 0, new_idx);
9519 btrfs_abort_transaction(trans, ret);
9523 if (old_inode->i_nlink == 1)
9524 BTRFS_I(old_inode)->dir_index = old_idx;
9525 if (new_inode->i_nlink == 1)
9526 BTRFS_I(new_inode)->dir_index = new_idx;
9528 if (root_log_pinned) {
9529 parent = new_dentry->d_parent;
9530 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9531 BTRFS_I(old_dir), parent,
9533 if (ret == BTRFS_NEED_LOG_SYNC)
9534 sync_log_root = true;
9535 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9536 commit_transaction = true;
9538 btrfs_end_log_trans(root);
9539 root_log_pinned = false;
9541 if (dest_log_pinned) {
9542 if (!commit_transaction) {
9543 parent = old_dentry->d_parent;
9544 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9545 BTRFS_I(new_dir), parent,
9547 if (ret == BTRFS_NEED_LOG_SYNC)
9548 sync_log_dest = true;
9549 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9550 commit_transaction = true;
9553 btrfs_end_log_trans(dest);
9554 dest_log_pinned = false;
9558 * If we have pinned a log and an error happened, we unpin tasks
9559 * trying to sync the log and force them to fallback to a transaction
9560 * commit if the log currently contains any of the inodes involved in
9561 * this rename operation (to ensure we do not persist a log with an
9562 * inconsistent state for any of these inodes or leading to any
9563 * inconsistencies when replayed). If the transaction was aborted, the
9564 * abortion reason is propagated to userspace when attempting to commit
9565 * the transaction. If the log does not contain any of these inodes, we
9566 * allow the tasks to sync it.
9568 if (ret && (root_log_pinned || dest_log_pinned)) {
9569 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9570 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9571 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9573 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9574 btrfs_set_log_full_commit(fs_info, trans);
9576 if (root_log_pinned) {
9577 btrfs_end_log_trans(root);
9578 root_log_pinned = false;
9580 if (dest_log_pinned) {
9581 btrfs_end_log_trans(dest);
9582 dest_log_pinned = false;
9585 if (!ret && sync_log_root && !commit_transaction) {
9586 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9589 commit_transaction = true;
9591 if (!ret && sync_log_dest && !commit_transaction) {
9592 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9595 commit_transaction = true;
9597 if (commit_transaction) {
9598 ret = btrfs_commit_transaction(trans);
9602 ret2 = btrfs_end_transaction(trans);
9603 ret = ret ? ret : ret2;
9606 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9607 up_read(&fs_info->subvol_sem);
9608 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9609 up_read(&fs_info->subvol_sem);
9614 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9615 struct btrfs_root *root,
9617 struct dentry *dentry)
9620 struct inode *inode;
9624 ret = btrfs_find_free_ino(root, &objectid);
9628 inode = btrfs_new_inode(trans, root, dir,
9629 dentry->d_name.name,
9631 btrfs_ino(BTRFS_I(dir)),
9633 S_IFCHR | WHITEOUT_MODE,
9636 if (IS_ERR(inode)) {
9637 ret = PTR_ERR(inode);
9641 inode->i_op = &btrfs_special_inode_operations;
9642 init_special_inode(inode, inode->i_mode,
9645 ret = btrfs_init_inode_security(trans, inode, dir,
9650 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9651 BTRFS_I(inode), 0, index);
9655 ret = btrfs_update_inode(trans, root, inode);
9657 unlock_new_inode(inode);
9659 inode_dec_link_count(inode);
9665 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9666 struct inode *new_dir, struct dentry *new_dentry,
9669 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9670 struct btrfs_trans_handle *trans;
9671 unsigned int trans_num_items;
9672 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9673 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9674 struct inode *new_inode = d_inode(new_dentry);
9675 struct inode *old_inode = d_inode(old_dentry);
9679 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9680 bool log_pinned = false;
9681 struct btrfs_log_ctx ctx;
9682 bool sync_log = false;
9683 bool commit_transaction = false;
9685 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9688 /* we only allow rename subvolume link between subvolumes */
9689 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9692 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9693 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9696 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9697 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9701 /* check for collisions, even if the name isn't there */
9702 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9703 new_dentry->d_name.name,
9704 new_dentry->d_name.len);
9707 if (ret == -EEXIST) {
9709 * eexist without a new_inode */
9710 if (WARN_ON(!new_inode)) {
9714 /* maybe -EOVERFLOW */
9721 * we're using rename to replace one file with another. Start IO on it
9722 * now so we don't add too much work to the end of the transaction
9724 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9725 filemap_flush(old_inode->i_mapping);
9727 /* close the racy window with snapshot create/destroy ioctl */
9728 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9729 down_read(&fs_info->subvol_sem);
9731 * We want to reserve the absolute worst case amount of items. So if
9732 * both inodes are subvols and we need to unlink them then that would
9733 * require 4 item modifications, but if they are both normal inodes it
9734 * would require 5 item modifications, so we'll assume they are normal
9735 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9736 * should cover the worst case number of items we'll modify.
9737 * If our rename has the whiteout flag, we need more 5 units for the
9738 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9739 * when selinux is enabled).
9741 trans_num_items = 11;
9742 if (flags & RENAME_WHITEOUT)
9743 trans_num_items += 5;
9744 trans = btrfs_start_transaction(root, trans_num_items);
9745 if (IS_ERR(trans)) {
9746 ret = PTR_ERR(trans);
9751 btrfs_record_root_in_trans(trans, dest);
9753 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9757 BTRFS_I(old_inode)->dir_index = 0ULL;
9758 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9759 /* force full log commit if subvolume involved. */
9760 btrfs_set_log_full_commit(fs_info, trans);
9762 btrfs_pin_log_trans(root);
9764 ret = btrfs_insert_inode_ref(trans, dest,
9765 new_dentry->d_name.name,
9766 new_dentry->d_name.len,
9768 btrfs_ino(BTRFS_I(new_dir)), index);
9773 inode_inc_iversion(old_dir);
9774 inode_inc_iversion(new_dir);
9775 inode_inc_iversion(old_inode);
9776 old_dir->i_ctime = old_dir->i_mtime =
9777 new_dir->i_ctime = new_dir->i_mtime =
9778 old_inode->i_ctime = current_time(old_dir);
9780 if (old_dentry->d_parent != new_dentry->d_parent)
9781 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9782 BTRFS_I(old_inode), 1);
9784 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9785 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9786 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9787 old_dentry->d_name.name,
9788 old_dentry->d_name.len);
9790 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9791 BTRFS_I(d_inode(old_dentry)),
9792 old_dentry->d_name.name,
9793 old_dentry->d_name.len);
9795 ret = btrfs_update_inode(trans, root, old_inode);
9798 btrfs_abort_transaction(trans, ret);
9803 inode_inc_iversion(new_inode);
9804 new_inode->i_ctime = current_time(new_inode);
9805 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9806 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9807 root_objectid = BTRFS_I(new_inode)->location.objectid;
9808 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9809 new_dentry->d_name.name,
9810 new_dentry->d_name.len);
9811 BUG_ON(new_inode->i_nlink == 0);
9813 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9814 BTRFS_I(d_inode(new_dentry)),
9815 new_dentry->d_name.name,
9816 new_dentry->d_name.len);
9818 if (!ret && new_inode->i_nlink == 0)
9819 ret = btrfs_orphan_add(trans,
9820 BTRFS_I(d_inode(new_dentry)));
9822 btrfs_abort_transaction(trans, ret);
9827 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9828 new_dentry->d_name.name,
9829 new_dentry->d_name.len, 0, index);
9831 btrfs_abort_transaction(trans, ret);
9835 if (old_inode->i_nlink == 1)
9836 BTRFS_I(old_inode)->dir_index = index;
9839 struct dentry *parent = new_dentry->d_parent;
9841 btrfs_init_log_ctx(&ctx, old_inode);
9842 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9843 BTRFS_I(old_dir), parent,
9845 if (ret == BTRFS_NEED_LOG_SYNC)
9847 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9848 commit_transaction = true;
9850 btrfs_end_log_trans(root);
9854 if (flags & RENAME_WHITEOUT) {
9855 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9859 btrfs_abort_transaction(trans, ret);
9865 * If we have pinned the log and an error happened, we unpin tasks
9866 * trying to sync the log and force them to fallback to a transaction
9867 * commit if the log currently contains any of the inodes involved in
9868 * this rename operation (to ensure we do not persist a log with an
9869 * inconsistent state for any of these inodes or leading to any
9870 * inconsistencies when replayed). If the transaction was aborted, the
9871 * abortion reason is propagated to userspace when attempting to commit
9872 * the transaction. If the log does not contain any of these inodes, we
9873 * allow the tasks to sync it.
9875 if (ret && log_pinned) {
9876 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9877 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9878 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9880 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9881 btrfs_set_log_full_commit(fs_info, trans);
9883 btrfs_end_log_trans(root);
9886 if (!ret && sync_log) {
9887 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9889 commit_transaction = true;
9891 if (commit_transaction) {
9892 ret = btrfs_commit_transaction(trans);
9896 ret2 = btrfs_end_transaction(trans);
9897 ret = ret ? ret : ret2;
9900 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9901 up_read(&fs_info->subvol_sem);
9906 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9907 struct inode *new_dir, struct dentry *new_dentry,
9910 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9913 if (flags & RENAME_EXCHANGE)
9914 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9917 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9920 struct btrfs_delalloc_work {
9921 struct inode *inode;
9922 struct completion completion;
9923 struct list_head list;
9924 struct btrfs_work work;
9927 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9929 struct btrfs_delalloc_work *delalloc_work;
9930 struct inode *inode;
9932 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9934 inode = delalloc_work->inode;
9935 filemap_flush(inode->i_mapping);
9936 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9937 &BTRFS_I(inode)->runtime_flags))
9938 filemap_flush(inode->i_mapping);
9941 complete(&delalloc_work->completion);
9944 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9946 struct btrfs_delalloc_work *work;
9948 work = kmalloc(sizeof(*work), GFP_NOFS);
9952 init_completion(&work->completion);
9953 INIT_LIST_HEAD(&work->list);
9954 work->inode = inode;
9955 WARN_ON_ONCE(!inode);
9956 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9957 btrfs_run_delalloc_work, NULL, NULL);
9963 * some fairly slow code that needs optimization. This walks the list
9964 * of all the inodes with pending delalloc and forces them to disk.
9966 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9968 struct btrfs_inode *binode;
9969 struct inode *inode;
9970 struct btrfs_delalloc_work *work, *next;
9971 struct list_head works;
9972 struct list_head splice;
9975 INIT_LIST_HEAD(&works);
9976 INIT_LIST_HEAD(&splice);
9978 mutex_lock(&root->delalloc_mutex);
9979 spin_lock(&root->delalloc_lock);
9980 list_splice_init(&root->delalloc_inodes, &splice);
9981 while (!list_empty(&splice)) {
9982 binode = list_entry(splice.next, struct btrfs_inode,
9985 list_move_tail(&binode->delalloc_inodes,
9986 &root->delalloc_inodes);
9987 inode = igrab(&binode->vfs_inode);
9989 cond_resched_lock(&root->delalloc_lock);
9992 spin_unlock(&root->delalloc_lock);
9995 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9996 &binode->runtime_flags);
9997 work = btrfs_alloc_delalloc_work(inode);
10003 list_add_tail(&work->list, &works);
10004 btrfs_queue_work(root->fs_info->flush_workers,
10007 if (nr != -1 && ret >= nr)
10010 spin_lock(&root->delalloc_lock);
10012 spin_unlock(&root->delalloc_lock);
10015 list_for_each_entry_safe(work, next, &works, list) {
10016 list_del_init(&work->list);
10017 wait_for_completion(&work->completion);
10021 if (!list_empty(&splice)) {
10022 spin_lock(&root->delalloc_lock);
10023 list_splice_tail(&splice, &root->delalloc_inodes);
10024 spin_unlock(&root->delalloc_lock);
10026 mutex_unlock(&root->delalloc_mutex);
10030 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10032 struct btrfs_fs_info *fs_info = root->fs_info;
10035 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10038 ret = start_delalloc_inodes(root, -1, true);
10044 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10046 struct btrfs_root *root;
10047 struct list_head splice;
10050 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10053 INIT_LIST_HEAD(&splice);
10055 mutex_lock(&fs_info->delalloc_root_mutex);
10056 spin_lock(&fs_info->delalloc_root_lock);
10057 list_splice_init(&fs_info->delalloc_roots, &splice);
10058 while (!list_empty(&splice) && nr) {
10059 root = list_first_entry(&splice, struct btrfs_root,
10061 root = btrfs_grab_fs_root(root);
10063 list_move_tail(&root->delalloc_root,
10064 &fs_info->delalloc_roots);
10065 spin_unlock(&fs_info->delalloc_root_lock);
10067 ret = start_delalloc_inodes(root, nr, false);
10068 btrfs_put_fs_root(root);
10076 spin_lock(&fs_info->delalloc_root_lock);
10078 spin_unlock(&fs_info->delalloc_root_lock);
10082 if (!list_empty(&splice)) {
10083 spin_lock(&fs_info->delalloc_root_lock);
10084 list_splice_tail(&splice, &fs_info->delalloc_roots);
10085 spin_unlock(&fs_info->delalloc_root_lock);
10087 mutex_unlock(&fs_info->delalloc_root_mutex);
10091 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10092 const char *symname)
10094 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10095 struct btrfs_trans_handle *trans;
10096 struct btrfs_root *root = BTRFS_I(dir)->root;
10097 struct btrfs_path *path;
10098 struct btrfs_key key;
10099 struct inode *inode = NULL;
10106 struct btrfs_file_extent_item *ei;
10107 struct extent_buffer *leaf;
10109 name_len = strlen(symname);
10110 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10111 return -ENAMETOOLONG;
10114 * 2 items for inode item and ref
10115 * 2 items for dir items
10116 * 1 item for updating parent inode item
10117 * 1 item for the inline extent item
10118 * 1 item for xattr if selinux is on
10120 trans = btrfs_start_transaction(root, 7);
10122 return PTR_ERR(trans);
10124 err = btrfs_find_free_ino(root, &objectid);
10128 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10129 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10130 objectid, S_IFLNK|S_IRWXUGO, &index);
10131 if (IS_ERR(inode)) {
10132 err = PTR_ERR(inode);
10138 * If the active LSM wants to access the inode during
10139 * d_instantiate it needs these. Smack checks to see
10140 * if the filesystem supports xattrs by looking at the
10143 inode->i_fop = &btrfs_file_operations;
10144 inode->i_op = &btrfs_file_inode_operations;
10145 inode->i_mapping->a_ops = &btrfs_aops;
10146 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10148 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10152 path = btrfs_alloc_path();
10157 key.objectid = btrfs_ino(BTRFS_I(inode));
10159 key.type = BTRFS_EXTENT_DATA_KEY;
10160 datasize = btrfs_file_extent_calc_inline_size(name_len);
10161 err = btrfs_insert_empty_item(trans, root, path, &key,
10164 btrfs_free_path(path);
10167 leaf = path->nodes[0];
10168 ei = btrfs_item_ptr(leaf, path->slots[0],
10169 struct btrfs_file_extent_item);
10170 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10171 btrfs_set_file_extent_type(leaf, ei,
10172 BTRFS_FILE_EXTENT_INLINE);
10173 btrfs_set_file_extent_encryption(leaf, ei, 0);
10174 btrfs_set_file_extent_compression(leaf, ei, 0);
10175 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10176 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10178 ptr = btrfs_file_extent_inline_start(ei);
10179 write_extent_buffer(leaf, symname, ptr, name_len);
10180 btrfs_mark_buffer_dirty(leaf);
10181 btrfs_free_path(path);
10183 inode->i_op = &btrfs_symlink_inode_operations;
10184 inode_nohighmem(inode);
10185 inode->i_mapping->a_ops = &btrfs_aops;
10186 inode_set_bytes(inode, name_len);
10187 btrfs_i_size_write(BTRFS_I(inode), name_len);
10188 err = btrfs_update_inode(trans, root, inode);
10190 * Last step, add directory indexes for our symlink inode. This is the
10191 * last step to avoid extra cleanup of these indexes if an error happens
10195 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10196 BTRFS_I(inode), 0, index);
10200 d_instantiate_new(dentry, inode);
10203 btrfs_end_transaction(trans);
10204 if (err && inode) {
10205 inode_dec_link_count(inode);
10206 discard_new_inode(inode);
10208 btrfs_btree_balance_dirty(fs_info);
10212 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10213 u64 start, u64 num_bytes, u64 min_size,
10214 loff_t actual_len, u64 *alloc_hint,
10215 struct btrfs_trans_handle *trans)
10217 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10218 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10219 struct extent_map *em;
10220 struct btrfs_root *root = BTRFS_I(inode)->root;
10221 struct btrfs_key ins;
10222 u64 cur_offset = start;
10225 u64 last_alloc = (u64)-1;
10227 bool own_trans = true;
10228 u64 end = start + num_bytes - 1;
10232 while (num_bytes > 0) {
10234 trans = btrfs_start_transaction(root, 3);
10235 if (IS_ERR(trans)) {
10236 ret = PTR_ERR(trans);
10241 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10242 cur_bytes = max(cur_bytes, min_size);
10244 * If we are severely fragmented we could end up with really
10245 * small allocations, so if the allocator is returning small
10246 * chunks lets make its job easier by only searching for those
10249 cur_bytes = min(cur_bytes, last_alloc);
10250 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10251 min_size, 0, *alloc_hint, &ins, 1, 0);
10254 btrfs_end_transaction(trans);
10257 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10259 last_alloc = ins.offset;
10260 ret = insert_reserved_file_extent(trans, inode,
10261 cur_offset, ins.objectid,
10262 ins.offset, ins.offset,
10263 ins.offset, 0, 0, 0,
10264 BTRFS_FILE_EXTENT_PREALLOC);
10266 btrfs_free_reserved_extent(fs_info, ins.objectid,
10268 btrfs_abort_transaction(trans, ret);
10270 btrfs_end_transaction(trans);
10274 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10275 cur_offset + ins.offset -1, 0);
10277 em = alloc_extent_map();
10279 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10280 &BTRFS_I(inode)->runtime_flags);
10284 em->start = cur_offset;
10285 em->orig_start = cur_offset;
10286 em->len = ins.offset;
10287 em->block_start = ins.objectid;
10288 em->block_len = ins.offset;
10289 em->orig_block_len = ins.offset;
10290 em->ram_bytes = ins.offset;
10291 em->bdev = fs_info->fs_devices->latest_bdev;
10292 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10293 em->generation = trans->transid;
10296 write_lock(&em_tree->lock);
10297 ret = add_extent_mapping(em_tree, em, 1);
10298 write_unlock(&em_tree->lock);
10299 if (ret != -EEXIST)
10301 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10302 cur_offset + ins.offset - 1,
10305 free_extent_map(em);
10307 num_bytes -= ins.offset;
10308 cur_offset += ins.offset;
10309 *alloc_hint = ins.objectid + ins.offset;
10311 inode_inc_iversion(inode);
10312 inode->i_ctime = current_time(inode);
10313 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10314 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10315 (actual_len > inode->i_size) &&
10316 (cur_offset > inode->i_size)) {
10317 if (cur_offset > actual_len)
10318 i_size = actual_len;
10320 i_size = cur_offset;
10321 i_size_write(inode, i_size);
10322 btrfs_ordered_update_i_size(inode, i_size, NULL);
10325 ret = btrfs_update_inode(trans, root, inode);
10328 btrfs_abort_transaction(trans, ret);
10330 btrfs_end_transaction(trans);
10335 btrfs_end_transaction(trans);
10337 if (cur_offset < end)
10338 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10339 end - cur_offset + 1);
10343 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10344 u64 start, u64 num_bytes, u64 min_size,
10345 loff_t actual_len, u64 *alloc_hint)
10347 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10348 min_size, actual_len, alloc_hint,
10352 int btrfs_prealloc_file_range_trans(struct inode *inode,
10353 struct btrfs_trans_handle *trans, int mode,
10354 u64 start, u64 num_bytes, u64 min_size,
10355 loff_t actual_len, u64 *alloc_hint)
10357 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10358 min_size, actual_len, alloc_hint, trans);
10361 static int btrfs_set_page_dirty(struct page *page)
10363 return __set_page_dirty_nobuffers(page);
10366 static int btrfs_permission(struct inode *inode, int mask)
10368 struct btrfs_root *root = BTRFS_I(inode)->root;
10369 umode_t mode = inode->i_mode;
10371 if (mask & MAY_WRITE &&
10372 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10373 if (btrfs_root_readonly(root))
10375 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10378 return generic_permission(inode, mask);
10381 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10383 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10384 struct btrfs_trans_handle *trans;
10385 struct btrfs_root *root = BTRFS_I(dir)->root;
10386 struct inode *inode = NULL;
10392 * 5 units required for adding orphan entry
10394 trans = btrfs_start_transaction(root, 5);
10396 return PTR_ERR(trans);
10398 ret = btrfs_find_free_ino(root, &objectid);
10402 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10403 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10404 if (IS_ERR(inode)) {
10405 ret = PTR_ERR(inode);
10410 inode->i_fop = &btrfs_file_operations;
10411 inode->i_op = &btrfs_file_inode_operations;
10413 inode->i_mapping->a_ops = &btrfs_aops;
10414 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10416 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10420 ret = btrfs_update_inode(trans, root, inode);
10423 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10428 * We set number of links to 0 in btrfs_new_inode(), and here we set
10429 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10432 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10434 set_nlink(inode, 1);
10435 d_tmpfile(dentry, inode);
10436 unlock_new_inode(inode);
10437 mark_inode_dirty(inode);
10439 btrfs_end_transaction(trans);
10441 discard_new_inode(inode);
10442 btrfs_btree_balance_dirty(fs_info);
10446 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10448 struct inode *inode = tree->private_data;
10449 unsigned long index = start >> PAGE_SHIFT;
10450 unsigned long end_index = end >> PAGE_SHIFT;
10453 while (index <= end_index) {
10454 page = find_get_page(inode->i_mapping, index);
10455 ASSERT(page); /* Pages should be in the extent_io_tree */
10456 set_page_writeback(page);
10464 * Add an entry indicating a block group or device which is pinned by a
10465 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10466 * negative errno on failure.
10468 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10469 bool is_block_group)
10471 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10472 struct btrfs_swapfile_pin *sp, *entry;
10473 struct rb_node **p;
10474 struct rb_node *parent = NULL;
10476 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10481 sp->is_block_group = is_block_group;
10483 spin_lock(&fs_info->swapfile_pins_lock);
10484 p = &fs_info->swapfile_pins.rb_node;
10487 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10488 if (sp->ptr < entry->ptr ||
10489 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10490 p = &(*p)->rb_left;
10491 } else if (sp->ptr > entry->ptr ||
10492 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10493 p = &(*p)->rb_right;
10495 spin_unlock(&fs_info->swapfile_pins_lock);
10500 rb_link_node(&sp->node, parent, p);
10501 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10502 spin_unlock(&fs_info->swapfile_pins_lock);
10506 /* Free all of the entries pinned by this swapfile. */
10507 static void btrfs_free_swapfile_pins(struct inode *inode)
10509 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10510 struct btrfs_swapfile_pin *sp;
10511 struct rb_node *node, *next;
10513 spin_lock(&fs_info->swapfile_pins_lock);
10514 node = rb_first(&fs_info->swapfile_pins);
10516 next = rb_next(node);
10517 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10518 if (sp->inode == inode) {
10519 rb_erase(&sp->node, &fs_info->swapfile_pins);
10520 if (sp->is_block_group)
10521 btrfs_put_block_group(sp->ptr);
10526 spin_unlock(&fs_info->swapfile_pins_lock);
10529 struct btrfs_swap_info {
10535 unsigned long nr_pages;
10539 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10540 struct btrfs_swap_info *bsi)
10542 unsigned long nr_pages;
10543 u64 first_ppage, first_ppage_reported, next_ppage;
10546 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10547 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10548 PAGE_SIZE) >> PAGE_SHIFT;
10550 if (first_ppage >= next_ppage)
10552 nr_pages = next_ppage - first_ppage;
10554 first_ppage_reported = first_ppage;
10555 if (bsi->start == 0)
10556 first_ppage_reported++;
10557 if (bsi->lowest_ppage > first_ppage_reported)
10558 bsi->lowest_ppage = first_ppage_reported;
10559 if (bsi->highest_ppage < (next_ppage - 1))
10560 bsi->highest_ppage = next_ppage - 1;
10562 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10565 bsi->nr_extents += ret;
10566 bsi->nr_pages += nr_pages;
10570 static void btrfs_swap_deactivate(struct file *file)
10572 struct inode *inode = file_inode(file);
10574 btrfs_free_swapfile_pins(inode);
10575 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10578 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10581 struct inode *inode = file_inode(file);
10582 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10583 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10584 struct extent_state *cached_state = NULL;
10585 struct extent_map *em = NULL;
10586 struct btrfs_device *device = NULL;
10587 struct btrfs_swap_info bsi = {
10588 .lowest_ppage = (sector_t)-1ULL,
10595 * If the swap file was just created, make sure delalloc is done. If the
10596 * file changes again after this, the user is doing something stupid and
10597 * we don't really care.
10599 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10604 * The inode is locked, so these flags won't change after we check them.
10606 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10607 btrfs_warn(fs_info, "swapfile must not be compressed");
10610 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10611 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10614 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10615 btrfs_warn(fs_info, "swapfile must not be checksummed");
10620 * Balance or device remove/replace/resize can move stuff around from
10621 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10622 * concurrently while we are mapping the swap extents, and
10623 * fs_info->swapfile_pins prevents them from running while the swap file
10624 * is active and moving the extents. Note that this also prevents a
10625 * concurrent device add which isn't actually necessary, but it's not
10626 * really worth the trouble to allow it.
10628 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10629 btrfs_warn(fs_info,
10630 "cannot activate swapfile while exclusive operation is running");
10634 * Snapshots can create extents which require COW even if NODATACOW is
10635 * set. We use this counter to prevent snapshots. We must increment it
10636 * before walking the extents because we don't want a concurrent
10637 * snapshot to run after we've already checked the extents.
10639 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10641 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10643 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10645 while (start < isize) {
10646 u64 logical_block_start, physical_block_start;
10647 struct btrfs_block_group_cache *bg;
10648 u64 len = isize - start;
10650 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10656 if (em->block_start == EXTENT_MAP_HOLE) {
10657 btrfs_warn(fs_info, "swapfile must not have holes");
10661 if (em->block_start == EXTENT_MAP_INLINE) {
10663 * It's unlikely we'll ever actually find ourselves
10664 * here, as a file small enough to fit inline won't be
10665 * big enough to store more than the swap header, but in
10666 * case something changes in the future, let's catch it
10667 * here rather than later.
10669 btrfs_warn(fs_info, "swapfile must not be inline");
10673 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10674 btrfs_warn(fs_info, "swapfile must not be compressed");
10679 logical_block_start = em->block_start + (start - em->start);
10680 len = min(len, em->len - (start - em->start));
10681 free_extent_map(em);
10684 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10690 btrfs_warn(fs_info,
10691 "swapfile must not be copy-on-write");
10696 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10702 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10703 btrfs_warn(fs_info,
10704 "swapfile must have single data profile");
10709 if (device == NULL) {
10710 device = em->map_lookup->stripes[0].dev;
10711 ret = btrfs_add_swapfile_pin(inode, device, false);
10716 } else if (device != em->map_lookup->stripes[0].dev) {
10717 btrfs_warn(fs_info, "swapfile must be on one device");
10722 physical_block_start = (em->map_lookup->stripes[0].physical +
10723 (logical_block_start - em->start));
10724 len = min(len, em->len - (logical_block_start - em->start));
10725 free_extent_map(em);
10728 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10730 btrfs_warn(fs_info,
10731 "could not find block group containing swapfile");
10736 ret = btrfs_add_swapfile_pin(inode, bg, true);
10738 btrfs_put_block_group(bg);
10745 if (bsi.block_len &&
10746 bsi.block_start + bsi.block_len == physical_block_start) {
10747 bsi.block_len += len;
10749 if (bsi.block_len) {
10750 ret = btrfs_add_swap_extent(sis, &bsi);
10755 bsi.block_start = physical_block_start;
10756 bsi.block_len = len;
10763 ret = btrfs_add_swap_extent(sis, &bsi);
10766 if (!IS_ERR_OR_NULL(em))
10767 free_extent_map(em);
10769 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10772 btrfs_swap_deactivate(file);
10774 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10780 sis->bdev = device->bdev;
10781 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10782 sis->max = bsi.nr_pages;
10783 sis->pages = bsi.nr_pages - 1;
10784 sis->highest_bit = bsi.nr_pages - 1;
10785 return bsi.nr_extents;
10788 static void btrfs_swap_deactivate(struct file *file)
10792 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10795 return -EOPNOTSUPP;
10799 static const struct inode_operations btrfs_dir_inode_operations = {
10800 .getattr = btrfs_getattr,
10801 .lookup = btrfs_lookup,
10802 .create = btrfs_create,
10803 .unlink = btrfs_unlink,
10804 .link = btrfs_link,
10805 .mkdir = btrfs_mkdir,
10806 .rmdir = btrfs_rmdir,
10807 .rename = btrfs_rename2,
10808 .symlink = btrfs_symlink,
10809 .setattr = btrfs_setattr,
10810 .mknod = btrfs_mknod,
10811 .listxattr = btrfs_listxattr,
10812 .permission = btrfs_permission,
10813 .get_acl = btrfs_get_acl,
10814 .set_acl = btrfs_set_acl,
10815 .update_time = btrfs_update_time,
10816 .tmpfile = btrfs_tmpfile,
10818 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10819 .lookup = btrfs_lookup,
10820 .permission = btrfs_permission,
10821 .update_time = btrfs_update_time,
10824 static const struct file_operations btrfs_dir_file_operations = {
10825 .llseek = generic_file_llseek,
10826 .read = generic_read_dir,
10827 .iterate_shared = btrfs_real_readdir,
10828 .open = btrfs_opendir,
10829 .unlocked_ioctl = btrfs_ioctl,
10830 #ifdef CONFIG_COMPAT
10831 .compat_ioctl = btrfs_compat_ioctl,
10833 .release = btrfs_release_file,
10834 .fsync = btrfs_sync_file,
10837 static const struct extent_io_ops btrfs_extent_io_ops = {
10838 /* mandatory callbacks */
10839 .submit_bio_hook = btrfs_submit_bio_hook,
10840 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10844 * btrfs doesn't support the bmap operation because swapfiles
10845 * use bmap to make a mapping of extents in the file. They assume
10846 * these extents won't change over the life of the file and they
10847 * use the bmap result to do IO directly to the drive.
10849 * the btrfs bmap call would return logical addresses that aren't
10850 * suitable for IO and they also will change frequently as COW
10851 * operations happen. So, swapfile + btrfs == corruption.
10853 * For now we're avoiding this by dropping bmap.
10855 static const struct address_space_operations btrfs_aops = {
10856 .readpage = btrfs_readpage,
10857 .writepage = btrfs_writepage,
10858 .writepages = btrfs_writepages,
10859 .readpages = btrfs_readpages,
10860 .direct_IO = btrfs_direct_IO,
10861 .invalidatepage = btrfs_invalidatepage,
10862 .releasepage = btrfs_releasepage,
10863 .set_page_dirty = btrfs_set_page_dirty,
10864 .error_remove_page = generic_error_remove_page,
10865 .swap_activate = btrfs_swap_activate,
10866 .swap_deactivate = btrfs_swap_deactivate,
10869 static const struct inode_operations btrfs_file_inode_operations = {
10870 .getattr = btrfs_getattr,
10871 .setattr = btrfs_setattr,
10872 .listxattr = btrfs_listxattr,
10873 .permission = btrfs_permission,
10874 .fiemap = btrfs_fiemap,
10875 .get_acl = btrfs_get_acl,
10876 .set_acl = btrfs_set_acl,
10877 .update_time = btrfs_update_time,
10879 static const struct inode_operations btrfs_special_inode_operations = {
10880 .getattr = btrfs_getattr,
10881 .setattr = btrfs_setattr,
10882 .permission = btrfs_permission,
10883 .listxattr = btrfs_listxattr,
10884 .get_acl = btrfs_get_acl,
10885 .set_acl = btrfs_set_acl,
10886 .update_time = btrfs_update_time,
10888 static const struct inode_operations btrfs_symlink_inode_operations = {
10889 .get_link = page_get_link,
10890 .getattr = btrfs_getattr,
10891 .setattr = btrfs_setattr,
10892 .permission = btrfs_permission,
10893 .listxattr = btrfs_listxattr,
10894 .update_time = btrfs_update_time,
10897 const struct dentry_operations btrfs_dentry_operations = {
10898 .d_delete = btrfs_dentry_delete,