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 btrfs_run_delalloc_range() 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 = offset_in_page(start);
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;
457 struct page **pages = NULL;
458 unsigned long nr_pages;
459 unsigned long total_compressed = 0;
460 unsigned long total_in = 0;
463 int compress_type = fs_info->compress_type;
466 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
469 actual_end = min_t(u64, i_size_read(inode), end + 1);
472 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
473 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
474 nr_pages = min_t(unsigned long, nr_pages,
475 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
478 * we don't want to send crud past the end of i_size through
479 * compression, that's just a waste of CPU time. So, if the
480 * end of the file is before the start of our current
481 * requested range of bytes, we bail out to the uncompressed
482 * cleanup code that can deal with all of this.
484 * It isn't really the fastest way to fix things, but this is a
485 * very uncommon corner.
487 if (actual_end <= start)
488 goto cleanup_and_bail_uncompressed;
490 total_compressed = actual_end - start;
493 * skip compression for a small file range(<=blocksize) that
494 * isn't an inline extent, since it doesn't save disk space at all.
496 if (total_compressed <= blocksize &&
497 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
498 goto cleanup_and_bail_uncompressed;
500 total_compressed = min_t(unsigned long, total_compressed,
501 BTRFS_MAX_UNCOMPRESSED);
506 * we do compression for mount -o compress and when the
507 * inode has not been flagged as nocompress. This flag can
508 * change at any time if we discover bad compression ratios.
510 if (inode_need_compress(inode, start, end)) {
512 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
514 /* just bail out to the uncompressed code */
519 if (BTRFS_I(inode)->defrag_compress)
520 compress_type = BTRFS_I(inode)->defrag_compress;
521 else if (BTRFS_I(inode)->prop_compress)
522 compress_type = BTRFS_I(inode)->prop_compress;
525 * we need to call clear_page_dirty_for_io on each
526 * page in the range. Otherwise applications with the file
527 * mmap'd can wander in and change the page contents while
528 * we are compressing them.
530 * If the compression fails for any reason, we set the pages
531 * dirty again later on.
533 * Note that the remaining part is redirtied, the start pointer
534 * has moved, the end is the original one.
537 extent_range_clear_dirty_for_io(inode, start, end);
541 /* Compression level is applied here and only here */
542 ret = btrfs_compress_pages(
543 compress_type | (fs_info->compress_level << 4),
544 inode->i_mapping, start,
551 unsigned long offset = offset_in_page(total_compressed);
552 struct page *page = pages[nr_pages - 1];
555 /* zero the tail end of the last page, we might be
556 * sending it down to disk
559 kaddr = kmap_atomic(page);
560 memset(kaddr + offset, 0,
562 kunmap_atomic(kaddr);
569 /* lets try to make an inline extent */
570 if (ret || total_in < actual_end) {
571 /* we didn't compress the entire range, try
572 * to make an uncompressed inline extent.
574 ret = cow_file_range_inline(inode, start, end, 0,
575 BTRFS_COMPRESS_NONE, NULL);
577 /* try making a compressed inline extent */
578 ret = cow_file_range_inline(inode, start, end,
580 compress_type, pages);
583 unsigned long clear_flags = EXTENT_DELALLOC |
584 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
585 EXTENT_DO_ACCOUNTING;
586 unsigned long page_error_op;
588 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
591 * inline extent creation worked or returned error,
592 * we don't need to create any more async work items.
593 * Unlock and free up our temp pages.
595 * We use DO_ACCOUNTING here because we need the
596 * delalloc_release_metadata to be done _after_ we drop
597 * our outstanding extent for clearing delalloc for this
600 extent_clear_unlock_delalloc(inode, start, end, end,
613 * we aren't doing an inline extent round the compressed size
614 * up to a block size boundary so the allocator does sane
617 total_compressed = ALIGN(total_compressed, blocksize);
620 * one last check to make sure the compression is really a
621 * win, compare the page count read with the blocks on disk,
622 * compression must free at least one sector size
624 total_in = ALIGN(total_in, PAGE_SIZE);
625 if (total_compressed + blocksize <= total_in) {
629 * The async work queues will take care of doing actual
630 * allocation on disk for these compressed pages, and
631 * will submit them to the elevator.
633 add_async_extent(async_cow, start, total_in,
634 total_compressed, pages, nr_pages,
637 if (start + total_in < end) {
648 * the compression code ran but failed to make things smaller,
649 * free any pages it allocated and our page pointer array
651 for (i = 0; i < nr_pages; i++) {
652 WARN_ON(pages[i]->mapping);
657 total_compressed = 0;
660 /* flag the file so we don't compress in the future */
661 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
662 !(BTRFS_I(inode)->prop_compress)) {
663 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
666 cleanup_and_bail_uncompressed:
668 * No compression, but we still need to write the pages in the file
669 * we've been given so far. redirty the locked page if it corresponds
670 * to our extent and set things up for the async work queue to run
671 * cow_file_range to do the normal delalloc dance.
673 if (page_offset(locked_page) >= start &&
674 page_offset(locked_page) <= end)
675 __set_page_dirty_nobuffers(locked_page);
676 /* unlocked later on in the async handlers */
679 extent_range_redirty_for_io(inode, start, end);
680 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
681 BTRFS_COMPRESS_NONE);
687 for (i = 0; i < nr_pages; i++) {
688 WARN_ON(pages[i]->mapping);
694 static void free_async_extent_pages(struct async_extent *async_extent)
698 if (!async_extent->pages)
701 for (i = 0; i < async_extent->nr_pages; i++) {
702 WARN_ON(async_extent->pages[i]->mapping);
703 put_page(async_extent->pages[i]);
705 kfree(async_extent->pages);
706 async_extent->nr_pages = 0;
707 async_extent->pages = NULL;
711 * phase two of compressed writeback. This is the ordered portion
712 * of the code, which only gets called in the order the work was
713 * queued. We walk all the async extents created by compress_file_range
714 * and send them down to the disk.
716 static noinline void submit_compressed_extents(struct async_cow *async_cow)
718 struct inode *inode = async_cow->inode;
719 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
720 struct async_extent *async_extent;
722 struct btrfs_key ins;
723 struct extent_map *em;
724 struct btrfs_root *root = BTRFS_I(inode)->root;
725 struct extent_io_tree *io_tree;
729 while (!list_empty(&async_cow->extents)) {
730 async_extent = list_entry(async_cow->extents.next,
731 struct async_extent, list);
732 list_del(&async_extent->list);
734 io_tree = &BTRFS_I(inode)->io_tree;
737 /* did the compression code fall back to uncompressed IO? */
738 if (!async_extent->pages) {
739 int page_started = 0;
740 unsigned long nr_written = 0;
742 lock_extent(io_tree, async_extent->start,
743 async_extent->start +
744 async_extent->ram_size - 1);
746 /* allocate blocks */
747 ret = cow_file_range(inode, async_cow->locked_page,
749 async_extent->start +
750 async_extent->ram_size - 1,
751 async_extent->start +
752 async_extent->ram_size - 1,
753 &page_started, &nr_written, 0,
759 * if page_started, cow_file_range inserted an
760 * inline extent and took care of all the unlocking
761 * and IO for us. Otherwise, we need to submit
762 * all those pages down to the drive.
764 if (!page_started && !ret)
765 extent_write_locked_range(inode,
767 async_extent->start +
768 async_extent->ram_size - 1,
771 unlock_page(async_cow->locked_page);
777 lock_extent(io_tree, async_extent->start,
778 async_extent->start + async_extent->ram_size - 1);
780 ret = btrfs_reserve_extent(root, async_extent->ram_size,
781 async_extent->compressed_size,
782 async_extent->compressed_size,
783 0, alloc_hint, &ins, 1, 1);
785 free_async_extent_pages(async_extent);
787 if (ret == -ENOSPC) {
788 unlock_extent(io_tree, async_extent->start,
789 async_extent->start +
790 async_extent->ram_size - 1);
793 * we need to redirty the pages if we decide to
794 * fallback to uncompressed IO, otherwise we
795 * will not submit these pages down to lower
798 extent_range_redirty_for_io(inode,
800 async_extent->start +
801 async_extent->ram_size - 1);
808 * here we're doing allocation and writeback of the
811 em = create_io_em(inode, async_extent->start,
812 async_extent->ram_size, /* len */
813 async_extent->start, /* orig_start */
814 ins.objectid, /* block_start */
815 ins.offset, /* block_len */
816 ins.offset, /* orig_block_len */
817 async_extent->ram_size, /* ram_bytes */
818 async_extent->compress_type,
819 BTRFS_ORDERED_COMPRESSED);
821 /* ret value is not necessary due to void function */
822 goto out_free_reserve;
825 ret = btrfs_add_ordered_extent_compress(inode,
828 async_extent->ram_size,
830 BTRFS_ORDERED_COMPRESSED,
831 async_extent->compress_type);
833 btrfs_drop_extent_cache(BTRFS_I(inode),
835 async_extent->start +
836 async_extent->ram_size - 1, 0);
837 goto out_free_reserve;
839 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
842 * clear dirty, set writeback and unlock the pages.
844 extent_clear_unlock_delalloc(inode, async_extent->start,
845 async_extent->start +
846 async_extent->ram_size - 1,
847 async_extent->start +
848 async_extent->ram_size - 1,
849 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
850 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
852 if (btrfs_submit_compressed_write(inode,
854 async_extent->ram_size,
856 ins.offset, async_extent->pages,
857 async_extent->nr_pages,
858 async_cow->write_flags)) {
859 struct page *p = async_extent->pages[0];
860 const u64 start = async_extent->start;
861 const u64 end = start + async_extent->ram_size - 1;
863 p->mapping = inode->i_mapping;
864 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
867 extent_clear_unlock_delalloc(inode, start, end, end,
871 free_async_extent_pages(async_extent);
873 alloc_hint = ins.objectid + ins.offset;
879 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
880 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
882 extent_clear_unlock_delalloc(inode, async_extent->start,
883 async_extent->start +
884 async_extent->ram_size - 1,
885 async_extent->start +
886 async_extent->ram_size - 1,
887 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
888 EXTENT_DELALLOC_NEW |
889 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
890 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
891 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
893 free_async_extent_pages(async_extent);
898 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
901 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
902 struct extent_map *em;
905 read_lock(&em_tree->lock);
906 em = search_extent_mapping(em_tree, start, num_bytes);
909 * if block start isn't an actual block number then find the
910 * first block in this inode and use that as a hint. If that
911 * block is also bogus then just don't worry about it.
913 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
915 em = search_extent_mapping(em_tree, 0, 0);
916 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
917 alloc_hint = em->block_start;
921 alloc_hint = em->block_start;
925 read_unlock(&em_tree->lock);
931 * when extent_io.c finds a delayed allocation range in the file,
932 * the call backs end up in this code. The basic idea is to
933 * allocate extents on disk for the range, and create ordered data structs
934 * in ram to track those extents.
936 * locked_page is the page that writepage had locked already. We use
937 * it to make sure we don't do extra locks or unlocks.
939 * *page_started is set to one if we unlock locked_page and do everything
940 * required to start IO on it. It may be clean and already done with
943 static noinline int cow_file_range(struct inode *inode,
944 struct page *locked_page,
945 u64 start, u64 end, u64 delalloc_end,
946 int *page_started, unsigned long *nr_written,
947 int unlock, struct btrfs_dedupe_hash *hash)
949 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
950 struct btrfs_root *root = BTRFS_I(inode)->root;
953 unsigned long ram_size;
954 u64 cur_alloc_size = 0;
955 u64 blocksize = fs_info->sectorsize;
956 struct btrfs_key ins;
957 struct extent_map *em;
959 unsigned long page_ops;
960 bool extent_reserved = false;
963 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
969 num_bytes = ALIGN(end - start + 1, blocksize);
970 num_bytes = max(blocksize, num_bytes);
971 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
973 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
976 /* lets try to make an inline extent */
977 ret = cow_file_range_inline(inode, start, end, 0,
978 BTRFS_COMPRESS_NONE, NULL);
981 * We use DO_ACCOUNTING here because we need the
982 * delalloc_release_metadata to be run _after_ we drop
983 * our outstanding extent for clearing delalloc for this
986 extent_clear_unlock_delalloc(inode, start, end,
988 EXTENT_LOCKED | EXTENT_DELALLOC |
989 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
990 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
991 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
993 *nr_written = *nr_written +
994 (end - start + PAGE_SIZE) / PAGE_SIZE;
997 } else if (ret < 0) {
1002 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1003 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1004 start + num_bytes - 1, 0);
1006 while (num_bytes > 0) {
1007 cur_alloc_size = num_bytes;
1008 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1009 fs_info->sectorsize, 0, alloc_hint,
1013 cur_alloc_size = ins.offset;
1014 extent_reserved = true;
1016 ram_size = ins.offset;
1017 em = create_io_em(inode, start, ins.offset, /* len */
1018 start, /* orig_start */
1019 ins.objectid, /* block_start */
1020 ins.offset, /* block_len */
1021 ins.offset, /* orig_block_len */
1022 ram_size, /* ram_bytes */
1023 BTRFS_COMPRESS_NONE, /* compress_type */
1024 BTRFS_ORDERED_REGULAR /* type */);
1029 free_extent_map(em);
1031 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1032 ram_size, cur_alloc_size, 0);
1034 goto out_drop_extent_cache;
1036 if (root->root_key.objectid ==
1037 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1038 ret = btrfs_reloc_clone_csums(inode, start,
1041 * Only drop cache here, and process as normal.
1043 * We must not allow extent_clear_unlock_delalloc()
1044 * at out_unlock label to free meta of this ordered
1045 * extent, as its meta should be freed by
1046 * btrfs_finish_ordered_io().
1048 * So we must continue until @start is increased to
1049 * skip current ordered extent.
1052 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1053 start + ram_size - 1, 0);
1056 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1058 /* we're not doing compressed IO, don't unlock the first
1059 * page (which the caller expects to stay locked), don't
1060 * clear any dirty bits and don't set any writeback bits
1062 * Do set the Private2 bit so we know this page was properly
1063 * setup for writepage
1065 page_ops = unlock ? PAGE_UNLOCK : 0;
1066 page_ops |= PAGE_SET_PRIVATE2;
1068 extent_clear_unlock_delalloc(inode, start,
1069 start + ram_size - 1,
1070 delalloc_end, locked_page,
1071 EXTENT_LOCKED | EXTENT_DELALLOC,
1073 if (num_bytes < cur_alloc_size)
1076 num_bytes -= cur_alloc_size;
1077 alloc_hint = ins.objectid + ins.offset;
1078 start += cur_alloc_size;
1079 extent_reserved = false;
1082 * btrfs_reloc_clone_csums() error, since start is increased
1083 * extent_clear_unlock_delalloc() at out_unlock label won't
1084 * free metadata of current ordered extent, we're OK to exit.
1092 out_drop_extent_cache:
1093 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1095 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1096 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1098 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1099 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1100 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1103 * If we reserved an extent for our delalloc range (or a subrange) and
1104 * failed to create the respective ordered extent, then it means that
1105 * when we reserved the extent we decremented the extent's size from
1106 * the data space_info's bytes_may_use counter and incremented the
1107 * space_info's bytes_reserved counter by the same amount. We must make
1108 * sure extent_clear_unlock_delalloc() does not try to decrement again
1109 * the data space_info's bytes_may_use counter, therefore we do not pass
1110 * it the flag EXTENT_CLEAR_DATA_RESV.
1112 if (extent_reserved) {
1113 extent_clear_unlock_delalloc(inode, start,
1114 start + cur_alloc_size,
1115 start + cur_alloc_size,
1119 start += cur_alloc_size;
1123 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1125 clear_bits | EXTENT_CLEAR_DATA_RESV,
1131 * work queue call back to started compression on a file and pages
1133 static noinline void async_cow_start(struct btrfs_work *work)
1135 struct async_cow *async_cow;
1137 async_cow = container_of(work, struct async_cow, work);
1139 compress_file_range(async_cow->inode, async_cow->locked_page,
1140 async_cow->start, async_cow->end, async_cow,
1142 if (num_added == 0) {
1143 btrfs_add_delayed_iput(async_cow->inode);
1144 async_cow->inode = NULL;
1149 * work queue call back to submit previously compressed pages
1151 static noinline void async_cow_submit(struct btrfs_work *work)
1153 struct btrfs_fs_info *fs_info;
1154 struct async_cow *async_cow;
1155 unsigned long nr_pages;
1157 async_cow = container_of(work, struct async_cow, work);
1159 fs_info = async_cow->fs_info;
1160 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1163 /* atomic_sub_return implies a barrier */
1164 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1166 cond_wake_up_nomb(&fs_info->async_submit_wait);
1169 * ->inode could be NULL if async_cow_start has failed to compress,
1170 * in which case we don't have anything to submit, yet we need to
1171 * always adjust ->async_delalloc_pages as its paired with the init
1172 * happening in cow_file_range_async
1174 if (async_cow->inode)
1175 submit_compressed_extents(async_cow);
1178 static noinline void async_cow_free(struct btrfs_work *work)
1180 struct async_cow *async_cow;
1181 async_cow = container_of(work, struct async_cow, work);
1182 if (async_cow->inode)
1183 btrfs_add_delayed_iput(async_cow->inode);
1187 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1188 u64 start, u64 end, int *page_started,
1189 unsigned long *nr_written,
1190 unsigned int write_flags)
1192 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1193 struct async_cow *async_cow;
1194 unsigned long nr_pages;
1197 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1199 while (start < end) {
1200 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1201 BUG_ON(!async_cow); /* -ENOMEM */
1203 * igrab is called higher up in the call chain, take only the
1204 * lightweight reference for the callback lifetime
1207 async_cow->inode = inode;
1208 async_cow->fs_info = fs_info;
1209 async_cow->locked_page = locked_page;
1210 async_cow->start = start;
1211 async_cow->write_flags = write_flags;
1213 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1214 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1217 cur_end = min(end, start + SZ_512K - 1);
1219 async_cow->end = cur_end;
1220 INIT_LIST_HEAD(&async_cow->extents);
1222 btrfs_init_work(&async_cow->work,
1223 btrfs_delalloc_helper,
1224 async_cow_start, async_cow_submit,
1227 nr_pages = (cur_end - start + PAGE_SIZE) >>
1229 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1231 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1233 *nr_written += nr_pages;
1234 start = cur_end + 1;
1240 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1241 u64 bytenr, u64 num_bytes)
1244 struct btrfs_ordered_sum *sums;
1247 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1248 bytenr + num_bytes - 1, &list, 0);
1249 if (ret == 0 && list_empty(&list))
1252 while (!list_empty(&list)) {
1253 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1254 list_del(&sums->list);
1263 * when nowcow writeback call back. This checks for snapshots or COW copies
1264 * of the extents that exist in the file, and COWs the file as required.
1266 * If no cow copies or snapshots exist, we write directly to the existing
1269 static noinline int run_delalloc_nocow(struct inode *inode,
1270 struct page *locked_page,
1271 u64 start, u64 end, int *page_started, int force,
1272 unsigned long *nr_written)
1274 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1275 struct btrfs_root *root = BTRFS_I(inode)->root;
1276 struct extent_buffer *leaf;
1277 struct btrfs_path *path;
1278 struct btrfs_file_extent_item *fi;
1279 struct btrfs_key found_key;
1280 struct extent_map *em;
1295 u64 ino = btrfs_ino(BTRFS_I(inode));
1297 path = btrfs_alloc_path();
1299 extent_clear_unlock_delalloc(inode, start, end, end,
1301 EXTENT_LOCKED | EXTENT_DELALLOC |
1302 EXTENT_DO_ACCOUNTING |
1303 EXTENT_DEFRAG, PAGE_UNLOCK |
1305 PAGE_SET_WRITEBACK |
1306 PAGE_END_WRITEBACK);
1310 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1312 cow_start = (u64)-1;
1315 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1319 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1320 leaf = path->nodes[0];
1321 btrfs_item_key_to_cpu(leaf, &found_key,
1322 path->slots[0] - 1);
1323 if (found_key.objectid == ino &&
1324 found_key.type == BTRFS_EXTENT_DATA_KEY)
1329 leaf = path->nodes[0];
1330 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1331 ret = btrfs_next_leaf(root, path);
1333 if (cow_start != (u64)-1)
1334 cur_offset = cow_start;
1339 leaf = path->nodes[0];
1345 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1347 if (found_key.objectid > ino)
1349 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1350 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1354 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1355 found_key.offset > end)
1358 if (found_key.offset > cur_offset) {
1359 extent_end = found_key.offset;
1364 fi = btrfs_item_ptr(leaf, path->slots[0],
1365 struct btrfs_file_extent_item);
1366 extent_type = btrfs_file_extent_type(leaf, fi);
1368 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1369 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1370 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1371 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1372 extent_offset = btrfs_file_extent_offset(leaf, fi);
1373 extent_end = found_key.offset +
1374 btrfs_file_extent_num_bytes(leaf, fi);
1376 btrfs_file_extent_disk_num_bytes(leaf, fi);
1377 if (extent_end <= start) {
1381 if (disk_bytenr == 0)
1383 if (btrfs_file_extent_compression(leaf, fi) ||
1384 btrfs_file_extent_encryption(leaf, fi) ||
1385 btrfs_file_extent_other_encoding(leaf, fi))
1388 * Do the same check as in btrfs_cross_ref_exist but
1389 * without the unnecessary search.
1392 btrfs_file_extent_generation(leaf, fi) <=
1393 btrfs_root_last_snapshot(&root->root_item))
1395 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1397 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1399 ret = btrfs_cross_ref_exist(root, ino,
1401 extent_offset, disk_bytenr);
1404 * ret could be -EIO if the above fails to read
1408 if (cow_start != (u64)-1)
1409 cur_offset = cow_start;
1413 WARN_ON_ONCE(nolock);
1416 disk_bytenr += extent_offset;
1417 disk_bytenr += cur_offset - found_key.offset;
1418 num_bytes = min(end + 1, extent_end) - cur_offset;
1420 * if there are pending snapshots for this root,
1421 * we fall into common COW way.
1423 if (!nolock && atomic_read(&root->snapshot_force_cow))
1426 * force cow if csum exists in the range.
1427 * this ensure that csum for a given extent are
1428 * either valid or do not exist.
1430 ret = csum_exist_in_range(fs_info, disk_bytenr,
1434 * ret could be -EIO if the above fails to read
1438 if (cow_start != (u64)-1)
1439 cur_offset = cow_start;
1442 WARN_ON_ONCE(nolock);
1445 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1448 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1449 extent_end = found_key.offset +
1450 btrfs_file_extent_ram_bytes(leaf, fi);
1451 extent_end = ALIGN(extent_end,
1452 fs_info->sectorsize);
1457 if (extent_end <= start) {
1460 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1464 if (cow_start == (u64)-1)
1465 cow_start = cur_offset;
1466 cur_offset = extent_end;
1467 if (cur_offset > end)
1473 btrfs_release_path(path);
1474 if (cow_start != (u64)-1) {
1475 ret = cow_file_range(inode, locked_page,
1476 cow_start, found_key.offset - 1,
1477 end, page_started, nr_written, 1,
1481 btrfs_dec_nocow_writers(fs_info,
1485 cow_start = (u64)-1;
1488 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1489 u64 orig_start = found_key.offset - extent_offset;
1491 em = create_io_em(inode, cur_offset, num_bytes,
1493 disk_bytenr, /* block_start */
1494 num_bytes, /* block_len */
1495 disk_num_bytes, /* orig_block_len */
1496 ram_bytes, BTRFS_COMPRESS_NONE,
1497 BTRFS_ORDERED_PREALLOC);
1500 btrfs_dec_nocow_writers(fs_info,
1505 free_extent_map(em);
1508 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1509 type = BTRFS_ORDERED_PREALLOC;
1511 type = BTRFS_ORDERED_NOCOW;
1514 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1515 num_bytes, num_bytes, type);
1517 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1518 BUG_ON(ret); /* -ENOMEM */
1520 if (root->root_key.objectid ==
1521 BTRFS_DATA_RELOC_TREE_OBJECTID)
1523 * Error handled later, as we must prevent
1524 * extent_clear_unlock_delalloc() in error handler
1525 * from freeing metadata of created ordered extent.
1527 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1530 extent_clear_unlock_delalloc(inode, cur_offset,
1531 cur_offset + num_bytes - 1, end,
1532 locked_page, EXTENT_LOCKED |
1534 EXTENT_CLEAR_DATA_RESV,
1535 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1537 cur_offset = extent_end;
1540 * btrfs_reloc_clone_csums() error, now we're OK to call error
1541 * handler, as metadata for created ordered extent will only
1542 * be freed by btrfs_finish_ordered_io().
1546 if (cur_offset > end)
1549 btrfs_release_path(path);
1551 if (cur_offset <= end && cow_start == (u64)-1)
1552 cow_start = cur_offset;
1554 if (cow_start != (u64)-1) {
1556 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1557 page_started, nr_written, 1, NULL);
1563 if (ret && cur_offset < end)
1564 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1565 locked_page, EXTENT_LOCKED |
1566 EXTENT_DELALLOC | EXTENT_DEFRAG |
1567 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1569 PAGE_SET_WRITEBACK |
1570 PAGE_END_WRITEBACK);
1571 btrfs_free_path(path);
1575 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1578 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1579 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1583 * @defrag_bytes is a hint value, no spinlock held here,
1584 * if is not zero, it means the file is defragging.
1585 * Force cow if given extent needs to be defragged.
1587 if (BTRFS_I(inode)->defrag_bytes &&
1588 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1589 EXTENT_DEFRAG, 0, NULL))
1596 * Function to process delayed allocation (create CoW) for ranges which are
1597 * being touched for the first time.
1599 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1600 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1601 struct writeback_control *wbc)
1604 int force_cow = need_force_cow(inode, start, end);
1605 unsigned int write_flags = wbc_to_write_flags(wbc);
1607 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1608 ret = run_delalloc_nocow(inode, locked_page, start, end,
1609 page_started, 1, nr_written);
1610 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1611 ret = run_delalloc_nocow(inode, locked_page, start, end,
1612 page_started, 0, nr_written);
1613 } else if (!inode_need_compress(inode, start, end)) {
1614 ret = cow_file_range(inode, locked_page, start, end, end,
1615 page_started, nr_written, 1, NULL);
1617 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1618 &BTRFS_I(inode)->runtime_flags);
1619 ret = cow_file_range_async(inode, locked_page, start, end,
1620 page_started, nr_written,
1624 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1629 void btrfs_split_delalloc_extent(struct inode *inode,
1630 struct extent_state *orig, u64 split)
1634 /* not delalloc, ignore it */
1635 if (!(orig->state & EXTENT_DELALLOC))
1638 size = orig->end - orig->start + 1;
1639 if (size > BTRFS_MAX_EXTENT_SIZE) {
1644 * See the explanation in btrfs_merge_delalloc_extent, the same
1645 * applies here, just in reverse.
1647 new_size = orig->end - split + 1;
1648 num_extents = count_max_extents(new_size);
1649 new_size = split - orig->start;
1650 num_extents += count_max_extents(new_size);
1651 if (count_max_extents(size) >= num_extents)
1655 spin_lock(&BTRFS_I(inode)->lock);
1656 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1657 spin_unlock(&BTRFS_I(inode)->lock);
1661 * Handle merged delayed allocation extents so we can keep track of new extents
1662 * that are just merged onto old extents, such as when we are doing sequential
1663 * writes, so we can properly account for the metadata space we'll need.
1665 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1666 struct extent_state *other)
1668 u64 new_size, old_size;
1671 /* not delalloc, ignore it */
1672 if (!(other->state & EXTENT_DELALLOC))
1675 if (new->start > other->start)
1676 new_size = new->end - other->start + 1;
1678 new_size = other->end - new->start + 1;
1680 /* we're not bigger than the max, unreserve the space and go */
1681 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1682 spin_lock(&BTRFS_I(inode)->lock);
1683 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1684 spin_unlock(&BTRFS_I(inode)->lock);
1689 * We have to add up either side to figure out how many extents were
1690 * accounted for before we merged into one big extent. If the number of
1691 * extents we accounted for is <= the amount we need for the new range
1692 * then we can return, otherwise drop. Think of it like this
1696 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1697 * need 2 outstanding extents, on one side we have 1 and the other side
1698 * we have 1 so they are == and we can return. But in this case
1700 * [MAX_SIZE+4k][MAX_SIZE+4k]
1702 * Each range on their own accounts for 2 extents, but merged together
1703 * they are only 3 extents worth of accounting, so we need to drop in
1706 old_size = other->end - other->start + 1;
1707 num_extents = count_max_extents(old_size);
1708 old_size = new->end - new->start + 1;
1709 num_extents += count_max_extents(old_size);
1710 if (count_max_extents(new_size) >= num_extents)
1713 spin_lock(&BTRFS_I(inode)->lock);
1714 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1715 spin_unlock(&BTRFS_I(inode)->lock);
1718 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1719 struct inode *inode)
1721 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1723 spin_lock(&root->delalloc_lock);
1724 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1725 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1726 &root->delalloc_inodes);
1727 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1728 &BTRFS_I(inode)->runtime_flags);
1729 root->nr_delalloc_inodes++;
1730 if (root->nr_delalloc_inodes == 1) {
1731 spin_lock(&fs_info->delalloc_root_lock);
1732 BUG_ON(!list_empty(&root->delalloc_root));
1733 list_add_tail(&root->delalloc_root,
1734 &fs_info->delalloc_roots);
1735 spin_unlock(&fs_info->delalloc_root_lock);
1738 spin_unlock(&root->delalloc_lock);
1742 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1743 struct btrfs_inode *inode)
1745 struct btrfs_fs_info *fs_info = root->fs_info;
1747 if (!list_empty(&inode->delalloc_inodes)) {
1748 list_del_init(&inode->delalloc_inodes);
1749 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1750 &inode->runtime_flags);
1751 root->nr_delalloc_inodes--;
1752 if (!root->nr_delalloc_inodes) {
1753 ASSERT(list_empty(&root->delalloc_inodes));
1754 spin_lock(&fs_info->delalloc_root_lock);
1755 BUG_ON(list_empty(&root->delalloc_root));
1756 list_del_init(&root->delalloc_root);
1757 spin_unlock(&fs_info->delalloc_root_lock);
1762 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1763 struct btrfs_inode *inode)
1765 spin_lock(&root->delalloc_lock);
1766 __btrfs_del_delalloc_inode(root, inode);
1767 spin_unlock(&root->delalloc_lock);
1771 * Properly track delayed allocation bytes in the inode and to maintain the
1772 * list of inodes that have pending delalloc work to be done.
1774 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1779 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1782 * set_bit and clear bit hooks normally require _irqsave/restore
1783 * but in this case, we are only testing for the DELALLOC
1784 * bit, which is only set or cleared with irqs on
1786 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1787 struct btrfs_root *root = BTRFS_I(inode)->root;
1788 u64 len = state->end + 1 - state->start;
1789 u32 num_extents = count_max_extents(len);
1790 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1792 spin_lock(&BTRFS_I(inode)->lock);
1793 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1794 spin_unlock(&BTRFS_I(inode)->lock);
1796 /* For sanity tests */
1797 if (btrfs_is_testing(fs_info))
1800 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1801 fs_info->delalloc_batch);
1802 spin_lock(&BTRFS_I(inode)->lock);
1803 BTRFS_I(inode)->delalloc_bytes += len;
1804 if (*bits & EXTENT_DEFRAG)
1805 BTRFS_I(inode)->defrag_bytes += len;
1806 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1807 &BTRFS_I(inode)->runtime_flags))
1808 btrfs_add_delalloc_inodes(root, inode);
1809 spin_unlock(&BTRFS_I(inode)->lock);
1812 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1813 (*bits & EXTENT_DELALLOC_NEW)) {
1814 spin_lock(&BTRFS_I(inode)->lock);
1815 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1817 spin_unlock(&BTRFS_I(inode)->lock);
1822 * Once a range is no longer delalloc this function ensures that proper
1823 * accounting happens.
1825 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1826 struct extent_state *state, unsigned *bits)
1828 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1829 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1830 u64 len = state->end + 1 - state->start;
1831 u32 num_extents = count_max_extents(len);
1833 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1834 spin_lock(&inode->lock);
1835 inode->defrag_bytes -= len;
1836 spin_unlock(&inode->lock);
1840 * set_bit and clear bit hooks normally require _irqsave/restore
1841 * but in this case, we are only testing for the DELALLOC
1842 * bit, which is only set or cleared with irqs on
1844 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1845 struct btrfs_root *root = inode->root;
1846 bool do_list = !btrfs_is_free_space_inode(inode);
1848 spin_lock(&inode->lock);
1849 btrfs_mod_outstanding_extents(inode, -num_extents);
1850 spin_unlock(&inode->lock);
1853 * We don't reserve metadata space for space cache inodes so we
1854 * don't need to call delalloc_release_metadata if there is an
1857 if (*bits & EXTENT_CLEAR_META_RESV &&
1858 root != fs_info->tree_root)
1859 btrfs_delalloc_release_metadata(inode, len, false);
1861 /* For sanity tests. */
1862 if (btrfs_is_testing(fs_info))
1865 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1866 do_list && !(state->state & EXTENT_NORESERVE) &&
1867 (*bits & EXTENT_CLEAR_DATA_RESV))
1868 btrfs_free_reserved_data_space_noquota(
1872 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1873 fs_info->delalloc_batch);
1874 spin_lock(&inode->lock);
1875 inode->delalloc_bytes -= len;
1876 if (do_list && inode->delalloc_bytes == 0 &&
1877 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1878 &inode->runtime_flags))
1879 btrfs_del_delalloc_inode(root, inode);
1880 spin_unlock(&inode->lock);
1883 if ((state->state & EXTENT_DELALLOC_NEW) &&
1884 (*bits & EXTENT_DELALLOC_NEW)) {
1885 spin_lock(&inode->lock);
1886 ASSERT(inode->new_delalloc_bytes >= len);
1887 inode->new_delalloc_bytes -= len;
1888 spin_unlock(&inode->lock);
1893 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1894 * in a chunk's stripe. This function ensures that bios do not span a
1897 * @page - The page we are about to add to the bio
1898 * @size - size we want to add to the bio
1899 * @bio - bio we want to ensure is smaller than a stripe
1900 * @bio_flags - flags of the bio
1902 * return 1 if page cannot be added to the bio
1903 * return 0 if page can be added to the bio
1904 * return error otherwise
1906 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1907 unsigned long bio_flags)
1909 struct inode *inode = page->mapping->host;
1910 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1911 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1916 if (bio_flags & EXTENT_BIO_COMPRESSED)
1919 length = bio->bi_iter.bi_size;
1920 map_length = length;
1921 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1925 if (map_length < length + size)
1931 * in order to insert checksums into the metadata in large chunks,
1932 * we wait until bio submission time. All the pages in the bio are
1933 * checksummed and sums are attached onto the ordered extent record.
1935 * At IO completion time the cums attached on the ordered extent record
1936 * are inserted into the btree
1938 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1941 struct inode *inode = private_data;
1942 blk_status_t ret = 0;
1944 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1945 BUG_ON(ret); /* -ENOMEM */
1950 * extent_io.c submission hook. This does the right thing for csum calculation
1951 * on write, or reading the csums from the tree before a read.
1953 * Rules about async/sync submit,
1954 * a) read: sync submit
1956 * b) write without checksum: sync submit
1958 * c) write with checksum:
1959 * c-1) if bio is issued by fsync: sync submit
1960 * (sync_writers != 0)
1962 * c-2) if root is reloc root: sync submit
1963 * (only in case of buffered IO)
1965 * c-3) otherwise: async submit
1967 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1968 int mirror_num, unsigned long bio_flags,
1971 struct inode *inode = private_data;
1972 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1973 struct btrfs_root *root = BTRFS_I(inode)->root;
1974 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1975 blk_status_t ret = 0;
1977 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1979 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1981 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1982 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1984 if (bio_op(bio) != REQ_OP_WRITE) {
1985 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1989 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1990 ret = btrfs_submit_compressed_read(inode, bio,
1994 } else if (!skip_sum) {
1995 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2000 } else if (async && !skip_sum) {
2001 /* csum items have already been cloned */
2002 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2004 /* we're doing a write, do the async checksumming */
2005 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2007 btrfs_submit_bio_start);
2009 } else if (!skip_sum) {
2010 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2016 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2020 bio->bi_status = ret;
2027 * given a list of ordered sums record them in the inode. This happens
2028 * at IO completion time based on sums calculated at bio submission time.
2030 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2031 struct inode *inode, struct list_head *list)
2033 struct btrfs_ordered_sum *sum;
2036 list_for_each_entry(sum, list, list) {
2037 trans->adding_csums = true;
2038 ret = btrfs_csum_file_blocks(trans,
2039 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2040 trans->adding_csums = false;
2047 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2048 unsigned int extra_bits,
2049 struct extent_state **cached_state, int dedupe)
2051 WARN_ON(PAGE_ALIGNED(end));
2052 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2053 extra_bits, cached_state);
2056 /* see btrfs_writepage_start_hook for details on why this is required */
2057 struct btrfs_writepage_fixup {
2059 struct btrfs_work work;
2062 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2064 struct btrfs_writepage_fixup *fixup;
2065 struct btrfs_ordered_extent *ordered;
2066 struct extent_state *cached_state = NULL;
2067 struct extent_changeset *data_reserved = NULL;
2069 struct inode *inode;
2074 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2078 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2079 ClearPageChecked(page);
2083 inode = page->mapping->host;
2084 page_start = page_offset(page);
2085 page_end = page_offset(page) + PAGE_SIZE - 1;
2087 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2090 /* already ordered? We're done */
2091 if (PagePrivate2(page))
2094 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2097 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2098 page_end, &cached_state);
2100 btrfs_start_ordered_extent(inode, ordered, 1);
2101 btrfs_put_ordered_extent(ordered);
2105 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2108 mapping_set_error(page->mapping, ret);
2109 end_extent_writepage(page, ret, page_start, page_end);
2110 ClearPageChecked(page);
2114 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2117 mapping_set_error(page->mapping, ret);
2118 end_extent_writepage(page, ret, page_start, page_end);
2119 ClearPageChecked(page);
2123 ClearPageChecked(page);
2124 set_page_dirty(page);
2125 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2127 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2133 extent_changeset_free(data_reserved);
2137 * There are a few paths in the higher layers of the kernel that directly
2138 * set the page dirty bit without asking the filesystem if it is a
2139 * good idea. This causes problems because we want to make sure COW
2140 * properly happens and the data=ordered rules are followed.
2142 * In our case any range that doesn't have the ORDERED bit set
2143 * hasn't been properly setup for IO. We kick off an async process
2144 * to fix it up. The async helper will wait for ordered extents, set
2145 * the delalloc bit and make it safe to write the page.
2147 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2149 struct inode *inode = page->mapping->host;
2150 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2151 struct btrfs_writepage_fixup *fixup;
2153 /* this page is properly in the ordered list */
2154 if (TestClearPagePrivate2(page))
2157 if (PageChecked(page))
2160 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2164 SetPageChecked(page);
2166 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2167 btrfs_writepage_fixup_worker, NULL, NULL);
2169 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2173 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2174 struct inode *inode, u64 file_pos,
2175 u64 disk_bytenr, u64 disk_num_bytes,
2176 u64 num_bytes, u64 ram_bytes,
2177 u8 compression, u8 encryption,
2178 u16 other_encoding, int extent_type)
2180 struct btrfs_root *root = BTRFS_I(inode)->root;
2181 struct btrfs_file_extent_item *fi;
2182 struct btrfs_path *path;
2183 struct extent_buffer *leaf;
2184 struct btrfs_key ins;
2186 int extent_inserted = 0;
2189 path = btrfs_alloc_path();
2194 * we may be replacing one extent in the tree with another.
2195 * The new extent is pinned in the extent map, and we don't want
2196 * to drop it from the cache until it is completely in the btree.
2198 * So, tell btrfs_drop_extents to leave this extent in the cache.
2199 * the caller is expected to unpin it and allow it to be merged
2202 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2203 file_pos + num_bytes, NULL, 0,
2204 1, sizeof(*fi), &extent_inserted);
2208 if (!extent_inserted) {
2209 ins.objectid = btrfs_ino(BTRFS_I(inode));
2210 ins.offset = file_pos;
2211 ins.type = BTRFS_EXTENT_DATA_KEY;
2213 path->leave_spinning = 1;
2214 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2219 leaf = path->nodes[0];
2220 fi = btrfs_item_ptr(leaf, path->slots[0],
2221 struct btrfs_file_extent_item);
2222 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2223 btrfs_set_file_extent_type(leaf, fi, extent_type);
2224 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2225 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2226 btrfs_set_file_extent_offset(leaf, fi, 0);
2227 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2228 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2229 btrfs_set_file_extent_compression(leaf, fi, compression);
2230 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2231 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2233 btrfs_mark_buffer_dirty(leaf);
2234 btrfs_release_path(path);
2236 inode_add_bytes(inode, num_bytes);
2238 ins.objectid = disk_bytenr;
2239 ins.offset = disk_num_bytes;
2240 ins.type = BTRFS_EXTENT_ITEM_KEY;
2243 * Release the reserved range from inode dirty range map, as it is
2244 * already moved into delayed_ref_head
2246 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2250 ret = btrfs_alloc_reserved_file_extent(trans, root,
2251 btrfs_ino(BTRFS_I(inode)),
2252 file_pos, qg_released, &ins);
2254 btrfs_free_path(path);
2259 /* snapshot-aware defrag */
2260 struct sa_defrag_extent_backref {
2261 struct rb_node node;
2262 struct old_sa_defrag_extent *old;
2271 struct old_sa_defrag_extent {
2272 struct list_head list;
2273 struct new_sa_defrag_extent *new;
2282 struct new_sa_defrag_extent {
2283 struct rb_root root;
2284 struct list_head head;
2285 struct btrfs_path *path;
2286 struct inode *inode;
2294 static int backref_comp(struct sa_defrag_extent_backref *b1,
2295 struct sa_defrag_extent_backref *b2)
2297 if (b1->root_id < b2->root_id)
2299 else if (b1->root_id > b2->root_id)
2302 if (b1->inum < b2->inum)
2304 else if (b1->inum > b2->inum)
2307 if (b1->file_pos < b2->file_pos)
2309 else if (b1->file_pos > b2->file_pos)
2313 * [------------------------------] ===> (a range of space)
2314 * |<--->| |<---->| =============> (fs/file tree A)
2315 * |<---------------------------->| ===> (fs/file tree B)
2317 * A range of space can refer to two file extents in one tree while
2318 * refer to only one file extent in another tree.
2320 * So we may process a disk offset more than one time(two extents in A)
2321 * and locate at the same extent(one extent in B), then insert two same
2322 * backrefs(both refer to the extent in B).
2327 static void backref_insert(struct rb_root *root,
2328 struct sa_defrag_extent_backref *backref)
2330 struct rb_node **p = &root->rb_node;
2331 struct rb_node *parent = NULL;
2332 struct sa_defrag_extent_backref *entry;
2337 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2339 ret = backref_comp(backref, entry);
2343 p = &(*p)->rb_right;
2346 rb_link_node(&backref->node, parent, p);
2347 rb_insert_color(&backref->node, root);
2351 * Note the backref might has changed, and in this case we just return 0.
2353 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2356 struct btrfs_file_extent_item *extent;
2357 struct old_sa_defrag_extent *old = ctx;
2358 struct new_sa_defrag_extent *new = old->new;
2359 struct btrfs_path *path = new->path;
2360 struct btrfs_key key;
2361 struct btrfs_root *root;
2362 struct sa_defrag_extent_backref *backref;
2363 struct extent_buffer *leaf;
2364 struct inode *inode = new->inode;
2365 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2371 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2372 inum == btrfs_ino(BTRFS_I(inode)))
2375 key.objectid = root_id;
2376 key.type = BTRFS_ROOT_ITEM_KEY;
2377 key.offset = (u64)-1;
2379 root = btrfs_read_fs_root_no_name(fs_info, &key);
2381 if (PTR_ERR(root) == -ENOENT)
2384 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2385 inum, offset, root_id);
2386 return PTR_ERR(root);
2389 key.objectid = inum;
2390 key.type = BTRFS_EXTENT_DATA_KEY;
2391 if (offset > (u64)-1 << 32)
2394 key.offset = offset;
2396 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2397 if (WARN_ON(ret < 0))
2404 leaf = path->nodes[0];
2405 slot = path->slots[0];
2407 if (slot >= btrfs_header_nritems(leaf)) {
2408 ret = btrfs_next_leaf(root, path);
2411 } else if (ret > 0) {
2420 btrfs_item_key_to_cpu(leaf, &key, slot);
2422 if (key.objectid > inum)
2425 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2428 extent = btrfs_item_ptr(leaf, slot,
2429 struct btrfs_file_extent_item);
2431 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2435 * 'offset' refers to the exact key.offset,
2436 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2437 * (key.offset - extent_offset).
2439 if (key.offset != offset)
2442 extent_offset = btrfs_file_extent_offset(leaf, extent);
2443 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2445 if (extent_offset >= old->extent_offset + old->offset +
2446 old->len || extent_offset + num_bytes <=
2447 old->extent_offset + old->offset)
2452 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2458 backref->root_id = root_id;
2459 backref->inum = inum;
2460 backref->file_pos = offset;
2461 backref->num_bytes = num_bytes;
2462 backref->extent_offset = extent_offset;
2463 backref->generation = btrfs_file_extent_generation(leaf, extent);
2465 backref_insert(&new->root, backref);
2468 btrfs_release_path(path);
2473 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2474 struct new_sa_defrag_extent *new)
2476 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2477 struct old_sa_defrag_extent *old, *tmp;
2482 list_for_each_entry_safe(old, tmp, &new->head, list) {
2483 ret = iterate_inodes_from_logical(old->bytenr +
2484 old->extent_offset, fs_info,
2485 path, record_one_backref,
2487 if (ret < 0 && ret != -ENOENT)
2490 /* no backref to be processed for this extent */
2492 list_del(&old->list);
2497 if (list_empty(&new->head))
2503 static int relink_is_mergable(struct extent_buffer *leaf,
2504 struct btrfs_file_extent_item *fi,
2505 struct new_sa_defrag_extent *new)
2507 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2510 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2513 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2516 if (btrfs_file_extent_encryption(leaf, fi) ||
2517 btrfs_file_extent_other_encoding(leaf, fi))
2524 * Note the backref might has changed, and in this case we just return 0.
2526 static noinline int relink_extent_backref(struct btrfs_path *path,
2527 struct sa_defrag_extent_backref *prev,
2528 struct sa_defrag_extent_backref *backref)
2530 struct btrfs_file_extent_item *extent;
2531 struct btrfs_file_extent_item *item;
2532 struct btrfs_ordered_extent *ordered;
2533 struct btrfs_trans_handle *trans;
2534 struct btrfs_root *root;
2535 struct btrfs_key key;
2536 struct extent_buffer *leaf;
2537 struct old_sa_defrag_extent *old = backref->old;
2538 struct new_sa_defrag_extent *new = old->new;
2539 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2540 struct inode *inode;
2541 struct extent_state *cached = NULL;
2550 if (prev && prev->root_id == backref->root_id &&
2551 prev->inum == backref->inum &&
2552 prev->file_pos + prev->num_bytes == backref->file_pos)
2555 /* step 1: get root */
2556 key.objectid = backref->root_id;
2557 key.type = BTRFS_ROOT_ITEM_KEY;
2558 key.offset = (u64)-1;
2560 index = srcu_read_lock(&fs_info->subvol_srcu);
2562 root = btrfs_read_fs_root_no_name(fs_info, &key);
2564 srcu_read_unlock(&fs_info->subvol_srcu, index);
2565 if (PTR_ERR(root) == -ENOENT)
2567 return PTR_ERR(root);
2570 if (btrfs_root_readonly(root)) {
2571 srcu_read_unlock(&fs_info->subvol_srcu, index);
2575 /* step 2: get inode */
2576 key.objectid = backref->inum;
2577 key.type = BTRFS_INODE_ITEM_KEY;
2580 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2581 if (IS_ERR(inode)) {
2582 srcu_read_unlock(&fs_info->subvol_srcu, index);
2586 srcu_read_unlock(&fs_info->subvol_srcu, index);
2588 /* step 3: relink backref */
2589 lock_start = backref->file_pos;
2590 lock_end = backref->file_pos + backref->num_bytes - 1;
2591 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2594 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2596 btrfs_put_ordered_extent(ordered);
2600 trans = btrfs_join_transaction(root);
2601 if (IS_ERR(trans)) {
2602 ret = PTR_ERR(trans);
2606 key.objectid = backref->inum;
2607 key.type = BTRFS_EXTENT_DATA_KEY;
2608 key.offset = backref->file_pos;
2610 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2613 } else if (ret > 0) {
2618 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2619 struct btrfs_file_extent_item);
2621 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2622 backref->generation)
2625 btrfs_release_path(path);
2627 start = backref->file_pos;
2628 if (backref->extent_offset < old->extent_offset + old->offset)
2629 start += old->extent_offset + old->offset -
2630 backref->extent_offset;
2632 len = min(backref->extent_offset + backref->num_bytes,
2633 old->extent_offset + old->offset + old->len);
2634 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2636 ret = btrfs_drop_extents(trans, root, inode, start,
2641 key.objectid = btrfs_ino(BTRFS_I(inode));
2642 key.type = BTRFS_EXTENT_DATA_KEY;
2645 path->leave_spinning = 1;
2647 struct btrfs_file_extent_item *fi;
2649 struct btrfs_key found_key;
2651 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2656 leaf = path->nodes[0];
2657 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2659 fi = btrfs_item_ptr(leaf, path->slots[0],
2660 struct btrfs_file_extent_item);
2661 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2663 if (extent_len + found_key.offset == start &&
2664 relink_is_mergable(leaf, fi, new)) {
2665 btrfs_set_file_extent_num_bytes(leaf, fi,
2667 btrfs_mark_buffer_dirty(leaf);
2668 inode_add_bytes(inode, len);
2674 btrfs_release_path(path);
2679 ret = btrfs_insert_empty_item(trans, root, path, &key,
2682 btrfs_abort_transaction(trans, ret);
2686 leaf = path->nodes[0];
2687 item = btrfs_item_ptr(leaf, path->slots[0],
2688 struct btrfs_file_extent_item);
2689 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2690 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2691 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2692 btrfs_set_file_extent_num_bytes(leaf, item, len);
2693 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2694 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2695 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2696 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2697 btrfs_set_file_extent_encryption(leaf, item, 0);
2698 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2700 btrfs_mark_buffer_dirty(leaf);
2701 inode_add_bytes(inode, len);
2702 btrfs_release_path(path);
2704 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2706 backref->root_id, backref->inum,
2707 new->file_pos); /* start - extent_offset */
2709 btrfs_abort_transaction(trans, ret);
2715 btrfs_release_path(path);
2716 path->leave_spinning = 0;
2717 btrfs_end_transaction(trans);
2719 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2725 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2727 struct old_sa_defrag_extent *old, *tmp;
2732 list_for_each_entry_safe(old, tmp, &new->head, list) {
2738 static void relink_file_extents(struct new_sa_defrag_extent *new)
2740 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2741 struct btrfs_path *path;
2742 struct sa_defrag_extent_backref *backref;
2743 struct sa_defrag_extent_backref *prev = NULL;
2744 struct rb_node *node;
2747 path = btrfs_alloc_path();
2751 if (!record_extent_backrefs(path, new)) {
2752 btrfs_free_path(path);
2755 btrfs_release_path(path);
2758 node = rb_first(&new->root);
2761 rb_erase(node, &new->root);
2763 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2765 ret = relink_extent_backref(path, prev, backref);
2778 btrfs_free_path(path);
2780 free_sa_defrag_extent(new);
2782 atomic_dec(&fs_info->defrag_running);
2783 wake_up(&fs_info->transaction_wait);
2786 static struct new_sa_defrag_extent *
2787 record_old_file_extents(struct inode *inode,
2788 struct btrfs_ordered_extent *ordered)
2790 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2791 struct btrfs_root *root = BTRFS_I(inode)->root;
2792 struct btrfs_path *path;
2793 struct btrfs_key key;
2794 struct old_sa_defrag_extent *old;
2795 struct new_sa_defrag_extent *new;
2798 new = kmalloc(sizeof(*new), GFP_NOFS);
2803 new->file_pos = ordered->file_offset;
2804 new->len = ordered->len;
2805 new->bytenr = ordered->start;
2806 new->disk_len = ordered->disk_len;
2807 new->compress_type = ordered->compress_type;
2808 new->root = RB_ROOT;
2809 INIT_LIST_HEAD(&new->head);
2811 path = btrfs_alloc_path();
2815 key.objectid = btrfs_ino(BTRFS_I(inode));
2816 key.type = BTRFS_EXTENT_DATA_KEY;
2817 key.offset = new->file_pos;
2819 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2822 if (ret > 0 && path->slots[0] > 0)
2825 /* find out all the old extents for the file range */
2827 struct btrfs_file_extent_item *extent;
2828 struct extent_buffer *l;
2837 slot = path->slots[0];
2839 if (slot >= btrfs_header_nritems(l)) {
2840 ret = btrfs_next_leaf(root, path);
2848 btrfs_item_key_to_cpu(l, &key, slot);
2850 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2852 if (key.type != BTRFS_EXTENT_DATA_KEY)
2854 if (key.offset >= new->file_pos + new->len)
2857 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2859 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2860 if (key.offset + num_bytes < new->file_pos)
2863 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2867 extent_offset = btrfs_file_extent_offset(l, extent);
2869 old = kmalloc(sizeof(*old), GFP_NOFS);
2873 offset = max(new->file_pos, key.offset);
2874 end = min(new->file_pos + new->len, key.offset + num_bytes);
2876 old->bytenr = disk_bytenr;
2877 old->extent_offset = extent_offset;
2878 old->offset = offset - key.offset;
2879 old->len = end - offset;
2882 list_add_tail(&old->list, &new->head);
2888 btrfs_free_path(path);
2889 atomic_inc(&fs_info->defrag_running);
2894 btrfs_free_path(path);
2896 free_sa_defrag_extent(new);
2900 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2903 struct btrfs_block_group_cache *cache;
2905 cache = btrfs_lookup_block_group(fs_info, start);
2908 spin_lock(&cache->lock);
2909 cache->delalloc_bytes -= len;
2910 spin_unlock(&cache->lock);
2912 btrfs_put_block_group(cache);
2915 /* as ordered data IO finishes, this gets called so we can finish
2916 * an ordered extent if the range of bytes in the file it covers are
2919 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2921 struct inode *inode = ordered_extent->inode;
2922 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2923 struct btrfs_root *root = BTRFS_I(inode)->root;
2924 struct btrfs_trans_handle *trans = NULL;
2925 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2926 struct extent_state *cached_state = NULL;
2927 struct new_sa_defrag_extent *new = NULL;
2928 int compress_type = 0;
2930 u64 logical_len = ordered_extent->len;
2932 bool truncated = false;
2933 bool range_locked = false;
2934 bool clear_new_delalloc_bytes = false;
2935 bool clear_reserved_extent = true;
2937 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2938 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2939 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2940 clear_new_delalloc_bytes = true;
2942 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2944 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2949 btrfs_free_io_failure_record(BTRFS_I(inode),
2950 ordered_extent->file_offset,
2951 ordered_extent->file_offset +
2952 ordered_extent->len - 1);
2954 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2956 logical_len = ordered_extent->truncated_len;
2957 /* Truncated the entire extent, don't bother adding */
2962 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2963 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2966 * For mwrite(mmap + memset to write) case, we still reserve
2967 * space for NOCOW range.
2968 * As NOCOW won't cause a new delayed ref, just free the space
2970 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2971 ordered_extent->len);
2972 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2974 trans = btrfs_join_transaction_nolock(root);
2976 trans = btrfs_join_transaction(root);
2977 if (IS_ERR(trans)) {
2978 ret = PTR_ERR(trans);
2982 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2983 ret = btrfs_update_inode_fallback(trans, root, inode);
2984 if (ret) /* -ENOMEM or corruption */
2985 btrfs_abort_transaction(trans, ret);
2989 range_locked = true;
2990 lock_extent_bits(io_tree, ordered_extent->file_offset,
2991 ordered_extent->file_offset + ordered_extent->len - 1,
2994 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2995 ordered_extent->file_offset + ordered_extent->len - 1,
2996 EXTENT_DEFRAG, 0, cached_state);
2998 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2999 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3000 /* the inode is shared */
3001 new = record_old_file_extents(inode, ordered_extent);
3003 clear_extent_bit(io_tree, ordered_extent->file_offset,
3004 ordered_extent->file_offset + ordered_extent->len - 1,
3005 EXTENT_DEFRAG, 0, 0, &cached_state);
3009 trans = btrfs_join_transaction_nolock(root);
3011 trans = btrfs_join_transaction(root);
3012 if (IS_ERR(trans)) {
3013 ret = PTR_ERR(trans);
3018 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3020 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3021 compress_type = ordered_extent->compress_type;
3022 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3023 BUG_ON(compress_type);
3024 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3025 ordered_extent->len);
3026 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3027 ordered_extent->file_offset,
3028 ordered_extent->file_offset +
3031 BUG_ON(root == fs_info->tree_root);
3032 ret = insert_reserved_file_extent(trans, inode,
3033 ordered_extent->file_offset,
3034 ordered_extent->start,
3035 ordered_extent->disk_len,
3036 logical_len, logical_len,
3037 compress_type, 0, 0,
3038 BTRFS_FILE_EXTENT_REG);
3040 clear_reserved_extent = false;
3041 btrfs_release_delalloc_bytes(fs_info,
3042 ordered_extent->start,
3043 ordered_extent->disk_len);
3046 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3047 ordered_extent->file_offset, ordered_extent->len,
3050 btrfs_abort_transaction(trans, ret);
3054 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3056 btrfs_abort_transaction(trans, ret);
3060 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3061 ret = btrfs_update_inode_fallback(trans, root, inode);
3062 if (ret) { /* -ENOMEM or corruption */
3063 btrfs_abort_transaction(trans, ret);
3068 if (range_locked || clear_new_delalloc_bytes) {
3069 unsigned int clear_bits = 0;
3072 clear_bits |= EXTENT_LOCKED;
3073 if (clear_new_delalloc_bytes)
3074 clear_bits |= EXTENT_DELALLOC_NEW;
3075 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3076 ordered_extent->file_offset,
3077 ordered_extent->file_offset +
3078 ordered_extent->len - 1,
3080 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3085 btrfs_end_transaction(trans);
3087 if (ret || truncated) {
3091 start = ordered_extent->file_offset + logical_len;
3093 start = ordered_extent->file_offset;
3094 end = ordered_extent->file_offset + ordered_extent->len - 1;
3095 clear_extent_uptodate(io_tree, start, end, NULL);
3097 /* Drop the cache for the part of the extent we didn't write. */
3098 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3101 * If the ordered extent had an IOERR or something else went
3102 * wrong we need to return the space for this ordered extent
3103 * back to the allocator. We only free the extent in the
3104 * truncated case if we didn't write out the extent at all.
3106 * If we made it past insert_reserved_file_extent before we
3107 * errored out then we don't need to do this as the accounting
3108 * has already been done.
3110 if ((ret || !logical_len) &&
3111 clear_reserved_extent &&
3112 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3113 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3114 btrfs_free_reserved_extent(fs_info,
3115 ordered_extent->start,
3116 ordered_extent->disk_len, 1);
3121 * This needs to be done to make sure anybody waiting knows we are done
3122 * updating everything for this ordered extent.
3124 btrfs_remove_ordered_extent(inode, ordered_extent);
3126 /* for snapshot-aware defrag */
3129 free_sa_defrag_extent(new);
3130 atomic_dec(&fs_info->defrag_running);
3132 relink_file_extents(new);
3137 btrfs_put_ordered_extent(ordered_extent);
3138 /* once for the tree */
3139 btrfs_put_ordered_extent(ordered_extent);
3144 static void finish_ordered_fn(struct btrfs_work *work)
3146 struct btrfs_ordered_extent *ordered_extent;
3147 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3148 btrfs_finish_ordered_io(ordered_extent);
3151 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3152 u64 end, int uptodate)
3154 struct inode *inode = page->mapping->host;
3155 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3156 struct btrfs_ordered_extent *ordered_extent = NULL;
3157 struct btrfs_workqueue *wq;
3158 btrfs_work_func_t func;
3160 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3162 ClearPagePrivate2(page);
3163 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3164 end - start + 1, uptodate))
3167 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3168 wq = fs_info->endio_freespace_worker;
3169 func = btrfs_freespace_write_helper;
3171 wq = fs_info->endio_write_workers;
3172 func = btrfs_endio_write_helper;
3175 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3177 btrfs_queue_work(wq, &ordered_extent->work);
3180 static int __readpage_endio_check(struct inode *inode,
3181 struct btrfs_io_bio *io_bio,
3182 int icsum, struct page *page,
3183 int pgoff, u64 start, size_t len)
3189 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3191 kaddr = kmap_atomic(page);
3192 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3193 btrfs_csum_final(csum, (u8 *)&csum);
3194 if (csum != csum_expected)
3197 kunmap_atomic(kaddr);
3200 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3201 io_bio->mirror_num);
3202 memset(kaddr + pgoff, 1, len);
3203 flush_dcache_page(page);
3204 kunmap_atomic(kaddr);
3209 * when reads are done, we need to check csums to verify the data is correct
3210 * if there's a match, we allow the bio to finish. If not, the code in
3211 * extent_io.c will try to find good copies for us.
3213 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3214 u64 phy_offset, struct page *page,
3215 u64 start, u64 end, int mirror)
3217 size_t offset = start - page_offset(page);
3218 struct inode *inode = page->mapping->host;
3219 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3220 struct btrfs_root *root = BTRFS_I(inode)->root;
3222 if (PageChecked(page)) {
3223 ClearPageChecked(page);
3227 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3230 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3231 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3232 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3236 phy_offset >>= inode->i_sb->s_blocksize_bits;
3237 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3238 start, (size_t)(end - start + 1));
3242 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3244 * @inode: The inode we want to perform iput on
3246 * This function uses the generic vfs_inode::i_count to track whether we should
3247 * just decrement it (in case it's > 1) or if this is the last iput then link
3248 * the inode to the delayed iput machinery. Delayed iputs are processed at
3249 * transaction commit time/superblock commit/cleaner kthread.
3251 void btrfs_add_delayed_iput(struct inode *inode)
3253 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3254 struct btrfs_inode *binode = BTRFS_I(inode);
3256 if (atomic_add_unless(&inode->i_count, -1, 1))
3259 atomic_inc(&fs_info->nr_delayed_iputs);
3260 spin_lock(&fs_info->delayed_iput_lock);
3261 ASSERT(list_empty(&binode->delayed_iput));
3262 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3263 spin_unlock(&fs_info->delayed_iput_lock);
3264 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3265 wake_up_process(fs_info->cleaner_kthread);
3268 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3271 spin_lock(&fs_info->delayed_iput_lock);
3272 while (!list_empty(&fs_info->delayed_iputs)) {
3273 struct btrfs_inode *inode;
3275 inode = list_first_entry(&fs_info->delayed_iputs,
3276 struct btrfs_inode, delayed_iput);
3277 list_del_init(&inode->delayed_iput);
3278 spin_unlock(&fs_info->delayed_iput_lock);
3279 iput(&inode->vfs_inode);
3280 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3281 wake_up(&fs_info->delayed_iputs_wait);
3282 spin_lock(&fs_info->delayed_iput_lock);
3284 spin_unlock(&fs_info->delayed_iput_lock);
3288 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3289 * @fs_info - the fs_info for this fs
3290 * @return - EINTR if we were killed, 0 if nothing's pending
3292 * This will wait on any delayed iputs that are currently running with KILLABLE
3293 * set. Once they are all done running we will return, unless we are killed in
3294 * which case we return EINTR. This helps in user operations like fallocate etc
3295 * that might get blocked on the iputs.
3297 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3299 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3300 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3307 * This creates an orphan entry for the given inode in case something goes wrong
3308 * in the middle of an unlink.
3310 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3311 struct btrfs_inode *inode)
3315 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3316 if (ret && ret != -EEXIST) {
3317 btrfs_abort_transaction(trans, ret);
3325 * We have done the delete so we can go ahead and remove the orphan item for
3326 * this particular inode.
3328 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3329 struct btrfs_inode *inode)
3331 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3335 * this cleans up any orphans that may be left on the list from the last use
3338 int btrfs_orphan_cleanup(struct btrfs_root *root)
3340 struct btrfs_fs_info *fs_info = root->fs_info;
3341 struct btrfs_path *path;
3342 struct extent_buffer *leaf;
3343 struct btrfs_key key, found_key;
3344 struct btrfs_trans_handle *trans;
3345 struct inode *inode;
3346 u64 last_objectid = 0;
3347 int ret = 0, nr_unlink = 0;
3349 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3352 path = btrfs_alloc_path();
3357 path->reada = READA_BACK;
3359 key.objectid = BTRFS_ORPHAN_OBJECTID;
3360 key.type = BTRFS_ORPHAN_ITEM_KEY;
3361 key.offset = (u64)-1;
3364 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3369 * if ret == 0 means we found what we were searching for, which
3370 * is weird, but possible, so only screw with path if we didn't
3371 * find the key and see if we have stuff that matches
3375 if (path->slots[0] == 0)
3380 /* pull out the item */
3381 leaf = path->nodes[0];
3382 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3384 /* make sure the item matches what we want */
3385 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3387 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3390 /* release the path since we're done with it */
3391 btrfs_release_path(path);
3394 * this is where we are basically btrfs_lookup, without the
3395 * crossing root thing. we store the inode number in the
3396 * offset of the orphan item.
3399 if (found_key.offset == last_objectid) {
3401 "Error removing orphan entry, stopping orphan cleanup");
3406 last_objectid = found_key.offset;
3408 found_key.objectid = found_key.offset;
3409 found_key.type = BTRFS_INODE_ITEM_KEY;
3410 found_key.offset = 0;
3411 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3412 ret = PTR_ERR_OR_ZERO(inode);
3413 if (ret && ret != -ENOENT)
3416 if (ret == -ENOENT && root == fs_info->tree_root) {
3417 struct btrfs_root *dead_root;
3418 struct btrfs_fs_info *fs_info = root->fs_info;
3419 int is_dead_root = 0;
3422 * this is an orphan in the tree root. Currently these
3423 * could come from 2 sources:
3424 * a) a snapshot deletion in progress
3425 * b) a free space cache inode
3426 * We need to distinguish those two, as the snapshot
3427 * orphan must not get deleted.
3428 * find_dead_roots already ran before us, so if this
3429 * is a snapshot deletion, we should find the root
3430 * in the dead_roots list
3432 spin_lock(&fs_info->trans_lock);
3433 list_for_each_entry(dead_root, &fs_info->dead_roots,
3435 if (dead_root->root_key.objectid ==
3436 found_key.objectid) {
3441 spin_unlock(&fs_info->trans_lock);
3443 /* prevent this orphan from being found again */
3444 key.offset = found_key.objectid - 1;
3451 * If we have an inode with links, there are a couple of
3452 * possibilities. Old kernels (before v3.12) used to create an
3453 * orphan item for truncate indicating that there were possibly
3454 * extent items past i_size that needed to be deleted. In v3.12,
3455 * truncate was changed to update i_size in sync with the extent
3456 * items, but the (useless) orphan item was still created. Since
3457 * v4.18, we don't create the orphan item for truncate at all.
3459 * So, this item could mean that we need to do a truncate, but
3460 * only if this filesystem was last used on a pre-v3.12 kernel
3461 * and was not cleanly unmounted. The odds of that are quite
3462 * slim, and it's a pain to do the truncate now, so just delete
3465 * It's also possible that this orphan item was supposed to be
3466 * deleted but wasn't. The inode number may have been reused,
3467 * but either way, we can delete the orphan item.
3469 if (ret == -ENOENT || inode->i_nlink) {
3472 trans = btrfs_start_transaction(root, 1);
3473 if (IS_ERR(trans)) {
3474 ret = PTR_ERR(trans);
3477 btrfs_debug(fs_info, "auto deleting %Lu",
3478 found_key.objectid);
3479 ret = btrfs_del_orphan_item(trans, root,
3480 found_key.objectid);
3481 btrfs_end_transaction(trans);
3489 /* this will do delete_inode and everything for us */
3492 /* release the path since we're done with it */
3493 btrfs_release_path(path);
3495 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3497 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3498 trans = btrfs_join_transaction(root);
3500 btrfs_end_transaction(trans);
3504 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3508 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3509 btrfs_free_path(path);
3514 * very simple check to peek ahead in the leaf looking for xattrs. If we
3515 * don't find any xattrs, we know there can't be any acls.
3517 * slot is the slot the inode is in, objectid is the objectid of the inode
3519 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3520 int slot, u64 objectid,
3521 int *first_xattr_slot)
3523 u32 nritems = btrfs_header_nritems(leaf);
3524 struct btrfs_key found_key;
3525 static u64 xattr_access = 0;
3526 static u64 xattr_default = 0;
3529 if (!xattr_access) {
3530 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3531 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3532 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3533 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3537 *first_xattr_slot = -1;
3538 while (slot < nritems) {
3539 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3541 /* we found a different objectid, there must not be acls */
3542 if (found_key.objectid != objectid)
3545 /* we found an xattr, assume we've got an acl */
3546 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3547 if (*first_xattr_slot == -1)
3548 *first_xattr_slot = slot;
3549 if (found_key.offset == xattr_access ||
3550 found_key.offset == xattr_default)
3555 * we found a key greater than an xattr key, there can't
3556 * be any acls later on
3558 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3565 * it goes inode, inode backrefs, xattrs, extents,
3566 * so if there are a ton of hard links to an inode there can
3567 * be a lot of backrefs. Don't waste time searching too hard,
3568 * this is just an optimization
3573 /* we hit the end of the leaf before we found an xattr or
3574 * something larger than an xattr. We have to assume the inode
3577 if (*first_xattr_slot == -1)
3578 *first_xattr_slot = slot;
3583 * read an inode from the btree into the in-memory inode
3585 static int btrfs_read_locked_inode(struct inode *inode,
3586 struct btrfs_path *in_path)
3588 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3589 struct btrfs_path *path = in_path;
3590 struct extent_buffer *leaf;
3591 struct btrfs_inode_item *inode_item;
3592 struct btrfs_root *root = BTRFS_I(inode)->root;
3593 struct btrfs_key location;
3598 bool filled = false;
3599 int first_xattr_slot;
3601 ret = btrfs_fill_inode(inode, &rdev);
3606 path = btrfs_alloc_path();
3611 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3613 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3615 if (path != in_path)
3616 btrfs_free_path(path);
3620 leaf = path->nodes[0];
3625 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3626 struct btrfs_inode_item);
3627 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3628 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3629 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3630 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3631 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3633 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3634 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3636 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3637 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3639 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3640 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3642 BTRFS_I(inode)->i_otime.tv_sec =
3643 btrfs_timespec_sec(leaf, &inode_item->otime);
3644 BTRFS_I(inode)->i_otime.tv_nsec =
3645 btrfs_timespec_nsec(leaf, &inode_item->otime);
3647 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3648 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3649 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3651 inode_set_iversion_queried(inode,
3652 btrfs_inode_sequence(leaf, inode_item));
3653 inode->i_generation = BTRFS_I(inode)->generation;
3655 rdev = btrfs_inode_rdev(leaf, inode_item);
3657 BTRFS_I(inode)->index_cnt = (u64)-1;
3658 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3662 * If we were modified in the current generation and evicted from memory
3663 * and then re-read we need to do a full sync since we don't have any
3664 * idea about which extents were modified before we were evicted from
3667 * This is required for both inode re-read from disk and delayed inode
3668 * in delayed_nodes_tree.
3670 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3671 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3672 &BTRFS_I(inode)->runtime_flags);
3675 * We don't persist the id of the transaction where an unlink operation
3676 * against the inode was last made. So here we assume the inode might
3677 * have been evicted, and therefore the exact value of last_unlink_trans
3678 * lost, and set it to last_trans to avoid metadata inconsistencies
3679 * between the inode and its parent if the inode is fsync'ed and the log
3680 * replayed. For example, in the scenario:
3683 * ln mydir/foo mydir/bar
3686 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3687 * xfs_io -c fsync mydir/foo
3689 * mount fs, triggers fsync log replay
3691 * We must make sure that when we fsync our inode foo we also log its
3692 * parent inode, otherwise after log replay the parent still has the
3693 * dentry with the "bar" name but our inode foo has a link count of 1
3694 * and doesn't have an inode ref with the name "bar" anymore.
3696 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3697 * but it guarantees correctness at the expense of occasional full
3698 * transaction commits on fsync if our inode is a directory, or if our
3699 * inode is not a directory, logging its parent unnecessarily.
3701 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3703 * Similar reasoning for last_link_trans, needs to be set otherwise
3704 * for a case like the following:
3709 * echo 2 > /proc/sys/vm/drop_caches
3713 * Would result in link bar and directory A not existing after the power
3716 BTRFS_I(inode)->last_link_trans = BTRFS_I(inode)->last_trans;
3719 if (inode->i_nlink != 1 ||
3720 path->slots[0] >= btrfs_header_nritems(leaf))
3723 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3724 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3727 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3728 if (location.type == BTRFS_INODE_REF_KEY) {
3729 struct btrfs_inode_ref *ref;
3731 ref = (struct btrfs_inode_ref *)ptr;
3732 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3733 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3734 struct btrfs_inode_extref *extref;
3736 extref = (struct btrfs_inode_extref *)ptr;
3737 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3742 * try to precache a NULL acl entry for files that don't have
3743 * any xattrs or acls
3745 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3746 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3747 if (first_xattr_slot != -1) {
3748 path->slots[0] = first_xattr_slot;
3749 ret = btrfs_load_inode_props(inode, path);
3752 "error loading props for ino %llu (root %llu): %d",
3753 btrfs_ino(BTRFS_I(inode)),
3754 root->root_key.objectid, ret);
3756 if (path != in_path)
3757 btrfs_free_path(path);
3760 cache_no_acl(inode);
3762 switch (inode->i_mode & S_IFMT) {
3764 inode->i_mapping->a_ops = &btrfs_aops;
3765 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3766 inode->i_fop = &btrfs_file_operations;
3767 inode->i_op = &btrfs_file_inode_operations;
3770 inode->i_fop = &btrfs_dir_file_operations;
3771 inode->i_op = &btrfs_dir_inode_operations;
3774 inode->i_op = &btrfs_symlink_inode_operations;
3775 inode_nohighmem(inode);
3776 inode->i_mapping->a_ops = &btrfs_aops;
3779 inode->i_op = &btrfs_special_inode_operations;
3780 init_special_inode(inode, inode->i_mode, rdev);
3784 btrfs_sync_inode_flags_to_i_flags(inode);
3789 * given a leaf and an inode, copy the inode fields into the leaf
3791 static void fill_inode_item(struct btrfs_trans_handle *trans,
3792 struct extent_buffer *leaf,
3793 struct btrfs_inode_item *item,
3794 struct inode *inode)
3796 struct btrfs_map_token token;
3798 btrfs_init_map_token(&token);
3800 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3801 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3802 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3804 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3805 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3807 btrfs_set_token_timespec_sec(leaf, &item->atime,
3808 inode->i_atime.tv_sec, &token);
3809 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3810 inode->i_atime.tv_nsec, &token);
3812 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3813 inode->i_mtime.tv_sec, &token);
3814 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3815 inode->i_mtime.tv_nsec, &token);
3817 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3818 inode->i_ctime.tv_sec, &token);
3819 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3820 inode->i_ctime.tv_nsec, &token);
3822 btrfs_set_token_timespec_sec(leaf, &item->otime,
3823 BTRFS_I(inode)->i_otime.tv_sec, &token);
3824 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3825 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3827 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3829 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3831 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3833 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3834 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3835 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3836 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3840 * copy everything in the in-memory inode into the btree.
3842 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3843 struct btrfs_root *root, struct inode *inode)
3845 struct btrfs_inode_item *inode_item;
3846 struct btrfs_path *path;
3847 struct extent_buffer *leaf;
3850 path = btrfs_alloc_path();
3854 path->leave_spinning = 1;
3855 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3863 leaf = path->nodes[0];
3864 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3865 struct btrfs_inode_item);
3867 fill_inode_item(trans, leaf, inode_item, inode);
3868 btrfs_mark_buffer_dirty(leaf);
3869 btrfs_set_inode_last_trans(trans, inode);
3872 btrfs_free_path(path);
3877 * copy everything in the in-memory inode into the btree.
3879 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3880 struct btrfs_root *root, struct inode *inode)
3882 struct btrfs_fs_info *fs_info = root->fs_info;
3886 * If the inode is a free space inode, we can deadlock during commit
3887 * if we put it into the delayed code.
3889 * The data relocation inode should also be directly updated
3892 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3893 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3894 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3895 btrfs_update_root_times(trans, root);
3897 ret = btrfs_delayed_update_inode(trans, root, inode);
3899 btrfs_set_inode_last_trans(trans, inode);
3903 return btrfs_update_inode_item(trans, root, inode);
3906 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3907 struct btrfs_root *root,
3908 struct inode *inode)
3912 ret = btrfs_update_inode(trans, root, inode);
3914 return btrfs_update_inode_item(trans, root, inode);
3919 * unlink helper that gets used here in inode.c and in the tree logging
3920 * recovery code. It remove a link in a directory with a given name, and
3921 * also drops the back refs in the inode to the directory
3923 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3924 struct btrfs_root *root,
3925 struct btrfs_inode *dir,
3926 struct btrfs_inode *inode,
3927 const char *name, int name_len)
3929 struct btrfs_fs_info *fs_info = root->fs_info;
3930 struct btrfs_path *path;
3932 struct extent_buffer *leaf;
3933 struct btrfs_dir_item *di;
3934 struct btrfs_key key;
3936 u64 ino = btrfs_ino(inode);
3937 u64 dir_ino = btrfs_ino(dir);
3939 path = btrfs_alloc_path();
3945 path->leave_spinning = 1;
3946 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3947 name, name_len, -1);
3948 if (IS_ERR_OR_NULL(di)) {
3949 ret = di ? PTR_ERR(di) : -ENOENT;
3952 leaf = path->nodes[0];
3953 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3954 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3957 btrfs_release_path(path);
3960 * If we don't have dir index, we have to get it by looking up
3961 * the inode ref, since we get the inode ref, remove it directly,
3962 * it is unnecessary to do delayed deletion.
3964 * But if we have dir index, needn't search inode ref to get it.
3965 * Since the inode ref is close to the inode item, it is better
3966 * that we delay to delete it, and just do this deletion when
3967 * we update the inode item.
3969 if (inode->dir_index) {
3970 ret = btrfs_delayed_delete_inode_ref(inode);
3972 index = inode->dir_index;
3977 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3981 "failed to delete reference to %.*s, inode %llu parent %llu",
3982 name_len, name, ino, dir_ino);
3983 btrfs_abort_transaction(trans, ret);
3987 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3989 btrfs_abort_transaction(trans, ret);
3993 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3995 if (ret != 0 && ret != -ENOENT) {
3996 btrfs_abort_transaction(trans, ret);
4000 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4005 btrfs_abort_transaction(trans, ret);
4007 btrfs_free_path(path);
4011 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4012 inode_inc_iversion(&inode->vfs_inode);
4013 inode_inc_iversion(&dir->vfs_inode);
4014 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4015 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4016 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4021 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4022 struct btrfs_root *root,
4023 struct btrfs_inode *dir, struct btrfs_inode *inode,
4024 const char *name, int name_len)
4027 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4029 drop_nlink(&inode->vfs_inode);
4030 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4036 * helper to start transaction for unlink and rmdir.
4038 * unlink and rmdir are special in btrfs, they do not always free space, so
4039 * if we cannot make our reservations the normal way try and see if there is
4040 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4041 * allow the unlink to occur.
4043 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4045 struct btrfs_root *root = BTRFS_I(dir)->root;
4048 * 1 for the possible orphan item
4049 * 1 for the dir item
4050 * 1 for the dir index
4051 * 1 for the inode ref
4054 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4057 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4059 struct btrfs_root *root = BTRFS_I(dir)->root;
4060 struct btrfs_trans_handle *trans;
4061 struct inode *inode = d_inode(dentry);
4064 trans = __unlink_start_trans(dir);
4066 return PTR_ERR(trans);
4068 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4071 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4072 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4073 dentry->d_name.len);
4077 if (inode->i_nlink == 0) {
4078 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4084 btrfs_end_transaction(trans);
4085 btrfs_btree_balance_dirty(root->fs_info);
4089 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4090 struct inode *dir, u64 objectid,
4091 const char *name, int name_len)
4093 struct btrfs_root *root = BTRFS_I(dir)->root;
4094 struct btrfs_path *path;
4095 struct extent_buffer *leaf;
4096 struct btrfs_dir_item *di;
4097 struct btrfs_key key;
4100 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4102 path = btrfs_alloc_path();
4106 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4107 name, name_len, -1);
4108 if (IS_ERR_OR_NULL(di)) {
4109 ret = di ? PTR_ERR(di) : -ENOENT;
4113 leaf = path->nodes[0];
4114 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4115 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4116 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4118 btrfs_abort_transaction(trans, ret);
4121 btrfs_release_path(path);
4123 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4124 dir_ino, &index, name, name_len);
4126 if (ret != -ENOENT) {
4127 btrfs_abort_transaction(trans, ret);
4130 di = btrfs_search_dir_index_item(root, path, dir_ino,
4132 if (IS_ERR_OR_NULL(di)) {
4137 btrfs_abort_transaction(trans, ret);
4141 leaf = path->nodes[0];
4142 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4145 btrfs_release_path(path);
4147 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4149 btrfs_abort_transaction(trans, ret);
4153 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4154 inode_inc_iversion(dir);
4155 dir->i_mtime = dir->i_ctime = current_time(dir);
4156 ret = btrfs_update_inode_fallback(trans, root, dir);
4158 btrfs_abort_transaction(trans, ret);
4160 btrfs_free_path(path);
4165 * Helper to check if the subvolume references other subvolumes or if it's
4168 static noinline int may_destroy_subvol(struct btrfs_root *root)
4170 struct btrfs_fs_info *fs_info = root->fs_info;
4171 struct btrfs_path *path;
4172 struct btrfs_dir_item *di;
4173 struct btrfs_key key;
4177 path = btrfs_alloc_path();
4181 /* Make sure this root isn't set as the default subvol */
4182 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4183 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4184 dir_id, "default", 7, 0);
4185 if (di && !IS_ERR(di)) {
4186 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4187 if (key.objectid == root->root_key.objectid) {
4190 "deleting default subvolume %llu is not allowed",
4194 btrfs_release_path(path);
4197 key.objectid = root->root_key.objectid;
4198 key.type = BTRFS_ROOT_REF_KEY;
4199 key.offset = (u64)-1;
4201 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4207 if (path->slots[0] > 0) {
4209 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4210 if (key.objectid == root->root_key.objectid &&
4211 key.type == BTRFS_ROOT_REF_KEY)
4215 btrfs_free_path(path);
4219 /* Delete all dentries for inodes belonging to the root */
4220 static void btrfs_prune_dentries(struct btrfs_root *root)
4222 struct btrfs_fs_info *fs_info = root->fs_info;
4223 struct rb_node *node;
4224 struct rb_node *prev;
4225 struct btrfs_inode *entry;
4226 struct inode *inode;
4229 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4230 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4232 spin_lock(&root->inode_lock);
4234 node = root->inode_tree.rb_node;
4238 entry = rb_entry(node, struct btrfs_inode, rb_node);
4240 if (objectid < btrfs_ino(entry))
4241 node = node->rb_left;
4242 else if (objectid > btrfs_ino(entry))
4243 node = node->rb_right;
4249 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4250 if (objectid <= btrfs_ino(entry)) {
4254 prev = rb_next(prev);
4258 entry = rb_entry(node, struct btrfs_inode, rb_node);
4259 objectid = btrfs_ino(entry) + 1;
4260 inode = igrab(&entry->vfs_inode);
4262 spin_unlock(&root->inode_lock);
4263 if (atomic_read(&inode->i_count) > 1)
4264 d_prune_aliases(inode);
4266 * btrfs_drop_inode will have it removed from the inode
4267 * cache when its usage count hits zero.
4271 spin_lock(&root->inode_lock);
4275 if (cond_resched_lock(&root->inode_lock))
4278 node = rb_next(node);
4280 spin_unlock(&root->inode_lock);
4283 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4285 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4286 struct btrfs_root *root = BTRFS_I(dir)->root;
4287 struct inode *inode = d_inode(dentry);
4288 struct btrfs_root *dest = BTRFS_I(inode)->root;
4289 struct btrfs_trans_handle *trans;
4290 struct btrfs_block_rsv block_rsv;
4296 * Don't allow to delete a subvolume with send in progress. This is
4297 * inside the inode lock so the error handling that has to drop the bit
4298 * again is not run concurrently.
4300 spin_lock(&dest->root_item_lock);
4301 if (dest->send_in_progress) {
4302 spin_unlock(&dest->root_item_lock);
4304 "attempt to delete subvolume %llu during send",
4305 dest->root_key.objectid);
4308 root_flags = btrfs_root_flags(&dest->root_item);
4309 btrfs_set_root_flags(&dest->root_item,
4310 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4311 spin_unlock(&dest->root_item_lock);
4313 down_write(&fs_info->subvol_sem);
4315 err = may_destroy_subvol(dest);
4319 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4321 * One for dir inode,
4322 * two for dir entries,
4323 * two for root ref/backref.
4325 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4329 trans = btrfs_start_transaction(root, 0);
4330 if (IS_ERR(trans)) {
4331 err = PTR_ERR(trans);
4334 trans->block_rsv = &block_rsv;
4335 trans->bytes_reserved = block_rsv.size;
4337 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4339 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4340 dentry->d_name.name, dentry->d_name.len);
4343 btrfs_abort_transaction(trans, ret);
4347 btrfs_record_root_in_trans(trans, dest);
4349 memset(&dest->root_item.drop_progress, 0,
4350 sizeof(dest->root_item.drop_progress));
4351 dest->root_item.drop_level = 0;
4352 btrfs_set_root_refs(&dest->root_item, 0);
4354 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4355 ret = btrfs_insert_orphan_item(trans,
4357 dest->root_key.objectid);
4359 btrfs_abort_transaction(trans, ret);
4365 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4366 BTRFS_UUID_KEY_SUBVOL,
4367 dest->root_key.objectid);
4368 if (ret && ret != -ENOENT) {
4369 btrfs_abort_transaction(trans, ret);
4373 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4374 ret = btrfs_uuid_tree_remove(trans,
4375 dest->root_item.received_uuid,
4376 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4377 dest->root_key.objectid);
4378 if (ret && ret != -ENOENT) {
4379 btrfs_abort_transaction(trans, ret);
4386 trans->block_rsv = NULL;
4387 trans->bytes_reserved = 0;
4388 ret = btrfs_end_transaction(trans);
4391 inode->i_flags |= S_DEAD;
4393 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4395 up_write(&fs_info->subvol_sem);
4397 spin_lock(&dest->root_item_lock);
4398 root_flags = btrfs_root_flags(&dest->root_item);
4399 btrfs_set_root_flags(&dest->root_item,
4400 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4401 spin_unlock(&dest->root_item_lock);
4403 d_invalidate(dentry);
4404 btrfs_prune_dentries(dest);
4405 ASSERT(dest->send_in_progress == 0);
4408 if (dest->ino_cache_inode) {
4409 iput(dest->ino_cache_inode);
4410 dest->ino_cache_inode = NULL;
4417 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4419 struct inode *inode = d_inode(dentry);
4421 struct btrfs_root *root = BTRFS_I(dir)->root;
4422 struct btrfs_trans_handle *trans;
4423 u64 last_unlink_trans;
4425 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4427 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4428 return btrfs_delete_subvolume(dir, dentry);
4430 trans = __unlink_start_trans(dir);
4432 return PTR_ERR(trans);
4434 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4435 err = btrfs_unlink_subvol(trans, dir,
4436 BTRFS_I(inode)->location.objectid,
4437 dentry->d_name.name,
4438 dentry->d_name.len);
4442 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4446 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4448 /* now the directory is empty */
4449 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4450 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4451 dentry->d_name.len);
4453 btrfs_i_size_write(BTRFS_I(inode), 0);
4455 * Propagate the last_unlink_trans value of the deleted dir to
4456 * its parent directory. This is to prevent an unrecoverable
4457 * log tree in the case we do something like this:
4459 * 2) create snapshot under dir foo
4460 * 3) delete the snapshot
4463 * 6) fsync foo or some file inside foo
4465 if (last_unlink_trans >= trans->transid)
4466 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4469 btrfs_end_transaction(trans);
4470 btrfs_btree_balance_dirty(root->fs_info);
4476 * Return this if we need to call truncate_block for the last bit of the
4479 #define NEED_TRUNCATE_BLOCK 1
4482 * this can truncate away extent items, csum items and directory items.
4483 * It starts at a high offset and removes keys until it can't find
4484 * any higher than new_size
4486 * csum items that cross the new i_size are truncated to the new size
4489 * min_type is the minimum key type to truncate down to. If set to 0, this
4490 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4492 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4493 struct btrfs_root *root,
4494 struct inode *inode,
4495 u64 new_size, u32 min_type)
4497 struct btrfs_fs_info *fs_info = root->fs_info;
4498 struct btrfs_path *path;
4499 struct extent_buffer *leaf;
4500 struct btrfs_file_extent_item *fi;
4501 struct btrfs_key key;
4502 struct btrfs_key found_key;
4503 u64 extent_start = 0;
4504 u64 extent_num_bytes = 0;
4505 u64 extent_offset = 0;
4507 u64 last_size = new_size;
4508 u32 found_type = (u8)-1;
4511 int pending_del_nr = 0;
4512 int pending_del_slot = 0;
4513 int extent_type = -1;
4515 u64 ino = btrfs_ino(BTRFS_I(inode));
4516 u64 bytes_deleted = 0;
4517 bool be_nice = false;
4518 bool should_throttle = false;
4520 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4523 * for non-free space inodes and ref cows, we want to back off from
4526 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4527 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4530 path = btrfs_alloc_path();
4533 path->reada = READA_BACK;
4536 * We want to drop from the next block forward in case this new size is
4537 * not block aligned since we will be keeping the last block of the
4538 * extent just the way it is.
4540 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4541 root == fs_info->tree_root)
4542 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4543 fs_info->sectorsize),
4547 * This function is also used to drop the items in the log tree before
4548 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4549 * it is used to drop the logged items. So we shouldn't kill the delayed
4552 if (min_type == 0 && root == BTRFS_I(inode)->root)
4553 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4556 key.offset = (u64)-1;
4561 * with a 16K leaf size and 128MB extents, you can actually queue
4562 * up a huge file in a single leaf. Most of the time that
4563 * bytes_deleted is > 0, it will be huge by the time we get here
4565 if (be_nice && bytes_deleted > SZ_32M &&
4566 btrfs_should_end_transaction(trans)) {
4571 path->leave_spinning = 1;
4572 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4578 /* there are no items in the tree for us to truncate, we're
4581 if (path->slots[0] == 0)
4588 leaf = path->nodes[0];
4589 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4590 found_type = found_key.type;
4592 if (found_key.objectid != ino)
4595 if (found_type < min_type)
4598 item_end = found_key.offset;
4599 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4600 fi = btrfs_item_ptr(leaf, path->slots[0],
4601 struct btrfs_file_extent_item);
4602 extent_type = btrfs_file_extent_type(leaf, fi);
4603 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4605 btrfs_file_extent_num_bytes(leaf, fi);
4607 trace_btrfs_truncate_show_fi_regular(
4608 BTRFS_I(inode), leaf, fi,
4610 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4611 item_end += btrfs_file_extent_ram_bytes(leaf,
4614 trace_btrfs_truncate_show_fi_inline(
4615 BTRFS_I(inode), leaf, fi, path->slots[0],
4620 if (found_type > min_type) {
4623 if (item_end < new_size)
4625 if (found_key.offset >= new_size)
4631 /* FIXME, shrink the extent if the ref count is only 1 */
4632 if (found_type != BTRFS_EXTENT_DATA_KEY)
4635 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4637 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4639 u64 orig_num_bytes =
4640 btrfs_file_extent_num_bytes(leaf, fi);
4641 extent_num_bytes = ALIGN(new_size -
4643 fs_info->sectorsize);
4644 btrfs_set_file_extent_num_bytes(leaf, fi,
4646 num_dec = (orig_num_bytes -
4648 if (test_bit(BTRFS_ROOT_REF_COWS,
4651 inode_sub_bytes(inode, num_dec);
4652 btrfs_mark_buffer_dirty(leaf);
4655 btrfs_file_extent_disk_num_bytes(leaf,
4657 extent_offset = found_key.offset -
4658 btrfs_file_extent_offset(leaf, fi);
4660 /* FIXME blocksize != 4096 */
4661 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4662 if (extent_start != 0) {
4664 if (test_bit(BTRFS_ROOT_REF_COWS,
4666 inode_sub_bytes(inode, num_dec);
4669 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4671 * we can't truncate inline items that have had
4675 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4676 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4677 btrfs_file_extent_compression(leaf, fi) == 0) {
4678 u32 size = (u32)(new_size - found_key.offset);
4680 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4681 size = btrfs_file_extent_calc_inline_size(size);
4682 btrfs_truncate_item(root->fs_info, path, size, 1);
4683 } else if (!del_item) {
4685 * We have to bail so the last_size is set to
4686 * just before this extent.
4688 ret = NEED_TRUNCATE_BLOCK;
4692 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4693 inode_sub_bytes(inode, item_end + 1 - new_size);
4697 last_size = found_key.offset;
4699 last_size = new_size;
4701 if (!pending_del_nr) {
4702 /* no pending yet, add ourselves */
4703 pending_del_slot = path->slots[0];
4705 } else if (pending_del_nr &&
4706 path->slots[0] + 1 == pending_del_slot) {
4707 /* hop on the pending chunk */
4709 pending_del_slot = path->slots[0];
4716 should_throttle = false;
4719 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4720 root == fs_info->tree_root)) {
4721 btrfs_set_path_blocking(path);
4722 bytes_deleted += extent_num_bytes;
4723 ret = btrfs_free_extent(trans, root, extent_start,
4724 extent_num_bytes, 0,
4725 btrfs_header_owner(leaf),
4726 ino, extent_offset);
4728 btrfs_abort_transaction(trans, ret);
4732 if (btrfs_should_throttle_delayed_refs(trans))
4733 should_throttle = true;
4737 if (found_type == BTRFS_INODE_ITEM_KEY)
4740 if (path->slots[0] == 0 ||
4741 path->slots[0] != pending_del_slot ||
4743 if (pending_del_nr) {
4744 ret = btrfs_del_items(trans, root, path,
4748 btrfs_abort_transaction(trans, ret);
4753 btrfs_release_path(path);
4756 * We can generate a lot of delayed refs, so we need to
4757 * throttle every once and a while and make sure we're
4758 * adding enough space to keep up with the work we are
4759 * generating. Since we hold a transaction here we
4760 * can't flush, and we don't want to FLUSH_LIMIT because
4761 * we could have generated too many delayed refs to
4762 * actually allocate, so just bail if we're short and
4763 * let the normal reservation dance happen higher up.
4765 if (should_throttle) {
4766 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4767 BTRFS_RESERVE_NO_FLUSH);
4779 if (ret >= 0 && pending_del_nr) {
4782 err = btrfs_del_items(trans, root, path, pending_del_slot,
4785 btrfs_abort_transaction(trans, err);
4789 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4790 ASSERT(last_size >= new_size);
4791 if (!ret && last_size > new_size)
4792 last_size = new_size;
4793 btrfs_ordered_update_i_size(inode, last_size, NULL);
4796 btrfs_free_path(path);
4801 * btrfs_truncate_block - read, zero a chunk and write a block
4802 * @inode - inode that we're zeroing
4803 * @from - the offset to start zeroing
4804 * @len - the length to zero, 0 to zero the entire range respective to the
4806 * @front - zero up to the offset instead of from the offset on
4808 * This will find the block for the "from" offset and cow the block and zero the
4809 * part we want to zero. This is used with truncate and hole punching.
4811 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4814 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4815 struct address_space *mapping = inode->i_mapping;
4816 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4817 struct btrfs_ordered_extent *ordered;
4818 struct extent_state *cached_state = NULL;
4819 struct extent_changeset *data_reserved = NULL;
4821 u32 blocksize = fs_info->sectorsize;
4822 pgoff_t index = from >> PAGE_SHIFT;
4823 unsigned offset = from & (blocksize - 1);
4825 gfp_t mask = btrfs_alloc_write_mask(mapping);
4830 if (IS_ALIGNED(offset, blocksize) &&
4831 (!len || IS_ALIGNED(len, blocksize)))
4834 block_start = round_down(from, blocksize);
4835 block_end = block_start + blocksize - 1;
4837 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4838 block_start, blocksize);
4843 page = find_or_create_page(mapping, index, mask);
4845 btrfs_delalloc_release_space(inode, data_reserved,
4846 block_start, blocksize, true);
4847 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4852 if (!PageUptodate(page)) {
4853 ret = btrfs_readpage(NULL, page);
4855 if (page->mapping != mapping) {
4860 if (!PageUptodate(page)) {
4865 wait_on_page_writeback(page);
4867 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4868 set_page_extent_mapped(page);
4870 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4872 unlock_extent_cached(io_tree, block_start, block_end,
4876 btrfs_start_ordered_extent(inode, ordered, 1);
4877 btrfs_put_ordered_extent(ordered);
4881 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4882 EXTENT_DIRTY | EXTENT_DELALLOC |
4883 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4884 0, 0, &cached_state);
4886 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4889 unlock_extent_cached(io_tree, block_start, block_end,
4894 if (offset != blocksize) {
4896 len = blocksize - offset;
4899 memset(kaddr + (block_start - page_offset(page)),
4902 memset(kaddr + (block_start - page_offset(page)) + offset,
4904 flush_dcache_page(page);
4907 ClearPageChecked(page);
4908 set_page_dirty(page);
4909 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4913 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4915 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4919 extent_changeset_free(data_reserved);
4923 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4924 u64 offset, u64 len)
4926 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4927 struct btrfs_trans_handle *trans;
4931 * Still need to make sure the inode looks like it's been updated so
4932 * that any holes get logged if we fsync.
4934 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4935 BTRFS_I(inode)->last_trans = fs_info->generation;
4936 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4937 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4942 * 1 - for the one we're dropping
4943 * 1 - for the one we're adding
4944 * 1 - for updating the inode.
4946 trans = btrfs_start_transaction(root, 3);
4948 return PTR_ERR(trans);
4950 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4952 btrfs_abort_transaction(trans, ret);
4953 btrfs_end_transaction(trans);
4957 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4958 offset, 0, 0, len, 0, len, 0, 0, 0);
4960 btrfs_abort_transaction(trans, ret);
4962 btrfs_update_inode(trans, root, inode);
4963 btrfs_end_transaction(trans);
4968 * This function puts in dummy file extents for the area we're creating a hole
4969 * for. So if we are truncating this file to a larger size we need to insert
4970 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4971 * the range between oldsize and size
4973 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4975 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4976 struct btrfs_root *root = BTRFS_I(inode)->root;
4977 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4978 struct extent_map *em = NULL;
4979 struct extent_state *cached_state = NULL;
4980 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4981 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4982 u64 block_end = ALIGN(size, fs_info->sectorsize);
4989 * If our size started in the middle of a block we need to zero out the
4990 * rest of the block before we expand the i_size, otherwise we could
4991 * expose stale data.
4993 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4997 if (size <= hole_start)
5001 struct btrfs_ordered_extent *ordered;
5003 lock_extent_bits(io_tree, hole_start, block_end - 1,
5005 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5006 block_end - hole_start);
5009 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5011 btrfs_start_ordered_extent(inode, ordered, 1);
5012 btrfs_put_ordered_extent(ordered);
5015 cur_offset = hole_start;
5017 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5018 block_end - cur_offset, 0);
5024 last_byte = min(extent_map_end(em), block_end);
5025 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5026 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5027 struct extent_map *hole_em;
5028 hole_size = last_byte - cur_offset;
5030 err = maybe_insert_hole(root, inode, cur_offset,
5034 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5035 cur_offset + hole_size - 1, 0);
5036 hole_em = alloc_extent_map();
5038 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5039 &BTRFS_I(inode)->runtime_flags);
5042 hole_em->start = cur_offset;
5043 hole_em->len = hole_size;
5044 hole_em->orig_start = cur_offset;
5046 hole_em->block_start = EXTENT_MAP_HOLE;
5047 hole_em->block_len = 0;
5048 hole_em->orig_block_len = 0;
5049 hole_em->ram_bytes = hole_size;
5050 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5051 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5052 hole_em->generation = fs_info->generation;
5055 write_lock(&em_tree->lock);
5056 err = add_extent_mapping(em_tree, hole_em, 1);
5057 write_unlock(&em_tree->lock);
5060 btrfs_drop_extent_cache(BTRFS_I(inode),
5065 free_extent_map(hole_em);
5068 free_extent_map(em);
5070 cur_offset = last_byte;
5071 if (cur_offset >= block_end)
5074 free_extent_map(em);
5075 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5079 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5081 struct btrfs_root *root = BTRFS_I(inode)->root;
5082 struct btrfs_trans_handle *trans;
5083 loff_t oldsize = i_size_read(inode);
5084 loff_t newsize = attr->ia_size;
5085 int mask = attr->ia_valid;
5089 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5090 * special case where we need to update the times despite not having
5091 * these flags set. For all other operations the VFS set these flags
5092 * explicitly if it wants a timestamp update.
5094 if (newsize != oldsize) {
5095 inode_inc_iversion(inode);
5096 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5097 inode->i_ctime = inode->i_mtime =
5098 current_time(inode);
5101 if (newsize > oldsize) {
5103 * Don't do an expanding truncate while snapshotting is ongoing.
5104 * This is to ensure the snapshot captures a fully consistent
5105 * state of this file - if the snapshot captures this expanding
5106 * truncation, it must capture all writes that happened before
5109 btrfs_wait_for_snapshot_creation(root);
5110 ret = btrfs_cont_expand(inode, oldsize, newsize);
5112 btrfs_end_write_no_snapshotting(root);
5116 trans = btrfs_start_transaction(root, 1);
5117 if (IS_ERR(trans)) {
5118 btrfs_end_write_no_snapshotting(root);
5119 return PTR_ERR(trans);
5122 i_size_write(inode, newsize);
5123 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5124 pagecache_isize_extended(inode, oldsize, newsize);
5125 ret = btrfs_update_inode(trans, root, inode);
5126 btrfs_end_write_no_snapshotting(root);
5127 btrfs_end_transaction(trans);
5131 * We're truncating a file that used to have good data down to
5132 * zero. Make sure it gets into the ordered flush list so that
5133 * any new writes get down to disk quickly.
5136 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5137 &BTRFS_I(inode)->runtime_flags);
5139 truncate_setsize(inode, newsize);
5141 /* Disable nonlocked read DIO to avoid the endless truncate */
5142 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5143 inode_dio_wait(inode);
5144 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5146 ret = btrfs_truncate(inode, newsize == oldsize);
5147 if (ret && inode->i_nlink) {
5151 * Truncate failed, so fix up the in-memory size. We
5152 * adjusted disk_i_size down as we removed extents, so
5153 * wait for disk_i_size to be stable and then update the
5154 * in-memory size to match.
5156 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5159 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5166 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5168 struct inode *inode = d_inode(dentry);
5169 struct btrfs_root *root = BTRFS_I(inode)->root;
5172 if (btrfs_root_readonly(root))
5175 err = setattr_prepare(dentry, attr);
5179 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5180 err = btrfs_setsize(inode, attr);
5185 if (attr->ia_valid) {
5186 setattr_copy(inode, attr);
5187 inode_inc_iversion(inode);
5188 err = btrfs_dirty_inode(inode);
5190 if (!err && attr->ia_valid & ATTR_MODE)
5191 err = posix_acl_chmod(inode, inode->i_mode);
5198 * While truncating the inode pages during eviction, we get the VFS calling
5199 * btrfs_invalidatepage() against each page of the inode. This is slow because
5200 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5201 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5202 * extent_state structures over and over, wasting lots of time.
5204 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5205 * those expensive operations on a per page basis and do only the ordered io
5206 * finishing, while we release here the extent_map and extent_state structures,
5207 * without the excessive merging and splitting.
5209 static void evict_inode_truncate_pages(struct inode *inode)
5211 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5212 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5213 struct rb_node *node;
5215 ASSERT(inode->i_state & I_FREEING);
5216 truncate_inode_pages_final(&inode->i_data);
5218 write_lock(&map_tree->lock);
5219 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5220 struct extent_map *em;
5222 node = rb_first_cached(&map_tree->map);
5223 em = rb_entry(node, struct extent_map, rb_node);
5224 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5225 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5226 remove_extent_mapping(map_tree, em);
5227 free_extent_map(em);
5228 if (need_resched()) {
5229 write_unlock(&map_tree->lock);
5231 write_lock(&map_tree->lock);
5234 write_unlock(&map_tree->lock);
5237 * Keep looping until we have no more ranges in the io tree.
5238 * We can have ongoing bios started by readpages (called from readahead)
5239 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5240 * still in progress (unlocked the pages in the bio but did not yet
5241 * unlocked the ranges in the io tree). Therefore this means some
5242 * ranges can still be locked and eviction started because before
5243 * submitting those bios, which are executed by a separate task (work
5244 * queue kthread), inode references (inode->i_count) were not taken
5245 * (which would be dropped in the end io callback of each bio).
5246 * Therefore here we effectively end up waiting for those bios and
5247 * anyone else holding locked ranges without having bumped the inode's
5248 * reference count - if we don't do it, when they access the inode's
5249 * io_tree to unlock a range it may be too late, leading to an
5250 * use-after-free issue.
5252 spin_lock(&io_tree->lock);
5253 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5254 struct extent_state *state;
5255 struct extent_state *cached_state = NULL;
5258 unsigned state_flags;
5260 node = rb_first(&io_tree->state);
5261 state = rb_entry(node, struct extent_state, rb_node);
5262 start = state->start;
5264 state_flags = state->state;
5265 spin_unlock(&io_tree->lock);
5267 lock_extent_bits(io_tree, start, end, &cached_state);
5270 * If still has DELALLOC flag, the extent didn't reach disk,
5271 * and its reserved space won't be freed by delayed_ref.
5272 * So we need to free its reserved space here.
5273 * (Refer to comment in btrfs_invalidatepage, case 2)
5275 * Note, end is the bytenr of last byte, so we need + 1 here.
5277 if (state_flags & EXTENT_DELALLOC)
5278 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5280 clear_extent_bit(io_tree, start, end,
5281 EXTENT_LOCKED | EXTENT_DIRTY |
5282 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5283 EXTENT_DEFRAG, 1, 1, &cached_state);
5286 spin_lock(&io_tree->lock);
5288 spin_unlock(&io_tree->lock);
5291 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5292 struct btrfs_block_rsv *rsv)
5294 struct btrfs_fs_info *fs_info = root->fs_info;
5295 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5296 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5300 struct btrfs_trans_handle *trans;
5303 ret = btrfs_block_rsv_refill(root, rsv,
5304 rsv->size + delayed_refs_extra,
5305 BTRFS_RESERVE_FLUSH_LIMIT);
5307 if (ret && ++failures > 2) {
5309 "could not allocate space for a delete; will truncate on mount");
5310 return ERR_PTR(-ENOSPC);
5314 * Evict can generate a large amount of delayed refs without
5315 * having a way to add space back since we exhaust our temporary
5316 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5317 * because we could deadlock with so many things in the flushing
5318 * code, so we have to try and hold some extra space to
5319 * compensate for our delayed ref generation. If we can't get
5320 * that space then we need see if we can steal our minimum from
5321 * the global reserve. We will be ratelimited by the amount of
5322 * space we have for the delayed refs rsv, so we'll end up
5323 * committing and trying again.
5325 trans = btrfs_join_transaction(root);
5326 if (IS_ERR(trans) || !ret) {
5327 if (!IS_ERR(trans)) {
5328 trans->block_rsv = &fs_info->trans_block_rsv;
5329 trans->bytes_reserved = delayed_refs_extra;
5330 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5331 delayed_refs_extra, 1);
5337 * Try to steal from the global reserve if there is space for
5340 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5341 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5344 /* If not, commit and try again. */
5345 ret = btrfs_commit_transaction(trans);
5347 return ERR_PTR(ret);
5351 void btrfs_evict_inode(struct inode *inode)
5353 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5354 struct btrfs_trans_handle *trans;
5355 struct btrfs_root *root = BTRFS_I(inode)->root;
5356 struct btrfs_block_rsv *rsv;
5359 trace_btrfs_inode_evict(inode);
5366 evict_inode_truncate_pages(inode);
5368 if (inode->i_nlink &&
5369 ((btrfs_root_refs(&root->root_item) != 0 &&
5370 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5371 btrfs_is_free_space_inode(BTRFS_I(inode))))
5374 if (is_bad_inode(inode))
5377 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5379 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5382 if (inode->i_nlink > 0) {
5383 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5384 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5388 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5392 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5395 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5398 btrfs_i_size_write(BTRFS_I(inode), 0);
5401 trans = evict_refill_and_join(root, rsv);
5405 trans->block_rsv = rsv;
5407 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5408 trans->block_rsv = &fs_info->trans_block_rsv;
5409 btrfs_end_transaction(trans);
5410 btrfs_btree_balance_dirty(fs_info);
5411 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5418 * Errors here aren't a big deal, it just means we leave orphan items in
5419 * the tree. They will be cleaned up on the next mount. If the inode
5420 * number gets reused, cleanup deletes the orphan item without doing
5421 * anything, and unlink reuses the existing orphan item.
5423 * If it turns out that we are dropping too many of these, we might want
5424 * to add a mechanism for retrying these after a commit.
5426 trans = evict_refill_and_join(root, rsv);
5427 if (!IS_ERR(trans)) {
5428 trans->block_rsv = rsv;
5429 btrfs_orphan_del(trans, BTRFS_I(inode));
5430 trans->block_rsv = &fs_info->trans_block_rsv;
5431 btrfs_end_transaction(trans);
5434 if (!(root == fs_info->tree_root ||
5435 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5436 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5439 btrfs_free_block_rsv(fs_info, rsv);
5442 * If we didn't successfully delete, the orphan item will still be in
5443 * the tree and we'll retry on the next mount. Again, we might also want
5444 * to retry these periodically in the future.
5446 btrfs_remove_delayed_node(BTRFS_I(inode));
5451 * this returns the key found in the dir entry in the location pointer.
5452 * If no dir entries were found, returns -ENOENT.
5453 * If found a corrupted location in dir entry, returns -EUCLEAN.
5455 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5456 struct btrfs_key *location)
5458 const char *name = dentry->d_name.name;
5459 int namelen = dentry->d_name.len;
5460 struct btrfs_dir_item *di;
5461 struct btrfs_path *path;
5462 struct btrfs_root *root = BTRFS_I(dir)->root;
5465 path = btrfs_alloc_path();
5469 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5471 if (IS_ERR_OR_NULL(di)) {
5472 ret = di ? PTR_ERR(di) : -ENOENT;
5476 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5477 if (location->type != BTRFS_INODE_ITEM_KEY &&
5478 location->type != BTRFS_ROOT_ITEM_KEY) {
5480 btrfs_warn(root->fs_info,
5481 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5482 __func__, name, btrfs_ino(BTRFS_I(dir)),
5483 location->objectid, location->type, location->offset);
5486 btrfs_free_path(path);
5491 * when we hit a tree root in a directory, the btrfs part of the inode
5492 * needs to be changed to reflect the root directory of the tree root. This
5493 * is kind of like crossing a mount point.
5495 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5497 struct dentry *dentry,
5498 struct btrfs_key *location,
5499 struct btrfs_root **sub_root)
5501 struct btrfs_path *path;
5502 struct btrfs_root *new_root;
5503 struct btrfs_root_ref *ref;
5504 struct extent_buffer *leaf;
5505 struct btrfs_key key;
5509 path = btrfs_alloc_path();
5516 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5517 key.type = BTRFS_ROOT_REF_KEY;
5518 key.offset = location->objectid;
5520 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5527 leaf = path->nodes[0];
5528 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5529 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5530 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5533 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5534 (unsigned long)(ref + 1),
5535 dentry->d_name.len);
5539 btrfs_release_path(path);
5541 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5542 if (IS_ERR(new_root)) {
5543 err = PTR_ERR(new_root);
5547 *sub_root = new_root;
5548 location->objectid = btrfs_root_dirid(&new_root->root_item);
5549 location->type = BTRFS_INODE_ITEM_KEY;
5550 location->offset = 0;
5553 btrfs_free_path(path);
5557 static void inode_tree_add(struct inode *inode)
5559 struct btrfs_root *root = BTRFS_I(inode)->root;
5560 struct btrfs_inode *entry;
5562 struct rb_node *parent;
5563 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5564 u64 ino = btrfs_ino(BTRFS_I(inode));
5566 if (inode_unhashed(inode))
5569 spin_lock(&root->inode_lock);
5570 p = &root->inode_tree.rb_node;
5573 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5575 if (ino < btrfs_ino(entry))
5576 p = &parent->rb_left;
5577 else if (ino > btrfs_ino(entry))
5578 p = &parent->rb_right;
5580 WARN_ON(!(entry->vfs_inode.i_state &
5581 (I_WILL_FREE | I_FREEING)));
5582 rb_replace_node(parent, new, &root->inode_tree);
5583 RB_CLEAR_NODE(parent);
5584 spin_unlock(&root->inode_lock);
5588 rb_link_node(new, parent, p);
5589 rb_insert_color(new, &root->inode_tree);
5590 spin_unlock(&root->inode_lock);
5593 static void inode_tree_del(struct inode *inode)
5595 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5596 struct btrfs_root *root = BTRFS_I(inode)->root;
5599 spin_lock(&root->inode_lock);
5600 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5601 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5602 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5603 empty = RB_EMPTY_ROOT(&root->inode_tree);
5605 spin_unlock(&root->inode_lock);
5607 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5608 synchronize_srcu(&fs_info->subvol_srcu);
5609 spin_lock(&root->inode_lock);
5610 empty = RB_EMPTY_ROOT(&root->inode_tree);
5611 spin_unlock(&root->inode_lock);
5613 btrfs_add_dead_root(root);
5618 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5620 struct btrfs_iget_args *args = p;
5621 inode->i_ino = args->location->objectid;
5622 memcpy(&BTRFS_I(inode)->location, args->location,
5623 sizeof(*args->location));
5624 BTRFS_I(inode)->root = args->root;
5628 static int btrfs_find_actor(struct inode *inode, void *opaque)
5630 struct btrfs_iget_args *args = opaque;
5631 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5632 args->root == BTRFS_I(inode)->root;
5635 static struct inode *btrfs_iget_locked(struct super_block *s,
5636 struct btrfs_key *location,
5637 struct btrfs_root *root)
5639 struct inode *inode;
5640 struct btrfs_iget_args args;
5641 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5643 args.location = location;
5646 inode = iget5_locked(s, hashval, btrfs_find_actor,
5647 btrfs_init_locked_inode,
5652 /* Get an inode object given its location and corresponding root.
5653 * Returns in *is_new if the inode was read from disk
5655 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5656 struct btrfs_root *root, int *new,
5657 struct btrfs_path *path)
5659 struct inode *inode;
5661 inode = btrfs_iget_locked(s, location, root);
5663 return ERR_PTR(-ENOMEM);
5665 if (inode->i_state & I_NEW) {
5668 ret = btrfs_read_locked_inode(inode, path);
5670 inode_tree_add(inode);
5671 unlock_new_inode(inode);
5677 * ret > 0 can come from btrfs_search_slot called by
5678 * btrfs_read_locked_inode, this means the inode item
5683 inode = ERR_PTR(ret);
5690 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5691 struct btrfs_root *root, int *new)
5693 return btrfs_iget_path(s, location, root, new, NULL);
5696 static struct inode *new_simple_dir(struct super_block *s,
5697 struct btrfs_key *key,
5698 struct btrfs_root *root)
5700 struct inode *inode = new_inode(s);
5703 return ERR_PTR(-ENOMEM);
5705 BTRFS_I(inode)->root = root;
5706 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5707 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5709 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5710 inode->i_op = &btrfs_dir_ro_inode_operations;
5711 inode->i_opflags &= ~IOP_XATTR;
5712 inode->i_fop = &simple_dir_operations;
5713 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5714 inode->i_mtime = current_time(inode);
5715 inode->i_atime = inode->i_mtime;
5716 inode->i_ctime = inode->i_mtime;
5717 BTRFS_I(inode)->i_otime = inode->i_mtime;
5722 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5724 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5725 struct inode *inode;
5726 struct btrfs_root *root = BTRFS_I(dir)->root;
5727 struct btrfs_root *sub_root = root;
5728 struct btrfs_key location;
5732 if (dentry->d_name.len > BTRFS_NAME_LEN)
5733 return ERR_PTR(-ENAMETOOLONG);
5735 ret = btrfs_inode_by_name(dir, dentry, &location);
5737 return ERR_PTR(ret);
5739 if (location.type == BTRFS_INODE_ITEM_KEY) {
5740 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5744 index = srcu_read_lock(&fs_info->subvol_srcu);
5745 ret = fixup_tree_root_location(fs_info, dir, dentry,
5746 &location, &sub_root);
5749 inode = ERR_PTR(ret);
5751 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5753 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5755 srcu_read_unlock(&fs_info->subvol_srcu, index);
5757 if (!IS_ERR(inode) && root != sub_root) {
5758 down_read(&fs_info->cleanup_work_sem);
5759 if (!sb_rdonly(inode->i_sb))
5760 ret = btrfs_orphan_cleanup(sub_root);
5761 up_read(&fs_info->cleanup_work_sem);
5764 inode = ERR_PTR(ret);
5771 static int btrfs_dentry_delete(const struct dentry *dentry)
5773 struct btrfs_root *root;
5774 struct inode *inode = d_inode(dentry);
5776 if (!inode && !IS_ROOT(dentry))
5777 inode = d_inode(dentry->d_parent);
5780 root = BTRFS_I(inode)->root;
5781 if (btrfs_root_refs(&root->root_item) == 0)
5784 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5790 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5793 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5795 if (inode == ERR_PTR(-ENOENT))
5797 return d_splice_alias(inode, dentry);
5800 unsigned char btrfs_filetype_table[] = {
5801 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5805 * All this infrastructure exists because dir_emit can fault, and we are holding
5806 * the tree lock when doing readdir. For now just allocate a buffer and copy
5807 * our information into that, and then dir_emit from the buffer. This is
5808 * similar to what NFS does, only we don't keep the buffer around in pagecache
5809 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5810 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5813 static int btrfs_opendir(struct inode *inode, struct file *file)
5815 struct btrfs_file_private *private;
5817 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5820 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5821 if (!private->filldir_buf) {
5825 file->private_data = private;
5836 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5839 struct dir_entry *entry = addr;
5840 char *name = (char *)(entry + 1);
5842 ctx->pos = get_unaligned(&entry->offset);
5843 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5844 get_unaligned(&entry->ino),
5845 get_unaligned(&entry->type)))
5847 addr += sizeof(struct dir_entry) +
5848 get_unaligned(&entry->name_len);
5854 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5856 struct inode *inode = file_inode(file);
5857 struct btrfs_root *root = BTRFS_I(inode)->root;
5858 struct btrfs_file_private *private = file->private_data;
5859 struct btrfs_dir_item *di;
5860 struct btrfs_key key;
5861 struct btrfs_key found_key;
5862 struct btrfs_path *path;
5864 struct list_head ins_list;
5865 struct list_head del_list;
5867 struct extent_buffer *leaf;
5874 struct btrfs_key location;
5876 if (!dir_emit_dots(file, ctx))
5879 path = btrfs_alloc_path();
5883 addr = private->filldir_buf;
5884 path->reada = READA_FORWARD;
5886 INIT_LIST_HEAD(&ins_list);
5887 INIT_LIST_HEAD(&del_list);
5888 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5891 key.type = BTRFS_DIR_INDEX_KEY;
5892 key.offset = ctx->pos;
5893 key.objectid = btrfs_ino(BTRFS_I(inode));
5895 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5900 struct dir_entry *entry;
5902 leaf = path->nodes[0];
5903 slot = path->slots[0];
5904 if (slot >= btrfs_header_nritems(leaf)) {
5905 ret = btrfs_next_leaf(root, path);
5913 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5915 if (found_key.objectid != key.objectid)
5917 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5919 if (found_key.offset < ctx->pos)
5921 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5923 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5924 name_len = btrfs_dir_name_len(leaf, di);
5925 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5927 btrfs_release_path(path);
5928 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5931 addr = private->filldir_buf;
5938 put_unaligned(name_len, &entry->name_len);
5939 name_ptr = (char *)(entry + 1);
5940 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5942 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
5944 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5945 put_unaligned(location.objectid, &entry->ino);
5946 put_unaligned(found_key.offset, &entry->offset);
5948 addr += sizeof(struct dir_entry) + name_len;
5949 total_len += sizeof(struct dir_entry) + name_len;
5953 btrfs_release_path(path);
5955 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5959 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5964 * Stop new entries from being returned after we return the last
5967 * New directory entries are assigned a strictly increasing
5968 * offset. This means that new entries created during readdir
5969 * are *guaranteed* to be seen in the future by that readdir.
5970 * This has broken buggy programs which operate on names as
5971 * they're returned by readdir. Until we re-use freed offsets
5972 * we have this hack to stop new entries from being returned
5973 * under the assumption that they'll never reach this huge
5976 * This is being careful not to overflow 32bit loff_t unless the
5977 * last entry requires it because doing so has broken 32bit apps
5980 if (ctx->pos >= INT_MAX)
5981 ctx->pos = LLONG_MAX;
5988 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5989 btrfs_free_path(path);
5994 * This is somewhat expensive, updating the tree every time the
5995 * inode changes. But, it is most likely to find the inode in cache.
5996 * FIXME, needs more benchmarking...there are no reasons other than performance
5997 * to keep or drop this code.
5999 static int btrfs_dirty_inode(struct inode *inode)
6001 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6002 struct btrfs_root *root = BTRFS_I(inode)->root;
6003 struct btrfs_trans_handle *trans;
6006 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6009 trans = btrfs_join_transaction(root);
6011 return PTR_ERR(trans);
6013 ret = btrfs_update_inode(trans, root, inode);
6014 if (ret && ret == -ENOSPC) {
6015 /* whoops, lets try again with the full transaction */
6016 btrfs_end_transaction(trans);
6017 trans = btrfs_start_transaction(root, 1);
6019 return PTR_ERR(trans);
6021 ret = btrfs_update_inode(trans, root, inode);
6023 btrfs_end_transaction(trans);
6024 if (BTRFS_I(inode)->delayed_node)
6025 btrfs_balance_delayed_items(fs_info);
6031 * This is a copy of file_update_time. We need this so we can return error on
6032 * ENOSPC for updating the inode in the case of file write and mmap writes.
6034 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6037 struct btrfs_root *root = BTRFS_I(inode)->root;
6038 bool dirty = flags & ~S_VERSION;
6040 if (btrfs_root_readonly(root))
6043 if (flags & S_VERSION)
6044 dirty |= inode_maybe_inc_iversion(inode, dirty);
6045 if (flags & S_CTIME)
6046 inode->i_ctime = *now;
6047 if (flags & S_MTIME)
6048 inode->i_mtime = *now;
6049 if (flags & S_ATIME)
6050 inode->i_atime = *now;
6051 return dirty ? btrfs_dirty_inode(inode) : 0;
6055 * find the highest existing sequence number in a directory
6056 * and then set the in-memory index_cnt variable to reflect
6057 * free sequence numbers
6059 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6061 struct btrfs_root *root = inode->root;
6062 struct btrfs_key key, found_key;
6063 struct btrfs_path *path;
6064 struct extent_buffer *leaf;
6067 key.objectid = btrfs_ino(inode);
6068 key.type = BTRFS_DIR_INDEX_KEY;
6069 key.offset = (u64)-1;
6071 path = btrfs_alloc_path();
6075 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6078 /* FIXME: we should be able to handle this */
6084 * MAGIC NUMBER EXPLANATION:
6085 * since we search a directory based on f_pos we have to start at 2
6086 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6087 * else has to start at 2
6089 if (path->slots[0] == 0) {
6090 inode->index_cnt = 2;
6096 leaf = path->nodes[0];
6097 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6099 if (found_key.objectid != btrfs_ino(inode) ||
6100 found_key.type != BTRFS_DIR_INDEX_KEY) {
6101 inode->index_cnt = 2;
6105 inode->index_cnt = found_key.offset + 1;
6107 btrfs_free_path(path);
6112 * helper to find a free sequence number in a given directory. This current
6113 * code is very simple, later versions will do smarter things in the btree
6115 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6119 if (dir->index_cnt == (u64)-1) {
6120 ret = btrfs_inode_delayed_dir_index_count(dir);
6122 ret = btrfs_set_inode_index_count(dir);
6128 *index = dir->index_cnt;
6134 static int btrfs_insert_inode_locked(struct inode *inode)
6136 struct btrfs_iget_args args;
6137 args.location = &BTRFS_I(inode)->location;
6138 args.root = BTRFS_I(inode)->root;
6140 return insert_inode_locked4(inode,
6141 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6142 btrfs_find_actor, &args);
6146 * Inherit flags from the parent inode.
6148 * Currently only the compression flags and the cow flags are inherited.
6150 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6157 flags = BTRFS_I(dir)->flags;
6159 if (flags & BTRFS_INODE_NOCOMPRESS) {
6160 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6161 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6162 } else if (flags & BTRFS_INODE_COMPRESS) {
6163 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6164 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6167 if (flags & BTRFS_INODE_NODATACOW) {
6168 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6169 if (S_ISREG(inode->i_mode))
6170 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6173 btrfs_sync_inode_flags_to_i_flags(inode);
6176 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6177 struct btrfs_root *root,
6179 const char *name, int name_len,
6180 u64 ref_objectid, u64 objectid,
6181 umode_t mode, u64 *index)
6183 struct btrfs_fs_info *fs_info = root->fs_info;
6184 struct inode *inode;
6185 struct btrfs_inode_item *inode_item;
6186 struct btrfs_key *location;
6187 struct btrfs_path *path;
6188 struct btrfs_inode_ref *ref;
6189 struct btrfs_key key[2];
6191 int nitems = name ? 2 : 1;
6195 path = btrfs_alloc_path();
6197 return ERR_PTR(-ENOMEM);
6199 inode = new_inode(fs_info->sb);
6201 btrfs_free_path(path);
6202 return ERR_PTR(-ENOMEM);
6206 * O_TMPFILE, set link count to 0, so that after this point,
6207 * we fill in an inode item with the correct link count.
6210 set_nlink(inode, 0);
6213 * we have to initialize this early, so we can reclaim the inode
6214 * number if we fail afterwards in this function.
6216 inode->i_ino = objectid;
6219 trace_btrfs_inode_request(dir);
6221 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6223 btrfs_free_path(path);
6225 return ERR_PTR(ret);
6231 * index_cnt is ignored for everything but a dir,
6232 * btrfs_set_inode_index_count has an explanation for the magic
6235 BTRFS_I(inode)->index_cnt = 2;
6236 BTRFS_I(inode)->dir_index = *index;
6237 BTRFS_I(inode)->root = root;
6238 BTRFS_I(inode)->generation = trans->transid;
6239 inode->i_generation = BTRFS_I(inode)->generation;
6242 * We could have gotten an inode number from somebody who was fsynced
6243 * and then removed in this same transaction, so let's just set full
6244 * sync since it will be a full sync anyway and this will blow away the
6245 * old info in the log.
6247 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6249 key[0].objectid = objectid;
6250 key[0].type = BTRFS_INODE_ITEM_KEY;
6253 sizes[0] = sizeof(struct btrfs_inode_item);
6257 * Start new inodes with an inode_ref. This is slightly more
6258 * efficient for small numbers of hard links since they will
6259 * be packed into one item. Extended refs will kick in if we
6260 * add more hard links than can fit in the ref item.
6262 key[1].objectid = objectid;
6263 key[1].type = BTRFS_INODE_REF_KEY;
6264 key[1].offset = ref_objectid;
6266 sizes[1] = name_len + sizeof(*ref);
6269 location = &BTRFS_I(inode)->location;
6270 location->objectid = objectid;
6271 location->offset = 0;
6272 location->type = BTRFS_INODE_ITEM_KEY;
6274 ret = btrfs_insert_inode_locked(inode);
6280 path->leave_spinning = 1;
6281 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6285 inode_init_owner(inode, dir, mode);
6286 inode_set_bytes(inode, 0);
6288 inode->i_mtime = current_time(inode);
6289 inode->i_atime = inode->i_mtime;
6290 inode->i_ctime = inode->i_mtime;
6291 BTRFS_I(inode)->i_otime = inode->i_mtime;
6293 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6294 struct btrfs_inode_item);
6295 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6296 sizeof(*inode_item));
6297 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6300 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6301 struct btrfs_inode_ref);
6302 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6303 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6304 ptr = (unsigned long)(ref + 1);
6305 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6308 btrfs_mark_buffer_dirty(path->nodes[0]);
6309 btrfs_free_path(path);
6311 btrfs_inherit_iflags(inode, dir);
6313 if (S_ISREG(mode)) {
6314 if (btrfs_test_opt(fs_info, NODATASUM))
6315 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6316 if (btrfs_test_opt(fs_info, NODATACOW))
6317 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6318 BTRFS_INODE_NODATASUM;
6321 inode_tree_add(inode);
6323 trace_btrfs_inode_new(inode);
6324 btrfs_set_inode_last_trans(trans, inode);
6326 btrfs_update_root_times(trans, root);
6328 ret = btrfs_inode_inherit_props(trans, inode, dir);
6331 "error inheriting props for ino %llu (root %llu): %d",
6332 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6337 discard_new_inode(inode);
6340 BTRFS_I(dir)->index_cnt--;
6341 btrfs_free_path(path);
6342 return ERR_PTR(ret);
6345 static inline u8 btrfs_inode_type(struct inode *inode)
6347 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6351 * utility function to add 'inode' into 'parent_inode' with
6352 * a give name and a given sequence number.
6353 * if 'add_backref' is true, also insert a backref from the
6354 * inode to the parent directory.
6356 int btrfs_add_link(struct btrfs_trans_handle *trans,
6357 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6358 const char *name, int name_len, int add_backref, u64 index)
6361 struct btrfs_key key;
6362 struct btrfs_root *root = parent_inode->root;
6363 u64 ino = btrfs_ino(inode);
6364 u64 parent_ino = btrfs_ino(parent_inode);
6366 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6367 memcpy(&key, &inode->root->root_key, sizeof(key));
6370 key.type = BTRFS_INODE_ITEM_KEY;
6374 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6375 ret = btrfs_add_root_ref(trans, key.objectid,
6376 root->root_key.objectid, parent_ino,
6377 index, name, name_len);
6378 } else if (add_backref) {
6379 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6383 /* Nothing to clean up yet */
6387 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6388 btrfs_inode_type(&inode->vfs_inode), index);
6389 if (ret == -EEXIST || ret == -EOVERFLOW)
6392 btrfs_abort_transaction(trans, ret);
6396 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6398 inode_inc_iversion(&parent_inode->vfs_inode);
6399 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6400 current_time(&parent_inode->vfs_inode);
6401 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6403 btrfs_abort_transaction(trans, ret);
6407 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6410 err = btrfs_del_root_ref(trans, key.objectid,
6411 root->root_key.objectid, parent_ino,
6412 &local_index, name, name_len);
6414 btrfs_abort_transaction(trans, err);
6415 } else if (add_backref) {
6419 err = btrfs_del_inode_ref(trans, root, name, name_len,
6420 ino, parent_ino, &local_index);
6422 btrfs_abort_transaction(trans, err);
6425 /* Return the original error code */
6429 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6430 struct btrfs_inode *dir, struct dentry *dentry,
6431 struct btrfs_inode *inode, int backref, u64 index)
6433 int err = btrfs_add_link(trans, dir, inode,
6434 dentry->d_name.name, dentry->d_name.len,
6441 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6442 umode_t mode, dev_t rdev)
6444 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6445 struct btrfs_trans_handle *trans;
6446 struct btrfs_root *root = BTRFS_I(dir)->root;
6447 struct inode *inode = NULL;
6453 * 2 for inode item and ref
6455 * 1 for xattr if selinux is on
6457 trans = btrfs_start_transaction(root, 5);
6459 return PTR_ERR(trans);
6461 err = btrfs_find_free_ino(root, &objectid);
6465 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6466 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6468 if (IS_ERR(inode)) {
6469 err = PTR_ERR(inode);
6475 * If the active LSM wants to access the inode during
6476 * d_instantiate it needs these. Smack checks to see
6477 * if the filesystem supports xattrs by looking at the
6480 inode->i_op = &btrfs_special_inode_operations;
6481 init_special_inode(inode, inode->i_mode, rdev);
6483 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6487 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6492 btrfs_update_inode(trans, root, inode);
6493 d_instantiate_new(dentry, inode);
6496 btrfs_end_transaction(trans);
6497 btrfs_btree_balance_dirty(fs_info);
6499 inode_dec_link_count(inode);
6500 discard_new_inode(inode);
6505 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6506 umode_t mode, bool excl)
6508 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6509 struct btrfs_trans_handle *trans;
6510 struct btrfs_root *root = BTRFS_I(dir)->root;
6511 struct inode *inode = NULL;
6517 * 2 for inode item and ref
6519 * 1 for xattr if selinux is on
6521 trans = btrfs_start_transaction(root, 5);
6523 return PTR_ERR(trans);
6525 err = btrfs_find_free_ino(root, &objectid);
6529 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6530 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6532 if (IS_ERR(inode)) {
6533 err = PTR_ERR(inode);
6538 * If the active LSM wants to access the inode during
6539 * d_instantiate it needs these. Smack checks to see
6540 * if the filesystem supports xattrs by looking at the
6543 inode->i_fop = &btrfs_file_operations;
6544 inode->i_op = &btrfs_file_inode_operations;
6545 inode->i_mapping->a_ops = &btrfs_aops;
6547 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6551 err = btrfs_update_inode(trans, root, inode);
6555 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6560 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6561 d_instantiate_new(dentry, inode);
6564 btrfs_end_transaction(trans);
6566 inode_dec_link_count(inode);
6567 discard_new_inode(inode);
6569 btrfs_btree_balance_dirty(fs_info);
6573 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6574 struct dentry *dentry)
6576 struct btrfs_trans_handle *trans = NULL;
6577 struct btrfs_root *root = BTRFS_I(dir)->root;
6578 struct inode *inode = d_inode(old_dentry);
6579 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6584 /* do not allow sys_link's with other subvols of the same device */
6585 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6588 if (inode->i_nlink >= BTRFS_LINK_MAX)
6591 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6596 * 2 items for inode and inode ref
6597 * 2 items for dir items
6598 * 1 item for parent inode
6599 * 1 item for orphan item deletion if O_TMPFILE
6601 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6602 if (IS_ERR(trans)) {
6603 err = PTR_ERR(trans);
6608 /* There are several dir indexes for this inode, clear the cache. */
6609 BTRFS_I(inode)->dir_index = 0ULL;
6611 inode_inc_iversion(inode);
6612 inode->i_ctime = current_time(inode);
6614 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6616 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6622 struct dentry *parent = dentry->d_parent;
6625 err = btrfs_update_inode(trans, root, inode);
6628 if (inode->i_nlink == 1) {
6630 * If new hard link count is 1, it's a file created
6631 * with open(2) O_TMPFILE flag.
6633 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6637 BTRFS_I(inode)->last_link_trans = trans->transid;
6638 d_instantiate(dentry, inode);
6639 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6641 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6642 err = btrfs_commit_transaction(trans);
6649 btrfs_end_transaction(trans);
6651 inode_dec_link_count(inode);
6654 btrfs_btree_balance_dirty(fs_info);
6658 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6660 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6661 struct inode *inode = NULL;
6662 struct btrfs_trans_handle *trans;
6663 struct btrfs_root *root = BTRFS_I(dir)->root;
6669 * 2 items for inode and ref
6670 * 2 items for dir items
6671 * 1 for xattr if selinux is on
6673 trans = btrfs_start_transaction(root, 5);
6675 return PTR_ERR(trans);
6677 err = btrfs_find_free_ino(root, &objectid);
6681 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6682 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6683 S_IFDIR | mode, &index);
6684 if (IS_ERR(inode)) {
6685 err = PTR_ERR(inode);
6690 /* these must be set before we unlock the inode */
6691 inode->i_op = &btrfs_dir_inode_operations;
6692 inode->i_fop = &btrfs_dir_file_operations;
6694 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6698 btrfs_i_size_write(BTRFS_I(inode), 0);
6699 err = btrfs_update_inode(trans, root, inode);
6703 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6704 dentry->d_name.name,
6705 dentry->d_name.len, 0, index);
6709 d_instantiate_new(dentry, inode);
6712 btrfs_end_transaction(trans);
6714 inode_dec_link_count(inode);
6715 discard_new_inode(inode);
6717 btrfs_btree_balance_dirty(fs_info);
6721 static noinline int uncompress_inline(struct btrfs_path *path,
6723 size_t pg_offset, u64 extent_offset,
6724 struct btrfs_file_extent_item *item)
6727 struct extent_buffer *leaf = path->nodes[0];
6730 unsigned long inline_size;
6734 WARN_ON(pg_offset != 0);
6735 compress_type = btrfs_file_extent_compression(leaf, item);
6736 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6737 inline_size = btrfs_file_extent_inline_item_len(leaf,
6738 btrfs_item_nr(path->slots[0]));
6739 tmp = kmalloc(inline_size, GFP_NOFS);
6742 ptr = btrfs_file_extent_inline_start(item);
6744 read_extent_buffer(leaf, tmp, ptr, inline_size);
6746 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6747 ret = btrfs_decompress(compress_type, tmp, page,
6748 extent_offset, inline_size, max_size);
6751 * decompression code contains a memset to fill in any space between the end
6752 * of the uncompressed data and the end of max_size in case the decompressed
6753 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6754 * the end of an inline extent and the beginning of the next block, so we
6755 * cover that region here.
6758 if (max_size + pg_offset < PAGE_SIZE) {
6759 char *map = kmap(page);
6760 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6768 * a bit scary, this does extent mapping from logical file offset to the disk.
6769 * the ugly parts come from merging extents from the disk with the in-ram
6770 * representation. This gets more complex because of the data=ordered code,
6771 * where the in-ram extents might be locked pending data=ordered completion.
6773 * This also copies inline extents directly into the page.
6775 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6777 size_t pg_offset, u64 start, u64 len,
6780 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6783 u64 extent_start = 0;
6785 u64 objectid = btrfs_ino(inode);
6787 struct btrfs_path *path = NULL;
6788 struct btrfs_root *root = inode->root;
6789 struct btrfs_file_extent_item *item;
6790 struct extent_buffer *leaf;
6791 struct btrfs_key found_key;
6792 struct extent_map *em = NULL;
6793 struct extent_map_tree *em_tree = &inode->extent_tree;
6794 struct extent_io_tree *io_tree = &inode->io_tree;
6795 const bool new_inline = !page || create;
6797 read_lock(&em_tree->lock);
6798 em = lookup_extent_mapping(em_tree, start, len);
6800 em->bdev = fs_info->fs_devices->latest_bdev;
6801 read_unlock(&em_tree->lock);
6804 if (em->start > start || em->start + em->len <= start)
6805 free_extent_map(em);
6806 else if (em->block_start == EXTENT_MAP_INLINE && page)
6807 free_extent_map(em);
6811 em = alloc_extent_map();
6816 em->bdev = fs_info->fs_devices->latest_bdev;
6817 em->start = EXTENT_MAP_HOLE;
6818 em->orig_start = EXTENT_MAP_HOLE;
6820 em->block_len = (u64)-1;
6822 path = btrfs_alloc_path();
6828 /* Chances are we'll be called again, so go ahead and do readahead */
6829 path->reada = READA_FORWARD;
6832 * Unless we're going to uncompress the inline extent, no sleep would
6835 path->leave_spinning = 1;
6837 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6841 } else if (ret > 0) {
6842 if (path->slots[0] == 0)
6847 leaf = path->nodes[0];
6848 item = btrfs_item_ptr(leaf, path->slots[0],
6849 struct btrfs_file_extent_item);
6850 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6851 if (found_key.objectid != objectid ||
6852 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6854 * If we backup past the first extent we want to move forward
6855 * and see if there is an extent in front of us, otherwise we'll
6856 * say there is a hole for our whole search range which can
6863 extent_type = btrfs_file_extent_type(leaf, item);
6864 extent_start = found_key.offset;
6865 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6866 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6867 extent_end = extent_start +
6868 btrfs_file_extent_num_bytes(leaf, item);
6870 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6872 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6875 size = btrfs_file_extent_ram_bytes(leaf, item);
6876 extent_end = ALIGN(extent_start + size,
6877 fs_info->sectorsize);
6879 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6884 if (start >= extent_end) {
6886 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6887 ret = btrfs_next_leaf(root, path);
6891 } else if (ret > 0) {
6894 leaf = path->nodes[0];
6896 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6897 if (found_key.objectid != objectid ||
6898 found_key.type != BTRFS_EXTENT_DATA_KEY)
6900 if (start + len <= found_key.offset)
6902 if (start > found_key.offset)
6905 /* New extent overlaps with existing one */
6907 em->orig_start = start;
6908 em->len = found_key.offset - start;
6909 em->block_start = EXTENT_MAP_HOLE;
6913 btrfs_extent_item_to_extent_map(inode, path, item,
6916 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6917 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6919 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6923 size_t extent_offset;
6929 size = btrfs_file_extent_ram_bytes(leaf, item);
6930 extent_offset = page_offset(page) + pg_offset - extent_start;
6931 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6932 size - extent_offset);
6933 em->start = extent_start + extent_offset;
6934 em->len = ALIGN(copy_size, fs_info->sectorsize);
6935 em->orig_block_len = em->len;
6936 em->orig_start = em->start;
6937 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6939 btrfs_set_path_blocking(path);
6940 if (!PageUptodate(page)) {
6941 if (btrfs_file_extent_compression(leaf, item) !=
6942 BTRFS_COMPRESS_NONE) {
6943 ret = uncompress_inline(path, page, pg_offset,
6944 extent_offset, item);
6951 read_extent_buffer(leaf, map + pg_offset, ptr,
6953 if (pg_offset + copy_size < PAGE_SIZE) {
6954 memset(map + pg_offset + copy_size, 0,
6955 PAGE_SIZE - pg_offset -
6960 flush_dcache_page(page);
6962 set_extent_uptodate(io_tree, em->start,
6963 extent_map_end(em) - 1, NULL, GFP_NOFS);
6968 em->orig_start = start;
6970 em->block_start = EXTENT_MAP_HOLE;
6972 btrfs_release_path(path);
6973 if (em->start > start || extent_map_end(em) <= start) {
6975 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6976 em->start, em->len, start, len);
6982 write_lock(&em_tree->lock);
6983 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6984 write_unlock(&em_tree->lock);
6986 btrfs_free_path(path);
6988 trace_btrfs_get_extent(root, inode, em);
6991 free_extent_map(em);
6992 return ERR_PTR(err);
6994 BUG_ON(!em); /* Error is always set */
6998 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7001 struct extent_map *em;
7002 struct extent_map *hole_em = NULL;
7003 u64 delalloc_start = start;
7009 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7013 * If our em maps to:
7015 * - a pre-alloc extent,
7016 * there might actually be delalloc bytes behind it.
7018 if (em->block_start != EXTENT_MAP_HOLE &&
7019 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7024 /* check to see if we've wrapped (len == -1 or similar) */
7033 /* ok, we didn't find anything, lets look for delalloc */
7034 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7035 end, len, EXTENT_DELALLOC, 1);
7036 delalloc_end = delalloc_start + delalloc_len;
7037 if (delalloc_end < delalloc_start)
7038 delalloc_end = (u64)-1;
7041 * We didn't find anything useful, return the original results from
7044 if (delalloc_start > end || delalloc_end <= start) {
7051 * Adjust the delalloc_start to make sure it doesn't go backwards from
7052 * the start they passed in
7054 delalloc_start = max(start, delalloc_start);
7055 delalloc_len = delalloc_end - delalloc_start;
7057 if (delalloc_len > 0) {
7060 const u64 hole_end = extent_map_end(hole_em);
7062 em = alloc_extent_map();
7071 * When btrfs_get_extent can't find anything it returns one
7074 * Make sure what it found really fits our range, and adjust to
7075 * make sure it is based on the start from the caller
7077 if (hole_end <= start || hole_em->start > end) {
7078 free_extent_map(hole_em);
7081 hole_start = max(hole_em->start, start);
7082 hole_len = hole_end - hole_start;
7085 if (hole_em && delalloc_start > hole_start) {
7087 * Our hole starts before our delalloc, so we have to
7088 * return just the parts of the hole that go until the
7091 em->len = min(hole_len, delalloc_start - hole_start);
7092 em->start = hole_start;
7093 em->orig_start = hole_start;
7095 * Don't adjust block start at all, it is fixed at
7098 em->block_start = hole_em->block_start;
7099 em->block_len = hole_len;
7100 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7101 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7104 * Hole is out of passed range or it starts after
7107 em->start = delalloc_start;
7108 em->len = delalloc_len;
7109 em->orig_start = delalloc_start;
7110 em->block_start = EXTENT_MAP_DELALLOC;
7111 em->block_len = delalloc_len;
7118 free_extent_map(hole_em);
7120 free_extent_map(em);
7121 return ERR_PTR(err);
7126 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7129 const u64 orig_start,
7130 const u64 block_start,
7131 const u64 block_len,
7132 const u64 orig_block_len,
7133 const u64 ram_bytes,
7136 struct extent_map *em = NULL;
7139 if (type != BTRFS_ORDERED_NOCOW) {
7140 em = create_io_em(inode, start, len, orig_start,
7141 block_start, block_len, orig_block_len,
7143 BTRFS_COMPRESS_NONE, /* compress_type */
7148 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7149 len, block_len, type);
7152 free_extent_map(em);
7153 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7154 start + len - 1, 0);
7163 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7166 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7167 struct btrfs_root *root = BTRFS_I(inode)->root;
7168 struct extent_map *em;
7169 struct btrfs_key ins;
7173 alloc_hint = get_extent_allocation_hint(inode, start, len);
7174 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7175 0, alloc_hint, &ins, 1, 1);
7177 return ERR_PTR(ret);
7179 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7180 ins.objectid, ins.offset, ins.offset,
7181 ins.offset, BTRFS_ORDERED_REGULAR);
7182 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7184 btrfs_free_reserved_extent(fs_info, ins.objectid,
7191 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7192 * block must be cow'd
7194 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7195 u64 *orig_start, u64 *orig_block_len,
7198 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7199 struct btrfs_path *path;
7201 struct extent_buffer *leaf;
7202 struct btrfs_root *root = BTRFS_I(inode)->root;
7203 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7204 struct btrfs_file_extent_item *fi;
7205 struct btrfs_key key;
7212 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7214 path = btrfs_alloc_path();
7218 ret = btrfs_lookup_file_extent(NULL, root, path,
7219 btrfs_ino(BTRFS_I(inode)), offset, 0);
7223 slot = path->slots[0];
7226 /* can't find the item, must cow */
7233 leaf = path->nodes[0];
7234 btrfs_item_key_to_cpu(leaf, &key, slot);
7235 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7236 key.type != BTRFS_EXTENT_DATA_KEY) {
7237 /* not our file or wrong item type, must cow */
7241 if (key.offset > offset) {
7242 /* Wrong offset, must cow */
7246 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7247 found_type = btrfs_file_extent_type(leaf, fi);
7248 if (found_type != BTRFS_FILE_EXTENT_REG &&
7249 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7250 /* not a regular extent, must cow */
7254 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7257 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7258 if (extent_end <= offset)
7261 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7262 if (disk_bytenr == 0)
7265 if (btrfs_file_extent_compression(leaf, fi) ||
7266 btrfs_file_extent_encryption(leaf, fi) ||
7267 btrfs_file_extent_other_encoding(leaf, fi))
7271 * Do the same check as in btrfs_cross_ref_exist but without the
7272 * unnecessary search.
7274 if (btrfs_file_extent_generation(leaf, fi) <=
7275 btrfs_root_last_snapshot(&root->root_item))
7278 backref_offset = btrfs_file_extent_offset(leaf, fi);
7281 *orig_start = key.offset - backref_offset;
7282 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7283 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7286 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7289 num_bytes = min(offset + *len, extent_end) - offset;
7290 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7293 range_end = round_up(offset + num_bytes,
7294 root->fs_info->sectorsize) - 1;
7295 ret = test_range_bit(io_tree, offset, range_end,
7296 EXTENT_DELALLOC, 0, NULL);
7303 btrfs_release_path(path);
7306 * look for other files referencing this extent, if we
7307 * find any we must cow
7310 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7311 key.offset - backref_offset, disk_bytenr);
7318 * adjust disk_bytenr and num_bytes to cover just the bytes
7319 * in this extent we are about to write. If there
7320 * are any csums in that range we have to cow in order
7321 * to keep the csums correct
7323 disk_bytenr += backref_offset;
7324 disk_bytenr += offset - key.offset;
7325 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7328 * all of the above have passed, it is safe to overwrite this extent
7334 btrfs_free_path(path);
7338 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7339 struct extent_state **cached_state, int writing)
7341 struct btrfs_ordered_extent *ordered;
7345 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7348 * We're concerned with the entire range that we're going to be
7349 * doing DIO to, so we need to make sure there's no ordered
7350 * extents in this range.
7352 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7353 lockend - lockstart + 1);
7356 * We need to make sure there are no buffered pages in this
7357 * range either, we could have raced between the invalidate in
7358 * generic_file_direct_write and locking the extent. The
7359 * invalidate needs to happen so that reads after a write do not
7363 (!writing || !filemap_range_has_page(inode->i_mapping,
7364 lockstart, lockend)))
7367 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7372 * If we are doing a DIO read and the ordered extent we
7373 * found is for a buffered write, we can not wait for it
7374 * to complete and retry, because if we do so we can
7375 * deadlock with concurrent buffered writes on page
7376 * locks. This happens only if our DIO read covers more
7377 * than one extent map, if at this point has already
7378 * created an ordered extent for a previous extent map
7379 * and locked its range in the inode's io tree, and a
7380 * concurrent write against that previous extent map's
7381 * range and this range started (we unlock the ranges
7382 * in the io tree only when the bios complete and
7383 * buffered writes always lock pages before attempting
7384 * to lock range in the io tree).
7387 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7388 btrfs_start_ordered_extent(inode, ordered, 1);
7391 btrfs_put_ordered_extent(ordered);
7394 * We could trigger writeback for this range (and wait
7395 * for it to complete) and then invalidate the pages for
7396 * this range (through invalidate_inode_pages2_range()),
7397 * but that can lead us to a deadlock with a concurrent
7398 * call to readpages() (a buffered read or a defrag call
7399 * triggered a readahead) on a page lock due to an
7400 * ordered dio extent we created before but did not have
7401 * yet a corresponding bio submitted (whence it can not
7402 * complete), which makes readpages() wait for that
7403 * ordered extent to complete while holding a lock on
7418 /* The callers of this must take lock_extent() */
7419 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7420 u64 orig_start, u64 block_start,
7421 u64 block_len, u64 orig_block_len,
7422 u64 ram_bytes, int compress_type,
7425 struct extent_map_tree *em_tree;
7426 struct extent_map *em;
7427 struct btrfs_root *root = BTRFS_I(inode)->root;
7430 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7431 type == BTRFS_ORDERED_COMPRESSED ||
7432 type == BTRFS_ORDERED_NOCOW ||
7433 type == BTRFS_ORDERED_REGULAR);
7435 em_tree = &BTRFS_I(inode)->extent_tree;
7436 em = alloc_extent_map();
7438 return ERR_PTR(-ENOMEM);
7441 em->orig_start = orig_start;
7443 em->block_len = block_len;
7444 em->block_start = block_start;
7445 em->bdev = root->fs_info->fs_devices->latest_bdev;
7446 em->orig_block_len = orig_block_len;
7447 em->ram_bytes = ram_bytes;
7448 em->generation = -1;
7449 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7450 if (type == BTRFS_ORDERED_PREALLOC) {
7451 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7452 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7453 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7454 em->compress_type = compress_type;
7458 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7459 em->start + em->len - 1, 0);
7460 write_lock(&em_tree->lock);
7461 ret = add_extent_mapping(em_tree, em, 1);
7462 write_unlock(&em_tree->lock);
7464 * The caller has taken lock_extent(), who could race with us
7467 } while (ret == -EEXIST);
7470 free_extent_map(em);
7471 return ERR_PTR(ret);
7474 /* em got 2 refs now, callers needs to do free_extent_map once. */
7479 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7480 struct buffer_head *bh_result,
7481 struct inode *inode,
7484 if (em->block_start == EXTENT_MAP_HOLE ||
7485 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7488 len = min(len, em->len - (start - em->start));
7490 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7492 bh_result->b_size = len;
7493 bh_result->b_bdev = em->bdev;
7494 set_buffer_mapped(bh_result);
7499 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7500 struct buffer_head *bh_result,
7501 struct inode *inode,
7502 struct btrfs_dio_data *dio_data,
7505 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7506 struct extent_map *em = *map;
7510 * We don't allocate a new extent in the following cases
7512 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7514 * 2) The extent is marked as PREALLOC. We're good to go here and can
7515 * just use the extent.
7518 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7519 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7520 em->block_start != EXTENT_MAP_HOLE)) {
7522 u64 block_start, orig_start, orig_block_len, ram_bytes;
7524 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7525 type = BTRFS_ORDERED_PREALLOC;
7527 type = BTRFS_ORDERED_NOCOW;
7528 len = min(len, em->len - (start - em->start));
7529 block_start = em->block_start + (start - em->start);
7531 if (can_nocow_extent(inode, start, &len, &orig_start,
7532 &orig_block_len, &ram_bytes) == 1 &&
7533 btrfs_inc_nocow_writers(fs_info, block_start)) {
7534 struct extent_map *em2;
7536 em2 = btrfs_create_dio_extent(inode, start, len,
7537 orig_start, block_start,
7538 len, orig_block_len,
7540 btrfs_dec_nocow_writers(fs_info, block_start);
7541 if (type == BTRFS_ORDERED_PREALLOC) {
7542 free_extent_map(em);
7546 if (em2 && IS_ERR(em2)) {
7551 * For inode marked NODATACOW or extent marked PREALLOC,
7552 * use the existing or preallocated extent, so does not
7553 * need to adjust btrfs_space_info's bytes_may_use.
7555 btrfs_free_reserved_data_space_noquota(inode, start,
7561 /* this will cow the extent */
7562 len = bh_result->b_size;
7563 free_extent_map(em);
7564 *map = em = btrfs_new_extent_direct(inode, start, len);
7570 len = min(len, em->len - (start - em->start));
7573 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7575 bh_result->b_size = len;
7576 bh_result->b_bdev = em->bdev;
7577 set_buffer_mapped(bh_result);
7579 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7580 set_buffer_new(bh_result);
7583 * Need to update the i_size under the extent lock so buffered
7584 * readers will get the updated i_size when we unlock.
7586 if (!dio_data->overwrite && start + len > i_size_read(inode))
7587 i_size_write(inode, start + len);
7589 WARN_ON(dio_data->reserve < len);
7590 dio_data->reserve -= len;
7591 dio_data->unsubmitted_oe_range_end = start + len;
7592 current->journal_info = dio_data;
7597 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7598 struct buffer_head *bh_result, int create)
7600 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7601 struct extent_map *em;
7602 struct extent_state *cached_state = NULL;
7603 struct btrfs_dio_data *dio_data = NULL;
7604 u64 start = iblock << inode->i_blkbits;
7605 u64 lockstart, lockend;
7606 u64 len = bh_result->b_size;
7607 int unlock_bits = EXTENT_LOCKED;
7611 unlock_bits |= EXTENT_DIRTY;
7613 len = min_t(u64, len, fs_info->sectorsize);
7616 lockend = start + len - 1;
7618 if (current->journal_info) {
7620 * Need to pull our outstanding extents and set journal_info to NULL so
7621 * that anything that needs to check if there's a transaction doesn't get
7624 dio_data = current->journal_info;
7625 current->journal_info = NULL;
7629 * If this errors out it's because we couldn't invalidate pagecache for
7630 * this range and we need to fallback to buffered.
7632 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7638 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7645 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7646 * io. INLINE is special, and we could probably kludge it in here, but
7647 * it's still buffered so for safety lets just fall back to the generic
7650 * For COMPRESSED we _have_ to read the entire extent in so we can
7651 * decompress it, so there will be buffering required no matter what we
7652 * do, so go ahead and fallback to buffered.
7654 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7655 * to buffered IO. Don't blame me, this is the price we pay for using
7658 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7659 em->block_start == EXTENT_MAP_INLINE) {
7660 free_extent_map(em);
7666 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7667 dio_data, start, len);
7671 /* clear and unlock the entire range */
7672 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7673 unlock_bits, 1, 0, &cached_state);
7675 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7677 /* Can be negative only if we read from a hole */
7680 free_extent_map(em);
7684 * We need to unlock only the end area that we aren't using.
7685 * The rest is going to be unlocked by the endio routine.
7687 lockstart = start + bh_result->b_size;
7688 if (lockstart < lockend) {
7689 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7690 lockend, unlock_bits, 1, 0,
7693 free_extent_state(cached_state);
7697 free_extent_map(em);
7702 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7703 unlock_bits, 1, 0, &cached_state);
7706 current->journal_info = dio_data;
7710 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7714 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7717 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7719 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7723 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7728 static int btrfs_check_dio_repairable(struct inode *inode,
7729 struct bio *failed_bio,
7730 struct io_failure_record *failrec,
7733 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7736 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7737 if (num_copies == 1) {
7739 * we only have a single copy of the data, so don't bother with
7740 * all the retry and error correction code that follows. no
7741 * matter what the error is, it is very likely to persist.
7743 btrfs_debug(fs_info,
7744 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7745 num_copies, failrec->this_mirror, failed_mirror);
7749 failrec->failed_mirror = failed_mirror;
7750 failrec->this_mirror++;
7751 if (failrec->this_mirror == failed_mirror)
7752 failrec->this_mirror++;
7754 if (failrec->this_mirror > num_copies) {
7755 btrfs_debug(fs_info,
7756 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7757 num_copies, failrec->this_mirror, failed_mirror);
7764 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7765 struct page *page, unsigned int pgoff,
7766 u64 start, u64 end, int failed_mirror,
7767 bio_end_io_t *repair_endio, void *repair_arg)
7769 struct io_failure_record *failrec;
7770 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7771 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7774 unsigned int read_mode = 0;
7777 blk_status_t status;
7778 struct bio_vec bvec;
7780 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7782 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7784 return errno_to_blk_status(ret);
7786 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7789 free_io_failure(failure_tree, io_tree, failrec);
7790 return BLK_STS_IOERR;
7793 segs = bio_segments(failed_bio);
7794 bio_get_first_bvec(failed_bio, &bvec);
7796 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7797 read_mode |= REQ_FAILFAST_DEV;
7799 isector = start - btrfs_io_bio(failed_bio)->logical;
7800 isector >>= inode->i_sb->s_blocksize_bits;
7801 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7802 pgoff, isector, repair_endio, repair_arg);
7803 bio->bi_opf = REQ_OP_READ | read_mode;
7805 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7806 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7807 read_mode, failrec->this_mirror, failrec->in_validation);
7809 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7811 free_io_failure(failure_tree, io_tree, failrec);
7818 struct btrfs_retry_complete {
7819 struct completion done;
7820 struct inode *inode;
7825 static void btrfs_retry_endio_nocsum(struct bio *bio)
7827 struct btrfs_retry_complete *done = bio->bi_private;
7828 struct inode *inode = done->inode;
7829 struct bio_vec *bvec;
7830 struct extent_io_tree *io_tree, *failure_tree;
7836 ASSERT(bio->bi_vcnt == 1);
7837 io_tree = &BTRFS_I(inode)->io_tree;
7838 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7839 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7842 ASSERT(!bio_flagged(bio, BIO_CLONED));
7843 bio_for_each_segment_all(bvec, bio, i)
7844 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7845 io_tree, done->start, bvec->bv_page,
7846 btrfs_ino(BTRFS_I(inode)), 0);
7848 complete(&done->done);
7852 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7853 struct btrfs_io_bio *io_bio)
7855 struct btrfs_fs_info *fs_info;
7856 struct bio_vec bvec;
7857 struct bvec_iter iter;
7858 struct btrfs_retry_complete done;
7864 blk_status_t err = BLK_STS_OK;
7866 fs_info = BTRFS_I(inode)->root->fs_info;
7867 sectorsize = fs_info->sectorsize;
7869 start = io_bio->logical;
7871 io_bio->bio.bi_iter = io_bio->iter;
7873 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7874 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7875 pgoff = bvec.bv_offset;
7877 next_block_or_try_again:
7880 init_completion(&done.done);
7882 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7883 pgoff, start, start + sectorsize - 1,
7885 btrfs_retry_endio_nocsum, &done);
7891 wait_for_completion_io(&done.done);
7893 if (!done.uptodate) {
7894 /* We might have another mirror, so try again */
7895 goto next_block_or_try_again;
7899 start += sectorsize;
7903 pgoff += sectorsize;
7904 ASSERT(pgoff < PAGE_SIZE);
7905 goto next_block_or_try_again;
7912 static void btrfs_retry_endio(struct bio *bio)
7914 struct btrfs_retry_complete *done = bio->bi_private;
7915 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7916 struct extent_io_tree *io_tree, *failure_tree;
7917 struct inode *inode = done->inode;
7918 struct bio_vec *bvec;
7928 ASSERT(bio->bi_vcnt == 1);
7929 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7931 io_tree = &BTRFS_I(inode)->io_tree;
7932 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7934 ASSERT(!bio_flagged(bio, BIO_CLONED));
7935 bio_for_each_segment_all(bvec, bio, i) {
7936 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7937 bvec->bv_offset, done->start,
7940 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7941 failure_tree, io_tree, done->start,
7943 btrfs_ino(BTRFS_I(inode)),
7949 done->uptodate = uptodate;
7951 complete(&done->done);
7955 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7956 struct btrfs_io_bio *io_bio, blk_status_t err)
7958 struct btrfs_fs_info *fs_info;
7959 struct bio_vec bvec;
7960 struct bvec_iter iter;
7961 struct btrfs_retry_complete done;
7968 bool uptodate = (err == 0);
7970 blk_status_t status;
7972 fs_info = BTRFS_I(inode)->root->fs_info;
7973 sectorsize = fs_info->sectorsize;
7976 start = io_bio->logical;
7978 io_bio->bio.bi_iter = io_bio->iter;
7980 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7981 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7983 pgoff = bvec.bv_offset;
7986 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7987 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7988 bvec.bv_page, pgoff, start, sectorsize);
7995 init_completion(&done.done);
7997 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7998 pgoff, start, start + sectorsize - 1,
7999 io_bio->mirror_num, btrfs_retry_endio,
8006 wait_for_completion_io(&done.done);
8008 if (!done.uptodate) {
8009 /* We might have another mirror, so try again */
8013 offset += sectorsize;
8014 start += sectorsize;
8020 pgoff += sectorsize;
8021 ASSERT(pgoff < PAGE_SIZE);
8029 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8030 struct btrfs_io_bio *io_bio, blk_status_t err)
8032 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8036 return __btrfs_correct_data_nocsum(inode, io_bio);
8040 return __btrfs_subio_endio_read(inode, io_bio, err);
8044 static void btrfs_endio_direct_read(struct bio *bio)
8046 struct btrfs_dio_private *dip = bio->bi_private;
8047 struct inode *inode = dip->inode;
8048 struct bio *dio_bio;
8049 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8050 blk_status_t err = bio->bi_status;
8052 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8053 err = btrfs_subio_endio_read(inode, io_bio, err);
8055 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8056 dip->logical_offset + dip->bytes - 1);
8057 dio_bio = dip->dio_bio;
8061 dio_bio->bi_status = err;
8062 dio_end_io(dio_bio);
8063 btrfs_io_bio_free_csum(io_bio);
8067 static void __endio_write_update_ordered(struct inode *inode,
8068 const u64 offset, const u64 bytes,
8069 const bool uptodate)
8071 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8072 struct btrfs_ordered_extent *ordered = NULL;
8073 struct btrfs_workqueue *wq;
8074 btrfs_work_func_t func;
8075 u64 ordered_offset = offset;
8076 u64 ordered_bytes = bytes;
8079 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8080 wq = fs_info->endio_freespace_worker;
8081 func = btrfs_freespace_write_helper;
8083 wq = fs_info->endio_write_workers;
8084 func = btrfs_endio_write_helper;
8087 while (ordered_offset < offset + bytes) {
8088 last_offset = ordered_offset;
8089 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8093 btrfs_init_work(&ordered->work, func,
8096 btrfs_queue_work(wq, &ordered->work);
8099 * If btrfs_dec_test_ordered_pending does not find any ordered
8100 * extent in the range, we can exit.
8102 if (ordered_offset == last_offset)
8105 * Our bio might span multiple ordered extents. In this case
8106 * we keep going until we have accounted the whole dio.
8108 if (ordered_offset < offset + bytes) {
8109 ordered_bytes = offset + bytes - ordered_offset;
8115 static void btrfs_endio_direct_write(struct bio *bio)
8117 struct btrfs_dio_private *dip = bio->bi_private;
8118 struct bio *dio_bio = dip->dio_bio;
8120 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8121 dip->bytes, !bio->bi_status);
8125 dio_bio->bi_status = bio->bi_status;
8126 dio_end_io(dio_bio);
8130 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8131 struct bio *bio, u64 offset)
8133 struct inode *inode = private_data;
8135 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8136 BUG_ON(ret); /* -ENOMEM */
8140 static void btrfs_end_dio_bio(struct bio *bio)
8142 struct btrfs_dio_private *dip = bio->bi_private;
8143 blk_status_t err = bio->bi_status;
8146 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8147 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8148 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8150 (unsigned long long)bio->bi_iter.bi_sector,
8151 bio->bi_iter.bi_size, err);
8153 if (dip->subio_endio)
8154 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8158 * We want to perceive the errors flag being set before
8159 * decrementing the reference count. We don't need a barrier
8160 * since atomic operations with a return value are fully
8161 * ordered as per atomic_t.txt
8166 /* if there are more bios still pending for this dio, just exit */
8167 if (!atomic_dec_and_test(&dip->pending_bios))
8171 bio_io_error(dip->orig_bio);
8173 dip->dio_bio->bi_status = BLK_STS_OK;
8174 bio_endio(dip->orig_bio);
8180 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8181 struct btrfs_dio_private *dip,
8185 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8186 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8190 * We load all the csum data we need when we submit
8191 * the first bio to reduce the csum tree search and
8194 if (dip->logical_offset == file_offset) {
8195 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8201 if (bio == dip->orig_bio)
8204 file_offset -= dip->logical_offset;
8205 file_offset >>= inode->i_sb->s_blocksize_bits;
8206 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8211 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8212 struct inode *inode, u64 file_offset, int async_submit)
8214 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8215 struct btrfs_dio_private *dip = bio->bi_private;
8216 bool write = bio_op(bio) == REQ_OP_WRITE;
8219 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8221 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8224 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8229 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8232 if (write && async_submit) {
8233 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8235 btrfs_submit_bio_start_direct_io);
8239 * If we aren't doing async submit, calculate the csum of the
8242 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8246 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8252 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8257 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8259 struct inode *inode = dip->inode;
8260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8262 struct bio *orig_bio = dip->orig_bio;
8263 u64 start_sector = orig_bio->bi_iter.bi_sector;
8264 u64 file_offset = dip->logical_offset;
8266 int async_submit = 0;
8268 int clone_offset = 0;
8271 blk_status_t status;
8273 map_length = orig_bio->bi_iter.bi_size;
8274 submit_len = map_length;
8275 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8276 &map_length, NULL, 0);
8280 if (map_length >= submit_len) {
8282 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8286 /* async crcs make it difficult to collect full stripe writes. */
8287 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8293 ASSERT(map_length <= INT_MAX);
8294 atomic_inc(&dip->pending_bios);
8296 clone_len = min_t(int, submit_len, map_length);
8299 * This will never fail as it's passing GPF_NOFS and
8300 * the allocation is backed by btrfs_bioset.
8302 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8304 bio->bi_private = dip;
8305 bio->bi_end_io = btrfs_end_dio_bio;
8306 btrfs_io_bio(bio)->logical = file_offset;
8308 ASSERT(submit_len >= clone_len);
8309 submit_len -= clone_len;
8310 if (submit_len == 0)
8314 * Increase the count before we submit the bio so we know
8315 * the end IO handler won't happen before we increase the
8316 * count. Otherwise, the dip might get freed before we're
8317 * done setting it up.
8319 atomic_inc(&dip->pending_bios);
8321 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8325 atomic_dec(&dip->pending_bios);
8329 clone_offset += clone_len;
8330 start_sector += clone_len >> 9;
8331 file_offset += clone_len;
8333 map_length = submit_len;
8334 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8335 start_sector << 9, &map_length, NULL, 0);
8338 } while (submit_len > 0);
8341 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8349 * Before atomic variable goto zero, we must make sure dip->errors is
8350 * perceived to be set. This ordering is ensured by the fact that an
8351 * atomic operations with a return value are fully ordered as per
8354 if (atomic_dec_and_test(&dip->pending_bios))
8355 bio_io_error(dip->orig_bio);
8357 /* bio_end_io() will handle error, so we needn't return it */
8361 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8364 struct btrfs_dio_private *dip = NULL;
8365 struct bio *bio = NULL;
8366 struct btrfs_io_bio *io_bio;
8367 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8370 bio = btrfs_bio_clone(dio_bio);
8372 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8378 dip->private = dio_bio->bi_private;
8380 dip->logical_offset = file_offset;
8381 dip->bytes = dio_bio->bi_iter.bi_size;
8382 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8383 bio->bi_private = dip;
8384 dip->orig_bio = bio;
8385 dip->dio_bio = dio_bio;
8386 atomic_set(&dip->pending_bios, 0);
8387 io_bio = btrfs_io_bio(bio);
8388 io_bio->logical = file_offset;
8391 bio->bi_end_io = btrfs_endio_direct_write;
8393 bio->bi_end_io = btrfs_endio_direct_read;
8394 dip->subio_endio = btrfs_subio_endio_read;
8398 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8399 * even if we fail to submit a bio, because in such case we do the
8400 * corresponding error handling below and it must not be done a second
8401 * time by btrfs_direct_IO().
8404 struct btrfs_dio_data *dio_data = current->journal_info;
8406 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8408 dio_data->unsubmitted_oe_range_start =
8409 dio_data->unsubmitted_oe_range_end;
8412 ret = btrfs_submit_direct_hook(dip);
8416 btrfs_io_bio_free_csum(io_bio);
8420 * If we arrived here it means either we failed to submit the dip
8421 * or we either failed to clone the dio_bio or failed to allocate the
8422 * dip. If we cloned the dio_bio and allocated the dip, we can just
8423 * call bio_endio against our io_bio so that we get proper resource
8424 * cleanup if we fail to submit the dip, otherwise, we must do the
8425 * same as btrfs_endio_direct_[write|read] because we can't call these
8426 * callbacks - they require an allocated dip and a clone of dio_bio.
8431 * The end io callbacks free our dip, do the final put on bio
8432 * and all the cleanup and final put for dio_bio (through
8439 __endio_write_update_ordered(inode,
8441 dio_bio->bi_iter.bi_size,
8444 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8445 file_offset + dio_bio->bi_iter.bi_size - 1);
8447 dio_bio->bi_status = BLK_STS_IOERR;
8449 * Releases and cleans up our dio_bio, no need to bio_put()
8450 * nor bio_endio()/bio_io_error() against dio_bio.
8452 dio_end_io(dio_bio);
8459 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8460 const struct iov_iter *iter, loff_t offset)
8464 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8465 ssize_t retval = -EINVAL;
8467 if (offset & blocksize_mask)
8470 if (iov_iter_alignment(iter) & blocksize_mask)
8473 /* If this is a write we don't need to check anymore */
8474 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8477 * Check to make sure we don't have duplicate iov_base's in this
8478 * iovec, if so return EINVAL, otherwise we'll get csum errors
8479 * when reading back.
8481 for (seg = 0; seg < iter->nr_segs; seg++) {
8482 for (i = seg + 1; i < iter->nr_segs; i++) {
8483 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8492 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8494 struct file *file = iocb->ki_filp;
8495 struct inode *inode = file->f_mapping->host;
8496 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8497 struct btrfs_dio_data dio_data = { 0 };
8498 struct extent_changeset *data_reserved = NULL;
8499 loff_t offset = iocb->ki_pos;
8503 bool relock = false;
8506 if (check_direct_IO(fs_info, iter, offset))
8509 inode_dio_begin(inode);
8512 * The generic stuff only does filemap_write_and_wait_range, which
8513 * isn't enough if we've written compressed pages to this area, so
8514 * we need to flush the dirty pages again to make absolutely sure
8515 * that any outstanding dirty pages are on disk.
8517 count = iov_iter_count(iter);
8518 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8519 &BTRFS_I(inode)->runtime_flags))
8520 filemap_fdatawrite_range(inode->i_mapping, offset,
8521 offset + count - 1);
8523 if (iov_iter_rw(iter) == WRITE) {
8525 * If the write DIO is beyond the EOF, we need update
8526 * the isize, but it is protected by i_mutex. So we can
8527 * not unlock the i_mutex at this case.
8529 if (offset + count <= inode->i_size) {
8530 dio_data.overwrite = 1;
8531 inode_unlock(inode);
8533 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8537 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8543 * We need to know how many extents we reserved so that we can
8544 * do the accounting properly if we go over the number we
8545 * originally calculated. Abuse current->journal_info for this.
8547 dio_data.reserve = round_up(count,
8548 fs_info->sectorsize);
8549 dio_data.unsubmitted_oe_range_start = (u64)offset;
8550 dio_data.unsubmitted_oe_range_end = (u64)offset;
8551 current->journal_info = &dio_data;
8552 down_read(&BTRFS_I(inode)->dio_sem);
8553 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8554 &BTRFS_I(inode)->runtime_flags)) {
8555 inode_dio_end(inode);
8556 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8560 ret = __blockdev_direct_IO(iocb, inode,
8561 fs_info->fs_devices->latest_bdev,
8562 iter, btrfs_get_blocks_direct, NULL,
8563 btrfs_submit_direct, flags);
8564 if (iov_iter_rw(iter) == WRITE) {
8565 up_read(&BTRFS_I(inode)->dio_sem);
8566 current->journal_info = NULL;
8567 if (ret < 0 && ret != -EIOCBQUEUED) {
8568 if (dio_data.reserve)
8569 btrfs_delalloc_release_space(inode, data_reserved,
8570 offset, dio_data.reserve, true);
8572 * On error we might have left some ordered extents
8573 * without submitting corresponding bios for them, so
8574 * cleanup them up to avoid other tasks getting them
8575 * and waiting for them to complete forever.
8577 if (dio_data.unsubmitted_oe_range_start <
8578 dio_data.unsubmitted_oe_range_end)
8579 __endio_write_update_ordered(inode,
8580 dio_data.unsubmitted_oe_range_start,
8581 dio_data.unsubmitted_oe_range_end -
8582 dio_data.unsubmitted_oe_range_start,
8584 } else if (ret >= 0 && (size_t)ret < count)
8585 btrfs_delalloc_release_space(inode, data_reserved,
8586 offset, count - (size_t)ret, true);
8587 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8591 inode_dio_end(inode);
8595 extent_changeset_free(data_reserved);
8599 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8601 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8602 __u64 start, __u64 len)
8606 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8610 return extent_fiemap(inode, fieinfo, start, len);
8613 int btrfs_readpage(struct file *file, struct page *page)
8615 struct extent_io_tree *tree;
8616 tree = &BTRFS_I(page->mapping->host)->io_tree;
8617 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8620 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8622 struct inode *inode = page->mapping->host;
8625 if (current->flags & PF_MEMALLOC) {
8626 redirty_page_for_writepage(wbc, page);
8632 * If we are under memory pressure we will call this directly from the
8633 * VM, we need to make sure we have the inode referenced for the ordered
8634 * extent. If not just return like we didn't do anything.
8636 if (!igrab(inode)) {
8637 redirty_page_for_writepage(wbc, page);
8638 return AOP_WRITEPAGE_ACTIVATE;
8640 ret = extent_write_full_page(page, wbc);
8641 btrfs_add_delayed_iput(inode);
8645 static int btrfs_writepages(struct address_space *mapping,
8646 struct writeback_control *wbc)
8648 return extent_writepages(mapping, wbc);
8652 btrfs_readpages(struct file *file, struct address_space *mapping,
8653 struct list_head *pages, unsigned nr_pages)
8655 return extent_readpages(mapping, pages, nr_pages);
8658 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8660 int ret = try_release_extent_mapping(page, gfp_flags);
8662 ClearPagePrivate(page);
8663 set_page_private(page, 0);
8669 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8671 if (PageWriteback(page) || PageDirty(page))
8673 return __btrfs_releasepage(page, gfp_flags);
8676 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8677 unsigned int length)
8679 struct inode *inode = page->mapping->host;
8680 struct extent_io_tree *tree;
8681 struct btrfs_ordered_extent *ordered;
8682 struct extent_state *cached_state = NULL;
8683 u64 page_start = page_offset(page);
8684 u64 page_end = page_start + PAGE_SIZE - 1;
8687 int inode_evicting = inode->i_state & I_FREEING;
8690 * we have the page locked, so new writeback can't start,
8691 * and the dirty bit won't be cleared while we are here.
8693 * Wait for IO on this page so that we can safely clear
8694 * the PagePrivate2 bit and do ordered accounting
8696 wait_on_page_writeback(page);
8698 tree = &BTRFS_I(inode)->io_tree;
8700 btrfs_releasepage(page, GFP_NOFS);
8704 if (!inode_evicting)
8705 lock_extent_bits(tree, page_start, page_end, &cached_state);
8708 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8709 page_end - start + 1);
8711 end = min(page_end, ordered->file_offset + ordered->len - 1);
8713 * IO on this page will never be started, so we need
8714 * to account for any ordered extents now
8716 if (!inode_evicting)
8717 clear_extent_bit(tree, start, end,
8718 EXTENT_DIRTY | EXTENT_DELALLOC |
8719 EXTENT_DELALLOC_NEW |
8720 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8721 EXTENT_DEFRAG, 1, 0, &cached_state);
8723 * whoever cleared the private bit is responsible
8724 * for the finish_ordered_io
8726 if (TestClearPagePrivate2(page)) {
8727 struct btrfs_ordered_inode_tree *tree;
8730 tree = &BTRFS_I(inode)->ordered_tree;
8732 spin_lock_irq(&tree->lock);
8733 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8734 new_len = start - ordered->file_offset;
8735 if (new_len < ordered->truncated_len)
8736 ordered->truncated_len = new_len;
8737 spin_unlock_irq(&tree->lock);
8739 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8741 end - start + 1, 1))
8742 btrfs_finish_ordered_io(ordered);
8744 btrfs_put_ordered_extent(ordered);
8745 if (!inode_evicting) {
8746 cached_state = NULL;
8747 lock_extent_bits(tree, start, end,
8752 if (start < page_end)
8757 * Qgroup reserved space handler
8758 * Page here will be either
8759 * 1) Already written to disk
8760 * In this case, its reserved space is released from data rsv map
8761 * and will be freed by delayed_ref handler finally.
8762 * So even we call qgroup_free_data(), it won't decrease reserved
8764 * 2) Not written to disk
8765 * This means the reserved space should be freed here. However,
8766 * if a truncate invalidates the page (by clearing PageDirty)
8767 * and the page is accounted for while allocating extent
8768 * in btrfs_check_data_free_space() we let delayed_ref to
8769 * free the entire extent.
8771 if (PageDirty(page))
8772 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8773 if (!inode_evicting) {
8774 clear_extent_bit(tree, page_start, page_end,
8775 EXTENT_LOCKED | EXTENT_DIRTY |
8776 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8777 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8780 __btrfs_releasepage(page, GFP_NOFS);
8783 ClearPageChecked(page);
8784 if (PagePrivate(page)) {
8785 ClearPagePrivate(page);
8786 set_page_private(page, 0);
8792 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8793 * called from a page fault handler when a page is first dirtied. Hence we must
8794 * be careful to check for EOF conditions here. We set the page up correctly
8795 * for a written page which means we get ENOSPC checking when writing into
8796 * holes and correct delalloc and unwritten extent mapping on filesystems that
8797 * support these features.
8799 * We are not allowed to take the i_mutex here so we have to play games to
8800 * protect against truncate races as the page could now be beyond EOF. Because
8801 * truncate_setsize() writes the inode size before removing pages, once we have
8802 * the page lock we can determine safely if the page is beyond EOF. If it is not
8803 * beyond EOF, then the page is guaranteed safe against truncation until we
8806 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8808 struct page *page = vmf->page;
8809 struct inode *inode = file_inode(vmf->vma->vm_file);
8810 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8811 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8812 struct btrfs_ordered_extent *ordered;
8813 struct extent_state *cached_state = NULL;
8814 struct extent_changeset *data_reserved = NULL;
8816 unsigned long zero_start;
8826 reserved_space = PAGE_SIZE;
8828 sb_start_pagefault(inode->i_sb);
8829 page_start = page_offset(page);
8830 page_end = page_start + PAGE_SIZE - 1;
8834 * Reserving delalloc space after obtaining the page lock can lead to
8835 * deadlock. For example, if a dirty page is locked by this function
8836 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8837 * dirty page write out, then the btrfs_writepage() function could
8838 * end up waiting indefinitely to get a lock on the page currently
8839 * being processed by btrfs_page_mkwrite() function.
8841 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8844 ret2 = file_update_time(vmf->vma->vm_file);
8848 ret = vmf_error(ret2);
8854 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8857 size = i_size_read(inode);
8859 if ((page->mapping != inode->i_mapping) ||
8860 (page_start >= size)) {
8861 /* page got truncated out from underneath us */
8864 wait_on_page_writeback(page);
8866 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8867 set_page_extent_mapped(page);
8870 * we can't set the delalloc bits if there are pending ordered
8871 * extents. Drop our locks and wait for them to finish
8873 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8876 unlock_extent_cached(io_tree, page_start, page_end,
8879 btrfs_start_ordered_extent(inode, ordered, 1);
8880 btrfs_put_ordered_extent(ordered);
8884 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8885 reserved_space = round_up(size - page_start,
8886 fs_info->sectorsize);
8887 if (reserved_space < PAGE_SIZE) {
8888 end = page_start + reserved_space - 1;
8889 btrfs_delalloc_release_space(inode, data_reserved,
8890 page_start, PAGE_SIZE - reserved_space,
8896 * page_mkwrite gets called when the page is firstly dirtied after it's
8897 * faulted in, but write(2) could also dirty a page and set delalloc
8898 * bits, thus in this case for space account reason, we still need to
8899 * clear any delalloc bits within this page range since we have to
8900 * reserve data&meta space before lock_page() (see above comments).
8902 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8903 EXTENT_DIRTY | EXTENT_DELALLOC |
8904 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8905 0, 0, &cached_state);
8907 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8910 unlock_extent_cached(io_tree, page_start, page_end,
8912 ret = VM_FAULT_SIGBUS;
8917 /* page is wholly or partially inside EOF */
8918 if (page_start + PAGE_SIZE > size)
8919 zero_start = offset_in_page(size);
8921 zero_start = PAGE_SIZE;
8923 if (zero_start != PAGE_SIZE) {
8925 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8926 flush_dcache_page(page);
8929 ClearPageChecked(page);
8930 set_page_dirty(page);
8931 SetPageUptodate(page);
8933 BTRFS_I(inode)->last_trans = fs_info->generation;
8934 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8935 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8937 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8940 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8941 sb_end_pagefault(inode->i_sb);
8942 extent_changeset_free(data_reserved);
8943 return VM_FAULT_LOCKED;
8949 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8950 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8951 reserved_space, (ret != 0));
8953 sb_end_pagefault(inode->i_sb);
8954 extent_changeset_free(data_reserved);
8958 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8960 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8961 struct btrfs_root *root = BTRFS_I(inode)->root;
8962 struct btrfs_block_rsv *rsv;
8964 struct btrfs_trans_handle *trans;
8965 u64 mask = fs_info->sectorsize - 1;
8966 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
8968 if (!skip_writeback) {
8969 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8976 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8977 * things going on here:
8979 * 1) We need to reserve space to update our inode.
8981 * 2) We need to have something to cache all the space that is going to
8982 * be free'd up by the truncate operation, but also have some slack
8983 * space reserved in case it uses space during the truncate (thank you
8984 * very much snapshotting).
8986 * And we need these to be separate. The fact is we can use a lot of
8987 * space doing the truncate, and we have no earthly idea how much space
8988 * we will use, so we need the truncate reservation to be separate so it
8989 * doesn't end up using space reserved for updating the inode. We also
8990 * need to be able to stop the transaction and start a new one, which
8991 * means we need to be able to update the inode several times, and we
8992 * have no idea of knowing how many times that will be, so we can't just
8993 * reserve 1 item for the entirety of the operation, so that has to be
8994 * done separately as well.
8996 * So that leaves us with
8998 * 1) rsv - for the truncate reservation, which we will steal from the
8999 * transaction reservation.
9000 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9001 * updating the inode.
9003 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9006 rsv->size = min_size;
9010 * 1 for the truncate slack space
9011 * 1 for updating the inode.
9013 trans = btrfs_start_transaction(root, 2);
9014 if (IS_ERR(trans)) {
9015 ret = PTR_ERR(trans);
9019 /* Migrate the slack space for the truncate to our reserve */
9020 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9025 * So if we truncate and then write and fsync we normally would just
9026 * write the extents that changed, which is a problem if we need to
9027 * first truncate that entire inode. So set this flag so we write out
9028 * all of the extents in the inode to the sync log so we're completely
9031 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9032 trans->block_rsv = rsv;
9035 ret = btrfs_truncate_inode_items(trans, root, inode,
9037 BTRFS_EXTENT_DATA_KEY);
9038 trans->block_rsv = &fs_info->trans_block_rsv;
9039 if (ret != -ENOSPC && ret != -EAGAIN)
9042 ret = btrfs_update_inode(trans, root, inode);
9046 btrfs_end_transaction(trans);
9047 btrfs_btree_balance_dirty(fs_info);
9049 trans = btrfs_start_transaction(root, 2);
9050 if (IS_ERR(trans)) {
9051 ret = PTR_ERR(trans);
9056 btrfs_block_rsv_release(fs_info, rsv, -1);
9057 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9058 rsv, min_size, false);
9059 BUG_ON(ret); /* shouldn't happen */
9060 trans->block_rsv = rsv;
9064 * We can't call btrfs_truncate_block inside a trans handle as we could
9065 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9066 * we've truncated everything except the last little bit, and can do
9067 * btrfs_truncate_block and then update the disk_i_size.
9069 if (ret == NEED_TRUNCATE_BLOCK) {
9070 btrfs_end_transaction(trans);
9071 btrfs_btree_balance_dirty(fs_info);
9073 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9076 trans = btrfs_start_transaction(root, 1);
9077 if (IS_ERR(trans)) {
9078 ret = PTR_ERR(trans);
9081 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9087 trans->block_rsv = &fs_info->trans_block_rsv;
9088 ret2 = btrfs_update_inode(trans, root, inode);
9092 ret2 = btrfs_end_transaction(trans);
9095 btrfs_btree_balance_dirty(fs_info);
9098 btrfs_free_block_rsv(fs_info, rsv);
9104 * create a new subvolume directory/inode (helper for the ioctl).
9106 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9107 struct btrfs_root *new_root,
9108 struct btrfs_root *parent_root,
9111 struct inode *inode;
9115 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9116 new_dirid, new_dirid,
9117 S_IFDIR | (~current_umask() & S_IRWXUGO),
9120 return PTR_ERR(inode);
9121 inode->i_op = &btrfs_dir_inode_operations;
9122 inode->i_fop = &btrfs_dir_file_operations;
9124 set_nlink(inode, 1);
9125 btrfs_i_size_write(BTRFS_I(inode), 0);
9126 unlock_new_inode(inode);
9128 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9130 btrfs_err(new_root->fs_info,
9131 "error inheriting subvolume %llu properties: %d",
9132 new_root->root_key.objectid, err);
9134 err = btrfs_update_inode(trans, new_root, inode);
9140 struct inode *btrfs_alloc_inode(struct super_block *sb)
9142 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9143 struct btrfs_inode *ei;
9144 struct inode *inode;
9146 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9153 ei->last_sub_trans = 0;
9154 ei->logged_trans = 0;
9155 ei->delalloc_bytes = 0;
9156 ei->new_delalloc_bytes = 0;
9157 ei->defrag_bytes = 0;
9158 ei->disk_i_size = 0;
9161 ei->index_cnt = (u64)-1;
9163 ei->last_unlink_trans = 0;
9164 ei->last_link_trans = 0;
9165 ei->last_log_commit = 0;
9167 spin_lock_init(&ei->lock);
9168 ei->outstanding_extents = 0;
9169 if (sb->s_magic != BTRFS_TEST_MAGIC)
9170 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9171 BTRFS_BLOCK_RSV_DELALLOC);
9172 ei->runtime_flags = 0;
9173 ei->prop_compress = BTRFS_COMPRESS_NONE;
9174 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9176 ei->delayed_node = NULL;
9178 ei->i_otime.tv_sec = 0;
9179 ei->i_otime.tv_nsec = 0;
9181 inode = &ei->vfs_inode;
9182 extent_map_tree_init(&ei->extent_tree);
9183 extent_io_tree_init(&ei->io_tree, inode);
9184 extent_io_tree_init(&ei->io_failure_tree, inode);
9185 ei->io_tree.track_uptodate = 1;
9186 ei->io_failure_tree.track_uptodate = 1;
9187 atomic_set(&ei->sync_writers, 0);
9188 mutex_init(&ei->log_mutex);
9189 mutex_init(&ei->delalloc_mutex);
9190 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9191 INIT_LIST_HEAD(&ei->delalloc_inodes);
9192 INIT_LIST_HEAD(&ei->delayed_iput);
9193 RB_CLEAR_NODE(&ei->rb_node);
9194 init_rwsem(&ei->dio_sem);
9199 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9200 void btrfs_test_destroy_inode(struct inode *inode)
9202 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9203 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9207 static void btrfs_i_callback(struct rcu_head *head)
9209 struct inode *inode = container_of(head, struct inode, i_rcu);
9210 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9213 void btrfs_destroy_inode(struct inode *inode)
9215 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9216 struct btrfs_ordered_extent *ordered;
9217 struct btrfs_root *root = BTRFS_I(inode)->root;
9219 WARN_ON(!hlist_empty(&inode->i_dentry));
9220 WARN_ON(inode->i_data.nrpages);
9221 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9222 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9223 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9224 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9225 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9226 WARN_ON(BTRFS_I(inode)->csum_bytes);
9227 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9230 * This can happen where we create an inode, but somebody else also
9231 * created the same inode and we need to destroy the one we already
9238 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9243 "found ordered extent %llu %llu on inode cleanup",
9244 ordered->file_offset, ordered->len);
9245 btrfs_remove_ordered_extent(inode, ordered);
9246 btrfs_put_ordered_extent(ordered);
9247 btrfs_put_ordered_extent(ordered);
9250 btrfs_qgroup_check_reserved_leak(inode);
9251 inode_tree_del(inode);
9252 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9254 call_rcu(&inode->i_rcu, btrfs_i_callback);
9257 int btrfs_drop_inode(struct inode *inode)
9259 struct btrfs_root *root = BTRFS_I(inode)->root;
9264 /* the snap/subvol tree is on deleting */
9265 if (btrfs_root_refs(&root->root_item) == 0)
9268 return generic_drop_inode(inode);
9271 static void init_once(void *foo)
9273 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9275 inode_init_once(&ei->vfs_inode);
9278 void __cold btrfs_destroy_cachep(void)
9281 * Make sure all delayed rcu free inodes are flushed before we
9285 kmem_cache_destroy(btrfs_inode_cachep);
9286 kmem_cache_destroy(btrfs_trans_handle_cachep);
9287 kmem_cache_destroy(btrfs_path_cachep);
9288 kmem_cache_destroy(btrfs_free_space_cachep);
9291 int __init btrfs_init_cachep(void)
9293 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9294 sizeof(struct btrfs_inode), 0,
9295 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9297 if (!btrfs_inode_cachep)
9300 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9301 sizeof(struct btrfs_trans_handle), 0,
9302 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9303 if (!btrfs_trans_handle_cachep)
9306 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9307 sizeof(struct btrfs_path), 0,
9308 SLAB_MEM_SPREAD, NULL);
9309 if (!btrfs_path_cachep)
9312 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9313 sizeof(struct btrfs_free_space), 0,
9314 SLAB_MEM_SPREAD, NULL);
9315 if (!btrfs_free_space_cachep)
9320 btrfs_destroy_cachep();
9324 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9325 u32 request_mask, unsigned int flags)
9328 struct inode *inode = d_inode(path->dentry);
9329 u32 blocksize = inode->i_sb->s_blocksize;
9330 u32 bi_flags = BTRFS_I(inode)->flags;
9332 stat->result_mask |= STATX_BTIME;
9333 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9334 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9335 if (bi_flags & BTRFS_INODE_APPEND)
9336 stat->attributes |= STATX_ATTR_APPEND;
9337 if (bi_flags & BTRFS_INODE_COMPRESS)
9338 stat->attributes |= STATX_ATTR_COMPRESSED;
9339 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9340 stat->attributes |= STATX_ATTR_IMMUTABLE;
9341 if (bi_flags & BTRFS_INODE_NODUMP)
9342 stat->attributes |= STATX_ATTR_NODUMP;
9344 stat->attributes_mask |= (STATX_ATTR_APPEND |
9345 STATX_ATTR_COMPRESSED |
9346 STATX_ATTR_IMMUTABLE |
9349 generic_fillattr(inode, stat);
9350 stat->dev = BTRFS_I(inode)->root->anon_dev;
9352 spin_lock(&BTRFS_I(inode)->lock);
9353 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9354 spin_unlock(&BTRFS_I(inode)->lock);
9355 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9356 ALIGN(delalloc_bytes, blocksize)) >> 9;
9360 static int btrfs_rename_exchange(struct inode *old_dir,
9361 struct dentry *old_dentry,
9362 struct inode *new_dir,
9363 struct dentry *new_dentry)
9365 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9366 struct btrfs_trans_handle *trans;
9367 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9368 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9369 struct inode *new_inode = new_dentry->d_inode;
9370 struct inode *old_inode = old_dentry->d_inode;
9371 struct timespec64 ctime = current_time(old_inode);
9372 struct dentry *parent;
9373 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9374 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9379 bool root_log_pinned = false;
9380 bool dest_log_pinned = false;
9381 struct btrfs_log_ctx ctx_root;
9382 struct btrfs_log_ctx ctx_dest;
9383 bool sync_log_root = false;
9384 bool sync_log_dest = false;
9385 bool commit_transaction = false;
9387 /* we only allow rename subvolume link between subvolumes */
9388 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9391 btrfs_init_log_ctx(&ctx_root, old_inode);
9392 btrfs_init_log_ctx(&ctx_dest, new_inode);
9394 /* close the race window with snapshot create/destroy ioctl */
9395 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9396 down_read(&fs_info->subvol_sem);
9397 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9398 down_read(&fs_info->subvol_sem);
9401 * We want to reserve the absolute worst case amount of items. So if
9402 * both inodes are subvols and we need to unlink them then that would
9403 * require 4 item modifications, but if they are both normal inodes it
9404 * would require 5 item modifications, so we'll assume their normal
9405 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9406 * should cover the worst case number of items we'll modify.
9408 trans = btrfs_start_transaction(root, 12);
9409 if (IS_ERR(trans)) {
9410 ret = PTR_ERR(trans);
9415 * We need to find a free sequence number both in the source and
9416 * in the destination directory for the exchange.
9418 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9421 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9425 BTRFS_I(old_inode)->dir_index = 0ULL;
9426 BTRFS_I(new_inode)->dir_index = 0ULL;
9428 /* Reference for the source. */
9429 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9430 /* force full log commit if subvolume involved. */
9431 btrfs_set_log_full_commit(fs_info, trans);
9433 btrfs_pin_log_trans(root);
9434 root_log_pinned = true;
9435 ret = btrfs_insert_inode_ref(trans, dest,
9436 new_dentry->d_name.name,
9437 new_dentry->d_name.len,
9439 btrfs_ino(BTRFS_I(new_dir)),
9445 /* And now for the dest. */
9446 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9447 /* force full log commit if subvolume involved. */
9448 btrfs_set_log_full_commit(fs_info, trans);
9450 btrfs_pin_log_trans(dest);
9451 dest_log_pinned = true;
9452 ret = btrfs_insert_inode_ref(trans, root,
9453 old_dentry->d_name.name,
9454 old_dentry->d_name.len,
9456 btrfs_ino(BTRFS_I(old_dir)),
9462 /* Update inode version and ctime/mtime. */
9463 inode_inc_iversion(old_dir);
9464 inode_inc_iversion(new_dir);
9465 inode_inc_iversion(old_inode);
9466 inode_inc_iversion(new_inode);
9467 old_dir->i_ctime = old_dir->i_mtime = ctime;
9468 new_dir->i_ctime = new_dir->i_mtime = ctime;
9469 old_inode->i_ctime = ctime;
9470 new_inode->i_ctime = ctime;
9472 if (old_dentry->d_parent != new_dentry->d_parent) {
9473 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9474 BTRFS_I(old_inode), 1);
9475 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9476 BTRFS_I(new_inode), 1);
9479 /* src is a subvolume */
9480 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9481 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9482 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9483 old_dentry->d_name.name,
9484 old_dentry->d_name.len);
9485 } else { /* src is an inode */
9486 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9487 BTRFS_I(old_dentry->d_inode),
9488 old_dentry->d_name.name,
9489 old_dentry->d_name.len);
9491 ret = btrfs_update_inode(trans, root, old_inode);
9494 btrfs_abort_transaction(trans, ret);
9498 /* dest is a subvolume */
9499 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9500 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9501 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9502 new_dentry->d_name.name,
9503 new_dentry->d_name.len);
9504 } else { /* dest is an inode */
9505 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9506 BTRFS_I(new_dentry->d_inode),
9507 new_dentry->d_name.name,
9508 new_dentry->d_name.len);
9510 ret = btrfs_update_inode(trans, dest, new_inode);
9513 btrfs_abort_transaction(trans, ret);
9517 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9518 new_dentry->d_name.name,
9519 new_dentry->d_name.len, 0, old_idx);
9521 btrfs_abort_transaction(trans, ret);
9525 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9526 old_dentry->d_name.name,
9527 old_dentry->d_name.len, 0, new_idx);
9529 btrfs_abort_transaction(trans, ret);
9533 if (old_inode->i_nlink == 1)
9534 BTRFS_I(old_inode)->dir_index = old_idx;
9535 if (new_inode->i_nlink == 1)
9536 BTRFS_I(new_inode)->dir_index = new_idx;
9538 if (root_log_pinned) {
9539 parent = new_dentry->d_parent;
9540 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9541 BTRFS_I(old_dir), parent,
9543 if (ret == BTRFS_NEED_LOG_SYNC)
9544 sync_log_root = true;
9545 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9546 commit_transaction = true;
9548 btrfs_end_log_trans(root);
9549 root_log_pinned = false;
9551 if (dest_log_pinned) {
9552 if (!commit_transaction) {
9553 parent = old_dentry->d_parent;
9554 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9555 BTRFS_I(new_dir), parent,
9557 if (ret == BTRFS_NEED_LOG_SYNC)
9558 sync_log_dest = true;
9559 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9560 commit_transaction = true;
9563 btrfs_end_log_trans(dest);
9564 dest_log_pinned = false;
9568 * If we have pinned a log and an error happened, we unpin tasks
9569 * trying to sync the log and force them to fallback to a transaction
9570 * commit if the log currently contains any of the inodes involved in
9571 * this rename operation (to ensure we do not persist a log with an
9572 * inconsistent state for any of these inodes or leading to any
9573 * inconsistencies when replayed). If the transaction was aborted, the
9574 * abortion reason is propagated to userspace when attempting to commit
9575 * the transaction. If the log does not contain any of these inodes, we
9576 * allow the tasks to sync it.
9578 if (ret && (root_log_pinned || dest_log_pinned)) {
9579 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9580 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9581 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9583 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9584 btrfs_set_log_full_commit(fs_info, trans);
9586 if (root_log_pinned) {
9587 btrfs_end_log_trans(root);
9588 root_log_pinned = false;
9590 if (dest_log_pinned) {
9591 btrfs_end_log_trans(dest);
9592 dest_log_pinned = false;
9595 if (!ret && sync_log_root && !commit_transaction) {
9596 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9599 commit_transaction = true;
9601 if (!ret && sync_log_dest && !commit_transaction) {
9602 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9605 commit_transaction = true;
9607 if (commit_transaction) {
9608 ret = btrfs_commit_transaction(trans);
9612 ret2 = btrfs_end_transaction(trans);
9613 ret = ret ? ret : ret2;
9616 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9617 up_read(&fs_info->subvol_sem);
9618 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9619 up_read(&fs_info->subvol_sem);
9624 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9625 struct btrfs_root *root,
9627 struct dentry *dentry)
9630 struct inode *inode;
9634 ret = btrfs_find_free_ino(root, &objectid);
9638 inode = btrfs_new_inode(trans, root, dir,
9639 dentry->d_name.name,
9641 btrfs_ino(BTRFS_I(dir)),
9643 S_IFCHR | WHITEOUT_MODE,
9646 if (IS_ERR(inode)) {
9647 ret = PTR_ERR(inode);
9651 inode->i_op = &btrfs_special_inode_operations;
9652 init_special_inode(inode, inode->i_mode,
9655 ret = btrfs_init_inode_security(trans, inode, dir,
9660 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9661 BTRFS_I(inode), 0, index);
9665 ret = btrfs_update_inode(trans, root, inode);
9667 unlock_new_inode(inode);
9669 inode_dec_link_count(inode);
9675 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9676 struct inode *new_dir, struct dentry *new_dentry,
9679 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9680 struct btrfs_trans_handle *trans;
9681 unsigned int trans_num_items;
9682 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9683 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9684 struct inode *new_inode = d_inode(new_dentry);
9685 struct inode *old_inode = d_inode(old_dentry);
9689 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9690 bool log_pinned = false;
9691 struct btrfs_log_ctx ctx;
9692 bool sync_log = false;
9693 bool commit_transaction = false;
9695 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9698 /* we only allow rename subvolume link between subvolumes */
9699 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9702 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9703 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9706 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9707 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9711 /* check for collisions, even if the name isn't there */
9712 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9713 new_dentry->d_name.name,
9714 new_dentry->d_name.len);
9717 if (ret == -EEXIST) {
9719 * eexist without a new_inode */
9720 if (WARN_ON(!new_inode)) {
9724 /* maybe -EOVERFLOW */
9731 * we're using rename to replace one file with another. Start IO on it
9732 * now so we don't add too much work to the end of the transaction
9734 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9735 filemap_flush(old_inode->i_mapping);
9737 /* close the racy window with snapshot create/destroy ioctl */
9738 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9739 down_read(&fs_info->subvol_sem);
9741 * We want to reserve the absolute worst case amount of items. So if
9742 * both inodes are subvols and we need to unlink them then that would
9743 * require 4 item modifications, but if they are both normal inodes it
9744 * would require 5 item modifications, so we'll assume they are normal
9745 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9746 * should cover the worst case number of items we'll modify.
9747 * If our rename has the whiteout flag, we need more 5 units for the
9748 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9749 * when selinux is enabled).
9751 trans_num_items = 11;
9752 if (flags & RENAME_WHITEOUT)
9753 trans_num_items += 5;
9754 trans = btrfs_start_transaction(root, trans_num_items);
9755 if (IS_ERR(trans)) {
9756 ret = PTR_ERR(trans);
9761 btrfs_record_root_in_trans(trans, dest);
9763 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9767 BTRFS_I(old_inode)->dir_index = 0ULL;
9768 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9769 /* force full log commit if subvolume involved. */
9770 btrfs_set_log_full_commit(fs_info, trans);
9772 btrfs_pin_log_trans(root);
9774 ret = btrfs_insert_inode_ref(trans, dest,
9775 new_dentry->d_name.name,
9776 new_dentry->d_name.len,
9778 btrfs_ino(BTRFS_I(new_dir)), index);
9783 inode_inc_iversion(old_dir);
9784 inode_inc_iversion(new_dir);
9785 inode_inc_iversion(old_inode);
9786 old_dir->i_ctime = old_dir->i_mtime =
9787 new_dir->i_ctime = new_dir->i_mtime =
9788 old_inode->i_ctime = current_time(old_dir);
9790 if (old_dentry->d_parent != new_dentry->d_parent)
9791 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9792 BTRFS_I(old_inode), 1);
9794 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9795 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9796 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9797 old_dentry->d_name.name,
9798 old_dentry->d_name.len);
9800 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9801 BTRFS_I(d_inode(old_dentry)),
9802 old_dentry->d_name.name,
9803 old_dentry->d_name.len);
9805 ret = btrfs_update_inode(trans, root, old_inode);
9808 btrfs_abort_transaction(trans, ret);
9813 inode_inc_iversion(new_inode);
9814 new_inode->i_ctime = current_time(new_inode);
9815 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9816 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9817 root_objectid = BTRFS_I(new_inode)->location.objectid;
9818 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9819 new_dentry->d_name.name,
9820 new_dentry->d_name.len);
9821 BUG_ON(new_inode->i_nlink == 0);
9823 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9824 BTRFS_I(d_inode(new_dentry)),
9825 new_dentry->d_name.name,
9826 new_dentry->d_name.len);
9828 if (!ret && new_inode->i_nlink == 0)
9829 ret = btrfs_orphan_add(trans,
9830 BTRFS_I(d_inode(new_dentry)));
9832 btrfs_abort_transaction(trans, ret);
9837 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9838 new_dentry->d_name.name,
9839 new_dentry->d_name.len, 0, index);
9841 btrfs_abort_transaction(trans, ret);
9845 if (old_inode->i_nlink == 1)
9846 BTRFS_I(old_inode)->dir_index = index;
9849 struct dentry *parent = new_dentry->d_parent;
9851 btrfs_init_log_ctx(&ctx, old_inode);
9852 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9853 BTRFS_I(old_dir), parent,
9855 if (ret == BTRFS_NEED_LOG_SYNC)
9857 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9858 commit_transaction = true;
9860 btrfs_end_log_trans(root);
9864 if (flags & RENAME_WHITEOUT) {
9865 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9869 btrfs_abort_transaction(trans, ret);
9875 * If we have pinned the log and an error happened, we unpin tasks
9876 * trying to sync the log and force them to fallback to a transaction
9877 * commit if the log currently contains any of the inodes involved in
9878 * this rename operation (to ensure we do not persist a log with an
9879 * inconsistent state for any of these inodes or leading to any
9880 * inconsistencies when replayed). If the transaction was aborted, the
9881 * abortion reason is propagated to userspace when attempting to commit
9882 * the transaction. If the log does not contain any of these inodes, we
9883 * allow the tasks to sync it.
9885 if (ret && log_pinned) {
9886 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9887 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9888 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9890 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9891 btrfs_set_log_full_commit(fs_info, trans);
9893 btrfs_end_log_trans(root);
9896 if (!ret && sync_log) {
9897 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9899 commit_transaction = true;
9901 if (commit_transaction) {
9902 ret = btrfs_commit_transaction(trans);
9906 ret2 = btrfs_end_transaction(trans);
9907 ret = ret ? ret : ret2;
9910 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9911 up_read(&fs_info->subvol_sem);
9916 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9917 struct inode *new_dir, struct dentry *new_dentry,
9920 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9923 if (flags & RENAME_EXCHANGE)
9924 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9927 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9930 struct btrfs_delalloc_work {
9931 struct inode *inode;
9932 struct completion completion;
9933 struct list_head list;
9934 struct btrfs_work work;
9937 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9939 struct btrfs_delalloc_work *delalloc_work;
9940 struct inode *inode;
9942 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9944 inode = delalloc_work->inode;
9945 filemap_flush(inode->i_mapping);
9946 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9947 &BTRFS_I(inode)->runtime_flags))
9948 filemap_flush(inode->i_mapping);
9951 complete(&delalloc_work->completion);
9954 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9956 struct btrfs_delalloc_work *work;
9958 work = kmalloc(sizeof(*work), GFP_NOFS);
9962 init_completion(&work->completion);
9963 INIT_LIST_HEAD(&work->list);
9964 work->inode = inode;
9965 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9966 btrfs_run_delalloc_work, NULL, NULL);
9972 * some fairly slow code that needs optimization. This walks the list
9973 * of all the inodes with pending delalloc and forces them to disk.
9975 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9977 struct btrfs_inode *binode;
9978 struct inode *inode;
9979 struct btrfs_delalloc_work *work, *next;
9980 struct list_head works;
9981 struct list_head splice;
9984 INIT_LIST_HEAD(&works);
9985 INIT_LIST_HEAD(&splice);
9987 mutex_lock(&root->delalloc_mutex);
9988 spin_lock(&root->delalloc_lock);
9989 list_splice_init(&root->delalloc_inodes, &splice);
9990 while (!list_empty(&splice)) {
9991 binode = list_entry(splice.next, struct btrfs_inode,
9994 list_move_tail(&binode->delalloc_inodes,
9995 &root->delalloc_inodes);
9996 inode = igrab(&binode->vfs_inode);
9998 cond_resched_lock(&root->delalloc_lock);
10001 spin_unlock(&root->delalloc_lock);
10004 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10005 &binode->runtime_flags);
10006 work = btrfs_alloc_delalloc_work(inode);
10012 list_add_tail(&work->list, &works);
10013 btrfs_queue_work(root->fs_info->flush_workers,
10016 if (nr != -1 && ret >= nr)
10019 spin_lock(&root->delalloc_lock);
10021 spin_unlock(&root->delalloc_lock);
10024 list_for_each_entry_safe(work, next, &works, list) {
10025 list_del_init(&work->list);
10026 wait_for_completion(&work->completion);
10030 if (!list_empty(&splice)) {
10031 spin_lock(&root->delalloc_lock);
10032 list_splice_tail(&splice, &root->delalloc_inodes);
10033 spin_unlock(&root->delalloc_lock);
10035 mutex_unlock(&root->delalloc_mutex);
10039 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10041 struct btrfs_fs_info *fs_info = root->fs_info;
10044 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10047 ret = start_delalloc_inodes(root, -1, true);
10053 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10055 struct btrfs_root *root;
10056 struct list_head splice;
10059 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10062 INIT_LIST_HEAD(&splice);
10064 mutex_lock(&fs_info->delalloc_root_mutex);
10065 spin_lock(&fs_info->delalloc_root_lock);
10066 list_splice_init(&fs_info->delalloc_roots, &splice);
10067 while (!list_empty(&splice) && nr) {
10068 root = list_first_entry(&splice, struct btrfs_root,
10070 root = btrfs_grab_fs_root(root);
10072 list_move_tail(&root->delalloc_root,
10073 &fs_info->delalloc_roots);
10074 spin_unlock(&fs_info->delalloc_root_lock);
10076 ret = start_delalloc_inodes(root, nr, false);
10077 btrfs_put_fs_root(root);
10085 spin_lock(&fs_info->delalloc_root_lock);
10087 spin_unlock(&fs_info->delalloc_root_lock);
10091 if (!list_empty(&splice)) {
10092 spin_lock(&fs_info->delalloc_root_lock);
10093 list_splice_tail(&splice, &fs_info->delalloc_roots);
10094 spin_unlock(&fs_info->delalloc_root_lock);
10096 mutex_unlock(&fs_info->delalloc_root_mutex);
10100 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10101 const char *symname)
10103 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10104 struct btrfs_trans_handle *trans;
10105 struct btrfs_root *root = BTRFS_I(dir)->root;
10106 struct btrfs_path *path;
10107 struct btrfs_key key;
10108 struct inode *inode = NULL;
10115 struct btrfs_file_extent_item *ei;
10116 struct extent_buffer *leaf;
10118 name_len = strlen(symname);
10119 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10120 return -ENAMETOOLONG;
10123 * 2 items for inode item and ref
10124 * 2 items for dir items
10125 * 1 item for updating parent inode item
10126 * 1 item for the inline extent item
10127 * 1 item for xattr if selinux is on
10129 trans = btrfs_start_transaction(root, 7);
10131 return PTR_ERR(trans);
10133 err = btrfs_find_free_ino(root, &objectid);
10137 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10138 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10139 objectid, S_IFLNK|S_IRWXUGO, &index);
10140 if (IS_ERR(inode)) {
10141 err = PTR_ERR(inode);
10147 * If the active LSM wants to access the inode during
10148 * d_instantiate it needs these. Smack checks to see
10149 * if the filesystem supports xattrs by looking at the
10152 inode->i_fop = &btrfs_file_operations;
10153 inode->i_op = &btrfs_file_inode_operations;
10154 inode->i_mapping->a_ops = &btrfs_aops;
10155 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10157 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10161 path = btrfs_alloc_path();
10166 key.objectid = btrfs_ino(BTRFS_I(inode));
10168 key.type = BTRFS_EXTENT_DATA_KEY;
10169 datasize = btrfs_file_extent_calc_inline_size(name_len);
10170 err = btrfs_insert_empty_item(trans, root, path, &key,
10173 btrfs_free_path(path);
10176 leaf = path->nodes[0];
10177 ei = btrfs_item_ptr(leaf, path->slots[0],
10178 struct btrfs_file_extent_item);
10179 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10180 btrfs_set_file_extent_type(leaf, ei,
10181 BTRFS_FILE_EXTENT_INLINE);
10182 btrfs_set_file_extent_encryption(leaf, ei, 0);
10183 btrfs_set_file_extent_compression(leaf, ei, 0);
10184 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10185 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10187 ptr = btrfs_file_extent_inline_start(ei);
10188 write_extent_buffer(leaf, symname, ptr, name_len);
10189 btrfs_mark_buffer_dirty(leaf);
10190 btrfs_free_path(path);
10192 inode->i_op = &btrfs_symlink_inode_operations;
10193 inode_nohighmem(inode);
10194 inode->i_mapping->a_ops = &btrfs_aops;
10195 inode_set_bytes(inode, name_len);
10196 btrfs_i_size_write(BTRFS_I(inode), name_len);
10197 err = btrfs_update_inode(trans, root, inode);
10199 * Last step, add directory indexes for our symlink inode. This is the
10200 * last step to avoid extra cleanup of these indexes if an error happens
10204 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10205 BTRFS_I(inode), 0, index);
10209 d_instantiate_new(dentry, inode);
10212 btrfs_end_transaction(trans);
10213 if (err && inode) {
10214 inode_dec_link_count(inode);
10215 discard_new_inode(inode);
10217 btrfs_btree_balance_dirty(fs_info);
10221 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10222 u64 start, u64 num_bytes, u64 min_size,
10223 loff_t actual_len, u64 *alloc_hint,
10224 struct btrfs_trans_handle *trans)
10226 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10227 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10228 struct extent_map *em;
10229 struct btrfs_root *root = BTRFS_I(inode)->root;
10230 struct btrfs_key ins;
10231 u64 cur_offset = start;
10234 u64 last_alloc = (u64)-1;
10236 bool own_trans = true;
10237 u64 end = start + num_bytes - 1;
10241 while (num_bytes > 0) {
10243 trans = btrfs_start_transaction(root, 3);
10244 if (IS_ERR(trans)) {
10245 ret = PTR_ERR(trans);
10250 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10251 cur_bytes = max(cur_bytes, min_size);
10253 * If we are severely fragmented we could end up with really
10254 * small allocations, so if the allocator is returning small
10255 * chunks lets make its job easier by only searching for those
10258 cur_bytes = min(cur_bytes, last_alloc);
10259 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10260 min_size, 0, *alloc_hint, &ins, 1, 0);
10263 btrfs_end_transaction(trans);
10266 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10268 last_alloc = ins.offset;
10269 ret = insert_reserved_file_extent(trans, inode,
10270 cur_offset, ins.objectid,
10271 ins.offset, ins.offset,
10272 ins.offset, 0, 0, 0,
10273 BTRFS_FILE_EXTENT_PREALLOC);
10275 btrfs_free_reserved_extent(fs_info, ins.objectid,
10277 btrfs_abort_transaction(trans, ret);
10279 btrfs_end_transaction(trans);
10283 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10284 cur_offset + ins.offset -1, 0);
10286 em = alloc_extent_map();
10288 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10289 &BTRFS_I(inode)->runtime_flags);
10293 em->start = cur_offset;
10294 em->orig_start = cur_offset;
10295 em->len = ins.offset;
10296 em->block_start = ins.objectid;
10297 em->block_len = ins.offset;
10298 em->orig_block_len = ins.offset;
10299 em->ram_bytes = ins.offset;
10300 em->bdev = fs_info->fs_devices->latest_bdev;
10301 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10302 em->generation = trans->transid;
10305 write_lock(&em_tree->lock);
10306 ret = add_extent_mapping(em_tree, em, 1);
10307 write_unlock(&em_tree->lock);
10308 if (ret != -EEXIST)
10310 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10311 cur_offset + ins.offset - 1,
10314 free_extent_map(em);
10316 num_bytes -= ins.offset;
10317 cur_offset += ins.offset;
10318 *alloc_hint = ins.objectid + ins.offset;
10320 inode_inc_iversion(inode);
10321 inode->i_ctime = current_time(inode);
10322 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10323 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10324 (actual_len > inode->i_size) &&
10325 (cur_offset > inode->i_size)) {
10326 if (cur_offset > actual_len)
10327 i_size = actual_len;
10329 i_size = cur_offset;
10330 i_size_write(inode, i_size);
10331 btrfs_ordered_update_i_size(inode, i_size, NULL);
10334 ret = btrfs_update_inode(trans, root, inode);
10337 btrfs_abort_transaction(trans, ret);
10339 btrfs_end_transaction(trans);
10344 btrfs_end_transaction(trans);
10346 if (cur_offset < end)
10347 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10348 end - cur_offset + 1);
10352 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10353 u64 start, u64 num_bytes, u64 min_size,
10354 loff_t actual_len, u64 *alloc_hint)
10356 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10357 min_size, actual_len, alloc_hint,
10361 int btrfs_prealloc_file_range_trans(struct inode *inode,
10362 struct btrfs_trans_handle *trans, int mode,
10363 u64 start, u64 num_bytes, u64 min_size,
10364 loff_t actual_len, u64 *alloc_hint)
10366 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10367 min_size, actual_len, alloc_hint, trans);
10370 static int btrfs_set_page_dirty(struct page *page)
10372 return __set_page_dirty_nobuffers(page);
10375 static int btrfs_permission(struct inode *inode, int mask)
10377 struct btrfs_root *root = BTRFS_I(inode)->root;
10378 umode_t mode = inode->i_mode;
10380 if (mask & MAY_WRITE &&
10381 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10382 if (btrfs_root_readonly(root))
10384 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10387 return generic_permission(inode, mask);
10390 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10392 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10393 struct btrfs_trans_handle *trans;
10394 struct btrfs_root *root = BTRFS_I(dir)->root;
10395 struct inode *inode = NULL;
10401 * 5 units required for adding orphan entry
10403 trans = btrfs_start_transaction(root, 5);
10405 return PTR_ERR(trans);
10407 ret = btrfs_find_free_ino(root, &objectid);
10411 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10412 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10413 if (IS_ERR(inode)) {
10414 ret = PTR_ERR(inode);
10419 inode->i_fop = &btrfs_file_operations;
10420 inode->i_op = &btrfs_file_inode_operations;
10422 inode->i_mapping->a_ops = &btrfs_aops;
10423 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10425 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10429 ret = btrfs_update_inode(trans, root, inode);
10432 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10437 * We set number of links to 0 in btrfs_new_inode(), and here we set
10438 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10441 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10443 set_nlink(inode, 1);
10444 d_tmpfile(dentry, inode);
10445 unlock_new_inode(inode);
10446 mark_inode_dirty(inode);
10448 btrfs_end_transaction(trans);
10450 discard_new_inode(inode);
10451 btrfs_btree_balance_dirty(fs_info);
10455 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10457 struct inode *inode = tree->private_data;
10458 unsigned long index = start >> PAGE_SHIFT;
10459 unsigned long end_index = end >> PAGE_SHIFT;
10462 while (index <= end_index) {
10463 page = find_get_page(inode->i_mapping, index);
10464 ASSERT(page); /* Pages should be in the extent_io_tree */
10465 set_page_writeback(page);
10473 * Add an entry indicating a block group or device which is pinned by a
10474 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10475 * negative errno on failure.
10477 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10478 bool is_block_group)
10480 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10481 struct btrfs_swapfile_pin *sp, *entry;
10482 struct rb_node **p;
10483 struct rb_node *parent = NULL;
10485 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10490 sp->is_block_group = is_block_group;
10492 spin_lock(&fs_info->swapfile_pins_lock);
10493 p = &fs_info->swapfile_pins.rb_node;
10496 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10497 if (sp->ptr < entry->ptr ||
10498 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10499 p = &(*p)->rb_left;
10500 } else if (sp->ptr > entry->ptr ||
10501 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10502 p = &(*p)->rb_right;
10504 spin_unlock(&fs_info->swapfile_pins_lock);
10509 rb_link_node(&sp->node, parent, p);
10510 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10511 spin_unlock(&fs_info->swapfile_pins_lock);
10515 /* Free all of the entries pinned by this swapfile. */
10516 static void btrfs_free_swapfile_pins(struct inode *inode)
10518 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10519 struct btrfs_swapfile_pin *sp;
10520 struct rb_node *node, *next;
10522 spin_lock(&fs_info->swapfile_pins_lock);
10523 node = rb_first(&fs_info->swapfile_pins);
10525 next = rb_next(node);
10526 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10527 if (sp->inode == inode) {
10528 rb_erase(&sp->node, &fs_info->swapfile_pins);
10529 if (sp->is_block_group)
10530 btrfs_put_block_group(sp->ptr);
10535 spin_unlock(&fs_info->swapfile_pins_lock);
10538 struct btrfs_swap_info {
10544 unsigned long nr_pages;
10548 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10549 struct btrfs_swap_info *bsi)
10551 unsigned long nr_pages;
10552 u64 first_ppage, first_ppage_reported, next_ppage;
10555 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10556 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10557 PAGE_SIZE) >> PAGE_SHIFT;
10559 if (first_ppage >= next_ppage)
10561 nr_pages = next_ppage - first_ppage;
10563 first_ppage_reported = first_ppage;
10564 if (bsi->start == 0)
10565 first_ppage_reported++;
10566 if (bsi->lowest_ppage > first_ppage_reported)
10567 bsi->lowest_ppage = first_ppage_reported;
10568 if (bsi->highest_ppage < (next_ppage - 1))
10569 bsi->highest_ppage = next_ppage - 1;
10571 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10574 bsi->nr_extents += ret;
10575 bsi->nr_pages += nr_pages;
10579 static void btrfs_swap_deactivate(struct file *file)
10581 struct inode *inode = file_inode(file);
10583 btrfs_free_swapfile_pins(inode);
10584 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10587 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10590 struct inode *inode = file_inode(file);
10591 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10592 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10593 struct extent_state *cached_state = NULL;
10594 struct extent_map *em = NULL;
10595 struct btrfs_device *device = NULL;
10596 struct btrfs_swap_info bsi = {
10597 .lowest_ppage = (sector_t)-1ULL,
10604 * If the swap file was just created, make sure delalloc is done. If the
10605 * file changes again after this, the user is doing something stupid and
10606 * we don't really care.
10608 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10613 * The inode is locked, so these flags won't change after we check them.
10615 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10616 btrfs_warn(fs_info, "swapfile must not be compressed");
10619 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10620 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10623 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10624 btrfs_warn(fs_info, "swapfile must not be checksummed");
10629 * Balance or device remove/replace/resize can move stuff around from
10630 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10631 * concurrently while we are mapping the swap extents, and
10632 * fs_info->swapfile_pins prevents them from running while the swap file
10633 * is active and moving the extents. Note that this also prevents a
10634 * concurrent device add which isn't actually necessary, but it's not
10635 * really worth the trouble to allow it.
10637 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10638 btrfs_warn(fs_info,
10639 "cannot activate swapfile while exclusive operation is running");
10643 * Snapshots can create extents which require COW even if NODATACOW is
10644 * set. We use this counter to prevent snapshots. We must increment it
10645 * before walking the extents because we don't want a concurrent
10646 * snapshot to run after we've already checked the extents.
10648 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10650 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10652 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10654 while (start < isize) {
10655 u64 logical_block_start, physical_block_start;
10656 struct btrfs_block_group_cache *bg;
10657 u64 len = isize - start;
10659 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10665 if (em->block_start == EXTENT_MAP_HOLE) {
10666 btrfs_warn(fs_info, "swapfile must not have holes");
10670 if (em->block_start == EXTENT_MAP_INLINE) {
10672 * It's unlikely we'll ever actually find ourselves
10673 * here, as a file small enough to fit inline won't be
10674 * big enough to store more than the swap header, but in
10675 * case something changes in the future, let's catch it
10676 * here rather than later.
10678 btrfs_warn(fs_info, "swapfile must not be inline");
10682 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10683 btrfs_warn(fs_info, "swapfile must not be compressed");
10688 logical_block_start = em->block_start + (start - em->start);
10689 len = min(len, em->len - (start - em->start));
10690 free_extent_map(em);
10693 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10699 btrfs_warn(fs_info,
10700 "swapfile must not be copy-on-write");
10705 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10711 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10712 btrfs_warn(fs_info,
10713 "swapfile must have single data profile");
10718 if (device == NULL) {
10719 device = em->map_lookup->stripes[0].dev;
10720 ret = btrfs_add_swapfile_pin(inode, device, false);
10725 } else if (device != em->map_lookup->stripes[0].dev) {
10726 btrfs_warn(fs_info, "swapfile must be on one device");
10731 physical_block_start = (em->map_lookup->stripes[0].physical +
10732 (logical_block_start - em->start));
10733 len = min(len, em->len - (logical_block_start - em->start));
10734 free_extent_map(em);
10737 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10739 btrfs_warn(fs_info,
10740 "could not find block group containing swapfile");
10745 ret = btrfs_add_swapfile_pin(inode, bg, true);
10747 btrfs_put_block_group(bg);
10754 if (bsi.block_len &&
10755 bsi.block_start + bsi.block_len == physical_block_start) {
10756 bsi.block_len += len;
10758 if (bsi.block_len) {
10759 ret = btrfs_add_swap_extent(sis, &bsi);
10764 bsi.block_start = physical_block_start;
10765 bsi.block_len = len;
10772 ret = btrfs_add_swap_extent(sis, &bsi);
10775 if (!IS_ERR_OR_NULL(em))
10776 free_extent_map(em);
10778 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10781 btrfs_swap_deactivate(file);
10783 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10789 sis->bdev = device->bdev;
10790 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10791 sis->max = bsi.nr_pages;
10792 sis->pages = bsi.nr_pages - 1;
10793 sis->highest_bit = bsi.nr_pages - 1;
10794 return bsi.nr_extents;
10797 static void btrfs_swap_deactivate(struct file *file)
10801 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10804 return -EOPNOTSUPP;
10808 static const struct inode_operations btrfs_dir_inode_operations = {
10809 .getattr = btrfs_getattr,
10810 .lookup = btrfs_lookup,
10811 .create = btrfs_create,
10812 .unlink = btrfs_unlink,
10813 .link = btrfs_link,
10814 .mkdir = btrfs_mkdir,
10815 .rmdir = btrfs_rmdir,
10816 .rename = btrfs_rename2,
10817 .symlink = btrfs_symlink,
10818 .setattr = btrfs_setattr,
10819 .mknod = btrfs_mknod,
10820 .listxattr = btrfs_listxattr,
10821 .permission = btrfs_permission,
10822 .get_acl = btrfs_get_acl,
10823 .set_acl = btrfs_set_acl,
10824 .update_time = btrfs_update_time,
10825 .tmpfile = btrfs_tmpfile,
10827 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10828 .lookup = btrfs_lookup,
10829 .permission = btrfs_permission,
10830 .update_time = btrfs_update_time,
10833 static const struct file_operations btrfs_dir_file_operations = {
10834 .llseek = generic_file_llseek,
10835 .read = generic_read_dir,
10836 .iterate_shared = btrfs_real_readdir,
10837 .open = btrfs_opendir,
10838 .unlocked_ioctl = btrfs_ioctl,
10839 #ifdef CONFIG_COMPAT
10840 .compat_ioctl = btrfs_compat_ioctl,
10842 .release = btrfs_release_file,
10843 .fsync = btrfs_sync_file,
10846 static const struct extent_io_ops btrfs_extent_io_ops = {
10847 /* mandatory callbacks */
10848 .submit_bio_hook = btrfs_submit_bio_hook,
10849 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10853 * btrfs doesn't support the bmap operation because swapfiles
10854 * use bmap to make a mapping of extents in the file. They assume
10855 * these extents won't change over the life of the file and they
10856 * use the bmap result to do IO directly to the drive.
10858 * the btrfs bmap call would return logical addresses that aren't
10859 * suitable for IO and they also will change frequently as COW
10860 * operations happen. So, swapfile + btrfs == corruption.
10862 * For now we're avoiding this by dropping bmap.
10864 static const struct address_space_operations btrfs_aops = {
10865 .readpage = btrfs_readpage,
10866 .writepage = btrfs_writepage,
10867 .writepages = btrfs_writepages,
10868 .readpages = btrfs_readpages,
10869 .direct_IO = btrfs_direct_IO,
10870 .invalidatepage = btrfs_invalidatepage,
10871 .releasepage = btrfs_releasepage,
10872 .set_page_dirty = btrfs_set_page_dirty,
10873 .error_remove_page = generic_error_remove_page,
10874 .swap_activate = btrfs_swap_activate,
10875 .swap_deactivate = btrfs_swap_deactivate,
10878 static const struct inode_operations btrfs_file_inode_operations = {
10879 .getattr = btrfs_getattr,
10880 .setattr = btrfs_setattr,
10881 .listxattr = btrfs_listxattr,
10882 .permission = btrfs_permission,
10883 .fiemap = btrfs_fiemap,
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_special_inode_operations = {
10889 .getattr = btrfs_getattr,
10890 .setattr = btrfs_setattr,
10891 .permission = btrfs_permission,
10892 .listxattr = btrfs_listxattr,
10893 .get_acl = btrfs_get_acl,
10894 .set_acl = btrfs_set_acl,
10895 .update_time = btrfs_update_time,
10897 static const struct inode_operations btrfs_symlink_inode_operations = {
10898 .get_link = page_get_link,
10899 .getattr = btrfs_getattr,
10900 .setattr = btrfs_setattr,
10901 .permission = btrfs_permission,
10902 .listxattr = btrfs_listxattr,
10903 .update_time = btrfs_update_time,
10906 const struct dentry_operations btrfs_dentry_operations = {
10907 .d_delete = btrfs_dentry_delete,